问:
Togglemenu closed inside navbar angular 2
I am creating some sidebar menu using angular 2.

This is what i have for now

app.component.html

```<code><button (click)="toggleMenu()" class="hamburger">
  <span>toggle menu</span>
</button>

<h1>
  {{title}}
</h1>

<app-menu [@slideInOut]="menuState"></app-menu>
</code>```

app.component.ts

```<code>import {Component, trigger, state, style, transition, animate} from '@angular/animations';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  animations: [
    trigger('slideInOut', [
      state('in', style({
        transform: 'translate3d(0, 0, 0)'
      })),
      state('out', style({
        transform: 'translate3d(100%, 0, 0)'
      })),
      transition('in => out', animate('400ms ease-in-out')),
      transition('out => in', animate('400ms ease-in-out'))
    ]),
  ]
})
export class AppComponent {
  title = 'app works!';

  menuState:string = 'out';

  toggleMenu() {
    // 1-line if statement that toggles the value:
    this.menuState = this.menuState === 'out' ? 'in' : 'out';
  }
}
</code>```

menu.component.ts

```<code>import { Component, OnInit } from '@angular/core';

@Component({
    selector: 'app-menu',
    templateUrl: './menu.component.html',
    styleUrls: ['./menu.component.scss']
})
export class MenuComponent implements OnInit {

    constructor() { }

    ngOnInit() {
    }
}
</code>```

menu.component.html

```<code><button (click)="toggleMenu()" class="hamburger">
      <span>toggle menu</span>
    </button>
    <ul>
      <li>Menu Item</li>
      <li>Menu Item</li>
      <li>Menu Item</li>
      <li>Menu Item</li>
      <li>Menu Item</li>
      <li>Menu Item</li>
    </ul>
</code>```

This iway i am toggle right side menu, but only problem i have is that inside menu componenet html i also have toggle that does not work, entire is made from this link
https://blog.thecodecampus.de/angular-2-animate-creating-sliding-side-navigation

What i need is to close the menu inside menu component, any idea how to do that??

答:
You can emit an event from the app-menu component.
You need to create an EventEmitter in  MenuComponent:

```<code>import { Component, OnInit } from '@angular/core';

@Component({
    selector: 'app-menu',
    templateUrl: './menu.component.html',
    styleUrls: ['./menu.component.scss']
})
export class MenuComponent implements OnInit {
    @Output() onMenuToggle = new EventEmitter();

    constructor() { }

    ngOnInit() {
    }

    toggleMenu() {
      this.onMenuToggle.emit(null) //Emit an event here
    }
}
</code>```

Then you need to use the emitted event in your template:

```<code><app-menu [@slideInOut]="menuState" (onMenuToggle)="toggleMenu()"></app-menu>
</code>```

Body:
I am creating some sidebar menu using angular 2.

This is what i have for now

app.component.html

<button (click)="toggleMenu()" class="hamburger">
  toggle menu
</button>

  {{title}}

<app-menu [@slideInOut]="menuState"></app-menu>

app.component.ts

import {Component, trigger, state, style, transition, animate} from '@angular/animations';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  animations: [
    trigger('slideInOut', [
      state('in', style({
        transform: 'translate3d(0, 0, 0)'
      })),
      state('out', style({
        transform: 'translate3d(100%, 0, 0)'
      })),
      transition('in => out', animate('400ms ease-in-out')),
      transition('out => in', animate('400ms ease-in-out'))
    ]),
  ]
})
export class AppComponent {
  title = 'app works!';

  menuState:string = 'out';

  toggleMenu() {
    // 1-line if statement that toggles the value:
    this.menuState = this.menuState === 'out' ? 'in' : 'out';
  }
}

menu.component.ts

import { Component, OnInit } from '@angular/core';

@Component({
    selector: 'app-menu',
    templateUrl: './menu.component.html',
    styleUrls: ['./menu.component.scss']
})
export class MenuComponent implements OnInit {

    constructor() { }

    ngOnInit() {
    }
}

menu.component.html

<button (click)="toggleMenu()" class="hamburger">
      toggle menu
    </button>

Menu Item

Menu Item

Menu Item

Menu Item

Menu Item

Menu Item

This iway i am toggle right side menu, but only problem i have is that inside menu componenet html i also have toggle that does not work, entire is made from this link
https://blog.thecodecampus.de/angular-2-animate-creating-sliding-side-navigation

What i need is to close the menu inside menu component, any idea how to do that??

Body:
You can emit an event from the app-menu component.
You need to create an EventEmitter in  MenuComponent:

import { Component, OnInit } from '@angular/core';

@Component({
    selector: 'app-menu',
    templateUrl: './menu.component.html',
    styleUrls: ['./menu.component.scss']
})
export class MenuComponent implements OnInit {
    @Output() onMenuToggle = new EventEmitter();

    constructor() { }

    ngOnInit() {
    }

    toggleMenu() {
      this.onMenuToggle.emit(null) //Emit an event here
    }
}

Then you need to use the emitted event in your template:

<app-menu [@slideInOut]="menuState" (onMenuToggle)="toggleMenu()"></app-menu>


来源: stackexchange

问:
Tags Displaying in the wrong order in XML development in Ruby
Goal: Producing an xml file from an Excel sheet:

I am trying to display:

```<code>   <SchufaService version="2.0"
   xmlns="http://www.schufa.de/siml/2.0/final">
</code>```

I am currently getting:

```<code>   <SchufaService
   xmlns="http://www.schufa.de/siml/2.0/final" version="2.0">
</code>```

I am using this Ruby code:

```<code>   xml.SchufaService("version": "2.0","xmlns":
   "https://www.schufa.de/siml/2.0/final") do
</code>```

Can anyone please advise?

答:
What you have shown in your question is a single tag (called "element" in XML) with two attributes. In XML, the order of attributes in a tag is not significant, nor is whitespace. Thus, the two tags you have posted are semantically exactly the same.

This is defined in the XML specification, Section 3.1:

Note that the order of attribute specifications in a start-tag or empty-element tag is not significant.

Any XML parser reading the output produced by your code will see exactly the same result as your "target" output.

ContentLicense: CC BY-SA 3.0

Body:
Goal: Producing an xml file from an Excel sheet:

I am trying to display:

   <SchufaService version="2.0"
   xmlns="http://www.schufa.de/siml/2.0/final">

I am currently getting:

   <SchufaService
   xmlns="http://www.schufa.de/siml/2.0/final" version="2.0">

I am using this Ruby code:

   xml.SchufaService("version": "2.0","xmlns":
   "https://www.schufa.de/siml/2.0/final") do

Can anyone please advise?


问:
C++ sort vector using non-static member function
I have a class called Sorter. It has two public items.

int type variable choice

member function called compare with a int type return value that accepts two objects as parameter.

I tried creating an instance of Sorter while passing choice with a value to the constructor,

Then i wanted to use C++ sort function to sort a vector. and to pass the member function compare of the instance i created.

The compare member function uses the variable choice to decide the sorting mechanism.

But i was not able to get the pointer to the member function compare of an instance of Sorter.

Could someone advice me on this?

答:
Unfortunately, the standard library is a bit lacking in combinators for things like this. However, boost::lambda can do the job:</p>

```<code>#include <boost/lambda/bind.hpp>

namespace l = boost::lambda;

struct foo {
    bool bar(char, char);
};

void test(foo *pFoo) {
    char a[2] = {0};

    std::sort(a, a+1,
            l::bind(&foo::bar, pFoo, l::_1, l::_2));
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Unfortunately, the standard library is a bit lacking in combinators for things like this. However, boost::lambda can do the job:

#include <boost/lambda/bind.hpp>

namespace l = boost::lambda;

struct foo {
    bool bar(char, char);
};

void test(foo *pFoo) {
    char a[2] = {0};

    std::sort(a, a+1,
            l::bind(&foo::bar, pFoo, l::_1, l::_2));
}


问:
trying to use ngClass instead ngIf
I would rewrite this NgIf over ngClass for a shorter code. Unfortunately, the class is not accepted. Can the problem be solved?</p>

```<code>The long Version:

 <div *ngIf="sp.outboundWeeks[i].status=='GREEN'">
                                        <div class="green">
                                            {{sp.outboundWeeks[i].utilizationRate}}
                                        </div>
                                    </div>
                                    <div *ngIf="sp.outboundWeeks[i].status=='RED'">
                                        <div class="red">
                                            {{sp.outboundWeeks[i].utilizationRate}}
                                        </div>
                                    </div>
                                    <div *ngIf="sp.outboundWeeks[i].status=='YELLOW'">
                                        <div class="yellow">
                                            {{sp.outboundWeeks[i].utilizationRate}}
                                        </div>
                                    </div>

the short version should be like the code below:

[ngClass]="{'green':cw.status[i]=='GREEN','yellow':cw.status=='YELLOW','red':cw.status=='RED'}">{{cw.utilizationRate}}
     </div>
</code>```

答:
I assume your objects are like:

```<code>    sp = {
    outboundWeeks: [{
      status: 'GREEN',
      utilizationRate: 'das',
    }],
  };
  cw = {
    status: ['GREEN'],
    utilizationRate: 'sad',
  };
</code>```

therefore the template should be similar to

```<code><div *ngIf="sp.outboundWeeks[0].status =='GREEN'">
      <div class="green">
        {{ sp.outboundWeeks[0].utilizationRate }}
      </div>
    </div>
    <div *ngIf="sp.outboundWeeks[0].status=='RED'">
      <div class="red">
        {{ sp.outboundWeeks[0].utilizationRate }}
      </div>
    </div>
    <div *ngIf="sp.outboundWeeks[0].status=='YELLOW'">
      <div class="yellow">
        {{ sp.outboundWeeks[0].utilizationRate }}
      </div>
    </div>

    //SHORT HAND
    <div [ngClass]="{'green': cw.status[0] === 'GREEN', 'yellow': cw.status[0] === 'YELLOW','red': cw.status[0] === 'RED'}">
      {{ cw.utilizationRate }}
    </div>
</code>```

I guess your iteration is not correct coz the short version is a bit different from the longer version that you have introduced, however, I have added a sample object to show you how it should work.

A better solution might be to just create a @Pipe which returns your proper class. it should be much cleaner and faster.

something like

```<code> <div [ngClass]="status | yourPipe">
      {{ cw.utilizationRate }}
 </div>
</code>```

Title: trying to use ngClass instead ngIf

Body:
I would rewrite this NgIf over ngClass for a shorter code. Unfortunately, the class is not accepted. Can the problem be solved?

The long Version:

                                            {{sp.outboundWeeks[i].utilizationRate}}

                                            {{sp.outboundWeeks[i].utilizationRate}}

                                            {{sp.outboundWeeks[i].utilizationRate}}

the short version should be like the code below:

[ngClass]="{'green':cw.status[i]=='GREEN','yellow':cw.status=='YELLOW','red':cw.status=='RED'}">{{cw.utilizationRate}}

Body:
I assume your objects are like:

    sp = {
    outboundWeeks: [{
      status: 'GREEN',
      utilizationRate: 'das',
    }],
  };
  cw = {
    status: ['GREEN'],
    utilizationRate: 'sad',
  };

therefore the template should be similar to

<div *ngIf="sp.outboundWeeks[0].status =='GREEN'">
      <div class="green">
        {{ sp.outboundWeeks[0].utilizationRate }}
      </div>
    </div>
    <div *ngIf="sp.outboundWeeks[0].status=='RED'">
      <div class="red">
        {{ sp.outboundWeeks[0].utilizationRate }}
      </div>
    </div>
    <div *ngIf="sp.outboundWeeks[0].status=='YELLOW'">
      <div class="yellow">
        {{ sp.outboundWeeks[0].utilizationRate }}
      </div>
    </div>

    //SHORT HAND
    <div [ngClass]="{'green': cw.status[0] === 'GREEN', 'yellow': cw.status[0] === 'YELLOW','red': cw.status[0] === 'RED'}">
      {{ cw.utilizationRate }}
    </div>

I guess your iteration is not correct coz the short version is a bit different from the longer version that you have introduced, however, I have added a sample object to show you how it should work.

A better solution might be to just create a @Pipe which returns your proper class. it should be much cleaner and faster.

something like

 <div [ngClass]="status | yourPipe">
      {{ cw.utilizationRate }}
 </div>


问:
Python/SQL - WHERE clause not applying to all Rows
I am having a problem with the following code in a Python program I built. The program pulls data from a database and puts it into an Excel spreadsheet based on a list of reference numbers 'GrantRefNumber' that they input.

It works, but for some reason only the FIRST reference number has the 'a.reporting_period_id like 'none-' applied to it, the rest do not.

I am using a variable substitution in the SQL code to put the list of reference numbers into the string.

Any help would be much appreciated!

SQL:

```<code>"SELECT a.fa_reference as [GrantRefNumber],
a.fa_name as [Award Title],
a.location as [RO],
ISNULL(cat.grant_department_name, '') as [Department],
a.funding_start_date as [Start Date],
a.funding_end_date as [End Date],
a.[pi]    as [PI ID],
a.pi_initials  as [PI Name],
a.pi_surname as [PI Surname],
r1_2 as [Type],

DATEADD(s, cast(last_submitted_date as int), '1970-01-01 00:00:00') as [Submitted Date]

from keywordagreements a inner join entries_publications p on a.id =
p.agreement_id left outer join mrc_categories cat  on a.origid = cat.id and cat.centre not in ('2')

where a.[pi] NOT LIKE 'S%' and response_code not like 'Test' and Closed is null
and a.reporting_period_id like 'none-'
and a.funding_organisation not like '%UKSA%' and {}'

Order by [RO], [PI ID], [GrantRefNumber]".format(finalList)
</code>```

finalList (variable substitution):

The finalList is a list of Reference Numbers that I get from the user in Python called 'items'

```<code>items = dfCall['GrantRefNumber'].values.tolist()
refList = " OR ".join(["a.fa_reference LIKE '%s'" % num for num in items])
finalList = refList[:-1]
</code>```

I am using PYODBC to extract the data.

The SQL in my code looks like this (I removed the quote marks (and some of the columns) in the previous code to make it easier to read):

```<code>stringQ = "SELECT a.fa_reference as [GrantRefNumber], a.fa_name as [Award Title]," \
          " a.location  as [RO], ISNULL(cat.grant_department_name, '') as [Department]," \
          " a.funding_start_date as [Start Date], a.funding_end_date        as [End Date]," \
          " a.[pi]  as [PI ID], a.pi_initials   as [PI Name]," \
          " a.pi_surname as [PI Surname], " \
          " r1_2 as [Type], ISNULL(r1_2_1, '')  as [PubMed ID]," \
          " r1_2_2  as [Author], r1_2_3 as [Publication], ISNULL(r1_2_4, '') as [Journal]," \
          " ISNULL(r1_2_8, '') as [Month], ISNULL(r1_2_9, '') as [Year], ISNULL(r1_2_4_1, '') as [Conference]," \
          " ISNULL(r1_2_36, '') as [PubMed Central ID], ISNULL (r1_2_19, '') as [DOI]," \
          " case when nullif(r1_2_1,'') is not null then 'http://europepmc.org/abstract/MED/' + r1_2_1 else case when" \
          " nullif(r1_4,'') is not null then r1_4 else case when nullif(r1_2_19,'') is not null then" \
          " 'http://dx.doi.org/' + r1_2_19 else isnull(r1_2_1,'') end  end end as [URL], ISNULL(r1_2_21, '') " \
          "as [ISBN]," \
          " ISNULL(r1_2_30, '') as [ISBN (Electronic)], " \
          " ISNULL(r1_2_25, '') as [Chapter Number], " \
          "ISNULL(r1_2_26, '')" \
          " as [Chapter Title], ISNULL(r1_2_27, '') as [Chapter Author]," \
          " ISNULL(r1_2_29, '') as [ISSN (Print)], ISNULL(r1_2_32, '')  as [ISSN (Digital)], " \
          "ISNULL(r1_2_31, '')  as [Web of Science ID], ISNULL(r1_2_34, '') as [Scopus ID], " \
          "ISNULL(r1_2_35, '')  as [arXiv DepositID]," \
          " ISNULL(r1_2_38, '') as [Bibcode], ISNULL(r1_2_39, '') as [Ethos], ISNULL(r1_2_43, '')   as [NASA-ADS ID]," \
          " ISNULL(r1_2_46, '') as [Inspire], ISNULL(r1_2_40, '') as [PMC Manuscript ID], ISNULL(r1_2_45, '')" \
          " as [ORCID Work Putcode]," \
          " ISNULL(r1_2_61, '') as [OpenAire Access License], ISNULL(r1_2_52, '') " \
          "as [In EPMC?], ISNULL(r1_2_53, '') as [In PMC?]," \
          " ISNULL(r1_2_51, '') as [EPMC Open Access], " \
          " DATEADD(s, cast(last_submitted_date as int), '1970-01-01 00:00:00') as [Submitted Date] " \
          "from keywordagreements a inner join entries_publications p on a.id = " \
          "p.agreement_id left outer join mrc_categories cat " \
          "on a.origid = cat.id and cat.centre not in ('2') where a.[pi] NOT LIKE 'S%' and " \
          "response_code not like 'Test' and Closed is null " \
          "and a.reporting_period_id like 'none-' " \
          "and a.funding_organisation not like '%UKSA%' and {}' " \
          "Order by [RO], [PI ID], [GrantRefNumber]".format(finalList)
</code>```

答: Ok, I think I have fixed it. I put the {}' in brackets i.e. ({}') as it was treating the other reference numbers as a separate statement because of the OR command.

Body:
I am having a problem with the following code in a Python program I built. The program pulls data from a database and puts it into an Excel spreadsheet based on a list of reference numbers 'GrantRefNumber' that they input.

It works, but for some reason only the FIRST reference number has the 'a.reporting_period_id like 'none-' applied to it, the rest do not.

I am using a variable substitution in the SQL code to put the list of reference numbers into the string.

Any help would be much appreciated!

SQL:

"SELECT a.fa_reference as [GrantRefNumber],
a.fa_name as [Award Title],
a.location as [RO],
ISNULL(cat.grant_department_name, '') as [Department],
a.funding_start_date as [Start Date],
a.funding_end_date as [End Date],
a.[pi]    as [PI ID],
a.pi_initials  as [PI Name],
a.pi_surname as [PI Surname],
r1_2 as [Type],

DATEADD(s, cast(last_submitted_date as int), '1970-01-01 00:00:00') as [Submitted Date]

from keywordagreements a inner join entries_publications p on a.id =
p.agreement_id left outer join mrc_categories cat  on a.origid = cat.id and cat.centre not in ('2')

where a.[pi] NOT LIKE 'S%' and response_code not like 'Test' and Closed is null
and a.reporting_period_id like 'none-'
and a.funding_organisation not like '%UKSA%' and {}'

Order by [RO], [PI ID], [GrantRefNumber]".format(finalList)

finalList (variable substitution):

The finalList is a list of Reference Numbers that I get from the user in Python called 'items'

items = dfCall['GrantRefNumber'].values.tolist()
refList = " OR ".join(["a.fa_reference LIKE '%s'" % num for num in items])
finalList = refList[:-1]

I am using PYODBC to extract the data.

The SQL in my code looks like this (I removed the quote marks (and some of the columns) in the previous code to make it easier to read):

stringQ = "SELECT a.fa_reference as [GrantRefNumber], a.fa_name as [Award Title]," \
          " a.location  as [RO], ISNULL(cat.grant_department_name, '') as [Department]," \
          " a.funding_start_date as [Start Date], a.funding_end_date        as [End Date]," \
          " a.[pi]  as [PI ID], a.pi_initials   as [PI Name]," \
          " a.pi_surname as [PI Surname], " \
          " r1_2 as [Type], ISNULL(r1_2_1, '')  as [PubMed ID]," \
          " r1_2_2  as [Author], r1_2_3 as [Publication], ISNULL(r1_2_4, '') as [Journal]," \
          " ISNULL(r1_2_8, '') as [Month], ISNULL(r1_2_9, '') as [Year], ISNULL(r1_2_4_1, '') as [Conference]," \
          " ISNULL(r1_2_36, '') as [PubMed Central ID], ISNULL (r1_2_19, '') as [DOI]," \
          " case when nullif(r1_2_1,'') is not null then 'http://europepmc.org/abstract/MED/' + r1_2_1 else case when" \
          " nullif(r1_4,'') is not null then r1_4 else case when nullif(r1_2_19,'') is not null then" \
          " 'http://dx.doi.org/' + r1_2_19 else isnull(r1_2_1,'') end  end end as [URL], ISNULL(r1_2_21, '') " \
          "as [ISBN]," \
          " ISNULL(r1_2_30, '') as [ISBN (Electronic)], " \
          " ISNULL(r1_2_25, '') as [Chapter Number], " \
          "ISNULL(r1_2_26, '')" \
          " as [Chapter Title], ISNULL(r1_2_27, '') as [Chapter Author]," \
          " ISNULL(r1_2_29, '') as [ISSN (Print)], ISNULL(r1_2_32, '')  as [ISSN (Digital)], " \
          "ISNULL(r1_2_31, '')  as [Web of Science ID], ISNULL(r1_2_34, '') as [Scopus ID], " \
          "ISNULL(r1_2_35, '')  as [arXiv DepositID]," \
          " ISNULL(r1_2_38, '') as [Bibcode], ISNULL(r1_2_39, '') as [Ethos], ISNULL(r1_2_43, '')   as [NASA-ADS ID]," \
          " ISNULL(r1_2_46, '') as [Inspire], ISNULL(r1_2_40, '') as [PMC Manuscript ID], ISNULL(r1_2_45, '')" \
          " as [ORCID Work Putcode]," \
          " ISNULL(r1_2_61, '') as [OpenAire Access License], ISNULL(r1_2_52, '') " \
          "as [In EPMC?], ISNULL(r1_2_53, '') as [In PMC?]," \
          " ISNULL(r1_2_51, '') as [EPMC Open Access], " \
          " DATEADD(s, cast(last_submitted_date as int), '1970-01-01 00:00:00') as [Submitted Date] " \
          "from keywordagreements a inner join entries_publications p on a.id = " \
          "p.agreement_id left outer join mrc_categories cat " \
          "on a.origid = cat.id and cat.centre not in ('2') where a.[pi] NOT LIKE 'S%' and " \
          "response_code not like 'Test' and Closed is null " \
          "and a.reporting_period_id like 'none-' " \
          "and a.funding_organisation not like '%UKSA%' and {}' " \
          "Order by [RO], [PI ID], [GrantRefNumber]".format(finalList)


问:
How do I "apply" to results of a parameter-less function
This works:

```<code>List(3, 1, 2).sorted apply 1
res1: Int = 2
</code>```

And this works:

```<code>var x = List(3, 1, 2).sorted
x: List[Int] = List(1, 2, 3)
x(1)
res2: Int = 2
</code>```

but this doesn't:

```<code>List(3, 1, 2).sorted (1)

error: type mismatch;
 found   : Int(1)
 required: Ordering[?]
       List(3, 1, 2).sorted (1)
                             ^
</code>```

And even parentheses don't clue the parser in to what I want:

```<code>(List(3, 1, 2).sorted)(1)

error: type mismatch;
 found   : Int(1)
 required: Ordering[?]
       (List(3, 1, 2).sorted)(1)
</code>```

It seems like a natural expression.  What am I doing wrong?

答:
The required parameter can be provided this way:

```<code>List(3, 1, 2).sorted(implicitly[Ordering[Int]])(1)
</code>```

Though using apply() looks shorter and less scary.

Body:
This works:

List(3, 1, 2).sorted apply 1
res1: Int = 2

And this works:

var x = List(3, 1, 2).sorted
x: List[Int] = List(1, 2, 3)
x(1)
res2: Int = 2

but this doesn't:

List(3, 1, 2).sorted (1)

error: type mismatch;
 found   : Int(1)
 required: Ordering[?]
       List(3, 1, 2).sorted (1)
                             ^

And even parentheses don't clue the parser in to what I want:

(List(3, 1, 2).sorted)(1)

error: type mismatch;
 found   : Int(1)
 required: Ordering[?]
       (List(3, 1, 2).sorted)(1)

It seems like a natural expression.  What am I doing wrong?

Body:
The required parameter can be provided this way:

List(3, 1, 2).sorted(implicitly[Ordering[Int]])(1)

Though using apply() looks shorter and less scary.


问:
iOS URLSession Error "JSON text did not start with array or object and option to allow fragments not set."
I'm currently on a project where I have to submit some data to PHP file and get the return from PHP.

Problem

When I try to do that using iOS URLSession, I'm getting an error,

```<code>The data couldn’t be read because it isn’t in the correct format.
Error Domain=NSCocoaErrorDomain Code=3840 "JSON text did not start with array or object and option to allow fragments not set."
UserInfo={NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}
</code>```

Because of this error, I made a sample php file where I return the value which I sent from Swift. And still getting this error along with some additional information.

```<code><NSHTTPURLResponse: 0x60400042e200> { URL: http://192.168.1.99/insertDataTest.php } { status code: 200, headers {
Connection = "Keep-Alive";
"Content-Length" = 5;
"Content-Type" = "application/json";
Date = "Thu, 07 Dec 2017 09:55:58 GMT";
"Keep-Alive" = "timeout=5, max=100";
Server = "Apache/2.4.10 (Raspbian)";
</code>```

} }

What I've done so far

Here I know the content coming from the PHP, cannot be read by Swift.
I'm sending a 5 digit string from Swift to PHP and since I'm returning it without doing anything, I'm getting length of 5 data. Also I manually added a code to php in orders to made header as application/json. But still getting this error. I'm sending json encoded data from PHP as well.

My Code

Swift:

```<code>let postParameters = "{\"usermobilenum\":12345}"
request.httpBody = postParameters.data(using: String.Encoding.utf8)
let task = URLSession.shared.dataTask(with: request as URLRequest)
{
    data, response, error in
    if error != nil
    {
      print("error is \(String(describing: error))")
      return;
    }

    do
    {
      print(response!)
      let myJSON = try  JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
      if let parseJSON = myJSON
      {
          var msg : String!
          msg = parseJSON["message"] as! String?
          print(msg)

      }
    }
    catch
    {
      print(error.localizedDescription)
      print(error)
    }

}
task.resume()
</code>```

PHP :

```<code><?php
header("Content-Type: application/json");
if($_SERVER["REQUEST_METHOD"]=="POST")
{
    $data =json_decode(file_get_contents('php://input'),true);
    $userPhone = $data["usermobilenum"];
    echo json_encode($userPhone);
    mysqli_close($connect);
}
else
{
    echo json_encode("Failed in POST Method");
}

?>
</code>```

I have no idea what this causes. I did try to find a solution for this in the internet and had no luck. Please help here. I'm using the latest Swift version.

答:
Luckily I found the solution for my own problem. I missed to understand the error. As it says "option to allow fragments not set.", What I did was adding option .allowFragments. So the whole line after this replacement,

```<code>let myJSON = try  JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary
</code>```

And I could solve the problem and get the answer PHP returns.

Body:
I'm currently on a project where I have to submit some data to PHP file and get the return from PHP.

Problem

When I try to do that using iOS URLSession, I'm getting an error,

The data couldn’t be read because it isn’t in the correct format.
Error Domain=NSCocoaErrorDomain Code=3840 "JSON text did not start with array or object and option to allow fragments not set."
UserInfo={NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}

Because of this error, I made a sample php file where I return the value which I sent from Swift. And still getting this error along with some additional information.

<NSHTTPURLResponse: 0x60400042e200> { URL: http://192.168.1.99/insertDataTest.php } { status code: 200, headers {
Connection = "Keep-Alive";
"Content-Length" = 5;
"Content-Type" = "application/json";
Date = "Thu, 07 Dec 2017 09:55:58 GMT";
"Keep-Alive" = "timeout=5, max=100";
Server = "Apache/2.4.10 (Raspbian)";

} }

What I've done so far

Here I know the content coming from the PHP, cannot be read by Swift.
I'm sending a 5 digit string from Swift to PHP and since I'm returning it without doing anything, I'm getting length of 5 data. Also I manually added a code to php in orders to made header as application/json. But still getting this error. I'm sending json encoded data from PHP as well.

My Code

Swift:

let postParameters = "{\"usermobilenum\":12345}"
request.httpBody = postParameters.data(using: String.Encoding.utf8)
let task = URLSession.shared.dataTask(with: request as URLRequest)
{
    data, response, error in
    if error != nil
    {
      print("error is \(String(describing: error))")
      return;
    }

    do
    {
      print(response!)
      let myJSON = try  JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
      if let parseJSON = myJSON
      {
          var msg : String!
          msg = parseJSON["message"] as! String?
          print(msg)

      }
    }
    catch
    {
      print(error.localizedDescription)
      print(error)
    }

}
task.resume()

PHP :

<?php
header("Content-Type: application/json");
if($_SERVER["REQUEST_METHOD"]=="POST")
{
    $data =json_decode(file_get_contents('php://input'),true);
    $userPhone = $data["usermobilenum"];
    echo json_encode($userPhone);
    mysqli_close($connect);
}
else
{
    echo json_encode("Failed in POST Method");
}

?>

I have no idea what this causes. I did try to find a solution for this in the internet and had no luck. Please help here. I'm using the latest Swift version.

Body:
Luckily I found the solution for my own problem. I missed to understand the error. As it says "option to allow fragments not set.", What I did was adding option .allowFragments. So the whole line after this replacement,

let myJSON = try  JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary

And I could solve the problem and get the answer PHP returns.


问:
Fast insert into table with Foreign Key constraints
I have to periodically insert data into table #1 that contains foreign key reference to table #2. And table #2 is quite big - about 200.000 rows. I'm trying to check rows that must be inserted into table #1 for foreign key constraint by simply removing those rows that definitely can't be inserted, and my query looks like this:

```<code>DELETE FROM temp_table1
WHERE temp_table1.fk NOT IN (SELECT id FROM table2) AND
temp_table1.id_d IS NOT NULL;
</code>```

The problem is, this method is veeery slow :( So is there any "right" method to insert rows in such situation?

I'm using Python3, Postgresql and Psycopg2, if it matters.

答:
You do not need the delete step. insert directly in instead:

```<code>insert into table1
select t1.*
from
    temp_table1 t1
    inner join
    table2 t2 on t1.fk = t2.id
where t1.id_d is not null
</code>```

Body:
I have to periodically insert data into table #1 that contains foreign key reference to table #2. And table #2 is quite big - about 200.000 rows. I'm trying to check rows that must be inserted into table #1 for foreign key constraint by simply removing those rows that definitely can't be inserted, and my query looks like this:

DELETE FROM temp_table1
WHERE temp_table1.fk NOT IN (SELECT id FROM table2) AND
temp_table1.id_d IS NOT NULL;

The problem is, this method is veeery slow :( So is there any "right" method to insert rows in such situation?

I'm using Python3, Postgresql and Psycopg2, if it matters.

Body:
You do not need the delete step. insert directly in instead:

insert into table1
select t1.*
from
    temp_table1 t1
    inner join
    table2 t2 on t1.fk = t2.id
where t1.id_d is not null


问:
How to know if an event is still bubbling?
I have an SVG element with some nested elements. I have attached a mouseout handler to the SVG element. When I press the mouse in the middle of the SVG element and move it out of the SVG element, I get the following list of events:

```<code>down
out <path ...>
out <circle r="39.5">
out <circle r="40">
out <circle r="49.5">
out <svg ...>
up
</code>```

This means the mouse has first left the path, than it has left the three concentric circles and finally it leaves the SVG element. I am just interested in the last event, which affects the element, who has the handler attached. The SVG element gets all the other events, because they bubble to the SVG element.

How can I know, if an event has been bubbled? How can I ignore those events, which do not affect the element, which has the handler attached?

答:
It seems to be necessary to check, if target is the same as currentTarget. The answer to another question claims, that this can be done with ===. So I use now the following condition in my mouseout handler, to skip the situations, when the event is still bubbling:

```<code>svg.onmouseout = function (event) {
  if (event.target === event.currentTarget) {
    // Do what needs to be done after the mouse leaves the SVG element.
  }
};
</code>```

Body:
I have an SVG element with some nested elements. I have attached a mouseout handler to the SVG element. When I press the mouse in the middle of the SVG element and move it out of the SVG element, I get the following list of events:

down
out <path ...>
out <circle r="39.5">
out <circle r="40">
out <circle r="49.5">
out <svg ...>
up

This means the mouse has first left the path, than it has left the three concentric circles and finally it leaves the SVG element. I am just interested in the last event, which affects the element, who has the handler attached. The SVG element gets all the other events, because they bubble to the SVG element.

How can I know, if an event has been bubbled? How can I ignore those events, which do not affect the element, which has the handler attached?

Body:
It seems to be necessary to check, if target is the same as currentTarget. The answer to another question claims, that this can be done with ===. So I use now the following condition in my mouseout handler, to skip the situations, when the event is still bubbling:

svg.onmouseout = function (event) {
  if (event.target === event.currentTarget) {
    // Do what needs to be done after the mouse leaves the SVG element.
  }
};


问:
Visual studio 2015 post build commnad failing with exit code 1. strange thing is it fails only on some projects
I am trying following post build event in some of my projects

```<code>copy /Y "$(TargetDir)*.dll" "$(SolutionDir)MyMainApp\bin\*.dll"
</code>```

But getting error

Error       The command "copy /Y "D:\myslolution\myimplementation\bin\Release*.dll" "D:\myslolution\MyMainApp\bin*.dll"" exited with code 1.

Any idea what's wrong in it?
strange thing is on multiple rebuild it sometimes work

答:
I think the syntax for the copy command should be:
copy /Y D:\myslolution\myimplementation\bin\Release\ *.dll D:\myslolution\MyMainApp\bin\

(\ *.dll after the source parameter, otherwise files that start with Release, and end with .dll are targeted)

you could try the command first in a cmd window to verify the syntax, before adding it to the post build.

After verifying the copy command syntax you can change it to:

copy /Y "$(TargetDir)\*.dll" "$(SolutionDir)\MyMainApp\bin\"

Body:
I am trying following post build event in some of my projects

copy /Y "$(TargetDir)*.dll" "$(SolutionDir)MyMainApp\bin\*.dll"

But getting error

Error       The command "copy /Y "D:\myslolution\myimplementation\bin\Release*.dll" "D:\myslolution\MyMainApp\bin*.dll"" exited with code 1.

Any idea what's wrong in it?
strange thing is on multiple rebuild it sometimes work


问:
I'd like to produce a function like split (arr, i, j) which divides array arr by axis i, j
I'd like to produce a function like split(arr, i, j), which divides array arr by axis i, j?

But I do not know how to do it. In the following method using array_split. It is impossible for me to obtain the two-dimensional array that we are seeking by merely dividing N-dimensional arrays into N-1 dimensional arrays.

```<code>import numpy as np

arr = np.arange(36).reshape(4,9)
dim = arr.ndim
ax = np.arange(dim)
arritr = [np.array_split(arr, arr.shape[ax[i]], ax[i]) for i in range(dim)]
print(arritr[0])
print(arritr[1])
</code>```

How can I achieve this?

Body:
I'd like to produce a function like split(arr, i, j), which divides array arr by axis i, j?

But I do not know how to do it. In the following method using array_split. It is impossible for me to obtain the two-dimensional array that we are seeking by merely dividing N-dimensional arrays into N-1 dimensional arrays.

import numpy as np

arr = np.arange(36).reshape(4,9)
dim = arr.ndim
ax = np.arange(dim)
arritr = [np.array_split(arr, arr.shape[ax[i]], ax[i]) for i in range(dim)]
print(arritr[0])
print(arritr[1])

How can I achieve this?

Body:
Are you looking for something like matlab's mat2cell? Then you could do:

import numpy as np

def ndsplit(a, splits):
    assert len(splits) <= a.ndim
    splits = [np.r_[0, s, m] for s, m in zip(splits, a.shape)]
    return np.frompyfunc(lambda *x: a[tuple(slice(s[i],s[i+1]) for s, i in zip(splits, x))], len(splits), 1)(*np.indices(tuple(len(s) - 1 for s in splits)))

# demo
a = np.arange(56).reshape(7, 8)
print(ndsplit(a, [(2, 4), (1, 5, 6)]))

# [[array([[0],
#        [8]])
#   array([[ 1,  2,  3,  4],
#        [ 9, 10, 11, 12]])
#   array([[ 5],
#        [13]]) array([[ 6,  7],
#        [14, 15]])]
#  [array([[16],
#        [24]])
#   array([[17, 18, 19, 20],
#        [25, 26, 27, 28]])
#   array([[21],
#        [29]]) array([[22, 23],
#        [30, 31]])]
#  [array([[32],
#        [40],
#        [48]])
#   array([[33, 34, 35, 36],
#        [41, 42, 43, 44],
#        [49, 50, 51, 52]])
#   array([[37],
#        [45],
#        [53]])
#   array([[38, 39],
#        [46, 47],
#        [54, 55]])]]


问:
How to display the currency symbol to the right in Angular
I have to display Euro currency like this : 583 €.

But with this code:

```<code>{{ price | currency:'EUR':true }}
</code>```

I get €583, is there any option in Angular core to move the symbol to right? A lot of european countries use the symbol at the right (France, Germany, Spain, Italy).

答:
Do it like this:

```<code>{{price | currency:'EUR':true:'1.0-0'}}
</code>```

No need for extra pipes, it uses the default currency pipe

Body:
I have to display Euro currency like this : 583 €.

But with this code:

{{ price | currency:'EUR':true }}

I get €583, is there any option in Angular core to move the symbol to right? A lot of european countries use the symbol at the right (France, Germany, Spain, Italy).

Body:
Do it like this:

{{price | currency:'EUR':true:'1.0-0'}}

No need for extra pipes, it uses the default currency pipe


问:
Select Particular Date using Python Selenium (Rollover dates)
All,

We are trying to automate the date picking process  for reference Click here! . Please refer date of birth  and Appointment date fields. The way we select date is is different. I am not able to get any idea about selecting the dates for both the fields. Could you please help me?

I have tried my best and it's working with below code except date fields

Python version : 2.7
Selenium 3.8.0
Chrome : 48X

```<code>    import selenium
    import sys
    from selenium import webdriver
    from selenium.webdriver.common.action_chains import ActionChains
    from selenium.webdriver.chrome.options import Options
    #profile = webdriver.FirefoxProfile()
    #profile.accept_untrusted_certs = True
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.support import expected_conditions as EC

    chrome_options = Options()
    chrome_options.add_argument("--disable-extensions")
    driver = webdriver.Chrome(chrome_options=chrome_options)

    driver.get('https://reentryvisa.inis.gov.ie/website/INISOA/IOA.nsf/AppointmentSelection?OpenForm');

    wait = WebDriverWait(driver, 10)
    driver.find_element_by_id('btCom').click()

    username = driver.find_element_by_id('GivenName')
    username.send_keys("First name here ")

    username = driver.find_element_by_id('Surname')
    username.send_keys("Surname here")

    username = driver.find_element_by_id('DOB')
    username.click()
 ActionChains(driver).move_to_element(username).click().send_keys('01/01/2011').perform()

    username = driver.find_element_by_id('Appdate')
    username.send_keys("12345")
</code>```

I tried seeing the html for id names etc but I dint find anything specific to year date or month. All I got was below code

```<code>    <script src="/website/INISOA/IOA.nsf/bootstrap-datepicker.js"></script>
    <link href="/website/INISOA/IOA.nsf/datepicker3.css" rel="stylesheet">

    <div class="form-group">
    <label class="control-label col-sm-3 col-md-3 col-lg-2" for="DOB">* Date    of Birth:</label>
    <div class="col-sm-3 col-md-3 col-lg-3">
    <div class="input-group date dobdate">

    <input name="DOB" value="" id="DOB" class="form-control readonlywhite"  placeholder="Date of birth" readonly>
    <span class="input-group-addon"><i class="glyphicon glyphicon-calendar"></i></span>
    </div>
    </div>
    </div>
</code>```

Please help me show away to select  the dates in both the fields (Date of birth and Appointment date)

答:
For the date of birth:

```<code>dob = driver.find_element_by_id('DOB')
driver.execute_script("arguments[0].value = arguments[1]", dob, '01/01/2011')
</code>```

For appointment date:

```<code>appdate = driver.find_element_by_id('Appdate')
driver.execute_script("arguments[0].value = arguments[1]", appdate, '12/12/2017')
</code>```

Body:
All,

We are trying to automate the date picking process  for reference Click here! . Please refer date of birth  and Appointment date fields. The way we select date is is different. I am not able to get any idea about selecting the dates for both the fields. Could you please help me?

I have tried my best and it's working with below code except date fields

Python version : 2.7
Selenium 3.8.0
Chrome : 48X

    import selenium
    import sys
    from selenium import webdriver
    from selenium.webdriver.common.action_chains import ActionChains
    from selenium.webdriver.chrome.options import Options
    #profile = webdriver.FirefoxProfile()
    #profile.accept_untrusted_certs = True
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.support import expected_conditions as EC

    chrome_options = Options()
    chrome_options.add_argument("--disable-extensions")
    driver = webdriver.Chrome(chrome_options=chrome_options)

    driver.get('https://reentryvisa.inis.gov.ie/website/INISOA/IOA.nsf/AppointmentSelection?OpenForm');

    wait = WebDriverWait(driver, 10)
    driver.find_element_by_id('btCom').click()

    username = driver.find_element_by_id('GivenName')
    username.send_keys("First name here ")

    username = driver.find_element_by_id('Surname')
    username.send_keys("Surname here")

    username = driver.find_element_by_id('DOB')
    username.click()
 ActionChains(driver).move_to_element(username).click().send_keys('01/01/2011').perform()

    username = driver.find_element_by_id('Appdate')
    username.send_keys("12345")

I tried seeing the html for id names etc but I dint find anything specific to year date or month. All I got was below code

    <link href="/website/INISOA/IOA.nsf/datepicker3.css" rel="stylesheet">

    * Date    of Birth:

    <input name="DOB" value="" id="DOB" class="form-control readonlywhite"  placeholder="Date of birth" readonly>

Please help me show away to select  the dates in both the fields (Date of birth and Appointment date)

Body:
For the date of birth:

dob = driver.find_element_by_id('DOB')
driver.execute_script("arguments[0].value = arguments[1]", dob, '01/01/2011')

For appointment date:

appdate = driver.find_element_by_id('Appdate')
driver.execute_script("arguments[0].value = arguments[1]", appdate, '12/12/2017')


问:
React Js custom accordion, open one item at the time
I have an accordion in React formed of a row component which is looped inside a body parent component. In the row I'm toggling the state showDetails to show/hide the details for each row, effectively opening the accordion item. But, since the state is for each row, how do I close one accordion item when I open another one?

Body:

```<code>export default class Body extends React.Component {
  render() {
    const {modelProps, showInfo, linkedRow} = this.props;
    return (
      <div className="c-table__body">
        {this.props.model.map(
          (subModel, i) =>
            linkedRow ?
              <LinkedRow
                key={`${i}`}
                model={subModel}
                modelProps={modelProps}
              />
              :
              <Row
                key={`${i}_${subModel.username}`}
                model={subModel}
                modelProps={modelProps}
                showInfo={showInfo}
                handleStatusChanged={this.props.handleStatusChanged}
              />
        )}
      </div>
    );
  }
}
</code>```

Row:

```<code>class Row extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      userId: '',
      showDetails: false,
      showModal: false,
      status: '',
      value: '',
      showInfo: false
    };
      render() {
        const { model, modelProps, showInfo } = this.props;
        return (
          <div className="c-table__row">
            <div className="c-table__row-wrapper">
              {modelProps.map((p, i) => (
                <div className={`c-table__item ${this.isStatusCell(model[p]) ? model[p] : p}`} key={i}>{this.isStatusCell(model[p]) ? this.toTitleCase(model[p]) : model[p]}</div>
              ))}

              {showInfo ? (
                <div className="c-table__item c-table__item-sm">
                  <a
                    name="view-user"
                    onClick={this.showDetailsPanel}
                    className={this.state.showDetails ? 'info showing' : 'info'}
                  >
                    <Icon yicon="Expand_Cross_30_by_30" />
                  </a>
                </div>
              ) : (
                ''
              )}
            </div>
            {this.state.showDetails ? (<ConnectedDetails user={model} statusToggle={this.handleStatusChange}/>) : null}
          </div>
        );
      }

}

export default Row;
</code>```

Not really sure how to approach this, maybe something in the body that check is there's any row open according to the showDetails state in the rows?

Thanks in advance

答:
The approach is to lift the state of which <Row /> is open to the  component.
Also the method that switch between opened <Row /> is on the  component.

```<code>toggleOpen = (idx) => {
 this.setState({ openRowIndex: idx });
}
</code>```

then when you rendered your <Row />s you can pass a prop isOpen:

```<code><Row
   key={`${i}_${subModel.username}`}
   model={subModel}
   modelProps={modelProps}
   showInfo={showInfo}
   handleStatusChanged={this.props.handleStatusChanged}
   isOpen={this.state.openRowIndex === i}
   onToggle={_ => this.toggleOpen(i)}
/>
</code>```

Body:
I have an accordion in React formed of a row component which is looped inside a body parent component. In the row I'm toggling the state showDetails to show/hide the details for each row, effectively opening the accordion item. But, since the state is for each row, how do I close one accordion item when I open another one?

Body:

export default class Body extends React.Component {
  render() {
    const {modelProps, showInfo, linkedRow} = this.props;
    return (

        {this.props.model.map(
          (subModel, i) =>
            linkedRow ?
              <LinkedRow
                key={`${i}`}
                model={subModel}
                modelProps={modelProps}
              />
              :
              <Row
                key={`${i}_${subModel.username}`}
                model={subModel}
                modelProps={modelProps}
                showInfo={showInfo}
                handleStatusChanged={this.props.handleStatusChanged}
              />
        )}

    );
  }
}

Row:

class Row extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      userId: '',
      showDetails: false,
      showModal: false,
      status: '',
      value: '',
      showInfo: false
    };
      render() {
        const { model, modelProps, showInfo } = this.props;
        return (

              {modelProps.map((p, i) => (
                <div className={`c-table__item ${this.isStatusCell(model[p]) ? model[p] : p}`} key={i}>{this.isStatusCell(model[p]) ? this.toTitleCase(model[p]) : model[p]}

              ))}

              {showInfo ? (

                    <Icon yicon="Expand_Cross_30_by_30" />

              ) : (
                ''
              )}

            {this.state.showDetails ? (<ConnectedDetails user={model} statusToggle={this.handleStatusChange}/>) : null}

        );
      }

}

export default Row;

Not really sure how to approach this, maybe something in the body that check is there's any row open according to the showDetails state in the rows?

Thanks in advance

Body:
The approach is to lift the state of which <Row /> is open to the <Body /> component.
Also the method that switch between opened <Row /> is on the <Body /> component.

toggleOpen = (idx) => {
 this.setState({ openRowIndex: idx });
}

then when you rendered your <Row />s you can pass a prop isOpen:

<Row
   key={`${i}_${subModel.username}`}
   model={subModel}
   modelProps={modelProps}
   showInfo={showInfo}
   handleStatusChanged={this.props.handleStatusChanged}
   isOpen={this.state.openRowIndex === i}
   onToggle={_ => this.toggleOpen(i)}
/>


问:
What is the preprocessor define for C++ language in Xcode precompile header?
In my Prefix.pch file I am using __OBJC__ preprocessor define for compilation of Objective C headers.  What is the equivalent for compilation of C++ headers?

```<code>#ifdef __OBJC__
    #import <Foundation/Foundation.h>
    #import <UIKit/UIKit.h>
#endif
</code>```

答:
There is a standard preprocessor constant, __cplusplus. Its value is expanded to version number of C++ standard being used:

__cplusplus

denotes the version of C++ standard that is being used, expands to
  value 199711L (until C++11), 201103L (C++11), 201402L (C++14), or
  201703L (C++17)

Source: cppreference

So, you can write, for example:

```<code>#ifdef __cplusplus
  #if __cplusplus >= 201103L
    // include new stuff
  #else
    // use legacy features
  #endif
#endif
</code>```

Body:
In my Prefix.pch file I am using __OBJC__ preprocessor define for compilation of Objective C headers.  What is the equivalent for compilation of C++ headers?

#ifdef __OBJC__
    #import <Foundation/Foundation.h>
    #import <UIKit/UIKit.h>
#endif

Body:
There is a standard preprocessor constant, __cplusplus. Its value is expanded to version number of C++ standard being used:

__cplusplus

denotes the version of C++ standard that is being used, expands to
  value 199711L (until C++11), 201103L (C++11), 201402L (C++14), or
  201703L (C++17)

Source: cppreference

So, you can write, for example:

#ifdef __cplusplus
  #if __cplusplus >= 201103L
    // include new stuff
  #else
    // use legacy features
  #endif
#endif


问:
How to check for changes in form controls using Angular5
Im using reactive forms, I have multiple inputs, I want display a single error for de three inputs, the validatons are; fields are required and blank spaces should not be entered.

component.html:

```<code>    <form [formGroup]="contratoForm" class="campo-form">
        <div class="campoFormulario">
            <label class="etiquetaFormulario" for="txtCodigoContrato">Código contrato</label>
            <div style="display:inline-block; position: relative;"  class="control">
                <input [formControl]="txtCodigoContrato" type="text" id="txtCodigoContrato" name="txtCodigoContrato" class="cajaTexto ancho80" />
                <span>/</span>
            </div>
            <div style="display:inline-block; position: relative;" class="control">
                <input [formControl]="txtCodigoContrato2" type="text" id="txtCodigoContrato2" name="txtCodigoContrato2" class="cajaTexto ancho80" />
            </div>
        </div>
        <div class="campoFormulario">
            <label class="etiquetaFormulario" for="txtContrato">Contrato</label>
            <div style="display:inline-block; position: relative;" class="control">
                <input [formControl]="txtContrato" type="text" id="txtContrato" name="txtContrato" class="cajaTexto ancho350" />

            </div>
        </div>
         <div *ngIf="((!txtCodigoContrato.valid && (txtCodigoContrato.dirty || txtCodigoContrato.touched)) && (txtCodigoContrato.hasError('required') || txtCodigoContrato.hasError('hasWhites')))
                ||
                ((!txtCodigoContrato2.valid && (txtCodigoContrato2.dirty || txtCodigoContrato2.touched)) && (txtCodigoContrato2.hasError('required') || txtCodigoContrato2.hasError('hasWhites')))
                ||
         ((!txtContrato.valid && (txtContrato.dirty || txtContrato.touched)) && (txtContrato.hasError('required') || txtContrato.hasError('hasWhites')))
                ">

            <span>check the fields in red, they are required</span>
        </div>
        <div class="buttons">
            <button class="btn btn-primary boton" type="button" style="float:right;" (click)="onCloseLink()">
                <span class="glyphicon glyphicon-off"></span> Cancel
            </button>

            <button class="btn btn-primary boton" type="button" style="float:right;" (click)="limpiar()">
                <span class="glyphicon glyphicon-trash"></span> Clean
            </button>
            <button type="submit" [disabled]="!contratoForm.valid" class="btn btn-primary boton" style="float:right;" (click)="onClick()">
                <span class="glyphicon glyphicon-floppy-disk"></span> Save
            </button>
        </div>
    </form>
</code>```

component.ts:

```<code>    import { Component, HostBinding, OnDestroy, OnInit, Input, Output, EventEmitter, ElementRef, NgModule, ViewChild, ChangeDetectorRef  } from '@angular/core';
    import { Validators, FormBuilder, FormControl, FormGroup, AbstractControl} from '@angular/forms';
    import { AfterViewChecked } from '@angular/core/src/metadata/lifecycle_hooks';

    @Component({
        selector: 'app-formulario-contrato',
        templateUrl: './contrato.component.html',
        styleUrls: ['./contrato.component.css']
    })
    export class FormularioContratoComponent  {

        contratoForm: FormGroup;

        constructor(private elRef: ElementRef, private formBuilder: FormBuilder, private cdRef: ChangeDetectorRef) {
            this.createForm();
        }

        txtCodigoContrato = new FormControl('', [
            Validators.required
            ,this.hasNotWhites
        ]);
        txtCodigoContrato2 = new FormControl('', [
            Validators.required
            , this.hasNotWhites
        ]);
        txtContrato = new FormControl('', [
            Validators.required
            , this.hasNotWhites
        ]);

        createForm() {
            this.contratoForm = this.formBuilder.group({
                txtCodigoContrato: this.txtCodigoContrato
                ,txtCodigoContrato2: this.txtCodigoContrato2
                ,txtContrato: this.txtContrato
            });
        }

        hasNotWhites(fieldControl: FormControl) {
            if (fieldControl.value.trim() != '') {
                return null
            }
            else {
               return { hasWhites: true };
            }
        }

        ngAfterViewChecked() {
            this.cdRef.detectChanges();
        }

        limpiar() {
        }

        onClick() {
            return null;
        }
</code>```

component.css:

```<code>/* some stuff...*/
:host /deep/ .control input.ng-invalid.ng-touched {
  border-color: #ff8080;
}
</code>```

The validations work correctly, that is, they jump when the field stays empty or when I enter blank spaces. My problem is that I have to add more form controls and the if it contains the message can be made illegible:

```<code>  <div *ngIf="((!txtCodigoContrato.valid && (txtCodigoContrato.dirty ||
  txtCodigoContrato.touched)) && (txtCodigoContrato.hasError('required') ||
  txtCodigoContrato.hasError('hasWhites')))
                ||
                ((!txtCodigoContrato2.valid && (txtCodigoContrato2.dirty ||
  txtCodigoContrato2.touched)) && (txtCodigoContrato2.hasError('required') ||
  txtCodigoContrato2.hasError('hasWhites')))
                ||
         ((!txtContrato.valid && (txtContrato.dirty || txtContrato.touched))
  && (txtContrato.hasError('required') || txtContrato.hasError('hasWhites')))
                ">
</code>```

Is there any way to control these values by typescript, that is, each time a value in the control changes it is controlled by a function in typeScript that returns true or false and if only ask for the value of that function in my div?

答:
try using valueChanges along with Array.some() functions

```<code>hasError: boolean = false;

constructor(private elRef: ElementRef,
            private formBuilder: FormBuilder,
            private cdRef: ChangeDetectorRef) {
  this.createForm();

  // listen to all changes on the form
  this.contratoForm.valueChanges.subscribe(_ => {
    const controllersToCheck = [
      'txtCodigoContrato',
      'txtCodigoContrato2',
      'txtContrato'
    ];
    this.hasError = controllersToCheck.some(ctrlName => {
      let ctrl = this.contratoForm.get(ctrlName);
      return (ctrl.dirty || ctrl.touched) &&
             (ctrl.hasError('required') || ctrl.hasError('hasWhites'));
    });
  });
}
</code>```

(checking !ctrl.valid is redundant because if controller has an error, then it is invalid)

HTML:

```<code><div *ngIf="hasError">
  <span>check the fields in red, they are required</span>
</div>
</code>```

UPDATE

As stated here

You can also listen to
   {@link AbstractControl#statusChanges statusChanges} to be notified when the validation status is
   re-calculated.

I think it will suit your case more, so try to subscribe to statusChanges event (instead of valueChanges):

```<code>this.contratoForm.statusChanges.subscribe( ..........
</code>```

UPDATE 2

use a function in your HTML:

```<code><div *ngIf="hasErrors()">
  <span>check the fields in red, they are required</span>
</div>
</code>```

add this function to your component ts file:

```<code>hasErrors() {
  const controllersToCheck = [
    'txtCodigoContrato',
    'txtCodigoContrato2',
    'txtContrato'
  ];
  return controllersToCheck.some(ctrlName => {
    let ctrl = this.contratoForm.get(ctrlName);
    return (ctrl.dirty || ctrl.touched) &&
           (ctrl.hasError('required') || ctrl.hasError('hasWhites'));
  });
}
</code>```

I created a STACKBLITZ

if you add new controllers with the same validation logic, just add their control names to controllersToCheck array

Body:
Im using reactive forms, I have multiple inputs, I want display a single error for de three inputs, the validatons are; fields are required and blank spaces should not be entered.

component.html:

    <form [formGroup]="contratoForm" class="campo-form">

            Código contrato

                <input [formControl]="txtCodigoContrato" type="text" id="txtCodigoContrato" name="txtCodigoContrato" class="cajaTexto ancho80" />
                /

                <input [formControl]="txtCodigoContrato2" type="text" id="txtCodigoContrato2" name="txtCodigoContrato2" class="cajaTexto ancho80" />

            Contrato

                <input [formControl]="txtContrato" type="text" id="txtContrato" name="txtContrato" class="cajaTexto ancho350" />

         <div *ngIf="((!txtCodigoContrato.valid && (txtCodigoContrato.dirty || txtCodigoContrato.touched)) && (txtCodigoContrato.hasError('required') || txtCodigoContrato.hasError('hasWhites')))
                ||
                ((!txtCodigoContrato2.valid && (txtCodigoContrato2.dirty || txtCodigoContrato2.touched)) && (txtCodigoContrato2.hasError('required') || txtCodigoContrato2.hasError('hasWhites')))
                ||
         ((!txtContrato.valid && (txtContrato.dirty || txtContrato.touched)) && (txtContrato.hasError('required') || txtContrato.hasError('hasWhites')))
                ">

            check the fields in red, they are required

            <button class="btn btn-primary boton" type="button" style="float:right;" (click)="onCloseLink()">
                 Cancel
            </button>

            <button class="btn btn-primary boton" type="button" style="float:right;" (click)="limpiar()">
                 Clean
            </button>
            <button type="submit" [disabled]="!contratoForm.valid" class="btn btn-primary boton" style="float:right;" (click)="onClick()">
                 Save
            </button>

    </form>

component.ts:

    import { Component, HostBinding, OnDestroy, OnInit, Input, Output, EventEmitter, ElementRef, NgModule, ViewChild, ChangeDetectorRef  } from '@angular/core';
    import { Validators, FormBuilder, FormControl, FormGroup, AbstractControl} from '@angular/forms';
    import { AfterViewChecked } from '@angular/core/src/metadata/lifecycle_hooks';

    @Component({
        selector: 'app-formulario-contrato',
        templateUrl: './contrato.component.html',
        styleUrls: ['./contrato.component.css']
    })
    export class FormularioContratoComponent  {

        contratoForm: FormGroup;

        constructor(private elRef: ElementRef, private formBuilder: FormBuilder, private cdRef: ChangeDetectorRef) {
            this.createForm();
        }

        txtCodigoContrato = new FormControl('', [
            Validators.required
            ,this.hasNotWhites
        ]);
        txtCodigoContrato2 = new FormControl('', [
            Validators.required
            , this.hasNotWhites
        ]);
        txtContrato = new FormControl('', [
            Validators.required
            , this.hasNotWhites
        ]);

        createForm() {
            this.contratoForm = this.formBuilder.group({
                txtCodigoContrato: this.txtCodigoContrato
                ,txtCodigoContrato2: this.txtCodigoContrato2
                ,txtContrato: this.txtContrato
            });
        }

        hasNotWhites(fieldControl: FormControl) {
            if (fieldControl.value.trim() != '') {
                return null
            }
            else {
               return { hasWhites: true };
            }
        }

        ngAfterViewChecked() {
            this.cdRef.detectChanges();
        }

        limpiar() {
        }

        onClick() {
            return null;
        }

component.css:

/* some stuff...*/
:host /deep/ .control input.ng-invalid.ng-touched {
  border-color: #ff8080;
}

The validations work correctly, that is, they jump when the field stays empty or when I enter blank spaces. My problem is that I have to add more form controls and the if it contains the message can be made illegible:

  <div *ngIf="((!txtCodigoContrato.valid && (txtCodigoContrato.dirty ||
  txtCodigoContrato.touched)) && (txtCodigoContrato.hasError('required') ||
  txtCodigoContrato.hasError('hasWhites')))
                ||
                ((!txtCodigoContrato2.valid && (txtCodigoContrato2.dirty ||
  txtCodigoContrato2.touched)) && (txtCodigoContrato2.hasError('required') ||
  txtCodigoContrato2.hasError('hasWhites')))
                ||
         ((!txtContrato.valid && (txtContrato.dirty || txtContrato.touched))
  && (txtContrato.hasError('required') || txtContrato.hasError('hasWhites')))
                ">

Is there any way to control these values by typescript, that is, each time a value in the control changes it is controlled by a function in typeScript that returns true or false and if only ask for the value of that function in my div?

Body:
try using valueChanges along with Array.some() functions

hasError: boolean = false;

constructor(private elRef: ElementRef,
            private formBuilder: FormBuilder,
            private cdRef: ChangeDetectorRef) {
  this.createForm();

  // listen to all changes on the form
  this.contratoForm.valueChanges.subscribe(_ => {
    const controllersToCheck = [
      'txtCodigoContrato',
      'txtCodigoContrato2',
      'txtContrato'
    ];
    this.hasError = controllersToCheck.some(ctrlName => {
      let ctrl = this.contratoForm.get(ctrlName);
      return (ctrl.dirty || ctrl.touched) &&
             (ctrl.hasError('required') || ctrl.hasError('hasWhites'));
    });
  });
}

(checking !ctrl.valid is redundant because if controller has an error, then it is invalid)

HTML:

<div *ngIf="hasError">
  <span>check the fields in red, they are required</span>
</div>

UPDATE

As stated here

You can also listen to
   {@link AbstractControl#statusChanges statusChanges} to be notified when the validation status is
   re-calculated.

I think it will suit your case more, so try to subscribe to statusChanges event (instead of valueChanges):

this.contratoForm.statusChanges.subscribe( ..........

UPDATE 2

use a function in your HTML:

<div *ngIf="hasErrors()">
  <span>check the fields in red, they are required</span>
</div>

add this function to your component ts file:

hasErrors() {
  const controllersToCheck = [
    'txtCodigoContrato',
    'txtCodigoContrato2',
    'txtContrato'
  ];
  return controllersToCheck.some(ctrlName => {
    let ctrl = this.contratoForm.get(ctrlName);
    return (ctrl.dirty || ctrl.touched) &&
           (ctrl.hasError('required') || ctrl.hasError('hasWhites'));
  });
}

I created a STACKBLITZ

if you add new controllers with the same validation logic, just add their control names to controllersToCheck array


问:
Stored Procedure/SQL script that allows me to add a record to a table
I have 2 tables, one with all the email data, and another with all the specific member email data that one creates a row if an email has been read.
Once an email has been read by a member its added to the Member_email_read table (which is created and populated based on all read emails).

I am trying to set (on mass) all of the messages to read (this would populate the Member_email_read table) but whilst I can add them one at a time
(see the stored procedue below), I am unable to add them on mass.

The two tables are Email, which holds a record for every email into the system. The other table is a table of all email that the member has read. Each time an email
is read a record is added to the Member_email_read table. They are assiocited on the message_id (and both should use the same user_id). The two tables are as follows -

```<code>SELECT [member_email_id]
  ,[member_email_FK_message_id]
  ,[member_email_FK_user_id]
  ,[member_email_status]
  ,[member_email_read_datetime]
  ,[member_email_delete_datetime]
FROM [MemberData].[dbo].[Member_email_read]

SELECT[message_id]
  ,[email_catlogue_num]
  ,[email_FK_user_id]
  ,[Email_time]
  ,[email_content]
  ,[Email_created_date]
FROM [MemberData].[dbo].[Email]
</code>```

To set all the messages (for a certain user) to unread all I would have to do is delete every record from that table for that user, which can be done with the following:

```<code>DELETE FROM [MemberData].[dbo].[Member_email_read]
WHERE [member_email_FK_message_id_FK_user_id] ='2';
</code>```

I am basically looking for the reverse of this delete.

I have created a Stored procedure that allows for the setting of ONE specific email to be set to read, however this stored procedure (when executed) requires the member to enter a
email_id, message_id, user_id, status, read_datetime & delete_datetime.

```<code>CREATE PROCEDURE [dbo].[set_member_email_to_read]

@member_email_id int,
@member_email_FK_message_id int,
@member_email_FK_user_id int
@member_email_status varchar(1),
@member_email_read_datetime dateTime,
@member_email_delete_datetime dateTime

as
if not exists (Select * from [dbo].[Member_email_read] where [member_email_FK_message_id] = @member_email_FK_message_id) begin
insert into [dbo].[Member_email_read]
    (
       [member_email_FK_message_id]
      ,[member_email_FK_user_id]
      ,[member_email_status]
      ,[member_email_read_datetime]
      ,[member_email_delete_datetime]
  )
  values
  (
        @member_email_FK_message_id,
        @member_email_FK_user_id
        @member_email_status,
        @member_email_read_datetime,
        @member_email_delete_datetime
  )

SELECT Convert(int,SCOPE_IDENTITY()) As InsertedID

end else begin
    update [dbo].[Member_email_read] set
   [member_email_FK_message_id]         =   @member_email_FK_message_id
  ,[member_email_FK_user_id]            =   @member_email_FK_user_id
  ,[member_email_status]                =   @member_email_status
  ,[member_email_read_datetime]         =   @member_email_read_datetime
  ,[member_email_delete_datetime]       =   @member_email_delete_datetime

where [member_email_FK_user_id] = @member_email_FK_user_id
if (@@ERROR = 0) begin
    SELECT Convert(int,@member_email_FK_user_id) As InsertedID
end
end
GO
</code>```

I was hoping to create a stored procedure (or general SQL script) that would allow me to enter in
a user_id and then allow for all emails for that user to change from unread to read (populate the Member_email_read table).

答:
You can try using MERGE to perform a bulk insert/update from your Email table into your Member_email_read table:

```<code>MERGE [MemberData].[dbo].[Member_email_read] AS tgt
USING (
    SELECT message_id, user_id, 'R', null, CURRENT_TIMESTAMP
    FROM [MemberData].[dbo].[Email]
    WHERE user_id = @UserId
) AS src (MessageId, UserId, Status, ReadDate, DeleteDate)
ON (
    tgt.member_email_FK_message_id = src.message_id
    AND tgt.member_email_FK_user_id = src.user_id
)
WHEN MATCHED THEN
    UPDATE SET tgt.member_email_status = src.Status,
               tgt.member_email_read_datetime = src.ReadDate,
               tgt.member_email_delete_datetime = src.DeleteDate
WHEN NOT MATCHED THEN
    INSERT (member_email_FK_message_id, member_email_FK_user_id,
            member_email_status, member_email_read_datetime, member_email_delete_datetime)
    VALUES (src.MessageId, src.UserId, src.Status, src.ReadDate, src.DeleteDate)
;
</code>```

This should work, though as I mentioned in my comment above, you should rethink your table design and simply add a read_datetime and delete_datetime (possibly a status column if you really need that as well) to your Email table, rather than having a whole separate table simply to hold records identifying a delete status.

Body:
I have 2 tables, one with all the email data, and another with all the specific member email data that one creates a row if an email has been read.
Once an email has been read by a member its added to the Member_email_read table (which is created and populated based on all read emails).

I am trying to set (on mass) all of the messages to read (this would populate the Member_email_read table) but whilst I can add them one at a time
(see the stored procedue below), I am unable to add them on mass.

The two tables are Email, which holds a record for every email into the system. The other table is a table of all email that the member has read. Each time an email
is read a record is added to the Member_email_read table. They are assiocited on the message_id (and both should use the same user_id). The two tables are as follows -

SELECT [member_email_id]
  ,[member_email_FK_message_id]
  ,[member_email_FK_user_id]
  ,[member_email_status]
  ,[member_email_read_datetime]
  ,[member_email_delete_datetime]
FROM [MemberData].[dbo].[Member_email_read]

SELECT[message_id]
  ,[email_catlogue_num]
  ,[email_FK_user_id]
  ,[Email_time]
  ,[email_content]
  ,[Email_created_date]
FROM [MemberData].[dbo].[Email]

To set all the messages (for a certain user) to unread all I would have to do is delete every record from that table for that user, which can be done with the following:

DELETE FROM [MemberData].[dbo].[Member_email_read]
WHERE [member_email_FK_message_id_FK_user_id] ='2';

I am basically looking for the reverse of this delete.

I have created a Stored procedure that allows for the setting of ONE specific email to be set to read, however this stored procedure (when executed) requires the member to enter a
email_id, message_id, user_id, status, read_datetime & delete_datetime.

CREATE PROCEDURE [dbo].[set_member_email_to_read]

@member_email_id int,
@member_email_FK_message_id int,
@member_email_FK_user_id int
@member_email_status varchar(1),
@member_email_read_datetime dateTime,
@member_email_delete_datetime dateTime

as
if not exists (Select * from [dbo].[Member_email_read] where [member_email_FK_message_id] = @member_email_FK_message_id) begin
insert into [dbo].[Member_email_read]
    (
       [member_email_FK_message_id]
      ,[member_email_FK_user_id]
      ,[member_email_status]
      ,[member_email_read_datetime]
      ,[member_email_delete_datetime]
  )
  values
  (
        @member_email_FK_message_id,
        @member_email_FK_user_id
        @member_email_status,
        @member_email_read_datetime,
        @member_email_delete_datetime
  )

SELECT Convert(int,SCOPE_IDENTITY()) As InsertedID

end else begin
    update [dbo].[Member_email_read] set
   [member_email_FK_message_id]         =   @member_email_FK_message_id
  ,[member_email_FK_user_id]            =   @member_email_FK_user_id
  ,[member_email_status]                =   @member_email_status
  ,[member_email_read_datetime]         =   @member_email_read_datetime
  ,[member_email_delete_datetime]       =   @member_email_delete_datetime

where [member_email_FK_user_id] = @member_email_FK_user_id
if (@@ERROR = 0) begin
    SELECT Convert(int,@member_email_FK_user_id) As InsertedID
end
end
GO

I was hoping to create a stored procedure (or general SQL script) that would allow me to enter in
a user_id and then allow for all emails for that user to change from unread to read (populate the Member_email_read table).

Body:
You can try using MERGE to perform a bulk insert/update from your Email table into your Member_email_read table:

MERGE [MemberData].[dbo].[Member_email_read] AS tgt
USING (
    SELECT message_id, user_id, 'R', null, CURRENT_TIMESTAMP
    FROM [MemberData].[dbo].[Email]
    WHERE user_id = @UserId
) AS src (MessageId, UserId, Status, ReadDate, DeleteDate)
ON (
    tgt.member_email_FK_message_id = src.message_id
    AND tgt.member_email_FK_user_id = src.user_id
)
WHEN MATCHED THEN
    UPDATE SET tgt.member_email_status = src.Status,
               tgt.member_email_read_datetime = src.ReadDate,
               tgt.member_email_delete_datetime = src.DeleteDate
WHEN NOT MATCHED THEN
    INSERT (member_email_FK_message_id, member_email_FK_user_id,
            member_email_status, member_email_read_datetime, member_email_delete_datetime)
    VALUES (src.MessageId, src.UserId, src.Status, src.ReadDate, src.DeleteDate)
;

This should work, though as I mentioned in my comment above, you should rethink your table design and simply add a read_datetime and delete_datetime (possibly a status column if you really need that as well) to your Email table, rather than having a whole separate table simply to hold records identifying a delete status.


问:
kettle Converting from other Databases to PostgreSQL
I have a problem when I convert mysql database to postgres.

mysql tablenames and columns are all uppercase but kettle creates postgres tables all lowercase when i run this job. The components of tableoutput prints log just like this

INSERT INTO USER_MENU ("FLOW_ID", "USER_ID" .... ,

I try mysql all lowercase, run successfully. I know postgres is case-sensitive but how to solve this case when mysql all uppercase or how to make the tableoutput to output lowercase sql.

Using kettle 6.1.0.1-R

答:
Quick answer: The create table statement is an editable text. In particular you can copy/paste it into a notepad (or any editor), change all to lowercase and copy/paste it back before to push the create button. (Useful also for non-standard SQL dialect, like Date/Time/Boolean types).

Neat answer: Edit the connection. On the right panel you have a General/Advanced/Options/Pooling/Cluster menu. Go to the Advanced panel. There you can tell weather your database is using uppercase or lowercase.

Stupid but quick use of the clever answer: Use the Advanced menu to force quote around identifiers.

Really smart answer: Edit the MySQL connection and select the Options menu, and refer to that page. Postgres conforms strictly to standand SQL, so be reluctant to change the Options default for Postgres connections.


问:
Pycharm - how to turn on autocompletion for non-project files?
I have current version of Pycharm Community Edition 2017.2.4 installed on Linux and on Windows.

In the one working on Windows, I open non-project files and while I write code in them, there is autocompletion for in-project modules, classes, etc.

On the Linux (Debian) however, when I write code in non-project file , there is autocompletion only for non-project modules.

Some additional info:

Those in-project modules are installed via PIP on both systems in the same way:
pip install -e .

I can run non-project files importing those project modules in both cases.

On Linux I use virtual-env but have set correct project interpreter (as suggested in similar question: Why isn't PyCharm's autocomplete working for libraries I install?)

It looks like autocompletion uses system interpreter for those non-project files only. I have loaded several projects and in one of them there is autocompletion for the other.

答:
Ok, I found out the problem was not with OS.

To turn on autocompletion for non-project files it is needed to add libraries you use to External libraries. Instruction how to do this is in https://stackoverflow.com/a/24206781/4601890


问:
Excel - Getting the first cell after which a continous range meets criteria
I have a relatively big database in Excel 2016 describing the costs of changing to a new product after two years.

The old product (Product A) has to be repaired after every n uses, which makes the cost curve look like a strairway. The new product (Product B) has no such costs, so in this case the curve would be linear. The two curves are divergent, but only slightly.

By comparing the two products, B is always cheaper directly after repairing Product A, because of the repair costs. Over the n time Product A has only lower costs, so until just before repair, Product A is a bit cheaper.
Price comparison

I have the cost savings in a column, and I am looking for the row of the last negative number, after which in a range of n cells all the numbers are positive.

I`ve tried to experiment with MATCH so far, but it stops after the first number is found.
e.g.:

A1

-45

15

-60

-20

30

15

40

50

Assuming, that n = 3 and -45 is in cell A1, I would like a formula, whitch gives me A4 as a result (as the following numbers in the next 3 cells are all positive).
MATCH stops at A1 (or A2 if looking for positive numbers).

Can it be done with an (array) formula? How?

A bit more generally: how can I "push" a condition check for a range through a whole column/array?

Thank you in advance.

答:
thank you for the tip. I was able to mathematically define a lower envelope for the function describing my values, so I could calculate the point where it crosses the x axis. That solved the problem.

Thank you again.


问:
Defining path to a file with $PSScriptRoot
This is not exactly asking for help, more like kind of curiosity. I have a path to a file defined like this in my script:

$RootDir = $PSScriptRoot
$ExcelFile = $RootDir + "\" + $File + ".xlsx"
```

<p>The <code>$File</code> variable is defined earlier in the script. This version works perfectly fine, but when I tried to simplify it like this to a single row, it didn't work:</p>

<pre class="lang-cs prettyprint-override"><code>$ExcelFile = $PSScriptRoot + "\" + $File + ".xlsx"
</code>```

Any idea why the second version does not work? It says that the file could not be found. I can't see any logical reason for it.

答:
For building paths use the Join-Path cmdlet:

```<code>$ExcelFile = Join-Path $PSScriptRoot ($File + '.xlsx')
</code>```

In your particular case you could also go with a simple string with variables:

```<code>$ExcelFile = "${PSScriptRoot}\${File}.xlsx"
</code>```

But Join-Path is the more resilient approach, because it automatically takes care of the path separator between the elements.

Body:
This is not exactly asking for help, more like kind of curiosity. I have a path to a file defined like this in my script:

$RootDir = $PSScriptRoot
$ExcelFile = $RootDir + "\" + $File + ".xlsx"

The $File variable is defined earlier in the script. This version works perfectly fine, but when I tried to simplify it like this to a single row, it didn't work:

$ExcelFile = $PSScriptRoot + "\" + $File + ".xlsx"

Any idea why the second version does not work? It says that the file could not be found. I can't see any logical reason for it.

Body:
For building paths use the Join-Path cmdlet:

$ExcelFile = Join-Path $PSScriptRoot ($File + '.xlsx')

In your particular case you could also go with a simple string with variables:

$ExcelFile = "${PSScriptRoot}\${File}.xlsx"

But Join-Path is the more resilient approach, because it automatically takes care of the path separator between the elements.


问:
C on linux: using fclose() on Filepointers made from Socket descriptors
I have to write a simple command-line client/server thingy for school and our teacher told us that using fdopen on Sockets is the easy way to go. A protocol is given that defines simple requests and responses only marked by EOF (so not within the request itself but the FIN flag will have to do).

Now my problem is that in order to get a response in the client I have to close the writing direction.
For this I'm using fclose()
Leaving out the details what I'm doing (skipping all the error handling and unrelated stuff)is pretty much:

```<code>sdr = socket(..);
sdw=dup(sdr);
writepointer = fdopen(sdw,"w");
readpointer = fdopen(sdr,"r");
send_message(writepointer);
fclose (writepointer);
</code>```

Now I would expect flcose() (which successfully return 0 btw) to send EOF, fflush(), close the pointer and close the underlying socket descriptor resulting in a fin flag being sent from the client to the server.

Now when I single step through the program and simultaniously look at tcpdump I see the request being sent (and ack'ed  by the server) when I call fclose() but no FIN flag.
This of course results in the Server not seeing that the request is done and my client getting very bored when trying to read a response later on.

I don't find many people using file pointers for tcp transfers here so a search for this didn't yield a whole lot.

Has anyone had this problem before?

答:
You have two ways to cause a shutdown of a TCP socket and you are doing neither of them. One of them is to call shutdown. You are not doing that. The other is to close the last descriptor that references the connection. You are not doing that.

Do one of those two things.

Your expectation that this will trigger a shutdown is unreasonable. You still have a socket open to the connection that can be used to both read from it and write to it. So it would be quite surprising if a TCP protocol shutdown was triggered.

Body:
I have to write a simple command-line client/server thingy for school and our teacher told us that using fdopen on Sockets is the easy way to go. A protocol is given that defines simple requests and responses only marked by EOF (so not within the request itself but the FIN flag will have to do).

Now my problem is that in order to get a response in the client I have to close the writing direction.
For this I'm using fclose()
Leaving out the details what I'm doing (skipping all the error handling and unrelated stuff)is pretty much:

sdr = socket(..);
sdw=dup(sdr);
writepointer = fdopen(sdw,"w");
readpointer = fdopen(sdr,"r");
send_message(writepointer);
fclose (writepointer);

Now I would expect flcose() (which successfully return 0 btw) to send EOF, fflush(), close the pointer and close the underlying socket descriptor resulting in a fin flag being sent from the client to the server.

Now when I single step through the program and simultaniously look at tcpdump I see the request being sent (and ack'ed  by the server) when I call fclose() but no FIN flag.
This of course results in the Server not seeing that the request is done and my client getting very bored when trying to read a response later on.

I don't find many people using file pointers for tcp transfers here so a search for this didn't yield a whole lot.

Has anyone had this problem before?


问:
JMeter - view more results in View Results Tree
In JMeter GUI when I check execution issues over time I'm using View Results Tree

When I want to stop and view an issue I can see only ~4000 request,

It seems that there's a maximum of requests that is display in GUI,

Can number of request in GUI be increased (or just show all)?

Also when test in running It's causing my problematic request to move up even if Scroll automatically? is unchecked

答:
In jmeter.properties view.results.tree.max_results property control the number

Set it to 0 for unlimited results.

# Maximum number of results in the results tree

# Set to 0 to store all results (might consume a lot of memory)

```<code>view.results.tree.max_results=0
</code>```

Edit updated in JMeter docs

Starting with version 3.2 the number of entries in the View is restricted to the value of the property view.results.tree.max_results which defaults to 500 entries. The old behaviour can be restored by setting the property to 0. Beware, that this might consume a lot of memory.

Body:
In jmeter.properties view.results.tree.max_results property control the number

Set it to 0 for unlimited results.

# Maximum number of results in the results tree

# Set to 0 to store all results (might consume a lot of memory)

view.results.tree.max_results=0

Edit updated in JMeter docs

Starting with version 3.2 the number of entries in the View is restricted to the value of the property view.results.tree.max_results which defaults to 500 entries. The old behaviour can be restored by setting the property to 0. Beware, that this might consume a lot of memory.

ContentLicense: CC BY-SA 4.0


问:
Response.Redirect Fails But then Works on Refresh IIS Express VS2013
I have an ASP.NET project in Visual Studio 2013, running locally in IIExpress (Version 8.08418.0) for testing.

The main page (adminDefault.aspx) redirects user to Login.aspx to authenticate (which is done silently based on userID that was passed to adminDefault.aspx as a url variable). The login page sends it back to adminDefault.aspx upon successful authentication. Default then loads data into a Gridview.

The whole process takes about 15 seconds.

When I run this from Visual Studio 2013, I get an error "This page can't be displayed" in about 4 seconds. But if I manually hit refresh, after working for a bit, everything comes in fine.

In my code, suspecting a timeout, I implicitly set this long enough to run through everything:

```<code> if (!this.IsPostBack)
            {

                Session.Timeout = 120;  // seconds before timeout
                try
                {
                    // OnUser should have been set from Login.asp. If it is null, send to Login
                    MembershipUser onUser = Membership.GetUser();
                    if (onUser == null)
                    {
                        Response.Redirect("/login.aspx", true);
                    }
                    else
                    {
                        String currentUserName = Membership.GetUser().UserName;
                        userRoles = Roles.GetRolesForUser(Membership.GetUser().UserName);
                    }
                }
</code>```

Even if the Session.Timeout is being ignored, the default is 20 Seconds, so I would expect it to work anyway.

So:
1) Why is the first run through failing?
2) Is there a way I can prevent it? Failing that can I catch the page not found, and refresh automatically?

EDIT: This has something to do with the trip to Login.aspx and back. If I remove Response.Redirect("/login.aspx", true);
Then this works as expected. The problem is, I need the Login.aspx for validation. Anyone have any thoughts as to why the trip to Login and back is not working... and then does upon refresh?

When I try to run this in Chrome, I don't get as far. Chrome shows me this:

Hitting the here just cycles for a moment and comes back to the screen.

The Developer Tool on IE are not helpful (at least that i can see) in this case. When I run my project in the debugger, it launches a new IE session. Before I can turn on developer tools and press "Play" to record events, the session has given me "Cannot display the page" error. Of course I can hit "play" in the tools and then refresh, but of course everything runs then without error. The refresh makes everything run right. I need to discover why it fails before then.

EDIT: This is the Login.aspx and Web.Security Code. I didn't write it, but it looks boilerplate:

```<code>  protected void Page_Load(object sender, EventArgs e)
    {
            string userName = "";
            bool authenticated = FormsAuthentication.Authenticate(ref userName);
            if (authenticated)
                {
                    FormsAuthentication.RedirectFromLoginPage(userName, false);
                }
     }
</code>```

And the Authentication code looks like this:

```<code>        /// <summary>
    /// Validates a user based on the  session id found in the ReturnURL against credentials stored in the ASP.NET membership.
    /// </summary>
    /// <param name="userName">The user name.</param>
    /// <returns>true if the user name and password are valid; otherwise, false.</returns>
    public static bool Authenticate(ref string userName)
    {
        bool Authenticated = Authenticate(ref userName, GetSessionId());
        return Authenticated;
    }

    /// <summary>
    /// Redirects an authenticated user back to the originally requested URL or the default URL using the specified cookie path for the forms-authentication cookie.
    /// </summary>
    /// <param name="userName">The authenticated user name. </param>
    /// <param name="createPersistentCookie">true to create a durable cookie (one that is saved across browser sessions); otherwise, false. </param>
    /// <param name="strCookiePath">The cookie path for the forms-authentication ticket. </param>
    public static void RedirectFromLoginPage(string userName, bool createPersistentCookie, string strCookiePath)
    {
        System.Web.Security.FormsAuthentication.SetAuthCookie(userName, false, strCookiePath);

        // Redirect back to request page.
        HttpContext.Current.Response.Redirect(GetRedirectUrl());
    }
</code>```

答:
If Login.aspx redirects to adminDefault.aspx before it gets to persist a session to your browser, an infinite redirect loop will happen.

My clues:

1) As you already have a redirect loop - although not intentionally infinite - there is a risk of it becoming infinite under unhandled circumstances

2) you say that a timeout may be occurring, but the server side timeout is ignored: this leads me to think that this happens client side, and in fact could be your browser breaking the redirect loop as a safety measure

3) refreshing helps: this breaks the redirect loop after your session has been persisted client side

4) removing your redirection to adminDefault.aspx helps: this not only breaks the infinite loop, but removes the concept of the redirect loop

A few things you can to do test the redirect loop theory:

1) set a breakpoint on Session.Timeout = 120; and see where things go from there. You'll expect to get to Response.Redirect("/login.aspx", true); once only, but will probably see this line being hit continuously (once per redirection)

or

2) install Fiddler and monitor your redirections.

If the above theory is correct, you have to ensure that Login.aspx gets to persist a session to the browser before redirecting to adminDefault.aspx. I.e., try and remove the redirection to adminDefault.aspx and see if you have gotten a session cookie after redirecting to Login.aspx - if not, you have your suspect. In short, Login.aspx is not done with it's work before you redirect back to adminDefault.aspx - so you have to let it. I can't be more specific without the Login.aspx code.

Body:
I have an ASP.NET project in Visual Studio 2013, running locally in IIExpress (Version 8.08418.0) for testing.

The main page (adminDefault.aspx) redirects user to Login.aspx to authenticate (which is done silently based on userID that was passed to adminDefault.aspx as a url variable). The login page sends it back to adminDefault.aspx upon successful authentication. Default then loads data into a Gridview.

The whole process takes about 15 seconds.

When I run this from Visual Studio 2013, I get an error "This page can't be displayed" in about 4 seconds. But if I manually hit refresh, after working for a bit, everything comes in fine.

In my code, suspecting a timeout, I implicitly set this long enough to run through everything:

 if (!this.IsPostBack)
            {

                Session.Timeout = 120;  // seconds before timeout
                try
                {
                    // OnUser should have been set from Login.asp. If it is null, send to Login
                    MembershipUser onUser = Membership.GetUser();
                    if (onUser == null)
                    {
                        Response.Redirect("/login.aspx", true);
                    }
                    else
                    {
                        String currentUserName = Membership.GetUser().UserName;
                        userRoles = Roles.GetRolesForUser(Membership.GetUser().UserName);
                    }
                }

Even if the Session.Timeout is being ignored, the default is 20 Seconds, so I would expect it to work anyway.

So:
1) Why is the first run through failing?
2) Is there a way I can prevent it? Failing that can I catch the page not found, and refresh automatically?

EDIT: This has something to do with the trip to Login.aspx and back. If I remove Response.Redirect("/login.aspx", true);
Then this works as expected. The problem is, I need the Login.aspx for validation. Anyone have any thoughts as to why the trip to Login and back is not working... and then does upon refresh?

When I try to run this in Chrome, I don't get as far. Chrome shows me this:

Hitting the here just cycles for a moment and comes back to the screen.

The Developer Tool on IE are not helpful (at least that i can see) in this case. When I run my project in the debugger, it launches a new IE session. Before I can turn on developer tools and press "Play" to record events, the session has given me "Cannot display the page" error. Of course I can hit "play" in the tools and then refresh, but of course everything runs then without error. The refresh makes everything run right. I need to discover why it fails before then.

EDIT: This is the Login.aspx and Web.Security Code. I didn't write it, but it looks boilerplate:

  protected void Page_Load(object sender, EventArgs e)
    {
            string userName = "";
            bool authenticated = FormsAuthentication.Authenticate(ref userName);
            if (authenticated)
                {
                    FormsAuthentication.RedirectFromLoginPage(userName, false);
                }
     }

And the Authentication code looks like this:

        ///
    /// Validates a user based on the  session id found in the ReturnURL against credentials stored in the ASP.NET membership.
    ///
    /// <param name="userName">The user name.</param>
    /// <returns>true if the user name and password are valid; otherwise, false.</returns>
    public static bool Authenticate(ref string userName)
    {
        bool Authenticated = Authenticate(ref userName, GetSessionId());
        return Authenticated;
    }

    ///
    /// Redirects an authenticated user back to the originally requested URL or the default URL using the specified cookie path for the forms-authentication cookie.
    ///
    /// <param name="userName">The authenticated user name. </param>
    /// <param name="createPersistentCookie">true to create a durable cookie (one that is saved across browser sessions); otherwise, false. </param>
    /// <param name="strCookiePath">The cookie path for the forms-authentication ticket. </param>
    public static void RedirectFromLoginPage(string userName, bool createPersistentCookie, string strCookiePath)
    {
        System.Web.Security.FormsAuthentication.SetAuthCookie(userName, false, strCookiePath);

        // Redirect back to request page.
        HttpContext.Current.Response.Redirect(GetRedirectUrl());
    }