问:
get the most two recent dates for each customer
basically, I need to retrieve the last two dates for customers who purchased in at least two different dates, implying there are some customer who had purchased only in one date, the data has the following form

```<code>client_id  date
1          2016-07-02
1          2016-07-02
1          2016-06-01
2          2015-06-01
</code>```

and I would like to get it in the following form

```<code>client_id      previous_date     last_date
1              2016-06-01        2016-07-02
</code>```

remarques:

a client can have multiple entries for the same date

a client can have entries only for one date, such customer should be discarded

答:
<s>
All you need is a group by...

```<code>--test date
declare  @tablename TABLE
(
    client_id int,
    [date] datetime
);

insert into @tablename
values( 1 , '2016-07-02'),
   (1 , '2016-07-02'),
   (1 , '2016-06-01'),
   (2 , '2015-06-01');

--query
SELECT client_id,MIN([DATE]) AS [PREVIOUS_DATE], MAX([DATE]) AS [LAST_DATE]
FROM @tablename
GROUP BY client_id
</code>```

</s>
Updated

```<code>-- create data
create table myTable
(
    client_id integer,
    given_date date
);

insert into myTable
values( 1 ,  '2016-07-02'),
   (1 ,  '2016-07-02'),
   (1 , '2016-06-01'),
   (1 , '2016-06-03'),
   (1 , '2016-06-09'),
   (2 , '2015-06-01'),
   (3 , '2016-06-03'),
   (3 , '2016-06-09');

-- query
SELECT sub.client_id, sub.PREVIOUS_DATE, sub.LAST_DATE
FROM
 (select
   ROW_NUMBER() OVER (PARTITION BY a.client_id order by b.given_date desc,(MAX(b.given_date) - a.given_date)) AS ROW_NUMBER,
   a.client_id,a.given_date AS PREVIOUS_DATE, MAX(b.given_date) - a.given_date AS diff, (b.given_date) AS LAST_DATE
    FROM myTable AS a
      JOIN myTable AS b
        ON b.client_id = a.client_id
    WHERE a.given_date <> b.given_date
    group by a.client_id, a.given_date, b.given_date) AS sub
WHERE sub.ROW_NUMBER = 1
</code>```

Body:
basically, I need to retrieve the last two dates for customers who purchased in at least two different dates, implying there are some customer who had purchased only in one date, the data has the following form

client_id  date
1          2016-07-02
1          2016-07-02
1          2016-06-01
2          2015-06-01

and I would like to get it in the following form

client_id      previous_date     last_date
1              2016-06-01        2016-07-02

remarques:

a client can have multiple entries for the same date

a client can have entries only for one date, such customer should be discarded

Body:
<s>
All you need is a group by...

--test date
declare  @tablename TABLE
(
    client_id int,
    [date] datetime
);

insert into @tablename
values( 1 , '2016-07-02'),
   (1 , '2016-07-02'),
   (1 , '2016-06-01'),
   (2 , '2015-06-01');

--query
SELECT client_id,MIN([DATE]) AS [PREVIOUS_DATE], MAX([DATE]) AS [LAST_DATE]
FROM @tablename
GROUP BY client_id

</s>
Updated

-- create data
create table myTable
(
    client_id integer,
    given_date date
);

insert into myTable
values( 1 ,  '2016-07-02'),
   (1 ,  '2016-07-02'),
   (1 , '2016-06-01'),
   (1 , '2016-06-03'),
   (1 , '2016-06-09'),
   (2 , '2015-06-01'),
   (3 , '2016-06-03'),
   (3 , '2016-06-09');

-- query
SELECT sub.client_id, sub.PREVIOUS_DATE, sub.LAST_DATE
FROM
 (select
   ROW_NUMBER() OVER (PARTITION BY a.client_id order by b.given_date desc,(MAX(b.given_date) - a.given_date)) AS ROW_NUMBER,
   a.client_id,a.given_date AS PREVIOUS_DATE, MAX(b.given_date) - a.given_date AS diff, (b.given_date) AS LAST_DATE
    FROM myTable AS a
      JOIN myTable AS b
        ON b.client_id = a.client_id
    WHERE a.given_date <> b.given_date
    group by a.client_id, a.given_date, b.given_date) AS sub
WHERE sub.ROW_NUMBER = 1


来源: stackexchange

问:
Robotic Process Automation (RPA) Express execution error
I have installed RPA express and recorded a process, but when I tried playing the recording it was showing an execution error " Unable to connect with robot". How can I get it resolved?</p>

答:
Check Bot Manager status. Probably, it's not started.

To start Bot manager, open RPA Express tray menu and click Start in the Bot Manager section.

If it does not help, choose All Components > Restart

ContentLicense: CC BY-SA 3.0


问:
Can't Select Checkbox, Selenium WebDriver
I am unable to select a checkbox with Selenium WebDriver in Java.
I tried by Xpath but no result.
WebDriver can't click on element.
I tried with Selenium IDE - recorder, no results.

Here it is - html code for checkbox

I try:

1.

```<code>driver.findElement(By.xpath(".//form[@id='placeOrderForm1']/div[@class='terms right']/label")).click();
</code>```

2.

```<code>driver.findElement(By.id("Terms1")).click();
</code>```

3.

```<code>driver.findElement(By.cssSelector("label")).click();
</code>```

4.

```<code>driver.findElement(By.xpath("//div[3]/form/div/input")).click();
</code>```

Nothing works.
Please help.

答:
You can find the element by a unique identifier. In this case, we can use name or id. The better choice is to go with id.

```<code>WebElement element = driver.findElement(By.name("termsCheck"));
element.click();
</code>```

or you can use this one also

```<code>driver.findElement(By.id("Terms1")).click();
</code>```

Body:
I am unable to select a checkbox with Selenium WebDriver in Java.
I tried by Xpath but no result.
WebDriver can't click on element.
I tried with Selenium IDE - recorder, no results.

Here it is - html code for checkbox

I try:

1.

driver.findElement(By.xpath(".//form[@id='placeOrderForm1']/div[@class='terms right']/label")).click();

2.

driver.findElement(By.id("Terms1")).click();

3.

driver.findElement(By.cssSelector("label")).click();

4.

driver.findElement(By.xpath("//div[3]/form/div/input")).click();

Nothing works.
Please help.

Body:
You can find the element by a unique identifier. In this case, we can use name or id. The better choice is to go with id.

WebElement element = driver.findElement(By.name("termsCheck"));
element.click();

or you can use this one also

driver.findElement(By.id("Terms1")).click();


问:
Asp.Net Forms Authentication when using iPhone UIWebView
I am writing a Asp.net MVC 2 application that uses Forms Authentication and currently I am having a problem with our iPhone application in regards to the authentication/login over the web. We have developed a simple iPhone app that uses the the UIWebView control. At this stage, all the app does is navigate to our Asp.Net website. Simple, right? The problem is, that the user cannot get past the login page. The repro steps are:

Open iPhone app.

The app navigates to the home page.

the user is not authenticated, so they are redirected to the login screen/page

The user enters the correct user name and password. clicks submit.

on the server side, the user is authenticated and a cookie is generated and sent to the client using FormsAuthentication.GetAuthCookie.

The server sends are redirect to send the user to the correct home page.

But the user is then redirected BACK to the login screen!

I've done some extensive debugging on this and what I do know is:

The cookie is being sent to the client, and the client is storing the cookie. Verified this in the iPhone debugger and also by using Javsascript to display cookie data on the page. The cookie is being sent back to the server. Verified this in the Visual Studio debugger. It is the correct cookie (it's the same one that was set). The property User.Identity.IsAuthenticated returns false for some reason, even though the auth cookie is contained in the Request object.  I have verified that the iPhone app is setup to accept cookies, and they are on the client.

Here is the funny thing: It works fine if you open the Safari browser on the iPhone and go to our site directly.

It has the same behaviour on the iPad too in that it doesn't get past the login screen. This repros on the emulators, and on devices.

This same web site has been tested with IE 7-8, Safari (for Windows), Blackberry, IEMobile 6.5, Phone 7 and it works find. The only circumstance that it doesn't work on is the UIWebView in the iPhone app.

答:
From the research I did, the reason why you can't set the User-Agent is that the UIWebView is setting the User-Agent value just before it sends out the request, that is, after you've made your request from your code.

The trick to get around this problem is to use something called "method swizzling", an advanced and potentially dangerous Objective-C concept that swaps out a standard method with one you provide. The end result is that when your request is sent out and the framework code adds the User-Agent it will be fooled into using the method you provided.

The following explains what I did to implement this but I am no Objective-C expert and would suggest to you to do some research to familiarize yourself with the technique. In particular, there was a link out there explaining better than me what is going on here, but at the moment I can't find it.

1) Add a category on NSObject to allow swizzling.

```<code>@interface NSObject (Swizzle)

+ (BOOL) swizzleMethod:(SEL)origSelector withMethod:(SEL)newSelector;

@end

@implementation NSObject (Swizzle)

+ (BOOL) swizzleMethod:(SEL) origSelector withMethod:(SEL)newSelector
{
    Method origMethod= class_getInstanceMethod(self, origSelector);
    Method newMethod= class_getInstanceMethod(self, newSelector);

    if (origMethod && newMethod)
    {
        if (class_addMethod(self, origSelector, method_getImplementation(newMethod), method_getTypeEncoding(newMethod)))
        {
            class_replaceMethod(self, newSelector, method_getImplementation(origMethod), method_getTypeEncoding(origMethod));
        }
        else {
            method_exchangeImplementations(origMethod, newMethod);
        }
        return YES;
    }
    return NO;
}
@end
</code>```

2) Subclass NSMutableURLRequest to allow the swizzle:

```<code>@interface NSMutableURLRequest (MyMutableURLRequest)

+ (void) setupUserAgentOverwrite;

@end
@implementation NSMutableURLRequest (MyMutableURLRequest)

- (void) newSetValue:(NSString*)value forHTTPHeaderField:(NSString*)field
{
    if ([field isEqualToString:@"User-Agent"])
    {
        value = USER_AGENT;  // ie, the value I want to use.
    }
    [self newSetValue:value forHTTPHeaderField:field];
}
+ (void) setupUserAgentOverwrite
{
    [self swizzleMethod:@selector(setValue:forHTTPHeaderField:)
             withMethod:@selector(newSetValue:forHTTPHeaderField:)];

}

@end
</code>```

3)  Call the static method to swap out the method.  I made this call in didFinishLaunchingWithOptions:

```<code>// Need to call this method so that User-Agent get updated correctly:
[NSMutableURLRequest setupUserAgentOverwrite];
</code>```

4) And then used it like this. (The connection delegate saves the data in a mutable array
and then manually sets the UIWebView using its loadData method when it finishes loading).

```<code>- (void)loadWithURLString:(NSString*)urlString
{
    NSURL *url = [NSURL URLWithString:urlString];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
_connection = [NSURLConnection connectionWithRequest:request delegate:self];
[_connection start];
}
</code>```

Body:
From the research I did, the reason why you can't set the User-Agent is that the UIWebView is setting the User-Agent value just before it sends out the request, that is, after you've made your request from your code.

The trick to get around this problem is to use something called "method swizzling", an advanced and potentially dangerous Objective-C concept that swaps out a standard method with one you provide. The end result is that when your request is sent out and the framework code adds the User-Agent it will be fooled into using the method you provided.

The following explains what I did to implement this but I am no Objective-C expert and would suggest to you to do some research to familiarize yourself with the technique. In particular, there was a link out there explaining better than me what is going on here, but at the moment I can't find it.

1) Add a category on NSObject to allow swizzling.

@interface NSObject (Swizzle)

+ (BOOL) swizzleMethod:(SEL)origSelector withMethod:(SEL)newSelector;

@end

@implementation NSObject (Swizzle)

+ (BOOL) swizzleMethod:(SEL) origSelector withMethod:(SEL)newSelector
{
    Method origMethod= class_getInstanceMethod(self, origSelector);
    Method newMethod= class_getInstanceMethod(self, newSelector);

    if (origMethod && newMethod)
    {
        if (class_addMethod(self, origSelector, method_getImplementation(newMethod), method_getTypeEncoding(newMethod)))
        {
            class_replaceMethod(self, newSelector, method_getImplementation(origMethod), method_getTypeEncoding(origMethod));
        }
        else {
            method_exchangeImplementations(origMethod, newMethod);
        }
        return YES;
    }
    return NO;
}
@end

2) Subclass NSMutableURLRequest to allow the swizzle:

@interface NSMutableURLRequest (MyMutableURLRequest)

+ (void) setupUserAgentOverwrite;

@end
@implementation NSMutableURLRequest (MyMutableURLRequest)

- (void) newSetValue:(NSString*)value forHTTPHeaderField:(NSString*)field
{
    if ([field isEqualToString:@"User-Agent"])
    {
        value = USER_AGENT;  // ie, the value I want to use.
    }
    [self newSetValue:value forHTTPHeaderField:field];
}
+ (void) setupUserAgentOverwrite
{
    [self swizzleMethod:@selector(setValue:forHTTPHeaderField:)
             withMethod:@selector(newSetValue:forHTTPHeaderField:)];

}

@end

3)  Call the static method to swap out the method.  I made this call in didFinishLaunchingWithOptions:

// Need to call this method so that User-Agent get updated correctly:
[NSMutableURLRequest setupUserAgentOverwrite];

4) And then used it like this. (The connection delegate saves the data in a mutable array
and then manually sets the UIWebView using its loadData method when it finishes loading).

- (void)loadWithURLString:(NSString*)urlString
{
    NSURL *url = [NSURL URLWithString:urlString];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
_connection = [NSURLConnection connectionWithRequest:request delegate:self];
[_connection start];
}

ContentLicense: CC BY-SA 2.5


问:
Jquery - Internet Explorer - Syntax Error
I have this site and in Internet Explorer I get this syntax error in IE only, Chrome its fine.

```<code>SCRIPT1002: Syntax error
File: communities.js, Line: 157, Column: 55
</code>```

Line 157 is this: priceArray = priceArray.filter(x => x != $(this).val());

Here is the whole code, but IE wont tell me what the syntax error is.

```<code>$('ul.dropdown-menu input[type=checkbox]').each(function () {
        $(this).change(function () {

            if ($(this).attr("id") == 'price') {
                if (this.checked) {
                    priceArray.push($(this).val());
                }
                else {
                    priceArray = priceArray.filter(x => x != $(this).val());
                }
            }
});
});
</code>```

What am I doing wrong and how do I fix it?

priceArray is defined at the top of the file:

```<code>var priceArray = [];
</code>```

答:
As Santi pointed out in the comments, IE does not support arrow functions.

The solution is to use a normal function. Normal functions however have their own this object, so you have to give filter the object that the provided function should be called with:

// ...
priceArray = priceArray.filter(function (x) {
  return x !== $(this).val();
}, this);
// ...
```

Body:
I have this site and in Internet Explorer I get this syntax error in IE only, Chrome its fine.

SCRIPT1002: Syntax error
File: communities.js, Line: 157, Column: 55

Line 157 is this: priceArray = priceArray.filter(x => x != $(this).val());

Here is the whole code, but IE wont tell me what the syntax error is.

$('ul.dropdown-menu input[type=checkbox]').each(function () {
        $(this).change(function () {

            if ($(this).attr("id") == 'price') {
                if (this.checked) {
                    priceArray.push($(this).val());
                }
                else {
                    priceArray = priceArray.filter(x => x != $(this).val());
                }
            }
});
});

What am I doing wrong and how do I fix it?

priceArray is defined at the top of the file:

var priceArray = [];


问:
Resource ownership in REST API
In the following scenario:

A User can create Games.

A User who creates a game is called Owner.

Games have their own unique id globally.

Other Users can join Games they don't own, these are called Players.

One would send a request to /game/{id} to get the Game data, which should be the same for every client, something like:

```<code>{
   name: 'My Game',
   sport: 'Football'
   ...
}
</code>```

Let's say that we have to show a "Settings" link for the Game owner in the Main Game Screen. This "Settings" link can't be displayed for regular Players.

Both Player and Owner can see the Main Game Screen.

How can I verify the ownership of this resource to show different components to the users?

I think that adding the ownerId to the response would be a liability since one could change the value on the client side, is that right?

Also, adding an isOwner field would make it impossible to cache the response.

答:
The answer here may lie in HATEOAS type structures. Your resource should contain a list of navigable links to other information/children/lists, etc. If 'settings' is an option for the requesting user, then a link to the settings should be returned as part of the object, otherwise no such link would exist.

Caching: This does present a problem, but it's solvable.

Title: Resource ownership in REST API

Body:
In the following scenario:

A User can create Games.

A User who creates a game is called Owner.

Games have their own unique id globally.

Other Users can join Games they don't own, these are called Players.

One would send a request to /game/{id} to get the Game data, which should be the same for every client, something like:

{
   name: 'My Game',
   sport: 'Football'
   ...
}

Let's say that we have to show a "Settings" link for the Game owner in the Main Game Screen. This "Settings" link can't be displayed for regular Players.

Both Player and Owner can see the Main Game Screen.

How can I verify the ownership of this resource to show different components to the users?

I think that adding the ownerId to the response would be a liability since one could change the value on the client side, is that right?

Also, adding an isOwner field would make it impossible to cache the response.


问:
AJAX does not send FormData Correctly?
I'm working on something to send one image file and few data to PHP file. So I'm using a Form to do that. This is my JS code;

```<code>var pictureForm = new FormData();
var imgFile = $('#avatarSelect')[0];
pictureForm.append('email', email);
pictureForm.append('firName',editfirName);
pictureForm.append('lstName',editlstName);
pictureForm.append('newPass',editpass);
pictureForm.append('newPhn', editphnNum);
pictureForm.append('pictureFile', imgFile.files[0]);

$.ajax({
        type: "POST",
        url: "php/accountUpdate.php",
        dataType:'json',
        data:{pictureForm},
        processData: false,
        contentType: false,
        success : function(response)
        {
            if(response==1)
            {
                alert("Success");

            }
            else
            {
                alert(response);

            }
        }
    });
</code>```

And accountUpdate.php;

```<code><?php
if($_POST)
{
$userEmail= $_POST['email'];
$userPass= $_POST['newPass'];
$userPhone = $_POST['newPhn'];
$userFName= $_POST['firName'];
$userLName = $_POST['lstName'];
$servername ="localhost";
$username="root";
$password="";
$dbname="AS2014459";

// Some code
}
else
 echo json_encode("Error");
?>
</code>```

My Problem

However this always alert me "Error". Means $_POST isn't set properly. I couldn't find the reason. But all the variables such as email,editfirname...etc are properly set and have values.

Also when I run that on my local server (removing PHP if($_POST) condition ) console log says undefined index : email.  Any guesses?

答:
Try changing the 1 with boolean value (true)

```<code>var pictureForm = new FormData();
var imgFile = $('#avatarSelect')[0];
pictureForm.append('email', email);
pictureForm.append('firName',editfirName);
pictureForm.append('lstName',editlstName);
pictureForm.append('newPass',editpass);
pictureForm.append('newPhn', editphnNum);
pictureForm.append('pictureFile', imgFile.files[0]);

$.ajax({
        type: "POST",
        url: "php/accountUpdate.php",
        dataType:'json',
        data:{pictureForm},
        processData: false,
        contentType: false,
        success : function(response)
        {
            if(response==true)
            {
                alert("Success");

            }
            else
            {
                alert(response);

            }
        }
    });
</code>```

Title: AJAX does not send FormData Correctly?

Body:
I'm working on something to send one image file and few data to PHP file. So I'm using a Form to do that. This is my JS code;

var pictureForm = new FormData();
var imgFile = $('#avatarSelect')[0];
pictureForm.append('email', email);
pictureForm.append('firName',editfirName);
pictureForm.append('lstName',editlstName);
pictureForm.append('newPass',editpass);
pictureForm.append('newPhn', editphnNum);
pictureForm.append('pictureFile', imgFile.files[0]);

$.ajax({
        type: "POST",
        url: "php/accountUpdate.php",
        dataType:'json',
        data:{pictureForm},
        processData: false,
        contentType: false,
        success : function(response)
        {
            if(response==1)
            {
                alert("Success");

            }
            else
            {
                alert(response);

            }
        }
    });

And accountUpdate.php;

<?php
if($_POST)
{
$userEmail= $_POST['email'];
$userPass= $_POST['newPass'];
$userPhone = $_POST['newPhn'];
$userFName= $_POST['firName'];
$userLName = $_POST['lstName'];
$servername ="localhost";
$username="root";
$password="";
$dbname="AS2014459";

// Some code
}
else
 echo json_encode("Error");
?>

My Problem

However this always alert me "Error". Means $_POST isn't set properly. I couldn't find the reason. But all the variables such as email,editfirname...etc are properly set and have values.

Also when I run that on my local server (removing PHP if($_POST) condition ) console log says undefined index : email.  Any guesses?

Body:
Try changing the 1 with boolean value (true)

var pictureForm = new FormData();
var imgFile = $('#avatarSelect')[0];
pictureForm.append('email', email);
pictureForm.append('firName',editfirName);
pictureForm.append('lstName',editlstName);
pictureForm.append('newPass',editpass);
pictureForm.append('newPhn', editphnNum);
pictureForm.append('pictureFile', imgFile.files[0]);

$.ajax({
        type: "POST",
        url: "php/accountUpdate.php",
        dataType:'json',
        data:{pictureForm},
        processData: false,
        contentType: false,
        success : function(response)
        {
            if(response==true)
            {
                alert("Success");

            }
            else
            {
                alert(response);

            }
        }
    });


问:
Textual filter very slow
I have a table with 10 to 1000 lines
I have a text field to filter the table.
I used this code to filter the display of each line depending on the filter:

```<code>$("#cs_name").keyup(function () {
        $(".cs_line").each(function () {
            if (!$(this).data('name').toLowerCase().includes($("#cs_name").val().toLowerCase())) {
                $(this).hide("fast");
            }
            else {
                $(this).show("fast");
            }
        });
    });
</code>```

It works fine if I have 10 or 20 lines, but when I have 1000 lines time between each letter is sooo long. up to 5 seconds sometimes.

Maybe there is a way to make it mor efficient.

For information, pagination is not an option, for some client reasons, I cannot have multiple pages.

Thanks a lot for your help

答:
I think the better option for you is to use Jquery Datatable. It offers really fast search on multiple columns and other ready-to-use functionality.

UPDATE:
Without using JQuery Datatable you can increase performance storing cs_line elements and not retrieving everytime with query selector.

Title: Textual filter very slow

Body:
I have a table with 10 to 1000 lines
I have a text field to filter the table.
I used this code to filter the display of each line depending on the filter:

$("#cs_name").keyup(function () {
        $(".cs_line").each(function () {
            if (!$(this).data('name').toLowerCase().includes($("#cs_name").val().toLowerCase())) {
                $(this).hide("fast");
            }
            else {
                $(this).show("fast");
            }
        });
    });

It works fine if I have 10 or 20 lines, but when I have 1000 lines time between each letter is sooo long. up to 5 seconds sometimes.

Maybe there is a way to make it mor efficient.

For information, pagination is not an option, for some client reasons, I cannot have multiple pages.

Thanks a lot for your help


问:
Strategy to create splits for Hbase Table.
```<code>   Can any one suggest me strategies while splitting HBASE table. I have data range starts from [a-z].
</code>```

I have splitted it in as {"e","j","o","u"}. Will it be efficient way.

答:
How are you data splitted ?

When you split a table you need to avoid hotspotting. Which can be for example prevented with salting. If your rows are evenly distributed, then your split is fine.

But if you don't control your data it is better to apply salting to your rows keys.

I will give you the example from the HBase documentation

If you have some rows like this :

```<code>foo001
foo002
foo003
foo004
</code>```

Then all your rows will go in the same split, which will cause hotspotting.

That's were salting is important if you add a random string at the beginning of your row, for example "e", "j", "o"  or "u" then you will distribute your data evenly

```<code>e-foo002
u-foo003
</code>```

And your data will be more evenly distributed. You can apply a random or determinist salting, it's up to you, but a determinist one is better, cause random can cause tricky stuff with salting.

As a (very) quick conclusion : if you have evenly distributed data, your splits are fine, else it would be better to apply salting

EDIT : Might be a good idea to explain this in the documentation on SO.

Body:
   Can any one suggest me strategies while splitting HBASE table. I have data range starts from [a-z].

I have splitted it in as {"e","j","o","u"}. Will it be efficient way.

Body:
How are you data splitted ?

When you split a table you need to avoid hotspotting. Which can be for example prevented with salting. If your rows are evenly distributed, then your split is fine.

But if you don't control your data it is better to apply salting to your rows keys.

I will give you the example from the HBase documentation

If you have some rows like this :

foo001
foo002
foo003
foo004

Then all your rows will go in the same split, which will cause hotspotting.

That's were salting is important if you add a random string at the beginning of your row, for example "e", "j", "o"  or "u" then you will distribute your data evenly

e-foo002
u-foo003

And your data will be more evenly distributed. You can apply a random or determinist salting, it's up to you, but a determinist one is better, cause random can cause tricky stuff with salting.

As a (very) quick conclusion : if you have evenly distributed data, your splits are fine, else it would be better to apply salting

EDIT : Might be a good idea to explain this in the documentation on SO.


问:
Get checked checkbox MVC5
I have searched some articles but none of them fits with my problem. i have this code in my cshtml

```<code>@model IEnumerable<MonitoreoIntegrado.Models.Sensores>
@using (Html.BeginForm("Graphics", "Datos_extensometro", FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
{
    @Html.AntiForgeryToken()
    <div style="margin:0; padding:0; border:none; position:absolute; bottom:5px; right:25px;"><input type="submit" id="enviar" class="btn btn-primary" value="Consultar"></div>
    <div style="float:left; width:428px; height:105px; padding:5px; overflow-y: scroll;">
        <h4 style="margin-top:0px;">Consultar multiples sensores</h4>
            @foreach (var item in Model)
            {
                @Html.CheckBox("sensoresCB", false, new { value = @item.idSensor.ToString() }) @item.nombre <a class="moverse" objetivo="@(item.idSensor)" href=""><span class="glyphicon glyphicon-map-marker" title="Ir al marcador"></span></a><br />
            }
    </div>
}
</code>```

and this in my controller:

```<code>[HttpPost]
[ValidateAntiForgeryToken]
[Authorize(Roles = RolesSistema.Administrador + "," + RolesSistema.Lectura)]
public ActionResult Graphics()
{
    return View();
}
</code>```

I need help to receive that checkboxes in my controller and check which of them are checked

答:
You should use unique id's for your inputs. The easiest way:

```<code>@for (var i = 0; i < Model.Count(); i++)
{
    @Html.CheckBox("sensoresCB["+i.ToString()+"]", false, new { value = Model[i].idSensor.ToString() })
    //your other stuff
}
</code>```

And on controller side:

```<code>[HttpPost]
[ValidateAntiForgeryToken]
[Authorize(Roles = RolesSistema.Administrador + "," + RolesSistema.Lectura)]
public ActionResult Graphics(bool[] sensoresCB) //note this
{
    return View();
}
</code>```

So you got the array with your selections. Use index to understand what checkbox it is.

Title: Get checked checkbox MVC5

Body:
I have searched some articles but none of them fits with my problem. i have this code in my cshtml

@model IEnumerable<MonitoreoIntegrado.Models.Sensores>
@using (Html.BeginForm("Graphics", "Datos_extensometro", FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
{
    @Html.AntiForgeryToken()

<input type="submit" id="enviar" class="btn btn-primary" value="Consultar">

Consultar multiples sensores

            @foreach (var item in Model)
            {
                @Html.CheckBox("sensoresCB", false, new { value = @item.idSensor.ToString() }) @item.nombre

            }

}

and this in my controller:

[HttpPost]
[ValidateAntiForgeryToken]
[Authorize(Roles = RolesSistema.Administrador + "," + RolesSistema.Lectura)]
public ActionResult Graphics()
{
    return View();
}

I need help to receive that checkboxes in my controller and check which of them are checked

Body:
You should use unique id's for your inputs. The easiest way:

@for (var i = 0; i < Model.Count(); i++)
{
    @Html.CheckBox("sensoresCB["+i.ToString()+"]", false, new { value = Model[i].idSensor.ToString() })
    //your other stuff
}

And on controller side:

[HttpPost]
[ValidateAntiForgeryToken]
[Authorize(Roles = RolesSistema.Administrador + "," + RolesSistema.Lectura)]
public ActionResult Graphics(bool[] sensoresCB) //note this
{
    return View();
}

So you got the array with your selections. Use index to understand what checkbox it is.


问:
Angular 1.6 $http.jsonp while using the google sheets API
The Angular 1.6's $http.jsonp does not play nice with the google sheets' API:

I'm trying to fetch and then get my data from google sheets, with the following:

```<code>var callback;
app.controller("meetingsTable", function ($scope, $http, $sce) {

var url = "http://spreadsheets.google.com/a/google.com/tq";
var trustedUrl = $sce.trustAsResourceUrl(url);
var key = 'MY_KEY';
var tq = 'select%20*%20limit%2010';
var tqx = 'responseHandler:callback';
var params = {
    key: key,
    tq: tq,
    status: 'ok',
    tqx: tqx
};

callback = function (response) {
    console.log(response); // entering here, not to the promise
    return response;
}

    $http.jsonp(trustedUrl, { params: params }).then(function (response) {
        console.log(response);
        retrun;
        //success things go here
    }, function (response) {
        //error things go here
    });
});
</code>```

I successfuly manged to get the data from the sheets, by using a function (callback), with a vnila js, by when I tried with angular, I got an "google.visualization.Query.setResponse" object in the sources, with the console error: Uncaught ReferenceError: google is not defined.

The most annoying thing - the promise doesn't recive the response, and I can't update my table's values ansyc.
I tried everything I could think of (and every suggestion in stackoverflow),
Things I tried:

passing the url as it is, without params, cuase myabe the $sce.trustAsResourceUrl needs the whole url.

passing without $sce (works in vanila js, not here).

naming my promise success function as "callback".

checking that all of the values in the sheets' API are here (again, works with vanila).

calling "callback" inside the promise, entering it as a function inside the promise.

getting all the jsonp inside a function that return the response, with&without the callback function.

removing the callback from the "tqx=responseHandler:callback" parameter all togther.

passing the promise as a callback in the tqx param.

using the 1.5< "JSON_CALLBACK", which doesn't work with 1.6.

making the request with the vanila js, and then passing it to the controller (dosen't work).

If I'll remember in more things, I will update below.

please, can anyone figure out what's the problem?
REALLY appreciate,
Thanks,
Yoav.

答:
Answering my own question:

if you guys have the same problem, use angular's $scope.$apply property. this is a not so well-documented property in Angular's API, so here's a nice guide
for when a how to use $apply, with a nice example.
My implementation:

```<code>$scope.tableContentData;
callback = function (response) {
    $scope.$apply(function () {
        $scope.tableContentData = response;
    });
};
$http.jsonp(trustedUrl).then(function () {
        //success stuff
    }, function () {
        //error stuff
    });
</code>```

when I declared callback outside my controller.

This was a nightmare.

Thanks for the votes-ups anyways!

Body:
The Angular 1.6's $http.jsonp does not play nice with the google sheets' API:

I'm trying to fetch and then get my data from google sheets, with the following:

var callback;
app.controller("meetingsTable", function ($scope, $http, $sce) {

var url = "http://spreadsheets.google.com/a/google.com/tq";
var trustedUrl = $sce.trustAsResourceUrl(url);
var key = 'MY_KEY';
var tq = 'select%20*%20limit%2010';
var tqx = 'responseHandler:callback';
var params = {
    key: key,
    tq: tq,
    status: 'ok',
    tqx: tqx
};

callback = function (response) {
    console.log(response); // entering here, not to the promise
    return response;
}

    $http.jsonp(trustedUrl, { params: params }).then(function (response) {
        console.log(response);
        retrun;
        //success things go here
    }, function (response) {
        //error things go here
    });
});

I successfuly manged to get the data from the sheets, by using a function (callback), with a vnila js, by when I tried with angular, I got an "google.visualization.Query.setResponse" object in the sources, with the console error: Uncaught ReferenceError: google is not defined.

The most annoying thing - the promise doesn't recive the response, and I can't update my table's values ansyc.
I tried everything I could think of (and every suggestion in stackoverflow),
Things I tried:

passing the url as it is, without params, cuase myabe the $sce.trustAsResourceUrl needs the whole url.

passing without $sce (works in vanila js, not here).

naming my promise success function as "callback".

checking that all of the values in the sheets' API are here (again, works with vanila).

calling "callback" inside the promise, entering it as a function inside the promise.

getting all the jsonp inside a function that return the response, with&without the callback function.

removing the callback from the "tqx=responseHandler:callback" parameter all togther.

passing the promise as a callback in the tqx param.

using the 1.5< "JSON_CALLBACK", which doesn't work with 1.6.

making the request with the vanila js, and then passing it to the controller (dosen't work).

If I'll remember in more things, I will update below.

please, can anyone figure out what's the problem?
REALLY appreciate,
Thanks,
Yoav.

Body:
Answering my own question:

if you guys have the same problem, use angular's $scope.$apply property. this is a not so well-documented property in Angular's API, so here's a nice guide
for when a how to use $apply, with a nice example.
My implementation:

$scope.tableContentData;
callback = function (response) {
    $scope.$apply(function () {
        $scope.tableContentData = response;
    });
};
$http.jsonp(trustedUrl).then(function () {
        //success stuff
    }, function () {
        //error stuff
    });

when I declared callback outside my controller.

This was a nightmare.

Thanks for the votes-ups anyways!


问:
How to give folder ownership to user with UID 1000?
The reason I need to give folder ownership to UID 1000 is to make sure Docker container can write to the mounted volume based on this answer.

But the answer assumes reader knows how to change ownership. I don't know. After some research, I know how to change ownership with this, but can't make it work.

```<code>chown UID 1000 /u ./jenkins_home
</code>```

My above command doesn't work. How do I change ownership to UID 1000???

答:
The accepted answer does explain how to change ownership.
The correct command would be chown 1000 ./jenkins_home.

Body:
The reason I need to give folder ownership to UID 1000 is to make sure Docker container can write to the mounted volume based on this answer.

But the answer assumes reader knows how to change ownership. I don't know. After some research, I know how to change ownership with this, but can't make it work.

chown UID 1000 /u ./jenkins_home

My above command doesn't work. How do I change ownership to UID 1000???


问:
Get All Users in an Active Directory Group
I'm using the following code sample to get a list of all users in a specified AD group (in this case, all users in the "Domain Users" group). My listed code works great, with one exception: it won't return users who have their primary group set to "Domain Users". How can I get a list of all users in the group, including those who have it set as their primary group?</p>

```<code>Private Sub GetUsers()

    Dim groupSearcher As New DirectorySearcher
    Dim groupSearchRoot As New DirectoryEntry("LDAP://OU=Users,DC=domain,DC=com")

    With groupSearcher
        .SearchRoot = groupSearchRoot
        .Filter = "(&(ObjectClass=Group)(CN=Domain Users))"
    End With

    Dim members As Object
    members = groupSearcher.FindOne.GetDirectoryEntry.Invoke("Members", Nothing)

    For Each member As Object In CType(members, IEnumerable)
        Console.WriteLine(New DirectoryEntry(member).Name.Remove(0, 3))
    Next
End Sub
</code>```

答: I'm searching for a robust way to do this too. If you specifically want users that are part of "Domain Admins", query for all users where primaryGroupID=512 (512 is a well-known ID that means "Domain Admins").</p>

Body:
I'm using the following code sample to get a list of all users in a specified AD group (in this case, all users in the "Domain Users" group). My listed code works great, with one exception: it won't return users who have their primary group set to "Domain Users". How can I get a list of all users in the group, including those who have it set as their primary group?

Private Sub GetUsers()

    Dim groupSearcher As New DirectorySearcher
    Dim groupSearchRoot As New DirectoryEntry("LDAP://OU=Users,DC=domain,DC=com")

    With groupSearcher
        .SearchRoot = groupSearchRoot
        .Filter = "(&(ObjectClass=Group)(CN=Domain Users))"
    End With

    Dim members As Object
    members = groupSearcher.FindOne.GetDirectoryEntry.Invoke("Members", Nothing)

    For Each member As Object In CType(members, IEnumerable)
        Console.WriteLine(New DirectoryEntry(member).Name.Remove(0, 3))
    Next
End Sub


问:
How to control shadow spread and blur?
I have designed UI elements in sketch, and one of them has a shadow with blur 1 and spread 0. I looked at the doc for the views layer property and layer doesn't have anything named spread or blur, or anything equivalent (the only control was merely shadowOpacity). How can control things like blur and spread?

Here are my settings in Sketch:

And here is what I want my shadow to look like:

And here is what it looks like at the moment:

Note, you have to click on the picture to actually see the shadow.

My code is as follows:

```<code>func setupLayer(){
    view.layer.cornerRadius = 2
    view.layer.shadowColor = Colors.Shadow.CGColor
    view.layer.shadowOffset = CGSize(width: 0, height: 1)
    view.layer.shadowOpacity = 0.9
    view.layer.shadowRadius = 5
}
</code>```

答:
My solution based on this post replies: (Swift 3)</p>

```<code>let shadowPath = UIBezierPath(rect: CGRect(x: -1,
                                           y: -2,
                                           width: target.frame.width + 2,
                                           height: target.frame.height + 2))

target.layer.shadowColor = UIColor(hexString: shadowColor).cgColor
target.layer.shadowOffset = CGSize(width: CGFloat(shadowOffsetX), height: CGFloat(shadowOffsetY))
target.layer.masksToBounds = false
target.layer.shadowOpacity = Float(shadowOpacity)
target.layer.shadowPath = shadowPath.cgPath
</code>```

ContentLicense: CC BY-SA 4.0

Title: How to control shadow spread and blur?

Body:
I have designed UI elements in sketch, and one of them has a shadow with blur 1 and spread 0. I looked at the doc for the views layer property and layer doesn't have anything named spread or blur, or anything equivalent (the only control was merely shadowOpacity). How can control things like blur and spread?

Here are my settings in Sketch:

And here is what I want my shadow to look like:

And here is what it looks like at the moment:

Note, you have to click on the picture to actually see the shadow.

My code is as follows:

func setupLayer(){
    view.layer.cornerRadius = 2
    view.layer.shadowColor = Colors.Shadow.CGColor
    view.layer.shadowOffset = CGSize(width: 0, height: 1)
    view.layer.shadowOpacity = 0.9
    view.layer.shadowRadius = 5
}

Body:
My solution based on this post replies: (Swift 3)

let shadowPath = UIBezierPath(rect: CGRect(x: -1,
                                           y: -2,
                                           width: target.frame.width + 2,
                                           height: target.frame.height + 2))

target.layer.shadowColor = UIColor(hexString: shadowColor).cgColor
target.layer.shadowOffset = CGSize(width: CGFloat(shadowOffsetX), height: CGFloat(shadowOffsetY))
target.layer.masksToBounds = false
target.layer.shadowOpacity = Float(shadowOpacity)
target.layer.shadowPath = shadowPath.cgPath


问:
iOS app not available for internal testing in TestFlight
I created a new iOS app in iTunes Connect and I am attempting to upload a build of my Xamarin app for internal testing via TestFlight.  I am unable to make the app available to testers because the build seems to disappear from the TestFlight tab.

After uploading the build via Application Loader, the build completes processing and is initially available on the TestFlight tab.

When I click on the build, I am taken to the build details with the option to provide export compliance information.

I enter the compliance information and select Start Internal Testing.

I am then taken back to the build information screen with the build in a state of "Ready to Submit."

At this point, if I click on the TestFlight tab to refresh the screen, the build is no longer listed under my version number.  I cannot find the build on the TestFlight tab to make it available for internal testing.

The build still appears on the Activity tab, and it can be selected as a build to submit it to the App Store as part of a release submission.  However, it is nowhere to be found on the TestFlight tab.

Am I missing a step in the process of making the build available on TestFlight for internal testing?

答: I generated one more build having AppStore build specified, uploaded it to iTunes connect and then it worked.</p>


问:
Split DataFrame and apply code to all DataFrames at once?
I would like to separate my DataFrame from twelve rows to three DataFrames by column value, and then apply a set of code to all DataFrames simultaneously.

```<code>    A     B      C
 1  A   0.25     0
 2  A   0.50     0
 3  A   0.75     0
 4  B   1.00     1
 5  B   1.25     1
 6  B   1.75     1
 7  C   0.50     1
 8  C  -0.25     0
 9  C   1.25     1
10  D   0.75     1
11  D  -0.75     0
12  D  -1.00    -1
</code>```

The resulting DataFrames should be:

```<code>    A     B      C
 1  A   0.25     0
 2  A   0.50     0
 3  A   0.75     0

 4  B   1.00     1
 5  B   1.25     1
 6  B   1.75     1

 7  C   0.50     1
 8  C  -0.25     0
 9  C   1.25     1

10  D   0.75     1
11  D  -0.75     0
12  D  -1.00    -1
</code>```

So far, I have tried df.groupby(['A']) and df.set_index(['A']) but theses functions do not seem to allow me to apply a set of code without errors.

答:
Simpliest is created dict of all DataFrames by convert to tuple and then to dict groupby object:

```<code>d = dict(tuple(df.groupby('A')))
print (d)
{'B':    A     B  C
4  B  1.00  1
5  B  1.25  1
6  B  1.75  1, 'A':    A     B  C
1  A  0.25  0
2  A  0.50  0
3  A  0.75  0, 'D':     A     B  C
10  D  0.75  1
11  D -0.75  0
12  D -1.00 -1, 'C':    A     B  C
7  C  0.50  1
8  C -0.25  0
9  C  1.25  1}

print (d['A'])
   A     B  C
1  A  0.25  0
2  A  0.50  0
3  A  0.75  0
</code>```

For apply functions is possible use:

```<code>for i, x in d.items():
    d[i] = x.mean(axis=1)

print (d['A'])
1    0.125
2    0.250
3    0.375
dtype: float64
</code>```

But better is use groupby with custom function - see docs:

```<code>def f(x):
    print (x)
    return x.mean(axis=1)

df1 = df.groupby('A').apply(f)
print (df1)
A  1     0.125
   2     0.250
   3     0.375
B  4     1.000
   5     1.125
   6     1.375
C  7     0.750
   8    -0.125
   9     1.125
D  10    0.875
   11   -0.375
   12   -1.000
dtype: float64
</code>```

Body:
I would like to separate my DataFrame from twelve rows to three DataFrames by column value, and then apply a set of code to all DataFrames simultaneously.

    A     B      C
 1  A   0.25     0
 2  A   0.50     0
 3  A   0.75     0
 4  B   1.00     1
 5  B   1.25     1
 6  B   1.75     1
 7  C   0.50     1
 8  C  -0.25     0
 9  C   1.25     1
10  D   0.75     1
11  D  -0.75     0
12  D  -1.00    -1

The resulting DataFrames should be:

    A     B      C
 1  A   0.25     0
 2  A   0.50     0
 3  A   0.75     0

 4  B   1.00     1
 5  B   1.25     1
 6  B   1.75     1

 7  C   0.50     1
 8  C  -0.25     0
 9  C   1.25     1

10  D   0.75     1
11  D  -0.75     0
12  D  -1.00    -1

So far, I have tried df.groupby(['A']) and df.set_index(['A']) but theses functions do not seem to allow me to apply a set of code without errors.

Body:
Simpliest is created dict of all DataFrames by convert to tuple and then to dict groupby object:

d = dict(tuple(df.groupby('A')))
print (d)
{'B':    A     B  C
4  B  1.00  1
5  B  1.25  1
6  B  1.75  1, 'A':    A     B  C
1  A  0.25  0
2  A  0.50  0
3  A  0.75  0, 'D':     A     B  C
10  D  0.75  1
11  D -0.75  0
12  D -1.00 -1, 'C':    A     B  C
7  C  0.50  1
8  C -0.25  0
9  C  1.25  1}

print (d['A'])
   A     B  C
1  A  0.25  0
2  A  0.50  0
3  A  0.75  0

For apply functions is possible use:

for i, x in d.items():
    d[i] = x.mean(axis=1)

print (d['A'])
1    0.125
2    0.250
3    0.375
dtype: float64

But better is use groupby with custom function - see docs:

def f(x):
    print (x)
    return x.mean(axis=1)

df1 = df.groupby('A').apply(f)
print (df1)
A  1     0.125
   2     0.250
   3     0.375
B  4     1.000
   5     1.125
   6     1.375
C  7     0.750
   8    -0.125
   9     1.125
D  10    0.875
   11   -0.375
   12   -1.000
dtype: float64


问:
Vis.js show only business hours in timeline
Not sure how to go about it but I'm using vis.js in my project and I need to display a timeline of the open hours of a business.  Is there a way to show only the business hours and not the whole 24 hours as having evening hours is pointless for my application.

I cannot seem to find options in the documentation to make this setting in my code options.

答:
The documentation you are looking for is the 'Hiding Periods' example: http://visjs.org/examples/timeline/other/hidingPeriods.html

To hide weekends you provide any weekend dates per:

To hide a weekend, pick any Saturday as start and the following Monday as end and set repeat to weekly.

To hide times outside of e.g. 9am to 5pm you provide a range of any arbitrary day with a start time of 5pm and a finish time of 9pm:

```<code>{
    start: '2017-03-04 17:00:00',
    end: '2017-03-05 09:00:00',
    repeat: 'daily'
}
</code>```

Here is a small example below:

var container = document.getElementById('timeline');

// sample timeline entry
var items = new vis.DataSet([{
  id: 1,
  content: 'foo',
  start: '2017-06-13 10:00:00',
  end: '2017-06-13 16:30:00'
}]);

// Configuration for the Timeline
var options = {
  // hide weekends - use any weekend and repeat weekly
  hiddenDates: [{
      start: '2017-03-04 00:00:00',
      end: '2017-03-06 00:00:00',
      repeat: 'weekly'
    },
    // hide outside of 9am to 5pm - use any 2 days and repeat daily
    {
      start: '2017-03-04 17:00:00',
      end: '2017-03-05 09:00:00',
      repeat: 'daily'
    }
  ],
  // start and end of timeline
  start: '2017-06-01',
  end: '2017-06-30',
  height: '140px',
  editable: false
};

// Create a Timeline
var timeline = new vis.Timeline(container, items, options);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://cdnjs.cloudflare.com/ajax/libs/vis/4.20.0/vis.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/vis/4.20.0/vis.min.js"></script>

<h3>Mon-Fri 9am to 5pm working hours timeline example</h3>
<div id="timeline"></div></code>```

Body:
The documentation you are looking for is the 'Hiding Periods' example: http://visjs.org/examples/timeline/other/hidingPeriods.html

To hide weekends you provide any weekend dates per:

To hide a weekend, pick any Saturday as start and the following Monday as end and set repeat to weekly.

To hide times outside of e.g. 9am to 5pm you provide a range of any arbitrary day with a start time of 5pm and a finish time of 9pm:

{
    start: '2017-03-04 17:00:00',
    end: '2017-03-05 09:00:00',
    repeat: 'daily'
}

Here is a small example below:

var container = document.getElementById('timeline');

// sample timeline entry
var items = new vis.DataSet([{
  id: 1,
  content: 'foo',
  start: '2017-06-13 10:00:00',
  end: '2017-06-13 16:30:00'
}]);

// Configuration for the Timeline
var options = {
  // hide weekends - use any weekend and repeat weekly
  hiddenDates: [{
      start: '2017-03-04 00:00:00',
      end: '2017-03-06 00:00:00',
      repeat: 'weekly'
    },
    // hide outside of 9am to 5pm - use any 2 days and repeat daily
    {
      start: '2017-03-04 17:00:00',
      end: '2017-03-05 09:00:00',
      repeat: 'daily'
    }
  ],
  // start and end of timeline
  start: '2017-06-01',
  end: '2017-06-30',
  height: '140px',
  editable: false
};

// Create a Timeline
var timeline = new vis.Timeline(container, items, options);

<link href="https://cdnjs.cloudflare.com/ajax/libs/vis/4.20.0/vis.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/vis/4.20.0/vis.min.js"></script>

<h3>Mon-Fri 9am to 5pm working hours timeline example</h3>
<div id="timeline"></div>


问:
Howto change from proportional to tabulated digits in menu items?
I want to change from proportional to tabulated digits in menu items? It's possible?

Menu without tabulated digits

答:
You can set the attributedTitle property of a NSMenuItem and provide whatever custom alignment or formatting you want through an NSAttributedString

Good examples of how to do string alignment in an attributed string can be seen here:

Attributed Text Center Alignment

Here is an answer that shows how to add tab stops to an attributed string:

How do I add tab stops to an NSAttributedString

You can even create an attributed string from RTF or HTML:

Creating an NSAttributedString from HTML (or RTF)


问:
Linked list: Should the type of pointer "next" and the name of struct be same?
```<code>#include<stdio.h>
#include<stdlib.h>
typedef struct {
    int val;
    struct node* next;
} Node, *NodePtr;
void makeInitialLinkedList(int a[], int n)
{
    int i;
    NodePtr rec=NULL;
    NodePtr head=NULL;
    for (i=0; i<n; i++) {
        NodePtr cur=(NodePtr)malloc(sizeof(Node));
        if (i==0) head=cur;
        if (rec!=NULL) rec->next=(node*)cur;
        cur->val=a[i];
        cur->next=NULL;
        rec=cur;
    }

    // test
    while(n--) {
        printf("%d ", head->val);
        head=(NodePtr)head->next;
    }
}
NodePtr copy(NodePtr head)
{
    return NULL;
}
int main()
{
    //Mission #2
    int initialDataArray[10]={5,3,2,8,9,7,0,6,4,1};
    makeInitialLinkedList(initialDataArray, 10);

}
</code>```

I do not understand why this works. I did not make a name initially for the struct and only made a surname "Node" by typedef. Then how does "struct node* next" work correctly? is node* a kind of data types like int* or char*? I thought like this:

```<code>typedef struct strName {
    int val;
    struct strName* next;
} strSurName, *strPtr;
</code>```

Does the type of pointer "next" and the initial name of struct have to same?

答:
I do not understand why this works.

It doesn't, you should get compilation errors, like these with gcc 6.3 or 4.2.1:

```<code>prog.c: In function ‘makeInitialLinkedList’:
prog.c:15:35: error: ‘node’ undeclared (first use in this function)
         if (rec!=NULL) rec->next=(node*)cur;
                                   ^~~~
prog.c:15:35: note: each undeclared identifier is reported only once for each function it appears in
prog.c:15:40: error: expected expression before ‘)’ token
         if (rec!=NULL) rec->next=(node*)cur;
                                        ^
</code>```

Live demo by Deduplicator.

is node* a kind of data types like int* or char*?

No. What you have there will result in an error, unless you define node yourself.

Does the type of pointer "next" and the initial name of struct have to same?

That's the idea.

Body:
#include<stdio.h>
#include<stdlib.h>
typedef struct {
    int val;
    struct node* next;
} Node, *NodePtr;
void makeInitialLinkedList(int a[], int n)
{
    int i;
    NodePtr rec=NULL;
    NodePtr head=NULL;
    for (i=0; i<n; i++) {
        NodePtr cur=(NodePtr)malloc(sizeof(Node));
        if (i==0) head=cur;
        if (rec!=NULL) rec->next=(node*)cur;
        cur->val=a[i];
        cur->next=NULL;
        rec=cur;
    }

    // test
    while(n--) {
        printf("%d ", head->val);
        head=(NodePtr)head->next;
    }
}
NodePtr copy(NodePtr head)
{
    return NULL;
}
int main()
{
    //Mission #2
    int initialDataArray[10]={5,3,2,8,9,7,0,6,4,1};
    makeInitialLinkedList(initialDataArray, 10);

}

I do not understand why this works. I did not make a name initially for the struct and only made a surname "Node" by typedef. Then how does "struct node* next" work correctly? is node* a kind of data types like int* or char*? I thought like this:

typedef struct strName {
    int val;
    struct strName* next;
} strSurName, *strPtr;

Does the type of pointer "next" and the initial name of struct have to same?

Body:
I do not understand why this works.

It doesn't, you should get compilation errors, like these with gcc 6.3 or 4.2.1:

prog.c: In function ‘makeInitialLinkedList’:
prog.c:15:35: error: ‘node’ undeclared (first use in this function)
         if (rec!=NULL) rec->next=(node*)cur;
                                   ^~~~
prog.c:15:35: note: each undeclared identifier is reported only once for each function it appears in
prog.c:15:40: error: expected expression before ‘)’ token
         if (rec!=NULL) rec->next=(node*)cur;
                                        ^

Live demo by Deduplicator.

is node* a kind of data types like int* or char*?

No. What you have there will result in an error, unless you define node yourself.

Does the type of pointer "next" and the initial name of struct have to same?

That's the idea.


问:
Updating Ruby via RVM issue, seems to be a problem with libxml
I was about to start my first Rails 3 app and thought I would upgrade to the latest version of ruby before I did and the ruby fails to make correctly.

I'm using Snow leopard on the 32bit kernal at the moment and every time I try and run 1.9.2 whether it's through readline or ssl I still get the following error:

```<code>ld: warning: in ../../libruby.dylib, file was built for unsupported file format which is not the architecture being linked (i386)
ld: in /Developer/SDKs/MacOSX10.6.sdk/usr/local/lib/libxml2.2.dylib, file was built for unsupported file format which is not the architecture being linked (i386)
collect2: ld returned 1 exit status
make[1]: *** [../../.ext/i386-darwin10.5.0/tcltklib.bundle] Error 1
</code>```

I tried using the 64 kernal using this among other as a guide http://www.markhneedham.com/blog/2010/07/08/installing-ruby-1-9-2-with-rvm-on-snow-leopard/  but then I get a similar message saying libxml1.dylib is failing because it's not set up to 64bit.

Has anyone got any ideas? it's driving me nuts...

答:
You need to make sure your Ruby is 64-bit, and the native gem drivers match it. ruby -v on 64-bit Snow Leopard should display:

```<code>ruby 1.9.2p0 (2010-08-18 revision 29036) [x86_64-darwin10.5.0]
</code>```

Your gems will complain about the architecture, returning the i386 fingerprint when there is a mismatch. To fix that you can try:

```<code>gem pristine --all
</code>```

which should walk through all gems and reload them from the clean cached versions. In that process any native drives should be rebuilt.

Body:
I was about to start my first Rails 3 app and thought I would upgrade to the latest version of ruby before I did and the ruby fails to make correctly.

I'm using Snow leopard on the 32bit kernal at the moment and every time I try and run 1.9.2 whether it's through readline or ssl I still get the following error:

ld: warning: in ../../libruby.dylib, file was built for unsupported file format which is not the architecture being linked (i386)
ld: in /Developer/SDKs/MacOSX10.6.sdk/usr/local/lib/libxml2.2.dylib, file was built for unsupported file format which is not the architecture being linked (i386)
collect2: ld returned 1 exit status
make[1]: *** [../../.ext/i386-darwin10.5.0/tcltklib.bundle] Error 1

I tried using the 64 kernal using this among other as a guide http://www.markhneedham.com/blog/2010/07/08/installing-ruby-1-9-2-with-rvm-on-snow-leopard/  but then I get a similar message saying libxml1.dylib is failing because it's not set up to 64bit.

Has anyone got any ideas? it's driving me nuts...

Body:
You need to make sure your Ruby is 64-bit, and the native gem drivers match it. ruby -v on 64-bit Snow Leopard should display:

ruby 1.9.2p0 (2010-08-18 revision 29036) [x86_64-darwin10.5.0]

Your gems will complain about the architecture, returning the i386 fingerprint when there is a mismatch. To fix that you can try:

gem pristine --all

which should walk through all gems and reload them from the clean cached versions. In that process any native drives should be rebuilt.


问:
Use non standard types in Azure Easy Tables
I'm trying to use Azures Easy Tables in my Xamarin Application.

I have data in 2 tables in azure which i added through csv. These tables include only standard types like string, date and numbers and are correctly synced to the device.

Additionally i have several other tables which are present in the local sync store. These tables / classes also use non standard types i defined myself. For example i habe a class Contact which has a property Company, which again is another class with several standard properties. These tables are currently only saved locally in the sync store, and it's working as expected. I'm now trying to sync these tables to to Azure Easy Tables.

So what i did was creating the table as an Azure Easy Table in Azure named Contact, with dynamic schema activated. When i try to Client.SyncContext.PushAsync() i get the following Exception:

```<code>MobileServiceLocalStoreException:
"Push operation has failed. See the PushResult for details."

Inner Exception / JsonReaderException:
"Failed to read errors from the local store."

Inner Exception / JsonException
"Unexpected character encountered while parsing value: C. Path '', line 0, position 0."
</code>```

Push Result seems to provide no information (Error Count 0)

I have no idea what this Exception tells me. Maybe the problem has something to do with the properties being non standard? How are these properties even mapped to an easy table. Is a non-standard property like company simply split into several columns like Name, Street, City?

Or does the Exception point to some other problem with the local sync Store? As i said, the local syncstore is currently working fine and the pull from azure easy tables for some tables is also working fine.

I'm grateful for every answer that might point me in the right direction.

答:
Per my understanding, you are handling 1:1 relationships between Contact and Company tables. For offline sync, you need to define the Contact and Company classes in your mobile client as follows:

For mobile client models

public class Contact : TableData
{
   public string ContactName {get;set;}
   public string Phone {get;set;}
   public string Address {get;set;}
   public string CompanyId {get;set;}
}

public class Company : TableData
{
   public string CompanyName {get;set;}
   public string Address {get;set;}
}
```

Note: As adrian hall's book Chapter3 :Relationships states about relationships on mobile client as follows:

There are a couple of rules you must follow within your client code:

You need to ensure that you create a Company before associating that Company with a Contact.

You need to store the CompanyId with the Contact, not the Company object (as you would normally do within Entity Framework).

If you InsertAsync a Company in offline mode, it will be placed into the operations queue prior to anything that uses it. Since the operations queue is processed in order, the Company will be sent to the backend prior to any record updates that would use it.

For Azure Easy Tables, you need to create both Contact and Company tables, and it would automatically create the Node.js backend for your created tables.

I would prefer handling tables individually and handling relationship management on the mobile client manually which could make the server much simpler by avoiding most of the complexity of relationships. Additionally, you could refer to Chapter 3 - Data Access and Offline Sync.

Body:
I'm trying to use Azures Easy Tables in my Xamarin Application.

I have data in 2 tables in azure which i added through csv. These tables include only standard types like string, date and numbers and are correctly synced to the device.

Additionally i have several other tables which are present in the local sync store. These tables / classes also use non standard types i defined myself. For example i habe a class Contact which has a property Company, which again is another class with several standard properties. These tables are currently only saved locally in the sync store, and it's working as expected. I'm now trying to sync these tables to to Azure Easy Tables.

So what i did was creating the table as an Azure Easy Table in Azure named Contact, with dynamic schema activated. When i try to Client.SyncContext.PushAsync() i get the following Exception:

MobileServiceLocalStoreException:
"Push operation has failed. See the PushResult for details."

Inner Exception / JsonReaderException:
"Failed to read errors from the local store."

Inner Exception / JsonException
"Unexpected character encountered while parsing value: C. Path '', line 0, position 0."

Push Result seems to provide no information (Error Count 0)

I have no idea what this Exception tells me. Maybe the problem has something to do with the properties being non standard? How are these properties even mapped to an easy table. Is a non-standard property like company simply split into several columns like Name, Street, City?

Or does the Exception point to some other problem with the local sync Store? As i said, the local syncstore is currently working fine and the pull from azure easy tables for some tables is also working fine.

I'm grateful for every answer that might point me in the right direction.

Body:
Per my understanding, you are handling 1:1 relationships between Contact and Company tables. For offline sync, you need to define the Contact and Company classes in your mobile client as follows:

For mobile client models

public class Contact : TableData
{
   public string ContactName {get;set;}
   public string Phone {get;set;}
   public string Address {get;set;}
   public string CompanyId {get;set;}
}

public class Company : TableData
{
   public string CompanyName {get;set;}
   public string Address {get;set;}
}

Note: As adrian hall's book Chapter3 :Relationships states about relationships on mobile client as follows:

There are a couple of rules you must follow within your client code:

You need to ensure that you create a Company before associating that Company with a Contact.

You need to store the CompanyId with the Contact, not the Company object (as you would normally do within Entity Framework).

If you InsertAsync a Company in offline mode, it will be placed into the operations queue prior to anything that uses it. Since the operations queue is processed in order, the Company will be sent to the backend prior to any record updates that would use it.

For Azure Easy Tables, you need to create both Contact and Company tables, and it would automatically create the Node.js backend for your created tables.

I would prefer handling tables individually and handling relationship management on the mobile client manually which could make the server much simpler by avoiding most of the complexity of relationships. Additionally, you could refer to Chapter 3 - Data Access and Offline Sync.


问:
Need a better understanding of these operations with const pointers in C
As a follow up to this question: How do you specify variables to be final in C?, I've been playing around with const variables. In particular, I've written and compiled the following program:

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

int main(void) {
    const int i = 5;
    int* i_ptr = &i;

    *i_ptr = *i_ptr + 1;      // (1)

    printf("%d %d\n", *i_ptr, i);

    int j = 10;
    const int* j_ptr = &j;

    j_ptr = i_ptr;       // (2)

    printf("%d %d\n", *j_ptr, j);

    return 0;
}
</code>```

I'm working with the following gcc compiler:

```<code>$ gcc --version
Apple LLVM version 8.1.0 (clang-802.0.42)
Target: x86_64-apple-darwin16.5.0
Thread model: posix
</code>```

In the code listing, I've marked two lines of code that behave differently than I'd expect:

(1)  I would expect the compiler to spit at me for trying to modify the const variable i that i_ptr but to my surprise it does not.

(2)  I would expect another error to be generated here because j_ptr has just been declared const and now modifying it is perfectly okay.

Further more, here is the output I get:

```<code>6 5
6 10
</code>```

What's surprising here is that, in the first line out output, i_ptr and i do not have the same values here. What gives? I certainly didn't call malloc and assign i_ptr to new memory.

So how is it pointing to something besides i?

What's even more puzzling is that, if I replace line (2) with this:

```<code>*j_ptr = *j_ptr + 1;
</code>```

I get

error: read-only variable is not assignable

I'd expect that, since j_ptr is pointing to non-const variable j, it should increment j. But that doesn't happen.

I'd really appreciate if someone could explain my observations, as I can't seem to come up with any reasons for why these const pointers should behave this counter-intuitively.

答:
Quoting C11, chapter §6.7.3

If an attempt is made to modify an object defined with a const-qualified type through use
  of an lvalue with non-const-qualified type, the behavior is undefined. [...]

So, the syntax is not forbidden as per the standard, just doing so  causes undefined behavior. Any compiler, with sufficient level of warnings enabled should scream at the assignments which attempts to discards the const qualifier.

Secondly, in case of const int* j_ptr = &j;, the const is applicable for the pointed type, not the value of the variable. Thus, you can change j_ptr, but not *j_ptr.

Body:
As a follow up to this question: How do you specify variables to be final in C?, I've been playing around with const variables. In particular, I've written and compiled the following program:

#include<stdio.h>

int main(void) {
    const int i = 5;
    int* i_ptr = &i;

    *i_ptr = *i_ptr + 1;      // (1)

    printf("%d %d\n", *i_ptr, i);

    int j = 10;
    const int* j_ptr = &j;

    j_ptr = i_ptr;       // (2)

    printf("%d %d\n", *j_ptr, j);

    return 0;
}

I'm working with the following gcc compiler:

$ gcc --version
Apple LLVM version 8.1.0 (clang-802.0.42)
Target: x86_64-apple-darwin16.5.0
Thread model: posix

In the code listing, I've marked two lines of code that behave differently than I'd expect:

(1)  I would expect the compiler to spit at me for trying to modify the const variable i that i_ptr but to my surprise it does not.

(2)  I would expect another error to be generated here because j_ptr has just been declared const and now modifying it is perfectly okay.

Further more, here is the output I get:

6 5
6 10

What's surprising here is that, in the first line out output, i_ptr and i do not have the same values here. What gives? I certainly didn't call malloc and assign i_ptr to new memory.

So how is it pointing to something besides i?

What's even more puzzling is that, if I replace line (2) with this:

*j_ptr = *j_ptr + 1;

I get

error: read-only variable is not assignable

I'd expect that, since j_ptr is pointing to non-const variable j, it should increment j. But that doesn't happen.

I'd really appreciate if someone could explain my observations, as I can't seem to come up with any reasons for why these const pointers should behave this counter-intuitively.


问:
How to change button color when radio input is selected, but input is wrapped in div before label?
I am trying to make our dinky radio buttons into lovely toggle buttons on our donation page. The HTML cannot be modified, and as it stands the inputs are wrapped in divs, then followed by the labels. I have zero knowledge of JS/jQuery and I imagine this task requires some.

Here is my fiddle: https://jsfiddle.net/cgz63qhd/

body {
  padding: 10px;
  font-family: sans-serif;
}

div.donation-levels {
  margin: 3px 0;
}

.donation-level-container {
  display: inline-block;
}

.donation-level-container input {
  visibility: hidden;
}

.donation-level-amount-container {
  text-align: center;
  margin: 5px 2px;
  padding: 0.7em 2em;
  color: #ffffff;
  background-color: #1a92b4;
  border-radius: 5px;
  display: inline-block;
  cursor: pointer;
  font-size: 22px;
}

.donation-level-amount-container:hover {
  background: #e8525f;
  color: #ffffff;
}

.donation-level-label-input-container input:checked~label {
  background: #e8525f;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="donation-level-container">
  <div class="form-content">

    <div class="donation-level-input-container form-input">

      <div class="donation-level-label-input-container">
        <input name="level_flexibleexpanded" id="level_flexibleexpanded5942" value="5942" onclick="evalMatchingGift('$35.00');" type="radio">
      </div>

      <label for="level_flexibleexpanded5942" onclick="">

    <div class="donation-level-amount-container">
    $35.00
    </div>

    </label>

    </div>

    <input name="level_flexibleexpandedsubmit" id="level_flexible_5942expandedsubmit" value="true" type="hidden">
  </div>
</div>
<div class="donation-level-container">
  <div class="form-content">

    <div class="donation-level-input-container form-input">

      <div class="donation-level-label-input-container">
        <input name="level_flexibleexpanded" id="level_flexibleexpanded5943" value="5943" onclick="evalMatchingGift('$60.00');" type="radio">
      </div>

      <label for="level_flexibleexpanded5943" onclick="">

    <div class="donation-level-amount-container">
    $60.00
    </div>

    </label>

    </div>

    <input name="level_flexibleexpandedsubmit" id="level_flexible_5943expandedsubmit" value="true" type="hidden">
  </div>
</div>
<div class="donation-level-container">
  <div class="form-content">

    <div class="donation-level-input-container form-input">

      <div class="donation-level-label-input-container">
        <input name="level_flexibleexpanded" id="level_flexibleexpanded5944" value="5944" onclick="evalMatchingGift('$120.00');" type="radio">
      </div>

      <label for="level_flexibleexpanded5944" onclick="">

    <div class="donation-level-amount-container">
    $120.00
    </div>

    </label>

    </div>

    <input name="level_flexibleexpandedsubmit" id="level_flexible_5944expandedsubmit" value="true" type="hidden">
  </div>
</div></code>```

Here is my inspiration donate page: https://action.audubon.org/donate/now

Alas, their labels are set up better so I think they were able to make the buttons with pure CSS (?).

My buttons currently are looking decent, are sized fine and colored nicely, but they just won't stay that coral color when clicked! Can someone help me out?

I've seen a lot of questions here on this topic but I can't seem to get anything to work.

I'm sure there are other issues in the code, please point them out if you see them!

答:
```<code>$(".donation-level-amount-container").on("click", function() {
  $('.donation-level-amount-container').each(function() {
      $(this).removeClass('active');
    });
  $(this).toggleClass('active');
})
</code>```

And css

```<code>.active {
  background:#e8525f;
  color:#ffffff;
}
</code>```

Working fiddle:
https://jsfiddle.net/29exoa4k/2/

Body:
I am trying to make our dinky radio buttons into lovely toggle buttons on our donation page. The HTML cannot be modified, and as it stands the inputs are wrapped in divs, then followed by the labels. I have zero knowledge of JS/jQuery and I imagine this task requires some.

Here is my fiddle: https://jsfiddle.net/cgz63qhd/

body {
  padding: 10px;
  font-family: sans-serif;
}

div.donation-levels {
  margin: 3px 0;
}

.donation-level-container {
  display: inline-block;
}

.donation-level-container input {
  visibility: hidden;
}

.donation-level-amount-container {
  text-align: center;
  margin: 5px 2px;
  padding: 0.7em 2em;
  color: #ffffff;
  background-color: #1a92b4;
  border-radius: 5px;
  display: inline-block;
  cursor: pointer;
  font-size: 22px;
}

.donation-level-amount-container:hover {
  background: #e8525f;
  color: #ffffff;
}

.donation-level-label-input-container input:checked~label {
  background: #e8525f;
}

        <input name="level_flexibleexpanded" id="level_flexibleexpanded5942" value="5942" onclick="evalMatchingGift('$35.00');" type="radio">

    $35.00

    <input name="level_flexibleexpandedsubmit" id="level_flexible_5942expandedsubmit" value="true" type="hidden">

        <input name="level_flexibleexpanded" id="level_flexibleexpanded5943" value="5943" onclick="evalMatchingGift('$60.00');" type="radio">

    $60.00

    <input name="level_flexibleexpandedsubmit" id="level_flexible_5943expandedsubmit" value="true" type="hidden">

        <input name="level_flexibleexpanded" id="level_flexibleexpanded5944" value="5944" onclick="evalMatchingGift('$120.00');" type="radio">

    $120.00

    <input name="level_flexibleexpandedsubmit" id="level_flexible_5944expandedsubmit" value="true" type="hidden">

Here is my inspiration donate page: https://action.audubon.org/donate/now

Alas, their labels are set up better so I think they were able to make the buttons with pure CSS (?).

My buttons currently are looking decent, are sized fine and colored nicely, but they just won't stay that coral color when clicked! Can someone help me out?

I've seen a lot of questions here on this topic but I can't seem to get anything to work.

I'm sure there are other issues in the code, please point them out if you see them!

Body:
$(".donation-level-amount-container").on("click", function() {
  $('.donation-level-amount-container').each(function() {
      $(this).removeClass('active');
    });
  $(this).toggleClass('active');
})

And css

.active {
  background:#e8525f;
  color:#ffffff;
}

Working fiddle:
https://jsfiddle.net/29exoa4k/2/


问:
Can't get radio button styling to work in plunker
I'm trying to get the skewed radio button style found here (https://codepen.io/anon/pen/yXNopJ) to work in my project. Visually it looks right but doesn't do anything on click. So to debug I thought I'd place this in plunker and play around with it in an isolated area. However when I copy and paste the html and css into Plunker the visuals don't work. Can anyone see why the visuals don't work in plunker but do in codepen?

http://plnkr.co/edit/IPiDZdLS51UzAwUcQZHp?p=preview

HTML

```<code><h2>Toggle 'em</h2>
<ul class="tg-list">
  <li class="tg-list-item">
    <h4>Light</h4>
    <input class="tgl tgl-light" id="cb1" type="checkbox"/>
    <label class="tgl-btn" for="cb1"></label>
  </li>
  <li class="tg-list-item">
    <h4>iOS</h4>
    <input class="tgl tgl-ios" id="cb2" type="checkbox"/>
    <label class="tgl-btn" for="cb2"></label>
  </li>
  <li class="tg-list-item">
    <h4>Skewed</h4>
    <input class="tgl tgl-skewed" id="cb3" type="checkbox"/>
    <label class="tgl-btn" data-tg-off="OFF" data-tg-on="ON" for="cb3"></label>
  </li>
  <li class="tg-list-item">
    <h4>Flat</h4>
    <input class="tgl tgl-flat" id="cb4" type="checkbox"/>
    <label class="tgl-btn" for="cb4"></label>
  </li>
  <li class="tg-list-item">
    <h4>Flip</h4>
    <input class="tgl tgl-flip" id="cb5" type="checkbox"/>
    <label class="tgl-btn" data-tg-off="Nope" data-tg-on="Yeah!" for="cb5"></label>
  </li>
</ul>
</code>```

CSS

```<code>html, body {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  min-height: 100%;
  -webkit-box-pack: center;
      -ms-flex-pack: center;
          justify-content: center;
  -webkit-box-align: center;
      -ms-flex-align: center;
          align-items: center;
  -webkit-box-orient: vertical;
  -webkit-box-direction: normal;
      -ms-flex-direction: column;
          flex-direction: column;
  font-family: sans-serif;
}

ul, li {
  list-style: none;
  margin: 0;
  padding: 0;
}

.tg-list {
  text-align: center;
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-align: center;
      -ms-flex-align: center;
          align-items: center;
}

.tg-list-item {
  margin: 0 2em;
}

h2 {
  color: #777;
}

h4 {
  color: #999;
}

.tgl {
  display: none;
}
.tgl, .tgl:after, .tgl:before, .tgl *, .tgl *:after, .tgl *:before, .tgl + .tgl-btn {
  box-sizing: border-box;
}
.tgl::-moz-selection, .tgl:after::-moz-selection, .tgl:before::-moz-selection, .tgl *::-moz-selection, .tgl *:after::-moz-selection, .tgl *:before::-moz-selection, .tgl + .tgl-btn::-moz-selection {
  background: none;
}
.tgl::selection, .tgl:after::selection, .tgl:before::selection, .tgl *::selection, .tgl *:after::selection, .tgl *:before::selection, .tgl + .tgl-btn::selection {
  background: none;
}
.tgl + .tgl-btn {
  outline: 0;
  display: block;
  width: 4em;
  height: 2em;
  position: relative;
  cursor: pointer;
  -webkit-user-select: none;
     -moz-user-select: none;
      -ms-user-select: none;
          user-select: none;
}
.tgl + .tgl-btn:after, .tgl + .tgl-btn:before {
  position: relative;
  display: block;
  content: "";
  width: 50%;
  height: 100%;
}
.tgl + .tgl-btn:after {
  left: 0;
}
.tgl + .tgl-btn:before {
  display: none;
}
.tgl:checked + .tgl-btn:after {
  left: 50%;
}

.tgl-light + .tgl-btn {
  background: #f0f0f0;
  border-radius: 2em;
  padding: 2px;
  -webkit-transition: all .4s ease;
  transition: all .4s ease;
}
.tgl-light + .tgl-btn:after {
  border-radius: 50%;
  background: #fff;
  -webkit-transition: all .2s ease;
  transition: all .2s ease;
}
.tgl-light:checked + .tgl-btn {
  background: #9FD6AE;
}

.tgl-ios + .tgl-btn {
  background: #fbfbfb;
  border-radius: 2em;
  padding: 2px;
  -webkit-transition: all .4s ease;
  transition: all .4s ease;
  border: 1px solid #e8eae9;
}
.tgl-ios + .tgl-btn:after {
  border-radius: 2em;
  background: #fbfbfb;
  -webkit-transition: left 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275), padding 0.3s ease, margin 0.3s ease;
  transition: left 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275), padding 0.3s ease, margin 0.3s ease;
  box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.1), 0 4px 0 rgba(0, 0, 0, 0.08);
}
.tgl-ios + .tgl-btn:hover:after {
  will-change: padding;
}
.tgl-ios + .tgl-btn:active {
  box-shadow: inset 0 0 0 2em #e8eae9;
}
.tgl-ios + .tgl-btn:active:after {
  padding-right: .8em;
}
.tgl-ios:checked + .tgl-btn {
  background: #86d993;
}
.tgl-ios:checked + .tgl-btn:active {
  box-shadow: none;
}
.tgl-ios:checked + .tgl-btn:active:after {
  margin-left: -.8em;
}

.tgl-skewed + .tgl-btn {
  overflow: hidden;
  -webkit-transform: skew(-10deg);
          transform: skew(-10deg);
  -webkit-backface-visibility: hidden;
          backface-visibility: hidden;
  -webkit-transition: all .2s ease;
  transition: all .2s ease;
  font-family: sans-serif;
  background: #888;
}
.tgl-skewed + .tgl-btn:after, .tgl-skewed + .tgl-btn:before {
  -webkit-transform: skew(10deg);
          transform: skew(10deg);
  display: inline-block;
  -webkit-transition: all .2s ease;
  transition: all .2s ease;
  width: 100%;
  text-align: center;
  position: absolute;
  line-height: 2em;
  font-weight: bold;
  color: #fff;
  text-shadow: 0 1px 0 rgba(0, 0, 0, 0.4);
}
.tgl-skewed + .tgl-btn:after {
  left: 100%;
  content: attr(data-tg-on);
}
.tgl-skewed + .tgl-btn:before {
  left: 0;
  content: attr(data-tg-off);
}
.tgl-skewed + .tgl-btn:active {
  background: #888;
}
.tgl-skewed + .tgl-btn:active:before {
  left: -10%;
}
.tgl-skewed:checked + .tgl-btn {
  background: #86d993;
}
.tgl-skewed:checked + .tgl-btn:before {
  left: -100%;
}
.tgl-skewed:checked + .tgl-btn:after {
  left: 0;
}
.tgl-skewed:checked + .tgl-btn:active:after {
  left: 10%;
}

.tgl-flat + .tgl-btn {
  padding: 2px;
  -webkit-transition: all .2s ease;
  transition: all .2s ease;
  background: #fff;
  border: 4px solid #f2f2f2;
  border-radius: 2em;
}
.tgl-flat + .tgl-btn:after {
  -webkit-transition: all .2s ease;
  transition: all .2s ease;
  background: #f2f2f2;
  content: "";
  border-radius: 1em;
}
.tgl-flat:checked + .tgl-btn {
  border: 4px solid #7FC6A6;
}
.tgl-flat:checked + .tgl-btn:after {
  left: 50%;
  background: #7FC6A6;
}

.tgl-flip + .tgl-btn {
  padding: 2px;
  -webkit-transition: all .2s ease;
  transition: all .2s ease;
  font-family: sans-serif;
  -webkit-perspective: 100px;
          perspective: 100px;
}
.tgl-flip + .tgl-btn:after, .tgl-flip + .tgl-btn:before {
  display: inline-block;
  -webkit-transition: all .4s ease;
  transition: all .4s ease;
  width: 100%;
  text-align: center;
  position: absolute;
  line-height: 2em;
  font-weight: bold;
  color: #fff;
  position: absolute;
  top: 0;
  left: 0;
  -webkit-backface-visibility: hidden;
          backface-visibility: hidden;
  border-radius: 4px;
}
.tgl-flip + .tgl-btn:after {
  content: attr(data-tg-on);
  background: #02C66F;
  -webkit-transform: rotateY(-180deg);
          transform: rotateY(-180deg);
}
.tgl-flip + .tgl-btn:before {
  background: #FF3A19;
  content: attr(data-tg-off);
}
.tgl-flip + .tgl-btn:active:before {
  -webkit-transform: rotateY(-20deg);
          transform: rotateY(-20deg);
}
.tgl-flip:checked + .tgl-btn:before {
  -webkit-transform: rotateY(180deg);
          transform: rotateY(180deg);
}
.tgl-flip:checked + .tgl-btn:after {
  -webkit-transform: rotateY(0);
          transform: rotateY(0);
  left: 0;
  background: #7FC6A6;
}
.tgl-flip:checked + .tgl-btn:active:after {
  -webkit-transform: rotateY(20deg);
          transform: rotateY(20deg);
}
</code>```

答:
Just add this code at the top of your html file.</p>

```<code><!DOCTYPE html>
<html>

  <head>
    <link rel="stylesheet" href="style.css">
    <script src="script.js"></script>
  </head>

  <body>
</code>```

Body:
I'm trying to get the skewed radio button style found here (https://codepen.io/anon/pen/yXNopJ) to work in my project. Visually it looks right but doesn't do anything on click. So to debug I thought I'd place this in plunker and play around with it in an isolated area. However when I copy and paste the html and css into Plunker the visuals don't work. Can anyone see why the visuals don't work in plunker but do in codepen?

http://plnkr.co/edit/IPiDZdLS51UzAwUcQZHp?p=preview

HTML

Toggle 'em

Light

    <input class="tgl tgl-light" id="cb1" type="checkbox"/>

iOS

    <input class="tgl tgl-ios" id="cb2" type="checkbox"/>

Skewed

    <input class="tgl tgl-skewed" id="cb3" type="checkbox"/>

Flat

    <input class="tgl tgl-flat" id="cb4" type="checkbox"/>

Flip

    <input class="tgl tgl-flip" id="cb5" type="checkbox"/>

CSS

html, body {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  min-height: 100%;
  -webkit-box-pack: center;
      -ms-flex-pack: center;
          justify-content: center;
  -webkit-box-align: center;
      -ms-flex-align: center;
          align-items: center;
  -webkit-box-orient: vertical;
  -webkit-box-direction: normal;
      -ms-flex-direction: column;
          flex-direction: column;
  font-family: sans-serif;
}

ul, li {
  list-style: none;
  margin: 0;
  padding: 0;
}

.tg-list {
  text-align: center;
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-align: center;
      -ms-flex-align: center;
          align-items: center;
}

.tg-list-item {
  margin: 0 2em;
}

h2 {
  color: #777;
}

h4 {
  color: #999;
}

.tgl {
  display: none;
}
.tgl, .tgl:after, .tgl:before, .tgl *, .tgl *:after, .tgl *:before, .tgl + .tgl-btn {
  box-sizing: border-box;
}
.tgl::-moz-selection, .tgl:after::-moz-selection, .tgl:before::-moz-selection, .tgl *::-moz-selection, .tgl *:after::-moz-selection, .tgl *:before::-moz-selection, .tgl + .tgl-btn::-moz-selection {
  background: none;
}
.tgl::selection, .tgl:after::selection, .tgl:before::selection, .tgl *::selection, .tgl *:after::selection, .tgl *:before::selection, .tgl + .tgl-btn::selection {
  background: none;
}
.tgl + .tgl-btn {
  outline: 0;
  display: block;
  width: 4em;
  height: 2em;
  position: relative;
  cursor: pointer;
  -webkit-user-select: none;
     -moz-user-select: none;
      -ms-user-select: none;
          user-select: none;
}
.tgl + .tgl-btn:after, .tgl + .tgl-btn:before {
  position: relative;
  display: block;
  content: "";
  width: 50%;
  height: 100%;
}
.tgl + .tgl-btn:after {
  left: 0;
}
.tgl + .tgl-btn:before {
  display: none;
}
.tgl:checked + .tgl-btn:after {
  left: 50%;
}

.tgl-light + .tgl-btn {
  background: #f0f0f0;
  border-radius: 2em;
  padding: 2px;
  -webkit-transition: all .4s ease;
  transition: all .4s ease;
}
.tgl-light + .tgl-btn:after {
  border-radius: 50%;
  background: #fff;
  -webkit-transition: all .2s ease;
  transition: all .2s ease;
}
.tgl-light:checked + .tgl-btn {
  background: #9FD6AE;
}

.tgl-ios + .tgl-btn {
  background: #fbfbfb;
  border-radius: 2em;
  padding: 2px;
  -webkit-transition: all .4s ease;
  transition: all .4s ease;
  border: 1px solid #e8eae9;
}
.tgl-ios + .tgl-btn:after {
  border-radius: 2em;
  background: #fbfbfb;
  -webkit-transition: left 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275), padding 0.3s ease, margin 0.3s ease;
  transition: left 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275), padding 0.3s ease, margin 0.3s ease;
  box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.1), 0 4px 0 rgba(0, 0, 0, 0.08);
}
.tgl-ios + .tgl-btn:hover:after {
  will-change: padding;
}
.tgl-ios + .tgl-btn:active {
  box-shadow: inset 0 0 0 2em #e8eae9;
}
.tgl-ios + .tgl-btn:active:after {
  padding-right: .8em;
}
.tgl-ios:checked + .tgl-btn {
  background: #86d993;
}
.tgl-ios:checked + .tgl-btn:active {
  box-shadow: none;
}
.tgl-ios:checked + .tgl-btn:active:after {
  margin-left: -.8em;
}

.tgl-skewed + .tgl-btn {
  overflow: hidden;
  -webkit-transform: skew(-10deg);
          transform: skew(-10deg);
  -webkit-backface-visibility: hidden;
          backface-visibility: hidden;
  -webkit-transition: all .2s ease;
  transition: all .2s ease;
  font-family: sans-serif;
  background: #888;
}
.tgl-skewed + .tgl-btn:after, .tgl-skewed + .tgl-btn:before {
  -webkit-transform: skew(10deg);
          transform: skew(10deg);
  display: inline-block;
  -webkit-transition: all .2s ease;
  transition: all .2s ease;
  width: 100%;
  text-align: center;
  position: absolute;
  line-height: 2em;
  font-weight: bold;
  color: #fff;
  text-shadow: 0 1px 0 rgba(0, 0, 0, 0.4);
}
.tgl-skewed + .tgl-btn:after {
  left: 100%;
  content: attr(data-tg-on);
}
.tgl-skewed + .tgl-btn:before {
  left: 0;
  content: attr(data-tg-off);
}
.tgl-skewed + .tgl-btn:active {
  background: #888;
}
.tgl-skewed + .tgl-btn:active:before {
  left: -10%;
}
.tgl-skewed:checked + .tgl-btn {
  background: #86d993;
}
.tgl-skewed:checked + .tgl-btn:before {
  left: -100%;
}
.tgl-skewed:checked + .tgl-btn:after {
  left: 0;
}
.tgl-skewed:checked + .tgl-btn:active:after {
  left: 10%;
}

.tgl-flat + .tgl-btn {
  padding: 2px;
  -webkit-transition: all .2s ease;
  transition: all .2s ease;
  background: #fff;
  border: 4px solid #f2f2f2;
  border-radius: 2em;
}
.tgl-flat + .tgl-btn:after {
  -webkit-transition: all .2s ease;
  transition: all .2s ease;
  background: #f2f2f2;
  content: "";
  border-radius: 1em;
}
.tgl-flat:checked + .tgl-btn {
  border: 4px solid #7FC6A6;
}
.tgl-flat:checked + .tgl-btn:after {
  left: 50%;
  background: #7FC6A6;
}

.tgl-flip + .tgl-btn {
  padding: 2px;
  -webkit-transition: all .2s ease;
  transition: all .2s ease;
  font-family: sans-serif;
  -webkit-perspective: 100px;
          perspective: 100px;
}
.tgl-flip + .tgl-btn:after, .tgl-flip + .tgl-btn:before {
  display: inline-block;
  -webkit-transition: all .4s ease;
  transition: all .4s ease;
  width: 100%;
  text-align: center;
  position: absolute;
  line-height: 2em;
  font-weight: bold;
  color: #fff;
  position: absolute;
  top: 0;
  left: 0;
  -webkit-backface-visibility: hidden;
          backface-visibility: hidden;
  border-radius: 4px;
}
.tgl-flip + .tgl-btn:after {
  content: attr(data-tg-on);
  background: #02C66F;
  -webkit-transform: rotateY(-180deg);
          transform: rotateY(-180deg);
}
.tgl-flip + .tgl-btn:before {
  background: #FF3A19;
  content: attr(data-tg-off);
}
.tgl-flip + .tgl-btn:active:before {
  -webkit-transform: rotateY(-20deg);
          transform: rotateY(-20deg);
}
.tgl-flip:checked + .tgl-btn:before {
  -webkit-transform: rotateY(180deg);
          transform: rotateY(180deg);
}
.tgl-flip:checked + .tgl-btn:after {
  -webkit-transform: rotateY(0);
          transform: rotateY(0);
  left: 0;
  background: #7FC6A6;
}
.tgl-flip:checked + .tgl-btn:active:after {
  -webkit-transform: rotateY(20deg);
          transform: rotateY(20deg);
}

Body:
Just add this code at the top of your html file.

<!DOCTYPE html>
<html>

  <head>
    <link rel="stylesheet" href="style.css">
    <script src="script.js"></script>
  </head>

  <body>


问:
What is the difference between these fuctions?
What is the difference between these two way of defining a method?

```<code> var Todo = {};
    Todo.abc = function(){
    }
</code>```

and

```<code>function abc(){
}
</code>```

答:
The first is an anonymous function expression, stored in the abc property. These are not hoisted.

The second is a function declaration. It has a name property and it is hoisted.

From MDN:

The main difference between a function expression and a function statement is the function name, which can be omitted in function expressions to create anonymous functions.

Function expressions in JavaScript are not hoisted, unlike function declarations. You can't use function expressions before you define them:

Body:
What is the difference between these two way of defining a method?

 var Todo = {};
    Todo.abc = function(){
    }

and

function abc(){
}