问:
Angular: Can't return value
I have API for getting information about one specific restaurant in the database, but I have to get it with a POST request. I successfully get restaurantID from auth.service and another API when the restaurant is logged in, But when I tried to log restaurant in console, I get undefined. Uniformly I don't have permission to show API here. The code:
Informacije component:

```<code>import { Component, OnInit } from '@angular/core';
import { AuthService } from '../services/auth.service';
import { RestaurantService } from '../services/restaurant.service';
import { Restaurant } from '../models/Restaurant';
import { LoggedRestaurant } from '../models/LoggedRestaurant';
import { Observable } from 'rxjs';

@Component({
  selector: 'app-informacije',
  templateUrl: './informacije.component.html',
  styleUrls: ['./informacije.component.scss']
})
export class InformacijeComponent implements OnInit {
  restaurant: Restaurant;
  loggedRestaurant: LoggedRestaurant;
  restaurantID = this.authService.currRestaurant[0].id;

  constructor(private restaurantService: RestaurantService, private authService: AuthService ) { }

  getRestaurant() {
    return this.restaurantService.getRestaurant(this.restaurantID).toPromise().then(data => {
      this.loggedRestaurant = data;
    });

 }

  async ngOnInit() {

    await this.restaurantService.getRestaurant(this.restaurantID).subscribe(
      data => {
      this.loggedRestaurant = data;
      console.log(this.loggedRestaurant)
      })

    this.restaurant = this.authService.currRestaurant[0];
    console.log(this.restaurant)
    console.log(this.loggedRestaurant)

    console.log(this.restaurantService.restaurantID)

  }
}

</code>```

restaurant.service

```<code>import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { Restaurant } from '../models/Restaurant';
import { LoggedRestaurant } from '../models/LoggedRestaurant';

import { AuthService } from './auth.service'

@Injectable({
  providedIn: 'root'
})
export class RestaurantService {

  private restaurantUrl = 'xxxxxx';

  public restaurant: Restaurant;
  public loggedRestaurant: LoggedRestaurant
  public restaurantID = this.authService.currRestaurant[0].id

  constructor(private http: HttpClient, private authService: AuthService) { }

  getRestaurant(ID): Observable<LoggedRestaurant> {

    console.log('ID je razmak' + this.restaurantID);

    return this.http.post<LoggedRestaurant>(this.restaurantUrl, ID);
  }

}
</code>```

auth.service

```<code>import { Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse, HttpHeaders, HttpParams } from '@angular/common/http';
import { throwError, Observable } from 'rxjs';
import { map, catchError } from 'rxjs/operators';

import { Restaurant } from '../models/Restaurant';

@Injectable({
  providedIn: 'root'
})
export class AuthService {

  loginUrl = 'xxxxx';
  errorData: {};

  constructor(private http: HttpClient) { }

  redirectUrl: string;

  login(email: string, password: string) {
    var postData = {email: email, password: password};
    return this.http.post<Restaurant>(this.loginUrl, postData)
    .pipe(map(restaurant => {
        if (restaurant) {
          localStorage.setItem('currentRestaurant', JSON.stringify(restaurant));
          return  restaurant;
        }
      }),
      catchError(this.handleError)
    );
  }

  isLoggedIn() {
    if (localStorage.getItem('currentRestaurant')) {
      return true;
    }
      return false;
  }

  getAuthorizationToken() {
    const currentRestaurant = JSON.parse(localStorage.getItem('currentRestaurant'));
    return currentRestaurant.token;
  }

  logout() {
    localStorage.removeItem('currentRestaurant');
  }

  private handleError(error: HttpErrorResponse) {
    if (error.error instanceof ErrorEvent) {

      // A client-side or network error occurred. Handle it accordingly.
      console.error('An error occurred:', error.error.message);
    } else {

      // The backend returned an unsuccessful response code.
      // The response body may contain clues as to what went wrong.
      console.error(`Backend returned code ${error.status}, ` + `body was: ${error.error}`);
    }

    // return an observable with a user-facing error message
    this.errorData = {
      errorTitle: 'Oops! Request for document failed',
      errorDesc: 'Something bad happened. Please try again later.'
    };
    return throwError(this.errorData);
  }

  currRestaurant: Restaurant = JSON.parse(localStorage.getItem('currentRestaurant'));
  currID = this. currRestaurant.id;
}
</code>```

答:
Being a post request, if you want to see the data you need to return the full response.

Add {observe: 'response'} to your request like so:

```<code>getRestaurant(ID): Observable<HttpResponse<LoggedRestaurant>> {

  console.log('ID je razmak' + this.restaurantID);
  return this.http.post<LoggedRestaurant>(this.restaurantUrl, ID, {observe:'response'});
}
</code>```

and retrieve it like so:

```<code>this.restaurantService.getRestaurant(this.restaurantID).subscribe(
  data => {
    this.loggedRestaurant = data.body;
    console.log(this.loggedRestaurant)
  })

</code>```

Let me know if that worked :)

Title: Angular: Can't return value

Body:
I have API for getting information about one specific restaurant in the database, but I have to get it with a POST request. I successfully get restaurantID from auth.service and another API when the restaurant is logged in, But when I tried to log restaurant in console, I get undefined. Uniformly I don't have permission to show API here. The code:
Informacije component:

import { Component, OnInit } from '@angular/core';
import { AuthService } from '../services/auth.service';
import { RestaurantService } from '../services/restaurant.service';
import { Restaurant } from '../models/Restaurant';
import { LoggedRestaurant } from '../models/LoggedRestaurant';
import { Observable } from 'rxjs';

@Component({
  selector: 'app-informacije',
  templateUrl: './informacije.component.html',
  styleUrls: ['./informacije.component.scss']
})
export class InformacijeComponent implements OnInit {
  restaurant: Restaurant;
  loggedRestaurant: LoggedRestaurant;
  restaurantID = this.authService.currRestaurant[0].id;

  constructor(private restaurantService: RestaurantService, private authService: AuthService ) { }

  getRestaurant() {
    return this.restaurantService.getRestaurant(this.restaurantID).toPromise().then(data => {
      this.loggedRestaurant = data;
    });

 }

  async ngOnInit() {

    await this.restaurantService.getRestaurant(this.restaurantID).subscribe(
      data => {
      this.loggedRestaurant = data;
      console.log(this.loggedRestaurant)
      })

    this.restaurant = this.authService.currRestaurant[0];
    console.log(this.restaurant)
    console.log(this.loggedRestaurant)

    console.log(this.restaurantService.restaurantID)

  }
}

restaurant.service

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { Restaurant } from '../models/Restaurant';
import { LoggedRestaurant } from '../models/LoggedRestaurant';

import { AuthService } from './auth.service'

@Injectable({
  providedIn: 'root'
})
export class RestaurantService {

  private restaurantUrl = 'xxxxxx';

  public restaurant: Restaurant;
  public loggedRestaurant: LoggedRestaurant
  public restaurantID = this.authService.currRestaurant[0].id

  constructor(private http: HttpClient, private authService: AuthService) { }

  getRestaurant(ID): Observable<LoggedRestaurant> {

    console.log('ID je razmak' + this.restaurantID);

    return this.http.post<LoggedRestaurant>(this.restaurantUrl, ID);
  }

}

auth.service

import { Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse, HttpHeaders, HttpParams } from '@angular/common/http';
import { throwError, Observable } from 'rxjs';
import { map, catchError } from 'rxjs/operators';

import { Restaurant } from '../models/Restaurant';

@Injectable({
  providedIn: 'root'
})
export class AuthService {

  loginUrl = 'xxxxx';
  errorData: {};

  constructor(private http: HttpClient) { }

  redirectUrl: string;

  login(email: string, password: string) {
    var postData = {email: email, password: password};
    return this.http.post<Restaurant>(this.loginUrl, postData)
    .pipe(map(restaurant => {
        if (restaurant) {
          localStorage.setItem('currentRestaurant', JSON.stringify(restaurant));
          return  restaurant;
        }
      }),
      catchError(this.handleError)
    );
  }

  isLoggedIn() {
    if (localStorage.getItem('currentRestaurant')) {
      return true;
    }
      return false;
  }

  getAuthorizationToken() {
    const currentRestaurant = JSON.parse(localStorage.getItem('currentRestaurant'));
    return currentRestaurant.token;
  }

  logout() {
    localStorage.removeItem('currentRestaurant');
  }

  private handleError(error: HttpErrorResponse) {
    if (error.error instanceof ErrorEvent) {

      // A client-side or network error occurred. Handle it accordingly.
      console.error('An error occurred:', error.error.message);
    } else {

      // The backend returned an unsuccessful response code.
      // The response body may contain clues as to what went wrong.
      console.error(`Backend returned code ${error.status}, ` + `body was: ${error.error}`);
    }

    // return an observable with a user-facing error message
    this.errorData = {
      errorTitle: 'Oops! Request for document failed',
      errorDesc: 'Something bad happened. Please try again later.'
    };
    return throwError(this.errorData);
  }

  currRestaurant: Restaurant = JSON.parse(localStorage.getItem('currentRestaurant'));
  currID = this. currRestaurant.id;
}

Body:
Being a post request, if you want to see the data you need to return the full response.

Add {observe: 'response'} to your request like so:

getRestaurant(ID): Observable<HttpResponse<LoggedRestaurant>> {

  console.log('ID je razmak' + this.restaurantID);
  return this.http.post<LoggedRestaurant>(this.restaurantUrl, ID, {observe:'response'});
}

and retrieve it like so:

this.restaurantService.getRestaurant(this.restaurantID).subscribe(
  data => {
    this.loggedRestaurant = data.body;
    console.log(this.loggedRestaurant)
  })

Let me know if that worked :)


来源: stackexchange

问:
Automating Eclipse tasks
I'm currently looking for ways to automate some tasks in Eclipse.

For instance, let's say I have a couple  of ant files that I'll want to run a couple of times per hour. Being able to assign a hot key to each one of them, so that I could easily run them without having to click, bring the context menu up and click again would bring joy into my life.

Other example would be build/run configurations. I have a couple of them on my project and I'd love to have a way of running each one of them with a different hot key configuration.

Moreover, the very nature of a project I'm currently working on involves a lot of experimentation and trying, so having to click and use my mouse a lot is definitely driving me insane. There are other similar things that I would like to get automated as well (for example, each time I do a commit I'd like to also run some command over my project's folder, etc).

Is there some tool for Eclipse(or outside it) that'll somehow allow me to automate these kinds of tasks? Would Vim for Eclipse help me anyhow?

After some years coding I feel like I have hit a stone wall. I came to the conclusion that I am losing way too much time with my mouse. Yes, I know that a lot of Eclipse actions have correspondent hot keys, but a lot of others don't. I want the ultimate solution !

答:
There are several solutions:

Use a console. Consoles allow to remember the last commands (on Unix, you can even search). So instead of mouse-fu, it's Alt-TabUpReturn

There was Eclipse Monkey to script Eclipse. Not sure if it still works but it might.

On Sourceforge is Practical Macro. No documentation that I could find, though.

EclipseShell might also work, not sure.

ContentLicense: CC BY-SA 3.0

Title: Automating Eclipse tasks


问:
Upload files with parameters from multipartformdata using alamofire 5 in ios swift
I am trying upload files with parameters (multipartformdata) but i can't do it with new version Alamofire 5, if you have some experience with Alamofire 5 please share it with me.</p>
```<code> func uploadPluckImage(imgData : Data, imageColumnName : String,  url:String,httpmethod:HTTPMethod,completionHandler: @escaping (NSDictionary?, String?) -> ()){
    let token = UserDefaults.standard.string(forKey: PrefKeys.loginToken) ?? ""
    let authorization = ["Authorization" : "Bearer \(token)"]
    let parameters: Parameters?
    parameters = [
        "garbageCollector": 0,
        "stuff_uuid": "2b4b750a-f4a6-4d61-84ce-7c42b5c030ee",
        "delete_file" : ""
    ]
    let headers : HTTPHeader?
    headers = ["Authorization" : "Bearer \(token)"]
    let imageURl = "http://68.183.152.132/api/v1/stuff/uploader"

    AF.upload(multipartFormData: { (multipart: MultipartFormData) in
        let imageData = self.firstImage.image?.jpegData(compressionQuality: 0.7)
            multipart.append(imageData, withName: "file", fileName: "file.png", mimeType: "image/png")

        for (key, value) in parameters!{
            multipart.append(value as! String).data(using: .utf8)!, withName: key)
        }
    },usingThreshold: UInt64.init(),
       to: imageURl,
       method: .post,
       headers: headers,
       encodingCompletion: { (result) in
        switch result {
        case .success(let upload, _, _):
            upload.uploadProgress(closure: { (progress) in
              print("Uploading")
            })
            break
        case .failure(let encodingError):
            print("err is \(encodingError)")
                break
            }
        })
}
</code>```

答:
This how I upload images and videos from a swift 5 app with Alamofire 5.

Images

```<code>    /**
     Send Image to server
     */

    func Post(imageOrVideo : UIImage?){

    let headers: HTTPHeaders = [
        /* "Authorization": "your_access_token",  in case you need authorization header */
        "Content-type": "multipart/form-data"
    ]

        AF.upload(
            multipartFormData: { multipartFormData in
                multipartFormData.append(imageOrVideo!.jpegData(compressionQuality: 0.5)!, withName: "upload_data" , fileName: "file.jpeg", mimeType: "image/jpeg")
        },
            to: "http://ip.here.--.--/new.php", method: .post , headers: headers)
            .response { resp in
                print(resp)

        }
}
</code>```

You can create a temporary resource and use the temporary url (good for videos):

```<code>/**
 Send video to server
 */
func PostVideoUrl(url : URL){

    let headers: HTTPHeaders = [
        "Content-type": "multipart/form-data"
    ]

    AF.upload(
        multipartFormData: { multipartFormData in
            multipartFormData.append(url, withName: "upload_data" , fileName: "movie.mp4", mimeType: "video/mp4")
    },
        to: "http://ip.here.--.--/newVideo.php", method: .post , headers: headers)
        .response { resp in
            print(resp)

    }

}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying upload files with parameters (multipartformdata) but i can't do it with new version Alamofire 5, if you have some experience with Alamofire 5 please share it with me.

 func uploadPluckImage(imgData : Data, imageColumnName : String,  url:String,httpmethod:HTTPMethod,completionHandler: @escaping (NSDictionary?, String?) -> ()){
    let token = UserDefaults.standard.string(forKey: PrefKeys.loginToken) ?? ""
    let authorization = ["Authorization" : "Bearer \(token)"]
    let parameters: Parameters?
    parameters = [
        "garbageCollector": 0,
        "stuff_uuid": "2b4b750a-f4a6-4d61-84ce-7c42b5c030ee",
        "delete_file" : ""
    ]
    let headers : HTTPHeader?
    headers = ["Authorization" : "Bearer \(token)"]
    let imageURl = "http://68.183.152.132/api/v1/stuff/uploader"

    AF.upload(multipartFormData: { (multipart: MultipartFormData) in
        let imageData = self.firstImage.image?.jpegData(compressionQuality: 0.7)
            multipart.append(imageData, withName: "file", fileName: "file.png", mimeType: "image/png")

        for (key, value) in parameters!{
            multipart.append(value as! String).data(using: .utf8)!, withName: key)
        }
    },usingThreshold: UInt64.init(),
       to: imageURl,
       method: .post,
       headers: headers,
       encodingCompletion: { (result) in
        switch result {
        case .success(let upload, _, _):
            upload.uploadProgress(closure: { (progress) in
              print("Uploading")
            })
            break
        case .failure(let encodingError):
            print("err is \(encodingError)")
                break
            }
        })
}

Body:
This how I upload images and videos from a swift 5 app with Alamofire 5.

Images

    /**
     Send Image to server
     */

    func Post(imageOrVideo : UIImage?){

    let headers: HTTPHeaders = [
        /* "Authorization": "your_access_token",  in case you need authorization header */
        "Content-type": "multipart/form-data"
    ]

        AF.upload(
            multipartFormData: { multipartFormData in
                multipartFormData.append(imageOrVideo!.jpegData(compressionQuality: 0.5)!, withName: "upload_data" , fileName: "file.jpeg", mimeType: "image/jpeg")
        },
            to: "http://ip.here.--.--/new.php", method: .post , headers: headers)
            .response { resp in
                print(resp)

        }
}

You can create a temporary resource and use the temporary url (good for videos):

/**
 Send video to server
 */
func PostVideoUrl(url : URL){

    let headers: HTTPHeaders = [
        "Content-type": "multipart/form-data"
    ]

    AF.upload(
        multipartFormData: { multipartFormData in
            multipartFormData.append(url, withName: "upload_data" , fileName: "movie.mp4", mimeType: "video/mp4")
    },
        to: "http://ip.here.--.--/newVideo.php", method: .post , headers: headers)
        .response { resp in
            print(resp)

    }

}


问:
How to check if all array values are blank in Javascript
I have an array like:

```<code>["", "", "", "1", "", ""]
</code>```

I want to alert when all the array values are blanks, i.e, when the array is like this:

```<code>["", "", "", "", "", ""]
</code>```

How can I achieve this.

答:
I implemented small function for checking empty array which will work in all browsers.

var list=["1", [], "", null, undefined, ""];
var listE=["", "", "","", "", "", ""];
var listE1=["", [], "", null, undefined, ""];

function isArrayEmpty(arr){
return arr.toString().replace(/,/g, '')=="";
}

alert(isArrayEmpty(list))
alert(isArrayEmpty(listE))
alert(isArrayEmpty(listE1))```

Body:
I have an array like:

["", "", "", "1", "", ""]

I want to alert when all the array values are blanks, i.e, when the array is like this:

["", "", "", "", "", ""]

How can I achieve this.


问:
How do I use if-else statement with python pandas dataframe isna() function?
I'm new to working with pandas dataframes and was trying to figure out a way to locate NaN values inside a cell of a dataframe. I'm using an if condition with isna() function.

My approach is that if the value is NaN, print "value empty" instead of returning a Boolean "True". This is my approach:

```<code>import pandas as pd

x= pd.read_csv("mdata_short.csv", header =[0])
print(x["retail_price"].iloc[12:13])
if x["retail_price"].iloc[12:13].isna() == True:
    print("value empty")
</code>```

I expected a "value empty output", but I'm getting an error saying:

"ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()."

I tried removing "== True" part in the IF statement, still getting the same error. I did a google search but couldn't find anything related to this issue. I don't understand where I'm going wrong.

Thank you in advance for your help.

答:
series.isna returns a series no matter you call it on whole series or a single item of series. It means your command compares a series to a single True values. Pandas doesn't want to guess how to compare, so it returns that error.

Try this:

```<code>if x["retail_price"].iloc[12:13].isna().values[0] == True:
    print('empty')
</code>```

Body:
I'm new to working with pandas dataframes and was trying to figure out a way to locate NaN values inside a cell of a dataframe. I'm using an if condition with isna() function.

My approach is that if the value is NaN, print "value empty" instead of returning a Boolean "True". This is my approach:

import pandas as pd

x= pd.read_csv("mdata_short.csv", header =[0])
print(x["retail_price"].iloc[12:13])
if x["retail_price"].iloc[12:13].isna() == True:
    print("value empty")

I expected a "value empty output", but I'm getting an error saying:

"ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()."

I tried removing "== True" part in the IF statement, still getting the same error. I did a google search but couldn't find anything related to this issue. I don't understand where I'm going wrong.

Thank you in advance for your help.

Body:
series.isna returns a series no matter you call it on whole series or a single item of series. It means your command compares a series to a single True values. Pandas doesn't want to guess how to compare, so it returns that error.

Try this:

if x["retail_price"].iloc[12:13].isna().values[0] == True:
    print('empty')


问:
How do you remove rows after changing the item in a JPA OneToOne relationship?
How do you get a OneToOne item to automatically remove with JPA/Hibernate?  I would expect simply setting the OneToOne item to be null in the class that contains would be smart enough to allow Hibernate to delete it.

Given a simple object, simplified:

```<code>@Entity
public class Container {
    private Item item;

    @OneToOne(cascade=CascadeType.ALL)
    public Item getItem() { return item; }

    public void setItem(Item newItem) { item = newItem; }
}
</code>```

When an Item is set on Container an Container is persisted with merge a row gets inserted.

```<code>Container container = new Container();
container.setItem(new Item());
container = entityManager.merge(container);
// Row count is 1
</code>```

But when the item is set null, or to another item, the old object still exists in the table.

```<code>container.setItem(null);
container = entityManager.merge(container);
// Row count is STILL 1, leaving orphaned rows.
</code>```

So, how do I remove these OneToOne orphans?

答:
As JPA 2.0 has been released for a very long time now, you could simply use:</p>

```<code>@OneToOne(cascade = CascadeType.ALL, orphanRemoval = true)
</code>```

OwnerDisplayName: Sheldon Young

ContentLicense: CC BY-SA 2.5

Body:
How do you get a OneToOne item to automatically remove with JPA/Hibernate?  I would expect simply setting the OneToOne item to be null in the class that contains would be smart enough to allow Hibernate to delete it.

Given a simple object, simplified:

@Entity
public class Container {
    private Item item;

    @OneToOne(cascade=CascadeType.ALL)
    public Item getItem() { return item; }

    public void setItem(Item newItem) { item = newItem; }
}

When an Item is set on Container an Container is persisted with merge a row gets inserted.

Container container = new Container();
container.setItem(new Item());
container = entityManager.merge(container);
// Row count is 1

But when the item is set null, or to another item, the old object still exists in the table.

container.setItem(null);
container = entityManager.merge(container);
// Row count is STILL 1, leaving orphaned rows.

So, how do I remove these OneToOne orphans?

Body:
As JPA 2.0 has been released for a very long time now, you could simply use:

@OneToOne(cascade = CascadeType.ALL, orphanRemoval = true)


问:
Why is Kudu node version not updating after setting is applied?
I've been trying to deploy an Angular Application to Azure App Service, the deploy fails and it gives the following log:

```<code>Command: "D:\home\site\deployments\tools\deploy.cmd"
Handling ASP.NET Core Web Application deployment.
  Restore completed in 862 ms for D:\home\site\repository\src\Bearbersys.ui\Bearbersys.ui.csproj.
Microsoft (R) Build Engine version 15.9.20+g88f5fadfbe for .NET Core
Copyright (C) Microsoft Corporation. All rights reserved.

  Restore completed in 418.94 ms for D:\home\site\repository\src\Bearbersys.ui\Bearbersys.ui.csproj.
  Bearbersys.ui -> D:\home\site\repository\src\Bearbersys.ui\bin\Release\netcoreapp2.2\Bearbersys.ui.dll
  Bearbersys.ui -> D:\home\site\repository\src\Bearbersys.ui\bin\Release\netcoreapp2.2\Bearbersys.ui.Views.dll
EXEC : npm ERR! error : Method Not Allowed [D:\home\site\repository\src\Bearbersys.ui\Bearbersys.ui.csproj]
  npm ERR!     at errorResponse (D:\Program Files (x86)\npm\1.4.28\node_modules\npm\lib\cache\add-named.js:260:10)
  npm ERR!     at D:\Program Files (x86)\npm\1.4.28\node_modules\npm\lib\cache\add-named.js:203:12
  npm ERR!     at saved (D:\Program Files (x86)\npm\1.4.28\node_modules\npm\node_modules\npm-registry-client\lib\get.js:167:7)
  npm ERR!     at Object.oncomplete (fs.js:108:15)
  npm ERR! If you need help, you may report this *entire* log,
  npm ERR! including the npm and node versions, at:
  npm ERR!     <http://github.com/npm/npm/issues>

  npm ERR! System Windows_NT 6.2.9200
  npm ERR! command "node" "D:\\Program Files (x86)\\npm\\1.4.28\\node_modules\\npm\\bin\\npm-cli.js" "install"
  npm ERR! cwd D:\home\site\repository\src\Bearbersys.ui\ClientApp
  npm ERR! node -v v0.10.40
  npm ERR! npm -v 1.4.28
  npm ERR! code E405
D:\home\site\repository\src\Bearbersys.ui\Bearbersys.ui.csproj(39,5): error MSB3073: The command "npm install" exited with code 1.
Failed exitCode=1, command=dotnet publish "D:\home\site\repository\src\Bearbersys.ui\Bearbersys.ui.csproj" --output "D:\local\Temp\8d6e13963485ed1" --configuration Release
An error has occurred during web site deployment.
\r\nD:\Program Files (x86)\SiteExtensions\Kudu\81.10329.3844\bin\Scripts\starter.cmd "D:\home\site\deployments\tools\deploy.cmd"
</code>```

After some research I've found that this has something to do with the node package in my App Service, thus I've tried to add the following Application Setting to it:

```<code>[
  {
    "name": "WEBSITE_NODE_DEFAULT_VERSION",
    "value": "10.15.3",
    "slotSetting": false
  }
]
</code>```

10.15.3 is the current node version and the same version installed in my computer when I created the Angular App, even though the setting is succefully applied the error persists after redeploying. I've also noticed that the node version showed by the log hasn't changed.

```<code>  npm ERR! node -v v0.10.40
  npm ERR! npm -v 1.4.28
</code>```

What am I possibly doing wrong?

答:
For nodejs release schedule, please refer to: https://github.com/nodejs/Release

Find current nodejs versions available in Azure Windows WebApps, navigate to this link:

```<code>https://<yourwebappname>.scm.azurewebsites.net/api/diagnostics/runtime
</code>```

You can only use the versions available in this list.

New versions are added regularly, so please check for newer versions using the /api/diagnostics/runtime url above.

Body:
I've been trying to deploy an Angular Application to Azure App Service, the deploy fails and it gives the following log:

Command: "D:\home\site\deployments\tools\deploy.cmd"
Handling ASP.NET Core Web Application deployment.
  Restore completed in 862 ms for D:\home\site\repository\src\Bearbersys.ui\Bearbersys.ui.csproj.
Microsoft (R) Build Engine version 15.9.20+g88f5fadfbe for .NET Core
Copyright (C) Microsoft Corporation. All rights reserved.

  Restore completed in 418.94 ms for D:\home\site\repository\src\Bearbersys.ui\Bearbersys.ui.csproj.
  Bearbersys.ui -> D:\home\site\repository\src\Bearbersys.ui\bin\Release\netcoreapp2.2\Bearbersys.ui.dll
  Bearbersys.ui -> D:\home\site\repository\src\Bearbersys.ui\bin\Release\netcoreapp2.2\Bearbersys.ui.Views.dll
EXEC : npm ERR! error : Method Not Allowed [D:\home\site\repository\src\Bearbersys.ui\Bearbersys.ui.csproj]
  npm ERR!     at errorResponse (D:\Program Files (x86)\npm\1.4.28\node_modules\npm\lib\cache\add-named.js:260:10)
  npm ERR!     at D:\Program Files (x86)\npm\1.4.28\node_modules\npm\lib\cache\add-named.js:203:12
  npm ERR!     at saved (D:\Program Files (x86)\npm\1.4.28\node_modules\npm\node_modules\npm-registry-client\lib\get.js:167:7)
  npm ERR!     at Object.oncomplete (fs.js:108:15)
  npm ERR! If you need help, you may report this *entire* log,
  npm ERR! including the npm and node versions, at:
  npm ERR!     <http://github.com/npm/npm/issues>

  npm ERR! System Windows_NT 6.2.9200
  npm ERR! command "node" "D:\\Program Files (x86)\\npm\\1.4.28\\node_modules\\npm\\bin\\npm-cli.js" "install"
  npm ERR! cwd D:\home\site\repository\src\Bearbersys.ui\ClientApp
  npm ERR! node -v v0.10.40
  npm ERR! npm -v 1.4.28
  npm ERR! code E405
D:\home\site\repository\src\Bearbersys.ui\Bearbersys.ui.csproj(39,5): error MSB3073: The command "npm install" exited with code 1.
Failed exitCode=1, command=dotnet publish "D:\home\site\repository\src\Bearbersys.ui\Bearbersys.ui.csproj" --output "D:\local\Temp\8d6e13963485ed1" --configuration Release
An error has occurred during web site deployment.
\r\nD:\Program Files (x86)\SiteExtensions\Kudu\81.10329.3844\bin\Scripts\starter.cmd "D:\home\site\deployments\tools\deploy.cmd"

After some research I've found that this has something to do with the node package in my App Service, thus I've tried to add the following Application Setting to it:

[
  {
    "name": "WEBSITE_NODE_DEFAULT_VERSION",
    "value": "10.15.3",
    "slotSetting": false
  }
]

10.15.3 is the current node version and the same version installed in my computer when I created the Angular App, even though the setting is succefully applied the error persists after redeploying. I've also noticed that the node version showed by the log hasn't changed.

  npm ERR! node -v v0.10.40
  npm ERR! npm -v 1.4.28

What am I possibly doing wrong?

Body:
For nodejs release schedule, please refer to: https://github.com/nodejs/Release

Find current nodejs versions available in Azure Windows WebApps, navigate to this link:

https://<yourwebappname>.scm.azurewebsites.net/api/diagnostics/runtime

You can only use the versions available in this list.

New versions are added regularly, so please check for newer versions using the /api/diagnostics/runtime url above.


问:
Update paypal billing plan (payment_definitions)
I want to change amount of a Billing Plan but I'm getting an error when trying to do that.
It's possible to change the terms of the Plan (payment_definitions) if the Plan has already Agreements associated with it?

Request:

```<code>curl -v -k -X PATCH 'https://api.sandbox.paypal.com/v1/payments/billing-plans/[plan id]' \
-H "Content-Type: application/json" \
-H "Authorization: Bearer <Access-Token>" \
-d '[
    {
        "path": "/payment_definitions/[payment_definitions_id]/amount",
        "value": {
            "currency": "EUR",
            "value" : "10"
        },
        "op": "replace"
    }
]'
</code>```

Response:

```<code>{
   "name":"BUSINESS_VALIDATION_ERROR",
   "details":[
      {
         "field":"validation_error",
         "issue":"Invalid Path provided."
      }
   ],
   "message":"Validation Error.",
   "information_link":"https://developer.paypal.com/webapps/developer/docs/api/#BUSINESS_VALIDATION_ERROR",
   "debug_id":"183e87c07085e"
}
</code>```

答:
Recently PayPal opened new API for subscription payment. Previous APIs for billing plan and billing agreement is deprecated now as you can see the notice in this page:

https://developer.paypal.com/docs/api/payments.billing-agreements/v1/

This new API supports upgrading and downgrading of user plans or change (for example) the license quantity.

https://developer.paypal.com/docs/subscriptions/

Hope this helps.

Body:
I want to change amount of a Billing Plan but I'm getting an error when trying to do that.
It's possible to change the terms of the Plan (payment_definitions) if the Plan has already Agreements associated with it?

Request:

curl -v -k -X PATCH 'https://api.sandbox.paypal.com/v1/payments/billing-plans/[plan id]' \
-H "Content-Type: application/json" \
-H "Authorization: Bearer <Access-Token>" \
-d '[
    {
        "path": "/payment_definitions/[payment_definitions_id]/amount",
        "value": {
            "currency": "EUR",
            "value" : "10"
        },
        "op": "replace"
    }
]'

Response:

{
   "name":"BUSINESS_VALIDATION_ERROR",
   "details":[
      {
         "field":"validation_error",
         "issue":"Invalid Path provided."
      }
   ],
   "message":"Validation Error.",
   "information_link":"https://developer.paypal.com/webapps/developer/docs/api/#BUSINESS_VALIDATION_ERROR",
   "debug_id":"183e87c07085e"
}


问:
Rails meta programming and performance
Rails conventions force framework and gem writers to make extensive use of reflection/meta programming. I've always assumed meta programming to be less efficient, and with the trend of using an ever growing number of gems, the question is - whats the PERFORMANCE impact? </p>

答:
Really depend what kind of metaprogramming. Some are no impact performance during the runtime. Just a little slow in starting.

Do benchmark on your case and see what kind of impact there are.

Title: Rails meta programming and performance


问:
Debugging AWS Lambda node.js ES6
I am trying to debug an AWS Lambda using lambda-local but the problem is that it doesn't recognize imports and exports in node.js.

Is there a workaround other than back-refactoring my entire API to requires?

答:
Imports and exports are not yet supported in Node.

You have two options:
1. Change your imports to use require. Or,
2. Use babel to transpile your code before deploying to Lambda.

If you use serverless-framework, the serverless-webpack plugin will be of big help to you.

Title: Debugging AWS Lambda node.js ES6


问:
How to achieve 2 way data binding on a div's innerhtml property using ngModel?
In my angular component ts file I have a model, with a property whose value is html formatted text.
The text is displayed in the UI using inner html property of a div in my component’s .html file.
The div is made editable by setting the editable property .

Code snippet :

```<code><div id="requestBody" contenteditable="true"
*ngIf="selectedReqTab==='reqBody'" [innerHTML]="formatJson(requestBody)"></div>
</code>```

Here formatJson returns the html formatted JSON text.

The issue :

The changes made in the text are not getting reflected in the corresponding model, even if we have 2 way data binding using ngModel.

```<code><div id="requestBody" contenteditable="true"
*ngIf="selectedReqTab==='reqBody'" [(ngModel)]=”requestBody”
[innerHTML]="formatJson(requestBody)"></div>
</code>```

What am I doing wrong here ? could you please suggest.

答:
contenteditable isn't an input, and two way binding works on inputs.

You have to update your model through input events, as shown here

```<code><p (input)="updateModel(model.innerText)" #model contenteditable>{{ name }}</p>
</code>```

Body:
In my angular component ts file I have a model, with a property whose value is html formatted text.
The text is displayed in the UI using inner html property of a div in my component’s .html file.
The div is made editable by setting the editable property .

Code snippet :

Here formatJson returns the html formatted JSON text.

The issue :

The changes made in the text are not getting reflected in the corresponding model, even if we have 2 way data binding using ngModel.

What am I doing wrong here ? could you please suggest.

Body:
contenteditable isn't an input, and two way binding works on inputs.

You have to update your model through input events, as shown here

<p (input)="updateModel(model.innerText)" #model contenteditable>{{ name }}</p>


问:
How to fix this code output to be like homework sample
I have homework to code calculator and the result must be the only integer
but the problem is it has space between two results I want 4, 2 but it has shown 4 ,  2

```<code>"""Plus Minus Connected"""
def main():
    fnumber = float(input())
    snumber = float(input())
    print(int(fnumber + snumber), ", ", int(fnumber - snumber))
main()
</code>```

example 2,2.5 output = 4 ,  0
but i want output = 4, 0
how to fix it

答:
try below, </p>

```<code>print(str(int(fnumber) + int(snumber))+", "+str(int(fnumber) - int(snumber)))
</code>```

Body:
I have homework to code calculator and the result must be the only integer
but the problem is it has space between two results I want 4, 2 but it has shown 4 ,  2

"""Plus Minus Connected"""
def main():
    fnumber = float(input())
    snumber = float(input())
    print(int(fnumber + snumber), ", ", int(fnumber - snumber))
main()

example 2,2.5 output = 4 ,  0
but i want output = 4, 0
how to fix it

Body:
try below,

print(str(int(fnumber) + int(snumber))+", "+str(int(fnumber) - int(snumber)))


问:
Windows Registry settings corresponding to PowerCfg.exe /setacvalueindex
In my powershell script, I use

```<code>powercfg /setacvalueindex 381b4222-f694-41f0-9685-ff5bb260df2e 238c9fa8-0aad-41ed-83f4-97be242c8f20 29f6c1db-86da-48c5-9fdb-f2b67b1f44da 0
</code>```

I wanted to later verify if the above value has been set or not.
How do i verify this ?

I couldn't find any GET version of this SET command-option, like GETacvalueIndex ?

or
is there any registry settings that gets set when we do this, so that I can verify it in windows registry ?

答:
Maybe we can use PowerReadACValue
（https://learn.microsoft.com/en-us/windows/desktop/api/powersetting/nf-powersetting-powerreadacvalue）

For example
(http://www.reza-aghaei.com/how-to-get-value-of-advanced-power-settings/)

```<code>[DllImport("powrprof.dll")]
static extern uint PowerGetActiveScheme(
    IntPtr UserRootPowerKey,
    ref IntPtr ActivePolicyGuid);
[DllImport("powrprof.dll")]
static extern uint PowerReadACValue(
    IntPtr RootPowerKey,
    ref Guid SchemeGuid,
    ref Guid SubGroupOfPowerSettingGuid,
    ref Guid PowerSettingGuid,
    ref int Type,
    ref int Buffer,
    ref uint BufferSize);

public static void Foo()
{
    var activePolicyGuidPTR = IntPtr.Zero;
    PowerGetActiveScheme(IntPtr.Zero, ref activePolicyGuidPTR);

    var activePolicyGuid = Marshal.PtrToStructure<Guid>(activePolicyGuidPTR);
    var type = 0;
    var value = 0;
    var valueSize = 4u;
    PowerReadACValue(IntPtr.Zero, ref activePolicyGuid,
        ref GUID_SLEEP_SUBGROUP, ref GUID_STANDBY_TIMEOUT,
        ref type, ref value, ref valueSize);

    var message = $"Sleep after {value} seconds.";
}
</code>```

Body:
In my powershell script, I use

powercfg /setacvalueindex 381b4222-f694-41f0-9685-ff5bb260df2e 238c9fa8-0aad-41ed-83f4-97be242c8f20 29f6c1db-86da-48c5-9fdb-f2b67b1f44da 0

I wanted to later verify if the above value has been set or not.
How do i verify this ?

I couldn't find any GET version of this SET command-option, like GETacvalueIndex ?

or
is there any registry settings that gets set when we do this, so that I can verify it in windows registry ?

Body:
Maybe we can use PowerReadACValue
（https://learn.microsoft.com/en-us/windows/desktop/api/powersetting/nf-powersetting-powerreadacvalue）

For example
(http://www.reza-aghaei.com/how-to-get-value-of-advanced-power-settings/)

[DllImport("powrprof.dll")]
static extern uint PowerGetActiveScheme(
    IntPtr UserRootPowerKey,
    ref IntPtr ActivePolicyGuid);
[DllImport("powrprof.dll")]
static extern uint PowerReadACValue(
    IntPtr RootPowerKey,
    ref Guid SchemeGuid,
    ref Guid SubGroupOfPowerSettingGuid,
    ref Guid PowerSettingGuid,
    ref int Type,
    ref int Buffer,
    ref uint BufferSize);

public static void Foo()
{
    var activePolicyGuidPTR = IntPtr.Zero;
    PowerGetActiveScheme(IntPtr.Zero, ref activePolicyGuidPTR);

    var activePolicyGuid = Marshal.PtrToStructure<Guid>(activePolicyGuidPTR);
    var type = 0;
    var value = 0;
    var valueSize = 4u;
    PowerReadACValue(IntPtr.Zero, ref activePolicyGuid,
        ref GUID_SLEEP_SUBGROUP, ref GUID_STANDBY_TIMEOUT,
        ref type, ref value, ref valueSize);

    var message = $"Sleep after {value} seconds.";
}


问:
ImportError: No module named '_curses' when trying to import blessings
I am trying to run this:

```<code>from blessings import Terminal

t = Terminal()

print (t.bold('Hi there!'))
print (t.bold_red_on_bright_green('It hurts my eyes!'))

with t.location(0, t.height - 1):
    print ('This is at the bottom.')
</code>```

Which is the first example here: https://pypi.python.org/pypi/blessings.

However, I get this error:

```<code>Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Users\�����\AppData\Local\Programs\Python\Python35-     32\lib\site-packages\blessings\__init__.py", line 5, in <module>
    import curses
  File "C:\Users\�����\AppData\Local\Programs\Python\Python35-32\lib\curses\__init__.py", line 13, in <module>
    from _curses import *
ImportError: No module named '_curses'
</code>```

My system is win10 x64.

答:
First Install curses using pip like this
Open Command Prompt

type "pip install windows-curses"(This Only works if pip is installed in environmental variables)

If running curses doesn't work using Pycharm, Try other Interpreters Apps like Atom, Visual Studios, and if that does not work, Install Python in Environmental Variables(Links will be at the bottom). Then Launch CMD or Command Prompt and type "python (the root of .py file)"
(eg. python C:\Users\user\Plane.py) and then press enter.

Link for installing Python in Environmental Variables - https://www.youtube.com/watch?v=1jyOHCTgWpg

Body:
I am trying to run this:

from blessings import Terminal

t = Terminal()

print (t.bold('Hi there!'))
print (t.bold_red_on_bright_green('It hurts my eyes!'))

with t.location(0, t.height - 1):
    print ('This is at the bottom.')

Which is the first example here: https://pypi.python.org/pypi/blessings.

However, I get this error:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Users\�����\AppData\Local\Programs\Python\Python35-     32\lib\site-packages\blessings\__init__.py", line 5, in <module>
    import curses
  File "C:\Users\�����\AppData\Local\Programs\Python\Python35-32\lib\curses\__init__.py", line 13, in <module>
    from _curses import *
ImportError: No module named '_curses'

My system is win10 x64.


问:
KeyEvent handling in android?
I want to programattically handle the ENTER key in android.
Is there any way to achieve this?
Please Help!!

Thanks in advance

答:
You need to carefully override the following function:</p>

```<code>@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {

    switch (keyCode) {
        case KeyEvent.KEYCODE_ENTER:
        {
            //your Action code
            return true;
        }
    }
    return super.onKeyDown(keyCode, event);
}
</code>```

Title: KeyEvent handling in android?

Body:
You need to carefully override the following function:

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {

    switch (keyCode) {
        case KeyEvent.KEYCODE_ENTER:
        {
            //your Action code
            return true;
        }
    }
    return super.onKeyDown(keyCode, event);
}


问:
How can I alter this column so Pandas will recognize it?
I'm working with a csv that lists citations issued by a local city to residents who violated a homesharing law. One of the columns has the addresses of the violators. I added another column with the census tracts that those addresses are located in, but pandas is not recognizing it for some reason.

For example, one of the census tracts that appears multiple times in the census_tract column is 7002.00. But when I enter

```<code>citations[citations.census_tract == '7002.00']
</code>```

All I get are the column headers with 0 rows.

But when I enter:

```<code>citations.census_tract
</code>```

I get an accurate list of the census tracts in the census_tract column

What should I do to the column so pandas will read it when I try to get an output == to a specific census tract?

答:
you are trying to filter a float value but filter is a string in your input,

change:

citations[citations.census_tract == '7002.00']

to :

```<code>citations[citations.census_tract == 7002.00]
</code>```

Another method as suggested by @jezrael using np.isclose():

```<code>np.isclose(citations.census_tract,7002.00)
</code>```

This will return a array of boolean based on condition matches.

Body:
I'm working with a csv that lists citations issued by a local city to residents who violated a homesharing law. One of the columns has the addresses of the violators. I added another column with the census tracts that those addresses are located in, but pandas is not recognizing it for some reason.

For example, one of the census tracts that appears multiple times in the census_tract column is 7002.00. But when I enter

citations[citations.census_tract == '7002.00']

All I get are the column headers with 0 rows.

But when I enter:

citations.census_tract

I get an accurate list of the census tracts in the census_tract column

What should I do to the column so pandas will read it when I try to get an output == to a specific census tract?

Body:
you are trying to filter a float value but filter is a string in your input,

change:

citations[citations.census_tract == '7002.00']

to :

citations[citations.census_tract == 7002.00]

Another method as suggested by @jezrael using np.isclose():

np.isclose(citations.census_tract,7002.00)

This will return a array of boolean based on condition matches.


问:
Is it possible to declare reference variables in for or while loop?
I wrote a short code that declares 6 reference variables from a class named 'ChosenCompanies' to practice classes and constructors in Java.

It is the following:

```<code>public static void main(String[] args) {

    String[] FinalCompaniesName = new String[6];

    ChosenCompanies com1 = new ChosenCompanies();
    ChosenCompanies com2 = new ChosenCompanies();
    ChosenCompanies com3 = new ChosenCompanies();
    ChosenCompanies com4 = new ChosenCompanies();
    ChosenCompanies com5 = new ChosenCompanies();
    ChosenCompanies com6 = new ChosenCompanies();

    Scanner scanner = new Scanner(System.in);
    int choice;
    int count = 1;
    while(count <= 2) {
        switch(count) {
        case 1:
            System.out.println("Choose one:");
            System.out.println("1. " + com1.name);
            System.out.println("2. " + com2.name);
            System.out.println("3. " + com3.name);
            choice = scanner.nextInt();
            switch(choice) {
            case 1:
                FinalCompaniesName[0] = com1.name;
                break;
            case 2:
                FinalCompaniesName[0] = com2.name;
                break;
            case 3:
                FinalCompaniesName[0] = com3.name;
                break;
            }
        break;
        case 2:
            System.out.println("Choose one:");
            System.out.println("1. " + com4.name);
            System.out.println("2. " + com5.name);
            System.out.println("3. " + com6.name);
            choice = scanner.nextInt();
            switch(choice) {
            case 1:
                FinalCompaniesName[1] = com4.name;
                break;
            case 2:
                FinalCompaniesName[1] = com5.name;
                break;
            case 3:
                FinalCompaniesName[1] = com6.name;
                break;
            }
            break;
        }
        count++;
    }
        System.out.println("You have chosen: "
 + FinalCompaniesName[0] + ", " + FinalCompaniesName[1]);

}
</code>```

As you can see from the above code, these two parts are almost the same except for the names of reference variables(com1, com2, com3, com4...):

part 1:

        switch(count) {
        case 1:
            System.out.println("Choose one:");
            System.out.println("1. " + com1.name);
            System.out.println("2. " + com2.name);
            System.out.println("3. " + com3.name);
            choice = scanner.nextInt();
            switch(choice) {
            case 1:
                FinalCompaniesName[0] = com1.name;
                break;
            case 2:
                FinalCompaniesName[0] = com2.name;
                break;
            case 3:
                FinalCompaniesName[0] = com3.name;
                break;
            }
         break;
```

<p>part 2:</p>

```        case 2:
            System.out.println("Choose one:");
            System.out.println("1. " + com4.name);
            System.out.println("2. " + com5.name);
            System.out.println("3. " + com6.name);
            choice = scanner.nextInt();
            switch(choice) {
            case 1:
                FinalCompaniesName[1] = com4.name;
                break;
            case 2:
                FinalCompaniesName[1] = com5.name;
                break;
            case 3:
                FinalCompaniesName[1] = com6.name;
                break;
                }
            break;
        }
```

I am wondering if I can minimize the amount of the code above by using a for or while loop, since the name of the reference variables are increased by 1, like integer 'i' in a common for statement.

In short, is it possible to declare reference variables by using loop?

答:
It is not possible in Java to create dynamic variables (but with reflections, see here)

You can create an array and use the i as index like chosenCompanies[i].

Otherwise you can use lists or maps.

Edit:

That would e.g. look like this. Apart from the sence of the code, this example shows only how you would use an array:

```<code>    String[] choosenCompanieNames = new String[2]; // you only store two values, not 6 values

    //lets store the values to chose in arrays
    String[] possibleCompanieNames = new String[6]; // 6 possible values to choose (com1 - com6)
    possibleCompanieNames[0] = "com1";
    possibleCompanieNames[1] = "com2";
    possibleCompanieNames[2] = "com3";
    possibleCompanieNames[3] = "com4";
    possibleCompanieNames[4] = "com5";
    possibleCompanieNames[5] = "com6";

    //I deleted the while loop, as it only has two ways and every way has its own code.

    Scanner scanner = new Scanner(System.in);
    int choice;

    System.out.println("Choose one:");
    System.out.println("1. " + possibleCompanieNames[0]);
    System.out.println("2. " + possibleCompanieNames[1]);
    System.out.println("3. " + possibleCompanieNames[2]);
    choice = scanner.nextInt();
    choosenCompanieNames[0] = possibleCompanieNames[choice-1]; //you must subtract one, as the array index starts at 0 and ends on 5

    System.out.println("Choose one:");
    System.out.println("1. " + possibleCompanieNames[3]);
    System.out.println("2. " + possibleCompanieNames[4]);
    System.out.println("3. " + possibleCompanieNames[5]);
    choice = scanner.nextInt();
    choosenCompanieNames[1] = possibleCompanieNames[3+choice-1]; //here you want com4, com5 and com6, so you can e.g. add 3 to index and substract one like code above. Or better add only 2, as 3-1=2

    System.out.println("You have chosen: "
         + choosenCompanieNames[0] + ", " + choosenCompanieNames[1]);
</code>```

Body:
I wrote a short code that declares 6 reference variables from a class named 'ChosenCompanies' to practice classes and constructors in Java.

It is the following:

public static void main(String[] args) {

    String[] FinalCompaniesName = new String[6];

    ChosenCompanies com1 = new ChosenCompanies();
    ChosenCompanies com2 = new ChosenCompanies();
    ChosenCompanies com3 = new ChosenCompanies();
    ChosenCompanies com4 = new ChosenCompanies();
    ChosenCompanies com5 = new ChosenCompanies();
    ChosenCompanies com6 = new ChosenCompanies();

    Scanner scanner = new Scanner(System.in);
    int choice;
    int count = 1;
    while(count <= 2) {
        switch(count) {
        case 1:
            System.out.println("Choose one:");
            System.out.println("1. " + com1.name);
            System.out.println("2. " + com2.name);
            System.out.println("3. " + com3.name);
            choice = scanner.nextInt();
            switch(choice) {
            case 1:
                FinalCompaniesName[0] = com1.name;
                break;
            case 2:
                FinalCompaniesName[0] = com2.name;
                break;
            case 3:
                FinalCompaniesName[0] = com3.name;
                break;
            }
        break;
        case 2:
            System.out.println("Choose one:");
            System.out.println("1. " + com4.name);
            System.out.println("2. " + com5.name);
            System.out.println("3. " + com6.name);
            choice = scanner.nextInt();
            switch(choice) {
            case 1:
                FinalCompaniesName[1] = com4.name;
                break;
            case 2:
                FinalCompaniesName[1] = com5.name;
                break;
            case 3:
                FinalCompaniesName[1] = com6.name;
                break;
            }
            break;
        }
        count++;
    }
        System.out.println("You have chosen: "
 + FinalCompaniesName[0] + ", " + FinalCompaniesName[1]);

}

As you can see from the above code, these two parts are almost the same except for the names of reference variables(com1, com2, com3, com4...):

part 1:

        switch(count) {
        case 1:
            System.out.println("Choose one:");
            System.out.println("1. " + com1.name);
            System.out.println("2. " + com2.name);
            System.out.println("3. " + com3.name);
            choice = scanner.nextInt();
            switch(choice) {
            case 1:
                FinalCompaniesName[0] = com1.name;
                break;
            case 2:
                FinalCompaniesName[0] = com2.name;
                break;
            case 3:
                FinalCompaniesName[0] = com3.name;
                break;
            }
         break;

part 2:

        case 2:
            System.out.println("Choose one:");
            System.out.println("1. " + com4.name);
            System.out.println("2. " + com5.name);
            System.out.println("3. " + com6.name);
            choice = scanner.nextInt();
            switch(choice) {
            case 1:
                FinalCompaniesName[1] = com4.name;
                break;
            case 2:
                FinalCompaniesName[1] = com5.name;
                break;
            case 3:
                FinalCompaniesName[1] = com6.name;
                break;
                }
            break;
        }

I am wondering if I can minimize the amount of the code above by using a for or while loop, since the name of the reference variables are increased by 1, like integer 'i' in a common for statement.

In short, is it possible to declare reference variables by using loop?

Body:
It is not possible in Java to create dynamic variables (but with reflections, see here)

You can create an array and use the i as index like chosenCompanies[i].

Otherwise you can use lists or maps.

Edit:

That would e.g. look like this. Apart from the sence of the code, this example shows only how you would use an array:

    String[] choosenCompanieNames = new String[2]; // you only store two values, not 6 values

    //lets store the values to chose in arrays
    String[] possibleCompanieNames = new String[6]; // 6 possible values to choose (com1 - com6)
    possibleCompanieNames[0] = "com1";
    possibleCompanieNames[1] = "com2";
    possibleCompanieNames[2] = "com3";
    possibleCompanieNames[3] = "com4";
    possibleCompanieNames[4] = "com5";
    possibleCompanieNames[5] = "com6";

    //I deleted the while loop, as it only has two ways and every way has its own code.

    Scanner scanner = new Scanner(System.in);
    int choice;

    System.out.println("Choose one:");
    System.out.println("1. " + possibleCompanieNames[0]);
    System.out.println("2. " + possibleCompanieNames[1]);
    System.out.println("3. " + possibleCompanieNames[2]);
    choice = scanner.nextInt();
    choosenCompanieNames[0] = possibleCompanieNames[choice-1]; //you must subtract one, as the array index starts at 0 and ends on 5

    System.out.println("Choose one:");
    System.out.println("1. " + possibleCompanieNames[3]);
    System.out.println("2. " + possibleCompanieNames[4]);
    System.out.println("3. " + possibleCompanieNames[5]);
    choice = scanner.nextInt();
    choosenCompanieNames[1] = possibleCompanieNames[3+choice-1]; //here you want com4, com5 and com6, so you can e.g. add 3 to index and substract one like code above. Or better add only 2, as 3-1=2

    System.out.println("You have chosen: "
         + choosenCompanieNames[0] + ", " + choosenCompanieNames[1]);


问:
Trying to get property 'email' of non-object
I am getting following error from my code written in Codeigniter when i enter a wrong E-mail.

A PHP Error was encountered Severity: Notice

Message: Trying to get property 'email' of non-object

Filename: controllers/forms.php

Line Number: 26

Backtrace:

File:
  E:\Software\XAMPP\xampp\htdocs\ciauth\application\controllers\forms.php
  Line: 26 Function: _error_handler

File: E:\Software\XAMPP\xampp\htdocs\ciauth\index.php Line: 315
  Function: require_once

Below is the controller

```<code><?php
class Forms extends CI_Controller
{
    public function __construct()
    {

        parent::__construct();
        $this->load->database();
        $this->load->library('session');
        $this->load->helper('url');
        $this->load->model('user_model', 'auth');
    }

   public function forgot_pass()
    {
        if($this->input->post('forgot_pass'))
        {
            $email=$this->input->post('email');
            $this->load->model('user_model', 'auth');
            $this->load->library('form_validation');
            $this->form_validation->set_rules('email', 'E-mail', 'required');

            if ($this->form_validation->run() == TRUE) {
            $que=$this->db->query("select password,email from users where email='$email'");
            $row=$que->row();
            $user_email=$row->email;
            if((!strcmp($email, $user_email)))
            {
                $pass=$row->password;
                $to = $user_email;
                $subject = "Password";
                $txt = "Your password is $pass .";
                $headers = "From: user@testdomain.com" . "\r\n" . "CC: hamza_zon@outlook.com ";
                mail($to,$subject,$txt,$headers);
                $this->load->view('user/header');
                $this->load->view('user/confirm');
                $this->load->view('user/footer');
                }
            else{
            $data['error']="Invalid Email ID !";
            }
        }
            else{
                $data['error']="Email ID is required !";
            }
    }
            $this->load->view('user/header');
            $this->load->view('user/forgot_pass',@$data);
            $this->load->view('user/footer');

   }
}
?>
</code>```

答:
you should check before $user_email=$row->email; that the as per your criteria record exist or not, if row is not exist then you will get that error

so you should check as below

```<code>$row=$que->row();
if($row) {

   $user_email=$row->email;
}
</code>```

Body:
I am getting following error from my code written in Codeigniter when i enter a wrong E-mail.

A PHP Error was encountered Severity: Notice

Message: Trying to get property 'email' of non-object

Filename: controllers/forms.php

Line Number: 26

Backtrace:

File:
  E:\Software\XAMPP\xampp\htdocs\ciauth\application\controllers\forms.php
  Line: 26 Function: _error_handler

File: E:\Software\XAMPP\xampp\htdocs\ciauth\index.php Line: 315
  Function: require_once

Below is the controller

<?php
class Forms extends CI_Controller
{
    public function __construct()
    {

        parent::__construct();
        $this->load->database();
        $this->load->library('session');
        $this->load->helper('url');
        $this->load->model('user_model', 'auth');
    }

   public function forgot_pass()
    {
        if($this->input->post('forgot_pass'))
        {
            $email=$this->input->post('email');
            $this->load->model('user_model', 'auth');
            $this->load->library('form_validation');
            $this->form_validation->set_rules('email', 'E-mail', 'required');

            if ($this->form_validation->run() == TRUE) {
            $que=$this->db->query("select password,email from users where email='$email'");
            $row=$que->row();
            $user_email=$row->email;
            if((!strcmp($email, $user_email)))
            {
                $pass=$row->password;
                $to = $user_email;
                $subject = "Password";
                $txt = "Your password is $pass .";
                $headers = "From: user@testdomain.com" . "\r\n" . "CC: hamza_zon@outlook.com ";
                mail($to,$subject,$txt,$headers);
                $this->load->view('user/header');
                $this->load->view('user/confirm');
                $this->load->view('user/footer');
                }
            else{
            $data['error']="Invalid Email ID !";
            }
        }
            else{
                $data['error']="Email ID is required !";
            }
    }
            $this->load->view('user/header');
            $this->load->view('user/forgot_pass',@$data);
            $this->load->view('user/footer');

   }
}
?>

Body:
you should check before $user_email=$row->email; that the as per your criteria record exist or not, if row is not exist then you will get that error

so you should check as below

$row=$que->row();
if($row) {

   $user_email=$row->email;
}


问:
Error when implementing springboot with H2db
I am new to coding. I am getting below error when trying to run java application in springboot with H2db.

```<code>
[ERROR] Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 8.777 s <<< FAILURE! - in com.example.demo.DemoApplicationTests
[ERROR] contextLoads(com.example.demo.DemoApplicationTests)  Time elapsed: 0.002 s  <<< ERROR!
java.lang.IllegalStateException: Failed to load ApplicationContext
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Invocation of init method failed; nested exception is org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
Caused by: org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
Caused by: org.hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set

[INFO]
[INFO] Results:
[INFO]
[ERROR] Errors:
[ERROR]   DemoApplicationTests.contextLoads » IllegalState Failed to load ApplicationCon...
[INFO]
[ERROR] Tests run: 1, Failures: 0, Errors: 1, Skipped: 0
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  13.028 s
[INFO] Finished at: 2019-05-26T22:46:54+05:30
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.22.2:test (default-test) on project demo: There are test failures.
[ERROR]
[ERROR] Please refer to C:\Users\v\Desktop\demo\target\surefire-reports for the individual test results.
[ERROR] Please refer to dump files (if any exist) [date].dump, [date]-jvmRun[N].dump and [date].dumpstream.
[ERROR] -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException
</code>```

Here is my xml:

```<code>
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.5.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>
</code>```

Application :

```<code>package com.example.demo;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;

import com.example.demo.StudentRepository;

@SpringBootApplication
@EntityScan("com.example.demo.Student")
@EnableJpaRepositories("com.example.demo.StudentRepository")
public class H2demoApplication implements CommandLineRunner {

    // mvn spring-boot:run
    private Logger LOG = LoggerFactory.getLogger("H2demoApplication");

    StudentRepository studentRepository;

    @Autowired
    public H2demoApplication(StudentRepository studentRepository) {
        this.studentRepository = studentRepository;
    }

    public static void main(String[] args) {
        SpringApplication.run(H2demoApplication.class, args);
    }

    @Override
    public void run(String... args) throws Exception {
        LOG.info("Student count in DB: {}", studentRepository.count());
    }
}

Entity:

package com.example.demo;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

@Entity
public class Student {

    @Id
    @GeneratedValue
    private Long ID;
    private String NAME;
    private String SECTION;

    public Student() {
    }

    public Student(Long ID, String NAME, String SECTION) {
        this.ID = ID;
        this.NAME = NAME;
        this.SECTION = SECTION;
    }

    public Long getId() {
        return ID;
    }

    public void setId(Long ID) {
        this.ID = ID;
    }

    public String getName() {
        return NAME;
    }

    public void setName(String NAME) {
        this.NAME = NAME;
    }

    public String getSection() {
        return SECTION;
    }

    public void setSection(String SECTION) {
        this.SECTION = SECTION;
    }

}

Repository:

package com.example.demo;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import com.example.demo.Student;

@Repository
public interface StudentRepository extends JpaRepository<Student, Long> {

}
</code>```

O/p should have "Student count in DB: 2"

my java version is :
java version "1.8.0_102"
Java(TM) SE Runtime Environment (build 1.8.0_102-b14)
Java HotSpot(TM) 64-Bit Server VM (build 25.102-b14, mixed mode)

Getting above error when running mvn clean install in command line.
I defined h2db configurations in application.properties file as below

H2 configurarion

```<code>spring.h2.console.enabled=true

spring.h2.console.path=/h2

Datasource

spring.datasource.url=jdbc:h2:~/test

spring.datasource.username=

spring.datasource.password=

spring.datasource.driver-class-name=org.h2.Driver
</code>```

in data.sql file kept data to be inserted :

```<code>insert into STUDENT
values(10001,'Ajay', 'AAA1');

insert into STUDENT
values(10002,'Ajit', 'AAA2');
</code>```

答:
The error looks like, it can't figure out the dialect to be used with H2.

The dialect specifies the type of database used in hibernate so that hibernate generate appropriate type of SQL statements.

The dialect to be used for h2 is this:

```<code>spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
</code>```

Also being new to programming might confuse you to write optimal code. It looks like, you are mixing up things from older versions of spring boot and spring. Please use,

https://start.spring.io

to generate your initial spring boot project with the required dependencies. You can follow the below tutorial which explains nicely to get started with spring boot and h2.

https://www.springboottutorial.com/spring-boot-and-h2-in-memory-database

Body:
I am new to coding. I am getting below error when trying to run java application in springboot with H2db.

[ERROR] Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 8.777 s <<< FAILURE! - in com.example.demo.DemoApplicationTests
[ERROR] contextLoads(com.example.demo.DemoApplicationTests)  Time elapsed: 0.002 s  <<< ERROR!
java.lang.IllegalStateException: Failed to load ApplicationContext
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Invocation of init method failed; nested exception is org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
Caused by: org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
Caused by: org.hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set

[INFO]
[INFO] Results:
[INFO]
[ERROR] Errors:
[ERROR]   DemoApplicationTests.contextLoads » IllegalState Failed to load ApplicationCon...
[INFO]
[ERROR] Tests run: 1, Failures: 0, Errors: 1, Skipped: 0
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  13.028 s
[INFO] Finished at: 2019-05-26T22:46:54+05:30
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.22.2:test (default-test) on project demo: There are test failures.
[ERROR]
[ERROR] Please refer to C:\Users\v\Desktop\demo\target\surefire-reports for the individual test results.
[ERROR] Please refer to dump files (if any exist) [date].dump, [date]-jvmRun[N].dump and [date].dumpstream.
[ERROR] -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException

Here is my xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.5.RELEASE</version>
        <relativePath/>
    </parent>
    <groupId>com.example</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

Application :

package com.example.demo;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;

import com.example.demo.StudentRepository;

@SpringBootApplication
@EntityScan("com.example.demo.Student")
@EnableJpaRepositories("com.example.demo.StudentRepository")
public class H2demoApplication implements CommandLineRunner {

    // mvn spring-boot:run
    private Logger LOG = LoggerFactory.getLogger("H2demoApplication");

    StudentRepository studentRepository;

    @Autowired
    public H2demoApplication(StudentRepository studentRepository) {
        this.studentRepository = studentRepository;
    }

    public static void main(String[] args) {
        SpringApplication.run(H2demoApplication.class, args);
    }

    @Override
    public void run(String... args) throws Exception {
        LOG.info("Student count in DB: {}", studentRepository.count());
    }
}

Entity:

package com.example.demo;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

@Entity
public class Student {

    @Id
    @GeneratedValue
    private Long ID;
    private String NAME;
    private String SECTION;

    public Student() {
    }

    public Student(Long ID, String NAME, String SECTION) {
        this.ID = ID;
        this.NAME = NAME;
        this.SECTION = SECTION;
    }

    public Long getId() {
        return ID;
    }

    public void setId(Long ID) {
        this.ID = ID;
    }

    public String getName() {
        return NAME;
    }

    public void setName(String NAME) {
        this.NAME = NAME;
    }

    public String getSection() {
        return SECTION;
    }

    public void setSection(String SECTION) {
        this.SECTION = SECTION;
    }

}

Repository:

package com.example.demo;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import com.example.demo.Student;

@Repository
public interface StudentRepository extends JpaRepository<Student, Long> {

}

O/p should have "Student count in DB: 2"

my java version is :
java version "1.8.0_102"
Java(TM) SE Runtime Environment (build 1.8.0_102-b14)
Java HotSpot(TM) 64-Bit Server VM (build 25.102-b14, mixed mode)

Getting above error when running mvn clean install in command line.
I defined h2db configurations in application.properties file as below

H2 configurarion

spring.h2.console.enabled=true

spring.h2.console.path=/h2

Datasource

spring.datasource.url=jdbc:h2:~/test

spring.datasource.username=

spring.datasource.password=

spring.datasource.driver-class-name=org.h2.Driver

in data.sql file kept data to be inserted :

insert into STUDENT
values(10001,'Ajay', 'AAA1');

insert into STUDENT
values(10002,'Ajit', 'AAA2');

Body:
The error looks like, it can't figure out the dialect to be used with H2.

The dialect specifies the type of database used in hibernate so that hibernate generate appropriate type of SQL statements.

The dialect to be used for h2 is this:

spring.jpa.database-platform=org.hibernate.dialect.H2Dialect

Also being new to programming might confuse you to write optimal code. It looks like, you are mixing up things from older versions of spring boot and spring. Please use,

https://start.spring.io

to generate your initial spring boot project with the required dependencies. You can follow the below tutorial which explains nicely to get started with spring boot and h2.

https://www.springboottutorial.com/spring-boot-and-h2-in-memory-database


答:
Try like this</p>

```<code>$que = $this->db->query("select password,email from users where email=".$email);

if(isset($row) && $row != ''){
  $txt = "Your password is" . $pass;
  //Coding...
}
</code>```

Title: Trying to get property 'email' of non-object

Body:
Try like this

$que = $this->db->query("select password,email from users where email=".$email);

if(isset($row) && $row != ''){
  $txt = "Your password is" . $pass;
  //Coding...
}


问:
Translating to english using word lists
Say I have a list of item-colour pairs:

Item1 red

Item2 red_in_finnish

Item3 red_in_polish

Item4 blue_in_russian

Item5 blue_in_estonian

Item6 blue_in_polish

I need to translate all the colours in foreign languages to English:

Item1 red

Item2 red

Item3 red

Item4 blue

Item5 blue

Item6 blue

In my actual code, I have many more than two colours, and about a dozen different arrays containing all the foreign words for each colour. This is the current way I am performing the replacement:

```<code>red_words = ['red_in_finnish', 'red_in_polish']
blue_words = ['blue_in_russian', 'blue_in_estonian', 'blue_in_polish']

for word in red_words:
   if word in item_name:
      item_name = item_name.replace(word, "red")
</code>```

The problem is that I do not know beforehand if each name contains any specific colour, so I need to check for all of them to make sure I replace everything.

Is there a smart way to do this? It would be perfect if it was possible to somehow map colours' foreign names to their English names.

答:
If I understand correctly, you can do this by iterating over the list once, using a dict. An example:

```<code>red_words = {'red': 'red', # English
             'rojo': 'red', # Spanish
             'rot': 'red', # German
             'rouge': 'red' # French
            }

blue_words = {'blue': 'blue',
              'azul': 'blue',
              'blau': 'blue',
              'bleu': 'blue'
             }

# More colours here...

combined_translations = {**red_words, **blue_words}

data = [('blue_thing', 'bleu'),
        ('also_blue_thing', 'azul'),
        ('blueberry', 'blue'),
        ('fire engine', 'red'),
        ('blood', 'rouge'),
        ('tomato', 'rot')]

translated = [(item, combined_translations[colour]) for item, colour in data]

print(translated)
</code>```

Output:

```<code>[('blue_thing', 'blue'),
 ('also_blue_thing', 'blue'),
 ('blueberry', 'blue'),
 ('fire engine', 'red'),
 ('blood', 'red'),
 ('tomato', 'red')]
</code>```

This will fail if, by some perverse chance, you have a word that is the same in two source languages, but each means a different colour in English.

Title: Translating to english using word lists

Body:
Say I have a list of item-colour pairs:

Item1 red

Item2 red_in_finnish

Item3 red_in_polish

Item4 blue_in_russian

Item5 blue_in_estonian

Item6 blue_in_polish

I need to translate all the colours in foreign languages to English:

Item1 red

Item2 red

Item3 red

Item4 blue

Item5 blue

Item6 blue

In my actual code, I have many more than two colours, and about a dozen different arrays containing all the foreign words for each colour. This is the current way I am performing the replacement:

red_words = ['red_in_finnish', 'red_in_polish']
blue_words = ['blue_in_russian', 'blue_in_estonian', 'blue_in_polish']

for word in red_words:
   if word in item_name:
      item_name = item_name.replace(word, "red")

The problem is that I do not know beforehand if each name contains any specific colour, so I need to check for all of them to make sure I replace everything.

Is there a smart way to do this? It would be perfect if it was possible to somehow map colours' foreign names to their English names.

Body:
If I understand correctly, you can do this by iterating over the list once, using a dict. An example:

red_words = {'red': 'red', # English
             'rojo': 'red', # Spanish
             'rot': 'red', # German
             'rouge': 'red' # French
            }

blue_words = {'blue': 'blue',
              'azul': 'blue',
              'blau': 'blue',
              'bleu': 'blue'
             }

# More colours here...

combined_translations = {**red_words, **blue_words}

data = [('blue_thing', 'bleu'),
        ('also_blue_thing', 'azul'),
        ('blueberry', 'blue'),
        ('fire engine', 'red'),
        ('blood', 'rouge'),
        ('tomato', 'rot')]

translated = [(item, combined_translations[colour]) for item, colour in data]

print(translated)

Output:

[('blue_thing', 'blue'),
 ('also_blue_thing', 'blue'),
 ('blueberry', 'blue'),
 ('fire engine', 'red'),
 ('blood', 'red'),
 ('tomato', 'red')]

This will fail if, by some perverse chance, you have a word that is the same in two source languages, but each means a different colour in English.


问:
Can you recommend a Python SOAP client that can accept WS-Attachments?
I've read mixed reviews of both Suds and ZSI -- two Python SOAP libraries.  However, I'm unclear whether either of them can support WS-Attachments.  I'd prefer to use Suds (appears to be more straightforward), but I'll defer to whichever library suits my needs.</p>

答: In my experience Suds was the only Python package that actually works.  I did not use attachments.</p>

OwnerDisplayName: Huuuze


问:
How to validate user input with numbers 0-9 and letters a-z and A-Z in Angular 7?
I am working on a project that must allow combination of numbers (0-9), characters (a -z and A-Z) and minimum length should be 8. I tried a lot, but I could not get a good solution.

```<code> ngOnInit() {
    this.newPasswordFormGroup = this.formBuilder.group({
      newPassword: ['', Validators.compose([Validators.required,
        Validators.minLength(8),
        Validators.pattern('^A-Za-z0-9')])],
      confirmPassword: ['', Validators.required],
    }, {
      validator: MustMatch('newPassword', 'confirmPassword')
  });
  }

<form [formGroup]="newPasswordFormGroup" role="form" (ngSubmit)="onSubmitPassword()">
                <div class="form-group text-left">
                    <input type="password" [ngClass]="{ 'is-invalid': submitted && f.newPassword.errors }" formControlName="newPassword" class="form-control input-underline input-lg textBox" id="newPassword" placeholder="Enter new password" />
                    <div *ngIf="submitted && f.newPassword.errors" class="invalid-feedback">
                        <div *ngIf="f.newPassword.errors.required">New password is required</div>
                    </div>
                    <div *ngIf="submitted && f.newPassword.errors" class="invalid-feedback">
                        <div *ngIf="f.newPassword.errors.pattern">#Password should be a minimum of 8 characters and contain a combination of letters and numbers</div>
                    </div>
                    <div *ngIf="submitted && f.newPassword.errors" class="invalid-feedback">
                        <div *ngIf="f.newPassword.errors.minlength">Password should be a minimum of 8 characters</div>
                    </div>
                </div>
                <div class="form-group text-left">
                    <input type="password" [ngClass]="{ 'is-invalid': submitted && f.confirmPassword.errors }" formControlName="confirmPassword" class="form-control input-underline input-lg textBox" id="confirmPassword" placeholder="Enter confirm password" />
                    <div *ngIf="submitted && f.confirmPassword.errors" class="invalid-feedback">
                        <div *ngIf="f.confirmPassword.errors.required">Confirm password is required</div>
                    </div>
                    <div *ngIf="submitted && f.confirmPassword.errors" class="invalid-feedback">
                        <div *ngIf="f.confirmPassword.errors.mustMatch">Passwords must match</div>
                    </div>
                </div>
                <div class="password-btn">
                    <button type="submit" [disabled]="isDisabled" class="btn btn-primary submit-btn"> Submit </button>
                </div>
            </form>
</code>```

Ex:
   It should be "s12sre34"

答:
I did like this. it worked for me.</p>

```<code>ngOnInit() {
    this.newPasswordFormGroup = this.formBuilder.group({
      newPassword: ['', Validators.compose([Validators.required,
        Validators.minLength(8),
        CustomValidator.findCombinationLettersAndNumbers()])],
      confirmPassword: ['', Validators.required],
    }, {
      validator: MustMatch('newPassword', 'confirmPassword')
  });
  }

 import { AbstractControl, ValidatorFn } from '@angular/forms';

 export class CustomValidator {

    public static findCombinationLettersAndNumbers(): ValidatorFn {

        return (c: AbstractControl): { [key: string]: boolean } | null => {
            // console.log('val:', c.value);

            let isDigit = false;
            let isCapsOrSmallLetter = false;
            // let isSmallLetter = false;
            let isSpecialChar = false;
            if ((!/\d/.test(c.value))) {
                // console.log('password must contain digits');
                isDigit = false;
            } else {
                isDigit = true;
            }
            if (!/[A-Za-z]/.test(c.value)) {
                // console.log('password must contain uppercase letter');
                isCapsOrSmallLetter = false;
            } else {
                isCapsOrSmallLetter = true;
            }
            // if (!/[a-z]/.test(c.value)) {
            //     console.log('password must contain lowercase letter');
            //     isSmallLetter = false;
            // } else {
            //     isSmallLetter = true;
            // }

            if (!/[ !@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/.test(c.value)) {
                // console.log('password must contain special character');
                isSpecialChar = true;
            }

            if (isDigit && isCapsOrSmallLetter && isSpecialChar === true) {
                // null is required here. otherwise form wonot submit.
                return null;
            }
            return { passwordval: true };

        };

    }

}
</code>```

Body:
I am working on a project that must allow combination of numbers (0-9), characters (a -z and A-Z) and minimum length should be 8. I tried a lot, but I could not get a good solution.

 ngOnInit() {
    this.newPasswordFormGroup = this.formBuilder.group({
      newPassword: ['', Validators.compose([Validators.required,
        Validators.minLength(8),
        Validators.pattern('^A-Za-z0-9')])],
      confirmPassword: ['', Validators.required],
    }, {
      validator: MustMatch('newPassword', 'confirmPassword')
  });
  }

<form [formGroup]="newPasswordFormGroup" role="form" (ngSubmit)="onSubmitPassword()">

                    <input type="password" [ngClass]="{ 'is-invalid': submitted && f.newPassword.errors }" formControlName="newPassword" class="form-control input-underline input-lg textBox" id="newPassword" placeholder="Enter new password" />

New password is required

#Password should be a minimum of 8 characters and contain a combination of letters and numbers

Password should be a minimum of 8 characters

                    <input type="password" [ngClass]="{ 'is-invalid': submitted && f.confirmPassword.errors }" formControlName="confirmPassword" class="form-control input-underline input-lg textBox" id="confirmPassword" placeholder="Enter confirm password" />

Confirm password is required

Passwords must match

                    <button type="submit" [disabled]="isDisabled" class="btn btn-primary submit-btn"> Submit </button>

            </form>

Ex:
   It should be "s12sre34"

Body:
I did like this. it worked for me.

ngOnInit() {
    this.newPasswordFormGroup = this.formBuilder.group({
      newPassword: ['', Validators.compose([Validators.required,
        Validators.minLength(8),
        CustomValidator.findCombinationLettersAndNumbers()])],
      confirmPassword: ['', Validators.required],
    }, {
      validator: MustMatch('newPassword', 'confirmPassword')
  });
  }

 import { AbstractControl, ValidatorFn } from '@angular/forms';

 export class CustomValidator {

    public static findCombinationLettersAndNumbers(): ValidatorFn {

        return (c: AbstractControl): { [key: string]: boolean } | null => {
            // console.log('val:', c.value);

            let isDigit = false;
            let isCapsOrSmallLetter = false;
            // let isSmallLetter = false;
            let isSpecialChar = false;
            if ((!/\d/.test(c.value))) {
                // console.log('password must contain digits');
                isDigit = false;
            } else {
                isDigit = true;
            }
            if (!/[A-Za-z]/.test(c.value)) {
                // console.log('password must contain uppercase letter');
                isCapsOrSmallLetter = false;
            } else {
                isCapsOrSmallLetter = true;
            }
            // if (!/[a-z]/.test(c.value)) {
            //     console.log('password must contain lowercase letter');
            //     isSmallLetter = false;
            // } else {
            //     isSmallLetter = true;
            // }

            if (!/[ !@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/.test(c.value)) {
                // console.log('password must contain special character');
                isSpecialChar = true;
            }

            if (isDigit && isCapsOrSmallLetter && isSpecialChar === true) {
                // null is required here. otherwise form wonot submit.
                return null;
            }
            return { passwordval: true };

        };

    }

}


答:
Apply condition as, because in your case it may not getting the result from table for that email,

```<code>if (isset($row))
{
</code>```

Note: row method returns a single result row. If your query has more than one row, it returns only the first row. The result is
  returned as an object. Here’s a usage example:

```<code>$que=$this->db->query("select password,email from users where email like '$email'");

$row = $que->row();

if (isset($row))
{
    $user_email = $row->email;
    $user_password = $row->password;
}
</code>```

Here is concise doc for the same.

Body:
Apply condition as, because in your case it may not getting the result from table for that email,

if (isset($row))
{

Note: row method returns a single result row. If your query has more than one row, it returns only the first row. The result is
  returned as an object. Here’s a usage example:

$que=$this->db->query("select password,email from users where email like '$email'");

$row = $que->row();

if (isset($row))
{
    $user_email = $row->email;
    $user_password = $row->password;
}

Here is concise doc for the same.


问:
MySQL and PHP not inserting rows with spaces or special characters
I have an Android App that I program, when users search parts, my php document on my web server I have setup to add what they searched into another table to just tack how many searches are being done through the app, when a field has no spaces it adds to the table just fine, however if the field has a space or special chars in it like a dash, it dose not insert into the table. I'm at a loss how to get this to work properly and I'm hoping someone might some insight into what I'm doing wrong here. Thank you all in advanced :)

PHP Code Server Side (MySql DB)

```<code>$sql = "INSERT INTO USAGE_STATS (ITEM_NAME, FSC, NIIN, PART_NUMBER)
VALUES ('$ITEM_NAME', '$FSC', '$NIIN', $PART_NUMBER)";

if ($conn->query($sql) === TRUE) {
    $row = mysqli_insert_id($conn);
} else {
    //do nothing
}
</code>```

The colation is set to "utf8_general_ci," feilds are set to "Text," and the datebase is a MyISAM

Edit:
Just tried another part, and the full part number is "5-86510-53" but when it was inserted into the table it just came out to "-86558" in the DB

UPDATE EDIT: No this has not been answered before, I was not asking how to prevent SQL injection attacks, I was asking what I was doing wrong here.... offering advice that I should do prepared statements is the kind of advice I was looking for. I want to thank everyone for pointing me in the right direction, but marking me down for asking a question about what I was doing wrong is not what I thought this site was supposed to be about... but thank you again to those who offered meaningful assistance :)

答:
First of all don't allow the data to be inserted with spaces and special characters in your database,As it will open doors for any one to do SQL injections,

For avoiding data with spaces and special characters you can use MySQL_real_escape_string which is an inbuilt function of MySQL you can use this if you are using MySQL without pdo's.

IF you are using pdo object then you can surely use prepare statement for you query as prepare statement is more secure and optimise way to write your query as it provide an advantage of using named parameters in your query.

Body:
I have an Android App that I program, when users search parts, my php document on my web server I have setup to add what they searched into another table to just tack how many searches are being done through the app, when a field has no spaces it adds to the table just fine, however if the field has a space or special chars in it like a dash, it dose not insert into the table. I'm at a loss how to get this to work properly and I'm hoping someone might some insight into what I'm doing wrong here. Thank you all in advanced :)

PHP Code Server Side (MySql DB)

$sql = "INSERT INTO USAGE_STATS (ITEM_NAME, FSC, NIIN, PART_NUMBER)
VALUES ('$ITEM_NAME', '$FSC', '$NIIN', $PART_NUMBER)";

if ($conn->query($sql) === TRUE) {
    $row = mysqli_insert_id($conn);
} else {
    //do nothing
}

The colation is set to "utf8_general_ci," feilds are set to "Text," and the datebase is a MyISAM

Edit:
Just tried another part, and the full part number is "5-86510-53" but when it was inserted into the table it just came out to "-86558" in the DB

UPDATE EDIT: No this has not been answered before, I was not asking how to prevent SQL injection attacks, I was asking what I was doing wrong here.... offering advice that I should do prepared statements is the kind of advice I was looking for. I want to thank everyone for pointing me in the right direction, but marking me down for asking a question about what I was doing wrong is not what I thought this site was supposed to be about... but thank you again to those who offered meaningful assistance :)