问:
Flow of a XSLT transformation

I got a question about the program flow of a XSLT transformation. I have the following XML:

```<code><Telefonliste>
    <Eintrag att="1">
        <name>Peter</name>
        <nachname>Pan</nachname>
        <Tel>12345</Tel>
    </Eintrag>
    <Eintrag>
        <name>Max</name>
        <nachname>Mustermann</nachname>
        <Tel>98765</Tel>
    </Eintrag>
</Telefonliste>
</code>```

And there is a xsl file A:

```<code><?xml version="1.0" encoding="UTF-8" ?>
<xsl:transform version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text"/>

<xsl:template match="/">
    Root node
    <xsl:apply-templates />
    Root node
</xsl:template>

<xsl:template match="node() | @*" >
    <xsl:text>Test</xsl:text>
</xsl:template>

</xsl:transform>
</code>```

And there is a xsl file B:

```<code><?xml version="1.0" encoding="UTF-8" ?>
<xsl:transform version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml"/>

<xsl:template match="/">
    Root node
    <xsl:apply-templates />
    Root node
</xsl:template>

<xsl:template match="node() | @*" >
    <xsl:value-of select="self::node()" />
</xsl:template>

</xsl:transform>
</code>```

The Output of A is:

```<code>Root node
Test
Root node
</code>```

This is exactly what I would suggest of that transformation. First the template for the root is called, prints "Root node" and then applies the template to child::node() (there is no select in the apply-templates clause). Then it calls the second template which prints a single time "Test". Then the template of the root node prints again "Root node" and then the transformation is finished.

If I run transformation B, i get the following output:

```<code>Root node
Peter
Pan
12345
Max
Mustermann
98765
Root node
</code>```

The printing of "Root node" is clear here. But why dies  prints ALL children node values? I can not understand it, there is no  loop. I would expect only one value, the value of the current context node...

Can someone explain that?

答:
Consider the following stylesheet:

```<code><xsl:transform version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml"/>

<xsl:template match="/Telefonliste">
    Root node
     <xsl:value-of select="self::node()" />
    Root node
</xsl:template>

</xsl:transform>
</code>```

Applied to your input, the result will be the same as in your transformation  B.

The reason for this is that the xsl:value-of instruction returns the string-value of the selected node - and this string-value includes all descendant text nodes.

Title: Flow of a XSLT transformation

Body:
I got a question about the program flow of a XSLT transformation. I have the following XML:

<Telefonliste>
    <Eintrag att="1">
        <name>Peter</name>
        <nachname>Pan</nachname>
        <Tel>12345</Tel>
    </Eintrag>
    <Eintrag>
        <name>Max</name>
        <nachname>Mustermann</nachname>
        <Tel>98765</Tel>
    </Eintrag>
</Telefonliste>

And there is a xsl file A:

<?xml version="1.0" encoding="UTF-8" ?>
<xsl:transform version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text"/>

<xsl:template match="/">
    Root node
    <xsl:apply-templates />
    Root node
</xsl:template>

<xsl:template match="node() | @*" >
    <xsl:text>Test</xsl:text>
</xsl:template>

</xsl:transform>

And there is a xsl file B:

<?xml version="1.0" encoding="UTF-8" ?>
<xsl:transform version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml"/>

<xsl:template match="/">
    Root node
    <xsl:apply-templates />
    Root node
</xsl:template>

<xsl:template match="node() | @*" >
    <xsl:value-of select="self::node()" />
</xsl:template>

</xsl:transform>

The Output of A is:

Root node
Test
Root node

This is exactly what I would suggest of that transformation. First the template for the root is called, prints "Root node" and then applies the template to child::node() (there is no select in the apply-templates clause). Then it calls the second template which prints a single time "Test". Then the template of the root node prints again "Root node" and then the transformation is finished.

If I run transformation B, i get the following output:

Root node
Peter
Pan
12345
Max
Mustermann
98765
Root node

The printing of "Root node" is clear here. But why dies  prints ALL children node values? I can not understand it, there is no  loop. I would expect only one value, the value of the current context node...

Can someone explain that?

Body:
Consider the following stylesheet:

<xsl:transform version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml"/>

<xsl:template match="/Telefonliste">
    Root node
     <xsl:value-of select="self::node()" />
    Root node
</xsl:template>

</xsl:transform>

Applied to your input, the result will be the same as in your transformation  B.

The reason for this is that the xsl:value-of instruction returns the string-value of the selected node - and this string-value includes all descendant text nodes.


来源: stackexchange

问:
$Env:ComputerName doesnt work with powershell Send-MailMessage in batch file
After a lot of errors and edits I got the Send-MailMessage to work through a command prompt.  Below iteration sends out the emails perfect.

```<code>powershell Send-MailMessage -From " `<user@domain>`" -To " `<user@domain.com>`" -Subject 'Some subject goes here' -Body 'Some body with alert regarding Host: $env:computername. List of deleted files is attached.' -Attachments 'C:\somefile.txt' -Priority High -dno onSuccess, onFailure -SmtpServer 'smtp.domain.com'
</code>```

However, this does not fetch the computername in the body. I have tried running this command in powershell directly and it works with the computername variable in body.

To get it to simply send out mails, I have already tried doing
  powershell -command "command" or powershell -command "{command} or
  powershell -command "& {command}" and so on and it doesnt even send
  out emails.

As I am now successful sending out emails, I need to have the Computername inside the body text.

答:
"$env:computername" doesnot work for me. It simply prints it as $env:computername

%computername% worked.

Here's what's working for me right now.

```<code>powershell Send-MailMessage -From " `<user@domain.com>`" -To " `<user@domain.com>`" -Subject 'Some subject goes here' -Body 'Some body with alert regarding Host: %computername%. Some file is attached.' -Attachments 'C:\somefile.txt' -Priority High -dno onSuccess, onFailure -SmtpServer 'smtp.domain.com'
</code>```

Update:

The above command worked on Win7 fine, but gave errors on server 2012.  Finally this is what worked on win 2012

```<code>powershell "Send-MailMessage -From "SomeWeb-Prod@domain.com" -To "fromuser@domain.com" -Subject 'Some notification for SomeWeb-Prod' -Body 'Some Alert for Host: %computername% with IP: %NetworkIP% at %time%. details in attached file.' -Attachments 'C:\somefile.txt' -Priority High -dno onFailure -SmtpServer 'smtp.domain.com'"
</code>```

ContentLicense: CC BY-SA 3.0

Body:
After a lot of errors and edits I got the Send-MailMessage to work through a command prompt.  Below iteration sends out the emails perfect.

powershell Send-MailMessage -From " `<user@domain>`" -To " `<user@domain.com>`" -Subject 'Some subject goes here' -Body 'Some body with alert regarding Host: $env:computername. List of deleted files is attached.' -Attachments 'C:\somefile.txt' -Priority High -dno onSuccess, onFailure -SmtpServer 'smtp.domain.com'

However, this does not fetch the computername in the body. I have tried running this command in powershell directly and it works with the computername variable in body.

To get it to simply send out mails, I have already tried doing
  powershell -command "command" or powershell -command "{command} or
  powershell -command "& {command}" and so on and it doesnt even send
  out emails.

As I am now successful sending out emails, I need to have the Computername inside the body text.

Body:
"$env:computername" doesnot work for me. It simply prints it as $env:computername

%computername% worked.

Here's what's working for me right now.

powershell Send-MailMessage -From " `<user@domain.com>`" -To " `<user@domain.com>`" -Subject 'Some subject goes here' -Body 'Some body with alert regarding Host: %computername%. Some file is attached.' -Attachments 'C:\somefile.txt' -Priority High -dno onSuccess, onFailure -SmtpServer 'smtp.domain.com'

Update:

The above command worked on Win7 fine, but gave errors on server 2012.  Finally this is what worked on win 2012

powershell "Send-MailMessage -From "SomeWeb-Prod@domain.com" -To "fromuser@domain.com" -Subject 'Some notification for SomeWeb-Prod' -Body 'Some Alert for Host: %computername% with IP: %NetworkIP% at %time%. details in attached file.' -Attachments 'C:\somefile.txt' -Priority High -dno onFailure -SmtpServer 'smtp.domain.com'"


问:
How to select a dropdown value in Selenium WebDriver using Java
I am new to selenium, currently am working on selenium webdriver i want to select a value from the drop down.
The id=periodId and the option is many in that am trying to select Last 52 weeks.

Here is the HTML code:

<select id="periodId" name="period" style="display: none;">
    <option value="l4w">Last 4 Weeks</option>
    <option value="l52w">Last 52 Weeks</option>
    <option value="daterange">Date Range</option>
    <option value="weekrange">Week Range</option>
    <option selected="" value="monthrange">Month Range</option>
    <option value="yeartodate">Year To Date</option>
</select>
```

Please suggest me some ways to click the drop down.

I tried with the above example lines but am getting error such as Element is not currently visible and so may not be interacted with
Command duration or timeout: 32 milliseconds
the drop downs values are the jquery multiselect widget format.

答:
You can use following methods to handle drop down in selenium.

```<code> 1. driver.selectByVisibleText("Text");
 2. driver.selectByIndex(1);
 3. driver.selectByValue("prog");
</code>```

For more details you can refer http://www.codealumni.com/handle-drop-selenium-webdriver/ this post.

It will definitely help you a lot in resolving your queries.

ContentLicense: CC BY-SA 4.0

Body:
I am new to selenium, currently am working on selenium webdriver i want to select a value from the drop down.
The id=periodId and the option is many in that am trying to select Last 52 weeks.

Here is the HTML code:

<select id="periodId" name="period" style="display: none;">
    <option value="l4w">Last 4 Weeks</option>
    <option value="l52w">Last 52 Weeks</option>
    <option value="daterange">Date Range</option>
    <option value="weekrange">Week Range</option>
    <option selected="" value="monthrange">Month Range</option>
    <option value="yeartodate">Year To Date</option>
</select>

Please suggest me some ways to click the drop down.

I tried with the above example lines but am getting error such as Element is not currently visible and so may not be interacted with
Command duration or timeout: 32 milliseconds
the drop downs values are the jquery multiselect widget format.

Body:
You can use following methods to handle drop down in selenium.

 1. driver.selectByVisibleText("Text");
 2. driver.selectByIndex(1);
 3. driver.selectByValue("prog");

For more details you can refer http://www.codealumni.com/handle-drop-selenium-webdriver/ this post.

It will definitely help you a lot in resolving your queries.


问:
excess whitespace in cqlsh SHOW SESSION
When attempting to show a session in CQLSH i'm getting an excessive amount of white space between each returned line, is there a way of removing the whitespace as what i'm getting is unreadable.

An example is below, i've trimmed hundreds of lines of whitespace, leaving enough in to demonstrate the point.

```<code>cqlsh:system_traces> SHOW SESSSION sessionid

Read 1 live and 0 tombstone cells [SharedPool-Worker-3] | 2017-07-05
09:27:24.194001 | 127.0.0.1 |         151744

Request complete | 2017-07-05 09:27:24.188936 | 127.0.0.1 |         151936
</code>```

答:
The solution to the problem is to output to a file as directed by: StackOverflow - Export cassandra query result to a csv file and read it with a text editor such as vim that can handle a crazy amount of whitespace without lagging.

What happened was there were an exceedingly large number of token ranges which stretched the width of a column so that each proceeding row needed a very large amount of whitespace to keep formatting.

Title: excess whitespace in cqlsh SHOW SESSION

Body:
When attempting to show a session in CQLSH i'm getting an excessive amount of white space between each returned line, is there a way of removing the whitespace as what i'm getting is unreadable.

An example is below, i've trimmed hundreds of lines of whitespace, leaving enough in to demonstrate the point.

cqlsh:system_traces> SHOW SESSSION sessionid

Read 1 live and 0 tombstone cells [SharedPool-Worker-3] | 2017-07-05
09:27:24.194001 | 127.0.0.1 |         151744

Request complete | 2017-07-05 09:27:24.188936 | 127.0.0.1 |         151936


问:
Angular 2/4 components communication thru a service
I have 2 components and 1 service that is shared:

Parent components display all companies, and the child has removeCompany method.

Problem is that when the I call the removeCompany method, the getCompanies() from parent is not updated(removeCompany() works if i call it in the parent);

What am I missing?

```<code>export class CompanyService {

  // Placeholder for last id so we can simulate automatic incrementing of id's
  private lastId = 0;
  // variable for holding companies
  private companies: Company[] =  [];

  // URL mockup web API
  private backendData = 'api/companies';

  constructor ( private http: Http ) {
    // Populate the companies variable on instantiation
    this.http.get(this.backendData)
      .map( (response: Response) => response.json().data )
      .subscribe((data) => {
        data.forEach(company => {
          this.companies.push(company);
          if (company.id > this.lastId) { this.lastId = company.id; }
        });
      });
  }

  // Simulate GET /companies
  getAllcompanies(): Company[] {
    return this.companies;
  }
  // Simulate DELETE /companies/:id
  deleteCompanyById(id: number): CompanyService {
    this.companies = this.companies
      .filter(company => company.id !== id);
    return this;
  }
</code>```

Components:

```<code>export class ParentComponent {

  constructor(private companyService: CompanyService) {}

  get companies() {
    return this.companyService.getAllcompanies();
  }
}

export class ChildComponent {
  @Input()company: Company;

  constructor(private companyService: CompanyService) {}

  removeCompany(company: Company): CompanyService {
    console.log(company);
    return this.companyService.deleteCompanyById(company.id);
  }
}
</code>```

HTML

```<code><parent *ngFor="company of companies">
  <child id="child" [company]="company">
    ...button (click)="removeCompany(company)"....
  </child>
</parent>
</code>```

答:
The problem here is , ParentComponent is not aware that ChildCompany deleted a company. To fix that , use BehaviorSubject in the service:

Instead of

```<code>private companies: Company[] =  [];
</code>```

Use

```<code>private companies = new BehaviorSubject<Company[]>([]);
</code>```

Instead of

```<code>this.companies.push(company)
</code>```

Use

```<code>this.companies.next([...this.companies.value, company]);
</code>```

Instead of

```<code>this.companies = this.companies
      .filter(company => company.id !== id);
</code>```

Use

```<code>this.companies.next(this.companies.value
      .filter(company => company.id !== id));
</code>```

Instead of

```<code>getAllcompanies(): Company[] {
    return this.companies;
}
</code>```

Use

```<code>getAllcompanies(): Observable<Company[]> {
    return this.companies;
}
</code>```

You need to subscribe inside the components.

```<code>get companies() {
    return this.companyService.getAllcompanies()
               .subscribe(companies => this.companies = companies );
}
</code>```

Body:
I have 2 components and 1 service that is shared:

Parent components display all companies, and the child has removeCompany method.

Problem is that when the I call the removeCompany method, the getCompanies() from parent is not updated(removeCompany() works if i call it in the parent);

What am I missing?

export class CompanyService {

  // Placeholder for last id so we can simulate automatic incrementing of id's
  private lastId = 0;
  // variable for holding companies
  private companies: Company[] =  [];

  // URL mockup web API
  private backendData = 'api/companies';

  constructor ( private http: Http ) {
    // Populate the companies variable on instantiation
    this.http.get(this.backendData)
      .map( (response: Response) => response.json().data )
      .subscribe((data) => {
        data.forEach(company => {
          this.companies.push(company);
          if (company.id > this.lastId) { this.lastId = company.id; }
        });
      });
  }

  // Simulate GET /companies
  getAllcompanies(): Company[] {
    return this.companies;
  }
  // Simulate DELETE /companies/:id
  deleteCompanyById(id: number): CompanyService {
    this.companies = this.companies
      .filter(company => company.id !== id);
    return this;
  }

Components:

export class ParentComponent {

  constructor(private companyService: CompanyService) {}

  get companies() {
    return this.companyService.getAllcompanies();
  }
}

export class ChildComponent {
  @Input()company: Company;

  constructor(private companyService: CompanyService) {}

  removeCompany(company: Company): CompanyService {
    console.log(company);
    return this.companyService.deleteCompanyById(company.id);
  }
}

HTML

<parent *ngFor="company of companies">
  <child id="child" [company]="company">
    ...button (click)="removeCompany(company)"....
  </child>
</parent>

Body:
The problem here is , ParentComponent is not aware that ChildCompany deleted a company. To fix that , use BehaviorSubject in the service:

Instead of

private companies: Company[] =  [];

Use

private companies = new BehaviorSubject<Company[]>([]);

Instead of

this.companies.push(company)

Use

this.companies.next([...this.companies.value, company]);

Instead of

this.companies = this.companies
      .filter(company => company.id !== id);

Use

this.companies.next(this.companies.value
      .filter(company => company.id !== id));

Instead of

getAllcompanies(): Company[] {
    return this.companies;
}

Use

getAllcompanies(): Observable<Company[]> {
    return this.companies;
}

You need to subscribe inside the components.

get companies() {
    return this.companyService.getAllcompanies()
               .subscribe(companies => this.companies = companies );
}


问:
AureliaJS - Call child function from parent
I'm using AureliaJS to build a dynamic forms scenario, where I have a parent form with the gross operations needed and multiple child's form's, that change based on user input.

These child's form's have only two specific things themselves. Their model and the validation rules for their model.

So my question is, how can the parent form call the validation rules from the current child form? From child I know that is possible call parent's view model. But from parent, how can I invoke any function from the child?

The scenario is similar off having one base class, that has one method and this method could be overriding on the child classes.

Any suggestion? I'm glad to change the approach if needed.

Here's an example: https://gist.run?id=1865041a15af60600cb7b538018bdccd

app.html

<template>
  This is an APP

  <compose view-model.bind="'parentForm'"></compose>
</template>
```

<p><strong>app.js</strong></p>

<pre class="lang-js prettyprint-override"><code>import { autoinject } from 'aurelia-framework';

@autoinject
export class App {

}
</code>```

childForm1.html

<template>
   Price :
  <input value.bind="model.data.price">

   VAT :
  <input value.bind="model.data.vat">

</template>
```

<p><strong>childForm1.js</strong></p>

<pre class="lang-js prettyprint-override"><code>import { autoinject } from 'aurelia-framework';

@autoinject
export class ChildForm1 {

  activate(model)
  {
    this.model = model;
  }

 validateRules (){

     if(this.model.data.price != '' && this.model.data.vat == '' )
      this.model.validateMessage = 'VAT is mandatory';
 }
}
</code>```

childForm2.html

<template>
  Address :
  <input value.bind="model.data.address">

  Phone :
  <input value.bind="model.data.phone">

</template>
```

<p><strong>childForm2.js</strong></p>

<pre class="lang-js prettyprint-override"><code>import { autoinject } from 'aurelia-framework';

@autoinject
export class ChildForm2 {

  activate(model)
  {
    this.model = model;
  }

 validateRules (){

   if(this.model.data.phone != '' && this.model.data.address == '' )
      this.model.validateMessage = 'Address is mandatory';
 }
}
</code>```

index.html

<!doctype html>

    <title>Aurelia</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">

Loading...

```

<p><strong>parentForm.html</strong></p>

<pre class="lang-html prettyprint-override"><code><template>
  <button click.delegate="changeChildForm1()">Change Child Form 1</button>
  <button click.delegate="changeChildForm2()">Change Child Form 2</button>
  <p/>
  <p/>
  <form>
    <label>User : </label>
    <input value.bind="model.data.user">
    <p/>
    <compose view-model.bind="childFormVM" model.bind="model"></compose>
    <button click.delegate="save()">Save</button>
    <p/>
    <span> Validation Message :  ${model.validateMessage}</span>
  </form>
   <p/>
  <span>Price : ${model.data.price}</span><p/>
  <span>Vat : ${model.data.vat}</span><p/>
  <span>Phone : ${model.data.phone}</span><p/>
  <span>Address : ${model.data.address}</span><p/>
</template>
</code>```

parentForm.js

import { autoinject } from 'aurelia-framework';

@autoinject
export class ParentForm {
  model = {
   validateMessage : '',
   data : {
    user : 'My Name'
   }
 };

 childFormVM = 'childForm1';

 validateMessage = '';

 changeChildForm1() {

   this.childFormVM = 'childForm1';
 }

  changeChildForm2() {

   this.childFormVM = 'childForm2';
 }

 save(){
   this.validateRules();
   // How to call the validation rules from child ?
 }

 validateRules (){

   this.model.validateMessage = 'Validate by parent';
 }
}
```

答:
One thing that immediately comes to mind is that you can inject the parent model into your child model in the constructor -- the injected instance will be the same, not a newly created one. This way, your parent can define a method that allows the child to register itself on the parent, and the parent can then invoke whatever methods exist on the child at the time of its choosing.

This creates a rather strong coupling between the components, though, so you will need to consider whether or not that is acceptable to you.

If it isn't, another way to approach the issue is to use the event aggregator. The parent form can dispatch an event on the aggregator, and the children will be subscribers listening for the event. In this case, depending on whether or not you host multiple such combinations on one page, you may want to include a unique identifier for the form that is sent along with the event and bind that ID to the child components, so they will know to only listen for events from their parent.

Body:
I'm using AureliaJS to build a dynamic forms scenario, where I have a parent form with the gross operations needed and multiple child's form's, that change based on user input.

These child's form's have only two specific things themselves. Their model and the validation rules for their model.

So my question is, how can the parent form call the validation rules from the current child form? From child I know that is possible call parent's view model. But from parent, how can I invoke any function from the child?

The scenario is similar off having one base class, that has one method and this method could be overriding on the child classes.

Any suggestion? I'm glad to change the approach if needed.

Here's an example: https://gist.run?id=1865041a15af60600cb7b538018bdccd

app.html

<template>
  This is an APP

  <compose view-model.bind="'parentForm'"></compose>
</template>

app.js

import { autoinject } from 'aurelia-framework';

@autoinject
export class App {

}

childForm1.html

<template>
   Price :
  <input value.bind="model.data.price">

   VAT :
  <input value.bind="model.data.vat">

</template>

childForm1.js

import { autoinject } from 'aurelia-framework';

@autoinject
export class ChildForm1 {

  activate(model)
  {
    this.model = model;
  }

 validateRules (){

     if(this.model.data.price != '' && this.model.data.vat == '' )
      this.model.validateMessage = 'VAT is mandatory';
 }
}

childForm2.html

<template>
  Address :
  <input value.bind="model.data.address">

  Phone :
  <input value.bind="model.data.phone">

</template>

childForm2.js

import { autoinject } from 'aurelia-framework';

@autoinject
export class ChildForm2 {

  activate(model)
  {
    this.model = model;
  }

 validateRules (){

   if(this.model.data.phone != '' && this.model.data.address == '' )
      this.model.validateMessage = 'Address is mandatory';
 }
}

index.html

<!doctype html>

    <title>Aurelia</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">

Loading...

parentForm.html

<template>
  <button click.delegate="changeChildForm1()">Change Child Form 1</button>
  <button click.delegate="changeChildForm2()">Change Child Form 2</button>

  <form>
    User :
    <input value.bind="model.data.user">

    <compose view-model.bind="childFormVM" model.bind="model"></compose>
    <button click.delegate="save()">Save</button>

     Validation Message :  ${model.validateMessage}
  </form>

  Price : ${model.data.price}

  Vat : ${model.data.vat}

  Phone : ${model.data.phone}

  Address : ${model.data.address}

</template>

parentForm.js

import { autoinject } from 'aurelia-framework';

@autoinject
export class ParentForm {
  model = {
   validateMessage : '',
   data : {
    user : 'My Name'
   }
 };

 childFormVM = 'childForm1';

 validateMessage = '';

 changeChildForm1() {

   this.childFormVM = 'childForm1';
 }

  changeChildForm2() {

   this.childFormVM = 'childForm2';
 }

 save(){
   this.validateRules();
   // How to call the validation rules from child ?
 }

 validateRules (){

   this.model.validateMessage = 'Validate by parent';
 }
}


问:
Remove trailing "=" when base64 encoding
I am noticing that whenever I base64 encode a string, a "=" is appended at the end.  Can I remove this character and then reliably decode it later by adding it back, or is this dangerous?  In other words, is the "=" always appended, or only in certain cases?

I want my encoded string to be as short as possible, that's why I want to know if I can always remove the "=" character and just add it back before decoding.

答:
The = is padding.

Wikipedia says

An additional pad character is
allocated which may be used to force
the encoded output into an integer
multiple of 4 characters (or
equivalently when the unencoded binary
text is not a multiple of 3 bytes) ;
these padding characters must then be
discarded when decoding but still
allow the calculation of the effective
length of the unencoded text, when its
input binary length would not be a
multiple of 3 bytes (the last non-pad
character is normally encoded so that
the last 6-bit block it represents
will be zero-padded on its least
significant bits, at most two pad
characters may occur at the end of the
encoded stream).

If you control the other end, you could remove it when in transport, then re-insert it (by checking the string length) before decoding.

Note that the data will not be valid Base64 in transport.

Also, Another user pointed out (relevant to PHP users):

Note that in PHP base64_decode will accept strings without padding, hence if you remove it to process it later in PHP it's not necessary to add it back. – Mahn Oct 16 '14 at 16:33

So if your destination is PHP, you can safely strip the padding and decode without fancy calculations.

Body:
The = is padding. <!------------>

Wikipedia says

An additional pad character is
allocated which may be used to force
the encoded output into an integer
multiple of 4 characters (or
equivalently when the unencoded binary
text is not a multiple of 3 bytes) ;
these padding characters must then be
discarded when decoding but still
allow the calculation of the effective
length of the unencoded text, when its
input binary length would not be a
multiple of 3 bytes (the last non-pad
character is normally encoded so that
the last 6-bit block it represents
will be zero-padded on its least
significant bits, at most two pad
characters may occur at the end of the
encoded stream).

If you control the other end, you could remove it when in transport, then re-insert it (by checking the string length) before decoding.

Note that the data will not be valid Base64 in transport.

Also, Another user pointed out (relevant to PHP users):

Note that in PHP base64_decode will accept strings without padding, hence if you remove it to process it later in PHP it's not necessary to add it back. – Mahn Oct 16 '14 at 16:33

So if your destination is PHP, you can safely strip the padding and decode without fancy calculations.


问:
Images in different density in android
I create raw folder in my project and give reference of images from this folder in project.
So in case of different density will android make it's changes according to screen size.
or i have to put all images in drawable folder.
if yes then please let me know it's resolution and density ratio.</p>

答:
I think this might be helpful.</p>

```<code>Density *mdpi   Resolution   Device                 iOS Equivalent

ldpi     0.75   320 x 240    Galaxy Y                     0.75x
mdpi     1      480 x 320    Galaxy Ace                   1x
hdpi     1.5    480 x 854    Android One                  1.5x
xhdpi    2      768 x 1280   Nexus 4                      2x
xxhdpi   3      1080 x 1920  Nexus 5, Samsung Galaxy S5   3x
xxxhdpi  4      1440 x 2560  Samsung Galaxy S6, S7        4x
</code>```

Title: Images in different density in android

Body:
I think this might be helpful.

Density *mdpi   Resolution   Device                 iOS Equivalent

ldpi     0.75   320 x 240    Galaxy Y                     0.75x
mdpi     1      480 x 320    Galaxy Ace                   1x
hdpi     1.5    480 x 854    Android One                  1.5x
xhdpi    2      768 x 1280   Nexus 4                      2x
xxhdpi   3      1080 x 1920  Nexus 5, Samsung Galaxy S5   3x
xxxhdpi  4      1440 x 2560  Samsung Galaxy S6, S7        4x


问:
Multipart upload to Amazon Glacier: Content-Range incompatible with Content-Length
I'm trying to upload a file around 1gb in size to Amazon Glacier. Somewhat arbitrarily, I've decided to break it into 32mb parts and upload them in serial.

import math
import boto3
from botocore.utils import calculate_tree_hash

client = boto3.client('glacier')
vault_name = 'my-vault'
size = 1073745600 # in bytes
size_mb = size / (2**20) # Convert to megabytes for readability
local_file = 'filename'

multi_up = client.initiate_multipart_upload(vaultName=vault_name,
                                        archiveDescription=local_file,
                                        partSize=str(2**25)) # 32 mb in bytes
parts = math.floor(size_mb / 32)
with open("/Users/alexchase/Desktop/{}".format(local_file), 'rb') as upload:
    for p in range(parts):
        # Calculate lower and upper bounds for the byte ranges. The last range
        # is bigger than the ones that come before.
        lower = (p * (2**25))
        upper = (((p + 1) * (2**25)) - 1) if (p + 1 < parts) else (size)
        up_part = client.upload_multipart_part(vaultName=vault_name,
                                           uploadId=multi_up['uploadId'],
                                           range='bytes {}-{}/*'.format(lower, upper),
                                           body=upload)
checksum = calculate_tree_hash(upload)
complete_up = client.complete_multipart_upload(archiveSize=str(size),
                                               checksum=checksum,
                                               uploadId=multi_up['uploadId'],
                                               vaultName=vault_name)
```

<p>This generates an error about the first byte range.</p>

<pre class="lang-py prettyprint-override"><code>---------------------------------------------------------------------------
InvalidParameterValueException            Traceback (most recent call last)
<ipython-input-2-9dd3ac986601> in <module>()
     93                         uploadId=multi_up['uploadId'],
     94                         range='bytes {}-{}/*'.format(lower, upper),
---> 95                         body=upload)
     96                     upload_info.append(up_part)
     97                 checksum = calculate_tree_hash(upload)

~/anaconda/lib/python3.5/site-packages/botocore/client.py in _api_call(self, *args, **kwargs)
    251                     "%s() only accepts keyword arguments." % py_operation_name)
    252             # The "self" in this scope is referring to the BaseClient.
--> 253             return self._make_api_call(operation_name, kwargs)
    254
    255         _api_call.__name__ = str(py_operation_name)

~/anaconda/lib/python3.5/site-packages/botocore/client.py in _make_api_call(self, operation_name, api_params)
    555             error_code = parsed_response.get("Error", {}).get("Code")
    556             error_class = self.exceptions.from_code(error_code)
--> 557             raise error_class(parsed_response, operation_name)
    558         else:
    559             return parsed_response

InvalidParameterValueException: An error occurred (InvalidParameterValueException) when calling the UploadMultipartPart operation:
Content-Range: bytes 0-33554431/* is incompatible with Content-Length: 1073745600
</code>```

Can anyone see what I'm doing wrong?

答:
@Michael-sqlbot is quite right, the issue with the Content-Range was that I was passing the whole file instead of a part. I fixed this by using the read() method, but then I discovered a separate issue, which is that (per the docs), the final part has to be the same size or smaller than the preceding parts. This means using math.ceil() instead of math.floor() to define the number of parts.

The working code is:

import math
import boto3
from botocore.utils import calculate_tree_hash

client = boto3.client('glacier')
vault_name = 'my-vault'
size = 1073745600 # in bytes
size_mb = size / (2**20) # Convert to megabytes for readability
local_file = 'filename'
partSize=(2**25)

multi_up = client.initiate_multipart_upload(vaultName=vault_name,
                                        archiveDescription=local_file,
                                        partSize=str(partSize)) # 32 mb in bytes
parts = math.ceil(size_mb / 32) # The number of <=32mb parts we need
with open("/Users/alexchase/Desktop/{}".format(local_file), 'rb') as upload:
    for p in range(parts):
        # Calculate lower and upper bounds for the byte ranges. The last range
        # is now smaller than the ones that come before.
        lower = (p * (partSize))
        upper = (((p + 1) * (partSize)) - 1) if (p + 1 < parts) else (size-1)
        read_size = upper-lower+1
        file_part = upload.read(read_size)
        up_part = client.upload_multipart_part(vaultName=vault_name,
                                           uploadId=multi_up['uploadId'],
                                           range='bytes {}-{}/*'.format(lower, upper),
                                           body=file_part)
checksum = calculate_tree_hash(upload)
complete_up = client.complete_multipart_upload(archiveSize=str(size),
                                               checksum=checksum,
                                               uploadId=multi_up['uploadId'],
                                               vaultName=vault_name)
```

Body:
I'm trying to upload a file around 1gb in size to Amazon Glacier. Somewhat arbitrarily, I've decided to break it into 32mb parts and upload them in serial.

import math
import boto3
from botocore.utils import calculate_tree_hash

client = boto3.client('glacier')
vault_name = 'my-vault'
size = 1073745600 # in bytes
size_mb = size / (2**20) # Convert to megabytes for readability
local_file = 'filename'

multi_up = client.initiate_multipart_upload(vaultName=vault_name,
                                        archiveDescription=local_file,
                                        partSize=str(2**25)) # 32 mb in bytes
parts = math.floor(size_mb / 32)
with open("/Users/alexchase/Desktop/{}".format(local_file), 'rb') as upload:
    for p in range(parts):
        # Calculate lower and upper bounds for the byte ranges. The last range
        # is bigger than the ones that come before.
        lower = (p * (2**25))
        upper = (((p + 1) * (2**25)) - 1) if (p + 1 < parts) else (size)
        up_part = client.upload_multipart_part(vaultName=vault_name,
                                           uploadId=multi_up['uploadId'],
                                           range='bytes {}-{}/*'.format(lower, upper),
                                           body=upload)
checksum = calculate_tree_hash(upload)
complete_up = client.complete_multipart_upload(archiveSize=str(size),
                                               checksum=checksum,
                                               uploadId=multi_up['uploadId'],
                                               vaultName=vault_name)

This generates an error about the first byte range.

---------------------------------------------------------------------------
InvalidParameterValueException            Traceback (most recent call last)
<ipython-input-2-9dd3ac986601> in <module>()
     93                         uploadId=multi_up['uploadId'],
     94                         range='bytes {}-{}/*'.format(lower, upper),
---> 95                         body=upload)
     96                     upload_info.append(up_part)
     97                 checksum = calculate_tree_hash(upload)

~/anaconda/lib/python3.5/site-packages/botocore/client.py in _api_call(self, *args, **kwargs)
    251                     "%s() only accepts keyword arguments." % py_operation_name)
    252             # The "self" in this scope is referring to the BaseClient.
--> 253             return self._make_api_call(operation_name, kwargs)
    254
    255         _api_call.__name__ = str(py_operation_name)

~/anaconda/lib/python3.5/site-packages/botocore/client.py in _make_api_call(self, operation_name, api_params)
    555             error_code = parsed_response.get("Error", {}).get("Code")
    556             error_class = self.exceptions.from_code(error_code)
--> 557             raise error_class(parsed_response, operation_name)
    558         else:
    559             return parsed_response

InvalidParameterValueException: An error occurred (InvalidParameterValueException) when calling the UploadMultipartPart operation:
Content-Range: bytes 0-33554431/* is incompatible with Content-Length: 1073745600

Can anyone see what I'm doing wrong?


问:
Scala: importing object in the same file with a different name
Lets say I have in the same file:

```<code>object x {
  case object z
}

object y {
  .. //want to internally refer to x.z as xxx.z
}
</code>```

In other words I need to rename an import of an object in the same file.

currently I resort to:

```<code>object y {
  import x
  val xxx=x
  .. //referring to x.z as xxx.z
}
</code>```

is there a better way of doing this? perhaps something along the lines of:

```<code>import .{x->xxx}
</code>```

答:
In Scala, you can rename imports like this:

```<code>import package.{x => xxx}
</code>```

See here for more details: http://blog.bruchez.name/2012/06/scala-tip-import-renames.html

EDIT: from comment below

If you are in the same file - you don't need to import anything:

```<code>object X {
  val a = 5
}

object Y {
  val x = X
  def p = println(x.a)
}

Y.p
</code>```

Outputs

```<code>5
</code>```

Body:
Lets say I have in the same file:

object x {
  case object z
}

object y {
  .. //want to internally refer to x.z as xxx.z
}

In other words I need to rename an import of an object in the same file.

currently I resort to:

object y {
  import x
  val xxx=x
  .. //referring to x.z as xxx.z
}

is there a better way of doing this? perhaps something along the lines of:

import .{x->xxx}

Body:
In Scala, you can rename imports like this:

import package.{x => xxx}

See here for more details: http://blog.bruchez.name/2012/06/scala-tip-import-renames.html

EDIT: from comment below

If you are in the same file - you don't need to import anything:

object X {
  val a = 5
}

object Y {
  val x = X
  def p = println(x.a)
}

Y.p

Outputs

5


问:
How to use data from the localstorage in angular 2
How to use data from the localstorage for the another component. Localstorage in service are:

localStorage.setItem('currentUser', JSON.stringify({ username: username, token: success,res:res.data}));

I want to use id, username etc from the data in another component How it possible

答:
you can retrieve current user from storage like

create one function for get a current user in your user service and use it globally

```<code>getCurrentUser(): void {
return JSON.parse(localStorage.getItem('currentUser'));
}
</code>```

Body:
you can retrieve current user from storage like

create one function for get a current user in your user service and use it globally

getCurrentUser(): void {
return JSON.parse(localStorage.getItem('currentUser'));
}


问:
ClaimsIdentity AuthenticationType changed after deserialization using JwtSecurityTokenHandler
First off, a wider background.

I am working on a web application backed by a separate web API. The authentication in the web app should be ActiveDirectory based and it should be handled by the web API.

So, the LogIn action on AccountController on the web application only sends a post request to the AuthenticationController - and there I do AD Authentication using UserPrincipal and PrincipalContext.
The authentication works fine and I create some claims.

The problems start when I need to post back the result to the web app, so that I can do the 'SignIn' like below

```<code>if (result.Claims == null)
{
    this.Logger.Error($"Something went wrong when discovering identity of user [{model.UserName}]");
    throw new InvalidOperationException(Strings_Error.ErrorWhileDiscoveringUserIdentity);
}

IAuthenticationManager authenticationManager = this.HttpContext.GetOwinContext().Authentication;
authenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
authenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = false }, result.Claims);
</code>```

I am using JwtSecurityTokenHandler to serialize the claims so that I can attach them to the response message from my Web Api controller.
The serialization happens as follows:

```<code>public static string GenerateToken(this ClaimsIdentity identity)
{
    SymmetricSecurityKey securityKey = new SymmetricSecurityKey(Encoding.Default.GetBytes(ClaimsIndentitySerializer.SecurityKey));
    SigningCredentials signingCredentials = new SigningCredentials(securityKey,SecurityAlgorithms.HmacSha256Signature);
    JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler();

    SecurityTokenDescriptor tokenDescriptor = new SecurityTokenDescriptor
    {
        Subject = identity,
        SigningCredentials = signingCredentials,
        Issuer = IssuerKey,
        Audience = "http://www.mycompany.com",
    };

    SecurityToken token = tokenHandler.CreateToken(tokenDescriptor);
    string tokenString = tokenHandler.WriteToken(token);

    return tokenString;
}
</code>```

Then the generating claims from the string:

```<code>public static ClaimsIdentity ReadToken(this string token)
{
    JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler();
    SymmetricSecurityKey securityKey = new SymmetricSecurityKey(Encoding.Default.GetBytes(ClaimsIndentitySerializer.SecurityKey));

    TokenValidationParameters validationParameters = new TokenValidationParameters()
    {
        ValidAudience = "http://www.mycompany.com",
        ValidIssuer = IssuerKey,
        IssuerSigningKey = securityKey
    };

    SecurityToken validatedToken = new JwtSecurityToken() as SecurityToken;
    ClaimsPrincipal claimsPrincipal = tokenHandler.ValidateToken(token, validationParameters, out validatedToken);

    return claimsPrincipal.Identity as ClaimsIdentity;
}
</code>```

I have created a unit test to check whether the claims match after being processed. And, much to my surprise, they are significantly different.

```<code>public void TestClaimsSerialization()
{
    ClaimsIdentity identity = new ClaimsIdentity(DefaultAuthenticationTypes.ApplicationCookie, ClaimsIdentity.DefaultNameClaimType, ClaimsIdentity.DefaultRoleClaimType);
    identity.AddClaim(new Claim("http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider", "Active Directory"));
    identity.AddClaim(new Claim(ClaimTypes.Name, "TestName"));
    identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, "TestNameIdentifier"));
    var token = identity.GenerateToken();
    var deserialized = token.ReadToken();
    Assert.Equal(identity.Name, deserialized.Name);
    Assert.Equal(identity.Claims.FirstOrDefault(x=>x.Type == ClaimTypes.NameIdentifier).Value, deserialized.Claims.FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier).Value);
    Assert.Equal(identity.AuthenticationType, deserialized.AuthenticationType); //the last assert fails
}
</code>```

The error is
Expected: ApplicationCookie Actual:   AuthenticationTypes.Federation

Other Asserts are OK, so the values are actually preserved.

Any idea why?

答:
I had a similar problem and I solved it by changing

```<code>return claimsPrincipal.Identity as ClaimsIdentity;
</code>```

to

```<code>return new ClaimsIdentity(claimsPrincipal.Claims, "ApplicationCookie");
</code>```

Body:
First off, a wider background.

I am working on a web application backed by a separate web API. The authentication in the web app should be ActiveDirectory based and it should be handled by the web API.

So, the LogIn action on AccountController on the web application only sends a post request to the AuthenticationController - and there I do AD Authentication using UserPrincipal and PrincipalContext.
The authentication works fine and I create some claims.

The problems start when I need to post back the result to the web app, so that I can do the 'SignIn' like below

if (result.Claims == null)
{
    this.Logger.Error($"Something went wrong when discovering identity of user [{model.UserName}]");
    throw new InvalidOperationException(Strings_Error.ErrorWhileDiscoveringUserIdentity);
}

IAuthenticationManager authenticationManager = this.HttpContext.GetOwinContext().Authentication;
authenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
authenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = false }, result.Claims);

I am using JwtSecurityTokenHandler to serialize the claims so that I can attach them to the response message from my Web Api controller.
The serialization happens as follows:

public static string GenerateToken(this ClaimsIdentity identity)
{
    SymmetricSecurityKey securityKey = new SymmetricSecurityKey(Encoding.Default.GetBytes(ClaimsIndentitySerializer.SecurityKey));
    SigningCredentials signingCredentials = new SigningCredentials(securityKey,SecurityAlgorithms.HmacSha256Signature);
    JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler();

    SecurityTokenDescriptor tokenDescriptor = new SecurityTokenDescriptor
    {
        Subject = identity,
        SigningCredentials = signingCredentials,
        Issuer = IssuerKey,
        Audience = "http://www.mycompany.com",
    };

    SecurityToken token = tokenHandler.CreateToken(tokenDescriptor);
    string tokenString = tokenHandler.WriteToken(token);

    return tokenString;
}

Then the generating claims from the string:

public static ClaimsIdentity ReadToken(this string token)
{
    JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler();
    SymmetricSecurityKey securityKey = new SymmetricSecurityKey(Encoding.Default.GetBytes(ClaimsIndentitySerializer.SecurityKey));

    TokenValidationParameters validationParameters = new TokenValidationParameters()
    {
        ValidAudience = "http://www.mycompany.com",
        ValidIssuer = IssuerKey,
        IssuerSigningKey = securityKey
    };

    SecurityToken validatedToken = new JwtSecurityToken() as SecurityToken;
    ClaimsPrincipal claimsPrincipal = tokenHandler.ValidateToken(token, validationParameters, out validatedToken);

    return claimsPrincipal.Identity as ClaimsIdentity;
}

I have created a unit test to check whether the claims match after being processed. And, much to my surprise, they are significantly different.

public void TestClaimsSerialization()
{
    ClaimsIdentity identity = new ClaimsIdentity(DefaultAuthenticationTypes.ApplicationCookie, ClaimsIdentity.DefaultNameClaimType, ClaimsIdentity.DefaultRoleClaimType);
    identity.AddClaim(new Claim("http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider", "Active Directory"));
    identity.AddClaim(new Claim(ClaimTypes.Name, "TestName"));
    identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, "TestNameIdentifier"));
    var token = identity.GenerateToken();
    var deserialized = token.ReadToken();
    Assert.Equal(identity.Name, deserialized.Name);
    Assert.Equal(identity.Claims.FirstOrDefault(x=>x.Type == ClaimTypes.NameIdentifier).Value, deserialized.Claims.FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier).Value);
    Assert.Equal(identity.AuthenticationType, deserialized.AuthenticationType); //the last assert fails
}

The error is
Expected: ApplicationCookie Actual:   AuthenticationTypes.Federation

Other Asserts are OK, so the values are actually preserved.

Any idea why?

Body:
I had a similar problem and I solved it by changing

return claimsPrincipal.Identity as ClaimsIdentity;

to

return new ClaimsIdentity(claimsPrincipal.Claims, "ApplicationCookie");


答:
= is added for padding. The length of a base64 string should be multiple of 4, so 1 or 2 = are added as necessary.

Read: No, you shouldn't remove it.

Title: Remove trailing "=" when base64 encoding

Body:
I am noticing that whenever I base64 encode a string, a "=" is appended at the end.  Can I remove this character and then reliably decode it later by adding it back, or is this dangerous?  In other words, is the "=" always appended, or only in certain cases?

I want my encoded string to be as short as possible, that's why I want to know if I can always remove the "=" character and just add it back before decoding.


问:
Windows App Deployment Failure to Lumia phone
I'm currently working on a Universal 8.1 app.
I've always deployed it for testing on my Lumia 535 without any problem. However, today I'm unable to deploy. I get this error code.

DEP6200 : Bootstrapping failed. Device cannot be found. 0x89731810: Deployment failed because no Windows Phone was detected. Make sure a phone is connected and powered on.

This problem occurred previously and disappeared when I updated my PC windows from build 10240 to 10586. Then I was using a Lumia 535 for deployment.
Now I'm using a Lumia 640xl and the problem suddenly resurfaced.
I've:
- repaired my visual studio installation
- changed USB cable
- tried the proposed solutions in the below links (except reverting to Win 8.1 or factory reset).

Still the problem persists.

I've tried all the solutions from these links Windows phone 8.1 emulator not loading OS

Error : DEP6200 : Bootstrapping 'Device' failed. Device cannot be found

Tools for Apache Cordova DEP6200 Windows Universal App Windows Phone Won't Connect

Fail to run an app developed on desktop (Visual Studio 2015) on usb-connected "Surface 3"

Windows 10 Mobile Error: DEP6200

Please what can I do?

答: I had the same problem for a long time, but finally found a solution. Plug in your Lumia, go to Device Manager and uninstall it with drivers, then reboot. Everything should work fine. I know, I'm a bit late, but this answer might help someone else;)</p>

OwnerDisplayName: Olumide Oyetoke


问:
Angular 2 Pipes: How to sort by multiple fields?
I have a list with the following details which I want to sort by the one with the most number of reviews and then sorted alphabetically afterwards.

```<code>    [
     {
      "reviews": 9,
      "name": 'B'
     }, {
      "reviews": 9,
      "name": 'A'
     }, {
      "reviews": 15,
      "name": 'C'
     }, {
      "reviews": 9,
      "name": 'D'
     },..
    ]
</code>```

My desired sequence for the sort will be: C A B D.
I have a simple sorting pipe to sort it by reviews but I wanted it to sort by name afterwards.

```<code>    items.sort(function(a, b) {
      return a['reviews'] - b['reviews'];
    }
</code>```

Thanks.

答:
```<code> @Pipe({
        name: 'filter'
    })
    export class FilterPipe implements PipeTransform {
        transform(items: Array<any>, filter: {[key: string]: any }): Array<any> {
            return items.filter(item => {
                let notMatchingField = Object.keys(filter)
                                             .find(key => item[key] !== filter[key]);

                return !notMatchingField; // true if matches all fields
            });
        }
    }
</code>```

Body:
I have a list with the following details which I want to sort by the one with the most number of reviews and then sorted alphabetically afterwards.

    [
     {
      "reviews": 9,
      "name": 'B'
     }, {
      "reviews": 9,
      "name": 'A'
     }, {
      "reviews": 15,
      "name": 'C'
     }, {
      "reviews": 9,
      "name": 'D'
     },..
    ]

My desired sequence for the sort will be: C A B D.
I have a simple sorting pipe to sort it by reviews but I wanted it to sort by name afterwards.

    items.sort(function(a, b) {
      return a['reviews'] - b['reviews'];
    }

Thanks.


问:
ROUNDING based on digits of number
I have the following Excel spreadsheet:

```<code>         A                 B
1        6.355            6.000
2       58.690           50.000
3      357.867          350.000
4    1.260.563        1.200.000
5   12.480.370       12.400.000
</code>```

In Column A I have a bunch of radnom numbers that can change everytime the user enters new data into the spreadsheet.

In Column B I want to CUT and ROUNDDOWN the numbers in Column A in the following systematic:

```<code>Number consists of 4 digits  -->  CUT and ROUNDDOWN after the 1st digit
Number consitst of 5 digits  -->  CUT and ROUNDDOWN after the 1st digit
Number consists of 6 digits  -->  CUT and ROUNDDOWN after the 2nd digit
Number consists of 7 digits  -->  CUT and ROUNDDOWN after the 2nd digit
Number consists of 8 digits  -->  CUT and ROUNDDOWN after the 3rd digit
</code>```

So far I have tried the following:

```<code>=ROUNDDOWN(A1,1-LEN(A1))
</code>```

However, this formular only works well for the 4-5 digits numbers. Afterwards I would have to change the 1 to a 2 and so on.

Is there a way to do this rounding automatically based on the systematic described above?

答:
Put the following formula in B1 downwards:

```<code>=ROUNDDOWN(A1,-(INT(LOG10(A1)/2)+2))
</code>```

Title: ROUNDING based on digits of number

Body:
I have the following Excel spreadsheet:

         A                 B
1        6.355            6.000
2       58.690           50.000
3      357.867          350.000
4    1.260.563        1.200.000
5   12.480.370       12.400.000

In Column A I have a bunch of radnom numbers that can change everytime the user enters new data into the spreadsheet.

In Column B I want to CUT and ROUNDDOWN the numbers in Column A in the following systematic:

Number consists of 4 digits  -->  CUT and ROUNDDOWN after the 1st digit
Number consitst of 5 digits  -->  CUT and ROUNDDOWN after the 1st digit
Number consists of 6 digits  -->  CUT and ROUNDDOWN after the 2nd digit
Number consists of 7 digits  -->  CUT and ROUNDDOWN after the 2nd digit
Number consists of 8 digits  -->  CUT and ROUNDDOWN after the 3rd digit

So far I have tried the following:

=ROUNDDOWN(A1,1-LEN(A1))

However, this formular only works well for the 4-5 digits numbers. Afterwards I would have to change the 1 to a 2 and so on.

Is there a way to do this rounding automatically based on the systematic described above?

Body:
Put the following formula in B1 downwards:

=ROUNDDOWN(A1,-(INT(LOG10(A1)/2)+2))


问:
How can I ensure a specific datatype when saving in mongo?
I'm using mongodb.

I'm saving a record with a very long number, but I don't want to save it as a number (a float number) I want it as a string.

e.g. I saved "171829572137423434" and I got "1.718295E+16" (just an example) But I need the complete number since is an ID, how can I force to save it as a string in mongodb?

By the way I am using PHP api.

答:
```<code>$number = 42;

// this stores as a number
$collection->insert(array('number'=>$number));

// this stores as a string
$collection->insert(array('number'=>strval($number)));
</code>```

ContentLicense: CC BY-SA 2.5


问:
Matlab: Why is the fill function not filling the area between two circles?
I'm trying to fill the intersecting area between two circles in Matlab. I've quite literally copied and pasted this piece of code from this article on Matlab Central.

```<code>t = linspace(0, 2*pi, 100);
cir = @(r,ctr) [r*cos(t)+ctr(1); r*sin(t)+ctr(2)]; % Circle Function
c1 = cir(1.0, [0; 0]);
c2 = cir(1.5, [1; 1]);
in1 = find(inpolygon(c1(1,:), c1(2,:), c2(1,:), c2(2,:))); % Circle #1 Points Inside Circle #2
in2 = find(inpolygon(c2(1,:), c2(2,:), c1(1,:), c1(2,:))); % Circle #2 Points Inside Circle #1
[fillx,ix] = sort([c1(1,in1) c2(1,in2)]); % Sort Points
filly = [c1(2,in1) (c2(2,in2))];
filly = filly(ix);
figure(1)
plot(c1(1,:), c1(2,:))
hold on
plot(c2(1,:), c2(2,:))
fill([fillx fliplr(fillx)], [filly fliplr(filly)], 'g', 'EdgeColor','none')
hold off
axis square
</code>```

What I end up with is the following image:

However, it should appear as this image:

Why is the area not being filled as it is in the example article?

答:
If you have Mapping Toolbox you can use polybool to find the intersection between to polygones, and than patch (which dosen't require Mapping Toolbox, and is better than fill) to draw it. The folowing code works even without the first 2 lines that use poly2cw, but it issues some warnings. This can be solved with the poly2cw trasfomation:

```<code>[c1(1,:), c1(2,:)] = poly2cw(c1(1,:), c1(2,:)); % clock-wise transform
[c2(1,:), c2(2,:)] = poly2cw(c2(1,:), c2(2,:)); % clock-wise transform
[xb, yb] = polybool('intersection',c1(1,:),c1(2,:),c2(1,:), c2(2,:));
plot(c1(1,:), c1(2,:))
hold on
plot(c2(1,:), c2(2,:))
patch(xb, yb, 1, 'FaceColor', 'g','EdgeColor','none')
axis equal
</code>```

Body:
I'm trying to fill the intersecting area between two circles in Matlab. I've quite literally copied and pasted this piece of code from this article on Matlab Central.

t = linspace(0, 2*pi, 100);
cir = @(r,ctr) [r*cos(t)+ctr(1); r*sin(t)+ctr(2)]; % Circle Function
c1 = cir(1.0, [0; 0]);
c2 = cir(1.5, [1; 1]);
in1 = find(inpolygon(c1(1,:), c1(2,:), c2(1,:), c2(2,:))); % Circle #1 Points Inside Circle #2
in2 = find(inpolygon(c2(1,:), c2(2,:), c1(1,:), c1(2,:))); % Circle #2 Points Inside Circle #1
[fillx,ix] = sort([c1(1,in1) c2(1,in2)]); % Sort Points
filly = [c1(2,in1) (c2(2,in2))];
filly = filly(ix);
figure(1)
plot(c1(1,:), c1(2,:))
hold on
plot(c2(1,:), c2(2,:))
fill([fillx fliplr(fillx)], [filly fliplr(filly)], 'g', 'EdgeColor','none')
hold off
axis square

What I end up with is the following image:

However, it should appear as this image:

Why is the area not being filled as it is in the example article?

Body:
If you have Mapping Toolbox you can use polybool to find the intersection between to polygones, and than patch (which dosen't require Mapping Toolbox, and is better than fill) to draw it. The folowing code works even without the first 2 lines that use poly2cw, but it issues some warnings. This can be solved with the poly2cw trasfomation:

[c1(1,:), c1(2,:)] = poly2cw(c1(1,:), c1(2,:)); % clock-wise transform
[c2(1,:), c2(2,:)] = poly2cw(c2(1,:), c2(2,:)); % clock-wise transform
[xb, yb] = polybool('intersection',c1(1,:),c1(2,:),c2(1,:), c2(2,:));
plot(c1(1,:), c1(2,:))
hold on
plot(c2(1,:), c2(2,:))
patch(xb, yb, 1, 'FaceColor', 'g','EdgeColor','none')
axis equal


问:
Why do string indices (albeit representing integers) work in arrays?
Why does the following enumerate correctly?

```<code>var arr = [];
arr[0] = 'foo';
arr['1'] = 'bar';

arr.forEach(v => console.log(v)); // foo, bar
</code>```

Both arr[1] and arr['1'] also work. Is this a feature of Array that strings corresponding to integers are mapped to their integer value?

答:
Is this a feature of Array that strings corresponding to integers are
  mapped to their integer value?

No. Think of Arrays just like regular objects.

When accessing a property of an object using bracket notation - the property must be quoted.

eg: var someVar = { a:1, b:2 } - to access the value of property 'a' with bracket notation we write: someVar['a']

So it makes perfect sense to access array elements via quoted indexes.

That being said, it isn't necessary to quote the index - and that's because - as others have mentioned - the index is coerced into a string by the JavaScript engine through an implicit toString conversion

Body:
Why does the following enumerate correctly?

var arr = [];
arr[0] = 'foo';
arr['1'] = 'bar';

arr.forEach(v => console.log(v)); // foo, bar

Both arr[1] and arr['1'] also work. Is this a feature of Array that strings corresponding to integers are mapped to their integer value?


问:
The client disconnected
I'm getting the following error in logs for WebAPI

System.Web.HttpException (0x800703E3): The client disconnected.    at
  System.Web.Hosting.IIS7WorkerRequest.EndRead(IAsyncResult asyncResult)
  at System.Web.HttpBufferlessInputStream.EndRead(IAsyncResult
  asyncResult)    at System.Threading.Tasks.TaskFactory
  1.FromAsyncTrimPromise 1.Complete(TInstance thisRef, Func 3 endMethod, IAsyncResult asyncResult, Boolean requiresSynchronization)
  --- End of stack trace from previous location where exception was thrown ---    at
  System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
  task)    at
  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
  task)    at System.IO.StreamReader.d__97.MoveNext()
  --- End of stack trace from previous location where exception was thrown ---    at
  System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
  task)    at
  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
  task)    at
  System.IO.StreamReader.d__62.MoveNext()
  --- End of stack trace from previous location where exception was thrown ---    at
  System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
  task)    at
  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
  task)    at Microsoft.Owin.OwinRequest.d__0.MoveNext()
  --- End of stack trace from previous location where exception was thrown ---    at
  System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
  task)    at
  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
  task)    at
  Microsoft.Owin.Security.OAuth.OAuthAuthorizationServerHandler.d__22.MoveNext()
  --- End of stack trace from previous location where exception was thrown ---    at
  System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
  task)    at
  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
  task)    at
  Microsoft.Owin.Security.OAuth.OAuthAuthorizationServerHandler.d__0.MoveNext()
  --- End of stack trace from previous location where exception was thrown ---    at
  System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
  task)    at
  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
  task)    at
  Microsoft.Owin.Security.Infrastructure.AuthenticationMiddleware
  1.d__0.MoveNext()
  --- End of stack trace from previous location where exception was thrown ---    at
  System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
  task)    at
  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
  task)    at Web.API.Middleware.OwinMiddleware.d__1.MoveNext()
  in D:\UAT\Web.API\Middleware\OwinMiddleware.cs:line 49

How can I handle and ignore these exceptions by exception filter? Why this error occurs and how can I reproduce that? I wanna catch and ignore only The client disconnected but not all HttpException

I saw this similar question but how can I do that in exception filter?

答:
You can ignore these exceptions.

The exception says what the problem is: "The client disconnected". It means that the client initiated a request but then disconnected before it bothered to read all of the response.

There are any numbers of reasons why that might be the case, but (unless you have a dodgy internet connection at your server end) it is almost certainly an issue at the client end. I regularly see these myself and mostly it seems to be related to a bot. So I filter them out and ignore them.

Title: The client disconnected


问:
To create an array that contains each digit as separate element from integer in JavaScript
My understanding is that bellow code will create an array name digits which contains all digits from n, I'm I right?

var n =  123456789;
var digits = (""+n).split("");

But I did'n understood (""+n) ?
Can anyone help me?
Thanks in advance.

答:
(""+n) means type casting the variable n into string

```<code>var n = 32;  // n is integer type
n = "" + n; // now n is string type (n = "32")
var digits = n.split("");//execute string split function
//now digits = ['3','2'] (array of chars or single string charector)
</code>```

Body:
(""+n) means type casting the variable n into string

var n = 32;  // n is integer type
n = "" + n; // now n is string type (n = "32")
var digits = n.split("");//execute string split function
//now digits = ['3','2'] (array of chars or single string charector)


答: n is type of a number, with (""+n), you are basically converting n to a string, so you can use split method. numbers do not have a split method

Title: To create an array that contains each digit as separate element from integer in JavaScript

Body:
My understanding is that bellow code will create an array name digits which contains all digits from n, I'm I right?

var n =  123456789;
var digits = (""+n).split("");

But I did'n understood (""+n) ?
Can anyone help me?
Thanks in advance.


问:
i cannot create a domain in openstack
i am trying to create a domain in openstack

i tried this code

```<code>export OS_TOKEN=admintoken
export OS_URL=http://20.20.20.119:35357/v3
export OS_IDENTITY_API_VERSION=3
openstack domain create --description "Default Domain" default
</code>```

the result should be like this
please see the first table on this link
https://www.server-world.info/en/note?os=CentOS_7&p=openstack_mitaka&f=4

but i am facing an error

the error is
"the request you have made requires authentication. (HTTP 401) (Request-ID: req-af227c0b-5db2-8e32-a391b133b466)"

kindly help so that i can create a domain

thank you very much

答: The OS_TOKEN value should be same as in your environment keystone.conf (/etc/keystone/keystone.conf) admin_token label.</p>

Title: i cannot create a domain in openstack

Body:
i am trying to create a domain in openstack

i tried this code

export OS_TOKEN=admintoken
export OS_URL=http://20.20.20.119:35357/v3
export OS_IDENTITY_API_VERSION=3
openstack domain create --description "Default Domain" default

the result should be like this
please see the first table on this link
https://www.server-world.info/en/note?os=CentOS_7&p=openstack_mitaka&f=4

but i am facing an error

the error is
"the request you have made requires authentication. (HTTP 401) (Request-ID: req-af227c0b-5db2-8e32-a391b133b466)"

kindly help so that i can create a domain

thank you very much


问:
Visual Basic format number to hower many number on left of decimal and 1 decimal without rounding
I am acutally using SSRS but it is for an expression so this is VB code. I am wondering how I would get a number such as 236.4723423 to appear at 236.4 instead of 236.5, so basically I jsut want to truncate it always after 1 decimal.

I tried Format = "N1" this rounds it
I tried Formate = "#######.0" and "######.#" and this rounds it as well.

Any ideas?

答:
Use the format "########.00", then once it's in string form, trim the last char.

Edit:

```<code>Dim myString as String
myString = CStr(FORMAT(((SUM(Fields!Shipment_Weight.Value)) / 2000),"######.00"))
myString = myString.Substring(0, myString.Length - 1) & "T"
</code>```

Body:
Use the format "########.00", then once it's in string form, trim the last char.

Edit:

Dim myString as String
myString = CStr(FORMAT(((SUM(Fields!Shipment_Weight.Value)) / 2000),"######.00"))
myString = myString.Substring(0, myString.Length - 1) & "T"


答:
```<code>items
 .sort(function(a, b) {
      return a['reviews'] - b['reviews'];
    }
  .sort(function(a, b) {
    let a = a['name'].toUpperCase();
    let b = b['name'].toUpperCase();
    return (a < b) ? -1 : (a > b) ? 1 : 0;
   });
</code>```

or you can use toLocalCompare

```<code>items
     .sort(function(a, b) {
          return a['reviews'] - b['reviews'];
        }
      .sort(function(a, b) {
        return a['name'].localeCompare(b['name']);
       });
</code>```

Title: Angular 2 Pipes: How to sort by multiple fields?

Body:
items
 .sort(function(a, b) {
      return a['reviews'] - b['reviews'];
    }
  .sort(function(a, b) {
    let a = a['name'].toUpperCase();
    let b = b['name'].toUpperCase();
    return (a < b) ? -1 : (a > b) ? 1 : 0;
   });

or you can use toLocalCompare

items
     .sort(function(a, b) {
          return a['reviews'] - b['reviews'];
        }
      .sort(function(a, b) {
        return a['name'].localeCompare(b['name']);
       });


问:
Post fails with node-mysql
I am trying to post data with node.js. I have written the following code and installed MySQL support via npm, but I failed to Post to database .

I am using standart express backend

Here is my code users.js

```<code>var express = require('express');
var router = express.Router();
var mysql = require('mysql');

var connection = mysql.createPool({
  host:'localhost',
  user:'alp',
  password:'******',
  database :'diablo'
});

/* post users listing.  connection.connect(); */

router.post('/', function(req, res,next) {
var username = req.body.username;
var password = req.body.password;

connection.query("SELECT * FROM user WHERE username = (?) AND password = (?)" ,[username,password], function(err,rows,fields) {
if (err) console.log(err);

if (rows.length > 0) {
  res.send({'success':true,'message':rows[0].username });
} else {
  res.send({'success':false,'message' : 'User not found , please try again'});
}
});

});

module.exports = router;
</code>```

Error Message

Response {   "_bodyInit": "{\"success\":false,\"message\":\"User not
  found , please try again\"}",   "_bodyText":
  "{\"success\":false,\"message\":\"User not found , please try
  again\"}",   "heade

What is my mistake?

By the way I checked other headlines. ı did not find it

答:
The problem here is that you are attempting to retrieve username and password from req.body object, and you failed to require body-parser in order to be able to do that, hence your username and password are undefined and your query fails to find the corresponding user.

To install the body-parser module just type npm install --s body-parser and then require it in your users.js file.

Title: Post fails with node-mysql

Body:
I am trying to post data with node.js. I have written the following code and installed MySQL support via npm, but I failed to Post to database .

I am using standart express backend

Here is my code users.js

var express = require('express');
var router = express.Router();
var mysql = require('mysql');

var connection = mysql.createPool({
  host:'localhost',
  user:'alp',
  password:'******',
  database :'diablo'
});

/* post users listing.  connection.connect(); */

router.post('/', function(req, res,next) {
var username = req.body.username;
var password = req.body.password;

connection.query("SELECT * FROM user WHERE username = (?) AND password = (?)" ,[username,password], function(err,rows,fields) {
if (err) console.log(err);

if (rows.length > 0) {
  res.send({'success':true,'message':rows[0].username });
} else {
  res.send({'success':false,'message' : 'User not found , please try again'});
}
});

});

module.exports = router;

Error Message

Response {   "_bodyInit": "{\"success\":false,\"message\":\"User not
  found , please try again\"}",   "_bodyText":
  "{\"success\":false,\"message\":\"User not found , please try
  again\"}",   "heade

What is my mistake?

By the way I checked other headlines. ı did not find it


问:
Loading tsv/csv file in excel sheet
This is my code.

```<code>    public static string LoadPackage(DirectoryInfo outputDir, string name)
    {
        FileInfo newFile = new FileInfo(outputDir.FullName + @"\test.xlsx");
        if (newFile.Exists)
        {
            newFile.Delete();
            newFile = new FileInfo(outputDir.FullName + @"\test.xlsx");
        }

        var format = new ExcelTextFormat();
        format.Delimiter = '\t';
        format.SkipLinesBeginning = 1;

        using (ExcelPackage package = new ExcelPackage())
        {
            LoadSheet(package, outputDir, name);

            package.SaveAs(newFile);

        }
        return newFile.FullName;
    }
</code>```

And after that i call LoadSheet method in order to fill my excel file from tsv file.

```<code>    public static void LoadSheet(ExcelPackage package, DirectoryInfo
    outputDir, string name)
    {

        var ws = package.Workbook.Worksheets.Add("Content");

        var format = new ExcelTextFormat();
        format.Delimiter = '\t';
        format.SkipLinesBeginning = 2;
        format.SkipLinesEnd = 1;

        var range = ws.Cells["A1"].LoadFromText(new
        FileInfo(outputDir.FullName + "\\" + name), format,
        TableStyles.Medium27, false);
    }
</code>```

And this is my code on button click event

```<code>        if (BrowseFileUpload.HasFile)
        {
            var name = BrowseFileUpload.PostedFile.FileName;
            InputTextBox.Text = name;
            LoadData.LoadPackage(new
            System.IO.DirectoryInfo("C:\\Users\\Nemanja\\Downloads"), name);

            InfoLabel.Text = "Your data has been imported!!!";
            InfoLabel.ForeColor = System.Drawing.Color.Blue;
            InfoLabel.Font.Size = 20;
        }
</code>```

Everything is ok i create new excel file, sheet save it but it does not load data that i need it to load inside excel file. It's only empty file or i get a error the file is corrupted recover what you can.

Can someone figure out what can be a problem based on my explanation and this code. Thank you all good people.

答:
I think that the problem may well be with the format of your source data. I've put together the following sample, based on your code, and it works fine.

```<code>var outFile = Path.ChangeExtension(filePath, ".xlsx");
using (var p = new ExcelPackage())
{
    var fmt = new ExcelTextFormat();
    fmt.Delimiter = '\t';
    fmt.SkipLinesBeginning = 2;
    fmt.SkipLinesEnd = 1;
    fmt.EOL = ((char)10).ToString();   // THIS LINE FIXED THE PROBLEM (UNIX NEWLINE)

    var ws = p.Workbook.Worksheets.Add("Imported Text");
    ws.Cells[1, 1].LoadFromText(new FileInfo(filePath), fmt, TableStyles.Medium27, false);
    p.SaveAs(new FileInfo(outFile));
}
</code>```

Try running your data through this and see if you get the same issue or not.

UPDATED

The problem was a unix-style newline in the file - EPPlus expects a windows-style newline by default

Title: Loading tsv/csv file in excel sheet

Body:
This is my code.

    public static string LoadPackage(DirectoryInfo outputDir, string name)
    {
        FileInfo newFile = new FileInfo(outputDir.FullName + @"\test.xlsx");
        if (newFile.Exists)
        {
            newFile.Delete();
            newFile = new FileInfo(outputDir.FullName + @"\test.xlsx");
        }

        var format = new ExcelTextFormat();
        format.Delimiter = '\t';
        format.SkipLinesBeginning = 1;

        using (ExcelPackage package = new ExcelPackage())
        {
            LoadSheet(package, outputDir, name);

            package.SaveAs(newFile);

        }
        return newFile.FullName;
    }

And after that i call LoadSheet method in order to fill my excel file from tsv file.

    public static void LoadSheet(ExcelPackage package, DirectoryInfo
    outputDir, string name)
    {

        var ws = package.Workbook.Worksheets.Add("Content");

        var format = new ExcelTextFormat();
        format.Delimiter = '\t';
        format.SkipLinesBeginning = 2;
        format.SkipLinesEnd = 1;

        var range = ws.Cells["A1"].LoadFromText(new
        FileInfo(outputDir.FullName + "\\" + name), format,
        TableStyles.Medium27, false);
    }

And this is my code on button click event

        if (BrowseFileUpload.HasFile)
        {
            var name = BrowseFileUpload.PostedFile.FileName;
            InputTextBox.Text = name;
            LoadData.LoadPackage(new
            System.IO.DirectoryInfo("C:\\Users\\Nemanja\\Downloads"), name);

            InfoLabel.Text = "Your data has been imported!!!";
            InfoLabel.ForeColor = System.Drawing.Color.Blue;
            InfoLabel.Font.Size = 20;
        }

Everything is ok i create new excel file, sheet save it but it does not load data that i need it to load inside excel file. It's only empty file or i get a error the file is corrupted recover what you can.

Can someone figure out what can be a problem based on my explanation and this code. Thank you all good people.

Body:
I think that the problem may well be with the format of your source data. I've put together the following sample, based on your code, and it works fine.

var outFile = Path.ChangeExtension(filePath, ".xlsx");
using (var p = new ExcelPackage())
{
    var fmt = new ExcelTextFormat();
    fmt.Delimiter = '\t';
    fmt.SkipLinesBeginning = 2;
    fmt.SkipLinesEnd = 1;
    fmt.EOL = ((char)10).ToString();   // THIS LINE FIXED THE PROBLEM (UNIX NEWLINE)

    var ws = p.Workbook.Worksheets.Add("Imported Text");
    ws.Cells[1, 1].LoadFromText(new FileInfo(filePath), fmt, TableStyles.Medium27, false);
    p.SaveAs(new FileInfo(outFile));
}

Try running your data through this and see if you get the same issue or not.

UPDATED

The problem was a unix-style newline in the file - EPPlus expects a windows-style newline by default


问:
How can I share a value from one page to another in Xamarin Forms?
I have this page:

```<code>using System.Diagnostics;
using Xamarin.Forms;

namespace Japanese
{
    public partial class PhrasesPage : ContentPage
    {

        public PhrasesPage()
        {
            var x = 99;
        }
    }
}
</code>```

and this page:

```<code>using System.Diagnostics;
using Xamarin.Forms;

namespace Japanese
{
    public partial class PhrasesPage2 : ContentPage
    {

        public PhrasesPage2()
        {
            var y = x;
        }
    }
}
</code>```

It's a very much simplified example but what I would like to know is how can I share the value of x so that it can be used on the PhrasesPage2>

答:
You will pass the value using the constructor of PhrasesPage2:

```<code>public PhrasesPage2(int x)
    {
        var y = x;
    }
</code>```

Than on page 1 when you want to navigate to page 2, you just pass the value when move to that page(here you use yourmethod you mostly use to navigate):
Navigation.PopAsync(new PhrasesPage2(x));

Body:
I have this page:

using System.Diagnostics;
using Xamarin.Forms;

namespace Japanese
{
    public partial class PhrasesPage : ContentPage
    {

        public PhrasesPage()
        {
            var x = 99;
        }
    }
}

and this page:

using System.Diagnostics;
using Xamarin.Forms;

namespace Japanese
{
    public partial class PhrasesPage2 : ContentPage
    {

        public PhrasesPage2()
        {
            var y = x;
        }
    }
}

It's a very much simplified example but what I would like to know is how can I share the value of x so that it can be used on the PhrasesPage2>

Body:
You will pass the value using the constructor of PhrasesPage2:

public PhrasesPage2(int x)
    {
        var y = x;
    }

Than on page 1 when you want to navigate to page 2, you just pass the value when move to that page(here you use yourmethod you mostly use to navigate):
Navigation.PopAsync(new PhrasesPage2(x));


问:
Error installing ScrAPI gem: ffi requires Ruby version >= 1.9.2
I am having issues installing the ScrAPI gem:

ERROR:  Error installing scrapi:
     ffi requires Ruby version >= 1.9.2.

I am running RVM and if I do ruby -v I get:

ruby -v
  ruby 1.9.2p110 (2010-12-20 revision 30269) [i686-linux]

答:
I am guessing you did

```<code>$ sudo gem install scrapi

sudo ruby -v
</code>```

Unless you followed Wayne's sudo RVM install I'm guessing root uses a different ruby.

Body:
I am guessing you did

$ sudo gem install scrapi

sudo ruby -v

Unless you followed Wayne's sudo RVM install I'm guessing root uses a different ruby.


问:
EF6 Code First, Context fluent API: How to set same field properties for multiple entities?
I have serveral entites inherited from the same base class

```<code>public class BaseEntity
{
   public string CreatedUser { get; set; }
   public DateTime? CreatedDate { get; set; }
   public string ChangedUser{ get; set; }
   public DateTime? ChangedDate { get; set; }

}
</code>```

Now in my my context builder I do not want to assign these field properties in every builder method seperatly.

I want a generalized method where I could add to each entitiy builder method like

```<code>private static void BasisFields(DbModelBuilder modelBuilder, Entity<TEntity> entitiy)
{
    modelBuilder.entitiy()
        .Property(k => k.CreatedUser)
        .HasMaxLength(32)
        .HasColumnType("varchar");

    modelBuilder.entitiy()
        .Property(k => k.CreatedDate)
        .HasColumnType("datetime");

    modelBuilder.entitiy()
        .Property(k => k.ChangedUser)
        .HasMaxLength(32)
        .HasColumnType("varchar");

    modelBuilder.entitiy()
        .Property(k => k.ChangedDate)
        .HasColumnType("datetime");

}
</code>```

But this code above is not correct, because I am a C# beginner...

How does it should look like?

答:
You can make the method generic:

```<code>private static void BasisFields<T>(DbModelBuilder modelBuilder)
    where T : BaseEntity
{
    modelBuilder.Entity<T>()
        .Property(k => k.CreatedUser)
        .HasMaxLength(32)
        .HasColumnType("varchar");

    modelBuilder.Entitity<T>()
        .Property(k => k.CreatedDate)
        .HasColumnType("datetime");

    modelBuilder.Entity<T>()
        .Property(k => k.ChangedUser)
        .HasMaxLength(32)
        .HasColumnType("varchar");

    modelBuilder.Entity<T>()
        .Property(k => k.ChangedDate)
        .HasColumnType("datetime");
}
</code>```

The generic constraint where T : BaseEntity ensures you can call it only with types that inherit BaseEntity and gives you access to the BaseEntity  properties inside the method body.

Now you should call it for every entity which inherits BaseEntity like

```<code>BasisFields<DerivedEntityA>(modelBuilder);
BasisFields<DerivedEntityB>(modelBuilder);
...
</code>```

If you want to make that process automatic for every entity which inherits BaseEntity, you can use the DbModelBuilder.Types<T> method:

Begins configuration of a lightweight convention that applies to all entities and complex types in the model that inherit from or implement the type specified by the generic argument.

So instead of writing a method and calling it for every derived entity, you can simply use:

```<code>modelBuilder.Types<BaseEntity>().Configure(c =>
{
    c.Property(k => k.CreatedUser)
        .HasMaxLength(32)
        .HasColumnType("varchar");

    c.Property(k => k.CreatedDate)
        .HasColumnType("datetime");

    c.Property(k => k.ChangedUser)
        .HasMaxLength(32)
        .HasColumnType("varchar");

    c.Property(k => k.ChangedDate)
        .HasColumnType("datetime");
});
</code>```

Body:
I have serveral entites inherited from the same base class

public class BaseEntity
{
   public string CreatedUser { get; set; }
   public DateTime? CreatedDate { get; set; }
   public string ChangedUser{ get; set; }
   public DateTime? ChangedDate { get; set; }

}

Now in my my context builder I do not want to assign these field properties in every builder method seperatly.

I want a generalized method where I could add to each entitiy builder method like

private static void BasisFields(DbModelBuilder modelBuilder, Entity<TEntity> entitiy)
{
    modelBuilder.entitiy()
        .Property(k => k.CreatedUser)
        .HasMaxLength(32)
        .HasColumnType("varchar");

    modelBuilder.entitiy()
        .Property(k => k.CreatedDate)
        .HasColumnType("datetime");

    modelBuilder.entitiy()
        .Property(k => k.ChangedUser)
        .HasMaxLength(32)
        .HasColumnType("varchar");

    modelBuilder.entitiy()
        .Property(k => k.ChangedDate)
        .HasColumnType("datetime");

}

But this code above is not correct, because I am a C# beginner...

How does it should look like?

Body:
You can make the method generic:

private static void BasisFields<T>(DbModelBuilder modelBuilder)
    where T : BaseEntity
{
    modelBuilder.Entity<T>()
        .Property(k => k.CreatedUser)
        .HasMaxLength(32)
        .HasColumnType("varchar");

    modelBuilder.Entitity<T>()
        .Property(k => k.CreatedDate)
        .HasColumnType("datetime");

    modelBuilder.Entity<T>()
        .Property(k => k.ChangedUser)
        .HasMaxLength(32)
        .HasColumnType("varchar");

    modelBuilder.Entity<T>()
        .Property(k => k.ChangedDate)
        .HasColumnType("datetime");
}

The generic constraint where T : BaseEntity ensures you can call it only with types that inherit BaseEntity and gives you access to the BaseEntity  properties inside the method body.

Now you should call it for every entity which inherits BaseEntity like

BasisFields<DerivedEntityA>(modelBuilder);
BasisFields<DerivedEntityB>(modelBuilder);
...

If you want to make that process automatic for every entity which inherits BaseEntity, you can use the DbModelBuilder.Types<T> method:

Begins configuration of a lightweight convention that applies to all entities and complex types in the model that inherit from or implement the type specified by the generic argument.

So instead of writing a method and calling it for every derived entity, you can simply use:

modelBuilder.Types<BaseEntity>().Configure(c =>
{
    c.Property(k => k.CreatedUser)
        .HasMaxLength(32)
        .HasColumnType("varchar");

    c.Property(k => k.CreatedDate)
        .HasColumnType("datetime");

    c.Property(k => k.ChangedUser)
        .HasMaxLength(32)
        .HasColumnType("varchar");

    c.Property(k => k.ChangedDate)
        .HasColumnType("datetime");
});


问:
Bind observable values on button click
I am using knockout to get and receive an object via JSON.
I have got a form that is used to display and edit values that are bound to a Javascript class.
My form has got an option for saving and discarding my values.
The problem is that if I enter a value to an observed property and click discard the values are not transmitted to the webservice but are saved in my "display form", though, which I do not want. If I click on discard the original values shall be displayed again.
Is it possible to perform my value-updating on a button click event (e.g. clicking "save") ?
Here a snippet of my current code:

```<code>jQuery(document).ready(function(){
    ko.applyBindings(new MyModel());
});

function MyModel(){
   this.Name = ko.observable("Bob");
}

<div data-bind="text: Name"></div>
<input type="text" data-bind="value: Name" />
<input type="button" onclick="discardChanges()" value="Discard" />
<input type="button" onclick="saveChanges()" value="Save" />
</code>```

If I modified the name and click Discard the original value (in this case Bob) should be restored whereas when I click Save the new value should be assigned (e.g. this.Name("Bill")).

Does anyone have an idea how to solve my problem?

答:
Using the ko.extension beneath

```<code>var MyModel = function (data) {
    var self = this;

    self.Name= ko.observable('');

    self.Underscore = ko.Underscore(self);

    self.Cancel = function () {
        self.Underscore.Cancel();
    }

    self.Confirm = function () {
        self.Underscore.Confirm();
    }
};
</code>```

HTML:

```<code> <input type="button" data-bind="click: Cancel" value="Discard" />
 <input type="button" data-bind="click: Confirm" value="Keep" />
</code>```

This knockout extension, it creates an underscore version of each observable ie self.Name() -> self._Name()

```<code>ko.Underscore = function (data) {
    var obj = data;
    var result = {};
    // Underscore Property Check
    var _isOwnProperty = function (isUnderscore, prop) {
        return (isUnderscore == null || prop.startsWith('_') == isUnderscore) && typeof obj[prop] == 'function' && obj.hasOwnProperty(prop) && ko.isObservable(obj[prop]) && !ko.isComputed(obj[prop])
    }
    // Creation of Underscore Properties
    result.init = function () {
        for (var prop in obj) {
            if (_isOwnProperty(null, prop)) {
                var val = obj[prop]();
                var temp = '_' + prop;
                if (obj[prop].isObservableArray)
                    obj[temp] = ko.observableArray(val);
                else
                    obj[temp] = ko.observable(val);
            }
        }
    };
    // Cancel
    result.Cancel = function () {
        for (var prop in obj) {
            if (_isOwnProperty(false, prop)) {
                var val = obj[prop]();
                var p = '_' + prop;
                obj[p](val);
            }
        }
    }
    // Confirm
    result.Confirm = function () {
        for (var prop in obj) {
            if (_isOwnProperty(true, prop)) {
                var val = obj[prop]();
                var p = prop.replace('_', '');
                obj[p](val);
            }
        }
    }
    // Observables
    result.Properties = function () {
        var obs = [];
        for (var prop in obj) {
            if (typeof obj[prop] == 'function' && obj.hasOwnProperty(prop) && ko.isObservable(obj[prop]) && !ko.isComputed(obj[prop])) {
                var val = obj[prop]();
                obs.push({ 'Name': prop, 'Value': val });
            }
        }
        return obs;
    }

    if (obj != null)
        result.init();

    return result;
}
</code>```

Title: Bind observable values on button click

Body:
I am using knockout to get and receive an object via JSON.
I have got a form that is used to display and edit values that are bound to a Javascript class.
My form has got an option for saving and discarding my values.
The problem is that if I enter a value to an observed property and click discard the values are not transmitted to the webservice but are saved in my "display form", though, which I do not want. If I click on discard the original values shall be displayed again.
Is it possible to perform my value-updating on a button click event (e.g. clicking "save") ?
Here a snippet of my current code:

jQuery(document).ready(function(){
    ko.applyBindings(new MyModel());
});

function MyModel(){
   this.Name = ko.observable("Bob");
}

<input type="text" data-bind="value: Name" />
<input type="button" onclick="discardChanges()" value="Discard" />
<input type="button" onclick="saveChanges()" value="Save" />

If I modified the name and click Discard the original value (in this case Bob) should be restored whereas when I click Save the new value should be assigned (e.g. this.Name("Bill")).

Does anyone have an idea how to solve my problem?

Body:
Using the ko.extension beneath

var MyModel = function (data) {
    var self = this;

    self.Name= ko.observable('');

    self.Underscore = ko.Underscore(self);

    self.Cancel = function () {
        self.Underscore.Cancel();
    }

    self.Confirm = function () {
        self.Underscore.Confirm();
    }
};

HTML:

 <input type="button" data-bind="click: Cancel" value="Discard" />
 <input type="button" data-bind="click: Confirm" value="Keep" />

This knockout extension, it creates an underscore version of each observable ie self.Name() -> self._Name()

ko.Underscore = function (data) {
    var obj = data;
    var result = {};
    // Underscore Property Check
    var _isOwnProperty = function (isUnderscore, prop) {
        return (isUnderscore == null || prop.startsWith('_') == isUnderscore) && typeof obj[prop] == 'function' && obj.hasOwnProperty(prop) && ko.isObservable(obj[prop]) && !ko.isComputed(obj[prop])
    }
    // Creation of Underscore Properties
    result.init = function () {
        for (var prop in obj) {
            if (_isOwnProperty(null, prop)) {
                var val = obj[prop]();
                var temp = '_' + prop;
                if (obj[prop].isObservableArray)
                    obj[temp] = ko.observableArray(val);
                else
                    obj[temp] = ko.observable(val);
            }
        }
    };
    // Cancel
    result.Cancel = function () {
        for (var prop in obj) {
            if (_isOwnProperty(false, prop)) {
                var val = obj[prop]();
                var p = '_' + prop;
                obj[p](val);
            }
        }
    }
    // Confirm
    result.Confirm = function () {
        for (var prop in obj) {
            if (_isOwnProperty(true, prop)) {
                var val = obj[prop]();
                var p = prop.replace('_', '');
                obj[p](val);
            }
        }
    }
    // Observables
    result.Properties = function () {
        var obs = [];
        for (var prop in obj) {
            if (typeof obj[prop] == 'function' && obj.hasOwnProperty(prop) && ko.isObservable(obj[prop]) && !ko.isComputed(obj[prop])) {
                var val = obj[prop]();
                obs.push({ 'Name': prop, 'Value': val });
            }
        }
        return obs;
    }

    if (obj != null)
        result.init();

    return result;
}


答:
It is doing the job of implicit type casting from int to string.
For ex.

```<code>4 + 2
</code>```

returns 6

```<code>4 + 2 + "2"
</code>```

returns 62

```<code>"2" + 2 + 4
</code>```

returns 224

The integers following "" are implicitly converted to string and cancatenated.

Body:
It is doing the job of implicit type casting from int to string.
For ex.

4 + 2

returns 6

4 + 2 + "2"

returns 62

"2" + 2 + 4

returns 224

The integers following "" are implicitly converted to string and cancatenated.


问:
Customize QSplitter handle color
How to change the color of QSplitter handle

```<code>m_pSplitMainWin->setHandleWidth(10);
m_pSplitMainWin->setStyleSheet("QSplitter::handle:background-color: rgb(55, 100, 110);");
</code>```

This is not working, PLease give your valuable input

答:
Works for me:

```<code>QSplitter::handle
{
    background-color: rgb(255, 255, 255);
}
</code>```

More complex example:

```<code>QSplitter#editorViewSplitter::handle:horizontal
{
    border-left: 1px solid lightGray;
}

QSplitter#editorViewSplitter::handle:vertical
{
    border-bottom: 1px solid lightGray;
}
</code>```

Title: Customize QSplitter handle color

Body:
How to change the color of QSplitter handle

m_pSplitMainWin->setHandleWidth(10);
m_pSplitMainWin->setStyleSheet("QSplitter::handle:background-color: rgb(55, 100, 110);");

This is not working, PLease give your valuable input

Body:
Works for me:

QSplitter::handle
{
    background-color: rgb(255, 255, 255);
}

More complex example:

QSplitter#editorViewSplitter::handle:horizontal
{
    border-left: 1px solid lightGray;
}

QSplitter#editorViewSplitter::handle:vertical
{
    border-bottom: 1px solid lightGray;
}