问:
I don't understand association class - UML class diagram

I  don't yet completely seem to understand how association class works, why the role class attributes can't just be inside the person class?

as example:

Person

name

position

description

答:
Suppose we live in a world where a person must have a role in a company in order to live and a company may exist without persons at all.

If that is all you want to know about the relationship between persons and companies, i.e. only the fact that there are such relationships and nothing more, you model it like this:

Then if you want in addition to capture  position and description of the Person's role you use so called AssociationClass (Role in our case):

Each instance of Role has four properties (both an attribute and an end of an association are Properties in UML):

Company

Person

position

description

For example, suppose a person named Scott Tiger has roles in two companies - Food Inc and Water Ltd and each company knows that Scott Tiger has role in it. Then there will be two instances of Role (shown as tuples):

```<code>(Food Inc., Scott Tigger, eater, eats here)
(Water Inc., Scott Tigger, drinker, drinks here)
</code>```

Now, returning to you question, it should be clear that an instance of Person with name, position, description attributes actually "lacks" Company and if you "add" an Company you will get Role, not Person!

So what you proposed in the end of your question is a valid design, if you model Company and Role and a person is just an attribute of Role:

It reads as follows: each instance of Company has zero or more Roles and each instance of Role has only one Company. Both ends of the association are navigable, i.e. Role knows its Company and Company knows its Roles.

UML Specification in clause 9.5.3 gives you the following advice:

A Property may represent an attribute of a Classifier, a memberEnd of an Association, or in some cases both simultaneously.

A useful convention for general modeling scenarios is that a Property whose type is a kind of Class is an Association
end, while a property whose type is a kind of DataType is not. This convention is not enforced by UML.

Body:
Suppose we live in a world where a person must have a role in a company in order to live and a company may exist without persons at all.

If that is all you want to know about the relationship between persons and companies, i.e. only the fact that there are such relationships and nothing more, you model it like this:

Then if you want in addition to capture  position and description of the Person's role you use so called AssociationClass (Role in our case):

Each instance of Role has four properties (both an attribute and an end of an association are Properties in UML):

Company

Person

position

description

For example, suppose a person named Scott Tiger has roles in two companies - Food Inc and Water Ltd and each company knows that Scott Tiger has role in it. Then there will be two instances of Role (shown as tuples):

(Food Inc., Scott Tigger, eater, eats here)
(Water Inc., Scott Tigger, drinker, drinks here)

Now, returning to you question, it should be clear that an instance of Person with name, position, description attributes actually "lacks" Company and if you "add" an Company you will get Role, not Person!

So what you proposed in the end of your question is a valid design, if you model Company and Role and a person is just an attribute of Role:

It reads as follows: each instance of Company has zero or more Roles and each instance of Role has only one Company. Both ends of the association are navigable, i.e. Role knows its Company and Company knows its Roles.

UML Specification in clause 9.5.3 gives you the following advice:

A Property may represent an attribute of a Classifier, a memberEnd of an Association, or in some cases both simultaneously.

A useful convention for general modeling scenarios is that a Property whose type is a kind of Class is an Association
end, while a property whose type is a kind of DataType is not. This convention is not enforced by UML.


来源: stackexchange

问:
Angular 7: Enabel and Disable buttons according to number to form fields filled
I very new to angular 7 and I came up with a situation where I have two buttons :

submit

Check

I have to enable check button when 3 form fields are filled i.e

```<code>semester, branch and subject
</code>```

on the other hand I want to enable submit button when all the 4 fields are filled i.e

```<code>semester, branch and subject, image
</code>```

I am using FromValidation and can successfully enable the submit button when 4 fields are filled, now the problem is how to enable the check button when 3 form fields are filled

component.html

```<code><app-teacher-header></app-teacher-header>
<div class="container">
  <div class="row">
    <div class="col-sm-12" *ngIf="!checkAssignment">
        <form>
            <div class="form-group">
                <label for="exampleInputEmail1">Name</label>
                <input type="text" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp"
                [(ngModel)]="assignment.name" name="name" [value]="assignment.name" disabled>
              </div>

              <!-----------------SEMESTER  ----------------------->
              <div class="form-group" #userform="ngForm" [formGroup]="assignmentUploadValidation">
                  <mat-form-field>
                      <mat-select [(ngModel)]="assignment.semester" name="semester"
                      formControlName="semester">
                        <mat-option *ngFor="let semester of semesters" [value]="semester.semester">
                            {{semester.semester}}
                        </mat-option>
                      </mat-select>
                      <div *ngIf="(validations.semester.invalid && validations.semester.touched) || validations.semester.dirty">
                        <small *ngIf="validations.semester.errors?.required" class="text-danger">Subject is required</small>
                      </div>
                    </mat-form-field>
              </div>
              <!----------------- /SEMESTER  ----------------------->

              <!-----------------BRANCH  ----------------------->

            <div class="form-group" #userform="ngForm" [formGroup]="assignmentUploadValidation">
              <mat-form-field>
                <mat-label>Select Branch</mat-label>
                <mat-select [(ngModel)]="assignment.branch"  [(ngModel)]="teacher.branch" name="branch" formControlName="branch"
                (openedChange)="branchChanges($event)">
                  <mat-option *ngFor="let branch of branchs" [value]="branch.branch">
                    {{branch.branch}}
                  </mat-option>
                </mat-select>
                <div *ngIf="(validations.branch.invalid && validations.branch.touched) || validations.branch.dirty">
                  <small *ngIf="validations.branch.errors?.required" class="text-danger">Branch is required</small>
                </div>
              </mat-form-field>
            </div>
            <!-----------------/BRANCH  ----------------------->

              <div class="form-group" #userform="ngForm" [formGroup]="assignmentUploadValidation">
                  <mat-form-field>
                      <mat-select [(ngModel)]="assignment.subject" [(ngModel)]="teacher.subject" name="subject"
                      formControlName="subject">
                        <mat-option *ngFor="let subject of subjects" [value]="subject.subject">
                            {{subject.subject}}
                        </mat-option>
                      </mat-select>
                      <div *ngIf="(validations.subject.invalid && validations.subject.touched) || validations.subject.dirty">
                        <small *ngIf="validations.subject.errors?.required" class="text-danger">Branch is required</small>
                      </div>
                    </mat-form-field>
              </div>

              <div class="form-group"  #userform="ngForm" [formGroup]="assignmentUploadValidation">
                <input type="file" name="image" (change)="onFileSelect($event)" formControlName="image">
                <div *ngIf="(validations.image.invalid && validations.image.touched) || validations.image.dirty">
                  <small *ngIf="validations.image.errors?.required" class="text-danger">Branch is required</small>
                </div>
              </div>

              <button type="submit" class="btn btn-primary" (click)="onUpload()" [disabled]="userform.invalid">Submit</button>
    </form>
    </div>
    <div class="col-sm-12">
        <app-check-assignment *ngIf="checkAssignment"
        [receivedFromTeacherAssignment]="recivedAssignment" [justMsg]="parentMsg"></app-check-assignment>
        <div>
          <button class="btn btn-primary" (click)="onCheckAssignment()">check</button>
        </div>
    </div>

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

component.ts

```<code>import { Component, OnInit } from '@angular/core';
import { Teacher } from 'src/app/shared/teacher.model';
import { TeachersService } from '../teachers.service';
import { SharedService } from 'src/app/shared/shared.service';
import { FormGroup, FormControl, Validators } from '@angular/forms';

export interface Assignment {
  name: string,
  semester : number,
  branch: string,
  subject: string,
  image: string
}

@Component({
  selector: 'app-teacher-assignment',
  templateUrl: './teacher-assignment.component.html',
  styleUrls: ['./teacher-assignment.component.css']
})
export class TeacherAssignmentComponent implements OnInit {
  private teacher = Teacher
  private recivedAssignment : {name: string, assignment: string}
  semesters = []
  branchs = [];

  subjects = [];

  checkAssignment = false;
  parentMsg : string = '';
  assignment : Assignment = {
    name: "",
    semester: null,
    branch: "",
    subject: "",
    image: ""
  }

  assignmentUploadValidation = new FormGroup({

     semester: new FormControl('',
     [

       Validators.required
     ]),
     branch: new FormControl('',[
       Validators.required
     ]),
     subject: new FormControl('', [
       Validators.required
     ]),
     image: new FormControl('', [
       Validators.required
     ])
   })

  constructor(private teacherServ: TeachersService, private sharedServ: SharedService) {}

  ngOnInit() {
  }

  get validations() {
    return this.assignmentUploadValidation.controls;
  }

  onUpload() {
    const fd = new FormData();
    for( var key in this.assignment) {
      fd.append(key , this.assignment[key])
    }

    if(fd) {
      this.teacherServ.uploadAssignment(fd)
      .subscribe(
        res => console.log(res),
        err => console.log(err)
      )
    }

    console.log("assignment: ",this.assignment)
  }

  onCheckAssignment() {
    this.checkAssignment=!this.checkAssignment
    console.log("THis is assignment", this.assignment)
    this.parentMsg = "demos"
    this.teacherServ.checkAssignment(this.assignment)
    .subscribe(
      res => {
        this.recivedAssignment = res.result[0]
        console.log(this.recivedAssignment)
      },
      err => console.log(err)
    )
  }

}
</code>```

答: you can use valueChanges: Observable<any> from FormControl class to track changes of field and when they have values check button.

ContentLicense: CC BY-SA 4.0

Body:
I very new to angular 7 and I came up with a situation where I have two buttons :

submit

Check

I have to enable check button when 3 form fields are filled i.e

semester, branch and subject

on the other hand I want to enable submit button when all the 4 fields are filled i.e

semester, branch and subject, image

I am using FromValidation and can successfully enable the submit button when 4 fields are filled, now the problem is how to enable the check button when 3 form fields are filled

component.html

<app-teacher-header></app-teacher-header>

        <form>

                Name
                <input type="text" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp"
                [(ngModel)]="assignment.name" name="name" [value]="assignment.name" disabled>

                  <mat-form-field>
                      <mat-select [(ngModel)]="assignment.semester" name="semester"
                      formControlName="semester">
                        <mat-option *ngFor="let semester of semesters" [value]="semester.semester">
                            {{semester.semester}}
                        </mat-option>
                      </mat-select>

                        Subject is required

                    </mat-form-field>

              <mat-form-field>
                <mat-label>Select Branch</mat-label>
                <mat-select [(ngModel)]="assignment.branch"  [(ngModel)]="teacher.branch" name="branch" formControlName="branch"
                (openedChange)="branchChanges($event)">
                  <mat-option *ngFor="let branch of branchs" [value]="branch.branch">
                    {{branch.branch}}
                  </mat-option>
                </mat-select>

                  Branch is required

              </mat-form-field>

                  <mat-form-field>
                      <mat-select [(ngModel)]="assignment.subject" [(ngModel)]="teacher.subject" name="subject"
                      formControlName="subject">
                        <mat-option *ngFor="let subject of subjects" [value]="subject.subject">
                            {{subject.subject}}
                        </mat-option>
                      </mat-select>

                        Branch is required

                    </mat-form-field>

                <input type="file" name="image" (change)="onFileSelect($event)" formControlName="image">

                  Branch is required

              <button type="submit" class="btn btn-primary" (click)="onUpload()" [disabled]="userform.invalid">Submit</button>
    </form>

        <app-check-assignment *ngIf="checkAssignment"
        [receivedFromTeacherAssignment]="recivedAssignment" [justMsg]="parentMsg"></app-check-assignment>

          <button class="btn btn-primary" (click)="onCheckAssignment()">check</button>

component.ts

import { Component, OnInit } from '@angular/core';
import { Teacher } from 'src/app/shared/teacher.model';
import { TeachersService } from '../teachers.service';
import { SharedService } from 'src/app/shared/shared.service';
import { FormGroup, FormControl, Validators } from '@angular/forms';

export interface Assignment {
  name: string,
  semester : number,
  branch: string,
  subject: string,
  image: string
}

@Component({
  selector: 'app-teacher-assignment',
  templateUrl: './teacher-assignment.component.html',
  styleUrls: ['./teacher-assignment.component.css']
})
export class TeacherAssignmentComponent implements OnInit {
  private teacher = Teacher
  private recivedAssignment : {name: string, assignment: string}
  semesters = []
  branchs = [];

  subjects = [];

  checkAssignment = false;
  parentMsg : string = '';
  assignment : Assignment = {
    name: "",
    semester: null,
    branch: "",
    subject: "",
    image: ""
  }

  assignmentUploadValidation = new FormGroup({

     semester: new FormControl('',
     [

       Validators.required
     ]),
     branch: new FormControl('',[
       Validators.required
     ]),
     subject: new FormControl('', [
       Validators.required
     ]),
     image: new FormControl('', [
       Validators.required
     ])
   })

  constructor(private teacherServ: TeachersService, private sharedServ: SharedService) {}

  ngOnInit() {
  }

  get validations() {
    return this.assignmentUploadValidation.controls;
  }

  onUpload() {
    const fd = new FormData();
    for( var key in this.assignment) {
      fd.append(key , this.assignment[key])
    }

    if(fd) {
      this.teacherServ.uploadAssignment(fd)
      .subscribe(
        res => console.log(res),
        err => console.log(err)
      )
    }

    console.log("assignment: ",this.assignment)
  }

  onCheckAssignment() {
    this.checkAssignment=!this.checkAssignment
    console.log("THis is assignment", this.assignment)
    this.parentMsg = "demos"
    this.teacherServ.checkAssignment(this.assignment)
    .subscribe(
      res => {
        this.recivedAssignment = res.result[0]
        console.log(this.recivedAssignment)
      },
      err => console.log(err)
    )
  }

}


问:
Transfering network data from R to Gephi
I have generated a microbial network based on microbial abundance correlation in R using igraph, hmisc and matrix packages. Now i want to work on it in Gephi. For that, I have to transfer my data to Gephi. I tried to prepare CSV file form this data but found this error:

Error in write_delim(x, path, delim = ",", na = na, append = append, col_names = col_names,  :
  is.data.frame(x) is not TRUE

Here is my complete code:

```<code>library(igraph)
library(Hmisc)
library(Matrix)
library(writexl)

otu.table <- read.csv(file.choose(), header = T, row.names = 1)
tax <- read.csv(file.choose(), header = T, row.names = 1)

dim(otu.table)
otu.table.filter <- otu.table[ ,colSums(otu.table) >= 0.1]
dim(tax)
otu.cor <- rcorr(as.matrix(otu.table), type="spearman", )

otu.pval <- forceSymmetric(otu.cor$P)
sel.tax <- tax[rownames(otu.pval),,drop=FALSE]
all.equal(rownames(sel.tax), rownames(otu.pval))
p.yes <- otu.pval<0.001

r.val = otu.cor$r>0.8 # select all the correlation values
p.yes.r <- r.val*p.yes
p.yes.r <- abs(p.yes.r)>0.8 # output is logical vector
p.yes.rr <- p.yes.r*r.val
adjm <- as.matrix(p.yes.rr)
colnames(adjm) <- as.vector(sel.tax$Phylum)
rownames(adjm) <- as.vector(sel.tax$Phylum)

net.grph=graph.adjacency(adjm,mode="undirected",weighted=TRUE,diag=FALSE)
edgew<-E(net.grph)$weight
V(net.grph)$color <- tax$Phylum
bad.vs<-V(net.grph)[degree(net.grph) == 0]

net.grph <-delete.vertices(net.grph, bad.vs)

plot(net.grph,
 vertex.size=8,
 vertex.frame.color="black",
 edge.curved=F,
 edge.width=edgew,
 layout=layout.fruchterman.reingold,
 edge.color=ifelse(edgew > 1,"red","blue"),
 vertex.label=NA,
 vertex.label.color="black",
 vertex.label.family="Times New Roman",
 vertex.label.font=0.1)

 write_csv(net.graph,"Documents\\R Analysis\\mydata.xlsx")
</code>```

Kindly tell me how do I transfer this data to Gephi?

答:
You should consider Cytoscape, which is far more efficient than Gephi (e.g., Cytoscape prompt you at the import of a big network with: "this is a very huge network, are you sure you want to plot that ?" vs. Gephi made you computer to freeze and crash with the same network).

In order to import your network in a program, you have to write the edges-list and (eventually) nodes-list on a csv or xls file. From an Igraph objet in you R environment, export your graph to a data.frame with: igraph::as_edgelist(some_igraph_network_objet, names = T), which return "a standard representation of a graph" aka edges-list (see https://igraph.org/r/doc/as_edgelist.html). Then write it on your machine, with some write.csv or some excel files (e.g., xlsx::write.xlsx). Same idea for nodeslist, if needed.

import that 'edges-list' or 'nodes-list' in your favorite network-analysis-program (Cytoscape only need a few indications for importing a graph from an excel edges-list, and show you some pop-up of your data: you see a sample of your data before importing). You could import a graph as an edges-list (csv or xls), in both cytoscape or in Gephi (e.g., tutorial to import edges-list.csv)

PS: If I miss the goal of 'convert from igraph to Gephi', according to this website, "Gephi has its own package, the rgexf package for R, that provides some support for creating Gephi styled graphs out of custom matrix/dataframe data" (you should take care of two columns, needed for each of your nodeslist and your edgeslist). This seems experimental but maybe useful in your case, see here and here.

Body:
I have generated a microbial network based on microbial abundance correlation in R using igraph, hmisc and matrix packages. Now i want to work on it in Gephi. For that, I have to transfer my data to Gephi. I tried to prepare CSV file form this data but found this error:

Error in write_delim(x, path, delim = ",", na = na, append = append, col_names = col_names,  :
  is.data.frame(x) is not TRUE

Here is my complete code:

library(igraph)
library(Hmisc)
library(Matrix)
library(writexl)

otu.table <- read.csv(file.choose(), header = T, row.names = 1)
tax <- read.csv(file.choose(), header = T, row.names = 1)

dim(otu.table)
otu.table.filter <- otu.table[ ,colSums(otu.table) >= 0.1]
dim(tax)
otu.cor <- rcorr(as.matrix(otu.table), type="spearman", )

otu.pval <- forceSymmetric(otu.cor$P)
sel.tax <- tax[rownames(otu.pval),,drop=FALSE]
all.equal(rownames(sel.tax), rownames(otu.pval))
p.yes <- otu.pval<0.001

r.val = otu.cor$r>0.8 # select all the correlation values
p.yes.r <- r.val*p.yes
p.yes.r <- abs(p.yes.r)>0.8 # output is logical vector
p.yes.rr <- p.yes.r*r.val
adjm <- as.matrix(p.yes.rr)
colnames(adjm) <- as.vector(sel.tax$Phylum)
rownames(adjm) <- as.vector(sel.tax$Phylum)

net.grph=graph.adjacency(adjm,mode="undirected",weighted=TRUE,diag=FALSE)
edgew<-E(net.grph)$weight
V(net.grph)$color <- tax$Phylum
bad.vs<-V(net.grph)[degree(net.grph) == 0]

net.grph <-delete.vertices(net.grph, bad.vs)

plot(net.grph,
 vertex.size=8,
 vertex.frame.color="black",
 edge.curved=F,
 edge.width=edgew,
 layout=layout.fruchterman.reingold,
 edge.color=ifelse(edgew > 1,"red","blue"),
 vertex.label=NA,
 vertex.label.color="black",
 vertex.label.family="Times New Roman",
 vertex.label.font=0.1)

 write_csv(net.graph,"Documents\\R Analysis\\mydata.xlsx")

Kindly tell me how do I transfer this data to Gephi?


问:
Swift: Hold code execution until API response received
I need to set up authorization screen:

1) Login and pass is inputted

2) App requests token from API

3) Response is received

4) App checks if response contains token: if contains, should perform authorization

PROBLEM TO SOLVE: app makes 4) before step 3)

What I tried: I used escaping closure in order to hold the execution until API data is received, but it helped only partially - it helped to hold only assignment of value to token, but I cannot hold 'if checks' still.

```<code>    override func shouldPerformSegue(withIdentifier identifier: String, sender: Any?) -> Bool {
    if identifier == "loginSegue" {

        let login = loginInput.text!
        let password = passInput.text!

        tokenLoader.getToken(login: login, password: password) { [weak self] token in
            self?.token = token.access_token
        }

        //THIS CODE I NEED TO HOLD UNTIL DATA FROM API RECEIVED
        if token != "" {
            return true
        } else {
            let alert = UIAlertController(title: nil, message: "Incorrect password", preferredStyle: .alert)
            let action = UIAlertAction(title: "OK", style: .cancel, handler: nil)
            alert.addAction(action)
            present(alert, animated: true, completion: nil)
            return false
        }
        //

    } else {
        return true
    }
}
</code>```

```<code>    class TokenLoader {
    let session = Session.instance
    let baseUrl = "http://46.254.18.193:9096"

    func getToken(login: String, password: String, completion: @escaping (AccessToken) -> Void) {
        let path = "/token"
        let parameters: Parameters = [
            "grant_type": "client_credentials",
            "client_id": login,
            "client_secret": password,
            "scope": "read"
        ]
        let url = baseUrl+path
        AF.request(url, method: .get, parameters: parameters).responseData { response in

            do {
                let token = try JSONDecoder().decode(AccessToken.self, from: response.value!)
                print(token)
                self.session.token = token.access_token
                completion(token)

            } catch {
                print(error)
            }
        }
    }
}
</code>```

答:
You can resolve the issue using this function ... perform it on event when you want to segue or to get token

```<code>func getTokenAndPerformSegue() {
    let login = loginInput.text
    let password = passInput.text

    if let getLogin = login ,let getPassword = password {

    tokenLoader.getToken(login: getLogin, password: getPassword) { [weak self] token in
           self?.token = token.access_token

        if token.isEmpty() {
            let alert = UIAlertController(title: nil, message: "Incorrect password", preferredStyle: .alert)
            let action = UIAlertAction(title: "OK", style: .cancel, handler: nil)
            alert.addAction(action)
            present(alert, animated: true, completion: nil)
        } else {
             performSegue(withIdentifier: "loginSegue", sender: nil)
        }

       }
    }

}
</code>```

you need to write it like this ... to return nil or error in completion

```<code> func getToken(login: String, password: String, completion: @escaping (AccessToken?) -> Void) {
        let path = "/token"
        let parameters: Parameters = [
            "grant_type": "client_credentials",
            "client_id": login,
            "client_secret": password,
            "scope": "read"
        ]
        let url = baseUrl+path
        AF.request(url, method: .get, parameters: parameters).responseData { response in

            do {
                let token = try JSONDecoder().decode(AccessToken.self, from: response.value!)
                print(token)
                self.session.token = token.access_token
                completion(token)

            } catch {
                completion(nil)
                print(error)
            }
        }
    }
</code>```

Let me know if you did not get anything or you need further help

Body:
I need to set up authorization screen:

1) Login and pass is inputted

2) App requests token from API

3) Response is received

4) App checks if response contains token: if contains, should perform authorization

PROBLEM TO SOLVE: app makes 4) before step 3)

What I tried: I used escaping closure in order to hold the execution until API data is received, but it helped only partially - it helped to hold only assignment of value to token, but I cannot hold 'if checks' still.

    override func shouldPerformSegue(withIdentifier identifier: String, sender: Any?) -> Bool {
    if identifier == "loginSegue" {

        let login = loginInput.text!
        let password = passInput.text!

        tokenLoader.getToken(login: login, password: password) { [weak self] token in
            self?.token = token.access_token
        }

        //THIS CODE I NEED TO HOLD UNTIL DATA FROM API RECEIVED
        if token != "" {
            return true
        } else {
            let alert = UIAlertController(title: nil, message: "Incorrect password", preferredStyle: .alert)
            let action = UIAlertAction(title: "OK", style: .cancel, handler: nil)
            alert.addAction(action)
            present(alert, animated: true, completion: nil)
            return false
        }
        //

    } else {
        return true
    }
}

    class TokenLoader {
    let session = Session.instance
    let baseUrl = "http://46.254.18.193:9096"

    func getToken(login: String, password: String, completion: @escaping (AccessToken) -> Void) {
        let path = "/token"
        let parameters: Parameters = [
            "grant_type": "client_credentials",
            "client_id": login,
            "client_secret": password,
            "scope": "read"
        ]
        let url = baseUrl+path
        AF.request(url, method: .get, parameters: parameters).responseData { response in

            do {
                let token = try JSONDecoder().decode(AccessToken.self, from: response.value!)
                print(token)
                self.session.token = token.access_token
                completion(token)

            } catch {
                print(error)
            }
        }
    }
}

Body:
You can resolve the issue using this function ... perform it on event when you want to segue or to get token

func getTokenAndPerformSegue() {
    let login = loginInput.text
    let password = passInput.text

    if let getLogin = login ,let getPassword = password {

    tokenLoader.getToken(login: getLogin, password: getPassword) { [weak self] token in
           self?.token = token.access_token

        if token.isEmpty() {
            let alert = UIAlertController(title: nil, message: "Incorrect password", preferredStyle: .alert)
            let action = UIAlertAction(title: "OK", style: .cancel, handler: nil)
            alert.addAction(action)
            present(alert, animated: true, completion: nil)
        } else {
             performSegue(withIdentifier: "loginSegue", sender: nil)
        }

       }
    }

}

you need to write it like this ... to return nil or error in completion

 func getToken(login: String, password: String, completion: @escaping (AccessToken?) -> Void) {
        let path = "/token"
        let parameters: Parameters = [
            "grant_type": "client_credentials",
            "client_id": login,
            "client_secret": password,
            "scope": "read"
        ]
        let url = baseUrl+path
        AF.request(url, method: .get, parameters: parameters).responseData { response in

            do {
                let token = try JSONDecoder().decode(AccessToken.self, from: response.value!)
                print(token)
                self.session.token = token.access_token
                completion(token)

            } catch {
                completion(nil)
                print(error)
            }
        }
    }

Let me know if you did not get anything or you need further help


问:
not able to connect to Database ( Postgresql in my case ) in loopback4
As soon I make an app from loopback 4 cli , while running commad npm run migrate after npm run build I am getting an error

```<code>Migrating schemas (alter existing schema)
Cannot migrate database schema Error: Timeout in connecting after 5000 ms
    at Timeout._onTimeout (/home/manthan/Desktop/temp/temp/node_modules/loopback-datasource-juggler/lib/datasource.js:2654:10)
    at listOnTimeout (internal/timers.js:549:17)
    at processTimers (internal/timers.js:492:7)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! temp@1.0.0 migrate: `node ./dist/migrate`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the temp@1.0.0 migrate script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/manthan/.npm/_logs/2020-05-22T06_41_17_958Z-debug.log
</code>```

Datasource config is correct and if i run same code on other system it runs pretty well as desired .

Package.json as follows

```<code>{
  "name": "temp",
  "version": "1.0.0",
  "description": "temp",
  "keywords": [
    "loopback-application",
    "loopback"
  ],
  "main": "dist/index.js",
  "types": "dist/index.d.ts",
  "engines": {
    "node": ">=10"
  },
  "scripts": {
    "build": "lb-tsc",
    "build:watch": "lb-tsc --watch",
    "lint": "npm run prettier:check && npm run eslint",
    "lint:fix": "npm run eslint:fix && npm run prettier:fix",
    "prettier:cli": "lb-prettier \"**/*.ts\" \"**/*.js\"",
    "prettier:check": "npm run prettier:cli -- -l",
    "prettier:fix": "npm run prettier:cli -- --write",
    "eslint": "lb-eslint --report-unused-disable-directives .",
    "eslint:fix": "npm run eslint -- --fix",
    "pretest": "npm run clean && npm run build",
    "test": "lb-mocha --allow-console-logs \"dist/__tests__\"",
    "posttest": "npm run lint",
    "test:dev": "lb-mocha --allow-console-logs dist/__tests__/**/*.js && npm run posttest",
    "docker:build": "docker build -t temp .",
    "docker:run": "docker run -p 3000:3000 -d temp",
    "migrate": "node ./dist/migrate",
    "prestart": "npm run build",
    "start": "node -r source-map-support/register .",
    "clean": "lb-clean dist *.tsbuildinfo .eslintcache"
  },
  "repository": {
    "type": "git"
  },
  "author": "",
  "license": "",
  "files": [
    "README.md",
    "dist",
    "src",
    "!*/__tests__"
  ],
  "dependencies": {
    "@loopback/boot": "^2.3.1",
    "@loopback/context": "^3.8.1",
    "@loopback/core": "^2.7.0",
    "@loopback/openapi-v3": "^3.4.1",
    "@loopback/repository": "^2.5.1",
    "@loopback/rest": "^5.0.1",
    "@loopback/rest-explorer": "^2.2.2",
    "@loopback/service-proxy": "^2.3.0",
    "loopback-connector-postgresql": "^3.9.1",
    "tslib": "^1.10.0"
  },
  "devDependencies": {
    "@loopback/build": "^5.4.1",
    "source-map-support": "^0.5.19",
    "@loopback/testlab": "^3.1.5",
    "@types/node": "^10.17.24",
    "@loopback/eslint-config": "^7.0.1",
    "eslint": "^7.0.0",
    "typescript": "~3.9.3"
  }
}

</code>```

答:
I had a similar issue recently and my problem was, on separate occasions, one of the following (in no particular order):

Database wasn't running

If DB was running

It was on the wrong IP and/or port (Mine was localhost:5432)

The DB creds were different on each system

The database name is different on each system

I would first ensure the DB is running through another tool (gui/terminal). I don't know what type of datasource you're using but if it's postgres use pgAdmin (it's free). If it's MySQL use phpMyAdmin. Once you know that the DB is actually running be sure to check that the credentials are not different.

So, you say "on other system it runs pretty well as desired", this tells me that you have some DB running on that system (A) with the correct credentials. If running this project on the other system (B) doesn't work you might not have a DB running there. If it is running you may not have access to the DB b/c it's the wrong port or wrong credentials

All of the above are just assumptions based on limited information. Having a servicefinder.datasource.ts file to look at (sanitized for security of course) would help diagnose the issue better if not the nature of the two systems from above.

let me know if this helps.

Body:
As soon I make an app from loopback 4 cli , while running commad npm run migrate after npm run build I am getting an error

Migrating schemas (alter existing schema)
Cannot migrate database schema Error: Timeout in connecting after 5000 ms
    at Timeout._onTimeout (/home/manthan/Desktop/temp/temp/node_modules/loopback-datasource-juggler/lib/datasource.js:2654:10)
    at listOnTimeout (internal/timers.js:549:17)
    at processTimers (internal/timers.js:492:7)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! temp@1.0.0 migrate: `node ./dist/migrate`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the temp@1.0.0 migrate script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/manthan/.npm/_logs/2020-05-22T06_41_17_958Z-debug.log

Datasource config is correct and if i run same code on other system it runs pretty well as desired .

Package.json as follows

{
  "name": "temp",
  "version": "1.0.0",
  "description": "temp",
  "keywords": [
    "loopback-application",
    "loopback"
  ],
  "main": "dist/index.js",
  "types": "dist/index.d.ts",
  "engines": {
    "node": ">=10"
  },
  "scripts": {
    "build": "lb-tsc",
    "build:watch": "lb-tsc --watch",
    "lint": "npm run prettier:check && npm run eslint",
    "lint:fix": "npm run eslint:fix && npm run prettier:fix",
    "prettier:cli": "lb-prettier \"**/*.ts\" \"**/*.js\"",
    "prettier:check": "npm run prettier:cli -- -l",
    "prettier:fix": "npm run prettier:cli -- --write",
    "eslint": "lb-eslint --report-unused-disable-directives .",
    "eslint:fix": "npm run eslint -- --fix",
    "pretest": "npm run clean && npm run build",
    "test": "lb-mocha --allow-console-logs \"dist/__tests__\"",
    "posttest": "npm run lint",
    "test:dev": "lb-mocha --allow-console-logs dist/__tests__/**/*.js && npm run posttest",
    "docker:build": "docker build -t temp .",
    "docker:run": "docker run -p 3000:3000 -d temp",
    "migrate": "node ./dist/migrate",
    "prestart": "npm run build",
    "start": "node -r source-map-support/register .",
    "clean": "lb-clean dist *.tsbuildinfo .eslintcache"
  },
  "repository": {
    "type": "git"
  },
  "author": "",
  "license": "",
  "files": [
    "README.md",
    "dist",
    "src",
    "!*/__tests__"
  ],
  "dependencies": {
    "@loopback/boot": "^2.3.1",
    "@loopback/context": "^3.8.1",
    "@loopback/core": "^2.7.0",
    "@loopback/openapi-v3": "^3.4.1",
    "@loopback/repository": "^2.5.1",
    "@loopback/rest": "^5.0.1",
    "@loopback/rest-explorer": "^2.2.2",
    "@loopback/service-proxy": "^2.3.0",
    "loopback-connector-postgresql": "^3.9.1",
    "tslib": "^1.10.0"
  },
  "devDependencies": {
    "@loopback/build": "^5.4.1",
    "source-map-support": "^0.5.19",
    "@loopback/testlab": "^3.1.5",
    "@types/node": "^10.17.24",
    "@loopback/eslint-config": "^7.0.1",
    "eslint": "^7.0.0",
    "typescript": "~3.9.3"
  }
}


问:
What are the benefits of using the real image height and width?
What are the benefits to using an images real height and width when rendering HTML?  That is if I have an image that 100x100 pixels but I want to display something that is 95x95 pixels, should I resize the image on the server or can I let the browser handle this?  I'm really looking for a general rule along with the reason.  Thanks.</p>

```<code><img src="image.jpg" style="width: 95px; height: 95px;" alt="an image" />
</code>```

答:
If you're always going to use the same height, it would make sense to resize it once beforehand - in as nice a way as possible - rather than getting everyone's browser to do it. After all, you can verify the results, make any tweaks you need, use the best software you can find and not worry about how long it takes to perform the resize etc.

On the other hand, I wouldn't expect the results to be very different visually, and unless you're talking about really slow computers (or a lot of images) it's probably not going to take up that much client CPU time. You may want to check the render time on slow mobile phones though, particularly if you're targeting mobile users.

ContentLicense: CC BY-SA 3.0


问:
how can get particular day of date when you have start and end date
I have a start date 4/10/2021 and end date 4/12/2021

I want get Tuesday, Thursday and Friday date in jquery

I found this solution:

```<code>var x = new Date();
//set the financial year starting date
x.setFullYear(2021, 10, 04);

//set the next financial year starting date
var y = new Date();
y.setFullYear(2021, 12, 04);
var j = 1;
var count = 0;

//getting the all fridays in a financial year
for ( var i = 0; x<y; i += j) {
    if (x.getDay() == 5) {
       $("#append_text").append("Date : " + x.getDate() + "/"
                        + (x.getMonth() + 1) + "<br>");
       x = new Date(x.getTime() + (7 * 24 * 60 * 60 * 1000));
       j = 7;
       count++;
    } else {
       j = 1;
       x = new Date(x.getTime() + (24 * 60 * 60 * 1000));
    }
}
$("#append_text").append("total fridays : " + count + "<br>");
</code>```

but it return only Friday and i think it doesn't work truly

The result is:

```<code>Date : 5/11
Date : 12/11
Date : 19/11
Date : 26/11
Date : 3/12
Date : 10/12
Date : 17/12
Date : 24/12
Date : 31/12
total fridays : 9
</code>```

The solution link is here:
Get Friday Dates of Year in javascript using jquery

do you have any solution for that?

答:
As mentioned in getDay() docs:

The getDay() method returns the day of the week for the specified date according to local time, where 0 represents Sunday.

So, clearly

```<code>if (x.getDay() == 5)
</code>```

5 here stands for Friday. So, if you also need Tuesday as 2 & Thursday as 4, you simply need to modify for loop like:

```<code>var day = x.getDay();
if (day === 2 || day === 4 || day === 5)
</code>```

Demo:

var x = new Date();
//set the financial year starting date
x.setFullYear(2021, 10, 04);

//set the next financial year starting date
var y = new Date();
y.setFullYear(2021, 12, 04);
var html = '';
var count = 0;

//getting the all fridays in a financial year
for (var i = 0; x < y; i++) {
  var day = x.getDay();
  if (day === 2 || day === 4 || day === 5) {
    html += "Date : " + x.getDate() + "/" + (x.getMonth() + 1) + "
";
    if (day === 5)count++;
  }
  x.setDate(x.getDate() + 1)
}
$("#append_text").append(html);
$("#append_text").append("total fridays : " + count + "
");```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id=append_text></div></code>```

Body:
I have a start date 4/10/2021 and end date 4/12/2021

I want get Tuesday, Thursday and Friday date in jquery

I found this solution:

var x = new Date();
//set the financial year starting date
x.setFullYear(2021, 10, 04);

//set the next financial year starting date
var y = new Date();
y.setFullYear(2021, 12, 04);
var j = 1;
var count = 0;

//getting the all fridays in a financial year
for ( var i = 0; x<y; i += j) {
    if (x.getDay() == 5) {
       $("#append_text").append("Date : " + x.getDate() + "/"
                        + (x.getMonth() + 1) + "
");
       x = new Date(x.getTime() + (7 * 24 * 60 * 60 * 1000));
       j = 7;
       count++;
    } else {
       j = 1;
       x = new Date(x.getTime() + (24 * 60 * 60 * 1000));
    }
}
$("#append_text").append("total fridays : " + count + "
");

but it return only Friday and i think it doesn't work truly

The result is:

Date : 5/11
Date : 12/11
Date : 19/11
Date : 26/11
Date : 3/12
Date : 10/12
Date : 17/12
Date : 24/12
Date : 31/12
total fridays : 9

The solution link is here:
Get Friday Dates of Year in javascript using jquery

do you have any solution for that?

Body:
As mentioned in getDay() docs:

The getDay() method returns the day of the week for the specified date according to local time, where 0 represents Sunday.

So, clearly

if (x.getDay() == 5)

5 here stands for Friday. So, if you also need Tuesday as 2 & Thursday as 4, you simply need to modify for loop like:

var day = x.getDay();
if (day === 2 || day === 4 || day === 5)

Demo:

var x = new Date();
//set the financial year starting date
x.setFullYear(2021, 10, 04);

//set the next financial year starting date
var y = new Date();
y.setFullYear(2021, 12, 04);
var html = '';
var count = 0;

//getting the all fridays in a financial year
for (var i = 0; x < y; i++) {
  var day = x.getDay();
  if (day === 2 || day === 4 || day === 5) {
    html += "Date : " + x.getDate() + "/" + (x.getMonth() + 1) + "<br>";
    if (day === 5)count++;
  }
  x.setDate(x.getDate() + 1)
}
$("#append_text").append(html);
$("#append_text").append("total fridays : " + count + "<br>");

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id=append_text></div>


问:
Why i can't access Data user in Session when in checkout page
I want to ask, what's wrong with the code that I made? I want to access the data of the user who is currently logged into the session so that it appears automatically filling out the checkout form. So users do not need to bother anymore to input data manually.

my checkout page error

I made it in native PHP, How to solve this? Thank you

This my checkout page COde

```<code><div class="col-md-8 order-md-1">
                    <h4 class="mb-3">Detail Pembayaran</h4>
                    <form method="post" action="akun.php?c_id=<?php echo $id_member; ?>" name="checkout" class="needs-validation" novalidate>
                        <?php
                           if (isset($_SESSION['user'])) {
                               $id_member = $_SESSION['user'];
                               $get_member = "SELECT * FROM tbluser where id_member = '$id_member'";
                               $run_member = mysqli_query($con,$get_member);
                               if ($row_member = mysqli_num_rows($run_member)>0) {
                                   $m_nama = $row_member['nama_member'];
                                   $m_username = $row_member['username_member'];
                                   $m_email = $row_member['email_member'];
                                   $m_alamat = $row_member['alamat_member'];

                               }
                           }
                         ?>
                        <div class="row">
                            <div class="col-md-12 mb-3">
                                <label >Nama Lengkap</label>
                                <input type="text" class="form-control" name="m_nama" value="<?php echo $m_nama ?>"
                                    disabled >
                                <div class="invalid-feedback">
                                    Nama Harus Valid.
                                </div>
                            </div>
                        </div>
                        <div class="mb-3">
                            <label>Username</label>
                            <div class="input-group">
                                <div class="input-group-prepend">
                                </div>
                                <input type="text" class="form-control" name="m_username" value="<?php echo $m_username ?>" disabled>
                                <div class="invalid-feedback" style="width: 100%;">
                                    username harus diisi.
                                </div>
                            </div>
                        </div>

                        <div class="mb-3">
                            <label>Email <span class="text-muted"></span></label>
                            <input type="email" class="form-control" value="<?php echo $m_email ?>" disabled>
                            <div class="invalid-feedback">
                                Email harus diisi.
                            </div>
                        </div>

                        <div class="mb-3">
                            <label for="address">Alamat</label>
                            <input type="text" class="form-control" value="<?php echo $m_alamat ?>" disabled>
                            <div class="invalid-feedback">
                                Alamat Harus diisi.
                            </div>
                        </div>
                        <hr class="mb-4">

                        <h4 class="mb-3">Pembayaran</h4>

                        <div class="d-block my-3">
                            <div class="custom-control custom-radio">
                                <input id="cash" name="paymentMethod" type="radio" class="custom-control-input" checked
                                    required>
                                <label class="custom-control-label" for="cash">Cash</label>
                            </div>
                            <div class="custom-control custom-radio">
                                <input id="transfer" name="paymentMethod" type="radio" class="custom-control-input"
                                    disabled>
                                <label class="custom-control-label" for="transfer">Transfer (Soon)</label>
                            </div>
                        </div>
                        <hr class="mb-4">
                        <input class="btn btn-primary btn-lg btn-block mb-5" type="submit" name="submit" value="Masukkan Ke
                            Keranjang">
                    </form>
</code>```

This is my Login page code(session declare)

```<code><?php
    session_start();
    if (isset($_SESSION["login"])) {
        header("Location: index-member.php");
    }

    include ("functions/functions.php");
    include ("inc/db.php");

    //cEK LOGIN TOMBOL SUDAH DI KLIK ATAU Belum
    if (isset($_POST["login"])) {
        $get_ip = getIpUser();
        $id_member = "select * from tbluser where id_member = '$get_ip'";
        $username_member = $_POST["m_username"];
        $password_member = $_POST["m_password"];

        $cek_username = mysqli_query($db, "SELECT * FROM tbluser WHERE username_member = '$username_member'");

        // Cek Username ada sama atau tidak
        if ( mysqli_num_rows($cek_username) === 1) {
            //CEK PASSWORD
            $row = mysqli_fetch_assoc($cek_username);
            if( password_verify($password_member, $row["password_member"]) ) {
                //Set Session
                $_SESSION["login"] = true;
                $_SESSION["user"] = $username_member;

                header("Location: index-member.php");
                exit;
            }
        }
        $error = true;
    }
 ?>

 <?php
</code>```

答:
You store the value of $_POST['m_username'] in $_SESSION['user'], but then query for id_member = $_SESSION['user']...

```<code>$get_ip = getIpUser();
$id_member = "select * from tbluser where id_member = '$get_ip'";
$username_member = $_POST["m_username"];
...

$_SESSION["user"] = $username_member;
</code>```

and

```<code>$id_member = $_SESSION['user'];
$get_member = "SELECT * FROM tbluser where id_member = '$id_member'";
</code>```

Body:
I want to ask, what's wrong with the code that I made? I want to access the data of the user who is currently logged into the session so that it appears automatically filling out the checkout form. So users do not need to bother anymore to input data manually.

my checkout page error

I made it in native PHP, How to solve this? Thank you

This my checkout page COde

Detail Pembayaran

                    <form method="post" action="akun.php?c_id=<?php echo $id_member; ?>" name="checkout" class="needs-validation" novalidate>
                        <?php
                           if (isset($_SESSION['user'])) {
                               $id_member = $_SESSION['user'];
                               $get_member = "SELECT * FROM tbluser where id_member = '$id_member'";
                               $run_member = mysqli_query($con,$get_member);
                               if ($row_member = mysqli_num_rows($run_member)>0) {
                                   $m_nama = $row_member['nama_member'];
                                   $m_username = $row_member['username_member'];
                                   $m_email = $row_member['email_member'];
                                   $m_alamat = $row_member['alamat_member'];

                               }
                           }
                         ?>

                                Nama Lengkap
                                <input type="text" class="form-control" name="m_nama" value="<?php echo $m_nama ?>"
                                    disabled >

                                    Nama Harus Valid.

                            Username

                                <input type="text" class="form-control" name="m_username" value="<?php echo $m_username ?>" disabled>

                                    username harus diisi.

                            Email
                            <input type="email" class="form-control" value="<?php echo $m_email ?>" disabled>

                                Email harus diisi.

                            Alamat
                            <input type="text" class="form-control" value="<?php echo $m_alamat ?>" disabled>

                                Alamat Harus diisi.

Pembayaran

                                <input id="cash" name="paymentMethod" type="radio" class="custom-control-input" checked
                                    required>
                                Cash

                                <input id="transfer" name="paymentMethod" type="radio" class="custom-control-input"
                                    disabled>
                                Transfer (Soon)

                        <input class="btn btn-primary btn-lg btn-block mb-5" type="submit" name="submit" value="Masukkan Ke
                            Keranjang">
                    </form>

This is my Login page code(session declare)

<?php
    session_start();
    if (isset($_SESSION["login"])) {
        header("Location: index-member.php");
    }

    include ("functions/functions.php");
    include ("inc/db.php");

    //cEK LOGIN TOMBOL SUDAH DI KLIK ATAU Belum
    if (isset($_POST["login"])) {
        $get_ip = getIpUser();
        $id_member = "select * from tbluser where id_member = '$get_ip'";
        $username_member = $_POST["m_username"];
        $password_member = $_POST["m_password"];

        $cek_username = mysqli_query($db, "SELECT * FROM tbluser WHERE username_member = '$username_member'");

        // Cek Username ada sama atau tidak
        if ( mysqli_num_rows($cek_username) === 1) {
            //CEK PASSWORD
            $row = mysqli_fetch_assoc($cek_username);
            if( password_verify($password_member, $row["password_member"]) ) {
                //Set Session
                $_SESSION["login"] = true;
                $_SESSION["user"] = $username_member;

                header("Location: index-member.php");
                exit;
            }
        }
        $error = true;
    }
 ?>

 <?php

Body:
You store the value of $_POST['m_username'] in $_SESSION['user'], but then query for id_member = $_SESSION['user']...

$get_ip = getIpUser();
$id_member = "select * from tbluser where id_member = '$get_ip'";
$username_member = $_POST["m_username"];
...

$_SESSION["user"] = $username_member;

and

$id_member = $_SESSION['user'];
$get_member = "SELECT * FROM tbluser where id_member = '$id_member'";


问:
Google chart Download and save PNG file
Here's my google pie chart. Right now, I can right click and save image as PNG.
However I need the image download to happen automatically on a specified folder when the page loads.

I tried various canvas options however couldn't get anything to work.

Download SVG as a PNG image

save google gauge chart as a png

Can someone help?

```<code><!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml"  xmlns:th="http://www.thymeleaf.org">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    </style>
    <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

    <script type="text/javascript">
        google.charts.load("current", {packages:['corechart']});
        google.charts.setOnLoadCallback(drawChart);

        function drawChart() {
            var data = google.visualization.arrayToDataTable([
                ['Task', 'Hours per Day'],
                ['Work',     11],
                ['Eat',      2],
                ['Commute',  2],
                ['Watch TV', 2],
                ['Sleep',    7]
            ]);
            var options = {
                    title: 'My Daily Activities',
                    is3D: true
            };
            var chart = new google.visualization.PieChart(document.getElementById('piechart_3d'));

          google.visualization.events.addListener(chart, 'ready', function () {
                piechart_3d.innerHTML = '<img src=' +  chart.getImageURI() + '>';
            });
            chart.draw(data, options);
        }
    </script>
</head>
<body>

    <div id="JSFiddle">
        <div id="piechart_3d" style="width: 1100px; height: 500px;"></div>
    </div>
</body>
</html>
</code>```

答:
You can achiev a download with the download html-attribute.

example:

```<code><a href="/image.png" download>
</code>```

To achiev that in your app do this:

add a download link

```<code><a id="download_link" href="/" download="">download</a>
</code>```

and change its href attribute as soon as the chart loaded

```<code>google.visualization.events.addListener(chart, 'ready', function () {
            piechart_3d.innerHTML = '<img id="chart" src=' + chart.getImageURI() + '>';
            document.getElementById("download_link").setAttribute("href", chart.getImageURI())
});
</code>```

if you want to download to happen automatically as soon as the page loaded:

make the a tag invisible

```<code><a style="display:none" id="download_link" href="/" download="">download</a>
</code>```

and fire a click event directly on it

```<code>document.getElementById("download_link").click();
</code>```

so the google.visualization.events.addListener function should look like this:

```<code>google.visualization.events.addListener(chart, 'ready', function () {
            piechart_3d.innerHTML = '<img id="chart" src=' + chart.getImageURI() + '>';
            document.getElementById("download_link").setAttribute("href", chart.getImageURI())
            document.getElementById("download_link").click();

 });
</code>```

the whole code should look like this: (auto-download)

```<code><!DOCTYPE html>
<html lang="en">

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    </style>
    <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>

<body>
    <div id="piechart_3d"></div>
    <a style="display:none" id="download_link" href="/" download>download</a>

</body>

<script>
    google.charts.load("current", { packages: ['corechart'] });
    google.charts.setOnLoadCallback(drawChart);

    function drawChart() {
        var data = google.visualization.arrayToDataTable([
            ['Task', 'Hours per Day'],
            ['Work', 11],
            ['Eat', 2],
            ['Commute', 2],
            ['Watch TV', 2],
            ['Sleep', 7]
        ]);
        var options = {
            title: 'My Daily Activities',
            is3D: true
        };
        var chart = new google.visualization.PieChart(document.getElementById('piechart_3d'));

        google.visualization.events.addListener(chart, 'ready', function () {
            piechart_3d.innerHTML = '<img id="chart" src=' + chart.getImageURI() + '>';
            document.getElementById("download_link").setAttribute("href", chart.getImageURI())
            document.getElementById("download_link").click();

        });
        chart.draw(data, options);
    }
</script>

</html>
</code>```

selecting a folder to put in the download is not possible (for security reasons)

Title: Google chart Download and save PNG file

Body:
Here's my google pie chart. Right now, I can right click and save image as PNG.
However I need the image download to happen automatically on a specified folder when the page loads.

I tried various canvas options however couldn't get anything to work.

Download SVG as a PNG image

save google gauge chart as a png

Can someone help?

<!DOCTYPE html>

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    </style>

Body:
You can achiev a download with the download html-attribute.

example:

<a href="/image.png" download>

To achiev that in your app do this:

add a download link

<a id="download_link" href="/" download="">download</a>

and change its href attribute as soon as the chart loaded

google.visualization.events.addListener(chart, 'ready', function () {
            piechart_3d.innerHTML = '<img id="chart" src=' + chart.getImageURI() + '>';
            document.getElementById("download_link").setAttribute("href", chart.getImageURI())
});

if you want to download to happen automatically as soon as the page loaded:

make the a tag invisible

<a style="display:none" id="download_link" href="/" download="">download</a>

and fire a click event directly on it

document.getElementById("download_link").click();

so the google.visualization.events.addListener function should look like this:

google.visualization.events.addListener(chart, 'ready', function () {
            piechart_3d.innerHTML = '<img id="chart" src=' + chart.getImageURI() + '>';
            document.getElementById("download_link").setAttribute("href", chart.getImageURI())
            document.getElementById("download_link").click();

 });

the whole code should look like this: (auto-download)

<!DOCTYPE html>
<html lang="en">

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    </style>
    <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>

<body>
    <div id="piechart_3d"></div>
    <a style="display:none" id="download_link" href="/" download>download</a>

</body>

<script>
    google.charts.load("current", { packages: ['corechart'] });
    google.charts.setOnLoadCallback(drawChart);

    function drawChart() {
        var data = google.visualization.arrayToDataTable([
            ['Task', 'Hours per Day'],
            ['Work', 11],
            ['Eat', 2],
            ['Commute', 2],
            ['Watch TV', 2],
            ['Sleep', 7]
        ]);
        var options = {
            title: 'My Daily Activities',
            is3D: true
        };
        var chart = new google.visualization.PieChart(document.getElementById('piechart_3d'));

        google.visualization.events.addListener(chart, 'ready', function () {
            piechart_3d.innerHTML = '<img id="chart" src=' + chart.getImageURI() + '>';
            document.getElementById("download_link").setAttribute("href", chart.getImageURI())
            document.getElementById("download_link").click();

        });
        chart.draw(data, options);
    }
</script>

</html>

selecting a folder to put in the download is not possible (for security reasons)


问:
problem with converting NSData to NSArray
Hi
I have a problem with converting NSData to NSArray

my code is:

```<code>NSData *data = [[NSData alloc] initWithBytes:(const void *)buf length:len];
NSArray *array = [NSKeyedUnarchiver unarchiveObjectWithData:data];
</code>```

can any one help me to do it.

答:
Use +[NSPropertyListSerialization dataWithPropertyList:format:options:error:] to convert the data, then check if the result -isKindOfClass:[NSArray class].

It will work :)

Body:
Hi
I have a problem with converting NSData to NSArray

my code is:

NSData *data = [[NSData alloc] initWithBytes:(const void *)buf length:len];
NSArray *array = [NSKeyedUnarchiver unarchiveObjectWithData:data];

can any one help me to do it.


问:
Python Using RandInt to Generate 3-Digit Pattern: Syntax Error
I'm reading a beginners text on Python Programming. And I'm getting a syntax error that, seemingly, is a typo in the text. The code is:

class LaserWeaponArmory(Scene):

    def enter(self):
        print(dedent("""
            You do a dive roll into the Weapon Armory, crouch and scan
            the room for more GOthon that might be hiding. It's dead
            quiet, too quiet.  You stand up and run to the far side of
            the room and find the neutron bomb in its container.
            There's a keypad lock on the box and you need the code to
            get the bomb out. If you get the code wrong 10 times then
            the lock closes forever and you can't get the bomb.  The
            code is 3 digits.
            """))

        code = f"{randint(1,9)}{randint(1,9)}{randint(1,9)}"
        guess = input("[keypad]> ")
        guesses = 0

        while guess != code and guesses <10:
            print("BZZZZEDDD!")
            guesses += 1
            guess = input("[keypad]> ")

        if guess == code:
            print(dedent("""
                The container clicks open and the seal breaks, letting
                gas out.  You grab the neutron bomb and run as fast as
                you can to the bridge where you must place it in the
                right spot.
                """))
            return 'the_bridge'
        else:
            print(dedent("""
                The lock buzzes one last time and then you hear a
                sickening melting sound as the mechanism is fused
                together.  You decide to sit there, and finally the
                Gothons blow up the ship from their ship and you die.
                """))
            return 'death'

```

<p>I'm getting the following error:</p>

```File "ex43.py", line 121
    code = f"{randint(1,9)}{randint(1,9)}{randint(1,9)}"
                                                       ^ SyntaxError: invalid syntax
```

So it seems to be trying to create a 3 digit pattern of random numbers?

答:
"randint" module is not imported. Add the following statement</p>

```<code>from random import randint
</code>```

Body:
I'm reading a beginners text on Python Programming. And I'm getting a syntax error that, seemingly, is a typo in the text. The code is:

class LaserWeaponArmory(Scene):

    def enter(self):
        print(dedent("""
            You do a dive roll into the Weapon Armory, crouch and scan
            the room for more GOthon that might be hiding. It's dead
            quiet, too quiet.  You stand up and run to the far side of
            the room and find the neutron bomb in its container.
            There's a keypad lock on the box and you need the code to
            get the bomb out. If you get the code wrong 10 times then
            the lock closes forever and you can't get the bomb.  The
            code is 3 digits.
            """))

        code = f"{randint(1,9)}{randint(1,9)}{randint(1,9)}"
        guess = input("[keypad]> ")
        guesses = 0

        while guess != code and guesses <10:
            print("BZZZZEDDD!")
            guesses += 1
            guess = input("[keypad]> ")

        if guess == code:
            print(dedent("""
                The container clicks open and the seal breaks, letting
                gas out.  You grab the neutron bomb and run as fast as
                you can to the bridge where you must place it in the
                right spot.
                """))
            return 'the_bridge'
        else:
            print(dedent("""
                The lock buzzes one last time and then you hear a
                sickening melting sound as the mechanism is fused
                together.  You decide to sit there, and finally the
                Gothons blow up the ship from their ship and you die.
                """))
            return 'death'

I'm getting the following error:

File "ex43.py", line 121
    code = f"{randint(1,9)}{randint(1,9)}{randint(1,9)}"
                                                       ^ SyntaxError: invalid syntax

So it seems to be trying to create a 3 digit pattern of random numbers?

Body:
"randint" module is not imported. Add the following statement

from random import randint


问:
Inserting link (from cell) as image in email
I'm trying to create an email for customers and embed an image that is linked to a site. The link will be different for each customer, but the link will always appear in the same cell (AH7).

The image is saved in "C:\Fake Folder\Fake SubFolder\image.png". I can upload the image online if it makes it easier/will be displayed consistently.

I can find bits and pieces of information but nothing that works all together.

```<code>Sub Mail_workbook_Outlook_1()

    Dim OutApp As Object
    Dim OutMail As Object
    Dim xStrBody As String
    xStrBody = "Hi" & ThisWorkbook.Sheets("Sheet1").Range("A1") _
      & "Please Click" & "<a href=" & ThisWorkbook.Sheets(Sheet1).Range(AH7) ">C:\Fake Folder\Fake SubFolder\image.png" "Thank you" & "<br>" _

    Set OutApp = CreateObject("Outlook.Application")
    Set OutMail = OutApp.CreateItem(0)

    On Error Resume Next
    With OutMail
        .To = ThisWorkbook.Sheets("Sheet1").Range(J1)
        .Subject = "Test Email"
        .HTMLBody = .HTLMBody & xStrBody
        .Display
    End With
    On Error GoTo 0

    Set OutMail = Nothing
    Set OutApp = Nothing
End Sub
</code>```

答:
You need to use html in the right way

```<code>Function FileNameFromPath(strFullPath As String) As String
    FileNameFromPath = Right(strFullPath, Len(strFullPath) - InStrRev(strFullPath, "\"))
End Function

Sub Mail_workbook_Outlook_test()

Dim OutApp As Object
Dim OutMail As Object
Dim imageFile As String
imageFile = "C:\Fake Folder\Fake SubFolder\image.png"

Dim fileName As String
fileName = FileNameFromPath(imageFile)

Dim xStrBody As Variant
    xStrBody = "<html><p>Hi " & ThisWorkbook.Sheets("Sheet1").Range("A1").Value _
          & "Please Click </p>" & "<a href=" & ThisWorkbook.Sheets("Sheet1").Range("AH7").Hyperlinks(1).Address _
          & "<img src=""" & fileName & """ height=520 width=750></a>" _
          & "<p>Thank you" & "<br></p>"

Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)

On Error Resume Next
With OutMail
    .to = ThisWorkbook.Sheets("Sheet1").Range("J1").Value
    .Subject = "Test Email"
    .attachments.Add imageFile, 1, 0
    .htmlBody = xStrBody
    .Display
End With
On Error GoTo 0

Set OutMail = Nothing
Set OutApp = Nothing
End Sub
</code>```

If you have the hyperlink address directly in cell AH7 you need to use .value instead of .Hyperlinks(1).Address for ThisWorkbook.Sheets("Sheet1").Range("AH7").Hyperlinks(1).Address. I also assumed that you several times did not add the quotes in the code of your original post.

Body:
I'm trying to create an email for customers and embed an image that is linked to a site. The link will be different for each customer, but the link will always appear in the same cell (AH7).

The image is saved in "C:\Fake Folder\Fake SubFolder\image.png". I can upload the image online if it makes it easier/will be displayed consistently.

I can find bits and pieces of information but nothing that works all together.

Sub Mail_workbook_Outlook_1()

    Dim OutApp As Object
    Dim OutMail As Object
    Dim xStrBody As String
    xStrBody = "Hi" & ThisWorkbook.Sheets("Sheet1").Range("A1") _
      & "Please Click" & "C:\Fake Folder\Fake SubFolder\image.png" "Thank you" & "
" _

    Set OutApp = CreateObject("Outlook.Application")
    Set OutMail = OutApp.CreateItem(0)

    On Error Resume Next
    With OutMail
        .To = ThisWorkbook.Sheets("Sheet1").Range(J1)
        .Subject = "Test Email"
        .HTMLBody = .HTLMBody & xStrBody
        .Display
    End With
    On Error GoTo 0

    Set OutMail = Nothing
    Set OutApp = Nothing
End Sub

Body:
You need to use html in the right way

Function FileNameFromPath(strFullPath As String) As String
    FileNameFromPath = Right(strFullPath, Len(strFullPath) - InStrRev(strFullPath, "\"))
End Function

Sub Mail_workbook_Outlook_test()

Dim OutApp As Object
Dim OutMail As Object
Dim imageFile As String
imageFile = "C:\Fake Folder\Fake SubFolder\image.png"

Dim fileName As String
fileName = FileNameFromPath(imageFile)

Dim xStrBody As Variant
    xStrBody = "<html><p>Hi " & ThisWorkbook.Sheets("Sheet1").Range("A1").Value _
          & "Please Click </p>" & "<a href=" & ThisWorkbook.Sheets("Sheet1").Range("AH7").Hyperlinks(1).Address _
          & "<img src=""" & fileName & """ height=520 width=750></a>" _
          & "<p>Thank you" & "<br></p>"

Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)

On Error Resume Next
With OutMail
    .to = ThisWorkbook.Sheets("Sheet1").Range("J1").Value
    .Subject = "Test Email"
    .attachments.Add imageFile, 1, 0
    .htmlBody = xStrBody
    .Display
End With
On Error GoTo 0

Set OutMail = Nothing
Set OutApp = Nothing
End Sub

If you have the hyperlink address directly in cell AH7 you need to use .value instead of .Hyperlinks(1).Address for ThisWorkbook.Sheets("Sheet1").Range("AH7").Hyperlinks(1).Address. I also assumed that you several times did not add the quotes in the code of your original post.


问:
How to calculate totals in dataframe by pandas
I have got this dataframe:

```<code>Date Trader1 Trader2 Trader3
01/04/2020  4   6   8
02/04/2020  4   6   8
03/04/2020  4   7   8
04/04/2020  4   7   8
05/04/2020  3   5   7
06/04/2020  2   4   7
07/04/2020  2   3   6
08/04/2020  3   3   6
09/04/2020  3   5   7
10/04/2020  3   5   7
11/04/2020  3   5   6
</code>```

I would like to get Totals for each column by using python/pandas library. When I apply a.loc['Total'] = pd.Series(a.sum()) I can get result as Totals for each column, but it also adds together values of Date column (dates). How can I calculate totals only for needed columns?

答:
```<code>data[['Trader1','Trader2','Trader3']].sum()
</code>```

I just saw your comment, There may be better ways, but  I think this should work

```<code>data[data.columns[1:]].sum()
</code>```

you have to provide the range in last line.

Body:
I have got this dataframe:

Date Trader1 Trader2 Trader3
01/04/2020  4   6   8
02/04/2020  4   6   8
03/04/2020  4   7   8
04/04/2020  4   7   8
05/04/2020  3   5   7
06/04/2020  2   4   7
07/04/2020  2   3   6
08/04/2020  3   3   6
09/04/2020  3   5   7
10/04/2020  3   5   7
11/04/2020  3   5   6

I would like to get Totals for each column by using python/pandas library. When I apply a.loc['Total'] = pd.Series(a.sum()) I can get result as Totals for each column, but it also adds together values of Date column (dates). How can I calculate totals only for needed columns?

Body:
data[['Trader1','Trader2','Trader3']].sum()

I just saw your comment, There may be better ways, but  I think this should work

data[data.columns[1:]].sum()

you have to provide the range in last line.


问:
how to use variables in maps or associative array in java
the problem:

i have 3 integer value.

```<code>integer val1 = 23 ;
integer val2 = 14 ;
integer val3 = 6;
</code>```

i need them to be associated with an IP. so i tried this.

```<code>Map<String, String> map = new HashMap<String, String>();
map.put("val1", "192.168.100.100");
map.put("val2", "192.168.100.101");
map.put("val3", "192.168.100.102");
</code>```

but it seems it doesn't store integers in map. when i tried this in my code:

```<code>  System.out.println(map.get("val1"));
</code>```

i got null as output.

my code:

my code is so long i can't paste here but i can explain some part of it. actually those 3 integers are random numbers so every time they are have different values.

```<code>  Random rand = new Random();
  int val1= rand.nextInt(101);
</code>```

then i need to associate them with IPs. then find the max integer and use its IP in the rest of code:

```<code>  int maxnum = Math.max(val3, Math.max(val1, val2));

  map.get(maxnum);
</code>```

how to solve the problem and achieve this?

答:
You want your integers to be the keys, but you built a Map where key type is String : Map<String, String> and as you see you provide "val1" as key whch is string, different of val1 the variable pointing here to an Integer

```<code>Integer val1 = 23 ;
Integer val2 = 14 ;
Integer val3 = 6;

Map<Integer, String> map = new HashMap<>();
map.put(val1, "192.168.100.100");
map.put(val2, "192.168.100.101");
map.put(val3, "192.168.100.102");

System.out.println(map.get(val1)); // "192.168.100.100"
System.out.println(map.get(23));   // "192.168.100.100"
</code>```

Body:
the problem:

i have 3 integer value.

integer val1 = 23 ;
integer val2 = 14 ;
integer val3 = 6;

i need them to be associated with an IP. so i tried this.

Map<String, String> map = new HashMap<String, String>();
map.put("val1", "192.168.100.100");
map.put("val2", "192.168.100.101");
map.put("val3", "192.168.100.102");

but it seems it doesn't store integers in map. when i tried this in my code:

  System.out.println(map.get("val1"));

i got null as output.

my code:

my code is so long i can't paste here but i can explain some part of it. actually those 3 integers are random numbers so every time they are have different values.

  Random rand = new Random();
  int val1= rand.nextInt(101);

then i need to associate them with IPs. then find the max integer and use its IP in the rest of code:

  int maxnum = Math.max(val3, Math.max(val1, val2));

  map.get(maxnum);

how to solve the problem and achieve this?

Body:
You want your integers to be the keys, but you built a Map where key type is String : Map<String, String> and as you see you provide "val1" as key whch is string, different of val1 the variable pointing here to an Integer

Integer val1 = 23 ;
Integer val2 = 14 ;
Integer val3 = 6;

Map<Integer, String> map = new HashMap<>();
map.put(val1, "192.168.100.100");
map.put(val2, "192.168.100.101");
map.put(val3, "192.168.100.102");

System.out.println(map.get(val1)); // "192.168.100.100"
System.out.println(map.get(23));   // "192.168.100.100"


问:
Unhide text files by java
I tried to hide and unhide a text file. I can hide only but when I tried to unhide, I get an error message.

```<code>        try {
            //Hide file;
            Process process = Runtime.getRuntime().exec("cmd.exe /c attrib +h test.txt");
            //wait for process to get over (i.e. for file hiding)
            process.waitFor();
        } catch (Exception e) {
            e.getMessage();
        }

        //Now, let's test whether file has been hidden or not
        boolean fileHidden = fileToBeHidden.isHidden();

        if (fileHidden) {
            System.out.println(fileName + " is hidden ");
        } else {
            System.out.println(fileName + " isn't hidden ");
        }
</code>```

this method hide file correctly but I couldn't unhide it again

答:
Try this for hide and unhide files.

```<code>import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class Test {

    public static void main(String[] args) {
        Test.fileProcess("test.txt", true);
        Test.fileProcess("test.txt", false);
    }

    public static void fileProcess(String fileName, boolean hide) {
        try {

            // you can change your full
            String filePath = System.getProperty("user.dir")
                    + File.separator
                    + "files"
                    + File.separator + fileName;

            File f = new File(filePath);
            if(!f.exists() && !f.isDirectory()) {
                System.out.println(fileName + " file is not exist ");
                return;
            }

            Path file = Paths.get(filePath);
            Files.setAttribute(file, "dos:hidden", hide);

            f = new File(filePath);

            boolean fileHidden = f.isHidden();
            if (fileHidden) {
                System.out.println(fileName + " is hidden ");
            } else {
                System.out.println(fileName + " isn't hidden ");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

</code>```

Output like this:

```<code>test.txt is hidden
test.txt isn't hidden
</code>```

Title: Unhide text files by java

Body:
I tried to hide and unhide a text file. I can hide only but when I tried to unhide, I get an error message.

        try {
            //Hide file;
            Process process = Runtime.getRuntime().exec("cmd.exe /c attrib +h test.txt");
            //wait for process to get over (i.e. for file hiding)
            process.waitFor();
        } catch (Exception e) {
            e.getMessage();
        }

        //Now, let's test whether file has been hidden or not
        boolean fileHidden = fileToBeHidden.isHidden();

        if (fileHidden) {
            System.out.println(fileName + " is hidden ");
        } else {
            System.out.println(fileName + " isn't hidden ");
        }

this method hide file correctly but I couldn't unhide it again

Body:
Try this for hide and unhide files.

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class Test {

    public static void main(String[] args) {
        Test.fileProcess("test.txt", true);
        Test.fileProcess("test.txt", false);
    }

    public static void fileProcess(String fileName, boolean hide) {
        try {

            // you can change your full
            String filePath = System.getProperty("user.dir")
                    + File.separator
                    + "files"
                    + File.separator + fileName;

            File f = new File(filePath);
            if(!f.exists() && !f.isDirectory()) {
                System.out.println(fileName + " file is not exist ");
                return;
            }

            Path file = Paths.get(filePath);
            Files.setAttribute(file, "dos:hidden", hide);

            f = new File(filePath);

            boolean fileHidden = f.isHidden();
            if (fileHidden) {
                System.out.println(fileName + " is hidden ");
            } else {
                System.out.println(fileName + " isn't hidden ");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

Output like this:

test.txt is hidden
test.txt isn't hidden


问:
DateTimeParse Exception
I am constantly getting an exception error in my code when parsing a date.
The Date looks like this:

```<code>Wed May 21 00:00:00 EDT 2008
</code>```

This is the code for trying to read it:

```<code>DateTimeFormatter formatter = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss zzz yyyy");
Property property = new Property();
property.setSale_date(LocalDateTime.parse(linesplit[8], formatter));
</code>```

Expected result: A LocalDateTime of 2008-05-21T00:00.

What I got instead:

Exception in thread "main" java.time.format.DateTimeParseException:
  Text 'Wed May 21 00:00:00 EDT 2008' could not be parsed at index 0

Am I doing this completely wrong?

答:
The devil is in the detail. You are basically doing it correctly, except:

You need to provide a locale for the formatter.

By parsing into a LocalDateTime you are losing information and possibly getting an unexpected result.

So I suggest:

```<code>    DateTimeFormatter formatter = DateTimeFormatter.ofPattern(
            "EEE MMM dd HH:mm:ss zzz yyyy", Locale.ROOT);

    String linesplit8 = "Wed May 21 00:00:00 EDT 2008";
    ZonedDateTime zdt = ZonedDateTime.parse(linesplit8, formatter);

    System.out.println(zdt);
</code>```

Output is:

2008-05-21T00:00-04:00[America/New_York]

Your string is in English. It looks like the output from Date.toString() (Date being the old-fashioned class used for times before Java 8). So it’s probably in English because that toString method always produced English output. So if your locale is not an English-speaking one, parsing is deemed to fail, and I believe this is the reason why it did. In this case it’s appropriate to use Locale.ROOT for the locale neutral English-speaking locale. A way to say “don’t apply any locale specific processing here”.

Your string contains a time zone abbreviation, EDT, which is part of identifying a unique point in time, so you will want to pick up this part of the information too. Therefore use a ZonedDateTime.

Links

There are some related/similar questions, for example:

how to parse output of new Date().toString()

java DateTimeFormatterBuilder fails on testtime

How do I Date format for dd MMM yyyy, as in 01 Apr 2020 [duplicate]

Title: DateTimeParse Exception

Body:
I am constantly getting an exception error in my code when parsing a date.
The Date looks like this:

Wed May 21 00:00:00 EDT 2008

This is the code for trying to read it:

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss zzz yyyy");
Property property = new Property();
property.setSale_date(LocalDateTime.parse(linesplit[8], formatter));

Expected result: A LocalDateTime of 2008-05-21T00:00.

What I got instead:

Exception in thread "main" java.time.format.DateTimeParseException:
  Text 'Wed May 21 00:00:00 EDT 2008' could not be parsed at index 0

Am I doing this completely wrong?

Body:
The devil is in the detail. You are basically doing it correctly, except:

You need to provide a locale for the formatter.

By parsing into a LocalDateTime you are losing information and possibly getting an unexpected result.

So I suggest:

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern(
            "EEE MMM dd HH:mm:ss zzz yyyy", Locale.ROOT);

    String linesplit8 = "Wed May 21 00:00:00 EDT 2008";
    ZonedDateTime zdt = ZonedDateTime.parse(linesplit8, formatter);

    System.out.println(zdt);

Output is:

2008-05-21T00:00-04:00[America/New_York]

Your string is in English. It looks like the output from Date.toString() (Date being the old-fashioned class used for times before Java 8). So it’s probably in English because that toString method always produced English output. So if your locale is not an English-speaking one, parsing is deemed to fail, and I believe this is the reason why it did. In this case it’s appropriate to use Locale.ROOT for the locale neutral English-speaking locale. A way to say “don’t apply any locale specific processing here”.

Your string contains a time zone abbreviation, EDT, which is part of identifying a unique point in time, so you will want to pick up this part of the information too. Therefore use a ZonedDateTime.

Links

There are some related/similar questions, for example:

how to parse output of new Date().toString()

java DateTimeFormatterBuilder fails on testtime

How do I Date format for dd MMM yyyy, as in 01 Apr 2020 [duplicate]


问:
Multiple people using a VBA userform on a common Database
So, my requirements need me to distribute a VBA userform excel file to different people in my organization, and a single database file which will be kept in a network drive (or any other shared location).
I have tested it and it works fine. To save the entry, it downloads the database from network location, saves the inputs from userform and then closes back the file.
My only concern is that what if multiple people are filling the userform at the same time and pressing the submit button. Will all the information get recorded on database or some entries might get lost?

Please guide me on this, and suggest me any thing that needs to be done.

答:
Use the Workbook.ReadOnly Properrty</p>

```<code> Dim dBook As Workbook, daWas As Variant

 ' First Switch Off Display Alerts
   daWas = Application.DisplayAlerts
   Application.DisplayAlerts = False
 ' Done

 ' Open & Check the Database Workbook
   Set dBook = Workbooks.Open("YourDatabaseWorkbook.xlsm")
   If dBook.ReadOnly Then
      dBook.Close False
      MsgBox "Database in Use - Retry Later"
   Else
      ' Write to dBook, Save & Close it
   End If
 ' Done

 ' RESET DisplayAlerts
   Application.DisplayAlerts = daWas
 ' Done
</code>```

Body:
Use the Workbook.ReadOnly Properrty

 Dim dBook As Workbook, daWas As Variant

 ' First Switch Off Display Alerts
   daWas = Application.DisplayAlerts
   Application.DisplayAlerts = False
 ' Done

 ' Open & Check the Database Workbook
   Set dBook = Workbooks.Open("YourDatabaseWorkbook.xlsm")
   If dBook.ReadOnly Then
      dBook.Close False
      MsgBox "Database in Use - Retry Later"
   Else
      ' Write to dBook, Save & Close it
   End If
 ' Done

 ' RESET DisplayAlerts
   Application.DisplayAlerts = daWas
 ' Done


问:
missing BEFORE, AFTER or INSTEAD OF keyword Oracle trigger Error
Everytime I run this trigger it gives this error:
ORA-04071: missing BEFORE, AFTER or INSTEAD OF keyword

```<code>    create or replace trigger raise_error
    on CLIENT_PREFERENCE
    instead of insert
    for each row
    declare
    v_cid number;
     v_acid number;
     v_con varchar2(20);
      v_actname varchar2(20)
     begin
    select inserted.ClientNo,inserted.ActivityID into v_cid, v_acid
    from inserted

   select condition into v_con
   from CCONDITION
   where ccondition.clientno=v_cid

   select Actname into v_actname
   from Activity
    where ActivityID=v_acid

   if v_con='Aquaphobia' and v_actname='Rafting'
    then
   print('ERROR!!!')
    end if;
    end
</code>```

Relational Schema:

```<code>    CLIENT (ClientNo, Name, Sex, DOB, Address, Phone, Email, Occupation, MaritalStatus, Spouse, Anniversary)
    CCONDITION (ClientNo, Condition)
    RESERVATION (ResNo, ResDate, NoOfGuests, StartDate, EndDate, ClientNo, Status)
    ACTIVITY (ActivityID, ActName, ActDescription, ActRate, RiskLevel)
    OUTDOOR_ACTIVITY (ActivityID)
    INDOOR_ACTIVITY (ActivityID, Location, OpeningHours)
    ACCOMMODATION (RoomNo, LevelNo, AccStatus, ConnectedRoomNo, AccTypeID)
    ACCOMMODATION_TYPE (AccTypeID, AccTypeName, AccTypeRate, NoOfBeds)
    EQUIPMENT (EquipmentID, EquipName, Stock, NextInspection)
    SUPPLIER (BillerCode, BusinessName, ContactPerson, Phone)
    SUPPLIES (EquipmentID, BillerCode)
    USES_EQUIPMENT (ActivityID, EquipmentID) CLIENT_PREFERENCE (ClientNo, ActivityID)
</code>```

Question:

A Trigger which automatically raises an error whenever a client with Aqua phobia selects Rafting as a preferred outdoor activity.

答:
Check the right syntax using CREATE TRIGGER syntax

You are missing BEFORE/AFTER and INSERT/UPDATE/DELETE clauses:

```<code>create or replace trigger rasie_error
    "BEFORE | AFTER " "INSERT | UPDATE | DELETE"
    on CLIENT_PREFERENCE
</code>```

Body:
Everytime I run this trigger it gives this error:
ORA-04071: missing BEFORE, AFTER or INSTEAD OF keyword

    create or replace trigger raise_error
    on CLIENT_PREFERENCE
    instead of insert
    for each row
    declare
    v_cid number;
     v_acid number;
     v_con varchar2(20);
      v_actname varchar2(20)
     begin
    select inserted.ClientNo,inserted.ActivityID into v_cid, v_acid
    from inserted

   select condition into v_con
   from CCONDITION
   where ccondition.clientno=v_cid

   select Actname into v_actname
   from Activity
    where ActivityID=v_acid

   if v_con='Aquaphobia' and v_actname='Rafting'
    then
   print('ERROR!!!')
    end if;
    end

Relational Schema:

    CLIENT (ClientNo, Name, Sex, DOB, Address, Phone, Email, Occupation, MaritalStatus, Spouse, Anniversary)
    CCONDITION (ClientNo, Condition)
    RESERVATION (ResNo, ResDate, NoOfGuests, StartDate, EndDate, ClientNo, Status)
    ACTIVITY (ActivityID, ActName, ActDescription, ActRate, RiskLevel)
    OUTDOOR_ACTIVITY (ActivityID)
    INDOOR_ACTIVITY (ActivityID, Location, OpeningHours)
    ACCOMMODATION (RoomNo, LevelNo, AccStatus, ConnectedRoomNo, AccTypeID)
    ACCOMMODATION_TYPE (AccTypeID, AccTypeName, AccTypeRate, NoOfBeds)
    EQUIPMENT (EquipmentID, EquipName, Stock, NextInspection)
    SUPPLIER (BillerCode, BusinessName, ContactPerson, Phone)
    SUPPLIES (EquipmentID, BillerCode)
    USES_EQUIPMENT (ActivityID, EquipmentID) CLIENT_PREFERENCE (ClientNo, ActivityID)

Question:

A Trigger which automatically raises an error whenever a client with Aqua phobia selects Rafting as a preferred outdoor activity.

Body:
Check the right syntax using CREATE TRIGGER syntax

You are missing BEFORE/AFTER and INSERT/UPDATE/DELETE clauses:

create or replace trigger rasie_error
    "BEFORE | AFTER " "INSERT | UPDATE | DELETE"
    on CLIENT_PREFERENCE


问:
How to Achieve Smooth Scrolling When Using SingleChildScrollView and Wrap Widget with a Lot of Children?
I am using a Wrap widget to wrap a bunch of cards and sometime the number of cards are high and causing the scroll to be unsmooth and sometime the app stop if the cards has images. The Wrap allows dynamic behavior across different devices size. Is there any way to solve this problem. I am wondering if I can build only the shown cards and not burden the memory with the other cards.? How to ensure smooth scrolling?</p>

```<code>       SingleChildScrollView(
            child: Center(
              child: Container(
                width: devWidth,
                margin: EdgeInsets.only(top: 15, bottom: 15),
                child: Wrap(
                    alignment: WrapAlignment.spaceEvenly,
                    runSpacing: devWidth * 0.03,
                    children: myList.map<Widget>((item) {
                      return itemCard(item);
                    }).toList()),
              ),
            ),
          )
</code>```

答:
you should use ListView.seperated() instead of Wrap

```<code>ListView.separated(
    itemCount: myList.length,
    separatorBuilder: (BuildContext Context, int index) {
       return SizedBox(height: devWidth * 0.03);
    },
    itemBuilder: (BuildContext context, int index) {
       return itemCard(myList[index]);
    },
)
</code>```

for using multiple items per row use code below:

```<code>ListView.separated(
    itemCount: myList.length / 3,
    separatorBuilder: (BuildContext Context, int index) {
       return SizedBox(height: devWidth * 0.03);
    },
    itemBuilder: (BuildContext context, int index) {
    int idx = index * 3;
           return Row(
              children : <Widget>[
                  itemCard(myList[idx]),
                  itemCard(myList[idx + 1]),
                  itemCard(myList[idx + 2])
              ]
           );
    },
)
</code>```

Body:
I am using a Wrap widget to wrap a bunch of cards and sometime the number of cards are high and causing the scroll to be unsmooth and sometime the app stop if the cards has images. The Wrap allows dynamic behavior across different devices size. Is there any way to solve this problem. I am wondering if I can build only the shown cards and not burden the memory with the other cards.? How to ensure smooth scrolling?

       SingleChildScrollView(
            child: Center(
              child: Container(
                width: devWidth,
                margin: EdgeInsets.only(top: 15, bottom: 15),
                child: Wrap(
                    alignment: WrapAlignment.spaceEvenly,
                    runSpacing: devWidth * 0.03,
                    children: myList.map<Widget>((item) {
                      return itemCard(item);
                    }).toList()),
              ),
            ),
          )

Body:
you should use ListView.seperated() instead of Wrap

ListView.separated(
    itemCount: myList.length,
    separatorBuilder: (BuildContext Context, int index) {
       return SizedBox(height: devWidth * 0.03);
    },
    itemBuilder: (BuildContext context, int index) {
       return itemCard(myList[index]);
    },
)

for using multiple items per row use code below:

ListView.separated(
    itemCount: myList.length / 3,
    separatorBuilder: (BuildContext Context, int index) {
       return SizedBox(height: devWidth * 0.03);
    },
    itemBuilder: (BuildContext context, int index) {
    int idx = index * 3;
           return Row(
              children : <Widget>[
                  itemCard(myList[idx]),
                  itemCard(myList[idx + 1]),
                  itemCard(myList[idx + 2])
              ]
           );
    },
)


问:
Common BreakPoints for Reponsive Design
What are some common Breakpoints to achieve the responsive layout for web pages

I use basically

@media screen and (max-width: 480px) {
}

@media screen and (min-resolution: 150dpi) {
}

@media screen and (max-resolution: 300dpi) {
}

@media screen and (min-width: 150px) {
}

@media screen and (min-height: 100px){
}

@media screen and (max-height: 450px) {
}
```

I'm using above mentioned breakpoints but could not achieve complete responsive layout

答:
Major Breakpoints

As a developer we need to adapt  design to three type of device (mobile, tablet, and desktop). You should use at least 3breakpoints for the most device flexibility.
Following are some major breakpoints

These breakpoints i mostly use:

0 - 600px: Phone

600 - 900px:    Tablet portrait

900 - 1200px:   Tablet landscape

[1200 - 1800] is where our normal styles apply

1800px + :     Big desktop

Visit to see statistics, these are the 6 most common screen sizes

Title: Common BreakPoints for Reponsive Design

Body:
What are some common Breakpoints to achieve the responsive layout for web pages

I use basically

@media screen and (max-width: 480px) {
}

@media screen and (min-resolution: 150dpi) {
}

@media screen and (max-resolution: 300dpi) {
}

@media screen and (min-width: 150px) {
}

@media screen and (min-height: 100px){
}

@media screen and (max-height: 450px) {
}

I'm using above mentioned breakpoints but could not achieve complete responsive layout


问:
Some problem in mongo update when the $in with upsert
The code:

```<code>      let newArray = ['test','when','mongo'];
      db.collection('test').update(
        { keyword: { $in: newArray } },
        { $inc: { search_num: 1 } },
        {
            upsert: true,
            multi: true,
        })
</code>```

i want to upsert like :

```<code>{keyword:"test",search_num:1},
{keyword:"when",search_num:1},
{keyword:"mongo",search_num:1}
</code>```

but it only insert :

```<code>{search_num:1}
</code>```

How can I insert the keyword foreach in the $in query array?

答:
Just a small work around, you can try this

```<code> let newArray = ['test','when','mongo'];

 newArray.forEach(element => {
    db.collection('test').update(
        { keyword: element },
        { keyword: element,
          search_num: 1},
        {upsert: true }
     )
 });
</code>```

Hope this helps.

Body:
The code:

      let newArray = ['test','when','mongo'];
      db.collection('test').update(
        { keyword: { $in: newArray } },
        { $inc: { search_num: 1 } },
        {
            upsert: true,
            multi: true,
        })

i want to upsert like :

{keyword:"test",search_num:1},
{keyword:"when",search_num:1},
{keyword:"mongo",search_num:1}

but it only insert :

{search_num:1}

How can I insert the keyword foreach in the $in query array?

Body:
Just a small work around, you can try this

 let newArray = ['test','when','mongo'];

 newArray.forEach(element => {
    db.collection('test').update(
        { keyword: element },
        { keyword: element,
          search_num: 1},
        {upsert: true }
     )
 });

Hope this helps.


问:
problem in accessing public server
I'm working on android platform and am facing some problem in fetching data from public server. The same application works well for local server. So let me know if there are any changes in eclipse setting or some other solution.

Thank you.

答:
I think it will be hard to answer without additional information.
Any chance for seeing some code?
What exactly are you trying to do?

Anyway, if it works locally, sounds like N/W problems. Can you ping the remote server?

Title: problem in accessing public server