问:
How to handle "ERROR: IOError: closed stream" in Golang scan function?
I am using knife bootstrap command in Golang code to bootstrap nodes. Some times there is wait in recipe and it waits for more than 10 minutes. In such cases I am getting an error "Error: IOStream Closed". Is there any way I can increase the time limit? Also I am continuously reading the logs from output and error stream of cmd.

```<code>func executeCMDWorkstation(cmd *exec.Cmd, projectId, cr_id string) bool {

stdout, err3 := cmd.StdoutPipe()
if err3 != nil {
    utils.Info.Println(err3)
    return false
}
defer stdout.Close()
stderr, err4 := cmd.StderrPipe()
if err4 != nil {
    utils.Info.Println(err4)
    return false
}
defer stderr.Close()

//cmd.Stdout = os.Stdout
//cmd.Stderr = os.Stderr
multi := io.MultiReader(stdout, stderr)
inp := bufio.NewScanner(multi)
err := cmd.Start()
if err != nil {
    utils.Info.Println("Error while creating client", err)
    return false
}
fmt.Println("Generating logs**************")
for inp.Scan() {

    line := inp.Text()
    if cr_id == "" {
        lg.SendDebugLogs(line, "projects/logs", projectId, "chef")
    } else {
        lg.SendDebugLogs(line, "changeRequests/logs", cr_id, "chef")
    }
}
exitStatus := cmd.Wait()
if exiterr, ok := exitStatus.(*exec.ExitError); ok {
    utils.Info.Println("************ Exit Status is:", exiterr, "************")
    return false
}

return true
</code>```

Any help to improve this process would be highly appreciated.

答:
After looking into some forums, Go Docs and trying some code changes, finally replacing the scan method in bufio to ReadLine of textproto worked for me.

I replaced the following code:

```<code>inp := bufio.NewScanner(multi)
err := cmd.Start()
if err != nil {
    utils.Info.Println("Error while creating client", err)
    return false
}
fmt.Println("Generating logs**************")
for inp.Scan() {
    line := inp.Text()
    if cr_id == "" {
        lg.SendDebugLogs(line, "projects/logs", projectId, "chef")
    } else {
        lg.SendDebugLogs(line, "changeRequests/logs", cr_id, "chef")
    }
}
</code>```

With the following code:

```<code>    inp1 := bufio.NewReader(multi)

    tp := textproto.NewReader( inp1 )

    err := cmd.Start()
    if err != nil {
        utils.Info.Println("Error while creating client", err)
        return false
    }
    fmt.Println("Generating logs**************")

    /*
    New code for logs starts here
     */

    for {
        line, readErr := tp.ReadLine()

        if readErr != nil {
                break
        }

        if cr_id == "" {
            lg.SendDebugLogs(line, "projects/logs", projectId, "chef")
        } else {
            lg.SendDebugLogs(line, "changeRequests/logs", cr_id, "chef")
        }
    }
</code>```

At last, this modification worked perfectly fine for me by handling immediate restarts as well as long sleeps/waits in the chef recipe or scripts. Basically I changed the stream reader I hope this will be helpful for anyone else facing the same problem :)

Body:
I am using knife bootstrap command in Golang code to bootstrap nodes. Some times there is wait in recipe and it waits for more than 10 minutes. In such cases I am getting an error "Error: IOStream Closed". Is there any way I can increase the time limit? Also I am continuously reading the logs from output and error stream of cmd.

func executeCMDWorkstation(cmd *exec.Cmd, projectId, cr_id string) bool {

stdout, err3 := cmd.StdoutPipe()
if err3 != nil {
    utils.Info.Println(err3)
    return false
}
defer stdout.Close()
stderr, err4 := cmd.StderrPipe()
if err4 != nil {
    utils.Info.Println(err4)
    return false
}
defer stderr.Close()

//cmd.Stdout = os.Stdout
//cmd.Stderr = os.Stderr
multi := io.MultiReader(stdout, stderr)
inp := bufio.NewScanner(multi)
err := cmd.Start()
if err != nil {
    utils.Info.Println("Error while creating client", err)
    return false
}
fmt.Println("Generating logs**************")
for inp.Scan() {

    line := inp.Text()
    if cr_id == "" {
        lg.SendDebugLogs(line, "projects/logs", projectId, "chef")
    } else {
        lg.SendDebugLogs(line, "changeRequests/logs", cr_id, "chef")
    }
}
exitStatus := cmd.Wait()
if exiterr, ok := exitStatus.(*exec.ExitError); ok {
    utils.Info.Println("************ Exit Status is:", exiterr, "************")
    return false
}

return true

Any help to improve this process would be highly appreciated.

Body:
After looking into some forums, Go Docs and trying some code changes, finally replacing the scan method in bufio to ReadLine of textproto worked for me.

I replaced the following code:

inp := bufio.NewScanner(multi)
err := cmd.Start()
if err != nil {
    utils.Info.Println("Error while creating client", err)
    return false
}
fmt.Println("Generating logs**************")
for inp.Scan() {
    line := inp.Text()
    if cr_id == "" {
        lg.SendDebugLogs(line, "projects/logs", projectId, "chef")
    } else {
        lg.SendDebugLogs(line, "changeRequests/logs", cr_id, "chef")
    }
}

With the following code:

    inp1 := bufio.NewReader(multi)

    tp := textproto.NewReader( inp1 )

    err := cmd.Start()
    if err != nil {
        utils.Info.Println("Error while creating client", err)
        return false
    }
    fmt.Println("Generating logs**************")

    /*
    New code for logs starts here
     */

    for {
        line, readErr := tp.ReadLine()

        if readErr != nil {
                break
        }

        if cr_id == "" {
            lg.SendDebugLogs(line, "projects/logs", projectId, "chef")
        } else {
            lg.SendDebugLogs(line, "changeRequests/logs", cr_id, "chef")
        }
    }

At last, this modification worked perfectly fine for me by handling immediate restarts as well as long sleeps/waits in the chef recipe or scripts. Basically I changed the stream reader I hope this will be helpful for anyone else facing the same problem :)


来源: stackexchange

问:
Python 3.0 Calling a value from a class function to print
Trying to call the total hours from the class/function down to the instance of the class I created below. (hope i worded that correctly)

```<code>class Employee:
  def __init__(self):
    self.wage = 0
    self.hours = 0
    if self.hours > 40:
      self.ot = self.hours - 40                 #overtime hours
      self.earned_ot = self.wage * 1.5          #overtime wage rate
      self.ot_total = self.ot * self.earned_ot  #pay for overtime hours
      self.pay = self.wage * 40                 #standard hour wage
      self.total = self.pay + self.ot_total     #standard wage + ot hour wage
    else:
      self.total = self.wage * self.hours

alice = Employee()
alice.wage = 20
alice.hours = 40
#alice.total =

bob = Employee()
bob.wage = 15
bob.hours = 50
#bob.total =

print("Alice: \n Net pay: ${} \nBob: \n Net pay: ${}" .format(alice.total,
bob.total))
</code>```

Issue I'm having seems simple enough but I can't for the life of me figure it out. I commented out the alice.total and bob.total for now, but those are what I need to get the print to work correctly.

I feel like i'm forgetting something simple, but browsing back through my notes/texts I can't figure it out. Does anyone who sees the issue that I'm having, have a link to something that might explain this? I'm not looking for an outright answer, just a point in the right direction.

Thanks.

答:
I think what you're looking for is the @property decorator:</p>

```<code>class Employee:
  def __init__(self):
    self.wage = 0
    self.hours = 0

  @property
  def total(self):
    if self.hours > 40:
      ot = self.hours - 40                 #overtime hours
      earned_ot = self.wage * 1.5          #overtime wage rate
      ot_total = ot * earned_ot  #pay for overtime hours
      pay = self.wage * 40                 #standard hour wage
      return pay + ot_total     #standard wage + ot hour wage
    else:
      return self.wage * self.hours
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Trying to call the total hours from the class/function down to the instance of the class I created below. (hope i worded that correctly)

class Employee:
  def __init__(self):
    self.wage = 0
    self.hours = 0
    if self.hours > 40:
      self.ot = self.hours - 40                 #overtime hours
      self.earned_ot = self.wage * 1.5          #overtime wage rate
      self.ot_total = self.ot * self.earned_ot  #pay for overtime hours
      self.pay = self.wage * 40                 #standard hour wage
      self.total = self.pay + self.ot_total     #standard wage + ot hour wage
    else:
      self.total = self.wage * self.hours

alice = Employee()
alice.wage = 20
alice.hours = 40
#alice.total =

bob = Employee()
bob.wage = 15
bob.hours = 50
#bob.total =

print("Alice: \n Net pay: ${} \nBob: \n Net pay: ${}" .format(alice.total,
bob.total))

Issue I'm having seems simple enough but I can't for the life of me figure it out. I commented out the alice.total and bob.total for now, but those are what I need to get the print to work correctly.

I feel like i'm forgetting something simple, but browsing back through my notes/texts I can't figure it out. Does anyone who sees the issue that I'm having, have a link to something that might explain this? I'm not looking for an outright answer, just a point in the right direction.

Thanks.

Body:
I think what you're looking for is the @property decorator:

class Employee:
  def __init__(self):
    self.wage = 0
    self.hours = 0

  @property
  def total(self):
    if self.hours > 40:
      ot = self.hours - 40                 #overtime hours
      earned_ot = self.wage * 1.5          #overtime wage rate
      ot_total = ot * earned_ot  #pay for overtime hours
      pay = self.wage * 40                 #standard hour wage
      return pay + ot_total     #standard wage + ot hour wage
    else:
      return self.wage * self.hours


问:
How to create an issue in Jira using the REST API?
How to create an issue in Jira using the REST API? I have tried the examples using curl. But I need to create defect in Eclipse using Java and REST API.</p>

答:
```<code>try {
        Client client = Client.create();
        client.addFilter(new HTTPBasicAuthFilter("username", "password"));

        String input = "{\"fields\":{\"project\":{\"key\":\"DEMO\"},\"summary\":\"REST Test\",\"description\": \"Creating of an issue using project keys and issue type names using the REST API\",\"issuetype\":{\"name\":\"Bug\"}}}";

        WebResource resource = client.resource("http://localhost:8080/rest/api/2/issue");
        ClientResponse response = resource.type("application/json").accept("application/json").post(ClientResponse.class,input);

        if (response.getStatus() != 201) {
            throw new RuntimeException("Failed : HTTP error code : "
                 + response.getStatus());
        }
        System.out.println("Output from server");
        System.out.println(response.getEntity(String.class));
    } catch (Exception e) {
        e.printStackTrace();
    }
</code>```

For more info:

https://docs.atlassian.com/jira/REST/cloud/#api/2/issue-createIssue

http://www.j-tricks.com/tutorials/java-rest-client-for-jira-using-jersey

ContentLicense: CC BY-SA 4.0

Body:
try {
        Client client = Client.create();
        client.addFilter(new HTTPBasicAuthFilter("username", "password"));

        String input = "{\"fields\":{\"project\":{\"key\":\"DEMO\"},\"summary\":\"REST Test\",\"description\": \"Creating of an issue using project keys and issue type names using the REST API\",\"issuetype\":{\"name\":\"Bug\"}}}";

        WebResource resource = client.resource("http://localhost:8080/rest/api/2/issue");
        ClientResponse response = resource.type("application/json").accept("application/json").post(ClientResponse.class,input);

        if (response.getStatus() != 201) {
            throw new RuntimeException("Failed : HTTP error code : "
                 + response.getStatus());
        }
        System.out.println("Output from server");
        System.out.println(response.getEntity(String.class));
    } catch (Exception e) {
        e.printStackTrace();
    }

For more info:

https://docs.atlassian.com/jira/REST/cloud/#api/2/issue-createIssue

http://www.j-tricks.com/tutorials/java-rest-client-for-jira-using-jersey


问:
How To Increment Numbers in Calculated field of TQuery?
I Have TQuery With Calculated Field N.

How To Increment Numbers in the example (N starts with 5):

I tried this but Nothing:

```<code>procedure TForm1.Query1CalcFields(DataSet: TDataSet);
var i:integer;
begin
  i := strtoint(edit2.Text);
  Query1['N'] := inttostr(i+1);
end;
</code>```

result:

```<code>N
2
2
2
2
.
.
</code>```

Note: Foxpro database ,i use BDE to connect with ,It does not have to be a calculated field ,i want the Incremented value to use it in print of quickreport like a single reference for each Page (not pagenumber).

答:
I Found This Solution With The Help Of @kobik

In Printing Of TQRLabel I Add This Code And No Needed To The Calculated Field Or Other Varible:

```<code>procedure TForm1.QRLabel1Print(sender: TObject; var Value: string);
begin
value:=inttostr(Query1.RecNo+strtoint(edit2.Text)-1);
end;
</code>```

The Tedit To Costume The Start Number At Runtime.

Body:
I Have TQuery With Calculated Field N.

How To Increment Numbers in the example (N starts with 5):

I tried this but Nothing:

procedure TForm1.Query1CalcFields(DataSet: TDataSet);
var i:integer;
begin
  i := strtoint(edit2.Text);
  Query1['N'] := inttostr(i+1);
end;

result:

N
2
2
2
2
.
.

Note: Foxpro database ,i use BDE to connect with ,It does not have to be a calculated field ,i want the Incremented value to use it in print of quickreport like a single reference for each Page (not pagenumber).

Body:
I Found This Solution With The Help Of @kobik

In Printing Of TQRLabel I Add This Code And No Needed To The Calculated Field Or Other Varible:

procedure TForm1.QRLabel1Print(sender: TObject; var Value: string);
begin
value:=inttostr(Query1.RecNo+strtoint(edit2.Text)-1);
end;

The Tedit To Costume The Start Number At Runtime.


问:
How to sort a list of objects by date when date is String?
I have the following Java POJO, Start date is a string:

POJO Object:

```<code>public class Schedule {

    private String id;

    private String startDate = "";

    //const and getters and setters
}
</code>```

I want to sort a list of these objects by the start date field:

Adding POJOS to list:

```<code>List<Schedule> schedules = new ArrayList<Schedule>();

Schedule s1 = new Schedule();
s1.setStartDate("2018-09-01T15:00:00+0000");

Schedule s2 = new Schedule();
s2.setStartDate("2018-09-15T15:00:00+0000");

schedules.add(s1);
schedules.add(s2);
</code>```

I have tried writing a comparator but it does not seem to work, is there a way of sorting strings by date (earliest first)?

Edit: I am currently using Java 7

答:
Best way is to convert your String to date in the class Schedule.

```<code>private static final SimpleDateFormat SDF = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");

public class Schedule {

    private String id;

    private String startDate = "";

    private Date startDateAsDate;

    public Date getStartDateAsDate() {
        if (startDateAsDate != null) {
            return startDateAsDate;
        }
        try {
            startDateAsDate = (Date) SDF.parseObject(startDate);
            return startDateAsDate;
        } catch (Exception e) {
            return null;
        }
    }
}

private class ScheduleComparator implements Comparator<Schedule> {

    @Override
    public int compare(Schedule o1, Schedule o2) {
        // TODO Auto-generated method stub
        return o1.getStartDateAsDate().compareTo(o2.getStartDateAsDate());
    }

}

Collections.sort(scheduleList, new ScheduleComparator());
// or
Arrays.sort(scheduleArray, new ScheduleComparator());
</code>```

Body:
I have the following Java POJO, Start date is a string:

POJO Object:

public class Schedule {

    private String id;

    private String startDate = "";

    //const and getters and setters
}

I want to sort a list of these objects by the start date field:

Adding POJOS to list:

List<Schedule> schedules = new ArrayList<Schedule>();

Schedule s1 = new Schedule();
s1.setStartDate("2018-09-01T15:00:00+0000");

Schedule s2 = new Schedule();
s2.setStartDate("2018-09-15T15:00:00+0000");

schedules.add(s1);
schedules.add(s2);

I have tried writing a comparator but it does not seem to work, is there a way of sorting strings by date (earliest first)?

Edit: I am currently using Java 7

Body:
Best way is to convert your String to date in the class Schedule.

private static final SimpleDateFormat SDF = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");

public class Schedule {

    private String id;

    private String startDate = "";

    private Date startDateAsDate;

    public Date getStartDateAsDate() {
        if (startDateAsDate != null) {
            return startDateAsDate;
        }
        try {
            startDateAsDate = (Date) SDF.parseObject(startDate);
            return startDateAsDate;
        } catch (Exception e) {
            return null;
        }
    }
}

private class ScheduleComparator implements Comparator<Schedule> {

    @Override
    public int compare(Schedule o1, Schedule o2) {
        // TODO Auto-generated method stub
        return o1.getStartDateAsDate().compareTo(o2.getStartDateAsDate());
    }

}

Collections.sort(scheduleList, new ScheduleComparator());
// or
Arrays.sort(scheduleArray, new ScheduleComparator());


问:
How to implement a permissions system like highrise or facebook
Hey I am looking to implement a permissions system like in highrise or facebook.

The issue with such an problem is that permissions have to defined on a instance of the object(visibility). Off the top of my head i can think of saving user_ids, or group_ids in a hash for every record. Is that the best way to do it?

I am using mongodb so that should make it easier. Although we can switch to sql also (highrise probably does it with sql).

Edit: I ended up writing a gem that works with mongoid, you can read more about it here

答:
@Abhishiv: given this task, I would implement some form of convention for setting access by field.

Given an object like the following:

```<code>{
  name : "me",
  user : "me01234",
  salary : "100",
  address : "123 Nowhere drive"
}
</code>```

I would add permissions by doing something like this:

```<code>{
  name : "me",
  user : "me01234",
  salary : "100",
  address : "123 Nowhere drive"
  p_salary : [ 'g/accounting', 'g/management', 'u/owner' ]
  p_address : [ 'g/accounting', 'g/hr', 'u/me' ]
}
</code>```

With conventions like this, you can maintain document-level access permissions. And it's pretty easy to see how to program such a thing.

Now typically you want access permissions on both the object and the collection itself. This keeps the whole process much more DRY. For such a thing, I would simply build a "permissions" collection that contains default permissions for each other collection in the DB.

Off the top of my head, I don't know of any framework that does this "out of the box". I would look at Mongoid and MongoMapper and see if this type of detail isn't appropriate for a plug-in.

ContentLicense: CC BY-SA 2.5

Body:
@Abhishiv: given this task, I would implement some form of convention for setting access by field.

Given an object like the following:

{
  name : "me",
  user : "me01234",
  salary : "100",
  address : "123 Nowhere drive"
}

I would add permissions by doing something like this:

{
  name : "me",
  user : "me01234",
  salary : "100",
  address : "123 Nowhere drive"
  p_salary : [ 'g/accounting', 'g/management', 'u/owner' ]
  p_address : [ 'g/accounting', 'g/hr', 'u/me' ]
}

With conventions like this, you can maintain document-level access permissions. And it's pretty easy to see how to program such a thing.

Now typically you want access permissions on both the object and the collection itself. This keeps the whole process much more DRY. For such a thing, I would simply build a "permissions" collection that contains default permissions for each other collection in the DB.

Off the top of my head, I don't know of any framework that does this "out of the box". I would look at Mongoid and MongoMapper and see if this type of detail isn't appropriate for a plug-in.


问:
Split string in a column into three columns in the same table and insert it into new table
Hello I am a beginner here.. here is my question

I have a table "tspade" with two columns that is shown below :

```<code>No  | Unixdatetime                                      |

1   | 1234567890 -1 #SUP: 2                             |

2   | 2345678901 -1 #SUP: 2                             |

3   | 3456789012 -1 #SUP: 3                             |

4   | 4567890123 -1 5678901234 -1 #SUP: 2               |

5   | 6789012345 -1 7890123456 -1 8901234567 -1 #SUP: 2 |
</code>```

I'd like to convert that table into like this :

```<code>No  | Unixdatetime1 | Unixdatetime2 | Unixdatetime3 |

1   | 1234567890    | 0             | 0             |

2   | 2345678901    | 0             | 0             |

3   | 3456789012    | 0             | 0             |

4   | 4567890123    | 5678901234    | 0             |

5   | 6789012345    | 7890123456    | 8901234567    |
</code>```

and save that to table try

I used this query :

```<code>Insert Into try (No,Unixdatetime1,Unixdatetime2,Unixdatetime3)
SELECT `No`, `Unixdatetime`,
    SUBSTRING_INDEX( `Unixdatetime` , ' -1 ', 1 ) AS Unixdatetime1,
    SUBSTRING_INDEX(SUBSTRING_INDEX( `Unixdatetime` , ' -1 ', 2 ),' -1 ',-1) AS Unixdatetime2,
    SUBSTRING_INDEX( `Unixdatetime` , ' -1 ', -1 ) AS Unixdatetime3
FROM tspade
</code>```

but it couldn't work...
Any advice or help?
Thanks in advance

答:
The problem is with the no. of columns in the try table and the select statement are not matching.

SELECT No, Unixdatetime, SUBSTRING_INDEX( Unixdatetime , ' -1 ', 1 ) AS Unixdatetime1, SUBSTRING_INDEX(SUBSTRING_INDEX( Unixdatetime , ' -1 ', 2 ),' -1 ',-1) AS Unixdatetime2, SUBSTRING_INDEX( Unixdatetime , ' -1 ', -1 ) AS Unixdatetime3 FROM tspade

Remove the highlighted column from select statement and then try.

Body:
Hello I am a beginner here.. here is my question

I have a table "tspade" with two columns that is shown below :

No  | Unixdatetime                                      |

1   | 1234567890 -1 #SUP: 2                             |

2   | 2345678901 -1 #SUP: 2                             |

3   | 3456789012 -1 #SUP: 3                             |

4   | 4567890123 -1 5678901234 -1 #SUP: 2               |

5   | 6789012345 -1 7890123456 -1 8901234567 -1 #SUP: 2 |

I'd like to convert that table into like this :

No  | Unixdatetime1 | Unixdatetime2 | Unixdatetime3 |

1   | 1234567890    | 0             | 0             |

2   | 2345678901    | 0             | 0             |

3   | 3456789012    | 0             | 0             |

4   | 4567890123    | 5678901234    | 0             |

5   | 6789012345    | 7890123456    | 8901234567    |

and save that to table try

I used this query :

Insert Into try (No,Unixdatetime1,Unixdatetime2,Unixdatetime3)
SELECT `No`, `Unixdatetime`,
    SUBSTRING_INDEX( `Unixdatetime` , ' -1 ', 1 ) AS Unixdatetime1,
    SUBSTRING_INDEX(SUBSTRING_INDEX( `Unixdatetime` , ' -1 ', 2 ),' -1 ',-1) AS Unixdatetime2,
    SUBSTRING_INDEX( `Unixdatetime` , ' -1 ', -1 ) AS Unixdatetime3
FROM tspade

but it couldn't work...
Any advice or help?
Thanks in advance


问:
How can I differentiate between validations in a form and display error message related to each validation separately?
Here is what i did...

```<code><form name="userForm" ng-submit="submitForm()" novalidate>
<!-- NAME -->
<div ng-class="{'has-error' : userForm.name.$invalid && !userForm.name.$pristine }">

  <label>Name</label>

  <input type="text" name="name" class="form-control" id = "focusedInput" ng-model="user.name" required>
  <p ng-show="userForm.name.$invalid && !userForm.name.$pristine" class="help-block">Your name is required.</p>
</div>

<!-- USERNAME -->
<div class="form-group" ng-class="{ 'has-error' : userForm.username.$invalid && !userForm.username.$pristine }">
    <label>Username</label>
    <input type="text" name="username" class="form-control" ng-model="user.username" required id = "focusedInput" ng-minlength="3" ng-maxlength="8">
    <p ng-show="userForm.username.$error.minlength" class="help-block">Username is too short.</p>
    <p ng-show="userForm.username.$error.maxlength" class="help-block">Username is too long.</p>
  <p ng-show="userForm.username.$invalid && !userForm.username.$pristine" class="help-block">Your Username is required.</p>

</div>

 <button type="submit" class="btn btn-primary" ng-disabled="userForm.$invalid">Submit</button>

</form>
</code>```

I tried to use similar validation for username field when it is left empty, as i did for name field. But the problem is : both the error messages related to name and username are getting printed at the start upto minimum length condition of the username field. Can anyone help me with this?

答:
Add the $dirty check to your ng-show. De $dirty flag is true when a user manipulated the form.</p>

```<code><p ng-show="userForm.username.$error.minlength && userForm.username.$dirty" class="help-block">Username is too short.</p>
</code>```

Body:
Here is what i did...

<form name="userForm" ng-submit="submitForm()" novalidate>

  Name

  <input type="text" name="name" class="form-control" id = "focusedInput" ng-model="user.name" required>

Your name is required.

    Username
    <input type="text" name="username" class="form-control" ng-model="user.username" required id = "focusedInput" ng-minlength="3" ng-maxlength="8">

Username is too short.

Username is too long.

Your Username is required.

 <button type="submit" class="btn btn-primary" ng-disabled="userForm.$invalid">Submit</button>

</form>

I tried to use similar validation for username field when it is left empty, as i did for name field. But the problem is : both the error messages related to name and username are getting printed at the start upto minimum length condition of the username field. Can anyone help me with this?

Body:
Add the $dirty check to your ng-show. De $dirty flag is true when a user manipulated the form.

<p ng-show="userForm.username.$error.minlength && userForm.username.$dirty" class="help-block">Username is too short.</p>


问:
How to center a div (CSS loader)
JS Fiddle: fiddle and here is the code:

.loader {
  border: 16px solid #f3f3f3;
  border-radius: 50%;
  border-top: 16px solid #3498db;
  width: 120px;
  height: 120px;
  -webkit-animation: spin 2s linear infinite;
  animation: spin 2s linear infinite;
}

@-webkit-keyframes spin {
  0% { -webkit-transform: rotate(0deg); }
  100% { -webkit-transform: rotate(360deg); }
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="loader"></div></code>```

How do I centre it horizontally & vertically?

I tried:

```<code>position:absolute;
left:50%;
top:50%;
transform:translate(-50%,-50%);
</code>```

But transform:translate(-50%,-50%); do not work

答:
Give below css to .loader class:

```<code>  margin:auto;
  left:0;
  right:0;
  top:0;
  bottom:0;
  position:fixed;
</code>```

.loader {
  border: 16px solid #f3f3f3;
  border-radius: 50%;
  border-top: 16px solid #3498db;
  width: 120px;
  height: 120px;
  -webkit-animation: spin 2s linear infinite;
  animation: spin 2s linear infinite;
  margin:auto;
  left:0;
  right:0;
  top:0;
  bottom:0;
  position:fixed;
}

@-webkit-keyframes spin {
  0% { -webkit-transform: rotate(0deg); }
  100% { -webkit-transform: rotate(360deg); }
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="loader"></div></code>```

Title: How to center a div (CSS loader)

Body:
JS Fiddle: fiddle and here is the code:

.loader {
  border: 16px solid #f3f3f3;
  border-radius: 50%;
  border-top: 16px solid #3498db;
  width: 120px;
  height: 120px;
  -webkit-animation: spin 2s linear infinite;
  animation: spin 2s linear infinite;
}

@-webkit-keyframes spin {
  0% { -webkit-transform: rotate(0deg); }
  100% { -webkit-transform: rotate(360deg); }
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

How do I centre it horizontally & vertically?

I tried:

position:absolute;
left:50%;
top:50%;
transform:translate(-50%,-50%);

But transform:translate(-50%,-50%); do not work

Body:
Give below css to .loader class:

  margin:auto;
  left:0;
  right:0;
  top:0;
  bottom:0;
  position:fixed;

.loader {
  border: 16px solid #f3f3f3;
  border-radius: 50%;
  border-top: 16px solid #3498db;
  width: 120px;
  height: 120px;
  -webkit-animation: spin 2s linear infinite;
  animation: spin 2s linear infinite;
  margin:auto;
  left:0;
  right:0;
  top:0;
  bottom:0;
  position:fixed;
}

@-webkit-keyframes spin {
  0% { -webkit-transform: rotate(0deg); }
  100% { -webkit-transform: rotate(360deg); }
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

<div class="loader"></div>


问:
VS 2008 Designer not executing default constructor anymore?
I just tested which type of code is executed by the WinForms Designer in VS 2008.
It seems that the designer is not executing the default constructor anymore.
I added a simple thing like this.Text = "foo"; nothing is changed in the designer.

Did I miss a change between VS 2005/2008? (or SP1)

tia

答:
Did you set a breakpoint to see it skip? </p>

<p>If its the first form in the project, instead of starting with "Run", you can F10 (Step Over) to start at the first line of code. From there you can trace the execution. </p>

<p>.NET 2.0 and above use Partial Classes for windows and web forms. Is it possible that the constructor that is being hit is not default.  </p>

OwnerDisplayName: Martin Moser

LastEditorDisplayName: Fabian Steeg

Body:
Did you set a breakpoint to see it skip?

If its the first form in the project, instead of starting with "Run", you can F10 (Step Over) to start at the first line of code. From there you can trace the execution.

.NET 2.0 and above use Partial Classes for windows and web forms. Is it possible that the constructor that is being hit is not default.

OwnerDisplayName: StingyJack


问:
Codeigniter and URL Rewrite on IIS 6
I need to install Codeigniter on a shared host that runs IIS 6.0.
I know about the issues with URL rewrite. Also about Isapi Rewrite, but I cant install or set anything on this host. The starting page runs fine, but I cant access any other controller of the application, I always get a 404..
I tried to change the $config['index_page'] and also $config['uri_protocol'], but nothing seems to work..
Is there some other way to get URL rewrite on IIS? Or maybe in PHP?
Thanks.

答:
If you can't install ISAPI Rewrite, look for

$config['enable_query_strings'] = FALSE;

in application/config/config.php and set it to TRUE. This will disable the "SEO-friendly" URLs and use normal query strings.

Title: Codeigniter and URL Rewrite on IIS 6


问:
why phaser game lagging in mobile devices
I am creating my first game using Phaser and it is running fine in desktop.
But it is lagging on android phones.

can anyone tell me what could be the reasons?

game is very small
smaller than 2mb.
Images used in game is also very tiny pngs.
is there anyway to find out any leaks in my code.

my main js file.

```<code>var buttetSpwanSpeed;
var bulletSpeed;
var enemySpwanSpeed;
var enemySpeed;
var golis;
var enemies;
var enemyLoop;
var scoreText;
var powers;
var bulletSize;
setStart();
//game phaser
var game=new Phaser.Game(window.innerWidth, window.innerHeight, Phaser.CANVAS,"gamearea");
var BootState={
    //loding accets
    preload: function(){
        this.load.image('LodingScreen', 'assets/desimulga.png');
        this.load.image('background', 'assets/blue.png');
    },
    create: function(){
        game.state.start("LoadingState");
    },

};

var LoadingState={
    //loding acc
    preload: function(){
        bg=this.game.add.tileSprite(0,0,600,300,'background');
        bg.height = game.height;
        bg.width = game.width;
        LodingScreen=this.game.add.sprite(this.game.world.centerX,this.game.world.centerY,'LodingScreen');
        LodingScreen.anchor.setTo(0.5);
        LodingScreen.scale.setTo(0.5,0.5);
        this.load.image('spaceship', 'assets/player.png');
        this.load.image('goli', 'assets/bullet.png');
        //load ememies
        this.load.image('enemy1', 'assets/enemies/enemy1.png');
        this.load.image('enemy2', 'assets/enemies/enemy2.png');
        this.load.image('enemy3', 'assets/enemies/enemy3.png');
        this.load.image('enemy4', 'assets/enemies/enemy4.png');
        this.load.image('enemy5', 'assets/enemies/enemy5.png');
        this.load.spritesheet('power1', 'assets/power/bulletUp.png',34,33,4);

        this.load.image('restart', 'assets/restart.png');
        this.load.spritesheet('blast', 'assets/explosion.png',400,400,8);
        game.load.audio('fire', 'assets/music/bullet.mp3');
        game.load.audio('killed', 'assets/music/killed.mp3');
        //game.load.audio('bg_music', 'assets/music/background.mp3');
        game.load.audio('death_music', 'assets/music/death.mp3');
        game.load.audio('start_music', 'assets/music/start.mp3');
    },
    create: function(){
        game.time.events.add(Phaser.Timer.SECOND * 2, function(){
            bg.kill();
            LodingScreen.kill();
            game.state.start("PreGameState");
    },this);
    },

};

var PreGameState={
    //loding accets
    create: function(){
        game.scale.refresh();
        bg=this.game.add.tileSprite(0,0,600,300,'background');
        bg.height = game.height;
        bg.width = game.width;
        Startb=this.game.add.text(this.game.world.centerX,this.game.world.centerY, 'TAP TO START' , { fontSize: '32px', fill: 'yellow' });
        Startb.anchor.setTo(0.5);
        Startb.scale.setTo(0.5,0.5);
        ship=this.game.add.sprite(this.game.world.centerX,this.game.world.height*0.4,'spaceship');
        ship.scale.setTo(0.4);
        ship.anchor.setTo(0.5);
        game.physics.arcade.enable(ship);
        bg.inputEnabled=true;

        start_music = game.add.audio('start_music');
        start_music.allowMultiple = true;
        start_music.addMarker('start_music', 0, 30);

        bg.events.onInputDown.add(function(){
            bg.inputEnabled=false;
            Startb.kill();
            start_music.play("start_music");
            // game.physics.arcade.moveToXY(ship, this.game.world.centerX, this.game.world.height*0.8, 300, 3000);
            // game.add.tween(ship).to( { y: game.world.height*0.8 }, 3000, Phaser.Easing.Sinusoidal.InOut, true);
            var tween = game.add.tween(ship).to({
            x: [this.game.world.centerX, this.game.world.width*0, this.game.world.width, this.game.world.centerX],
            y: [this.game.world.height*0.4, this.game.world.height*0.5, this.game.world.height*0.6, this.game.world.height*0.8],
            }, 2000,Phaser.Easing.Quadratic.Out, true).interpolation(function(v, k){
                return Phaser.Math.bezierInterpolation(v, k);
            });

            game.time.events.add(Phaser.Timer.SECOND * 2, function() {
                bg.kill();
                ship.kill();
                game.state.start("GameState");
            } ,this);

        }, this);
    },

};

var GameState={
    //loding accets
    preload: function(){

    },
    create: function(){
        //background
        this.background=this.game.add.tileSprite(0,0,600,300,'background');
        this.background.height = game.height;
        this.background.width = game.width;
        this.background.inputEnabled=true;
        this.background.input.enableDrag(true);
        this.background.input.startDrag = function(pointer) {
            pointer.shipStart = new Phaser.Point(GameState.ship.x, GameState.ship.y);
            Phaser.InputHandler.prototype.startDrag.call(this, pointer);
        };
        this.background.input.updateDrag = function(pointer) {
            GameState.ship.x = pointer.shipStart.x - pointer.positionDown.x + pointer.x;
            GameState.ship.y = pointer.shipStart.y - pointer.positionDown.y + pointer.y;
            GameState.background.x=0;
            GameState.background.y=0;
        };
        //ship
        this.ship=this.game.add.sprite(this.game.world.centerX,this.game.world.height*0.8,'spaceship');
        this.ship.scale.setTo(0.4);
        this.ship.anchor.setTo(0.5);
        game.physics.arcade.enable(this.ship);
        // this.ship.inputEnabled=true;
        // this.ship.input.enableDrag(true);
        //score
        this.scoreText = this.game.add.text(16, 16, 'Kills: 0', { fontSize: '32px', fill: '#fff' });
        //background Music
        // music = game.add.audio('bg_music');
        //music.play('', 0, 1, true);
        //bullet sound
        bullet_sound = game.add.audio('fire');
        bullet_sound.allowMultiple = true;
        bullet_sound.volume=0.5;
        bullet_sound.addMarker('fire', 0, 0.5);
        //Killed sound
        killed_sound = game.add.audio('killed');
        killed_sound.allowMultiple = true;
        killed_sound.addMarker('killed', 0, 0.5);
        //death music
        death_music = game.add.audio('death_music');
        death_music.allowMultiple = true;
        death_music.addMarker('death_music', 0, 10);
        //groups of bullets and enemies
        golis=game.add.group();
        enemies=game.add.group();
        powers=game.add.group();
        //fire bullet loop
        fireLoop=game.time.events.loop(Phaser.Timer.SECOND*1/buttetSpwanSpeed, fireBullet, this);
        //this.game.input.onTap.add(fireBullet, this);
        //create ememy loop
        enemyLoop=game.time.events.loop(Phaser.Timer.SECOND*1/enemySpwanSpeed, createEnemy, this);
        //change ememy speed and enemy spwan speed loop
        enemySpeedLoop=game.time.events.loop(Phaser.Timer.SECOND*1.5, changeEnemySpeed, this);
        //give powerup
        powerUp=game.time.events.loop(Phaser.Timer.SECOND*20, powerFun, this);
    },
    update: function(){
        //scrolling background
        this.background.tilePosition.y+=2;

        //keybord control
        if (game.input.keyboard.isDown(Phaser.Keyboard.UP))
        {
            this.ship.y-=2;
        }
        if (game.input.keyboard.isDown(Phaser.Keyboard.DOWN))
        {
            this.ship.y+=2;
        }
        if (game.input.keyboard.isDown(Phaser.Keyboard.RIGHT))
        {
            this.ship.x+=2;
        }
        if (game.input.keyboard.isDown(Phaser.Keyboard.LEFT))
        {
            this.ship.x-=2;
        }

        //dont go out
        if(this.ship.y<0+this.ship.height/2)
        {
            this.ship.y=0+this.ship.height/2;
        }
        if(this.ship.y>this.game.world.height-this.ship.height/2)
        {
            this.ship.y=this.game.world.height-this.ship.height/2;
        }

        if(this.ship.x<0+this.ship.width/2)
        {
            this.ship.x=0+this.ship.width/2;
        }
        if(this.ship.x>this.game.world.width-this.ship.width/2)
        {
            this.ship.x=this.game.world.width-this.ship.width/2;
        }
        //check for collisions
        game.physics.arcade.overlap(golis,enemies,b_e_collide,null,this);
        game.physics.arcade.overlap(this.ship,enemies,s_e_collide,null,this);
        game.physics.arcade.overlap(this.ship,powers,s_power1_collide,null,this);

    },
};

//setting start game conditions
function setStart(){
    buttetSpwanSpeed=2;
    bulletSpeed=2000;
    enemySpwanSpeed=1;
    enemySpeed=300;
    score=0;
    bulletSize=1.2
}

//fire bullet function
function fireBullet(){
    goli=this.game.add.sprite(this.ship.x,this.ship.y-this.ship.height/2,'goli');
    goli.anchor.setTo(0.5);
    goli.scale.setTo(bulletSize,1);
    goli.checkWorldBounds = true;
    goli.outOfBoundsKill = true;
    //adding to group
    golis.add(goli);
    game.world.moveDown(goli);
    game.physics.arcade.enable(goli);
    goli.body.collisonWorldBounds=true;
    goli.body.velocity.y=-bulletSpeed;
    bullet_sound.play("fire");
}
//create enemy function
function createEnemy(){
    enemyNo=game.rnd.integerInRange(1, 5);
    x1=game.rnd.integerInRange(0,this.game.world.width);
    x2=game.rnd.integerInRange(0,this.game.world.width);
    enemy=this.game.add.sprite(x1,10,'enemy'+enemyNo);
    enemy.anchor.setTo(0.5);
    enemy.scale.setTo(0.4);
    enemy.checkWorldBounds = true;
    enemies.add(enemy);
    enemy.outOfBoundsKill = true;
    game.physics.arcade.enable(enemy);
    enemy.body.collisonWorldBounds=true;
    enemy.angle=90;
    enemy.no=enemyNo;

    //moving enemy
    angleRedian=game.physics.arcade.moveToXY(enemy, x2, this.game.world.height+enemy.height, enemySpeed,0);
    angleDegree=angleRedian*57.2958;
    enemy.angle=90+angleDegree;

}

//runs when bullet collide to enemy
function b_e_collide(goli,enemy){
    //blast
    blast=this.game.add.sprite(enemy.x,enemy.y,'blast');
    blast.anchor.setTo(0.5);
    blast.scale.setTo(0.5);
    var explosion=blast.animations.add('explosion');
    blast.animations.play('explosion',30,false,true);

    //killing
    goli.kill();
    enemy.kill();

    //update scores
    if(enemy.no<4)
    {
        score+=1;
        killed_sound.play('killed');
    }
    this.scoreText.text = 'Kills: ' + score;
}
//runs when ship collide to enemy
function s_e_collide(ship,enemy){

    blast=this.game.add.sprite(enemy.x,enemy.y,'blast');
    blast.anchor.setTo(0.5);
    blast.scale.setTo(0.5);
    var explosion=blast.animations.add('explosion');
    blast.animations.play('explosion',10,false,true);
    ship.kill();
    enemy.kill();
    //music.stop();
    this.scoreText.kill();
    death_music.play("death_music");
    game.time.events.remove(fireLoop);
    game.time.events.add(Phaser.Timer.SECOND * 2, function() {
        fianlScore = this.game.add.text(this.game.world.centerX,this.game.world.centerY, 'KILL: '+score, { fontSize: '32px', fill: 'yellow' });
        fianlScore.anchor.setTo(0.5);
        gameOverText = this.game.add.text(this.game.world.centerX,this.game.world.centerY - fianlScore.height, 'GAME OVER', { fontSize: '32px', fill: 'red' });
        gameOverText.anchor.setTo(0.5);
        //restart button
        restart=this.game.add.sprite(this.game.world.centerX,this.game.world.centerY + fianlScore.height+10,'restart');
        restart.anchor.setTo(0.5);
        restart.scale.setTo(0.05,0.05);
        restart.inputEnabled = true;
        restart.events.onInputDown.add(restartGame, this);
        game.time.events.stop();
    }, this);

}
//runs when ship collide power1
function s_power1_collide(ship,power){
    power.kill();
    game.time.events.remove(fireLoop);
    fireLoop=game.time.events.loop(Phaser.Timer.SECOND*1/10, fireBullet, this);
    game.time.events.add(Phaser.Timer.SECOND * 10, function(){
        game.time.events.remove(fireLoop);
        fireLoop=game.time.events.loop(Phaser.Timer.SECOND*1/buttetSpwanSpeed, fireBullet, this);
    },this);

}

function changeEnemySpeed()
{
    if(enemySpeed<=900)
    {
        enemySpeed+=5;
    }
    if(enemySpwanSpeed<=3)
    {
        enemySpwanSpeed+=0.025;
    }
    enemyLoop.delay=Phaser.Timer.SECOND*1/enemySpwanSpeed;
}

//send power up
function powerFun()
{
    x1=game.rnd.integerInRange(0,this.game.world.width);
    x2=game.rnd.integerInRange(0,this.game.world.width);
    power=this.game.add.sprite(x1,10,'power1');
    power.anchor.setTo(0.5);
    var shine=power.animations.add('shine');
    power.animations.play('shine',5,true,true);
    power.checkWorldBounds = true;
    power.outOfBoundsKill = true;
    powers.add(power);
    game.physics.arcade.enable(power);
    power.body.collisonWorldBounds=true;
    game.physics.arcade.moveToXY(power, x2, this.game.world.height+power.height, 400,0);
    powerDelay=game.rnd.integerInRange(20,35);
    powerUp.delay=Phaser.Timer.SECOND*powerDelay;
}

function restartGame(){
    setStart();
    game.time.events.start();
    game.state.start("PreGameState");
}

game.state.add("GameState",GameState);
game.state.add("BootState",BootState);
game.state.add("LoadingState",LoadingState);
game.state.add("PreGameState",PreGameState);
game.state.start("BootState");
</code>```

since the game is so small in size I think it should run smoothly on mobile devices.
it runs good on some high end mobile devices but gets slow as time progresses.
this is my first game so I am not very good with game designing concepts.

答:
Hi I currently got this issue fixed myself for my games cross platform.

Things I did were

Load alll sprites right at my main screen/or loading screen
If you have reusable sprites use the command .kill() not .destory() which will take more memory to reload sprite unless the sprite is not coming back to screen then it’s ok to destroy.
Recycle everything let’s say you use a bullet asoon as it hits the wall boom kill and get it back.

And sad part in some cases even by doing sometimes it’ll still lag and have some glitches here and there you just have to see at what point is happening. Use break points to see exactly what sprites are causing it and consider also if the image doesn’t have transparency to use .jpeg

Good luck hope this helps

Body:
I am creating my first game using Phaser and it is running fine in desktop.
But it is lagging on android phones.

can anyone tell me what could be the reasons?

game is very small
smaller than 2mb.
Images used in game is also very tiny pngs.
is there anyway to find out any leaks in my code.

my main js file.

var buttetSpwanSpeed;
var bulletSpeed;
var enemySpwanSpeed;
var enemySpeed;
var golis;
var enemies;
var enemyLoop;
var scoreText;
var powers;
var bulletSize;
setStart();
//game phaser
var game=new Phaser.Game(window.innerWidth, window.innerHeight, Phaser.CANVAS,"gamearea");
var BootState={
    //loding accets
    preload: function(){
        this.load.image('LodingScreen', 'assets/desimulga.png');
        this.load.image('background', 'assets/blue.png');
    },
    create: function(){
        game.state.start("LoadingState");
    },

};

var LoadingState={
    //loding acc
    preload: function(){
        bg=this.game.add.tileSprite(0,0,600,300,'background');
        bg.height = game.height;
        bg.width = game.width;
        LodingScreen=this.game.add.sprite(this.game.world.centerX,this.game.world.centerY,'LodingScreen');
        LodingScreen.anchor.setTo(0.5);
        LodingScreen.scale.setTo(0.5,0.5);
        this.load.image('spaceship', 'assets/player.png');
        this.load.image('goli', 'assets/bullet.png');
        //load ememies
        this.load.image('enemy1', 'assets/enemies/enemy1.png');
        this.load.image('enemy2', 'assets/enemies/enemy2.png');
        this.load.image('enemy3', 'assets/enemies/enemy3.png');
        this.load.image('enemy4', 'assets/enemies/enemy4.png');
        this.load.image('enemy5', 'assets/enemies/enemy5.png');
        this.load.spritesheet('power1', 'assets/power/bulletUp.png',34,33,4);

        this.load.image('restart', 'assets/restart.png');
        this.load.spritesheet('blast', 'assets/explosion.png',400,400,8);
        game.load.audio('fire', 'assets/music/bullet.mp3');
        game.load.audio('killed', 'assets/music/killed.mp3');
        //game.load.audio('bg_music', 'assets/music/background.mp3');
        game.load.audio('death_music', 'assets/music/death.mp3');
        game.load.audio('start_music', 'assets/music/start.mp3');
    },
    create: function(){
        game.time.events.add(Phaser.Timer.SECOND * 2, function(){
            bg.kill();
            LodingScreen.kill();
            game.state.start("PreGameState");
    },this);
    },

};

var PreGameState={
    //loding accets
    create: function(){
        game.scale.refresh();
        bg=this.game.add.tileSprite(0,0,600,300,'background');
        bg.height = game.height;
        bg.width = game.width;
        Startb=this.game.add.text(this.game.world.centerX,this.game.world.centerY, 'TAP TO START' , { fontSize: '32px', fill: 'yellow' });
        Startb.anchor.setTo(0.5);
        Startb.scale.setTo(0.5,0.5);
        ship=this.game.add.sprite(this.game.world.centerX,this.game.world.height*0.4,'spaceship');
        ship.scale.setTo(0.4);
        ship.anchor.setTo(0.5);
        game.physics.arcade.enable(ship);
        bg.inputEnabled=true;

        start_music = game.add.audio('start_music');
        start_music.allowMultiple = true;
        start_music.addMarker('start_music', 0, 30);

        bg.events.onInputDown.add(function(){
            bg.inputEnabled=false;
            Startb.kill();
            start_music.play("start_music");
            // game.physics.arcade.moveToXY(ship, this.game.world.centerX, this.game.world.height*0.8, 300, 3000);
            // game.add.tween(ship).to( { y: game.world.height*0.8 }, 3000, Phaser.Easing.Sinusoidal.InOut, true);
            var tween = game.add.tween(ship).to({
            x: [this.game.world.centerX, this.game.world.width*0, this.game.world.width, this.game.world.centerX],
            y: [this.game.world.height*0.4, this.game.world.height*0.5, this.game.world.height*0.6, this.game.world.height*0.8],
            }, 2000,Phaser.Easing.Quadratic.Out, true).interpolation(function(v, k){
                return Phaser.Math.bezierInterpolation(v, k);
            });

            game.time.events.add(Phaser.Timer.SECOND * 2, function() {
                bg.kill();
                ship.kill();
                game.state.start("GameState");
            } ,this);

        }, this);
    },

};

var GameState={
    //loding accets
    preload: function(){

    },
    create: function(){
        //background
        this.background=this.game.add.tileSprite(0,0,600,300,'background');
        this.background.height = game.height;
        this.background.width = game.width;
        this.background.inputEnabled=true;
        this.background.input.enableDrag(true);
        this.background.input.startDrag = function(pointer) {
            pointer.shipStart = new Phaser.Point(GameState.ship.x, GameState.ship.y);
            Phaser.InputHandler.prototype.startDrag.call(this, pointer);
        };
        this.background.input.updateDrag = function(pointer) {
            GameState.ship.x = pointer.shipStart.x - pointer.positionDown.x + pointer.x;
            GameState.ship.y = pointer.shipStart.y - pointer.positionDown.y + pointer.y;
            GameState.background.x=0;
            GameState.background.y=0;
        };
        //ship
        this.ship=this.game.add.sprite(this.game.world.centerX,this.game.world.height*0.8,'spaceship');
        this.ship.scale.setTo(0.4);
        this.ship.anchor.setTo(0.5);
        game.physics.arcade.enable(this.ship);
        // this.ship.inputEnabled=true;
        // this.ship.input.enableDrag(true);
        //score
        this.scoreText = this.game.add.text(16, 16, 'Kills: 0', { fontSize: '32px', fill: '#fff' });
        //background Music
        // music = game.add.audio('bg_music');
        //music.play('', 0, 1, true);
        //bullet sound
        bullet_sound = game.add.audio('fire');
        bullet_sound.allowMultiple = true;
        bullet_sound.volume=0.5;
        bullet_sound.addMarker('fire', 0, 0.5);
        //Killed sound
        killed_sound = game.add.audio('killed');
        killed_sound.allowMultiple = true;
        killed_sound.addMarker('killed', 0, 0.5);
        //death music
        death_music = game.add.audio('death_music');
        death_music.allowMultiple = true;
        death_music.addMarker('death_music', 0, 10);
        //groups of bullets and enemies
        golis=game.add.group();
        enemies=game.add.group();
        powers=game.add.group();
        //fire bullet loop
        fireLoop=game.time.events.loop(Phaser.Timer.SECOND*1/buttetSpwanSpeed, fireBullet, this);
        //this.game.input.onTap.add(fireBullet, this);
        //create ememy loop
        enemyLoop=game.time.events.loop(Phaser.Timer.SECOND*1/enemySpwanSpeed, createEnemy, this);
        //change ememy speed and enemy spwan speed loop
        enemySpeedLoop=game.time.events.loop(Phaser.Timer.SECOND*1.5, changeEnemySpeed, this);
        //give powerup
        powerUp=game.time.events.loop(Phaser.Timer.SECOND*20, powerFun, this);
    },
    update: function(){
        //scrolling background
        this.background.tilePosition.y+=2;

        //keybord control
        if (game.input.keyboard.isDown(Phaser.Keyboard.UP))
        {
            this.ship.y-=2;
        }
        if (game.input.keyboard.isDown(Phaser.Keyboard.DOWN))
        {
            this.ship.y+=2;
        }
        if (game.input.keyboard.isDown(Phaser.Keyboard.RIGHT))
        {
            this.ship.x+=2;
        }
        if (game.input.keyboard.isDown(Phaser.Keyboard.LEFT))
        {
            this.ship.x-=2;
        }

        //dont go out
        if(this.ship.y<0+this.ship.height/2)
        {
            this.ship.y=0+this.ship.height/2;
        }
        if(this.ship.y>this.game.world.height-this.ship.height/2)
        {
            this.ship.y=this.game.world.height-this.ship.height/2;
        }

        if(this.ship.x<0+this.ship.width/2)
        {
            this.ship.x=0+this.ship.width/2;
        }
        if(this.ship.x>this.game.world.width-this.ship.width/2)
        {
            this.ship.x=this.game.world.width-this.ship.width/2;
        }
        //check for collisions
        game.physics.arcade.overlap(golis,enemies,b_e_collide,null,this);
        game.physics.arcade.overlap(this.ship,enemies,s_e_collide,null,this);
        game.physics.arcade.overlap(this.ship,powers,s_power1_collide,null,this);

    },
};

//setting start game conditions
function setStart(){
    buttetSpwanSpeed=2;
    bulletSpeed=2000;
    enemySpwanSpeed=1;
    enemySpeed=300;
    score=0;
    bulletSize=1.2
}

//fire bullet function
function fireBullet(){
    goli=this.game.add.sprite(this.ship.x,this.ship.y-this.ship.height/2,'goli');
    goli.anchor.setTo(0.5);
    goli.scale.setTo(bulletSize,1);
    goli.checkWorldBounds = true;
    goli.outOfBoundsKill = true;
    //adding to group
    golis.add(goli);
    game.world.moveDown(goli);
    game.physics.arcade.enable(goli);
    goli.body.collisonWorldBounds=true;
    goli.body.velocity.y=-bulletSpeed;
    bullet_sound.play("fire");
}
//create enemy function
function createEnemy(){
    enemyNo=game.rnd.integerInRange(1, 5);
    x1=game.rnd.integerInRange(0,this.game.world.width);
    x2=game.rnd.integerInRange(0,this.game.world.width);
    enemy=this.game.add.sprite(x1,10,'enemy'+enemyNo);
    enemy.anchor.setTo(0.5);
    enemy.scale.setTo(0.4);
    enemy.checkWorldBounds = true;
    enemies.add(enemy);
    enemy.outOfBoundsKill = true;
    game.physics.arcade.enable(enemy);
    enemy.body.collisonWorldBounds=true;
    enemy.angle=90;
    enemy.no=enemyNo;

    //moving enemy
    angleRedian=game.physics.arcade.moveToXY(enemy, x2, this.game.world.height+enemy.height, enemySpeed,0);
    angleDegree=angleRedian*57.2958;
    enemy.angle=90+angleDegree;

}

//runs when bullet collide to enemy
function b_e_collide(goli,enemy){
    //blast
    blast=this.game.add.sprite(enemy.x,enemy.y,'blast');
    blast.anchor.setTo(0.5);
    blast.scale.setTo(0.5);
    var explosion=blast.animations.add('explosion');
    blast.animations.play('explosion',30,false,true);

    //killing
    goli.kill();
    enemy.kill();

    //update scores
    if(enemy.no<4)
    {
        score+=1;
        killed_sound.play('killed');
    }
    this.scoreText.text = 'Kills: ' + score;
}
//runs when ship collide to enemy
function s_e_collide(ship,enemy){

    blast=this.game.add.sprite(enemy.x,enemy.y,'blast');
    blast.anchor.setTo(0.5);
    blast.scale.setTo(0.5);
    var explosion=blast.animations.add('explosion');
    blast.animations.play('explosion',10,false,true);
    ship.kill();
    enemy.kill();
    //music.stop();
    this.scoreText.kill();
    death_music.play("death_music");
    game.time.events.remove(fireLoop);
    game.time.events.add(Phaser.Timer.SECOND * 2, function() {
        fianlScore = this.game.add.text(this.game.world.centerX,this.game.world.centerY, 'KILL: '+score, { fontSize: '32px', fill: 'yellow' });
        fianlScore.anchor.setTo(0.5);
        gameOverText = this.game.add.text(this.game.world.centerX,this.game.world.centerY - fianlScore.height, 'GAME OVER', { fontSize: '32px', fill: 'red' });
        gameOverText.anchor.setTo(0.5);
        //restart button
        restart=this.game.add.sprite(this.game.world.centerX,this.game.world.centerY + fianlScore.height+10,'restart');
        restart.anchor.setTo(0.5);
        restart.scale.setTo(0.05,0.05);
        restart.inputEnabled = true;
        restart.events.onInputDown.add(restartGame, this);
        game.time.events.stop();
    }, this);

}
//runs when ship collide power1
function s_power1_collide(ship,power){
    power.kill();
    game.time.events.remove(fireLoop);
    fireLoop=game.time.events.loop(Phaser.Timer.SECOND*1/10, fireBullet, this);
    game.time.events.add(Phaser.Timer.SECOND * 10, function(){
        game.time.events.remove(fireLoop);
        fireLoop=game.time.events.loop(Phaser.Timer.SECOND*1/buttetSpwanSpeed, fireBullet, this);
    },this);

}

function changeEnemySpeed()
{
    if(enemySpeed<=900)
    {
        enemySpeed+=5;
    }
    if(enemySpwanSpeed<=3)
    {
        enemySpwanSpeed+=0.025;
    }
    enemyLoop.delay=Phaser.Timer.SECOND*1/enemySpwanSpeed;
}

//send power up
function powerFun()
{
    x1=game.rnd.integerInRange(0,this.game.world.width);
    x2=game.rnd.integerInRange(0,this.game.world.width);
    power=this.game.add.sprite(x1,10,'power1');
    power.anchor.setTo(0.5);
    var shine=power.animations.add('shine');
    power.animations.play('shine',5,true,true);
    power.checkWorldBounds = true;
    power.outOfBoundsKill = true;
    powers.add(power);
    game.physics.arcade.enable(power);
    power.body.collisonWorldBounds=true;
    game.physics.arcade.moveToXY(power, x2, this.game.world.height+power.height, 400,0);
    powerDelay=game.rnd.integerInRange(20,35);
    powerUp.delay=Phaser.Timer.SECOND*powerDelay;
}

function restartGame(){
    setStart();
    game.time.events.start();
    game.state.start("PreGameState");
}

game.state.add("GameState",GameState);
game.state.add("BootState",BootState);
game.state.add("LoadingState",LoadingState);
game.state.add("PreGameState",PreGameState);
game.state.start("BootState");

since the game is so small in size I think it should run smoothly on mobile devices.
it runs good on some high end mobile devices but gets slow as time progresses.
this is my first game so I am not very good with game designing concepts.


问:
PHP undefined index database issues
I am having issues with displaying the database table. My database table (activities) have the following value, ID (Primary Key), type, title, description and picture. I am trying to retrieve and display title,description and picture in a table format but is facing an  error

"Notice: Undefined index: title, Notice: Undefined index: description
  and Notice: Undefined index: picture"

which I am unable to solve it.
Below are my php code:

```<code>      <div class="col-md-4 col-md-offset-1">
           <div id="content">
               <table><?php
                $servername = "localhost";
                $username = "root";
                $password = "";
                $dbname = "sentosa_resort";

                $conn = new mysqli($servername, $username, $password,
               $dbname);
               // Check connection
               if ($conn->connect_error) {
                   die("Connection failed: " . $conn->connect_error);
               }

                $query = "SELECT title,description,picture FROM activites";
                $result = $conn->query($sql);;

                 // start a table tag in the HTML

                while($row=mysqli_fetch_array($result)){
                    $title = $row['title'];
                    $description = $row['description'];
                   $picture = $row['picture'];
                    echo "<tr>";
                    echo "<td>" . $title . "</td>";
                    echo "<td>" . $description . "</td>";
                     echo "<td>" . $picture . "</td>";
                    echo "</tr>";
                }
                ?></table>
                </div>
          </div>
</code>```

答:
Kindly check your code for an extra semi colon in line number 16...

OR

You can use mysqli_fetch_row

```<code> <div class="col-md-4 col-md-offset-1">
                       <div id="content">
                           <table>
        <?php
                            $servername = "localhost";
                            $username = "root";
                            $password = "";
                            $dbname = "sentosa_resort";

                            $conn = new mysqli($servername, $username, $password,
                           $dbname);
                           // Check connection
                           if ($conn->connect_error) {
                               die("Connection failed: " . $conn->connect_error);
                           }

                            $query = "SELECT title,description,picture FROM activites";
                            $result = $conn->query($query);

                             // start a table tag in the HTML

                            while($row=mysqli_fetch_row($result)){
                                $title = $row['0'];
                                $description = $row['1'];
                               $picture = $row['2'];
                                echo "<tr>";
                                echo "<td>" . $title . "</td>";
                                echo "<td>" . $description . "</td>";
                                 echo "<td>" . $picture . "</td>";
                                echo "</tr>";
                            }
                            ?>
    </table>
                            </div>
                      </div>
</code>```

Title: PHP undefined index database issues

Body:
I am having issues with displaying the database table. My database table (activities) have the following value, ID (Primary Key), type, title, description and picture. I am trying to retrieve and display title,description and picture in a table format but is facing an  error

"Notice: Undefined index: title, Notice: Undefined index: description
  and Notice: Undefined index: picture"

which I am unable to solve it.
Below are my php code:

<?php
                $servername = "localhost";
                $username = "root";
                $password = "";
                $dbname = "sentosa_resort";

                $conn = new mysqli($servername, $username, $password,
               $dbname);
               // Check connection
               if ($conn->connect_error) {
                   die("Connection failed: " . $conn->connect_error);
               }

                $query = "SELECT title,description,picture FROM activites";
                $result = $conn->query($sql);;

                 // start a table tag in the HTML

                while($row=mysqli_fetch_array($result)){
                    $title = $row['title'];
                    $description = $row['description'];
                   $picture = $row['picture'];
                    echo "
";
                    echo "" . $title . "	";
                    echo "" . $description . "	";
                     echo "" . $picture . "	";
                    echo "
";
                }
                ?>

Body:
Kindly check your code for an extra semi colon in line number 16...

OR

You can use mysqli_fetch_row

 <div class="col-md-4 col-md-offset-1">
                       <div id="content">
                           <table>
        <?php
                            $servername = "localhost";
                            $username = "root";
                            $password = "";
                            $dbname = "sentosa_resort";

                            $conn = new mysqli($servername, $username, $password,
                           $dbname);
                           // Check connection
                           if ($conn->connect_error) {
                               die("Connection failed: " . $conn->connect_error);
                           }

                            $query = "SELECT title,description,picture FROM activites";
                            $result = $conn->query($query);

                             // start a table tag in the HTML

                            while($row=mysqli_fetch_row($result)){
                                $title = $row['0'];
                                $description = $row['1'];
                               $picture = $row['2'];
                                echo "<tr>";
                                echo "<td>" . $title . "</td>";
                                echo "<td>" . $description . "</td>";
                                 echo "<td>" . $picture . "</td>";
                                echo "</tr>";
                            }
                            ?>
    </table>
                            </div>
                      </div>


问:
Am I using Javascript call-backs appropriately (object-oriented style)?
I have the following code example to use an object that receives the action from the callback.  Doesn't seem like this is a good design pattern.  Or is it?

When setTimeOut() fires on the function after 1 second, it uses the objInstance global variable (DOM scope) to access the ClassExample object instance.  Can someone recommend a better way to utilize callbacks within an object oriented design?

The whole idea is so I can use the callback to update data within my object instance (increment a variable for example).

```<code>function ClassExample{
    this.initiate = function() {
        setTimeOut(objInstance.afterTimeOut,1000); //using the objects global handle
    }

    this.afterTimeOut = function() {
        alert("Received!");
    }

}

var objInstance = new ClassExample(); //instance
objInstance.initiate();
</code>```

答:
```<code>this.initiate = function() {
    var instance = this;
    setTimeOut(function() {
        instance.afterTimeOut();
    }, 1000);
};
</code>```

By saving this to a local variable, you can avoid using the global handle at all.  Also this prevent the afterTimeout() from losing it's this.

Body:
I have the following code example to use an object that receives the action from the callback.  Doesn't seem like this is a good design pattern.  Or is it?

When setTimeOut() fires on the function after 1 second, it uses the objInstance global variable (DOM scope) to access the ClassExample object instance.  Can someone recommend a better way to utilize callbacks within an object oriented design?

The whole idea is so I can use the callback to update data within my object instance (increment a variable for example).

function ClassExample{
    this.initiate = function() {
        setTimeOut(objInstance.afterTimeOut,1000); //using the objects global handle
    }

    this.afterTimeOut = function() {
        alert("Received!");
    }

}

var objInstance = new ClassExample(); //instance
objInstance.initiate();

Body:
this.initiate = function() {
    var instance = this;
    setTimeOut(function() {
        instance.afterTimeOut();
    }, 1000);
};

By saving this to a local variable, you can avoid using the global handle at all.  Also this prevent the afterTimeout() from losing it's this.


问:
PolymerElements API reference?
Where can I find a full API reference for PolymerElements?

For example, the description for PaperDialogBehavior says

Use the dialog-dismiss and dialog-confirm attributes on interactive controls to close the dialog. If the user dismisses the dialog with dialog-confirm, the closingReason will update to include confirmed: true.

But I can't find any further information anywhere about what closingReason actually is (a property? a parameter passed to some callback?) and how it "includes" confirmed: true.

Instead of wasting time on guessing how to do every single little thing when using Polymer, it would be nice to have an actual API reference. Is there one?

答:
There isn't any further information. Documentation isn't well written and you have to find many things on your own. Just remember that everything in Polymer is about properties. So closingReson is property that you can access on paper-dialog (or any other elements using paperDialogBehavior).

This property contains object {confirmed: true|false}

Truly said, behaviors has extremely badly written documentations. It is very confusing. For example:

modal: boolean = false
  If modal is true, this implies no-cancel-on-outside-click, no-cancel-on-esc-key and with-backdrop.

but none of those properties are specified in paperDialogBehavior, because it is inherited from iron-overlay-behavior. And these inheritences are not documented (mostly).

Title: PolymerElements API reference?


问:
Automatically scroll on the table using link_to rails
How can I automatically scroll or focus on the table upon redirect using the class name when the button is clicked I used a link_to enclosed inside is a div

```<code> <%= link_to employees_path do %>
   <div>......
   </div>
 <% end %>

<tbody>
 <% @request.each do |s| %>
 <tr data-expanded="true">
     <td><%= s.date.strftime('%B %Y') %></td>
     <td><%= s.name %></td>
     <td><%= s.created_at %></td>
     <td><%= s.updated_at %></td>
 </tr>
 <% end %>
 </tbody>
</table>
</code>```

I tried using but it doesnt work on the table

```<code> autofocus: true
</code>```

and I also tried to mimic it going to the bottom of the page

```<code><script>
$('html,body').animate({scrollTop: document.body.scrollHeight},"fast");
</script>
</code>```

What I want is when the user clicks the button the user will be automatically scrolled to the table or focused on table, but only when the button is clicked will it be focused.

答:
Solved it by adding an anchor </p>

```<code><%= link_to employees_path(anchor: "value") do %>

<a name = "value"></a>
</code>```

Body:
How can I automatically scroll or focus on the table upon redirect using the class name when the button is clicked I used a link_to enclosed inside is a div

 <%= link_to employees_path do %>

......

 <% end %>

 <% @request.each do |s| %>

     <%= s.date.strftime('%B %Y') %>
     <%= s.name %>
     <%= s.created_at %>
     <%= s.updated_at %>

 <% end %>

I tried using but it doesnt work on the table

 autofocus: true

and I also tried to mimic it going to the bottom of the page

What I want is when the user clicks the button the user will be automatically scrolled to the table or focused on table, but only when the button is clicked will it be focused.

Body:
Solved it by adding an anchor

<%= link_to employees_path(anchor: "value") do %>

<a name = "value"></a>


问:
Confusion using object oriented design .. need help
Let say we have an Order class and OrderManagerService class.

Order class: [some state and methods that act on the state]

Item[]

status

OrderManagerService class: [have no state. only following static methods]

createOrder

getOrder

Question: Let say we are using a relational DB in the back. Our goal is to update Order status. Well, the status need to get updated in the DB. My concern is where to put the updateStatus method.

Should I call OrderManagerService.getOrder then, call Order.updateStatus?

or create a new method as OrderManagerService.updateOrderStatus?

well, 1st option seems following encapsulation. But, personally I dont like it as we may end up calling DAO layer from entity objects [perhaps, that might be ok]. Wondering what would be a right design choice and why? any help is greatly appreciated.

答:
How about observer pattern?

updateStatus() would be in Order class, which would be observed by OrderManagerService class.

Each time you changed status (or anyting else) Manager would see it and do some actions if needed (for example update the status in the DB).

The manager could bind to Order when creating an instance and returning it in getOrder() method.

You could also implement some method to unbind Manager from an order if an instance of the order is destroyed (concern only in unmanaged languages).


问:
Generate apk name as package name in Android Studio
Android studio will generate default apk name as app-(release|debug).apk.

How to generate apk file name same as package name of the app like com.example-debug.apk.

答:
This may help you. This code will create app name like applicationId-release.apk or applicationId-debug.apk in which applicationId can be your package name.

```<code>buildTypes {

    applicationVariants.all { variant ->
        variant.outputs.each { output ->
            def newName = output.outputFile.name
            newName = newName.replace("app-", applicationId)
            output.outputFile = new File(output.outputFile.parent, newName)
        }
    }
}
</code>```

Body:
This may help you. This code will create app name like applicationId-release.apk or applicationId-debug.apk in which applicationId can be your package name.

buildTypes {

    applicationVariants.all { variant ->
        variant.outputs.each { output ->
            def newName = output.outputFile.name
            newName = newName.replace("app-", applicationId)
            output.outputFile = new File(output.outputFile.parent, newName)
        }
    }
}


问:
TypeError: a bytes-like object is required, not 'str' with serverless and Python3
I have an aws-lambda function that is triggered whenever a CSV file is uploaded to s3 bucket. I am using serverless framework with Python 3.6, the issue is that i am getting this error message

a bytes-like object is required, not 'str': TypeError

Traceback (most recent call last):

File "/var/task/handler.py", line 33, in csvfile

fichier = obj['Body'].read().split('\n')

TypeError: a bytes-like object is required, not 'str'

I have did some research in the net here, the issue, is i am not using the open method cause the file is read by s3 event so don't know how to fix it

Here is my code :

```<code>import logging
import boto3
from nvd3 import pieChart
import sys
import csv

xdata = []
ydata = []
xdata1 = []
ydata1 = []

logger = logging.getLogger()
logger.setLevel(logging.INFO)

def csvfile(event, context):

    s3 = boto3.client('s3')
    # retrieve bucket name and file_key from the S3 event
    bucket_name = event['Records'][0]['s3']['bucket']['name']
    file_key = event['Records'][0]['s3']['object']['key']
    logger.info('Reading {} from {}'.format(file_key, bucket_name))
    # get the object
    obj = s3.get_object(Bucket=bucket_name, Key=file_key)
    # get lines inside the csv
    fichier = obj['Body'].read().split('\n')
    #print lines
     for ligne in fichier:
        if len(ligne) > 1:
            logger.info(ligne.decode())
            liste = ligne.split(',')
            print(liste)
            if liste[2] == 'ByCateg':
                xdata.append(liste[4])
                ydata.append(liste[1])
            elif liste[2] == 'ByTypes':
                xdata1.append(liste[4])
                ydata1.append(liste[1])

         print ' '.join(xdata)

print('Function execution Completed')
</code>```

and here is my serverless.yml code:

```<code>service: aws-python # NOTE: update this with your service name

provider:
  name: aws
  runtime: python3.6
  stage: dev
  region: us-east-1
  iamRoleStatements:
        - Effect: "Allow"
          Action:
              - s3:*
              - "ses:SendEmail"
              - "ses:SendRawEmail"
              - "s3:PutBucketNotification"
          Resource: "*"

    functions:
  csvfile:
    handler: handler.csvfile
    description: send mail whenever a csv file is uploaded on S3
    events:
      - s3:
          bucket: car2
          event: s3:ObjectCreated:*
          rules:
            - suffix: .csv
</code>```

答:
The problem is that

```<code>fichier = obj['Body'].read()
</code>```

returns a bytes object, not a string. This is because the encoding may require more than a single character. Now you're using split on a bytes object, but you can't split it using a string, you need to split using another bytes object. Specifically

```<code>fichier = obj['Body'].read().split(b'\n')
</code>```

should fix your error, but depending on what you're expecting maybe decoding is more appropriate before the split?

```<code>fichier = obj['Body'].read().decode("utf-8").split('\n')
</code>```

Body:
I have an aws-lambda function that is triggered whenever a CSV file is uploaded to s3 bucket. I am using serverless framework with Python 3.6, the issue is that i am getting this error message

a bytes-like object is required, not 'str': TypeError

Traceback (most recent call last):

File "/var/task/handler.py", line 33, in csvfile

fichier = obj['Body'].read().split('\n')

TypeError: a bytes-like object is required, not 'str'

I have did some research in the net here, the issue, is i am not using the open method cause the file is read by s3 event so don't know how to fix it

Here is my code :

import logging
import boto3
from nvd3 import pieChart
import sys
import csv

xdata = []
ydata = []
xdata1 = []
ydata1 = []

logger = logging.getLogger()
logger.setLevel(logging.INFO)

def csvfile(event, context):

    s3 = boto3.client('s3')
    # retrieve bucket name and file_key from the S3 event
    bucket_name = event['Records'][0]['s3']['bucket']['name']
    file_key = event['Records'][0]['s3']['object']['key']
    logger.info('Reading {} from {}'.format(file_key, bucket_name))
    # get the object
    obj = s3.get_object(Bucket=bucket_name, Key=file_key)
    # get lines inside the csv
    fichier = obj['Body'].read().split('\n')
    #print lines
     for ligne in fichier:
        if len(ligne) > 1:
            logger.info(ligne.decode())
            liste = ligne.split(',')
            print(liste)
            if liste[2] == 'ByCateg':
                xdata.append(liste[4])
                ydata.append(liste[1])
            elif liste[2] == 'ByTypes':
                xdata1.append(liste[4])
                ydata1.append(liste[1])

         print ' '.join(xdata)

print('Function execution Completed')

and here is my serverless.yml code:

service: aws-python # NOTE: update this with your service name

provider:
  name: aws
  runtime: python3.6
  stage: dev
  region: us-east-1
  iamRoleStatements:
        - Effect: "Allow"
          Action:
              - s3:*
              - "ses:SendEmail"
              - "ses:SendRawEmail"
              - "s3:PutBucketNotification"
          Resource: "*"

    functions:
  csvfile:
    handler: handler.csvfile
    description: send mail whenever a csv file is uploaded on S3
    events:
      - s3:
          bucket: car2
          event: s3:ObjectCreated:*
          rules:
            - suffix: .csv

Body:
The problem is that

fichier = obj['Body'].read()

returns a bytes object, not a string. This is because the encoding may require more than a single character. Now you're using split on a bytes object, but you can't split it using a string, you need to split using another bytes object. Specifically

fichier = obj['Body'].read().split(b'\n')

should fix your error, but depending on what you're expecting maybe decoding is more appropriate before the split?

fichier = obj['Body'].read().decode("utf-8").split('\n')


问:
Join arrays expression in ECMAScript 2016
I am new to JavaScript. I need to write simple script which should join several arrays into one. I found this example:

```<code>var arr1 = ['a', 'b', 'c'];
var arr2 = ['d', 'e', 'f'];

var arr3 = arr1.concat(arr2);
</code>```

But I have more than two arrays.
Is it possible to concat several arrays in one expression?

答:
You can supply multiple arrays to Array.prototype.concat function.

```<code>var arr1 = [1, 2, 3];
var arr2 = [4, 5, 6];
var arr3 = [7, 8, 9];

arr1.concat(arr2, arr3);     //[1, 2, 3, 4, 5, 6, 7, 8, 9]
</code>```

Body:
I am new to JavaScript. I need to write simple script which should join several arrays into one. I found this example:

var arr1 = ['a', 'b', 'c'];
var arr2 = ['d', 'e', 'f'];

var arr3 = arr1.concat(arr2);

But I have more than two arrays.
Is it possible to concat several arrays in one expression?

Body:
You can supply multiple arrays to Array.prototype.concat function.

var arr1 = [1, 2, 3];
var arr2 = [4, 5, 6];
var arr3 = [7, 8, 9];

arr1.concat(arr2, arr3);     //[1, 2, 3, 4, 5, 6, 7, 8, 9]


问:
Why I get error when I submit login form using jQuery Post?
I have this partial view:

```<code>@model GeomindEnterprise.Models.LoginViewModel

<div class="row">
    <div class="col-md-6 col-sm-6 col-xs-6">
        <!-- /SOCIAL LOGIN -->
        @using (Html.BeginForm("Login", "Account", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { @class = "sky-form", role = "form" }))
        {

            <fieldset class="nomargin">
                <div class="row">
                    <div class="col-md-10 col-md-offset-1">
                        @Html.AntiForgeryToken()

                        @Html.ValidationSummary(true, "", new { @class = "text-danger" })

                        <label class="input margin-bottom-10">
                            <i class="ico-append fa fa-envelope"></i>
                            @Html.TextBoxFor(m => m.UserName, new { @placeholder = "Email" })
                            @Html.ValidationMessageFor(m => m.UserName, "", new { @class = "text-danger" })
                        </label>

                        <label class="input margin-bottom-10">
                            <i class="ico-append fa fa-lock"></i>
                            @Html.PasswordFor(m => m.Password, new { placeholder = "Password" })
                            @Html.ValidationMessageFor(m => m.Password, "", new { @class = "text-danger" })
                        </label>

                        <label class="form-group">
                            @Html.CheckBoxFor(m => m.RememberMe, new { @class = "col-md-1" })
                            @Html.LabelFor(m => m.RememberMe)
                        </label>

                        <footer>
                            <button type="submit" onclick="myFunction()" class="btn btn-default noradius pull-right"><i class="fa fa-check"></i> OK, LOG IN</button>
                        </footer>
                    </div>
                </div>

            </fieldset>

        }
    </div>
</div>
</code>```

When I click button submit, this javascript method is called:

```<code> function myFunction() {
        debugger;
        jQuery.ajax({
            type: "POST",
            url: '@Url.Action("Login", "Account")',
            contentType: "application/json; charset=utf-8",
            data: jQuery('form').serialize(),
            datatype: "json",
            success: function (data) {
                debugger;
                jQuery('#myModalContent').html(data);
            },
            error: function () {
                alert("Dynamic content load failed.");
            }
        });
    }
</code>```

The javascript method above calls this action:

```<code>//
// POST: /Account/Login
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
    //some logic
}
</code>```

When the acction Login is called I get this error:

```<code>    The required anti-forgery form field "__RequestVerificationToken" is not present.
</code>```

Any idea why I get this error?And how to fix it?

答:
Remove the contentType: "application/json; charset=utf-8", ajax option, so that you use the default "application/x-www-form-urlencoded; charset=UTF-8" which you need when using .serialize() (note that the token is included in the request when using .serialize())

As a side note, you should be handling the forms .submit() event so you can validate the form before submitting. Remove the onclick="myFunction()" from your submit button and change the script to

```<code>$('form').submit(function(e) {
    e.preventDefault();
    if (!$(this).valid) {
        return; // cancel the ajax call and display error messages
    }
    ... make ajax call
});
</code>```

You also have datatype: "json",, but the fact you also have $('#myModalContent').html(data); suggests that your controller method returns html (a PartialViewResult), not json, so it should be datatype: "html", (or just omit that option and the $.ajax() method will work it out)

Body:
I have this partial view:

@model GeomindEnterprise.Models.LoginViewModel

        @using (Html.BeginForm("Login", "Account", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { @class = "sky-form", role = "form" }))
        {

            <fieldset class="nomargin">

                        @Html.AntiForgeryToken()

                        @Html.ValidationSummary(true, "", new { @class = "text-danger" })

                            @Html.TextBoxFor(m => m.UserName, new { @placeholder = "Email" })
                            @Html.ValidationMessageFor(m => m.UserName, "", new { @class = "text-danger" })

                            @Html.PasswordFor(m => m.Password, new { placeholder = "Password" })
                            @Html.ValidationMessageFor(m => m.Password, "", new { @class = "text-danger" })

                            @Html.CheckBoxFor(m => m.RememberMe, new { @class = "col-md-1" })
                            @Html.LabelFor(m => m.RememberMe)

                            <button type="submit" onclick="myFunction()" class="btn btn-default noradius pull-right"> OK, LOG IN</button>

            </fieldset>

        }

When I click button submit, this javascript method is called:

 function myFunction() {
        debugger;
        jQuery.ajax({
            type: "POST",
            url: '@Url.Action("Login", "Account")',
            contentType: "application/json; charset=utf-8",
            data: jQuery('form').serialize(),
            datatype: "json",
            success: function (data) {
                debugger;
                jQuery('#myModalContent').html(data);
            },
            error: function () {
                alert("Dynamic content load failed.");
            }
        });
    }

The javascript method above calls this action:

//
// POST: /Account/Login
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
    //some logic
}

When the acction Login is called I get this error:

    The required anti-forgery form field "__RequestVerificationToken" is not present.

Any idea why I get this error?And how to fix it?

Body:
Remove the contentType: "application/json; charset=utf-8", ajax option, so that you use the default "application/x-www-form-urlencoded; charset=UTF-8" which you need when using .serialize() (note that the token is included in the request when using .serialize())

As a side note, you should be handling the forms .submit() event so you can validate the form before submitting. Remove the onclick="myFunction()" from your submit button and change the script to

$('form').submit(function(e) {
    e.preventDefault();
    if (!$(this).valid) {
        return; // cancel the ajax call and display error messages
    }
    ... make ajax call
});

You also have datatype: "json",, but the fact you also have $('#myModalContent').html(data); suggests that your controller method returns html (a PartialViewResult), not json, so it should be datatype: "html", (or just omit that option and the $.ajax() method will work it out)


问:
Find a function module by its name?
Is there any module/function in python that can search functions by context or by name in python modules.

The R equivalent, if findFn from the sos package is very useful, to Search in contributed R packages.

```<code> library(sos)
 findFn('some words defintions')      ## find a package that contain such definition
 findFn('some_function_name')   ## find the some_function_name package
</code>```

For example:

```<code> findFn('Connect oracle')
</code>```

will redirect you to a link which suggest to use the ROracle package.

答:
U can use 'eval'

```<code>FunctioNameAsString = test
FunctionArgumentsAsString = ''

eval('self.'+FunctioNameAsString+'()')
</code>```

=

```<code>self.test()
</code>```

or

```<code>eval('self.__class__.'+FunctioNameAsString+'()')
</code>```

=

```<code>self.__class__.test()
</code>```

Title: Find a function module by its name?

Body:
Is there any module/function in python that can search functions by context or by name in python modules.

The R equivalent, if findFn from the sos package is very useful, to Search in contributed R packages.

 library(sos)
 findFn('some words defintions')      ## find a package that contain such definition
 findFn('some_function_name')   ## find the some_function_name package

For example:

 findFn('Connect oracle')

will redirect you to a link which suggest to use the ROracle package.

Body:
U can use 'eval'

FunctioNameAsString = test
FunctionArgumentsAsString = ''

eval('self.'+FunctioNameAsString+'()')

=

self.test()

or

eval('self.__class__.'+FunctioNameAsString+'()')

=

self.__class__.test()


问:
Call the dialog from Intent
Is it possible to call a dialog from Intent. I have two Activity RegisterActivity and AuthenticActivity and I implemented custom dialog on RegisterActivity but I also need same dialog on AuthenticActivity. So how can we get that dialog on AuthenticActivity. Can we get that from Intent, Please suggest me? I don't want to write code on both Activity.</p>

答:
Make static constant method like,

```<code>public static void showDialog(PASS_REQUIRED_PARAMS){
// do your stuff
}
</code>```

To call this method you just need to write,

```<code>CLASS_NAME.showDialog(PASS_REQUIRED_PARAMS)
</code>```

Title: Call the dialog from Intent

Body:
Make static constant method like,

public static void showDialog(PASS_REQUIRED_PARAMS){
// do your stuff
}

To call this method you just need to write,

CLASS_NAME.showDialog(PASS_REQUIRED_PARAMS)