问:
npm install error - MSB3428: Could not load the Visual C++ component "VCBuild.exe"
I'm trying to use the

```<code>npm install steam
</code>```

but I am getting an error saying

I'm not sure how to fix this and I have gotten this on two different npm module installs. I can install other modules however.

What I have tried:
Install whatever dependencies it needs. (ursa, node-gyp etc)
Install Visual C++ 2005.
Install Visual C++ 2010.
Change the enviroment variable path to /VC/ (found on another StackOverflow thread/question.
Googled, googled & googled.

I also get an error trying do:

```<code>npm install ursa
</code>```

The error is:

答:
For those the above answer does not work, here is another possible solution to look at.

Issue:
On installing npm os-service package i was getting below error
error MSB4019: The imported project "d:\M icrosoft.Cpp.Default.props" was not found. Confirm that the path in the  declaration is correct

Even the installation of build tools or VS 2015 did not work for me. So I tried installing below directly via PowerShell (as admin)

https://chocolatey.org/packages/visualcpp-build-tools/14.0.25420.1
Command:
choco install visualcpp-build-tools --version 14.0.25420.1

Once this was installed, set an environment variable
VCTargetsPath=C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\v140

Then installation of the package worked perfectly fine after these.

Body:
I'm trying to use the

npm install steam

but I am getting an error saying

I'm not sure how to fix this and I have gotten this on two different npm module installs. I can install other modules however.

What I have tried:
Install whatever dependencies it needs. (ursa, node-gyp etc)
Install Visual C++ 2005.
Install Visual C++ 2010.
Change the enviroment variable path to /VC/ (found on another StackOverflow thread/question.
Googled, googled & googled.

I also get an error trying do:

npm install ursa

The error is:


来源: stackexchange

问:
How to run a dynamically linked executable syscall emulation mode se.py in gem5?
After How to solve "FATAL: kernel too old" when running gem5 in syscall emulation SE mode? I managed to run a statically linked hello world under certain conditions.

But if I try to run an ARM dynamically linked one against the stdlib with:

```<code>./out/common/gem5/build/ARM/gem5.opt ./gem5/gem5/configs/example/se.py -c ./a.out
</code>```

it fails with:

```<code>fatal: Unable to open dynamic executable's interpreter.
</code>```

How to make it find the interpreter? Hopefully without copying my cross' toolchain's interpreter on my host's root.

For x86_64 it works if I use my native compiler, and as expected strace says that it is using the native interpreter, but it does not work if I use a cross compiler.

The current FAQ says it is not possible to use dynamic executables: http://gem5.org/Frequently_Asked_Questions but I don't trust it, and then these presentations mention it:

http://www.gem5.org/wiki/images/0/0c/2015_ws_08_dynamic-linker.pdf

http://research.cs.wisc.edu/multifacet/papers/learning_gem5_tutorial.pdf

but not how to actually use it.

QEMU user mode has the -L option for that.

Tested in gem5 49f96e7b77925837aa5bc84d4c3453ab5f07408e

https://www.mail-archive.com/gem5-users@gem5.org/msg15582.html

答:
The cross-compiled binary should have an .interp entry if it's a dynamic executable.

Verify it with readelf:

```<code> readelf -a $bin_name | grep interp
</code>```

The simulator is setup to find this section in main executable when it loads the executable into the simulated address space. If this sections exists, a c-string is set to point to that text (normally something like /lib64/ld-linux-x86-64.so.2). The simulator then calls glibc's open function with that c-string as the parameter. Effectively, this opens the dynamic linker-loader for the simulator as a normal file. The simulator then maps the file into the simulated address space in phases with mmap and mmap_fixed.

For cross compilation, this code must fail. The error message follows it directly if the simulator cannot open the file. To make this work, you need to debug the opening process and possibly the subsequent pasting of the loader into the address space. There is mechanism to set the program's entry point into the loader rather than directly into the code section of the main binary. (It's done through the auxiliary vector on the stack.) You may need to play around with that as well.

The interesting code is (as of 05/29/19) in src/base/loader/elf_object.cc.

ContentLicense: CC BY-SA 4.0

Body:
After How to solve "FATAL: kernel too old" when running gem5 in syscall emulation SE mode? I managed to run a statically linked hello world under certain conditions.

But if I try to run an ARM dynamically linked one against the stdlib with:

./out/common/gem5/build/ARM/gem5.opt ./gem5/gem5/configs/example/se.py -c ./a.out

it fails with:

fatal: Unable to open dynamic executable's interpreter.

How to make it find the interpreter? Hopefully without copying my cross' toolchain's interpreter on my host's root.

For x86_64 it works if I use my native compiler, and as expected strace says that it is using the native interpreter, but it does not work if I use a cross compiler.

The current FAQ says it is not possible to use dynamic executables: http://gem5.org/Frequently_Asked_Questions but I don't trust it, and then these presentations mention it:

http://www.gem5.org/wiki/images/0/0c/2015_ws_08_dynamic-linker.pdf

http://research.cs.wisc.edu/multifacet/papers/learning_gem5_tutorial.pdf

but not how to actually use it.

QEMU user mode has the -L option for that.

Tested in gem5 49f96e7b77925837aa5bc84d4c3453ab5f07408e

https://www.mail-archive.com/gem5-users@gem5.org/msg15582.html

Body:
The cross-compiled binary should have an .interp entry if it's a dynamic executable.

Verify it with readelf:

 readelf -a $bin_name | grep interp

The simulator is setup to find this section in main executable when it loads the executable into the simulated address space. If this sections exists, a c-string is set to point to that text (normally something like /lib64/ld-linux-x86-64.so.2). The simulator then calls glibc's open function with that c-string as the parameter. Effectively, this opens the dynamic linker-loader for the simulator as a normal file. The simulator then maps the file into the simulated address space in phases with mmap and mmap_fixed.

For cross compilation, this code must fail. The error message follows it directly if the simulator cannot open the file. To make this work, you need to debug the opening process and possibly the subsequent pasting of the loader into the address space. There is mechanism to set the program's entry point into the loader rather than directly into the code section of the main binary. (It's done through the auxiliary vector on the stack.) You may need to play around with that as well.

The interesting code is (as of 05/29/19) in src/base/loader/elf_object.cc.


问:
How to get all enum values as an array
I have the following enum.

```<code>enum EstimateItemStatus: Printable {
    case Pending
    case OnHold
    case Done

    var description: String {
        switch self {
        case .Pending: return "Pending"
        case .OnHold: return "On Hold"
        case .Done: return "Done"
        }
    }

    init?(id : Int) {
        switch id {
        case 1:
            self = .Pending
        case 2:
            self = .OnHold
        case 3:
            self = .Done
        default:
            return nil
        }
    }
}
</code>```

I need to get all the raw values as an array of strings (like so ["Pending", "On Hold", "Done"]).

I added this method to the enum.

```<code>func toArray() -> [String] {
    var n = 1
    return Array(
        GeneratorOf<EstimateItemStatus> {
            return EstimateItemStatus(id: n++)!.description
        }
    )
}
</code>```

But I'm getting the following error.

Cannot find an initializer for type 'GeneratorOf' that accepts an argument list of type '(() -> _)'

Is there is an easier, better or more elegant way to do this?

答:
Update for Swift 5

Easiest solution I've found is to use .allCases on an enum that extends CaseIterable

```<code>enum EstimateItemStatus: CaseIterable {
    case Pending
    case OnHold
    case Done

    var description: String {
        switch self {
        case .Pending: return "Pending"
        case .OnHold: return "On Hold"
        case .Done: return "Done"
        }
    }

    init?(id : Int) {
        switch id {
        case 1:
            self = .Pending
        case 2:
            self = .OnHold
        case 3:
            self = .Done
        default:
            return nil
        }
    }
}
</code>```

.allCases on any CaseIterable enum will return a Collection of that element.

```<code>var myEnumArray = EstimateItemStatus.allCases
</code>```

more info about CaseIterable

Title: How to get all enum values as an array

Body:
I have the following enum.

enum EstimateItemStatus: Printable {
    case Pending
    case OnHold
    case Done

    var description: String {
        switch self {
        case .Pending: return "Pending"
        case .OnHold: return "On Hold"
        case .Done: return "Done"
        }
    }

    init?(id : Int) {
        switch id {
        case 1:
            self = .Pending
        case 2:
            self = .OnHold
        case 3:
            self = .Done
        default:
            return nil
        }
    }
}

I need to get all the raw values as an array of strings (like so ["Pending", "On Hold", "Done"]).

I added this method to the enum.

func toArray() -> [String] {
    var n = 1
    return Array(
        GeneratorOf<EstimateItemStatus> {
            return EstimateItemStatus(id: n++)!.description
        }
    )
}

But I'm getting the following error.

Cannot find an initializer for type 'GeneratorOf' that accepts an argument list of type '(() -> _)'

Is there is an easier, better or more elegant way to do this?

Body:
Update for Swift 5

Easiest solution I've found is to use .allCases on an enum that extends CaseIterable

enum EstimateItemStatus: CaseIterable {
    case Pending
    case OnHold
    case Done

    var description: String {
        switch self {
        case .Pending: return "Pending"
        case .OnHold: return "On Hold"
        case .Done: return "Done"
        }
    }

    init?(id : Int) {
        switch id {
        case 1:
            self = .Pending
        case 2:
            self = .OnHold
        case 3:
            self = .Done
        default:
            return nil
        }
    }
}

.allCases on any CaseIterable enum will return a Collection of that element.

var myEnumArray = EstimateItemStatus.allCases

more info about CaseIterable


问:
Display different colored content detail for each option from the dropdown in Angular Material
I wanted to display the content with different color when user selected an option. For example on the dropdown list, there's three option for the items. If user selects on Confirmed in Status placeholder, the content will display "Confirmed" in green and when user selects Not Confirmed, the item will display the wording "Not Confirmed" in Red. If user select "Confirmed and Shipped", the color will show Yellow. How do I get it to work? I'm new to Angular. I have tried so many ways but it won't work. </p>

```<code><mat-form-field>
  <mat-select placeholder="Status" [formControl]="statusTypeFilter">
    <mat-option value="1">Confirmed</mat-option>
    <mat-option value="2">Not Confirmed</mat-option>
    <mat-option value="3">Confirmed and Shipped</mat-option>
</mat-form-field>

<div class="table-container mat-elevation-z8">
  <table mat-table [dataSource]="ItemConfirmationList" multiTemplateDataRows matSort matSortActive="no">
    <ng-container matColumnDef="StatusName">
      <th mat-header-cell *matHeaderCellDef mat-sort- header>Status</th>
      <td mat-cell *matCellDef="let element">{{element.StatusName }}</td>
    </ng-container>
</div>
</code>```

答:
You should create 3 CSS styles, each one of them for different status

CSS

```<code>.confirmed {
  color: green;
}
.not-confirmed {
  color: red
}
</code>```

Then in your template, use [ngClass] to apply the CSS

```<code><td [ngClass]="{ 'confirmed': status === 'Confirmed', 'not-confirmed': status === 'Not Confirmed', 'confirm-shipped': status === 'Confirmed and Shipped' }"
 mat-cell *matCellDef="let element">
   {{element.StatusName}}
</td>
</code>```

PS: I assumed that you are storing dropdown value in status variable

Body:
I wanted to display the content with different color when user selected an option. For example on the dropdown list, there's three option for the items. If user selects on Confirmed in Status placeholder, the content will display "Confirmed" in green and when user selects Not Confirmed, the item will display the wording "Not Confirmed" in Red. If user select "Confirmed and Shipped", the color will show Yellow. How do I get it to work? I'm new to Angular. I have tried so many ways but it won't work.

<mat-form-field>
  <mat-select placeholder="Status" [formControl]="statusTypeFilter">
    <mat-option value="1">Confirmed</mat-option>
    <mat-option value="2">Not Confirmed</mat-option>
    <mat-option value="3">Confirmed and Shipped</mat-option>
</mat-form-field>

    <ng-container matColumnDef="StatusName">
      Status
      {{element.StatusName }}
    </ng-container>

Body:
You should create 3 CSS styles, each one of them for different status

CSS

.confirmed {
  color: green;
}
.not-confirmed {
  color: red
}

Then in your template, use [ngClass] to apply the CSS

<td [ngClass]="{ 'confirmed': status === 'Confirmed', 'not-confirmed': status === 'Not Confirmed', 'confirm-shipped': status === 'Confirmed and Shipped' }"
 mat-cell *matCellDef="let element">
   {{element.StatusName}}
</td>

PS: I assumed that you are storing dropdown value in status variable


问:
My PUT method isn't working in angular even though it works in spring
I have a webpage that displays a logged in user information which is called from database using a spring REST API. Next to each user property there's an edit button when clicked displays an input field which the user can use to edit that property (I've only added it the password field so far).

For some reason after I click on the button and edit the property nothing happens even though it's supposed to display 'works' in the console.

Here's the spring controller method that handles the update:

```<code>@PutMapping("myProfile/edit")
public ResponseEntity<Object> updateProfile(@CurrentUser User currentUser, @RequestBody EditUserProfileRequest user){
    User updatedUser = userService.updateProfile(currentUser, user);
    return ResponseEntity.ok().body("Update Success!");
}
</code>```

Here's the service method:

```<code>@Override
public User updateProfile(User currentUser, EditUserProfileRequest input) {
    User user = this.getUserByUsername(currentUser.getUsername());
    user.setEditedProfile(input);
    if(input.getPassword()!=null){
        user.setPassword(passwordEncoder.encode(input.getPassword()));
    }
    User saveMe = userRepository.save(user);
    return saveMe;
}
</code>```

The EditUserProfileRequest class:

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

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@AllArgsConstructor
@NoArgsConstructor
@Data
public class EditUserProfileRequest {
   private String firstName;
   private String lastName;
   private String password;
   private String email;
   private String location;
   private String bio;
   private Long phoneNumber;
   private Long zipCode;
}
</code>```

Here's the html code for the password field which would display the normal password first then change to input fields after clicking on the edit button:

```<code><div style="margin-top: 3px; margin-bottom: 3px;">
        <h5 style="float: left; margin-left: 160px; margin-top: 18px;">
          <b>Password: </b>
        </h5>
        <div id="hashPassword" style="display: block">
          <div style="width: 100px; margin-left: 233px; float: left;">
              <span style="font-weight: 600">*********</span>
          </div>
          <mat-icon id="hashPassword" aria-label="EDIT" aria-hidden="false" (click)="editPassword()" style="cursor: pointer; margin-left: 446px">edit</mat-icon>
        </div>
        <div id="editPassword" style="display: none">
          <div style="width: 800px; margin-left: 233px; float: left;">
          <form [formGroup]="passwordEditForm" (ngSubmit)="onPasswordSubmit()">
            <div class="form-group">
              <label>Password</label>
              <input type="password" formControlName="password" class="form-control" [ngClass]="{ 'is-invalid': submitted && f.password.errors }" />
              <div *ngIf="submitted && f.password.errors" class="invalid-feedback">
                  <div *ngIf="f.password.errors.required">Password is required</div>
                  <div *ngIf="f.password.errors.minlength">Password must be at least 4 characters</div>
              </div>
          </div>
          <div class="form-group">
              <label>Confirm Password</label>
              <input type="password" formControlName="confirmPassword" class="form-control" [ngClass]="{ 'is-invalid': submitted && f.confirmPassword.errors }" />
              <div *ngIf="submitted && f.confirmPassword.errors" class="invalid-feedback">
                  <div *ngIf="f.confirmPassword.errors.required">Confirm Password is required</div>
                  <div *ngIf="f.confirmPassword.errors.mustMatch">Passwords must match</div>
              </div>
          </div>
          <div class="form-group">
            <button type="button" class="btn btn-primary">Confirm Edit</button>
          </div>
          </form>
        </div>
        </div>
      </div>
</code>```

Here's my my component that handles the calls the edit function:

```<code>import { Component, OnInit, ChangeDetectorRef, OnDestroy } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { MediaMatcher } from '@angular/cdk/layout';
import { Router } from '@angular/router';
import { DomSanitizer } from '@angular/platform-browser';
import { Observable } from 'rxjs';
import { HttpHeaders, HttpClient } from '@angular/common/http';
import { MustMatch } from '../must-match.validators';
import { UserService } from '../user.service';

@Component({
  selector: 'app-myacc',
  templateUrl: './myacc.component.html',
  styleUrls: ['./myacc.component.scss']
})
export class MyaccComponent implements OnInit {
  loginUser: any = {};
  imgSrc: any;
  submitted = false;
  passwordEditForm: FormGroup;
  constructor(private router: Router,
  private sanitizer: DomSanitizer,
  private http: HttpClient,
  private fb: FormBuilder,
  private service: UserService) {
}

ngOnInit() {
  console.log(window.URL);
  this.loginUser = JSON.parse(localStorage.getItem('currentUser'));
  console.log(this.loginUser);
  this.passwordEditForm = this.fb.group({
    password: ['', [Validators.required, Validators.minLength(4)]],
    confirmPassword: ['', Validators.required]
  }, {
    validator: MustMatch('password', 'confirmPassword')
  });
}

editPassword() {
  document.getElementById('hashPassword').style.display = 'none';
  document.getElementById('editPassword').style.display = 'block';
}

get f() {
  return this.passwordEditForm.controls;
}

onPasswordSubmit() {
  this.submitted = true;
  if (this.passwordEditForm.invalid) {
    return;
  } else {
  this.service.editUser(this.passwordEditForm.value, this.loginUser.token).subscribe(res => {
    console.log('works');
  }, err => {
    console.log(err);
  });
}
}

}
</code>```

And finally the User service that has the edit method:

```<code>import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable({
  providedIn: 'root'
})
export class UserService {
  constructor(private http: HttpClient) {
    this.http = http;
  }

  getAllUsers(token: any): Observable<any> {
    // tslint:disable-next-line: object-literal-key-quotes
    const headers = new HttpHeaders({'Authorization': 'Bearer ' + token});
    return this.http.get('http://localhost:8082/users', {headers: headers});
  }

  getUser(token: any): Observable<any> {
    // tslint:disable-next-line: object-literal-key-quotes
    const headers = new HttpHeaders({'Authorization': 'Bearer ' + token});
    return this.http.get('http://localhost:8082/getuser', {headers: headers});
  }

  getAllOffer(): Observable<any> {
    return this.http.get('http://localhost:8082/getAllOffer');
  }

  getServices(): Observable<any> {
    return this.http.get('http://localhost:8082/services');
  }

  editUser(user, token): Observable<any> {
    const headers = new HttpHeaders({'Authorization': 'Bearer ' + token});
    return this.http.put('http://localhost:8082/myProfile/edit', user, token);
  }
}
</code>```

答:
The third argument of HttpClient.put() should be an options object. Update your editUser method so that you are passing an object containing your headers as the third argument instead of token:

```<code>editUser(user, token): Observable<any> {
  const headers = new HttpHeaders({'Authorization': 'Bearer ' + token});
  return this.http.put('http://localhost:8082/myProfile/edit', user, { headers });
}
</code>```

Hopefully that helps!

Body:
I have a webpage that displays a logged in user information which is called from database using a spring REST API. Next to each user property there's an edit button when clicked displays an input field which the user can use to edit that property (I've only added it the password field so far).

For some reason after I click on the button and edit the property nothing happens even though it's supposed to display 'works' in the console.

Here's the spring controller method that handles the update:

@PutMapping("myProfile/edit")
public ResponseEntity<Object> updateProfile(@CurrentUser User currentUser, @RequestBody EditUserProfileRequest user){
    User updatedUser = userService.updateProfile(currentUser, user);
    return ResponseEntity.ok().body("Update Success!");
}

Here's the service method:

@Override
public User updateProfile(User currentUser, EditUserProfileRequest input) {
    User user = this.getUserByUsername(currentUser.getUsername());
    user.setEditedProfile(input);
    if(input.getPassword()!=null){
        user.setPassword(passwordEncoder.encode(input.getPassword()));
    }
    User saveMe = userRepository.save(user);
    return saveMe;
}

The EditUserProfileRequest class:

package com.example.demo.contract;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@AllArgsConstructor
@NoArgsConstructor
@Data
public class EditUserProfileRequest {
   private String firstName;
   private String lastName;
   private String password;
   private String email;
   private String location;
   private String bio;
   private Long phoneNumber;
   private Long zipCode;
}

Here's the html code for the password field which would display the normal password first then change to input fields after clicking on the edit button:

          Password:

              *********

          <mat-icon id="hashPassword" aria-label="EDIT" aria-hidden="false" (click)="editPassword()" style="cursor: pointer; margin-left: 446px">edit</mat-icon>

          <form [formGroup]="passwordEditForm" (ngSubmit)="onPasswordSubmit()">

              Password
              <input type="password" formControlName="password" class="form-control" [ngClass]="{ 'is-invalid': submitted && f.password.errors }" />

Password is required

Password must be at least 4 characters

              Confirm Password
              <input type="password" formControlName="confirmPassword" class="form-control" [ngClass]="{ 'is-invalid': submitted && f.confirmPassword.errors }" />

Confirm Password is required

Passwords must match

            <button type="button" class="btn btn-primary">Confirm Edit</button>

          </form>

Here's my my component that handles the calls the edit function:

import { Component, OnInit, ChangeDetectorRef, OnDestroy } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { MediaMatcher } from '@angular/cdk/layout';
import { Router } from '@angular/router';
import { DomSanitizer } from '@angular/platform-browser';
import { Observable } from 'rxjs';
import { HttpHeaders, HttpClient } from '@angular/common/http';
import { MustMatch } from '../must-match.validators';
import { UserService } from '../user.service';

@Component({
  selector: 'app-myacc',
  templateUrl: './myacc.component.html',
  styleUrls: ['./myacc.component.scss']
})
export class MyaccComponent implements OnInit {
  loginUser: any = {};
  imgSrc: any;
  submitted = false;
  passwordEditForm: FormGroup;
  constructor(private router: Router,
  private sanitizer: DomSanitizer,
  private http: HttpClient,
  private fb: FormBuilder,
  private service: UserService) {
}

ngOnInit() {
  console.log(window.URL);
  this.loginUser = JSON.parse(localStorage.getItem('currentUser'));
  console.log(this.loginUser);
  this.passwordEditForm = this.fb.group({
    password: ['', [Validators.required, Validators.minLength(4)]],
    confirmPassword: ['', Validators.required]
  }, {
    validator: MustMatch('password', 'confirmPassword')
  });
}

editPassword() {
  document.getElementById('hashPassword').style.display = 'none';
  document.getElementById('editPassword').style.display = 'block';
}

get f() {
  return this.passwordEditForm.controls;
}

onPasswordSubmit() {
  this.submitted = true;
  if (this.passwordEditForm.invalid) {
    return;
  } else {
  this.service.editUser(this.passwordEditForm.value, this.loginUser.token).subscribe(res => {
    console.log('works');
  }, err => {
    console.log(err);
  });
}
}

}

And finally the User service that has the edit method:

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable({
  providedIn: 'root'
})
export class UserService {
  constructor(private http: HttpClient) {
    this.http = http;
  }

  getAllUsers(token: any): Observable<any> {
    // tslint:disable-next-line: object-literal-key-quotes
    const headers = new HttpHeaders({'Authorization': 'Bearer ' + token});
    return this.http.get('http://localhost:8082/users', {headers: headers});
  }

  getUser(token: any): Observable<any> {
    // tslint:disable-next-line: object-literal-key-quotes
    const headers = new HttpHeaders({'Authorization': 'Bearer ' + token});
    return this.http.get('http://localhost:8082/getuser', {headers: headers});
  }

  getAllOffer(): Observable<any> {
    return this.http.get('http://localhost:8082/getAllOffer');
  }

  getServices(): Observable<any> {
    return this.http.get('http://localhost:8082/services');
  }

  editUser(user, token): Observable<any> {
    const headers = new HttpHeaders({'Authorization': 'Bearer ' + token});
    return this.http.put('http://localhost:8082/myProfile/edit', user, token);
  }
}

Body:
The third argument of HttpClient.put() should be an options object. Update your editUser method so that you are passing an object containing your headers as the third argument instead of token:

editUser(user, token): Observable<any> {
  const headers = new HttpHeaders({'Authorization': 'Bearer ' + token});
  return this.http.put('http://localhost:8082/myProfile/edit', user, { headers });
}

Hopefully that helps!


问:
IBM MQ - how to connect to Queue manager with multiple connections names ( one is fail over)
I am quite new to IBM MQ's. Mine is a multi-instance queue manager.

One instance is like fail-over.

How can I connect to them even if one of is down.

I am not sure whether my terminology is right or not?

I am trying to connect using below example now

https://raw.githubusercontent.com/ibm-messaging/mq-dev-samples/master/gettingStarted/jms/JmsPutGet.java

答:
Instead of populating WMQ_HOST_NAME and WMQ_PORT populate WMQ_CONNECTION_NAME_LIST with a comma separated list that is in the format host1(port1),host2(port2). IBM MQ will attempt to connect to host1 first and if it fails it will attempt host2 during the initial connection attempt.

If you want the client to reconnect on failure you will need to enable mq auto reconnect like this:

```<code>cf.setClientReconnectOptions(WMQConstants.WMQ_CLIENT_RECONNECT);
cf.setClientReconnectTimeout(1800); // how long in seconds to continue to attempt reconnection before failing
</code>```

Body:
Instead of populating WMQ_HOST_NAME and WMQ_PORT populate WMQ_CONNECTION_NAME_LIST with a comma separated list that is in the format host1(port1),host2(port2). IBM MQ will attempt to connect to host1 first and if it fails it will attempt host2 during the initial connection attempt.

If you want the client to reconnect on failure you will need to enable mq auto reconnect like this:

cf.setClientReconnectOptions(WMQConstants.WMQ_CLIENT_RECONNECT);
cf.setClientReconnectTimeout(1800); // how long in seconds to continue to attempt reconnection before failing


问:
Where can I find my BuildConfig in the APK analyzer after minifying the code with ProGuard?
Please take a look at the following two images from Analyze APK on Android Studio.

First one is with minifyEnabled = false, and

another one is with minifyEnabled = true (after decoding with mapping.txt of course)

minifyEnabled = false. BuildConfig is there.

minifyEnabled = true (decoded with mapping.txt). BuildConfig is not there.

I can find BuildConfig in classes.dex before minifying, but not after minifying. I can't find any document/discussion about this, but is there some rule to strip BuildConfig from classes.dex after minifying with ProGuard? In that case, does it mean that it is relatively safe to put sensitive information in BuildConfig? Or, probably it is just hidden in some other place?

My ProGuard version is 4.7 if that matters.

答: An additional feature of the minifying step is the inlining of constants. This would explain why the BuildConfig disappears, and yet the values still exist where needed. Once the values get inlined, there are no more references to the BuildConfig class and the minifier can remove it entirely.</p>


问:
How to handle GenericClass<Any> for abstraction
I'm trying to figure out how to use generics instantiated with different types together as an abstraction.  For example, put them in one array or pass them to a function.  I know this is tricky because the objects need a concrete class at compile time.  However, experimenting with using  as the concrete class, I stumbled upon the playground code below.  Even if the class is instantiated as Generic1<Any>, the type of the underlying value property is correctly recognized.  So my mystery is this: how can type(of: g1.value) be Int even though type(of:g1) is Generic1<Any>? And given that it is, why can't I cast g1 to Generic1<Int>?  Thanks!

```<code>class Generic1<T> {
    var value: T
    init(_ value:T) {
        self.value = value
    }
}

func handleGeneric(_ g: Generic1<Any>) {
    print("--------------------")
    print(type(of:g))
    print(type(of:g.value))
    print(g.value)
    print("--------------------")
}

let g1 = Generic1<Any>(1)
let g2 = Generic1<Any>("hello")

handleGeneric(g1)
handleGeneric(g2)
</code>```

Output

```<code>--------------------
Generic1<Any>
Int
1
--------------------
--------------------
Generic1<Any>
String
hello
--------------------
</code>```

答:
How can type(of: g1.value) be Int even though type(of:g1) is Generic1<Any>

type(of:) uses runtime type information (stored in the existential container that Any instances use) to give you the concrete type. I don't think it can ever return a super class, a protocol or anything besides the concrete type. The concrete type of g1.value is Int, and the concrete type of g1 is Generic<Any>.

why can't I cast g1 to Generic1<Int>

Because Swift's generics are not covariant. That is, C is not a subtype of C, even if A is a subtype of B. See https://stackoverflow.com/a/30487474/3141234

Body:
I'm trying to figure out how to use generics instantiated with different types together as an abstraction.  For example, put them in one array or pass them to a function.  I know this is tricky because the objects need a concrete class at compile time.  However, experimenting with using  as the concrete class, I stumbled upon the playground code below.  Even if the class is instantiated as Generic1<Any>, the type of the underlying value property is correctly recognized.  So my mystery is this: how can type(of: g1.value) be Int even though type(of:g1) is Generic1<Any>? And given that it is, why can't I cast g1 to Generic1<Int>?  Thanks!

class Generic1<T> {
    var value: T
    init(_ value:T) {
        self.value = value
    }
}

func handleGeneric(_ g: Generic1<Any>) {
    print("--------------------")
    print(type(of:g))
    print(type(of:g.value))
    print(g.value)
    print("--------------------")
}

let g1 = Generic1<Any>(1)
let g2 = Generic1<Any>("hello")

handleGeneric(g1)
handleGeneric(g2)

Output

--------------------
Generic1<Any>
Int
1
--------------------
--------------------
Generic1<Any>
String
hello
--------------------

Body:
How can type(of: g1.value) be Int even though type(of:g1) is Generic1<Any>

type(of:) uses runtime type information (stored in the existential container that Any instances use) to give you the concrete type. I don't think it can ever return a super class, a protocol or anything besides the concrete type. The concrete type of g1.value is Int, and the concrete type of g1 is Generic<Any>.

why can't I cast g1 to Generic1<Int>

Because Swift's generics are not covariant. That is, C<A> is not a subtype of C<B>, even if A is a subtype of B. See https://stackoverflow.com/a/30487474/3141234


问:
Git: How to list all branches that were created from a specific branch?
I need to generate a report with all branch names that were created from  develop branch (which was branched off master sometime in the past). My approach was to get the first and last commits in develop using git log --pretty=format:"%h" master..develop, then use the range of commits with git branch --contains <hash>.

However, the above approach has a few problems:

I need to run to commands to know the range of commits to consider in my query.

I'll have to repeat the git branch --contains command each hash in the range.

The output from git branch --contains commands will contain redundant results for most cases because of the fact that most commits are common between branches.

I'm hoping there is a better and more direct way of doing this. Below I'll try to illustrate the case of interest:

```<code>  master
    ^
    |                      develop
a---b                        ^
     \                       |
      --c--d---e---f---g--h--i
           \      \    \      \
            k-l    m    n      o--p
              ^    ^    ^         ^
              |    |    |         |
         branch_1  | branch_3     |
                 branch_2       branch_4

// Desired output:
branch_1
branch_2
branch_3
branch_4
</code>```

答:
A branch name simply points to one commit.  All earlier commits that are part of that branch are found by walking backwards through the graph from that point.  That's how the master..develop part works, for instance: it selects commits that are ancestors of develop, excluding any commits that are ancestors of master.

(Note that in, e.g., this situation:

```<code>          o--o   <-- master
         /
...--o--o
         \
          *--*--*   <-- develop
</code>```

the two-dot master..develop syntax includes the three starred commits.)

I think what you are asking for here is:

```<code>for each branch name $branch:
    if $branch identifies a commit that is a descendant of any
               of the commits in the set `master..develop`:
        print $branch
</code>```

But any commit that's a descendant of, say, commit i is by definition a descendant of commit c.  So, as tkruse notes in a comment:

```<code>git branch --contains <hash-of-c>
</code>```

should suffice.  To find the commit to use here, you can run git rev-list --topo-order master..develop | tail -1.  (If you use --reverse and head -1 you can get a broken-pipe failure, so the tail -1 method is better.  Annoyingly, you cannot combine --reverse with -n 1.)

You may be worried about a glitch with this sort of case:

```<code>          o--o   <-- master
         /
...--o--o--1--o--o   <-- branch-X
         \  \
          2--*--*   <-- develop
           \
            o   <-- branch-Y
</code>```

You may want branch-X and branch-Y included, and they are not going to be found by using one single git branch --contains operation as they're descendants of two different commits in the master..develop range, denoted here as 1 and 2.  Here, you really do need multiple git branch --contains-es, or, alternatively:

```<code>set -- $(git rev-list master..develop)
git for-each-ref --format='%(refname)' refs/heads | while read ref; do
    branch=${ref#refs/heads/}
    tip=$(git rev-parse $ref)
    take=false
    for i do
        if git merge-base --is-ancestor $i $tip; then
            take=true
            break
        fi
    done
    $take && echo $branch
done
</code>```

(untested and at least one bug fixed so far).  But this will be much slower than the simple git branch --contains test.  The logic here is to determine whether any of the commit hash IDs in the rev-list output is an ancestor of the tip of the branch in question.

(Note that this will print develop—git merge-base --is-ancestor considers a commit to be its own ancestor—so you might want to explicitly skip that one.)

(You can speed this up a lot by finding just the appropriate base commits.  In the example above, for instance, there are just two.  You can then use --contains on those and union the named branches.  The number of bases to use is a function of the number and structure of any merge commits in master..develop.  It may be possible to use git rev-list --boundary to find just the boundary commits; I have not experimented with this.)

Addendum

I realized during lunch that there's an easy way to find the minimal set of commits for --contains or --is-ancestor testing.  Start with the complete list of commits in the range, sorted into topological order with parents first, e.g.:

```<code>set -- $(git rev-list --reverse --topo-order master..develop)
</code>```

Then start with an empty list of "commits that we must inspect":

```<code>hashes=
</code>```

Now, for each hash ID in the list of all possible hashes, test each one, e.g.:

```<code>if ! is_descendant $i $hashes; then
    hashes="$hashes $i"
fi
</code>```

where is_descendant is:

```<code># return true (i.e., 0) if $1 is a descendant of any of
# $2, $3, ..., $n
is_descendant() {
    local i c=$1
    shift
    for i do
        # $i \ancestor $c => $c \descendant $i
        git merge-base --is-ancestor $i $commit_to_test && return 0
    done
    return 1
}
</code>```

After the loop is done, $hashes contains the minimal set of commits that can be used for --contains or --is-ancestor testing.

Body:
I need to generate a report with all branch names that were created from  develop branch (which was branched off master sometime in the past). My approach was to get the first and last commits in develop using git log --pretty=format:"%h" master..develop, then use the range of commits with git branch --contains <hash>.

However, the above approach has a few problems:

I need to run to commands to know the range of commits to consider in my query.

I'll have to repeat the git branch --contains command each hash in the range.

The output from git branch --contains commands will contain redundant results for most cases because of the fact that most commits are common between branches.

I'm hoping there is a better and more direct way of doing this. Below I'll try to illustrate the case of interest:

  master
    ^
    |                      develop
a---b                        ^
     \                       |
      --c--d---e---f---g--h--i
           \      \    \      \
            k-l    m    n      o--p
              ^    ^    ^         ^
              |    |    |         |
         branch_1  | branch_3     |
                 branch_2       branch_4

// Desired output:
branch_1
branch_2
branch_3
branch_4

Body:
A branch name simply points to one commit.  All earlier commits that are part of that branch are found by walking backwards through the graph from that point.  That's how the master..develop part works, for instance: it selects commits that are ancestors of develop, excluding any commits that are ancestors of master.

(Note that in, e.g., this situation:

          o--o   <-- master
         /
...--o--o
         \
          *--*--*   <-- develop

the two-dot master..develop syntax includes the three starred commits.)

I think what you are asking for here is:

for each branch name $branch:
    if $branch identifies a commit that is a descendant of any
               of the commits in the set `master..develop`:
        print $branch

But any commit that's a descendant of, say, commit i is by definition a descendant of commit c.  So, as tkruse notes in a comment:

git branch --contains <hash-of-c>

should suffice.  To find the commit to use here, you can run git rev-list --topo-order master..develop | tail -1.  (If you use --reverse and head -1 you can get a broken-pipe failure, so the tail -1 method is better.  Annoyingly, you cannot combine --reverse with -n 1.)

You may be worried about a glitch with this sort of case:

          o--o   <-- master
         /
...--o--o--1--o--o   <-- branch-X
         \  \
          2--*--*   <-- develop
           \
            o   <-- branch-Y

You may want branch-X and branch-Y included, and they are not going to be found by using one single git branch --contains operation as they're descendants of two different commits in the master..develop range, denoted here as 1 and 2.  Here, you really do need multiple git branch --contains-es, or, alternatively:

set -- $(git rev-list master..develop)
git for-each-ref --format='%(refname)' refs/heads | while read ref; do
    branch=${ref#refs/heads/}
    tip=$(git rev-parse $ref)
    take=false
    for i do
        if git merge-base --is-ancestor $i $tip; then
            take=true
            break
        fi
    done
    $take && echo $branch
done

(untested and at least one bug fixed so far).  But this will be much slower than the simple git branch --contains test.  The logic here is to determine whether any of the commit hash IDs in the rev-list output is an ancestor of the tip of the branch in question.

(Note that this will print develop—git merge-base --is-ancestor considers a commit to be its own ancestor—so you might want to explicitly skip that one.)

(You can speed this up a lot by finding just the appropriate base commits.  In the example above, for instance, there are just two.  You can then use --contains on those and union the named branches.  The number of bases to use is a function of the number and structure of any merge commits in master..develop.  It may be possible to use git rev-list --boundary to find just the boundary commits; I have not experimented with this.)

Addendum

I realized during lunch that there's an easy way to find the minimal set of commits for --contains or --is-ancestor testing.  Start with the complete list of commits in the range, sorted into topological order with parents first, e.g.:

set -- $(git rev-list --reverse --topo-order master..develop)

Then start with an empty list of "commits that we must inspect":

hashes=

Now, for each hash ID in the list of all possible hashes, test each one, e.g.:

if ! is_descendant $i $hashes; then
    hashes="$hashes $i"
fi

where is_descendant is:

# return true (i.e., 0) if $1 is a descendant of any of
# $2, $3, ..., $n
is_descendant() {
    local i c=$1
    shift
    for i do
        # $i \ancestor $c => $c \descendant $i
        git merge-base --is-ancestor $i $commit_to_test && return 0
    done
    return 1
}

After the loop is done, $hashes contains the minimal set of commits that can be used for --contains or --is-ancestor testing.


问:
tiles of map and css can not be loaded while cypress test run
at first thanks for the great maps, API and documentation.

We are building a single page app and we are using the here maps for that. To test our app we use cypress.

When we first implement the test everything runs fine and we got nice test results. But since yesterday we are facing the following problem. When cypress runs our test, the css and the tiles can not be loaded.

For The css we get an 500 response, which seems to be a little bit strange.

For the tiles we get an failed as response, which I don´t know what that could mean.
cypress log

When we run the app by itself, everything seems to be fine.

Thanks in advance.

答: I use  "cypress": "3.3.1", there is a proxy setting


问:
Timezone names for .NET application in LINUX
I have an ASP.NET CORE app.
While this code works in Windows:

```<code> var utcNow = DateTime.UtcNow;
 var currentDateTime = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(utcNow, "US Eastern Standard Time");
</code>```

Will this work when deployed on Linux Kubernetes cluster - given the harcoded timezone name  "US Eastern Standard Time"

Or do I need to configure a different name?

Thanks

Anand

答:
For LINUX the name to use is "EST"

```<code>    var utcNow = DateTime.UtcNow;
    string estTz = string.Empty;
#if RUN_ON_WINDOWS
    estTz = "US Eastern Standard Time";
#else
    estTz = "EST";
#endif
    var currentDateTime = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(utcNow, estTz); // nyse tz
</code>```

In case you are interested we have RUN_ON_WINDOWS in .csproj that the TeamCity build process for LINUX or WINDOWS deployment overwrites accordingly.
<ItemGroup Condition="'$(RunOnWindows)'=='true'">

Body:
I have an ASP.NET CORE app.
While this code works in Windows:

 var utcNow = DateTime.UtcNow;
 var currentDateTime = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(utcNow, "US Eastern Standard Time");

Will this work when deployed on Linux Kubernetes cluster - given the harcoded timezone name  "US Eastern Standard Time"

Or do I need to configure a different name?

Thanks

Anand

Body:
For LINUX the name to use is "EST"

    var utcNow = DateTime.UtcNow;
    string estTz = string.Empty;
#if RUN_ON_WINDOWS
    estTz = "US Eastern Standard Time";
#else
    estTz = "EST";
#endif
    var currentDateTime = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(utcNow, estTz); // nyse tz

In case you are interested we have RUN_ON_WINDOWS in .csproj that the TeamCity build process for LINUX or WINDOWS deployment overwrites accordingly.
<ItemGroup Condition="'$(RunOnWindows)'=='true'">


问:
How can I force SPA clients to hard refresh if there is a new build?
I have a single page application and need the clients to be on the latest version. Caching is aggressive so waiting for them to invalidate isn't feasible.

Is there a way to tell the client to look at a resource (say something like build.txt) and if that resource contains a build number greater than the current one loaded, invalidate the cache and refresh?

答:
As this question has been tagged with progressive-web-apps I'm going to assume that it's installing a service-worker, which is what is aggressively caching the resources.

This post runs though showing a "new version available" popup for PWAs - even if it's not the particular behaviour you want, it explains a lot about how service-workers get updated.

This question/answer also goes over how often the service-worker is checked for updates.

This question/answer goes over pros/cons of always using skipWaiting to keep the client immediately up to date.

Edit: If you're just dealing with regular HTTP Cache, try using location.reload(true) (reload with the forcedReload flag set) when you detect that there's a newer version on the server.  In the past I've done this by putting the release number into the js code at build/release time, and having the server add its release number to every response as a header. A simple compare of the values after an ajax call can confirm whether the ui and server release numbers match and take action when they don't.


问:
why Istio rate-limiting working incorrect?
I configured rate-limiting correctly according to the istio tutorial, and it worked. But when I lowered the limit, it seemed that rate-limiting had not changed.Here are all my configuration files. I hope you can give me some help. Thank you very much.

```<code>apiVersion: config.istio.io/v1alpha2
kind: handler
metadata:
  name: quotahandler
  namespace: istio-system
spec:
  compiledAdapter: memquota
  params:
    quotas:
    - name: requestcountquota.instance.istio-system
      maxAmount: 500
      validDuration: 1s
      overrides:
      - dimensions:
          destination: productpage
          source: "10.28.11.20"
        maxAmount: 500
        validDuration: 1s
      - dimensions:
          destination: productpage
        maxAmount: 500  （Here I increased the number of requests per second.）
        validDuration: 1s
---
apiVersion: config.istio.io/v1alpha2
kind: instance
metadata:
  name: requestcountquota
  namespace: istio-system
spec:
  compiledTemplate: quota
  params:
    dimensions:
      source: request.headers["x-forwarded-for"] | "unknown"
      destination: destination.labels["app"] | destination.service.name | "unknown"
      destinationVersion: destination.labels["version"] | "unknown"
---
apiVersion: config.istio.io/v1alpha2
kind: QuotaSpec
metadata:
  name: request-count
  namespace: istio-system
spec:
  rules:
  - quotas:
    - charge: 1
      quota: requestcountquota
---
apiVersion: config.istio.io/v1alpha2
kind: QuotaSpecBinding
metadata:
  name: request-count
  namespace: istio-system
spec:
  quotaSpecs:
  - name: request-count
    namespace: istio-system
  services:
  - name: productpage
    namespace: default
    #  - service: '*'  # Uncomment this to bind *all* services to request-count
---
apiVersion: config.istio.io/v1alpha2
kind: rule
metadata:
  name: quota
  namespace: istio-system
spec:
  # quota only applies if you are not logged in.
  # match: match(request.headers["cookie"], "user=*") == false
  actions:
  - handler: quotahandler
    instances:
    - requestcountquota
</code>```

At first, I configure it directly.

```<code>- dimensions:
Destination: product page
MaxAmount: 1
Valid Duration: 5S
</code>```

Rate-limiting works well.
When I configure:

```<code>- dimensions:
Destination: product page
MaxAmount: 500
ValidDuration: 1s
</code>```

The request will still return 429 in a short time，configuration (500/s) should be unrestricted at this time.During the test, I visited k8s product page service IP directly, such as curl 10.233.5.240:9080/product page.

I hope you can tell me why. Thank you very much for your answer.

答: I've solved this problem because the istio-policy component has insufficient resources (cpu&memory) and is allocated too little by default, which makes the policy ineffective.But I don't know why. Please explain what's in memquota or redisquota. Aren't quota configurations all in envoy configurations?</p>

Body:
I configured rate-limiting correctly according to the istio tutorial, and it worked. But when I lowered the limit, it seemed that rate-limiting had not changed.Here are all my configuration files. I hope you can give me some help. Thank you very much.

apiVersion: config.istio.io/v1alpha2
kind: handler
metadata:
  name: quotahandler
  namespace: istio-system
spec:
  compiledAdapter: memquota
  params:
    quotas:
    - name: requestcountquota.instance.istio-system
      maxAmount: 500
      validDuration: 1s
      overrides:
      - dimensions:
          destination: productpage
          source: "10.28.11.20"
        maxAmount: 500
        validDuration: 1s
      - dimensions:
          destination: productpage
        maxAmount: 500  （Here I increased the number of requests per second.）
        validDuration: 1s
---
apiVersion: config.istio.io/v1alpha2
kind: instance
metadata:
  name: requestcountquota
  namespace: istio-system
spec:
  compiledTemplate: quota
  params:
    dimensions:
      source: request.headers["x-forwarded-for"] | "unknown"
      destination: destination.labels["app"] | destination.service.name | "unknown"
      destinationVersion: destination.labels["version"] | "unknown"
---
apiVersion: config.istio.io/v1alpha2
kind: QuotaSpec
metadata:
  name: request-count
  namespace: istio-system
spec:
  rules:
  - quotas:
    - charge: 1
      quota: requestcountquota
---
apiVersion: config.istio.io/v1alpha2
kind: QuotaSpecBinding
metadata:
  name: request-count
  namespace: istio-system
spec:
  quotaSpecs:
  - name: request-count
    namespace: istio-system
  services:
  - name: productpage
    namespace: default
    #  - service: '*'  # Uncomment this to bind *all* services to request-count
---
apiVersion: config.istio.io/v1alpha2
kind: rule
metadata:
  name: quota
  namespace: istio-system
spec:
  # quota only applies if you are not logged in.
  # match: match(request.headers["cookie"], "user=*") == false
  actions:
  - handler: quotahandler
    instances:
    - requestcountquota

At first, I configure it directly.

- dimensions:
Destination: product page
MaxAmount: 1
Valid Duration: 5S

Rate-limiting works well.
When I configure:

- dimensions:
Destination: product page
MaxAmount: 500
ValidDuration: 1s

The request will still return 429 in a short time，configuration (500/s) should be unrestricted at this time.During the test, I visited k8s product page service IP directly, such as curl 10.233.5.240:9080/product page.

I hope you can tell me why. Thank you very much for your answer.


问:
"C:\Microsoft.Cpp.Default.props" was not found
I have a project created in Visual Studio, 2013.

The project file has the following properties:

ToolsVersion="12.0",
PlatformToolset = v120.

I have Visual Studio 2013 and Microsoft Build Tools 2015 installed.
This project gets successfully built using MSBuild 12.0. Upon the attempt to build it with MSBuild 14.0 I get an error

```<code>MSB4019: The imported project "C:\Microsoft.Cpp.Default.props" was not found. Confirm that the path in the <Import> declaration is correct, and that the file exists on disk.
</code>```

As I understand, the problem is that the variable VCTargetsPath doesn’t get evaluated.  If I specify the variable VCTargetsPath before the build (with the value C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\V120), the problem is solved.

However, this approach is not very convenient in case the path is different. Is it possible to somehow solve the problem in a more optimal way?

The registry key and its value:

```<code>HKLM\Software\WOW6432Node\Microsoft\MSBuild\ToolsVersions\12.0\VCTargetsPath $([MSBuild]::ValueOrDefault('$(VCTargetsPath)','$(MSBuildExtensionsPath32)\Microsoft.Cpp\v4.0\V120\'))
</code>```

答:
For those the above answer does not work, here is another possible solution to look at.

Even the installation of build tools or VS 2015 did not work for me. So I tried installing below directly via PowerShell (as admin)

https://chocolatey.org/packages/visualcpp-build-tools/14.0.25420.1
Command:
choco install visualcpp-build-tools --version 14.0.25420.1

Once this was installed, set an environment variable VCTargetsPath=C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\v140

ContentLicense: CC BY-SA 3.0

Body:
I have a project created in Visual Studio, 2013.

The project file has the following properties:

ToolsVersion="12.0",
PlatformToolset = v120.

I have Visual Studio 2013 and Microsoft Build Tools 2015 installed.
This project gets successfully built using MSBuild 12.0. Upon the attempt to build it with MSBuild 14.0 I get an error

MSB4019: The imported project "C:\Microsoft.Cpp.Default.props" was not found. Confirm that the path in the <Import> declaration is correct, and that the file exists on disk.

As I understand, the problem is that the variable VCTargetsPath doesn’t get evaluated.  If I specify the variable VCTargetsPath before the build (with the value C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\V120), the problem is solved.

However, this approach is not very convenient in case the path is different. Is it possible to somehow solve the problem in a more optimal way?

The registry key and its value:

HKLM\Software\WOW6432Node\Microsoft\MSBuild\ToolsVersions\12.0\VCTargetsPath $([MSBuild]::ValueOrDefault('$(VCTargetsPath)','$(MSBuildExtensionsPath32)\Microsoft.Cpp\v4.0\V120\'))


问:
Copy data to sheet named in column header and cell named at beginning of row, then loop
I have some production data in a table on my Source worksheet. In the header of each column is the name of the Destination worksheet, where the data in that column is to be pasted. In Column A at the beginning of each row is the destination column on the destination worksheet; and in Column B is the destination row. Column C concatenates the two to display the cell name, e.g, T138, which would be the destination cell on the destination worksheets. I haven't been a member long enough to embed an image in this post, but there is an pic of the table here:

So each datum on the Source worksheet is to be copied and then pasted to the worksheet named in the column header and the cell named in column C at the beginning of the row (or alternatively, in the column named in Col.A and the row named in Col.B) Then the script should loop back through the rest of the data cells and do the same for each of them: copy data, paste to sheet specified in column header and cell specified at the beginning of the row in Col.C.

Even though I am a total beginner, I actually thought this would be a fairly simple matter. But I haven't been able to figure out how to do this. I've tried various scripts, but none of them even began to do the job, and they really aren't even worth displaying here. I was hoping someone could point me in the right direction. Worse yet, none of my extensive searches have turned up anything like what I want to do. Maybe I just haven't used the right search terms. "Variable" seems to have gotten the closest to useable search results, but not exactly.

Here is an image of what one of the destination sheets looks like, in relevant part:

Here's a better image:

答:
This code will Loop over each cell in the range of G3 to J and LastRow. Copying the cell if it's numeric to the sheet based on the column header and the cell from column C.</p>
```<code>Public Sub MoveData()
Dim rcell As Range, rng As Range

LastRow = ActiveSheet.UsedRange.Rows.Count + ActiveSheet.UsedRange.Rows(1).Row - 1
'MsgBox LastRow

Set rng = Application.ActiveSheet.Range("G3:J" & LastRow)

For Each rcell In rng.Cells
    If Not Len(rcell.Value) = 0 Then

        'MsgBox rcell.Value
        Header = rcell.Offset(1 - rcell.Row).Value
        'MsgBox Header
        Set DestSheet = ThisWorkbook.Sheets(Header)
        Set DestCell = ActiveSheet.Range("C" & rcell.Row)
        'MsgBox DestCell

        Application.ActiveSheet.Range(rcell.Address).Copy Destination:=Sheets(Header).Range(DestCell)
    End If
Next rcell

End Sub
</code>```

Body:
This code will Loop over each cell in the range of G3 to J and LastRow. Copying the cell if it's numeric to the sheet based on the column header and the cell from column C.

Public Sub MoveData()
Dim rcell As Range, rng As Range

LastRow = ActiveSheet.UsedRange.Rows.Count + ActiveSheet.UsedRange.Rows(1).Row - 1
'MsgBox LastRow

Set rng = Application.ActiveSheet.Range("G3:J" & LastRow)

For Each rcell In rng.Cells
    If Not Len(rcell.Value) = 0 Then

        'MsgBox rcell.Value
        Header = rcell.Offset(1 - rcell.Row).Value
        'MsgBox Header
        Set DestSheet = ThisWorkbook.Sheets(Header)
        Set DestCell = ActiveSheet.Range("C" & rcell.Row)
        'MsgBox DestCell

        Application.ActiveSheet.Range(rcell.Address).Copy Destination:=Sheets(Header).Range(DestCell)
    End If
Next rcell

End Sub


问:
Looping an array together with a jquery hover function
I'm trying to... God, this is hard to explain.

I got an array called 'triggers' with these variables:

"#1_trigger","#2_trigger","#3_trigger"

And inside a jQuery each(), I create another variable called 'targets' that copies everything from 'triggers' and replaces all _trigger to _target. I then append the 'triggers' to anchor IDs, and 'targets' to hidden div IDs.

What I want to do, is this: When hovering a _trigger, the _target will show up. I've managed to make it work with only one variable, but not with multiple.

As I said, it's kind of hard to explain what I want to do in text, so here's a demo and my progress so far:
http://jsfiddle.net/WJWe3/6/

I've been stuck with this one for too many hours now, please help!

答:
When you set the id for an element, it should not start with #. It's only when you use it as a selector in jQuery that it starts with #.

However, you don't even need to use the id. Create the a and div element as objects instead of as a string, then you can hook up the hover event directly to the link, and access the div directly, instead of trying to find it after adding it to the page.

jsfiddle.net/WJWe3/16/

```<code>var triggers = ["1_trigger", "2_trigger", "3_trigger"];

jQuery.each(triggers, function(i, val) {
    var target = $('<div/>', { className: 'hidden' }).text('You found me!');
    var link = $('<a/>', { href: '#' }).text(val).hover(function(){
        target.stop().fadeTo("normal", 1.00);
    }, function(){
        target.stop().fadeTo("normal", 0.00);
    });;
    $("#experiment").append(link).append(target).append("<br/>");
});
</code>```

Body:
When you set the id for an element, it should not start with #. It's only when you use it as a selector in jQuery that it starts with #.

However, you don't even need to use the id. Create the a and div element as objects instead of as a string, then you can hook up the hover event directly to the link, and access the div directly, instead of trying to find it after adding it to the page.

jsfiddle.net/WJWe3/16/

var triggers = ["1_trigger", "2_trigger", "3_trigger"];

jQuery.each(triggers, function(i, val) {
    var target = $('<div/>', { className: 'hidden' }).text('You found me!');
    var link = $('<a/>', { href: '#' }).text(val).hover(function(){
        target.stop().fadeTo("normal", 1.00);
    }, function(){
        target.stop().fadeTo("normal", 0.00);
    });;
    $("#experiment").append(link).append(target).append("<br/>");
});


问:
Display date in TextBox with type="date"
I want to display stored date on database on TextBox  type="date"

```<code> <asp:TextBox ID="DateStatus"  runat="server" Type="date" CssClass="form-control"></asp:TextBox>
</code>```

but nothing is displayed in the textbox i used. I tried this

```<code>Dim getdate As Date = DetailTable.Rows(0)(3)
DateStatus.Text= getDate
</code>```

Also this which i found here

```<code> Dim getdate As Date = DetailTable.Rows(0)(3)
 DateStatus.Text = DateTime.UtcNow.ToString(getdate)
</code>```

When i debugged the code, the date passed correctly.

When i remove type="date"   the requested date is displayed just fine

Is it not Possible to do this?

on SideNote when i generate my table using <Asp:detailsview> the date is generated with time 12:00:00 despite the field declared only as Datein the schema, but i don't think it's relevant to my current issue since every thing looked fine during debugging

And Originally i store the date as Text (@date, DateStatus.Text)

答:
This is HTML 5 stuff. If you have a real date from your database, I simulated like this

```<code><asp:TextBox ID="txt1" runat="server" TextMode="date" />

        Dim d As New Date(1922, 12, 25)
        txt1.Text = d.ToString("yyyy-MM-dd")
        'displays 12/25/1922
</code>```

HTML 5 expects a string in the format yyyy-MM-dd and a supporting browser will display depending on Culture setting.

Body:
I want to display stored date on database on TextBox  type="date"

 <asp:TextBox ID="DateStatus"  runat="server" Type="date" CssClass="form-control"></asp:TextBox>

but nothing is displayed in the textbox i used. I tried this

Dim getdate As Date = DetailTable.Rows(0)(3)
DateStatus.Text= getDate

Also this which i found here

 Dim getdate As Date = DetailTable.Rows(0)(3)
 DateStatus.Text = DateTime.UtcNow.ToString(getdate)

When i debugged the code, the date passed correctly.

When i remove type="date"   the requested date is displayed just fine

Is it not Possible to do this?

on SideNote when i generate my table using <Asp:detailsview> the date is generated with time 12:00:00 despite the field declared only as Datein the schema, but i don't think it's relevant to my current issue since every thing looked fine during debugging

And Originally i store the date as Text (@date, DateStatus.Text)

Body:
This is HTML 5 stuff. If you have a real date from your database, I simulated like this

<asp:TextBox ID="txt1" runat="server" TextMode="date" />

        Dim d As New Date(1922, 12, 25)
        txt1.Text = d.ToString("yyyy-MM-dd")
        'displays 12/25/1922

HTML 5 expects a string in the format yyyy-MM-dd and a supporting browser will display depending on Culture setting.


问:
How can I fix the code so Python will select the random number
I'm a Python beginning learner. Recently our school teacher asked us to do a project with following requirements:

Randomly pick a number from 1-6 for two players.

Each player starts with 100 points.

Each player rolls one dice. The player with the lower roll loses the number of points shown on the higher dice.

Play until one of the player's score is lower or equal to zero.

The run is Python 3.7.2, and here is the code:

```<code>import random
dice1 = random.randint(1,6)
dice2 = random.randint(1,6) #random number
player1 = 100
player2 = 100 #the initial marks for both players
While player1 > 0 or player2 > 0:
    if dice1 > dice2: #when the player1 has the higher number
        player2 = player2 - dice1
        print("player1", player1, "player2", player2)
    elif dice2 > dice1: #when the player 2 has the higher number
        player1 = player1 - dice2
        print("player1", player1, "player2", player2)
    elif dice1 == dice2: #when two player get the same number
        print("It's a tie.")
    if player1 <= 0:
        print("player2 win")
        break
    elif player2 <= 0:
        print("player1 win")
        break
</code>```

I tried several times. When I run it, there were two problems:

One of the score keeps 100 all the time while the other one is kept changing until it is lower or equal to zero.

The result just keep coming up with "It's a tie."

I was confused with the result and had no idea how to fix it...
Really appreciate any and all help! Thanks|ू･ω･` )

答:
Your code only rolls the dice (gets a random number set) once.
Move the dice roll inside the while loop like so:</p>

```<code>import random

player1 = 100
player2 = 100 #the initial marks for both players
while (player1 > 0 and player2 > 0):
    dice1 = random.randint(1, 6)
    dice2 = random.randint(1, 6)
    if dice1 > dice2: #when the player1 has the higher number
        player2 = player2 - dice1
        print("player1", player1, "player2", player2)
    elif dice2 > dice1: #when the player 2 has the higher number
        player1 = player1 - dice2
        print("player1", player1, "player2", player2)
    elif dice1 == dice2: #when two player get the same number
        print("It's a tie.")
    if player1 <= 0:
        print("player2 win")
        break
    elif player2 <= 0:
        print("player1 win")
        break
</code>```

Body:
I'm a Python beginning learner. Recently our school teacher asked us to do a project with following requirements:

Randomly pick a number from 1-6 for two players.

Each player starts with 100 points.

Each player rolls one dice. The player with the lower roll loses the number of points shown on the higher dice.

Play until one of the player's score is lower or equal to zero.

The run is Python 3.7.2, and here is the code:

import random
dice1 = random.randint(1,6)
dice2 = random.randint(1,6) #random number
player1 = 100
player2 = 100 #the initial marks for both players
While player1 > 0 or player2 > 0:
    if dice1 > dice2: #when the player1 has the higher number
        player2 = player2 - dice1
        print("player1", player1, "player2", player2)
    elif dice2 > dice1: #when the player 2 has the higher number
        player1 = player1 - dice2
        print("player1", player1, "player2", player2)
    elif dice1 == dice2: #when two player get the same number
        print("It's a tie.")
    if player1 <= 0:
        print("player2 win")
        break
    elif player2 <= 0:
        print("player1 win")
        break

I tried several times. When I run it, there were two problems:

One of the score keeps 100 all the time while the other one is kept changing until it is lower or equal to zero.

The result just keep coming up with "It's a tie."

I was confused with the result and had no idea how to fix it...
Really appreciate any and all help! Thanks|ू･ω･` )

Body:
Your code only rolls the dice (gets a random number set) once.
Move the dice roll inside the while loop like so:

import random

player1 = 100
player2 = 100 #the initial marks for both players
while (player1 > 0 and player2 > 0):
    dice1 = random.randint(1, 6)
    dice2 = random.randint(1, 6)
    if dice1 > dice2: #when the player1 has the higher number
        player2 = player2 - dice1
        print("player1", player1, "player2", player2)
    elif dice2 > dice1: #when the player 2 has the higher number
        player1 = player1 - dice2
        print("player1", player1, "player2", player2)
    elif dice1 == dice2: #when two player get the same number
        print("It's a tie.")
    if player1 <= 0:
        print("player2 win")
        break
    elif player2 <= 0:
        print("player1 win")
        break


问:
How to control the parallelism or concurrency of an Airflow installation?
In some of my Apache Airflow installations, DAGs or tasks that are scheduled to run do not run even when the scheduler doesn't appear to be fully loaded. How can I increase the number of DAGs or tasks that can run concurrently?

Similarly, if my installation is under high load and I want to limit how quickly my Airflow workers pull queued tasks (such as to reduce resource consumption), what can I adjust to reduce the average load?

答:
Here's an expanded list of configuration options that are available since Airflow v1.10.2. Some can be set on a per-DAG or per-operator basis, but may also fall back to the setup-wide defaults when they are not specified.

Options that can be specified on a per-DAG basis:

concurrency: the number of task instances allowed to run concurrently across all active runs of the DAG this is set on. Defaults to core.dag_concurrency if not set

max_active_runs: maximum number of active runs for this DAG. The scheduler will not create new active DAG runs once this limit is hit. Defaults to core.max_active_runs_per_dag if not set

Examples:

# Only allow one run of this DAG to be running at any given time
dag = DAG('my_dag_id', max_active_runs=1)

# Allow a maximum of 10 tasks to be running across a max of 2 active DAG runs
dag = DAG('example2', concurrency=10, max_active_runs=2)
```
<hr />
<p>Options that can be specified <strong>on a per-operator basis</strong>:</p>
<ul>
<li><code>pool</code>: the pool to execute the task in. Pools can be used to limit parallelism for <em>only a subset</em> of tasks</li>
<li><code>task_concurrency</code>: concurrency limit for the same task across multiple DAG runs</li>
</ul>
<p>Example:</p>
<pre class="lang-py prettyprint-override"><code>t1 = BaseOperator(pool='my_custom_pool', task_concurrency=12)
</code>```

Options that are specified across an entire Airflow setup:

core.parallelism: maximum number of tasks running across an entire Airflow installation

core.dag_concurrency: max number of tasks that can be running per DAG (across multiple DAG runs)

core.non_pooled_task_slot_count: number of task slots allocated to tasks not running in a pool

core.max_active_runs_per_dag: maximum number of active DAG runs, per DAG

scheduler.max_threads: how many threads the scheduler process should use to use to schedule DAGs

celery.worker_concurrency: max number of task instances that a worker will process at a time if using CeleryExecutor

celery.sync_parallelism: number of processes CeleryExecutor should use to sync task state

Body:
Here's an expanded list of configuration options that are available since Airflow v1.10.2. Some can be set on a per-DAG or per-operator basis, but may also fall back to the setup-wide defaults when they are not specified.

Options that can be specified on a per-DAG basis:

concurrency: the number of task instances allowed to run concurrently across all active runs of the DAG this is set on. Defaults to core.dag_concurrency if not set

max_active_runs: maximum number of active runs for this DAG. The scheduler will not create new active DAG runs once this limit is hit. Defaults to core.max_active_runs_per_dag if not set

Examples:

# Only allow one run of this DAG to be running at any given time
dag = DAG('my_dag_id', max_active_runs=1)

# Allow a maximum of 10 tasks to be running across a max of 2 active DAG runs
dag = DAG('example2', concurrency=10, max_active_runs=2)

Options that can be specified on a per-operator basis:

pool: the pool to execute the task in. Pools can be used to limit parallelism for only a subset of tasks

task_concurrency: concurrency limit for the same task across multiple DAG runs

Example:

t1 = BaseOperator(pool='my_custom_pool', task_concurrency=12)

Options that are specified across an entire Airflow setup:

core.parallelism: maximum number of tasks running across an entire Airflow installation

core.dag_concurrency: max number of tasks that can be running per DAG (across multiple DAG runs)

core.non_pooled_task_slot_count: number of task slots allocated to tasks not running in a pool

core.max_active_runs_per_dag: maximum number of active DAG runs, per DAG

scheduler.max_threads: how many threads the scheduler process should use to use to schedule DAGs

celery.worker_concurrency: max number of task instances that a worker will process at a time if using CeleryExecutor

celery.sync_parallelism: number of processes CeleryExecutor should use to sync task state


问:
Pandas - Identify if a date in a pandas column is falls on Saturday or Sunday
I want to identify if a date value is on a Saturday or Sunday. If it is, then I want to change said date to the friday prior. (example df and result df below - these are real dates from May 2019, as you can see there is a Saturday(5/4/19) and Sunday(5/26/19) date pulled into the week prior in the results df. The (5/2/19) date stays the same as it is a weekday not a weekend.

```<code>import pandas as pd
data = [['5/3/19','5/4/19'],['5/3/19','5/2/19'],['5/24/19','5/26/19']]
df = pd.DataFrame(data,columns=['Date1','Date2'])
print(df)

data2 = [['5/3/19','5/3/19'],['5/3/19','5/2/19'],['5/24/19','5/24/19']]
resultsdf = pd.DataFrame(data2,columns=['Date1','Date2'])
print(resultsdf)
</code>```

I am running this code for a Month to Date range. I have to have the code to group a large data set into a MTD view - but I am having trouble creating variables for a list of sat/sunday ( as there will be 8-10 weekend dates per month) Here is my code:

```<code>import pandas as pd
import xlrd # added when using visual studio
import datetime
from datetime import datetime
today = pd.to_datetime(datetime.now().date())
day_of_week = today.dayofweek
last_monday = today - pd.to_timedelta(day_of_week, unit='d')
month_day = today.day
start_month_scope = today - pd.to_timedelta(month_day, unit = 'd')
first_day_of_month = start_month_scope + pd.to_timedelta(1, unit = 'd')
</code>```

The problem with the code below is that is only works if I need to find the saturday & sunday on 7 day (M-f) period.

```<code>last_sunday = last_monday + pd.to_timedelta(6, unit='d')
last_sat = last_sunday - pd.to_timedelta(1, unit='d')
last_fri = last_sunday - pd.to_timedelta(2, unit='d')
</code>```

I need some variable to input to the code below:

```<code>finaldf.loc[(finaldf['Due_Date'] == last_sat), 'Due_Date'] = last_fri
</code>```

So 'last_fri' would be just the most recent friday from the given saturday or sunday, so referencing my example df there is the 5/4/19 example which gets pulled back into a 5/3/19 (the last friday for that instance) or the 5/26/19 gets pulled back to 5/24/19. As you can see the code would have to understand first if the date is saturday and sunday then next what is the closest friday prior.

* if all the above got confusing please just reference my df -> resulftdf *

答:
Here's a oneliner:</p>

```<code>df.Date1 -= pd.to_timedelta(
    (df.Date1.dt.dayofweek - 4).apply(lambda v: v if v > 0 else 0), unit="D"
)
</code>```

Body:
I want to identify if a date value is on a Saturday or Sunday. If it is, then I want to change said date to the friday prior. (example df and result df below - these are real dates from May 2019, as you can see there is a Saturday(5/4/19) and Sunday(5/26/19) date pulled into the week prior in the results df. The (5/2/19) date stays the same as it is a weekday not a weekend.

import pandas as pd
data = [['5/3/19','5/4/19'],['5/3/19','5/2/19'],['5/24/19','5/26/19']]
df = pd.DataFrame(data,columns=['Date1','Date2'])
print(df)

data2 = [['5/3/19','5/3/19'],['5/3/19','5/2/19'],['5/24/19','5/24/19']]
resultsdf = pd.DataFrame(data2,columns=['Date1','Date2'])
print(resultsdf)

I am running this code for a Month to Date range. I have to have the code to group a large data set into a MTD view - but I am having trouble creating variables for a list of sat/sunday ( as there will be 8-10 weekend dates per month) Here is my code:

import pandas as pd
import xlrd # added when using visual studio
import datetime
from datetime import datetime
today = pd.to_datetime(datetime.now().date())
day_of_week = today.dayofweek
last_monday = today - pd.to_timedelta(day_of_week, unit='d')
month_day = today.day
start_month_scope = today - pd.to_timedelta(month_day, unit = 'd')
first_day_of_month = start_month_scope + pd.to_timedelta(1, unit = 'd')

The problem with the code below is that is only works if I need to find the saturday & sunday on 7 day (M-f) period.

last_sunday = last_monday + pd.to_timedelta(6, unit='d')
last_sat = last_sunday - pd.to_timedelta(1, unit='d')
last_fri = last_sunday - pd.to_timedelta(2, unit='d')

I need some variable to input to the code below:

finaldf.loc[(finaldf['Due_Date'] == last_sat), 'Due_Date'] = last_fri

So 'last_fri' would be just the most recent friday from the given saturday or sunday, so referencing my example df there is the 5/4/19 example which gets pulled back into a 5/3/19 (the last friday for that instance) or the 5/26/19 gets pulled back to 5/24/19. As you can see the code would have to understand first if the date is saturday and sunday then next what is the closest friday prior.

* if all the above got confusing please just reference my df -> resulftdf *

Body:
Here's a oneliner:

df.Date1 -= pd.to_timedelta(
    (df.Date1.dt.dayofweek - 4).apply(lambda v: v if v > 0 else 0), unit="D"
)


问:
Swift Firebase get Data to Class Object
I want to get the following structure (screenshot of Firebase Database):

In chats I have the id of the chat. There are the users with the child userid and the values of id and name.
At first I look for the chats which a user have and want to get then the details of the chatId (users with their id and name)

I have the following class in Swift:

```<code>class Chat {
var chatId: String!
var userIds: [String]!
var userNames: [String]!
}
</code>```

I have the following code to get the details, but I get not the userIds or userNames from the chatId:

```<code>func getChatsFromFirebase() {
    self.ref = Database.database().reference()
    self.ref?.child("users").child(userdefaults.getUserId()).child("chats").observe(.childAdded, with: { (snapshot) in
        let chat = Chat()
        chat.chatId = snapshot.key
        chat.userIds = []
        chat.userNames = []

        //print(chat.chatId)

        for i in 0..<self.chats.count {
            let usersRef = self.ref.child("chats").child(self.chats[i].chatId).child("users").observeSingleEvent(of: .value, with: { (snapshot) in
                let value = snapshot.value as? NSDictionary

                for userid in value!.allKeys as! [String] {
                    let usersdetailsRef = self.ref.child("chats").child(self.chats[i].chatId).child("users").child(userid).queryOrdered(byChild: "name").observeSingleEvent(of: .value, with: { (snapshot) in

                        let value = snapshot.value as? NSDictionary
                        //print(value)
                        let id = value?["id"] as? String ?? ""
                        let name = value?["name"] as? String ?? ""
                        //print( id + ": " + name)
                        chat.userIds.append(id)
                        chat.userNames.append(name)
                    })
                }
            })
        }
        self.chats.append(chat)
        self.tableView.reloadData()
    })
}
</code>```

I am very new to the Firebase topic. Can someone help me here?
Thanks.

答:
Well You need to change your datamodel first. You dont need to store id value in , 12345 in this case. you can already fetch the key. Also, in /users/chats, you just can just save the chat id as either chat1 : IBDrbfku887BLIY or IBDrbfku887BLIY : true. You can always fetch them through value or the key respectively.

And in your chat document, you just need to reference the user id, i.e just get them and store them as user1 and user2. You can add more users if your usecase requires more.

Reconfigure your Data Model as follows.

Now You need 2 Objects Users and Chats as follows :

Users.swift

```<code>class User : NSObject {

        private var _name: String!
        private var _username: String!
        private var _userid: String!
        private var _userRef: DatabaseReference!

        var name: String! {
            get {
                return _name
            } set {
                _name = newValue
            }
        }

        var username : String! {
            get {
                return _username
            } set {
                _username = newValue
            }
        }

        var userid: String! {
            get {
                return _userid
            } set {
                _userid = newValue
            }
        }

        var userRef: DatabaseReference! {
            get {
                return _userRef
            } set {
                _userRef = newValue
            }
        }

        init(userid: String, userData: Dictionary<String, Any>){

            self._userid = userid

            _userRef = Database.database().reference().child(_userid)

            if let username = userData["username"] as? String {
                self._username = username
            }

            if let name = userData["name"] as? String {
                self._name = name
            }

        }

    }
</code>```

Chats.swift

```<code>class Chat : NSObject {

        private var _chatid: String!
        private var _user1: String!
        private var _user2: String!
        private var _chatRef: DatabaseReference!

        var user1: String! {
            get {
                return _user1
            } set {
                _user1 = newValue
            }
        }

        var user2 : String! {
            get {
                return _user2
            } set {
                _user2 = newValue
            }
        }

        var chatid: String! {
            get {
                return _chatid
            } set {
                _chatid = newValue
            }
        }

        var chatRef: DatabaseReference! {
            get {
                return _chatRef
            } set {
                _chatRef = newValue
            }
        }

        init(chatid: String, chatData: Dictionary<String, Any>){

            self._chatid = chatid

            _chatRef = Database.database().reference().child(_chatid)

            if let user = chatData["users"] as? Dictionary<String, Any> {
                if let user1 = user["user1"] as? String {
                    self._user1 = user1
                }
                if let user2 = user["user2"] as? String {
                    self._user2 = user2
                }
            }

        }

    }
</code>```

The major issue/or an overlooked issue here is the type of the data. In the /users, you id 12345 will be of type String. But when you fetch the same from /chats, it returns as Int. This downloads the value but never converts it. Always take care while seeding/testing your data.

To fetch the user's credentials just reference that through another query. This is what you can do :

```<code>var allUsers = [User]()
    var allChats = [Chat]()

    func viewDidLoad() {
        super.viewDidLoad()
        fetchAllChats()
    }

    func getUser(from userId: String, completion: @escaping (User) -> Void) {

        Database.database().reference().child("users").child(userId).observeSingleEvent(of: .value, with: { snapshot in
            if let datasnap = snapshot.value as? Dictionary<String, Any> {
                let user = User(userid: userId, userData: datasnap)
                completion(user)
            }
        })
    }

    func fetchAllChats() {
        Database.database().reference().child("chats").observeSingleEvent(of: .value, with: { snapshot in
           allChat.removeAll()
            if let snapshot = snapshot.value as? Dictionary<String, Any> {
                for snap in snapshot {
                    if let chatd = snap.value as? Dictionary<String, Any> {
                        let chat = Chat(chatid: snap.key, chatData: chatd)
                        self.allChats.append(chat)
                    }
                }
            }
            // collectionview.reloadData() <--------- only if required.
        })
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let chatData = allChats[indexPath.row]
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: CellId, for: indexPath) as! Cell
        getUser(from: chatData.user1) { user in
            cell.label.text = user.usernme
        }
        return cell
    }
</code>```

Title: Swift Firebase get Data to Class Object

Body:
I want to get the following structure (screenshot of Firebase Database):

In chats I have the id of the chat. There are the users with the child userid and the values of id and name.
At first I look for the chats which a user have and want to get then the details of the chatId (users with their id and name)

I have the following class in Swift:

class Chat {
var chatId: String!
var userIds: [String]!
var userNames: [String]!
}

I have the following code to get the details, but I get not the userIds or userNames from the chatId:

func getChatsFromFirebase() {
    self.ref = Database.database().reference()
    self.ref?.child("users").child(userdefaults.getUserId()).child("chats").observe(.childAdded, with: { (snapshot) in
        let chat = Chat()
        chat.chatId = snapshot.key
        chat.userIds = []
        chat.userNames = []

        //print(chat.chatId)

        for i in 0..<self.chats.count {
            let usersRef = self.ref.child("chats").child(self.chats[i].chatId).child("users").observeSingleEvent(of: .value, with: { (snapshot) in
                let value = snapshot.value as? NSDictionary

                for userid in value!.allKeys as! [String] {
                    let usersdetailsRef = self.ref.child("chats").child(self.chats[i].chatId).child("users").child(userid).queryOrdered(byChild: "name").observeSingleEvent(of: .value, with: { (snapshot) in

                        let value = snapshot.value as? NSDictionary
                        //print(value)
                        let id = value?["id"] as? String ?? ""
                        let name = value?["name"] as? String ?? ""
                        //print( id + ": " + name)
                        chat.userIds.append(id)
                        chat.userNames.append(name)
                    })
                }
            })
        }
        self.chats.append(chat)
        self.tableView.reloadData()
    })
}

I am very new to the Firebase topic. Can someone help me here?
Thanks.

Body:
Well You need to change your datamodel first. You dont need to store id value in , 12345 in this case. you can already fetch the key. Also, in /users/chats, you just can just save the chat id as either chat1 : IBDrbfku887BLIY or IBDrbfku887BLIY : true. You can always fetch them through value or the key respectively.

And in your chat document, you just need to reference the user id, i.e just get them and store them as user1 and user2. You can add more users if your usecase requires more.

Reconfigure your Data Model as follows.

Now You need 2 Objects Users and Chats as follows :

Users.swift

class User : NSObject {

        private var _name: String!
        private var _username: String!
        private var _userid: String!
        private var _userRef: DatabaseReference!

        var name: String! {
            get {
                return _name
            } set {
                _name = newValue
            }
        }

        var username : String! {
            get {
                return _username
            } set {
                _username = newValue
            }
        }

        var userid: String! {
            get {
                return _userid
            } set {
                _userid = newValue
            }
        }

        var userRef: DatabaseReference! {
            get {
                return _userRef
            } set {
                _userRef = newValue
            }
        }

        init(userid: String, userData: Dictionary<String, Any>){

            self._userid = userid

            _userRef = Database.database().reference().child(_userid)

            if let username = userData["username"] as? String {
                self._username = username
            }

            if let name = userData["name"] as? String {
                self._name = name
            }

        }

    }

Chats.swift

class Chat : NSObject {

        private var _chatid: String!
        private var _user1: String!
        private var _user2: String!
        private var _chatRef: DatabaseReference!

        var user1: String! {
            get {
                return _user1
            } set {
                _user1 = newValue
            }
        }

        var user2 : String! {
            get {
                return _user2
            } set {
                _user2 = newValue
            }
        }

        var chatid: String! {
            get {
                return _chatid
            } set {
                _chatid = newValue
            }
        }

        var chatRef: DatabaseReference! {
            get {
                return _chatRef
            } set {
                _chatRef = newValue
            }
        }

        init(chatid: String, chatData: Dictionary<String, Any>){

            self._chatid = chatid

            _chatRef = Database.database().reference().child(_chatid)

            if let user = chatData["users"] as? Dictionary<String, Any> {
                if let user1 = user["user1"] as? String {
                    self._user1 = user1
                }
                if let user2 = user["user2"] as? String {
                    self._user2 = user2
                }
            }

        }

    }

The major issue/or an overlooked issue here is the type of the data. In the /users, you id 12345 will be of type String. But when you fetch the same from /chats, it returns as Int. This downloads the value but never converts it. Always take care while seeding/testing your data.

To fetch the user's credentials just reference that through another query. This is what you can do :

var allUsers = [User]()
    var allChats = [Chat]()

    func viewDidLoad() {
        super.viewDidLoad()
        fetchAllChats()
    }

    func getUser(from userId: String, completion: @escaping (User) -> Void) {

        Database.database().reference().child("users").child(userId).observeSingleEvent(of: .value, with: { snapshot in
            if let datasnap = snapshot.value as? Dictionary<String, Any> {
                let user = User(userid: userId, userData: datasnap)
                completion(user)
            }
        })
    }

    func fetchAllChats() {
        Database.database().reference().child("chats").observeSingleEvent(of: .value, with: { snapshot in
           allChat.removeAll()
            if let snapshot = snapshot.value as? Dictionary<String, Any> {
                for snap in snapshot {
                    if let chatd = snap.value as? Dictionary<String, Any> {
                        let chat = Chat(chatid: snap.key, chatData: chatd)
                        self.allChats.append(chat)
                    }
                }
            }
            // collectionview.reloadData() <--------- only if required.
        })
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let chatData = allChats[indexPath.row]
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: CellId, for: indexPath) as! Cell
        getUser(from: chatData.user1) { user in
            cell.label.text = user.usernme
        }
        return cell
    }


问:
Is there a way to create collection of objects from another in Java (LINQ-like)?
Totally newbie question: how does one get properties from one collection of objects into another in Java?

In C# I usually use LINQ's awesome syntax for this kind of task. Here's an example:

```<code>        List<Hero> Heroes = new List<Hero>()
        {
            new Hero() { Name = "Iron Man", Superpower = "Being Iron Man, duh", Age = 48 },
            new Hero() { Name = "Spider-Man", Superpower = "Spidey things", Age = 16 }

        };

        List<AlterEgo> AlterEgos = Heroes.Select(x => new AlterEgo { Age = x.Age }).ToList();
</code>```

After the .Select, I get two AlterEgos with Ages 48 and 16. Is there a way to do this kind of thing in Java?

答:
Streams are Java's parallel of LINQ. Here's what your code would like in Java, with adaptations for style and syntax:

```<code>List<Hero> heroes = Arrays.asList(
        new Hero("Iron Man", "Being Iron Man, duh", 48),
        new Hero("Spider-Man", "Spidey things", 16)
);

List<AlterEgo> alterEgos = heroes.stream()
        .map(x -> new AlterEgo(x.getAge()))
        .collect(Collectors.toList());
</code>```

As for the follow-up in the comments, Java doesn't have proper anonymous objects, but you can create instances of anonymous classes and access their properties, as long as you can avoid naming the type. Java 10 makes this a little easier with the var keyword:

```<code>var list = heroes.stream()
        .map(x -> new Object() {
            int age = x.getAge();
            String name = x.getName();
        })
        .collect(Collectors.toList());

list.forEach(x -> System.out.println(x.age));
</code>```

Body:
Totally newbie question: how does one get properties from one collection of objects into another in Java?

In C# I usually use LINQ's awesome syntax for this kind of task. Here's an example:

        List<Hero> Heroes = new List<Hero>()
        {
            new Hero() { Name = "Iron Man", Superpower = "Being Iron Man, duh", Age = 48 },
            new Hero() { Name = "Spider-Man", Superpower = "Spidey things", Age = 16 }

        };

        List<AlterEgo> AlterEgos = Heroes.Select(x => new AlterEgo { Age = x.Age }).ToList();

After the .Select, I get two AlterEgos with Ages 48 and 16. Is there a way to do this kind of thing in Java?

Body:
Streams are Java's parallel of LINQ. Here's what your code would like in Java, with adaptations for style and syntax:

List<Hero> heroes = Arrays.asList(
        new Hero("Iron Man", "Being Iron Man, duh", 48),
        new Hero("Spider-Man", "Spidey things", 16)
);

List<AlterEgo> alterEgos = heroes.stream()
        .map(x -> new AlterEgo(x.getAge()))
        .collect(Collectors.toList());

As for the follow-up in the comments, Java doesn't have proper anonymous objects, but you can create instances of anonymous classes and access their properties, as long as you can avoid naming the type. Java 10 makes this a little easier with the var keyword:

var list = heroes.stream()
        .map(x -> new Object() {
            int age = x.getAge();
            String name = x.getName();
        })
        .collect(Collectors.toList());

list.forEach(x -> System.out.println(x.age));