问:
How to get post data after form submission by asp.net
I have the following form in one of my asp.net :

```<code>    <html>
<head>
    <script type="text/javascript">

            function GetSampleModel() {
                try {
                    var wldscan = new ActiveXObject("WebLogonDemoClient.WLDScan");

                    var Sl_No = wldscan.GetSl();
                    var sampleModel = wldscan.GetVerifyTemplate();
                    if (sampleModel.length == 0) {
                        alert("Something is Error!!!", "Error");
                    }
                    else {
                        document.getElementById("scan").Sl.Value = Sl_No;
                        document.getElementById("scan").SampleModel.Value = sampleModel;
                        document.getElementById("scan").submit();
                    }
                }
                catch (err) {
                    alert("To verify with a fingerprint device, you should install the WebLogonDemoClient software first.", "Software Not Install Error");
                }
            }
        </script>

        <title>Logon</title>
    </head>
    <body onload="GetSampleModel()">
        <form name="scan" id="scan" method="Post" action="" runat="server">
            <input type="Hidden" name="SampleModel" value="">
            <input type="Hidden" name="Sl" value="">
        </form>
    </body>
    </html>
</code>```

The action of this form is as following :

```<code>http://localhost/finger/famverifyTX.aspx?name=18&appuser='RANA001'&ailogid='1'&depamount=50&sessid='28902343093145'&custno='18'
</code>```

After form submission, I am trying to get submitted data in another page by the following code :

```<code>sl = Request.Form["Sl"];
 String SampleModel = Request.Form["SampleModel"];
</code>```

But there is no data in these 2 variables. Where am I doing mistake ? Please help me .

```<code>NameValueCollection nvclc = Request.Form;
</code>```

After debuggin I am seeing the value of variable as following :

```<code>{__VIEWSTATE=%2fwEPDwUKLTE4MDU5MzAwNg9kFgICAw8WAh4GYWN0aW9uBUNmYW12ZXJpZnlUWC5hc3B4P25hbWU9JmFwcHVzZXI9JmFpbG9naWQ9JmRlcGFtb3VudD0mc2Vzc2lkPSZjdXN0bm89ZGRLaLIbf6gMRB5SeuUkSj7FHaf%2fRZQuSXp1AE1b4qHvCw%3d%3d&SampleModel=&Sl=&__VIEWSTATEGENERATOR=9EF55AFD}
</code>```

I have this code :

```<code> string[] keys = Request.Form.AllKeys;
        var value = "";
        for (int i = 0; i < keys.Length; i++)
        {
            // here you get the name eg test[0].quantity
            // keys[i];
            // to get the value you use
            value = Request.Form[keys[i]];
            Response.Write("Keys is " + keys[i] + " and value is " + value+"<br>");

        }
</code>```

This code shows this output :

```<code>Keys is SampleModel and value is
Keys is Sl and value is
</code>```

So the value of SampleModel and Sl is nothing . How can I get this value from fmaVerifyTX.aspx page ? Please help me .

答:
The following code works for me : </p>

```<code>document.getElementById("Sl").setAttribute('value', Sl_No);
document.getElementById("SampleModel").setAttribute('value', sampleModel);
</code>```

Body:
I have the following form in one of my asp.net :

        <title>Logon</title>

        <form name="scan" id="scan" method="Post" action="" runat="server">
            <input type="Hidden" name="SampleModel" value="">
            <input type="Hidden" name="Sl" value="">
        </form>

The action of this form is as following :

http://localhost/finger/famverifyTX.aspx?name=18&appuser='RANA001'&ailogid='1'&depamount=50&sessid='28902343093145'&custno='18'

After form submission, I am trying to get submitted data in another page by the following code :

sl = Request.Form["Sl"];
 String SampleModel = Request.Form["SampleModel"];

But there is no data in these 2 variables. Where am I doing mistake ? Please help me .

NameValueCollection nvclc = Request.Form;

After debuggin I am seeing the value of variable as following :

{__VIEWSTATE=%2fwEPDwUKLTE4MDU5MzAwNg9kFgICAw8WAh4GYWN0aW9uBUNmYW12ZXJpZnlUWC5hc3B4P25hbWU9JmFwcHVzZXI9JmFpbG9naWQ9JmRlcGFtb3VudD0mc2Vzc2lkPSZjdXN0bm89ZGRLaLIbf6gMRB5SeuUkSj7FHaf%2fRZQuSXp1AE1b4qHvCw%3d%3d&SampleModel=&Sl=&__VIEWSTATEGENERATOR=9EF55AFD}

I have this code :

 string[] keys = Request.Form.AllKeys;
        var value = "";
        for (int i = 0; i < keys.Length; i++)
        {
            // here you get the name eg test[0].quantity
            // keys[i];
            // to get the value you use
            value = Request.Form[keys[i]];
            Response.Write("Keys is " + keys[i] + " and value is " + value+"
");

        }

This code shows this output :

Keys is SampleModel and value is
Keys is Sl and value is

So the value of SampleModel and Sl is nothing . How can I get this value from fmaVerifyTX.aspx page ? Please help me .

Body:
The following code works for me :

document.getElementById("Sl").setAttribute('value', Sl_No);
document.getElementById("SampleModel").setAttribute('value', sampleModel);


来源: stackexchange

问:
Map to substring key in pandas
```<code>>>> print(df)
         out_0          out_1                b       c        e      d
0  out_GFD_994  out_GFD_Part2  NSE_FO_BHP_1703  -27022   361.45 -13200
1  out_GFD_994  out_GFD_Part2  NSE_FO_BHP_1704   30132   399.98  13200
2  out_GFD_994  out_GFD_Part2  NSE_FO_MQG_1703 -145173  1177.97 -11200
3  out_GFD_994  out_GFD_Part2  NSE_FO_MQG_1704  158747  1180.55  12300
4  out_GFD_994  out_GFD_Part2  NSE_FO_TLS_1703   23316  1247.50   3200
5  out_GFD_994  out_GFD_Part2  NSE_FO_TLS_1704  -19333  1253.62  -3200
</code>```

Need to map each key in column b to value in file ( example NSE_FO_BHP_1703 matches to NSE_FO_BHP_1703_* in file)
if  key in file contains LONG as substring, then subtract value in column d
if key in file contains SHORT as substring, then add value in column d

such that the NSE_FO_BHP_1703_MAXLONGPOS = 200000 changes to 213200 change NSE_FO_BHP_1703_MAXSHORTPOS to 186800. Change the MAXLONGEXPOSURE and MAXSHORTEXPOSURE to 263200 and 236800 respectively.
This would be done for every key in b column of df.

```<code>NSE_FO_BHP_1703_MAXLONGPOS = 200000
NSE_FO_BHP_1703_MAXSHORTPOS = 200000
NSE_FO_BHP_1703_MAXLONGEXPOSURE = 250000
NSE_FO_BHP_1703_MAXSHORTEXPOSURE = 250000
NSE_FO_BHP_1704_MAXLONGPOS = 200000
NSE_FO_BHP_1704_MAXSHORTPOS = 200000
NSE_FO_BHP_1704_MAXLONGEXPOSURE = 250000
NSE_FO_BHP_1704_MAXSHORTEXPOSURE = 250000
NSE_FO_TLS_1703_MAXLONGPOS = 100000
NSE_FO_TLS_1703_MAXSHORTPOS = 100000
NSE_FO_TLS_1703_MAXLONGEXPOSURE = 200000
NSE_FO_TLS_1703_MAXSHORTEXPOSURE = 200000
NSE_FO_TLS_1704_MAXLONGPOS = 100000
NSE_FO_TLS_1704_MAXSHORTPOS = 100000
NSE_FO_TLS_1704_MAXLONGEXPOSURE = 200000
NSE_FO_TLS_1704_MAXSHORTEXPOSURE = 200000
NSE_FO_MQG_1703_MAXLONGPOS = 300000
NSE_FO_MQG_1703_MAXSHORTPOS = 300000
NSE_FO_MQG_1703_MAXLONGEXPOSURE = 400000
NSE_FO_MQG_1703_MAXSHORTEXPOSURE = 400000
NSE_FO_DEF_1704_MAXLONGPOS = 300000
NSE_FO_MQG_1704_MAXSHORTPOS = 300000
NSE_FO_MQG_1704_MAXLONGEXPOSURE = 400000
NSE_FO_MQG_1704_MAXSHORTEXPOSURE = 400000
</code>```

答:
I think you can use if all data are in pair - *LONG* and *SHORT*:

```<code>from pandas.compat import StringIO

temp=u"""
NSE_FO_BHP_1703_MAXLONGPOS = 200000
NSE_FO_BHP_1703_MAXSHORTPOS = 200000
NSE_FO_BHP_1703_MAXLONGEXPOSURE = 250000
NSE_FO_BHP_1703_MAXSHORTEXPOSURE = 250000
NSE_FO_BHP_1704_MAXLONGPOS = 200000
NSE_FO_BHP_1704_MAXSHORTPOS = 200000
NSE_FO_BHP_1704_MAXLONGEXPOSURE = 250000
NSE_FO_BHP_1704_MAXSHORTEXPOSURE = 250000
NSE_FO_TLS_1703_MAXLONGPOS = 100000
NSE_FO_TLS_1703_MAXSHORTPOS = 100000
NSE_FO_TLS_1703_MAXLONGEXPOSURE = 200000
NSE_FO_TLS_1703_MAXSHORTEXPOSURE = 200000
NSE_FO_TLS_1704_MAXLONGPOS = 100000
NSE_FO_TLS_1704_MAXSHORTPOS = 100000
NSE_FO_TLS_1704_MAXLONGEXPOSURE = 200000
NSE_FO_TLS_1704_MAXSHORTEXPOSURE = 200000
NSE_FO_MQG_1703_MAXLONGPOS = 300000
NSE_FO_MQG_1703_MAXSHORTPOS = 300000
NSE_FO_MQG_1703_MAXLONGEXPOSURE = 400000
NSE_FO_MQG_1703_MAXSHORTEXPOSURE = 400000
NSE_FO_DEF_1704_MAXLONGPOS = 300000
NSE_FO_MQG_1704_MAXSHORTPOS = 300000
NSE_FO_MQG_1704_MAXLONGEXPOSURE = 400000
NSE_FO_MQG_1704_MAXSHORTEXPOSURE = 400000"""
#after testing replace 'StringIO(temp)' to 'filename.csv'
df2 = pd.read_csv(StringIO(temp), sep="\s+=\s+", engine='python', names=['A','B'])
</code>```

```<code>#create dict for map
d = df1.set_index('b')['d'].to_dict()
#split by last _ and map
a = df2.A.str.rsplit('_', n=1).str[0].map(d)
#if LONG substract, else add
df2['C'] = np.where(df2.A.str.contains('LONG'), df2.B - a, df2.B + a)
print (df2)
                                   A       B         C
0         NSE_FO_BHP_1703_MAXLONGPOS  200000  213200.0
1        NSE_FO_BHP_1703_MAXSHORTPOS  200000  186800.0
2    NSE_FO_BHP_1703_MAXLONGEXPOSURE  250000  263200.0
3   NSE_FO_BHP_1703_MAXSHORTEXPOSURE  250000  236800.0
4         NSE_FO_BHP_1704_MAXLONGPOS  200000  186800.0
5        NSE_FO_BHP_1704_MAXSHORTPOS  200000  213200.0
6    NSE_FO_BHP_1704_MAXLONGEXPOSURE  250000  236800.0
7   NSE_FO_BHP_1704_MAXSHORTEXPOSURE  250000  263200.0
8         NSE_FO_TLS_1703_MAXLONGPOS  100000   96800.0
9        NSE_FO_TLS_1703_MAXSHORTPOS  100000  103200.0
10   NSE_FO_TLS_1703_MAXLONGEXPOSURE  200000  196800.0
11  NSE_FO_TLS_1703_MAXSHORTEXPOSURE  200000  203200.0
12        NSE_FO_TLS_1704_MAXLONGPOS  100000  103200.0
13       NSE_FO_TLS_1704_MAXSHORTPOS  100000   96800.0
14   NSE_FO_TLS_1704_MAXLONGEXPOSURE  200000  203200.0
15  NSE_FO_TLS_1704_MAXSHORTEXPOSURE  200000  196800.0
16        NSE_FO_MQG_1703_MAXLONGPOS  300000  311200.0
17       NSE_FO_MQG_1703_MAXSHORTPOS  300000  288800.0
18   NSE_FO_MQG_1703_MAXLONGEXPOSURE  400000  411200.0
19  NSE_FO_MQG_1703_MAXSHORTEXPOSURE  400000  388800.0
20        NSE_FO_DEF_1704_MAXLONGPOS  300000       NaN <-no data in df1 - map return NaN
21       NSE_FO_MQG_1704_MAXSHORTPOS  300000  312300.0
22   NSE_FO_MQG_1704_MAXLONGEXPOSURE  400000  387700.0
23  NSE_FO_MQG_1704_MAXSHORTEXPOSURE  400000  412300.0
</code>```

ContentLicense: CC BY-SA 3.0

Title: Map to substring key in pandas

Body:
>>> print(df)
         out_0          out_1                b       c        e      d
0  out_GFD_994  out_GFD_Part2  NSE_FO_BHP_1703  -27022   361.45 -13200
1  out_GFD_994  out_GFD_Part2  NSE_FO_BHP_1704   30132   399.98  13200
2  out_GFD_994  out_GFD_Part2  NSE_FO_MQG_1703 -145173  1177.97 -11200
3  out_GFD_994  out_GFD_Part2  NSE_FO_MQG_1704  158747  1180.55  12300
4  out_GFD_994  out_GFD_Part2  NSE_FO_TLS_1703   23316  1247.50   3200
5  out_GFD_994  out_GFD_Part2  NSE_FO_TLS_1704  -19333  1253.62  -3200

Need to map each key in column b to value in file ( example NSE_FO_BHP_1703 matches to NSE_FO_BHP_1703_* in file)
if  key in file contains LONG as substring, then subtract value in column d
if key in file contains SHORT as substring, then add value in column d

such that the NSE_FO_BHP_1703_MAXLONGPOS = 200000 changes to 213200 change NSE_FO_BHP_1703_MAXSHORTPOS to 186800. Change the MAXLONGEXPOSURE and MAXSHORTEXPOSURE to 263200 and 236800 respectively.
This would be done for every key in b column of df.

NSE_FO_BHP_1703_MAXLONGPOS = 200000
NSE_FO_BHP_1703_MAXSHORTPOS = 200000
NSE_FO_BHP_1703_MAXLONGEXPOSURE = 250000
NSE_FO_BHP_1703_MAXSHORTEXPOSURE = 250000
NSE_FO_BHP_1704_MAXLONGPOS = 200000
NSE_FO_BHP_1704_MAXSHORTPOS = 200000
NSE_FO_BHP_1704_MAXLONGEXPOSURE = 250000
NSE_FO_BHP_1704_MAXSHORTEXPOSURE = 250000
NSE_FO_TLS_1703_MAXLONGPOS = 100000
NSE_FO_TLS_1703_MAXSHORTPOS = 100000
NSE_FO_TLS_1703_MAXLONGEXPOSURE = 200000
NSE_FO_TLS_1703_MAXSHORTEXPOSURE = 200000
NSE_FO_TLS_1704_MAXLONGPOS = 100000
NSE_FO_TLS_1704_MAXSHORTPOS = 100000
NSE_FO_TLS_1704_MAXLONGEXPOSURE = 200000
NSE_FO_TLS_1704_MAXSHORTEXPOSURE = 200000
NSE_FO_MQG_1703_MAXLONGPOS = 300000
NSE_FO_MQG_1703_MAXSHORTPOS = 300000
NSE_FO_MQG_1703_MAXLONGEXPOSURE = 400000
NSE_FO_MQG_1703_MAXSHORTEXPOSURE = 400000
NSE_FO_DEF_1704_MAXLONGPOS = 300000
NSE_FO_MQG_1704_MAXSHORTPOS = 300000
NSE_FO_MQG_1704_MAXLONGEXPOSURE = 400000
NSE_FO_MQG_1704_MAXSHORTEXPOSURE = 400000

Body:
I think you can use if all data are in pair - *LONG* and *SHORT*:

from pandas.compat import StringIO

temp=u"""
NSE_FO_BHP_1703_MAXLONGPOS = 200000
NSE_FO_BHP_1703_MAXSHORTPOS = 200000
NSE_FO_BHP_1703_MAXLONGEXPOSURE = 250000
NSE_FO_BHP_1703_MAXSHORTEXPOSURE = 250000
NSE_FO_BHP_1704_MAXLONGPOS = 200000
NSE_FO_BHP_1704_MAXSHORTPOS = 200000
NSE_FO_BHP_1704_MAXLONGEXPOSURE = 250000
NSE_FO_BHP_1704_MAXSHORTEXPOSURE = 250000
NSE_FO_TLS_1703_MAXLONGPOS = 100000
NSE_FO_TLS_1703_MAXSHORTPOS = 100000
NSE_FO_TLS_1703_MAXLONGEXPOSURE = 200000
NSE_FO_TLS_1703_MAXSHORTEXPOSURE = 200000
NSE_FO_TLS_1704_MAXLONGPOS = 100000
NSE_FO_TLS_1704_MAXSHORTPOS = 100000
NSE_FO_TLS_1704_MAXLONGEXPOSURE = 200000
NSE_FO_TLS_1704_MAXSHORTEXPOSURE = 200000
NSE_FO_MQG_1703_MAXLONGPOS = 300000
NSE_FO_MQG_1703_MAXSHORTPOS = 300000
NSE_FO_MQG_1703_MAXLONGEXPOSURE = 400000
NSE_FO_MQG_1703_MAXSHORTEXPOSURE = 400000
NSE_FO_DEF_1704_MAXLONGPOS = 300000
NSE_FO_MQG_1704_MAXSHORTPOS = 300000
NSE_FO_MQG_1704_MAXLONGEXPOSURE = 400000
NSE_FO_MQG_1704_MAXSHORTEXPOSURE = 400000"""
#after testing replace 'StringIO(temp)' to 'filename.csv'
df2 = pd.read_csv(StringIO(temp), sep="\s+=\s+", engine='python', names=['A','B'])

#create dict for map
d = df1.set_index('b')['d'].to_dict()
#split by last _ and map
a = df2.A.str.rsplit('_', n=1).str[0].map(d)
#if LONG substract, else add
df2['C'] = np.where(df2.A.str.contains('LONG'), df2.B - a, df2.B + a)
print (df2)
                                   A       B         C
0         NSE_FO_BHP_1703_MAXLONGPOS  200000  213200.0
1        NSE_FO_BHP_1703_MAXSHORTPOS  200000  186800.0
2    NSE_FO_BHP_1703_MAXLONGEXPOSURE  250000  263200.0
3   NSE_FO_BHP_1703_MAXSHORTEXPOSURE  250000  236800.0
4         NSE_FO_BHP_1704_MAXLONGPOS  200000  186800.0
5        NSE_FO_BHP_1704_MAXSHORTPOS  200000  213200.0
6    NSE_FO_BHP_1704_MAXLONGEXPOSURE  250000  236800.0
7   NSE_FO_BHP_1704_MAXSHORTEXPOSURE  250000  263200.0
8         NSE_FO_TLS_1703_MAXLONGPOS  100000   96800.0
9        NSE_FO_TLS_1703_MAXSHORTPOS  100000  103200.0
10   NSE_FO_TLS_1703_MAXLONGEXPOSURE  200000  196800.0
11  NSE_FO_TLS_1703_MAXSHORTEXPOSURE  200000  203200.0
12        NSE_FO_TLS_1704_MAXLONGPOS  100000  103200.0
13       NSE_FO_TLS_1704_MAXSHORTPOS  100000   96800.0
14   NSE_FO_TLS_1704_MAXLONGEXPOSURE  200000  203200.0
15  NSE_FO_TLS_1704_MAXSHORTEXPOSURE  200000  196800.0
16        NSE_FO_MQG_1703_MAXLONGPOS  300000  311200.0
17       NSE_FO_MQG_1703_MAXSHORTPOS  300000  288800.0
18   NSE_FO_MQG_1703_MAXLONGEXPOSURE  400000  411200.0
19  NSE_FO_MQG_1703_MAXSHORTEXPOSURE  400000  388800.0
20        NSE_FO_DEF_1704_MAXLONGPOS  300000       NaN <-no data in df1 - map return NaN
21       NSE_FO_MQG_1704_MAXSHORTPOS  300000  312300.0
22   NSE_FO_MQG_1704_MAXLONGEXPOSURE  400000  387700.0
23  NSE_FO_MQG_1704_MAXSHORTEXPOSURE  400000  412300.0


问:
C: what is wrong with this char pointer assignment?
A newbie question:

I was practice assignment to a char pointer, but found there was nothing printed out. Here is the code:

```<code>#include <stdio.h>

int main (void)
{
    char * option_string = NULL;
    option_string = (char*)malloc(sizeof(5));
    memset(option_string, 0, sizeof(char) * 5);

    int j;
    for ( j = 0; j < 5; j++)
    {
        *option_string++ = 'a';
    }

    printf("print options_string: %s\n", option_string); //!nothing was printed out!
    free(option_string);
    return 0;
}
</code>```

Thanks in advance!

答:
You increment the pointer option_string which in turn makes it point past the end of string.

Try
    malloc(6);

```<code>for ( j = 0; j < 5; j++)
{
    option_string[j] = 'a';
}
</code>```

instead.

ContentLicense: CC BY-SA 2.5

Body:
A newbie question:

I was practice assignment to a char pointer, but found there was nothing printed out. Here is the code:

#include <stdio.h>

int main (void)
{
    char * option_string = NULL;
    option_string = (char*)malloc(sizeof(5));
    memset(option_string, 0, sizeof(char) * 5);

    int j;
    for ( j = 0; j < 5; j++)
    {
        *option_string++ = 'a';
    }

    printf("print options_string: %s\n", option_string); //!nothing was printed out!
    free(option_string);
    return 0;
}

Thanks in advance!

Body:
You increment the pointer option_string which in turn makes it point past the end of string.

Try
    malloc(6);

for ( j = 0; j < 5; j++)
{
    option_string[j] = 'a';
}

instead.


问:
WS-Trust MEX endpoint in IdentityServer 2 returns HTTP 400 for GET requests
We've customised IdentityServer 2 to provide identity federation capability into Azure AD (for Office 365, etc). This has a WS-Federation endpoint for the passive requester flow and WS-Trust for active clients. The MEX endpoint for WS-Trust should return the WSDL for the WS-Trust SOAP in response to both a POST (as Lync uses) and GET (as Windows 10 sign in uses). Unfortunately, it is returning HTTP 400: ws-trust system.servicemodel.protocolexception "There is a problem with the XML that was received from the network".

As can be seen in the source:
https://github.com/IdentityServer/IdentityServer2/blob/master/src/Libraries/Thinktecture.IdentityServer.Protocols/WSTrust/TokenServiceHostFactory.cs

```<code>var host = new WSTrustServiceHost(config, baseAddresses);

// add behavior for load balancing support
host.Description.Behaviors.Add(new UseRequestHeadersForMetadataAddressBehavior());

// modify address filter mode for load balancing
var serviceBehavior = host.Description.Behaviors.Find<ServiceBehaviorAttribute>();
serviceBehavior.AddressFilterMode = AddressFilterMode.Any;
serviceBehavior.IncludeExceptionDetailInFaults = true;
</code>```

An instance of System.ServiceModel.Security.WSTrustServiceHost is being stood up to handle calls to WS-Trust, and handle its metadata. Checking the ServiceMetadataBehavior that is added by default in WSTrustServiceHost ctor, we can see that it does enable metadata for GET over both HTTP and HTTPS.
http://referencesource.microsoft.com/#System.ServiceModel/System/ServiceModel/Security/WSTrustServiceHost.cs,8c80389f2532b060,references

So I'm a little confused why https://myhost.com/issue/wstrust/mex returns the metadata when hit with a POST, but returns 400 when you send it a GET. The exception is being thrown in a EnqueueMessageAsyncResult.CompleteParseAndEnqueue() in System.ServiceModel
http://referencesource.microsoft.com/#System.ServiceModel/System/ServiceModel/Channels/HttpPipeline.cs,b347567a68ab778c,references

Any help greatly appreciated!

答:
For others stuck in the same place, I have explicitly set the TokenServiceHostFactory to respond to HTTP GET.  </p>

```<code>// added for AAD Windows 10 sign in - device requests metadata with GET
ServiceMetadataBehavior metad = host.Description.Behaviors.Find<ServiceMetadataBehavior>();
if (metad == null)
    metad = new ServiceMetadataBehavior();
for (int i = 0; i < baseAddresses.Length; i++)
{
    // there will be two bindings: one for http and one secure
    switch (baseAddresses[i].Scheme)
    {
        case "http":
            metad.HttpGetEnabled = true;
            metad.HttpGetUrl = new Uri(baseAddresses[i], "/issue/wstrust/mex");
            break;
        case "https":
            metad.HttpsGetEnabled = true;
            metad.HttpsGetUrl = new Uri(baseAddresses[i], "/issue/wstrust/mex");
            break;
    }
}
</code>```

Body:
We've customised IdentityServer 2 to provide identity federation capability into Azure AD (for Office 365, etc). This has a WS-Federation endpoint for the passive requester flow and WS-Trust for active clients. The MEX endpoint for WS-Trust should return the WSDL for the WS-Trust SOAP in response to both a POST (as Lync uses) and GET (as Windows 10 sign in uses). Unfortunately, it is returning HTTP 400: ws-trust system.servicemodel.protocolexception "There is a problem with the XML that was received from the network".

As can be seen in the source:
https://github.com/IdentityServer/IdentityServer2/blob/master/src/Libraries/Thinktecture.IdentityServer.Protocols/WSTrust/TokenServiceHostFactory.cs

var host = new WSTrustServiceHost(config, baseAddresses);

// add behavior for load balancing support
host.Description.Behaviors.Add(new UseRequestHeadersForMetadataAddressBehavior());

// modify address filter mode for load balancing
var serviceBehavior = host.Description.Behaviors.Find<ServiceBehaviorAttribute>();
serviceBehavior.AddressFilterMode = AddressFilterMode.Any;
serviceBehavior.IncludeExceptionDetailInFaults = true;

An instance of System.ServiceModel.Security.WSTrustServiceHost is being stood up to handle calls to WS-Trust, and handle its metadata. Checking the ServiceMetadataBehavior that is added by default in WSTrustServiceHost ctor, we can see that it does enable metadata for GET over both HTTP and HTTPS.
http://referencesource.microsoft.com/#System.ServiceModel/System/ServiceModel/Security/WSTrustServiceHost.cs,8c80389f2532b060,references

So I'm a little confused why https://myhost.com/issue/wstrust/mex returns the metadata when hit with a POST, but returns 400 when you send it a GET. The exception is being thrown in a EnqueueMessageAsyncResult.CompleteParseAndEnqueue() in System.ServiceModel
http://referencesource.microsoft.com/#System.ServiceModel/System/ServiceModel/Channels/HttpPipeline.cs,b347567a68ab778c,references

Any help greatly appreciated!

Body:
For others stuck in the same place, I have explicitly set the TokenServiceHostFactory to respond to HTTP GET.

// added for AAD Windows 10 sign in - device requests metadata with GET
ServiceMetadataBehavior metad = host.Description.Behaviors.Find<ServiceMetadataBehavior>();
if (metad == null)
    metad = new ServiceMetadataBehavior();
for (int i = 0; i < baseAddresses.Length; i++)
{
    // there will be two bindings: one for http and one secure
    switch (baseAddresses[i].Scheme)
    {
        case "http":
            metad.HttpGetEnabled = true;
            metad.HttpGetUrl = new Uri(baseAddresses[i], "/issue/wstrust/mex");
            break;
        case "https":
            metad.HttpsGetEnabled = true;
            metad.HttpsGetUrl = new Uri(baseAddresses[i], "/issue/wstrust/mex");
            break;
    }
}


问:
NSMutablearray addobject , added objects not expected
I've a question about NSMutablearray addobject, I think it's about object lifecycle. Searched but not got answer.

Here's the code:

```<code>    NSMutableString *str1 = [[NSMutableString alloc]init] ;
    NSMutableArray *arr1 = [[NSMutableArray alloc]init] ;
    for (int i=0 ;i<3 ;i++) {
        str1 =[NSMutableString stringWithFormat:@"%ld",(random() % 100) ] ;
        [arr1 addObject:str1] ;
        NSLog(@"arr1 inside loop:%@",arr1) ;
        [str1 setString:@""] ;    }
    NSLog(@"arr1 outside loop:%@",arr1) ;

    NSMutableString *str2 = [[NSMutableString alloc]init] ;
    NSMutableArray *arr2 = [[NSMutableArray alloc]init] ;
    for (int i=0 ;i<3 ;i++) {
        str2 =[NSMutableString stringWithFormat:@"%ld",(random() % 100) ] ;
        [arr2 addObject:str2] ;        }
    [str2 setString:@"abc"] ;
    NSLog(@"arr1:%@",arr2) ;
</code>```

I expect that arr1 & arr2 both include 3 random number objects.
but the real output is:

```<code>arr1 inside loop:(
    83
)
arr1 inside loop:(
    "",
    86
)
arr1 inside loop:(
    "",
    "",
    77
)
arr1 outside loop:(
    "",
    "",
    ""
)
arr2:(
    15,
    93,
    abc
)
</code>```

Q1: Arr1, why the added objects changed to ""?
(If the reason is all 3 objects are just 3 pointers and they point to the same object, then I have Q2 --)

Q2: Arr2, why the last object of arr2 is "abc" but the others not.

Thanks!

答:
Q1:Arr1, why the added objects changed to ""?

Every time you used [NSMutableString stringWithFormat:@"%ld",(random() % 100) ] ; you created a new NSMutableString object and changed the pointer of str1 so it would point to that new object.

However, when you used [str1 setString:@""] ;, you changed str1's object value, so you changed the array object value as well, since [arr1 addObject:str1] ; adds the str1 pointer to the arr1 array only.

Q2:Arr2, why the last object of arr2 is "abc" but the others not.

This is your code with { and } in separated lines:

```<code>for (int i=0 ;i<3 ;i++)
{
    str2 =[NSMutableString stringWithFormat:@"%ld",(random() % 100) ];
    [arr2 addObject:str2] ;
}
[str2 setString:@"abc"] ;
NSLog(@"arr1:%@",arr2) ;
</code>```

You are creating new objects with [NSMutableString stringWithFormat:@"%ld",(random() % 100) ]; and changing the str2 pointer, adding its pointer to arr2 in [arr2 addObject:str2] ;.

After the for, you use [str2 setString:@"abc"], str2 is pointing to the last object that you created inside your for, which is the last item that you added to the array.

Body:
I've a question about NSMutablearray addobject, I think it's about object lifecycle. Searched but not got answer.

Here's the code:

    NSMutableString *str1 = [[NSMutableString alloc]init] ;
    NSMutableArray *arr1 = [[NSMutableArray alloc]init] ;
    for (int i=0 ;i<3 ;i++) {
        str1 =[NSMutableString stringWithFormat:@"%ld",(random() % 100) ] ;
        [arr1 addObject:str1] ;
        NSLog(@"arr1 inside loop:%@",arr1) ;
        [str1 setString:@""] ;    }
    NSLog(@"arr1 outside loop:%@",arr1) ;

    NSMutableString *str2 = [[NSMutableString alloc]init] ;
    NSMutableArray *arr2 = [[NSMutableArray alloc]init] ;
    for (int i=0 ;i<3 ;i++) {
        str2 =[NSMutableString stringWithFormat:@"%ld",(random() % 100) ] ;
        [arr2 addObject:str2] ;        }
    [str2 setString:@"abc"] ;
    NSLog(@"arr1:%@",arr2) ;

I expect that arr1 & arr2 both include 3 random number objects.
but the real output is:

arr1 inside loop:(
    83
)
arr1 inside loop:(
    "",
    86
)
arr1 inside loop:(
    "",
    "",
    77
)
arr1 outside loop:(
    "",
    "",
    ""
)
arr2:(
    15,
    93,
    abc
)

Q1: Arr1, why the added objects changed to ""?
(If the reason is all 3 objects are just 3 pointers and they point to the same object, then I have Q2 --)

Q2: Arr2, why the last object of arr2 is "abc" but the others not.

Thanks!

Body:
Q1:Arr1, why the added objects changed to ""?

Every time you used [NSMutableString stringWithFormat:@"%ld",(random() % 100) ] ; you created a new NSMutableString object and changed the pointer of str1 so it would point to that new object.

However, when you used [str1 setString:@""] ;, you changed str1's object value, so you changed the array object value as well, since [arr1 addObject:str1] ; adds the str1 pointer to the arr1 array only.

Q2:Arr2, why the last object of arr2 is "abc" but the others not.

This is your code with { and } in separated lines:

for (int i=0 ;i<3 ;i++)
{
    str2 =[NSMutableString stringWithFormat:@"%ld",(random() % 100) ];
    [arr2 addObject:str2] ;
}
[str2 setString:@"abc"] ;
NSLog(@"arr1:%@",arr2) ;

You are creating new objects with [NSMutableString stringWithFormat:@"%ld",(random() % 100) ]; and changing the str2 pointer, adding its pointer to arr2 in [arr2 addObject:str2] ;.

After the for, you use [str2 setString:@"abc"], str2 is pointing to the last object that you created inside your for, which is the last item that you added to the array.


问:
Can't execute Js script using Selenium+Python
I have a few date inputs in UI and I've got a problem when trying to fill the date in it - after filling, and switching to the next input, the date erases. I've dicided to execute Js script, which will change the value of input and set the right date.

So, I do this:

```<code>wd.find_element_by_css_selector('input[value\\.bind="data.object[\'construction_date\']"]').execute_script("'$('input').val('01.01.1991')")
</code>```

And got the AttributeError on execution:

```<code> AttributeError: 'WebDriver' object has no attribute 'window'
</code>```

How can I fix the problem?

答:
If you want to change elements' value with JavaScriptExecutor you might try:

```<code>element = wd.find_element_by_css_selector('input[value\\.bind="data.object[\'construction_date\']"]')
wd.execute_script('arguments[0].value="01.01.1991";', element)
</code>```

Body:
I have a few date inputs in UI and I've got a problem when trying to fill the date in it - after filling, and switching to the next input, the date erases. I've dicided to execute Js script, which will change the value of input and set the right date.

So, I do this:

wd.find_element_by_css_selector('input[value\\.bind="data.object[\'construction_date\']"]').execute_script("'$('input').val('01.01.1991')")

And got the AttributeError on execution:

 AttributeError: 'WebDriver' object has no attribute 'window'

How can I fix the problem?

Body:
If you want to change elements' value with JavaScriptExecutor you might try:

element = wd.find_element_by_css_selector('input[value\\.bind="data.object[\'construction_date\']"]')
wd.execute_script('arguments[0].value="01.01.1991";', element)


问:
HttpClient and stream issues
A year ago I wrote a cmdlet that handles Multipart/form-data requests and it is leveraging the .net class HttpClient in order to do so. I described it in details here.

In a nutshell this is the core of my cmdlet:

```<code>$networkCredential = New-Object -TypeName System.Net.NetworkCredential -ArgumentList @($Credential.UserName, $Credential.Password)
$httpClientHandler = New-Object -TypeName System.Net.Http.HttpClientHandler
$httpClientHandler.Credentials = $networkCredential

$httpClient = New-Object -TypeName System.Net.Http.Httpclient -ArgumentList @($httpClientHandler)

$packageFileStream = New-Object -TypeName System.IO.FileStream -ArgumentList @($packagePath, [System.IO.FileMode]::Open)

$contentDispositionHeaderValue = New-Object -TypeName  System.Net.Http.Headers.ContentDispositionHeaderValue -ArgumentList @("form-data")
$contentDispositionHeaderValue.Name = "fileData"
$contentDispositionHeaderValue.FileName = $fileName

$streamContent = New-Object -TypeName System.Net.Http.StreamContent -ArgumentList @($packageFileStream)
$streamContent.Headers.ContentDisposition = $contentDispositionHeaderValue
$streamContent.Headers.ContentType = New-Object -TypeName System.Net.Http.Headers.MediaTypeHeaderValue -ArgumentList @("application/octet-stream")

$content = New-Object -TypeName System.Net.Http.MultipartFormDataContent
$content.Add($streamContent)

try
{
    $response = $httpClient.PostAsync("$EndpointUrl/package/upload/$fileName", $content).GetAwaiter().GetResult()

    if (!$response.IsSuccessStatusCode)
    {
        $responseBody = $response.Content.ReadAsStringAsync().GetAwaiter().GetResult()
        $errorMessage = "Status code {0}. Reason {1}. Server reported the following message: {2}." -f $response.StatusCode, $response.ReasonPhrase, $responseBody

        throw [System.Net.Http.HttpRequestException] $errorMessage
    }

    return [xml]$response.Content.ReadAsStringAsync().GetAwaiter().GetResult()
}
catch [Exception]
{
    throw
}
finally
{
    if($null -ne $httpClient)
    {
        $httpClient.Dispose()
    }

    if($null -ne $response)
    {
        $response.Dispose()
    }
}
</code>```

I was using this code in a VSTS Build task for over a year with success. Recently it started intermittently failing. In one run it succeeds then the next one fails and so on. I can't understand why this is the case and I would use some help.

The code fails on PostAsync method invocation and following is the exception I do see:

```<code>2017-03-24T15:17:38.4470248Z ##[debug]System.NotSupportedException: The stream does not support concurrent IO read or write operations.
2017-03-24T15:17:38.4626512Z ##[debug]   at System.Net.ConnectStream.InternalWrite(Boolean async, Byte[] buffer, Int32 offset, Int32 size, AsyncCallback callback, Object state)
2017-03-24T15:17:38.4626512Z ##[debug]   at System.Net.ConnectStream.BeginWrite(Byte[] buffer, Int32 offset, Int32 size, AsyncCallback callback, Object state)
2017-03-24T15:17:38.4626512Z ##[debug]   at System.Net.Http.StreamToStreamCopy.TryStartWriteSync(Int32 bytesRead)
2017-03-24T15:17:38.4626512Z ##[debug]   at System.Net.Http.StreamToStreamCopy.BufferReadCallback(IAsyncResult ar)
2017-03-24T15:17:38.4626512Z ##[debug]--- End of stack trace from previous location where exception was thrown ---
2017-03-24T15:17:38.4626512Z ##[debug]   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
2017-03-24T15:17:38.4626512Z ##[debug]   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
2017-03-24T15:17:38.4626512Z ##[debug]   at CallSite.Target(Closure , CallSite , Object )
2017-03-24T15:17:38.4939015Z ##[error]The stream does not support concurrent IO read or write operations.
</code>```

I have tried to execute this on different build servers, on hosted agent, etc. but the result is the same. Also if I try to execute this code from an interactive session on my build server from ISE I can't have the code to fail.
I posed a similar question on the VSTS build task project here but till now, no luck.

Does anyone have a suggestion or a test I can do in order to understand what is going on and why is this failing?

I would appreciate any tip.

UPDATE 1:

I executed my code by running it as a background job via a Start-Job cmdlet and I can't get it to fail. So it needs to be something related with the way the VSTS agent executes my code. I'll keep digging. If you have any suggestions, they are still more then welcome.

答:
System.Net.Http.StreamContent and System.IO.FileStream are instantiated but not disposed.

Add the code to invoke Dispose like you did in finally block.

```<code>try
{
    # enclose the program
}
finally
{
    if($null -ne $streamContent)
    {
        $streamContent.Dispose()
    }
    if($null -ne $packageFileStream)
    {
        $packageFileStream.Dispose()
    }
}
</code>```

Title: HttpClient and stream issues

Body:
A year ago I wrote a cmdlet that handles Multipart/form-data requests and it is leveraging the .net class HttpClient in order to do so. I described it in details here.

In a nutshell this is the core of my cmdlet:

$networkCredential = New-Object -TypeName System.Net.NetworkCredential -ArgumentList @($Credential.UserName, $Credential.Password)
$httpClientHandler = New-Object -TypeName System.Net.Http.HttpClientHandler
$httpClientHandler.Credentials = $networkCredential

$httpClient = New-Object -TypeName System.Net.Http.Httpclient -ArgumentList @($httpClientHandler)

$packageFileStream = New-Object -TypeName System.IO.FileStream -ArgumentList @($packagePath, [System.IO.FileMode]::Open)

$contentDispositionHeaderValue = New-Object -TypeName  System.Net.Http.Headers.ContentDispositionHeaderValue -ArgumentList @("form-data")
$contentDispositionHeaderValue.Name = "fileData"
$contentDispositionHeaderValue.FileName = $fileName

$streamContent = New-Object -TypeName System.Net.Http.StreamContent -ArgumentList @($packageFileStream)
$streamContent.Headers.ContentDisposition = $contentDispositionHeaderValue
$streamContent.Headers.ContentType = New-Object -TypeName System.Net.Http.Headers.MediaTypeHeaderValue -ArgumentList @("application/octet-stream")

$content = New-Object -TypeName System.Net.Http.MultipartFormDataContent
$content.Add($streamContent)

try
{
    $response = $httpClient.PostAsync("$EndpointUrl/package/upload/$fileName", $content).GetAwaiter().GetResult()

    if (!$response.IsSuccessStatusCode)
    {
        $responseBody = $response.Content.ReadAsStringAsync().GetAwaiter().GetResult()
        $errorMessage = "Status code {0}. Reason {1}. Server reported the following message: {2}." -f $response.StatusCode, $response.ReasonPhrase, $responseBody

        throw [System.Net.Http.HttpRequestException] $errorMessage
    }

    return [xml]$response.Content.ReadAsStringAsync().GetAwaiter().GetResult()
}
catch [Exception]
{
    throw
}
finally
{
    if($null -ne $httpClient)
    {
        $httpClient.Dispose()
    }

    if($null -ne $response)
    {
        $response.Dispose()
    }
}

I was using this code in a VSTS Build task for over a year with success. Recently it started intermittently failing. In one run it succeeds then the next one fails and so on. I can't understand why this is the case and I would use some help.

The code fails on PostAsync method invocation and following is the exception I do see:

2017-03-24T15:17:38.4470248Z ##[debug]System.NotSupportedException: The stream does not support concurrent IO read or write operations.
2017-03-24T15:17:38.4626512Z ##[debug]   at System.Net.ConnectStream.InternalWrite(Boolean async, Byte[] buffer, Int32 offset, Int32 size, AsyncCallback callback, Object state)
2017-03-24T15:17:38.4626512Z ##[debug]   at System.Net.ConnectStream.BeginWrite(Byte[] buffer, Int32 offset, Int32 size, AsyncCallback callback, Object state)
2017-03-24T15:17:38.4626512Z ##[debug]   at System.Net.Http.StreamToStreamCopy.TryStartWriteSync(Int32 bytesRead)
2017-03-24T15:17:38.4626512Z ##[debug]   at System.Net.Http.StreamToStreamCopy.BufferReadCallback(IAsyncResult ar)
2017-03-24T15:17:38.4626512Z ##[debug]--- End of stack trace from previous location where exception was thrown ---
2017-03-24T15:17:38.4626512Z ##[debug]   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
2017-03-24T15:17:38.4626512Z ##[debug]   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
2017-03-24T15:17:38.4626512Z ##[debug]   at CallSite.Target(Closure , CallSite , Object )
2017-03-24T15:17:38.4939015Z ##[error]The stream does not support concurrent IO read or write operations.

I have tried to execute this on different build servers, on hosted agent, etc. but the result is the same. Also if I try to execute this code from an interactive session on my build server from ISE I can't have the code to fail.
I posed a similar question on the VSTS build task project here but till now, no luck.

Does anyone have a suggestion or a test I can do in order to understand what is going on and why is this failing?

I would appreciate any tip.

UPDATE 1:

I executed my code by running it as a background job via a Start-Job cmdlet and I can't get it to fail. So it needs to be something related with the way the VSTS agent executes my code. I'll keep digging. If you have any suggestions, they are still more then welcome.

Body:
System.Net.Http.StreamContent and System.IO.FileStream are instantiated but not disposed.

Add the code to invoke Dispose like you did in finally block.

try
{
    # enclose the program
}
finally
{
    if($null -ne $streamContent)
    {
        $streamContent.Dispose()
    }
    if($null -ne $packageFileStream)
    {
        $packageFileStream.Dispose()
    }
}


问:
ArrayList of int[] in a recursive method
I have a project to do for school in which i have to use a recursive method that will calculate all the switching possibilities between some numbers.
I.E : [1,2] => 1,2 and 2,1.

So i've used this method and it seemed to be working properly when i just print the solutions on the console, but when i want to stock the tabs in an ArrayList (i need to use them later) it will always add the same order. In my exemple it would have added 1,2 and 1,2 instead of 1,2 and 2,1.

Here's my code :

```<code>public  static void permute(int start, int[] input, ArrayList <int[]> al) {
    //This method is recursive, it will open multiple instances of the input tab by calling itself and modify them, then stock tab in ArrayList when the operations are done for this tab.
    //ArrayList must be empty.

    //Printing tab if iterations for that specific tab are done
    if (start == input.length) {
        al.add(input);
        ////////////////////////////////
        // For printing tabs in console.
        // for(int x: input){
        // System.out.print(x);
        // }
        // System.out.println("");
        ////////////////////////////////
    //End the specific tab loop when it's printed

    return;
    }
    for (int i = start; i < input.length; i++) {
        // Changing numbers
        int temp = input[i];
        input[i] = input[start];
        input[start] = temp;

        //////////////////////////////////////////////////
        // Tests to see algorithm steps
        //
        // System.out.print("temp : " + temp + " ... ");
        // System.out.print("i : "+i + " ... ");
        // System.out.print("start : " + start);
        // System.out.println("");
        // System.out.print("---");
        // for(int x: input){
        //  System.out.print(x);
        // }
        // System.out.println("");
        //////////////////////////////////////////////////

        //Changing numbers
        permute(start + 1, input, al);

       // Changing numbers
        int temp2 = input[i];
        input[i] = input[start];
        input[start] = temp2;

}
</code>```

}

I use start = 0, input = {1,2,3} and the ArrayList is empty before the method starts.

Hope you can help, thanks !

答:
The problem is that you are adding a reference to an array into your ArrayList, reference that you then keep changing in your algorithm.

By the end of it, you will have perm(N) copies of the same array.

All you have to do is to add a deep-copy of the array into the ArrayList, like this:

```<code>al.add(Arrays.copyOf(input, input.length));
</code>```

instead of

```<code>al.add(input);
</code>```

Printing the resulting ArrayList will then produce the following output:

```<code>[1, 2, 3]
[1, 3, 2]
[2, 1, 3]
[2, 3, 1]
[3, 2, 1]
[3, 1, 2]
</code>```

Body:
I have a project to do for school in which i have to use a recursive method that will calculate all the switching possibilities between some numbers.
I.E : [1,2] => 1,2 and 2,1.

So i've used this method and it seemed to be working properly when i just print the solutions on the console, but when i want to stock the tabs in an ArrayList (i need to use them later) it will always add the same order. In my exemple it would have added 1,2 and 1,2 instead of 1,2 and 2,1.

Here's my code :

public  static void permute(int start, int[] input, ArrayList <int[]> al) {
    //This method is recursive, it will open multiple instances of the input tab by calling itself and modify them, then stock tab in ArrayList when the operations are done for this tab.
    //ArrayList must be empty.

    //Printing tab if iterations for that specific tab are done
    if (start == input.length) {
        al.add(input);
        ////////////////////////////////
        // For printing tabs in console.
        // for(int x: input){
        // System.out.print(x);
        // }
        // System.out.println("");
        ////////////////////////////////
    //End the specific tab loop when it's printed

    return;
    }
    for (int i = start; i < input.length; i++) {
        // Changing numbers
        int temp = input[i];
        input[i] = input[start];
        input[start] = temp;

        //////////////////////////////////////////////////
        // Tests to see algorithm steps
        //
        // System.out.print("temp : " + temp + " ... ");
        // System.out.print("i : "+i + " ... ");
        // System.out.print("start : " + start);
        // System.out.println("");
        // System.out.print("---");
        // for(int x: input){
        //  System.out.print(x);
        // }
        // System.out.println("");
        //////////////////////////////////////////////////

        //Changing numbers
        permute(start + 1, input, al);

       // Changing numbers
        int temp2 = input[i];
        input[i] = input[start];
        input[start] = temp2;

}

}

I use start = 0, input = {1,2,3} and the ArrayList is empty before the method starts.

Hope you can help, thanks !

Body:
The problem is that you are adding a reference to an array into your ArrayList, reference that you then keep changing in your algorithm.

By the end of it, you will have perm(N) copies of the same array.

All you have to do is to add a deep-copy of the array into the ArrayList, like this:

al.add(Arrays.copyOf(input, input.length));

instead of

al.add(input);

Printing the resulting ArrayList will then produce the following output:

[1, 2, 3]
[1, 3, 2]
[2, 1, 3]
[2, 3, 1]
[3, 2, 1]
[3, 1, 2]


问:
How to join two json path query in json path extractor of jmeter?
Let's say I have this popular data sample.

```<code>{
    "store": {
        "book": [
            {
                "category": "reference",
                "author": "Nigel Rees",
                "title": "Sayings of the Century",
                "price": 8.95
            },
            {
                "category": "fiction",
                "author": "Evelyn Waugh",
                "color": "red",
                "title": "Sword of Honour",
                "price": 12.99
            },
            {
                "category": "fiction",
                "author": "Herman Melville",
                "color": "blue",
                "title": "Moby Dick",
                "isbn": "0-553-21311-3",
                "price": 8.99
            },
            {
                "category": "fiction",
                "author": "J. R. R. Tolkien",
                "title": "The Lord of the Rings",
                "isbn": "0-395-19395-8",
                "price": 22.99
            }
        ],
        "bicycle": {
            "color": "red",
            "price": 19.95
        }
    },
    "expensive": 10
}
</code>```

What I want from here is a all the book where category == fiction and all the bicycle where color == red.

That is, I want,

```<code>   {
        "category": "fiction",
        "author": "Evelyn Waugh",
        "color": "red",
        "title": "Sword of Honour",
        "price": 12.99
    },
    {
        "category": "fiction",
        "author": "Herman Melville",
        "color": "blue",
        "title": "Moby Dick",
        "isbn": "0-553-21311-3",
        "price": 8.99
    },
    {
        "category": "fiction",
        "author": "J. R. R. Tolkien",
        "title": "The Lord of the Rings",
        "isbn": "0-395-19395-8",
        "price": 22.99
    },
    "bicycle": {
         "color": "red",
         "price": 19.95
    }
</code>```

I know, I can use $.store.book[?(@.category == "fiction")] to achieve the targeted books and $.store.bicycle[?(@.color == 'red')] to achieve the targeted bicycle.

But how can I achieve both at one go?

答:
I would recommend implementing your scenario using JSR223 PostProcessor and Groovy language. Example code to extract the elements and build a new JSON out of the filtered data will look something like:

```<code>import groovy.json.JsonBuilder
import groovy.json.JsonSlurper

def json = new JsonSlurper().parseText(prev.getResponseDataAsString())

def fictionBooks = json.store.book.findAll {it.category == "fiction"}
def redBikes = json.store.bicycle.findAll{it.color="red"}

JsonBuilder builder = new JsonBuilder(fictionBooks + redBikes)

prev.setResponseData(builder.toPrettyString())
</code>```

The above code will replace the parent sampler response data with the filtered JSON

References:

Groovy: Parsing and Producing JSON

JsonBuilder class reference

Groovy Is the New Black

Body:
Let's say I have this popular data sample.

{
    "store": {
        "book": [
            {
                "category": "reference",
                "author": "Nigel Rees",
                "title": "Sayings of the Century",
                "price": 8.95
            },
            {
                "category": "fiction",
                "author": "Evelyn Waugh",
                "color": "red",
                "title": "Sword of Honour",
                "price": 12.99
            },
            {
                "category": "fiction",
                "author": "Herman Melville",
                "color": "blue",
                "title": "Moby Dick",
                "isbn": "0-553-21311-3",
                "price": 8.99
            },
            {
                "category": "fiction",
                "author": "J. R. R. Tolkien",
                "title": "The Lord of the Rings",
                "isbn": "0-395-19395-8",
                "price": 22.99
            }
        ],
        "bicycle": {
            "color": "red",
            "price": 19.95
        }
    },
    "expensive": 10
}

What I want from here is a all the book where category == fiction and all the bicycle where color == red.

That is, I want,

   {
        "category": "fiction",
        "author": "Evelyn Waugh",
        "color": "red",
        "title": "Sword of Honour",
        "price": 12.99
    },
    {
        "category": "fiction",
        "author": "Herman Melville",
        "color": "blue",
        "title": "Moby Dick",
        "isbn": "0-553-21311-3",
        "price": 8.99
    },
    {
        "category": "fiction",
        "author": "J. R. R. Tolkien",
        "title": "The Lord of the Rings",
        "isbn": "0-395-19395-8",
        "price": 22.99
    },
    "bicycle": {
         "color": "red",
         "price": 19.95
    }

I know, I can use $.store.book[?(@.category == "fiction")] to achieve the targeted books and $.store.bicycle[?(@.color == 'red')] to achieve the targeted bicycle.

But how can I achieve both at one go?

Body:
I would recommend implementing your scenario using JSR223 PostProcessor and Groovy language. Example code to extract the elements and build a new JSON out of the filtered data will look something like:

import groovy.json.JsonBuilder
import groovy.json.JsonSlurper

def json = new JsonSlurper().parseText(prev.getResponseDataAsString())

def fictionBooks = json.store.book.findAll {it.category == "fiction"}
def redBikes = json.store.bicycle.findAll{it.color="red"}

JsonBuilder builder = new JsonBuilder(fictionBooks + redBikes)

prev.setResponseData(builder.toPrettyString())

The above code will replace the parent sampler response data with the filtered JSON

References:

Groovy: Parsing and Producing JSON

JsonBuilder class reference

Groovy Is the New Black


问:
Highlight a Cell in Excel Based on Identical Contents in a Column with Varying Contents
I am trying to figure out if it is possible to use a formula with conditional formatting or a VBA macro to highlight a cell based on a cell with identical contents in another column, with varying data.

To explain more thoroughly, let's say I have column A, with unique content in each row, rows 1-280.  Each row is formatted to be a string of text, such as "12E00" or "97EBC." I also have column T, which is based on imported data, and may contain some of, but not all of, nor in the same row, the data from column A. It also starts at row 9, not row 1. This is repeated on 47 different tabs, with differing row contents on different tabs (some may have 1-280, others may have 1-160).

Is there some conditional formatting formula/macro (with an explanation of the working components of possible, so that I can learn myself and educate my supervision on the inner workings) that would allow me to highlight any of the cells in column A that have the same text string shown somewhere in column T? Additionally, keeping in mind that I'm checking every row in column A against column T and that column T will only contain some of the text strings in column A.

答:
I assume there is a better way to accomplish this.

But if I understood the question correctly, then try using: =ISNUMBER(MATCH(cell,column,0))

I would then make a column next to Column A for each sheet you want to check.

Example table, with a column for each sheet checked, and a column for checking if any sheets matched. Matched cells are highlighted.

47 columns might be too much to, therefore I used Column B to do:

=OR(Table1[@[sheetName]:[otherSheetName]])

Each column have the formula: =ISNUMBER(MATCH([@[Column A]],INDIRECT(C$1&"!T:T"),0)) (C$1 is pointing to the column's header row)

Utilizing INDIRECT() the column will always look in column T in the sheet with the same name as the column header.

The highlighting is done with these conditional formatting rules


问:
Crop Video to Square in iOS [Swift 3]
I am having trouble cropping a video to square with Swift 3, and iOS 10.x. After I perform my crop routine, I save the video to my photo library and it looks the same as the original.

I am using the following post as reference: Cropping AVAsset video with AVFoundation not working iOS 8

```<code>func suqareCropVideo(inputURL: NSURL, completion: @escaping (_ outputURL : NSURL?) -> ())
{
    let videoAsset: AVAsset = AVAsset( url: inputURL as URL )
    let clipVideoTrack = videoAsset.tracks( withMediaType: AVMediaTypeVideo ).first! as AVAssetTrack

    let composition = AVMutableComposition()
    composition.addMutableTrack(withMediaType: AVMediaTypeVideo, preferredTrackID: CMPersistentTrackID())

    let videoComposition = AVMutableVideoComposition()
    videoComposition.renderSize = CGSize( width: clipVideoTrack.naturalSize.height, height: clipVideoTrack.naturalSize.height )
    videoComposition.frameDuration = CMTimeMake(1, 30)

    let transformer = AVMutableVideoCompositionLayerInstruction(assetTrack: clipVideoTrack)

    let instruction = AVMutableVideoCompositionInstruction()
    instruction.timeRange = CMTimeRangeMake(kCMTimeZero, CMTimeMakeWithSeconds(60, 30))

    let transform1: CGAffineTransform = CGAffineTransform(translationX: clipVideoTrack.naturalSize.height, y: (clipVideoTrack.naturalSize.width - clipVideoTrack.naturalSize.height) / 2)
    let transform2 = transform1.rotated(by: .pi/2)
    let finalTransform = transform2

    transformer.setTransform(finalTransform, at: kCMTimeZero)

    instruction.layerInstructions = [transformer]
    videoComposition.instructions = [instruction]

    // Export
    let exportSession = AVAssetExportSession(asset: videoAsset, presetName: AVAssetExportPresetHighestQuality)!
    print ("random id = \(NSUUID().uuidString)")

    let croppedOutputFileUrl = URL( fileURLWithPath: getOutputPath( NSUUID().uuidString) ) // CREATE RANDOM FILE NAME HERE
    exportSession.outputURL = croppedOutputFileUrl
    exportSession.outputFileType = AVFileTypeQuickTimeMovie

    exportSession.exportAsynchronously() { handler -> Void in
        if exportSession.status == .completed {
            print("Export complete")
            DispatchQueue.main.async(execute: {
                completion(croppedOutputFileUrl as NSURL)
            })
            return
        } else if exportSession.status == .failed {
            print("Export failed - \(String(describing: exportSession.error))")
        }

        completion(nil)
        return
    }
}
</code>```

Usage shown below:

```<code>    if videoURL != nil {
        print ("crop video")
        suqareCropVideo(inputURL: self.videoURL, completion: { (outputURL) -> () in
            print ("compressed url = \(String(describing: outputURL))")

            // Save video to photo library
            PHPhotoLibrary.shared().performChanges({
                PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL:outputURL! as URL)
            }) { saved, error in
                if saved {
                    print ("save successful")
                }
                else {
                    print ("save failed")
                }
            }
        })
    }
</code>```

答:
You're not actually setting the video composition on the exporter

So try

```<code>exportSession.videoComposition = videoComposition
</code>```

before starting the export.

Title: Crop Video to Square in iOS [Swift 3]

Body:
I am having trouble cropping a video to square with Swift 3, and iOS 10.x. After I perform my crop routine, I save the video to my photo library and it looks the same as the original.

I am using the following post as reference: Cropping AVAsset video with AVFoundation not working iOS 8

func suqareCropVideo(inputURL: NSURL, completion: @escaping (_ outputURL : NSURL?) -> ())
{
    let videoAsset: AVAsset = AVAsset( url: inputURL as URL )
    let clipVideoTrack = videoAsset.tracks( withMediaType: AVMediaTypeVideo ).first! as AVAssetTrack

    let composition = AVMutableComposition()
    composition.addMutableTrack(withMediaType: AVMediaTypeVideo, preferredTrackID: CMPersistentTrackID())

    let videoComposition = AVMutableVideoComposition()
    videoComposition.renderSize = CGSize( width: clipVideoTrack.naturalSize.height, height: clipVideoTrack.naturalSize.height )
    videoComposition.frameDuration = CMTimeMake(1, 30)

    let transformer = AVMutableVideoCompositionLayerInstruction(assetTrack: clipVideoTrack)

    let instruction = AVMutableVideoCompositionInstruction()
    instruction.timeRange = CMTimeRangeMake(kCMTimeZero, CMTimeMakeWithSeconds(60, 30))

    let transform1: CGAffineTransform = CGAffineTransform(translationX: clipVideoTrack.naturalSize.height, y: (clipVideoTrack.naturalSize.width - clipVideoTrack.naturalSize.height) / 2)
    let transform2 = transform1.rotated(by: .pi/2)
    let finalTransform = transform2

    transformer.setTransform(finalTransform, at: kCMTimeZero)

    instruction.layerInstructions = [transformer]
    videoComposition.instructions = [instruction]

    // Export
    let exportSession = AVAssetExportSession(asset: videoAsset, presetName: AVAssetExportPresetHighestQuality)!
    print ("random id = \(NSUUID().uuidString)")

    let croppedOutputFileUrl = URL( fileURLWithPath: getOutputPath( NSUUID().uuidString) ) // CREATE RANDOM FILE NAME HERE
    exportSession.outputURL = croppedOutputFileUrl
    exportSession.outputFileType = AVFileTypeQuickTimeMovie

    exportSession.exportAsynchronously() { handler -> Void in
        if exportSession.status == .completed {
            print("Export complete")
            DispatchQueue.main.async(execute: {
                completion(croppedOutputFileUrl as NSURL)
            })
            return
        } else if exportSession.status == .failed {
            print("Export failed - \(String(describing: exportSession.error))")
        }

        completion(nil)
        return
    }
}

Usage shown below:

    if videoURL != nil {
        print ("crop video")
        suqareCropVideo(inputURL: self.videoURL, completion: { (outputURL) -> () in
            print ("compressed url = \(String(describing: outputURL))")

            // Save video to photo library
            PHPhotoLibrary.shared().performChanges({
                PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL:outputURL! as URL)
            }) { saved, error in
                if saved {
                    print ("save successful")
                }
                else {
                    print ("save failed")
                }
            }
        })
    }

Body:
You're not actually setting the video composition on the exporter

So try

exportSession.videoComposition = videoComposition

before starting the export.


问:
Any reason for using compose() instead of lambda expressions?
I was comparing the use of compose() default method with its equivalent  lambda expression and couldn't find any reason why prefering the former.

Maybe the reason is related to code expressiveness or functional style programming, as pointed here

However, comparing the two approaches to solve the question How to do function composition? I see only disadvantages in using compose() instead of lambda expressions.

1st approach with compose() according to the accepted answer:

```<code>Function<Person, Address> personToAddress = Person::getAddress;
Function<Address, String> addressToCountry = Address::getCountry;
Function<Person, String> toCountry = addressToCountry.compose(personToAddress);
</code>```

2nd approach with a lambda expression:

```<code>Function<Person, String> toCountry = p -> p.getAddress().getCountry();
</code>```

Why do I prefer the second one? First, it is less verbose . Second, it does not require the explicit auxiliary variables personToAddress and addressToCountry.

So, is there any reason for using compose() instead of using a lambda explicitly?

答: One reason is if you do not create one or even both of the functions in the same piece of code, but get them passed in from somewhere else. Then you can either write a lambda that calls apply() on the given function(s), or use compose(), which would probably be cleaner.

Body:
I was comparing the use of compose() default method with its equivalent  lambda expression and couldn't find any reason why prefering the former.

Maybe the reason is related to code expressiveness or functional style programming, as pointed here

However, comparing the two approaches to solve the question How to do function composition? I see only disadvantages in using compose() instead of lambda expressions.

1st approach with compose() according to the accepted answer:

Function<Person, Address> personToAddress = Person::getAddress;
Function<Address, String> addressToCountry = Address::getCountry;
Function<Person, String> toCountry = addressToCountry.compose(personToAddress);

2nd approach with a lambda expression:

Function<Person, String> toCountry = p -> p.getAddress().getCountry();

Why do I prefer the second one? First, it is less verbose . Second, it does not require the explicit auxiliary variables personToAddress and addressToCountry.

So, is there any reason for using compose() instead of using a lambda explicitly?


问:
Migrating through several versions in core data
I have Core Data application and I have been migrating (upgrading) the core data model. Each time I create a new version I create a mapping model for each version.
Right now I have 16 versions and I have mapping models that go like this:
1to2.xcmappingmodel
2to3.xcmappingmodel
3to4.xcmappingmodel
...etc. up to 16

This works fine, but a problem arises when one user has a data file with version 10 and updates the application that has version 16. Some how I thought Core Data will automatically upgrade from 10 to 16, but an error shows up that says "Missing Mapping Model". To make sure the mapping models where correct, I upgrade it to each version one by one (10 to 11, 11 to 12,  etc..) and it did work...
Here is my code.

I specify the model version with this code:

```<code>NSBundle *modelWrapper = [NSBundle bundleWithPath:[[NSBundle mainBundle] pathForResource:@"TaskApp_DataModel" ofType:@"momd"]];
NSString *modelPath = [modelWrapper pathForResource:@"TaskApp_DataModel 16" ofType:@"mom"];
NSLog(@"%@",modelPath);
managedObjectModel = [[NSManagedObjectModel alloc]initWithContentsOfURL:[NSURL fileURLWithPath:modelPath]];
</code>```

And I define the Migrate Automatic option here:

```<code>  NSURL *url = [NSURL fileURLWithPath: [applicationSupportDirectory stringByAppendingPathComponent: @"storedata-sql"]];

NSMutableDictionary *dict = [NSMutableDictionary dictionary];
[dict setObject:[NSNumber numberWithBool:YES] forKey:NSMigratePersistentStoresAutomaticallyOption];

if (![persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType
                                            configuration:nil
                                            URL:url
                                            options:dict
                                            error:&error]){
</code>```

Does anyone know how to upgrade this?
Thank you.

答:
it will only try to go from the users existing version(possibly v1), to the current version. if you have 3 versions then you need maps for v1-v2,v2-v3,v1-v3. have all of the 16 versions shipped?
 if so you may need to start making new migration maps, it may also be worth enabling automatic migration if you haven't tried it before, as it can be very good at filling in the gaps. i think it is:

[dict setObject:[NSNumber numberWithBool:YES] forKey:NSInfersMappingModel];

but you will have to double check that.

sorry to be the bringer of bad news

Body:
I have Core Data application and I have been migrating (upgrading) the core data model. Each time I create a new version I create a mapping model for each version.
Right now I have 16 versions and I have mapping models that go like this:
1to2.xcmappingmodel
2to3.xcmappingmodel
3to4.xcmappingmodel
...etc. up to 16

This works fine, but a problem arises when one user has a data file with version 10 and updates the application that has version 16. Some how I thought Core Data will automatically upgrade from 10 to 16, but an error shows up that says "Missing Mapping Model". To make sure the mapping models where correct, I upgrade it to each version one by one (10 to 11, 11 to 12,  etc..) and it did work...
Here is my code.

I specify the model version with this code:

NSBundle *modelWrapper = [NSBundle bundleWithPath:[[NSBundle mainBundle] pathForResource:@"TaskApp_DataModel" ofType:@"momd"]];
NSString *modelPath = [modelWrapper pathForResource:@"TaskApp_DataModel 16" ofType:@"mom"];
NSLog(@"%@",modelPath);
managedObjectModel = [[NSManagedObjectModel alloc]initWithContentsOfURL:[NSURL fileURLWithPath:modelPath]];

And I define the Migrate Automatic option here:

  NSURL *url = [NSURL fileURLWithPath: [applicationSupportDirectory stringByAppendingPathComponent: @"storedata-sql"]];

NSMutableDictionary *dict = [NSMutableDictionary dictionary];
[dict setObject:[NSNumber numberWithBool:YES] forKey:NSMigratePersistentStoresAutomaticallyOption];

if (![persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType
                                            configuration:nil
                                            URL:url
                                            options:dict
                                            error:&error]){

Does anyone know how to upgrade this?
Thank you.


问:
What do these spring session keys stand for in Redis?
I'm integrating Spring Session, Spring Security with SpringBoot by following this tutorial.

The solution works well for me. It saves sessions to Redis as expected.

I'm curious what do these keys/values(such as expirations, index, sessions:expires) stand for. Anyone knows about it?

答:
The RedisOperationsSessionRepository Storage Details part of Spring Session's reference manual covers the storage related implementation details in depth. You can find the same information in javadoc of RedisOperationsSessionRepository class.

In short, expirations/expires is related to internal handling of session expiry, and index stores indexes which can be used to retrieve sessions using FindByIndexNameSessionRepository.


问:
datatype in the table should be Date/time or short tgext?
I am desiging dataentryform in access . I made tables and the datatye of one field is Date/time but in property field in format I put mm.\yyyy to get month and year . how should I define input mask for it? I want to see --.----
when I enter data in form I can see calender beside this field but I have to choose day as well I dont want to choose day however the day that I chose doesnt save in table but I have to choose day aw well.

more explaination: I have 2 fields that should define as mm.yyyy .one field is (start of project example 01.2010) and the next field is end of project which also has the same format mm.yyyy (03.2015).
and later I want to get a query which shows duration of project ( end of project - start of project) . so I should also do calculation according to my data.
but I dont know what kind of data type should I define in the table for these two fields. at first I tried Date/Time . but I couldnt find suitable format. then I changed it to short text and I entered 00.0000 in input mask.
what is the best solution because I have to calculate duration of project according to these two fields later? (in queries)

答:
There are many ways around this. One is simply to allow the user to type freely in an unbound textbox, then validate/correct before updating.

Another is to have two/three juxtaposed textboxes for year-month(-day), then build the date value with DateSerial(y, m, d).

in VBA, mm/yyyy alone can never form a date value, so must silently add a day somehow.

Input masks should be avoided as they are a prime hate object for users.

If you insist, you can get an idea how to handle this from my article:

Entering ISO formatted date with input mask and full validation in Microsoft Access

It assumes the ISO sequence because year-month determines the possible day values.

Addendum:

Though decimal months is not an exact measure due to the varying day counts of the months, you will get pretty close with this function:

```<code>Public Function DecimalMonths( _
    ByVal Date1 As Date, _
    ByVal Date2 As Date) _
    As Double

    Dim Part1   As Double
    Dim Part2   As Double
    Dim Months  As Double
    Dim Days1   As Integer
    Dim Days2   As Integer

    Days1 = Day(DateSerial(Year(Date1), Month(Date1) + 1, 0))
    Days2 = Day(DateSerial(Year(Date2), Month(Date2) + 1, 0))

    Months = DateDiff("m", Date1, Date2)
    Part1 = (Day(Date1) - 1) / Days1
    Part2 = (Day(Date2) - 1) / Days2

    Months = Months - Part1 + Part2

    DecimalMonths = Months

End Function
</code>```

Please note, that the count from 2017-04-15 to 2017-06-01 is 1.53

while it would be 1.5 from 2017-04-16 to 2017-06-01.

Body:
There are many ways around this. One is simply to allow the user to type freely in an unbound textbox, then validate/correct before updating.

Another is to have two/three juxtaposed textboxes for year-month(-day), then build the date value with DateSerial(y, m, d).

in VBA, mm/yyyy alone can never form a date value, so must silently add a day somehow.

Input masks should be avoided as they are a prime hate object for users.

If you insist, you can get an idea how to handle this from my article:

Entering ISO formatted date with input mask and full validation in Microsoft Access

It assumes the ISO sequence because year-month determines the possible day values.

Addendum:

Though decimal months is not an exact measure due to the varying day counts of the months, you will get pretty close with this function:

Public Function DecimalMonths( _
    ByVal Date1 As Date, _
    ByVal Date2 As Date) _
    As Double

    Dim Part1   As Double
    Dim Part2   As Double
    Dim Months  As Double
    Dim Days1   As Integer
    Dim Days2   As Integer

    Days1 = Day(DateSerial(Year(Date1), Month(Date1) + 1, 0))
    Days2 = Day(DateSerial(Year(Date2), Month(Date2) + 1, 0))

    Months = DateDiff("m", Date1, Date2)
    Part1 = (Day(Date1) - 1) / Days1
    Part2 = (Day(Date2) - 1) / Days2

    Months = Months - Part1 + Part2

    DecimalMonths = Months

End Function

Please note, that the count from 2017-04-15 to 2017-06-01 is 1.53

while it would be 1.5 from 2017-04-16 to 2017-06-01.


问:
Django: order by field of many-to-many relation
Given django models A and B:

```<code>class A(models.Model):
    things = models.ManyToManyField('B')

class B(models.Model):
    score = models.FloatField()
    text = models.CharField(max_length=100)
</code>```

How do I get a list of A entities ordered by the text of the highest-scoring B in things?

答:
If I understand you correctly, this should do it.   list will contain a list of all the objects of model A sorted by the text of each object's highest scoring thing.

```<code>dict = {}
list = []
for a in A.objects.all():
    dict[a] = a.things.all().order_by("-score")[0].text
for k, v in sorted(dict.items(), key=lambda x: x[1]):
    list.append(k)
</code>```

There might be a prettier way to write it, but I can't think of one off the top of my head...

Body:
Given django models A and B:

class A(models.Model):
    things = models.ManyToManyField('B')

class B(models.Model):
    score = models.FloatField()
    text = models.CharField(max_length=100)

How do I get a list of A entities ordered by the text of the highest-scoring B in things?

Body:
If I understand you correctly, this should do it.   list will contain a list of all the objects of model A sorted by the text of each object's highest scoring thing.

dict = {}
list = []
for a in A.objects.all():
    dict[a] = a.things.all().order_by("-score")[0].text
for k, v in sorted(dict.items(), key=lambda x: x[1]):
    list.append(k)

There might be a prettier way to write it, but I can't think of one off the top of my head...


问:
Converting an array of long to ArrayList<Long>
This sadly doesn't work:

```<code>long[] longs = new long[]{1L};
ArrayList<Long> longArray = new ArrayList<Long>(longs);
</code>```

Is there a nicer way except adding them manually?

答:
In JDK 1.8,with Lambda and Stream API,We can do it like this:</p>

```<code>long[] longArr = {3L, 4L, 5L, 6L, 7L};
List<Long> longBoxArr = Arrays.stream(longArr).boxed().collect(Collectors.toList());
</code>```

Body:
This sadly doesn't work:

long[] longs = new long[]{1L};
ArrayList<Long> longArray = new ArrayList<Long>(longs);

Is there a nicer way except adding them manually?

Body:
In JDK 1.8,with Lambda and Stream API,We can do it like this:

long[] longArr = {3L, 4L, 5L, 6L, 7L};
List<Long> longBoxArr = Arrays.stream(longArr).boxed().collect(Collectors.toList());


问:
How to give value to previously defined string inside onClick block in android studio
So i have 2 activities that link to each other through an intent, but i need the second page to know what was clicked in the previous page. Heres what i mean.

```<code>public class featuredvendors extends AppCompatActivity {

public String nextpageref;
</code>```

The string i would like to edit is declared above.

```<code>t2.setOnClickListener(new View.OnClickListener(){
        public void onClick(View v){
            nextpageref="post1";
            Intent t2 = new Intent(featuredvendors.this, featureddetails.class);

            startActivity(t2);
        }
    });
</code>```

So essentially, i want to change the value of nextpageref based on what was clicked on. However it seems that i cant change the value inside an onClick block. Is there anyway i can pass the value "post1" to a string, but ONLY when this particular button is clicked? I need it this way because the next page 'featureddetails' needs to know this String value in order to pull the correct information from the DB.

答:
SendingActivity

```<code>   Intent intent = new Intent(SendingActivity.this, RecievingActivity.class);
    intent. putString("keyName", value);  // pass your values and retrieve them in the other Activity using keyName
    startActivity(intent);
</code>```

Second Screen.java

public class newclass extends Activity
{
    private TextView Textv;

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.intent);
    Textv = (TextView)findViewById(R.id.tv2);
    Intent i= getIntent();
    i.getStringExtra("keyName");
}
</code>```

}

Body:
So i have 2 activities that link to each other through an intent, but i need the second page to know what was clicked in the previous page. Heres what i mean.

public class featuredvendors extends AppCompatActivity {

public String nextpageref;

The string i would like to edit is declared above.

t2.setOnClickListener(new View.OnClickListener(){
        public void onClick(View v){
            nextpageref="post1";
            Intent t2 = new Intent(featuredvendors.this, featureddetails.class);

            startActivity(t2);
        }
    });

So essentially, i want to change the value of nextpageref based on what was clicked on. However it seems that i cant change the value inside an onClick block. Is there anyway i can pass the value "post1" to a string, but ONLY when this particular button is clicked? I need it this way because the next page 'featureddetails' needs to know this String value in order to pull the correct information from the DB.

Body:
SendingActivity

   Intent intent = new Intent(SendingActivity.this, RecievingActivity.class);
    intent. putString("keyName", value);  // pass your values and retrieve them in the other Activity using keyName
    startActivity(intent);

Second Screen.java

public class newclass extends Activity
{
    private TextView Textv;

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.intent);
    Textv = (TextView)findViewById(R.id.tv2);
    Intent i= getIntent();
    i.getStringExtra("keyName");
}

}


问:
Retrieve the commit hash
I'm currently working on a deployment script to run as part of my GitLab CI setup. What I want is to copy a file from one location to another and rename it.

Now I want to be able to find what commit that file was generated with, so I'd like to add the hash of the commit to it.

For that to work I'd like to use something like this:

```<code>cp myLogFile.log /var/log/gitlab-runs/$COMMITHASH.log
</code>```

The output should be a file named eg.

```<code>/var/log/gitlab-runs/9b43adf.log
</code>```

How is this possible to achieve using GitLab CI?

答:
In your example you used the short git hash that you would get with the predefined variable CI_COMMIT_SHA by building a substring like this:

```<code>${CI_COMMIT_SHA:0:8}
</code>```

or by using the short sha directly

```<code>$CI_COMMIT_SHORT_SHA
</code>```

ContentLicense: CC BY-SA 4.0

Title: Retrieve the commit hash

Body:
I'm currently working on a deployment script to run as part of my GitLab CI setup. What I want is to copy a file from one location to another and rename it.

Now I want to be able to find what commit that file was generated with, so I'd like to add the hash of the commit to it.

For that to work I'd like to use something like this:

cp myLogFile.log /var/log/gitlab-runs/$COMMITHASH.log

The output should be a file named eg.

/var/log/gitlab-runs/9b43adf.log

How is this possible to achieve using GitLab CI?

Body:
In your example you used the short git hash that you would get with the predefined variable CI_COMMIT_SHA by building a substring like this:

${CI_COMMIT_SHA:0:8}

or by using the short sha directly

$CI_COMMIT_SHORT_SHA


问:
Excel VBA: How to autocreate hyperlink from cell value?
I have a table called Table1

In Column B, I have the ticket number. e.g: 76537434

Requirement: when any change happens in any cell in column B, that cell (Target cell) to be changed into a hyperlink such that the hyperlink address would be example.com/id=76537434

Cell value i.e. 76537434 must remain the same

答:
Add this event handler to your worksheet's code module:</p>

```<code>Private Sub Worksheet_Change(ByVal Target As Range)
    If Target.Column <> 2 Then Exit Sub
    Target.Hyperlinks.Delete ' or Target.ClearHyperlinks to conserve the formatting
    Me.Hyperlinks.Add Target, "http://example.com/id=" & Target.value
End Sub
</code>```

Body:
Add this event handler to your worksheet's code module:

Private Sub Worksheet_Change(ByVal Target As Range)
    If Target.Column <> 2 Then Exit Sub
    Target.Hyperlinks.Delete ' or Target.ClearHyperlinks to conserve the formatting
    Me.Hyperlinks.Add Target, "http://example.com/id=" & Target.value
End Sub


问:
Fastest Way To std::vector<Derived> to std::vector<Base>
Here is the test code:

```<code>class A{};
class B : public A{};

void Test(const std::vector<A>& a)
{
}

int main()
{
    std::vector<A> a;
    std::vector<B> b;
    Test(a);
    Test(b);//Compiler Error
    return 0;
}
</code>```

Since std::vector and std::vector is different type, we can't make conversion from one to another.

An optional way can be:

```<code>class A{};
class B : public A{};

void Test(const std::vector<A>& a)
{
}

int main()
{
    std::vector<A> a;
    std::vector<B> b;
    Test(a);
    Test(std::vector<A>(b.begin(), b.end()));
    return 0;
}
</code>```

It acts, but it takes extra copying from B to A. If A or B is a large object, it can be very slow. A better choice is:

```<code>class A{};
class B : public A{};

void Test(const std::vector<A>& a)
{
}

int main()
{
    std::vector<A> a;
    std::vector<B> b;
    Test(a);
    Test(std::vector<A>(std::make_move_iterator(b.begin()), std::make_move_iterator(b.end())));
    return 0;
}
</code>```

Since it just move the iter instead of the whole B class, it take a better performance. But there are some extra cost - If b is a very large vector with huge number of items, iteration also can slow down my code.

So I wonder if there is a way to directly convert std::vector to std::vector without any extra cost?

答:
I don't know if it's useful for you but the best I can think is pass std::vector<Derived> to the function and iterate the element as Base elements.

Something like

```<code>template <typename D>
void Test (std::vector<D> const & v)
 {
   for ( A const & elem : v )
    {
      // use elem
    }
 }
</code>```

Using SFINAE you can enable Test() only for vectors of Base or derived from Base elements as follows

```<code>template <typename D>
typename std::enable_if<std::is_base_of<A, D>::value>::type
     Test (std::vector<D> const & v)
 {
   for ( A const & elem : v )
    {
      // use elem
    }
 }
</code>```

So you have

```<code>int main ()
 {
   std::vector<A>   a;
   std::vector<B>   b;
   std::vector<int> c;

   Test(a);    // compile
   Test(b);    // compile
   // Test(c); // compiler error
 }
</code>```

Body:
Here is the test code:

class A{};
class B : public A{};

void Test(const std::vector& a)
{
}

int main()
{
    std::vector a;
    std::vector b;
    Test(a);
    Test(b);//Compiler Error
    return 0;
}

Since std::vector and std::vector is different type, we can't make conversion from one to another.

An optional way can be:

class A{};
class B : public A{};

void Test(const std::vector& a)
{
}

int main()
{
    std::vector a;
    std::vector b;
    Test(a);
    Test(std::vector(b.begin(), b.end()));
    return 0;
}

It acts, but it takes extra copying from B to A. If A or B is a large object, it can be very slow. A better choice is:

class A{};
class B : public A{};

void Test(const std::vector& a)
{
}

int main()
{
    std::vector a;
    std::vector b;
    Test(a);
    Test(std::vector(std::make_move_iterator(b.begin()), std::make_move_iterator(b.end())));
    return 0;
}

Since it just move the iter instead of the whole B class, it take a better performance. But there are some extra cost - If b is a very large vector with huge number of items, iteration also can slow down my code.

So I wonder if there is a way to directly convert std::vector to std::vector without any extra cost?

Body:
I don't know if it's useful for you but the best I can think is pass std::vector<Derived> to the function and iterate the element as Base elements.

Something like

template <typename D>
void Test (std::vector<D> const & v)
 {
   for ( A const & elem : v )
    {
      // use elem
    }
 }

Using SFINAE you can enable Test() only for vectors of Base or derived from Base elements as follows

template <typename D>
typename std::enable_if<std::is_base_of<A, D>::value>::type
     Test (std::vector<D> const & v)
 {
   for ( A const & elem : v )
    {
      // use elem
    }
 }

So you have

int main ()
 {
   std::vector<A>   a;
   std::vector<B>   b;
   std::vector<int> c;

   Test(a);    // compile
   Test(b);    // compile
   // Test(c); // compiler error
 }


问:
C: what is wrong with this char pointer assignment?
A newbie question:

I was practice assignment to a char pointer, but found there was nothing printed out. Here is the code:

```<code>#include <stdio.h>

int main (void)
{
    char * option_string = NULL;
    option_string = (char*)malloc(sizeof(5));
    memset(option_string, 0, sizeof(char) * 5);

    int j;
    for ( j = 0; j < 5; j++)
    {
        *option_string++ = 'a';
    }

    printf("print options_string: %s\n", option_string); //!nothing was printed out!
    free(option_string);
    return 0;
}
</code>```

Thanks in advance!

答: Your malloc(sizeof(5)) seems wrong. What is the size of 5? (Hint: It's not 5.)

Body:
A newbie question:

I was practice assignment to a char pointer, but found there was nothing printed out. Here is the code:

#include <stdio.h>

int main (void)
{
    char * option_string = NULL;
    option_string = (char*)malloc(sizeof(5));
    memset(option_string, 0, sizeof(char) * 5);

    int j;
    for ( j = 0; j < 5; j++)
    {
        *option_string++ = 'a';
    }

    printf("print options_string: %s\n", option_string); //!nothing was printed out!
    free(option_string);
    return 0;
}

Thanks in advance!


问:
Read-only (visually) CheckBox
I need to have 2 groups of controls on the screen: inputs and outputs (so they have 2 states: On or Off). Thus CheckBox seems to be a good choice. Checking any output will set it.

However, when displaying inputs there will be no user interaction with it. User is only allowed to see its value, not to change it.

Question: how to make checkbos visually appears as read-only ?

Could think about possible solutions:

Make CheckBox disabled. Bad: there will be no tooltip (possible to solve it? by fake panel on top?) and visually disabled CheckBox is not nice (and I don't want to make user think it is disabled).

Use different control. Which one? Label doesn't have nice placeholder for the On/Off value. RadioButton look differently, but they usually means there is a single choice out of many, while values of inputs are independent.

Making own component. Drawing the whole CheckBox is a bit overkill (and honestly, I don't know how to do it to have Win7 appearance). Would it be possible to add only ReadOnly appearance to the box part easily?

What do you guys think?

答:
It is not necessary to write the entire control, just write a derivative of Checkbox.

A ReadOnly property is added to the control, this causes the control to handle when it can change its value.

```<code>public class CheckBoxReadOnly : CheckBox
{

    private bool _readOnly = false;
    [DefaultValue(false)]
    public bool ReadOnly
    {
        get { return _readOnly; }
        set
        {
            if (_readOnly != value)
            {
                _readOnly = value;
                OnReadOnlyChanged(new EventArgs());
            }
        }
    }

    int _flag = 0;

    public event EventHandler ReadOnlyChanged;

    protected void OnReadOnlyChanged(EventArgs e)
    {
        ReadOnlyChanged?.Invoke(this, e);
    }

    protected override void OnCheckedChanged(EventArgs e)
    {
        if (ReadOnly)
        {
            _flag++;
            if (_flag == 1)
                Checked = !Checked;
        }
        else
        {
            base.OnCheckedChanged(e);
        }
        _flag = 0;
    }
}
</code>```

Title: Read-only (visually) CheckBox

Body:
It is not necessary to write the entire control, just write a derivative of Checkbox.

A ReadOnly property is added to the control, this causes the control to handle when it can change its value.

public class CheckBoxReadOnly : CheckBox
{

    private bool _readOnly = false;
    [DefaultValue(false)]
    public bool ReadOnly
    {
        get { return _readOnly; }
        set
        {
            if (_readOnly != value)
            {
                _readOnly = value;
                OnReadOnlyChanged(new EventArgs());
            }
        }
    }

    int _flag = 0;

    public event EventHandler ReadOnlyChanged;

    protected void OnReadOnlyChanged(EventArgs e)
    {
        ReadOnlyChanged?.Invoke(this, e);
    }

    protected override void OnCheckedChanged(EventArgs e)
    {
        if (ReadOnly)
        {
            _flag++;
            if (_flag == 1)
                Checked = !Checked;
        }
        else
        {
            base.OnCheckedChanged(e);
        }
        _flag = 0;
    }
}


问:
PHP SUM object values
When I try print_r( $category->child() )I got this: (pastebin: https://pastebin.com/hSnfMpLH)

```Array ( [2] => IPS\forums\Forum Object ( [_url:protected] => [_childrenResults:protected] => Array ( [44ecbc64e2a074fc12588cf2dbcb2596] => Array ( ) ) [_permissions:protected] => Array ( [perm_id] => 2 [perm_view] => * [perm_2] => * [perm_3] => 3,4,6 [perm_4] => 3,4,6 [perm_5] => 3,4,6 [perm_6] => [perm_7] => ) [_originalPermissions:protected] => Array ( [perm_id] => 2 [perm_view] => * [perm_2] => * [perm_3] => 3,4,6 [perm_4] => 3,4,6 [perm_5] => 3,4,6 [perm_6] => [perm_7] => ) [noCopyButton] => [contentPostedIn:protected] => Array ( ) [_followData] => [queued:protected] => [_data:protected] => Array ( [id] => 2 [topics] => 1 [posts] => 1490710 [last_post] => 1490714195 [last_poster_id] => 1 [last_poster_name] => Evaldas [position] => 1 [password] => [password_override] => [last_title] => Welcome! [last_id] => 1 [sort_key] => last_post [show_rules] => 0 [preview_posts] => 0 [allow_poll] => 1 [inc_postcount] => 1 [skin_id] => 0 [parent_id] => 1 [redirect_url] => [redirect_on] => 0 [redirect_hits] => 0 [sub_can_post] => 1 [permission_showtopic] => 0 [queued_topics] => 0 [queued_posts] => 0 [forum_allow_rating] => 0 [min_posts_post] => 0 [min_posts_view] => 0 [can_view_others] => 1 [name_seo] => a-test-forum [seo_last_title] => welcome [seo_last_name] => dewagg [last_x_topic_ids] => [forums_bitoptions] => 0 [disable_sharelinks] => 0 [tag_predefined] => [archived_topics] => 0 [archived_posts] => 0 [ipseo_priority] => -1 [viglink] => 1 [qa_rate_questions] => * [qa_rate_answers] => * [icon] => [category_id] => 1 [app] => forums [perm_type] => forum [perm_type_id] => 2 [owner_only] => 0 [friend_only] => 0 [authorized_users] => ) [_new:protected] => [changed] => Array ( ) [skipCloneDuplication] => ) [8] => IPS\forums\Forum Object ( [_url:protected] => [_childrenResults:protected] => Array ( [44ecbc64e2a074fc12588cf2dbcb2596] => Array ( ) ) [_permissions:protected] => Array ( [perm_id] => 50 [perm_view] => * [perm_2] => * [perm_3] => 4,3,6 [perm_4] => 4,3,6 [perm_5] => 4,3,6 [perm_6] => [perm_7] => ) [_originalPermissions:protected] => Array ( [perm_id] => 50 [perm_view] => * [perm_2] => * [perm_3] => 4,3,6 [perm_4] => 4,3,6 [perm_5] => 4,3,6 [perm_6] => [perm_7] => ) [noCopyButton] => [contentPostedIn:protected] => Array ( ) [_followData] => [queued:protected] => [_data:protected] => Array ( [id] => 8 [topics] => 2 [posts] => 2 [last_post] => 1490712622 [last_poster_id] => 1 [last_poster_name] => Evaldas [position] => 7 [password] => [password_override] => [last_title] => hahahahah [last_id] => 4 [sort_key] => last_post [show_rules] => 0 [preview_posts] => 0 [allow_poll] => 1 [inc_postcount] => 1 [skin_id] => [parent_id] => 1 [redirect_url] => [redirect_on] => 0 [redirect_hits] => 0 [sub_can_post] => 1 [permission_showtopic] => 0 [queued_topics] => 0 [queued_posts] => 0 [forum_allow_rating] => 0 [min_posts_post] => 0 [min_posts_view] => 0 [can_view_others] => 1 [name_seo] => test-forum [seo_last_title] => hahahahah [seo_last_name] => dewagg [last_x_topic_ids] => [forums_bitoptions] => 8 [disable_sharelinks] => 0 [tag_predefined] => [archived_topics] => 0 [archived_posts] => 0 [ipseo_priority] => -1 [viglink] => 1 [qa_rate_questions] => * [qa_rate_answers] => * [icon] => [category_id] => 1 [app] => forums [perm_type] => forum [perm_type_id] => 8 [owner_only] => 0 [friend_only] => 0 [authorized_users] => ) [_new:protected] => [changed] => Array ( ) [skipCloneDuplication] => ) ) 1```

How can I sum all topics? I've tried: array_sum( $category->child()['topics'] ) etc, but It not works. Sorry for my bad english

P.S found on stackoverflow:

Or as suggested by @MarkBaker:

$sum = array_sum((array)$myobj);

But how can I select 'topics' ?

var_dump https://pastebin.com/EqJ5TPuA

New code:

```<code>public function countingTotalTopics()
{
    foreach( $this->children() as $child )
    {
        $return = $child->topics;
    }

    return $return;
}
</code>```

And when I try $category->countingTotalTopics() it gives me topics only from first child, how can I get it from another? I think I should call $child->countingTotalTopics() again in foreach, but how?

答:
You are currently getting only the last child's topics. Use this array_merge-based function instead:

```<code>public function countingTotalTopics() {
    $return = [];
    foreach( $this->children() as $child ) {
        $return = array_merge($return, (array) $child->topics);
    }
    return $return;
}
</code>```

Title: PHP SUM object values

Body:
When I try print_r( $category->child() )I got this: (pastebin: https://pastebin.com/hSnfMpLH)

Array ( [2] => IPS\forums\Forum Object ( [_url:protected] => [_childrenResults:protected] => Array ( [44ecbc64e2a074fc12588cf2dbcb2596] => Array ( ) ) [_permissions:protected] => Array ( [perm_id] => 2 [perm_view] => * [perm_2] => * [perm_3] => 3,4,6 [perm_4] => 3,4,6 [perm_5] => 3,4,6 [perm_6] => [perm_7] => ) [_originalPermissions:protected] => Array ( [perm_id] => 2 [perm_view] => * [perm_2] => * [perm_3] => 3,4,6 [perm_4] => 3,4,6 [perm_5] => 3,4,6 [perm_6] => [perm_7] => ) [noCopyButton] => [contentPostedIn:protected] => Array ( ) [_followData] => [queued:protected] => [_data:protected] => Array ( [id] => 2 [topics] => 1 [posts] => 1490710 [last_post] => 1490714195 [last_poster_id] => 1 [last_poster_name] => Evaldas [position] => 1 [password] => [password_override] => [last_title] => Welcome! [last_id] => 1 [sort_key] => last_post [show_rules] => 0 [preview_posts] => 0 [allow_poll] => 1 [inc_postcount] => 1 [skin_id] => 0 [parent_id] => 1 [redirect_url] => [redirect_on] => 0 [redirect_hits] => 0 [sub_can_post] => 1 [permission_showtopic] => 0 [queued_topics] => 0 [queued_posts] => 0 [forum_allow_rating] => 0 [min_posts_post] => 0 [min_posts_view] => 0 [can_view_others] => 1 [name_seo] => a-test-forum [seo_last_title] => welcome [seo_last_name] => dewagg [last_x_topic_ids] => [forums_bitoptions] => 0 [disable_sharelinks] => 0 [tag_predefined] => [archived_topics] => 0 [archived_posts] => 0 [ipseo_priority] => -1 [viglink] => 1 [qa_rate_questions] => * [qa_rate_answers] => * [icon] => [category_id] => 1 [app] => forums [perm_type] => forum [perm_type_id] => 2 [owner_only] => 0 [friend_only] => 0 [authorized_users] => ) [_new:protected] => [changed] => Array ( ) [skipCloneDuplication] => ) [8] => IPS\forums\Forum Object ( [_url:protected] => [_childrenResults:protected] => Array ( [44ecbc64e2a074fc12588cf2dbcb2596] => Array ( ) ) [_permissions:protected] => Array ( [perm_id] => 50 [perm_view] => * [perm_2] => * [perm_3] => 4,3,6 [perm_4] => 4,3,6 [perm_5] => 4,3,6 [perm_6] => [perm_7] => ) [_originalPermissions:protected] => Array ( [perm_id] => 50 [perm_view] => * [perm_2] => * [perm_3] => 4,3,6 [perm_4] => 4,3,6 [perm_5] => 4,3,6 [perm_6] => [perm_7] => ) [noCopyButton] => [contentPostedIn:protected] => Array ( ) [_followData] => [queued:protected] => [_data:protected] => Array ( [id] => 8 [topics] => 2 [posts] => 2 [last_post] => 1490712622 [last_poster_id] => 1 [last_poster_name] => Evaldas [position] => 7 [password] => [password_override] => [last_title] => hahahahah [last_id] => 4 [sort_key] => last_post [show_rules] => 0 [preview_posts] => 0 [allow_poll] => 1 [inc_postcount] => 1 [skin_id] => [parent_id] => 1 [redirect_url] => [redirect_on] => 0 [redirect_hits] => 0 [sub_can_post] => 1 [permission_showtopic] => 0 [queued_topics] => 0 [queued_posts] => 0 [forum_allow_rating] => 0 [min_posts_post] => 0 [min_posts_view] => 0 [can_view_others] => 1 [name_seo] => test-forum [seo_last_title] => hahahahah [seo_last_name] => dewagg [last_x_topic_ids] => [forums_bitoptions] => 8 [disable_sharelinks] => 0 [tag_predefined] => [archived_topics] => 0 [archived_posts] => 0 [ipseo_priority] => -1 [viglink] => 1 [qa_rate_questions] => * [qa_rate_answers] => * [icon] => [category_id] => 1 [app] => forums [perm_type] => forum [perm_type_id] => 8 [owner_only] => 0 [friend_only] => 0 [authorized_users] => ) [_new:protected] => [changed] => Array ( ) [skipCloneDuplication] => ) ) 1

How can I sum all topics? I've tried: array_sum( $category->child()['topics'] ) etc, but It not works. Sorry for my bad english

P.S found on stackoverflow:

Or as suggested by @MarkBaker:

$sum = array_sum((array)$myobj);

But how can I select 'topics' ?

var_dump https://pastebin.com/EqJ5TPuA

New code:

public function countingTotalTopics()
{
    foreach( $this->children() as $child )
    {
        $return = $child->topics;
    }

    return $return;
}

And when I try $category->countingTotalTopics() it gives me topics only from first child, how can I get it from another? I think I should call $child->countingTotalTopics() again in foreach, but how?

Body:
You are currently getting only the last child's topics. Use this array_merge-based function instead:

public function countingTotalTopics() {
    $return = [];
    foreach( $this->children() as $child ) {
        $return = array_merge($return, (array) $child->topics);
    }
    return $return;
}


问:
Creating custom posts directly from the ACF form
I'm trying to mimic the 'Locations' functionality of Events Manager plugin where the user, when adding new events, can search for existing locations and if not found - create one straight from the form.

Is there an ACF way of approaching this? I was thinking of using the acf_form functionality but I'm not sure how to plug it into a form.

Wordpress 4.7.3, ACF Pro 5.5.11

答:
Found a way to do that by using the 'Clone' field and cloning field groups for the custom post type I wanted to create. Then I hooked to acf/save_post action and using wp_insert_post() and update_field() managed to create a new custom post from a different post's custom post.

This was used in replicating 'Events Manager' functionality. I had a custom post type 'Event' and 'Location'. When adding a new 'Event' I could select from the existing locations or (and that's what I used the new functionality) add a new location.

I hope that helps someone else who's working on similar things :)