问:
Azure Search .Net SDK throws InvalidOperationException with SerializationBinder
I'm playing around with Azure Search .NET SDK on .NET Core (specifically, cloning the sample from Github - https://github.com/Azure-Samples/search-dotnet-getting-started)

When entering any operation with index (create, delete...) it throws an exception with SerializationBinder from Newtonsoft.Json like this

```<code>System.InvalidOperationException: Cannot get SerializationBinder because an ISerializationBinder was previously set.    at Newtonsoft.Json.JsonSerializer.get_Binder()
--- End of inner exception stack trace ---
    at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
    at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
    at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
    at Microsoft.Rest.Azure.JsonSerializerExtensions.WithoutConverter(JsonSerializer serializer, JsonConverter converterToExclude)
    at Microsoft.Rest.Azure.CloudErrorJsonConverter.ReadJson(JsonReader reader, Type objectType, Object existingValue, JsonSerializer serializer)
    at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.DeserializeConvertable(JsonConverter converter, JsonReader reader, Type objectType, Object existingValue)
    at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(JsonReader reader, Type objectType, Boolean checkAdditionalContent)
    at Newtonsoft.Json.JsonSerializer.DeserializeInternal(JsonReader reader, Type objectType)
    at Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject[T](String json, JsonSerializerSettings settings)    at Microsoft.Azure.Search.IndexesOperations.<GetWithHttpMessagesAsync>d__12.MoveNext()
    --- End of stack trace from previous location where exception was thrown ---
        at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()    at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)    at Microsoft.Azure.Search.ExistsHelper.<ExistsFromGetResponse>d__0`1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---    at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()    at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)    at Microsoft.Azure.Search.IndexesOperationsExtensions.<ExistsAsync>d__3.MoveNext()
--- End of stack trace from previous location where exception was thrown --
</code>```

I believe that's something wrong with the SDK itself as I cloned the public github repo. Is that right?

答:
This was caused by a known compatibility issue that many Azure SDKs have with JSON.NET version 10. The details are here and here.

This was fixed in Microsoft.Azure.Search versions 3.0.5 and 4.0.2-preview.

Body:
I'm playing around with Azure Search .NET SDK on .NET Core (specifically, cloning the sample from Github - https://github.com/Azure-Samples/search-dotnet-getting-started)

When entering any operation with index (create, delete...) it throws an exception with SerializationBinder from Newtonsoft.Json like this

System.InvalidOperationException: Cannot get SerializationBinder because an ISerializationBinder was previously set.    at Newtonsoft.Json.JsonSerializer.get_Binder()
--- End of inner exception stack trace ---
    at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
    at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
    at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
    at Microsoft.Rest.Azure.JsonSerializerExtensions.WithoutConverter(JsonSerializer serializer, JsonConverter converterToExclude)
    at Microsoft.Rest.Azure.CloudErrorJsonConverter.ReadJson(JsonReader reader, Type objectType, Object existingValue, JsonSerializer serializer)
    at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.DeserializeConvertable(JsonConverter converter, JsonReader reader, Type objectType, Object existingValue)
    at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(JsonReader reader, Type objectType, Boolean checkAdditionalContent)
    at Newtonsoft.Json.JsonSerializer.DeserializeInternal(JsonReader reader, Type objectType)
    at Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject[T](String json, JsonSerializerSettings settings)    at Microsoft.Azure.Search.IndexesOperations.<GetWithHttpMessagesAsync>d__12.MoveNext()
    --- End of stack trace from previous location where exception was thrown ---
        at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()    at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)    at Microsoft.Azure.Search.ExistsHelper.<ExistsFromGetResponse>d__0`1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---    at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()    at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)    at Microsoft.Azure.Search.IndexesOperationsExtensions.<ExistsAsync>d__3.MoveNext()
--- End of stack trace from previous location where exception was thrown --

I believe that's something wrong with the SDK itself as I cloned the public github repo. Is that right?


来源: stackexchange

问:
Recieving cookie in angular from php response
I've been trying to retrieve cookie from php for awhile.

from php I have this method:

```<code>public function created()
{
  $datetime = date_create()->format('Y-m-d H:i:s');
  $json =file_get_contents('php://input');
  var_dump($json);
  $decoded = json_decode($json, true);
  $cookie="";
  $obj=new \stdClass();

  if($decoded['cookie']==""){
    $cookie=$random = rand(1,1000);
    setcookie( "cookie", "$cookie", time() + (10 * 365 * 24 * 60 * 60), "/", "http://localhost" );
  }
  else{
    $cookie=$decoded['cookie'];
  }

        $user=[
            'name'=>$decoded['name'],
            'surname'=>$decoded['surname'],
            'email'=>$decoded['email'],
            'review'=>$decoded['review'],
            'time'=>$datetime,
            'cookie'=>$cookie,
        ];
  $obj->cookie=$cookie;
  DatabaseModel::newuser($user);
  //return response()->json($cookie);
}
</code>```

which creates cookie if none exists and I see it in my response headers. (Don't pay attention to how I create cookie for now, I now rand() function is not the right way, it's just for testing)

In my angular side I have :

```<code>function PostReview(JSONObject) {
        if (JSONObject != null) {
            debugger;

            $http({

                url: 'http://localhost:8000/creation',
                method: "POST",
                data: JSONObject,
                headers: {
                    "Content-Type": "application/x-www-form-urlencoded;charset=utf-8;",
                    "Accept": "application/json"

                },

            })
                .then(function (data) {

                    console.log(data.headers('Set-cookie'));

                }, function (data) {
                    console.log(data.headers('Set-cookie'));
                });
        }

    }
</code>```

I would like to post my JSON object and recieve cookie with response. However I am quite stuck. I tried with .success() but it's deprecated, so I am using .then() , but then I print console.log(data.headers('Set-cookie')); I get null result. Does anybody ever had similar problem?

I also tried:

```<code>.then(function (data, status, headers, config) {

                    console.log(headers('Set-cookie'));

                }, function (data, status, headers, config) {
                    console.log(headers('Set-cookie'));
                });
</code>```

and:

```<code>.then(function(response) {
                    if (response.data == 'ok') {
                        $cookies['X-AUTH-TOKEN']=response.headers('X-AUTH-TOKEN');
                        // below put,put,putObject Cookies value is valid for Angular version >= 1.4
                       var $cookie= $cookies.putObject('X-AUTH-TOKEN',response.headers('X-AUTH-TOKEN'));
                        console.log($cookie);
                        debugger;

                    }

                });
</code>```

but none of them worked. What problem could it be?

My client side:

```<code>function PostReview(JSONObject) {
        if (JSONObject != null) {
            debugger;

            $http({

                url: 'http://localhost:8000/creation',
                method: "POST",
                data: JSONObject,
                headers: {
                    "Content-Type": "application/x-www-form-urlencoded;charset=utf-8;",
                    "Accept": "application/json"
                }

            })
        }
    }
</code>```

in my controllers:

```<code>$scope.Cookie = $cookies.get('cookie');
    $scope.$watch('Cookie', function() {
        $scope.Cookie = $cookies.get('cookie');
    });
</code>```

WHhat about cross-domain cookies?

答:
set-cookie is an instruction to your client app (e.g. the browser your code is running on) - not for your code.
it should be automatically saving the cookie to your client, then it'll be sent automatcally to the server in wach call.
to get the current cookies you can use $cookies.

if the cookie doesn't saved, there could be veriety of reasons why, e.g. maybe the domain-name do not match,
basically, in order to read the cookie, all the parameters of the set-cookie should match the current page, and also the expiration-date should be in the future (or omited).

ok, find your problem, you should add the port number, like so:

```<code>setcookie( "cookie", "$cookie", time() + (10 * 365 * 24 * 60 * 60), "/", "http://localhost:8000" );
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I've been trying to retrieve cookie from php for awhile.

from php I have this method:

public function created()
{
  $datetime = date_create()->format('Y-m-d H:i:s');
  $json =file_get_contents('php://input');
  var_dump($json);
  $decoded = json_decode($json, true);
  $cookie="";
  $obj=new \stdClass();

  if($decoded['cookie']==""){
    $cookie=$random = rand(1,1000);
    setcookie( "cookie", "$cookie", time() + (10 * 365 * 24 * 60 * 60), "/", "http://localhost" );
  }
  else{
    $cookie=$decoded['cookie'];
  }

        $user=[
            'name'=>$decoded['name'],
            'surname'=>$decoded['surname'],
            'email'=>$decoded['email'],
            'review'=>$decoded['review'],
            'time'=>$datetime,
            'cookie'=>$cookie,
        ];
  $obj->cookie=$cookie;
  DatabaseModel::newuser($user);
  //return response()->json($cookie);
}

which creates cookie if none exists and I see it in my response headers. (Don't pay attention to how I create cookie for now, I now rand() function is not the right way, it's just for testing)

In my angular side I have :

function PostReview(JSONObject) {
        if (JSONObject != null) {
            debugger;

            $http({

                url: 'http://localhost:8000/creation',
                method: "POST",
                data: JSONObject,
                headers: {
                    "Content-Type": "application/x-www-form-urlencoded;charset=utf-8;",
                    "Accept": "application/json"

                },

            })
                .then(function (data) {

                    console.log(data.headers('Set-cookie'));

                }, function (data) {
                    console.log(data.headers('Set-cookie'));
                });
        }

    }

I would like to post my JSON object and recieve cookie with response. However I am quite stuck. I tried with .success() but it's deprecated, so I am using .then() , but then I print console.log(data.headers('Set-cookie')); I get null result. Does anybody ever had similar problem?

I also tried:

.then(function (data, status, headers, config) {

                    console.log(headers('Set-cookie'));

                }, function (data, status, headers, config) {
                    console.log(headers('Set-cookie'));
                });

and:

.then(function(response) {
                    if (response.data == 'ok') {
                        $cookies['X-AUTH-TOKEN']=response.headers('X-AUTH-TOKEN');
                        // below put,put,putObject Cookies value is valid for Angular version >= 1.4
                       var $cookie= $cookies.putObject('X-AUTH-TOKEN',response.headers('X-AUTH-TOKEN'));
                        console.log($cookie);
                        debugger;

                    }

                });

but none of them worked. What problem could it be?

My client side:

function PostReview(JSONObject) {
        if (JSONObject != null) {
            debugger;

            $http({

                url: 'http://localhost:8000/creation',
                method: "POST",
                data: JSONObject,
                headers: {
                    "Content-Type": "application/x-www-form-urlencoded;charset=utf-8;",
                    "Accept": "application/json"
                }

            })
        }
    }

in my controllers:

$scope.Cookie = $cookies.get('cookie');
    $scope.$watch('Cookie', function() {
        $scope.Cookie = $cookies.get('cookie');
    });

WHhat about cross-domain cookies?

Body:
set-cookie is an instruction to your client app (e.g. the browser your code is running on) - not for your code.
it should be automatically saving the cookie to your client, then it'll be sent automatcally to the server in wach call.
to get the current cookies you can use $cookies.

if the cookie doesn't saved, there could be veriety of reasons why, e.g. maybe the domain-name do not match,
basically, in order to read the cookie, all the parameters of the set-cookie should match the current page, and also the expiration-date should be in the future (or omited).

ok, find your problem, you should add the port number, like so:

setcookie( "cookie", "$cookie", time() + (10 * 365 * 24 * 60 * 60), "/", "http://localhost:8000" );


问:
What is the specific reason for the runtime error I'm getting here?
```<code>#include<stdio.h>
#include<string.h>
void main()
{
    char a,b,c;
    printf("Enter alien names:\n");
    scanf("%s\n%s\n%s\n",a,b,c);
    printf("The alien names are %s, %s and %s. A meteor hit %s's spaceship. A star scratched %s\'s spaceship. But %s fixed %s and %s\'s spaceships. The three became friends and are from the planet BYG (which means BLUE YELLOW GREEN)",a,b,c,a,b,c,a,b);
}
</code>```

What is the specific reason for the runtime error I'm getting here?

答:
What is the specific reason for the runtime error I'm getting here?

The function scanf using the format specifier %s expects to be passed the address of a char array, in which to place the input data. For example an array such as

```<code>char a[100];
</code>```

However, you pass simple char variables a and b and c which can hold values in the range -128 to 127, or 0 to 255, depending on whether the implementation's char is signed or unsigned.

These variables were not even initialised, so indeterminate values were passed to scanf. But even if they had been initialised, it is very likely that the values passed will cause a segfault, when used as addresses.

My compiler issued 2 warnings for each of a, b and c passed to scanf.

warning C4477: 'scanf' : format string '%s' requires an argument of type 'char *', but variadic argument 1 has type 'int'

warning C4700: uninitialized local variable 'a' used

Please enable and act on all compiler warnings.

Body:
#include<stdio.h>
#include<string.h>
void main()
{
    char a,b,c;
    printf("Enter alien names:\n");
    scanf("%s\n%s\n%s\n",a,b,c);
    printf("The alien names are %s, %s and %s. A meteor hit %s's spaceship. A star scratched %s\'s spaceship. But %s fixed %s and %s\'s spaceships. The three became friends and are from the planet BYG (which means BLUE YELLOW GREEN)",a,b,c,a,b,c,a,b);
}

What is the specific reason for the runtime error I'm getting here?

Body:
What is the specific reason for the runtime error I'm getting here?

The function scanf using the format specifier %s expects to be passed the address of a char array, in which to place the input data. For example an array such as

char a[100];

However, you pass simple char variables a and b and c which can hold values in the range -128 to 127, or 0 to 255, depending on whether the implementation's char is signed or unsigned.

These variables were not even initialised, so indeterminate values were passed to scanf. But even if they had been initialised, it is very likely that the values passed will cause a segfault, when used as addresses.

My compiler issued 2 warnings for each of a, b and c passed to scanf.

warning C4477: 'scanf' : format string '%s' requires an argument of type 'char *', but variadic argument 1 has type 'int'

warning C4700: uninitialized local variable 'a' used

Please enable and act on all compiler warnings.


问:
PHP exec returns correctly for some commands using sudo, not others
I'm getting successful output when I issue the following in a PHP script:

```<code>$peers_summary = exec('sudo asterisk -x "sip show peers"', $sip_peers);
</code>```

$sip_peers contains the full output of the exec command, listing the peers in standard table format that Asterisk provides. However, when I issue:

```<code>$test = exec('sudo asterisk -x "sip show peer trunk-to-pbx"', $trunk);
</code>```

$trunk is completely empty: array(0) {}, and
$test is an empty string: string(0) ""

trunk-to-pbx is a valid peer in my Asterisk installation, and I've verified that issuing sudo asterisk -x "sip show peer trunk-to-pbx" at the prompt is successful (as is sudo asterisk -x "sip show peers"), so I'm not sure why the second command returns empty from exec(). I thought initially that it might be an output character limit, but the output has less than 2,000 characters - couldn't be a memory or limit issue. I tried set_time_limit(0) even though the execution is virtually instantaneous at the prompt.

Why is the second exec() returning empty?

答: The problem was not with exec(), or asterisk, or the command I was passing to exec(); there's a sudoers file that whitelists commands, and my command needed inclusion before the exec() would work. Inherited codebase. Thanks Chris Stryczynski, for your suggestions.

Body:
I'm getting successful output when I issue the following in a PHP script:

$peers_summary = exec('sudo asterisk -x "sip show peers"', $sip_peers);

$sip_peers contains the full output of the exec command, listing the peers in standard table format that Asterisk provides. However, when I issue:

$test = exec('sudo asterisk -x "sip show peer trunk-to-pbx"', $trunk);

$trunk is completely empty: array(0) {}, and
$test is an empty string: string(0) ""

trunk-to-pbx is a valid peer in my Asterisk installation, and I've verified that issuing sudo asterisk -x "sip show peer trunk-to-pbx" at the prompt is successful (as is sudo asterisk -x "sip show peers"), so I'm not sure why the second command returns empty from exec(). I thought initially that it might be an output character limit, but the output has less than 2,000 characters - couldn't be a memory or limit issue. I tried set_time_limit(0) even though the execution is virtually instantaneous at the prompt.

Why is the second exec() returning empty?


问:
How do I use the "POST" method on an AJAX call in JavaScript?
I'm using the (free) Face++ API that's returns some good data based on uploaded pictures and/or picture URLs. I'm taking a class now that has introduced us to ajax calls using jQuery, but so far, we only use method: "GET"

Can anyone help me understand HOW to use the "POST" method for an ajax call in jQuery?

W3schools.com has demonstrated the call like this:

```<code>$.post(URL,data,callback);
</code>```

However, I'm more accustomed to seeing the call made a little differently...perhaps like this:

$.ajax({

  url: URL_request,
  method: "POST"

}).done(callback);```

Face++ is asking that I pass it some information...
"api_key"
"face_tokens"
"landmark"
...and some other stuff that is specific to that API. My question is:

Where/How do I pass that data to the site?

...should the known information be passed as concatenations to the URL_request?
...is the known information hard coded in the object that's passed to ajax?

答:
First of all, you'll want to check out the docs. There are a variety of examples that show you different ways to post data.

Back to your actual question: you DON'T want to add the extra data to the URL. This is known as the 'query string'. Query strings are useful for adding data to GET requests, but for a POST request, it's better to use the body. You can attach data to the body of a POST request like so:

```<code>$.ajax({
  url: URL_request,
  method: "POST",
  data: { API_KEY: 'ABC123BBQ'}
}).done(callback);
</code>```

Body:
I'm using the (free) Face++ API that's returns some good data based on uploaded pictures and/or picture URLs. I'm taking a class now that has introduced us to ajax calls using jQuery, but so far, we only use method: "GET"

Can anyone help me understand HOW to use the "POST" method for an ajax call in jQuery?

W3schools.com has demonstrated the call like this:

$.post(URL,data,callback);

However, I'm more accustomed to seeing the call made a little differently...perhaps like this:

$.ajax({

  url: URL_request,
  method: "POST"

}).done(callback);

Face++ is asking that I pass it some information...
"api_key"
"face_tokens"
"landmark"
...and some other stuff that is specific to that API. My question is:

Where/How do I pass that data to the site?

...should the known information be passed as concatenations to the URL_request?
...is the known information hard coded in the object that's passed to ajax?

Body:
First of all, you'll want to check out the docs. There are a variety of examples that show you different ways to post data.

Back to your actual question: you DON'T want to add the extra data to the URL. This is known as the 'query string'. Query strings are useful for adding data to GET requests, but for a POST request, it's better to use the body. You can attach data to the body of a POST request like so:

$.ajax({
  url: URL_request,
  method: "POST",
  data: { API_KEY: 'ABC123BBQ'}
}).done(callback);


问:
retrieving rows with max date
I have two tables like this:

```<code>Table1 (Number column is unique)

Number | date

1234      2008-10-06 17:11:00

5678      2005-10-19 16:20:00

9023      2005-12-09 16:20:00

4243      2009-01-06 17:11:00

5234      2009-01-14 17:11:00

Table 2

Number | code

1234     A1

1234     B1

5678     A1

9023     A1

4243     C1

5234     C1
</code>```

I am trying to retrieve data from these two tables so that I get only one row for each code in Table 2 that is the most recent (from table 1).

Based on this example, my result would be:

1234  A1 (because thats the one with latest date)

1234  B1 (because thats the one with latest date)

5234  C1 (because thats the one with latest date)

答:
Here is a version of Dave's answer that works on SQL Server</p>

```<code> SELECT number, code FROM (
  SELECT Table2.number,
         Table2.code,
         row_number() OVER ( PARTITION BY table2.code ORDER BY table1.date DESC ) date_sort_key
    FROM table1, Table2
    WHERE Table2.number = table1.number
  ) a
  WHERE date_sort_key = 1
</code>```

ContentLicense: CC BY-SA 2.5

Title: retrieving rows with max date

Body:
I have two tables like this:

Table1 (Number column is unique)

Number | date

1234      2008-10-06 17:11:00

5678      2005-10-19 16:20:00

9023      2005-12-09 16:20:00

4243      2009-01-06 17:11:00

5234      2009-01-14 17:11:00

Table 2

Number | code

1234     A1

1234     B1

5678     A1

9023     A1

4243     C1

5234     C1

I am trying to retrieve data from these two tables so that I get only one row for each code in Table 2 that is the most recent (from table 1).

Based on this example, my result would be:

1234  A1 (because thats the one with latest date)

1234  B1 (because thats the one with latest date)

5234  C1 (because thats the one with latest date)

Body:
Here is a version of Dave's answer that works on SQL Server

 SELECT number, code FROM (
  SELECT Table2.number,
         Table2.code,
         row_number() OVER ( PARTITION BY table2.code ORDER BY table1.date DESC ) date_sort_key
    FROM table1, Table2
    WHERE Table2.number = table1.number
  ) a
  WHERE date_sort_key = 1

OwnerDisplayName: Rob Boek


问:
D3 using classed() to add and remove class with checkbox
I am having trouble removing a class that I have added using a checkbox. The checkbox is checked to begin with. When it is unchecked by the user it adds a "hideRect" class with classed('hideRect', true);
this works great BUT when I check the box again the class doesn't go away.

Here is my code:

```<code>this.$node.append('input')
    .attr('type', 'checkbox')
    .attr('checked', true)
    .attr('value', 'med')
    .on('click', () => this.updateRectLine());
  }

private updateRectLine() {

  //var rect = this.$node.getElementsByClassName('.MEDICATION');
  var cbMed = this.$node.attr("checked");
  if (cbMed !== true){
      this.$node.selectAll(".MEDICATION").classed('hideRect', true);
  }

  else if (cbMed == true){
      this.$node.selectAll(".MEDICATION").classed('hideRect', false);
  }
</code>```

}

thanks in advance!

答:
You need to update the below function like this

```<code>private updateRectLine() {
  var cbMed = this.$node.select("input[type='checkbox']").prop("checked");
  if (!cbMed)
    this.$node.selectAll(".MEDICATION").classed('hideRect', true);
  else
    this.$node.selectAll(".MEDICATION").classed('hideRect', false);
}
</code>```

.attr() function only returns the value the checkbox was initialized to, to check for a checkbox's check state, you want to use property checked present on check box elements

Body:
I am having trouble removing a class that I have added using a checkbox. The checkbox is checked to begin with. When it is unchecked by the user it adds a "hideRect" class with classed('hideRect', true);
this works great BUT when I check the box again the class doesn't go away.

Here is my code:

this.$node.append('input')
    .attr('type', 'checkbox')
    .attr('checked', true)
    .attr('value', 'med')
    .on('click', () => this.updateRectLine());
  }

private updateRectLine() {

  //var rect = this.$node.getElementsByClassName('.MEDICATION');
  var cbMed = this.$node.attr("checked");
  if (cbMed !== true){
      this.$node.selectAll(".MEDICATION").classed('hideRect', true);
  }

  else if (cbMed == true){
      this.$node.selectAll(".MEDICATION").classed('hideRect', false);
  }

}

thanks in advance!

Body:
You need to update the below function like this

private updateRectLine() {
  var cbMed = this.$node.select("input[type='checkbox']").prop("checked");
  if (!cbMed)
    this.$node.selectAll(".MEDICATION").classed('hideRect', true);
  else
    this.$node.selectAll(".MEDICATION").classed('hideRect', false);
}

.attr() function only returns the value the checkbox was initialized to, to check for a checkbox's check state, you want to use property checked present on check box elements


问:
What kinds of changes do ViewChildren and ContentChildren QueryLists listen for?
Let's say you had the following code:

<img src="https://i.stack.imgur.com/7IFx1.png" alt="@ViewChildren('item') items: QueryList<any>;">

And somewhere else the code:

<img src="https://i.stack.imgur.com/qac0F.png" alt="this.items.changes.subscribe(() => {})">

What are the changes that would cause () => {} to be called? What about @ContentChildren()? I couldn't find any documentation on this.

Additionally, is there a way to get more information about the change that happened? (e.g. the type of change, the element with which the change occurred, etc.)

EDIT: The answer to the "Additionally" portion above can be found in the comments section of the answer that is marked correct.

答:
Both @ViewChildren and @ContentChildren are used to get a list of Angular components.

So if you have a component ItemComponent the binding would be like this.

```<code>@ViewChildren(ItemComponent) items: QueryList<ItemComponent>;
</code>```

QueryList will be a list of objects that are of ItemComponent type.

The events in the query list emit when the number of items in the list has changed. Either a component was added or destroyed. This can often often happen when *ngFor is used or other template modifiers.

Body:
Both @ViewChildren and @ContentChildren are used to get a list of Angular components.

So if you have a component ItemComponent the binding would be like this.

@ViewChildren(ItemComponent) items: QueryList<ItemComponent>;

QueryList will be a list of objects that are of ItemComponent type.

The events in the query list emit when the number of items in the list has changed. Either a component was added or destroyed. This can often often happen when *ngFor is used or other template modifiers.


问:
PhpStorm WebStorm angular-cli project; how to turn off lint
I'm running PhpStorm 2017.2, and I created an angular-cli project in a folder that already some modules and components built with angular-cli.

I get thousands of linting errors that are making it impossible for me to quickly find and address actual Typescript errors. I would like to disable linting until I've dealt with serious errors but I don't know how.

In accordance with the advice given here, I've tried to delete the tslint section from .angular-cli.json, then restart the PhpStorm software. However, I'm still getting the linting errors (eg: "Comment must start with a space"

Why is linting still happening, and how can I disable it until I'm finished addressing actual TS errors?

答: In Your IDE, you need to go to Preferences (I use WebStorm), select the section TypeScript and TSLint and uncheck the Enable box (see attached screenshot.)


问:
Able to float td elements consistently?
It's getting late and I'm rapidly losing the ability to think.

Is it possible to float  elements consistently across a few decent browsers? Seems to work in Firefox, I hear Bad Things about IE but then I'm free of those shackles for this project. Really, I'm concerned about Chrome's lack of want to play.

EDIT: If it helps at all, I am extremely lax about browser compliance this time 'round, I expect deploying this app only to a controlled user group, and its a tool, not a model of perfect code - so I'm willing to blind-eye a dirty hack if there's one going.

答:
While floating td is weird and shouldn't be done, my call would be to make them display:block before trying anything else.

I'd need to see some code in order to be more specific about what to do.

Title: Able to float td elements consistently?


问:
Scala Play No implicit format for Seq[Option[models.ProcessStepTemplatesModel]] available
I have scala Play application where I want to do something like this:

```<code>implicit val ProcessStepsFormat: OFormat[ProcessSteps] = Json.format[ProcessSteps]

case class ProcessSteps(stepsData: Seq[Option[ProcessStepTemplatesModel]])
</code>```

Problem Is that I got this error:

```<code>No implicit format for Seq[Option[models.ProcessStepTemplatesModel]] available.
</code>```

How can I change the format that It will work?

thanks at all

UPDATE

```<code>case class ProcessStepTemplatesModel(
                                      id: Option[Int],
                                      title: String,
                                      createdat: String,
                                      updatedat: String,
                                      deadline: Option[Date],
                                      comment: Option[String],
                                      stepType: Int,
                                      deleted: Boolean,
                                      processtemplate: Option[Int],
                                      derivedProcesses: Seq[ProcessStepTemplatesDerivedProcessesModel],
                                      prerequisites: Seq[ProcessStepPrerequisitesModel],
                                      postconditions: Seq[ProcessStepPostconditionModel],
                                      addProcessToProcessStepArray: Seq[ProcessStepsTemplates_ProcessTemplatesModel])

object ProcessStepTemplatesModel {
  implicit val processStepFormat = Json.format[ProcessStepTemplatesModel]
}
</code>```

答: Did you declare an implicit format for ProcessStepTemplatesModel ?

Body:
I have scala Play application where I want to do something like this:

implicit val ProcessStepsFormat: OFormat[ProcessSteps] = Json.format[ProcessSteps]

case class ProcessSteps(stepsData: Seq[Option[ProcessStepTemplatesModel]])

Problem Is that I got this error:

No implicit format for Seq[Option[models.ProcessStepTemplatesModel]] available.

How can I change the format that It will work?

thanks at all

UPDATE

case class ProcessStepTemplatesModel(
                                      id: Option[Int],
                                      title: String,
                                      createdat: String,
                                      updatedat: String,
                                      deadline: Option[Date],
                                      comment: Option[String],
                                      stepType: Int,
                                      deleted: Boolean,
                                      processtemplate: Option[Int],
                                      derivedProcesses: Seq[ProcessStepTemplatesDerivedProcessesModel],
                                      prerequisites: Seq[ProcessStepPrerequisitesModel],
                                      postconditions: Seq[ProcessStepPostconditionModel],
                                      addProcessToProcessStepArray: Seq[ProcessStepsTemplates_ProcessTemplatesModel])

object ProcessStepTemplatesModel {
  implicit val processStepFormat = Json.format[ProcessStepTemplatesModel]
}


问:
One sample t test in python from scratch - getting incorrect p value
I'm trying to recreate a two-tailed one sample t-test in python from scratch to deepen my understanding, and I seem to have working code for some samples of data, but I found one example does not match the output from scipy.ttest_1samp and I'm trying to figure out why.

The t statistics match but I am getting different p values. Is there something wrong with my t.cdf function that is giving me wrong p values?

My code:

```<code>sample = [10.81261135, 9.68035252, 9.87293556,  10.06308861,
        9.57381722, 10.00922156, 10.90522431, 9.70843104,
        10.16614481, 10.09447189, 10.51260742, 10.17503686,
        10.38718472, 10.52334431, 9.55808306, 10.24290938,
        10.6048062 , 10.27535938, 9.6329808 ,  9.67338239]
mu = 7.128061097
sam_mean = np.mean(sample)
sam_std = np.std(sample, ddof=1)
n = len(sample)
df = n-1
t = (sam_mean-mu) / (sam_std / (n**(1/2.)))
p = (scs.t.cdf(t,df))*2
return (t,p)
</code>```

My results:

```<code>(32.369715406889142, 2.0)
</code>```

Results from scipy.ttest_1samp:

```<code>Ttest_1sampResult(statistic=32.369715406889142, pvalue=4.3828444145707213e-18)
</code>```

答:
Replace

```<code>p = (scs.t.cdf(t,df))*2
</code>```

with

```<code>p = (scs.t.sf(abs(t),df))*2
</code>```

or with

```<code>p = min(scs.t.cdf(t,df), scs.t.sf(t, df))*2
</code>```

t.sf(x, df) is the survival function (i.e. it is 1 - t.cdf(x, df)).

Body:
I'm trying to recreate a two-tailed one sample t-test in python from scratch to deepen my understanding, and I seem to have working code for some samples of data, but I found one example does not match the output from scipy.ttest_1samp and I'm trying to figure out why.

The t statistics match but I am getting different p values. Is there something wrong with my t.cdf function that is giving me wrong p values?

My code:

sample = [10.81261135, 9.68035252, 9.87293556,  10.06308861,
        9.57381722, 10.00922156, 10.90522431, 9.70843104,
        10.16614481, 10.09447189, 10.51260742, 10.17503686,
        10.38718472, 10.52334431, 9.55808306, 10.24290938,
        10.6048062 , 10.27535938, 9.6329808 ,  9.67338239]
mu = 7.128061097
sam_mean = np.mean(sample)
sam_std = np.std(sample, ddof=1)
n = len(sample)
df = n-1
t = (sam_mean-mu) / (sam_std / (n**(1/2.)))
p = (scs.t.cdf(t,df))*2
return (t,p)

My results:

(32.369715406889142, 2.0)

Results from scipy.ttest_1samp:

Ttest_1sampResult(statistic=32.369715406889142, pvalue=4.3828444145707213e-18)

Body:
Replace

p = (scs.t.cdf(t,df))*2

with

p = (scs.t.sf(abs(t),df))*2

or with

p = min(scs.t.cdf(t,df), scs.t.sf(t, df))*2

t.sf(x, df) is the survival function (i.e. it is 1 - t.cdf(x, df)).


问:
Remove duplicate file names from a listing, disregarding directory
I am running Linux and writing a BASH script.

I have a text file that has an absolute file path on each line. I have found that sometimes one of my text files will have an identical file but listed under a different path. I want to remove these lines that contain identical files such that the file is represented only once.

For instance, if I have:

```<code>/path/to/number1/file1.txt
/path/to/number1/file2.txt
/path/to/number1/file3.txt
/path/to/number2/file3.txt
</code>```

I want the resulting file to contain:

```<code>/path/to/number1/file1.txt
/path/to/number1/file2.txt
/path/to/number1/file3.txt
</code>```

The path length is variable (the file name cannot be guaranteed to be at field 4, for instance).

I have tried previous solutions to similar problems that use uniq, but uniq doesn't seem to provide an option to match the last field, nor does it allow one to set the delimiter. What are some solutions to this?

答:
Short awk solution:

```<code>awk -F'/' '!a[$NF]++' file
</code>```

-F'/' - treating / as field separator

!a[$NF]++ - ensures output for only unique filenames (contained in the last column $NF)

The output:

```<code>/path/to/number1/file1.txt
/path/to/number1/file2.txt
/path/to/number1/file3.txt
</code>```

Body:
I am running Linux and writing a BASH script.

I have a text file that has an absolute file path on each line. I have found that sometimes one of my text files will have an identical file but listed under a different path. I want to remove these lines that contain identical files such that the file is represented only once.

For instance, if I have:

/path/to/number1/file1.txt
/path/to/number1/file2.txt
/path/to/number1/file3.txt
/path/to/number2/file3.txt

I want the resulting file to contain:

/path/to/number1/file1.txt
/path/to/number1/file2.txt
/path/to/number1/file3.txt

The path length is variable (the file name cannot be guaranteed to be at field 4, for instance).

I have tried previous solutions to similar problems that use uniq, but uniq doesn't seem to provide an option to match the last field, nor does it allow one to set the delimiter. What are some solutions to this?

Body:
Short awk solution:

awk -F'/' '!a[$NF]++' file

-F'/' - treating / as field separator

!a[$NF]++ - ensures output for only unique filenames (contained in the last column $NF)

The output:

/path/to/number1/file1.txt
/path/to/number1/file2.txt
/path/to/number1/file3.txt


问:
How to get started writing Metasploit modules/exploits?
I want to contribute code to the Metasploit Framework but I haven't got to know their formatting guidelines and code requirements. What are the contribution guidelines to get started to write your own Metasploit modules? </p>

答:
If you follow this link:

How to get started with writing an auxiliary module

You'll find not only a helpful reference for setting up a metasploit module, but also an entire wiki with (at time of writing) 106 pages on metasploit development and use.

Now, I say reference and not tutorial because making metasploit modules 10% boilerplate code that you need to look up and 90% good-old-ruby that has nothing to do with metasploit.

Take, for example, this simple template module:

```<code>require 'msf/core'

class MetasploitModule < Msf::Auxiliary

  include Msf::Auxiliary::Scanner

  def initialize(info = {})
    super(update_info(info,
      'Name'           => 'Module name',
      'Description'    => %q{
        Say something that the user might want to know.
      },
      'Author'         => [ 'Name' ],
      'License'        => MSF_LICENSE
    ))
  end

  def run
    # use `print_status` to print to the metasploit console, instead of `puts`
  end

end
</code>```

Walking through it line by line:

```<code>require 'msf/core'
</code>```

First we require the metasploit files so we can use them.

```<code>class MetasploitModule < Msf::Auxiliary
</code>```

Then we define a new class which inherits from the metasploit auxiliary class.

```<code>  include Msf::Auxiliary::Scanner
</code>```

Here we include the metasploit scanner so we can use it in our code. You can include any of metasploit's modules here to use them within your own module; however, you likely won't find tutorials for the modules. You're expected to read the documentation to learn how to use them.

```<code>  def initialize(info = {})
    super(update_info(info,
      'Name'           => 'Module name',
      'Description'    => %q{
        Say something that the user might want to know.
      },
      'Author'         => [ 'Name' ],
      'License'        => MSF_LICENSE
    ))
  end
</code>```

This initialize method is basically boilerplate code that tells metasploit information about your module so it can display said information to users inside the metasploit console.

```<code>  def run
    # use `print_status` to print to the metasploit console, instead of `puts`
  end
</code>```

This is where your code goes! This is also where metasploit ends and good-old-ruby begins. If you're making an HTTP server to echo a malicious payload, use an http server gem and write your logic. You can use metasploit modules here, but you use them (and learn how to use them) the same way you would any other ruby gem or library: look up the documentation and the API reference.

```<code>end
</code>```

And that's it! Ultimately, you're discovering what makes IT security such a difficult field. There aren't any tutorials that can teach you how to hack or frameworks that can help you create exploits. Metasploit is more of a tool for curating collections of exploits, and writing your own module is just "plugging" your exploit into metasploit so other people can easily use it. The exploit itself is simply some ruby code, made to do something clever using basic network libraries.

Creating a completely new and useful hacking tool would be a big deal that some paid security professionals only dream of achieving. I suggest you pick a hacking tool which already exists (password cracker, network scanner, web crawler, etc), research that tool's purpose and functions, get well-acquainted with using it, and work on creating your own version of one. Then, once you've got it doing what you want, take your code and wrap it in a metasploit template so it can be accessed from metasploit.

If you get stuck along the way, you can come back to StackOverflow with more specific questions (eg "How can I scan for open ports on an IP?" or "How do I access options inside a metasploit module?") and we'll be happy to help you with those!

Cheers and good luck!

ContentLicense: CC BY-SA 4.0

Body:
If you follow this link:

How to get started with writing an auxiliary module

You'll find not only a helpful reference for setting up a metasploit module, but also an entire wiki with (at time of writing) 106 pages on metasploit development and use.

Now, I say reference and not tutorial because making metasploit modules 10% boilerplate code that you need to look up and 90% good-old-ruby that has nothing to do with metasploit.

Take, for example, this simple template module:

require 'msf/core'

class MetasploitModule < Msf::Auxiliary

  include Msf::Auxiliary::Scanner

  def initialize(info = {})
    super(update_info(info,
      'Name'           => 'Module name',
      'Description'    => %q{
        Say something that the user might want to know.
      },
      'Author'         => [ 'Name' ],
      'License'        => MSF_LICENSE
    ))
  end

  def run
    # use `print_status` to print to the metasploit console, instead of `puts`
  end

end

Walking through it line by line:

require 'msf/core'

First we require the metasploit files so we can use them.

class MetasploitModule < Msf::Auxiliary

Then we define a new class which inherits from the metasploit auxiliary class.

  include Msf::Auxiliary::Scanner

Here we include the metasploit scanner so we can use it in our code. You can include any of metasploit's modules here to use them within your own module; however, you likely won't find tutorials for the modules. You're expected to read the documentation to learn how to use them.

  def initialize(info = {})
    super(update_info(info,
      'Name'           => 'Module name',
      'Description'    => %q{
        Say something that the user might want to know.
      },
      'Author'         => [ 'Name' ],
      'License'        => MSF_LICENSE
    ))
  end

This initialize method is basically boilerplate code that tells metasploit information about your module so it can display said information to users inside the metasploit console.

  def run
    # use `print_status` to print to the metasploit console, instead of `puts`
  end

This is where your code goes! This is also where metasploit ends and good-old-ruby begins. If you're making an HTTP server to echo a malicious payload, use an http server gem and write your logic. You can use metasploit modules here, but you use them (and learn how to use them) the same way you would any other ruby gem or library: look up the documentation and the API reference.

end

And that's it! Ultimately, you're discovering what makes IT security such a difficult field. There aren't any tutorials that can teach you how to hack or frameworks that can help you create exploits. Metasploit is more of a tool for curating collections of exploits, and writing your own module is just "plugging" your exploit into metasploit so other people can easily use it. The exploit itself is simply some ruby code, made to do something clever using basic network libraries.

Creating a completely new and useful hacking tool would be a big deal that some paid security professionals only dream of achieving. I suggest you pick a hacking tool which already exists (password cracker, network scanner, web crawler, etc), research that tool's purpose and functions, get well-acquainted with using it, and work on creating your own version of one. Then, once you've got it doing what you want, take your code and wrap it in a metasploit template so it can be accessed from metasploit.

If you get stuck along the way, you can come back to StackOverflow with more specific questions (eg "How can I scan for open ports on an IP?" or "How do I access options inside a metasploit module?") and we'll be happy to help you with those!

Cheers and good luck!


问:
parsing comma seperated values in MS-SQL (no csv or such)
I use a closed source commercial application that uses an MS-SQL database. I regularly have to query this database myself for various purposes. This means the table and database design is fixed, and I can't do anything about it at all. I just have to live with it. Now I have two tables with the following layouts (abstracted, not to discredit the software/database designer)

```<code>t1: ID (int), att1(varchar), att2(varchar), .... attx(varchar)

t2: ID (int), t1_ids(varchar)
</code>```

Now the contents of this t1_ids is (shudder) a comma separated list of t1 id's. (for example 12, 456, 43, 675, 54). What I want to do is (you guessed it) join those two tables.

Fortunately for me, these are very small tables, and I don't care about performance in terms of complexity at all (could be O(n^m) as far as I care).

Ideally I would like to make a view that joins these two tables. I don't have any requirements for inserting or updating, just for select statements. What would be the easiest and clearest (in terms of maintainability) way to do this?

答:
To get the first and last too use this:

```<code>select *
from t1
    join t2 on '%,' + t1.ID + ',%' like ',' + T2.t1_ids + ','
</code>```

It doesn't matter if T2.t1_ids start or end with . The valid values are enclosed by commas.

Body:
I use a closed source commercial application that uses an MS-SQL database. I regularly have to query this database myself for various purposes. This means the table and database design is fixed, and I can't do anything about it at all. I just have to live with it. Now I have two tables with the following layouts (abstracted, not to discredit the software/database designer)

t1: ID (int), att1(varchar), att2(varchar), .... attx(varchar)

t2: ID (int), t1_ids(varchar)

Now the contents of this t1_ids is (shudder) a comma separated list of t1 id's. (for example 12, 456, 43, 675, 54). What I want to do is (you guessed it) join those two tables.

Fortunately for me, these are very small tables, and I don't care about performance in terms of complexity at all (could be O(n^m) as far as I care).

Ideally I would like to make a view that joins these two tables. I don't have any requirements for inserting or updating, just for select statements. What would be the easiest and clearest (in terms of maintainability) way to do this?

Body:
To get the first and last too use this:

select *
from t1
    join t2 on '%,' + t1.ID + ',%' like ',' + T2.t1_ids + ','

It doesn't matter if T2.t1_ids start or end with . The valid values are enclosed by commas.


问:
Compare mapped objects and validate mapping dynamically
Let's consider a dynamic mapping of an anonymous type to a predefined one:

```<code>Mapper.Initialize(cfg => cfg.CreateMissingTypeMaps = true);

var dest = Mapper.Map<Dest>(new {a = 42});
</code>```

I would like to ensure all Dest properties were mapped. Actual values don't matter, it can be null on anything else.

This check would be similar to Mapper.Configuration.AssertConfigurationIsValid() (it doesn't consider new type maps) performed before/after each map call.

Simple property-to-property Reflection comparison won't work because Automapper configuration should be taken into account (I mean all these nice features like automatic type conversion, flattening etc.). So the check should use Automapper API... or not?

P.S. I understand that it could significantly decrease the perfomance. The idea is to achieve a kind of code contract and enable it in dev configurations only. Any suggestions?

答:
I think unit tests, which will test your mapping logic, will do the same job as you expecting from your "framework".

Only, instead of using Automapper straight in your code, create wrapper which you will use everywhere you need and which you will test

```<code>public static class MapperWrapper
{
    public static Dest Map(object source)
    {
        return Mapper.Map<Dest>(source);
    }
}
</code>```

Unit tests will provide "code contract" for MapperWrapper.Map method and Automapper configuration. Tests will also play a role of "safe net" for developers when they "play" with Automapper configuration.

```<code>// In example used
// NUnit as test framework
// FluentAssertions as assertion framework

[TestFixture]
public class MapperWrapperTests
{
    [Test]
    public void Map_ShouldReturnInstanceWithCorrectValueOfAProperty()
    {
        var expectedA = 42;
        var input = new { A = expectedA };

        var actualResult = MapperWrapper.Map(input);

        actualResult.A.Should().Be(expectedA);
    }

    // FluentAssertions framework provide "deep object graph" assertion
    [Test]
    public void Map_ShouldReturnInstanceWithCorrectValues()
    {
        var expectedResult = new Dest
        {
            Id = 42,
            Name = "Forty-Two",
            SomeAnotherType = new AnotherType { IsValid = true }
        };
        var input = new
        {
            Id = "42",
            Name = "Forty-Two",
            SomeAnotherType = new { IsValid = true }
        };

        var actualResult = MapperWrapper.Map(input);

        actualResult.ShouldBeEquivalentTo(expectedResult);
    }
}
</code>```

By executing those tests on every build you will get feedback about is Automapper configuration correct.

Instead of using singleton MapperWrapper you can introduce abstraction of it (interface or abstract class), implements that abstraction with Automapper methods.

With abstraction your application will not depend tightly on Automapper.

Body:
Let's consider a dynamic mapping of an anonymous type to a predefined one:

Mapper.Initialize(cfg => cfg.CreateMissingTypeMaps = true);

var dest = Mapper.Map<Dest>(new {a = 42});

I would like to ensure all Dest properties were mapped. Actual values don't matter, it can be null on anything else.

This check would be similar to Mapper.Configuration.AssertConfigurationIsValid() (it doesn't consider new type maps) performed before/after each map call.

Simple property-to-property Reflection comparison won't work because Automapper configuration should be taken into account (I mean all these nice features like automatic type conversion, flattening etc.). So the check should use Automapper API... or not?

P.S. I understand that it could significantly decrease the perfomance. The idea is to achieve a kind of code contract and enable it in dev configurations only. Any suggestions?

Body:
I think unit tests, which will test your mapping logic, will do the same job as you expecting from your "framework".

Only, instead of using Automapper straight in your code, create wrapper which you will use everywhere you need and which you will test

public static class MapperWrapper
{
    public static Dest Map(object source)
    {
        return Mapper.Map<Dest>(source);
    }
}

Unit tests will provide "code contract" for MapperWrapper.Map method and Automapper configuration. Tests will also play a role of "safe net" for developers when they "play" with Automapper configuration.

// In example used
// NUnit as test framework
// FluentAssertions as assertion framework

[TestFixture]
public class MapperWrapperTests
{
    [Test]
    public void Map_ShouldReturnInstanceWithCorrectValueOfAProperty()
    {
        var expectedA = 42;
        var input = new { A = expectedA };

        var actualResult = MapperWrapper.Map(input);

        actualResult.A.Should().Be(expectedA);
    }

    // FluentAssertions framework provide "deep object graph" assertion
    [Test]
    public void Map_ShouldReturnInstanceWithCorrectValues()
    {
        var expectedResult = new Dest
        {
            Id = 42,
            Name = "Forty-Two",
            SomeAnotherType = new AnotherType { IsValid = true }
        };
        var input = new
        {
            Id = "42",
            Name = "Forty-Two",
            SomeAnotherType = new { IsValid = true }
        };

        var actualResult = MapperWrapper.Map(input);

        actualResult.ShouldBeEquivalentTo(expectedResult);
    }
}

By executing those tests on every build you will get feedback about is Automapper configuration correct.

Instead of using singleton MapperWrapper you can introduce abstraction of it (interface or abstract class), implements that abstraction with Automapper methods.

With abstraction your application will not depend tightly on Automapper.


问:
Different results for date() and gmdate()
I found something I can't really explain, maybe someone here can give me a hint.

I have the following test code, that prints 2 formatted timestamps, one for the 31.03.2013 and one for 31.03.2014, using date()and gmdate():

```<code><?php

function print_date($timestamp, $year) {
  // Add timezone offset for germany
  $timestamp += 3600;
  print "in $year\n";
  print "date:   " . date('d.m.Y H:i:s', $timestamp) . "\n";
  print "gmdate: " . gmdate('d.m.Y H:i:s', $timestamp) . "\n";
  print "\n";
}

$end_2013 = 1364684400; // 31.03.2013
$end_2014 = 1396216800; // 31.03.2014
print_date($end_2013, '2013');
print_date($end_2014, '2014');

print "Default timezone: " . date_default_timezone_get() . "\n";
</code>```

The result surprises me:

```<code>in 2013
date:   31.03.2013 01:00:00
gmdate: 31.03.2013 00:00:00

in 2014
date:   31.03.2014 01:00:00
gmdate: 30.03.2014 23:00:00

Default timezone: Europe/Berlin
</code>```

Where does the difference in 2014 come from? My first thought is daylight savings time, but why doesn't that have an effect in 2013?
Why are there 2 hours difference in 2014 but only 1 hour difference in 2013?

答:
gmdate() always Format in GMT/UTC date and time But date() always format according to the default time zone

Try this

```<code> <?php
   date_default_timezone_set("Asia/Bangkok");
   echo gmdate('Y-m-d H:i:s');
   echo date('Y-m-d H:i:s');
  ?>
</code>```

Body:
I found something I can't really explain, maybe someone here can give me a hint.

I have the following test code, that prints 2 formatted timestamps, one for the 31.03.2013 and one for 31.03.2014, using date()and gmdate():

<?php

function print_date($timestamp, $year) {
  // Add timezone offset for germany
  $timestamp += 3600;
  print "in $year\n";
  print "date:   " . date('d.m.Y H:i:s', $timestamp) . "\n";
  print "gmdate: " . gmdate('d.m.Y H:i:s', $timestamp) . "\n";
  print "\n";
}

$end_2013 = 1364684400; // 31.03.2013
$end_2014 = 1396216800; // 31.03.2014
print_date($end_2013, '2013');
print_date($end_2014, '2014');

print "Default timezone: " . date_default_timezone_get() . "\n";

The result surprises me:

in 2013
date:   31.03.2013 01:00:00
gmdate: 31.03.2013 00:00:00

in 2014
date:   31.03.2014 01:00:00
gmdate: 30.03.2014 23:00:00

Default timezone: Europe/Berlin

Where does the difference in 2014 come from? My first thought is daylight savings time, but why doesn't that have an effect in 2013?
Why are there 2 hours difference in 2014 but only 1 hour difference in 2013?

Body:
gmdate() always Format in GMT/UTC date and time But date() always format according to the default time zone

Try this

 <?php
   date_default_timezone_set("Asia/Bangkok");
   echo gmdate('Y-m-d H:i:s');
   echo date('Y-m-d H:i:s');
  ?>


问:
How to add two json data together in javascript
I have Json Curl Data representing Post and Comments and I  have  successfully retrieved and displayed them one after the other. below is the code for Retrieving Post and comments

```<code>function loadPost(){
    $.post(
        'post.json',
        function(response){
            $.each(JSON.parse(response).items, function(i,v){
                $('.info').append('<li><div class="msg-lhs"><span>'+v.post_id+'</span> <span>'+v.courses+'</span> </div></li>');
            });
        }
   );

   function loadComment(){
       $.post(
           'comment.json',
           function(response){
               $.each(JSON.parse(response).items, function(i,v){
                   $('.info').append('<li><div class="msg-lhs"><span>'+v.post_id+'</span> <span>'+v.comment+'</span> </div></li>');
               });
           }
       );
</code>```

below is the Json Format output for post and comment

```<code>{"items":[{"post_id":"101","courses":"physics"},
{"post_id":"102","courses":"Biology"},
{"post_id":"103","courses":"Chemistry"},
{"post_id":"104","courses":"Geophysics"},
{"post_id":"105","courses":"GeoChemistry"}]}

{"items":[{"post_id":"101","comment":"This  physcis is cool"},
{"post_id":"101","comment":"love this course on physics"},
{"post_id":"102","comment":"Biology is the scientific study of living things"},
{"post_id":"103","comment":"chemistry is good"},
{"post_id":"103","comment":"chemistry is the study of matter and compounds etc"}]}
</code>```

Now my problem is how can I append comments directly under posts with same post_id
when displaying json contents in javascript. can someone help me fix that.

Thanks

答:
Call the loadComment method after loadPost() response binding completed

in loadPost() response binding give postid to div

find the div in loadComment and bind the comments to div.

```<code>function loadPost(){
    $.post(
        'post.json',
        function(response){
            $.each(JSON.parse(response).items, function(i,v){
                $('.info').append('<li><div class="msg-lhs" id="'+v.post_id+'"><span>'+v.post_id+'</span> <span>'+v.courses+'</span> </div></li>');
            });
            loadComment();
        }
   );

   function loadComment(){
       $.post(
           'comment.json',
           function(response){
               $.each(JSON.parse(response).items, function(i,v){
                   $('.info').find("#"+v.post_id).append('<span>'+v.comment+'</span>');
               });
           }
       );
</code>```

Body:
I have Json Curl Data representing Post and Comments and I  have  successfully retrieved and displayed them one after the other. below is the code for Retrieving Post and comments

function loadPost(){
    $.post(
        'post.json',
        function(response){
            $.each(JSON.parse(response).items, function(i,v){
                $('.info').append('

'+v.post_id+' '+v.courses+'

');
            });
        }
   );

   function loadComment(){
       $.post(
           'comment.json',
           function(response){
               $.each(JSON.parse(response).items, function(i,v){
                   $('.info').append('

'+v.post_id+' '+v.comment+'

');
               });
           }
       );

below is the Json Format output for post and comment

{"items":[{"post_id":"101","courses":"physics"},
{"post_id":"102","courses":"Biology"},
{"post_id":"103","courses":"Chemistry"},
{"post_id":"104","courses":"Geophysics"},
{"post_id":"105","courses":"GeoChemistry"}]}

{"items":[{"post_id":"101","comment":"This  physcis is cool"},
{"post_id":"101","comment":"love this course on physics"},
{"post_id":"102","comment":"Biology is the scientific study of living things"},
{"post_id":"103","comment":"chemistry is good"},
{"post_id":"103","comment":"chemistry is the study of matter and compounds etc"}]}

Now my problem is how can I append comments directly under posts with same post_id
when displaying json contents in javascript. can someone help me fix that.

Thanks

Body:
Call the loadComment method after loadPost() response binding completed

in loadPost() response binding give postid to div

find the div in loadComment and bind the comments to div.

function loadPost(){
    $.post(
        'post.json',
        function(response){
            $.each(JSON.parse(response).items, function(i,v){
                $('.info').append('<li><div class="msg-lhs" id="'+v.post_id+'"><span>'+v.post_id+'</span> <span>'+v.courses+'</span> </div></li>');
            });
            loadComment();
        }
   );

   function loadComment(){
       $.post(
           'comment.json',
           function(response){
               $.each(JSON.parse(response).items, function(i,v){
                   $('.info').find("#"+v.post_id).append('<span>'+v.comment+'</span>');
               });
           }
       );


问:
Disable right click in GTK window
I would disable right click (and so context menu) in a Python GTK window (pyGTK) where inside is located a "window" pyWebKitGtk.

Someone can help me writing some lines of code?

I think that would better delete event directly in pyGTK but if you know how don't show context menu in pyWebKitGtk is good anyway.

TNK TNK TNK

Realy cutted code:

```<code>
import gtk
import webkit

window = gtk.Window(gtk.WINDOW_TOPLEVEL)
window.connect("destroy", gtk.main_quit)

browser = webkit.WebView()
browser.open("http://www.stackoverflow.com")
scroller = gtk.ScrolledWindow()
scroller.add(browser)
window.add(scroller)

window.show_all()
gtk.main()
</code>```

答:
You can use the enable-default-context-menu setting:</p>

```<code>webview.props.settings.props.enable_default_context_menu = False
</code>```

Title: Disable right click in GTK window

Body:
I would disable right click (and so context menu) in a Python GTK window (pyGTK) where inside is located a "window" pyWebKitGtk.

Someone can help me writing some lines of code?

I think that would better delete event directly in pyGTK but if you know how don't show context menu in pyWebKitGtk is good anyway.

TNK TNK TNK

Realy cutted code:

import gtk
import webkit

window = gtk.Window(gtk.WINDOW_TOPLEVEL)
window.connect("destroy", gtk.main_quit)

browser = webkit.WebView()
browser.open("http://www.stackoverflow.com")
scroller = gtk.ScrolledWindow()
scroller.add(browser)
window.add(scroller)

window.show_all()
gtk.main()

Body:
You can use the enable-default-context-menu setting:

webview.props.settings.props.enable_default_context_menu = False


问:
How to properly retrieve value from Firebase Realtime Database?
I have the following data structure:

see here

name could have an unlimited number of children.

And the code below:

```<code>DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference dirFire = rootRef.child("messages").child("name");

 dirFire.addListenerForSingleValueEvent(new ValueEventListener() {
 @Override
 public void onDataChange(DataSnapshot dataSnapshot) {
    String name = dataSnapshot.getValue(String.class);
    //do what you want with the name
 }

 @Override
 public void onCancelled(DatabaseError databaseError) {

 }
 });
</code>```

With the code above, I can't retrieve the value of name. How can I retrieve name if the key is unknown to the client?

答:
Obtain your data into hashMap..</p>

```<code>  FirebaseDatabase.getInstance().getReference()
            .child("messages")
            .addListenerForSingleValueEvent(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot rootSnapshot) {
                    if (rootSnapshot.exists()) {
                        final Map<String, Map<String, String>> messageNameMap = new HashMap<>();
                        for (DataSnapshot messageSnapshot : rootSnapshot.getChildren()) {
                            final String messageKey = messageSnapshot.getKey();
                            HashMap<String, String> nameMap = new HashMap<String, String>();
                            if (messageSnapshot.child("name").exists()) {
                                for (DataSnapshot nameSnapshot : messageSnapshot.child("name").getChildren()) {
                                    final String nameKey = nameSnapshot.getKey();
                                    final String nameValue = nameSnapshot.getValue(String.class);
                                    nameMap.put(nameKey, nameValue);
                                }
                            }
                            if (!nameMap.isEmpty()) {
                                messageNameMap.put(messageKey, nameMap);
                            }
                        }

                        if (!messageNameMap.isEmpty()) {
                            // Here messageNameMap contains your data as such

                            // key: -Ko8bLawP4... val: Map Containing:
                            //                          key: -Ko8wk... val: Jonathan Smith
                            //                          key: -Ko8wk... val: Kapler Moe
                        }
                    }
                }

                @Override
                public void onCancelled(DatabaseError databaseError) {

                }
            });
</code>```

Body:
I have the following data structure:

see here

name could have an unlimited number of children.

And the code below:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference dirFire = rootRef.child("messages").child("name");

 dirFire.addListenerForSingleValueEvent(new ValueEventListener() {
 @Override
 public void onDataChange(DataSnapshot dataSnapshot) {
    String name = dataSnapshot.getValue(String.class);
    //do what you want with the name
 }

 @Override
 public void onCancelled(DatabaseError databaseError) {

 }
 });

With the code above, I can't retrieve the value of name. How can I retrieve name if the key is unknown to the client?

Body:
Obtain your data into hashMap..

  FirebaseDatabase.getInstance().getReference()
            .child("messages")
            .addListenerForSingleValueEvent(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot rootSnapshot) {
                    if (rootSnapshot.exists()) {
                        final Map<String, Map<String, String>> messageNameMap = new HashMap<>();
                        for (DataSnapshot messageSnapshot : rootSnapshot.getChildren()) {
                            final String messageKey = messageSnapshot.getKey();
                            HashMap<String, String> nameMap = new HashMap<String, String>();
                            if (messageSnapshot.child("name").exists()) {
                                for (DataSnapshot nameSnapshot : messageSnapshot.child("name").getChildren()) {
                                    final String nameKey = nameSnapshot.getKey();
                                    final String nameValue = nameSnapshot.getValue(String.class);
                                    nameMap.put(nameKey, nameValue);
                                }
                            }
                            if (!nameMap.isEmpty()) {
                                messageNameMap.put(messageKey, nameMap);
                            }
                        }

                        if (!messageNameMap.isEmpty()) {
                            // Here messageNameMap contains your data as such

                            // key: -Ko8bLawP4... val: Map Containing:
                            //                          key: -Ko8wk... val: Jonathan Smith
                            //                          key: -Ko8wk... val: Kapler Moe
                        }
                    }
                }

                @Override
                public void onCancelled(DatabaseError databaseError) {

                }
            });


问:
Log all network requests initiated by PHP?
I'm trying to understand a codebase and it would help to know when it's accessing remote resources. Is there a way to log all outbound requests using PHP (i.e. without using a network sniffer)? I want to log all curl_exec, file_get_contents, ftp_get, etc.

答:
If you want to find all of the actual function calls in the code, you could use the xdebug profiler.

Install and enable the xdebug profiler (not on a production server).

Run through every feature of your application.

Open the profiler output file in an application (QCacheGrind, PHPStorm, etc.).

Search for calls to curl_exec, file_get_contents, etc.

These applications will show you file name and line number called, as well as the full stack trace that got to those calls.


问:
ngOnDestroy Uncaught (in promise): TypeError: Cannot read property 'unsubscribe' of undefined
I'm getting an error when unsubscribing during the ngOnDestroy method in my shopping-edit.component.ts when i click the link to go to my recipes page. here is the image

error on link click

here is a link to my git https://github.com/CHBaker/First-Angular-App

and my code snippet:

```<code>import {
    Component,
    OnInit,
    OnDestroy,
    ViewChild
} from '@angular/core';
import { NgForm } from '@angular/forms';
import { Subscription } from 'rxjs/Subscription';

import { Ingredient } from '../../shared/ingredient.model';
import { ShoppingListService } from '../shopping-list.service';

@Component({
    selector: 'app-shopping-edit',
    templateUrl: './shopping-edit.component.html',
    styleUrls: ['./shopping-edit.component.css']
})
export class ShoppingEditComponent implements OnInit, OnDestroy {
    @ViewChild('f') slForm: NgForm;
    subscription: Subscription;
    editMode = false;
    editedItemIndex: number;
    editedItem: Ingredient;

    constructor(private slService: ShoppingListService) { }

    ngOnInit() {
        this.slService.startedEditing
            .subscribe(
                (index: number) => {
                    this.editedItemIndex = index;
                    this.editMode = true;
                    this.editedItem = this.slService.getIngredient(index);
                    this.slForm.setValue({
                        name: this.editedItem.name,
                        amount: this.editedItem.amount
                    })
                }
            );
    }

    onSubmit(form: NgForm) {
        const value = form.value;
        const newIngredient = new Ingredient(value.name, value.amount);
        if (this.editMode) {
            this.slService.updateIngredient(this.editedItemIndex, newIngredient);
        } else {
            this.slService.addIngredient(newIngredient);
        }
        this.editMode = false;
        form.reset();
    }

    onClear() {
        this.slForm.reset();
        this.editMode = false;
    }

    onDelete() {
        this.slService.deleteIngredient(this.editedItemIndex);
        this.onClear();
    }

    ngOnDestroy() {
        this.subscription.unsubscribe();
    }
}
</code>```

答:
I fixed it, stupid mistake.

define this.subscription = on ngOnInit before subscribing.

Body:
I'm getting an error when unsubscribing during the ngOnDestroy method in my shopping-edit.component.ts when i click the link to go to my recipes page. here is the image

error on link click

here is a link to my git https://github.com/CHBaker/First-Angular-App

and my code snippet:

import {
    Component,
    OnInit,
    OnDestroy,
    ViewChild
} from '@angular/core';
import { NgForm } from '@angular/forms';
import { Subscription } from 'rxjs/Subscription';

import { Ingredient } from '../../shared/ingredient.model';
import { ShoppingListService } from '../shopping-list.service';

@Component({
    selector: 'app-shopping-edit',
    templateUrl: './shopping-edit.component.html',
    styleUrls: ['./shopping-edit.component.css']
})
export class ShoppingEditComponent implements OnInit, OnDestroy {
    @ViewChild('f') slForm: NgForm;
    subscription: Subscription;
    editMode = false;
    editedItemIndex: number;
    editedItem: Ingredient;

    constructor(private slService: ShoppingListService) { }

    ngOnInit() {
        this.slService.startedEditing
            .subscribe(
                (index: number) => {
                    this.editedItemIndex = index;
                    this.editMode = true;
                    this.editedItem = this.slService.getIngredient(index);
                    this.slForm.setValue({
                        name: this.editedItem.name,
                        amount: this.editedItem.amount
                    })
                }
            );
    }

    onSubmit(form: NgForm) {
        const value = form.value;
        const newIngredient = new Ingredient(value.name, value.amount);
        if (this.editMode) {
            this.slService.updateIngredient(this.editedItemIndex, newIngredient);
        } else {
            this.slService.addIngredient(newIngredient);
        }
        this.editMode = false;
        form.reset();
    }

    onClear() {
        this.slForm.reset();
        this.editMode = false;
    }

    onDelete() {
        this.slService.deleteIngredient(this.editedItemIndex);
        this.onClear();
    }

    ngOnDestroy() {
        this.subscription.unsubscribe();
    }
}


问:
.NET Framework 3.5 and TLS 1.2
I currently have a web application that uses the .NET 3.5 framework and I am wondering if it will be compatible with TLS 1.2. No where in our code are we dictating TLS version. This is a legacy application and recompiling is not on the table right now. I am not finding much info on whether you can or cannot, but I was under the impression that compatibility is more dependent on the OS version. It looks like the minimum is 2008 R2. The goal is to get paypal to communicate properly come July 1st. </p>

答:
As was mentioned .net 3.5.1 DOES now support TLS 1.2; but you don't need the registry changes mentioned by @Paulina's answer.

I'm using VS 2008 with .net 3.5.30729.4926. All I had to do was:

Add imports:

```<code>Imports System.Security.Authentication
Imports System.Net
</code>```

Add this to my code (C#):

```<code>public const SslProtocols _Tls12 = (SslProtocols)0x00000C00;
public const SecurityProtocolType Tls12 = (SecurityProtocolType)_Tls12;
ServicePointManager.SecurityProtocol = Tls12
</code>```

VB.net version:

```<code>Const _Tls12 As SslProtocols = DirectCast(&HC00, SslProtocols)
Const Tls12 As SecurityProtocolType = DirectCast(_Tls12, SecurityProtocolType)
ServicePointManager.SecurityProtocol = Tls12
</code>```

Culled from: https://support.microsoft.com/en-us/help/3154518/support-for-tls-system-default-versions-included-in-the-.net-framework Note: by defining the const in my code I could ignore everything else in the article including the registry edits and cs files.

Title: .NET Framework 3.5 and TLS 1.2

Body:
As was mentioned .net 3.5.1 DOES now support TLS 1.2; but you don't need the registry changes mentioned by @Paulina's answer.

I'm using VS 2008 with .net 3.5.30729.4926. All I had to do was:

Add imports:

Imports System.Security.Authentication
Imports System.Net

Add this to my code (C#):

public const SslProtocols _Tls12 = (SslProtocols)0x00000C00;
public const SecurityProtocolType Tls12 = (SecurityProtocolType)_Tls12;
ServicePointManager.SecurityProtocol = Tls12

VB.net version:

Const _Tls12 As SslProtocols = DirectCast(&HC00, SslProtocols)
Const Tls12 As SecurityProtocolType = DirectCast(_Tls12, SecurityProtocolType)
ServicePointManager.SecurityProtocol = Tls12

Culled from: https://support.microsoft.com/en-us/help/3154518/support-for-tls-system-default-versions-included-in-the-.net-framework Note: by defining the const in my code I could ignore everything else in the article including the registry edits and cs files.


答:
There's an expressive solution using pure bash built ins.

With associative arrays as sets, you can do it by continuously checking if the key is already being used, in which case you simply continue the loop.

```<code># We will have a set which will contain existing filenames as keys.
declare -A fileSet

while read fullPath; do
    fileName="${fullPath##*/}" # basename
    if [ ! -n "${fileSet[$fileName]}" ]; then # If the file is not already in the set.
        echo $fullPath >> $FILEOUTPUT
        fileSet[$fileName]=1
    fi
done < $FILEINPUT
</code>```

Title: Remove duplicate file names from a listing, disregarding directory

Body:
I am running Linux and writing a BASH script.

I have a text file that has an absolute file path on each line. I have found that sometimes one of my text files will have an identical file but listed under a different path. I want to remove these lines that contain identical files such that the file is represented only once.

For instance, if I have:

/path/to/number1/file1.txt
/path/to/number1/file2.txt
/path/to/number1/file3.txt
/path/to/number2/file3.txt

I want the resulting file to contain:

/path/to/number1/file1.txt
/path/to/number1/file2.txt
/path/to/number1/file3.txt

The path length is variable (the file name cannot be guaranteed to be at field 4, for instance).

I have tried previous solutions to similar problems that use uniq, but uniq doesn't seem to provide an option to match the last field, nor does it allow one to set the delimiter. What are some solutions to this?

Body:
There's an expressive solution using pure bash built ins.

With associative arrays as sets, you can do it by continuously checking if the key is already being used, in which case you simply continue the loop.

# We will have a set which will contain existing filenames as keys.
declare -A fileSet

while read fullPath; do
    fileName="${fullPath##*/}" # basename
    if [ ! -n "${fileSet[$fileName]}" ]; then # If the file is not already in the set.
        echo $fullPath >> $FILEOUTPUT
        fileSet[$fileName]=1
    fi
done < $FILEINPUT


问:
Ionic2 toggle change toggle button state based on method
So I've scoured all the stackoverflows I can find, but I can't seem to solve this problem.
What I want is to toggle a  switch on page view to be whatever it was set to last. The value the toggle is supposed to be is the return value of a method that checks if it should be true or false.

```<code><ion-toggle class="user-toggle" (ionChange)="userChange($event, user)" checked="isInChosen(user)"> </ion-toggle>
</code>```

I confirmed that when I use the tag checked="true", it works as expected and loads to be active on load. However, when isInChosen(user) is put, it always starts false regardless of the actual return value of the method. Rather, it doesn't call the method at all.
I feel like I'm missing something obvious here, and I probably am.

edit: source code for isInChosen(user)

```<code>isInChosen(user) {
   return this.chosenUsers.indexOf(user) != -1;
}
</code>```

userChange(event, user)

```<code>userChange(event, user) {
    if (this.isInChosen(user)) {
        var index = this.chosenUsers.indexOf(user);
        this.chosenUsers.splice(index, 1);

    } else {
        this.chosenUsers.push(user);
    }
}
</code>```

答: I did miss something obvious there. Forgot that Angular2 changed things so I had to surround checked with square brackets, like so: [checked]=

Body:
So I've scoured all the stackoverflows I can find, but I can't seem to solve this problem.
What I want is to toggle a  switch on page view to be whatever it was set to last. The value the toggle is supposed to be is the return value of a method that checks if it should be true or false.

<ion-toggle class="user-toggle" (ionChange)="userChange($event, user)" checked="isInChosen(user)"> </ion-toggle>

I confirmed that when I use the tag checked="true", it works as expected and loads to be active on load. However, when isInChosen(user) is put, it always starts false regardless of the actual return value of the method. Rather, it doesn't call the method at all.
I feel like I'm missing something obvious here, and I probably am.

edit: source code for isInChosen(user)

isInChosen(user) {
   return this.chosenUsers.indexOf(user) != -1;
}

userChange(event, user)

userChange(event, user) {
    if (this.isInChosen(user)) {
        var index = this.chosenUsers.indexOf(user);
        this.chosenUsers.splice(index, 1);

    } else {
        this.chosenUsers.push(user);
    }
}


问:
Open source converter which can convert mp4 to 3gp and 3gp to mp4
please provide me link of good open source exe which i can call from .net and convert mp4 to 3gp and 3gp to mp4.

Thanks

答:
Finally i got the answer:
using ffmpeg we can do it like:

ffmpeg -y -i input.mp4 -r 20 -s 352x288 -b 400k -acodec libfaac -ac 1 -ar 8000 -ab 24k file.3gp


问:
Get all value of specific data attribute
I have data-tablet-src more than one as you see and I want to list them with key and value for example like this:

```<code>data-tablet-src => https://unsplash.it/1000/300?image=21
data-tablet-src => https://unsplash.it/1000/300?image=1001
bla...bla..bla...
</code>```

$(document).ready(function(){
$('#mycarousel .item img[data-tablet-src]').each(function (index, value) {
 alert("index:" + index+"value: "+value);
});

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="carousel-inner" role="listbox">
    <div class="item active">
        <img src="https://unsplash.it/1000/300?image=68" data-tablet-src="https://unsplash.it/1000/300?image=21">
    </div>
    <div class="item">
        <img src="https://unsplash.it/1000/300?image=43" data-tablet-src="https://unsplash.it/1000/300?image=1001">
    </div>
    <div class="item">
        <img src="https://unsplash.it/1000/300?image=67" data-tablet-src="https://unsplash.it/1000/300?image=1002">
    </div>
    <div class="item">
        <img src="https://unsplash.it/1000/300?image=47" data-tablet-src="https://unsplash.it/1000/300?image=1005">
    </div>
    <div class="item">
        <img src="https://unsplash.it/1000/300?image=72" data-tablet-src="https://unsplash.it/1000/300?image=63">
    </div>
  </div></code>```

答:
You can map the data values back to an array based on elements index like this

```<code>var sources = $('.carousel-inner .item img').map(function() {
    return $(this).data('tablet-src');
}).get();
</code>```

FIDDLE

Body:
I have data-tablet-src more than one as you see and I want to list them with key and value for example like this:

data-tablet-src => https://unsplash.it/1000/300?image=21
data-tablet-src => https://unsplash.it/1000/300?image=1001
bla...bla..bla...

$(document).ready(function(){
$('#mycarousel .item img[data-tablet-src]').each(function (index, value) {
 alert("index:" + index+"value: "+value);
});

});

Body:
You can map the data values back to an array based on elements index like this

var sources = $('.carousel-inner .item img').map(function() {
    return $(this).data('tablet-src');
}).get();

FIDDLE


问:
DataTable.Select.Where VB.Net - Delete rows
I'm currently pulling information using a query that I'm not allowed to tamper with:

```<code>Dim dt As DataTable = BLL.GetData(variable).Tables(0)
</code>```

Immediately afterwards, I'm removing any records where a field begins with a specific value:

```<code>For Each dr As DataRow In dt.Rows
    If dr.Item(2).ToString().StartsWith("value") Then
        dr.Delete()
    End If
Next
</code>```

What I'd really like to do is something like:

```<code>dt.Select.Where(field1 => field1.StartsWith("value")).Delete()
</code>```

I know that is not the syntax of it and I'm probably very off from what it would be like.  The For Each works fine, I'm just trying to "simplify" it.  Any idea?  Any and all help is appreciated.

答:
The answer I think you are looking for is below from Microsoft. https://msdn.microsoft.com/en-us/library/det4aw50(v=vs.110).aspx?cs-save-lang=1&cs-lang=vb#code-snippet-2

Dim table As DataTable = DataSet1.Tables("Orders")

```<code>' Presuming the DataTable has a column named Date.
Dim expression As String
expression = "Date > #1/1/00#"
Dim foundRows() As DataRow

' Use the Select method to find all rows matching the filter.
foundRows = table.Select(expression)

Dim i As Integer
' Print column 0 of each returned row.
For i = 0 to foundRows.GetUpperBound(0)
   Console.WriteLine(foundRows(i)(0))
Next i
</code>```

Body:
I'm currently pulling information using a query that I'm not allowed to tamper with:

Dim dt As DataTable = BLL.GetData(variable).Tables(0)

Immediately afterwards, I'm removing any records where a field begins with a specific value:

For Each dr As DataRow In dt.Rows
    If dr.Item(2).ToString().StartsWith("value") Then
        dr.Delete()
    End If
Next

What I'd really like to do is something like:

dt.Select.Where(field1 => field1.StartsWith("value")).Delete()

I know that is not the syntax of it and I'm probably very off from what it would be like.  The For Each works fine, I'm just trying to "simplify" it.  Any idea?  Any and all help is appreciated.

Body:
The answer I think you are looking for is below from Microsoft. https://msdn.microsoft.com/en-us/library/det4aw50(v=vs.110).aspx?cs-save-lang=1&cs-lang=vb#code-snippet-2

Dim table As DataTable = DataSet1.Tables("Orders")

' Presuming the DataTable has a column named Date.
Dim expression As String
expression = "Date > #1/1/00#"
Dim foundRows() As DataRow

' Use the Select method to find all rows matching the filter.
foundRows = table.Select(expression)

Dim i As Integer
' Print column 0 of each returned row.
For i = 0 to foundRows.GetUpperBound(0)
   Console.WriteLine(foundRows(i)(0))
Next i


问:
softlayer api: how to get Secondary Addresses of virtual machine
softlayer api: How to order Public Secondary IP Addresses when I ordering?

I have order a virtual machine with 8 secondary ip address. by using api, how can I retrive the 8 secondary ip address.

答:
You may retrieve the list required by using Network_Subnet::getIpAddresses method. Please try the following REST request:

```<code>https://$username:$apiKey@api.softlayer.com/rest/v3.1/SoftLayer_Network_Subnet/$subnetId/getIpAddresses?objectMask=mask[ipAddress, note, id, subnetId]
</code>```

The code above is using objectMasks to display only what portal shows you, as in this case, your 8 or any number of Ip Addresses on a specific subnet, remember to change the first $username:$apikey values for valid credentials, and also the $subnetId identifier.

UPDATE:
You may search the subnet Id of of a VSI by using:

SoftLayer_Virtual_Guest::getObject

```<code>https://$username:$apiKey@api.softlayer.com/rest/v3.1/SoftLayer_Virtual_Guest/$virtualGuestId/getObject?objectMask=mask[accountId,fullyQualifiedDomainName,primaryIpAddress,hostname,domain,frontendNetworkComponents[guestId,primaryIpAddress,subnets[id]]]
</code>```

Remember to change the $virtualGuestId for your VSI id value.

For more information please see below:

Object Masks

Get Subnet Capacity

Body:
You may retrieve the list required by using Network_Subnet::getIpAddresses method. Please try the following REST request:

https://$username:$apiKey@api.softlayer.com/rest/v3.1/SoftLayer_Network_Subnet/$subnetId/getIpAddresses?objectMask=mask[ipAddress, note, id, subnetId]

The code above is using objectMasks to display only what portal shows you, as in this case, your 8 or any number of Ip Addresses on a specific subnet, remember to change the first $username:$apikey values for valid credentials, and also the $subnetId identifier.

UPDATE:
You may search the subnet Id of of a VSI by using:

SoftLayer_Virtual_Guest::getObject

https://$username:$apiKey@api.softlayer.com/rest/v3.1/SoftLayer_Virtual_Guest/$virtualGuestId/getObject?objectMask=mask[accountId,fullyQualifiedDomainName,primaryIpAddress,hostname,domain,frontendNetworkComponents[guestId,primaryIpAddress,subnets[id]]]

Remember to change the $virtualGuestId for your VSI id value.

For more information please see below:

Object Masks

Get Subnet Capacity


问:
Can't find images over https
I'm having a question. I'm trying to service my webshop over https (using letsencrypt). I've added the following in my .htaccess file to direct all traffic over https:

```<code># All HTTPS to HTTP.
RewriteEngine on
RewriteBase /
RewriteCond %{HTTPS} !on
RewriteRule (.*) https://www.domain.nl%{REQUEST_URI} [L,R=301]
</code>```

I'm using apache2 on a ubuntu 16.04 server. I have a folder in my root /domain_files/uploads which 301's as /var/www/domain/uploads/

Now images are not available anymore over https:
https://www.domain.nl/uploads/profilepictures/MXY6x2r8t4U_facebook_profilepic.jpg

http:
http://www.domain.nl/uploads/profilepictures/MXY6x2r8t4U_facebook_profilepic.jpg

答: It seemed that I had a different .conf file in my Apache2 specially for https:// connections. I updated the 301 path's and it worked!</p>

Title: Can't find images over https

Body:
I'm having a question. I'm trying to service my webshop over https (using letsencrypt). I've added the following in my .htaccess file to direct all traffic over https:

# All HTTPS to HTTP.
RewriteEngine on
RewriteBase /
RewriteCond %{HTTPS} !on
RewriteRule (.*) https://www.domain.nl%{REQUEST_URI} [L,R=301]

I'm using apache2 on a ubuntu 16.04 server. I have a folder in my root /domain_files/uploads which 301's as /var/www/domain/uploads/

Now images are not available anymore over https:
https://www.domain.nl/uploads/profilepictures/MXY6x2r8t4U_facebook_profilepic.jpg

http:
http://www.domain.nl/uploads/profilepictures/MXY6x2r8t4U_facebook_profilepic.jpg


问:
How to add button "upload" when using Camera in Iphone?
I have a tableView, and I want to take a picture when clicking in one of the cells and upload it to a certain server.
I have managed to do this so far:

```<code>- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

//do actions
UIImagePickerController *picker = [[UIImagePickerController alloc] init];

// Set the image picker source to the camera:
picker.sourceType = UIImagePickerControllerSourceTypeCamera;

// Hide the camera controls:
picker.showsCameraControls = YES;
picker.navigationBarHidden = NO;

// Make the view full screen:
picker.wantsFullScreenLayout = YES;
//picker.cameraViewTransform = CGAffineTransformScale(picker.cameraViewTransform, CAMERA_TRANSFORM_X, CAMERA_TRANSFORM_Y);

// Now insert our overlay view (it has to be here cuz it's a modal view):
//picker.cameraOverlayView = overlayView;

matches *aMatch = [appDelegate.matches objectAtIndex:indexPath.row];
NSLog(@"%@", [NSString stringWithFormat:@"%d", aMatch.match_id]);

// Show the picker:
[self presentModalViewController:picker animated:YES];

[picker release];
</code>```

}

It starts the camera and takes the picture, but I would like to get an "Upload" button when clicking in "use", can you help me? is it posible? (like the facebook app)
By the way, whe I click in use it comes back to the table view, but where is the image? is it saved in picker?

答:
Maybe I didn't explain myself very good, but here is an example of what I was trying to do ( customize the look of the camera by adding an upload button): http://developer.apple.com/library/ios/#samplecode/PhotoPicker/Introduction/Intro.html%23//apple_ref/doc/uid/DTS40010196-Intro-DontLinkElementID_2
Thank you.</p>

Body:
I have a tableView, and I want to take a picture when clicking in one of the cells and upload it to a certain server.
I have managed to do this so far:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

//do actions
UIImagePickerController *picker = [[UIImagePickerController alloc] init];

// Set the image picker source to the camera:
picker.sourceType = UIImagePickerControllerSourceTypeCamera;

// Hide the camera controls:
picker.showsCameraControls = YES;
picker.navigationBarHidden = NO;

// Make the view full screen:
picker.wantsFullScreenLayout = YES;
//picker.cameraViewTransform = CGAffineTransformScale(picker.cameraViewTransform, CAMERA_TRANSFORM_X, CAMERA_TRANSFORM_Y);

// Now insert our overlay view (it has to be here cuz it's a modal view):
//picker.cameraOverlayView = overlayView;

matches *aMatch = [appDelegate.matches objectAtIndex:indexPath.row];
NSLog(@"%@", [NSString stringWithFormat:@"%d", aMatch.match_id]);

// Show the picker:
[self presentModalViewController:picker animated:YES];

[picker release];

}

It starts the camera and takes the picture, but I would like to get an "Upload" button when clicking in "use", can you help me? is it posible? (like the facebook app)
By the way, whe I click in use it comes back to the table view, but where is the image? is it saved in picker?