问:
How can I reference control added in ngFor?
I am adding several inputs using ngFor in a template driven form and I would like to add corresponding error messages for when the inputs are invalid.  Normally if I was not using ngFor I would use #inputName="ngModel".  Is there any way for me to do something like this in order to reference the dynamically added input?

Basically I want to do something like this:

```<code><div *ngFor="let field of fields; let i = index">
        <label>{{field.label}}</label> <input [ngModel]="field.value" required #field{{i}}="ngModel" />
        <div *ngIf="field{{i}}.invalid"> This field is required </div>
</div>
</code>```

答:
You shouldn't need to do anything special to reference that field in the template - just use an alias directly (e.g. 'f')</p>

```<code>  <div *ngFor="let field of fields; let i = index">
    <label>{{field.label}}</label> <input [ngModel]="field.value" required #f="ngModel" />
    <div *ngIf="f.invalid"> This field is required </div>
  </div>
</code>```

Body:
I am adding several inputs using ngFor in a template driven form and I would like to add corresponding error messages for when the inputs are invalid.  Normally if I was not using ngFor I would use #inputName="ngModel".  Is there any way for me to do something like this in order to reference the dynamically added input?

Basically I want to do something like this:

        {{field.label}} <input [ngModel]="field.value" required #field{{i}}="ngModel" />

 This field is required

Body:
You shouldn't need to do anything special to reference that field in the template - just use an alias directly (e.g. 'f')

  <div *ngFor="let field of fields; let i = index">
    <label>{{field.label}}</label> <input [ngModel]="field.value" required #f="ngModel" />
    <div *ngIf="f.invalid"> This field is required </div>
  </div>


来源: stackexchange

问:
How can I clone an Ember Data record, including relationships?
I've figured out that I can clone an Ember Data record and copy its Attributes, but none of the belongsTo/hasMany relationships are cloned. Can I do this somehow if I don't know what relationships would be possible, going off of the relationships that exist?

For reference, here is what I've got that will clone an Ember Data record's attributes:

```<code>var attributeKeys = oldModel.get('constructor.attributes.keys.list');
var newRecord = this.get('store').createRecord(oldModel.constructor.typeKey);
newRecord.setProperties(oldModel.getProperties(attributeKeys));
</code>```

答:
Here is the simple way to clone your Ember Model with relationships.
working fine.

Create a Copyable mixin like,

```<code>import Ember from 'ember';

export default Ember.Mixin.create(Ember.Copyable, {

    copy(deepClone) {
      var model = this, attrs = model.toJSON(), class_type = model.constructor;
      var root = Ember.String.decamelize(class_type.toString().split(':')[1]);

      if(deepClone) {
          this.eachRelationship(function(key, relationship){
              if (relationship.kind == 'belongsTo') {
                  attrs[key] = model.get(key).copy(true);
              } else if(relationship.kind == 'hasMany' && Ember.isArray(attrs[key])) {
                  attrs[key].splice(0);
                  model.get(key).forEach(function(obj) {
                      attrs[key].addObject(obj.copy(true));
                  });
              }
          });
      }
      return this.store.createRecord(root, attrs);
    }
});
</code>```

Add the mixin in your model,

Note: If you want to clone your child model then, you need to include the mixin in child model as well

USAGE:

With relationship : YOURMODEL.copy(true)

Without relationship : YOURMODEL.copy()

ContentLicense: CC BY-SA 3.0

Body:
I've figured out that I can clone an Ember Data record and copy its Attributes, but none of the belongsTo/hasMany relationships are cloned. Can I do this somehow if I don't know what relationships would be possible, going off of the relationships that exist?

For reference, here is what I've got that will clone an Ember Data record's attributes:

var attributeKeys = oldModel.get('constructor.attributes.keys.list');
var newRecord = this.get('store').createRecord(oldModel.constructor.typeKey);
newRecord.setProperties(oldModel.getProperties(attributeKeys));

Body:
Here is the simple way to clone your Ember Model with relationships.
working fine.

Create a Copyable mixin like,

import Ember from 'ember';

export default Ember.Mixin.create(Ember.Copyable, {

    copy(deepClone) {
      var model = this, attrs = model.toJSON(), class_type = model.constructor;
      var root = Ember.String.decamelize(class_type.toString().split(':')[1]);

      if(deepClone) {
          this.eachRelationship(function(key, relationship){
              if (relationship.kind == 'belongsTo') {
                  attrs[key] = model.get(key).copy(true);
              } else if(relationship.kind == 'hasMany' && Ember.isArray(attrs[key])) {
                  attrs[key].splice(0);
                  model.get(key).forEach(function(obj) {
                      attrs[key].addObject(obj.copy(true));
                  });
              }
          });
      }
      return this.store.createRecord(root, attrs);
    }
});

Add the mixin in your model,

Note: If you want to clone your child model then, you need to include the mixin in child model as well

USAGE:

With relationship : YOURMODEL.copy(true)

Without relationship : YOURMODEL.copy()


问:
Avoid overlapping regex matching in Java
For some reason this piece of Java code is giving me overlapping matches:

```<code>Pattern pat = Pattern.compile("(" + leftContext + ")" + ".*" + "(" + rightContext + ")", Pattern.DOTALL);
</code>```

any way/option so it avoids detecting overlaps? e.g.
leftContext rightContext rightContext
should be be 1 match instead of 2

Here's the complete code:

```<code>public static String replaceWithContext(String input, String leftContext, String rightContext, String newString){
  Pattern pat = Pattern.compile("(" + leftContext + ")" + ".*" + "(" + rightContext + ")", Pattern.DOTALL);
  Matcher matcher = pat.matcher(input);
  StringBuffer buffer = new StringBuffer();

  while (matcher.find()) {
   matcher.appendReplacement(buffer, "");
   buffer.append(matcher.group(1) + newString + matcher.group(2));
  }
  matcher.appendTail(buffer);

  return buffer.toString();
 }
</code>```

So here's the final answer using a negative lookahead, my bad for not realizing * was greedy:

```<code>Pattern pat = Pattern.compile("(" +
    leftContext + ")" + "(?:(?!" +
    rightContext + ").)*" + "(" +
    rightContext + ")", Pattern.DOTALL);
</code>```

答:
Your use of the word "overlapping" is confusing.  Apparently, what you meant was that the regex is too greedy, matching everything from the first leftContext to the last rightContext.  It seems you figured that out already--and came up with a better approach as well--but there's still at least one potential problem.

You said leftContext and rightContext are "plain Strings", by which I assume you meant they aren't supposed to be interpreted as regexes, but they will be.  You need to escape them, or any regex metacharacters they contain will cause incorrect results or run-time exceptions.  The same goes for your replacement string, although only $ and the backslash have special meanings there.  Here's an example (notice the non-greedy .*?, too):

```<code>public static String replaceWithContext(String input, String leftContext, String rightContext, String newString){
  String lcRegex = Pattern.quote(leftContext);
  String rcRegex = Pattern.quote(rightContext);
  String replace = Matcher.quoteReplacment(newString);
  Pattern pat = Pattern.compile("(" + lcRegex + ").*?(" + rcRegex + ")", Pattern.DOTALL);
</code>```

One other thing: if you aren't doing any post-match processing on the matched text, you can use replaceAll instead of rolling your own with appendReplacement and appendTail:

```<code>return input.replaceAll("(?s)(" + lcRegex + ")" +
                        "(?:(?!" + rcRegex + ").)*" +
                        "(" + rcRegex + ")",
    "$1" + replace + "$2");
</code>```

ContentLicense: CC BY-SA 2.5

Body:
For some reason this piece of Java code is giving me overlapping matches:

Pattern pat = Pattern.compile("(" + leftContext + ")" + ".*" + "(" + rightContext + ")", Pattern.DOTALL);

any way/option so it avoids detecting overlaps? e.g.
leftContext rightContext rightContext
should be be 1 match instead of 2

Here's the complete code:

public static String replaceWithContext(String input, String leftContext, String rightContext, String newString){
  Pattern pat = Pattern.compile("(" + leftContext + ")" + ".*" + "(" + rightContext + ")", Pattern.DOTALL);
  Matcher matcher = pat.matcher(input);
  StringBuffer buffer = new StringBuffer();

  while (matcher.find()) {
   matcher.appendReplacement(buffer, "");
   buffer.append(matcher.group(1) + newString + matcher.group(2));
  }
  matcher.appendTail(buffer);

  return buffer.toString();
 }

So here's the final answer using a negative lookahead, my bad for not realizing * was greedy:

Pattern pat = Pattern.compile("(" +
    leftContext + ")" + "(?:(?!" +
    rightContext + ").)*" + "(" +
    rightContext + ")", Pattern.DOTALL);

Body:
Your use of the word "overlapping" is confusing.  Apparently, what you meant was that the regex is too greedy, matching everything from the first leftContext to the last rightContext.  It seems you figured that out already--and came up with a better approach as well--but there's still at least one potential problem.

You said leftContext and rightContext are "plain Strings", by which I assume you meant they aren't supposed to be interpreted as regexes, but they will be.  You need to escape them, or any regex metacharacters they contain will cause incorrect results or run-time exceptions.  The same goes for your replacement string, although only $ and the backslash have special meanings there.  Here's an example (notice the non-greedy .*?, too):

public static String replaceWithContext(String input, String leftContext, String rightContext, String newString){
  String lcRegex = Pattern.quote(leftContext);
  String rcRegex = Pattern.quote(rightContext);
  String replace = Matcher.quoteReplacment(newString);
  Pattern pat = Pattern.compile("(" + lcRegex + ").*?(" + rcRegex + ")", Pattern.DOTALL);

One other thing: if you aren't doing any post-match processing on the matched text, you can use replaceAll instead of rolling your own with appendReplacement and appendTail:

return input.replaceAll("(?s)(" + lcRegex + ")" +
                        "(?:(?!" + rcRegex + ").)*" +
                        "(" + rcRegex + ")",
    "$1" + replace + "$2");


问:
Iframe in Materialize Carousel Not working
In Materialize Carousel method instead of normal images, I have inserted Iframe to embed a web link in slides. On inserting Iframes, clicking to switch slide doesn't work.

Carousel Method:

```<code><div class="carousel">
    <a class="carousel-item"> <iframe style=' max-height: 700px; max-width: 420px; width: 340px; height: 566px;' src='http://www.website.com' frameborder='0' allowfullscreen scrolling='no'></iframe></a>
    <a class="carousel-item"> <iframe style=' max-height: 700px; max-width: 420px; width: 340px; height: 566px;' src='http://www.website.com' frameborder='0' allowfullscreen scrolling='no'></iframe></a>
    <a class="carousel-item"> <iframe style=' max-height: 700px; max-width: 420px; width: 340px; height: 566px;' src='http://www.website.com' frameborder='0' allowfullscreen scrolling='no'></iframe></a>
    <a class="carousel-item"> <iframe style=' max-height: 700px; max-width: 420px; width: 340px; height: 566px;' src='http://www.website.com' frameborder='0' allowfullscreen scrolling='no'></iframe></a>
</div>
</code>```

The non active slides are not clickable. On clicking, they don't get activated.
Kindly help me find a solution

答:
In the iframe's style attribute, add:

```<code>pointer-events: none;
</code>```

to disable click events on the iframe. This will make sure click events correctly bubble up to the Materialize Carousel plugin.

Body:
In Materialize Carousel method instead of normal images, I have inserted Iframe to embed a web link in slides. On inserting Iframes, clicking to switch slide doesn't work.

Carousel Method:

The non active slides are not clickable. On clicking, they don't get activated.
Kindly help me find a solution

Body:
In the iframe's style attribute, add:

pointer-events: none;

to disable click events on the iframe. This will make sure click events correctly bubble up to the Materialize Carousel plugin.


问:
Regular Expression to match account number consisting of specific 3 character string followed by 9 digits
I'm trying to craft a regular expression which will match an account number which consists of specific 3 characters strings followed by 9 digits.
e.g.

```<code>abc123456789
xyz123456789
def987654321
</code>```

I've figured out how to accomplish with the following expression but wanted to know if there was a better way:

```<code>abc[0-9]{9}|xyz[0-9]{9}|def[0-9]{9}
</code>```

答:
You can make the OR only for the specific strings since it is the only one thing changing:</p>

```<code>(abc|xyz|def)[0-9]{9}
</code>```

Body:
I'm trying to craft a regular expression which will match an account number which consists of specific 3 characters strings followed by 9 digits.
e.g.

abc123456789
xyz123456789
def987654321

I've figured out how to accomplish with the following expression but wanted to know if there was a better way:

abc[0-9]{9}|xyz[0-9]{9}|def[0-9]{9}

Body:
You can make the OR only for the specific strings since it is the only one thing changing:

(abc|xyz|def)[0-9]{9}


问:
Alternatives to Model View ViewModel for WPF
I've just been reading Josh Smith's MVVM article and am working on a WPF application at the moment.  I'm umming and ahing about transfering my work so far to MVVM but find the idea of working purely through databinding and ICommands without any UI event handlers, a little daunting in the sense that it could take a while to convert what I've done up to now.

I'm a self taught C#-er and I've yet to apply patterns such as this to my projects which have up to now just been using the code-behind model and separating out business logic and data access into separate assemblies.

I know that my code can get a little confused sometimes with regard to what belongs where so I was looking into patterns as a way to help me get things straight.

What other patterns might I look at?  Any links to articles appreciated.

答: My advice when adopting the MVVM pattern for WPF applications is to leverage off one of the existing toolkits such as MVVMLight by Laurent Bugnion. Once you get your head around messaging the loss of event driven code behind based logic seems plausible.  It's still a little tedious in terms of LOB development if you're coming from an old-school forms over data background but once you are into the swing of it you will see the benefits and UI power that can be derived from bindings and value converters.</p>


问:
How to control memory while using Keras with tensorflow backend?
I have created a wrapper class which initializes a keras.models.Sequential model and has a couple of methods for starting the training process and monitoring the progress. I instantiate this class in my main file and perform the training process. Fairly mundane stuff.

My question is:

How to free all the GPU memory allocated by tensorflow. I tried the following with no luck:

```<code>import keras.backend.tensorflow_backend as K
with K.get_session() as sess:
    K.set_session(sess)
    import tensorflow as tf
    from neural_net import NeuralNet
    with tf.device('/gpu:0'):
        nn = NeuralNet('config', train_db_path, test_db_path)
        nn.train(1000, 1)
        print 'Done'
    K._SESSION.close()
    K.set_session(None)
</code>```

Even after the session has been closed and reset to None, nvidia-smi does not reflect any reduction in memory usage. Any ideas?

Idea

Would it be meaningful to add a __exit__ method to my NeuralNet class and instantiate it as:

```<code>with NeuralNet() as nn:
    nn.train(1000, 1)
</code>```

How should I free up the resources of the keras model in this method?

Test environment

I'm using iPython Notebook on an Ubuntu 14.04 with 3 GTX 960 GPUs.

Reference:

https://github.com/fchollet/keras/issues/2102

https://groups.google.com/forum/#!topic/keras-users/MFUEY9P1sc8

答:
The following works for me to reinitialize the state of Keras layers in my Jupyter notebook for every run:

```<code>from keras import backend as K
K.clear_session()
sess = tf.Session()
K.set_session(sess)
</code>```

Also, the graph is named and reset every time the notebook runs using:

```<code>graphr = K.get_session().graph
with graphr.as_default():
    #...graph building statements...
</code>```

Note : I am still trying to wrap my head around the concepts of Keras and tensorflow ( I believe they are described poorly in documentation and examples ) but the above works.

Body:
I have created a wrapper class which initializes a keras.models.Sequential model and has a couple of methods for starting the training process and monitoring the progress. I instantiate this class in my main file and perform the training process. Fairly mundane stuff.

My question is:

How to free all the GPU memory allocated by tensorflow. I tried the following with no luck:

import keras.backend.tensorflow_backend as K
with K.get_session() as sess:
    K.set_session(sess)
    import tensorflow as tf
    from neural_net import NeuralNet
    with tf.device('/gpu:0'):
        nn = NeuralNet('config', train_db_path, test_db_path)
        nn.train(1000, 1)
        print 'Done'
    K._SESSION.close()
    K.set_session(None)

Even after the session has been closed and reset to None, nvidia-smi does not reflect any reduction in memory usage. Any ideas?

Idea

Would it be meaningful to add a __exit__ method to my NeuralNet class and instantiate it as:

with NeuralNet() as nn:
    nn.train(1000, 1)

How should I free up the resources of the keras model in this method?

Test environment

I'm using iPython Notebook on an Ubuntu 14.04 with 3 GTX 960 GPUs.

Reference:

https://github.com/fchollet/keras/issues/2102

https://groups.google.com/forum/#!topic/keras-users/MFUEY9P1sc8

Body:
The following works for me to reinitialize the state of Keras layers in my Jupyter notebook for every run:

from keras import backend as K
K.clear_session()
sess = tf.Session()
K.set_session(sess)

Also, the graph is named and reset every time the notebook runs using:

graphr = K.get_session().graph
with graphr.as_default():
    #...graph building statements...

Note : I am still trying to wrap my head around the concepts of Keras and tensorflow ( I believe they are described poorly in documentation and examples ) but the above works.


问:
Avoiding Collisions With Self in Unity
I'm firing lasers from a cannon in a 2d space game in unity using the following method:

```<code>[Command]
private void CmdFire()
{
    GameObject laser = (GameObject)Instantiate(LaserPrefab, leftShot ? leftCannon.position : rightCannon.position, leftShot ? leftCannon.rotation * Quaternion.Euler(0, 0, 90) : rightCannon.rotation * Quaternion.Euler(0, 0, 90));
    Physics2D.IgnoreCollision(laser.GetComponent<Collider2D>(), transform.FindChild("PlayerShip").GetComponent<Collider2D>());
    Physics2D.IgnoreCollision(laser.GetComponent<Collider2D>(), transform.FindChild("PlayerShip").FindChild(leftShot?"LeftCannon":"RightCannon").GetComponent<Collider2D>());
    laser.GetComponent<SpriteRenderer>().sortingOrder = 0;
    laser.GetComponent<Rigidbody2D>().velocity = laser.transform.right * 10;
    NetworkServer.Spawn(laser);
    leftShot = !leftShot;
    Destroy(laser, 2f);
}
</code>```

The important bit being the Physics2D.IgnoreCollision() sections that are designed to stop them shooting themselves. This works exactly as expected on the host (you can shoot the other ships but not yourself) but the lasers constantly hit their own ship on the client machines.

As you can see here:

This is my first attempt at making a multiplayer game in Unity so any help would be appreciated.

答:
In the OnCollisionEnter2D of the laser, check if the gameObject is the "yourself"
by comparing the ID

If( collider.gameObject.GetInstanceID() != yourself.gameObject.GetInstanceID() )

Title: Avoiding Collisions With Self in Unity

Body:
I'm firing lasers from a cannon in a 2d space game in unity using the following method:

[Command]
private void CmdFire()
{
    GameObject laser = (GameObject)Instantiate(LaserPrefab, leftShot ? leftCannon.position : rightCannon.position, leftShot ? leftCannon.rotation * Quaternion.Euler(0, 0, 90) : rightCannon.rotation * Quaternion.Euler(0, 0, 90));
    Physics2D.IgnoreCollision(laser.GetComponent<Collider2D>(), transform.FindChild("PlayerShip").GetComponent<Collider2D>());
    Physics2D.IgnoreCollision(laser.GetComponent<Collider2D>(), transform.FindChild("PlayerShip").FindChild(leftShot?"LeftCannon":"RightCannon").GetComponent<Collider2D>());
    laser.GetComponent<SpriteRenderer>().sortingOrder = 0;
    laser.GetComponent<Rigidbody2D>().velocity = laser.transform.right * 10;
    NetworkServer.Spawn(laser);
    leftShot = !leftShot;
    Destroy(laser, 2f);
}

The important bit being the Physics2D.IgnoreCollision() sections that are designed to stop them shooting themselves. This works exactly as expected on the host (you can shoot the other ships but not yourself) but the lasers constantly hit their own ship on the client machines.

As you can see here:

This is my first attempt at making a multiplayer game in Unity so any help would be appreciated.


问:
Change a JS function within WP Plugin
Wondering how I can insert / change a JS function in a plugin in functions.php instead of modifying the plugin directly?
This plugin is called max mega menu

I have read up about using add_action and remove_action and custom hooks. I cannot seem to find a good example to work with.

I want to wrap the inner content of the function with this

```<code>if (!plugin.isMobileView()) {
   //code here
}
</code>```

UPDATE

See my answer below - I did not need the plugin script altogether, so I dequeued it.
My question should really be now "How to disable a wordpress plugin script"

答:
I realised I did not need the whole plugin script and website was fine without it.

So I dequeued the script

```<code>function mmm_dequeue_script() {
    wp_dequeue_script( 'megamenu' );
}
add_action( 'wp_print_scripts', 'mmm_dequeue_script', 100 );
</code>```

Sorry unrelated to the question now.
Cheers hope this help someone trying to do the same thing.

Title: Change a JS function within WP Plugin

Body:
Wondering how I can insert / change a JS function in a plugin in functions.php instead of modifying the plugin directly?
This plugin is called max mega menu

I have read up about using add_action and remove_action and custom hooks. I cannot seem to find a good example to work with.

I want to wrap the inner content of the function with this

if (!plugin.isMobileView()) {
   //code here
}

UPDATE

See my answer below - I did not need the plugin script altogether, so I dequeued it.
My question should really be now "How to disable a wordpress plugin script"

Body:
I realised I did not need the whole plugin script and website was fine without it.

So I dequeued the script

function mmm_dequeue_script() {
    wp_dequeue_script( 'megamenu' );
}
add_action( 'wp_print_scripts', 'mmm_dequeue_script', 100 );

Sorry unrelated to the question now.
Cheers hope this help someone trying to do the same thing.


问:
How to set vertical align to middle in my case?
I am trying to modify htmls element to achieve two things:

Vertical align two glyphicons and texts to middle.
(vertical align middle doesn't work)

Modify css to have a small gap between text "thanks" and glyphicons to become something like <icon><thanks><icon> instead of  <icon>   <thanks>   <icon>

I have created a jsfiddle:
https://jsfiddle.net/vwdhd1wy/

It seems odd that it created two gap without any additional css. Can someone help me about it?

答:
Please use this HTML/CSS</p>

```<code><div class="mid">
   <span class="left glyphicon glyphicon-forward"></span>
   <span class="middle">Thansk</span>
   <span class="right glyphicon glyphicon-backward"></span>
</div>

    .mid{display:table;}
    .left {
      background-color: red;
      height: 30px;
      vertical-align:middle;
       display:table-cell;
    }

    .middle {
      height: 30px;
      display:table-cell;
      background-color: grey;
      vertical-align:middle;
    }

    .right {
      background-color: red;
        height: 30px;
        vertical-align:middle;
         display:table-cell;
    }
</code>```

Body:
Please use this HTML/CSS

<div class="mid">
   <span class="left glyphicon glyphicon-forward"></span>
   <span class="middle">Thansk</span>
   <span class="right glyphicon glyphicon-backward"></span>
</div>

    .mid{display:table;}
    .left {
      background-color: red;
      height: 30px;
      vertical-align:middle;
       display:table-cell;
    }

    .middle {
      height: 30px;
      display:table-cell;
      background-color: grey;
      vertical-align:middle;
    }

    .right {
      background-color: red;
        height: 30px;
        vertical-align:middle;
         display:table-cell;
    }


问:
When I use the DropDownListFor in view mode, [Required(ErrorMessage = "")] not worked
I found that if I use the DropDownListFor in view mode, the [Required(ErrorMessage = "")] of the variable will not work in the form.

Model :

```<code>    [Key]
    [Required(ErrorMessage = "Pls input id")]
    public int StaffId { get; set; }

    [DisplayName("UserType")]
    public int UserTypeId { get; set; }
</code>```

Controller :

```<code>    public ActionResult Create()
    {

        List<SelectListItem> listItem = new List<SelectListItem>();
        listItem.Add(new SelectListItem { Text = "A", Value = "1" });
        listItem.Add(new SelectListItem { Text = "B", Value = "2" });
        listItem.Add(new SelectListItem { Text = "C", Value = "3" });
        ViewData["List"] = new SelectList(listItem, "Value", "Text", "");

        return View();
    }
</code>```

View :

```<code><div class="form-horizontal">
    <hr />
    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    <div class="form-group">
        @Html.LabelFor(model => model.StaffId, "StaffId", htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.StaffId, new { htmlAttributes = new { @class = "form-control" },  })
            @Html.ValidationMessageFor(model => model.StaffId, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.UserTypeId, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownListFor(model => model.UserTypeId, ViewData["List"] as SelectList, "請選擇", htmlAttributes: new { @class = "form-control" })
            @*@Html.EditorFor(model => model.UserTypeId, new { htmlAttributes = new { @class = "form-control" } })*@
            @Html.ValidationMessageFor(model => model.UserTypeId, "", new { @class = "text-danger" })
        </div>
    </div>
</code>```

If the StaffId is null, then it will return error in the Microsoft Visual Studio,

答:
If the StaffId is null.....

With the code you shown, StaffId property of your view model (Assuming you are using an object of that as the parameter of your action method) will never be null because it is not nullable. If user did not select anything other than your defaul label, it will be 0 (default int value).

Now regarding the errror, this usually happens when you post your form and in the httppost action method you are returning the same view without reloading the relevant collection needed to populate the dropdown in ViewData. So make sure you reload the collection before returning to the view.

```<code>[HttpPost]
public ActionResult Index(YourViewModel model)
{
  if(ModelState.IsValid)
  {
       // to do :Save and Redirect ( PRG pattern)
  }
  // Let's reload the collection needed to render the dropdown
  var listItem = new List<SelectListItem>(){
    new SelectListItem { Text = "A", Value = "1" },
    new SelectListItem { Text = "B", Value = "2" }
  };
  ViewData["List"] = new SelectList(listItem, "Value", "Text", "");
  return View(model);
}
</code>```

Body:
I found that if I use the DropDownListFor in view mode, the [Required(ErrorMessage = "")] of the variable will not work in the form.

Model :

    [Key]
    [Required(ErrorMessage = "Pls input id")]
    public int StaffId { get; set; }

    [DisplayName("UserType")]
    public int UserTypeId { get; set; }

Controller :

    public ActionResult Create()
    {

        List<SelectListItem> listItem = new List<SelectListItem>();
        listItem.Add(new SelectListItem { Text = "A", Value = "1" });
        listItem.Add(new SelectListItem { Text = "B", Value = "2" });
        listItem.Add(new SelectListItem { Text = "C", Value = "3" });
        ViewData["List"] = new SelectList(listItem, "Value", "Text", "");

        return View();
    }

View :

    @Html.ValidationSummary(true, "", new { @class = "text-danger" })

        @Html.LabelFor(model => model.StaffId, "StaffId", htmlAttributes: new { @class = "control-label col-md-2" })

            @Html.EditorFor(model => model.StaffId, new { htmlAttributes = new { @class = "form-control" },  })
            @Html.ValidationMessageFor(model => model.StaffId, "", new { @class = "text-danger" })

        @Html.LabelFor(model => model.UserTypeId, htmlAttributes: new { @class = "control-label col-md-2" })

            @Html.DropDownListFor(model => model.UserTypeId, ViewData["List"] as SelectList, "請選擇", htmlAttributes: new { @class = "form-control" })
            @*@Html.EditorFor(model => model.UserTypeId, new { htmlAttributes = new { @class = "form-control" } })*@
            @Html.ValidationMessageFor(model => model.UserTypeId, "", new { @class = "text-danger" })

If the StaffId is null, then it will return error in the Microsoft Visual Studio,

Body:
If the StaffId is null.....

With the code you shown, StaffId property of your view model (Assuming you are using an object of that as the parameter of your action method) will never be null because it is not nullable. If user did not select anything other than your defaul label, it will be 0 (default int value).

Now regarding the errror, this usually happens when you post your form and in the httppost action method you are returning the same view without reloading the relevant collection needed to populate the dropdown in ViewData. So make sure you reload the collection before returning to the view.

[HttpPost]
public ActionResult Index(YourViewModel model)
{
  if(ModelState.IsValid)
  {
       // to do :Save and Redirect ( PRG pattern)
  }
  // Let's reload the collection needed to render the dropdown
  var listItem = new List<SelectListItem>(){
    new SelectListItem { Text = "A", Value = "1" },
    new SelectListItem { Text = "B", Value = "2" }
  };
  ViewData["List"] = new SelectList(listItem, "Value", "Text", "");
  return View(model);
}


问:
No iOS socket frameworks can connect to server socket
I'm trying to use a socket framework to connect to a socket I have. I am able to connect just fine with raw socket code like:

```<code>uint portNo = 9900;
CFReadStreamRef readStream;
CFWriteStreamRef writeStream;
CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef)@"123.456.789.159", portNo, &readStream, &writeStream);
inputStream = (__bridge NSInputStream *)readStream;
outputStream = (__bridge NSOutputStream *)writeStream;

[inputStream setDelegate:self];
[outputStream setDelegate:self];

[inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[inputStream open];
[outputStream open];
</code>```

but when I try with any framework I get an error and I'm completely stumped as to why. I've tried SocketRocket and Jetfire. Here's the code for connecting in SocketRocket that I've tried:

```<code>_webSocket.delegate = nil;
[_webSocket close];

_webSocket = [[SRWebSocket alloc] initWithURL:[NSURL URLWithString:@"wss://123.456.789.159"]];
_webSocket.delegate = self;

NSLog(@"Opening Connection...");
[_webSocket open];
</code>```

I've also tried with the port number added.

```<code>_webSocket = [[SRWebSocket alloc] initWithURL:[NSURL       URLWithString:@"wss://123.456.789.159:9900"]];
</code>```

Also tried with http, https, ws. Still nothing.

Anybody have an idea as to why?

答:
WebSocket is a protocol for bringing raw socket like functionality on top of HTTP. The socket that your server is exposing likely does not support the WebSocket protocol. </p>

<p>If you want a higher-level API for raw socket programming on iOS, CocoaAsyncSocket might be a good option for you. </p>

Body:
I'm trying to use a socket framework to connect to a socket I have. I am able to connect just fine with raw socket code like:

uint portNo = 9900;
CFReadStreamRef readStream;
CFWriteStreamRef writeStream;
CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef)@"123.456.789.159", portNo, &readStream, &writeStream);
inputStream = (__bridge NSInputStream *)readStream;
outputStream = (__bridge NSOutputStream *)writeStream;

[inputStream setDelegate:self];
[outputStream setDelegate:self];

[inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[inputStream open];
[outputStream open];

but when I try with any framework I get an error and I'm completely stumped as to why. I've tried SocketRocket and Jetfire. Here's the code for connecting in SocketRocket that I've tried:

_webSocket.delegate = nil;
[_webSocket close];

_webSocket = [[SRWebSocket alloc] initWithURL:[NSURL URLWithString:@"wss://123.456.789.159"]];
_webSocket.delegate = self;

NSLog(@"Opening Connection...");
[_webSocket open];

I've also tried with the port number added.

_webSocket = [[SRWebSocket alloc] initWithURL:[NSURL       URLWithString:@"wss://123.456.789.159:9900"]];

Also tried with http, https, ws. Still nothing.

Anybody have an idea as to why?

Body:
WebSocket is a protocol for bringing raw socket like functionality on top of HTTP. The socket that your server is exposing likely does not support the WebSocket protocol.

If you want a higher-level API for raw socket programming on iOS, CocoaAsyncSocket might be a good option for you.


问:
Error:Execution failed for task ':app:transformClassesWithDexForDebug'
The error

Error:Execution failed for task ':app:transformClassesWithDexForDebug'.
  com.android.build.transform.api.TransformException: com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process 'command '/usr/lib/jvm/java-8-oracle/bin/java'' finished with non-zero exit value 1

My app gradle file:

```<code>apply plugin: 'com.android.application'
apply plugin: 'com.google.gms.google-services'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.1"
    defaultConfig {
        applicationId 'Hidden application ID'
        minSdkVersion 15
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
        multiDexEnabled true
    }
    buildTypes {
        debug {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
        release {
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    lintOptions {
        disable 'InvalidPackage'
    }
    packagingOptions {
        exclude 'META-INF/services/javax.annotation.processing.Processor'
    }
    productFlavors {
    }
}

repositories {
    mavenCentral()
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    compile 'com.android.support:multidex:1.0.1'
    compile 'com.android.support:appcompat-v7:23.1.1'
    compile 'com.android.support:design:23.1.1'
    compile 'com.android.support:cardview-v7:23.1.1'
    compile 'com.jakewharton:butterknife:7.0.1'
    compile 'com.mcxiaoke.volley:library-aar:1.0.0'
    compile 'com.google.android.gms:play-services:8.1.0'
    compile 'com.facebook.android:facebook-android-sdk:4.7.0'
    compile 'com.googlecode.libphonenumber:libphonenumber:7.2.1'
    compile 'com.getbase:floatingactionbutton:1.10.1'
    compile 'com.android.support:preference-v7:23.1.1'
}
</code>```

While debugging, if I set minifyEnabled to true, then it compiles. However, then I cannot debug my application.

I checked this other question: Execution failed for task ':app:transformClassesWithDexForDebug' while implementing Google sign in for Android, but there is only one answer and implementing it does not resolve the issue unfortunately.

AFAIK, the error is caused due to addition of too many Gradle dependencies, but I may be wrong (I really hope to be wrong because all these packages are really important!).

Please help me to resolve this error. Much thanks!

答:
Move the apply plugin declaration at the bottom of the file:

apply plugin: 'com.google.gms.google-services'

Body:
The error

Error:Execution failed for task ':app:transformClassesWithDexForDebug'.
  com.android.build.transform.api.TransformException: com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process 'command '/usr/lib/jvm/java-8-oracle/bin/java'' finished with non-zero exit value 1

My app gradle file:

apply plugin: 'com.android.application'
apply plugin: 'com.google.gms.google-services'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.1"
    defaultConfig {
        applicationId 'Hidden application ID'
        minSdkVersion 15
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
        multiDexEnabled true
    }
    buildTypes {
        debug {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
        release {
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    lintOptions {
        disable 'InvalidPackage'
    }
    packagingOptions {
        exclude 'META-INF/services/javax.annotation.processing.Processor'
    }
    productFlavors {
    }
}

repositories {
    mavenCentral()
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    compile 'com.android.support:multidex:1.0.1'
    compile 'com.android.support:appcompat-v7:23.1.1'
    compile 'com.android.support:design:23.1.1'
    compile 'com.android.support:cardview-v7:23.1.1'
    compile 'com.jakewharton:butterknife:7.0.1'
    compile 'com.mcxiaoke.volley:library-aar:1.0.0'
    compile 'com.google.android.gms:play-services:8.1.0'
    compile 'com.facebook.android:facebook-android-sdk:4.7.0'
    compile 'com.googlecode.libphonenumber:libphonenumber:7.2.1'
    compile 'com.getbase:floatingactionbutton:1.10.1'
    compile 'com.android.support:preference-v7:23.1.1'
}

While debugging, if I set minifyEnabled to true, then it compiles. However, then I cannot debug my application.

I checked this other question: Execution failed for task ':app:transformClassesWithDexForDebug' while implementing Google sign in for Android, but there is only one answer and implementing it does not resolve the issue unfortunately.

AFAIK, the error is caused due to addition of too many Gradle dependencies, but I may be wrong (I really hope to be wrong because all these packages are really important!).

Please help me to resolve this error. Much thanks!


问:
Ember clone model for new record
I want to make a clone of a model currently being edited.

I've found a couple of ways that almost work. But neither are perfect.

1) model.get('data.attributes') gets all the attributes except for relationships in camelCase form, generates a new record fine but the relationships are missing of course.

2) model.serialize() generates a JSON object, with all attributes including relationships. But createRecord will not handle it well since the object is not camelCased (attributes with underscores like first_name will not be handled)

After my clone has been created I want to transaction.createRecord(App.Document, myNewModelObject) change/set a couple of attributes and finally commit(). Anyone have some insight in how to do this?

答:
Here is the simple way to clone your Ember Model with relationships. working fine.

Create a Copyable mixin like,

```<code>import Ember from 'ember';

export default Ember.Mixin.create(Ember.Copyable, {

    copy(deepClone) {
      var model = this, attrs = model.toJSON(), class_type = model.constructor;
      var root = Ember.String.decamelize(class_type.toString().split(':')[1]);

      if(deepClone) {
          this.eachRelationship(function(key, relationship){
              if (relationship.kind == 'belongsTo') {
                  attrs[key] = model.get(key).copy(true);
              } else if(relationship.kind == 'hasMany' && Ember.isArray(attrs[key])) {
                  attrs[key].splice(0);
                  model.get(key).forEach(function(obj) {
                      attrs[key].addObject(obj.copy(true));
                  });
              }
          });
      }
      return this.store.createRecord(root, attrs);
    }
});
</code>```

Add the mixin in your model,

Note: If you want to clone your child model then, you need to include the mixin in child model as well

USAGE:

With relationship : YOURMODEL.copy(true)

Without relationship : YOURMODEL.copy()

Title: Ember clone model for new record

Body:
Here is the simple way to clone your Ember Model with relationships. working fine.

Create a Copyable mixin like,

import Ember from 'ember';

export default Ember.Mixin.create(Ember.Copyable, {

    copy(deepClone) {
      var model = this, attrs = model.toJSON(), class_type = model.constructor;
      var root = Ember.String.decamelize(class_type.toString().split(':')[1]);

      if(deepClone) {
          this.eachRelationship(function(key, relationship){
              if (relationship.kind == 'belongsTo') {
                  attrs[key] = model.get(key).copy(true);
              } else if(relationship.kind == 'hasMany' && Ember.isArray(attrs[key])) {
                  attrs[key].splice(0);
                  model.get(key).forEach(function(obj) {
                      attrs[key].addObject(obj.copy(true));
                  });
              }
          });
      }
      return this.store.createRecord(root, attrs);
    }
});

Add the mixin in your model,

Note: If you want to clone your child model then, you need to include the mixin in child model as well

USAGE:

With relationship : YOURMODEL.copy(true)

Without relationship : YOURMODEL.copy()


问:
Simulating WCF route in WEB API 2
We currently have an old legacy WCF service that I really don't want to maintain but several clients still have access. We currently run all our API services in WEB API 2 in Azure. To enable backward compatibility I was hoping to simulate the WCF routing in WEB API using attribute routing like so:

```<code>[RoutePrefix("registration.svc")]
public class RegistrationDeprecatedController : ApiController
{

    [HttpPost]
    [Route("login")]
    public async Task<HttpResponseMessage> Login(CredentialModel creds)
    {...
</code>```

Locally this runs like a dream. As soon as I publish to an Azure AppService however all I get is 404 not found. The specific route in question:

```<code>/registration.svc/login
</code>```

My suspicion is that IIS hosting has the .svc route file associate to process the requests as a WCF call. An extensive search online failed to find anything on how I can change this association or even confirm if this is the case. Any ideas on how to fix or alternative solutions will be greatly appreciated.

Update

Found a solution but its not perfect. Found out that it is possible to directly connect to IIS on the AppService instance and change the Handler Mappings. This is not perfect as it would require a manual change when creating a new instance or deployment slot and I would prefer to automate the entire process.

If anyone else would like to do this you can follow a tutorial by benjamin perkins. I did have to install an IIS Manager for remote administration  extension on windows 10 however for this to work. I removed all mappings associated to *.svc and the routing is now working.

答:
Final solution was to remove the handlers in the web.config.

```<code>  <system.webServer>
    <handlers>
      <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
      <remove name="OPTIONSVerbHandler" />
      <remove name="TRACEVerbHandler" />
      <remove name="svc-Integrated" />
      <remove name="svc-Integrated-4.0" />
      <remove name="svc-ISAPI-2.0" />
      <remove name="svc-ISAPI-2.0-64" />
      <remove name="svc-ISAPI-4.0_32bit" />
      <remove name="svc-ISAPI-4.0_64bit" />
      ....
    </handlers>
</code>```

I was able to find the names by connection to IIS on the AppService instance. I was unsure which ones needed to be removed so I removed all that handlers associated with *.svc.

Title: Simulating WCF route in WEB API 2

Body:
We currently have an old legacy WCF service that I really don't want to maintain but several clients still have access. We currently run all our API services in WEB API 2 in Azure. To enable backward compatibility I was hoping to simulate the WCF routing in WEB API using attribute routing like so:

[RoutePrefix("registration.svc")]
public class RegistrationDeprecatedController : ApiController
{

    [HttpPost]
    [Route("login")]
    public async Task<HttpResponseMessage> Login(CredentialModel creds)
    {...

Locally this runs like a dream. As soon as I publish to an Azure AppService however all I get is 404 not found. The specific route in question:

/registration.svc/login

My suspicion is that IIS hosting has the .svc route file associate to process the requests as a WCF call. An extensive search online failed to find anything on how I can change this association or even confirm if this is the case. Any ideas on how to fix or alternative solutions will be greatly appreciated.

Update

Found a solution but its not perfect. Found out that it is possible to directly connect to IIS on the AppService instance and change the Handler Mappings. This is not perfect as it would require a manual change when creating a new instance or deployment slot and I would prefer to automate the entire process.

If anyone else would like to do this you can follow a tutorial by benjamin perkins. I did have to install an IIS Manager for remote administration  extension on windows 10 however for this to work. I removed all mappings associated to *.svc and the routing is now working.

Body:
Final solution was to remove the handlers in the web.config.

  <system.webServer>
    <handlers>
      <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
      <remove name="OPTIONSVerbHandler" />
      <remove name="TRACEVerbHandler" />
      <remove name="svc-Integrated" />
      <remove name="svc-Integrated-4.0" />
      <remove name="svc-ISAPI-2.0" />
      <remove name="svc-ISAPI-2.0-64" />
      <remove name="svc-ISAPI-4.0_32bit" />
      <remove name="svc-ISAPI-4.0_64bit" />
      ....
    </handlers>

I was able to find the names by connection to IIS on the AppService instance. I was unsure which ones needed to be removed so I removed all that handlers associated with *.svc.


问:
can i call a php function using onclick
Click me

```<code>  <?php
        function myfun(){
             echo "Hello World";
        }
        ?>
</code>```

I really don't know how does it work i just want to learn php. Please help me by solving my problem. when i'm clicking the button it's showing nothing.

答:
You can't invoke a server side function (PHP) in a client side language (JavaScript).

However, you can emulate this by using AJAX and requesting an external webpage:

index.html

$("button").click(function () {
  $(this).attr("disabled",true);
  $.get("http://neil.computer/stack/test.php",function (data) {
    $(document.body).html(data);
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<button>Load HTML!</button></code>```

test.php

```<code><?php

function myfun(){
     echo "Hello World";
}

myfun();

?>
</code>```

Title: can i call a php function using onclick

Body:
Click me

  <?php
        function myfun(){
             echo "Hello World";
        }
        ?>

I really don't know how does it work i just want to learn php. Please help me by solving my problem. when i'm clicking the button it's showing nothing.

Body:
You can't invoke a server side function (PHP) in a client side language (JavaScript).

However, you can emulate this by using AJAX and requesting an external webpage:

index.html

$("button").click(function () {
  $(this).attr("disabled",true);
  $.get("http://neil.computer/stack/test.php",function (data) {
    $(document.body).html(data);
  });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<button>Load HTML!</button>

test.php

<?php

function myfun(){
     echo "Hello World";
}

myfun();

?>


问:
C write struct to file
I am trying to save struct data to file. I saved the data this way.

```<code>node_trx * trx_list;
trx_list = calloc(1, sizeof(node_trx *));
trx_list->amount = "123123123";
trx_list->currency = 123;
trx_list->next_node = NULL;
if (1 != fwrite(trx_list, length, 1, f)) {
    //error
}
free(trx_list);
</code>```

Here is my struct:

```<code>typedef struct {
  char amount;
  int currency;
  struct node_trx * next_node; } node_trx;
</code>```

Main problem is after i saved struct to file and then after read, when print values, it is printing wrong values. For example: i stored currency as 123, then printed 6788576 this kind of numbers.

here is my reading code:

```<code>int read_last_trx_from_file (const char * file_name, node_trx * * trx, unsigned * trx_len)
{
  FILE * f;
  *trx = NULL;

  if (NULL == (f = fopen(tools_get_full_filename_const(file_name), "rb")))
  {
    return 2; //error
  }

  size_t fsize;
  fseek(f, 0, SEEK_END);
  fsize = ftell(f);
  fprintf(stdout, "file size: %zd\n", fsize);
  if (!fsize)
  {
    fclose(f);
    return 3; //no data
  } else {
    if (fsize == 1) {
        return 3; // no data
    }
  }

  rewind(f);
  if (NULL != (*trx = (node_trx *) calloc(1, fsize)))
  {
    if (1 != fread(*trx, fsize, 1, f))
    {
        fclose(f);
        free(*trx);
        return 2; //error
    }
  }
  fclose(f);

  *trx_len = fsize;
  return 0; //OK }
</code>```

Main function that calls read function:

```<code>int display_trx() {
  node_trx * card_data;
     if (3 != read_last_trx_from_file(LAST_TRX_OBJECT, &card_data, &data_set_len)) {
          if (card_data != NULL) {
            printf("%s AMOUNT \n", card_data->amount);
            printf("%d CURRENCY \n", &card_data->currency);
        }
     }
}
</code>```

After i read this way , when i print amount data, segmentation fault error occurs. so why segment error occured?
And when i print currency, it printing 734364636 this kinda numbers. So why it prints wrong numbers.
Or i only wrote pointer of struct to file?
Please help me guys.

答:
There are two obvious errors in your code.

In struct declaration, the type of amount is char, but when you initialize it in trx_list->amount = "123123123";, you assigned a string, or char[10] array (there is an extra one for NULL terminator).

In function display_trx, second printf, the result of &card_data->currency is int *, not int. If you want to print out currency, why don't follow the first print, use card_data->currency (without &)? You get that large number because you are printing pointer value implicitly converted into int, or the address of currency in card_data.

And there is one error which compiler will not warn you (because it is not syntactically wrong.). As BLUEPIXY said in the comments, when allocating and initializing trx_list, you should really use calloc(1, sizeof(node_trx)). You are allocating space for what pointer trx_list points to, not the pointer itself, so there should not be an asterisk in sizeof.

My suggestion is using a "smart" compiler, such as gcc, and enable warnings. This is a good practice (at least for me). Thank you!

Title: C write struct to file

Body:
I am trying to save struct data to file. I saved the data this way.

node_trx * trx_list;
trx_list = calloc(1, sizeof(node_trx *));
trx_list->amount = "123123123";
trx_list->currency = 123;
trx_list->next_node = NULL;
if (1 != fwrite(trx_list, length, 1, f)) {
    //error
}
free(trx_list);

Here is my struct:

typedef struct {
  char amount;
  int currency;
  struct node_trx * next_node; } node_trx;

Main problem is after i saved struct to file and then after read, when print values, it is printing wrong values. For example: i stored currency as 123, then printed 6788576 this kind of numbers.

here is my reading code:

int read_last_trx_from_file (const char * file_name, node_trx * * trx, unsigned * trx_len)
{
  FILE * f;
  *trx = NULL;

  if (NULL == (f = fopen(tools_get_full_filename_const(file_name), "rb")))
  {
    return 2; //error
  }

  size_t fsize;
  fseek(f, 0, SEEK_END);
  fsize = ftell(f);
  fprintf(stdout, "file size: %zd\n", fsize);
  if (!fsize)
  {
    fclose(f);
    return 3; //no data
  } else {
    if (fsize == 1) {
        return 3; // no data
    }
  }

  rewind(f);
  if (NULL != (*trx = (node_trx *) calloc(1, fsize)))
  {
    if (1 != fread(*trx, fsize, 1, f))
    {
        fclose(f);
        free(*trx);
        return 2; //error
    }
  }
  fclose(f);

  *trx_len = fsize;
  return 0; //OK }

Main function that calls read function:

int display_trx() {
  node_trx * card_data;
     if (3 != read_last_trx_from_file(LAST_TRX_OBJECT, &card_data, &data_set_len)) {
          if (card_data != NULL) {
            printf("%s AMOUNT \n", card_data->amount);
            printf("%d CURRENCY \n", &card_data->currency);
        }
     }
}

After i read this way , when i print amount data, segmentation fault error occurs. so why segment error occured?
And when i print currency, it printing 734364636 this kinda numbers. So why it prints wrong numbers.
Or i only wrote pointer of struct to file?
Please help me guys.


问:
Should I catch all my exceptions in the global.asax?
If I am just logging exception details in my web app, do I really need to put in exception handling logic for each tier? Why not just let them all bubble up the stack trace to the global.asax and log them there?</p>

答:
I would suggest against using any exception handling logic in any layer of your application unless:

The exception is not a fatal one, meaning that there is some action you can take to recover, or

The application should continue functioning and the exception should be "ignored." An example: when checking out at an online retailer you are sent a receipt via email. If that fails - but the other order processing stuff succeeds - the user should not be shown an error page. Here, we want the workflow to continue even though there is an exception. Most exceptions do not fall into this category.

Of course, exceptions - whether they are fatal or not or should be "ignored" or not - need to be logged and developers notified. This is best handled through an event handler for the Application.Error event. Yes, this can be done in Global.asax, but I think it's cleaner to use an HTTP Module-based approach, either Health Monitoring or ELMAH.

I've written an article on this topic that I'd like to recommend to you - Exception Handling Advice for ASP.NET Web Applications. Here is the article in summary:

My advice for handling exceptions in an ASP.NET application can be boiled down to the following guidelines:

(a) Create and use a meaningful custom error page.

(b) In general, do not catch exceptions. Let them bubble up to the ASP.NET runtime. Some cases where catching an exception makes sense include:

When there is a plausible way to recover from the exception by performing some alternative logic,

When a peripheral part of the application's workflow throws and exception and that exception should not derail the entire application, and

When you need to include additional information with the exception by throwing a new exception that has the original exception as its inner exception.

(c) Log all exceptions to some persistent store and use email (or some other medium) to notify developers when an exception occurs in production. Consider using ELMAH or ASP.NET's built-in Health Monitoring system to facilitate this process.


问:
Change log4j2 log level from string to int
within the log4j2 configuration I am trying to convert the loglevels from string to an int.

Following the directions located in log4j2 Patterns section

image snippet of example log4j2 pattern mapping

Following the example above I created in log4j2.xml config:

```<code>    <JMS name="jmsQueue"
destinationBindingName="${sys:env}.logging"
factoryName="org.apache.activemq.jndi.ActiveMQInitialContextFactory"
factoryBindingName="ConnectionFactory"
providerURL="${sys:log4j.providerurl}"
userName="log"
password="log">
    <PatternLayout pattern='{"Message":"%m","LogLevel":%level{Debug=1,Info=2,Warn=3,Error=4,Fatal=5,Trace=6},"Type":"middleware","App":"${app_name}","Env":"${sys:env}","data":{"Event_Time":"%d{ISO8601}","Thread":"%t","Class":"%c"}}'/>
</JMS>
</code>```

The edited PatternLayout I would now expect would replace the string debug,info,warn etc. with the mapped int values of 1,2,3 . .

This is not the case, I still receive string value.  If someone could suggest where I am making the mistake I would appreciate it. thank you.

edit:

```<code><?xml version="1.0" encoding="utf-8"?>
<Configuration>
    <!-- replace > app_name_here_only < with the distinct name of your service. you will use this name to search for within kibana (ex: type:middleware app:<app_name>) -->
    <Properties>
        <Property name="app_name">middleware_united</Property>
    </Properties>
    <!-- do not configure below this line -->
    <Appenders>
        <RollingFile name="file" fileName="${sys:mule.home}${sys:file.separator}logs${sys:file.separator}${app_name}.log" filePattern="${sys:mule.home}${sys:file.separator}logs${sys:file.separator}${app_name}-%i.log">
            <PatternLayout pattern="%d [%t] %-5p %c - %m%n"/>
            <SizeBasedTriggeringPolicy size="10 MB"/>
            <DefaultRolloverStrategy max="10"/>
        </RollingFile>
        <JMS name="jmsQueue" destinationBindingName="${sys:env}.logging" factoryName="org.apache.activemq.jndi.ActiveMQInitialContextFactory" factoryBindingName="ConnectionFactory" providerURL="${sys:log4j.providerurl}" userName="log" password="log">
    <PatternLayout pattern='{"Type":"middleware","Env":"${sys:env}","App":"${app_name}","LogLevel":%level{Debug=1,Info=2,Warn=3,Error=4,Fatal=5,Trace=6},"Message":"%m","data":{"Event_Time":"%d{ISO8601}","Thread":"%t","Class":"%c"}}'/>
        </JMS>
    </Appenders>
    <Loggers>
        <!-- CXF is used heavily by Mule for web services -->
        <AsyncLogger name="org.apache.cxf" level="WARN"/>
        <!-- Apache Commons tend to make a lot of noise which can clutter the log-->
        <AsyncLogger name="org.apache" level="WARN"/>
        <!-- Reduce startup noise -->
        <AsyncLogger name="org.springframework.beans.factory" level="WARN"/>
        <!-- Mule classes -->
        <AsyncLogger name="org.mule" level="INFO"/>
        <AsyncLogger name="com.mulesoft" level="INFO"/>
        <!-- Reduce DM verbosity -->
        <AsyncLogger name="org.jetel" level="WARN"/>
        <AsyncLogger name="Tracking" level="WARN"/>
        <AsyncRoot level="INFO">
            <AppenderRef ref="file"/>
            <AppenderRef ref="jmsQueue"/>
        </AsyncRoot>
    </Loggers>
</Configuration>
</code>```

答:
I've tested your pattern but it worked well.

Here's my log4j2.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<Configuration>
    <Appenders>
        <Console name="STDOUT" target="SYSTEM_OUT">
            <PatternLayout
                    pattern='{"Type":"middleware","Env":"${sys:env}","App":"${app_name}","LogLevel":%level{Debug=1,Info=2,Warn=3,Error=4,Fatal=5,Trace=6},"Message":"%m","data":{"Event_Time":"%d{ISO8601}","Thread":"%t","Class":"%c"}}'/>
        </Console>
    </Appenders>

    <Loggers>
        <Root level="DEBUG">
            <AppenderRef ref="STDOUT"/>
        </Root>
    </Loggers>
</Configuration>
</code>```

And here's the output:

```<code>{"Type":"middleware","Env":"${sys:env}","App":"${app_name}","LogLevel":2,"Message":"b","data":{"Event_Time":"2017-03-29T11:28:14,477","Thread":"main","Class":"test.Log4j2"}}
</code>```

Body:
within the log4j2 configuration I am trying to convert the loglevels from string to an int.

Following the directions located in log4j2 Patterns section

image snippet of example log4j2 pattern mapping

Following the example above I created in log4j2.xml config:

    <JMS name="jmsQueue"
destinationBindingName="${sys:env}.logging"
factoryName="org.apache.activemq.jndi.ActiveMQInitialContextFactory"
factoryBindingName="ConnectionFactory"
providerURL="${sys:log4j.providerurl}"
userName="log"
password="log">
    <PatternLayout pattern='{"Message":"%m","LogLevel":%level{Debug=1,Info=2,Warn=3,Error=4,Fatal=5,Trace=6},"Type":"middleware","App":"${app_name}","Env":"${sys:env}","data":{"Event_Time":"%d{ISO8601}","Thread":"%t","Class":"%c"}}'/>
</JMS>

The edited PatternLayout I would now expect would replace the string debug,info,warn etc. with the mapped int values of 1,2,3 . .

This is not the case, I still receive string value.  If someone could suggest where I am making the mistake I would appreciate it. thank you.

edit:

<?xml version="1.0" encoding="utf-8"?>
<Configuration>

    <Properties>
        <Property name="app_name">middleware_united</Property>
    </Properties>

    <Appenders>
        <RollingFile name="file" fileName="${sys:mule.home}${sys:file.separator}logs${sys:file.separator}${app_name}.log" filePattern="${sys:mule.home}${sys:file.separator}logs${sys:file.separator}${app_name}-%i.log">
            <PatternLayout pattern="%d [%t] %-5p %c - %m%n"/>
            <SizeBasedTriggeringPolicy size="10 MB"/>
            <DefaultRolloverStrategy max="10"/>
        </RollingFile>
        <JMS name="jmsQueue" destinationBindingName="${sys:env}.logging" factoryName="org.apache.activemq.jndi.ActiveMQInitialContextFactory" factoryBindingName="ConnectionFactory" providerURL="${sys:log4j.providerurl}" userName="log" password="log">
    <PatternLayout pattern='{"Type":"middleware","Env":"${sys:env}","App":"${app_name}","LogLevel":%level{Debug=1,Info=2,Warn=3,Error=4,Fatal=5,Trace=6},"Message":"%m","data":{"Event_Time":"%d{ISO8601}","Thread":"%t","Class":"%c"}}'/>
        </JMS>
    </Appenders>
    <Loggers>

        <AsyncLogger name="org.apache.cxf" level="WARN"/>

        <AsyncLogger name="org.apache" level="WARN"/>

        <AsyncLogger name="org.springframework.beans.factory" level="WARN"/>

        <AsyncLogger name="org.mule" level="INFO"/>
        <AsyncLogger name="com.mulesoft" level="INFO"/>

        <AsyncLogger name="org.jetel" level="WARN"/>
        <AsyncLogger name="Tracking" level="WARN"/>
        <AsyncRoot level="INFO">
            <AppenderRef ref="file"/>
            <AppenderRef ref="jmsQueue"/>
        </AsyncRoot>
    </Loggers>
</Configuration>

Body:
I've tested your pattern but it worked well.

Here's my log4j2.xml

<?xml version="1.0" encoding="UTF-8"?>
<Configuration>
    <Appenders>
        <Console name="STDOUT" target="SYSTEM_OUT">
            <PatternLayout
                    pattern='{"Type":"middleware","Env":"${sys:env}","App":"${app_name}","LogLevel":%level{Debug=1,Info=2,Warn=3,Error=4,Fatal=5,Trace=6},"Message":"%m","data":{"Event_Time":"%d{ISO8601}","Thread":"%t","Class":"%c"}}'/>
        </Console>
    </Appenders>

    <Loggers>
        <Root level="DEBUG">
            <AppenderRef ref="STDOUT"/>
        </Root>
    </Loggers>
</Configuration>

And here's the output:

{"Type":"middleware","Env":"${sys:env}","App":"${app_name}","LogLevel":2,"Message":"b","data":{"Event_Time":"2017-03-29T11:28:14,477","Thread":"main","Class":"test.Log4j2"}}


问:
Can't throw error from within an async promise executor function
I've been trying to get a conceptual understanding of why the following code doesn't catch the throw. If you remove the async keyword from the new Promise(async (resolve, ... part then it works fine, so it has to do with the fact that the Promise executor is an async function.

```<code>(async function() {

  try {
    await fn();
  } catch(e) {
    console.log("CAUGHT fn error -->",e)
  }

})();

function fn() {

  return new Promise(async (resolve, reject) => {
    // ...
    throw new Error("<<fn error>>");
    // ...
  });

}
</code>```

The answers here, here, and here repeat that "if you're in any other asynchronous callback, you must use reject", but by "asynchronous" they're not referring to async functions, so I don't think their explanations apply here (and if they do, I don't understand how).

If instead of throw we use reject, the above code works fine. I'd like to understand, fundamentally, why throw doesn't work here. Thanks!

答:
This is the async/await version of the Promise constructor antipattern!

Never ever use an async function as a Promise executor function (even when you can make it work1)!

[1: by calling resolve and reject instead of using return and throw statements]

by "asynchronous" they're not referring to async functions, so I don't think their explanations apply here

They could as well. A simple example where it cannot work is

```<code>new Promise(async function() {
    await delay(…);
    throw new Error(…);
})
</code>```

which is equivalent to

```<code>new Promise(function() {
    return delay(…).then(function() {
        throw new Error(…);
    });
})
</code>```

where it's clear now that the throw is inside an asynchronous callback.

The Promise constructor can only catch synchronous exceptions, and an async function never throws - it always returns a promise (which might get rejected though). And that return value is ignored, as the promise is waiting for resolve to be called.

Body:
I've been trying to get a conceptual understanding of why the following code doesn't catch the throw. If you remove the async keyword from the new Promise(async (resolve, ... part then it works fine, so it has to do with the fact that the Promise executor is an async function.

(async function() {

  try {
    await fn();
  } catch(e) {
    console.log("CAUGHT fn error -->",e)
  }

})();

function fn() {

  return new Promise(async (resolve, reject) => {
    // ...
    throw new Error("<<fn error>>");
    // ...
  });

}

The answers here, here, and here repeat that "if you're in any other asynchronous callback, you must use reject", but by "asynchronous" they're not referring to async functions, so I don't think their explanations apply here (and if they do, I don't understand how).

If instead of throw we use reject, the above code works fine. I'd like to understand, fundamentally, why throw doesn't work here. Thanks!

Body:
This is the async/await version of the Promise constructor antipattern!

Never ever use an async function as a Promise executor function (even when you can make it work1)!

[1: by calling resolve and reject instead of using return and throw statements]

by "asynchronous" they're not referring to async functions, so I don't think their explanations apply here

They could as well. A simple example where it cannot work is

new Promise(async function() {
    await delay(…);
    throw new Error(…);
})

which is equivalent to

new Promise(function() {
    return delay(…).then(function() {
        throw new Error(…);
    });
})

where it's clear now that the throw is inside an asynchronous callback.

The Promise constructor can only catch synchronous exceptions, and an async function never throws - it always returns a promise (which might get rejected though). And that return value is ignored, as the promise is waiting for resolve to be called.


问:
For loop overwriting text in HTML
My array called myEmployees has 5 names in it, yet when I run the code it only prints out 3 of them. I believe this is happening because the for loop in the script is overwriting the previous line that it wrote in the HTML document. How can I fix this?

Yearly Bulletin Board Announcements!

Congratulations to Taylor, you have been here for 9 years and you meet the magic number! You get 2 extra weeks of PTO!

Derek, thank you for your service over the past 8 years. I look forward to many more years working with you!

Tyler, no longer works here.

The above  is what shows on my screen when I run the code, there should be two other statements to appear. Any suggestions would be greatly appreciated!

```<code><body>

  <h1>Yearly Buttetin Board Announcements!</h1>
  <h2 id='win'></h2>
  <h3 id='here'></h3>
  <h4 id='notHere'></h4>

  <script src='app.js'></script>
</body>
</code>```

TypeScript

```<code>for( i = 0; i < myEmployees.length; i++ ) {
    const employee = myEmployees[i];
    let magicNumber   = employee.extraVacay;
    let stillEmployed = employee.stillEmployed;
    let timeInJob     = employee.timeInJob;
    let name          = employee.name;

    if( magicNumber > 30 && timeInJob > 5 && stillEmployed == true ) {

        document.getElementById('win').innerHTML = (`Congratulations to ${name}, you have been here for ${timeInJob} years and you meet the magic number! You get 2 extra weeks of PTO!`);

    }
    else if (stillEmployed == true) {

        document.getElementById('here').innerHTML = (`${name}, thank you for your service over the past ${timeInJob} years. I look forward to many more years working with you!`);

    }
    else {

        document.getElementById('notHere').innerHTML = (`${name}, no longer works here.`)
    }
};
</code>```

答:
You are correct-- innerHTML is overwriting the previous value-- use += instead:

```<code>document.getElementById('here').innerHTML += (`${name}, thank you for your service over the past ${timeInJob} years. I look forward to many more years working with you!`);
</code>```

Title: For loop overwriting text in HTML

Body:
My array called myEmployees has 5 names in it, yet when I run the code it only prints out 3 of them. I believe this is happening because the for loop in the script is overwriting the previous line that it wrote in the HTML document. How can I fix this?

Yearly Bulletin Board Announcements!

Congratulations to Taylor, you have been here for 9 years and you meet the magic number! You get 2 extra weeks of PTO!

Derek, thank you for your service over the past 8 years. I look forward to many more years working with you!

Tyler, no longer works here.

The above  is what shows on my screen when I run the code, there should be two other statements to appear. Any suggestions would be greatly appreciated!

Yearly Buttetin Board Announcements!

TypeScript

for( i = 0; i < myEmployees.length; i++ ) {
    const employee = myEmployees[i];
    let magicNumber   = employee.extraVacay;
    let stillEmployed = employee.stillEmployed;
    let timeInJob     = employee.timeInJob;
    let name          = employee.name;

    if( magicNumber > 30 && timeInJob > 5 && stillEmployed == true ) {

        document.getElementById('win').innerHTML = (`Congratulations to ${name}, you have been here for ${timeInJob} years and you meet the magic number! You get 2 extra weeks of PTO!`);

    }
    else if (stillEmployed == true) {

        document.getElementById('here').innerHTML = (`${name}, thank you for your service over the past ${timeInJob} years. I look forward to many more years working with you!`);

    }
    else {

        document.getElementById('notHere').innerHTML = (`${name}, no longer works here.`)
    }
};

Body:
You are correct-- innerHTML is overwriting the previous value-- use += instead:

document.getElementById('here').innerHTML += (`${name}, thank you for your service over the past ${timeInJob} years. I look forward to many more years working with you!`);


问:
Cannot install @angular/cli
I am trying to work on angular2 for which I have installed nodeJS. I have followed the steps given here https://github.com/angular/angular-cli#prerequisites but there seems to be an issue. Here's what I did in the Command Prompt(Admin):

```<code>C:\WINDOWS\system32>node -v
v6.10.1

C:\WINDOWS\system32>npm -v
3.10.10

C:\WINDOWS\system32>npm install -g @angular/cli
[ ..............] / loadRequestedDeps: sill install loadAllDepsIntoIdealTree
</code>```

My command prompt is stuck at this command and shows no sign of response. I will be glad if there are any suggestions on solving this issue of mine. Is there anything I am missing here?

答:
Can you try from the users directory C:\Users\userName or PC name just as shown in the below figure, and make sure you're not limited to any network related issues !

https://s-media-cache-ak0.pinimg.com/originals/87/50/24/87502456dd8043729b794bf00ee2c7e7.jpg

Title: Cannot install @angular/cli

Body:
I am trying to work on angular2 for which I have installed nodeJS. I have followed the steps given here https://github.com/angular/angular-cli#prerequisites but there seems to be an issue. Here's what I did in the Command Prompt(Admin):

C:\WINDOWS\system32>node -v
v6.10.1

C:\WINDOWS\system32>npm -v
3.10.10

C:\WINDOWS\system32>npm install -g @angular/cli
[ ..............] / loadRequestedDeps: sill install loadAllDepsIntoIdealTree

My command prompt is stuck at this command and shows no sign of response. I will be glad if there are any suggestions on solving this issue of mine. Is there anything I am missing here?


问:
How to implement background/asynchronous write-behind caching in PHP?
I have a particular PHP page that, for various reasons, needs to save ~200 fields to a database.  These are 200 separate insert and/or update statements.  Now the obvious thing to do is reduce this number but, like I said, for reasons I won't bother going into I can't do this.

I wasn't expecting this problem.  Selects seem reasonably performant in MySQL but inserts/updates aren't (it takes about 15-20 seconds to do this update, which is naturally unacceptable).  I've written Java/Oracle systems that can happily do thousands of inserts/updates in the same time (in both cases running local databases; MySQL 5 vs OracleXE).

Now in something like Java or .Net I could quite easily do one of the following:

Write the data to an in-memory
write-behind cache (ie it would
know how to persist to the database
and could do so asynchronously);

Write the data to an in-memory cache
and use the PaaS (Persistence as a
Service) model ie a listener to the
cache would persist the fields; or

Simply start a background process
that could persist the data.

The minimal solution is to have a cache that I can simply update, which will separately go and upate the database in its own time (ie it'll return immediately after update the in-memory cache).  This can either be a global cache or a session cache (although a global shared cache does appeal in other ways).

Any other solutions to this kind of problem?

答: One more solution that you could use (instead of tuning mysql :) ) is to use some JMS server and STOMP connection driver for PHP for write data to database server in a asynchronous manner. ActiveMQ have built-in support for STOMP protocol. And there is StompConnect project which is STOMP proxy for any JMS compilant server (OpenMQ, JBossMQ etc).</p>

OwnerDisplayName: cletus

LastEditorDisplayName: cletus

OwnerDisplayName: dotsid


问:
name of the new mobile safari button
On the previous version (<4.2) ios safari, the way to describe how to add a webapp to the home screen (used even by apple on http://www.apple.com/webapps/whatarewebapps.html was "tap the plus sign, and then tap “Add to Home screen."

Now there is no longer a plus sign.

Is there a proper name for the 'share button'? It's main feature is an arrow but there are two other buttons with arrows.

Any ideas (or the official name) for this button?

答: I see it as a sort of "pop out of the page" icon. Or you could refer to it as the "curved arrow".</p>

Title: name of the new mobile safari button


问:
Automate deployment of static website files to S3 after the build
I have a react app(SPA) that is deployed on S3 and publicly accessible. After each build, I have to manually upload the index.html, and other static assets to S3. Is there any ways to automate this process ?

I did an exhaustive search on CD(continuous deployment) to S3, here is a SO question about the same.

I am aggregating all the information from my exhaustive research. I have written the below answer, which contains various methods to achieve this.

答:
There are many ways to do the automation of S3 deployment. Here are the things I gathered:

1. AWS SNS and Lambda:

This process is useful, if you want to trigger any AWS services on github push.So, here is the process:

The github push triggers a message to SNS.

The Lambda which is subscribed to the SNS topic is invoked.

Inside the Lambda, I clone the github repository.

Use AWS's S3 SDK to upload the build or dist directory to your S3 bucket. Here is a high level architecture of the above process:

The downside of this approach is cloning large repos takes time and Lambdas are billed per second. So, this may become expensive for large repos.

2. Travis:

Travis is known for its CI(continuous integration) library. A .travis.yml is essential for the integration process.

If you want to make some tests after the build and then on success, upload the files to S3. Then this approach will be the best way. Travis is free for open source projects.

The downside is, I could not find a way to isolate a directory from the repo and upload that specific directory alone.

3. AWS cli:

This is the cheapest and best way to upload the files to S3. I used this approach. I got this information from this medium post.

Usually in react apps the build scripts are triggered by the npm or yarn written as scripts in the package.json. Here is the command for uploading the files to S3:

aws s3 sync build/ s3://<bucket-name>

I added this script as part of the build scripts in package.json. This was very handy and thus automated the manual process of uploading the files to S3.

This answer is based on my perspective. If anything is incorrect or If I had missed something, please feel free to comment and I will add it to the answer.


问:
Matching enum Strings in Java in If conditions
I have an enum:

```<code>public enum Status{
   A("A"),
   B("B"),
   C("C"),
   D("D"),
   E("E")
}
</code>```

A,B,C are in one category and D&E are a different category.
Now when I get a string, I want to decide which category it falls in.
Basically,

```<code>String s;
if   s.equals( Status.A.toString()) || s.equals(Status.B.toString()) || s.equals( Status.C.toString())
            return 1;

        else return 2;
</code>```

Now, this is manageable with 5 letters. If I have 26 letters, the number of if conditions will be unmanageable. Is there a better way to write this?

答:
How about you maintain a list of enums per category and then compare your string with the enums in a category list? See the following example.</p>

```<code>    List<Status> category1 = new ArrayList<Status>();
    category1.add(Status.A);
    category1.add(Status.B);
    category1.add(Status.C);
    List<Status> category2 = new ArrayList<Status>();
    category2.add(Status.D);
    category2.add(Status.E);

    for(Status e : category1) {
        if(s.equals(e.toString()))
            return true;
    }

    for(Status e : category2) {
        if(s.equals(e.toString()))
            return true;
    }

    return false;
</code>```

Body:
I have an enum:

public enum Status{
   A("A"),
   B("B"),
   C("C"),
   D("D"),
   E("E")
}

A,B,C are in one category and D&E are a different category.
Now when I get a string, I want to decide which category it falls in.
Basically,

String s;
if   s.equals( Status.A.toString()) || s.equals(Status.B.toString()) || s.equals( Status.C.toString())
            return 1;

        else return 2;

Now, this is manageable with 5 letters. If I have 26 letters, the number of if conditions will be unmanageable. Is there a better way to write this?

Body:
How about you maintain a list of enums per category and then compare your string with the enums in a category list? See the following example.

    List<Status> category1 = new ArrayList<Status>();
    category1.add(Status.A);
    category1.add(Status.B);
    category1.add(Status.C);
    List<Status> category2 = new ArrayList<Status>();
    category2.add(Status.D);
    category2.add(Status.E);

    for(Status e : category1) {
        if(s.equals(e.toString()))
            return true;
    }

    for(Status e : category2) {
        if(s.equals(e.toString()))
            return true;
    }

    return false;


问:
join or merge with overwrite in pandas
I want to perform a join/merge/append operation on a dataframe with datetime index.

Let's say I have df1 and I want to add df2 to it.  df2 can have fewer or more columns, and overlapping indexes.  For all rows where the indexes match, if df2 has the same column as df1, I want the values of df1 be overwritten with those from df2.

How can I obtain the desired result?

答:
For a merge like this, the update method of a DataFrame is useful.

Taking the examples from the documentation:

```<code>import pandas as pd
import numpy as np

df1 = pd.DataFrame([[np.nan, 3., 5.], [-4.6, 2.1, np.nan],
                   [np.nan, 7., np.nan]])
df2 = pd.DataFrame([[-42.6, np.nan, -8.2], [-5., 1.6, 4]],
                   index=[1, 2])
</code>```

Data before the update:

```<code>>>> df1
     0    1    2
0  NaN  3.0  5.0
1 -4.6  2.1  NaN
2  NaN  7.0  NaN
>>>
>>> df2
      0    1    2
1 -42.6  NaN -8.2
2  -5.0  1.6  4.0
</code>```

Let's update df1 with data from df2:

```<code>df1.update(df2)
</code>```

Data after the update:

```<code>>>> df1
      0    1    2
0   NaN  3.0  5.0
1 -42.6  2.1 -8.2
2  -5.0  1.6  4.0
</code>```

Remarks:

It's important to notice that this is an operation "in place", modifying the DataFrame that calls update.

Also note that non NaN values in df1 are not overwritten with NaN values in df2

Title: join or merge with overwrite in pandas

Body:
For a merge like this, the update method of a DataFrame is useful.

Taking the examples from the documentation:

import pandas as pd
import numpy as np

df1 = pd.DataFrame([[np.nan, 3., 5.], [-4.6, 2.1, np.nan],
                   [np.nan, 7., np.nan]])
df2 = pd.DataFrame([[-42.6, np.nan, -8.2], [-5., 1.6, 4]],
                   index=[1, 2])

Data before the update:

>>> df1
     0    1    2
0  NaN  3.0  5.0
1 -4.6  2.1  NaN
2  NaN  7.0  NaN
>>>
>>> df2
      0    1    2
1 -42.6  NaN -8.2
2  -5.0  1.6  4.0

Let's update df1 with data from df2:

df1.update(df2)

Data after the update:

>>> df1
      0    1    2
0   NaN  3.0  5.0
1 -42.6  2.1 -8.2
2  -5.0  1.6  4.0

Remarks:

It's important to notice that this is an operation "in place", modifying the DataFrame that calls update.

Also note that non NaN values in df1 are not overwritten with NaN values in df2

ContentLicense: CC BY-SA 4.0


问:
How can I add instance names to movieclips using AS3
I have a FLA document with a movie clip called "mc_walls".  This movie clip is in the stage over 50 times in the movie and I haven't assigned an instance name each movie clip.

I was wondering if there was a way to add the instance names using some actionscript?

I want all the "mc_walls" to have the name "wall".

I tried this code:

```<code>mc_wall.name = "wall";
</code>```

But it returns with this error:
1119: Access of possibly undefined property name through a reference with static type Class.

Help will be great :)

Many Thanks,

Peter

答:
If you're trying to name MovieClips in the same Scene for control later, this may work with an array:</p>

```<code>var wall:Array = new Array();

for (var i: int = 0; i < 3; ++i) {

    var mc:Rampart = new Rampart();

    wall[i] = mc;

    mc.y = 100 * (i+1);
    mc.x = 100;

    addChild(mc);
}

wall[0].x = 300;
</code>```

Body:
I have a FLA document with a movie clip called "mc_walls".  This movie clip is in the stage over 50 times in the movie and I haven't assigned an instance name each movie clip.

I was wondering if there was a way to add the instance names using some actionscript?

I want all the "mc_walls" to have the name "wall".

I tried this code:

mc_wall.name = "wall";

But it returns with this error:
1119: Access of possibly undefined property name through a reference with static type Class.

Help will be great :)

Many Thanks,

Peter

Body:
If you're trying to name MovieClips in the same Scene for control later, this may work with an array:

var wall:Array = new Array();

for (var i: int = 0; i < 3; ++i) {

    var mc:Rampart = new Rampart();

    wall[i] = mc;

    mc.y = 100 * (i+1);
    mc.x = 100;

    addChild(mc);
}

wall[0].x = 300;


问:
Ajax jabber/XMPP client recommendations (real experience only please) !
i'm setting up a chat system for my niche social site and have decided on ejabberd for the server side, but i cannot find any decent web-based ajax clients. most seem to be abandoned years ago or simply do not work. i've looked at every single one here :

http://xmpp.org/xmpp-software/clients/

Is anyone running a live site and using an ajax-based client that they can vouch for that works and is in active development ? I do not mind paying for something, but I do not want to do any development work whatsoever.

thanks in advance.

答: I played with strophe.js a lot in the past. It is a really cool library for writting xmpp clients(pure javascript). In his book professional xmpp he explains how to write a multi-user-chat client in javascript. I guess you have to do some coding, but this library is really powerfull and you have complete control.


问:
How to append a single labeled tick to x-axis using matplotlib?
Suppose I have a simple plot set up in matplotlib:

```<code>fig, ax = plt.subplots(1,1)
p=ax.plot([1,2,3,4,5], [10,9,8,7,6])
</code>```

How could I add a tick to the x-axis at the value 1.5 with the label "here is 1.5"?

I understand that I could use plt.xticks(), but then I would need to specify all ticks and labels.

答:
Something like this will work:

```<code>import matplotlib.pyplot as plt

x=range(10)
y=range(10)

fig, ax = plt.subplots(1,1)
p=ax.plot(x,y)
ax.set_xticks([1.5])
ax.set_xticklabels(["Here is 1.5"])
fig.show()
</code>```

If you want to add an additional x-tick:

```<code>import matplotlib.pyplot as plt
import numpy as np

x=range(10)
y=range(10)

fig, ax = plt.subplots(1,1)

p=ax.plot(x,y)

xt = ax.get_xticks()
xt=np.append(xt,1.5)

xtl=xt.tolist()
xtl[-1]="Here is 1.5"
ax.set_xticks(xt)
ax.set_xticklabels(xtl)

fig.show()
</code>```

You can play around with label rotation if you need.

Body:
Suppose I have a simple plot set up in matplotlib:

fig, ax = plt.subplots(1,1)
p=ax.plot([1,2,3,4,5], [10,9,8,7,6])

How could I add a tick to the x-axis at the value 1.5 with the label "here is 1.5"?

I understand that I could use plt.xticks(), but then I would need to specify all ticks and labels.

Body:
Something like this will work:

import matplotlib.pyplot as plt

x=range(10)
y=range(10)

fig, ax = plt.subplots(1,1)
p=ax.plot(x,y)
ax.set_xticks([1.5])
ax.set_xticklabels(["Here is 1.5"])
fig.show()

If you want to add an additional x-tick:

import matplotlib.pyplot as plt
import numpy as np

x=range(10)
y=range(10)

fig, ax = plt.subplots(1,1)

p=ax.plot(x,y)

xt = ax.get_xticks()
xt=np.append(xt,1.5)

xtl=xt.tolist()
xtl[-1]="Here is 1.5"
ax.set_xticks(xt)
ax.set_xticklabels(xtl)

fig.show()

You can play around with label rotation if you need.


问:
breakpoint on all files from a certain directory
I like to use ipdb to debug my code. I know we could stop the code on a file on a specific line with b(reak) file:lineno. That command will set a breakpoint in file at line 'no'.

Actually, I have inserted import ipdb; ipdb.set_trace() on a specific file. Each time I use the command s(tep), it executes and step into functions. My problem is it is too slow before seeing what I want to see. The stacktrace showed me lines I do not necessarily want to see. Then I was thinking to put a breakpoint on all files from a certain directory, i.e., b mydirectory/**. Therefore, eachtime I will execute c, it will show me all lines I want to see. However, I can't execute such command (i.e., b mydirectory/**). Could anyone have a solution to this problem?

Thanks!

P.S. The following picture show ton of those irrelevant files I don't want to see. In fact, it is normal to see those files, because I am working on a django project.

Please tell me if the question is unclear

答:
```<code>import pdb; pdb.Pdb(skip=['mydirectory.*']).set_trace()
</code>```

mydirectory have to be a python module, here is more info from the documentaion

The skip argument, if given, must be an iterable of glob-style module
  name patterns. The debugger will not step into frames that originate
  in a module that matches one of these patterns. [1]

source: https://docs.python.org/2/library/pdb.html#pdb.Pdb

Body:
import pdb; pdb.Pdb(skip=['mydirectory.*']).set_trace()

mydirectory have to be a python module, here is more info from the documentaion

The skip argument, if given, must be an iterable of glob-style module
  name patterns. The debugger will not step into frames that originate
  in a module that matches one of these patterns. [1]

source: https://docs.python.org/2/library/pdb.html#pdb.Pdb


答:
PHP is a server-side application so there, so you cannot directly call it onClick() because that event happens on the client side.

However, you can call it via JavaScript!  More specifically aJax.

Here's a good place to start

Here's a quick example from What is Sleep`s answer

AJax:

```<code>function callPHP() {
    $.ajax ({
        url: "yourPageName.php",
        data: { action : assign }, //optional
        success: function( result ) {
            //do something after you receive the result
        }
    }
</code>```

PHP:

```<code>if ($_POST["action"] == "assign")
{
    assign(your parameters); //You need to put the parameters you want to pass in
                             //the data field of the ajax call, and use $_POST[]
                             //to get them
}
</code>```

Title: can i call a php function using onclick

Body:
Click me

  <?php
        function myfun(){
             echo "Hello World";
        }
        ?>

I really don't know how does it work i just want to learn php. Please help me by solving my problem. when i'm clicking the button it's showing nothing.

Body:
PHP is a server-side application so there, so you cannot directly call it onClick() because that event happens on the client side.

However, you can call it via JavaScript!  More specifically aJax.

Here's a good place to start

Here's a quick example from What is Sleep`s answer

AJax:

function callPHP() {
    $.ajax ({
        url: "yourPageName.php",
        data: { action : assign }, //optional
        success: function( result ) {
            //do something after you receive the result
        }
    }

PHP:

if ($_POST["action"] == "assign")
{
    assign(your parameters); //You need to put the parameters you want to pass in
                             //the data field of the ajax call, and use $_POST[]
                             //to get them
}


问:
Using WHERE clause with BETWEEN and null date parameters
One of my WHERE clauses is the following:

```<code>AND (DateCreated BETWEEN @DateFrom and @DateTo OR (@DateFrom IS NULL OR @DateTo IS NULL))
</code>```

@DateFrom and @DateTo are input parameters that may be NULL.

If they are both null, then I need to basically ignore the BETWEEN and return all records.

If @DateFrom is NULL, but @DateTo is NOT NULL, then I need to return all records with DateCreated being no greater than @DateTo (inclusive).

If @DateFrom is NOT NULL, but @DateTo is NULL, then I need to return all records with DateCreated being no earlier than @DateFrom (inclusive) up to today's date.

DateCreated is not a null or some time it is null field.

So far my WHERE clause is not working exactly like I want.

答:
```<code>AND (DateCreated BETWEEN @DateFrom and @DateTo OR (ISNULL(@DateFrom, '')='' OR ISNULL(@DateTo, '')=''))
</code>```

Body:
One of my WHERE clauses is the following:

AND (DateCreated BETWEEN @DateFrom and @DateTo OR (@DateFrom IS NULL OR @DateTo IS NULL))

@DateFrom and @DateTo are input parameters that may be NULL.

If they are both null, then I need to basically ignore the BETWEEN and return all records.

If @DateFrom is NULL, but @DateTo is NOT NULL, then I need to return all records with DateCreated being no greater than @DateTo (inclusive).

If @DateFrom is NOT NULL, but @DateTo is NULL, then I need to return all records with DateCreated being no earlier than @DateFrom (inclusive) up to today's date.

DateCreated is not a null or some time it is null field.

So far my WHERE clause is not working exactly like I want.


问:
SEH exception with code 0xc0000005 thrown in the test body
I am writing a test using GoogleTest for the following class and I am getting the above error.

```<code>class Base
{
    // Other Functions;

    CSig objSig[50];
}
</code>```

The Class CSig is as follows:

```<code>class CSig
{
    //... constructor, destructor(empty) and some functions
    CMod *objMod;
    CDemod *objDemod;
}

CSig :: CSig
{
    bIsInitialised = false;

    for (int i=0; i<MAX_NUM; i++)
    {
        PStrokePrev[i] = 0.0;
    }
}
</code>```

However, when I discard CSig objSig[50], the tests run fine.

What can I do to solve this issue? Also, I need to have CSig objSig[50] in the Base class.

答: I am having a similar issue and its pertaining to un-initialized variables and running the test in release build. I had a char * un-initialized after which initialized to NULL seems to have fixed the issue.</p>

Body:
I am writing a test using GoogleTest for the following class and I am getting the above error.

class Base
{
    // Other Functions;

    CSig objSig[50];
}

The Class CSig is as follows:

class CSig
{
    //... constructor, destructor(empty) and some functions
    CMod *objMod;
    CDemod *objDemod;
}

CSig :: CSig
{
    bIsInitialised = false;

    for (int i=0; i<MAX_NUM; i++)
    {
        PStrokePrev[i] = 0.0;
    }
}

However, when I discard CSig objSig[50], the tests run fine.

What can I do to solve this issue? Also, I need to have CSig objSig[50] in the Base class.