问:
Angular 4 select option tag not binding to model because of Materialize CSS
I have an Angular 4 app and I am making a register form.
The User has to select a Job Title out of a list, made with select en option tags.
I link the values to my model, but Job Title is the only one that is not working, when I console.log() the model, there is no attribute jobTitle.

What is going wrong in my html or ts?

HTML:

```<code><form name="form" (ngSubmit)="f.form.valid && register()" #f="ngForm" novalidate>
        <div class="form-group" [ngClass]="{ 'has-error': f.submitted && !firstName.valid }">
          <label>First Name</label>
          <input type="text" class="form-control validate" name="firstName" [(ngModel)]="model.firstName"
                 #firstName="ngModel"
                 required/>
          <div *ngIf="f.submitted && !firstName.valid" class="help-block red-text">First Name is required</div>
        </div>
        <div class="form-group" [ngClass]="{ 'has-error': f.submitted && !lastName.valid }">
          <label>Last Name</label>
          <input type="text" class="form-control validate" name="lastName" [(ngModel)]="model.lastName"
                 #lastName="ngModel"
                 required/>
          <div *ngIf="f.submitted && !lastName.valid" class="help-block red-text">Last Name is required</div>
        </div>
        <div class="form-group" [ngClass]="{ 'has-error': f.submitted && !username.valid }">
          <label>Username</label>
          <input type="text" class="form-control validate" name="username" [(ngModel)]="model.username"
                 #username="ngModel"
                 required/>
          <div *ngIf="f.submitted && !username.valid" class="help-block red-text">Username is required</div>
        </div>
        <div class="form-group" [ngClass]="{ 'has-error': f.submitted && !email.valid }">
          <label>Email</label>
          <input type="email" class="form-control validate" name="email" [(ngModel)]="model.email" #email="ngModel"
                 required/>
          <div *ngIf="f.submitted && !email.valid" class="help-block red-text">Correct email is required</div>
        </div>
        <div class="form-group" [ngClass]="{ 'has-error': f.submitted && !tel.valid }">
          <label>Telephone</label>
          <input type="tel" class="form-control validate" name="tel" [(ngModel)]="model.tel" #tel="ngModel"
                 required/>
          <div *ngIf="f.submitted && !tel.valid" class="help-block red-text">Correct Telephonenumber is required</div>
        </div>

        <div class="form-group" [ngClass]="{ 'has-error': f.submitted && !company.valid }">
          <label>Company</label>
          <input type="text" class="form-control validate" name="company" [(ngModel)]="model.company" #company="ngModel"
                 required/>
          <div *ngIf="f.submitted && !company.valid" class="help-block red-text">Company is required</div>
        </div>

        <div class="form-group">
          <label>Job Title</label>
          <select  name="jobTitle" [(ngModel)]="model.jobTitle" #jobTitle="ngModel">
            <optgroup label="Business">
              <option [ngValue]="'Administrative'">Administrative</option>
              <option [ngValue]="'Banking'">Banking</option>
              <option [ngValue]="'Consulting'">Consulting</option>
              <option [ngValue]="'Corporate'">Corporate</option>
              <option [ngValue]="'Human Resources'">Human Resources</option>
              <option [ngValue]="'Insurance'">Insurance</option>
              <option [ngValue]="'Legal'">Legal</option>
              <option [ngValue]="'Public Relations'">Public Relations</option>
              <option [ngValue]="'Purchasing'">Purchasing</option>
              <option [ngValue]="'Sales'">Sales</option>
            </optgroup>
            <optgroup label="Creative Industry">
              <option [ngValue]="'Event Planning'">Event Planning</option>
              <option [ngValue]="'Fashion'">Fashion</option>
              <option [ngValue]="'Marketing'">Marketing</option>
              <option [ngValue]="'Social Media'">Social Media</option>
            </optgroup>
            <optgroup label="Service Industry">
              <option [ngValue]="'Customer Service'">Customer Service</option>
              <option [ngValue]="'Hospitality'">Hospitality</option>
              <option [ngValue]="'Real Estate'">Real Estate</option>
              <option [ngValue]="'Restaurant'">Restaurant</option>
              <option [ngValue]="'Retail'">Retail</option>
              <option [ngValue]="'Travel'">Travel</option>
            </optgroup>
            <optgroup label="Skilled,Trade">
              <option [ngValue]="'Construction'">Construction</option>
              <option [ngValue]="'Maintenance'">Maintenance</option>
              <option [ngValue]="'Manufacturing'">Manufacturing</option>
              <option [ngValue]="'Transportation'">Transportation</option>
            </optgroup>
            <optgroup label="Technical">
              <option [ngValue]="'Engineering'">Engineering</option>
              <option [ngValue]="'Environmental'">Environmental</option>
              <option [ngValue]="'Healthcare'">Healthcare/Medical</option>
              <option [ngValue]="'Information Technology'">Information Technology (IT)</option>
              <option [ngValue]="'Science'">Science</option>
            </optgroup>
            <optgroup label="Others">
              <option [ngValue]="'Animal'">Animal</option>
              <option [ngValue]="'Fundraiser'">Fundraiser</option>
              <option [ngValue]="'Non-Profit'">Non-Profit</option>
              <option [ngValue]="'School'">School</option>
              <option [ngValue]="'Sports'">Sports</option>
              <option [ngValue]="'Entry Level Job'">Entry Level Job</option>
              <option [ngValue]="'Not defined'" selected>Not defined</option>
            </optgroup>
          </select>
        </div>

        <div class="form-group" [ngClass]="{ 'has-error': f.submitted && !password.valid }">
          <label for="pass">Password</label>
          <input type="password" id="pass" class="form-control validate" name="password" [(ngModel)]="model.password"
                 #password="ngModel"
                 required/>
          <div *ngIf="f.submitted && !password.valid" class="help-block red-text">Password is required</div>
        </div>
        <div class="form-group">
          <div class="button-set">
            <button [disabled]="loading" class="btn btn-primary">Register</button>
            <a [routerLink]="['/login']" class="btn btn-secondary">Log in</a>
          </div>
        </div>
      </form>
</code>```

TS

```<code>import { Component} from '@angular/core';

import { AlertService} from '../../_services/index';
declare let $ : any;

@Component({
  moduleId: module.id,
  templateUrl: 'register.component.html',
  styleUrls: ['../../app.component.css']
})

export class RegisterComponent {
  private loading:boolean = false;
  public model:any = {};
  constructor(private alertService:AlertService) {
  }

  public register() {
    this.loading = true;
    this.alertService.success('Registration successful', true);
    console.log(JSON.stringify(this.model));
  }
}
</code>```

CURRENT SOLUTION
Do not use materialize css, that solves my problem, when I set my select tag to browser.default than it works.

to initialize Materialize CSS select and options I do the following in my TS file

```<code>ngOnInit() {
    $(function(){
      $('select').material_select();
    }); // end of document ready

    this.model.jobTitle = 'Not Defined';
  }
</code>```

答:
Its working for me</p>

```<code><div class="input-field col s12">
    <select formControlName="status" [(ngModel)]="selectedStatus" materialize="material_select">
        <option [ngValue]="" disabled>Select</option>
        <option [ngValue]="1">Enable</option>
        <option [ngValue]="0">Disable</option>
    </select>
    <label>Status</label>
</div>
</code>```

Body:
I have an Angular 4 app and I am making a register form.
The User has to select a Job Title out of a list, made with select en option tags.
I link the values to my model, but Job Title is the only one that is not working, when I console.log() the model, there is no attribute jobTitle.

What is going wrong in my html or ts?

HTML:

<form name="form" (ngSubmit)="f.form.valid && register()" #f="ngForm" novalidate>

          First Name
          <input type="text" class="form-control validate" name="firstName" [(ngModel)]="model.firstName"
                 #firstName="ngModel"
                 required/>

First Name is required

          Last Name
          <input type="text" class="form-control validate" name="lastName" [(ngModel)]="model.lastName"
                 #lastName="ngModel"
                 required/>

Last Name is required

          Username
          <input type="text" class="form-control validate" name="username" [(ngModel)]="model.username"
                 #username="ngModel"
                 required/>

Username is required

          Email
          <input type="email" class="form-control validate" name="email" [(ngModel)]="model.email" #email="ngModel"
                 required/>

Correct email is required

          Telephone
          <input type="tel" class="form-control validate" name="tel" [(ngModel)]="model.tel" #tel="ngModel"
                 required/>

Correct Telephonenumber is required

          Company
          <input type="text" class="form-control validate" name="company" [(ngModel)]="model.company" #company="ngModel"
                 required/>

Company is required

          Job Title
          <select  name="jobTitle" [(ngModel)]="model.jobTitle" #jobTitle="ngModel">
            <optgroup label="Business">
              <option [ngValue]="'Administrative'">Administrative</option>
              <option [ngValue]="'Banking'">Banking</option>
              <option [ngValue]="'Consulting'">Consulting</option>
              <option [ngValue]="'Corporate'">Corporate</option>
              <option [ngValue]="'Human Resources'">Human Resources</option>
              <option [ngValue]="'Insurance'">Insurance</option>
              <option [ngValue]="'Legal'">Legal</option>
              <option [ngValue]="'Public Relations'">Public Relations</option>
              <option [ngValue]="'Purchasing'">Purchasing</option>
              <option [ngValue]="'Sales'">Sales</option>
            </optgroup>
            <optgroup label="Creative Industry">
              <option [ngValue]="'Event Planning'">Event Planning</option>
              <option [ngValue]="'Fashion'">Fashion</option>
              <option [ngValue]="'Marketing'">Marketing</option>
              <option [ngValue]="'Social Media'">Social Media</option>
            </optgroup>
            <optgroup label="Service Industry">
              <option [ngValue]="'Customer Service'">Customer Service</option>
              <option [ngValue]="'Hospitality'">Hospitality</option>
              <option [ngValue]="'Real Estate'">Real Estate</option>
              <option [ngValue]="'Restaurant'">Restaurant</option>
              <option [ngValue]="'Retail'">Retail</option>
              <option [ngValue]="'Travel'">Travel</option>
            </optgroup>
            <optgroup label="Skilled,Trade">
              <option [ngValue]="'Construction'">Construction</option>
              <option [ngValue]="'Maintenance'">Maintenance</option>
              <option [ngValue]="'Manufacturing'">Manufacturing</option>
              <option [ngValue]="'Transportation'">Transportation</option>
            </optgroup>
            <optgroup label="Technical">
              <option [ngValue]="'Engineering'">Engineering</option>
              <option [ngValue]="'Environmental'">Environmental</option>
              <option [ngValue]="'Healthcare'">Healthcare/Medical</option>
              <option [ngValue]="'Information Technology'">Information Technology (IT)</option>
              <option [ngValue]="'Science'">Science</option>
            </optgroup>
            <optgroup label="Others">
              <option [ngValue]="'Animal'">Animal</option>
              <option [ngValue]="'Fundraiser'">Fundraiser</option>
              <option [ngValue]="'Non-Profit'">Non-Profit</option>
              <option [ngValue]="'School'">School</option>
              <option [ngValue]="'Sports'">Sports</option>
              <option [ngValue]="'Entry Level Job'">Entry Level Job</option>
              <option [ngValue]="'Not defined'" selected>Not defined</option>
            </optgroup>
          </select>

          Password
          <input type="password" id="pass" class="form-control validate" name="password" [(ngModel)]="model.password"
                 #password="ngModel"
                 required/>

Password is required

            <button [disabled]="loading" class="btn btn-primary">Register</button>
            Log in

      </form>

TS

import { Component} from '@angular/core';

import { AlertService} from '../../_services/index';
declare let $ : any;

@Component({
  moduleId: module.id,
  templateUrl: 'register.component.html',
  styleUrls: ['../../app.component.css']
})

export class RegisterComponent {
  private loading:boolean = false;
  public model:any = {};
  constructor(private alertService:AlertService) {
  }

  public register() {
    this.loading = true;
    this.alertService.success('Registration successful', true);
    console.log(JSON.stringify(this.model));
  }
}

CURRENT SOLUTION
Do not use materialize css, that solves my problem, when I set my select tag to browser.default than it works.

to initialize Materialize CSS select and options I do the following in my TS file

ngOnInit() {
    $(function(){
      $('select').material_select();
    }); // end of document ready

    this.model.jobTitle = 'Not Defined';
  }

Body:
Its working for me

<div class="input-field col s12">
    <select formControlName="status" [(ngModel)]="selectedStatus" materialize="material_select">
        <option [ngValue]="" disabled>Select</option>
        <option [ngValue]="1">Enable</option>
        <option [ngValue]="0">Disable</option>
    </select>
    <label>Status</label>
</div>


来源: stackexchange

问:
Remove null params in HttpParams
I have a criteria object for which some attributes can be null, if I don't do anything the query string include those like &p=undefined which is not desirable since at the WebApi these come as"null" instead of null
So given this in the Angular client

```<code>      return this._http
          .get<ExposureDifference[]>(AppSettings.ExposureRunDataQueryString, {params : <any>criteria, withCredentials: true})
          .catch<any, ExposureDifference[]>(this._trace.handleError("GET " + AppSettings.ExposureRunDataQueryString + criteria, []))
          .finally(() => this.isLoading = false);
</code>```

I could get the query string as

```<code>http://localhost:63037/api/exposureRuns/data/?id=3&secsymb=undefined&fund=EL&esectype=SWAP_CDS
</code>```

Is there a way to exclude the undefined parameters from the query string?

答:
You should filter them client side using JavaScript's delete (MDN) keyword if they have a value of undefined (which is different than the key not being in the object at all):

```<code>if (queryObject.secsymb === undefined) {
  delete queryObject.secsymb;
}
</code>```

and then use a default method parameter in your controller method:

```<code>GetExposureRunsData(int id, string fund, SecType sectype, string secsymb = null)
</code>```

If you ensure that the query string parameter is not included then your parameter will default to null

ContentLicense: CC BY-SA 3.0

Title: Remove null params in HttpParams

Body:
I have a criteria object for which some attributes can be null, if I don't do anything the query string include those like &p=undefined which is not desirable since at the WebApi these come as"null" instead of null
So given this in the Angular client

      return this._http
          .get<ExposureDifference[]>(AppSettings.ExposureRunDataQueryString, {params : <any>criteria, withCredentials: true})
          .catch<any, ExposureDifference[]>(this._trace.handleError("GET " + AppSettings.ExposureRunDataQueryString + criteria, []))
          .finally(() => this.isLoading = false);

I could get the query string as

http://localhost:63037/api/exposureRuns/data/?id=3&secsymb=undefined&fund=EL&esectype=SWAP_CDS

Is there a way to exclude the undefined parameters from the query string?

Body:
You should filter them client side using JavaScript's delete (MDN) keyword if they have a value of undefined (which is different than the key not being in the object at all):

if (queryObject.secsymb === undefined) {
  delete queryObject.secsymb;
}

and then use a default method parameter in your controller method:

GetExposureRunsData(int id, string fund, SecType sectype, string secsymb = null)

If you ensure that the query string parameter is not included then your parameter will default to null


问:
Image View Double Border
I'm calling a function that sets up a UIImageView:

```<code>func setupImageView(_ imageView: UIImageView) {}
</code>```

I want to give that UIImageView an image, round its corners, and give it two different borders.

Here is what I am currently doing:

```<code>imageView.image = imageConstants.imageThatIsWanted
imageView.clipsToBounds = true
imageView.layer.cornerRadius = imageView.frame.height / 2
imageView.layer.borderWidth = 3.0
imageView.layer.borderColor = UIColor.white.cgColor
</code>```

What is the best way to apply a second borderColor of color blue around the white border?

I tried creating a sublayer as a CALayer and giving it a blue border, but this goes behind the image, and also inside of the white border. I also tried drawing a UIBezierPath, but that stays inside of the white border as well.

答:
```<code>import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var secondView: UIView!
    @IBOutlet weak var imgView: UIImageView!
    override func viewDidLoad() {
        super.viewDidLoad()
        imgView.layer.cornerRadius = imgView.frame.size.height/2
         secondView.layer.cornerRadius = secondView.frame.size.height/2
        imgView.layer.borderWidth = 5.0
        imgView.layer.borderColor = UIColor.red.cgColor
        imgView.clipsToBounds = true
         secondView.clipsToBounds = true
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}
</code>```

Title: Image View Double Border

Body:
I'm calling a function that sets up a UIImageView:

func setupImageView(_ imageView: UIImageView) {}

I want to give that UIImageView an image, round its corners, and give it two different borders.

Here is what I am currently doing:

imageView.image = imageConstants.imageThatIsWanted
imageView.clipsToBounds = true
imageView.layer.cornerRadius = imageView.frame.height / 2
imageView.layer.borderWidth = 3.0
imageView.layer.borderColor = UIColor.white.cgColor

What is the best way to apply a second borderColor of color blue around the white border?

I tried creating a sublayer as a CALayer and giving it a blue border, but this goes behind the image, and also inside of the white border. I also tried drawing a UIBezierPath, but that stays inside of the white border as well.


问:
How to rename uploaded file before saving it into a directory in PHP?
I use this Simple upload and resize image on PHP project to do my project.
https://gist.github.com/zeuxisoo/910107/483c7b6082dcc484d7b4cee21aad12650c53e416
but I don't know how to rename the file after upload.
I want to rename file and upload it into server as well as in database. The follow is code:

```<code>public function run() {
    $total = count($this->files);
    for($i=0; $i<$total; $i++) {
        if (empty($this->files['name'][$i]) === false) {
            if (move_uploaded_file($this->files['tmp_name'][$i], $this->store_directory.'/'.$this->files['name'][$i]) == false) {
                $this->errors['type'] = "run";
                $this->errors['file_name'] = $this->files['name'][$i];
            }
        }
    }

    return empty($this->errors);
}
</code>```

I use a lot of method , eg basename
It can't to it, any idea?? Thanks

答:
Instead of using move_uploaded_file use it as per code example given below.

```<code>$temp = explode(".", $_FILES["file"]["name"]);
$newfilename = round(microtime(true)) . '.' . end($temp);
move_uploaded_file($_FILES["file"]["tmp_name"], "../img/imageDirectory/" . $newfilename);
</code>```

Body:
I use this Simple upload and resize image on PHP project to do my project.
https://gist.github.com/zeuxisoo/910107/483c7b6082dcc484d7b4cee21aad12650c53e416
but I don't know how to rename the file after upload.
I want to rename file and upload it into server as well as in database. The follow is code:

public function run() {
    $total = count($this->files);
    for($i=0; $i<$total; $i++) {
        if (empty($this->files['name'][$i]) === false) {
            if (move_uploaded_file($this->files['tmp_name'][$i], $this->store_directory.'/'.$this->files['name'][$i]) == false) {
                $this->errors['type'] = "run";
                $this->errors['file_name'] = $this->files['name'][$i];
            }
        }
    }

    return empty($this->errors);
}

I use a lot of method , eg basename
It can't to it, any idea?? Thanks

Body:
Instead of using move_uploaded_file use it as per code example given below.

$temp = explode(".", $_FILES["file"]["name"]);
$newfilename = round(microtime(true)) . '.' . end($temp);
move_uploaded_file($_FILES["file"]["tmp_name"], "../img/imageDirectory/" . $newfilename);


答:
You can do this

```<code>public function run() {
    $total = count($this->files);
    for($i=0; $i<$total; $i++) {
        if (empty($this->files['name'][$i]) === false) {

              $tempName = explode(".", $this->files['name'][$i]);
              $newName = "IMAGE_NAME"; //generate unique string to avoid conflict
              $newfilename = $newName . '.' . end($tempName );
            if (move_uploaded_file($this->files['tmp_name'][$i], $this->store_directory.'/'.$newfilename) == false) {
                $this->errors['type'] = "run";
                $this->errors['file_name'] = $this->files['name'][$i];
            }
        }
    }

    return empty($this->errors);
}
</code>```

In $newName you can generate new name for your file.

Update

To avoid conflict use unique string each time when you generate the name.

Title: How to rename uploaded file before saving it into a directory in PHP?

Body:
You can do this

public function run() {
    $total = count($this->files);
    for($i=0; $i<$total; $i++) {
        if (empty($this->files['name'][$i]) === false) {

              $tempName = explode(".", $this->files['name'][$i]);
              $newName = "IMAGE_NAME"; //generate unique string to avoid conflict
              $newfilename = $newName . '.' . end($tempName );
            if (move_uploaded_file($this->files['tmp_name'][$i], $this->store_directory.'/'.$newfilename) == false) {
                $this->errors['type'] = "run";
                $this->errors['file_name'] = $this->files['name'][$i];
            }
        }
    }

    return empty($this->errors);
}

In $newName you can generate new name for your file.

Update

To avoid conflict use unique string each time when you generate the name.

ContentLicense: CC BY-SA 4.0


答:
Here is your solution</p>

```<code>public function run(){
    $total = count($this->files);
    for($i=0; $i<$total; $i++){
        if(empty($this->files['name'][$i]) === false){
            $ext = substr(strtolower(strrchr($this->files['name'][$i], '.')), 1); //get the extension
            $new_name = 'new-name'.date('dmY').$ext;
            if (move_uploaded_file($this->files['tmp_name'][$i], $this->store_directory.'/'.$new_name) == false) {
                $this->errors['type'] = "run";
                $this->errors['file_name'] = $this->files['name'][$i];
            }
        }
    }
    return empty($this->errors);
}
</code>```

Body:
Here is your solution

public function run(){
    $total = count($this->files);
    for($i=0; $i<$total; $i++){
        if(empty($this->files['name'][$i]) === false){
            $ext = substr(strtolower(strrchr($this->files['name'][$i], '.')), 1); //get the extension
            $new_name = 'new-name'.date('dmY').$ext;
            if (move_uploaded_file($this->files['tmp_name'][$i], $this->store_directory.'/'.$new_name) == false) {
                $this->errors['type'] = "run";
                $this->errors['file_name'] = $this->files['name'][$i];
            }
        }
    }
    return empty($this->errors);
}


问:
changing step in the loop T-SQL

Hello.
I have some trouble. I have a table with dates for 4 years. I need to run loop through it using a day value = 7, month value = 30 and years = 365.
How can I change this value inside the loop?

```<code>WHILE @start_date <= @finish_date
    BEGIN
        -- SOME ALGORITHM
        SET @start_date = @start_date + 1
    END
</code>```

I would like to get changing value @start1 = 7 + 1; @start1 = 30 + 1 and @start1 = 365 + 1.
I think it's possible, but I haven't any idea (haven't any working idea at the moment)

I was trying to use CASE construction, but when I ran it - my DBeaver application was shut down immediately.

答:
I think you can use DATEADD with YEAR/MONTH/DAY

```<code>DECLARE @start_date date='20140101'
DECLARE @finish_date date='20160101'

WHILE @start_date <= @finish_date
BEGIN
    PRINT CONVERT(varchar(10),@start_date,120)
    SET @start_date = DATEADD(YEAR,1,@start_date)
    --SET @start_date = DATEADD(MONTH,1,@start_date)
    --SET @start_date = DATEADD(DAY,1,@start_date)
END
</code>```

Title: changing step in the loop T-SQL

Body:
Hello.
I have some trouble. I have a table with dates for 4 years. I need to run loop through it using a day value = 7, month value = 30 and years = 365.
How can I change this value inside the loop?

WHILE @start_date <= @finish_date
    BEGIN
        -- SOME ALGORITHM
        SET @start_date = @start_date + 1
    END

I would like to get changing value @start1 = 7 + 1; @start1 = 30 + 1 and @start1 = 365 + 1.
I think it's possible, but I haven't any idea (haven't any working idea at the moment)

I was trying to use CASE construction, but when I ran it - my DBeaver application was shut down immediately.

Body:
I think you can use DATEADD with YEAR/MONTH/DAY

DECLARE @start_date date='20140101'
DECLARE @finish_date date='20160101'

WHILE @start_date <= @finish_date
BEGIN
    PRINT CONVERT(varchar(10),@start_date,120)
    SET @start_date = DATEADD(YEAR,1,@start_date)
    --SET @start_date = DATEADD(MONTH,1,@start_date)
    --SET @start_date = DATEADD(DAY,1,@start_date)
END


问:
HashSet<T> on Windows Phone 7
Is there no System.Collections.Generic.HashSet on Windows Phone 7?</p>

答:
It is supported in SL4

HashSet(Of T) Class

However on Widows Phone 7, is compatible with Silverlight 3.0 API and SL 4 is not supported. So the answer is no, you can not use HashSet for Windows Phone 7 yet.

ContentLicense: CC BY-SA 2.5

Title: HashSet<T> on Windows Phone 7


问:
Node ORM and Python ORM for same DB?
If I have two backends, one NodeJS and one Python both of them are accessing the same database. Is it possible to use an ORM for both or is that really bad practice? It seems like that would lead to a maintenance nightmare.</p>

答: so long as both ORMs put few constraints on the database structure it should be fine. </p>

Title: Node ORM and Python ORM for same DB?


问:
Why i'm getting error?com.android.volley.timeouterror
Hello guys can someone help me with this class? I am getting an error and I am only new to the android studio and mobile development. I'm in the process of learning and acquiring knowledge. Please help me. </p>

```<code>RequestQueue requestQueue = Volley.newRequestQueue(this);

StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
    @Override
    public void onResponse(String response) {
        Toast.makeText(Register.this, response, Toast.LENGTH_LONG).show();
    }
}, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
        Toast.makeText(Register.this, error.toString(), Toast.LENGTH_LONG).show();

    }
}) {

    @Override
    protected Map<String, String> getParams() throws AuthFailureError {

        Map<String, String> params = new HashMap<String, String>();
        params.put(NAME, pangaran);
        params.put(SURNAME, apelyido);
        params.put(ADDRESS, lugar);
        params.put(CONTACTNO, kontak);
        params.put(USERNAME, username1);
        params.put(PASSWORD, password1);
        return params;

    }
};

requestQueue.add(stringRequest);
</code>```

答:
May be you can increase the timeout to check the fine working of everything. Since you said that your code worked for you earlier, the possible reason could be your server took less time to respond to your request which may not be same at all the time due to traffics.

Try adding following lines to you existing code.

```<code>stringRequest.setRetryPolicy(new RetryPolicy() {
        @Override
        public int getCurrentTimeout() {
            return 30000;
        }

        @Override
        public int getCurrentRetryCount() {
            return 30000;
        }

        @Override
        public void retry(VolleyError error) throws VolleyError {

        }
    });
</code>```

Body:
Hello guys can someone help me with this class? I am getting an error and I am only new to the android studio and mobile development. I'm in the process of learning and acquiring knowledge. Please help me.

RequestQueue requestQueue = Volley.newRequestQueue(this);

StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
    @Override
    public void onResponse(String response) {
        Toast.makeText(Register.this, response, Toast.LENGTH_LONG).show();
    }
}, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
        Toast.makeText(Register.this, error.toString(), Toast.LENGTH_LONG).show();

    }
}) {

    @Override
    protected Map<String, String> getParams() throws AuthFailureError {

        Map<String, String> params = new HashMap<String, String>();
        params.put(NAME, pangaran);
        params.put(SURNAME, apelyido);
        params.put(ADDRESS, lugar);
        params.put(CONTACTNO, kontak);
        params.put(USERNAME, username1);
        params.put(PASSWORD, password1);
        return params;

    }
};

requestQueue.add(stringRequest);

Body:
May be you can increase the timeout to check the fine working of everything. Since you said that your code worked for you earlier, the possible reason could be your server took less time to respond to your request which may not be same at all the time due to traffics.

Try adding following lines to you existing code.

stringRequest.setRetryPolicy(new RetryPolicy() {
        @Override
        public int getCurrentTimeout() {
            return 30000;
        }

        @Override
        public int getCurrentRetryCount() {
            return 30000;
        }

        @Override
        public void retry(VolleyError error) throws VolleyError {

        }
    });


问:
Android : Nested if statements jump between statements
In my Android application I am trying to read an xml file using XMLPullParser using the following code:

```<code>while (eventType != XmlPullParser.END_DOCUMENT)
                {
                    if (eventType == XmlPullParser.START_TAG)
                    {
                        s = xpp.getName();
                        if (xpp.getName().equalsIgnoreCase("container"))
                        {
                            state = stateContainer;
                            con = new Container();
                            con.setId(xpp.getAttributeValue(0));
                            con.setParentId(xpp.getAttributeValue(1));
                            con.setRestricted(xpp.getAttributeValue(2));
                        }
                        else if (xpp.getName().equalsIgnoreCase("title"))
                        {
                            state = stateTitle;
                        }
                        else
                        {
                            state = stateUnknown;
                        }
                    }
                    else if (eventType == XmlPullParser.TEXT)
                    {
                        s = xpp.getText();
                        if (state == stateTitle)
                        {
                            con.setTitle(s);
                        }
                    }
                    else if (eventType == XmlPullParser.END_TAG)
                    {
                        s = xpp.getText();
                        if (xpp.getText().equalsIgnoreCase("container"))
                        {
                            listAdapter.add(con);
                        }
                    }
                    eventType = xpp.next();
                }
</code>```

However, it seems to jump into the line 'listAdapter.add(con);' when none of the other if clauses are true in the other if statements. For example:

else if (eventType == XmlPullParser.TEXT) returns true. It then tries if (state == stateTitle) which returns false. It should jump to eventType == xpp.next(); but instead goes to listAdapter.add(con); which is nested in a different if statement. This also happens with some other if statements.

I would say I'm no beginner when it comes to programming but I can not seem to work out where this problem is coming from!

Thanks

答:
There is no magic.

If, while debugging you see the control flow acting as you describe it, then it seems likely that the code you are executing does not match the source.  Try doing a clean and a full rebuild.

Body:
In my Android application I am trying to read an xml file using XMLPullParser using the following code:

while (eventType != XmlPullParser.END_DOCUMENT)
                {
                    if (eventType == XmlPullParser.START_TAG)
                    {
                        s = xpp.getName();
                        if (xpp.getName().equalsIgnoreCase("container"))
                        {
                            state = stateContainer;
                            con = new Container();
                            con.setId(xpp.getAttributeValue(0));
                            con.setParentId(xpp.getAttributeValue(1));
                            con.setRestricted(xpp.getAttributeValue(2));
                        }
                        else if (xpp.getName().equalsIgnoreCase("title"))
                        {
                            state = stateTitle;
                        }
                        else
                        {
                            state = stateUnknown;
                        }
                    }
                    else if (eventType == XmlPullParser.TEXT)
                    {
                        s = xpp.getText();
                        if (state == stateTitle)
                        {
                            con.setTitle(s);
                        }
                    }
                    else if (eventType == XmlPullParser.END_TAG)
                    {
                        s = xpp.getText();
                        if (xpp.getText().equalsIgnoreCase("container"))
                        {
                            listAdapter.add(con);
                        }
                    }
                    eventType = xpp.next();
                }

However, it seems to jump into the line 'listAdapter.add(con);' when none of the other if clauses are true in the other if statements. For example:

else if (eventType == XmlPullParser.TEXT) returns true. It then tries if (state == stateTitle) which returns false. It should jump to eventType == xpp.next(); but instead goes to listAdapter.add(con); which is nested in a different if statement. This also happens with some other if statements.

I would say I'm no beginner when it comes to programming but I can not seem to work out where this problem is coming from!

Thanks


问:
R Count number of rows by Date and hour
I have in R a big dataset spanning several days and need to create a new vector which counts the number of rows belonging to each hour of each date, with zeros if the hours in between are not represented (so there will be 24 values in the vector for each day). For example:

```<code>Date
29/07/2012 20:00:01
29/07/2012 20:00:02
29/07/2012 20:00:03
29/07/2012 22:01:01
29/07/2012 22:02:01
29/07/2012 22:02:03
30/07/2012 02:05:05
30/07/2012 02:05:06
30/07/2012 12:09:07
30/07/2012 12:10:06
31/07/2012 01:24:36
31/07/2012 01:24:40
</code>```

would give a vector of

```<code>3,0,3,0,0,0,2,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,2
</code>```

I've found similar things (Count number of observations per day, month and year in R and R group by date, and summarize the values) but they use as.Date as they don't account for hour and I haven't been able to adapt them to work.

How would I do this? Thanks!

答:
We can do this with tidyverse.  After converting the 'Date' column datetime class, get the count based on the Date and the hour, grouped by 'Date1', complete for any missing sequence

```<code>library(tidyverse)
df1 %>%
    mutate(Date = dmy_hms(Date)) %>%
    count(Date1 = as.Date(Date), Hour = hour(Date)) %>%
    group_by(Date1) %>%
    complete(Date1, Hour = min(Hour):24, fill = list(n = 0)) %>%
    arrange(Date1, Hour)
</code>```

Title: R Count number of rows by Date and hour

Body:
I have in R a big dataset spanning several days and need to create a new vector which counts the number of rows belonging to each hour of each date, with zeros if the hours in between are not represented (so there will be 24 values in the vector for each day). For example:

Date
29/07/2012 20:00:01
29/07/2012 20:00:02
29/07/2012 20:00:03
29/07/2012 22:01:01
29/07/2012 22:02:01
29/07/2012 22:02:03
30/07/2012 02:05:05
30/07/2012 02:05:06
30/07/2012 12:09:07
30/07/2012 12:10:06
31/07/2012 01:24:36
31/07/2012 01:24:40

would give a vector of

3,0,3,0,0,0,2,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,2

I've found similar things (Count number of observations per day, month and year in R and R group by date, and summarize the values) but they use as.Date as they don't account for hour and I haven't been able to adapt them to work.

How would I do this? Thanks!

Body:
We can do this with tidyverse.  After converting the 'Date' column datetime class, get the count based on the Date and the hour, grouped by 'Date1', complete for any missing sequence

library(tidyverse)
df1 %>%
    mutate(Date = dmy_hms(Date)) %>%
    count(Date1 = as.Date(Date), Hour = hour(Date)) %>%
    group_by(Date1) %>%
    complete(Date1, Hour = min(Hour):24, fill = list(n = 0)) %>%
    arrange(Date1, Hour)


问:
Babel Preset ENV issues
Good day:

I've just installed Babel Preset-ENV through NPM and getting this issue:

```<code>[nodemon] starting `babel-node server.js server.js`
/home/vagrant/api/node_modules/babel-core/lib/transformation/file/options/option-manager.js:328
        throw e;
        ^

TypeError: Cannot read property 'loose' of undefined (While processing preset: "/home/vagrant/api/node_modules/@babel/preset-env/lib/index.js")
    at _default (/home/vagrant/api/node_modules/@babel/plugin-transform-modules-commonjs/lib/index.js:19:22)
    at Function.memoisePluginContainer (/home/vagrant/api/node_modules/babel-core/lib/transformation/file/options/option-manager.js:113:13)
    at Function.normalisePlugin (/home/vagrant/api/node_modules/babel-core/lib/transformation/file/options/option-manager.js:146:32)
    at /home/vagrant/api/node_modules/babel-core/lib/transformation/file/options/option-manager.js:184:30
    at Array.map (native)
    at Function.normalisePlugins (/home/vagrant/api/node_modules/babel-core/lib/transformation/file/options/option-manager.js:158:20)
    at OptionManager.mergeOptions (/home/vagrant/api/node_modules/babel-core/lib/transformation/file/options/option-manager.js:234:36)
    at /home/vagrant/api/node_modules/babel-core/lib/transformation/file/options/option-manager.js:265:14
    at /home/vagrant/api/node_modules/babel-core/lib/transformation/file/options/option-manager.js:323:22
    at Array.map (native)
</code>```

My Package.JSON is the following:

```<code>{
  "name": "api",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "nodemon -L server.js --ignore 'db/schema.json' --exec babel-node server.js"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@babel/core": "^7.0.0-beta.32",
    "@babel/preset-env": "^7.0.0-beta.32",
    "babel-core": "^6.26.0",
    "express": "^4.16.2",
    "express-graphql": "^0.6.11",
    "express-oauth-server": "^2.0.0",
    "graphql": "^0.11.7",
    "jsonwebtoken": "^8.1.0",
    "mongo": "^0.1.0",
    "mongoose": "^4.13.2",
    "password-hash": "^1.2.2",
    "react-relay": "^1.4.1"
  },
  "devDependencies": {
    "babel-cli": "^6.26.0"
  }
}
</code>```

And also my .babelrc is this:

```<code>vagrant@vagrant-ubuntu-trusty-64:~/api$ cat .babelrc
{
  "presets": [
    ["@babel/preset-env", {
      "targets": {
        "node": "current"
      }
    }]
  ]
}
</code>```

Before the upgrade I was using stage-0 and es2015 presets that were working however, after the upgrade this has been buggy. Note, my NPM version is 4.6.1.

Thanks.

答:
Make sure your Babel dependencies are compatible with each other.

this:

```<code>"@babel/core": "^7.0.0-beta.32",
"@babel/preset-env": "^7.0.0-beta.32",
"babel-core": "^6.26.0",
"babel-cli": "^6.26.0"
</code>```

should be this:

```<code>"@babel/cli": "^7.0.0-beta.34",
"@babel/core": "^7.0.0-beta.34",
"@babel/node": "^7.0.0-beta.34",
</code>```

Title: Babel Preset ENV issues

Body:
Good day:

I've just installed Babel Preset-ENV through NPM and getting this issue:

[nodemon] starting `babel-node server.js server.js`
/home/vagrant/api/node_modules/babel-core/lib/transformation/file/options/option-manager.js:328
        throw e;
        ^

TypeError: Cannot read property 'loose' of undefined (While processing preset: "/home/vagrant/api/node_modules/@babel/preset-env/lib/index.js")
    at _default (/home/vagrant/api/node_modules/@babel/plugin-transform-modules-commonjs/lib/index.js:19:22)
    at Function.memoisePluginContainer (/home/vagrant/api/node_modules/babel-core/lib/transformation/file/options/option-manager.js:113:13)
    at Function.normalisePlugin (/home/vagrant/api/node_modules/babel-core/lib/transformation/file/options/option-manager.js:146:32)
    at /home/vagrant/api/node_modules/babel-core/lib/transformation/file/options/option-manager.js:184:30
    at Array.map (native)
    at Function.normalisePlugins (/home/vagrant/api/node_modules/babel-core/lib/transformation/file/options/option-manager.js:158:20)
    at OptionManager.mergeOptions (/home/vagrant/api/node_modules/babel-core/lib/transformation/file/options/option-manager.js:234:36)
    at /home/vagrant/api/node_modules/babel-core/lib/transformation/file/options/option-manager.js:265:14
    at /home/vagrant/api/node_modules/babel-core/lib/transformation/file/options/option-manager.js:323:22
    at Array.map (native)

My Package.JSON is the following:

{
  "name": "api",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "nodemon -L server.js --ignore 'db/schema.json' --exec babel-node server.js"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@babel/core": "^7.0.0-beta.32",
    "@babel/preset-env": "^7.0.0-beta.32",
    "babel-core": "^6.26.0",
    "express": "^4.16.2",
    "express-graphql": "^0.6.11",
    "express-oauth-server": "^2.0.0",
    "graphql": "^0.11.7",
    "jsonwebtoken": "^8.1.0",
    "mongo": "^0.1.0",
    "mongoose": "^4.13.2",
    "password-hash": "^1.2.2",
    "react-relay": "^1.4.1"
  },
  "devDependencies": {
    "babel-cli": "^6.26.0"
  }
}

And also my .babelrc is this:

vagrant@vagrant-ubuntu-trusty-64:~/api$ cat .babelrc
{
  "presets": [
    ["@babel/preset-env", {
      "targets": {
        "node": "current"
      }
    }]
  ]
}

Before the upgrade I was using stage-0 and es2015 presets that were working however, after the upgrade this has been buggy. Note, my NPM version is 4.6.1.

Thanks.

Body:
Make sure your Babel dependencies are compatible with each other.

this:

"@babel/core": "^7.0.0-beta.32",
"@babel/preset-env": "^7.0.0-beta.32",
"babel-core": "^6.26.0",
"babel-cli": "^6.26.0"

should be this:

"@babel/cli": "^7.0.0-beta.34",
"@babel/core": "^7.0.0-beta.34",
"@babel/node": "^7.0.0-beta.34",


问:
Show all options of datalist on focus
Is there any way to show all options of datalist on focus? I need to show all the options even after a key press.

```<code><form action="" method="get">
 <input list="browsers" name="browser">
 <datalist id="browsers">
  <option value="Internet Explorer">
  <option value="Firefox">
  <option value="Chrome">
  <option value="Opera">
  <option value="Safari">
 </datalist>
 <input type="submit">
</form>
</code>```

FIDDLE

PS: This is not same as this question. My datalist options are generated dynamically using jquery.

答:
```<code>$('input').on('click', function() {
  $(this).val('');
});
</code>```

try this this will work

Title: Show all options of datalist on focus

Body:
Is there any way to show all options of datalist on focus? I need to show all the options even after a key press.

<form action="" method="get">
 <input list="browsers" name="browser">
 <datalist id="browsers">
  <option value="Internet Explorer">
  <option value="Firefox">
  <option value="Chrome">
  <option value="Opera">
  <option value="Safari">
 </datalist>
 <input type="submit">
</form>

FIDDLE

PS: This is not same as this question. My datalist options are generated dynamically using jquery.

Body:
$('input').on('click', function() {
  $(this).val('');
});

try this this will work


问:
Agile Web Development with Rails 5 - Action Cable
I'm working through the ActionCable example within the book.  All of the code is added as described and I can see the ActionCable server log hit but the updating page never updates the cost of the item.  What am I missing?

The following log entry tells me that ActionCable is firing.  the code is below.

```<code>  Product Load (0.1ms)  SELECT "products".* FROM "products"
  Rendered store/index.html.erb (6.0ms)
[ActionCable] Broadcasting to products: {:html=>"<p id=\"notice\"></p>\n\n<h1>Your Pragmatic Catalog</h1>\n\n\n\n      <div class=\"entry\">\n\n        <img src=\"/assets/dcbang-28758120ca6616f3f95a4b73dda112a1f8e6ac3175e35b67e78d0ab0bd177566.jpg\" alt=\"Dcbang\" />\n        <h3>Rails, Angular, Postgres, and Bootstrap</h3>\n\n        <p>\r\n      <em>Powerful, Effective, and Efficient Full-Stack Web Development</em>\r\n      As a Rails developer, you care about user experience and performance,\r\n      but you also want simple and maintainable code. Achieve all that by\r\n      embracing the full stack of web development, from styling with\r\n      Bootstrap, building an interactive user interface with AngularJS, to\r\n      storing data quickly and reliably in PostgreSQL. Take a holistic view of\r\n      full-stack development to create usable, high-performing applications,\r\n      and learn to use these technologies effectively in a Ruby on Rails\r\n      environment.\r\n      </p>\n\n        <div class=\"price_line\">\n        <span class=\"price\">$80.00</span>\n\n          <form class=\"button_to\" method=\"post\" action=\"/line_items?product_id=2\" data-remote=\"true\"><input type=\"submit\" value=\"Add to Cart\" /><input type=\"hidden\" name=\"authenticity_token\" value=\"FCedsTsN/GG6cm0VhcmY7SdGjpRzCKuuSyxKJt/Kak1Xdv/gUFVU1UYXr8n7nm2cKgvjwS23zcBorzf5P5lieg==\" /></form>\n\n        </div>\n\n      </div>\n\n\n      <div class=\"entry\">\n\n        <img src=\"/assets/7apps-f67c3d908f537bac34a290206cc1db4c6f4611196c550e49ba836b796a2602bb.jpg\" alt=\"7apps\" />\n        <h3>Seven Mobile Apps in Seven Weeks</h3>\n\n        <p>\r\n      <em>Native Apps, Multiple Platforms</em>\r\n      Answer the question “Can we build this for ALL the devices?” with a\r\n      resounding YES. This book will help you get there with a real-world\r\n      introduction to seven platforms, whether you’re new to mobile or an\r\n      experienced developer needing to expand your options. Plus, you’ll find\r\n      out which cross-platform solution makes the most sense for your needs.\r\n      </p>\n\n        <div class=\"price_line\">\n        <span class=\"price\">$26.00</span>\n\n          <form class=\"button_to\" method=\"post\" action=\"/line_items?product_id=3\" data-remote=\"true\"><input type=\"submit\" value=\"Add to Cart\" /><input type=\"hidden\" name=\"authenticity_token\" value=\"faFaDWHEcOVsP5x1x8s+A3Zd6fpFbVsW4JZzdDgpNOA+8DhcCpzYUZBaXqm5nMtyexCErxvSPXjDFQ6r2Ho81w==\" /></form>\n\n        </div>\n\n      </div>\n\n\n      <div class=\"entry\">\n\n        <img src=\"/assets/adrpo-23a974519e0d4353c6906f82b40bd4cd98b09a2ce748825370c7aa59763f5ac7.jpg\" alt=\"Adrpo\" />\n        <h3>Ruby Performance Optimization</h3>\n\n        <p>\n      <em>Why Ruby Is Slow, and How to Fix It</em>\n      You don’t have to accept slow Ruby or Rails performance. In this\n      comprehensive guide to Ruby optimization, you’ll learn how to write\n      faster Ruby code—but that’s just the beginning. See exactly what makes\n      Ruby and Rails code slow, and how to fix it. Alex Dymo will guide you\n      through perils of memory and CPU optimization, profiling, measuring,\n      performance testing, garbage collection, and tuning. You’ll find that\n      all those “hard” things aren’t so difficult after all, and your code\n      will run orders of magnitude faster.\n      </p>\n\n        <div class=\"price_line\">\n        <span class=\"price\">$46.00</span>\n\n          <form class=\"button_to\" method=\"post\" action=\"/line_items?product_id=4\" data-remote=\"true\"><input type=\"submit\" value=\"Add to Cart\" /><input type=\"hidden\" name=\"authenticity_token\" value=\"tN4iplT2QTAi9zwvn9ZXkNHwKPJouOcXz+zr0Pnytuz3j0D3P67phN6S/vPhgaLh3L1FpzYHgXnsb5YPGaG+2w==\" /></form>\n\n        </div>\n\n      </div>\n\n"}
Redirected to http://localhost:3000/products/2
Completed 302 Found in 23ms (ActiveRecord: 1.8ms)

  **#assets/javascripts/channels/products.coffee**
  App.products = App.cable.subscriptions.create "ProductsChannel",
  connected: ->
    # Called when the subscription is ready for use on the server

  disconnected: ->
    # Called when the subscription has been terminated by the server

  received: (data) ->
    # Called when there's incoming data on the websocket for this channel
  $(".store #main").html(data.html)

 **#app/views/store/index.html.erb**
    <p id="notice"><%= notice %></p>

    <h1>Your Pragmatic Catalog</h1>

    <% cache @products do %>
      <% @products.each do |product| %>
        <% cache product do %>

          <div class="entry">

            <%= image_tag(product.image_url) %>
            <h3><%= product.title %></h3>

            <%= sanitize(product.description) %>

            <div class="price_line">
            <span class="price"><%= number_to_currency(product.price) %></span>

              <%= button_to 'Add to Cart', line_items_path(product_id: product.id), remote:true %>

            </div>

          </div>

        <% end %>
      <% end %>
    <% end %>

#app/channels/products_channel.rb
class ProductsChannel < ApplicationCable::Channel
  def subscribed
    # stream_from "some_channel"
    stream_from "products"
  end

  def unsubscribed
    # Any cleanup needed when channel is unsubscribed

  end
end

#application.html.erb
<!DOCTYPE html>
<html>
  <head>
    <title>Pragprog Books Online Store</title>

    <%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track': 'reload' %>
    <%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>
    <%= csrf_meta_tags %>
  </head>

  <body class='<%= controller.controller_name %>'>

    <div id="banner">

      <%= image_tag 'logo.svg', alt: 'The Pragmatic Bookshelf' %>
      <span class="title"><%= @page_title %></span>
    </div>

    <div id="columns">
      <div id="side">

        <div id="cart">
          <% if @cart %>
              <%= hidden_div_if(@cart.line_items.empty?, id: 'cart') do %>
                <%= render @cart %>
              <% end %>
          <% end %>

        </div>

        <ul>

          <li><a href="http://www...">Home</a></li>
          <li><a href="http://www.../faq">Questions</a></li>
          <li><a href="http://www.../news">News</a></li>
          <li><a href="http://www.../contact">Contact</a></li>

        </ul>

      </div>

      <div id="main">
        <%= yield %>
      </div>
    </div>

  </body>
</html>
</code>```

答:
In your received function you are trying to access an element that doesn't seem to exist (.store #main), since you don't have an element with the class store on the code you posted.

Try and change your code to say:

```<code>  received: (data) ->
    $("#main").html(data.html)
</code>```

As the #main element exists on the page.

Body:
I'm working through the ActionCable example within the book.  All of the code is added as described and I can see the ActionCable server log hit but the updating page never updates the cost of the item.  What am I missing?

The following log entry tells me that ActionCable is firing.  the code is below.

  Product Load (0.1ms)  SELECT "products".* FROM "products"
  Rendered store/index.html.erb (6.0ms)
[ActionCable] Broadcasting to products: {:html=>"

\n\n
Your Pragmatic Catalog
\n\n\n\n
\n\n        \n
Rails, Angular, Postgres, and Bootstrap
\n\n
\r\n      Powerful, Effective, and Efficient Full-Stack Web Development\r\n      As a Rails developer, you care about user experience and performance,\r\n      but you also want simple and maintainable code. Achieve all that by\r\n      embracing the full stack of web development, from styling with\r\n      Bootstrap, building an interactive user interface with AngularJS, to\r\n      storing data quickly and reliably in PostgreSQL. Take a holistic view of\r\n      full-stack development to create usable, high-performing applications,\r\n      and learn to use these technologies effectively in a Ruby on Rails\r\n      environment.\r\n
\n\n
\n        $80.00\n\n          <form class=\"button_to\" method=\"post\" action=\"/line_items?product_id=2\" data-remote=\"true\"><input type=\"submit\" value=\"Add to Cart\" /><input type=\"hidden\" name=\"authenticity_token\" value=\"FCedsTsN/GG6cm0VhcmY7SdGjpRzCKuuSyxKJt/Kak1Xdv/gUFVU1UYXr8n7nm2cKgvjwS23zcBorzf5P5lieg==\" /></form>\n\n
\n\n
\n\n\n
\n\n        \n
Seven Mobile Apps in Seven Weeks
\n\n
\r\n      Native Apps, Multiple Platforms\r\n      Answer the question “Can we build this for ALL the devices?” with a\r\n      resounding YES. This book will help you get there with a real-world\r\n      introduction to seven platforms, whether you’re new to mobile or an\r\n      experienced developer needing to expand your options. Plus, you’ll find\r\n      out which cross-platform solution makes the most sense for your needs.\r\n
\n\n
\n        $26.00\n\n          <form class=\"button_to\" method=\"post\" action=\"/line_items?product_id=3\" data-remote=\"true\"><input type=\"submit\" value=\"Add to Cart\" /><input type=\"hidden\" name=\"authenticity_token\" value=\"faFaDWHEcOVsP5x1x8s+A3Zd6fpFbVsW4JZzdDgpNOA+8DhcCpzYUZBaXqm5nMtyexCErxvSPXjDFQ6r2Ho81w==\" /></form>\n\n
\n\n
\n\n\n
\n\n        \n
Ruby Performance Optimization
\n\n
\n      Why Ruby Is Slow, and How to Fix It\n      You don’t have to accept slow Ruby or Rails performance. In this\n      comprehensive guide to Ruby optimization, you’ll learn how to write\n      faster Ruby code—but that’s just the beginning. See exactly what makes\n      Ruby and Rails code slow, and how to fix it. Alex Dymo will guide you\n      through perils of memory and CPU optimization, profiling, measuring,\n      performance testing, garbage collection, and tuning. You’ll find that\n      all those “hard” things aren’t so difficult after all, and your code\n      will run orders of magnitude faster.\n
\n\n
\n        $46.00\n\n          <form class=\"button_to\" method=\"post\" action=\"/line_items?product_id=4\" data-remote=\"true\"><input type=\"submit\" value=\"Add to Cart\" /><input type=\"hidden\" name=\"authenticity_token\" value=\"tN4iplT2QTAi9zwvn9ZXkNHwKPJouOcXz+zr0Pnytuz3j0D3P67phN6S/vPhgaLh3L1FpzYHgXnsb5YPGaG+2w==\" /></form>\n\n
\n\n
\n\n"}
Redirected to http://localhost:3000/products/2
Completed 302 Found in 23ms (ActiveRecord: 1.8ms)

  **#assets/javascripts/channels/products.coffee**
  App.products = App.cable.subscriptions.create "ProductsChannel",
  connected: ->
    # Called when the subscription is ready for use on the server

  disconnected: ->
    # Called when the subscription has been terminated by the server

  received: (data) ->
    # Called when there's incoming data on the websocket for this channel
  $(".store #main").html(data.html)

 **#app/views/store/index.html.erb**

<%= notice %>

Your Pragmatic Catalog

    <% cache @products do %>
      <% @products.each do |product| %>
        <% cache product do %>

            <%= image_tag(product.image_url) %>

<%= product.title %>

            <%= sanitize(product.description) %>

            <%= number_to_currency(product.price) %>

              <%= button_to 'Add to Cart', line_items_path(product_id: product.id), remote:true %>

        <% end %>
      <% end %>
    <% end %>

#app/channels/products_channel.rb
class ProductsChannel < ApplicationCable::Channel
  def subscribed
    # stream_from "some_channel"
    stream_from "products"
  end

  def unsubscribed
    # Any cleanup needed when channel is unsubscribed

  end
end

#application.html.erb
<!DOCTYPE html>

    <title>Pragprog Books Online Store</title>

    <%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track': 'reload' %>
    <%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>
    <%= csrf_meta_tags %>

  <body class='<%= controller.controller_name %>'>

      <%= image_tag 'logo.svg', alt: 'The Pragmatic Bookshelf' %>
      <%= @page_title %>

          <% if @cart %>
              <%= hidden_div_if(@cart.line_items.empty?, id: 'cart') do %>
                <%= render @cart %>
              <% end %>
          <% end %>

Home

Questions

News

Contact

        <%= yield %>

Body:
In your received function you are trying to access an element that doesn't seem to exist (.store #main), since you don't have an element with the class store on the code you posted.

Try and change your code to say:

  received: (data) ->
    $("#main").html(data.html)

As the #main element exists on the page.


问:
Generate ID's for text and calendar control in Jquery
I want to generate Id's for input type text  whenever I click on .add class. Currently Whenever I click on .add class it generates the id's with same name for each input control. So while adding data it does not work properly.

So how should I generate ID's for each text whenever I click on .add class. Please suggest.

Here is what is generates.

Generated HTML

$('.add').on('click', function() {
  var $tr = $(this).closest('tr');
  var $tr2 = $tr.clone(true, true);
  $tr2.find(".vendorName").children('label').remove();
  $tr2.find(".vendorFromDate").children('label').remove();
  $tr2.find(".vendorToDate").children('label').remove();
  $tr2.find(".vendorName").children().unwrap();
  $tr2.find(".vendorFromDate").children().unwrap();
  $tr2.find(".vendorToDate").children().unwrap();
  $tr2.insertAfter($tr);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<tr>
  <td>
    <div class="row noPadding vendorForm">
      <div class="vendorDaterow">
        <div class="vendorName" id="dvVendorNameData">
          <label>SP Vender Name</label><span><input type="text" name="nmVendorData" id="txtVendorName1" /></span>
        </div>
        <div class="vendorFromDate">
          <label>From Date</label><span class="datepicker"><input type="text" name="nmVendorData" id="spFromDate1" /><i class="fa fa-calendar" aria-hidden="true"></i></span>
        </div>
        <div class="vendorToDate">
          <label>To Date</label><span class="datepicker"><input type="text" name="nmVendorData" id="spToDate1" /><i class="fa fa-calendar" aria-hidden="true"></i></span>
        </div>
      </div>
      <div class="add">
        <i class="fa fa-plus" aria-hidden="true"></i>
      </div>
      <i class="max">(Maximum 5 Vendors)</i>

    </div>
  </td>
</tr></code>```

Please suggest how should I generate the dynamic ID.

答:
Check this

(function () {
  var toAddCloneCount = 2;

$('.add').on('click', function() {
  var $tr = $(this).closest('tr');
  var $tr2 = $tr.clone(true, true);
  $tr2.find(".vendorName").children('label').remove();
  $tr2.find(".add").children().remove();
  $tr2.find(".vendorFromDate").children('label').remove();
  $tr2.find(".vendorToDate").children('label').remove();
  $tr2.find('#txtVendorName').prop('id', 'txtVendorName' + toAddCloneCount);
  $tr2.find('#spFromDate1').prop('id', 'spFromDate' + toAddCloneCount);
  $tr2.find('#spToDate1').prop('id', 'spToDate' + toAddCloneCount++);
  $tr2.insertAfter($tr);
});
})();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.vendorName,.vendorFromDate,.vendorToDate{
width:33%;float:left;}</code>```

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"/>

                                            SP Vender Name@*Shri Kamalkanth Co.*@<input type="text" name="nmVendorData" id="txtVendorName" />

                                            From Date<input type="text" id="spFromDate1" />

                                            To Date<input type="text" id="spToDate1" />

                                    (Maximum 5 Vendors)

```

Body:
I want to generate Id's for input type text  whenever I click on .add class. Currently Whenever I click on .add class it generates the id's with same name for each input control. So while adding data it does not work properly.

So how should I generate ID's for each text whenever I click on .add class. Please suggest.

Here is what is generates.

Generated HTML

$('.add').on('click', function() {
  var $tr = $(this).closest('tr');
  var $tr2 = $tr.clone(true, true);
  $tr2.find(".vendorName").children('label').remove();
  $tr2.find(".vendorFromDate").children('label').remove();
  $tr2.find(".vendorToDate").children('label').remove();
  $tr2.find(".vendorName").children().unwrap();
  $tr2.find(".vendorFromDate").children().unwrap();
  $tr2.find(".vendorToDate").children().unwrap();
  $tr2.insertAfter($tr);
});

          SP Vender Name<input type="text" name="nmVendorData" id="txtVendorName1" />

          From Date<input type="text" name="nmVendorData" id="spFromDate1" />

          To Date<input type="text" name="nmVendorData" id="spToDate1" />

      (Maximum 5 Vendors)

Please suggest how should I generate the dynamic ID.

Body:
Check this

(function () {
  var toAddCloneCount = 2;

$('.add').on('click', function() {
  var $tr = $(this).closest('tr');
  var $tr2 = $tr.clone(true, true);
  $tr2.find(".vendorName").children('label').remove();
  $tr2.find(".add").children().remove();
  $tr2.find(".vendorFromDate").children('label').remove();
  $tr2.find(".vendorToDate").children('label').remove();
  $tr2.find('#txtVendorName').prop('id', 'txtVendorName' + toAddCloneCount);
  $tr2.find('#spFromDate1').prop('id', 'spFromDate' + toAddCloneCount);
  $tr2.find('#spToDate1').prop('id', 'spToDate' + toAddCloneCount++);
  $tr2.insertAfter($tr);
});
})();

.vendorName,.vendorFromDate,.vendorToDate{
width:33%;float:left;}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
                            <td>
                                <div class="row noPadding vendorForm">
                                    <div class="vendorDaterow">
                                        <div class="vendorName">
                                            <label>SP Vender Name</label><span>@*Shri Kamalkanth Co.*@<input type="text" name="nmVendorData" id="txtVendorName" /></span>
                                        </div>
                                        <div class="vendorFromDate">
                                            <label>From Date</label><span class="datepicker"><input type="text" id="spFromDate1" /><i class="fa fa-calendar" aria-hidden="true"></i></span>
                                        </div>
                                        <div class="vendorToDate">
                                            <label>To Date</label><span class="datepicker"><input type="text" id="spToDate1" /><i class="fa fa-calendar" aria-hidden="true"></i></span>
                                        </div>
                                    </div>
                                    <div class="add">
                                        <i class="fa fa-plus" aria-hidden="true"></i>
                                    </div>
                                    <i class="max">(Maximum 5 Vendors)</i>

                                </div>
                            </td>
                        </tr>
</table>


问:
Sending dynamic php page with mailgun
I am trying to send dynamic emails via the mailgun API in PHP but i'm not having any luck.

I can successfully send emails if i just send simple dynamic content. E.g.

```<code>$email = test@test.com;
$firstname = Tester;
$result = $mgClient->sendMessage($domain, array(
'from'    => 'Support Team <hello@xyz.com>',
'to'      => $email,
'subject' => 'Welcome to XYZ.com',
'html'    => "<html>Dear $firstname, this is a test.</html>"
), array(

));
</code>```

However i'd like to be able to pull content from a dynamic page E.g welcomeemail.php?userid=1. So i tried to use:

```<code>$html = file_get_contents(welcomeemail.php?userid=1
'html'   => $html
</code>```

However I get the following error "Warning: file_get_contents(welcomeemail.php?userid=1): failed to open stream: No such file or directory.

When I remove the ?userid=1, it works fine but obviously without the dynamic content.

Can you please provide any suggestions on how I can incorporate dynamic content into my emails?

答: You should put the full http path to welcomeemail.php. For an example file_get_contents('http://localhost/welcomeemail.php?userid=1'). When you don't put it like that the file_get_contents() looks for the file 'welcomeemail.php?userid=1' in the file system which is obviously doesn't exist.  </p>

Title: Sending dynamic php page with mailgun

Body:
I am trying to send dynamic emails via the mailgun API in PHP but i'm not having any luck.

I can successfully send emails if i just send simple dynamic content. E.g.

$email = test@test.com;
$firstname = Tester;
$result = $mgClient->sendMessage($domain, array(
'from'    => 'Support Team <hello@xyz.com>',
'to'      => $email,
'subject' => 'Welcome to XYZ.com',
'html'    => "Dear $firstname, this is a test."
), array(

));

However i'd like to be able to pull content from a dynamic page E.g welcomeemail.php?userid=1. So i tried to use:

$html = file_get_contents(welcomeemail.php?userid=1
'html'   => $html

However I get the following error "Warning: file_get_contents(welcomeemail.php?userid=1): failed to open stream: No such file or directory.

When I remove the ?userid=1, it works fine but obviously without the dynamic content.

Can you please provide any suggestions on how I can incorporate dynamic content into my emails?


问:
Operator precedence in C Definitions
Wikipedia claims that the [] operator precedes the * operator in evaluation.

Then, why does the following statement:

```<code>char *a[3];
</code>```

declare an array of 3 character pointers, rather than a pointer to an array of 3 characters as per the operator precedence?

答:
Here's the grammar for a declarator as taken from the standard (§ 6.7.5):

```
<i>declarator</i>:
    <i>pointer<sub>opt</sub> direct-declarator</i>

<i>direct-declarator</i>:
    <i>identifier</i>
    <code>(</code> <i>declarator</i> <code>)</code>
    <i>direct-declarator</i> <code>[</code> <i>type-qualifier-list<sub>opt</sub> assignment-expression<sub>opt</sub></i> <code>]</code>
    <i>direct-declarator</i> <code>[ static</code> <i>type-qualifier-list<sub>opt</sub> assignment-expression</i> <code>]</code>
    <i>direct-declarator</i> <code>[</code> <i>type-qualifier-list</i> <code>static</code> <i>assignment-expression</i> <code>]</code>
    <i>direct-declarator</i> <code>[</code> <i>type-qualifier-list<sub>opt</sub></i> <code>* ]</code>
    <i>direct-declarator</i> <code>(</code> <i>parameter-type-list</i> <code>)</code>
    <i>direct-declarator</i> <code>(</code> <i>identifier-list<sub>opt</sub></i> <code>)</code>

<i>pointer</i>:
    <code>*</code> <i>type-qualifier-list<sub>opt</sub></i>
    <code>*</code> <i>type-qualifier-list<sub>opt</sub> pointer</i>

<i>type-qualifier-list</i>:
    <i>type-qualifier</i>
    <i>type-qualifier-list type-qualifier</i>

<i>parameter-type-list</i>:
    <i>parameter-list</i>
    <i>parameter-list</i> <code>, ...</code>

<i>parameter-list</i>:
    <i>parameter-declaration</i>
    <i>parameter-list</i> <code>,</code> <i>parameter-declaration</i>

<i>parameter-declaration</i>:
    <i>declaration-specifiers declarator</i>
    <i>declaration-specifiers abstract-declarator<sub>opt</sub></i>

<i>identifier-list</i>:
    <i>identifier</i>
    <i>identifier-list</i> <code>,</code> <i>identifier</i>
```

As you can see, both [] and () bind to the declarator before *.  Take the declaration

```<code>int *a[N];
</code>```

The declarator is *a[N], which fits the pointeropt direct-declarator pattern above, and is thus parsed as *(a[N]), so a is an N-element array of pointer.

To sum up:

```<code>T *a[N]      -- declares an N-element array of pointer to T
T (*a)[N]    -- declares a pointer to an N-element array of T
T *f()       -- declares a function returning pointer to T
T (*f)()     -- declares a pointer to a function returning T
</code>```

Title: Operator precedence in C Definitions

Body:
Wikipedia claims that the [] operator precedes the * operator in evaluation.

Then, why does the following statement:

char *a[3];

declare an array of 3 character pointers, rather than a pointer to an array of 3 characters as per the operator precedence?

Body:
Here's the grammar for a declarator as taken from the standard (§ 6.7.5):

declarator:
    pointeropt direct-declarator

direct-declarator:
    identifier
    ( declarator )
    direct-declarator [ type-qualifier-listopt assignment-expressionopt ]
    direct-declarator [ static type-qualifier-listopt assignment-expression ]
    direct-declarator [ type-qualifier-list static assignment-expression ]
    direct-declarator [ type-qualifier-listopt * ]
    direct-declarator ( parameter-type-list )
    direct-declarator ( identifier-listopt )

pointer:
    * type-qualifier-listopt
    * type-qualifier-listopt pointer

type-qualifier-list:
    type-qualifier
    type-qualifier-list type-qualifier

parameter-type-list:
    parameter-list
    parameter-list , ...

parameter-list:
    parameter-declaration
    parameter-list , parameter-declaration

parameter-declaration:
    declaration-specifiers declarator
    declaration-specifiers abstract-declaratoropt

identifier-list:
    identifier
    identifier-list , identifier

As you can see, both [] and () bind to the declarator before *.  Take the declaration

int *a[N];

The declarator is *a[N], which fits the pointeropt direct-declarator pattern above, and is thus parsed as *(a[N]), so a is an N-element array of pointer.

To sum up:

T *a[N]      -- declares an N-element array of pointer to T
T (*a)[N]    -- declares a pointer to an N-element array of T
T *f()       -- declares a function returning pointer to T
T (*f)()     -- declares a pointer to a function returning T


问:
Ecto Simple Foreign Key
In my Phoenix app, I have a Contact table and an Address table. The contact schema is:

```<code>schema "contacts" do
    field :name, :string
    field :number, :string
    has_one :address, App.Address, on_delete: :nothing

    timestamps()
end
</code>```

The address schema is

```<code>schema "addresses" do
    field :name, :string
    field :lat, :decimal
    field :lng, :decimal

    timestamps()
end
</code>```

I just want to have address_id in contacts be selected via a dropdown of addresses filled from the database. However, phoenix is returning

```<code>`App.Address.contact_id` in `where` does not exist in the schema in query:

from a in App.Address,
  where: a.contact_id == ^9435,
  select: {a.contact_id, a}
</code>```

So it is trying to find the contact_id field in address, however I want address to belong to a contact or many contacts, but I don't want the contact_id field in the address table. How is this to be accomplished with ecto associations?

I am aware I can do this with an intermediary table that has an entry for each contact_id and address_id paired up, but I would rather avoid doing so because I think that adds a level of unnecessary complexity and abstraction.

EDIT: Thank you for the answer, I realized I just needed to think of it in the reverse just a few minutes after posting. When thinking of it as an address has many contacts and a contact has one address the relationships make sense. I was just stuck thinking that address belongs to a contact when that is not necessarily true.

答:
If a Contact can have only one Address and an Address can be in multiple Contacts and there's an address_id field in the contacts table, you need a belongs_to relationship in Contact and a has_many in Contact.

```<code>schema "contacts" do
  belongs_to :address, App.Address
  ...
end

schema "addresses" do
  has_many :contact, App.Contact
  ...
end
</code>```

Now you can get the address of a Contact like this:

```<code>contact = Repo.get(Contact, 1234) |> Repo.preload([:address])
IO.inspect contact.address.name
</code>```

Title: Ecto Simple Foreign Key

Body:
In my Phoenix app, I have a Contact table and an Address table. The contact schema is:

schema "contacts" do
    field :name, :string
    field :number, :string
    has_one :address, App.Address, on_delete: :nothing

    timestamps()
end

The address schema is

schema "addresses" do
    field :name, :string
    field :lat, :decimal
    field :lng, :decimal

    timestamps()
end

I just want to have address_id in contacts be selected via a dropdown of addresses filled from the database. However, phoenix is returning

`App.Address.contact_id` in `where` does not exist in the schema in query:

from a in App.Address,
  where: a.contact_id == ^9435,
  select: {a.contact_id, a}

So it is trying to find the contact_id field in address, however I want address to belong to a contact or many contacts, but I don't want the contact_id field in the address table. How is this to be accomplished with ecto associations?

I am aware I can do this with an intermediary table that has an entry for each contact_id and address_id paired up, but I would rather avoid doing so because I think that adds a level of unnecessary complexity and abstraction.

EDIT: Thank you for the answer, I realized I just needed to think of it in the reverse just a few minutes after posting. When thinking of it as an address has many contacts and a contact has one address the relationships make sense. I was just stuck thinking that address belongs to a contact when that is not necessarily true.

Body:
If a Contact can have only one Address and an Address can be in multiple Contacts and there's an address_id field in the contacts table, you need a belongs_to relationship in Contact and a has_many in Contact.

schema "contacts" do
  belongs_to :address, App.Address
  ...
end

schema "addresses" do
  has_many :contact, App.Contact
  ...
end

Now you can get the address of a Contact like this:

contact = Repo.get(Contact, 1234) |> Repo.preload([:address])
IO.inspect contact.address.name


问:
Pygame ship movement only Up & Down (left right is working)

This part is gamefunction.py file

```<code>import sys

import pygame

def check_keydown_events(event,ship):
    """Respond to the keypressess."""
    if event.key == pygame.K_RIGHT:
        ship.moving_right = True
    elif event.key == pygame.K_LEFT:
        ship.moving_left = True
    elif event.key == pygame.K_UP:
        ship.moving_up = True
    elif event.key == pygame.K_DOWN:
        ship.moving_down = True

def check_keyup_events(event, ship):
    """Respond to the keyreleases."""
    if event.key == pygame.K_RIGHT:
        ship.moving_right = False
    elif event.key == pygame.K_LEFT:
        ship.moving_left = False
    elif event.key == pygame.K_UP:
        ship.moving_up = False
    elif event.key == pygame.K_DOWN:
        ship.moving_down = False

def check_events(ship):
    """Respond to keypresses and mouse events."""
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()

        elif event.type == pygame.KEYDOWN:
            check_keydown_events(event,ship)
        elif event.type == pygame.KEYUP:
            check_keyup_events(event, ship)
</code>```

this is named ship.py

```<code>import pygame

class Ship():

    def __init__(self,ai_settings,screen):
        """Initialize the ship and set its starting position."""
        self.screen = screen
        self.ai_settings = ai_settings
        #Load the ship image and get its rect.
        self.image = pygame.image.load('images/ship.png')
        self.rect = self.image.get_rect()
        self.screen_rect = screen.get_rect()

        #Start each new ship at the bottom center of the screen.
        self.rect.centerx = self.screen_rect.centerx
        self.rect.bottom = self.screen_rect.bottom

        #Store a decimal value for the ship's center.
        self.center = float(self.rect.centerx)
        #Movement Flags
        self.moving_right = False
        self.moving_left = False
        self.moving_up = False
        self.moving_down = False

    def update(self):
        """Update the ship's position based on the movement flag."""
        #Update the ship's center value, not the rect
        if self.moving_right and self.rect.right<self.screen_rect.right:
            self.center += self.ai_settings.ship_speed_factor
        if self.moving_left and self.rect.left>0:
            self.center -= self.ai_settings.ship_speed_factor
        #Up-dwon motion added ***Please check the logic for 1200x800 screen***
        if self.moving_up and self.rect.top<self.screen_rect.top:
            self.center += self.ai_settings.ship_speed_factor
        if self.moving_down and self.rect.bottom>800:
            self.center -= self.ai_settings.ship_speed_factor

        #Update rect object from self.center.
        self.rect.centerx = self.center
</code>```

答:
Ship.py

```<code>.....
self.bottom = float(self.rect.bottom)
self.moving_up = False
self.moving_down = False

def update(self):
    .....
    # check if the ship is moving up and stop the ship to move up if
    # it's top edge position is less than
    # screen's top (top right corner is 0,0) position
    if self.moving_up and self.rect.top > self.screen_rect.top:
        self.bottom -= self.ai_settings.ship_speed_factor

    # check if the ship is moving down and stop the ship when it's
    # bottom position is greater than the screen bottom edge position.
    if self.moving_down and self.rect.bottom < self.screen_rect.bottom:
        self.bottom += self.ai_settings.ship_speed_factor

    self.rect.bottom = self.bottom
</code>```

game_function.py

```<code>def check_keydown_event(event, ship):
    """Respond to keypresses"""
    ....
    elif event.key == pygame.K_UP:
        ship.moving_up = True
    elif event.key == pygame.K_DOWN:
        ship.moving_down = True

def check_keyup_event(event, ship):
    ....
    elif event.key == pygame.K_UP:
        ship.moving_up = False
    elif event.key == pygame.K_DOWN:
        ship.moving_down = False
</code>```

Body:
This part is gamefunction.py file

import sys

import pygame

def check_keydown_events(event,ship):
    """Respond to the keypressess."""
    if event.key == pygame.K_RIGHT:
        ship.moving_right = True
    elif event.key == pygame.K_LEFT:
        ship.moving_left = True
    elif event.key == pygame.K_UP:
        ship.moving_up = True
    elif event.key == pygame.K_DOWN:
        ship.moving_down = True

def check_keyup_events(event, ship):
    """Respond to the keyreleases."""
    if event.key == pygame.K_RIGHT:
        ship.moving_right = False
    elif event.key == pygame.K_LEFT:
        ship.moving_left = False
    elif event.key == pygame.K_UP:
        ship.moving_up = False
    elif event.key == pygame.K_DOWN:
        ship.moving_down = False

def check_events(ship):
    """Respond to keypresses and mouse events."""
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()

        elif event.type == pygame.KEYDOWN:
            check_keydown_events(event,ship)
        elif event.type == pygame.KEYUP:
            check_keyup_events(event, ship)

this is named ship.py

import pygame

class Ship():

    def __init__(self,ai_settings,screen):
        """Initialize the ship and set its starting position."""
        self.screen = screen
        self.ai_settings = ai_settings
        #Load the ship image and get its rect.
        self.image = pygame.image.load('images/ship.png')
        self.rect = self.image.get_rect()
        self.screen_rect = screen.get_rect()

        #Start each new ship at the bottom center of the screen.
        self.rect.centerx = self.screen_rect.centerx
        self.rect.bottom = self.screen_rect.bottom

        #Store a decimal value for the ship's center.
        self.center = float(self.rect.centerx)
        #Movement Flags
        self.moving_right = False
        self.moving_left = False
        self.moving_up = False
        self.moving_down = False

    def update(self):
        """Update the ship's position based on the movement flag."""
        #Update the ship's center value, not the rect
        if self.moving_right and self.rect.right<self.screen_rect.right:
            self.center += self.ai_settings.ship_speed_factor
        if self.moving_left and self.rect.left>0:
            self.center -= self.ai_settings.ship_speed_factor
        #Up-dwon motion added ***Please check the logic for 1200x800 screen***
        if self.moving_up and self.rect.top<self.screen_rect.top:
            self.center += self.ai_settings.ship_speed_factor
        if self.moving_down and self.rect.bottom>800:
            self.center -= self.ai_settings.ship_speed_factor

        #Update rect object from self.center.
        self.rect.centerx = self.center

Body:
Ship.py

.....
self.bottom = float(self.rect.bottom)
self.moving_up = False
self.moving_down = False

def update(self):
    .....
    # check if the ship is moving up and stop the ship to move up if
    # it's top edge position is less than
    # screen's top (top right corner is 0,0) position
    if self.moving_up and self.rect.top > self.screen_rect.top:
        self.bottom -= self.ai_settings.ship_speed_factor

    # check if the ship is moving down and stop the ship when it's
    # bottom position is greater than the screen bottom edge position.
    if self.moving_down and self.rect.bottom < self.screen_rect.bottom:
        self.bottom += self.ai_settings.ship_speed_factor

    self.rect.bottom = self.bottom

game_function.py

def check_keydown_event(event, ship):
    """Respond to keypresses"""
    ....
    elif event.key == pygame.K_UP:
        ship.moving_up = True
    elif event.key == pygame.K_DOWN:
        ship.moving_down = True

def check_keyup_event(event, ship):
    ....
    elif event.key == pygame.K_UP:
        ship.moving_up = False
    elif event.key == pygame.K_DOWN:
        ship.moving_down = False


问:
ng-repeat values in single input with comma separated
I have list array.Inside that I have one nested array called types.
I am trying to show types.work inside an input field with comma separated.

This is what I have tried:

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

app.controller('MainCtrl', function($scope) {
 $scope.init = function(){
 $scope.list=[
   {
     "name":"john",
     "types":[
       {"work":"aa"},
       {"work":"bb"}
     ]
   }
 ];
      }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.11/angular.min.js"></script>

<div ng-app="app">
  <div ng-controller="MainCtrl" ng-init="init()">
   <input type="text" ng-model="list.name">
   <label ng-repeat="data in list.types">{{data.work}}{{$last ? '' : ', '}}</label>
  </div>
</div></code>```

Can anyone tell me that how to use ng-repeat values in single input?.

答:
use multiple ng-repeat to access the nested array.

```<code> <label ng-repeat="data in list">
      <label  ng-repeat="d in data.types">

        {{d.work}}
      </label>

</label>
</code>```

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

app.controller('MainCtrl', function($scope) {
 $scope.init = function(){
 $scope.list=[
   {
     "name":"john",
     "types":[
       {"work":"aa"},
       {"work":"bb"}
     ]
   }
 ];
 $scope.name = $scope.list[0].types.map((o) => o.work)
  $scope.name =  $scope.name.join(",")
 }

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.11/angular.min.js"></script>

<div ng-app="app">
  <div ng-controller="MainCtrl" ng-init="init()">
   <input type="text" ng-model="name">
   <label ng-repeat="data in list">
      <label  ng-repeat="d in data.types">

        {{d.work}}
      </label>

   </label>
  </div>
</div></code>```

Body:
I have list array.Inside that I have one nested array called types.
I am trying to show types.work inside an input field with comma separated.

This is what I have tried:

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

app.controller('MainCtrl', function($scope) {
 $scope.init = function(){
 $scope.list=[
   {
     "name":"john",
     "types":[
       {"work":"aa"},
       {"work":"bb"}
     ]
   }
 ];
      }
});

   <input type="text" ng-model="list.name">
   {{data.work}}{{$last ? '' : ', '}}

Can anyone tell me that how to use ng-repeat values in single input?.

Body:
use multiple ng-repeat to access the nested array.

 <label ng-repeat="data in list">
      <label  ng-repeat="d in data.types">

        {{d.work}}
      </label>

</label>

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

app.controller('MainCtrl', function($scope) {
 $scope.init = function(){
 $scope.list=[
   {
     "name":"john",
     "types":[
       {"work":"aa"},
       {"work":"bb"}
     ]
   }
 ];
 $scope.name = $scope.list[0].types.map((o) => o.work)
  $scope.name =  $scope.name.join(",")
 }

});

<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.11/angular.min.js"></script>

<div ng-app="app">
  <div ng-controller="MainCtrl" ng-init="init()">
   <input type="text" ng-model="name">
   <label ng-repeat="data in list">
      <label  ng-repeat="d in data.types">

        {{d.work}}
      </label>

   </label>
  </div>
</div>


问:
Typescript : Type 'Observable<{}>' is not assignable to type 'Observable'
I have a problem with Observable type, any idea?

```<code>import { PostModel } from '../model/postModel';
import { Subject } from 'rxjs/Subject';
import { Observable } from 'rxjs/Observable';
import * as _ from 'lodash';

class DataStore {

    private posts: PostModel[]  = [];

    private postListSubject = new Subject();

    public postsList$: Observable<PostModel[]> = this.postListSubject.asObservable();

    initializeLessonsList(newPost: PostModel[]) {
        this.posts = _.cloneDeep(newPost);
        this.broadcast();
    }

    addLesson(newPost: PostModel) {
        this.posts.push(_.cloneDeep(newPost));
        this.broadcast();
    }

    broadcast() {
        this.postListSubject.next(_.cloneDeep(this.posts));
    }
}

export const store = new DataStore();
</code>```

on the line public postsList$: Observable<PostModel[]> = this.postListSubject.asObservable(); I am getting this error

[ts] Type 'Observable<{}>' is not assignable to type
  'Observable'.   Type '{}' is not assignable to type
  'PostModel[]'.
      Property 'includes' is missing in type '{}'.

答:
Add type information to your postListSubject declaration to allow the TypeScript compiler to infer the correct type of the Observable that is returned by Subject.asObservable():

```<code>private postListSubject = new Subject<PostModel[]>();
</code>```

Body:
I have a problem with Observable type, any idea?

import { PostModel } from '../model/postModel';
import { Subject } from 'rxjs/Subject';
import { Observable } from 'rxjs/Observable';
import * as _ from 'lodash';

class DataStore {

    private posts: PostModel[]  = [];

    private postListSubject = new Subject();

    public postsList$: Observable<PostModel[]> = this.postListSubject.asObservable();

    initializeLessonsList(newPost: PostModel[]) {
        this.posts = _.cloneDeep(newPost);
        this.broadcast();
    }

    addLesson(newPost: PostModel) {
        this.posts.push(_.cloneDeep(newPost));
        this.broadcast();
    }

    broadcast() {
        this.postListSubject.next(_.cloneDeep(this.posts));
    }
}

export const store = new DataStore();

on the line public postsList$: Observable<PostModel[]> = this.postListSubject.asObservable(); I am getting this error

[ts] Type 'Observable<{}>' is not assignable to type
  'Observable'.   Type '{}' is not assignable to type
  'PostModel[]'.
      Property 'includes' is missing in type '{}'.

Body:
Add type information to your postListSubject declaration to allow the TypeScript compiler to infer the correct type of the Observable that is returned by Subject.asObservable():

private postListSubject = new Subject<PostModel[]>();