问:
Asp.Net Core Model binding, how to get empty field to bind as a blank string?
If a form like the one below is submitted and MyField is left blank on the form, then by default Asp.Net Core model binding will place null into the corresponding property on the model as indicated below.

Example Form

```<code> <form asp-controller="SomeController" asp-action="SomeAction">
        <label asp-for="MyField">My Field</label><input asp-for="MyField" type="text" />
        <button type="submit">Submit</button>
 </form>
</code>```

Example Model

```<code> public class MyModel{
     public string MyField { get; set; }
 }
</code>```

Example Action Method

```<code>    [HttpPost]
    public IActionResult Post(MyModel m) {
          //m.MyField will be null if the field was left empty
          //but I want it set to a blank string by the model binder
    }
</code>```

However, since MyField is actually transmitted in the Http Post body I'd prefer that the model binder set the MyField property on the model to a blank string rather than setting it to null.  I'd prefer to reserve null for cases where MyField is not transmitted in the Http Post body.  How can the model binder be changed to exhibit this behavior?

答:
Studying the ASP.NET Core code for SimpleTypeModelBinder at https://github.com/aspnet/Mvc/blob/rel/1.1.3/src/Microsoft.AspNetCore.Mvc.Core/ModelBinding/Binders/SimpleTypeModelBinder.cs I could see that there is a ModelMetadata.ConvertEmptyStringToNull setting which is set to true by default that is causing the blank string to be converted to null on data binding.  But the property is read only so at first I couldn't figure out how to changes its value.

@rsheptolut's post on this page https://github.com/aspnet/Mvc/issues/4988 led me to a solution.

Solution:

The value has to get set at startup.  This can be done via this class:

public class CustomMetadataProvider : IMetadataDetailsProvider, IDisplayMetadataProvider {
    public void CreateDisplayMetadata(DisplayMetadataProviderContext context) {

        if (context.Key.MetadataKind == ModelMetadataKind.Property) {

            context.DisplayMetadata.ConvertEmptyStringToNull = false;
        }
    }
}
```
<p>When it's hooked into MvcOptions in the <code>ConfigureServices</code> method of the startup.cs file like so</p>
<pre class="lang-cs prettyprint-override"><code>services.AddMvc()
       .AddMvcOptions(options => options.ModelMetadataDetailsProviders.Add(new CustomMetadataProvider ()));
</code>```

Now site wide, the default for a blank field that is posted back will be for the data binder to set the corresponding model property to a blank string rather than to null. Yea!

Body:
If a form like the one below is submitted and MyField is left blank on the form, then by default Asp.Net Core model binding will place null into the corresponding property on the model as indicated below.

Example Form

 <form asp-controller="SomeController" asp-action="SomeAction">
        My Field<input asp-for="MyField" type="text" />
        <button type="submit">Submit</button>
 </form>

Example Model

 public class MyModel{
     public string MyField { get; set; }
 }

Example Action Method

    [HttpPost]
    public IActionResult Post(MyModel m) {
          //m.MyField will be null if the field was left empty
          //but I want it set to a blank string by the model binder
    }

However, since MyField is actually transmitted in the Http Post body I'd prefer that the model binder set the MyField property on the model to a blank string rather than setting it to null.  I'd prefer to reserve null for cases where MyField is not transmitted in the Http Post body.  How can the model binder be changed to exhibit this behavior?

Body:
Studying the ASP.NET Core code for SimpleTypeModelBinder at https://github.com/aspnet/Mvc/blob/rel/1.1.3/src/Microsoft.AspNetCore.Mvc.Core/ModelBinding/Binders/SimpleTypeModelBinder.cs I could see that there is a ModelMetadata.ConvertEmptyStringToNull setting which is set to true by default that is causing the blank string to be converted to null on data binding.  But the property is read only so at first I couldn't figure out how to changes its value.

@rsheptolut's post on this page https://github.com/aspnet/Mvc/issues/4988 led me to a solution.

Solution:

The value has to get set at startup.  This can be done via this class:

public class CustomMetadataProvider : IMetadataDetailsProvider, IDisplayMetadataProvider {
    public void CreateDisplayMetadata(DisplayMetadataProviderContext context) {

        if (context.Key.MetadataKind == ModelMetadataKind.Property) {

            context.DisplayMetadata.ConvertEmptyStringToNull = false;
        }
    }
}

When it's hooked into MvcOptions in the ConfigureServices method of the startup.cs file like so

services.AddMvc()
       .AddMvcOptions(options => options.ModelMetadataDetailsProviders.Add(new CustomMetadataProvider ()));

Now site wide, the default for a blank field that is posted back will be for the data binder to set the corresponding model property to a blank string rather than to null. Yea!

ContentLicense: CC BY-SA 4.0


来源: stackexchange

问:
Does array assignment create a new reference
I am running into the following situation. I am initializing an array, and assigning it to an object's property.

```<code>var arr = [1,2,3,4,5];
var obj = { 'numbers': arr };
</code>```

I understand that I passed a reference to my array arr to my object obj. So I can do the following:

```<code>arr.push(6);
console.log(obj);
</code>```

will display the following, as expected:

```<code>{ numbers: [ 1, 2, 3, 4, 5, 6] }
</code>```

Now for the unexpected part. The value of arr changes, through an external event, and I want the value of obj.numbers to change at the same time. But it does not:

```<code>arr = [0,0,0,0,0];
console.log(arr);
console.log(obj);
arr --> [0,0,0,0,0]
obj --> { numbers: [ 1, 2, 3, 4, 5, 6] }
</code>```

So the value of my arr variable changed, but not the numbers property in my obj variable.

So, my only explanation is, that as soon as you perform an assignment to an array, you break the old reference and create a new reference. Is that so?

And how would I assign my new values [0,0,0,0,0] to my arr variable and the obj.numbers (at the same time)?

答:
It works right. Variable is a place where you save a reference. You save in arr another reference.

You can update first array using this code.

```<code>arr.length = 0;
arr.push(...[0, 0, 0, 0, 0]);
</code>```

slice method won't help you because it return new copy of array.

ContentLicense: CC BY-SA 3.0

Body:
I am running into the following situation. I am initializing an array, and assigning it to an object's property.

var arr = [1,2,3,4,5];
var obj = { 'numbers': arr };

I understand that I passed a reference to my array arr to my object obj. So I can do the following:

arr.push(6);
console.log(obj);

will display the following, as expected:

{ numbers: [ 1, 2, 3, 4, 5, 6] }

Now for the unexpected part. The value of arr changes, through an external event, and I want the value of obj.numbers to change at the same time. But it does not:

arr = [0,0,0,0,0];
console.log(arr);
console.log(obj);
arr --> [0,0,0,0,0]
obj --> { numbers: [ 1, 2, 3, 4, 5, 6] }

So the value of my arr variable changed, but not the numbers property in my obj variable.

So, my only explanation is, that as soon as you perform an assignment to an array, you break the old reference and create a new reference. Is that so?

And how would I assign my new values [0,0,0,0,0] to my arr variable and the obj.numbers (at the same time)?

Body:
It works right. Variable is a place where you save a reference. You save in arr another reference.

You can update first array using this code.

arr.length = 0;
arr.push(...[0, 0, 0, 0, 0]);

slice method won't help you because it return new copy of array.


问:
Vue js - reference variable in object
I am new to vue and can't find a solution to this -

I have a JSON object here, and I am trying to dynamically fetch the "info" of a user based on their "userRegion".

```<code>{
"userData": {
    "kr": {
      "info": {
        "name": "testing-123",
     }
    },
    "any": null,
    "us": null,
    "eu": {
      "info": {
        "name": "testing-456",
     }
    },
  },
   "userRegion": "eu"
}
</code>```

I then have this object in vue and I want to dynamically change region and pull the data from the object based on this region value in the "user" object below.

```<code> user:{
        region:  this.userData.userRegion,
        name: this.userData[this.user.region].info.name
    },
</code>```

For example, I have tried using something like this

```<code>this.userData.userData[this.user.region]
</code>```

but I get an error:

```<code>TypeError: Cannot read property 'region' of undefined"
</code>```

the variable I am using "userData" is passed down from the parent like so:

```<code><infoWindow :userData='userData'></infoWindow>
</code>```

and is set as a prop:

```<code>props: {
        userData: app.userData,
     },
</code>```

any help would be aprpeciated, thanks

答:
I don’t really understand where you are setting this user, whether its part of an initialized data object, or a computed property. However, there is a temporal issue there:

```<code>user: {
    region: this.userData.userRegion,
    name: this.userData[this.user.region].info.name
},
</code>```

In order to set up user.name, user.region needs to be already there. But since you are creating the user object at once, this does not work. So you either have to split that up, or repeat the logic for the user region again:

```<code>user: {
    region: this.userData.userRegion,
    name: this.userData[this.userData.userRegion].info.name
},
</code>```

Title: Vue js - reference variable in object

Body:
I am new to vue and can't find a solution to this -

I have a JSON object here, and I am trying to dynamically fetch the "info" of a user based on their "userRegion".

{
"userData": {
    "kr": {
      "info": {
        "name": "testing-123",
     }
    },
    "any": null,
    "us": null,
    "eu": {
      "info": {
        "name": "testing-456",
     }
    },
  },
   "userRegion": "eu"
}

I then have this object in vue and I want to dynamically change region and pull the data from the object based on this region value in the "user" object below.

 user:{
        region:  this.userData.userRegion,
        name: this.userData[this.user.region].info.name
    },

For example, I have tried using something like this

this.userData.userData[this.user.region]

but I get an error:

TypeError: Cannot read property 'region' of undefined"

the variable I am using "userData" is passed down from the parent like so:

<infoWindow :userData='userData'></infoWindow>

and is set as a prop:

props: {
        userData: app.userData,
     },

any help would be aprpeciated, thanks

Body:
I don’t really understand where you are setting this user, whether its part of an initialized data object, or a computed property. However, there is a temporal issue there:

user: {
    region: this.userData.userRegion,
    name: this.userData[this.user.region].info.name
},

In order to set up user.name, user.region needs to be already there. But since you are creating the user object at once, this does not work. So you either have to split that up, or repeat the logic for the user region again:

user: {
    region: this.userData.userRegion,
    name: this.userData[this.userData.userRegion].info.name
},


问:
How to include elements from unmodified list in modified list with Java Streams?
I am trying to do a map operation on a List<Integer>:

```<code>list.stream().map(i -> i - 2).collect(Collectors.toList());
</code>```

Instead of performing the operation on the last element of the list, I would like it to just be passed through. ...Collectors.toList()).add(i) doesn't work, of course, because i is out of scope.

For example, the input list [1, 2, 3, 4] should output [-1, 0, 1, 4]

答:
StreamEx provides the extract API for this question:</p>

```<code>StreamEx.of(1, 2, 3, 4).mapLastOrElse(i -> i - 2, Function.identity()).toList();
</code>```

Body:
I am trying to do a map operation on a List<Integer>:

list.stream().map(i -> i - 2).collect(Collectors.toList());

Instead of performing the operation on the last element of the list, I would like it to just be passed through. ...Collectors.toList()).add(i) doesn't work, of course, because i is out of scope.

For example, the input list [1, 2, 3, 4] should output [-1, 0, 1, 4]

Body:
StreamEx provides the extract API for this question:

StreamEx.of(1, 2, 3, 4).mapLastOrElse(i -> i - 2, Function.identity()).toList();


问:
html5 in a WebView, detect when video is started
In a WebView, I'm trying to load a html5 page where I embed a <video> but is there any way I can detect when the user selects the play button or the video starts playing?

Right now is when I play the video, default is it fires an Intentto open Android's default player, I don't want it to fire an Intent, I want to use a Dialog and play it there. If anybody can give an idea. Thanks.

答:
I do it in this way:

```<code> boolean videoPlay=false;
 webView.setWebChromeClient(new WebChromeClient() {
    @Override
    public Bitmap getDefaultVideoPoster() {
       super.getDefaultVideoPoster();
       videoPlay=true;
       Log.d("vplayyyyyyyy",String.valueOf(videoPlay));
       return null;
    }
 });
</code>```

hope this help :)

Body:
I do it in this way:

 boolean videoPlay=false;
 webView.setWebChromeClient(new WebChromeClient() {
    @Override
    public Bitmap getDefaultVideoPoster() {
       super.getDefaultVideoPoster();
       videoPlay=true;
       Log.d("vplayyyyyyyy",String.valueOf(videoPlay));
       return null;
    }
 });

hope this help :)


问:
Updating Notification Continuously
Hello There I am a newbie for Android Development, working to learn it to my own!
I just want to update my notification in a Java Thread in my application (I am just learning and curious about how can I do it).

I have an activity, a simple thread to increment an Integer value. Then, I just want to show it in my Notification whenever the Integer value increments!
My Code is as:

```<code>    public class MainActivity extends Activity{
        private final String LOG_KEY = this.getClass().getSimpleName();
        private int c = 0;
        private boolean flag = true;
        private NotificationCompat.Builder builder;
        private NotificationManager notificationManager;

        @Override
        protected void onCreate(Bundle savedInstanceState){
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

            builder = new NotificationCompat.Builder(MainActivity.this)
               .setSmallIcon(R.mipmap.ic_launcher)
               .setAutoCancel(false);

            builder.setOngoing(true);

            notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);

            Thread t = new Thread(new MyThread());
            t.start();
        }//OnCreate ends

        @Override
        protected void onStop() {
            super.onStop();
            flag = false;
        }//stop ends

        @Override
        protected void onDestroy() {
            super.onDestroy();
            flag = false;
        }//destroy ends

        private class MyThread implements Runnable {
            @Override
            public void run() {
                while (flag) {
                    c+=1;
                    showNotification(Integer.toString(c) + " Counts");
                }//while ends
            }//run ends

            private void showNotification(String msg) {
                try {
                    //set the notification
                    builder.setContentText(msg);
                    notificationManager.notify(0, builder.build());
                } catch (Exception exp) {
                    Log.e("xmn", exp.toString());
                }//try catch ends
            }//showNotification ends

        }//private class ends
    }//MainActivity class ends here
</code>```

As from my code, the notification appears and updates the value! But the problem is that it freezes the device and application at a sudden!

I just want help for what I am doing wrong as I am a newbie and learning it to my own. Any help and idea will be highly appreciated!

Thanks

答:
The problem is that you produce too much notifications more then a device can consume.

For your goal (just learn) you can add a some pause between notifications like that:

```<code>private void showNotification(String msg) {
    try {
        //set the notification
        Thread.sleep(1000);  //set the pause

        builder.setContentText(msg);
        notificationManager.notify(0, builder.build());
    } catch (Exception exp) {
        Log.e("xmn", exp.toString());
    }//try catch ends
}//showNotification ends
</code>```

Title: Updating Notification Continuously

Body:
Hello There I am a newbie for Android Development, working to learn it to my own!
I just want to update my notification in a Java Thread in my application (I am just learning and curious about how can I do it).

I have an activity, a simple thread to increment an Integer value. Then, I just want to show it in my Notification whenever the Integer value increments!
My Code is as:

    public class MainActivity extends Activity{
        private final String LOG_KEY = this.getClass().getSimpleName();
        private int c = 0;
        private boolean flag = true;
        private NotificationCompat.Builder builder;
        private NotificationManager notificationManager;

        @Override
        protected void onCreate(Bundle savedInstanceState){
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

            builder = new NotificationCompat.Builder(MainActivity.this)
               .setSmallIcon(R.mipmap.ic_launcher)
               .setAutoCancel(false);

            builder.setOngoing(true);

            notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);

            Thread t = new Thread(new MyThread());
            t.start();
        }//OnCreate ends

        @Override
        protected void onStop() {
            super.onStop();
            flag = false;
        }//stop ends

        @Override
        protected void onDestroy() {
            super.onDestroy();
            flag = false;
        }//destroy ends

        private class MyThread implements Runnable {
            @Override
            public void run() {
                while (flag) {
                    c+=1;
                    showNotification(Integer.toString(c) + " Counts");
                }//while ends
            }//run ends

            private void showNotification(String msg) {
                try {
                    //set the notification
                    builder.setContentText(msg);
                    notificationManager.notify(0, builder.build());
                } catch (Exception exp) {
                    Log.e("xmn", exp.toString());
                }//try catch ends
            }//showNotification ends

        }//private class ends
    }//MainActivity class ends here

As from my code, the notification appears and updates the value! But the problem is that it freezes the device and application at a sudden!

I just want help for what I am doing wrong as I am a newbie and learning it to my own. Any help and idea will be highly appreciated!

Thanks

Body:
The problem is that you produce too much notifications more then a device can consume.

For your goal (just learn) you can add a some pause between notifications like that:

private void showNotification(String msg) {
    try {
        //set the notification
        Thread.sleep(1000);  //set the pause

        builder.setContentText(msg);
        notificationManager.notify(0, builder.build());
    } catch (Exception exp) {
        Log.e("xmn", exp.toString());
    }//try catch ends
}//showNotification ends


问:
In .net, is there an opposite function to Server.HTMLEncode()?
.Net's Server.HTMLEncode() is the very helpful function that takes an HTML string and replaces special characters with their entity equivalents - "<" becomes &lt ; and so forth.

Is there a (built-in) function that does the reverse?  There doesn't seem to be, and I am incredulous.  While I could certainly write my own (and have in the past) Server.HTMLEncode has all kinds of cool handling for different string encodings and high-level unicode characters that I would really not have crash my hand-rolled decoder in a year's time.

What do other people do when they need the plain HTML back?

Update:
To answer the first batch of questions, I present the MSDN article on the
Server object, which has Encode but no Decode...  I'm as amazed as anyone.

Update2: as several alert readers have pointed out, the docs I was looking at were for classic ASP, not ASP.Net.  Thanks guys, that's an important MSDN safety tip.

答: Server.HtmlDecode ....</p>

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Eddie

Body: Server.HtmlDecode ....

OwnerDisplayName: Sergio


问:
List all files changed by a particular user in subversion
Is it possible to get a list of all files modified/added/deleted by a particular user?

The goal is to get an idea of what a user did for the day (or date range).

答:
Here's a small script to show which files were changed by a certain user between revisions.</p>

```<code>#!/bin/bash
# @param $1: Start revision
# @param $2: End revision
# @param $3: User
#
# Example: svn_scapegoat.sh 1000:HEAD jdoe

svn_changed()
{
    svn blame --revision $1:$2 -- $4 | grep -E "^ [0-9]* *${3} "
}

svn diff --revision $1:$2 --summarize | \
cut -c9- | \
while read path
do
    if [ -n "$(svn_changed $1 $2 $3 $path)" ]
    then
        echo "$3 changed $path"
    else
        echo "Someone else changed $path"
    fi
done
</code>```

OwnerDisplayName: Blankman

Body:
Here's a small script to show which files were changed by a certain user between revisions.

#!/bin/bash
# @param $1: Start revision
# @param $2: End revision
# @param $3: User
#
# Example: svn_scapegoat.sh 1000:HEAD jdoe

svn_changed()
{
    svn blame --revision $1:$2 -- $4 | grep -E "^ [0-9]* *${3} "
}

svn diff --revision $1:$2 --summarize | \
cut -c9- | \
while read path
do
    if [ -n "$(svn_changed $1 $2 $3 $path)" ]
    then
        echo "$3 changed $path"
    else
        echo "Someone else changed $path"
    fi
done


问:
Keras: Functional API -- Layer Datatype Error
I am trying to separate each of the outputs of a keras Conv2D layer using a for loop, and then adding another layer to it through the Functional API, but I am getting a type error. The code is:

```<code>import keras
from keras.models import Sequential, Model
from keras.layers import Flatten, Dense, Dropout, Input, Activation
from keras.layers.convolutional import Conv2D, MaxPooling2D, ZeroPadding2D
from keras.layers.merge import Add
from keras.optimizers import SGD
import cv2, numpy as np
import glob
import csv

def conv_layer:
    input = Input(shape=(3,224,224))
    k = 64
    x = np.empty(k, dtype=object)
    y = np.empty(k, dtype=object)
    z = np.empty(k, dtype=object)
    for i in range(0,k):
        x[i] = Conv2D(1, (3,3), data_format='channels_first', padding='same')(input)
        y[i] = Conv2D(1, (3,3), data_format='channels_first', padding='same')(x[i])
        z[i] = keras.layers.add([x[i], y[i]])
    out = Activation('relu')(z)
    model = Model(inputs, out, name='split-layer-model')

    return model
</code>```

But, it is throwing the following error:

```<code>Traceback (most recent call last):
  File "vgg16-local-connections.py", line 352, in <module>
    model = VGG_16_local_connections()
  File "vgg16-local-connections.py", line 40, in VGG_16_local_connections
    out = Activation('relu')(z)
  File "/Users/klab/anaconda2/lib/python2.7/site-packages/keras/engine/topology.py", line 519, in __call__
    input_shapes.append(K.int_shape(x_elem))
  File "/Users/klab/anaconda2/lib/python2.7/site-packages/keras/backend/tensorflow_backend.py", line 409, in int_shape
    shape = x.get_shape()
AttributeError: 'numpy.ndarray' object has no attribute 'get_shape'
</code>```

So, the datatype of z does not match the one of the Functional API. How can I fix this? Any help will be deeply appreciated!

答:
I think you meant:

```<code>out = Activation('relu')(z[k - 1])
</code>```

Your code sets the whole vector z with all layers to be an input to Activation which Keras does not know how to handle.

Body:
I am trying to separate each of the outputs of a keras Conv2D layer using a for loop, and then adding another layer to it through the Functional API, but I am getting a type error. The code is:

import keras
from keras.models import Sequential, Model
from keras.layers import Flatten, Dense, Dropout, Input, Activation
from keras.layers.convolutional import Conv2D, MaxPooling2D, ZeroPadding2D
from keras.layers.merge import Add
from keras.optimizers import SGD
import cv2, numpy as np
import glob
import csv

def conv_layer:
    input = Input(shape=(3,224,224))
    k = 64
    x = np.empty(k, dtype=object)
    y = np.empty(k, dtype=object)
    z = np.empty(k, dtype=object)
    for i in range(0,k):
        x[i] = Conv2D(1, (3,3), data_format='channels_first', padding='same')(input)
        y[i] = Conv2D(1, (3,3), data_format='channels_first', padding='same')(x[i])
        z[i] = keras.layers.add([x[i], y[i]])
    out = Activation('relu')(z)
    model = Model(inputs, out, name='split-layer-model')

    return model

But, it is throwing the following error:

Traceback (most recent call last):
  File "vgg16-local-connections.py", line 352, in <module>
    model = VGG_16_local_connections()
  File "vgg16-local-connections.py", line 40, in VGG_16_local_connections
    out = Activation('relu')(z)
  File "/Users/klab/anaconda2/lib/python2.7/site-packages/keras/engine/topology.py", line 519, in __call__
    input_shapes.append(K.int_shape(x_elem))
  File "/Users/klab/anaconda2/lib/python2.7/site-packages/keras/backend/tensorflow_backend.py", line 409, in int_shape
    shape = x.get_shape()
AttributeError: 'numpy.ndarray' object has no attribute 'get_shape'

So, the datatype of z does not match the one of the Functional API. How can I fix this? Any help will be deeply appreciated!

Body:
I think you meant:

out = Activation('relu')(z[k - 1])

Your code sets the whole vector z with all layers to be an input to Activation which Keras does not know how to handle.


问:
SSIS Redirect Duplicate/Error Records
My SSIS package reads a small .txt file and loads into a table. No problems so far.

However, sometimes this package fails due to PK issues, which is understandable (duplicates are within the source table).

I'd like to allow the good data to continue to flow to the table, and to redirect the duplicates a different table for further investigation.

My thoughts were to simply route the red/flat file source error output to a new OLEDB Destination/table, and change the source Error Output to Error = Redirect Row.

However, I continue to get the error: Violation of PRIMARY KEY constraint.

答: I would handle this by importing the entire file into a blank staging table and then calling a stored procedure that imports the new records into the final destination table, and imports any duplicate records into your other table.</p>

Title: SSIS Redirect Duplicate/Error Records


问:
ruby Split lines using selective tags that appear multiple times in file in any order
I have a file that has the contents as below:

```<code>this is test line 1
this is testing purpose
<public>
am inside of public
doing lot of stuffs and priting result here
</public>
<public>
am inside of another public
doing another set of stuffs and priting here
</public>
</code>```

I want to split this file into three different sections:

The lines which are not inside any of the   section

The lines which are inside of first   section

The lines which are inside of second   section

I tried with take_while and drop_while,

```<code>File.open(filename).each_line.take_while do |l|
  !l.include?('</public>')
end.drop_while do |l|
  !l.include?('<public>')
end.drop(1))
</code>```

but it extracts only the first <public>...</public> section.

In some situation the order might change, like the public section will come first and the remaining content will come at last or middle. If the content order is same as above template then I can follow the below mothod

```<code>File.read(filename).split(/<\/?public>/)
                   .map(&:strip)
                   .reject(&:empty?)
</code>```

which I got answer from Split lines using tags that appear multiple times in file.

But looking some generic method where I can handle the data if the order is in anyway.

I am looking for a better solution. Any suggestion would be appreciated.

答:
Consider this:</p>

```<code>require 'nokogiri'

doc = Nokogiri::XML(<<EOT)
<root>
this is test line 1
<public>
am inside of public
</public>
<public>
am inside of another public
</public>
</root>
EOT

text_inside_public_tags = doc.search('public').map(&:text)
# => ["\n" +
#    "am inside of public\n", "\n" +
#    "am inside of another public\n"]

doc.search('public').each(&:remove)

text_outside_public_tags = doc.at('root').text
# => "\n" +
#    "this is test line 1 \n" +
#    "\n" +
#    "\n"
</code>```

Body:
I have a file that has the contents as below:

this is test line 1
this is testing purpose
<public>
am inside of public
doing lot of stuffs and priting result here
</public>
<public>
am inside of another public
doing another set of stuffs and priting here
</public>

I want to split this file into three different sections:

The lines which are not inside any of the   section

The lines which are inside of first   section

The lines which are inside of second   section

I tried with take_while and drop_while,

File.open(filename).each_line.take_while do |l|
  !l.include?('</public>')
end.drop_while do |l|
  !l.include?('<public>')
end.drop(1))

but it extracts only the first <public>...</public> section.

In some situation the order might change, like the public section will come first and the remaining content will come at last or middle. If the content order is same as above template then I can follow the below mothod

File.read(filename).split(/<\/?public>/)
                   .map(&:strip)
                   .reject(&:empty?)

which I got answer from Split lines using tags that appear multiple times in file.

But looking some generic method where I can handle the data if the order is in anyway.

I am looking for a better solution. Any suggestion would be appreciated.

Body:
Consider this:

require 'nokogiri'

doc = Nokogiri::XML(<<EOT)
<root>
this is test line 1
<public>
am inside of public
</public>
<public>
am inside of another public
</public>
</root>
EOT

text_inside_public_tags = doc.search('public').map(&:text)
# => ["\n" +
#    "am inside of public\n", "\n" +
#    "am inside of another public\n"]

doc.search('public').each(&:remove)

text_outside_public_tags = doc.at('root').text
# => "\n" +
#    "this is test line 1 \n" +
#    "\n" +
#    "\n"


问:
How can I do DNS lookups in Python, including referring to /etc/hosts?
dnspython will do my DNS lookups very nicely, but it entirely ignores the contents of /etc/hosts.

Is there a python library call which will do the right thing? ie check first in etc/hosts, and only fall back to DNS lookups otherwise?

答:
```<code>list( map( lambda x: x[4][0], socket.getaddrinfo( \
     'www.example.com.',22,type=socket.SOCK_STREAM)))
</code>```

gives you a list of the addresses for www.example.com.  (ipv4 and ipv6)

Body:
list( map( lambda x: x[4][0], socket.getaddrinfo( \
     'www.example.com.',22,type=socket.SOCK_STREAM)))

gives you a list of the addresses for www.example.com.  (ipv4 and ipv6)


问:
TFS GIT - How to commit only certain files?
I am new to using Git in TFS.

Say I have 10 files that I modified, however I would only like to commit 2 of those files.

Previously with TFS I could include/exclude what file(s) I wanted to check in.

What would the equivalent be in Git?

Would I Stage my 2 files I want to commit and check those in?  Or would I stage the 8 files and commit my 2 changes?

答:
go to your root directory

stage the files you want to commit

git add fileName

commit the files you staged

git commit -m "my message"


问:
': not a valid identifier Read and Curl
```<code>#!/bin/bash
# Connection to CR
read -p "CRIP: " varCRIP
read -p "CRUSER: " varCRUSER
read -p "CRPASS: " varCRPASS
echo curl -k -X GET “http\://$varCRIP/cgi-bin/CGILink\?cmd=validate\&user=$varCRUSER\&passwd=$varCRPASS”
#curl -k -X GET “http\://$varCRIP/cgi-bin/CGILink\?cmd=validate\&user=$varCRUSER\&passwd=$varCRPASS"
</code>```

```<code>btude@DESKTOP-SQI0GTI:~$ ./ccr.sh
': not a valid identifiervarCRIP
': not a valid identifiervarCRUSER
': not a valid identifiervarCRPASS
curl -k -X GET “http:///cgi-bin/CGILink?cmd=validate&user=&passwd=”
</code>```

HELP!

I am trying to input data in a var then insert it in a curl command to run

答:
Your quotes ” look weird. This could mean you have a non-breakable space in your thing because you copy/pasted from MS-Word or something.

Try this (retyped the space  manually):

```<code>read -p "CRIP:" varCRIP
read -p "CRUSER:" varCRUSER
read -p "CRPASS:" varCRPASS
</code>```

Then change your quotes:

```<code>curl -k -X GET 'http\://$varCRIP/cgi-bin/CGILink\?cmd=validate\&user=$varCRUSER\&passwd=$varCRPASS'
</code>```

Title: ': not a valid identifier Read and Curl

Body:
#!/bin/bash
# Connection to CR
read -p "CRIP: " varCRIP
read -p "CRUSER: " varCRUSER
read -p "CRPASS: " varCRPASS
echo curl -k -X GET “http\://$varCRIP/cgi-bin/CGILink\?cmd=validate\&user=$varCRUSER\&passwd=$varCRPASS”
#curl -k -X GET “http\://$varCRIP/cgi-bin/CGILink\?cmd=validate\&user=$varCRUSER\&passwd=$varCRPASS"

btude@DESKTOP-SQI0GTI:~$ ./ccr.sh
': not a valid identifiervarCRIP
': not a valid identifiervarCRUSER
': not a valid identifiervarCRPASS
curl -k -X GET “http:///cgi-bin/CGILink?cmd=validate&user=&passwd=”

HELP!

I am trying to input data in a var then insert it in a curl command to run

Body:
Your quotes ” look weird. This could mean you have a non-breakable space in your thing because you copy/pasted from MS-Word or something.

Try this (retyped the space  manually):

read -p "CRIP:" varCRIP
read -p "CRUSER:" varCRUSER
read -p "CRPASS:" varCRPASS

Then change your quotes:

curl -k -X GET 'http\://$varCRIP/cgi-bin/CGILink\?cmd=validate\&user=$varCRUSER\&passwd=$varCRPASS'


问:
Node.Js in Erlang style?
I am a complete noob when it comes to both Node.Js and Erlang.
But wouldn't it be possible to build a Node.js app that emulates Erlang behavior?

e.g. you pass json messages across an distributed node.js server park and even pass new code to those servers w/o going offline, just like erlang.

If you have a message handler callback that is activated when a message is received, then this message handler could check if the message is a code update message and thus replace itself(the current handler) with the new code.

So it should be possible to have Node.Js servers with no downtime for code updates w/o too much fuss, right?

答:
Here is a blog comparing experiences using Erlang and Node.js:

http://blog.mysyncpad.com/post/2073441622/node-js-vs-erlang-syncpads-experience

Here is another comparison which purposefully does not compare speed as such:

http://jlouisramblings.blogspot.com/2010/12/differences-between-nodejs-and-erlang_14.html

Title: Node.Js in Erlang style?


问:
(unix) How to write script to count the number of files in a directory using loop
How can I create a bash script to count the number of files in a directory using a loop.

The script should take a target directory and output: Number of files in ::

答:
```<code>#!/bin/bash

counter=0

if [ ! -d "$1" ]
  then
    printf "%s\n" " $1 is not a directory"
    exit 0
fi

directory="$1"
number="${directory##*/}"
number=${#number}

if [ $number -gt 0 ]
  then
    directory="$directory/"
fi

for line in ${directory}*
  do
    if [ -d "$line" ]
       then
         continue
       else
         counter=$(( $counter + 1))
    fi
  done
printf "%s\n" "Number of files in $directory :: $counter"
</code>```


问:
Binding DataColumn.Caption to DataGrid Header
My question is similar to Why DataColumn.Caption doesn't work?, but for WPF. I have a DataGrid bound to a DataTable using an MVVM pattern. The DataGrid has AutoGenerateColumns = true. How do I bind the DataGridColumn header text to the DataColumn.Caption instead of DataColumn.ColumnName? I was hoping for a solution like this:

```<code><DataGrid ItemsSource="MyDataTable" AutoGenerateColumns="true">
    <DataGrid.Resources>
        <Style TargetType="{x:Type DataGridColumnHeader}">
            <Setter Property="ContentTemplate">
                <Setter.Value>
                    <DataTemplate>
                        <TextBlock Text="{Binding DataColumn.Caption}"> <!--this does not work-->
...
</DataGrid>
</code>```

答:
I ended up solving this issue in the code behind.</p>

```<code>private void dgResults_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
    e.Column.Header = tableResults.Columns[e.PropertyName].Caption;
}
</code>```

Body:
My question is similar to Why DataColumn.Caption doesn't work?, but for WPF. I have a DataGrid bound to a DataTable using an MVVM pattern. The DataGrid has AutoGenerateColumns = true. How do I bind the DataGridColumn header text to the DataColumn.Caption instead of DataColumn.ColumnName? I was hoping for a solution like this:

<DataGrid ItemsSource="MyDataTable" AutoGenerateColumns="true">
    <DataGrid.Resources>

Body:
I ended up solving this issue in the code behind.

private void dgResults_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
    e.Column.Header = tableResults.Columns[e.PropertyName].Caption;
}


问:
Error after MVC app authenticates with Azure AD
I am debugging an application on our testing server that throws an error after you successfully authenticate with Azure AD. I believe OWIN Katana middle-ware is trying to cache the access token it received from Azure AD into its token cache but it cant startup the database to cache it. It works fine when i run it locally on my development machine.

I feel like I'm missing something obvious, I'm new to the Katana middle-ware and OpenID Connect in general.

On the test server it gives this error: A network-related or instance-specific error occurred while establishing a connection to SQL Server.

In the windows Event Viewer on the server i get this error a ton of times:

Event 528, SQLLocalDB 13.0
Windows API call WaitForMultipleObjects returned error code: 575. Windows system error message is: {Application Error}
The application was unable to start correctly (0x%lx). Click OK to close the application.
Reported at line: 3730.

Stack Trace:

```<code> at

System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData, DbConnectionPool pool, String accessToken, Boolean applyTransientFaultHandling)
   at System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions)
   at System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnectionPool pool, DbConnection owningObject, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions)
   at System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
   at System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
   at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection)
   at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection)
   at System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection)
   at System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
   at System.Data.SqlClient.SqlConnection.TryOpenInner(TaskCompletionSource`1 retry)
   at System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry)
   at System.Data.SqlClient.SqlConnection.Open()
   at System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch[TTarget,TInterceptionContext](TTarget target, Action`2 operation, TInterceptionContext interceptionContext, Action`3 executing, Action`3 executed)
   at System.Data.Entity.Infrastructure.Interception.DbConnectionDispatcher.Open(DbConnection connection, DbInterceptionContext interceptionContext)
   at System.Data.Entity.SqlServer.SqlProviderServices.<>c__DisplayClass33.<UsingConnection>b__32()
   at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.<>c__DisplayClass1.<Execute>b__0()
   at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func`1 operation)
   at System.Data.Entity.SqlServer.SqlProviderServices.UsingMasterConnection(DbConnection sqlConnection, Action`1 act)
   at System.Data.Entity.SqlServer.SqlProviderServices.CreateDatabaseFromScript(Nullable`1 commandTimeout, DbConnection sqlConnection, String createDatabaseScript)
   at System.Data.Entity.SqlServer.SqlProviderServices.DbCreateDatabase(DbConnection connection, Nullable`1 commandTimeout, StoreItemCollection storeItemCollection)
   at System.Data.Entity.Migrations.Utilities.DatabaseCreator.Create(DbConnection connection)
   at System.Data.Entity.Migrations.DbMigrator.EnsureDatabaseExists(Action mustSucceedToKeepDatabase)
   at System.Data.Entity.Migrations.DbMigrator.Update(String targetMigration)
   at System.Data.Entity.Internal.DatabaseCreator.CreateDatabase(InternalContext internalContext, Func`3 createMigrator, ObjectContext objectContext)
   at System.Data.Entity.Database.Create(DatabaseExistenceState existenceState)
   at System.Data.Entity.CreateDatabaseIfNotExists`1.InitializeDatabase(TContext context)
   at System.Data.Entity.Internal.InternalContext.PerformInitializationAction(Action action)
   at System.Data.Entity.Internal.InternalContext.PerformDatabaseInitialization()
   at System.Data.Entity.Internal.RetryAction`1.PerformAction(TInput input)
   at System.Data.Entity.Internal.LazyInternalContext.InitializeDatabaseAction(Action`1 action)
   at System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType)
   at System.Data.Entity.Internal.Linq.InternalSet`1.Initialize()
   at System.Data.Entity.Internal.Linq.InternalSet`1.get_InternalContext()
   at System.Data.Entity.Infrastructure.DbQuery`1.System.Linq.IQueryable.get_Provider()
   at System.Linq.Queryable.FirstOrDefault[TSource](IQueryable`1 source, Expression`1 predicate)
   at MealPlanSignup.Web.Models.ADALTokenCache..ctor(String signedInUserId) in C:\Agent\_work\9\s\MealPlanSignup.Web\Models\AdalTokenCache.cs:line 14
   at MealPlanSignup.Web.Startup.<ConfigureAuth>b__7_0(AuthorizationCodeReceivedNotification context) in C:\Agent\_work\9\s\MealPlanSignup.Web\App_Start\Startup.Auth.cs:line 54
   at Microsoft.Owin.Security.OpenIdConnect.OpenIdConnectAuthenticationHandler.<AuthenticateCoreAsync>d__1a.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at Microsoft.Owin.Security.OpenIdConnect.OpenIdConnectAuthenticationHandler.<AuthenticateCoreAsync>d__1a.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Owin.Security.Infrastructure.AuthenticationHandler.<BaseInitializeAsync>d__0.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Owin.Security.Infrastructure.AuthenticationMiddleware`1.<Invoke>d__0.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.IntegratedPipelineContextStage.<RunApp>d__5.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Owin.Security.Infrastructure.AuthenticationMiddleware`1.<Invoke>d__0.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.IntegratedPipelineContextStage.<RunApp>d__5.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNon
</code>```

Web config connection string and EF config:

```<code><add name="DefaultConnection" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\aspnet-MealPlanSignup.Web-20170303111008.mdf;Initial Catalog=aspnet-MealPlanSignup.Web-20170303111008;Integrated Security=True" providerName="System.Data.SqlClient" />
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />

<entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="mssqllocaldb" />
      </parameters>
    </defaultConnectionFactory>
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>
</code>```

答: The ADALTokenChache that visual studio builds out for you by default uses a dbcontext built out for the localdb, when i moved it to a test server which didnt have sqlserver express or localdb installed it bombed out.  I just ended up adding the tokenCache table to a database we already had running and changed my connection string to use it instead. Fei Xue was correct, i appreciate his help and patients with someone trying to learn!</p>

Body:
I am debugging an application on our testing server that throws an error after you successfully authenticate with Azure AD. I believe OWIN Katana middle-ware is trying to cache the access token it received from Azure AD into its token cache but it cant startup the database to cache it. It works fine when i run it locally on my development machine.

I feel like I'm missing something obvious, I'm new to the Katana middle-ware and OpenID Connect in general.

On the test server it gives this error: A network-related or instance-specific error occurred while establishing a connection to SQL Server.

In the windows Event Viewer on the server i get this error a ton of times:

Event 528, SQLLocalDB 13.0
Windows API call WaitForMultipleObjects returned error code: 575. Windows system error message is: {Application Error}
The application was unable to start correctly (0x%lx). Click OK to close the application.
Reported at line: 3730.

Stack Trace:

 at

System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData, DbConnectionPool pool, String accessToken, Boolean applyTransientFaultHandling)
   at System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions)
   at System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnectionPool pool, DbConnection owningObject, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions)
   at System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
   at System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
   at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection)
   at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection)
   at System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection)
   at System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
   at System.Data.SqlClient.SqlConnection.TryOpenInner(TaskCompletionSource`1 retry)
   at System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry)
   at System.Data.SqlClient.SqlConnection.Open()
   at System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch[TTarget,TInterceptionContext](TTarget target, Action`2 operation, TInterceptionContext interceptionContext, Action`3 executing, Action`3 executed)
   at System.Data.Entity.Infrastructure.Interception.DbConnectionDispatcher.Open(DbConnection connection, DbInterceptionContext interceptionContext)
   at System.Data.Entity.SqlServer.SqlProviderServices.<>c__DisplayClass33.<UsingConnection>b__32()
   at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.<>c__DisplayClass1.<Execute>b__0()
   at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func`1 operation)
   at System.Data.Entity.SqlServer.SqlProviderServices.UsingMasterConnection(DbConnection sqlConnection, Action`1 act)
   at System.Data.Entity.SqlServer.SqlProviderServices.CreateDatabaseFromScript(Nullable`1 commandTimeout, DbConnection sqlConnection, String createDatabaseScript)
   at System.Data.Entity.SqlServer.SqlProviderServices.DbCreateDatabase(DbConnection connection, Nullable`1 commandTimeout, StoreItemCollection storeItemCollection)
   at System.Data.Entity.Migrations.Utilities.DatabaseCreator.Create(DbConnection connection)
   at System.Data.Entity.Migrations.DbMigrator.EnsureDatabaseExists(Action mustSucceedToKeepDatabase)
   at System.Data.Entity.Migrations.DbMigrator.Update(String targetMigration)
   at System.Data.Entity.Internal.DatabaseCreator.CreateDatabase(InternalContext internalContext, Func`3 createMigrator, ObjectContext objectContext)
   at System.Data.Entity.Database.Create(DatabaseExistenceState existenceState)
   at System.Data.Entity.CreateDatabaseIfNotExists`1.InitializeDatabase(TContext context)
   at System.Data.Entity.Internal.InternalContext.PerformInitializationAction(Action action)
   at System.Data.Entity.Internal.InternalContext.PerformDatabaseInitialization()
   at System.Data.Entity.Internal.RetryAction`1.PerformAction(TInput input)
   at System.Data.Entity.Internal.LazyInternalContext.InitializeDatabaseAction(Action`1 action)
   at System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType)
   at System.Data.Entity.Internal.Linq.InternalSet`1.Initialize()
   at System.Data.Entity.Internal.Linq.InternalSet`1.get_InternalContext()
   at System.Data.Entity.Infrastructure.DbQuery`1.System.Linq.IQueryable.get_Provider()
   at System.Linq.Queryable.FirstOrDefault[TSource](IQueryable`1 source, Expression`1 predicate)
   at MealPlanSignup.Web.Models.ADALTokenCache..ctor(String signedInUserId) in C:\Agent\_work\9\s\MealPlanSignup.Web\Models\AdalTokenCache.cs:line 14
   at MealPlanSignup.Web.Startup.<ConfigureAuth>b__7_0(AuthorizationCodeReceivedNotification context) in C:\Agent\_work\9\s\MealPlanSignup.Web\App_Start\Startup.Auth.cs:line 54
   at Microsoft.Owin.Security.OpenIdConnect.OpenIdConnectAuthenticationHandler.<AuthenticateCoreAsync>d__1a.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at Microsoft.Owin.Security.OpenIdConnect.OpenIdConnectAuthenticationHandler.<AuthenticateCoreAsync>d__1a.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Owin.Security.Infrastructure.AuthenticationHandler.<BaseInitializeAsync>d__0.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Owin.Security.Infrastructure.AuthenticationMiddleware`1.<Invoke>d__0.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.IntegratedPipelineContextStage.<RunApp>d__5.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Owin.Security.Infrastructure.AuthenticationMiddleware`1.<Invoke>d__0.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.IntegratedPipelineContextStage.<RunApp>d__5.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNon

Web config connection string and EF config:

<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\aspnet-MealPlanSignup.Web-20170303111008.mdf;Initial Catalog=aspnet-MealPlanSignup.Web-20170303111008;Integrated Security=True" providerName="System.Data.SqlClient" />

<entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="mssqllocaldb" />
      </parameters>
    </defaultConnectionFactory>
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>


问:
Pigscript Logic Implementation
I am new to pigscript. I am stuck while working on the example below.  Could anyone help me on how to get the Output specified below using pigscript?

Input:

```<code>1|ABC|NC
1|DEF|NC
2|CFD|NY
2|CGF|NY
</code>```

Output:

```<code>1|ABC,DEF|NC
2|CFD,CGF|NY
</code>```

Script:

```<code>A = LOAD 'testfile.txt' USING PigStorage('|') AS (Id:chararray,name:chararray,state:chararray);
B = FOREACH A GENERATE Id,name;
C = FOREACH A GENERATE Id,name,state;
C = DISTINCT C;
GROUPED = GROUP B BY Id;
D = FOREACH GROUPED GENERATE group AS Id,c.name AS name_val;
E = JOIN D BY Id, C BY Id;
X = FOREACH E GENERATE D.Id as docid,D.name_val as termid,C.state;
Dump X;
</code>```

答:
```<code>Its working as now expected after adding BagToString method.

A = LOAD 'testfile.txt' USING PigStorage('|') AS (f1:int,f2:chararray,f3:chararray);
B = GROUP A BY (f1,f3);
C = FOREACH B GENERATE FLATTEN(group) as (f1,f3),A.f2 AS f2;
D = FOREACH C GENERATE f1,  BagToString(f2, ','), f3;
STORE D INTO '[path]' USING PigStorage('|');
</code>```

Title: Pigscript Logic Implementation

Body:
I am new to pigscript. I am stuck while working on the example below.  Could anyone help me on how to get the Output specified below using pigscript?

Input:

1|ABC|NC
1|DEF|NC
2|CFD|NY
2|CGF|NY

Output:

1|ABC,DEF|NC
2|CFD,CGF|NY

Script:

A = LOAD 'testfile.txt' USING PigStorage('|') AS (Id:chararray,name:chararray,state:chararray);
B = FOREACH A GENERATE Id,name;
C = FOREACH A GENERATE Id,name,state;
C = DISTINCT C;
GROUPED = GROUP B BY Id;
D = FOREACH GROUPED GENERATE group AS Id,c.name AS name_val;
E = JOIN D BY Id, C BY Id;
X = FOREACH E GENERATE D.Id as docid,D.name_val as termid,C.state;
Dump X;


问:
Call javascript in web view on Android
I made HTML file with JavaScript functions in and Android UI to call these functions. I don't know how to call JS in web views on Android. Please help.
Example:</p>

```<code>//JavaScript
<script>
function doSomething(){
//do something
}
</script>

//Android Java
Button clickButton = (Button) findViewById(R.id.button);
clickButton.setOnClickListener( new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            //call JS function doSomething()
        }
});
</code>```

答:
It is a duplicate from previous questions. But I will try and give you a starting point.

Before you load your  webview(but after you had created an instance of the webview) you need to set a Javascript interface class.

Basically:

```<code>mWebView.addJavascriptInterface(WebInterface(this), "Android");
// more settings or whatever
mWebView.loadUrl("yourUrl.html.whatever");
</code>```

the interface is a class that will live wherever you want, if it is a simple project you might as well keep it inside of the MainActivity class. It is up to you to know how to structure your application, but the basic gist of the class would look like this:

```<code>public class WebInterface {
    Context mContext;
    public WebInterface(Context c) { this.mContext = c;}

    @JavascriptInterface
    public void showAlert() {
     Toast.makeText(mContext, "This is being called from the interface", Toast.LENGTH_SHORT).show();
    }
}
</code>```

Notice that the name of the class is the same name as the one you added to the webview. This is pretty obvious at this point, but you need for them to be the same.

Now, you are probably wondering about the "Android" part. Check this, in your JS code you would do something like this:

```<code><script>
function doSomething(){
 Android.showAlert();
}
</script>
</code>```

Can you see the pattern here? Android is the identifier for the Java code you want to run inside your JS, since the method you defined inside the WebInterface class is called showAlert() you would call it inside the WebInterface by using the Android identifier. This can be named in any way you want, but for the sake of simplicity I have left it at Android.

Try and see the other examples made in other SO questions to see if they match what you want to do. In this case, I would say that the one I provided above should be more than enough.

Title: Call javascript in web view on Android

Body:
I made HTML file with JavaScript functions in and Android UI to call these functions. I don't know how to call JS in web views on Android. Please help.
Example:

//JavaScript

//Android Java
Button clickButton = (Button) findViewById(R.id.button);
clickButton.setOnClickListener( new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            //call JS function doSomething()
        }
});

Body:
It is a duplicate from previous questions. But I will try and give you a starting point.

Before you load your  webview(but after you had created an instance of the webview) you need to set a Javascript interface class.

Basically:

mWebView.addJavascriptInterface(WebInterface(this), "Android");
// more settings or whatever
mWebView.loadUrl("yourUrl.html.whatever");

the interface is a class that will live wherever you want, if it is a simple project you might as well keep it inside of the MainActivity class. It is up to you to know how to structure your application, but the basic gist of the class would look like this:

public class WebInterface {
    Context mContext;
    public WebInterface(Context c) { this.mContext = c;}

    @JavascriptInterface
    public void showAlert() {
     Toast.makeText(mContext, "This is being called from the interface", Toast.LENGTH_SHORT).show();
    }
}

Notice that the name of the class is the same name as the one you added to the webview. This is pretty obvious at this point, but you need for them to be the same.

Now, you are probably wondering about the "Android" part. Check this, in your JS code you would do something like this:

<script>
function doSomething(){
 Android.showAlert();
}
</script>

Can you see the pattern here? Android is the identifier for the Java code you want to run inside your JS, since the method you defined inside the WebInterface class is called showAlert() you would call it inside the WebInterface by using the Android identifier. This can be named in any way you want, but for the sake of simplicity I have left it at Android.

Try and see the other examples made in other SO questions to see if they match what you want to do. In this case, I would say that the one I provided above should be more than enough.


问:
Doctrine 2: There is no column with name '$columnName' on table '$table'
When I do:

```<code>vendor/bin/doctrine-module orm:schema-tool:update
</code>```

Doctrine 2.4 gives me this error:

```<code>[Doctrine\DBAL\Schema\SchemaException]
There is no column with name 'resource_id' on table 'role_resource'.
</code>```

My actual MySQL database schema has the column and the table, as evident from running this command (no errors thrown):

```<code>mysql> select resource_id from role_resource;
Empty set (0.00 sec)
</code>```

Thus, the error must be somewhere in the Doctrine's representation of the schema.  I did a var_dump() of $this object, and here is what I get (partial):

```<code>object(Doctrine\DBAL\Schema\Table)#546 (10) {
    ["_name"   :protected] => string(13) "role_resource"
    ["_columns":protected] => array(0) { }
</code>```

Note that indeed, the _columns key does not contain any columns, which is how Doctrine checks for column names.

In my case, the partial trace dump is as follows:

SchemaException.php#L85

Table.php#L252

Table.php#L161

Reading other posts with similar problem, seem to suggest that I may have an error in the column case (upper vs lower).  While it is possible I have missed something, but looking over my actual schema on the Database and the Annotations in my code seem to suggest a match (all lowercase).  Similarly, Doctrine2's code does incorporate checks for such casing errors.  So I am ruling out the error casing possibility.

Another post I've seen suggests that there may be an error in my Annotations, i.e. wrong naming, syntax, or id placement.  I don't know, I checked it and it seems fine.  Here is what I have:

```<code>class Role implements HierarchicalRoleInterface
{
/**
 * @var \Doctrine\Common\Collections\Collection
 * @ORM\ManyToMany(targetEntity="ModuleName\Entity\Resource")
 * @ORM\JoinTable(name="role_resource",
 * joinColumns={@ORM\JoinColumn(name="role_id", referencedColumnName="id")},
 * inverseJoinColumns={@ORM\JoinColumn(name="resource_id", referencedColumnName="id")}
 * )
 */
protected $resource;
</code>```

So at the moment, I am stuck, and unable to use the ORM's schema-generation tools.  This is a persistent error.  I have scraped my database, generated schema anew using ORM, but still get stuck on this error whenever I try to do an update via ORM, as I describe in this post.  Where perhaps should I look next?

Update:  traced it to this code:
$sql before this line ==

```<code>SELECT COLUMN_NAME AS Field,
    COLUMN_TYPE AS Type,
    IS_NULLABLE AS `Null`,
    COLUMN_KEY AS `Key`,
    COLUMN_DEFAULT AS `Default`,
    EXTRA AS Extra,
    COLUMN_COMMENT AS Comment,
    CHARACTER_SET_NAME AS CharacterSet,
    COLLATION_NAME AS CollactionName,
FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = 'loginauth' AND TABLE_NAME = 'role_resource'
</code>```

which when I run it form MySQL prompt, returns (some columns were trimmed):

```<code>+-------------+---------+------+-----+--------------+----------------+
| Field       | Type    | Null | Key | CharacterSet | CollactionName |
+-------------+---------+------+-----+--------------+----------------+
| role_id     | int(11) | NO   | PRI | NULL         | NULL           |
| resource_id | int(11) | NO   | PRI | NULL         | NULL           |
+-------------+---------+------+-----+--------------+----------------+
</code>```

and the $this->executeQuery($sql, $params, $types) returns the proper(?) statement that runs fine on my prompt, but when ->fetchAll() is called, specifically this fetchAll() it breaks down and returns an empty array.  Can I have someone make sense out of this?

MORE:

Essentially, from above links, $this->executeQuery($sql, $params, $types) returns:

```<code>object(Doctrine\DBAL\Driver\PDOStatement)#531 (1) {
    ["queryString"]=> string(332) "SELECT COLUMN_NAME AS Field, COLUMN_TYPE AS Type, IS_NULLABLE AS `Null`, COLUMN_KEY AS `Key`, COLUMN_DEFAULT AS `Default`, EXTRA AS Extra, COLUMN_COMMENT AS Comment, CHARACTER_SET_NAME AS CharacterSet, COLLATION_NAME AS CollactionName FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = 'loginauth' AND TABLE_NAME = 'role_resource'"
}
</code>```

but then $this->executeQuery($sql, $params, $types)->fetchAll() (adding fetchAll()), returns this:

```<code>array(0) {
}
</code>```

And that is so sad my friends :(  because I don't know why it returns an empty array, when the statement in queryString above is so clearly valid and fruitful.

答:
Late answer, but may be helps some one
I had the same problem. It was because I used Symphony's command line to create my entity and camel case calling some of its properties. Then, when Doctrine create the table, also via command line, it change camel case for "_ "convention.</p>

Body:
When I do:

vendor/bin/doctrine-module orm:schema-tool:update

Doctrine 2.4 gives me this error:

[Doctrine\DBAL\Schema\SchemaException]
There is no column with name 'resource_id' on table 'role_resource'.

My actual MySQL database schema has the column and the table, as evident from running this command (no errors thrown):

mysql> select resource_id from role_resource;
Empty set (0.00 sec)

Thus, the error must be somewhere in the Doctrine's representation of the schema.  I did a var_dump() of $this object, and here is what I get (partial):

object(Doctrine\DBAL\Schema\Table)#546 (10) {
    ["_name"   :protected] => string(13) "role_resource"
    ["_columns":protected] => array(0) { }

Note that indeed, the _columns key does not contain any columns, which is how Doctrine checks for column names.

In my case, the partial trace dump is as follows:

SchemaException.php#L85

Table.php#L252

Table.php#L161

Reading other posts with similar problem, seem to suggest that I may have an error in the column case (upper vs lower).  While it is possible I have missed something, but looking over my actual schema on the Database and the Annotations in my code seem to suggest a match (all lowercase).  Similarly, Doctrine2's code does incorporate checks for such casing errors.  So I am ruling out the error casing possibility.

Another post I've seen suggests that there may be an error in my Annotations, i.e. wrong naming, syntax, or id placement.  I don't know, I checked it and it seems fine.  Here is what I have:

class Role implements HierarchicalRoleInterface
{
/**
 * @var \Doctrine\Common\Collections\Collection
 * @ORM\ManyToMany(targetEntity="ModuleName\Entity\Resource")
 * @ORM\JoinTable(name="role_resource",
 * joinColumns={@ORM\JoinColumn(name="role_id", referencedColumnName="id")},
 * inverseJoinColumns={@ORM\JoinColumn(name="resource_id", referencedColumnName="id")}
 * )
 */
protected $resource;

So at the moment, I am stuck, and unable to use the ORM's schema-generation tools.  This is a persistent error.  I have scraped my database, generated schema anew using ORM, but still get stuck on this error whenever I try to do an update via ORM, as I describe in this post.  Where perhaps should I look next?

Update:  traced it to this code:
$sql before this line ==

SELECT COLUMN_NAME AS Field,
    COLUMN_TYPE AS Type,
    IS_NULLABLE AS `Null`,
    COLUMN_KEY AS `Key`,
    COLUMN_DEFAULT AS `Default`,
    EXTRA AS Extra,
    COLUMN_COMMENT AS Comment,
    CHARACTER_SET_NAME AS CharacterSet,
    COLLATION_NAME AS CollactionName,
FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = 'loginauth' AND TABLE_NAME = 'role_resource'

which when I run it form MySQL prompt, returns (some columns were trimmed):

+-------------+---------+------+-----+--------------+----------------+
| Field       | Type    | Null | Key | CharacterSet | CollactionName |
+-------------+---------+------+-----+--------------+----------------+
| role_id     | int(11) | NO   | PRI | NULL         | NULL           |
| resource_id | int(11) | NO   | PRI | NULL         | NULL           |
+-------------+---------+------+-----+--------------+----------------+

and the $this->executeQuery($sql, $params, $types) returns the proper(?) statement that runs fine on my prompt, but when ->fetchAll() is called, specifically this fetchAll() it breaks down and returns an empty array.  Can I have someone make sense out of this?

MORE:

Essentially, from above links, $this->executeQuery($sql, $params, $types) returns:

object(Doctrine\DBAL\Driver\PDOStatement)#531 (1) {
    ["queryString"]=> string(332) "SELECT COLUMN_NAME AS Field, COLUMN_TYPE AS Type, IS_NULLABLE AS `Null`, COLUMN_KEY AS `Key`, COLUMN_DEFAULT AS `Default`, EXTRA AS Extra, COLUMN_COMMENT AS Comment, CHARACTER_SET_NAME AS CharacterSet, COLLATION_NAME AS CollactionName FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = 'loginauth' AND TABLE_NAME = 'role_resource'"
}

but then $this->executeQuery($sql, $params, $types)->fetchAll() (adding fetchAll()), returns this:

array(0) {
}

And that is so sad my friends :(  because I don't know why it returns an empty array, when the statement in queryString above is so clearly valid and fruitful.


问:
yii2 unique validator only when field not empty
In Yii2 I have two fields in my Database: email and shopId

Email and shopId should be unique together

Email could also be empty (NULL) while shopId is always an integer

These are my rules in the Model:

```<code>[['email'],'default','value' => NULL],
[['shopId'], 'integer'],
[['email','shopId'], 'unique', 'targetAttribute' => ['email', 'shopId'], 'message' => 'Already taken!'],
</code>```

This is not working when I have two entries with e.g. email="NULL" and shopId="1".

How can I solve this?

答: Set skipOnEmpty property to false http://www.yiiframework.com/doc-2.0/yii-validators-validator.html#$skipOnEmpty-detail

Body:
In Yii2 I have two fields in my Database: email and shopId

Email and shopId should be unique together

Email could also be empty (NULL) while shopId is always an integer

These are my rules in the Model:

[['email'],'default','value' => NULL],
[['shopId'], 'integer'],
[['email','shopId'], 'unique', 'targetAttribute' => ['email', 'shopId'], 'message' => 'Already taken!'],

This is not working when I have two entries with e.g. email="NULL" and shopId="1".

How can I solve this?


问:
Is operator< (less than) on pointers consistent?
Note: This question is not about total order. A total order on pointers of the same type can be obtained using std::less.

According to this, comparing two pointers with operator< isn't allowed if they point for example into different allocations.

In which sense isn't it allowed? Is it implementation defined, unspecified or undefined behaviour?

I think I read somewhere that it's unspecified. An implementation isn't required to document what the behaviour is, but there must be some behaviour. So that would mean, comparing any two pointers is still legal, but doesn't neccessarily yield a total order. Does that mean, that we still have to get a consistent result, when comparing the same two pointers twice? The general case would be: Does invoking the same unspecified behaviour twice within an application always yield the same result?

```<code>int i1, i2;
int* a = &i1;
int* b = &i2;
bool b1 = a < b; // unspecified, right?
bool b2 = a < b;
assert(b1 == b2); // Is this guaranteed to be true?
</code>```

答:
Comparing two unrelated pointers (i.e. pointers not pointing to the same memory, or not pointing to different parts of the same "array") can only be done using equality == and inequality !=. All other comparison is unspecified.

If you have two pointers pointing to the same place, or inside the same array, then you can compare them using the relative operators.

So if you have e.g.

```<code>int* p1 = new int[10];
int* p2 = new int[5];
</code>```

you can only use == and != to compare the pointers p1 and p2.

But if you have

```<code>int a = new int[10];
int* p1 = &a[0];
int* p2 = &a[3];
</code>```

then you can use also < and > (and of course <= and >=) to compare p1 and p2

Body:
Note: This question is not about total order. A total order on pointers of the same type can be obtained using std::less.

According to this, comparing two pointers with operator< isn't allowed if they point for example into different allocations.

In which sense isn't it allowed? Is it implementation defined, unspecified or undefined behaviour?

I think I read somewhere that it's unspecified. An implementation isn't required to document what the behaviour is, but there must be some behaviour. So that would mean, comparing any two pointers is still legal, but doesn't neccessarily yield a total order. Does that mean, that we still have to get a consistent result, when comparing the same two pointers twice? The general case would be: Does invoking the same unspecified behaviour twice within an application always yield the same result?

int i1, i2;
int* a = &i1;
int* b = &i2;
bool b1 = a < b; // unspecified, right?
bool b2 = a < b;
assert(b1 == b2); // Is this guaranteed to be true?

Body:
Comparing two unrelated pointers (i.e. pointers not pointing to the same memory, or not pointing to different parts of the same "array") can only be done using equality == and inequality !=. All other comparison is unspecified.

If you have two pointers pointing to the same place, or inside the same array, then you can compare them using the relative operators.

So if you have e.g.

int* p1 = new int[10];
int* p2 = new int[5];

you can only use == and != to compare the pointers p1 and p2.

But if you have

int a = new int[10];
int* p1 = &a[0];
int* p2 = &a[3];

then you can use also < and > (and of course <= and >=) to compare p1 and p2


问:
Calling C++ function from Excel and VBA using DLL created in C++
I created a DLL containing a function named "koduj". Calling this function by using it inside an Excel worksheet cell returns the desired result. Calling "koduj" from VBA returns wrong answer.

koduj needs two arguments: string nr_id and integer x1. It calculates sum of nr_id's letters in ASCII representation and adds x1. Calculated sum is than returned.

I was following instructions found here.

Here's my .cpp sourcefile:

#include<Windows.h>
#include<string>
using namespace std;

//Convert BSTR to wstring for convenience
wstring BSTR_to_wstring (BSTR text){
    return wstring(text, SysStringLen(text));
}

//Calculate sum of letters in ASCII representation
int ASCII_sum (wstring ws){
    int sum = 0;
    for (unsigned int i = 0; i < ws.length(); i++)
        sum += ws[i];
    return sum;
}

//"koduj" function
int _stdcall koduj (BSTR nr_id, int & x1){
    wstring ws_nr_id = BSTR_to_wstring(nr_id);
    return ASCII_sum(ws_nr_id) + x1;
}
```

<p>Here's my VBA function declaration:</p>

<pre class="lang-vb prettyprint-override"><code>Declare Function koduj _
Lib "<dll_directory_and_full_name>" (ByVal x As String, ByRef y As Integer) As Integer
</code>```

By writing:

=koduj("aaa";1)
```

<p>Inside a worksheet cell I get desired result (292)</p>

<p>Debugging this VBA code:</p>

<pre class="lang-vb prettyprint-override"><code>Sub test()

Dim a As Integer
a = koduj("aaa", 1)

End Sub
</code>```

reveals wrong result (a = 24930)

I believe my C++ code is fine, as it works properly when called from Excel's worksheet.

答:
The reason is that even though VBA strings are internally UTF-16, VB always converts them to ASCII before talking to the outside world (Declared functions, file input/output). So when you Declare a parameter As String, VBA automatically converts the string and passes it out as ASCII. The matching parameter type on the C++ side should be LPSTR or LPCSTR.

If you want to use BSTR on the C++ side, you need to also create an IDL file for that function, compile it into a TLB and reference the TLB from VBA, only then VBA will respect and use BSTR.

Another problem is that C++'s int translates to VBA's Long.

The reason why it works when called from Excel sheet is that apparently Excel ignores the VBA rules for string conversion. I believe this to be a bug.

Body:
I created a DLL containing a function named "koduj". Calling this function by using it inside an Excel worksheet cell returns the desired result. Calling "koduj" from VBA returns wrong answer.

koduj needs two arguments: string nr_id and integer x1. It calculates sum of nr_id's letters in ASCII representation and adds x1. Calculated sum is than returned.

I was following instructions found here.

Here's my .cpp sourcefile:

#include<Windows.h>
#include<string>
using namespace std;

//Convert BSTR to wstring for convenience
wstring BSTR_to_wstring (BSTR text){
    return wstring(text, SysStringLen(text));
}

//Calculate sum of letters in ASCII representation
int ASCII_sum (wstring ws){
    int sum = 0;
    for (unsigned int i = 0; i < ws.length(); i++)
        sum += ws[i];
    return sum;
}

//"koduj" function
int _stdcall koduj (BSTR nr_id, int & x1){
    wstring ws_nr_id = BSTR_to_wstring(nr_id);
    return ASCII_sum(ws_nr_id) + x1;
}

Here's my VBA function declaration:

Declare Function koduj _
Lib "<dll_directory_and_full_name>" (ByVal x As String, ByRef y As Integer) As Integer

By writing:

=koduj("aaa";1)

Inside a worksheet cell I get desired result (292)

Debugging this VBA code:

Sub test()

Dim a As Integer
a = koduj("aaa", 1)

End Sub

reveals wrong result (a = 24930)

I believe my C++ code is fine, as it works properly when called from Excel's worksheet.


问:
Rails: Stripe appears to work but no charge is created
I have a rails app where Stripe is set up similar to this documentation.  When I hit the "Pay With Card" button and enter the test card information it says it's successful, then gives me an error message saying:

```<code>No route matches [POST] "/charges/new"
</code>```

Even though my routes are like this:

```<code>resources :charges
get 'charges/shipping'
get 'charges/address'
post 'charges/update_order'
</code>```

My charges_controller reads like this:

```<code>class ChargesController < ApplicationController

   ...

  def new
    @order = current_order
  end

  def create
    # Amount in cents
    @amount = current_order.total * 100
    @user = current_user
    @order = current_order

    if @user.stripe_customer_id
      customer = @user.stripe_customer_id
    else
      customer = Stripe::Customer.create(
        :email => params[:stripeEmail],
        :source  => params[:stripeToken]
      )
      @user.update_attributes(stripe_customer_id: customer.id)
    end
    @order.update_attributes(order_status_id: 2)
    @order.update_attributes(date_placed: DateTime.now)
    # OrderMailer.order_placed(@order.user, @order).deliver_now
    session[:order_id] = nil

    charge = Stripe::Charge.create(
      :customer    => @user.stripe_customer_id,
      :amount      => @amount.to_i,
      :description => 'Rails Stripe customer',
      :currency    => 'usd'
    )

  rescue Stripe::CardError => e
    flash[:error] = e.message
    redirect_to new_charge_path
  end

  private

  def order_params
    params.permit(:subtotal, :tax, :shipping, :total, :order_status_id, :user_id, :date_placed, :shipping_choice)
  end
end
</code>```

If I manually insert a post "charges/new" into the routes.rb it says it's successful, but it redirects to the same page (indicating a Stripe::CardError) and no charge registers in the stripe dashboard.

Can anyone see where I'm going wrong?

答:
It looks like you're not permitting the 'stripeToken' parameter in your order_params. Because of camel-case that might be a little fiddly, but make sure you're allowing that param with something like:

```<code>params.permit( :"stripeToken" …
</code>```

Without this, that parameter is null, and would give you a Stripe failure.

Body:
I have a rails app where Stripe is set up similar to this documentation.  When I hit the "Pay With Card" button and enter the test card information it says it's successful, then gives me an error message saying:

No route matches [POST] "/charges/new"

Even though my routes are like this:

resources :charges
get 'charges/shipping'
get 'charges/address'
post 'charges/update_order'

My charges_controller reads like this:

class ChargesController < ApplicationController

   ...

  def new
    @order = current_order
  end

  def create
    # Amount in cents
    @amount = current_order.total * 100
    @user = current_user
    @order = current_order

    if @user.stripe_customer_id
      customer = @user.stripe_customer_id
    else
      customer = Stripe::Customer.create(
        :email => params[:stripeEmail],
        :source  => params[:stripeToken]
      )
      @user.update_attributes(stripe_customer_id: customer.id)
    end
    @order.update_attributes(order_status_id: 2)
    @order.update_attributes(date_placed: DateTime.now)
    # OrderMailer.order_placed(@order.user, @order).deliver_now
    session[:order_id] = nil

    charge = Stripe::Charge.create(
      :customer    => @user.stripe_customer_id,
      :amount      => @amount.to_i,
      :description => 'Rails Stripe customer',
      :currency    => 'usd'
    )

  rescue Stripe::CardError => e
    flash[:error] = e.message
    redirect_to new_charge_path
  end

  private

  def order_params
    params.permit(:subtotal, :tax, :shipping, :total, :order_status_id, :user_id, :date_placed, :shipping_choice)
  end
end

If I manually insert a post "charges/new" into the routes.rb it says it's successful, but it redirects to the same page (indicating a Stripe::CardError) and no charge registers in the stripe dashboard.

Can anyone see where I'm going wrong?

Body:
It looks like you're not permitting the 'stripeToken' parameter in your order_params. Because of camel-case that might be a little fiddly, but make sure you're allowing that param with something like:

params.permit( :"stripeToken" …

Without this, that parameter is null, and would give you a Stripe failure.


问:
Moving mouse and keep .mouseenter function
This is my first time creating something with jQuery, so I am really excited. I did this small thing where you can hover on artists names and see the concerts available.

Really proud of myself, but I'd like now to be able to move my cursor to the dates (and maybe later I'll create a link for them), but if I move the mouse outside of the big square, then .mouseleave activates and baaam, it's gone.

How should I do this?

Here's the code (the hover is not working, I don't understand why :()

$(document).ready(function () {

    $('show').hide();
    $('.alldates').hide();

    $('.band').mouseenter(function() {
        $(this).fadeTo('fast',1);
        $(this).next().show(200);
    });

    $('.band').mouseleave(function() {

        $(this).fadeTo('fast',0.5);
        $(this).next().hide(200);
    });

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
    font-family: 'Roboto';

}

.container {
    display: flex;
    flex-direction: row;
    justify-content: space-around;
    flex-wrap: wrap;

}

ul,li {
    list-style-type: none;
    list-style: none;
}

.band {
    opacity: 0.5;
    margin-top: 20px;
    display: flex;
    flex-direction: column;
    justify-content:center;
    width: 240px;
    height: 240px;
    align-items: center;
    border-radius: 3px;
    box-shadow: 0px 0px 6px rgba(0,0,0,0.2);
    color: white;
}

.band p {
    font-size: 20px;
    font-weight: 500;
}

show {
    font-size: 16px;
}

.alldates {
    margin-top: 10px;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    height: 120px;
}

.date {
    display: flex;
    justify-content: space-around;
    border: solid 1px #95989A;
    height: 52px;
    align-items: center;
    border-radius: 3px;
    color:#95989A;
}

.band1 {
    background-color: rgba(40,177,227,1);
}

.band2 {
    background-color: rgba(227,40,52,1);
}

.band3 {
    background-color: rgba(227,213,40,1);
}

.band4 {
    background-color: rgba(0,0,0,1);
}

.band5 {
    background-color: rgba(171,40,227,1);
}</code>```

All Time Low

        <show>Show dates</show>

30 Oct 2017

London

2 Nov 2017

Paris

Johnny Cash

        <show>Show dates</show>

30 Oct 2017

London

2 Nov 2017

Paris

30 Seconds to Mars

        <show>Show dates</show>

30 Oct 2017

London

2 Nov 2017

Paris

Never Shout Never

        <show>Show dates</show>

30 Oct 2017

London

2 Nov 2017

Paris

Miley Cyrus

        <show>Show dates</show>

30 Oct 2017

London

2 Nov 2017

Paris

```

Thank you so much in advance!

答:
Change the selector to .info so mouseenter is triggered on the parent element that wraps both of your elements. Then use $.find() to toggle the state of the children of the .info you're hovering.

$(document).ready(function () {
    $('show').hide();
    $('.alldates').hide();

    $('.info').mouseenter(function() {
        $(this).find('.band').fadeTo('fast',1);
        $(this).find('.alldates').show(200);
    });

    $('.info').mouseleave(function() {
        $(this).find('.band').fadeTo('fast',0.5);
        $(this).find('.alldates').hide(200);
    });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
    font-family: 'Roboto';
}

.container {
    display: flex;
    flex-direction: row;
    justify-content: space-around;
    flex-wrap: wrap;
}

ul,li {
    list-style-type: none;
    list-style: none;
}

.band {
    opacity: 0.5;
    margin-top: 20px;
    display: flex;
    flex-direction: column;
    justify-content:center;
    width: 240px;
    height: 240px;
    align-items: center;
    border-radius: 3px;
    box-shadow: 0px 0px 6px rgba(0,0,0,0.2);
    color: white;
}

.band p {
    font-size: 20px;
    font-weight: 500;
}

show {
    font-size: 16px;
}

.alldates {
    margin-top: 10px;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    height: 120px;
}

.date {
    display: flex;
    justify-content: space-around;
    border: solid 1px #95989A;
    height: 52px;
    align-items: center;
    border-radius: 3px;
    color:#95989A;
}

.band1 {background-color: rgba(40,177,227,1);}
.band2 {background-color: rgba(227,40,52,1);}
.band3 {background-color: rgba(227,213,40,1);}
.band4 {background-color: rgba(0,0,0,1);}
.band5 {background-color: rgba(171,40,227,1);}</code>```

All Time Low

      <show>Show dates</show>

30 Oct 2017

London

2 Nov 2017

Paris

Johnny Cash

      <show>Show dates</show>

30 Oct 2017

London

2 Nov 2017

Paris

30 Seconds to Mars

      <show>Show dates</show>

30 Oct 2017

London

2 Nov 2017

Paris

Never Shout Never

      <show>Show dates</show>

30 Oct 2017

London

2 Nov 2017

Paris

Miley Cyrus

      <show>Show dates</show>

30 Oct 2017

London

2 Nov 2017

Paris

```

Body:
This is my first time creating something with jQuery, so I am really excited. I did this small thing where you can hover on artists names and see the concerts available.

Really proud of myself, but I'd like now to be able to move my cursor to the dates (and maybe later I'll create a link for them), but if I move the mouse outside of the big square, then .mouseleave activates and baaam, it's gone.

How should I do this?

Here's the code (the hover is not working, I don't understand why :()

$(document).ready(function () {

    $('show').hide();
    $('.alldates').hide();

    $('.band').mouseenter(function() {
        $(this).fadeTo('fast',1);
        $(this).next().show(200);
    });

    $('.band').mouseleave(function() {

        $(this).fadeTo('fast',0.5);
        $(this).next().hide(200);
    });

});

body {
    font-family: 'Roboto';

}

.container {
    display: flex;
    flex-direction: row;
    justify-content: space-around;
    flex-wrap: wrap;

}

ul,li {
    list-style-type: none;
    list-style: none;
}

.band {
    opacity: 0.5;
    margin-top: 20px;
    display: flex;
    flex-direction: column;
    justify-content:center;
    width: 240px;
    height: 240px;
    align-items: center;
    border-radius: 3px;
    box-shadow: 0px 0px 6px rgba(0,0,0,0.2);
    color: white;
}

.band p {
    font-size: 20px;
    font-weight: 500;
}

show {
    font-size: 16px;
}

.alldates {
    margin-top: 10px;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    height: 120px;
}

.date {
    display: flex;
    justify-content: space-around;
    border: solid 1px #95989A;
    height: 52px;
    align-items: center;
    border-radius: 3px;
    color:#95989A;
}

.band1 {
    background-color: rgba(40,177,227,1);
}

.band2 {
    background-color: rgba(227,40,52,1);
}

.band3 {
    background-color: rgba(227,213,40,1);
}

.band4 {
    background-color: rgba(0,0,0,1);
}

.band5 {
    background-color: rgba(171,40,227,1);
}

All Time Low

        <show>Show dates</show>

30 Oct 2017

London

2 Nov 2017

Paris

Johnny Cash

        <show>Show dates</show>

30 Oct 2017

London

2 Nov 2017

Paris

30 Seconds to Mars

        <show>Show dates</show>

30 Oct 2017

London

2 Nov 2017

Paris

Never Shout Never

        <show>Show dates</show>

30 Oct 2017

London

2 Nov 2017

Paris

Miley Cyrus

        <show>Show dates</show>

30 Oct 2017

London

2 Nov 2017

Paris

Thank you so much in advance!

Body:
Change the selector to .info so mouseenter is triggered on the parent element that wraps both of your elements. Then use $.find() to toggle the state of the children of the .info you're hovering.

$(document).ready(function () {
    $('show').hide();
    $('.alldates').hide();

    $('.info').mouseenter(function() {
        $(this).find('.band').fadeTo('fast',1);
        $(this).find('.alldates').show(200);
    });

    $('.info').mouseleave(function() {
        $(this).find('.band').fadeTo('fast',0.5);
        $(this).find('.alldates').hide(200);
    });
});

body {
    font-family: 'Roboto';
}

.container {
    display: flex;
    flex-direction: row;
    justify-content: space-around;
    flex-wrap: wrap;
}

ul,li {
    list-style-type: none;
    list-style: none;
}

.band {
    opacity: 0.5;
    margin-top: 20px;
    display: flex;
    flex-direction: column;
    justify-content:center;
    width: 240px;
    height: 240px;
    align-items: center;
    border-radius: 3px;
    box-shadow: 0px 0px 6px rgba(0,0,0,0.2);
    color: white;
}

.band p {
    font-size: 20px;
    font-weight: 500;
}

show {
    font-size: 16px;
}

.alldates {
    margin-top: 10px;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    height: 120px;
}

.date {
    display: flex;
    justify-content: space-around;
    border: solid 1px #95989A;
    height: 52px;
    align-items: center;
    border-radius: 3px;
    color:#95989A;
}

.band1 {background-color: rgba(40,177,227,1);}
.band2 {background-color: rgba(227,40,52,1);}
.band3 {background-color: rgba(227,213,40,1);}
.band4 {background-color: rgba(0,0,0,1);}
.band5 {background-color: rgba(171,40,227,1);}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="container">

  <div class="info">
    <div class="band band1">
      <p>All Time Low</p>
      <show>Show dates</show>
    </div>

    <div class="alldates">
      <div class="date">
        <li id="time">30 Oct 2017</li>
        <li id="place">London</li>
      </div>
      <div class="date">
        <li id="time">2 Nov 2017</li>
        <li id="place">Paris</li>
      </div>
    </div>
  </div>

  <div class="info">
    <div class="band band2">
      <p>Johnny Cash</p>
      <show>Show dates</show>
    </div>

    <div class="alldates">
      <div class="date">
        <li id="time">30 Oct 2017</li>
        <li id="place">London</li>
      </div>
      <div class="date">
        <li id="time">2 Nov 2017</li>
        <li id="place">Paris</li>
      </div>
    </div>
  </div>

  <div class="info">
    <div class="band band3">
      <p>30 Seconds to Mars</p>
      <show>Show dates</show>
    </div>

    <div class="alldates">
      <div class="date">
        <li id="time">30 Oct 2017</li>
        <li id="place">London</li>
      </div>
      <div class="date">
        <li id="time">2 Nov 2017</li>
        <li id="place">Paris</li>
      </div>
    </div>
  </div>

  <div class="info">
    <div class="band band4">
      <p>Never Shout Never</p>
      <show>Show dates</show>
    </div>

    <div class="alldates">
      <div class="date">
        <li id="time">30 Oct 2017</li>
        <li id="place">London</li>
      </div>
      <div class="date">
        <li id="time">2 Nov 2017</li>
        <li id="place">Paris</li>
      </div>
    </div>
  </div>

  <div class="info">
    <div class="band band5">
      <p>Miley Cyrus</p>
      <show>Show dates</show>
    </div>

    <div class="alldates">
      <div class="date">
        <li id="time">30 Oct 2017</li>
        <li id="place">London</li>
      </div>
      <div class="date">
        <li id="time">2 Nov 2017</li>
        <li id="place">Paris</li>
      </div>
    </div>
  </div>

</div>