问:
where does ''options" come from in this JavaScript block of code?
i have this code from MDN which i am trying to understand !

first:>

where does 'options' came from in this block :-

for (var i = 0; i < selectObject.options.length; i++) {
    if (selectObject.options[i].selected)*

second:>

```<code>  why it 'options' does work fine inside the function and not work outside the function
</code>```

Here is the code-

```<code><form name="selectForm">
  <p>
    <label for="musicTypes">Choose some music types, then click the button below:</label>
    <select id="musicTypes" name="musicTypes" multiple="multiple">
      <option selected="selected">R&B</option>
      <option>Jazz</option>
      <option>Blues</option>
      <option>New Age</option>
      <option>Classical</option>
      <option>Opera</option>
    </select>
  </p>
  <p><input id="btn" type="button" value="How many are selected?" /></p>
</form>

<script>
function howMany(selectObject) {
  var numberSelected = 0;
  for (var i = 0; i < selectObject.options.length; i++) {
    if (selectObject.options[i].selected) {
      numberSelected++;
    }
  }
  return numberSelected;
}

var btn = document.getElementById('btn');
btn.addEventListener('click', function() {
  alert('Number of options selected: ' + howMany(document.selectForm.musicTypes));
});
</script>
</code>```

答:
1) options are part of HTML DOM and are responsible for selecting options elements inside the specified select element

2) It does work outside of function on any select element, but i'm assuming you are trying to use selectObject outside of the function, which violates variable scope.

Read more:

[1] https://www.w3schools.com/jsref/coll_select_options.asp

[2] https://www.w3schools.com/js/js_scope.asp

Body:
i have this code from MDN which i am trying to understand !

first:>

where does 'options' came from in this block :-

for (var i = 0; i < selectObject.options.length; i++) {
    if (selectObject.options[i].selected)*

second:>

  why it 'options' does work fine inside the function and not work outside the function

Here is the code-

<form name="selectForm">

    Choose some music types, then click the button below:
    <select id="musicTypes" name="musicTypes" multiple="multiple">
      <option selected="selected">R&B</option>
      <option>Jazz</option>
      <option>Blues</option>
      <option>New Age</option>
      <option>Classical</option>
      <option>Opera</option>
    </select>

<input id="btn" type="button" value="How many are selected?" />

</form>


来源: stackexchange

问:
Android Studio Build Error Duplicate Entry
I tried to build APK but i took an error message.

Error:Execution failed for task ':app:transformClassesWithJarMergingForDebug'.
  com.android.build.api.transform.TransformException: java.util.zip.ZipException: duplicate entry: android/support/constraint/ConstraintLayout.class

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    buildToolsVersion '26.0.2'
    defaultConfig {
        applicationId "com.pc.gozlukdenemexxx"
        minSdkVersion 15
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        multiDexEnabled true
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:26.+'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    testCompile 'junit:junit:4.12'
}
</code>```

答:
I found a solution. In ConstraintLayout.java file i deleted this method :

```<code>class ConstraintLayout extends View {
    public ConstraintLayout(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }
</code>```

But i wonder, deleting this method cause more problems?

ContentLicense: CC BY-SA 3.0

Body:
I tried to build APK but i took an error message.

Error:Execution failed for task ':app:transformClassesWithJarMergingForDebug'.
  com.android.build.api.transform.TransformException: java.util.zip.ZipException: duplicate entry: android/support/constraint/ConstraintLayout.class

apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    buildToolsVersion '26.0.2'
    defaultConfig {
        applicationId "com.pc.gozlukdenemexxx"
        minSdkVersion 15
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        multiDexEnabled true
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:26.+'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    testCompile 'junit:junit:4.12'
}

Body:
I found a solution. In ConstraintLayout.java file i deleted this method :

class ConstraintLayout extends View {
    public ConstraintLayout(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

But i wonder, deleting this method cause more problems?


问:
"Creating an image format with an unknown type is an error" with UIImagePickerController
While choosing an image from the image picker in iOS 10 Swift 3 I am getting an error - Creating an image format with an unknown type is an error

```<code> func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {

    imagePost.image = image
    self.dismiss(animated: true, completion: nil)
}
</code>```

The image is not getting selected and updated. I need help or suggestion to know if the syntax or anything regarding this method has been changed in iOS10 or Swift 3 or is there any other way to do this.

答:
```<code>func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
    if let image = info[UIImagePickerControllerOriginalImage] as? UIImage {
        imgViewPhoto.image = image
    } else{
        print("Something went wrong")
    }

    picker.dismiss(animated: true, completion: nil)

}
</code>```

Body:
While choosing an image from the image picker in iOS 10 Swift 3 I am getting an error - Creating an image format with an unknown type is an error

 func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {

    imagePost.image = image
    self.dismiss(animated: true, completion: nil)
}

The image is not getting selected and updated. I need help or suggestion to know if the syntax or anything regarding this method has been changed in iOS10 or Swift 3 or is there any other way to do this.


问:
Tensorflow Object Detection API with Mobilenets overfits custom multiclass dataset
The model overfits the training set and fails to generalise to test set.

How could I add dropout to the feature extractor part of the model? (the .config file only provides a key value to add dropout to the box predictor)

What other measures I could take to minimize overfitting?

More details below:

I am attempting to retrain the model checkpoint "ssd_mobilenet_v1_coco_11_06_2017" on a dataset of toy animals. There are 14 classes, with 400-600 images in each. The network learns the training set in less than 30k steps. Tensorboard. The loss seems to remain quite volatile still after initial training, although I am not experienced enough to assess that.

I am testing the model by applying the exported graph to images and inspecting the results manually. (I just haven't had time to implement validation properly). The model works very well on pictures taken in very similar conditions to those in the training set. These bad test set images are randomly set aside from the training set which was acquired by taking many images in succession with slight changes in camera angle. The training set also includes various lighting conditions, backgrounds, distortions and camera locations. I would estimate it gets the classes and locations right in roughly 95% of the images from the bad test set. From this I conclude that the model fits the training set very well and can generalise a little bit.

However, the model performs very poorly on pictures taken separately with a different camera at a different time (i.e. there should be much less correlation between this test set and the training set). I would estimate the performance in this good test set is roughly 25%. From this I conclude that the model is overfitting and failing to generalise.

I have tried making some changes in the .config file.

Increasing the l2_regularizer weight from 0.00004 to 0.0001 for both the feature extractor and box predictor.

Setting box predictor use_dropout to true in order to enable the 20% dropout.

I am using Tensorflow 1.4 pip install and models cloned from github from about 3 weeks ago.

I call the train.py in object_detection with the following arguments:

```<code>python train.py --logtostderr --train_dir=/home/X/TrainDir/Process --pipeline_config_path=/home/X/ssd_mobilenet_v1_coco.config
</code>```

My configuration file is the following:

```<code># SSD with Mobilenet v1 configuration for MSCOCO Dataset.
# Users should configure the fine_tune_checkpoint field in the train config as
# well as the label_map_path and input_path fields in the train_input_reader and
# eval_input_reader. Search for "PATH_TO_BE_CONFIGURED" to find the fields that
# should be configured.

model {
  ssd {
    num_classes: 14
    box_coder {
      faster_rcnn_box_coder {
        y_scale: 10.0
        x_scale: 10.0
        height_scale: 5.0
        width_scale: 5.0
      }
    }
    matcher {
      argmax_matcher {
        matched_threshold: 0.5
        unmatched_threshold: 0.5
        ignore_thresholds: false
        negatives_lower_than_unmatched: true
        force_match_for_each_row: true
      }
    }
    similarity_calculator {
      iou_similarity {
      }
    }
    anchor_generator {
      ssd_anchor_generator {
        num_layers: 6
        min_scale: 0.2
        max_scale: 0.95
        aspect_ratios: 1.0
        aspect_ratios: 2.0
        aspect_ratios: 0.5
        aspect_ratios: 3.0
        aspect_ratios: 0.3333
      }
    }
    image_resizer {
      fixed_shape_resizer {
        height: 300
        width: 300
      }
    }
    box_predictor {
      convolutional_box_predictor {
        min_depth: 0
        max_depth: 0
        num_layers_before_predictor: 0
        use_dropout: true
        dropout_keep_probability: 0.8
        kernel_size: 1
        box_code_size: 4
        apply_sigmoid_to_scores: false
        conv_hyperparams {
          activation: RELU_6,
          regularizer {
            l2_regularizer {
              weight: 0.0001
            }
          }
          initializer {
            truncated_normal_initializer {
              stddev: 0.03
              mean: 0.0
            }
          }
          batch_norm {
            train: true,
            scale: true,
            center: true,
            decay: 0.9997,
            epsilon: 0.001,
          }
        }
      }
    }
    feature_extractor {
      type: 'ssd_mobilenet_v1'
      min_depth: 16
      depth_multiplier: 1.0
      conv_hyperparams {
        activation: RELU_6,
        regularizer {
          l2_regularizer {
            weight: 0.0001
          }
        }
        initializer {
          truncated_normal_initializer {
            stddev: 0.03
            mean: 0.0
          }
        }
        batch_norm {
          train: true,
          scale: true,
          center: true,
          decay: 0.9997,
          epsilon: 0.001,
        }
      }
    }
    loss {
      classification_loss {
        weighted_sigmoid {
          anchorwise_output: true
        }
      }
      localization_loss {
        weighted_smooth_l1 {
          anchorwise_output: true
        }
      }
      hard_example_miner {
        num_hard_examples: 3000
        iou_threshold: 0.99
        loss_type: CLASSIFICATION
        max_negatives_per_positive: 3
        min_negatives_per_image: 0
      }
      classification_weight: 1.0
      localization_weight: 1.0
    }
    normalize_loss_by_num_matches: true
    post_processing {
      batch_non_max_suppression {
        score_threshold: 1e-8
        iou_threshold: 0.6
        max_detections_per_class: 100
        max_total_detections: 100
      }
      score_converter: SIGMOID
    }
  }
}

train_config: {
  batch_size: 8
  optimizer {
    rms_prop_optimizer: {
      learning_rate: {
        exponential_decay_learning_rate {
          initial_learning_rate: 0.004
          decay_steps: 800720
          decay_factor: 0.95
        }
      }
      momentum_optimizer_value: 0.9
      decay: 0.9
      epsilon: 1.0
    }
  }
  fine_tune_checkpoint: "/home/X/tensorflow/models/research/object_detection/ssd_mobilenet_v1_coco_11_06_2017/model.ckpt"
  from_detection_checkpoint: true
  # Note: The below line limits the training process to 200K steps, which we
  # empirically found to be sufficient enough to train the pets dataset. This
  # effectively bypasses the learning rate schedule (the learning rate will
  # never decay). Remove the below line to train indefinitely.
  num_steps: 200000
  data_augmentation_options {
    random_horizontal_flip {
    }
  }
  data_augmentation_options {
    ssd_random_crop {
    }
  }
}

train_input_reader: {
  tf_record_input_reader {
    input_path: "/home/X/TrainDir/train.record"
  }
  label_map_path: "/home/X/TrainDir/data_label_map.pbtxt"
}

eval_config: {
  num_examples: 1200
  # Note: The below line limits the evaluation process to 10 evaluations.
  # Remove the below line to evaluate indefinitely.
  max_evals: 30
}

eval_input_reader: {
  tf_record_input_reader {
    input_path: "/home/X/TrainDir/test.record"
  }
  label_map_path: "/home/X/TrainDir/data_label_map.pbtxt"
  shuffle: false
  num_readers: 1
  num_epochs: 1
}
</code>```

答:
After some tricks the network learned well and started to generalise on the good test set.

I included learning rate decay of about 10% every 5000 steps (this already helped quite a bit).

I added to the training set of toy animals about 10% extra images of images of real animals of the same kind. This improved generalisation drastically.

Training for longer improved results further.

I left the regularisation and box_predictor dropout to their original values.

The trained network performed well in a real world scenario, doing online detection of these animals while the pictures were taken in a completely new scene and lighting condition.

The following added on 06/03/2020

In response to the request in the comments, I dug out the configuration file I had stored with this project (> 2 years ago). It is most likely the final configuration I ended up using, which worked well.

```<code># SSD with Mobilenet v1 configuration for MSCOCO Dataset.
# Users should configure the fine_tune_checkpoint field in the train config as
# well as the label_map_path and input_path fields in the train_input_reader and
# eval_input_reader. Search for "PATH_TO_BE_CONFIGURED" to find the fields that
# should be configured.

model {
  ssd {
    num_classes: 14
    box_coder {
      faster_rcnn_box_coder {
        y_scale: 10.0
        x_scale: 10.0
        height_scale: 5.0
        width_scale: 5.0
      }
    }
    matcher {
      argmax_matcher {
        matched_threshold: 0.5
        unmatched_threshold: 0.5
        ignore_thresholds: false
        negatives_lower_than_unmatched: true
        force_match_for_each_row: true
      }
    }
    similarity_calculator {
      iou_similarity {
      }
    }
    anchor_generator {
      ssd_anchor_generator {
        num_layers: 6
        min_scale: 0.2
        max_scale: 0.95
        aspect_ratios: 1.0
        aspect_ratios: 2.0
        aspect_ratios: 0.5
        aspect_ratios: 3.0
        aspect_ratios: 0.3333
      }
    }
    image_resizer {
      fixed_shape_resizer {
        height: 300
        width: 300
      }
    }
    box_predictor {
      convolutional_box_predictor {
        min_depth: 0
        max_depth: 0
        num_layers_before_predictor: 0
        use_dropout: true
        dropout_keep_probability: 0.8
        kernel_size: 1
        box_code_size: 4
        apply_sigmoid_to_scores: false
        conv_hyperparams {
          activation: RELU_6,
          regularizer {
            l2_regularizer {
              weight: 0.00004
            }
          }
          initializer {
            truncated_normal_initializer {
              stddev: 0.03
              mean: 0.0
            }
          }
          batch_norm {
            train: true,
            scale: true,
            center: true,
            decay: 0.9997,
            epsilon: 0.001,
          }
        }
      }
    }
    feature_extractor {
      type: 'ssd_mobilenet_v1'
      min_depth: 16
      depth_multiplier: 1.0
      conv_hyperparams {
        activation: RELU_6,
        regularizer {
          l2_regularizer {
            weight: 0.00004
          }
        }
        initializer {
          truncated_normal_initializer {
            stddev: 0.03
            mean: 0.0
          }
        }
        batch_norm {
          train: true,
          scale: true,
          center: true,
          decay: 0.9997,
          epsilon: 0.001,
        }
      }
    }
    loss {
      classification_loss {
        weighted_sigmoid {
          anchorwise_output: true
        }
      }
      localization_loss {
        weighted_smooth_l1 {
          anchorwise_output: true
        }
      }
      hard_example_miner {
        num_hard_examples: 3000
        iou_threshold: 0.99
        loss_type: CLASSIFICATION
        max_negatives_per_positive: 3
        min_negatives_per_image: 0
      }
      classification_weight: 1.0
      localization_weight: 1.0
    }
    normalize_loss_by_num_matches: true
    post_processing {
      batch_non_max_suppression {
        score_threshold: 1e-8
        iou_threshold: 0.6
        max_detections_per_class: 100
        max_total_detections: 100
      }
      score_converter: SIGMOID
    }
  }
}

train_config: {
  batch_size: 8
  optimizer {
    rms_prop_optimizer: {
      learning_rate: {
        exponential_decay_learning_rate {
          initial_learning_rate: 0.004
          decay_steps: 7000
          decay_factor: 0.75
        }
      }
      momentum_optimizer_value: 0.9
      decay: 0.9
      epsilon: 1.0
    }
  }
  fine_tune_checkpoint: "/home/sander/tensorflow/models/research/object_detection/ssd_mobilenet_v1_coco_11_06_2017/model.ckpt"
  from_detection_checkpoint: true
  # Note: The below line limits the training process to 200K steps, which we
  # empirically found to be sufficient enough to train the pets dataset. This
  # effectively bypasses the learning rate schedule (the learning rate will
  # never decay). Remove the below line to train indefinitely.
  num_steps: 200000
  data_augmentation_options {
    random_horizontal_flip {
    }
  }
  data_augmentation_options {
    ssd_random_crop {
    }
  }
}

train_input_reader: {
  tf_record_input_reader {
    input_path: "/home/sander/ROBOT/TrainDir/train.record"
  }
  label_map_path: "/home/sander/ROBOT/TrainDir/data_label_map.pbtxt"
}

eval_config: {
  num_examples: 1200
  # Note: The below line limits the evaluation process to 10 evaluations.
  # Remove the below line to evaluate indefinitely.
  max_evals: 30
}

eval_input_reader: {
  tf_record_input_reader {
    input_path: "/home/sander/ROBOT/TrainDir/test.record"
  }
  label_map_path: "/home/sander/ROBOT/TrainDir/data_label_map.pbtxt"
  shuffle: false
  num_readers: 1
  num_epochs: 1
}
</code>```

Body:
The model overfits the training set and fails to generalise to test set.

How could I add dropout to the feature extractor part of the model? (the .config file only provides a key value to add dropout to the box predictor)

What other measures I could take to minimize overfitting?

More details below:

I am attempting to retrain the model checkpoint "ssd_mobilenet_v1_coco_11_06_2017" on a dataset of toy animals. There are 14 classes, with 400-600 images in each. The network learns the training set in less than 30k steps. Tensorboard. The loss seems to remain quite volatile still after initial training, although I am not experienced enough to assess that.

I am testing the model by applying the exported graph to images and inspecting the results manually. (I just haven't had time to implement validation properly). The model works very well on pictures taken in very similar conditions to those in the training set. These bad test set images are randomly set aside from the training set which was acquired by taking many images in succession with slight changes in camera angle. The training set also includes various lighting conditions, backgrounds, distortions and camera locations. I would estimate it gets the classes and locations right in roughly 95% of the images from the bad test set. From this I conclude that the model fits the training set very well and can generalise a little bit.

However, the model performs very poorly on pictures taken separately with a different camera at a different time (i.e. there should be much less correlation between this test set and the training set). I would estimate the performance in this good test set is roughly 25%. From this I conclude that the model is overfitting and failing to generalise.

I have tried making some changes in the .config file.

Increasing the l2_regularizer weight from 0.00004 to 0.0001 for both the feature extractor and box predictor.

Setting box predictor use_dropout to true in order to enable the 20% dropout.

I am using Tensorflow 1.4 pip install and models cloned from github from about 3 weeks ago.

I call the train.py in object_detection with the following arguments:

python train.py --logtostderr --train_dir=/home/X/TrainDir/Process --pipeline_config_path=/home/X/ssd_mobilenet_v1_coco.config

My configuration file is the following:

# SSD with Mobilenet v1 configuration for MSCOCO Dataset.
# Users should configure the fine_tune_checkpoint field in the train config as
# well as the label_map_path and input_path fields in the train_input_reader and
# eval_input_reader. Search for "PATH_TO_BE_CONFIGURED" to find the fields that
# should be configured.

model {
  ssd {
    num_classes: 14
    box_coder {
      faster_rcnn_box_coder {
        y_scale: 10.0
        x_scale: 10.0
        height_scale: 5.0
        width_scale: 5.0
      }
    }
    matcher {
      argmax_matcher {
        matched_threshold: 0.5
        unmatched_threshold: 0.5
        ignore_thresholds: false
        negatives_lower_than_unmatched: true
        force_match_for_each_row: true
      }
    }
    similarity_calculator {
      iou_similarity {
      }
    }
    anchor_generator {
      ssd_anchor_generator {
        num_layers: 6
        min_scale: 0.2
        max_scale: 0.95
        aspect_ratios: 1.0
        aspect_ratios: 2.0
        aspect_ratios: 0.5
        aspect_ratios: 3.0
        aspect_ratios: 0.3333
      }
    }
    image_resizer {
      fixed_shape_resizer {
        height: 300
        width: 300
      }
    }
    box_predictor {
      convolutional_box_predictor {
        min_depth: 0
        max_depth: 0
        num_layers_before_predictor: 0
        use_dropout: true
        dropout_keep_probability: 0.8
        kernel_size: 1
        box_code_size: 4
        apply_sigmoid_to_scores: false
        conv_hyperparams {
          activation: RELU_6,
          regularizer {
            l2_regularizer {
              weight: 0.0001
            }
          }
          initializer {
            truncated_normal_initializer {
              stddev: 0.03
              mean: 0.0
            }
          }
          batch_norm {
            train: true,
            scale: true,
            center: true,
            decay: 0.9997,
            epsilon: 0.001,
          }
        }
      }
    }
    feature_extractor {
      type: 'ssd_mobilenet_v1'
      min_depth: 16
      depth_multiplier: 1.0
      conv_hyperparams {
        activation: RELU_6,
        regularizer {
          l2_regularizer {
            weight: 0.0001
          }
        }
        initializer {
          truncated_normal_initializer {
            stddev: 0.03
            mean: 0.0
          }
        }
        batch_norm {
          train: true,
          scale: true,
          center: true,
          decay: 0.9997,
          epsilon: 0.001,
        }
      }
    }
    loss {
      classification_loss {
        weighted_sigmoid {
          anchorwise_output: true
        }
      }
      localization_loss {
        weighted_smooth_l1 {
          anchorwise_output: true
        }
      }
      hard_example_miner {
        num_hard_examples: 3000
        iou_threshold: 0.99
        loss_type: CLASSIFICATION
        max_negatives_per_positive: 3
        min_negatives_per_image: 0
      }
      classification_weight: 1.0
      localization_weight: 1.0
    }
    normalize_loss_by_num_matches: true
    post_processing {
      batch_non_max_suppression {
        score_threshold: 1e-8
        iou_threshold: 0.6
        max_detections_per_class: 100
        max_total_detections: 100
      }
      score_converter: SIGMOID
    }
  }
}

train_config: {
  batch_size: 8
  optimizer {
    rms_prop_optimizer: {
      learning_rate: {
        exponential_decay_learning_rate {
          initial_learning_rate: 0.004
          decay_steps: 800720
          decay_factor: 0.95
        }
      }
      momentum_optimizer_value: 0.9
      decay: 0.9
      epsilon: 1.0
    }
  }
  fine_tune_checkpoint: "/home/X/tensorflow/models/research/object_detection/ssd_mobilenet_v1_coco_11_06_2017/model.ckpt"
  from_detection_checkpoint: true
  # Note: The below line limits the training process to 200K steps, which we
  # empirically found to be sufficient enough to train the pets dataset. This
  # effectively bypasses the learning rate schedule (the learning rate will
  # never decay). Remove the below line to train indefinitely.
  num_steps: 200000
  data_augmentation_options {
    random_horizontal_flip {
    }
  }
  data_augmentation_options {
    ssd_random_crop {
    }
  }
}

train_input_reader: {
  tf_record_input_reader {
    input_path: "/home/X/TrainDir/train.record"
  }
  label_map_path: "/home/X/TrainDir/data_label_map.pbtxt"
}

eval_config: {
  num_examples: 1200
  # Note: The below line limits the evaluation process to 10 evaluations.
  # Remove the below line to evaluate indefinitely.
  max_evals: 30
}

eval_input_reader: {
  tf_record_input_reader {
    input_path: "/home/X/TrainDir/test.record"
  }
  label_map_path: "/home/X/TrainDir/data_label_map.pbtxt"
  shuffle: false
  num_readers: 1
  num_epochs: 1
}

Body:
After some tricks the network learned well and started to generalise on the good test set.

I included learning rate decay of about 10% every 5000 steps (this already helped quite a bit).

I added to the training set of toy animals about 10% extra images of images of real animals of the same kind. This improved generalisation drastically.

Training for longer improved results further.

I left the regularisation and box_predictor dropout to their original values.

The trained network performed well in a real world scenario, doing online detection of these animals while the pictures were taken in a completely new scene and lighting condition.

The following added on 06/03/2020

In response to the request in the comments, I dug out the configuration file I had stored with this project (> 2 years ago). It is most likely the final configuration I ended up using, which worked well.

# SSD with Mobilenet v1 configuration for MSCOCO Dataset.
# Users should configure the fine_tune_checkpoint field in the train config as
# well as the label_map_path and input_path fields in the train_input_reader and
# eval_input_reader. Search for "PATH_TO_BE_CONFIGURED" to find the fields that
# should be configured.

model {
  ssd {
    num_classes: 14
    box_coder {
      faster_rcnn_box_coder {
        y_scale: 10.0
        x_scale: 10.0
        height_scale: 5.0
        width_scale: 5.0
      }
    }
    matcher {
      argmax_matcher {
        matched_threshold: 0.5
        unmatched_threshold: 0.5
        ignore_thresholds: false
        negatives_lower_than_unmatched: true
        force_match_for_each_row: true
      }
    }
    similarity_calculator {
      iou_similarity {
      }
    }
    anchor_generator {
      ssd_anchor_generator {
        num_layers: 6
        min_scale: 0.2
        max_scale: 0.95
        aspect_ratios: 1.0
        aspect_ratios: 2.0
        aspect_ratios: 0.5
        aspect_ratios: 3.0
        aspect_ratios: 0.3333
      }
    }
    image_resizer {
      fixed_shape_resizer {
        height: 300
        width: 300
      }
    }
    box_predictor {
      convolutional_box_predictor {
        min_depth: 0
        max_depth: 0
        num_layers_before_predictor: 0
        use_dropout: true
        dropout_keep_probability: 0.8
        kernel_size: 1
        box_code_size: 4
        apply_sigmoid_to_scores: false
        conv_hyperparams {
          activation: RELU_6,
          regularizer {
            l2_regularizer {
              weight: 0.00004
            }
          }
          initializer {
            truncated_normal_initializer {
              stddev: 0.03
              mean: 0.0
            }
          }
          batch_norm {
            train: true,
            scale: true,
            center: true,
            decay: 0.9997,
            epsilon: 0.001,
          }
        }
      }
    }
    feature_extractor {
      type: 'ssd_mobilenet_v1'
      min_depth: 16
      depth_multiplier: 1.0
      conv_hyperparams {
        activation: RELU_6,
        regularizer {
          l2_regularizer {
            weight: 0.00004
          }
        }
        initializer {
          truncated_normal_initializer {
            stddev: 0.03
            mean: 0.0
          }
        }
        batch_norm {
          train: true,
          scale: true,
          center: true,
          decay: 0.9997,
          epsilon: 0.001,
        }
      }
    }
    loss {
      classification_loss {
        weighted_sigmoid {
          anchorwise_output: true
        }
      }
      localization_loss {
        weighted_smooth_l1 {
          anchorwise_output: true
        }
      }
      hard_example_miner {
        num_hard_examples: 3000
        iou_threshold: 0.99
        loss_type: CLASSIFICATION
        max_negatives_per_positive: 3
        min_negatives_per_image: 0
      }
      classification_weight: 1.0
      localization_weight: 1.0
    }
    normalize_loss_by_num_matches: true
    post_processing {
      batch_non_max_suppression {
        score_threshold: 1e-8
        iou_threshold: 0.6
        max_detections_per_class: 100
        max_total_detections: 100
      }
      score_converter: SIGMOID
    }
  }
}

train_config: {
  batch_size: 8
  optimizer {
    rms_prop_optimizer: {
      learning_rate: {
        exponential_decay_learning_rate {
          initial_learning_rate: 0.004
          decay_steps: 7000
          decay_factor: 0.75
        }
      }
      momentum_optimizer_value: 0.9
      decay: 0.9
      epsilon: 1.0
    }
  }
  fine_tune_checkpoint: "/home/sander/tensorflow/models/research/object_detection/ssd_mobilenet_v1_coco_11_06_2017/model.ckpt"
  from_detection_checkpoint: true
  # Note: The below line limits the training process to 200K steps, which we
  # empirically found to be sufficient enough to train the pets dataset. This
  # effectively bypasses the learning rate schedule (the learning rate will
  # never decay). Remove the below line to train indefinitely.
  num_steps: 200000
  data_augmentation_options {
    random_horizontal_flip {
    }
  }
  data_augmentation_options {
    ssd_random_crop {
    }
  }
}

train_input_reader: {
  tf_record_input_reader {
    input_path: "/home/sander/ROBOT/TrainDir/train.record"
  }
  label_map_path: "/home/sander/ROBOT/TrainDir/data_label_map.pbtxt"
}

eval_config: {
  num_examples: 1200
  # Note: The below line limits the evaluation process to 10 evaluations.
  # Remove the below line to evaluate indefinitely.
  max_evals: 30
}

eval_input_reader: {
  tf_record_input_reader {
    input_path: "/home/sander/ROBOT/TrainDir/test.record"
  }
  label_map_path: "/home/sander/ROBOT/TrainDir/data_label_map.pbtxt"
  shuffle: false
  num_readers: 1
  num_epochs: 1
}

ContentLicense: CC BY-SA 4.0


问:
Stream File to Chome Broken, Firefox Working
I wrote an ASP.Net web page that will take a QueryString and stream a file to the client. The file is stored in a SQL Server database. Everything works great when I'm running the web site locally during development. When I run it in production from the server I can get a file through Firefox, but not Chrome. In Chrome I get Error 100 (net::ERR_CONNECTION_CLOSED): Unknown error.

See some other posts that mention this could be related to Content-Length, however, I can't understand why this would work in development and not production. For that reason I think there must be something else going on here.

Thanks for any suggestions/hints.

Here is my code:

```<code>    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    Dim Data_ID As String = Request.QueryString("Data_ID")

    Using dt As New Enterprise_Error_Log.Field_FileDataTable
        Using ta As New Field_FileTableAdapter
            ta.Fill(dt, Data_ID)

            If dt.Rows.Count > 0 Then
                Dim myRow As Enterprise_Error_Log.Field_FileRow = dt.Rows(0)
                Dim myFileName As String = myRow("Field_File_Name")
                'Dim myFileData() As Byte = myRow("Field_File")
                Dim myFileLength As String = myRow("Field_File_Length")

                Response.BufferOutput = False
                Response.AddHeader("Content-Disposition", "inline;filename=""" & myFileName & """")
                Response.AddHeader("Content-Length", myFileLength)

                StreamFile(Data_ID)

                Response.Close()

            End If

        End Using
    End Using

End Sub

Private Sub StreamFile(ByVal Data_ID As String)
    Dim bolGotContentType As Boolean = False

    Using conn = New SqlConnection(Enterprise_Error_LogConnectionString.ConnectionString)
        Using cmd = conn.CreateCommand()
            conn.Open()
            cmd.CommandText = "SELECT Field_File FROM Ext_Error_Log WHERE (Data_ID = @Data_ID)"
            cmd.Parameters.AddWithValue("@Data_ID", Data_ID)

            Using reader = cmd.ExecuteReader(Data.CommandBehavior.SequentialAccess)
                While reader.Read()
                    Dim buffer As Byte() = New Byte(8040) {}
                    ' Read chunks of 1KB
                    Dim bytesRead As Long = 0
                    Dim dataIndex As Long = 0
                    Do
                        'read next chunk
                        bytesRead = reader.GetBytes(0, dataIndex, buffer, 0, buffer.Length)
                        If bytesRead > 0 Then
                            'advance index
                            dataIndex += bytesRead

                            'if this is the first chunk, get the mime type from it.
                            If Not bolGotContentType Then
                                Response.ContentType = "application/octet-stream" 'getMimeFromFile(buffer)
                                bolGotContentType = True
                            End If

                            Response.BinaryWrite(buffer)
                            Response.Flush()
                        End If
                    Loop Until bytesRead = 0

                End While

            End Using
        End Using
    End Using

End Sub
</code>```

My headers are as follows:

```<code>Cache-Control: private
Date: Mon, 24 Jan 2011 20:37:33 GMT

Content-Length: 3153269
Content-Type: application/octet-stream

Content-Disposition: attachment;filename="C:\Users\CBARTH\AppData\Local\Temp\tmp4BC8.mdmp.gz";size=3153169
Server: Microsoft-IIS/6.0
X-AspNet-Version: 2.0.50727
X-Powered-By: ASP.NET

Content-Encoding: gzip
</code>```

答: I recommend inspecting the actual response in an HTTP trace tool (Firefox LiveHTTP headers comes to mind), and to check whether something weird with Content-Length is going on (set multiple times?)</p>

ContentLicense: CC BY-SA 2.5

Body:
I wrote an ASP.Net web page that will take a QueryString and stream a file to the client. The file is stored in a SQL Server database. Everything works great when I'm running the web site locally during development. When I run it in production from the server I can get a file through Firefox, but not Chrome. In Chrome I get Error 100 (net::ERR_CONNECTION_CLOSED): Unknown error.

See some other posts that mention this could be related to Content-Length, however, I can't understand why this would work in development and not production. For that reason I think there must be something else going on here.

Thanks for any suggestions/hints.

Here is my code:

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    Dim Data_ID As String = Request.QueryString("Data_ID")

    Using dt As New Enterprise_Error_Log.Field_FileDataTable
        Using ta As New Field_FileTableAdapter
            ta.Fill(dt, Data_ID)

            If dt.Rows.Count > 0 Then
                Dim myRow As Enterprise_Error_Log.Field_FileRow = dt.Rows(0)
                Dim myFileName As String = myRow("Field_File_Name")
                'Dim myFileData() As Byte = myRow("Field_File")
                Dim myFileLength As String = myRow("Field_File_Length")

                Response.BufferOutput = False
                Response.AddHeader("Content-Disposition", "inline;filename=""" & myFileName & """")
                Response.AddHeader("Content-Length", myFileLength)

                StreamFile(Data_ID)

                Response.Close()

            End If

        End Using
    End Using

End Sub

Private Sub StreamFile(ByVal Data_ID As String)
    Dim bolGotContentType As Boolean = False

    Using conn = New SqlConnection(Enterprise_Error_LogConnectionString.ConnectionString)
        Using cmd = conn.CreateCommand()
            conn.Open()
            cmd.CommandText = "SELECT Field_File FROM Ext_Error_Log WHERE (Data_ID = @Data_ID)"
            cmd.Parameters.AddWithValue("@Data_ID", Data_ID)

            Using reader = cmd.ExecuteReader(Data.CommandBehavior.SequentialAccess)
                While reader.Read()
                    Dim buffer As Byte() = New Byte(8040) {}
                    ' Read chunks of 1KB
                    Dim bytesRead As Long = 0
                    Dim dataIndex As Long = 0
                    Do
                        'read next chunk
                        bytesRead = reader.GetBytes(0, dataIndex, buffer, 0, buffer.Length)
                        If bytesRead > 0 Then
                            'advance index
                            dataIndex += bytesRead

                            'if this is the first chunk, get the mime type from it.
                            If Not bolGotContentType Then
                                Response.ContentType = "application/octet-stream" 'getMimeFromFile(buffer)
                                bolGotContentType = True
                            End If

                            Response.BinaryWrite(buffer)
                            Response.Flush()
                        End If
                    Loop Until bytesRead = 0

                End While

            End Using
        End Using
    End Using

End Sub

My headers are as follows:

Cache-Control: private
Date: Mon, 24 Jan 2011 20:37:33 GMT

Content-Length: 3153269
Content-Type: application/octet-stream

Content-Disposition: attachment;filename="C:\Users\CBARTH\AppData\Local\Temp\tmp4BC8.mdmp.gz";size=3153169
Server: Microsoft-IIS/6.0
X-AspNet-Version: 2.0.50727
X-Powered-By: ASP.NET

Content-Encoding: gzip


问:
Calculate total elapsed time of Promises till reject?
I want to test how much requests i can do and get their total time elapsed. My Promise function

```<code>async execQuery(response, query) {
    let request = new SQL.Request();

    return new Promise((resolve, reject) => {
        request.query(query, (error, result) => {
            if (error) {
                reject(error);
            } else {
                resolve(result);
            }
        });
    });
}
</code>```

And my api

```<code>app.get('/api/bookings/:uid', (req, res) => {
    let st = new stopwatch();
    let id = req.params.uid;

    let query = `SELECT * FROM booking.TransactionDetails WHERE UID='${id}'`;
    for (let i = 0; i < 10000; i++) {
        st.start();
        db.execQuery(res, query);
    }
});
</code>```

I can't stop the for loop since its async but I also don't know how can I stop executing other calls after the one which first rejects so i can get the counter and the elapsed time of all successful promises. How can i achieve that?

答:
You can easily create a composable wrapper for this, or a subclass:

Inheritance:

```<code>class TimedPromise extends Promise {
  constructor(executor) {
    this.startTime = performance.now(); // or Date.now
    super(executor);
    let end = () => this.endTime = performance.now();
    this.then(end, end); // replace with finally when available
  }
  get time() {
    return this.startTime - this.endTime; // time in milliseconds it took
  }
}
</code>```

Then you can use methods like:

```<code>TimedPromise.all(promises);
TimedPromise.race(promises);

var foo = new TimedPromise(resolve => setTimeout(resolve, 100);
let res = await foo;
console.log(foo.time); // how long foo took
</code>```

Plus then chaining would work, async functions won't (since they always return native promises).

Composition:

```<code>function time(promise) {
   var startTime = performance.now(), endTime;
   let end = () => endTime = performance.now();
   promise.then(end, end); // replace with finally when appropriate.
   return () => startTime - endTime;
}
</code>```

Then usage is:

```<code> var foo = new Promise(resolve => setTimeout(resolve, 100);
 var timed = time(foo);
 await foo;
 console.log(timed()); // how long foo took
</code>```

This has the advantage of working everywhere, but the disadvantage of manually having to time every promise. I prefer this approach for its explicitness and arguably nicer design.

As a caveat, since a rejection handler is attached, you have to be 100% sure you're adding your own .catch or then handler since otherwise the error will not log to the console.

Body:
I want to test how much requests i can do and get their total time elapsed. My Promise function

async execQuery(response, query) {
    let request = new SQL.Request();

    return new Promise((resolve, reject) => {
        request.query(query, (error, result) => {
            if (error) {
                reject(error);
            } else {
                resolve(result);
            }
        });
    });
}

And my api

app.get('/api/bookings/:uid', (req, res) => {
    let st = new stopwatch();
    let id = req.params.uid;

    let query = `SELECT * FROM booking.TransactionDetails WHERE UID='${id}'`;
    for (let i = 0; i < 10000; i++) {
        st.start();
        db.execQuery(res, query);
    }
});

I can't stop the for loop since its async but I also don't know how can I stop executing other calls after the one which first rejects so i can get the counter and the elapsed time of all successful promises. How can i achieve that?

Body:
You can easily create a composable wrapper for this, or a subclass:

Inheritance:

class TimedPromise extends Promise {
  constructor(executor) {
    this.startTime = performance.now(); // or Date.now
    super(executor);
    let end = () => this.endTime = performance.now();
    this.then(end, end); // replace with finally when available
  }
  get time() {
    return this.startTime - this.endTime; // time in milliseconds it took
  }
}

Then you can use methods like:

TimedPromise.all(promises);
TimedPromise.race(promises);

var foo = new TimedPromise(resolve => setTimeout(resolve, 100);
let res = await foo;
console.log(foo.time); // how long foo took

Plus then chaining would work, async functions won't (since they always return native promises).

Composition:

function time(promise) {
   var startTime = performance.now(), endTime;
   let end = () => endTime = performance.now();
   promise.then(end, end); // replace with finally when appropriate.
   return () => startTime - endTime;
}

Then usage is:

 var foo = new Promise(resolve => setTimeout(resolve, 100);
 var timed = time(foo);
 await foo;
 console.log(timed()); // how long foo took

This has the advantage of working everywhere, but the disadvantage of manually having to time every promise. I prefer this approach for its explicitness and arguably nicer design.

As a caveat, since a rejection handler is attached, you have to be 100% sure you're adding your own .catch or then handler since otherwise the error will not log to the console.


问:
Apply CSS class only to the button that was clicked
I'm trying to apply a CSS class only to the button that was clicked (to set it active).

Here's my code:

filter.component.html

```<code><div class="button-container">
    <button class="rules" [class.active]="active" (click)="toggleActive()" type="button">Rules</button>
    <button class="dailies" [class.active]="active" (click)="toggleActive()" type="button">Dailies</button>
    <button class="emotions" [class.active]="active" (click)="toggleActive()" type="button">Emotions</button>
</div>
</code>```

filter.component.ts

```<code>export class FilterComponent {
    active: boolean = false;

    toggleActive(): void {
      this.active = !this.active;
    }
  constructor() {}
}
</code>```

My problem is, the class gets applied to all 3 buttons. And the active class looks different on each of the buttons. How can I fix this?

答:
You can do it this way :

Template side :

```<code><div class="button-container">
    <button class="rules" [class.active]="active.rules" (click)="toggleActive('rules')" type="button">Rules</button>
    <button class="dailies" [class.active]="active.dailies" (click)="toggleActive('dailies')" type="button">Dailies</button>
    <button class="emotions" [class.active]="active.emotions" (click)="toggleActive('emotions')" type="button">Emotions</button>
</div>
</code>```

Component side :

```<code>active = {};

toggleActive(el): void {
    this.active[el] = this.active[el] ? false : true;
}
</code>```

WORKING DEMO

Body:
I'm trying to apply a CSS class only to the button that was clicked (to set it active).

Here's my code:

filter.component.html

    <button class="rules" [class.active]="active" (click)="toggleActive()" type="button">Rules</button>
    <button class="dailies" [class.active]="active" (click)="toggleActive()" type="button">Dailies</button>
    <button class="emotions" [class.active]="active" (click)="toggleActive()" type="button">Emotions</button>

filter.component.ts

export class FilterComponent {
    active: boolean = false;

    toggleActive(): void {
      this.active = !this.active;
    }
  constructor() {}
}

My problem is, the class gets applied to all 3 buttons. And the active class looks different on each of the buttons. How can I fix this?

Body:
You can do it this way :

Template side :

<div class="button-container">
    <button class="rules" [class.active]="active.rules" (click)="toggleActive('rules')" type="button">Rules</button>
    <button class="dailies" [class.active]="active.dailies" (click)="toggleActive('dailies')" type="button">Dailies</button>
    <button class="emotions" [class.active]="active.emotions" (click)="toggleActive('emotions')" type="button">Emotions</button>
</div>

Component side :

active = {};

toggleActive(el): void {
    this.active[el] = this.active[el] ? false : true;
}

WORKING DEMO


问:
Python produce function names from string
I would like to use functions based on strings passed in argument as below. The code gives the following error: AttributeError: 'Obj' object has no attribute 'funA'

The functions funA and funB are defined within fun because they are only used within fun and nowhere else

```<code>class Obj(object):
    def __init__(self):
        self.A = 2
        self.B = 3

    def fun(self, ar):
        def funA(self):
            print self.A

        def funB(self):
            x = self.B + 4
            print self.B

        for letter in ar:
            name = 'fun' + letter
            getattr(self, name)()

obj_instance = Obj()
obj_instance.fun(['A', 'B'])
</code>```

答:
As an alternative you can try the following code. It gives you the opportunity to check whether a function exists or not.</p>

```<code>class Obj(object):
    def __init__(self):
        self.A = 2
        self.B = 3

    def fun(self, ar):
        def funA():
            print self.A

        def funB():
            x = self.B + 4
            print self.B
            print x

        for letter in ar:
            name = 'fun' + letter
            if name in locals():
                locals()[name]()

obj_instance = Obj()
obj_instance.fun(['A', 'B'])
</code>```

Body:
I would like to use functions based on strings passed in argument as below. The code gives the following error: AttributeError: 'Obj' object has no attribute 'funA'

The functions funA and funB are defined within fun because they are only used within fun and nowhere else

class Obj(object):
    def __init__(self):
        self.A = 2
        self.B = 3

    def fun(self, ar):
        def funA(self):
            print self.A

        def funB(self):
            x = self.B + 4
            print self.B

        for letter in ar:
            name = 'fun' + letter
            getattr(self, name)()

obj_instance = Obj()
obj_instance.fun(['A', 'B'])

Body:
As an alternative you can try the following code. It gives you the opportunity to check whether a function exists or not.

class Obj(object):
    def __init__(self):
        self.A = 2
        self.B = 3

    def fun(self, ar):
        def funA():
            print self.A

        def funB():
            x = self.B + 4
            print self.B
            print x

        for letter in ar:
            name = 'fun' + letter
            if name in locals():
                locals()[name]()

obj_instance = Obj()
obj_instance.fun(['A', 'B'])


问:
Express + JWT exclude certain routes
I have an Node application running with express and jsonwebtoken. I have made a check before every request for the api calls to check the jsonwebtoken. I have manually excluded the routes like below. Is there any better way to exclude some routes from this? How can I do that?

```<code>import * as express from 'express';
import * as jwt from 'jsonwebtoken';

import UserCtrl from './controllers/user';

export default function setRoutes(app) {

  const router = express.Router();

  // route middleware to verify a token
  router.use(function (req, res, next) {
    if ((req.method == 'POST' || req.method == 'OPTIONS') && (req.url == '/user' || req.url == '/login' || req.url == '/user/activate')) {
      next();
    } else {
      // check header or url parameters or post parameters for token
      var token = req.headers.authorization;
      // decode token
      if (token) {
        // verifies secret and checks exp
        jwt.verify(token, process.env.SECRET_TOKEN, function (err, decoded) {
          if (err) {
            return res.status(401).send({
              success: false,
              message: 'Sign in to continue.'
            });
          } else {
            // if everything is good, save to request for use in other routes
            next();
          }
        });
      } else {
        // if there is no token
        // return an error
        return res.status(401).send({
          success: false,
          message: 'Sign in to continue.'
        });
      }
    }
  });

  const userCtrl = new UserCtrl();

  router.route('/login').post(userCtrl.login);
  router.route('/user/activate').post(userCtrl.activate);
  router.route('/users').get(userCtrl.getAll);
  router.route('/users/count').get(userCtrl.count);
  router.route('/user').post(userCtrl.signup);
  router.route('/user/:id').get(userCtrl.get);
  router.route('/user/:id').put(userCtrl.update);
  router.route('/user/:id').delete(userCtrl.delete);

  app.use('/api/v1', router);
}
</code>```

答:
You can extract the function (the one that verifies the token) and use it as a middleware for specific routes in your router. That way you don't have to specify which routes that need login inside the function.

Like this:

```<code>function isLoggedIn(req, res, next) {
    // check header or url parameters or post parameters for token
    var token = req.headers.authorization;
    // decode token
    if (token) {
        // verifies secret and checks exp
        jwt.verify(token, process.env.SECRET_TOKEN, function(err, decoded) {
            if (err) {
                return res.status(401).send({
                    success: false,
                    message: 'Sign in to continue.'
                });
            } else {
                // if everything is good, save to request for use in other routes
                next();
            }
        });
    } else {
        // if there is no token
        // return an error
        return res.status(401).send({
            success: false,
            message: 'Sign in to continue.'
        });
    }
}

const userCtrl = new UserCtrl();

// Routes that require no login
router.post('/login', userCtrl.login);
router.get('/users', userCtrl.getAll);
router.post('/user/activate', userCtrl.activate);

// Routes that require login
router.get('/users/count', isLoggedIn, userCtrl.count);
router.post('/user', isLoggedIn, userCtrl.signup);
router.get('/user/:id', isLoggedIn, userCtrl.get);
router.put('/user/:id', isLoggedIn, userCtrl.update);
router.delete('/user/:id', isLoggedIn, userCtrl.delete);

app.use('/api/v1', router);
</code>```

You can read more about Express Middlewares here.

Title: Express + JWT exclude certain routes

Body:
I have an Node application running with express and jsonwebtoken. I have made a check before every request for the api calls to check the jsonwebtoken. I have manually excluded the routes like below. Is there any better way to exclude some routes from this? How can I do that?

import * as express from 'express';
import * as jwt from 'jsonwebtoken';

import UserCtrl from './controllers/user';

export default function setRoutes(app) {

  const router = express.Router();

  // route middleware to verify a token
  router.use(function (req, res, next) {
    if ((req.method == 'POST' || req.method == 'OPTIONS') && (req.url == '/user' || req.url == '/login' || req.url == '/user/activate')) {
      next();
    } else {
      // check header or url parameters or post parameters for token
      var token = req.headers.authorization;
      // decode token
      if (token) {
        // verifies secret and checks exp
        jwt.verify(token, process.env.SECRET_TOKEN, function (err, decoded) {
          if (err) {
            return res.status(401).send({
              success: false,
              message: 'Sign in to continue.'
            });
          } else {
            // if everything is good, save to request for use in other routes
            next();
          }
        });
      } else {
        // if there is no token
        // return an error
        return res.status(401).send({
          success: false,
          message: 'Sign in to continue.'
        });
      }
    }
  });

  const userCtrl = new UserCtrl();

  router.route('/login').post(userCtrl.login);
  router.route('/user/activate').post(userCtrl.activate);
  router.route('/users').get(userCtrl.getAll);
  router.route('/users/count').get(userCtrl.count);
  router.route('/user').post(userCtrl.signup);
  router.route('/user/:id').get(userCtrl.get);
  router.route('/user/:id').put(userCtrl.update);
  router.route('/user/:id').delete(userCtrl.delete);

  app.use('/api/v1', router);
}

Body:
You can extract the function (the one that verifies the token) and use it as a middleware for specific routes in your router. That way you don't have to specify which routes that need login inside the function.

Like this:

function isLoggedIn(req, res, next) {
    // check header or url parameters or post parameters for token
    var token = req.headers.authorization;
    // decode token
    if (token) {
        // verifies secret and checks exp
        jwt.verify(token, process.env.SECRET_TOKEN, function(err, decoded) {
            if (err) {
                return res.status(401).send({
                    success: false,
                    message: 'Sign in to continue.'
                });
            } else {
                // if everything is good, save to request for use in other routes
                next();
            }
        });
    } else {
        // if there is no token
        // return an error
        return res.status(401).send({
            success: false,
            message: 'Sign in to continue.'
        });
    }
}

const userCtrl = new UserCtrl();

// Routes that require no login
router.post('/login', userCtrl.login);
router.get('/users', userCtrl.getAll);
router.post('/user/activate', userCtrl.activate);

// Routes that require login
router.get('/users/count', isLoggedIn, userCtrl.count);
router.post('/user', isLoggedIn, userCtrl.signup);
router.get('/user/:id', isLoggedIn, userCtrl.get);
router.put('/user/:id', isLoggedIn, userCtrl.update);
router.delete('/user/:id', isLoggedIn, userCtrl.delete);

app.use('/api/v1', router);

You can read more about Express Middlewares here.


问:
MySQL - Get similarity score from where two different rows meet same condition from two columns
What I want to do is generate a similarity percentage amount by comparing a ratings column from one table with the ratings column from another table.

However, this needs to be limited to instances where an id from one table matches an id in another table, is for a specific user and a rating exists in the ratings column from both tables.

For example, table1 has the following columns and data:

```<code>   id   |   rate (out of 10)
=====================
   1    |    8
   2    |    10
   3    |    5
   4    |    4
   5    |    0
   6    |    9
   7    |    8
</code>```

And table2 has the following columns and data:

```<code> movid  |   userid   |   rating (out of 10)
================================
   1    |     3      |    6
   2    |     2      |    10
   3    |     1      |    4
   4    |     3      |    7
   5    |     3      |    6
   6    |     4      |    8
   7    |     3      |    5
</code>```

So lets say I want to use any rows where 'userid' = 3 and compare their 'rating' from table2 to the 'rate' column from table1 where 'rate' > 0 and id/movid from the two tables has the same number.

Using the example above, the results to compare should be limited to:

```<code>   id   |   rate
=====================
   1    |    8
   4    |    4
   7    |    8

 movid  |   userid   |   rating
================================
   1    |     3      |    6
   4    |     3      |    7
   7    |     3      |    5
</code>```

Even though userid 3 had a rating for movid 5 in table2, it had a 0 rate (no rating) for id 5 in table1, so it will not compare those.

This would compare the ratings for each id/movid and then put it into an overall total. As the rating numbers are based on a score out of 10, I'm guessing the best way to determine the similarity percentage is to take the difference between each id/movid, subtract it from 10 to get the percentage number.

For id/movid 1, 'rate' in table1 is 8 and 'rating' in table2 is 6. The difference between those numbers is 2. We subtract 2 from 10, to get 80% similarity score for id/movid 1.

That would need to happen for each comparison and then total it all together.

So by my calculation, the similarity score for id/movid 1, 4 and 7 all combined would be 73% (rounded without decimals).

This total percentage amount is the end result I am trying to achieve. Can anyone help me out? I'm now bald after all of the hair I've pulled out trying to get this to work.

答:
Following is not the best solution, but it should work:</p>

```<code>select ROUND(sum(tmp.similarity_score)/max(tmp.cnt)) as Total_similarity_score
from
(
select t1.id,t1.rate,t2.movid,t2.rating,
(10 - abs(t1.rate-t2.rating))*10 as similarity_score,
(@cnt := @cnt +1)  as cnt
from t1
inner join t2
on t2.movid = t1.id
cross join (select @cnt := 0)r
where userid = 3
and t1.rate <> 0
)tmp
;
</code>```

Body:
What I want to do is generate a similarity percentage amount by comparing a ratings column from one table with the ratings column from another table.

However, this needs to be limited to instances where an id from one table matches an id in another table, is for a specific user and a rating exists in the ratings column from both tables.

For example, table1 has the following columns and data:

   id   |   rate (out of 10)
=====================
   1    |    8
   2    |    10
   3    |    5
   4    |    4
   5    |    0
   6    |    9
   7    |    8

And table2 has the following columns and data:

 movid  |   userid   |   rating (out of 10)
================================
   1    |     3      |    6
   2    |     2      |    10
   3    |     1      |    4
   4    |     3      |    7
   5    |     3      |    6
   6    |     4      |    8
   7    |     3      |    5

So lets say I want to use any rows where 'userid' = 3 and compare their 'rating' from table2 to the 'rate' column from table1 where 'rate' > 0 and id/movid from the two tables has the same number.

Using the example above, the results to compare should be limited to:

   id   |   rate
=====================
   1    |    8
   4    |    4
   7    |    8

 movid  |   userid   |   rating
================================
   1    |     3      |    6
   4    |     3      |    7
   7    |     3      |    5

Even though userid 3 had a rating for movid 5 in table2, it had a 0 rate (no rating) for id 5 in table1, so it will not compare those.

This would compare the ratings for each id/movid and then put it into an overall total. As the rating numbers are based on a score out of 10, I'm guessing the best way to determine the similarity percentage is to take the difference between each id/movid, subtract it from 10 to get the percentage number.

For id/movid 1, 'rate' in table1 is 8 and 'rating' in table2 is 6. The difference between those numbers is 2. We subtract 2 from 10, to get 80% similarity score for id/movid 1.

That would need to happen for each comparison and then total it all together.

So by my calculation, the similarity score for id/movid 1, 4 and 7 all combined would be 73% (rounded without decimals).

This total percentage amount is the end result I am trying to achieve. Can anyone help me out? I'm now bald after all of the hair I've pulled out trying to get this to work.

Body:
Following is not the best solution, but it should work:

select ROUND(sum(tmp.similarity_score)/max(tmp.cnt)) as Total_similarity_score
from
(
select t1.id,t1.rate,t2.movid,t2.rating,
(10 - abs(t1.rate-t2.rating))*10 as similarity_score,
(@cnt := @cnt +1)  as cnt
from t1
inner join t2
on t2.movid = t1.id
cross join (select @cnt := 0)r
where userid = 3
and t1.rate <> 0
)tmp
;


问:
How to repeatedly show a Dialog with PyGTK / Gtkbuilder?
I have created a PyGTK application that shows a Dialog when the user presses a button.
The dialog is loaded in my __init__ method with:

```<code>builder = gtk.Builder()
builder.add_from_file("filename")
builder.connect_signals(self)
self.myDialog = builder.get_object("dialog_name")
</code>```

In the event handler, the dialog is shown with the command self.myDialog.run(), but this only works once, because after run() the dialog is automatically destroyed. If I click the button a second time, the application crashes.

I read that there is a way to use show() instead of run() where the dialog is not destroyed, but I feel like this is not the right way for me because I would like the dialog to behave modally and to return control to the code only after the user has closed it.

Is there a simple way to repeatedly show a dialog using the run() method using gtkbuilder? I tried reloading the whole dialog using the gtkbuilder, but that did not really seem to work, the dialog was missing all child elements (and I would prefer to have to use the builder only once, at the beginning of the program).

[SOLUTION] (edited)

As pointed out by the answer below, using hide() does the trick. I first thought you still needed to catch the "delete-event", but this in fact not necessary. A simple example that works is:

```<code>
import pygtk
import gtk

class DialogTest:

    def rundialog(self, widget, data=None):
        self.dia.show_all()
        result = self.dia.run()
        self.dia.hide()

    def destroy(self, widget, data=None):
        gtk.main_quit()

    def __init__(self):
        self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
        self.window.connect("destroy", self.destroy)

        self.dia = gtk.Dialog('TEST DIALOG', self.window,
           gtk.DIALOG_MODAL  | gtk.DIALOG_DESTROY_WITH_PARENT)
        self.dia.vbox.pack_start(gtk.Label('This is just a Test'))

        self.button = gtk.Button("Run Dialog")
        self.button.connect("clicked", self.rundialog, None)
        self.window.add(self.button)
        self.button.show()
        self.window.show()

if __name__ == "__main__":
    testApp = DialogTest()
    gtk.main()
</code>```

答:
Your dialog should only need to run once. Assuming a menu item triggers the dialog, the code should look something like this:

```<code>def on_menu_item_clicked(self, widget, data=None):
    dialog = FunkyDialog()
    response = dialog.run()

    if response = gtk.RESPONSE_OK:
        // do something with the dialog data

    dialog.destroy()
</code>```

dialog.run() is a blocking main-loop that returns when the dialog send a response. This is normally done via the Ok and Cancel buttons. When this happens, the dialog is finished and needs to be destroyed.

To show the dialog repeatedly, the user should follow the same workflow (in the example above, that would be clicking on a menu item). The dialog is responsible, in __init__, for setting itself up. If you hide() the dialog, you have the problem of communicating with that dialog so it stays up-to-date with the rest of the application even when it's hidden.

One of the reasons some people want to "run the dialog repeatedly" is because the user has entered invalid information, and you want to give the user the opportunity to correct it. This must be dealt with in the dialog's response signal handler. The order of events in a dialog is:

User physically pushes the Ok button

Dialog sends the response gtk.RESPONSE_OK (-5)

Dialog calls the handler for the response signal

Dialog calls the handler for the Ok button

Dialog run() method returns the response

To prevent steps 4 and 5 from happening, the response handler must suppress the response signal. This is achieved as follows:

```<code>def on_dialog_response(self, dialog, response, data=None:
    if response == gtk.RESPONSE_OK:
        if data_is_not_valid:
            # Display an error message to the user

            # Suppress the response
            dialog.emit_stop_by_name('response')
</code>```

Body:
I have created a PyGTK application that shows a Dialog when the user presses a button.
The dialog is loaded in my __init__ method with:

builder = gtk.Builder()
builder.add_from_file("filename")
builder.connect_signals(self)
self.myDialog = builder.get_object("dialog_name")

In the event handler, the dialog is shown with the command self.myDialog.run(), but this only works once, because after run() the dialog is automatically destroyed. If I click the button a second time, the application crashes.

I read that there is a way to use show() instead of run() where the dialog is not destroyed, but I feel like this is not the right way for me because I would like the dialog to behave modally and to return control to the code only after the user has closed it.

Is there a simple way to repeatedly show a dialog using the run() method using gtkbuilder? I tried reloading the whole dialog using the gtkbuilder, but that did not really seem to work, the dialog was missing all child elements (and I would prefer to have to use the builder only once, at the beginning of the program).

[SOLUTION] (edited)

As pointed out by the answer below, using hide() does the trick. I first thought you still needed to catch the "delete-event", but this in fact not necessary. A simple example that works is:

import pygtk
import gtk

class DialogTest:

    def rundialog(self, widget, data=None):
        self.dia.show_all()
        result = self.dia.run()
        self.dia.hide()

    def destroy(self, widget, data=None):
        gtk.main_quit()

    def __init__(self):
        self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
        self.window.connect("destroy", self.destroy)

        self.dia = gtk.Dialog('TEST DIALOG', self.window,
           gtk.DIALOG_MODAL  | gtk.DIALOG_DESTROY_WITH_PARENT)
        self.dia.vbox.pack_start(gtk.Label('This is just a Test'))

        self.button = gtk.Button("Run Dialog")
        self.button.connect("clicked", self.rundialog, None)
        self.window.add(self.button)
        self.button.show()
        self.window.show()

if __name__ == "__main__":
    testApp = DialogTest()
    gtk.main()

Body:
Your dialog should only need to run once. Assuming a menu item triggers the dialog, the code should look something like this:

def on_menu_item_clicked(self, widget, data=None):
    dialog = FunkyDialog()
    response = dialog.run()

    if response = gtk.RESPONSE_OK:
        // do something with the dialog data

    dialog.destroy()

dialog.run() is a blocking main-loop that returns when the dialog send a response. This is normally done via the Ok and Cancel buttons. When this happens, the dialog is finished and needs to be destroyed.

To show the dialog repeatedly, the user should follow the same workflow (in the example above, that would be clicking on a menu item). The dialog is responsible, in __init__, for setting itself up. If you hide() the dialog, you have the problem of communicating with that dialog so it stays up-to-date with the rest of the application even when it's hidden.

One of the reasons some people want to "run the dialog repeatedly" is because the user has entered invalid information, and you want to give the user the opportunity to correct it. This must be dealt with in the dialog's response signal handler. The order of events in a dialog is:

User physically pushes the Ok button

Dialog sends the response gtk.RESPONSE_OK (-5)

Dialog calls the handler for the response signal

Dialog calls the handler for the Ok button

Dialog run() method returns the response

To prevent steps 4 and 5 from happening, the response handler must suppress the response signal. This is achieved as follows:

def on_dialog_response(self, dialog, response, data=None:
    if response == gtk.RESPONSE_OK:
        if data_is_not_valid:
            # Display an error message to the user

            # Suppress the response
            dialog.emit_stop_by_name('response')


问:
adb command fail to execute if path contain spaces
I am trying to delete the file using adb command. But the file contain spaces. So adb command throws an error after reading half of the file name till space. Is there a way to overcome this issue. I am executing following adb command

When I execute

```<code>adb shell rm /sdcard/samsung_Nexus S_converter.xml
</code>```

Error message: rm failed for /sdcard/samsung_Nexus, No such file or directory

How ever when I execute:

```<code>adb shell rm /sdcard/samsung_Nexus_S_converter.xml
</code>```

File deletion is successful

I searched for solution for this, if there is any workaround. How ever I couldnt find any.

答:
By me it wasn't enough to escape spaces with backslashes:

```<code>$ adb shell ls /storage/sdcard1/audio/Die\ Toten\ Hosen/
/storage/sdcard1/audio/Die: No such file or directory
Toten: No such file or directory
Hosen/: No such file or directory
</code>```

For some reason I also had to surround the path with ' (single quotation):

```<code>$ adb shell ls '/storage/sdcard1/audio/Die\ Toten\ Hosen/'
03 - Boxed Set
04 - Compilations
05 - Live Albums
</code>```

While surrounding without escaping didn't work:

```<code>$ adb shell ls '/storage/sdcard1/audio/Die Toten Hosen'
/storage/sdcard1/audio/Die: No such file or directory
Toten: No such file or directory
Hosen: No such file or directory
</code>```

Body:
I am trying to delete the file using adb command. But the file contain spaces. So adb command throws an error after reading half of the file name till space. Is there a way to overcome this issue. I am executing following adb command

When I execute

adb shell rm /sdcard/samsung_Nexus S_converter.xml

Error message: rm failed for /sdcard/samsung_Nexus, No such file or directory

How ever when I execute:

adb shell rm /sdcard/samsung_Nexus_S_converter.xml

File deletion is successful

I searched for solution for this, if there is any workaround. How ever I couldnt find any.

Body:
By me it wasn't enough to escape spaces with backslashes:

$ adb shell ls /storage/sdcard1/audio/Die\ Toten\ Hosen/
/storage/sdcard1/audio/Die: No such file or directory
Toten: No such file or directory
Hosen/: No such file or directory

For some reason I also had to surround the path with ' (single quotation):

$ adb shell ls '/storage/sdcard1/audio/Die\ Toten\ Hosen/'
03 - Boxed Set
04 - Compilations
05 - Live Albums

While surrounding without escaping didn't work:

$ adb shell ls '/storage/sdcard1/audio/Die Toten Hosen'
/storage/sdcard1/audio/Die: No such file or directory
Toten: No such file or directory
Hosen: No such file or directory


问:
How to get the Total Disk Space and Free Disk space using AttributesOfFileSystemForpaths in swift 2.0
This is the way I use in Objective-C

```<code>-(uint64_t)getFreeDiskspace {
float totalSpace = 0;
float totalFreeSpace = 0;
NSError *error = nil;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSDictionary *dictionary = [[NSFileManager defaultManager] attributesOfFileSystemForPath:[paths lastObject] error: &error];

if (dictionary) {
    NSNumber *fileSystemSizeInBytes = [dictionary objectForKey: NSFileSystemSize];
    NSNumber *freeFileSystemSizeInBytes = [dictionary objectForKey:NSFileSystemFreeSize];
    totalSpace = [fileSystemSizeInBytes floatValue];
    self.totalSpace = [NSString stringWithFormat:@"%.3f GB",totalSpace/(1024*1024*1024)];
    totalFreeSpace = [freeFileSystemSizeInBytes unsignedLongLongValue];
    self.freeSpace = [NSString stringWithFormat:@"%.3f GB",totalFreeSpace/(1024*1024*1024)];

} else {
    LogError(@"Error Obtaining System Memory Info: Domain = %@, Code = %ld", [error domain], (long)[error code]);
}

return totalFreeSpace;
</code>```

}

I tried converting it to swift and errors in

```<code>if(dictionary)
</code>```

and

```<code>attributesOfFileSystemForPaths
</code>```

were shown.Can anyone help me in converting this to swift 2.0 ? It would do a world of good to my project. Thank You in Advance.

答:
Update Swift-4

```<code>func getFreeDiskspace() -> Int64? {
        let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
        if let dictionary = try? FileManager.default.attributesOfFileSystem(forPath: paths.last!) {
            if let freeSize = dictionary[FileAttributeKey.systemFreeSize] as? NSNumber {
                return freeSize.int64Value
            }
        }else{
            print("Error Obtaining System Memory Info:")
        }
        return nil
    }

if let getFreespace = getFreeDiskspace() {
   print(getFreespace) // free disk space
}
</code>```

Body:
This is the way I use in Objective-C

-(uint64_t)getFreeDiskspace {
float totalSpace = 0;
float totalFreeSpace = 0;
NSError *error = nil;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSDictionary *dictionary = [[NSFileManager defaultManager] attributesOfFileSystemForPath:[paths lastObject] error: &error];

if (dictionary) {
    NSNumber *fileSystemSizeInBytes = [dictionary objectForKey: NSFileSystemSize];
    NSNumber *freeFileSystemSizeInBytes = [dictionary objectForKey:NSFileSystemFreeSize];
    totalSpace = [fileSystemSizeInBytes floatValue];
    self.totalSpace = [NSString stringWithFormat:@"%.3f GB",totalSpace/(1024*1024*1024)];
    totalFreeSpace = [freeFileSystemSizeInBytes unsignedLongLongValue];
    self.freeSpace = [NSString stringWithFormat:@"%.3f GB",totalFreeSpace/(1024*1024*1024)];

} else {
    LogError(@"Error Obtaining System Memory Info: Domain = %@, Code = %ld", [error domain], (long)[error code]);
}

return totalFreeSpace;

}

I tried converting it to swift and errors in

if(dictionary)

and

attributesOfFileSystemForPaths

were shown.Can anyone help me in converting this to swift 2.0 ? It would do a world of good to my project. Thank You in Advance.

Body:
Update Swift-4

func getFreeDiskspace() -> Int64? {
        let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
        if let dictionary = try? FileManager.default.attributesOfFileSystem(forPath: paths.last!) {
            if let freeSize = dictionary[FileAttributeKey.systemFreeSize] as? NSNumber {
                return freeSize.int64Value
            }
        }else{
            print("Error Obtaining System Memory Info:")
        }
        return nil
    }

if let getFreespace = getFreeDiskspace() {
   print(getFreespace) // free disk space
}


问:
Swift - CollectionView Add Single Cell With Custom Animation
I have a UIViewController with a CollectionView inside of it, and a button that simply adds a new cell to the end of the CollectionView.
I add it by using this:

```<code>func addNewFolderCell {
    self.folder!.childFolders!.append(folder)
    let count = self.folder!.childFolders!.count
    let index = count > 0 ? count - 1 : count
    let indexPath = IndexPath(item: index, section: 0)
    collectionView?.performBatchUpdates({
        collectionView!.insertItems(at: [indexPath])
    })
}
</code>```

And that works, but I'd like to customize the default animation, so that I can perform a scale and fade in when the cell is added. I.E.:

```<code>UIView.animate(withDuration: 1.4, delay: 0.15 * Double(indexPath.row),  animations: {
    cell.alpha = 1.0
    cell.transform = CGAffineTransform(scaleX: 1.0, y: 1.0)
})
</code>```

I found this tutorial, but I can't figure out how to get it to work when you're in a UIViewController instead of a UICollectionViewController:

https://littlebitesofcocoa.com/306-customizing-collection-view-cell-insertion-animations

答:
Just try this answer and tell me it's working for you or not.

 Don't forget to call UICollectionViewDelegateFlowLayout

```<code>var insertingIndexPaths = [IndexPath]()

 func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
    let attributes = "YourCollectionview".layoutAttributesForItem(at: indexPath)

    if insertingIndexPaths.contains(indexPath) {
        attributes?.alpha = 1.0
        attributes?.transform = CGAffineTransform(
            scaleX: 0.1,
            y: 0.1
        )
    }
    return attributes
}
</code>```

//Here is your button click to insert new item

```<code>@IBAction func btn_click_sign_in(_ sender: Any) {
        //here you have insert one item into your array
        // for Exa. My array count is 3 here.
        // So I am adding new object array.append(element)

        let indexPath = IndexPath(
            item: **yourArray count** - 1,
            section: 0
        )
        "YourCollectionview"?.performBatchUpdates({
            self.coll_pagview?.insertItems(at: [indexPath])
        }, completion: nil)
    }
</code>```

Body:
I have a UIViewController with a CollectionView inside of it, and a button that simply adds a new cell to the end of the CollectionView.
I add it by using this:

func addNewFolderCell {
    self.folder!.childFolders!.append(folder)
    let count = self.folder!.childFolders!.count
    let index = count > 0 ? count - 1 : count
    let indexPath = IndexPath(item: index, section: 0)
    collectionView?.performBatchUpdates({
        collectionView!.insertItems(at: [indexPath])
    })
}

And that works, but I'd like to customize the default animation, so that I can perform a scale and fade in when the cell is added. I.E.:

UIView.animate(withDuration: 1.4, delay: 0.15 * Double(indexPath.row),  animations: {
    cell.alpha = 1.0
    cell.transform = CGAffineTransform(scaleX: 1.0, y: 1.0)
})

I found this tutorial, but I can't figure out how to get it to work when you're in a UIViewController instead of a UICollectionViewController:

https://littlebitesofcocoa.com/306-customizing-collection-view-cell-insertion-animations

Body:
Just try this answer and tell me it's working for you or not.

 Don't forget to call UICollectionViewDelegateFlowLayout

var insertingIndexPaths = [IndexPath]()

 func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
    let attributes = "YourCollectionview".layoutAttributesForItem(at: indexPath)

    if insertingIndexPaths.contains(indexPath) {
        attributes?.alpha = 1.0
        attributes?.transform = CGAffineTransform(
            scaleX: 0.1,
            y: 0.1
        )
    }
    return attributes
}

//Here is your button click to insert new item

@IBAction func btn_click_sign_in(_ sender: Any) {
        //here you have insert one item into your array
        // for Exa. My array count is 3 here.
        // So I am adding new object array.append(element)

        let indexPath = IndexPath(
            item: **yourArray count** - 1,
            section: 0
        )
        "YourCollectionview"?.performBatchUpdates({
            self.coll_pagview?.insertItems(at: [indexPath])
        }, completion: nil)
    }


问:
Getting the value of dropdownlist in php
I have the following the html/php code :

```<code><!DOCTYPE html>
<html>
<head>
    <title>Voiture</title>
</head>

<body>
    Welcome<br>
    <form method="post" action="">
        Liste de voiture<select name="selected" id="selected">
            <?php
            $sql = 'select Type from voiture';
            $result = $conn->query($sql);
            $json = array();
            while ($row = $result->fetch_assoc()) {
                if(!in_array($row['Type'], $json)){
                    $json[] = $row['Type'];
                    echo '<option name = "'.$row['Type'].'">'.$row['Type'].'</option>';
                }
            }
               ?>

        </select> <br>

        <span id="sel" name="sel"></span>
        <table border="1">
            <tr id="header">
                <td>Type</td>
                <td>Model</td>
                <td>Couleur</td>
                <td>Prix</td>
                <td>User</td>
                <td>Action</td>
            </tr>
        </table>
        <input type="submit" name="submit" hidden>
    </form>
    <script src="jquery-3.2.1.js"></script>
    <script>
        $(function(){
            $('#selected').on('change',function(){
                $('#sel').text(document.getElementById('selected').value);
                $.getJSON('phpVoiture.php',function(data){
                    for (var x = 0 ; x < data.length ; x++){
                        $('<tr><td>'+data[x]['type']+'</td>'+'<td>'+data[x]['Model']+
                                '</td><td>'+data[x]['Couleur']+'</td>'+
                                '<td>'+data[x]['Prix']+'</td>'+'<td></td></tr>').insertAfter($('#header'));
                    }
                });
            });
        });
    </script>
</body>
</html>
</code>```

And the following php page :

```<code><?php

require_once ('./dbConnect.php');
include ('./Voiture.php');

$sel = $_POST['selected'];
$conn = mysqli_connect(servername, username, password, db ,port);
$query = "select * from voiture where Type = '".sel."'";
$result = mysqli_query($conn, $query);
$json = array();
if(mysqli_num_rows($result)>0){
    while($row = mysqli_fetch_assoc($result)){
        $json[] = [
            'type' => $row['Type'],
            'model' => $row['Model'],
            'couleur' => $row['Couleur'],
            'prix' => $row['Prix']
        ];
    }
}
else{
    echo mysqli_num_rows($result);
}
echo json_encode($json);
</code>```

The problem is that when I select an option in the drop down list nothing happens. I want the query in the second php page to select the cars that have the type that I selected in the drop down list. I tried troubleshooting by echo an alert in both pages that have the value of the selected option, but this step also failed, so I think there is an issue with retrieving the value of the selected option. Any help would be appreciated.

答:
You're not sending the selected value to the server.  Add it to the AJAX call:

```<code>$.getJSON('phpVoiture.php', { selected: $('#selected').val() }, function(data){
    //...
});
</code>```

Also, your <option> elements don't have values.  You used name instead, but that belongs on the <select>.  Use value:

```<code>echo '<option value="'.$row['Type'].'">'.$row['Type'].'</option>';
</code>```

Additionally, you're using a GET request instead of a POST request.  So you need to look for the value in the $_GET array:

```<code>$sel = $_GET['selected'];
</code>```

You have other typos too, such as an incorrect use of a variable in PHP:

```<code>"...".sel."..."
</code>```

would be:

```<code>"...".$sel."..."
</code>```

Though this brings up a point about SQL injection.  You really shouldn't be directly concatenating the variable like that at all.  Instead, use prepared statements with query parameters.

It's entirely possible that there continue to be other mistakes in the code I simply haven't spotted yet.  You'll want your debugging to include two things:

Looking at your PHP logs for errors.

Using your browser's debugging tools to observe the AJAX request/response.

Body:
I have the following the html/php code :

<!DOCTYPE html>

    <title>Voiture</title>

    Welcome

    <form method="post" action="">
        Liste de voiture<select name="selected" id="selected">
            <?php
            $sql = 'select Type from voiture';
            $result = $conn->query($sql);
            $json = array();
            while ($row = $result->fetch_assoc()) {
                if(!in_array($row['Type'], $json)){
                    $json[] = $row['Type'];
                    echo '<option name = "'.$row['Type'].'">'.$row['Type'].'</option>';
                }
            }
               ?>

        </select>

                Type
                Model
                Couleur
                Prix
                User
                Action

        <input type="submit" name="submit" hidden>
    </form>

And the following php page :

<?php

require_once ('./dbConnect.php');
include ('./Voiture.php');

$sel = $_POST['selected'];
$conn = mysqli_connect(servername, username, password, db ,port);
$query = "select * from voiture where Type = '".sel."'";
$result = mysqli_query($conn, $query);
$json = array();
if(mysqli_num_rows($result)>0){
    while($row = mysqli_fetch_assoc($result)){
        $json[] = [
            'type' => $row['Type'],
            'model' => $row['Model'],
            'couleur' => $row['Couleur'],
            'prix' => $row['Prix']
        ];
    }
}
else{
    echo mysqli_num_rows($result);
}
echo json_encode($json);

The problem is that when I select an option in the drop down list nothing happens. I want the query in the second php page to select the cars that have the type that I selected in the drop down list. I tried troubleshooting by echo an alert in both pages that have the value of the selected option, but this step also failed, so I think there is an issue with retrieving the value of the selected option. Any help would be appreciated.

Body:
You're not sending the selected value to the server.  Add it to the AJAX call:

$.getJSON('phpVoiture.php', { selected: $('#selected').val() }, function(data){
    //...
});

Also, your <option> elements don't have values.  You used name instead, but that belongs on the <select>.  Use value:

echo '<option value="'.$row['Type'].'">'.$row['Type'].'</option>';

Additionally, you're using a GET request instead of a POST request.  So you need to look for the value in the $_GET array:

$sel = $_GET['selected'];

You have other typos too, such as an incorrect use of a variable in PHP:

"...".sel."..."

would be:

"...".$sel."..."

Though this brings up a point about SQL injection.  You really shouldn't be directly concatenating the variable like that at all.  Instead, use prepared statements with query parameters.

It's entirely possible that there continue to be other mistakes in the code I simply haven't spotted yet.  You'll want your debugging to include two things:

Looking at your PHP logs for errors.

Using your browser's debugging tools to observe the AJAX request/response.


问:
Use JavaScript to prevent a later `<script>` tag from being evaluated?
This is a bit of an oddball use case, but I have my reasons:

I'd like to be able to write

```<code><script type="text/javascript" src="first.js"></script>
<script type="text/javascript" src="second.js"></script>
</code>```

in my markup and, using the code in first.js, prevent or delay the execution of second.js. Is this possible, in any browser? What if the contents of first.js are inlined? (If it helps, assume that the second script tag has an id attribute.)

Since I've gotten a couple of answers that missed what I'm getting at, I should clarify:

The solution must be entirely within first.js. Anything that require changes to the original HTML of the page, or to second.js, is not acceptable.

It is acceptable to load second.js via Ajax and execute it using eval. That's the easy part. The hard part is preventing the immediate execution of second.js.

Assume that you don't know what's in second.js. So, you can't just replace each global function called by second.js with a no-op function. (Plus, this would almost certainly lead to errors.)

If you know of a solution that works in some browsers but not in others, I'd love to hear it.

Example: To make this a little more concrete, let's say that the code

```<code><script type="text/javascript">
  function func() {
    window.meaningOfLife = 42;
    window.loadSecond();
  };
  setTimeout(func, 10);
</script>
</code>```

precedes the two script includes, and that second.js contains the line

```<code>if (window.meaningOfLife !== 42) {throw new Error();}
</code>```

first.js should be able to prevent this error by delaying second.js from executing until window.loadSecond is run. (Assume the implementation of window.loadSecond is also in first.js.) It is not allowed to touch window.meaningOfLife.

Update: Alohci's answer meets these requirements, but only on the condition that the second script tag comes immediately after the first, with nothing but whitespace in between. If someone could extend his hack to avoid that requirement, without introducing other unwanted consequences, that would be amazing...

答:
Given your specific requirements set, this is actually quite simple and should work completely cross-browser. It does require however, that first.js immediately precedes second.js without anything between them except white space.

First, let's assume that the HTML looks like this:

```<code><!DOCTYPE html>
<html>
  <head>
    <title>Test Case</title>
    <meta charset="UTF-8" />
    <script type="text/javascript">
      function func() {
        window.meaningOfLife = 42;
        window.loadSecond();
      };
    </script>
    <script type="text/javascript" src="first.js"></script>
    <script type="text/javascript" src="second.js"></script>
  </head>
  <body>
    <p>Lorem ipsum dolor sit amet ...</p>
    <a href="javascript:func()">Run Func()</a>
  </body>
</html>
</code>```

I've removed the setTimeout because that can cause func() to run before start.js runs causing a "loadSecond is not defined" error. Instead, I've provided an anchor to be clicked on to run func().

Second, let's assume that second.js looks like this:

```<code>document.body.appendChild(document.createTextNode("second.js has run. "));
if (window.meaningOfLife !== 42) {throw new Error();}
</code>```

Here, I've just added a line to append some text to the document body, so that it is easier to see when second.js actually runs.

Then the solution for first.js is this:

```<code>function loadSecond()
{
    var runSecond = document.createElement("script");
    runSecond.setAttribute("src", "second.js");
    document.body.appendChild(runSecond);
}

document.write("<script type='application/x-suppress'>");
</code>```

The loadSecond function is just there to run second.js when func() runs.

The key to the solution is the document.write line. It will inject into the HTML

Body:
This is a bit of an oddball use case, but I have my reasons:

I'd like to be able to write

in my markup and, using the code in first.js, prevent or delay the execution of second.js. Is this possible, in any browser? What if the contents of first.js are inlined? (If it helps, assume that the second script tag has an id attribute.)

Since I've gotten a couple of answers that missed what I'm getting at, I should clarify:

The solution must be entirely within first.js. Anything that require changes to the original HTML of the page, or to second.js, is not acceptable.

It is acceptable to load second.js via Ajax and execute it using eval. That's the easy part. The hard part is preventing the immediate execution of second.js.

Assume that you don't know what's in second.js. So, you can't just replace each global function called by second.js with a no-op function. (Plus, this would almost certainly lead to errors.)

If you know of a solution that works in some browsers but not in others, I'd love to hear it.

Example: To make this a little more concrete, let's say that the code

precedes the two script includes, and that second.js contains the line

if (window.meaningOfLife !== 42) {throw new Error();}

first.js should be able to prevent this error by delaying second.js from executing until window.loadSecond is run. (Assume the implementation of window.loadSecond is also in first.js.) It is not allowed to touch window.meaningOfLife.

Update: Alohci's answer meets these requirements, but only on the condition that the second script tag comes immediately after the first, with nothing but whitespace in between. If someone could extend his hack to avoid that requirement, without introducing other unwanted consequences, that would be amazing...

Body:
Given your specific requirements set, this is actually quite simple and should work completely cross-browser. It does require however, that first.js immediately precedes second.js without anything between them except white space.

First, let's assume that the HTML looks like this:

<!DOCTYPE html>
<html>
  <head>
    <title>Test Case</title>
    <meta charset="UTF-8" />
    <script type="text/javascript">
      function func() {
        window.meaningOfLife = 42;
        window.loadSecond();
      };
    </script>
    <script type="text/javascript" src="first.js"></script>
    <script type="text/javascript" src="second.js"></script>
  </head>
  <body>
    <p>Lorem ipsum dolor sit amet ...</p>
    <a href="javascript:func()">Run Func()</a>
  </body>
</html>

I've removed the setTimeout because that can cause func() to run before start.js runs causing a "loadSecond is not defined" error. Instead, I've provided an anchor to be clicked on to run func().

Second, let's assume that second.js looks like this:

document.body.appendChild(document.createTextNode("second.js has run. "));
if (window.meaningOfLife !== 42) {throw new Error();}

Here, I've just added a line to append some text to the document body, so that it is easier to see when second.js actually runs.

Then the solution for first.js is this:

function loadSecond()
{
    var runSecond = document.createElement("script");
    runSecond.setAttribute("src", "second.js");
    document.body.appendChild(runSecond);
}

document.write("<script type='application/x-suppress'>");

The loadSecond function is just there to run second.js when func() runs.

The key to the solution is the document.write line. It will inject into the HTML <script type='application/x-suppress'> between the close script tag of first.js and the open script tag of second.js.

The parser will see this and start a new script element. Because the type attribute has a value which is not one that the browser recognises as being JavaScript, it will not attempt to run its content. (So there are an infinite number of possible type attribute values you could use here, but you must include a type attribute, as in its absence, the browser will assume that the script's content is JavaScript.)

The second.js script's opening tag will then be parsed as text content of the new script element and not executed. Finally the second.js script's closing tag will be re-purposed to close the new script element instead, which means that the remainder of the HTML is parsed correctly.

You can see a working version at http://www.alohci.net/static/jsprevent/jsprevent.htm