问:
Cannot do local remoting
I can use Invoke-Command to another machine on the network.
I have already run Enable-PSRemoting as an Administrator.

PSVersion 5.0.10586.117

Windows 7 Professional SP1

What am I missing?

```
PS C:\Windows\system32> winrm quickconfig
WinRM service is already running on this machine.
WinRM is already set up for remote management on this computer.

PS C:\Windows\system32> Invoke-Command -ComputerName localhost -ScriptBlock { dir }
[localhost] Connecting to remote server localhost failed with the following error
message : The client cannot connect to the destination specified in the request.
Verify that the service on the destination is running and is accepting requests.
Consult the logs and documentation for the WS-Management service running on the
destination, most commonly IIS or WinRM. If the destination is the WinRM service,
run the following command on the destination to analyze and configure the WinRM
service: "winrm quickconfig". For more information, see the
about_Remote_Troubleshooting Help topic.
    + CategoryInfo          : OpenError: (localhost:String) [], PSRemotingTransportException
    + FullyQualifiedErrorId : CannotConnect,PSSessionStateBroken
```

After setting DisableStrictNameChecking to one (1), the same error message appears.

After setting BackConnectionHostNames to "localhost" and "ALFRED", the same error message appears.

After setting DisableLoopbackCheck to one (1), the following message appears.

```<code>PS C:\Windows\system32> winrm quickconfig
WinRM service is already running on this machine.
WSManFault
    Message
        ProviderFault
            WSManFault
                Message = WinRM firewall exception will not work since one of the network connection types on this ma
chine is set to Public. Change the network connection type to either Domain or Private and try again.

Error number:  -2144108183 0x80338169
WinRM firewall exception will not work since one of the network connection
types on this machine is set to Public. Ch
ange the network connection type to either Domain or Private and try again.
</code>```

It appears that I do not have permission to change the network type. I am on a corporate VPN. The company.com network is Domain network, but the other network is Public network. If I cannot change it, then it seems that I cannot get there from here.

答:
Delete WinRM old listener .

winrm delete winrm/config/Listener?Address=*+Transport=HTTPS

first need to create a self-signed certificate and get its thumbprint

1.New-SelfSignedCertificate -DnsName "" -CertStoreLocation Cert:\LocalMachine\My

Copy the thumbprint to clipboard and run the following command. This command will register the HTTPS listener in WinRM

2.winrm create winrm/config/Listener?Address=*+Transport=HTTPS @{Hostname=""; CertificateThumbprint=""}

Add a new firewall rule

```<code>port=5986
netsh advfirewall firewall add rule name="Windows Remote Management (HTTPS-In)" dir=in action=allow protocol=TCP localport=$port
</code>```

Title: Cannot do local remoting

Body:
I can use Invoke-Command to another machine on the network.
I have already run Enable-PSRemoting as an Administrator.

PSVersion 5.0.10586.117

Windows 7 Professional SP1

What am I missing?

PS C:\Windows\system32> winrm quickconfig
WinRM service is already running on this machine.
WinRM is already set up for remote management on this computer.

PS C:\Windows\system32> Invoke-Command -ComputerName localhost -ScriptBlock { dir }
[localhost] Connecting to remote server localhost failed with the following error
message : The client cannot connect to the destination specified in the request.
Verify that the service on the destination is running and is accepting requests.
Consult the logs and documentation for the WS-Management service running on the
destination, most commonly IIS or WinRM. If the destination is the WinRM service,
run the following command on the destination to analyze and configure the WinRM
service: "winrm quickconfig". For more information, see the
about_Remote_Troubleshooting Help topic.
    + CategoryInfo          : OpenError: (localhost:String) [], PSRemotingTransportException
    + FullyQualifiedErrorId : CannotConnect,PSSessionStateBroken

After setting DisableStrictNameChecking to one (1), the same error message appears.

After setting BackConnectionHostNames to "localhost" and "ALFRED", the same error message appears.

After setting DisableLoopbackCheck to one (1), the following message appears.

PS C:\Windows\system32> winrm quickconfig
WinRM service is already running on this machine.
WSManFault
    Message
        ProviderFault
            WSManFault
                Message = WinRM firewall exception will not work since one of the network connection types on this ma
chine is set to Public. Change the network connection type to either Domain or Private and try again.

Error number:  -2144108183 0x80338169
WinRM firewall exception will not work since one of the network connection
types on this machine is set to Public. Ch
ange the network connection type to either Domain or Private and try again.

It appears that I do not have permission to change the network type. I am on a corporate VPN. The company.com network is Domain network, but the other network is Public network. If I cannot change it, then it seems that I cannot get there from here.

Body:
Delete WinRM old listener .

winrm delete winrm/config/Listener?Address=*+Transport=HTTPS

first need to create a self-signed certificate and get its thumbprint

1.New-SelfSignedCertificate -DnsName "" -CertStoreLocation Cert:\LocalMachine\My

Copy the thumbprint to clipboard and run the following command. This command will register the HTTPS listener in WinRM

2.winrm create winrm/config/Listener?Address=*+Transport=HTTPS @{Hostname=""; CertificateThumbprint=""}

Add a new firewall rule

port=5986
netsh advfirewall firewall add rule name="Windows Remote Management (HTTPS-In)" dir=in action=allow protocol=TCP localport=$port


来源: stackexchange

问:
use rails button in form as link
I have a table with sliders (part of a form) in one column and a button (link to other page)

```<code><button onclick="location.href='/main';">
   <i class="icon icon-078-settings icon--s2" aria-hidden="true"></i>
</button>
</code>```

Instead of opening the page, the button just submits the form. Any way I can fix this without breaking the table or the form?

答:
try below code:

```<code><a href='/main' class="btn btn-primary">
  <i class="icon icon-078-settings icon--s2" aria-hidden="true"></i>
</a>
</code>```

If you used bootstrap css then you can add classes btn and btn-paimary which makes button.

ContentLicense: CC BY-SA 3.0

Title: use rails button in form as link

Body:
I have a table with sliders (part of a form) in one column and a button (link to other page)

<button onclick="location.href='/main';">

</button>

Instead of opening the page, the button just submits the form. Any way I can fix this without breaking the table or the form?

Body:
try below code:

<a href='/main' class="btn btn-primary">
  <i class="icon icon-078-settings icon--s2" aria-hidden="true"></i>
</a>

If you used bootstrap css then you can add classes btn and btn-paimary which makes button.


问:
How can I get the content of CKEditor using JQuery?
I'm using CKEditor. I am saving the form values with ajax using page methods.

But the content of CKEditor value cannot be saving into the table.

I dont postback the page.

What can I do for that?

答:
you can retreive data like this :

```<code><script>
var data = CKEDITOR.instances.editor1.getData();
// Your code to save "data", usually through Ajax.
</script>
</code>```

reference :
http://docs.ckeditor.com/#!/guide/dev_savedata

ContentLicense: CC BY-SA 4.0

Body:
you can retreive data like this :

<script>
var data = CKEDITOR.instances.editor1.getData();
// Your code to save "data", usually through Ajax.
</script>

reference :
http://docs.ckeditor.com/#!/guide/dev_savedata


问:
Formatting with SQL DATEPART
I am using DATEPART(WEEK,mydate) to return the week number of my date, but when the week is only single number i.e. at the beginning of the year I want to format it as 01 instead of 1.

I am using SQL Server 2014, I have tried using the option format(datepart(week,mydate),'ww') but am just getting ww as my answer which as you can tell isn't quite right

答:
Try this </p>

```<code> SELECT RIGHT('0' + RTRIM(DATEPART(WEEK,GETDATE())), 2)
--selects 23
 SELECT RIGHT('0' + RTRIM(DATEPART(WEEK,'2017-01-01 03:58:13.110')), 2)
-- selects 01
</code>```

Title: Formatting with SQL DATEPART

Body:
Try this

 SELECT RIGHT('0' + RTRIM(DATEPART(WEEK,GETDATE())), 2)
--selects 23
 SELECT RIGHT('0' + RTRIM(DATEPART(WEEK,'2017-01-01 03:58:13.110')), 2)
-- selects 01


问:
ng-repeat filter either equals to first name or last name
in angularJs is there way to filter ng-repeat by matching two or more fields?
for example I want to list all the person who has letter "J" in either first name or last name.
if I use current function it list out the person who has letter 'J' in both first name and last name</p>

```<code><!DOCTYPE html>
<html ng-app="myApp">

<head>
    <meta name="format-detection" content="telephone=no">
    <meta name="msapplication-tap-highlight" content="no">
    <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width">
    <title>Welcome To My Homepage</title>
    <link href="css/style.css" rel="stylesheet" />
    <link href="css/bootstrap.min.css" rel="stylesheet" />
</head>

<body ng-controller="MyCtrl">
    <div ng-controller="MyCtrl">
        <input type="text" ng-model="search">{{search}}
        <table border="1">
            <tr ng-repeat="row in list | filter:{firstName:search} | filter:{lastName:search}">
                <td>{{row.firstName}} {{row.lastName}}</td>
            </tr>
        </table>
    </div>

    <script src="js/jquery-2.2.1.js"></script>
    <script src="js/angular.js"></script>
    <script src="js/bootstrap.min.js"></script>
    <script type="text/javascript">

        var myApp = angular.module('myApp',[]);

        myApp.controller('MyCtrl', ['$scope','$http','$filter', function($scope,$http,$filter) {

            $scope.list = [{
                    "id": 1,
                    "address": "New York City",
                    "firstName": "Jennifer",
                    "middleName": null,
                    "lastName": "Aniston"
                    }, {
                        "id": 1,
                        "address": "New York City",
                        "firstName": "Jennifer",
                        "middleName": null,
                        "lastName": "Leela"
                    }, {
                        "id": 2,
                        "address": "Beverley Hills",
                        "firstName": "Angelina",
                        "middleName": null,
                        "lastName": "Jolie"
                    }, {
                    "id": 3,
                    "address": "London",
                    "firstName": "Emma",
                    "middleName": null,
                    "lastName": "Watson"
            }];

        }]);
    </script>

</html>
</code>```

答:
<input type="text" ng-model="search.$"> , through this it filters by search matching character in any of the property.

So filter it once as

var myApp = angular.module('myApp', []);

myApp.controller('MyCtrl', ['$scope', '$http', '$filter', function($scope, $http, $filter) {

  $scope.list = [{
    "id": 1,
    "address": "New York City",
    "firstName": "Jennifer",
    "middleName": null,
    "lastName": "Aniston"
  }, {
    "id": 1,
    "address": "New York City",
    "firstName": "Jennifer",
    "middleName": null,
    "lastName": "Leela"
  }, {
    "id": 2,
    "address": "Beverley Hills",
    "firstName": "Angelina",
    "middleName": null,
    "lastName": "Jolie"
  }, {
    "id": 3,
    "address": "London",
    "firstName": "Emma",
    "middleName": null,
    "lastName": "Watson"
  }];

}]);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<html ng-app="myApp">

<body ng-controller="MyCtrl">
  <div ng-controller="MyCtrl">
    <input type="text" ng-model="search.$">{{search}}
    <table border="1">
      <tr ng-repeat="row in list | filter:search">
        <td>{{row.firstName}} {{row.lastName}}</td>
      </tr>
    </table>
  </div>

</html></code>```

Body:
in angularJs is there way to filter ng-repeat by matching two or more fields?
for example I want to list all the person who has letter "J" in either first name or last name.
if I use current function it list out the person who has letter 'J' in both first name and last name

<!DOCTYPE html>

    <meta name="format-detection" content="telephone=no">
    <meta name="msapplication-tap-highlight" content="no">
    <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width">
    <title>Welcome To My Homepage</title>
    <link href="css/style.css" rel="stylesheet" />
    <link href="css/bootstrap.min.css" rel="stylesheet" />

        <input type="text" ng-model="search">{{search}}

                {{row.firstName}} {{row.lastName}}

Body:
<input type="text" ng-model="search.$"> , through this it filters by search matching character in any of the property.

So filter it once as <tr ng-repeat="row in list | filter:search">

var myApp = angular.module('myApp', []);

myApp.controller('MyCtrl', ['$scope', '$http', '$filter', function($scope, $http, $filter) {

  $scope.list = [{
    "id": 1,
    "address": "New York City",
    "firstName": "Jennifer",
    "middleName": null,
    "lastName": "Aniston"
  }, {
    "id": 1,
    "address": "New York City",
    "firstName": "Jennifer",
    "middleName": null,
    "lastName": "Leela"
  }, {
    "id": 2,
    "address": "Beverley Hills",
    "firstName": "Angelina",
    "middleName": null,
    "lastName": "Jolie"
  }, {
    "id": 3,
    "address": "London",
    "firstName": "Emma",
    "middleName": null,
    "lastName": "Watson"
  }];

}]);

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<html ng-app="myApp">

<body ng-controller="MyCtrl">
  <div ng-controller="MyCtrl">
    <input type="text" ng-model="search.$">{{search}}
    <table border="1">
      <tr ng-repeat="row in list | filter:search">
        <td>{{row.firstName}} {{row.lastName}}</td>
      </tr>
    </table>
  </div>

</html>


问:
Static allocation of opaque data types
Very often malloc() is absolutely not allowed when programming for embedded systems. Most of the time I'm pretty able to deal with this, but one thing irritates me: it keeps me from using so called 'opaque types' to enable data hiding. Normally I'd do something like this:

```<code>// In file module.h
typedef struct handle_t handle_t;

handle_t *create_handle();
void operation_on_handle(handle_t *handle, int an_argument);
void another_operation_on_handle(handle_t *handle, char etcetera);
void close_handle(handle_t *handle);

// In file module.c
struct handle_t {
    int foo;
    void *something;
    int another_implementation_detail;
};

handle_t *create_handle() {
    handle_t *handle = malloc(sizeof(struct handle_t));
    // other initialization
    return handle;
}
</code>```

There you go: create_handle() performs a malloc() to create an 'instance'. A construction often used to prevent having to malloc() is to change the prototype of create_handle() like this:

```<code>void create_handle(handle_t *handle);
</code>```

And then the caller could create the handle this way:

```<code>// In file caller.c
void i_am_the_caller() {
    handle_t a_handle;    // Allocate a handle on the stack instead of malloc()
    create_handle(&a_handle);
    // ... a_handle is ready to go!
}
</code>```

But unfortunately this code is obviously invalid, the size of handle_t isn't known!

I never really found a solution to solve this in a proper way. I'd very like to know if anyone has a proper way of doing this, or maybe a complete different approach to enable data hiding in C (not using static globals in the module.c of course, one must be able to create multiple instances).

答:
I'm a little confused why you say you can't use malloc(). Obviously on an embedded system you have limited memory and the usual solution is to have your own memory manager which mallocs a large memory pool and then allocates chunks of this out as needed. I've seen various different implementations of this idea in my time.

To answer your question though, why don't you simply statically allocate a fixed size array of them in module.c add an "in-use" flag, and then have create_handle() simply return the pointer to the first free element.

As an extension to this idea, the "handle" could then be an integer index rather than the actual pointer which avoids any chance of the user trying to abuse it by casting it to their own definition of the object.

ContentLicense: CC BY-SA 2.5

Title: Static allocation of opaque data types

Body:
Very often malloc() is absolutely not allowed when programming for embedded systems. Most of the time I'm pretty able to deal with this, but one thing irritates me: it keeps me from using so called 'opaque types' to enable data hiding. Normally I'd do something like this:

// In file module.h
typedef struct handle_t handle_t;

handle_t *create_handle();
void operation_on_handle(handle_t *handle, int an_argument);
void another_operation_on_handle(handle_t *handle, char etcetera);
void close_handle(handle_t *handle);

// In file module.c
struct handle_t {
    int foo;
    void *something;
    int another_implementation_detail;
};

handle_t *create_handle() {
    handle_t *handle = malloc(sizeof(struct handle_t));
    // other initialization
    return handle;
}

There you go: create_handle() performs a malloc() to create an 'instance'. A construction often used to prevent having to malloc() is to change the prototype of create_handle() like this:

void create_handle(handle_t *handle);

And then the caller could create the handle this way:

// In file caller.c
void i_am_the_caller() {
    handle_t a_handle;    // Allocate a handle on the stack instead of malloc()
    create_handle(&a_handle);
    // ... a_handle is ready to go!
}

But unfortunately this code is obviously invalid, the size of handle_t isn't known!

I never really found a solution to solve this in a proper way. I'd very like to know if anyone has a proper way of doing this, or maybe a complete different approach to enable data hiding in C (not using static globals in the module.c of course, one must be able to create multiple instances).


问:
Removing NA from csv data file
I am using this codes to import data

```<code>counts<-read.csv("data.csv", stringsAsFactors=FALSE, header=FALSE)
</code>```

link to view the data

and to remove NAs from data I am using 2 methods

1

```<code>lists <- lapply(as.list(counts), function(x) x[x != ""])
</code>```

2

```<code>removeEMPTYstrings <- function(x) {
 newVectorWOstrings <- x[x != ""]
 return(newVectorWOstrings)
}

lists <- lapply(as.list(counts), removeEMPTYstrings)
</code>```

but both of these ways are not removing NAs from the data and I am still getting this message "Error: NAs in dataset".

I just want to remove/ignore/unread the NAs in the data and not to remove entire column or row.

Thank you.

答:
We can use na.omit to remove the NA

```<code>counts1 <- na.omit(counts)
</code>```

Or complete.cases

```<code>counts1 <- counts[complete.cases(counts),]
</code>```

Or if we need to remove the NA by each column

```<code>lapply(counts, function(x) x[!is.na(x)])
</code>```

Title: Removing NA from csv data file

Body:
I am using this codes to import data

counts<-read.csv("data.csv", stringsAsFactors=FALSE, header=FALSE)

link to view the data

and to remove NAs from data I am using 2 methods

1

lists <- lapply(as.list(counts), function(x) x[x != ""])

2

removeEMPTYstrings <- function(x) {
 newVectorWOstrings <- x[x != ""]
 return(newVectorWOstrings)
}

lists <- lapply(as.list(counts), removeEMPTYstrings)

but both of these ways are not removing NAs from the data and I am still getting this message "Error: NAs in dataset".

I just want to remove/ignore/unread the NAs in the data and not to remove entire column or row.

Thank you.

Body:
We can use na.omit to remove the NA

counts1 <- na.omit(counts)

Or complete.cases

counts1 <- counts[complete.cases(counts),]

Or if we need to remove the NA by each column

lapply(counts, function(x) x[!is.na(x)])


问:
Using Microsoft Bot Framework, when I write on Messenger channel, how to push the result to a specific Slack channel ? (with Node)
Currently my users are using a Messenger channel.

Here is what it goes: my users type "Talk to a coach" in my bot, then they can write whatever they want, and then the result should be pushed to a specific private channel using Slack.

How can I achieve that ?

EDIT: The private channel is a list of users request that can be processed when coaches are available, so users don't have to be in a waiting list

答:
You are looking for the ability to "hand off" a customer from a bot to a human agent.

This topic is depicted in the official documentation and there are several samples available, for Node.js you may be interested in this one: https://github.com/palindromed/Bot-HandOff


问:
Bootstrap data-toggle="buttons" radio checked property
I see that the Bootstrap radio buttons (created with data-toggle="buttons") change event switches the active class between the labels and does no effect on the checked properties of the real radio buttons. Is that a normal behaviour or do I have a mistake?

Or, how can I bind this active class of label and checked property of the radio each other in two-way so that they change at the same time?

Example Code:

```<code><div class="btn-group" data-toggle="buttons">
  <label class="btn btn-primary active">
    <input type="radio" name="options" id="option1" autocomplete="off" checked> Radio 1 (preselected)
  </label>
  <label class="btn btn-primary">
    <input type="radio" name="options" id="option2" autocomplete="off"> Radio 2
  </label>
  <label class="btn btn-primary">
    <input type="radio" name="options" id="option3" autocomplete="off"> Radio 3
  </label>
</div>
</code>```

答:
If you’re pre-toggling a button, you must manually add the .active class and aria-pressed="true" to the .

https://v4-alpha.getbootstrap.com/components/buttons/#toggle-states

Body:
I see that the Bootstrap radio buttons (created with data-toggle="buttons") change event switches the active class between the labels and does no effect on the checked properties of the real radio buttons. Is that a normal behaviour or do I have a mistake?

Or, how can I bind this active class of label and checked property of the radio each other in two-way so that they change at the same time?

Example Code:

    <input type="radio" name="options" id="option1" autocomplete="off" checked> Radio 1 (preselected)

    <input type="radio" name="options" id="option2" autocomplete="off"> Radio 2

    <input type="radio" name="options" id="option3" autocomplete="off"> Radio 3


问:
MakeFile not working?
I have one Java file (example.java) and one Makefile, while trying to execute the Makefile with make command I am getting the below error:

Makefile:5: * target pattern contains no `%'.  Stop.**

Below is the content of my Makefile

```<code>CP=-cp .:/usr/share/java/log4j.jar:/usr/share/java/jackson/jackson-core-
asl.jar:/usr/share/java/jackson/jackson-mapper-
asl.jar:/usr/share/java/jackson/jackson-
smile.jar:/usr/share/java/jackson/jackson-
jaxrs.jar:/usr/share/java/jackson/jackson-
mrbean.jar:/usr/share/java/jackson/jackson-
xc.jar:../../../lib/java/lib/alarm-logging-libs.jar
all: alarm_example.class

example.class: example.java
        javac -d . $(CP) example.java
clean:
        rm -fr *.class
</code>```

Request you kindly have a look and provide your suggestion.
Thanks in Advance

答:
This is a bad error message. It either means that a character in your filenames could be part of a regular expression or that you should

check the value of any variables in your target and prerequisite lists to be sure they do not contain colons.

You might find this useful (from the manual): Errors Generated by Make

If you see these errors and you aren’t trying to create a static pattern rule, check the value of any variables in your target and prerequisite lists to be sure they do not contain colons. See Syntax of Static Pattern Rules.

Title: MakeFile not working?

Body:
I have one Java file (example.java) and one Makefile, while trying to execute the Makefile with make command I am getting the below error:

Makefile:5: * target pattern contains no `%'.  Stop.**

Below is the content of my Makefile

CP=-cp .:/usr/share/java/log4j.jar:/usr/share/java/jackson/jackson-core-
asl.jar:/usr/share/java/jackson/jackson-mapper-
asl.jar:/usr/share/java/jackson/jackson-
smile.jar:/usr/share/java/jackson/jackson-
jaxrs.jar:/usr/share/java/jackson/jackson-
mrbean.jar:/usr/share/java/jackson/jackson-
xc.jar:../../../lib/java/lib/alarm-logging-libs.jar
all: alarm_example.class

example.class: example.java
        javac -d . $(CP) example.java
clean:
        rm -fr *.class

Request you kindly have a look and provide your suggestion.
Thanks in Advance


问:
if someone give me a request to take some data from my apps, how can i accept the request in laravel controller?
The request will be in json format, the request is

```<code>{
"app_id": 1234,
"app_key": "our_app_key",
"bus_id": 67,
"data": [{
    "seat_id": 1
}, {
    "seat_id": 2
}]
</code>```

}

and this is my routes.php file

```<code>Route::get('getBookingSeats', 'SelectBoxController@getBookingSeats');
</code>```

below my controller function:

```<code>public function getBookingSeats(Request $request){

    return response()->json($data);
}
</code>```

in my controller function how can get the json data, like app_id, app_key, bus_id, and data[seat_id, seat_id]. Is it possible if yes how? please help me.

答:
I'm not sure this is exactly what you are trying to do, but the request received must be a POST request if you are getting the JSON data in the request. If it is, do the following:

Route:

```<code>Route::post('getBookingSeats', 'SelectBoxController@getBookingSeats');
</code>```

Controller:

```<code>public function getBookingSeats(Request $request)
{
    $app_id = $request->app_id;
    $app_key = $request->app_key;
    $bus_id = $request->bus_id;
    $seat_IDs = $request->data;

    // use the data however you want and create your response

    return response()->json('data' => $data);
}
</code>```

Body:
The request will be in json format, the request is

{
"app_id": 1234,
"app_key": "our_app_key",
"bus_id": 67,
"data": [{
    "seat_id": 1
}, {
    "seat_id": 2
}]

}

and this is my routes.php file

Route::get('getBookingSeats', 'SelectBoxController@getBookingSeats');

below my controller function:

public function getBookingSeats(Request $request){

    return response()->json($data);
}

in my controller function how can get the json data, like app_id, app_key, bus_id, and data[seat_id, seat_id]. Is it possible if yes how? please help me.

Body:
I'm not sure this is exactly what you are trying to do, but the request received must be a POST request if you are getting the JSON data in the request. If it is, do the following:

Route:

Route::post('getBookingSeats', 'SelectBoxController@getBookingSeats');

Controller:

public function getBookingSeats(Request $request)
{
    $app_id = $request->app_id;
    $app_key = $request->app_key;
    $bus_id = $request->bus_id;
    $seat_IDs = $request->data;

    // use the data however you want and create your response

    return response()->json('data' => $data);
}


问:
Changing data-scroll-speeds with jQuery?
I am using the code below to change the scroll speed of certain elements. Code I have copied from HERE.

To double check my overall code I have also added a color change to ".slogan-a-line".

The if/else is depending on if "#image-ul" is fully above the bottom edge of the browser window.

My problem is that –when either resizing or scrolling the browser window– the color of ".slogan-a-line" does change as it should, but the data-scroll-speeds on other elements do not. When (re)loading they do.

Initially, when first loading the webpage, the correct data-scroll-speed is set by the code. But when resizing the browser window –to change whether "#image-ul" is fully above the bottom edge of the browser window or not– the data scroll speeds do not change, till I refresh the webpage (so the id and class names are correct).

I need the data-scroll-speeds to change without having to refresh the browser window. Can anyone see what I have done wrong?

```<code><script>
  // Assign attribute specific "data-scroll-speed" to elements upon loading, resizing and scrolling of the webpage page. "if/else" is depending on if #image-ul is fully above the bottom edge of the browser window.
  $(document).ready(function() {
    $(window).on('load resize scroll', function() {
      var WindowScrollTop = $(this).scrollTop(),
        Div_one_top = $('#image-ul').offset().top,
        Div_one_height = $('#image-ul').outerHeight(true),
        Window_height = $(this).outerHeight(true);
      if (WindowScrollTop + Window_height >= (Div_one_top + Div_one_height)) {
        $('#sloganenglish').attr('data-scroll-speed', '2');
        $('.slow-scroll-slider').attr('data-scroll-speed', '5');
        $('.slogan-a-line').css('color', 'green');
      } else {
        $('#sloganenglish').attr('data-scroll-speed', '1');
        $('.slow-scroll-slider').attr('data-scroll-speed', '1');
        $('.slogan-a-line').css('color', 'red');
      }
    }).scroll();
  });

  // data-scroll-speed script
  $.fn.moveIt = function() {
    var $window = $(window);
    var instances = [];

    $(this).each(function() {
      instances.push(new moveItItem($(this)));
    });

    window.onscroll = function() {
      var scrollTop = $window.scrollTop();
      instances.forEach(function(inst) {
        inst.update(scrollTop);
      });
    }
  }

  var moveItItem = function(el) {
    this.el = $(el);
    this.speed = parseInt(this.el.attr('data-scroll-speed'));
  };

  moveItItem.prototype.update = function(scrollTop) {
    var pos = scrollTop / this.speed;
    this.el.css('transform', 'translateY(' + -pos + 'px)');
  };

  // Initialization
  $(function() {
    $('[data-scroll-speed]').moveIt();
  });
</script>
</code>```

答:
See an answer EXAMPLE HERE!

```<code>    //
// default speed ist the lowest valid scroll speed.
//
var default_speed = 1;
//
// speed increments defines the increase/decrease of the acceleration
// between current scroll speed and data-scroll-speed
//
var speed_increment = 0.01;
//
// maximum scroll speed of the elements
//
var data_scroll_speed_a = 4; // #sloganenglish
var data_scroll_speed_b = 5; // .slogan-a-line
//
//
//
var increase_speed, decrease_speed, target_speed, current_speed, speed_increments;
$(document).ready(function() {
     $(window).on('load resize scroll', function() {
         var WindowScrollTop = $(this).scrollTop(),
             Div_one_top = $('#image-ul').offset().top,
             Div_one_height = $('#image-ul').outerHeight(true),
             Window_height = $(this).outerHeight(true);
         if (WindowScrollTop + Window_height >= (Div_one_top + Div_one_height)) {
             $('#sloganenglish').attr('data-scroll-speed', data_scroll_speed_a).attr('data-current-scroll-speed', default_speed).attr('data-speed-increments', data_scroll_speed_a * speed_increment);
             $('.slogan-a-line').attr('data-scroll-speed', data_scroll_speed_b).attr('data-current-scroll-speed', default_speed).attr('data-speed-increments', data_scroll_speed_b * speed_increment);
             $('.slogan-a-line').css('color', 'yellow');
             increase_speed = true;
             decrease_speed = false;
         } else {
             $('#sloganenglish').attr('data-scroll-speed', '1').attr('data-current-scroll-speed', default_speed);
             $('.slogan-a-line').attr('data-scroll-speed', '1').attr('data-current-scroll-speed', default_speed);
             $('.slogan-a-line').css('color', 'red');
             decrease_speed = true;
             increase_speed = false;
         }
     }).scroll();
 });

 // data-scroll-speed script
 $.fn.moveIt = function() {
     var $window = $(window);
     var instances = [];

     $(this).each(function() {
         instances.push(new moveItItem($(this)));
     });

     window.onscroll = function() {
         var scrollTop = $window.scrollTop();
         instances.forEach(function(inst) {
             inst.update(scrollTop);
         });
     }
 }

 var moveItItem = function(el) {
     this.el = $(el);
     this.speed = parseInt(this.el.attr('data-scroll-speed'));
     this.current_speed = 1.0;
 };

 moveItItem.prototype.update = function(scrollTop) {

     target_speed = parseInt(this.el.attr('data-scroll-speed'));
     current_speed = this.current_speed;
     speed_increments = parseFloat(this.el.attr('data-speed-increments'));

     if(increase_speed){
         if(current_speed < target_speed){
              current_speed += speed_increments;
         } else {
            current_speed = target_speed;
         }
     } else if(decrease_speed){
         if(current_speed > default_speed){
            current_speed -= speed_increments;
         }
         if($(window).scrollTop() === 0){
            current_speed = default_speed;
         }
     }
     this.current_speed = current_speed;
     var pos = scrollTop / this.current_speed;
     this.el.css('transform', 'translateY(' + -pos + 'px)');
 };

 // Initialization
 $(function() {
     $('[data-scroll-speed]').moveIt();
 });
</code>```

Body:
See an answer EXAMPLE HERE!

    //
// default speed ist the lowest valid scroll speed.
//
var default_speed = 1;
//
// speed increments defines the increase/decrease of the acceleration
// between current scroll speed and data-scroll-speed
//
var speed_increment = 0.01;
//
// maximum scroll speed of the elements
//
var data_scroll_speed_a = 4; // #sloganenglish
var data_scroll_speed_b = 5; // .slogan-a-line
//
//
//
var increase_speed, decrease_speed, target_speed, current_speed, speed_increments;
$(document).ready(function() {
     $(window).on('load resize scroll', function() {
         var WindowScrollTop = $(this).scrollTop(),
             Div_one_top = $('#image-ul').offset().top,
             Div_one_height = $('#image-ul').outerHeight(true),
             Window_height = $(this).outerHeight(true);
         if (WindowScrollTop + Window_height >= (Div_one_top + Div_one_height)) {
             $('#sloganenglish').attr('data-scroll-speed', data_scroll_speed_a).attr('data-current-scroll-speed', default_speed).attr('data-speed-increments', data_scroll_speed_a * speed_increment);
             $('.slogan-a-line').attr('data-scroll-speed', data_scroll_speed_b).attr('data-current-scroll-speed', default_speed).attr('data-speed-increments', data_scroll_speed_b * speed_increment);
             $('.slogan-a-line').css('color', 'yellow');
             increase_speed = true;
             decrease_speed = false;
         } else {
             $('#sloganenglish').attr('data-scroll-speed', '1').attr('data-current-scroll-speed', default_speed);
             $('.slogan-a-line').attr('data-scroll-speed', '1').attr('data-current-scroll-speed', default_speed);
             $('.slogan-a-line').css('color', 'red');
             decrease_speed = true;
             increase_speed = false;
         }
     }).scroll();
 });

 // data-scroll-speed script
 $.fn.moveIt = function() {
     var $window = $(window);
     var instances = [];

     $(this).each(function() {
         instances.push(new moveItItem($(this)));
     });

     window.onscroll = function() {
         var scrollTop = $window.scrollTop();
         instances.forEach(function(inst) {
             inst.update(scrollTop);
         });
     }
 }

 var moveItItem = function(el) {
     this.el = $(el);
     this.speed = parseInt(this.el.attr('data-scroll-speed'));
     this.current_speed = 1.0;
 };

 moveItItem.prototype.update = function(scrollTop) {

     target_speed = parseInt(this.el.attr('data-scroll-speed'));
     current_speed = this.current_speed;
     speed_increments = parseFloat(this.el.attr('data-speed-increments'));

     if(increase_speed){
         if(current_speed < target_speed){
              current_speed += speed_increments;
         } else {
            current_speed = target_speed;
         }
     } else if(decrease_speed){
         if(current_speed > default_speed){
            current_speed -= speed_increments;
         }
         if($(window).scrollTop() === 0){
            current_speed = default_speed;
         }
     }
     this.current_speed = current_speed;
     var pos = scrollTop / this.current_speed;
     this.el.css('transform', 'translateY(' + -pos + 'px)');
 };

 // Initialization
 $(function() {
     $('[data-scroll-speed]').moveIt();
 });


问:
using Imputer in scikit-learn
I need to fill the missing temperature value with the mean value of that month using Imputer() in scikit-learn.

First I split the dataframe into groups based on the month.  Then I called the imputer function to calculate the mean for that group and fill in the missing values.

Here is the code I wrote but it didn't work:

```<code>def impute_missing (data_1_group):
    imp = Imputer(missing_values='NaN', strategy='mean', axis=0)
    imp.fit(data_1_group)
    data_1_group=imp.transform(data_1_group['datetime'])
    return(data_1_group)

for data_1_group in data_1.groupby(pd.TimeGrouper("M")):
    impute_missing(data_1_group)
</code>```

Any suggestion?

答:
try this small change

imp=imp.fit(data_1_group['datetime'])
data_1_group=imp.transform(data_1_group['datetime'])

Though I m new to scikit myself, I am recommending the solution that worked for me. This is because

1) imp object needs to override to fit, as in the first line

2) it needs to fit and impute the same dataset, which in this case seems to be data_1_group['datetime']

I hope this helps

Title: using Imputer in scikit-learn

Body:
I need to fill the missing temperature value with the mean value of that month using Imputer() in scikit-learn.

First I split the dataframe into groups based on the month.  Then I called the imputer function to calculate the mean for that group and fill in the missing values.

Here is the code I wrote but it didn't work:

def impute_missing (data_1_group):
    imp = Imputer(missing_values='NaN', strategy='mean', axis=0)
    imp.fit(data_1_group)
    data_1_group=imp.transform(data_1_group['datetime'])
    return(data_1_group)

for data_1_group in data_1.groupby(pd.TimeGrouper("M")):
    impute_missing(data_1_group)

Any suggestion?


问:
Xamarin - Refresh list after PopAsync()
I am writing an application using Xamarin-forms. When I navigate away from my page which edits a list, using popAsync() , I want to refresh a list on the previous page so that my changes are shown.

my PopulateMachineSelectionList() adds my machine objects to the list.

This is what I've tried so far

```<code>    protected override void OnAppearing()
    {

        PopulateMachineSelectionList();
        base.OnAppearing();
    }

    async void PopulateMachineSelectionList()
    {
        loadedMachines = await machineSync.GetMachines();
        if (loadedMachines.Count() != 0)
        {
            machineSelectionList.Clear();

            foreach (Machine mach in loadedMachines)
            { //I have an archive boolean that determines whether or not machines should be shown
                if (!mach.archived)
                {
                    Console.WriteLine("Adding: " + mach.name + " to the list template");
                    machineSelectionList.Add(new ListTemplate(null, mach.name, true, true));
                }
            }
            Console.WriteLine("Refresh List");
            machineList.ItemsSource = machineSelectionList;

        }
        machineList.SelectedItem = null;

    }
</code>```

答:
Try something like, the following code:

```<code>machineList.ItemsSource.Clear();
machineList.ItemsSource.Add(machineSelectionList);
</code>```

Possibly this will trigger, the propertychanged Event.

Title: Xamarin - Refresh list after PopAsync()

Body:
I am writing an application using Xamarin-forms. When I navigate away from my page which edits a list, using popAsync() , I want to refresh a list on the previous page so that my changes are shown.

my PopulateMachineSelectionList() adds my machine objects to the list.

This is what I've tried so far

    protected override void OnAppearing()
    {

        PopulateMachineSelectionList();
        base.OnAppearing();
    }

    async void PopulateMachineSelectionList()
    {
        loadedMachines = await machineSync.GetMachines();
        if (loadedMachines.Count() != 0)
        {
            machineSelectionList.Clear();

            foreach (Machine mach in loadedMachines)
            { //I have an archive boolean that determines whether or not machines should be shown
                if (!mach.archived)
                {
                    Console.WriteLine("Adding: " + mach.name + " to the list template");
                    machineSelectionList.Add(new ListTemplate(null, mach.name, true, true));
                }
            }
            Console.WriteLine("Refresh List");
            machineList.ItemsSource = machineSelectionList;

        }
        machineList.SelectedItem = null;

    }

Body:
Try something like, the following code:

machineList.ItemsSource.Clear();
machineList.ItemsSource.Add(machineSelectionList);

Possibly this will trigger, the propertychanged Event.


问:
sql : how to find duplicates rows?
i got a table users (id,first_name,last_name,...)
i want to find duplicate users in that table (users which has the same first_name AND the same last_name).

let's say my data is :

```<code> 1;bill;campton
 2;sarah;connor
 3;bill;campton
</code>```

i need to get

```<code>  1;bill;campton;3;bill;campton
</code>```

i dont want to get

```<code>  1;bill;campton;3;bill;campton
  3;bill;campton;1;bill;campton
</code>```

How could i do that?
I use SQL Server 2005

thank you

答:
One way

```<code>select first_name, last_name
from table
group by first_name, last_name
having count(*) > 1
</code>```

If you want also the IDs then you can do this

```<code> SELECT t1.*
 FROM table t1
 join
 (select first_name, last_name
from table
group by first_name, last_name
having count(*) > 1) x ON t1.last_name = x.last_name
AND t1.first_name = x.first_name
</code>```

Title: sql : how to find duplicates rows?

Body:
i got a table users (id,first_name,last_name,...)
i want to find duplicate users in that table (users which has the same first_name AND the same last_name).

let's say my data is :

 1;bill;campton
 2;sarah;connor
 3;bill;campton

i need to get

  1;bill;campton;3;bill;campton

i dont want to get

  1;bill;campton;3;bill;campton
  3;bill;campton;1;bill;campton

How could i do that?
I use SQL Server 2005

thank you

Body:
One way

select first_name, last_name
from table
group by first_name, last_name
having count(*) > 1

If you want also the IDs then you can do this

 SELECT t1.*
 FROM table t1
 join
 (select first_name, last_name
from table
group by first_name, last_name
having count(*) > 1) x ON t1.last_name = x.last_name
AND t1.first_name = x.first_name


答:
Yes, you can create a custom filter, like the one below. I'm currently using it for the same situation :)

```<code>(function() {
'use strict';

angular
    .module('myApp')
    .filter('tableFilter', tableFilter);

function tableFilter() {
    // Just add arguments to your HTML separated by :
    // And add them as parameters here, for example:

    return function (dataArray, searchTerm) {
        // If no array is given, exit.
        if (!dataArray) {
            return;
        }
        // If no search term exists, return the array unfiltered.
        else if (!searchTerm) {
            return dataArray;
        }
        // Otherwise, continue.
        else {
            // Convert filter text to lower case.
            var term = searchTerm.toLowerCase();
            // Return the array and filter it by looking for any occurrences of the search term in each items firstName or lastName.
            return dataArray.filter(function (object) {
                var termInFirstName = object.firstName.toLowerCase().indexOf(term) > -1;
                var termInLastName = object.lastName.toLowerCase().indexOf(term) > -1;
                return termInFirstName || termInLastName;
            });
        }
    }
  }
})();
</code>```

then, you can simply use it like this in your html :

```<code><div ng-controller="MyCtrl">
    <input type="text" ng-model="search">{{search}}
    <table border="1">
        <tr ng-repeat="row in list | tableFilter:search">
            <td>{{row.firstName}} {{row.lastName}}</td>
        </tr>
    </table>
</div>
</code>```

Hope it helps :)

Title: ng-repeat filter either equals to first name or last name

Body:
Yes, you can create a custom filter, like the one below. I'm currently using it for the same situation :)

(function() {
'use strict';

angular
    .module('myApp')
    .filter('tableFilter', tableFilter);

function tableFilter() {
    // Just add arguments to your HTML separated by :
    // And add them as parameters here, for example:

    return function (dataArray, searchTerm) {
        // If no array is given, exit.
        if (!dataArray) {
            return;
        }
        // If no search term exists, return the array unfiltered.
        else if (!searchTerm) {
            return dataArray;
        }
        // Otherwise, continue.
        else {
            // Convert filter text to lower case.
            var term = searchTerm.toLowerCase();
            // Return the array and filter it by looking for any occurrences of the search term in each items firstName or lastName.
            return dataArray.filter(function (object) {
                var termInFirstName = object.firstName.toLowerCase().indexOf(term) > -1;
                var termInLastName = object.lastName.toLowerCase().indexOf(term) > -1;
                return termInFirstName || termInLastName;
            });
        }
    }
  }
})();

then, you can simply use it like this in your html :

<div ng-controller="MyCtrl">
    <input type="text" ng-model="search">{{search}}
    <table border="1">
        <tr ng-repeat="row in list | tableFilter:search">
            <td>{{row.firstName}} {{row.lastName}}</td>
        </tr>
    </table>
</div>

Hope it helps :)


问:
Passing method to lodash with vue gives 'Expected a function'
I am trying to pass a Vue function to the lodash throttle method. Shouldn't I just be able to do something like this?

When I am trying to do this I am getting the following error:

Error in callback for watcher "query": "TypeError: Expected a function"

Watcher

```<code>watch: {
    query() {
        throttle(this.autocomplete(), 400);
    }
}
</code>```

Methods

```<code>methods: {
    autocomplete() {}
}
</code>```

Even though I am passing a function reference I am still getting an error message. If I wrap it with a anonymous function it won't fire:

```<code>throttle(() => { this.autocomplete(); }, 400);
</code>```

I just checked and the autocomplete function does actually seem to fire regardless of the error that it is not a function in my example at the top.

What is going wrong here?

Edit:

Jsfiddle: http://jsfiddle.net/yMv7y/2780/

答:
You are passing the return value of this.autocomplete() (maybe undefined) and not the function reference. If you want to do the latter, you have to omit the brackets:

```<code>watch: {
    query() {
        throttle(this.autocomplete, 400);
    }
}
</code>```

Body:
I am trying to pass a Vue function to the lodash throttle method. Shouldn't I just be able to do something like this?

When I am trying to do this I am getting the following error:

Error in callback for watcher "query": "TypeError: Expected a function"

Watcher

watch: {
    query() {
        throttle(this.autocomplete(), 400);
    }
}

Methods

methods: {
    autocomplete() {}
}

Even though I am passing a function reference I am still getting an error message. If I wrap it with a anonymous function it won't fire:

throttle(() => { this.autocomplete(); }, 400);

I just checked and the autocomplete function does actually seem to fire regardless of the error that it is not a function in my example at the top.

What is going wrong here?

Edit:

Jsfiddle: http://jsfiddle.net/yMv7y/2780/

Body:
You are passing the return value of this.autocomplete() (maybe undefined) and not the function reference. If you want to do the latter, you have to omit the brackets:

watch: {
    query() {
        throttle(this.autocomplete, 400);
    }
}


问:
Indeterminate ProgressBar animation jerk in Dispatcher.BeginInvoke
I have a piece of code testing the GUI and threading behavior. I want to keep ProgressBar animation running (with IsIndeterminate="True") as I query the database and add a large number of rows (10K+) into the DataGrid. Even if I wrap the database and GUI code in Dispatcher.BeginInvoke, the ProgressBar animation would jerk as the DataGrid is being filled.

I would expect the ProgressBar animation would either freeze (if on GUI thread) or run smoothly (if on a separately thread), but I cannot understand why the animation is running jerkingly.

Please do not suggest BackgroundWorker, as I want to understand the problem in this question, and why BeginInvoke is not separating the threads. I simply loop through SqlDataReader and add to DataGrid as Item one by one instead of databinding to a source or a datatable.

```<code>// XAML
<Button Click="Button_Click"></Button>
<ProgressBar IsIndeterminate="True"></ProgressBar>
<DataGrid ... ></DataGrid>

// C#
private void Button_Click(object sendoer, RoutedEventArgs e)
{
    this.Dispatcher.BeginInvoke(DispatcherPriority.Normal,(ThreadStart)delegate()
    {
        // Query database and update GUI (e.g. DataGrid)
    });
}
</code>```

答:
The Dispatcher always executes code on the thread it is associated with (the UI thread in your case), regardless of whether you use Invoke or InvokeAsync (which is a convenient shorthand for BeginInvoke). So all the work regarding loading data from database and updating the DataGrid is done on UI thread, hence the animation is not smooth.

The difference between Invoke and InvokeAsync is that the former is executed synchronously, and the latter is executed asynchronously. What it means is that in the first case the calling thread will be suspended until the delegate has finished executing (i.e. it will be synchronized), whereas in the second case the thread will continue its execution without waiting for the delegate to finish. Let me try to point out this difference using examples.

Example I. The methods are called from the UI thread (as in your case)

Let's assume we only have one thread (the UI thread). Calling Invoke will not have any noticeable effect, since the delegate will be executed immediately and only then the execution will continue. So this:

```<code>Dispatcher.Invoke(() => DoSomeStuff());
DoSomeOtherStuff();
</code>```

will have the same effect as this:

```<code>DoSomeStuff();
DoSomeOtherStuff();
</code>```

Calling BeginInvoke however will have an effect such that the delegate will be scheduled to execute only after all scheduled tasks with higher priority (or already scheduled with the same priority) are executed. So in this case:

```<code>Dispatcher.InvokeAsync(() => DoSomeStuff());
DoSomeOtherStuff();
</code>```

DoSomeOtherStuff() will be executed first, and DoSomeStuff() second. This is often used for example in event handlers where you need some code to be executed only after the event is completely handled (e.g. see this question).

Example II. The methods are called from a different thread

Let's assume we have two threads - the UI thread, and a worker thread. If we call Invoke from the worker thread:

```<code>Dispatcher.Invoke(() => DoSomeStuff());
DoSomeOtherStuff();
</code>```

first DoSomeStuff() will be executed on UI thread, and then DoSomeOtherStuff() will be executed on worker thread. In case of InvokeAsync:

```<code>Dispatcher.InvokeAsync(() => DoSomeStuff());
DoSomeOtherStuff();
</code>```

we only know that DoSomeStuff() will be executed on UI thread and DoSomeOtherStuff() will be executed on worker thread, but the order in which they will be executed is indeterminate*.

Usually Invoke is used when your delegate yields some result and you need it to continue execution on the worker thread (for example when you need to obtain a dependency property value). InvokeAsync on the other hand is usually used when the delegate does not yield any result (or the result is ignored), such as in your case - updating DataGrid does not yield any result worth waiting for so you can immediately continue to load the next batch of data.

I hope that sheds some light on the issue for you and you can see why the solution to "jerky UI" is to delegate heavy work to another thread and only use dispatcher to interact with UI. That's were suggestions to use BackgroundWorker or Task come from.

*Actually they probably will be executed simultaneously. What I meant was if for example both methods only print some text to console, the order of messages in the console is indeterminate.

Body:
I have a piece of code testing the GUI and threading behavior. I want to keep ProgressBar animation running (with IsIndeterminate="True") as I query the database and add a large number of rows (10K+) into the DataGrid. Even if I wrap the database and GUI code in Dispatcher.BeginInvoke, the ProgressBar animation would jerk as the DataGrid is being filled.

I would expect the ProgressBar animation would either freeze (if on GUI thread) or run smoothly (if on a separately thread), but I cannot understand why the animation is running jerkingly.

Please do not suggest BackgroundWorker, as I want to understand the problem in this question, and why BeginInvoke is not separating the threads. I simply loop through SqlDataReader and add to DataGrid as Item one by one instead of databinding to a source or a datatable.

// XAML
<Button Click="Button_Click"></Button>
<ProgressBar IsIndeterminate="True"></ProgressBar>
<DataGrid ... ></DataGrid>

// C#
private void Button_Click(object sendoer, RoutedEventArgs e)
{
    this.Dispatcher.BeginInvoke(DispatcherPriority.Normal,(ThreadStart)delegate()
    {
        // Query database and update GUI (e.g. DataGrid)
    });
}

Body:
The Dispatcher always executes code on the thread it is associated with (the UI thread in your case), regardless of whether you use Invoke or InvokeAsync (which is a convenient shorthand for BeginInvoke). So all the work regarding loading data from database and updating the DataGrid is done on UI thread, hence the animation is not smooth.

The difference between Invoke and InvokeAsync is that the former is executed synchronously, and the latter is executed asynchronously. What it means is that in the first case the calling thread will be suspended until the delegate has finished executing (i.e. it will be synchronized), whereas in the second case the thread will continue its execution without waiting for the delegate to finish. Let me try to point out this difference using examples.

Example I. The methods are called from the UI thread (as in your case)

Let's assume we only have one thread (the UI thread). Calling Invoke will not have any noticeable effect, since the delegate will be executed immediately and only then the execution will continue. So this:

Dispatcher.Invoke(() => DoSomeStuff());
DoSomeOtherStuff();

will have the same effect as this:

DoSomeStuff();
DoSomeOtherStuff();

Calling BeginInvoke however will have an effect such that the delegate will be scheduled to execute only after all scheduled tasks with higher priority (or already scheduled with the same priority) are executed. So in this case:

Dispatcher.InvokeAsync(() => DoSomeStuff());
DoSomeOtherStuff();

DoSomeOtherStuff() will be executed first, and DoSomeStuff() second. This is often used for example in event handlers where you need some code to be executed only after the event is completely handled (e.g. see this question).

Example II. The methods are called from a different thread

Let's assume we have two threads - the UI thread, and a worker thread. If we call Invoke from the worker thread:

Dispatcher.Invoke(() => DoSomeStuff());
DoSomeOtherStuff();

first DoSomeStuff() will be executed on UI thread, and then DoSomeOtherStuff() will be executed on worker thread. In case of InvokeAsync:

Dispatcher.InvokeAsync(() => DoSomeStuff());
DoSomeOtherStuff();

we only know that DoSomeStuff() will be executed on UI thread and DoSomeOtherStuff() will be executed on worker thread, but the order in which they will be executed is indeterminate*.

Usually Invoke is used when your delegate yields some result and you need it to continue execution on the worker thread (for example when you need to obtain a dependency property value). InvokeAsync on the other hand is usually used when the delegate does not yield any result (or the result is ignored), such as in your case - updating DataGrid does not yield any result worth waiting for so you can immediately continue to load the next batch of data.

I hope that sheds some light on the issue for you and you can see why the solution to "jerky UI" is to delegate heavy work to another thread and only use dispatcher to interact with UI. That's were suggestions to use BackgroundWorker or Task come from.

*Actually they probably will be executed simultaneously. What I meant was if for example both methods only print some text to console, the order of messages in the console is indeterminate.


问:
Firebase Cloud Messaging using Web API C#
I am referencing from the following link to achieve push notification, but how can I get the device Id? I put my mobile MMID as device ID but it's not working. Do I need to register my android mobile on firebase or need to install firebase package to get the registerID?

Send push to Android by C# using FCM (Firebase Cloud Messaging)

Any suggestions would be appreciated.

答:
The deviceId refers to the Registration Token:

An ID generated by the FCM SDK for each client app instance. Required for single device and device group messaging. Note that registration tokens must be kept secret.

which is generated on the client side, in your case, Android. You'll have to Setup your Android App to generate the token and receive messages. Also see the possible duplicate post.


问:
Ruby on Rails - Nested Devise form validations
guys!

I have an Customer form with an nested User form (I'm using Devise) where you can add as many users you want.

When I have to edit only the customer I don't know how to skip an user password validation (when I have a form with only 1 user I just use the method update_without_password).

Do you guys have any clue?

Thanks a lot!

答:
In customer model you must have something like:

```<code>validates_associated :user
</code>```

Try changing it to:

```<code>validates_associated :user,on: :create
</code>```

Body:
In customer model you must have something like:

validates_associated :user

Try changing it to:

validates_associated :user,on: :create


问:
Importing txt file with missing values with numpy
I have the following form of a txt file:

Notice that some of the fields are completely missing, but the fact that they are missing is important. In the attached image all the measurements are missing due to technical failure but it can happen that value in only one of the columns is missing while the others are given.

I am trying to import such .txt file with the following code.

```<code>import numpy as np
data=np.genfromtxt(filepath, skip_header=1, invalid_raise=False, usecols=(2, 3, 4, 5, 6, 7))
</code>```

Which results in an error:

Line #2123 (got 2 columns instead of 6)

Line #3171 (got 2 columns instead of 6)

Line #3172 (got 2 columns instead of 6)

but still produces some usable result. As I said, the fact that the data at 13:30 is missing is important and can't be simply ignored. However, the above code does exactly that - ignores/skips the row at 13:30. Instead I would like it to fill that row with some predefined value or just denote it in some other way that can be identified later in the processing.

Any way to do that?

答:
np.genfromtxt() takes the argument missing_values. If you set it to:

```<code>data=np.genfromtxt(filepath, skip_header=1, invalid_raise=False, usecols=(2,3, 4, 5, 6, 7), missing_value=???)
</code>```

it should replace missing values by nans. But notice that there has to be a filler if this should work. Otherwise you may use the usecols argument in that way that you first chose your cols with missing values and seperate them from the main data. Afterwards you could merge them again. A second very good approach of dealing with missing values is the use of pandas.read_csv() instead. Furthermore, its much faster than np.genfromtxt.

Body:
I have the following form of a txt file:

Notice that some of the fields are completely missing, but the fact that they are missing is important. In the attached image all the measurements are missing due to technical failure but it can happen that value in only one of the columns is missing while the others are given.

I am trying to import such .txt file with the following code.

import numpy as np
data=np.genfromtxt(filepath, skip_header=1, invalid_raise=False, usecols=(2, 3, 4, 5, 6, 7))

Which results in an error:

Line #2123 (got 2 columns instead of 6)

Line #3171 (got 2 columns instead of 6)

Line #3172 (got 2 columns instead of 6)

but still produces some usable result. As I said, the fact that the data at 13:30 is missing is important and can't be simply ignored. However, the above code does exactly that - ignores/skips the row at 13:30. Instead I would like it to fill that row with some predefined value or just denote it in some other way that can be identified later in the processing.

Any way to do that?

Body:
np.genfromtxt() takes the argument missing_values. If you set it to:

data=np.genfromtxt(filepath, skip_header=1, invalid_raise=False, usecols=(2,3, 4, 5, 6, 7), missing_value=???)

it should replace missing values by nans. But notice that there has to be a filler if this should work. Otherwise you may use the usecols argument in that way that you first chose your cols with missing values and seperate them from the main data. Afterwards you could merge them again. A second very good approach of dealing with missing values is the use of pandas.read_csv() instead. Furthermore, its much faster than np.genfromtxt.


问:
Attaching click event won't work
I've wanted to attach click event to an object not yet added to the DOM like here.

I've used a code from the answer but nothing happens when I click anything.

Here's my HTML:

```<code><html>
<head>
<script src="resources/js/components/jquery/jquery-3.1.1.min.js"></script>
<script src="file.js"></script>
</head>
<body>
    <a href="#">asl;kdfjl</a>
    <div id="my-button">sdgdf</div>
</body>
</html>
</code>```

JavaScripts are in those location and I can see them in Sources tab in Chrome.

My file.js has content exactly copy-pasted from jsfiddle:

```<code>$('body').on('click','a',function(e){
    e.preventDefault();
    createMyButton();
});

createMyButton = function(data) {
    $('a').after('<div id="my-button">test</div>');
};

$('body').on('click','#my-button',function (e) {
      alert("yeahhhh!!! but this doesn't work for me :(");
});
</code>```

答:
As your code is in the head tag, you need to use a DOM ready wrapper to ensure your code executes after the DOM has rendered elements.

The jsfiddle doesn't have it because the fiddle is set to run the code onload already.

```<code>$(function(){
    $('body').on('click','a',function(e){
        e.preventDefault();
        createMyButton();
    });

    createMyButton = function(data) {
        $('a').after('<div id="my-button">test</div>');
    };

    $('body').on('click','#my-button',function (e) {
         alert("yeahhhh!!! but this doesn't work for me :(");
    });
});
</code>```

Title: Attaching click event won't work

Body:
I've wanted to attach click event to an object not yet added to the DOM like here.

I've used a code from the answer but nothing happens when I click anything.

Here's my HTML:

    asl;kdfjl

sdgdf

JavaScripts are in those location and I can see them in Sources tab in Chrome.

My file.js has content exactly copy-pasted from jsfiddle:

$('body').on('click','a',function(e){
    e.preventDefault();
    createMyButton();
});

createMyButton = function(data) {
    $('a').after('
test
');
};

$('body').on('click','#my-button',function (e) {
      alert("yeahhhh!!! but this doesn't work for me :(");
});

Body:
As your code is in the head tag, you need to use a DOM ready wrapper to ensure your code executes after the DOM has rendered elements.

The jsfiddle doesn't have it because the fiddle is set to run the code onload already.

$(function(){
    $('body').on('click','a',function(e){
        e.preventDefault();
        createMyButton();
    });

    createMyButton = function(data) {
        $('a').after('<div id="my-button">test</div>');
    };

    $('body').on('click','#my-button',function (e) {
         alert("yeahhhh!!! but this doesn't work for me :(");
    });
});


问:
scraping website with login page
I currently login to the time from website using the following script.

```<code>browser = webdriver.Chrome('E:/Shared Folders/Users/runnerjp/chromedriver/chromedriver.exe')
browser.get("https://www.timeform.com/horse-racing/account/sign-in?returnUrl=%2Fhorse-racing%2F")
time.sleep(3)
username = browser.find_element_by_id("EmailAddress")
password = browser.find_element_by_id("Password")
username.send_keys("usr")
password.send_keys("pass")
login_attempt = browser.find_element_by_xpath("//input[@type='submit']")
time.sleep(3)
login_attempt.submit()
</code>```

it works but I find using Chrome web driver is hammering my CPU. Is there an alternative code I could use that does not mean I need to physically load the page to sign in?

答:
Use requests instead. You can use it to log in:

```<code>import requests
requests.get('https://api.github.com/user', auth=('user', 'pass'))
</code>```

More information here:
http://docs.python-requests.org/en/master/user/authentication/

Title: scraping website with login page

Body:
I currently login to the time from website using the following script.

browser = webdriver.Chrome('E:/Shared Folders/Users/runnerjp/chromedriver/chromedriver.exe')
browser.get("https://www.timeform.com/horse-racing/account/sign-in?returnUrl=%2Fhorse-racing%2F")
time.sleep(3)
username = browser.find_element_by_id("EmailAddress")
password = browser.find_element_by_id("Password")
username.send_keys("usr")
password.send_keys("pass")
login_attempt = browser.find_element_by_xpath("//input[@type='submit']")
time.sleep(3)
login_attempt.submit()

it works but I find using Chrome web driver is hammering my CPU. Is there an alternative code I could use that does not mean I need to physically load the page to sign in?

Body:
Use requests instead. You can use it to log in:

import requests
requests.get('https://api.github.com/user', auth=('user', 'pass'))

More information here:
http://docs.python-requests.org/en/master/user/authentication/


问:
How can I send stuff commands to a start-in-detached screen?
Any session that I start with "-d -m" doesn't accept "-X stuff [...]" commands unless I've attached to the screen at least once.  There is no error message, the commands just do not get through.

The problem is that I start the session from a cron job and am unable to attach to the screen from within cron.

Steps to repeat

```<code>$ screen -m -d -S mydaemon bash
$ screen -S mydaemon -X stuff "`printf "exit\\r"`"
$ screen -ls
        32456.mydaemon  (Detached)
$ screen -r -S mydaemon
$ ^a d
$ screen -S mydaemon -X stuff "`printf "exit\\r"`"
$ screen -ls
No Sockets found in /var/run/screen/S-user
</code>```

^a d indicates pressing Ctrl+a then pressing d.

Versions

```<code>CentOS release 5.5 (Final)
Screen version 4.00.03 (FAU) 23-Oct-06
</code>```

答: Have you considered using tmux instead? It is much more suitable for non-interactive tasks.

Body:
Any session that I start with "-d -m" doesn't accept "-X stuff [...]" commands unless I've attached to the screen at least once.  There is no error message, the commands just do not get through.

The problem is that I start the session from a cron job and am unable to attach to the screen from within cron.

Steps to repeat

$ screen -m -d -S mydaemon bash
$ screen -S mydaemon -X stuff "`printf "exit\\r"`"
$ screen -ls
        32456.mydaemon  (Detached)
$ screen -r -S mydaemon
$ ^a d
$ screen -S mydaemon -X stuff "`printf "exit\\r"`"
$ screen -ls
No Sockets found in /var/run/screen/S-user

^a d indicates pressing Ctrl+a then pressing d.

Versions

CentOS release 5.5 (Final)
Screen version 4.00.03 (FAU) 23-Oct-06


问:
Saving scroll state of NestedScrollView
My application revolves around a HomeActivity which contains 4 tabs at the bottom. Each of these tabs is a fragment, all of them are added (not replaced) from the start, and they are hidden/shown upon tapping the appropriate tab.

My problem is that whenever I change tab, the state of my scroll is lost. Each fragment which exhibits that issue uses a android.support.v4.widget.NestedScrollView (see below for an example).

Note: My fragments that use a RecyclerView or ListView keep their scroll state for some reason.

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <include layout="@layout/include_appbar_title" />

    <android.support.v4.widget.NestedScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <!-- Content -->

    </android.support.v4.widget.NestedScrollView>

</LinearLayout>
</code>```

I read several posts regarding saving the instance state (this one, that one for example), and their solution either don't work in my scenario, or are not practical to implement given I have 4-12 different fragments I'd need to modify to make it work.

What is the best way to have a Nested Scroll View keep its scroll position on fragment changes ?

答:
One solution I found on inthecheesefactory is that fragments, by default, have their state saved (from the input in a EditText, to the scroll position), but ONLY if an ID is given to the xml element.

In my case, just adding an ID to my NestedScrollView fixed the problem:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <include layout="@layout/include_appbar_title" />

    <android.support.v4.widget.NestedScrollView
        android:id="@+id/NestedScrollView"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <!-- Content -->

    </android.support.v4.widget.NestedScrollView>

</LinearLayout>
</code>```

Title: Saving scroll state of NestedScrollView

Body:
My application revolves around a HomeActivity which contains 4 tabs at the bottom. Each of these tabs is a fragment, all of them are added (not replaced) from the start, and they are hidden/shown upon tapping the appropriate tab.

My problem is that whenever I change tab, the state of my scroll is lost. Each fragment which exhibits that issue uses a android.support.v4.widget.NestedScrollView (see below for an example).

Note: My fragments that use a RecyclerView or ListView keep their scroll state for some reason.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <include layout="@layout/include_appbar_title" />

    <android.support.v4.widget.NestedScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    </android.support.v4.widget.NestedScrollView>

</LinearLayout>

I read several posts regarding saving the instance state (this one, that one for example), and their solution either don't work in my scenario, or are not practical to implement given I have 4-12 different fragments I'd need to modify to make it work.

What is the best way to have a Nested Scroll View keep its scroll position on fragment changes ?

Body:
One solution I found on inthecheesefactory is that fragments, by default, have their state saved (from the input in a EditText, to the scroll position), but ONLY if an ID is given to the xml element.

In my case, just adding an ID to my NestedScrollView fixed the problem:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <include layout="@layout/include_appbar_title" />

    <android.support.v4.widget.NestedScrollView
        android:id="@+id/NestedScrollView"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <!-- Content -->

    </android.support.v4.widget.NestedScrollView>

</LinearLayout>


问:
use rails button in form as link
I have a table with sliders (part of a form) in one column and a button (link to other page)

```<code><button onclick="location.href='/main';">
   <i class="icon icon-078-settings icon--s2" aria-hidden="true"></i>
</button>
</code>```

Instead of opening the page, the button just submits the form. Any way I can fix this without breaking the table or the form?

答:
Instead of opening the page, the button just submits the form.

Yes! Buttons are meant to perform actions that effects on front-end or back-end, they are not meant for navigation. You should use links(a.k.a anchors) to perform navigation.

```<code><a href='/main'>
  <i class="icon icon-078-settings icon--s2" aria-hidden="true"></i>
</a>
</code>```

Title: use rails button in form as link

Body:
I have a table with sliders (part of a form) in one column and a button (link to other page)

<button onclick="location.href='/main';">

</button>

Instead of opening the page, the button just submits the form. Any way I can fix this without breaking the table or the form?

Body:
Instead of opening the page, the button just submits the form.

Yes! Buttons are meant to perform actions that effects on front-end or back-end, they are not meant for navigation. You should use links(a.k.a anchors) to perform navigation.

<a href='/main'>
  <i class="icon icon-078-settings icon--s2" aria-hidden="true"></i>
</a>


问:
MVC ViewModel HttpPost return value has null values
I spent some time on this problem. I'm passing a ViewModel back from my View to the Controller via a form HttpPost. However, only SelectedItemId has value. Users and Rights are null.

View model UserRightViewModel

```<code>public class UserRightViewModel
{
    public string SelectedItemId { get; set; }

    public SelectList Users;

    public List<RightViewModel> Rights { get; set; }
}
</code>```

View model RightsViewModel

```<code>public class RightsViewModel
{
    public int ID { get; set; }

    public string Name{ get; set; }

    public bool isSelected { get; set; }
}
</code>```

Controller Post

```<code>[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Index(UserRightsViewModel _viewModel)
{
   UserRightsViewModel viewModel = _viewModel;
   /*value _viewModel = null for Users and Rights
   /* code stuff */
   return View(viewModel);
}
</code>```

View

```<code>@model Web.ViewModels.UserRightsViewModel
     @using (Html.BeginForm())
     {
         @Html.AntiForgeryToken()

    <div class="content-wrapper">
        <!-- Content Header (Page header) -->
        <section class="content-header">
            <h1>
                @ViewBag.Title
            </h1>
            @*<ol class="breadcrumb">
                    <li><a href="#"><i class="fa fa-dashboard"></i> Home</a></li>
                    <li><a href="#">Examples</a></li>
                    <li class="active">Blank page</li>
                </ol>*@
        </section>

        <!-- Main content -->
        <section class="content">

            <!-- Default box -->
            <div class="box">
                <div class="box-header with-border">

                    <div class="box-tools pull-right">
                        <button type="button" class="btn btn-box-tool" data-widget="collapse" data-toggle="tooltip" title="Collapse">
                            <i class="fa fa-minus"></i>
                        </button>
                        <button type="button" class="btn btn-box-tool" data-widget="remove" data-toggle="tooltip" title="Remove">
                            <i class="fa fa-times"></i>
                        </button>
                    </div>
                </div>

        <br />
                <div class="form-group">
                    @Html.LabelFor(model => model.SelectedItemId, "User", new { @class = "control-label col-md-2" })
                    <div class="col-md-10">
                        @Html.DropDownListFor(m => m.SelectedItemId, Model.Users, new { onchange = "redirect(this.value)", @class = "form-control" })
                        @Html.ValidationMessageFor(model => model.SelectedItemId)
                    </div>
                </div>
                <br />

          <div class="box-body">

                    @for (int i = 0; i < Model.Rights.Count(); i += 2)
                    {
                        <div class="row form-group">
                            <div class="col-md-6">
                                <div class="row">
                                    <div class="col-md-4">
                                        <div class="col-md-6">

                                        </div>
                                        <div class="col-md-6">
                                            @Html.CheckBoxFor(model => model.Rights.ElementAt(i).isSelected, new { @class = "checkbox checkbox-center" })
                                            @Html.ValidationMessageFor(model => model.Rights.ElementAt(i).isSelected, "", new { @class = "text-danger" })
                                        </div>
                                    </div>
                                    <div class="col-md-8">

                                        @Model.Rights.ElementAt(i).Denumire
                                    </div>
                                </div>

                            </div>
                            <div class="col-md-6">
                                <div class="row">
                                    <div class="col-md-4">
                                        <div class="col-md-6">

                                        </div>
                                        <div class="col-md-6">
                                            @Html.CheckBoxFor(model => model.Rights.ElementAt(i + 1).isSelected, new { @class = "checkbox checkbox-center" })
                                            @Html.ValidationMessageFor(model => model.Rights.ElementAt(i + 1).isSelected, "", new { @class = "text-danger" })
                                        </div>
                                    </div>
                                    <div class="col-md-8">
                                        @Model.Rights.ElementAt(i + 1).Name
                                    </div>
                                </div>
                            </div>
                        </div>

                    }
                    <br />
                    <br />
                    <div class="form-group">
                        <div class="row">
                            <div class="col-md-6">
                                <div class="col-md-9">

                                </div>
                                <div class="col-md-3">
                                    <input type="submit" value="Save" class="btn btn-primary" />
                                </div>
                            </div>
                            <div class="col-md-6">
                                @Html.ActionLink("Cancel", "Index", null, new { @class = "btn btn-danger" })
                            </div>
                        </div>
                    </div>
                </div>
               </div>
        </section>
    </div>
}
</code>```

I have no idea why some values are null. Why some of values are sent and some not?

答:
Users is null because your not (and nor should you) creating and input for each property of each SelectListItem in the SelectList (if you need to return the view you re-populate the value in the POST method). And in any case, its a field, not a property (has no { get; set; }) so the DefaultModelBinder cannot set it).

Rights is null because you cannot use .ElementAt() to generate form controls for a collection (inspect the html your generating and you will see that the name attributes have no relationship to your model). The name attributes need to be

```<code><input name="Rights[0].ID" ... />
<input name="Rights[0].Name" ... />
<input name="Rights[0].isSelected" ... />
<input name="Rights[1].ID" ... />
<input name="Rights[1].Name" ... />
<input name="Rights[1].isSelected" ... />
....
</code>```

Note that your only generating a for control for the isSelected property which on its own would be meaningless in the POST method and you will an least want to include a hidden input for the ID property.

It appears from your code that you want to generate a 2 column layout, in which case your code should be (simplified)

```<code><div class="row form-group">
    @for(int i = 0; i < Model.Rights.Count; i++)
    {
        <div class="col-md-6">
            @Html.HiddenFor(m => m.Rights[0].ID)
            @Html.CheckBoxFor(m => m.Rights[0].isSelected)
        </div>
        // End current 'row' and start a new one every 2nd item
        if ((i + 1) % 2 == 0)
        {
            @:</div><div class="row form-group">
        }
    }
</div>
</code>```

Body:
I spent some time on this problem. I'm passing a ViewModel back from my View to the Controller via a form HttpPost. However, only SelectedItemId has value. Users and Rights are null.

View model UserRightViewModel

public class UserRightViewModel
{
    public string SelectedItemId { get; set; }

    public SelectList Users;

    public List<RightViewModel> Rights { get; set; }
}

View model RightsViewModel

public class RightsViewModel
{
    public int ID { get; set; }

    public string Name{ get; set; }

    public bool isSelected { get; set; }
}

Controller Post

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Index(UserRightsViewModel _viewModel)
{
   UserRightsViewModel viewModel = _viewModel;
   /*value _viewModel = null for Users and Rights
   /* code stuff */
   return View(viewModel);
}

View

@model Web.ViewModels.UserRightsViewModel
     @using (Html.BeginForm())
     {
         @Html.AntiForgeryToken()

                @ViewBag.Title

            @*

 Home

Examples

Blank page

*@

                        <button type="button" class="btn btn-box-tool" data-widget="collapse" data-toggle="tooltip" title="Collapse">

                        </button>
                        <button type="button" class="btn btn-box-tool" data-widget="remove" data-toggle="tooltip" title="Remove">

                        </button>

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

                        @Html.DropDownListFor(m => m.SelectedItemId, Model.Users, new { onchange = "redirect(this.value)", @class = "form-control" })
                        @Html.ValidationMessageFor(model => model.SelectedItemId)

                    @for (int i = 0; i < Model.Rights.Count(); i += 2)
                    {

                                            @Html.CheckBoxFor(model => model.Rights.ElementAt(i).isSelected, new { @class = "checkbox checkbox-center" })
                                            @Html.ValidationMessageFor(model => model.Rights.ElementAt(i).isSelected, "", new { @class = "text-danger" })

                                        @Model.Rights.ElementAt(i).Denumire

                                            @Html.CheckBoxFor(model => model.Rights.ElementAt(i + 1).isSelected, new { @class = "checkbox checkbox-center" })
                                            @Html.ValidationMessageFor(model => model.Rights.ElementAt(i + 1).isSelected, "", new { @class = "text-danger" })

                                        @Model.Rights.ElementAt(i + 1).Name

                    }

                                    <input type="submit" value="Save" class="btn btn-primary" />

                                @Html.ActionLink("Cancel", "Index", null, new { @class = "btn btn-danger" })

}

I have no idea why some values are null. Why some of values are sent and some not?

Body:
Users is null because your not (and nor should you) creating and input for each property of each SelectListItem in the SelectList (if you need to return the view you re-populate the value in the POST method). And in any case, its a field, not a property (has no { get; set; }) so the DefaultModelBinder cannot set it).

Rights is null because you cannot use .ElementAt() to generate form controls for a collection (inspect the html your generating and you will see that the name attributes have no relationship to your model). The name attributes need to be

<input name="Rights[0].ID" ... />
<input name="Rights[0].Name" ... />
<input name="Rights[0].isSelected" ... />
<input name="Rights[1].ID" ... />
<input name="Rights[1].Name" ... />
<input name="Rights[1].isSelected" ... />
....

Note that your only generating a for control for the isSelected property which on its own would be meaningless in the POST method and you will an least want to include a hidden input for the ID property.

It appears from your code that you want to generate a 2 column layout, in which case your code should be (simplified)

<div class="row form-group">
    @for(int i = 0; i < Model.Rights.Count; i++)
    {
        <div class="col-md-6">
            @Html.HiddenFor(m => m.Rights[0].ID)
            @Html.CheckBoxFor(m => m.Rights[0].isSelected)
        </div>
        // End current 'row' and start a new one every 2nd item
        if ((i + 1) % 2 == 0)
        {
            @:</div><div class="row form-group">
        }
    }
</div>


问:
How to change an HTML class with JavaScript using getElementsByClassName
How to change a class with Javascript using getElementsByClassName. I got it to work a little but it won't change the class one at the time bet only do it one time to.

I click the button to change css class it do it on all the div and I can do it more in one time.

Here is my Code

```<code>function Button_Color(Show_This) {
    var x = document.getElementById("Color_box");
    var i;
    var Show_This;

    if (Show_This == 1)
    {
        var d = document.getElementsByClassName("id_blue");
        d[0].className = "hid";

        var o = document.getElementsByClassName("id_red");
        o[0].className = " uhid";
    }
    if (Show_This == 2) {

            var d = document.getElementsByClassName("id_blue");
        d[0].className = "hid";

        var o = document.getElementsByClassName("id_red");
        o[0].className = " uhid";
    }

}
</code>```

Here is a like to show you how it looks now with html css js
https://jsfiddle.net/ee51o5h5/1/

I want it to show red only when you click the little red one and blue only when you click the little blue one.

i am dyslexic and from a non-english speaking country so sorry for any miss up.

答:
you just need to find all elements in the desired class, iterate them and change their classes to the class that makes their color:</p>

```<code>    if (Show_This == 1)
    {
        document.getElementsByClassName("box-color02").forEach(function(element){
        element.className = "box-size box-color01";});
    }
    if (Show_This == 2)
    {
        document.getElementsByClassName("box-color01").forEach(function(element){
        element.className = "box-size box-color02";});
    }
</code>```

Body:
How to change a class with Javascript using getElementsByClassName. I got it to work a little but it won't change the class one at the time bet only do it one time to.

I click the button to change css class it do it on all the div and I can do it more in one time.

Here is my Code

function Button_Color(Show_This) {
    var x = document.getElementById("Color_box");
    var i;
    var Show_This;

    if (Show_This == 1)
    {
        var d = document.getElementsByClassName("id_blue");
        d[0].className = "hid";

        var o = document.getElementsByClassName("id_red");
        o[0].className = " uhid";
    }
    if (Show_This == 2) {

            var d = document.getElementsByClassName("id_blue");
        d[0].className = "hid";

        var o = document.getElementsByClassName("id_red");
        o[0].className = " uhid";
    }

}

Here is a like to show you how it looks now with html css js
https://jsfiddle.net/ee51o5h5/1/

I want it to show red only when you click the little red one and blue only when you click the little blue one.

i am dyslexic and from a non-english speaking country so sorry for any miss up.

Body:
you just need to find all elements in the desired class, iterate them and change their classes to the class that makes their color:

    if (Show_This == 1)
    {
        document.getElementsByClassName("box-color02").forEach(function(element){
        element.className = "box-size box-color01";});
    }
    if (Show_This == 2)
    {
        document.getElementsByClassName("box-color01").forEach(function(element){
        element.className = "box-size box-color02";});
    }


问:
python - readable list of objects
This is probably a kinda commonly asked question but I could do with help on this. I have a list of class objects and I'm trying to figure out how to make it print an item from that class but rather than desplaying in the;

```<code><__main__.evolutions instance at 0x01B8EA08>
</code>```

but instead to show a selected attribute of a chosen object of the class. Can anyone help with that?

答:
You'll want to override your class's "to string" method:</p>

```<code>class Foo:
    def __str__(self):
        return "String representation of me"
</code>```

Title: python - readable list of objects

Body:
This is probably a kinda commonly asked question but I could do with help on this. I have a list of class objects and I'm trying to figure out how to make it print an item from that class but rather than desplaying in the;

<__main__.evolutions instance at 0x01B8EA08>

but instead to show a selected attribute of a chosen object of the class. Can anyone help with that?

Body:
You'll want to override your class's "to string" method:

class Foo:
    def __str__(self):
        return "String representation of me"

OwnerDisplayName: Dana


问:
TypeError : 'NoneType' object not callable when using split in Python with BeautifulSoup
I was playing around with the BeautifulSoup and Requests APIs today. So I thought I would write a simple scraper that would follow links to a depth of 2(if that makes sense). All the links in the webpage that i am scraping are relative. (For eg: href="/free-man-aman-sethi/books/9788184001341.htm" title="A Free Man">) So to make them absolute I thought I would join the page url with the relative links using urljoin.

To do this I had to first extract the href value from the  tags and for that I thought I would use split:

```<code>#!/bin/python
#crawl.py
import requests
from bs4 import BeautifulSoup
from urlparse import urljoin

html_source=requests.get("http://www.flipkart.com/books")
soup=BeautifulSoup(html_source.content)
links=soup.find_all("a")
temp=links[0].split('"')
</code>```

This gives the following error:

```<code>Traceback (most recent call last):
  File "test.py", line 10, in <module>
    temp=links[0].split('"')
TypeError: 'NoneType' object is not callable
</code>```

Having dived in before properly going through the documentation, I realize that this is probably not the best way to achieve my objective but why is there a TypeError?

答:
I just encountered the same error - so for what it's worth four years later: if you need to split up the soup element you can also use str() on it before you split it. In your case that would be:</p>

```<code>    temp = str(links).split('"')
</code>```

Body:
I was playing around with the BeautifulSoup and Requests APIs today. So I thought I would write a simple scraper that would follow links to a depth of 2(if that makes sense). All the links in the webpage that i am scraping are relative. (For eg: ) So to make them absolute I thought I would join the page url with the relative links using urljoin.

To do this I had to first extract the href value from the  tags and for that I thought I would use split:

#!/bin/python
#crawl.py
import requests
from bs4 import BeautifulSoup
from urlparse import urljoin

html_source=requests.get("http://www.flipkart.com/books")
soup=BeautifulSoup(html_source.content)
links=soup.find_all("a")
temp=links[0].split('"')

This gives the following error:

Traceback (most recent call last):
  File "test.py", line 10, in <module>
    temp=links[0].split('"')
TypeError: 'NoneType' object is not callable

Having dived in before properly going through the documentation, I realize that this is probably not the best way to achieve my objective but why is there a TypeError?

Body:
I just encountered the same error - so for what it's worth four years later: if you need to split up the soup element you can also use str() on it before you split it. In your case that would be:

    temp = str(links).split('"')


问:
Create dynamic subdomains
It has been a while since I've been thinking over this feature that some websites are implementing and it looks to be very successful.

Websites like tumblr.com, blogger.com, wordpress.com allow users to register new sub-domain names from within the website by using a simple HTML/PHP form. With my current knowledge of PHP I couldn't figure out myself how this is done. I've read some posts on this and still can't build a clear idea about this.

So, how do I create a script that allows users to register their own sub-domains on my website (www.username.mydomain.com) and more than that, how do I allow them to use a different website template (as wordpress.com does). Is this possible to be done on a shared server or a dedicated server is needed?

答: It's easy to create the wildcard subdomains. Check my post for create the wildcard subdomains dynamically in Create subdomains on the fly with .htaccess (PHP) .</p>

Title: Create dynamic subdomains