问:
Angular - trouble with fetching from array
so in my angular project, I've been instructed to make selectedEmployee: EmpInfo type and set the [value] of the select to emp and then use selectedEmployee as the object that I reference to display the data. I'm really new to Angular and not quite sure how to implement that. I thought that I did it right but in the browser, I'm getting an error that says "cannot read property 'EmpKey' of undefined in tracker.component.ts. I'm really stuck, any help is greatly appreciated. Thanks!

Here's my tracker.component.ts

import { Component, OnInit, Input} from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

import { PTODataService } from './pto-data.service';
import { PTOData } from './pto-data';
import { EmpInfoService } from './emp-info.service';
import { EmpInfo } from './emp-info';

@Component({
    selector: 'pto-tracker',
    templateUrl: `./tracker.component.html`,
    styleUrls: ['./tracker.component.css']
})

export class TrackerComponent implements OnInit{
    empInfo: EmpInfo[] = new Array<EmpInfo>();
    ptoData: PTOData[];
    isHidden: boolean = false;

    selectedEmployee: EmpInfo;

    public selectedType: string = "PTO";

    constructor(
        private empInfoService: EmpInfoService,
        private ptoDataService: PTODataService) { }

    getEmpInfo(): void {
        this.empInfoService.getEmpInfos().then(
            empInfo => this.empInfo = empInfo
            );
    }

    getPTOData(): void {
        this.ptoDataService.getPTODatas().then(
            ptoData => this.ptoData = ptoData
        );
    }

    ngOnInit(): void {
        this.getEmpInfo();
        this.getPTOData();
    }

    toggleSummary(): void {
        this.isHidden = !this.isHidden;
    }
}```
</div>
</div>
</p>

<p>my tracker.component.html</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="row">
  <div [ngClass]="{'col-xs-12':isHidden === true, 'col-xs-7': isHidden !== false}">
    <button class="btn btn-default btn-primary" style="width:50px; height: 50px; float:right; padding-bottom: 10px; padding-top: 10px;margin:5px;" (click)="toggleSummary()"><i class="fa fa-pencil-square-o fa-2x" aria-hidden="true"></i></button>

    <div class="col-xs-12 no-pad" style="padding-bottom:50px;">
      <div class="col-xs-3">
        <select class="form-control" id="empName" [(ngModel)]="selectedEmployee">
          <option selected="selected" disabled>Employee Name...</option>
          <option *ngFor="let emp of empInfo | orderByLast : 'LastName'" [ngValue]="emp">{{emp.EmpID}} - {{emp.FirstName}} {{emp.LastName}}</option>
        </select>
      </div>
      <div class="col-xs-2">
        <select class="form-control" id="PTOtype" [(ngModel)]="selectedType">
          <option selected="selected" value="PTO">PTO</option>
          <option value="etoEarned">ETO - Earned</option>
          <option value="etoUsed">ETO - Used</option>
          <option value="STDLTD">STD/LTD</option>
          <option value="Uncharged">Uncharged</option>
        </select>
      </div>
    </div>
    <div class="col-xs-12">
      <table class="table table-striped table-bordered">
        <thead>
          <tr>
            <th>Date</th>
            <th>Full/Half</th>
            <th>Hours</th>
            <th>Scheduled?</th>
            <th>Notes</th>
            <th>In P/R?</th>
          </tr>
        </thead>
        <tfoot>
          <tr>
            <td colspan="6">
              <span class="requestText">Requests:</span>
            </td>
          </tr>
        </tfoot>
        <tbody>
          <tr *ngFor="let pto of ptoData">
            <ng-container *ngIf="pto.type === selectedType">
              <ng-container *ngIf="pto.EmpKey === selectedEmployee?.EmpKey">
                <td>{{pto.date | date: 'MM/dd/y'}}</td>
                <td>{{pto.fullhalf}}</td>
                <td>{{pto.hours}}</td>
                <td>{{pto.scheduled}}</td>
                <td>{{pto.notes}}</td>
                <td>{{pto.inPR}}</td>
              </ng-container>
            </ng-container>
          </tr>
        </tbody>
      </table>
    </div>
    </div>
  <div *ngIf="isHidden" class="col-xs-5">
        <pto-summary [empInfo]="selectedEmployee"></pto-summary>
  </div>
</div></code>```

my summary.component.ts

import { Component, OnInit, Input } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { EmpInfoService } from './emp-info.service';
import { TrackerComponent } from './tracker.component';
import { EmpInfo } from './emp-info';

@Component({
    selector: 'pto-summary',
    templateUrl: `./summary.component.html`,
    styleUrls: ['./summary.component.css']
})

export class SummaryComponent implements OnInit{

    empInfo: EmpInfo[];
    @Input() selectedEmployee: EmpInfo;

    timeVar = " hours";
    checkboxValue = false;

    constructor(private empInfoService: EmpInfoService) { }

    getEmpInfo(): void {
        this.empInfoService.getEmpInfos().then(
            empInfo => this.empInfo = empInfo
        );
    }

    ngOnInit(): void {
        this.getEmpInfo();
    }

    changeTime(): void {
        if (!this.checkboxValue)
        {
            this.timeVar = " hours"

            this.selectedEmployee.STDLTD = this.selectedEmployee.STDLTD * 8;
            this.selectedEmployee.Uncharged = this.selectedEmployee.Uncharged * 8;

            this.selectedEmployee.PTOBase = this.selectedEmployee.PTOBase * 8;
            this.selectedEmployee.PTOCarry = this.selectedEmployee.PTOCarry * 8;
            this.selectedEmployee.PTOBorrowed = this.selectedEmployee.PTOBorrowed * 8;
            this.selectedEmployee.PTOBalance = this.selectedEmployee.PTOBalance * 8;
            this.selectedEmployee.PTORequests = this.selectedEmployee.PTORequests * 8;
            this.selectedEmployee.PTORemaining = this.selectedEmployee.PTORemaining * 8;

            this.selectedEmployee.ETOEarned = this.selectedEmployee.ETOEarned * 8;
            this.selectedEmployee.ETORequests = this.selectedEmployee.ETORequests * 8;
            this.selectedEmployee.ETORemaining = this.selectedEmployee.ETORemaining * 8;
        }
        else
        {
            this.timeVar = " days"

            this.selectedEmployee.STDLTD = this.selectedEmployee.STDLTD / 8;
            this.selectedEmployee.Uncharged = this.selectedEmployee.Uncharged / 8;

            this.selectedEmployee.PTOBase = this.selectedEmployee.PTOBase / 8;
            this.selectedEmployee.PTOCarry = this.selectedEmployee.PTOCarry / 8;
            this.selectedEmployee.PTOBorrowed = this.selectedEmployee.PTOBorrowed / 8;
            this.selectedEmployee.PTOBalance = this.selectedEmployee.PTOBalance / 8;
            this.selectedEmployee.PTORequests = this.selectedEmployee.PTORequests / 8;
            this.selectedEmployee.PTORemaining = this.selectedEmployee.PTORemaining / 8;

            this.selectedEmployee.ETOEarned = this.selectedEmployee.ETOEarned / 8;
            this.selectedEmployee.ETORequests = this.selectedEmployee.ETORequests / 8;
            this.selectedEmployee.ETORemaining = this.selectedEmployee.ETORemaining / 8;
        }
    }
}```
</div>
</div>
</p>

<p>and my summary.component.html</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="panel panel-default">
  <div class="panel-heading">
    <h3 class="panel-title pull-left">{{selectedEmployee.LastName | uppercase}} Summary</h3>
    <div style="float: right;">
      <div class="onoffswitch">
        <input [(ngModel)]="checkboxValue" (change)="changeTime()" type="checkbox" name="onoffswitch" class="onoffswitch-checkbox" id="myonoffswitch" checked>
        <label class="onoffswitch-label" for="myonoffswitch">
          <span class="onoffswitch-inner"></span>
          <span class="onoffswitch-switch"></span>
        </label>
      </div>
    </div>
    <div class="clearfix"></div>
  </div>
  <div class="panel-body">
    <form class="form-horizontal" role="form" style="overflow-x:auto;">
      <fieldset>
        <div class="col-xs-6">
          <div class="form-group">
            <label class="col-xs-5"> Status </label>
            <div class="col-xs-7">
              <select class="form-control" id="empStatus" [(ngModel)]="selectedEmployee.EmpStat" name="empStatus">
                <option value="Current">Current</option>
                <option value="Terminated">Terminated</option>
              </select>
            </div>
          </div>
        </div>
        <div class="col-xs-6">
          <div class="form-group">
            <label class="col-xs-5"> Anniversary </label>
            <div class="col-xs-7">
              <div class="input-group">
                <input class='form-control' type="text" id="empAnniversary" [(ngModel)]="selectedEmployee.Anniversary" name="empAnniversary" />
                <span class="input-group-addon">years</span>
              </div>
            </div>
          </div>
         </div>
        <div class="col-xs-6">
          <div class="form-group">
            <label class="col-xs-5"> Start Date </label>
            <div class="col-xs-7">
              <input class='form-control' type="text" id="empStartDate" [ngModel]="selectedEmployee.StartDate | date: 'MM/dd/y'" name="empStartDate"/>
            </div>
          </div>
        </div>
        <div class="col-xs-6">
          <div class="form-group">
            <label class="col-xs-5"> Adjusted Start </label>
            <div class="col-xs-7">
              <input class='form-control' type="text" id="empAdjustedStart" [ngModel]="selectedEmployee.AdjustedStart | date: 'MM/dd/y'" name="empAdjustedStart"/>
            </div>
          </div>
        </div>
        <div class="col-xs-6">
          <div class="form-group">
            <label class="col-xs-5"> STD/LTD </label>
            <div class="col-xs-7">
              <div class="input-group">
                <input class='form-control' type="text" id="empSTDLTD" [(ngModel)]="selectedEmployee.STDLTD" name="empSTDLTD" />
                <span class="input-group-addon">{{timeVar}}</span>
              </div>
            </div>
          </div>
        </div>
        <div class="col-xs-6">
          <div class="form-group">
            <label class="col-xs-5"> Uncharged </label>
            <div class="col-xs-7">
              <div class="input-group">
                <input class='form-control' type="text" id="empUncharged" [(ngModel)]="selectedEmployee.Uncharged" name="empUncharged" />
                <span class="input-group-addon">{{timeVar}}</span>
              </div>
            </div>
          </div>
        </div>
      </fieldset>

      <fieldset>

        <h4>PTO</h4>
        <br />

        <div class="col-xs-12">
          <div class="form-group">
            <div class="col-xs-1"></div>
            <label class="col-xs-2"> Base </label>
            <div class="col-xs-3">
              <div class="input-group">
                <input class='form-control' type="text" id="ptoBase" [(ngModel)]="selectedEmployee.PTOBase" name="ptoBase" />
                <span class="input-group-addon">{{timeVar}}</span>
              </div>
            </div>
            <div class="col-xs-6">
            </div>
          </div>
        </div>
        <div class="col-xs-6">
          <div class="form-group">
            <label class="col-xs-2" style="font-weight: bold;"> + </label>
            <label class="col-xs-4"> Carryover </label>
            <div class="col-xs-6">
              <div class="input-group">
                <input class='form-control' type="text" id="ptoCarry" [(ngModel)]="selectedEmployee.PTOCarry" name="ptoCarry" />
                <span class="input-group-addon">{{timeVar}}</span>
              </div>
            </div>
          </div>
        </div>
        <div class="col-xs-6">
          <div class="form-group">
            <div class="col-xs-1"></div>
            <label class="col-xs-4"> Balance </label>
            <div class="col-xs-6">
              <div class="input-group">
                <input class='form-control' type="text" id="ptoBalance" [(ngModel)]="selectedEmployee.PTOBalance" name="ptoBalance" />
                <span class="input-group-addon">{{timeVar}}</span>
              </div>
            </div>
            <div class="col-xs-1"></div>
          </div>
        </div>
        <div class="col-xs-6">
          <div class="form-group">
            <label class="col-xs-2" style="font-weight: bold;"> ― </label>
            <label class="col-xs-4"> Borrowed </label>
            <div class="col-xs-6">
              <div class="input-group">
                <input class='form-control' type="text" id="ptoBorrowed" [(ngModel)]="selectedEmployee.PTOBorrowed" name="ptoBorrowed" />
                <span class="input-group-addon">{{timeVar}}</span>
              </div>
            </div>
          </div>
          <hr style="border: solid 1px black;border-bottom:1px solid black;clear:both" />
        </div>
        <div class="col-xs-6">
          <div class="form-group">
            <label class="col-xs-1" style="font-weight: bold;"> ― </label>
            <label class="col-xs-4"> Requests </label>
            <div class="col-xs-6">
              <div class="input-group">
                <input class='form-control' type="text" id="ptoRequests" [(ngModel)]="selectedEmployee.PTORequests" name="ptoRequests" />
                <span class="input-group-addon">{{timeVar}}</span>
              </div>
            </div>
            <div class="col-xs-1"></div>
          </div>
          <hr style="border: solid 1px black;border-bottom:1px solid black;clear:both" />
        </div>
        <div class="col-xs-6">
          <div class="form-group">
            <label class="col-xs-2" style="font-weight: bold;"> = </label>
            <label class="col-xs-4"> Balance </label>
            <div class="col-xs-6">
              <div class="input-group">
                <input class='form-control' type="text" id="ptoBalance" [(ngModel)]="selectedEmployee.PTOBalance" name="ptoBalance" />
                <span class="input-group-addon">{{timeVar}}</span>
              </div>
            </div>
          </div>
        </div>
        <div class="col-xs-6">
          <div class="form-group">
            <label class="col-xs-1" style="font-weight: bold;"> = </label>
            <label class="col-xs-4"> Available </label>
            <div class="col-xs-6">
              <div class="input-group">
                <input class='form-control' type="text" id="ptoRemaining" [(ngModel)]="selectedEmployee.PTORemaining" name="ptoRemaining" />
                <span class="input-group-addon">{{timeVar}}</span>
              </div>
            </div>
            <div class="col-xs-1"></div>
          </div>
        </div>
      </fieldset>

      <fieldset>

        <h4>ETO</h4>
        <br />

          <div class="col-xs-6">
            <div class="form-group">
              <div class="col-xs-2"></div>
              <label class="col-xs-4"> Earned </label>
              <div class="col-xs-6">
                <div class="input-group">
                  <input class='form-control' type="text" id="etoEarned" [(ngModel)]="selectedEmployee.ETOEarned" name="etoEarned" />
                  <span class="input-group-addon">{{timeVar}}</span>
                </div>
              </div>
            </div>
            <div class="form-group">
              <label class="col-xs-2"> ― </label>
              <label class="col-xs-4"> Requests </label>
              <div class="col-xs-6">
              <div class="input-group">
                <input class='form-control' type="text" id="etoRequests" [(ngModel)]="selectedEmployee.ETORequests" name="etoRequests" />
                <span class="input-group-addon">{{timeVar}}</span>
              </div>
              </div>
            </div>
            <hr style="border: solid 1px black;border-bottom:1px solid black;clear:both" />
            <div class="form-group">
              <label class="col-xs-2"> = </label>
              <label class="col-xs-4"> Available </label>
              <div class="col-xs-6">
                <div class="input-group">
                  <input class='form-control' type="text" id="etoRemaining" [(ngModel)]="selectedEmployee.ETORemaining" name="etoRemaining" />
                  <span class="input-group-addon">{{timeVar}}</span>
                </div>
              </div>
            </div>
          </div>
          <div class="col-xs-6"></div>

      </fieldset>
    </form>
  </div>
</div></code>```

答:
At line 7 of tracker.component.html you need to use two-way data binding to keep the value in sync with the model like so:

[(ngModel)]="selectedEmployee"
```

<p>Because the value is not set initially you need to use the elvis operator to access properties on the object. This will short-circuit if any part on the object chain is undefined. Like so:</p>

<pre class="lang-html prettyprint-override"><code><ng-container *ngIf="pto.EmpKey === selectedEmployee?.EmpKey">
</code>```

To pass the selected employee to the summary component you need to setup an input parameter like so:

export class SummaryComponent implements OnInit{

    @Input() selectedEmployee: EmpInfo;
}
```

<p>And then provide that to the component in the tracker-component.html like so:</p>

<pre class="lang-html prettyprint-override"><code><pto-summary [selectedEmployee]="selectedEmployee"></pto-summary>
</code>```

Body:
so in my angular project, I've been instructed to make selectedEmployee: EmpInfo type and set the [value] of the select to emp and then use selectedEmployee as the object that I reference to display the data. I'm really new to Angular and not quite sure how to implement that. I thought that I did it right but in the browser, I'm getting an error that says "cannot read property 'EmpKey' of undefined in tracker.component.ts. I'm really stuck, any help is greatly appreciated. Thanks!

Here's my tracker.component.ts

import { Component, OnInit, Input} from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

import { PTODataService } from './pto-data.service';
import { PTOData } from './pto-data';
import { EmpInfoService } from './emp-info.service';
import { EmpInfo } from './emp-info';

@Component({
    selector: 'pto-tracker',
    templateUrl: `./tracker.component.html`,
    styleUrls: ['./tracker.component.css']
})

export class TrackerComponent implements OnInit{
    empInfo: EmpInfo[] = new Array<EmpInfo>();
    ptoData: PTOData[];
    isHidden: boolean = false;

    selectedEmployee: EmpInfo;

    public selectedType: string = "PTO";

    constructor(
        private empInfoService: EmpInfoService,
        private ptoDataService: PTODataService) { }

    getEmpInfo(): void {
        this.empInfoService.getEmpInfos().then(
            empInfo => this.empInfo = empInfo
            );
    }

    getPTOData(): void {
        this.ptoDataService.getPTODatas().then(
            ptoData => this.ptoData = ptoData
        );
    }

    ngOnInit(): void {
        this.getEmpInfo();
        this.getPTOData();
    }

    toggleSummary(): void {
        this.isHidden = !this.isHidden;
    }
}

my tracker.component.html

    <button class="btn btn-default btn-primary" style="width:50px; height: 50px; float:right; padding-bottom: 10px; padding-top: 10px;margin:5px;" (click)="toggleSummary()"></button>

        <select class="form-control" id="empName" [(ngModel)]="selectedEmployee">
          <option selected="selected" disabled>Employee Name...</option>
          <option *ngFor="let emp of empInfo | orderByLast : 'LastName'" [ngValue]="emp">{{emp.EmpID}} - {{emp.FirstName}} {{emp.LastName}}</option>
        </select>

        <select class="form-control" id="PTOtype" [(ngModel)]="selectedType">
          <option selected="selected" value="PTO">PTO</option>
          <option value="etoEarned">ETO - Earned</option>
          <option value="etoUsed">ETO - Used</option>
          <option value="STDLTD">STD/LTD</option>
          <option value="Uncharged">Uncharged</option>
        </select>

            Date
            Full/Half
            Hours
            Scheduled?
            Notes
            In P/R?

              Requests:

            <ng-container *ngIf="pto.type === selectedType">
              <ng-container *ngIf="pto.EmpKey === selectedEmployee?.EmpKey">
                {{pto.date | date: 'MM/dd/y'}}
                {{pto.fullhalf}}
                {{pto.hours}}
                {{pto.scheduled}}
                {{pto.notes}}
                {{pto.inPR}}
              </ng-container>
            </ng-container>

        <pto-summary [empInfo]="selectedEmployee"></pto-summary>

my summary.component.ts

import { Component, OnInit, Input } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { EmpInfoService } from './emp-info.service';
import { TrackerComponent } from './tracker.component';
import { EmpInfo } from './emp-info';

@Component({
    selector: 'pto-summary',
    templateUrl: `./summary.component.html`,
    styleUrls: ['./summary.component.css']
})

export class SummaryComponent implements OnInit{

    empInfo: EmpInfo[];
    @Input() selectedEmployee: EmpInfo;

    timeVar = " hours";
    checkboxValue = false;

    constructor(private empInfoService: EmpInfoService) { }

    getEmpInfo(): void {
        this.empInfoService.getEmpInfos().then(
            empInfo => this.empInfo = empInfo
        );
    }

    ngOnInit(): void {
        this.getEmpInfo();
    }

    changeTime(): void {
        if (!this.checkboxValue)
        {
            this.timeVar = " hours"

            this.selectedEmployee.STDLTD = this.selectedEmployee.STDLTD * 8;
            this.selectedEmployee.Uncharged = this.selectedEmployee.Uncharged * 8;

            this.selectedEmployee.PTOBase = this.selectedEmployee.PTOBase * 8;
            this.selectedEmployee.PTOCarry = this.selectedEmployee.PTOCarry * 8;
            this.selectedEmployee.PTOBorrowed = this.selectedEmployee.PTOBorrowed * 8;
            this.selectedEmployee.PTOBalance = this.selectedEmployee.PTOBalance * 8;
            this.selectedEmployee.PTORequests = this.selectedEmployee.PTORequests * 8;
            this.selectedEmployee.PTORemaining = this.selectedEmployee.PTORemaining * 8;

            this.selectedEmployee.ETOEarned = this.selectedEmployee.ETOEarned * 8;
            this.selectedEmployee.ETORequests = this.selectedEmployee.ETORequests * 8;
            this.selectedEmployee.ETORemaining = this.selectedEmployee.ETORemaining * 8;
        }
        else
        {
            this.timeVar = " days"

            this.selectedEmployee.STDLTD = this.selectedEmployee.STDLTD / 8;
            this.selectedEmployee.Uncharged = this.selectedEmployee.Uncharged / 8;

            this.selectedEmployee.PTOBase = this.selectedEmployee.PTOBase / 8;
            this.selectedEmployee.PTOCarry = this.selectedEmployee.PTOCarry / 8;
            this.selectedEmployee.PTOBorrowed = this.selectedEmployee.PTOBorrowed / 8;
            this.selectedEmployee.PTOBalance = this.selectedEmployee.PTOBalance / 8;
            this.selectedEmployee.PTORequests = this.selectedEmployee.PTORequests / 8;
            this.selectedEmployee.PTORemaining = this.selectedEmployee.PTORemaining / 8;

            this.selectedEmployee.ETOEarned = this.selectedEmployee.ETOEarned / 8;
            this.selectedEmployee.ETORequests = this.selectedEmployee.ETORequests / 8;
            this.selectedEmployee.ETORemaining = this.selectedEmployee.ETORemaining / 8;
        }
    }
}

and my summary.component.html

{{selectedEmployee.LastName | uppercase}} Summary

        <input [(ngModel)]="checkboxValue" (change)="changeTime()" type="checkbox" name="onoffswitch" class="onoffswitch-checkbox" id="myonoffswitch" checked>

    <form class="form-horizontal" role="form" style="overflow-x:auto;">
      <fieldset>

             Status

              <select class="form-control" id="empStatus" [(ngModel)]="selectedEmployee.EmpStat" name="empStatus">
                <option value="Current">Current</option>
                <option value="Terminated">Terminated</option>
              </select>

             Anniversary

                <input class='form-control' type="text" id="empAnniversary" [(ngModel)]="selectedEmployee.Anniversary" name="empAnniversary" />
                years

             Start Date

              <input class='form-control' type="text" id="empStartDate" [ngModel]="selectedEmployee.StartDate | date: 'MM/dd/y'" name="empStartDate"/>

             Adjusted Start

              <input class='form-control' type="text" id="empAdjustedStart" [ngModel]="selectedEmployee.AdjustedStart | date: 'MM/dd/y'" name="empAdjustedStart"/>

             STD/LTD

                <input class='form-control' type="text" id="empSTDLTD" [(ngModel)]="selectedEmployee.STDLTD" name="empSTDLTD" />
                {{timeVar}}

             Uncharged

                <input class='form-control' type="text" id="empUncharged" [(ngModel)]="selectedEmployee.Uncharged" name="empUncharged" />
                {{timeVar}}

      </fieldset>

      <fieldset>

PTO

             Base

                <input class='form-control' type="text" id="ptoBase" [(ngModel)]="selectedEmployee.PTOBase" name="ptoBase" />
                {{timeVar}}

             +
             Carryover

                <input class='form-control' type="text" id="ptoCarry" [(ngModel)]="selectedEmployee.PTOCarry" name="ptoCarry" />
                {{timeVar}}

             Balance

                <input class='form-control' type="text" id="ptoBalance" [(ngModel)]="selectedEmployee.PTOBalance" name="ptoBalance" />
                {{timeVar}}

             ―
             Borrowed

                <input class='form-control' type="text" id="ptoBorrowed" [(ngModel)]="selectedEmployee.PTOBorrowed" name="ptoBorrowed" />
                {{timeVar}}

             ―
             Requests

                <input class='form-control' type="text" id="ptoRequests" [(ngModel)]="selectedEmployee.PTORequests" name="ptoRequests" />
                {{timeVar}}

             =
             Balance

                <input class='form-control' type="text" id="ptoBalance" [(ngModel)]="selectedEmployee.PTOBalance" name="ptoBalance" />
                {{timeVar}}

             =
             Available

                <input class='form-control' type="text" id="ptoRemaining" [(ngModel)]="selectedEmployee.PTORemaining" name="ptoRemaining" />
                {{timeVar}}

      </fieldset>

      <fieldset>

ETO

               Earned

                  <input class='form-control' type="text" id="etoEarned" [(ngModel)]="selectedEmployee.ETOEarned" name="etoEarned" />
                  {{timeVar}}

               ―
               Requests

                <input class='form-control' type="text" id="etoRequests" [(ngModel)]="selectedEmployee.ETORequests" name="etoRequests" />
                {{timeVar}}

               =
               Available

                  <input class='form-control' type="text" id="etoRemaining" [(ngModel)]="selectedEmployee.ETORemaining" name="etoRemaining" />
                  {{timeVar}}

      </fieldset>
    </form>

Body:
At line 7 of tracker.component.html you need to use two-way data binding to keep the value in sync with the model like so:

[(ngModel)]="selectedEmployee"

Because the value is not set initially you need to use the elvis operator to access properties on the object. This will short-circuit if any part on the object chain is undefined. Like so:

<ng-container *ngIf="pto.EmpKey === selectedEmployee?.EmpKey">

To pass the selected employee to the summary component you need to setup an input parameter like so:

export class SummaryComponent implements OnInit{

    @Input() selectedEmployee: EmpInfo;
}

And then provide that to the component in the tracker-component.html like so:

<pto-summary [selectedEmployee]="selectedEmployee"></pto-summary>


来源: stackexchange

问:
In .net, is there an opposite function to Server.HTMLEncode()?
.Net's Server.HTMLEncode() is the very helpful function that takes an HTML string and replaces special characters with their entity equivalents - "<" becomes &lt ; and so forth.

Is there a (built-in) function that does the reverse?  There doesn't seem to be, and I am incredulous.  While I could certainly write my own (and have in the past) Server.HTMLEncode has all kinds of cool handling for different string encodings and high-level unicode characters that I would really not have crash my hand-rolled decoder in a year's time.

What do other people do when they need the plain HTML back?

Update:
To answer the first batch of questions, I present the MSDN article on the
Server object, which has Encode but no Decode...  I'm as amazed as anyone.

Update2: as several alert readers have pointed out, the docs I was looking at were for classic ASP, not ASP.Net.  Thanks guys, that's an important MSDN safety tip.

答: You didn't see a HtmlDecode in the same place you found the HtmlEncode?</p>

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Eddie

OwnerDisplayName: Cristian Libardo


问:
execute if statement if a value found in a multidimensional array
I have a piece of code which sole purpose is to find a desired value in a multidimensional array and if a match is found execute a if statement.

i have used array_search() method which returns the index of the match.So it means if match is found in the first index it returns that index which is 0.That is false by definition.

So when match is found in the first index ,my if statement doesn't get executed.How to solve this porblem?

```<code>$arr = array(

   0 =>array(
       'name' => 'mr.x',
       'id' => 1
   ),
   1 =>array(
       'name'=>'mr.y',
       'id'  =>2
   )

);

$match = array_search(2,array_column($arr,'id'));

echo $match;

if($match){

    echo 'a match found !';
}
</code>```

答:
May be you would like to use this recursive search to get the value and execute the code.</p>

```<code>$found = recursive_array_search($search_item, $your_array);
if ( $found ){
    echo 'a match found !';
}

function recursive_array_search($needle,$haystack) {
    foreach($haystack as $key=>$value) {
        $current_key=$key;
        if($needle===$value OR (is_array($value) && recursive_array_search($needle,$value) !== false)) {
            return $current_key;
        }
    }
    return false;
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a piece of code which sole purpose is to find a desired value in a multidimensional array and if a match is found execute a if statement.

i have used array_search() method which returns the index of the match.So it means if match is found in the first index it returns that index which is 0.That is false by definition.

So when match is found in the first index ,my if statement doesn't get executed.How to solve this porblem?

$arr = array(

   0 =>array(
       'name' => 'mr.x',
       'id' => 1
   ),
   1 =>array(
       'name'=>'mr.y',
       'id'  =>2
   )

);

$match = array_search(2,array_column($arr,'id'));

echo $match;

if($match){

    echo 'a match found !';
}

Body:
May be you would like to use this recursive search to get the value and execute the code.

$found = recursive_array_search($search_item, $your_array);
if ( $found ){
    echo 'a match found !';
}

function recursive_array_search($needle,$haystack) {
    foreach($haystack as $key=>$value) {
        $current_key=$key;
        if($needle===$value OR (is_array($value) && recursive_array_search($needle,$value) !== false)) {
            return $current_key;
        }
    }
    return false;
}


问:
What version of the compiler is in a microsoft.net.compilers package?
Documentation for microsoft.net.compilers package (at https://www.nuget.org/packages/Microsoft.Net.Compilers/) says

.Net Compilers package. Referencing this package will cause the
  project to be built using the specific version of the C# and Visual
  Basic compilers contained in the package, as opposed to any system
  installed version.

... which begs the question: what version of the compiler is in the package?

That same page says that it supports .NET framework 4.5, but that's not the compiler version, is it?

There are several versions of the package. I assume then that different versions of the package may contain different versions of the compiler. Is there a table somewhere that specifies which compiler version is in each package version?

I guess the package contains both c# and vb compilers, but I'm only interested in c#.

答:
From https://github.com/dotnet/roslyn/wiki/NuGet-packages:

Versions 1.x mean C# 6.0 (Visual Studio 2015 and updates). For instance, 1.3.2 corresponds to the most recent update (update 3) of Visual Studio 2015.

Version 2.0 means C# 7.0 (Visual Studio 2017 version 15.0).

Version 2.1 is still C# 7.0, but with a couple fixes (Visual Studio 2017 version 15.1).

Version 2.2 is still C# 7.0, but with a couple more fixes (Visual Studio 2017 version 15.2).

Version 2.3 means C# 7.1 (Visual Studio 2017 version 15.3).

Version 2.4 is still C# 7.1 and VB 15.3, but with a couple fixes (Visual Studio 2017 version 15.4).

Version 2.6 means C# 7.2 and VB 15.5 (Visual Studio 2017 version 15.5).

Version 2.7 means C# 7.2 and VB 15.5, but with a number of fixes (Visual Studio 2017 version 15.6).

Version 2.8 means C# 7.3 (Visual Studio 2017 version 15.7)

Version 2.9 is still C# 7.3 and VB 15.5, but with more fixes (Visual Studio 2017 version 15.8)

Version 2.10 is still C# 7.3 and VB 15.5, but a couple more fixes (Visual Studio 2017 version 15.9)

Version 3.0 includes C# 8.0 beta (Visual Studio 2019 version 16.0), but 2.11 was used for preview1.

Version 3.1 includes a preview of C# 8.0 (Visual Studio 2019 version 16.1)

Version 3.2 includes a preview of C# 8.0 (Visual Studio 2019 version 16.2)

Version 3.3 includes C# 8.0 (Visual Studio 2019 version 16.3, .NET Core 3.0)

Version 3.4 includes C# 8.0 (Visual Studio 2019 version 16.4, .NET Core 3.1)

For language features, see https://github.com/dotnet/csharplang/blob/master/Language-Version-History.md

ContentLicense: CC BY-SA 4.0


问:
awk concatenate based on column value
I'm trying to concatenate strings in column 2 based on shared value in column 1.
my file is like this:

2,John Doe
2,Roger Sterling
2,Blake Chaser
3,Rocky Horror
3,Jason Biggs
3,Bill Shakespeare```
</div>
</div>
</p>

<p>and I need this:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>2,John Doe, Roger Sterling, Blake Chaser
3,Rocky Horror, Jason Biggs, Bill Shakespeare</code>```

I've tried a number of awk commands but I can't get it. Any help is appreciated

答:
```<code>awk -F "," '{arr[$1] = arr[$1] FS $2} END {for (i in arr) print i arr[i]}' file
</code>```

Title: awk concatenate based on column value

Body:
I'm trying to concatenate strings in column 2 based on shared value in column 1.
my file is like this:

2,John Doe
2,Roger Sterling
2,Blake Chaser
3,Rocky Horror
3,Jason Biggs
3,Bill Shakespeare

and I need this:

2,John Doe, Roger Sterling, Blake Chaser
3,Rocky Horror, Jason Biggs, Bill Shakespeare

I've tried a number of awk commands but I can't get it. Any help is appreciated


问:
How to select textbox values in windows form
I've set textbox as multiline, and now whenever I mouse click on muliple items of that textbox, it is shown selected. May I know how can I do this?</p>

答:
If you want to select or highlight the entered text/content of a Text-Box control, then use the following method:

textBox.Select();

Please see if this helps.

Thanks.


问:
Is operator< (less than) on pointers consistent?
Note: This question is not about total order. A total order on pointers of the same type can be obtained using std::less.

According to this, comparing two pointers with operator< isn't allowed if they point for example into different allocations.

In which sense isn't it allowed? Is it implementation defined, unspecified or undefined behaviour?

I think I read somewhere that it's unspecified. An implementation isn't required to document what the behaviour is, but there must be some behaviour. So that would mean, comparing any two pointers is still legal, but doesn't neccessarily yield a total order. Does that mean, that we still have to get a consistent result, when comparing the same two pointers twice? The general case would be: Does invoking the same unspecified behaviour twice within an application always yield the same result?

```<code>int i1, i2;
int* a = &i1;
int* b = &i2;
bool b1 = a < b; // unspecified, right?
bool b2 = a < b;
assert(b1 == b2); // Is this guaranteed to be true?
</code>```

答:
Comparing pointers as shown in your example makes little sense because "a" and "b" value depends on how is the data stored in memory, not on the content stored in that location.

Pointers are addresses in memory (usually stored as 32 bit integer). Unless you change any of them, their comparison will return the same result. You might not know what that result is, but you'll know that it'll be the same every time.

Therefore, in your case, you will get the same result for both b1 and b2, so the assertion will pass.

Here is an example where comparing pointers does make sense:

```<code>int data[1000];
int *end = data + 50;
for (int *c = data; c < end; c++)
     ... use *c
</code>```

Body:
Note: This question is not about total order. A total order on pointers of the same type can be obtained using std::less.

According to this, comparing two pointers with operator< isn't allowed if they point for example into different allocations.

In which sense isn't it allowed? Is it implementation defined, unspecified or undefined behaviour?

I think I read somewhere that it's unspecified. An implementation isn't required to document what the behaviour is, but there must be some behaviour. So that would mean, comparing any two pointers is still legal, but doesn't neccessarily yield a total order. Does that mean, that we still have to get a consistent result, when comparing the same two pointers twice? The general case would be: Does invoking the same unspecified behaviour twice within an application always yield the same result?

int i1, i2;
int* a = &i1;
int* b = &i2;
bool b1 = a < b; // unspecified, right?
bool b2 = a < b;
assert(b1 == b2); // Is this guaranteed to be true?

Body:
Comparing pointers as shown in your example makes little sense because "a" and "b" value depends on how is the data stored in memory, not on the content stored in that location.

Pointers are addresses in memory (usually stored as 32 bit integer). Unless you change any of them, their comparison will return the same result. You might not know what that result is, but you'll know that it'll be the same every time.

Therefore, in your case, you will get the same result for both b1 and b2, so the assertion will pass.

Here is an example where comparing pointers does make sense:

int data[1000];
int *end = data + 50;
for (int *c = data; c < end; c++)
     ... use *c


问:
Assigning a Series object to a DataFrame
I'm trying to do:

```<code>def processor(self, col):
    # Some work here
    col.fillna(0, inplace=True)
    return col

def main(df):
    pool = Pool(self.cpu_size)
    for series_obj, data in pool.imap(
            processor, [df[i] for i in df[col_list]]):
        print(bool(series_obj.is_copy))
        print(bool(df.is_copy))
        df[series_obj.name] = series_obj
</code>```

But I get a warning:

A value is trying to be set on a copy of a slice from a DataFrame.

How can I do the same operation with DataFrame and Series objects without this warning?

p.s.: May be it's a hint that processed series_obj is a column from the initial df, but print(bool(series_obj.is_copy)) returns False and print(bool(df.is_copy)) returns True.

The issue was in the df argument which was created using chained indexing.

答: The issue was in the df argument which was created using chained indexing. but the error was appear during execution of the main function. </p>

Body:
I'm trying to do:

def processor(self, col):
    # Some work here
    col.fillna(0, inplace=True)
    return col

def main(df):
    pool = Pool(self.cpu_size)
    for series_obj, data in pool.imap(
            processor, [df[i] for i in df[col_list]]):
        print(bool(series_obj.is_copy))
        print(bool(df.is_copy))
        df[series_obj.name] = series_obj

But I get a warning:

A value is trying to be set on a copy of a slice from a DataFrame.

How can I do the same operation with DataFrame and Series objects without this warning?

p.s.: May be it's a hint that processed series_obj is a column from the initial df, but print(bool(series_obj.is_copy)) returns False and print(bool(df.is_copy)) returns True.

The issue was in the df argument which was created using chained indexing.


问:
Meteor node.js latest version
Why does Meteor use node.js 4.8.2 while the latest version of node.js is 7.7.3?

```<code>$ node --version
    v7.7.3

$ meteor node --version
    v4.8.2
</code>```

答:
update: According to the PR for Meteor 1.6 , it will pack Node v8.

Because Meteor is a big framework and is hard to keep such a big framework stable and up to date with Node.

As Meteor 1.5 has been just released, it is developed on Node v4.

According to Ben from the MDG, the bundled version of Node for Meteor will be updated to the next LTS (Node v6) on the next Meteor 1.6 release.

The plan for Meteor 1.6 is simple: upgrade Meteor from Node 4 to Node 6, now that Node 4 no longer enjoys long-term support (LTS), and Node 6 is the official stable version. Much of this work has already happened in parallel with Meteor 1.5, so we anticipate a much shorter release cycle for Meteor 1.6. Please see this pull request if you want to get involved, as your help will surely speed that effort along.

Title: Meteor node.js latest version

Body:
Why does Meteor use node.js 4.8.2 while the latest version of node.js is 7.7.3?

$ node --version
    v7.7.3

$ meteor node --version
    v4.8.2


问:
How Can I Get Mitmproxy Docker to Work on Windows Bash?
When I try running mitmproxy Docker container on Windows bash, I get an error message that the Docker daemon isn't running. How can I get it to run?

```<code>docker run --rm -it -p 8080:8080 mitmproxy/mitmproxy

docker: Cannot connect to the Docker daemon. Is the docker daemon running on this host?.
</code>```

答:
You need to do two things to get mitmproxy Docker container to work on Windows bash.

First, in bash: export DOCKER_HOST=tcp://127.0.0.1:2375

Secondly, in Windows: check the box in Docker Settings->General->"Expose daemon on tcp://localhost:2375 without TLS"

Now the following command will run correctly in bash.

```<code>docker run --rm -it -p 8080:8080 mitmproxy/mitmproxy
</code>```

Body:
When I try running mitmproxy Docker container on Windows bash, I get an error message that the Docker daemon isn't running. How can I get it to run?

docker run --rm -it -p 8080:8080 mitmproxy/mitmproxy

docker: Cannot connect to the Docker daemon. Is the docker daemon running on this host?.

Body:
You need to do two things to get mitmproxy Docker container to work on Windows bash.

First, in bash: export DOCKER_HOST=tcp://127.0.0.1:2375

Secondly, in Windows: check the box in Docker Settings->General->"Expose daemon on tcp://localhost:2375 without TLS"

Now the following command will run correctly in bash.

docker run --rm -it -p 8080:8080 mitmproxy/mitmproxy


问:
drupal 6.19 password reset redirect
I trying in drupal 6.19  to redirect the 'user/password' page after submit to 'alter location'   then user page.

I am using in theme hook to get the preprocess function and in it I edit the $variables as:

```<code>$variables['form']['#action'] = 'alter location';
</code>```

and after that I use drupal_render() .

in the drupal debug I see that the #action is set to the 'alter location' but in the
html tag I still see action='user/password' and it not redirect me to the desired location.

Thanks in advance

答:
thanks!!!

I solve it by useing -> hook_form_FORM_ID_alter function as like.... mymodulename_form_FORM_ID_alter

as saw here link text

this is what I did and it did the job for me:

function mymodulename_form_FORM_ID_alter (&$form){
  $form['#action'] = 'alter_location';
}

Title: drupal 6.19 password reset redirect

Body:
I trying in drupal 6.19  to redirect the 'user/password' page after submit to 'alter location'   then user page.

I am using in theme hook to get the preprocess function and in it I edit the $variables as:

$variables['form']['#action'] = 'alter location';

and after that I use drupal_render() .

in the drupal debug I see that the #action is set to the 'alter location' but in the
html tag I still see action='user/password' and it not redirect me to the desired location.

Thanks in advance


问:
Elastic Beanstalk with CloudWatch logs and Nginx
I have activated the CloudWatch logs in my EBS Application. I have enabled like screenshot attached:

But when I look in awslogs.log, I can find all the time this error:

```<code>cwlogs.push.stream - WARNING - 3317 - Thread-1 - No file is found with given path '/var/log/httpd/error.log*'.
cwlogs.push.stream - WARNING - 3317 - Thread-1 - No file is found with given path '/var/log/httpd/access.log*'.
</code>```

I don't know why, because httpd is a service from Apache, and I'm working with Nginx (with Node.js as origin).

How can I disable/remove this error?

Thanks.

答:
This is happening because the awslogs application on your EC2 instance is looking for those files to send to the CloudWatch.

You can check and edit the configuration file located at:

```<code>/etc/awslogs/awslogs.conf
</code>```

Make sure to restart the service:

```<code>sudo service awslogs restart
</code>```

You can specify your own files there and create different groups and what not.

Resources:

https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/AgentReference.html

Body:
I have activated the CloudWatch logs in my EBS Application. I have enabled like screenshot attached:

But when I look in awslogs.log, I can find all the time this error:

cwlogs.push.stream - WARNING - 3317 - Thread-1 - No file is found with given path '/var/log/httpd/error.log*'.
cwlogs.push.stream - WARNING - 3317 - Thread-1 - No file is found with given path '/var/log/httpd/access.log*'.

I don't know why, because httpd is a service from Apache, and I'm working with Nginx (with Node.js as origin).

How can I disable/remove this error?

Thanks.

Body:
This is happening because the awslogs application on your EC2 instance is looking for those files to send to the CloudWatch.

You can check and edit the configuration file located at:

/etc/awslogs/awslogs.conf

Make sure to restart the service:

sudo service awslogs restart

You can specify your own files there and create different groups and what not.

Resources:

https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/AgentReference.html


问:
HTML panel to appear/disappear depending on DataTables Select
Im using datatables responsive/select right now to display some data. How would I go about making it so when I click on any of these rows in the table, it opens up the "col-md-6" panel? So hidden when no rows are selected, then shown when a row is selected.

```<code><!-- begin row -->
<div class="row">
    <!-- begin col-2 -->
    <div class="col-md-2">
        <div id="menu-panel"></div>
        <!-- begin panel -->
        <div class="panel panel-inverse">
            <div class="panel-heading">
                <div class="panel-heading-btn">
                    <a href="javascript:;" class="btn btn-xs btn-icon btn-circle btn-default" data-click="panel-expand"><i class="fa fa-expand"></i></a>
                </div>
                <h4 class="panel-title">Digital Inputs</h4>
            </div>
            <div class="alert alert-info fade in">
                <button type="button" class="close" data-dismiss="alert">
                    <span aria-hidden="true">×</span>
                </button>
                Click on a Digital Input to edit its properties.
            </div>
            <div class="panel-body">
                <table id="data-table" class="table table-striped table-bordered nowrap" width="100%">
                    <thead>
                        <tr>
                            <th>Input</th>
                            <th>Name</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr class="gradeA">
                            <td>1</td>
                            <td>Digital Input 1</td>
                        </tr>
                        <tr class="gradeA">
                            <td>2</td>
                            <td>Digital Input 2</td>
                        </tr>
                        <tr class="gradeA">
                            <td>3</td>
                            <td>Digital Input 3</td>
                        </tr>
                        <tr class="gradeA">
                            <td>4</td>
                            <td>Digital Input 4</td>
                        </tr>
                        <tr class="gradeA">
                            <td>5</td>
                            <td>Digital Input 5</td>
                        </tr>
                        <tr class="gradeA">
                            <td>6</td>
                            <td>Digital Input 6</td>
                        </tr>
                        <tr class="gradeA">
                            <td>7</td>
                            <td>Digital Input 7</td>
                        </tr>
                        <tr class="gradeA">
                            <td>8</td>
                            <td>Digital Input 8</td>
                        </tr>
                        <tr class="gradeA">
                            <td>9</td>
                            <td>Digital Input 9</td>
                        </tr>
                        <tr class="gradeA">
                            <td>10</td>
                            <td>Digital Input 10</td>
                        </tr>
                        <tr class="gradeA">
                            <td>11</td>
                            <td>Digital Input 11</td>
                        </tr>
                        <tr class="gradeA">
                            <td>12</td>
                            <td>Digital Input 12</td>
                        </tr>
                        <tr class="gradeA">
                            <td>13</td>
                            <td>Digital Input 13</td>
                        </tr>
                        <tr class="gradeA">
                            <td>14</td>
                            <td>Digital Input 14</td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
        <!-- end panel -->
    </div>

    <!-- begin col-2 -->
    <div class="col-md-6">
        <!-- begin panel -->
        <div class="panel panel-inverse" data-sortable-id="form-stuff-2">
            <div class="panel-heading">
                <div class="panel-heading-btn">
                    <a href="javascript:;" class="btn btn-xs btn-icon btn-circle btn-default" data-click="panel-expand"><i class="fa fa-expand"></i></a>
                </div>
                <h4 class="panel-title">New RTU FZB-1000 - FZB-1000</h4>
            </div>
            <div class="panel-body">
                <form class="form-horizontal" action="/" method="POST">
                <legend>Digital Input Basic Settings</legend>
                    <div class="form-group">
                        <label class="col-md-4 control-label">Digital Input:</label>
                        <div class="col-md-8">
                            <input type="text" class="form-control" placeholder="1" disabled />
                        </div>
                    </div>
                     <div class="form-group">
                            <label class="col-md-4 control-label">Display Input:</label>
                            <div class="col-md-2">
                                <input type="checkbox" name="" value="" checked><br>
                            </div>
                    </div>
                    <div class="form-group">
                            <label class="col-md-4 control-label">Signal Name:</label>
                            <div class="col-md-8">
                                <input type="device" class="form-control" value="Digital Input 1" />
                            </div>
                        </div>
            </div>
        </div>
        <!-- end panel -->
        <div class="col-md-8 col-md-offset-4">
            <button type="submit" class="btn btn-sm btn-primary m-r-5">Save</button>
            <button type="submit" class="btn btn-sm btn-default">Cancel</button>
        </div>
    </div>
    <!-- end col-10 -->

</div>
<!-- end row -->
</code>```

```<code>App.restartGlobalFunction();
App.setPageTitle('Color Admin | Managed Tables - Select');
$.getScript('assets/plugins/DataTables/media/js/jquery.dataTables.js').done(function() {
$.getScript('assets/plugins/DataTables/media/js/dataTables.bootstrap.min.js').done(function() {
    $.getScript('assets/plugins/DataTables/extensions/Select/js/dataTables.select.min.js').done(function() {
        $.getScript('assets/plugins/DataTables/extensions/Responsive/js/dataTables.responsive.min.js').done(function() {
            $.getScript('assets/js/table-manage-select.demo.min.js').done(function() {
                TableManageTableSelect.init();
            });
        });
    });
});
});
</code>```

答:
You can do something like this.. give your input field id for example
digital input: id="digital-input-number" and for digital signal id="digital-input-name" and here goes the code...

```<code> $('.gradeA td').on('click',function(){
                var text=[];
                 text = $(this).parent().find('td');
                    //console.log(text[0].innerText);
                   // console.log(text[1].innerText);
                $("#digital-input-number").val(text[0].innerText);
                $("#digital-input-name").val(text[1].innerText);

            });
</code>```

this code will put the value of your table to form dynamically i.e you click on one row data of that row goes to the form which i suppose you want to see.

Body:
Im using datatables responsive/select right now to display some data. How would I go about making it so when I click on any of these rows in the table, it opens up the "col-md-6" panel? So hidden when no rows are selected, then shown when a row is selected.

Digital Inputs

                <button type="button" class="close" data-dismiss="alert">
                    ×
                </button>
                Click on a Digital Input to edit its properties.

                            Input
                            Name

                            1
                            Digital Input 1

                            2
                            Digital Input 2

                            3
                            Digital Input 3

                            4
                            Digital Input 4

                            5
                            Digital Input 5

                            6
                            Digital Input 6

                            7
                            Digital Input 7

                            8
                            Digital Input 8

                            9
                            Digital Input 9

                            10
                            Digital Input 10

                            11
                            Digital Input 11

                            12
                            Digital Input 12

                            13
                            Digital Input 13

                            14
                            Digital Input 14

New RTU FZB-1000 - FZB-1000

                <form class="form-horizontal" action="/" method="POST">
                <legend>Digital Input Basic Settings</legend>

                        Digital Input:

                            <input type="text" class="form-control" placeholder="1" disabled />

                            Display Input:

                                <input type="checkbox" name="" value="" checked>

                            Signal Name:

                                <input type="device" class="form-control" value="Digital Input 1" />

            <button type="submit" class="btn btn-sm btn-primary m-r-5">Save</button>
            <button type="submit" class="btn btn-sm btn-default">Cancel</button>

App.restartGlobalFunction();
App.setPageTitle('Color Admin | Managed Tables - Select');
$.getScript('assets/plugins/DataTables/media/js/jquery.dataTables.js').done(function() {
$.getScript('assets/plugins/DataTables/media/js/dataTables.bootstrap.min.js').done(function() {
    $.getScript('assets/plugins/DataTables/extensions/Select/js/dataTables.select.min.js').done(function() {
        $.getScript('assets/plugins/DataTables/extensions/Responsive/js/dataTables.responsive.min.js').done(function() {
            $.getScript('assets/js/table-manage-select.demo.min.js').done(function() {
                TableManageTableSelect.init();
            });
        });
    });
});
});

Body:
You can do something like this.. give your input field id for example
digital input: id="digital-input-number" and for digital signal id="digital-input-name" and here goes the code...

 $('.gradeA td').on('click',function(){
                var text=[];
                 text = $(this).parent().find('td');
                    //console.log(text[0].innerText);
                   // console.log(text[1].innerText);
                $("#digital-input-number").val(text[0].innerText);
                $("#digital-input-name").val(text[1].innerText);

            });

this code will put the value of your table to form dynamically i.e you click on one row data of that row goes to the form which i suppose you want to see.


问:
CSS Interactation (Pointer) Media Query at risk?
W3C's Media Query Level 4 Working Draft (updated May 19, 2017) now states that interactive media queries are "at risk." What does this mean?

According to caniuse.com, this feature has already been adopted by most modern browsers and I was strongly considering implementing a strategy for hover effects that relies on this technology, but this "at risk" notice gives me pause.

答:
The document itself explains this tag:

The following features are at-risk, and may be dropped during the CR period:

the hover, any-hover, pointer, and any-pointer media features

“At-risk” is a W3C Process term-of-art, and does not necessarily imply that the feature is in danger of being dropped or delayed. It means that the WG believes the feature may have difficulty being interoperably implemented in a timely manner, and marking it as such allows the WG to drop the feature if necessary when transitioning to the Proposed Rec stage, without having to publish a new Candidate Rec without the feature first.

-- https://www.w3.org/TR/mediaqueries-4/#status


问:
Validate if one of two form fields is filled?
At least one of the two fields is required, if field 1 is filled or field 2 is filled the form is sent, the required is just one of them filled. I'm trying to do this with the code below, but isn't working fine, this is working only validating like required the field 1 (text1). Thank you!

var field1 = text1;
var field2 = text2;

if (text2.length) {
    if (!field1.length || !field2.length) {
        return false;
    }
} else if (!field1.length) {
    return false;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="text" placeholder="text 1*" name="text1" class="text1" data-target="previewText1" maxlength="11">
<input type="text" placeholder="text 2" value="" name="text2" class="text2" data-target="previewText2" maxlength="11"></code>```

答:
Like that :</p>

```<code>var field1 = document.getElementsByClassName("text1").value;
var field2 = document.getElementsByClassName("text2").value;

// Check if one of the fields is not empty
if (field1.length || field2.length) {
        return true;
}
return false;
</code>```

Body:
At least one of the two fields is required, if field 1 is filled or field 2 is filled the form is sent, the required is just one of them filled. I'm trying to do this with the code below, but isn't working fine, this is working only validating like required the field 1 (text1). Thank you!

var field1 = text1;
var field2 = text2;

if (text2.length) {
    if (!field1.length || !field2.length) {
        return false;
    }
} else if (!field1.length) {
    return false;
}

<input type="text" placeholder="text 1*" name="text1" class="text1" data-target="previewText1" maxlength="11">
<input type="text" placeholder="text 2" value="" name="text2" class="text2" data-target="previewText2" maxlength="11">

Body:
Like that :

var field1 = document.getElementsByClassName("text1").value;
var field2 = document.getElementsByClassName("text2").value;

// Check if one of the fields is not empty
if (field1.length || field2.length) {
        return true;
}
return false;


问:
How to find out the location of the httpd.conf configuration file controlling the behavior of the python 2.7 httpserver module.?
I am running python -m httpserver on Macintosh OS X.

Here's the Python 2.7 code implementing the httpserver:

```<code>import CGIHTTPServer
import BaseHTTPServer

class Handler(CGIHTTPServer.CGIHTTPRequestHandler):
    cgi_directories = ["/cgi"]

PORT = 9999

httpd = BaseHTTPServer.HTTPServer(("", PORT), Handler)
print "serving at port", PORT
httpd.serve_forever()
</code>```

When I type at the web browser http://localhost:9999/adder.html, I wish to find out the location of the httpd.conf configuration file controlling the behavior of the python 2.7 httpserver module.

There is also an apache24 httpd daemon process running simultaneously. I would guess that they are both using different httpd.conf files in different locations. The httpd.conf file corresponding to the apache24 httpd daemon process is frozen in root read onlypermission which I cannot change so that I make the python 2.7 cgi script executable through the auspices of the cgi module as shown below in the excerpt from this URL,
Python script does not run through CGI on Apache2 because Lesley University's information technology specialists have blocked users like myself from running operating system command as sudo .

Without the cgi_module, even code that is chmod +x will not be executable, so uncomment this line:

LoadModule cgi_module libexec/apache2/mod_cgi.so

And change your Directory to look like this (mine works like this):

    AllowOverride None
    Allow from all
    Require all granted
    Options ExecCGI
    AddHandler cgi-script .py

Without this change to the responsible httpd.conf file, I get the following
nonsensical message:

Opening adder.cgi , You have chosen to open adder.gui which is a binary file(5.0KB) from httpd://localhost.9999. Would you like to save this file? Cancel or Save

instead of seeing adder.cgi launch a child process.

I am hypothesizing that the python 2.7 httpserver module can reference a non-default httpd.conf in  subdirectory relative to the current working directory.

Please let me know if you need more data from me. Thank you for looking at this question.

答:
After reading the ServerFault article https://serverfault.com/questions/168132/setting-up-cgihttpserver-on-osx titled "Setting up CGIHTTPServer on OSX", my Python 2.7 CGI script using /usr/bin/env python was successfully served on a desktop MacIntosh OS X running CGIHTTPServer when I browsed to http://127.0.0.1:8000/WWW/test.py.

Apparently the CGIHTTPServer.py class does not read from the Apache Web server configuration file httpd.conf. Instead the information contained in httpd.conf is "baked into" the CGIHTTPServer.py class source code.

Body:
I am running python -m httpserver on Macintosh OS X.

Here's the Python 2.7 code implementing the httpserver:

import CGIHTTPServer
import BaseHTTPServer

class Handler(CGIHTTPServer.CGIHTTPRequestHandler):
    cgi_directories = ["/cgi"]

PORT = 9999

httpd = BaseHTTPServer.HTTPServer(("", PORT), Handler)
print "serving at port", PORT
httpd.serve_forever()

When I type at the web browser http://localhost:9999/adder.html, I wish to find out the location of the httpd.conf configuration file controlling the behavior of the python 2.7 httpserver module.

There is also an apache24 httpd daemon process running simultaneously. I would guess that they are both using different httpd.conf files in different locations. The httpd.conf file corresponding to the apache24 httpd daemon process is frozen in root read onlypermission which I cannot change so that I make the python 2.7 cgi script executable through the auspices of the cgi module as shown below in the excerpt from this URL,
Python script does not run through CGI on Apache2 because Lesley University's information technology specialists have blocked users like myself from running operating system command as sudo .

Without the cgi_module, even code that is chmod +x will not be executable, so uncomment this line:

LoadModule cgi_module libexec/apache2/mod_cgi.so

And change your Directory to look like this (mine works like this):

    AllowOverride None
    Allow from all
    Require all granted
    Options ExecCGI
    AddHandler cgi-script .py

Without this change to the responsible httpd.conf file, I get the following
nonsensical message:

Opening adder.cgi , You have chosen to open adder.gui which is a binary file(5.0KB) from httpd://localhost.9999. Would you like to save this file? Cancel or Save

instead of seeing adder.cgi launch a child process.

I am hypothesizing that the python 2.7 httpserver module can reference a non-default httpd.conf in  subdirectory relative to the current working directory.

Please let me know if you need more data from me. Thank you for looking at this question.


问:
DateTime parsing problem (DateTime.ParseExact)
[Please vote to close this - see my last comment.]

Hi,

Something like this:

```<code>DateTime.ParseExact("25/12/2008 00:00:00", "dd/MM/yyyy HH:mm:ss", CultureInfo.InvariantCulture);
</code>```

works fine on my development machine but not after deployment (server).

I guess it has to do with some time zone configuration. I have tried:

```<code><%@ ... UICulture="en" Culture="en-US" %>
</code>```

with no avail. Any suggestions on a postcard please. Thanks.

Christian

PS: Exception:

String was not recognized as a valid DateTime

PPS: I have updated the question. I actually feed in the time bit. sorry about that!

PPPS:
I have now realised that all this has to do with Excel and oledb. The string 25/12/2008 looks like this "12/25/2008 12:00:00 AM" on the server and like this "25/12/2008 00:00:00" on the developement machine. I adjusted the time zone of the server to UK without avail. What else can I do? Thank and sorry about all this confusion!!!

答:
Something like this

You'd do better posting exactly what failed, and the exact error, rather than "something like" what failed.

I would expect your sample to give a FormatException, since the string you're converting ("25/12/2008", no time) does not match the format specified ("dd/MM/yyyy hh:mm:ss").

Also a bit strange to be using hh rather than HH in your format - hh is a 12-hour clock.

I would expect any of the following to work.

```<code>// No time component
DateTime.ParseExact("25/12/2008", "dd/MM/yyyy", new CultureInfo("en-US"));

// Works for hours <=12, result is always AM
DateTime.ParseExact("25/12/2008 11:00:00", "dd/MM/yyyy hh:mm:ss", new CultureInfo("en-US"));

// Works for hours using 24-hour clock
DateTime.ParseExact("25/12/2008 13:00:00", "dd/MM/yyyy HH:mm:ss", new CultureInfo("en-US"));
</code>```

Body:
[Please vote to close this - see my last comment.]

Hi,

Something like this:

DateTime.ParseExact("25/12/2008 00:00:00", "dd/MM/yyyy HH:mm:ss", CultureInfo.InvariantCulture);

works fine on my development machine but not after deployment (server).

I guess it has to do with some time zone configuration. I have tried:

<%@ ... UICulture="en" Culture="en-US" %>

with no avail. Any suggestions on a postcard please. Thanks.

Christian

PS: Exception:

String was not recognized as a valid DateTime

PPS: I have updated the question. I actually feed in the time bit. sorry about that!

PPPS:
I have now realised that all this has to do with Excel and oledb. The string 25/12/2008 looks like this "12/25/2008 12:00:00 AM" on the server and like this "25/12/2008 00:00:00" on the developement machine. I adjusted the time zone of the server to UK without avail. What else can I do? Thank and sorry about all this confusion!!!

Body:
Something like this

You'd do better posting exactly what failed, and the exact error, rather than "something like" what failed.

I would expect your sample to give a FormatException, since the string you're converting ("25/12/2008", no time) does not match the format specified ("dd/MM/yyyy hh:mm:ss").

Also a bit strange to be using hh rather than HH in your format - hh is a 12-hour clock.

I would expect any of the following to work.

// No time component
DateTime.ParseExact("25/12/2008", "dd/MM/yyyy", new CultureInfo("en-US"));

// Works for hours <=12, result is always AM
DateTime.ParseExact("25/12/2008 11:00:00", "dd/MM/yyyy hh:mm:ss", new CultureInfo("en-US"));

// Works for hours using 24-hour clock
DateTime.ParseExact("25/12/2008 13:00:00", "dd/MM/yyyy HH:mm:ss", new CultureInfo("en-US"));


问:
Android: animation works by code but not by xml
I have a very simple animation: an imageview has to go up and then down all the time. Initially I tried with xml:

```<code><set xmlns:android="http://schemas.android.com/apk/res/android"
 android:shareInterpolator="false"
 android:fillAfter="true">
<set
    android:interpolator="@android:anim/linear_interpolator"
    android:repeatCount="-1"
    android:repeatMode="reverse">
    <translate
        android:fromYDelta="0"
        android:toYDelta="10"
        android:duration="300">
    </translate>
</set>
</code>```

```<code>Animation mAnimation= AnimationUtils.loadAnimation(this, R.anim.myanimation);
immagineNemico.startAnimation(mAnimation);
</code>```

But it didn't work:my imageview didn't go up, only down. So I read an answer of a question and I did the animation by code:

```<code>    immagineNemico.setVisibility(View.VISIBLE);
    TranslateAnimation mAnimation = new TranslateAnimation(
            TranslateAnimation.ABSOLUTE, 0f,
            TranslateAnimation.ABSOLUTE, 0f,
            TranslateAnimation.RELATIVE_TO_PARENT, 0f,
            TranslateAnimation.RELATIVE_TO_PARENT, 0.02f);
    mAnimation.setDuration(300);
    mAnimation.setRepeatCount(-1);
    mAnimation.setRepeatMode(Animation.REVERSE);
    mAnimation.setInterpolator(new LinearInterpolator());
    immagineNemico.setAnimation(mAnimation);
</code>```

And it worked. But why didn't the xml animation work? They are almost the same! Where is the error?

答:
I've experienced the same issue: animations work when set by code but not in XML. The short answer is that there are bugs/intentionally confusing design in Android animations where some XML elements are ignored.

This answer to a related question is what first tipped me off that there would be things that work when done programmatically vs. via XML: https://stackoverflow.com/a/6351812/8003750

I know this is not the most satisfying answer but in short - even if the XML is perfect, there are cases where it will not work.

Body:
I have a very simple animation: an imageview has to go up and then down all the time. Initially I tried with xml:

<set xmlns:android="http://schemas.android.com/apk/res/android"
 android:shareInterpolator="false"
 android:fillAfter="true">
<set
    android:interpolator="@android:anim/linear_interpolator"
    android:repeatCount="-1"
    android:repeatMode="reverse">
    <translate
        android:fromYDelta="0"
        android:toYDelta="10"
        android:duration="300">
    </translate>
</set>

Animation mAnimation= AnimationUtils.loadAnimation(this, R.anim.myanimation);
immagineNemico.startAnimation(mAnimation);

But it didn't work:my imageview didn't go up, only down. So I read an answer of a question and I did the animation by code:

    immagineNemico.setVisibility(View.VISIBLE);
    TranslateAnimation mAnimation = new TranslateAnimation(
            TranslateAnimation.ABSOLUTE, 0f,
            TranslateAnimation.ABSOLUTE, 0f,
            TranslateAnimation.RELATIVE_TO_PARENT, 0f,
            TranslateAnimation.RELATIVE_TO_PARENT, 0.02f);
    mAnimation.setDuration(300);
    mAnimation.setRepeatCount(-1);
    mAnimation.setRepeatMode(Animation.REVERSE);
    mAnimation.setInterpolator(new LinearInterpolator());
    immagineNemico.setAnimation(mAnimation);

And it worked. But why didn't the xml animation work? They are almost the same! Where is the error?


问:
Switching branch on Xcode 9
I am having trouble finding the menu item to switch branch using Xcode 9. The working copies menu seems to have disappeared. Any ideas?

Xcode 9

Xcode 8

答:
Press ⌘2 to open the new Source Control Navigator.

Right-click on the master icon.

To switch to a different branch

Right-click on a non-current branch

Choose Checkout...

Press ↩ or click on the Checkout button.

Title: Switching branch on Xcode 9


问:
window.location.reload doesn't work
I have a timer on my page for 10 min. and when time exceed page supposed to refresh itself and remove the session values.

It was working very well but suddenly it stopped working.. Timer gets stuck at 0:01.

It's look like when location.reload() executes then page get stuck. Explorer's status bar keep showing the loading icon.. over and over again.

My code is below:

```<code><script>
                    var counter = setInterval(timer, 1000);

                    function timer() {
                        count = count - 1;

                        // if time exceed then refresh the page.
                        if (count <= 0) {
                            location.reload();
                        }
                        else
                        {
                            var timerSpan = document.getElementById("timerCountdown");

                            if (count <= timerTurnToRed) {
                                //Make Red
                                timerSpan.className = "finalCountdown";
                            }

                            // Calculate remaining minutes & seconds
                            var remainingMinutes = Math.floor(count / 60)

                            // Check if it is negative
                            if (remainingMinutes < 0)
                                location.reload();

                            var remainingSecs = count - (remainingMinutes * 60);
                            if (remainingSecs < 10) {
                                remainingSecs = "0" + remainingSecs.toString();
                            }

                            timerSpan.innerHTML = remainingMinutes + ":" + remainingSecs;
                        }
                    }
                </script>
</code>```

答:
Don't get where is the problem it works as expected. StackOverflow code evaluator will prevent reloading.

var count = 15;
var timerTurnToRed = 10;
var counter = setInterval(timer, 1000);

                    function timer() {
                        count--;

                        // if time exceed then refresh the page.
                        if (count <= 0) {
                            location.reload();
                        }
                        else
                        {
                            var timerSpan = document.getElementById("timerCountdown");

                            if (count <= timerTurnToRed) {
                                //Make Red
                                timerSpan.className = "finalCountdown";
                            }

                            var remainingMinutes = Math.floor(count / 60);

                            // Check if it is negative
                            if (remainingMinutes < 0)
                                location.reload();

                            var remainingSecs = count - (remainingMinutes * 60);
                            if (remainingSecs < 10) {
                                remainingSecs = "0" + remainingSecs.toString();
                            }

                            timerSpan.innerHTML = remainingMinutes + ":" + remainingSecs;
                        }
                    }```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.finalCountdown {color: red;}</code>```

```

Title: window.location.reload doesn't work

Body:
Don't get where is the problem it works as expected. StackOverflow code evaluator will prevent reloading.

var count = 15;
var timerTurnToRed = 10;
var counter = setInterval(timer, 1000);

                    function timer() {
                        count--;

                        // if time exceed then refresh the page.
                        if (count <= 0) {
                            location.reload();
                        }
                        else
                        {
                            var timerSpan = document.getElementById("timerCountdown");

                            if (count <= timerTurnToRed) {
                                //Make Red
                                timerSpan.className = "finalCountdown";
                            }

                            var remainingMinutes = Math.floor(count / 60);

                            // Check if it is negative
                            if (remainingMinutes < 0)
                                location.reload();

                            var remainingSecs = count - (remainingMinutes * 60);
                            if (remainingSecs < 10) {
                                remainingSecs = "0" + remainingSecs.toString();
                            }

                            timerSpan.innerHTML = remainingMinutes + ":" + remainingSecs;
                        }
                    }

.finalCountdown {color: red;}

<div id="timerCountdown"></div>


问:
Stuck in the following dp code
I wrote the following dp code for finding the prime factors of a number.

```<code>#include <bits/stdc++.h>
#define max 1000001
using namespace std;
vector <int> prime;
vector<bool> isprime(max,true);
vector<bool> visited(max,false);
vector<int> data(max,-1);
void dp(int n,int last)
{
    if(n >= max || visited[n])
        return;
    visited[n] = true;
    for(int i = last;i<prime.size();i++)
    {
        if(n*prime[i] >= max || data[n*prime[i]] != -1)
            return;
        data[n*prime[i]] = prime[i];
        dp(n*prime[i],i);
    }
}
int main()
{
    isprime[1] = false;
    data[1] = 1;
    for(int i = 4;i<max;i += 2)
        isprime[i] = false;
    for(int i = 3; i*i< max;i += 2)
    {
        for(int j = i*i; j < max;j += i)
            isprime[j] = false;
    }
    prime.push_back(2);
    data[2] = 2;
    for(int i =3;i<max;i += 2)
        if(isprime[i])
        {
            prime.push_back(i);
            data[i] = i;
        }

    for(int i = 0;i<prime.size();i++)
    {
        dp(prime[i],i);
    }
        cout<<"...1\n";
    for(int i = 2;i<=8000;i++)
    {
        cout<<i<<" :- ";
        int temp = i;
        while(temp!= 1)
        {
            cout<<data[temp]<<" ";
            temp = temp/data[temp];
        }
        cout<<endl;
    }

    return 0;
}
</code>```

Here, last is the last index of prime number n.
But I am getting segmentation fault for this, when I change max to 10001, it runs perfectly. I'm not getting why is this happening since the data-structures used are 1-d vectors which can hold values up to 10^6 easily.

答:
I checked your program out using GDB. The segfault is taking place at this line:

```<code>if(n*prime[i] >= max || data[n*prime[i]] != -1)
</code>```

In your first ever call to DP in your for loop, where you call dp(2,0), the recursive calls eventually generate this call: dp(92692,2585).

```<code>92692 * 2585 = 239608820
</code>```

This number is larger than a 32 bit integer can hold, so the r-value generated by the integer multiplication of those two numbers overflows and becomes negative. nprime[i] becomes negative, so your first condition of the above loop fails, and the second is checked. data[n * prime[i]] is accessed, and since n*prime[i] is negative, your program accesses invalid memory and segfaults. To fix this, simply change n to a long long in your parameter list and you should be fine.

```<code>void dp(long long n, int last)
</code>```

Title: Stuck in the following dp code

Body:
I wrote the following dp code for finding the prime factors of a number.

#include <bits/stdc++.h>
#define max 1000001
using namespace std;
vector <int> prime;
vector<bool> isprime(max,true);
vector<bool> visited(max,false);
vector<int> data(max,-1);
void dp(int n,int last)
{
    if(n >= max || visited[n])
        return;
    visited[n] = true;
    for(int i = last;i<prime.size();i++)
    {
        if(n*prime[i] >= max || data[n*prime[i]] != -1)
            return;
        data[n*prime[i]] = prime[i];
        dp(n*prime[i],i);
    }
}
int main()
{
    isprime[1] = false;
    data[1] = 1;
    for(int i = 4;i<max;i += 2)
        isprime[i] = false;
    for(int i = 3; i*i< max;i += 2)
    {
        for(int j = i*i; j < max;j += i)
            isprime[j] = false;
    }
    prime.push_back(2);
    data[2] = 2;
    for(int i =3;i<max;i += 2)
        if(isprime[i])
        {
            prime.push_back(i);
            data[i] = i;
        }

    for(int i = 0;i<prime.size();i++)
    {
        dp(prime[i],i);
    }
        cout<<"...1\n";
    for(int i = 2;i<=8000;i++)
    {
        cout<<i<<" :- ";
        int temp = i;
        while(temp!= 1)
        {
            cout<<data[temp]<<" ";
            temp = temp/data[temp];
        }
        cout<<endl;
    }

    return 0;
}

Here, last is the last index of prime number n.
But I am getting segmentation fault for this, when I change max to 10001, it runs perfectly. I'm not getting why is this happening since the data-structures used are 1-d vectors which can hold values up to 10^6 easily.

Body:
I checked your program out using GDB. The segfault is taking place at this line:

if(n*prime[i] >= max || data[n*prime[i]] != -1)

In your first ever call to DP in your for loop, where you call dp(2,0), the recursive calls eventually generate this call: dp(92692,2585).

92692 * 2585 = 239608820

This number is larger than a 32 bit integer can hold, so the r-value generated by the integer multiplication of those two numbers overflows and becomes negative. nprime[i] becomes negative, so your first condition of the above loop fails, and the second is checked. data[n * prime[i]] is accessed, and since n*prime[i] is negative, your program accesses invalid memory and segfaults. To fix this, simply change n to a long long in your parameter list and you should be fine.

void dp(long long n, int last)


问:
(unix) How to write script to count the number of files in a directory using loop
How can I create a bash script to count the number of files in a directory using a loop.

The script should take a target directory and output: Number of files in ::

答:
I would use (GNU) find and wc:

```<code>find /path/to/dir -maxdepth 1 -type f -printf '.' | wc -c
</code>```

The above find command prints a dot for every file in the directory and wc -c counts those dots. This would work well with any kind of special character (including whitespaces and newlines) in the filenames.

Body:
I would use (GNU) find and wc:

find /path/to/dir -maxdepth 1 -type f -printf '.' | wc -c

The above find command prints a dot for every file in the directory and wc -c counts those dots. This would work well with any kind of special character (including whitespaces and newlines) in the filenames.


问:
How can I get the timezone offset without the DST formatted correctly?
I have not found a way to get the timezone offset without  Daylight Savings Time interference.

```<code>LocalDateTime dt = LocalDateTime.now();
...
ZoneId zone = ZoneId.of(s);
ZonedDateTime zdt = dt.atZone(zone);
ZoneOffset offset = zdt.getOffset();
</code>```

This would seem like it works, but the initial DataTime might be influenced by DST.

There is also this:

```<code>int rawOffset = tZone.getRawOffset();
</code>```

However, this is always a positive number, so we don't ever get -05:00 back.

So what I want is a way to get the offset without DST interference. Any thoughts?

答:
Use ZoneRules.getStandardOffset(Instant).

```<code>ZoneId zone = ZoneId.of(s);
ZoneRules rules = zone.getRules();
ZoneOffset standardOffset = rules.getStandardOffset(Instant.now());
</code>```

Body:
I have not found a way to get the timezone offset without  Daylight Savings Time interference.

LocalDateTime dt = LocalDateTime.now();
...
ZoneId zone = ZoneId.of(s);
ZonedDateTime zdt = dt.atZone(zone);
ZoneOffset offset = zdt.getOffset();

This would seem like it works, but the initial DataTime might be influenced by DST.

There is also this:

int rawOffset = tZone.getRawOffset();

However, this is always a positive number, so we don't ever get -05:00 back.

So what I want is a way to get the offset without DST interference. Any thoughts?

Body:
Use ZoneRules.getStandardOffset(Instant).

ZoneId zone = ZoneId.of(s);
ZoneRules rules = zone.getRules();
ZoneOffset standardOffset = rules.getStandardOffset(Instant.now());


问:
running unit-tests after every successful compilation
Consider Visual Studio C++ solution with a static lib project and a console app with unit-tests. App post-build step is "$(TargetDir)$(TargetFileName)" to run tests automatically on each successful compilation.

When compilation is successful but tests fail I want to debug them sometimes, so I need to run them from VS. The problem is if tests fail the build is considered failed also, and so VS refuses to run.

A not ideal solution is to enable an option

so when you try to run failed build you get

(the option is on by default but sooner or later everybody clicks on "Do not show this dialog again")

It's not ideal because it's confusing, it triggers build again (compilation is skipped as it was successful but tests are run again, and the option is global meaning it applies to all your projects even those that don't need it. It's certainly not a very big deal, just wonder if people have some clever hacks for this.

For example, C# projects build events have an option "When the build updates the project output" - perfect for unit-testing after each compilation.

The project is cross-platform, so VS testing framework is not applicable.

答:
I'd propose to add "makefile project" (File -> Add-> New Project -> Visual C++ -> General -> Makefile project) that would consist of "run unit test" command. And make test app itself not containing self-run.

Then your entire solution would fail on test failure, but test itself would success.

Your situation is not usual, though. Typically, apart from test app, a solution would contain "useful work app", and then unit test would go to pre-build of "useful work app" (which would also have dependency on test app)


答:
So, basically, I should have used & to combine two conditions:

```<code>for y in range(1991,2011):
    for i in df.loc[df.year == y, 'PREC']:
        if i <= np.percentile(df.loc[df.year == y, 'PREC'], 10):
            df.loc[(df['year'] == y) & (df['PREC'] == i), 'intensity'] = 'light'
</code>```

Title: Replacing values based on multiple column values and conditions in pandas dataframe

Body:
I have the following dataframe:

     TIME   PREC    ET   PET  YIELD       date  year  intensity
0        1   1.21  0.02  0.02   0.00 1991-01-01  1991          1
1        2   0.00  0.03  0.04   0.00 1991-01-02  1991          1
2        3   0.00  0.03  0.05   0.00 1991-01-03  1991          1
3        4   0.00  0.04  0.05   0.00 1991-01-04  1991          1
4        5   0.00  0.05  0.07   0.00 1991-01-05  1991          1
5        6   0.00  0.03  0.05   0.00 1991-01-06  1991          1
6        7   0.00  0.02  0.04   0.00 1991-01-07  1991          1
7        8   1.14  0.03  0.04   0.00 1991-01-08  1991          1
8        9   0.10  0.02  0.03   0.00 1991-01-09  1991          1
9       10   0.00  0.03  0.04   0.00 1991-01-10  1991          1
10      11   0.10  0.05  0.11   0.00 1991-01-11  1991          1
11      12   0.00  0.06  0.15   0.00 1991-01-12  1991          1
12      13   2.30  0.14  0.44   0.00 1991-01-13  1991          1
13      14   0.17  0.09  0.29   0.00 1991-01-14  1991          1
14      15   0.00  0.13  0.35   0.00 1991-01-15  1991          1
15      16   0.00  0.14  0.39   0.00 1991-01-16  1991          1
16      17   0.00  0.10  0.31   0.00 1991-01-17  1991          1
17      18   0.00  0.15  0.51   0.00 1991-01-18  1991          1
18      19   0.00  0.22  0.58   0.00 1991-01-19  1991          1
19      20   0.10  0.04  0.09   0.00 1991-01-20  1991          1
20      21   0.00  0.04  0.06   0.00 1991-01-21  1991          1
21      22   0.27  0.13  0.43   0.00 1991-01-22  1991          1
22      23   0.00  0.10  0.25   0.00 1991-01-23  1991          1
23      24   0.00  0.03  0.04   0.00 1991-01-24  1991          1
24      25   0.00  0.04  0.05   0.00 1991-01-25  1991          1
25      26   0.43  0.04  0.15   0.00 1991-01-26  1991          1
26      27   0.17  0.06  0.23   0.00 1991-01-27  1991          1
27      28   0.50  0.02  0.04   0.00 1991-01-28  1991          1
28      29   0.00  0.03  0.04   0.00 1991-01-29  1991          1
29      30   0.00  0.04  0.08   0.00 1991-01-30  1991          1
   ...    ...   ...   ...    ...        ...   ...        ...
7275   336   0.00  0.04  0.06   0.03 2010-12-02  2010          1
7276   337   0.30  0.05  0.08   0.02 2010-12-03  2010          1
7277   338   1.62  0.08  0.12   0.02 2010-12-04  2010          1
7278   339   0.00  0.10  0.15   0.02 2010-12-05  2010          1
7279   340   0.00  0.09  0.15   0.02 2010-12-06  2010          1
7280   341   0.00  0.04  0.06   0.02 2010-12-07  2010          1
7281   342   0.00  0.04  0.06   0.02 2010-12-08  2010          1
7282   343   0.00  0.16  0.25   0.02 2010-12-09  2010          1
7283   344   0.00  0.22  0.35   0.02 2010-12-10  2010          1
7284   345   0.04  0.04  0.06   0.02 2010-12-11  2010          1
7285   346   0.01  0.02  0.03   0.02 2010-12-12  2010          1
7286   347   0.04  0.02  0.03   0.02 2010-12-13  2010          1
7287   348   0.00  0.05  0.08   0.02 2010-12-14  2010          1
7288   349   0.37  0.08  0.13   0.02 2010-12-15  2010          1
7289   350  13.19  0.08  0.13   0.02 2010-12-16  2010          1
7290   351   1.33  0.06  0.10   0.02 2010-12-17  2010          1
7291   352   0.00  0.08  0.12   0.02 2010-12-18  2010          1
7292   353   0.01  0.05  0.08   0.02 2010-12-19  2010          1
7293   354   0.00  0.03  0.04   0.02 2010-12-20  2010          1
7294   355   9.70  0.07  0.12   0.02 2010-12-21  2010          1
7295   356   0.00  0.06  0.11   0.02 2010-12-22  2010          1
7296   357   0.00  0.07  0.12   0.02 2010-12-23  2010          1
7297   358   0.13  0.08  0.13   0.02 2010-12-24  2010          1
7298   359   0.10  0.09  0.15   0.02 2010-12-25  2010          1
7299   360   0.00  0.07  0.12   0.02 2010-12-26  2010          1
7300   361   0.00  0.08  0.14   0.02 2010-12-27  2010          1
7301   362   0.61  0.18  0.32   0.02 2010-12-28  2010          1
7302   363   0.00  0.15  0.26   0.02 2010-12-29  2010          1
7303   364   3.95  0.10  0.18   0.02 2010-12-30  2010          1
7304   365   0.10  0.10  0.18   0.01 2010-12-31  2010          1

I would like to categorize the data based on the values in PREC and year columns. Here's the template of the code that I have:

for y in range(1991,2011):
    for i in df.loc[df.year == y, 'PREC']:
        if i <= np.percentile(df.loc[df.year == y, 'PREC'], 10):
            df.loc[df.PREC.isin([i]), 'intensity'] = 'light'

However, this code categorize intensity in the whole dataframe, but I need to categorize  PREC for each year. So, how to do this?

Body:
So, basically, I should have used & to combine two conditions:

for y in range(1991,2011):
    for i in df.loc[df.year == y, 'PREC']:
        if i <= np.percentile(df.loc[df.year == y, 'PREC'], 10):
            df.loc[(df['year'] == y) & (df['PREC'] == i), 'intensity'] = 'light'