问:
Access SQL query to SELECT from one table and INSERT into another
Below is my query.  Access does not like it, giving me the error Syntax error (missing operator) in query expression 'answer WHERE question = 1'.

Hopefully you can see what I am trying to do.  Please pay particular attention to 3rd, 4th, and 5th lines under the SELECT statement.

```<code>INSERT INTO Table2 (respondent,1,2,3-1,3-2,3-3,4,5)
SELECT respondent,
answer WHERE question = 1,
answer WHERE question = 2,
answer WHERE answer = 'text 1' AND question = 3,
answer WHERE answer = 'text 2' AND question = 3,
answer WHERE answer = 'text 3' AND question = 3,
answer WHERE question = 4,
longanswer WHERE question 5 FROM Table1 GROUP BY respondent;
</code>```

UPDATE:

I have made a little progress with this, but I still cannot get my data in the format I really want.  I used several Iif statements to get as far as I am now, but GROUP BY simply isn't working the way I would expect it to.  I have also tried variations on my SELECT statement (like SELECT DISTINCT TOP 100 PERCENT and TRANSFORM) but I guess I am not using them correctly because I always get errors.  Here is what my data looks like now:

All I need to do now is smash all the similar respondent rows together (that is, respondent rows that have the same number) so all the cells that are empty are removed.

答:
The way you "smash all the similar respondent rows together (that is, respondent rows that have the same number) so all the cells that are empty are removed" is simple: you use GROUP BY.

Assuming (you haven't given us the schema) that the schema for your source table looks something like this:

```<code>create table response
(
  respondent_id int          not null , -- PK.1 respondent
  question_id   int          not null , -- PK.2 question number
  answer        varchar(200)     null ,

  primary key clustered ( respondent_id , question_id ) ,

)
</code>```

which is to say that each respondent has at most one response to a particular question, then your select statement to get the desired result set will look something like this (in Transact-SQL -- Access SQL will look somewhat different:

```<code>select respondent_id = t.respondent_id ,
       q1            = max( q1.answer  ) ,
       q2            = max( q2.answer  ) ,
       q3a           = max( q3a.answer ) ,
       q3b           = max( q3b.answer ) ,
       q3c           = max( q3c.answer ) ,
       q4            = max( q4.answer  ) ,
       q5            = max( q5.answer  )
from ( select distinct respondent_id from response ) t
left join response q1  on q1.respondent_id  = t.respondent_id and q1.question_id  = 1
left join response q2  on q2.respondent_id  = t.respondent_id and q2.question_id  = 2
left join response q3a on q3a.respondent_id = t.respondent_id and q3a.question_id = 3 and q3a.answer = 'q3a answer'
left join response q3b on q3b.respondent_id = t.respondent_id and q3b.question_id = 3 and q3b.answer = 'q3b answer'
left join response q3c on q3c.respondent_id = t.respondent_id and q3c.question_id = 3 and q3c.answer = 'q3c answer'
left join response q4  on q4.respondent_id  = t.respondent_id and q4.question_id  = 4
left join response q5  on q5.respondent_id  = t.respondent_id and q5.question_id  = 5
group by t.respondent_id
</code>```

You could also do it with a single table in the FROM clause, thus:

```<code>select respondent_id = t.respondent_id ,
       q1            = max( case t.question_id when 1 then t.answer else null end ) ,
       q2            = max( case t.question_id when 2 then t.answer else null end ) ,
       q3a           = max( case when t.question_id = 3 and t.answer = 'q3a answer' then t.answer else null end ) ,
       q3b           = max( case when t.question_id = 3 and t.answer = 'q3b answer' then t.answer else null end ) ,
       q3c           = max( case when t.question_id = 3 and t.answer = 'q3c answer' then t.answer else null end ) ,
       q4            = max( case t.question_id when 4 then t.answer else null end ) ,
       q5            = max( case t.question_id when 5 then t.answer else null end )
from response t
group by t.respondent_id
</code>```

Body:
Below is my query.  Access does not like it, giving me the error Syntax error (missing operator) in query expression 'answer WHERE question = 1'.

Hopefully you can see what I am trying to do.  Please pay particular attention to 3rd, 4th, and 5th lines under the SELECT statement.

INSERT INTO Table2 (respondent,1,2,3-1,3-2,3-3,4,5)
SELECT respondent,
answer WHERE question = 1,
answer WHERE question = 2,
answer WHERE answer = 'text 1' AND question = 3,
answer WHERE answer = 'text 2' AND question = 3,
answer WHERE answer = 'text 3' AND question = 3,
answer WHERE question = 4,
longanswer WHERE question 5 FROM Table1 GROUP BY respondent;

UPDATE:

I have made a little progress with this, but I still cannot get my data in the format I really want.  I used several Iif statements to get as far as I am now, but GROUP BY simply isn't working the way I would expect it to.  I have also tried variations on my SELECT statement (like SELECT DISTINCT TOP 100 PERCENT and TRANSFORM) but I guess I am not using them correctly because I always get errors.  Here is what my data looks like now:

All I need to do now is smash all the similar respondent rows together (that is, respondent rows that have the same number) so all the cells that are empty are removed.

Body:
The way you "smash all the similar respondent rows together (that is, respondent rows that have the same number) so all the cells that are empty are removed" is simple: you use GROUP BY.

Assuming (you haven't given us the schema) that the schema for your source table looks something like this:

create table response
(
  respondent_id int          not null , -- PK.1 respondent
  question_id   int          not null , -- PK.2 question number
  answer        varchar(200)     null ,

  primary key clustered ( respondent_id , question_id ) ,

)

which is to say that each respondent has at most one response to a particular question, then your select statement to get the desired result set will look something like this (in Transact-SQL -- Access SQL will look somewhat different:

select respondent_id = t.respondent_id ,
       q1            = max( q1.answer  ) ,
       q2            = max( q2.answer  ) ,
       q3a           = max( q3a.answer ) ,
       q3b           = max( q3b.answer ) ,
       q3c           = max( q3c.answer ) ,
       q4            = max( q4.answer  ) ,
       q5            = max( q5.answer  )
from ( select distinct respondent_id from response ) t
left join response q1  on q1.respondent_id  = t.respondent_id and q1.question_id  = 1
left join response q2  on q2.respondent_id  = t.respondent_id and q2.question_id  = 2
left join response q3a on q3a.respondent_id = t.respondent_id and q3a.question_id = 3 and q3a.answer = 'q3a answer'
left join response q3b on q3b.respondent_id = t.respondent_id and q3b.question_id = 3 and q3b.answer = 'q3b answer'
left join response q3c on q3c.respondent_id = t.respondent_id and q3c.question_id = 3 and q3c.answer = 'q3c answer'
left join response q4  on q4.respondent_id  = t.respondent_id and q4.question_id  = 4
left join response q5  on q5.respondent_id  = t.respondent_id and q5.question_id  = 5
group by t.respondent_id

You could also do it with a single table in the FROM clause, thus:

select respondent_id = t.respondent_id ,
       q1            = max( case t.question_id when 1 then t.answer else null end ) ,
       q2            = max( case t.question_id when 2 then t.answer else null end ) ,
       q3a           = max( case when t.question_id = 3 and t.answer = 'q3a answer' then t.answer else null end ) ,
       q3b           = max( case when t.question_id = 3 and t.answer = 'q3b answer' then t.answer else null end ) ,
       q3c           = max( case when t.question_id = 3 and t.answer = 'q3c answer' then t.answer else null end ) ,
       q4            = max( case t.question_id when 4 then t.answer else null end ) ,
       q5            = max( case t.question_id when 5 then t.answer else null end )
from response t
group by t.respondent_id


来源: stackexchange

问:
button click should only change the clicked item but it's changing all the items Angular 4

The above picture is my current display. when i click on edit button it should only convert the paragraph tag to input field of the selected row.

But in my case it's changing all the paragraph into input fields, i found some solutions but none of them is working.

```<code><div id="lists">
            <table id='mytable' cellspacing='0' cellpadding='0'>
                <tr  class="row" [ngClass]="{'selected': i === selectedIndex}"  *ngFor= 'let item of list let i = index' [attr.data-index]='i'  [ngStyle]="{'background-color': i%2 == '0' ? 'gray' : ''}">
                    <td class='default-field'>
                        <p class='para' *ngIf="showHideP">{{i+1}}. {{item}}</p>
                    </td>
                    <td class="edit-field" *ngIf="tbox" >
                        <input type="text" class="myCl" [value]="val" >
                        <!-- style='display:inline-block;' -->
                    </td>
                    <td class='btns' >

                    <input type='button' value='edit' class='edit-btn' (click)='hidePara(item,i)' *ngIf="edt">

                    <input type='button' value='save' class='save-btn' *ngIf="sbtn" (click)='hidePara1(item,i)'>
                    <input type='button' value='DELETE' class='delete-btn' (click)='deleterow(i)'>
                    </td>
                </tr>
            </table>

        </div>
</code>```

above code is html code

```<code>  export class AppComponentComponent implements OnInit
{
  list: string[];
  val: string;
  search:string;
  showHideP: boolean;
  tbox: boolean;
  sbtn: boolean;
  edt: boolean;

 constructor() {
    this.list=["Purchase a ring for my beautiful wife","get new GALAXY Note 150","Complete kevin's work ASAP","Buy 2 dozen eggs","Get milk on my way to home"];
   this.showHideP = true;
   this.tbox = false;
   this.sbtn = false;
   this.edt = true;

  }
  selectedIndex = 0;
  ngOnInit()  {

  }
  insert=function(temp)
  {
   if(temp!="")
   {
       this.list.unshift(temp);
       this.search="";
   }
   else
   {
        alert("Enter something");
   }
 }
  deleterow=function(p)
  {
     if (p > -1) {
     this.list.splice(p, 1);
   }
  }

   hidePara(item,ii){
   this.val=this.list[ii];
   this.showHideP = !this.showHideP;  //for hiding paragraph
   this.tbox = !this.tbox;  //showing text box
   this.edt=!this.edt;  //hide edt button
   this.sbtn = !this.sbtn;  //display save button

 }

  hidePara1(item,ii){

    this.showHideP = !this.showHideP;  //for hiding paragraph
    this.tbox = !this.tbox;  //showing text box
    this.edt=!this.edt;  //hide edt button
    this.sbtn = !this.sbtn;  //display save button
  }
</code>```

}

the above code is my component, when i click on edit button it shows text fields in paragraph place and save button will display and when i click on save button it changes to original condition

After adding Alexis_ni code it is working fine but it shows like this

答:
You can try it like this:

```<code><div id="lists">
    <table id='mytable' cellspacing='0' cellpadding='0'>
        <tr  class="row" [ngClass]="{'selected': i === selectedIndex}"  *ngFor= 'let item of list let i = index' [attr.data-index]='i'  [ngStyle]="{'background-color': i%2 == '0' ? 'gray' : ''}">
            <td style="width:300px; max-width:300px !important" class='default-field' *ngIf="selectedIndex!=i  ">
                <p class='para' >{{i+1}}. {{item}}</p>
            </td>
            <td style="width:300px; max-width:300px !important" class="edit-field" *ngIf="selectedIndex==i   " >
                <input type="text" class="myCl" [value]="val" >
            </td>
            <td class='btns' >

            <input type='button' value='edit' class='edit-btn'  (click)='hidePara(item,i)' *ngIf="selectedIndex!=i">

            <input type='button' value='save' class='save-btn' *ngIf="selectedIndex==i" (click)='hidePara1(item,i)'>
            <input type='button' value='DELETE' class='delete-btn' (click)='deleterow(i)'>
            </td>
        </tr>
    </table>

</div>
</code>```

Typescript:

```<code>      selectedIndex = -1;
    hidePara(item,ii){
  this.selectedIndex=ii;
   this.val=this.list[ii];
   this.showHideP = !this.showHideP;  //for hiding paragraph
   this.tbox = !this.tbox;  //showing text box
   this.edt=!this.edt;  //hide edt button
   this.sbtn = !this.sbtn;  //display save button

 }

  hidePara1(item,ii){
    this.selectedIndex=-1;
    this.showHideP = !this.showHideP;  //for hiding paragraph
    this.tbox = !this.tbox;  //showing text box
    this.edt=!this.edt;  //hide edt button
    this.sbtn = !this.sbtn;  //display save button
  }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
The above picture is my current display. when i click on edit button it should only convert the paragraph tag to input field of the selected row.

But in my case it's changing all the paragraph into input fields, i found some solutions but none of them is working.

{{i+1}}. {{item}}

                        <input type="text" class="myCl" [value]="val" >

                    <input type='button' value='edit' class='edit-btn' (click)='hidePara(item,i)' *ngIf="edt">

                    <input type='button' value='save' class='save-btn' *ngIf="sbtn" (click)='hidePara1(item,i)'>
                    <input type='button' value='DELETE' class='delete-btn' (click)='deleterow(i)'>

above code is html code

  export class AppComponentComponent implements OnInit
{
  list: string[];
  val: string;
  search:string;
  showHideP: boolean;
  tbox: boolean;
  sbtn: boolean;
  edt: boolean;

 constructor() {
    this.list=["Purchase a ring for my beautiful wife","get new GALAXY Note 150","Complete kevin's work ASAP","Buy 2 dozen eggs","Get milk on my way to home"];
   this.showHideP = true;
   this.tbox = false;
   this.sbtn = false;
   this.edt = true;

  }
  selectedIndex = 0;
  ngOnInit()  {

  }
  insert=function(temp)
  {
   if(temp!="")
   {
       this.list.unshift(temp);
       this.search="";
   }
   else
   {
        alert("Enter something");
   }
 }
  deleterow=function(p)
  {
     if (p > -1) {
     this.list.splice(p, 1);
   }
  }

   hidePara(item,ii){
   this.val=this.list[ii];
   this.showHideP = !this.showHideP;  //for hiding paragraph
   this.tbox = !this.tbox;  //showing text box
   this.edt=!this.edt;  //hide edt button
   this.sbtn = !this.sbtn;  //display save button

 }

  hidePara1(item,ii){

    this.showHideP = !this.showHideP;  //for hiding paragraph
    this.tbox = !this.tbox;  //showing text box
    this.edt=!this.edt;  //hide edt button
    this.sbtn = !this.sbtn;  //display save button
  }

}

the above code is my component, when i click on edit button it shows text fields in paragraph place and save button will display and when i click on save button it changes to original condition

After adding Alexis_ni code it is working fine but it shows like this

Body:
You can try it like this:

<div id="lists">
    <table id='mytable' cellspacing='0' cellpadding='0'>
        <tr  class="row" [ngClass]="{'selected': i === selectedIndex}"  *ngFor= 'let item of list let i = index' [attr.data-index]='i'  [ngStyle]="{'background-color': i%2 == '0' ? 'gray' : ''}">
            <td style="width:300px; max-width:300px !important" class='default-field' *ngIf="selectedIndex!=i  ">
                <p class='para' >{{i+1}}. {{item}}</p>
            </td>
            <td style="width:300px; max-width:300px !important" class="edit-field" *ngIf="selectedIndex==i   " >
                <input type="text" class="myCl" [value]="val" >
            </td>
            <td class='btns' >

            <input type='button' value='edit' class='edit-btn'  (click)='hidePara(item,i)' *ngIf="selectedIndex!=i">

            <input type='button' value='save' class='save-btn' *ngIf="selectedIndex==i" (click)='hidePara1(item,i)'>
            <input type='button' value='DELETE' class='delete-btn' (click)='deleterow(i)'>
            </td>
        </tr>
    </table>

</div>

Typescript:

      selectedIndex = -1;
    hidePara(item,ii){
  this.selectedIndex=ii;
   this.val=this.list[ii];
   this.showHideP = !this.showHideP;  //for hiding paragraph
   this.tbox = !this.tbox;  //showing text box
   this.edt=!this.edt;  //hide edt button
   this.sbtn = !this.sbtn;  //display save button

 }

  hidePara1(item,ii){
    this.selectedIndex=-1;
    this.showHideP = !this.showHideP;  //for hiding paragraph
    this.tbox = !this.tbox;  //showing text box
    this.edt=!this.edt;  //hide edt button
    this.sbtn = !this.sbtn;  //display save button
  }


问:
Nested ng-click argument undefined
I am using a Dynamic list created using ng repeat. Each item has a ng-click on it . But few items are conditioned  which makes a form appear and the form submit again have a ng click on it.
Here is my HTML.

```<code><div>
  <div class="dropdown">
    <span class="dropdown-toggle"  data-toggle="dropdown">Services
    <span class="caret"></span></span>
    <ul class="dropdown-menu list-group">
      <li>
          <div class="input-group">
         <input type="text" placeholder="Search" ng-model='dfilter.Name' class="form-control">
      </div>
      </li>
      <li class="divider"></li>
      <li class= "service_list_li" ng-repeat="d in services | filter:dfilter"  ng-click="hitDrupal(d.Name,d.endpoint,d.api)">{{ d.Name }}</li>
    </ul>
 </div>
 <div>
   <form name="dynamic_fields">
     <input type="text" ng-model="drupDynam.one"  ng-if="drupal_dynamic1">
     <input type="text" ng-model="drupDynam.two"  ng-if="drupal_dynamic2" >
     <input type="submit" ng-disabled="dynamic_fields.$pending" ng-click="goDynamic(drupDynam)"  value="Go!" ng-show="drupal_dynamic1">
   </form>
 </div>
</div>
</code>```

And here is the JS:

```<code> $scope.hitDrupal = function(Name,endpoint,api)
{
  $scope.drupal_dynamic1 = false;
  $scope.drupal_dynamic2 = false;
  if (endpoint=='login') {
     //Do something
  }
  else if (Name == 'New') {
       $scope.drupal_dynamic1 = true;
       $scope.goDynamic = function(drupDynam)
       {
          dynamic_api = api + '/' + drupDynam.one;
          console.log(dynamic_api);
          //Do Something
       }
  }
else
{
 //Do Something
}
}
</code>```

So the Issue is i am getting the all arguments for the hitDrupal function. i.e Name,endpoint and api. But getting an undefined for second ngclick argument i.e drupDynam.

I have tried passing individual variables also instead of the comlete object.
I have used ng-submit on the form instead of ng-click.
But no help.

答:
Since you have drupDynam in the template, it should be on scope. So you don't need to pass it as an argument. I would say, that the following should work if drupDynam.one and drupDynam.two work in the template properly:

```<code>$scope.goDynamic = function() {
   dynamic_api = api + '/' + $scope.drupDynam.one;
   console.log(dynamic_api);
}
</code>```

If no, then something's not ok with drupDynam initialization. You may try to output it right in the template:

```<code><input type="submit" ng-disabled="dynamic_fields.$pending" ng-click="goDynamic(drupDynam)"  value="Go!" ng-show="drupal_dynamic1">
drupDynam: {{drupDynam}} drupDynam.one: {{drupDynam.one}}
</code>```

By the two-way binding the view must be changed immediately after the value of drupDynam is changed on scope, so you'll be able to see it before the click. And if it's not good, you need to investigate the drupDynam assignments in code. Where do you set its value?

Title: Nested ng-click argument undefined

Body:
I am using a Dynamic list created using ng repeat. Each item has a ng-click on it . But few items are conditioned  which makes a form appear and the form submit again have a ng click on it.
Here is my HTML.

    Services

         <input type="text" placeholder="Search" ng-model='dfilter.Name' class="form-control">

{{ d.Name }}

   <form name="dynamic_fields">
     <input type="text" ng-model="drupDynam.one"  ng-if="drupal_dynamic1">
     <input type="text" ng-model="drupDynam.two"  ng-if="drupal_dynamic2" >
     <input type="submit" ng-disabled="dynamic_fields.$pending" ng-click="goDynamic(drupDynam)"  value="Go!" ng-show="drupal_dynamic1">
   </form>

And here is the JS:

 $scope.hitDrupal = function(Name,endpoint,api)
{
  $scope.drupal_dynamic1 = false;
  $scope.drupal_dynamic2 = false;
  if (endpoint=='login') {
     //Do something
  }
  else if (Name == 'New') {
       $scope.drupal_dynamic1 = true;
       $scope.goDynamic = function(drupDynam)
       {
          dynamic_api = api + '/' + drupDynam.one;
          console.log(dynamic_api);
          //Do Something
       }
  }
else
{
 //Do Something
}
}

So the Issue is i am getting the all arguments for the hitDrupal function. i.e Name,endpoint and api. But getting an undefined for second ngclick argument i.e drupDynam.

I have tried passing individual variables also instead of the comlete object.
I have used ng-submit on the form instead of ng-click.
But no help.

Body:
Since you have drupDynam in the template, it should be on scope. So you don't need to pass it as an argument. I would say, that the following should work if drupDynam.one and drupDynam.two work in the template properly:

$scope.goDynamic = function() {
   dynamic_api = api + '/' + $scope.drupDynam.one;
   console.log(dynamic_api);
}

If no, then something's not ok with drupDynam initialization. You may try to output it right in the template:

<input type="submit" ng-disabled="dynamic_fields.$pending" ng-click="goDynamic(drupDynam)"  value="Go!" ng-show="drupal_dynamic1">
drupDynam: {{drupDynam}} drupDynam.one: {{drupDynam.one}}

By the two-way binding the view must be changed immediately after the value of drupDynam is changed on scope, so you'll be able to see it before the click. And if it's not good, you need to investigate the drupDynam assignments in code. Where do you set its value?


问:
Noflo: How to have a network with only one component
I am trying to integrate noflo in my browser application. To understand the send and receive of the IIP, I have created a 'forwarder component' which will just output whatever is input to it. I am creating a graph with just one component and trying to send IIP to it to extract a response.

My fbp code for testGraph is following:

```<code># (all)
INPORT=Forwarder.IN:CONTENTIN
# (all)
OUTPORT=Forwarder.OUT:CONTENTOUT
</code>```

following is my react call trying to send an IIP and extract a reply:

```<code>    const loader = new noflo.ComponentLoader(__dirname);
    loader.load('testGraph',(err,instance)=>{

        if(err){
            throw err;
        }
    instance.start((errr)=>{

        if(errr){
            throw errr;
        }
        const inp = noflo.internalSocket.createSocket();
        const outp = noflo.internalSocket.createSocket();

        instance.inPorts.CONTENTIN.attach(inp);
        instance.outPorts.CONTENTOUT.attach(outp);

        outp.on('ip',(ip)=>{
            console.log(ip);
        });

        inp.send('Test Start!');
    });

});
</code>```

The problem is:

instance.inPorts.CONTENTIN.attach(inp);

  instance.outPorts.CONTENTOUT.attach(outp);

because CONTENTIN and CONTENTOUT are undefined. I will appreciate greatly any help regarding this.

Thanks.

答:
The graph has to be as below:</p>

```<code># (all)
INPORT=Forward.IN:CONTENTIN
# (all)
OUTPORT=Forward.OUT:CONTENTOUT
Forward(Forwarder)
</code>```

Body:
I am trying to integrate noflo in my browser application. To understand the send and receive of the IIP, I have created a 'forwarder component' which will just output whatever is input to it. I am creating a graph with just one component and trying to send IIP to it to extract a response.

My fbp code for testGraph is following:

# (all)
INPORT=Forwarder.IN:CONTENTIN
# (all)
OUTPORT=Forwarder.OUT:CONTENTOUT

following is my react call trying to send an IIP and extract a reply:

    const loader = new noflo.ComponentLoader(__dirname);
    loader.load('testGraph',(err,instance)=>{

        if(err){
            throw err;
        }
    instance.start((errr)=>{

        if(errr){
            throw errr;
        }
        const inp = noflo.internalSocket.createSocket();
        const outp = noflo.internalSocket.createSocket();

        instance.inPorts.CONTENTIN.attach(inp);
        instance.outPorts.CONTENTOUT.attach(outp);

        outp.on('ip',(ip)=>{
            console.log(ip);
        });

        inp.send('Test Start!');
    });

});

The problem is:

instance.inPorts.CONTENTIN.attach(inp);

  instance.outPorts.CONTENTOUT.attach(outp);

because CONTENTIN and CONTENTOUT are undefined. I will appreciate greatly any help regarding this.

Thanks.

Body:
The graph has to be as below:

# (all)
INPORT=Forward.IN:CONTENTIN
# (all)
OUTPORT=Forward.OUT:CONTENTOUT
Forward(Forwarder)


问:
About google chart js
I'm using the Google Charts API to include various graphs on a webapp I'm working on.What chart type I`m using is Area Charts,Line Charts OR Column Charts.

When i switch display of the chart into week display,i want the title of any point is like the below.How should i do?Which param should i set.

答:
from the pic, it looks as though you're referring to the title of the tooltip

this is the formatted value of the x-axis

each cell in the data table has a value, and a formatted value

which can be set using object notation...

```<code>{
  v: 1,
  f: 'Jan 1, 2017 - Jan, 7 2017'
}
</code>```

or using the following data table methods...

```<code>setValue(row, col, val)
setFormattedValue(row, col, formattedVal)
setCell(row, col, val, formattedVal)
</code>```

in the following example,
the value of the x-axis is the week number (zero-based),

and the formatted value is the date range.

a date formatter is used to build the formatted value...

```<code>var xValue = {
  v: (i - startDate.getTime()) / oneWeek,
  f: formatDate.formatValue(dateBegin) + ' - ' + formatDate.formatValue(dateEnd)
};
</code>```

see following working snippet...

google.charts.load('current', {
  packages: ['corechart']
}).then(function () {
  var formatDate = new google.visualization.DateFormat({
    pattern: 'MMM dd, yyyy'
  });

  var data = new google.visualization.DataTable();
  data.addColumn('number', 'Week');
  data.addColumn('number', 'y0');

  var oneWeek = (1000 * 60 * 60 * 24 * 7);
  var startDate = new Date(2017, 0, 1);
  var endDate = new Date();
  for (var i = startDate.getTime(); i < endDate.getTime(); i = i + oneWeek) {
    // x value
    var dateBegin = new Date(i);
    var dateEnd = new Date(i + oneWeek - 1);
    var xValue = {
      v: (i - startDate.getTime()) / oneWeek,
      f: formatDate.formatValue(dateBegin) + ' - ' + formatDate.formatValue(dateEnd)
    };

    // y value (y = 2x + 8)
    var yValue = 2 * xValue.v + 8;

    // add data row
    data.addRow([
      xValue,
      yValue
    ]);
  }

  var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
  chart.draw(data);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div></code>```

Title: About google chart js

Body:
from the pic, it looks as though you're referring to the title of the tooltip

this is the formatted value of the x-axis

each cell in the data table has a value, and a formatted value

which can be set using object notation...

{
  v: 1,
  f: 'Jan 1, 2017 - Jan, 7 2017'
}

or using the following data table methods...

setValue(row, col, val)
setFormattedValue(row, col, formattedVal)
setCell(row, col, val, formattedVal)

in the following example,
the value of the x-axis is the week number (zero-based),

and the formatted value is the date range.

a date formatter is used to build the formatted value...

var xValue = {
  v: (i - startDate.getTime()) / oneWeek,
  f: formatDate.formatValue(dateBegin) + ' - ' + formatDate.formatValue(dateEnd)
};

see following working snippet...

google.charts.load('current', {
  packages: ['corechart']
}).then(function () {
  var formatDate = new google.visualization.DateFormat({
    pattern: 'MMM dd, yyyy'
  });

  var data = new google.visualization.DataTable();
  data.addColumn('number', 'Week');
  data.addColumn('number', 'y0');

  var oneWeek = (1000 * 60 * 60 * 24 * 7);
  var startDate = new Date(2017, 0, 1);
  var endDate = new Date();
  for (var i = startDate.getTime(); i < endDate.getTime(); i = i + oneWeek) {
    // x value
    var dateBegin = new Date(i);
    var dateEnd = new Date(i + oneWeek - 1);
    var xValue = {
      v: (i - startDate.getTime()) / oneWeek,
      f: formatDate.formatValue(dateBegin) + ' - ' + formatDate.formatValue(dateEnd)
    };

    // y value (y = 2x + 8)
    var yValue = 2 * xValue.v + 8;

    // add data row
    data.addRow([
      xValue,
      yValue
    ]);
  }

  var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
  chart.draw(data);
});

<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>


问:
update database date values format using MY-SQL
i have date stored in database on date column in dd-mm-yyyy format. This column data type is VARCHAR. i wanted to convert those stored dates in yyy-mm-dd format. i tried using this MYSQL query:

```<code>UPDATE status SET new_time_creation = STR_TO_DATE(date, '%Y-%m-%d');
</code>```

but this does not convert the dates properly (eg. 30-05-2016 => 2030-05-20).
please help me with this query or suggest best on even using php to update the date format. Thanks!

答:
```<code>UPDATE status SET new_time_creation = STR_TO_DATE(date, '%d-%m-%Y');
</code>```

try this. You need to format your date '%d-%m-%Y' in here. So basically in your code you want the order to be days-months-years but you update in the opposite order.

Body:
i have date stored in database on date column in dd-mm-yyyy format. This column data type is VARCHAR. i wanted to convert those stored dates in yyy-mm-dd format. i tried using this MYSQL query:

UPDATE status SET new_time_creation = STR_TO_DATE(date, '%Y-%m-%d');

but this does not convert the dates properly (eg. 30-05-2016 => 2030-05-20).
please help me with this query or suggest best on even using php to update the date format. Thanks!

Body:
UPDATE status SET new_time_creation = STR_TO_DATE(date, '%d-%m-%Y');

try this. You need to format your date '%d-%m-%Y' in here. So basically in your code you want the order to be days-months-years but you update in the opposite order.


问:
Unable to render automatic slideshow with react
I'm trying to create an automatic slideshow in react, using react-slideshow. I'm very new to react and have just begun. I got this code from here.

```<code>import React from 'react';
import { Fade } from 'react-slideshow-image';
const images = [
  './img/p1.png',
  './img/p1.png',
  './img/p1.png'
];

const Slideshow = () => {
return (
    <Fade
      images={images}
      duration="5000"
      transitionDuration="1000"/>
   )
}
</code>```

What I am not getting is how to make this slideshow actually render. What I have done is called this function from inside a component in the same file i.e.

```<code>class App extends Component {
  render() {
    return (
      <div className="App">
      {Slideshow();}
    </div>
    );
  }
}
export default App;
</code>```

This is not rendering any slideshow or image, about which I'm not too surprised. The function is running. I console logged something and it got logged on the console. The rest of the page (I have other divs not shown here) is rendered and there is no error thrown. How to make this work?

答:
Slideshow is a React component, so you need to render it using JSX, not invoke the function:

```<code>class App extends Component {
  render() {
    return (
      <div className="App">
        <Slideshow/>
      </div>
    );
  }
}
export default App;
</code>```

Body:
I'm trying to create an automatic slideshow in react, using react-slideshow. I'm very new to react and have just begun. I got this code from here.

import React from 'react';
import { Fade } from 'react-slideshow-image';
const images = [
  './img/p1.png',
  './img/p1.png',
  './img/p1.png'
];

const Slideshow = () => {
return (
    <Fade
      images={images}
      duration="5000"
      transitionDuration="1000"/>
   )
}

What I am not getting is how to make this slideshow actually render. What I have done is called this function from inside a component in the same file i.e.

class App extends Component {
  render() {
    return (

      {Slideshow();}

    );
  }
}
export default App;

This is not rendering any slideshow or image, about which I'm not too surprised. The function is running. I console logged something and it got logged on the console. The rest of the page (I have other divs not shown here) is rendered and there is no error thrown. How to make this work?

Body:
Slideshow is a React component, so you need to render it using JSX, not invoke the function:

class App extends Component {
  render() {
    return (
      <div className="App">
        <Slideshow/>
      </div>
    );
  }
}
export default App;


问:
Disabling the previous dates and the current date using MaterialCalendarView in android
How to disable the previous and the current date by using MaterialCalendarView library in android, i want those disabled days will not bi clickable.
and i use this block of code</p>

```<code>        public boolean shouldDecorate(CalendarDay day) {
            CalendarDay date= CalendarDay.today();
            return date != null && day.equals(date);
        }

        @Override
        public void decorate(DayViewFacade view) {
            view.setSelectionDrawable(getDrawable(R.drawable.drawable_circle));
            view.setDaysDisabled(true);
        }
</code>```

答:
use this </p>

```<code>Calendar calendar = Calendar.getInstance();
calendarView.state().edit().setMinimumDate(calendar.getTime()).commit();
</code>```

Body:
How to disable the previous and the current date by using MaterialCalendarView library in android, i want those disabled days will not bi clickable.
and i use this block of code

        public boolean shouldDecorate(CalendarDay day) {
            CalendarDay date= CalendarDay.today();
            return date != null && day.equals(date);
        }

        @Override
        public void decorate(DayViewFacade view) {
            view.setSelectionDrawable(getDrawable(R.drawable.drawable_circle));
            view.setDaysDisabled(true);
        }

Body:
use this

Calendar calendar = Calendar.getInstance();
calendarView.state().edit().setMinimumDate(calendar.getTime()).commit();


问:
PHP/SOAP - How to create working request with SOAP
Here is my request in SoapUI:

With SoapUI i send the request and i receive good response.

Here is my PHP code so far:

```<code><?PHP
    $wsdl = 'https://onlinefatura.xyz/foyws/FoyOnlineApiGateWS.asmx';

    try{
        $clinet=new SoapClient($wsdl);

        $ver =array(
            "UserName"=>"USERNAME",
            "Password"=>"PASSWORD",
            "ApiKey"=>"APIKEYHERE",
            "Date"=>"2017-11-09",
        );
        $quates=$clinet->GetAddedBalanceList($ver);

        var_dump($quates);

    }

    catch(SoapFault $e)
    {
        echo $e->getMessage();
    }
</code>```

When i execute the code i receive:

SOAP-ERROR: Parsing WSDL: Couldn't load from 'https://onlinefatura.xyz/foyws/FoyOnlineApiGateWS.asmx' : Premature end of data in tag html line 3

Somehow i'm doing something wrong. I'm not really sure if i made my PHP request correct.

Where is my mistake, and how the correct request should look like ?

答:
With an SoapClient error like "Premature end of data in tag html" your link to the WSDL file is usually not correct.

Try this one: https://onlinefatura.xyz/foyws/FoyOnlineApiGateWS.asmx?WSDL

Body:
Here is my request in SoapUI:

With SoapUI i send the request and i receive good response.

Here is my PHP code so far:

<?PHP
    $wsdl = 'https://onlinefatura.xyz/foyws/FoyOnlineApiGateWS.asmx';

    try{
        $clinet=new SoapClient($wsdl);

        $ver =array(
            "UserName"=>"USERNAME",
            "Password"=>"PASSWORD",
            "ApiKey"=>"APIKEYHERE",
            "Date"=>"2017-11-09",
        );
        $quates=$clinet->GetAddedBalanceList($ver);

        var_dump($quates);

    }

    catch(SoapFault $e)
    {
        echo $e->getMessage();
    }

When i execute the code i receive:

SOAP-ERROR: Parsing WSDL: Couldn't load from 'https://onlinefatura.xyz/foyws/FoyOnlineApiGateWS.asmx' : Premature end of data in tag html line 3

Somehow i'm doing something wrong. I'm not really sure if i made my PHP request correct.

Where is my mistake, and how the correct request should look like ?


问:
Guarantee that certain messages will not be serialized
Suppose, in a certain state, an akka actor A creates a child actor B:

Context.ActorOf(Props.Create(() => new BActor(RawDetails)));

RawDetails is a fairly large but simple object without references that must be transformed in the actual data object SmartDetails which contains many references.

SmartDetails is created in the constructor of BActor and must now be sent to akka actor A.

I must have the guarantee that SmartDetails will not be serialized when sending it from B to A.

Is this a valid way to proceed in akka?

We tested it and it works, i.e. it is not serialized.

I am searching for documentation where e.g. I can find a statement that a child actor is created in the same process as the parent actor and that serialization will not take place.

When message SmartDetails is serialized akka will crash because SmartDetails is too big.

The original RawDetails came from another actor in serialized form, and it was "shipped" in small simple packets.

答:
By default messages within the same ActorSystem (same process and AppDomain) are not serialized - hence why it's so important they be immutable.

The documentation mentions it here, under the "Verification" section:

Normally, messages sent between local actors (i.e. same CLR) do not
  undergo serialization. For testing, sometimes, it may be desirable to
  force serialization on all messages (both remote and local).

But messages sent to another actor system via remoting/clustering will be serialized.


问:
Where can I to write my logic in APIView?
In the CreateAPIView I can override the create method to add my logic:

```<code>class OpenstackAccountCreateAPIView(CreateAPIView):
    """
    create openstack account
    """
    serializer_class = OpenstackAccountCreateSerializer

    def create(self, request, *args, **kwargs):
        # put my logic here
        ......
</code>```

But if I have a APIView, where can I to write my logic?

```<code>class OpenstackAccountLoginAPIView(APIView):
    serializer_class = OpenstackAccountLoginSerializer
    # where can I put my login logic?
</code>```

My OpenstackAccountLoginSerializer in serializers.py:

```<code>class OpenstackAccountLoginSerializer(Serializer):
    password = serializers.CharField()
</code>```

答:
```<code>class OpenstackAccountLoginAPIView(APIView):
    serializer_class = OpenstackAccountLoginSerializer
    def get(self, request):
        """
        Return a list of all users.
        """
    def post(self, request):
        """
        Create users.
        """
</code>```

Body:
In the CreateAPIView I can override the create method to add my logic:

class OpenstackAccountCreateAPIView(CreateAPIView):
    """
    create openstack account
    """
    serializer_class = OpenstackAccountCreateSerializer

    def create(self, request, *args, **kwargs):
        # put my logic here
        ......

But if I have a APIView, where can I to write my logic?

class OpenstackAccountLoginAPIView(APIView):
    serializer_class = OpenstackAccountLoginSerializer
    # where can I put my login logic?

My OpenstackAccountLoginSerializer in serializers.py:

class OpenstackAccountLoginSerializer(Serializer):
    password = serializers.CharField()


问:
How do I run terraform init from a different folder?
I want to script terraform for CI/CD purpose and I don't like CDing in scripts, I rather have specific paths.

I tried terraform init c:\my\folder\containing\tf-file

But running that puts the .terraform folder in my cwd.

答:
UPDATE: Terraform cli now supports -chdir=PATH/TO/TF_files

https://www.terraform.io/cli/commands#switching-working-directory-with-chdir

By default, terraform init assumes that the working directory already
contains a configuration and will attempt to initialize that
configuration.

Optionally, init can be run against an empty directory with the
-from-module=MODULE-SOURCE option, in which case the given module will be copied into the target directory before any other initialization
steps are run.

https://www.terraform.io/docs/commands/init.html

ContentLicense: CC BY-SA 4.0


问:
data binding Angular 4
I have a component with a variable say 'id' and in this component i'm calling a service that's take that variable(id) as parameter,
in my template I assign the value of a radio Button to the variable(id)..
the problem is ..I'm calling my Service in "ngOnInit()", so it doesn't take the value of the radio button , but takes the initial value of the "id"..
Here is my code:

in my component:

```<code> import { Component, OnInit } from '@angular/core';
 import { BartersService } from '../../core/services/barters.service';

 export class BarterViewComponent implements OnInit {
 id:string="";
 allCategories ;
 constructor( private barServ: BartersService) { }
  ngOnInit() {
   this.barServ.findByPage(this.id)
   .subscribe(respone => {
   this.allCategories = respone.data;
    });

    }
 onSelectionChange(val) {
  this.id = val;
 }

}
</code>```

in my Template :

```<code><div *ngFor="let cat of allCategories ; let i=index;">
   <input  style="margin-bottom: 10px;" type="radio" #R
      (change)="onSelectionChange(R.value )" name="rad"  value="cat['id']">
      {{cat['name']}}
</div>
</code>```

Target:

the target is updating the view based on the selection of the radio button.

答:
Change this

```<code>value="cat['id']"
</code>```

to

[value]="cat['id']" or value="{{cat['id']}}"

Title: data binding Angular 4

Body:
I have a component with a variable say 'id' and in this component i'm calling a service that's take that variable(id) as parameter,
in my template I assign the value of a radio Button to the variable(id)..
the problem is ..I'm calling my Service in "ngOnInit()", so it doesn't take the value of the radio button , but takes the initial value of the "id"..
Here is my code:

in my component:

 import { Component, OnInit } from '@angular/core';
 import { BartersService } from '../../core/services/barters.service';

 export class BarterViewComponent implements OnInit {
 id:string="";
 allCategories ;
 constructor( private barServ: BartersService) { }
  ngOnInit() {
   this.barServ.findByPage(this.id)
   .subscribe(respone => {
   this.allCategories = respone.data;
    });

    }
 onSelectionChange(val) {
  this.id = val;
 }

}

in my Template :

   <input  style="margin-bottom: 10px;" type="radio" #R
      (change)="onSelectionChange(R.value )" name="rad"  value="cat['id']">
      {{cat['name']}}

Target:

the target is updating the view based on the selection of the radio button.

Body:
Change this

value="cat['id']"

to

[value]="cat['id']" or value="{{cat['id']}}"


问:
Async not working as I expected
I've read all I can find on async programming in asp.net (c#). I've made sense of most of how it's supposed to work and when it should be used. Yet I find basic examples not working as I expect. Without Task.Run it doesn't seem to actually run asynchronously.

Can someone tell me what I'm missing in this example?

Say the code is like so

```<code>public async Task SubTask2()
{
    LongRunningOperation2();
    Response.Write("<br>------------------------ Finished -------------------------<br>");
}

private async Task<Boolean> LongRunningOperation1()
{
    int counter;

    for (counter = 0; counter < 50000; counter++)
    {
        Response.Write(counter + "<br>");
    }
    return await Task.FromResult<bool>(true);
}

private async Task<Boolean> LongRunningOperation2()
{
    await LongRunningOperation1();
    Response.Write("<br>------------------------ Long Task -------------------------<br>");
    return true;
}
</code>```

Shouldn't LongRunningOperation2() return to SubTask2() and print "finished" before or while writing out numbers? Instead it prints finished at the end. Using Task.Run works as expected but then I don't see the point of ever not using Task.Run

答:
A design consideration of the async/await pattern is that sometimes code that has an async signature might return synchronously (immediately) - perhaps due to caching or local data buffering (reading data from a socket, perhaps, and having spare data left to consume from the buffer), or perhaps due to IoC etc providing a synchronous implementation of an asynchronous signature. In that scenario, the entire engine is designed to optimize by not doing anything as callbacks, but continuing to run synchronously. This is not an edge-case - recent C# updates have extended this by adding support for custom awaitables (in particular: ValueTask<T>) to make this even more efficient in the case when something completes with a synchronous but non-trivial result.

The purpose of async is to facilitate scenarios that have genuinely async components, freeing up the thread to do more useful things than waiting for an async operation to complete. It is not about parallelization.

In your case, all of your code is actually synchronous, so it continues to run synchronously all the way through.

Title: Async not working as I expected

Body:
I've read all I can find on async programming in asp.net (c#). I've made sense of most of how it's supposed to work and when it should be used. Yet I find basic examples not working as I expect. Without Task.Run it doesn't seem to actually run asynchronously.

Can someone tell me what I'm missing in this example?

Say the code is like so

public async Task SubTask2()
{
    LongRunningOperation2();
    Response.Write("
------------------------ Finished -------------------------
");
}

private async Task<Boolean> LongRunningOperation1()
{
    int counter;

    for (counter = 0; counter < 50000; counter++)
    {
        Response.Write(counter + "
");
    }
    return await Task.FromResult<bool>(true);
}

private async Task<Boolean> LongRunningOperation2()
{
    await LongRunningOperation1();
    Response.Write("
------------------------ Long Task -------------------------
");
    return true;
}

Shouldn't LongRunningOperation2() return to SubTask2() and print "finished" before or while writing out numbers? Instead it prints finished at the end. Using Task.Run works as expected but then I don't see the point of ever not using Task.Run


问:
Pure NodeJS and GraphQL, no middleware
Is there any example code implementing GraphQL on NodeJS without using any other middleware like Express, Apollo, etc. Just pure NodeJS http server with GraphQL, and any SQL db.

upd: If someone interested, you can check out my implementation on github - pureGraphQLapi

答:
Nothing prevents you from using Node.js and GraphQL only ; you will be writing a little more code though.

Create your HTTP Server with Node.js only

Listen to incoming requests and use POST json body (for example) to pass query and variables to graphql function

Title: Pure NodeJS and GraphQL, no middleware


问:
Smooth edges of non-rectangular form in .NET
I've created a form with rounded corners using Form.Region. It works, but unfortunately the rounding appears rough. Are there any tricks for smoothing such shaped form corners? I know many applications support this, just not sure how to make it in .NET.

Thanks guys.

答:
There is no good fix for this, regions cannot be anti-aliased.  This is inevitable, anti-aliasing only works when you know the background colors so you can blend properly.  That's not an option for windows, the background is by design unpredictable.  If this is a splash screen then you can fake it by taking a screen shot of the background and drawing your fake window on top of it.  Won't work for more than a few seconds.

Best thing to do is to keep the corner radius small so it is not so noticeable.  Also use a tool like SysInternals' ZoomIt and take a close look at the rounded corners of a program like Windows Media Player.  Note the gray tones it uses to draw the border.

ContentLicense: CC BY-SA 2.5


问:
Using type definition
In my code I have:

```<code>type Dimension big.Int
</code>```

However, it is not clear to me how I can initialize a dimension object.
I know that I can create a big.Int object by doing:

```<code>i := big.NewInt(100)
</code>```

However, how do I convert it to Dimension, or better, how can I initialized it directly as Dimension?

答:
Given:

```<code>type Dimension big.Int
</code>```

There is no way to declare a Dimension without using the big package's Int initializer, since it contains unexported fields.  So your best bet is to wrap the underlying initializer with your own:

```<code>func NewDimension(i int64) *Dimension {
    x := big.NewInt(100)
    z := Dimension(*x)
    return &z
}
</code>```

Then call it as:

```<code>i := NewDimension(100)
</code>```

Title: Using type definition

Body:
In my code I have:

type Dimension big.Int

However, it is not clear to me how I can initialize a dimension object.
I know that I can create a big.Int object by doing:

i := big.NewInt(100)

However, how do I convert it to Dimension, or better, how can I initialized it directly as Dimension?

Body:
Given:

type Dimension big.Int

There is no way to declare a Dimension without using the big package's Int initializer, since it contains unexported fields.  So your best bet is to wrap the underlying initializer with your own:

func NewDimension(i int64) *Dimension {
    x := big.NewInt(100)
    z := Dimension(*x)
    return &z
}

Then call it as:

i := NewDimension(100)


问:
How to calculate size of children
If I want to implement Widget which sizes itself by sizing children, how do I do it?

Somehow I need to defer sizing until all children have figure out their size.

答:
You can create a custom layout, using CustomMultiChildLayout or CustomSingleChildLayout.

Or, if this fits your needs, use IntrinsicWidth/IntrinsicHeight widgets.

Custom layouts are basically a Stack with only positionned children. Children pick their size and then the layout choose their position.
BUT it has a limitation. The layout size can't depend on it's children size.

Instrinsinc widgets are much simpler but also more limited.
A use case would be to wrap a Row widget in IntrincWidget, to simulate the css display: flex; align-items: stretch;

If you need something more complex, you'll need to create your own RenderObject.
Yup, this is counter-intuitive.

Title: How to calculate size of children


问:
Currency regular expression for GBP/USD/EUR
Need some help with creating a regular expression that satisfies the following rules. Any suggestions would be greatly appreciated.

(1a.) Optionally start with:
    £, $, €

1b. Currency value must start with one to three digits

2a. Before a comma: There must be one to three digits

2b. After a comma: There must be three digits

2c. After a decimal point: There can only be digits

3a. Currency value must end with one or many digits

[3b.] Value may be followed by:
    tn/Tn/Trillion/trillion, bn/Bn/Billion/billion, m/Million/million.

(3c.) Optionally end with:
    p/P/Pence/pence, c/C/Cents/cents, €/Euro(s)/euro(s), Dollars/dollars, Pounds/pounds.

Rule 1a and 3c are mutually exclusive, however one of them must be used:

$1 dollar ✘
1 ✘
$1 ✓
1 dollar ✓
```

<p><strong>Rule 3b may be used with Rule 1a or 3c</strong>, but does not need to be used:</p>

<pre class="lang-none prettyprint-override"><code>$1 trillion ✓
1 trillion dollars ✓
$1 ✓
</code>```

Rule 2a/2b may be used zero or many times:

$1 ✓
$1,000,000,000,000 ✓
```

<p><strong>Rule 2c may only be used once or zero times:</strong></p>

<pre class="lang-none prettyprint-override"><code>$1 ✓
$1.000 ✓
</code>```

Expected Result:

$1 dollar ✘
1 ✘
$1,00000.000,000 ✘
1,000.00 ✘

$1 ✓
1 dollar ✓
$1 trillion ✓
1 trillion dollars ✓
$1,000,000,000,000 ✓
$1.000 ✓
$1,000,000,000,000.000000 ✓
```

<p>Here's what I have so far:</p>

```[£€$]?[0-9]+[,.]?[0-9][pcm][ euros| euro]*
```

答:
To manage with mutual exclusion you can use grouping for currency sign and test group for plain currency name:

```<code>^([$£€])?\d{1,3}(?:,\d{3})*(?:\.\d+)?\s?(?:(?:[BMbm]|[Tt]r)(?:illion)?)?(?(1)|\s(?:(?:[Dd]ollar|[Pp]ound|[Ee]uro|[Cc]ent)s?|€|[Pp]ence))$
</code>```

Demo

Body:
Need some help with creating a regular expression that satisfies the following rules. Any suggestions would be greatly appreciated.

(1a.) Optionally start with:
    £, $, €

1b. Currency value must start with one to three digits

2a. Before a comma: There must be one to three digits

2b. After a comma: There must be three digits

2c. After a decimal point: There can only be digits

3a. Currency value must end with one or many digits

[3b.] Value may be followed by:
    tn/Tn/Trillion/trillion, bn/Bn/Billion/billion, m/Million/million.

(3c.) Optionally end with:
    p/P/Pence/pence, c/C/Cents/cents, €/Euro(s)/euro(s), Dollars/dollars, Pounds/pounds.

Rule 1a and 3c are mutually exclusive, however one of them must be used:

$1 dollar ✘
1 ✘
$1 ✓
1 dollar ✓

Rule 3b may be used with Rule 1a or 3c, but does not need to be used:

$1 trillion ✓
1 trillion dollars ✓
$1 ✓

Rule 2a/2b may be used zero or many times:

$1 ✓
$1,000,000,000,000 ✓

Rule 2c may only be used once or zero times:

$1 ✓
$1.000 ✓

Expected Result:

$1 dollar ✘
1 ✘
$1,00000.000,000 ✘
1,000.00 ✘

$1 ✓
1 dollar ✓
$1 trillion ✓
1 trillion dollars ✓
$1,000,000,000,000 ✓
$1.000 ✓
$1,000,000,000,000.000000 ✓

Here's what I have so far:

[£€$]?[0-9]+[,.]?[0-9][pcm][ euros| euro]*

Body:
To manage with mutual exclusion you can use grouping for currency sign and test group for plain currency name:

^([$£€])?\d{1,3}(?:,\d{3})*(?:\.\d+)?\s?(?:(?:[BMbm]|[Tt]r)(?:illion)?)?(?(1)|\s(?:(?:[Dd]ollar|[Pp]ound|[Ee]uro|[Cc]ent)s?|€|[Pp]ence))$

Demo


问:
Replacing tags in HtmlAgility
I'm trying to replace all of my h1 tags with h2 tags and I'm using HtmlAgility pack.

I did this:

```<code>var headers = doc.DocumentNode.SelectNodes("//h1");
if (headers != null)
{
    foreach (HtmlNode item in headers)
    {
        //item.Replace??
    }
}
</code>```

and i got stuck there. I've tried this:

```<code>var headers = doc.DocumentNode.SelectNodes("//h1");
if (headers != null)
{
    foreach (HtmlNode item in headers)
    {
        HtmlNode newNode = new HtmlNode(HtmlNodeType.Element, doc, item.StreamPosition);
        newNode.InnerHtml = item.InnerHtml;
        // newNode suppose to set to h2
        item.ParentNode.ReplaceChild(newNode, item);
    }
}
</code>```

problem there is that i have no idea how to create a new h2, get all the attributes etc.
i'm sure theres a simple way to do that, any ideas?

答:
A similar approach replacing the tags using Descendants instead of SelectNodes:</p>

```<code>IEnumerable<HtmlNode> tagDescendants = doc.DocumentNode.Descendants("h1");
foreach (HtmlNode htmlNode in tagDescendants)
{
    htmlNode.Name = "h2";
}
</code>```

Title: Replacing tags in HtmlAgility

Body:
I'm trying to replace all of my h1 tags with h2 tags and I'm using HtmlAgility pack.

I did this:

var headers = doc.DocumentNode.SelectNodes("//h1");
if (headers != null)
{
    foreach (HtmlNode item in headers)
    {
        //item.Replace??
    }
}

and i got stuck there. I've tried this:

var headers = doc.DocumentNode.SelectNodes("//h1");
if (headers != null)
{
    foreach (HtmlNode item in headers)
    {
        HtmlNode newNode = new HtmlNode(HtmlNodeType.Element, doc, item.StreamPosition);
        newNode.InnerHtml = item.InnerHtml;
        // newNode suppose to set to h2
        item.ParentNode.ReplaceChild(newNode, item);
    }
}

problem there is that i have no idea how to create a new h2, get all the attributes etc.
i'm sure theres a simple way to do that, any ideas?

Body:
A similar approach replacing the tags using Descendants instead of SelectNodes:

IEnumerable<HtmlNode> tagDescendants = doc.DocumentNode.Descendants("h1");
foreach (HtmlNode htmlNode in tagDescendants)
{
    htmlNode.Name = "h2";
}


问:
npm install packagename --save-dev not updating package.json
Are there simple or subtle reasons that package.json would not update after running a --save-dev? This is my command:

npm install modulename --save-dev

Run from the root of the project. The command succeeds, the new module shows up in the node_modules directory as expected. Help would be appreciated. I am using npm v 1.4.28

The entirety of my current package.json is:

```<code>{
    "name": "FooWeb",
    "version": "1.0.0",
    "description": "Foo Web",
    "devDependencies": {
        "gulp": "3.8.11",
        "gulp-jshint": "1.9.2",
        "gulp-concat": "2.5.2",
        "gulp-sass": "1.3.3",
        "gulp-sourcemaps": "1.4.0",
        "gulp-watch": "4.1.1"
    }
}
</code>```

I do get warnings on install of a package that I have no repository field or README, but I think that is not related.

答:
I was trying to install the gruntjs using
    "npm install --save grunt-sass" but the package.json won't update

I did everything mentioned above but no luck. But funny thing is if i try adding a package say "underscore (npm install --save underscore)" the son gets updated. I am not sure if this is a problem with the nam as such. I did install as a super user.

Body:
Are there simple or subtle reasons that package.json would not update after running a --save-dev? This is my command:

npm install modulename --save-dev

Run from the root of the project. The command succeeds, the new module shows up in the node_modules directory as expected. Help would be appreciated. I am using npm v 1.4.28

The entirety of my current package.json is:

{
    "name": "FooWeb",
    "version": "1.0.0",
    "description": "Foo Web",
    "devDependencies": {
        "gulp": "3.8.11",
        "gulp-jshint": "1.9.2",
        "gulp-concat": "2.5.2",
        "gulp-sass": "1.3.3",
        "gulp-sourcemaps": "1.4.0",
        "gulp-watch": "4.1.1"
    }
}

I do get warnings on install of a package that I have no repository field or README, but I think that is not related.


问:
How do I override a magento 2 theme's phtml with my own custom theme?
I'm attempting to customise the ultimo theme (although presumably this would apply to any magento theme). I have created a new custom theme which (using theme.xml) uses Infortis/ultimo as it's parent.

Ultimo has the following path for it's header.phtml

```<code>ultimo/default/template/page/html/header.phtml
</code>```

I've tried a number of different options for my theme to override this - none of which appear to work e.g.

```<code>frontend/my_theme/default/template/html/header.phtml
frontend/my_theme/default/template/page/html/header.phtml
</code>```

Does anyone have any ideas?

答:
It seems you are using magneto 1.X (By your reference code)

In Magento 1.X

First you should configure your new package/theme in the backed.

```<code>System -> Configuration -> Design -> Package = my_theme

Themes: default (no change should be necessary)
</code>```

Now you can modified file header.phtml

```<code>app\design\frontend\my_theme\default\template\html\header.phtml
</code>```

In Magento 2

```<code>app\design\frontend\<VENDOR_NAME>\<THEME_NAME>\Magento_Theme\templates\html\header.phtml
</code>```

Body:
I'm attempting to customise the ultimo theme (although presumably this would apply to any magento theme). I have created a new custom theme which (using theme.xml) uses Infortis/ultimo as it's parent.

Ultimo has the following path for it's header.phtml

ultimo/default/template/page/html/header.phtml

I've tried a number of different options for my theme to override this - none of which appear to work e.g.

frontend/my_theme/default/template/html/header.phtml
frontend/my_theme/default/template/page/html/header.phtml

Does anyone have any ideas?

Body:
It seems you are using magneto 1.X (By your reference code)

In Magento 1.X

First you should configure your new package/theme in the backed.

System -> Configuration -> Design -> Package = my_theme

Themes: default (no change should be necessary)

Now you can modified file header.phtml

app\design\frontend\my_theme\default\template\html\header.phtml

In Magento 2

app\design\frontend\<VENDOR_NAME>\<THEME_NAME>\Magento_Theme\templates\html\header.phtml


问:
What's the ugliest code you were forced to write by outside limitations?
What is the ugliest code that you wrote - not because you didn't know better, but because of limitations of the software, the hardware or the company policy?

Because of unusual choices in database layouts and programming languages, I once built a C program that read in a SQL database structure and generated another C program that'd read that database and back it up into a file, or copy it into a second database that shared more or less the same columns. It was a monster clunky code generator.

答:
A program that exchanged information between two applications. Needless to say the data between the two programs was in different format, different use-cases, and even meant different things from one app to the other. There were TONS of special cases and "nice" conversions:

```<code>if (InputString == "01"))
         { Output.ClientID = Input.Address;}
else if ((InputString = "02") && (Input.Address == null) &&(Input.ClientID < 1300))
        { Output.ClientID = Input.ClientID +1;}
else if (Input.ClientID = 0 )
        { Input.ClientID = 2084; }
</code>```

And on, and on for hundreds of lines.

This was for internal use in a large manufacturing plant... I cried durring most of the time I worked there.

Body:
A program that exchanged information between two applications. Needless to say the data between the two programs was in different format, different use-cases, and even meant different things from one app to the other. There were TONS of special cases and "nice" conversions:

if (InputString == "01"))
         { Output.ClientID = Input.Address;}
else if ((InputString = "02") && (Input.Address == null) &&(Input.ClientID < 1300))
        { Output.ClientID = Input.ClientID +1;}
else if (Input.ClientID = 0 )
        { Input.ClientID = 2084; }

And on, and on for hundreds of lines.

This was for internal use in a large manufacturing plant... I cried durring most of the time I worked there.


问:
SQL Set Question
How can I make the following sql statement part of the "SET" in my query? I want to pull out a list in a column and have my "SET" run against that. That way my "SET" isn't just one variable but rather a list to run against. Make sence? </p>

```<code>DECLARE @Item as char(32)
declare @result varchar(max);
SET @Item = '034100-3JK';
</code>```

<p>I want to use something like the following to have it query against instead of the 034100-3JK: </p>

```<code>select distinct
        a.t_sitm as StartItem
from
        ttibom010101 as a
        INNER JOIN ttiitm001101 as b on a.t_sitm = b.t_item
where
        b.t_ctyp != 'TOP'
        and b.t_ctyp != 'SUB'
</code>```

答:
Question in conjunction with comment

Im trying to run this: select a.t_sitm
  as StartItem ,a.t_mitm ,a.t_sitm
  ,b.t_ctyp ,a.t_qana from ttibom010101
  as a INNER JOIN ttiitm001101 as b on
  a.t_sitm = b.t_item where b.t_ctyp !=
  'TOP' and b.t_ctyp != 'SUB' and
  a.t_sitm =@Items

If all you are trying to do is test against a list, then use a constant list instead of a variable

```<code>and a.t_sitm in ('abc','def','ghi')
</code>```

If you're trying to pass a single string parameter to SQL Server, then you need a function to split it into rows of a table, first grab the function dbo.Split from here (one of many usable "split" functions)

http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=StringArrayInput

Then you can use this query (IN form)

```<code>select a.t_sitm as StartItem ,a.t_mitm ,a.t_sitm ,b.t_ctyp ,a.t_qana
from ttibom010101 as a
INNER JOIN ttiitm001101 as b on a.t_sitm = b.t_item
where b.t_ctyp != 'TOP' and b.t_ctyp != 'SUB'
and a.t_sitm in (select Value from dbo.split(',',@item))
</code>```

Or in JOIN form

```<code>select a.t_sitm as StartItem ,a.t_mitm ,a.t_sitm ,b.t_ctyp ,a.t_qana
from ttibom010101 as a
INNER JOIN ttiitm001101 as b on a.t_sitm = b.t_item
inner join dbo.split(',',@item) S on S.Value = a.t_sitm
where b.t_ctyp != 'TOP' and b.t_ctyp != 'SUB'
</code>```

Title: SQL Set Question

Body:
How can I make the following sql statement part of the "SET" in my query? I want to pull out a list in a column and have my "SET" run against that. That way my "SET" isn't just one variable but rather a list to run against. Make sence?

DECLARE @Item as char(32)
declare @result varchar(max);
SET @Item = '034100-3JK';

I want to use something like the following to have it query against instead of the 034100-3JK:

select distinct
        a.t_sitm as StartItem
from
        ttibom010101 as a
        INNER JOIN ttiitm001101 as b on a.t_sitm = b.t_item
where
        b.t_ctyp != 'TOP'
        and b.t_ctyp != 'SUB'

Body:
Question in conjunction with comment

Im trying to run this: select a.t_sitm
  as StartItem ,a.t_mitm ,a.t_sitm
  ,b.t_ctyp ,a.t_qana from ttibom010101
  as a INNER JOIN ttiitm001101 as b on
  a.t_sitm = b.t_item where b.t_ctyp !=
  'TOP' and b.t_ctyp != 'SUB' and
  a.t_sitm =@Items

If all you are trying to do is test against a list, then use a constant list instead of a variable

and a.t_sitm in ('abc','def','ghi')

If you're trying to pass a single string parameter to SQL Server, then you need a function to split it into rows of a table, first grab the function dbo.Split from here (one of many usable "split" functions)

http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=StringArrayInput

Then you can use this query (IN form)

select a.t_sitm as StartItem ,a.t_mitm ,a.t_sitm ,b.t_ctyp ,a.t_qana
from ttibom010101 as a
INNER JOIN ttiitm001101 as b on a.t_sitm = b.t_item
where b.t_ctyp != 'TOP' and b.t_ctyp != 'SUB'
and a.t_sitm in (select Value from dbo.split(',',@item))

Or in JOIN form

select a.t_sitm as StartItem ,a.t_mitm ,a.t_sitm ,b.t_ctyp ,a.t_qana
from ttibom010101 as a
INNER JOIN ttiitm001101 as b on a.t_sitm = b.t_item
inner join dbo.split(',',@item) S on S.Value = a.t_sitm
where b.t_ctyp != 'TOP' and b.t_ctyp != 'SUB'


问:
before_action except: PATCH
I'm defining some variables that I need for my header, into my application controller. But I would like to disable it for my AJAX requests. So I would like to know if it's possible to disable a before action for all the PATCH requests. Like on the example below

ApplicationController:

```<code>before_action :some_value, except: PATCH method

def some_value
  @main_group = current_user.groups.first
  @groups = current_user.groups - @main_group
end
</code>```

答:
Don't know if there's a way to define that on before_action declaration, but guess you could check on your method for request.patch?, like this:

```<code>def some_value
  if !request.patch?
    @main_group = current_user.groups.first
    @groups = current_user.groups - @main_group
  end
end
</code>```

Hope this helps, good luck

Title: before_action except: PATCH

Body:
I'm defining some variables that I need for my header, into my application controller. But I would like to disable it for my AJAX requests. So I would like to know if it's possible to disable a before action for all the PATCH requests. Like on the example below

ApplicationController:

before_action :some_value, except: PATCH method

def some_value
  @main_group = current_user.groups.first
  @groups = current_user.groups - @main_group
end

Body:
Don't know if there's a way to define that on before_action declaration, but guess you could check on your method for request.patch?, like this:

def some_value
  if !request.patch?
    @main_group = current_user.groups.first
    @groups = current_user.groups - @main_group
  end
end

Hope this helps, good luck


问:
Jenkins Plugins are missing in Available tab
While setting up the Jenkins, I skipped the plugins installation in the wizard. Now I am trying to install it manually. I searched a lot and came to know that I can install it through the web in Manage Jenkins -> Plugin Manager -> Available tab. No plugins are available here. I even typed plugin names in filter but still could not succeed.

Here I am trying to install Git Plugin.

When I click on Check now button, It throws some below Java exception.

Full Stack Trace

```<code>sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at sun.security.provider.certpath.SunCertPathBuilder.build(SunCertPathBuilder.java:141)
    at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(SunCertPathBuilder.java:126)
    at java.security.cert.CertPathBuilder.build(CertPathBuilder.java:280)
    at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:382)
Caused: sun.security.validator.ValidatorException: PKIX path building failed
    at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:387)
    at sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:292)
    at sun.security.validator.Validator.validate(Validator.java:260)
    at sun.security.ssl.X509TrustManagerImpl.validate(X509TrustManagerImpl.java:324)
    at sun.security.ssl.X509TrustManagerImpl.checkTrusted(X509TrustManagerImpl.java:229)
    at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:124)
    at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1491)
Caused: javax.net.ssl.SSLHandshakeException
    at sun.security.ssl.Alerts.getSSLException(Alerts.java:192)
    at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1949)
    at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:302)
    at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:296)
    at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1509)
    at sun.security.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:216)
    at sun.security.ssl.Handshaker.processLoop(Handshaker.java:979)
    at sun.security.ssl.Handshaker.process_record(Handshaker.java:914)
    at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1062)
    at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1375)
    at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1403)
    at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1387)
    at sun.net.www.protocol.https.HttpsClient.afterConnect(HttpsClient.java:559)
    at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:185)
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1513)
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1441)
    at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:254)
    at hudson.model.DownloadService.loadJSON(DownloadService.java:167)
    at hudson.model.UpdateSite.updateDirectlyNow(UpdateSite.java:190)
    at hudson.PluginManager.doCheckUpdatesServer(PluginManager.java:1624)
    at java.lang.invoke.MethodHandle.invokeWithArguments(MethodHandle.java:627)
    at org.kohsuke.stapler.Function$MethodFunction.invoke(Function.java:343)
    at org.kohsuke.stapler.interceptor.RequirePOST$Processor.invoke(RequirePOST.java:52)
    at org.kohsuke.stapler.PreInvokeInterceptedFunction.invoke(PreInvokeInterceptedFunction.java:26)
    at org.kohsuke.stapler.Function.bindAndInvoke(Function.java:184)
    at org.kohsuke.stapler.Function.bindAndInvokeAndServeResponse(Function.java:117)
    at org.kohsuke.stapler.MetaClass$1.doDispatch(MetaClass.java:129)
    at org.kohsuke.stapler.NameBasedDispatcher.dispatch(NameBasedDispatcher.java:58)
    at org.kohsuke.stapler.Stapler.tryInvoke(Stapler.java:715)
    at org.kohsuke.stapler.Stapler.invoke(Stapler.java:845)
    at org.kohsuke.stapler.MetaClass$2.doDispatch(MetaClass.java:186)
    at org.kohsuke.stapler.NameBasedDispatcher.dispatch(NameBasedDispatcher.java:58)
    at org.kohsuke.stapler.Stapler.tryInvoke(Stapler.java:715)
    at org.kohsuke.stapler.Stapler.invoke(Stapler.java:845)
    at org.kohsuke.stapler.Stapler.invoke(Stapler.java:649)
    at org.kohsuke.stapler.Stapler.service(Stapler.java:238)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:292)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at hudson.util.PluginServletFilter$1.doFilter(PluginServletFilter.java:135)
    at hudson.util.PluginServletFilter.doFilter(PluginServletFilter.java:138)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at hudson.security.csrf.CrumbFilter.doFilter(CrumbFilter.java:85)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at hudson.security.ChainedServletFilter$1.doFilter(ChainedServletFilter.java:84)
    at hudson.security.UnwrapSecurityExceptionFilter.doFilter(UnwrapSecurityExceptionFilter.java:51)
    at hudson.security.ChainedServletFilter$1.doFilter(ChainedServletFilter.java:87)
    at jenkins.security.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:117)
    at hudson.security.ChainedServletFilter$1.doFilter(ChainedServletFilter.java:87)
    at org.acegisecurity.providers.anonymous.AnonymousProcessingFilter.doFilter(AnonymousProcessingFilter.java:125)
    at hudson.security.ChainedServletFilter$1.doFilter(ChainedServletFilter.java:87)
    at org.acegisecurity.ui.rememberme.RememberMeProcessingFilter.doFilter(RememberMeProcessingFilter.java:142)
    at hudson.security.ChainedServletFilter$1.doFilter(ChainedServletFilter.java:87)
    at org.acegisecurity.ui.AbstractProcessingFilter.doFilter(AbstractProcessingFilter.java:271)
    at hudson.security.ChainedServletFilter$1.doFilter(ChainedServletFilter.java:87)
    at jenkins.security.BasicHeaderProcessor.doFilter(BasicHeaderProcessor.java:93)
    at hudson.security.ChainedServletFilter$1.doFilter(ChainedServletFilter.java:87)
    at org.acegisecurity.context.HttpSessionContextIntegrationFilter.doFilter(HttpSessionContextIntegrationFilter.java:249)
    at hudson.security.HttpSessionContextIntegrationFilter2.doFilter(HttpSessionContextIntegrationFilter2.java:67)
    at hudson.security.ChainedServletFilter$1.doFilter(ChainedServletFilter.java:87)
    at hudson.security.ChainedServletFilter.doFilter(ChainedServletFilter.java:90)
    at hudson.security.HudsonFilter.doFilter(HudsonFilter.java:171)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at org.kohsuke.stapler.compression.CompressionFilter.doFilter(CompressionFilter.java:49)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at hudson.util.CharacterEncodingFilter.doFilter(CharacterEncodingFilter.java:82)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at org.kohsuke.stapler.DiagnosticThreadNameFilter.doFilter(DiagnosticThreadNameFilter.java:30)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:94)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:616)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:620)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:502)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1132)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:684)
    at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.doRun(AprEndpoint.java:2527)
    at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:2516)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)
</code>```

Can somebody assist me with the plugin installation?

答:
This issue comes up when your Jenkins master cannot access the Internet
This can happen due to two common scenarios
 1) Issue with the internet connection to the Jenkins master server
 2) Jenkins Server is behind Proxy

Go to Manage Jenkins > Manage Plugins > Advanced

Jenkins plugin url

Go to advanced option and paste the url and click Test button.
It should return success if everything is fine.
I am unable to include a screenshot here.

Body:
While setting up the Jenkins, I skipped the plugins installation in the wizard. Now I am trying to install it manually. I searched a lot and came to know that I can install it through the web in Manage Jenkins -> Plugin Manager -> Available tab. No plugins are available here. I even typed plugin names in filter but still could not succeed.

Here I am trying to install Git Plugin.

When I click on Check now button, It throws some below Java exception.

Full Stack Trace

sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at sun.security.provider.certpath.SunCertPathBuilder.build(SunCertPathBuilder.java:141)
    at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(SunCertPathBuilder.java:126)
    at java.security.cert.CertPathBuilder.build(CertPathBuilder.java:280)
    at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:382)
Caused: sun.security.validator.ValidatorException: PKIX path building failed
    at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:387)
    at sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:292)
    at sun.security.validator.Validator.validate(Validator.java:260)
    at sun.security.ssl.X509TrustManagerImpl.validate(X509TrustManagerImpl.java:324)
    at sun.security.ssl.X509TrustManagerImpl.checkTrusted(X509TrustManagerImpl.java:229)
    at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:124)
    at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1491)
Caused: javax.net.ssl.SSLHandshakeException
    at sun.security.ssl.Alerts.getSSLException(Alerts.java:192)
    at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1949)
    at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:302)
    at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:296)
    at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1509)
    at sun.security.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:216)
    at sun.security.ssl.Handshaker.processLoop(Handshaker.java:979)
    at sun.security.ssl.Handshaker.process_record(Handshaker.java:914)
    at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1062)
    at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1375)
    at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1403)
    at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1387)
    at sun.net.www.protocol.https.HttpsClient.afterConnect(HttpsClient.java:559)
    at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:185)
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1513)
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1441)
    at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:254)
    at hudson.model.DownloadService.loadJSON(DownloadService.java:167)
    at hudson.model.UpdateSite.updateDirectlyNow(UpdateSite.java:190)
    at hudson.PluginManager.doCheckUpdatesServer(PluginManager.java:1624)
    at java.lang.invoke.MethodHandle.invokeWithArguments(MethodHandle.java:627)
    at org.kohsuke.stapler.Function$MethodFunction.invoke(Function.java:343)
    at org.kohsuke.stapler.interceptor.RequirePOST$Processor.invoke(RequirePOST.java:52)
    at org.kohsuke.stapler.PreInvokeInterceptedFunction.invoke(PreInvokeInterceptedFunction.java:26)
    at org.kohsuke.stapler.Function.bindAndInvoke(Function.java:184)
    at org.kohsuke.stapler.Function.bindAndInvokeAndServeResponse(Function.java:117)
    at org.kohsuke.stapler.MetaClass$1.doDispatch(MetaClass.java:129)
    at org.kohsuke.stapler.NameBasedDispatcher.dispatch(NameBasedDispatcher.java:58)
    at org.kohsuke.stapler.Stapler.tryInvoke(Stapler.java:715)
    at org.kohsuke.stapler.Stapler.invoke(Stapler.java:845)
    at org.kohsuke.stapler.MetaClass$2.doDispatch(MetaClass.java:186)
    at org.kohsuke.stapler.NameBasedDispatcher.dispatch(NameBasedDispatcher.java:58)
    at org.kohsuke.stapler.Stapler.tryInvoke(Stapler.java:715)
    at org.kohsuke.stapler.Stapler.invoke(Stapler.java:845)
    at org.kohsuke.stapler.Stapler.invoke(Stapler.java:649)
    at org.kohsuke.stapler.Stapler.service(Stapler.java:238)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:292)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at hudson.util.PluginServletFilter$1.doFilter(PluginServletFilter.java:135)
    at hudson.util.PluginServletFilter.doFilter(PluginServletFilter.java:138)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at hudson.security.csrf.CrumbFilter.doFilter(CrumbFilter.java:85)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at hudson.security.ChainedServletFilter$1.doFilter(ChainedServletFilter.java:84)
    at hudson.security.UnwrapSecurityExceptionFilter.doFilter(UnwrapSecurityExceptionFilter.java:51)
    at hudson.security.ChainedServletFilter$1.doFilter(ChainedServletFilter.java:87)
    at jenkins.security.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:117)
    at hudson.security.ChainedServletFilter$1.doFilter(ChainedServletFilter.java:87)
    at org.acegisecurity.providers.anonymous.AnonymousProcessingFilter.doFilter(AnonymousProcessingFilter.java:125)
    at hudson.security.ChainedServletFilter$1.doFilter(ChainedServletFilter.java:87)
    at org.acegisecurity.ui.rememberme.RememberMeProcessingFilter.doFilter(RememberMeProcessingFilter.java:142)
    at hudson.security.ChainedServletFilter$1.doFilter(ChainedServletFilter.java:87)
    at org.acegisecurity.ui.AbstractProcessingFilter.doFilter(AbstractProcessingFilter.java:271)
    at hudson.security.ChainedServletFilter$1.doFilter(ChainedServletFilter.java:87)
    at jenkins.security.BasicHeaderProcessor.doFilter(BasicHeaderProcessor.java:93)
    at hudson.security.ChainedServletFilter$1.doFilter(ChainedServletFilter.java:87)
    at org.acegisecurity.context.HttpSessionContextIntegrationFilter.doFilter(HttpSessionContextIntegrationFilter.java:249)
    at hudson.security.HttpSessionContextIntegrationFilter2.doFilter(HttpSessionContextIntegrationFilter2.java:67)
    at hudson.security.ChainedServletFilter$1.doFilter(ChainedServletFilter.java:87)
    at hudson.security.ChainedServletFilter.doFilter(ChainedServletFilter.java:90)
    at hudson.security.HudsonFilter.doFilter(HudsonFilter.java:171)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at org.kohsuke.stapler.compression.CompressionFilter.doFilter(CompressionFilter.java:49)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at hudson.util.CharacterEncodingFilter.doFilter(CharacterEncodingFilter.java:82)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at org.kohsuke.stapler.DiagnosticThreadNameFilter.doFilter(DiagnosticThreadNameFilter.java:30)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:94)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:616)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:620)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:502)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1132)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:684)
    at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.doRun(AprEndpoint.java:2527)
    at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:2516)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)

Can somebody assist me with the plugin installation?


问:
Generation of random numbers but controlling the count of those numbers
If i want to generate 0,1,2 randomly in a 2D matrix but i want to control the count of 0,1,2. Is this can be done by any inbuilt c function??(I am using C and new to programming.)</p>

答:
Let's suppose that you have a 3x3 matrix and you want three each of 0, 1, 2.  The most practical way to do this is to fill in the matrix with the right number of numbers in a non-random way, like

```<code>0 0 0
1 1 1
2 2 2
</code>```

and then use a Fisher-Yates shuffle to put them in a random order.  You will have to implement the shuffle yourself, but you can use rand() in the normal way in your implementation.

This works for any situation where a fixed number of fixed values need to be put into random positions within a list.

Body:
Let's suppose that you have a 3x3 matrix and you want three each of 0, 1, 2.  The most practical way to do this is to fill in the matrix with the right number of numbers in a non-random way, like

0 0 0
1 1 1
2 2 2

and then use a Fisher-Yates shuffle to put them in a random order.  You will have to implement the shuffle yourself, but you can use rand() in the normal way in your implementation.

This works for any situation where a fixed number of fixed values need to be put into random positions within a list.


问:
PHP merge and reorder multidimensional array
I have 2 PHP arrays that look like this..

```<code>$array1
--------
Array
(
    [0] => Array
        (
            [0] => 64
            [1] => Apple
        )

    [1] => Array
        (
            [0] => 22
            [1] => Pear
        )

    [2] => Array
        (
            [0] => 3
            [1] => Raisin
        )

    [3] => Array
        (
            [0] => 15
            [1] => Grape
        )

    [4] => Array
        (
            [0] => 11
            [1] => Banana
        )

    [5] => Array
        (
            [0] => 4
            [1] => Orange
        )
)

$array2
--------
Array
(

    [0] => Array
        (
            [0] => 22
            [1] => Pear
        )

    [1] => Array
        (
            [0] => 11
            [1] => Banana
        )

)
</code>```

I want to merge the arrays together but put the matching items from $array2 at the top so the result would look like this...

```<code>$array3
-------
Array
(

    [0] => Array
        (
            [0] => 22
            [1] => Pear
        )

    [1] => Array
        (
            [0] => 11
            [1] => Banana
        )

    [2] => Array
        (
            [0] => 64
            [1] => Apple
        )

    [3] => Array
        (
            [0] => 3
            [1] => Raisin
        )

    [4] => Array
        (
            [0] => 15
            [1] => Grape
        )

    [5] => Array
        (
            [0] => 4
            [1] => Orange
        )
)
</code>```

I'm not sure how to approach, should I merge the two first and then try and do some ordering, or is there a more efficient approach?

答:
Get the 2nd array and then a rest of the 1st array</p>

```<code>array_merge($arr2, array_udiff($arr1, $arr2, function($i1, $i2) {return $i1[0]-$i2[0];}));
</code>```

Body:
I have 2 PHP arrays that look like this..

$array1
--------
Array
(
    [0] => Array
        (
            [0] => 64
            [1] => Apple
        )

    [1] => Array
        (
            [0] => 22
            [1] => Pear
        )

    [2] => Array
        (
            [0] => 3
            [1] => Raisin
        )

    [3] => Array
        (
            [0] => 15
            [1] => Grape
        )

    [4] => Array
        (
            [0] => 11
            [1] => Banana
        )

    [5] => Array
        (
            [0] => 4
            [1] => Orange
        )
)

$array2
--------
Array
(

    [0] => Array
        (
            [0] => 22
            [1] => Pear
        )

    [1] => Array
        (
            [0] => 11
            [1] => Banana
        )

)

I want to merge the arrays together but put the matching items from $array2 at the top so the result would look like this...

$array3
-------
Array
(

    [0] => Array
        (
            [0] => 22
            [1] => Pear
        )

    [1] => Array
        (
            [0] => 11
            [1] => Banana
        )

    [2] => Array
        (
            [0] => 64
            [1] => Apple
        )

    [3] => Array
        (
            [0] => 3
            [1] => Raisin
        )

    [4] => Array
        (
            [0] => 15
            [1] => Grape
        )

    [5] => Array
        (
            [0] => 4
            [1] => Orange
        )
)

I'm not sure how to approach, should I merge the two first and then try and do some ordering, or is there a more efficient approach?

Body:
Get the 2nd array and then a rest of the 1st array

array_merge($arr2, array_udiff($arr1, $arr2, function($i1, $i2) {return $i1[0]-$i2[0];}));


问:
Python - Input Error
Please could some one explain me why i get this error :

```<code>>>> pnome = input('primeiro nome: ')
primeiro nome: Hugo
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1, in <module>
NameError: name 'Hugo' is not defined
</code>```

Im new to Python.

答: Use pnome = raw_input('primeiro nome: ') Since you are using 2.x python version

Title: Python - Input Error

Body:
Please could some one explain me why i get this error :

>>> pnome = input('primeiro nome: ')
primeiro nome: Hugo
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1, in <module>
NameError: name 'Hugo' is not defined

Im new to Python.


问:
Changing fopen() mode midway through?
I this piece of code:

```<code>$file = fopen($path, 'r+');
flock($file, LOCK_EX);
// reading the file into an array and doing some stuff to it
for ($i=0; $i<count($array); $i++)
  {
  fwrite($file, $array[$i]);
  }
flock($file, LOCK_UN);
fclose($file);
</code>```

Basically what I want to do is: open a file > lock it > read it > do some stuff > clear the file > write to file > unlock it > close it.

The problem is the clearing part. I know I could do it with fopen($file, 'w+') but then reading would be a problem. Maybe I can change the mode somehow?

Any help would be appreciated, Paul

答: You can have separate lock empty file and call flock($file, LOCK_EX); on that file and open another file for writing.</p>

Title: Changing fopen() mode midway through?

Body:
I this piece of code:

$file = fopen($path, 'r+');
flock($file, LOCK_EX);
// reading the file into an array and doing some stuff to it
for ($i=0; $i<count($array); $i++)
  {
  fwrite($file, $array[$i]);
  }
flock($file, LOCK_UN);
fclose($file);

Basically what I want to do is: open a file > lock it > read it > do some stuff > clear the file > write to file > unlock it > close it.

The problem is the clearing part. I know I could do it with fopen($file, 'w+') but then reading would be a problem. Maybe I can change the mode somehow?

Any help would be appreciated, Paul


问:
json must be a str not bytes
def main(target_db):

```<code># get available logs

output = subprocess.Popen(['aws','rds', 'describe-db-log-files', '--db-instance-identifier', target_db],stdout=subprocess.PIPE).communicate()[0]

dict_output = json.loads(output)
log_file_names = map(lambda l:l['LogFileName'], dict_output['DescribeDBLogFiles'])

mkdir_p('logs/error')

# aws rds download-db-log-file-portion --db-instance-identifier prod-api --log-file-name error/postgresql.log.2015-04-20-18 --output text > logs/error/postgresql.log.2015-04-20-18
for log_file_name in log_file_names:
    content = subprocess.Popen(['aws','rds', 'download-db-log-file-portion', '--db-instance-identifier', target_db, '--log-file-name', log_file_name, '--output', 'text'],stdout=subprocess.PIPE).communicate()[0]
    with open('logs/%s' % log_file_name, 'wb') as fw:
        fw.write(content)
</code>```

I am getting an error json must be str not bytes while running the script in line where it loads as a json object  (dict_output = json.loads(output)).

答:
First try to print type like that:

print type(output)

If it isn't string try to convert it to string using this:

output = str(output) or dict_output = json.loads(str(output))

Hope this will help.

Title: json must be a str not bytes

Body:
def main(target_db):

# get available logs

output = subprocess.Popen(['aws','rds', 'describe-db-log-files', '--db-instance-identifier', target_db],stdout=subprocess.PIPE).communicate()[0]

dict_output = json.loads(output)
log_file_names = map(lambda l:l['LogFileName'], dict_output['DescribeDBLogFiles'])

mkdir_p('logs/error')

# aws rds download-db-log-file-portion --db-instance-identifier prod-api --log-file-name error/postgresql.log.2015-04-20-18 --output text > logs/error/postgresql.log.2015-04-20-18
for log_file_name in log_file_names:
    content = subprocess.Popen(['aws','rds', 'download-db-log-file-portion', '--db-instance-identifier', target_db, '--log-file-name', log_file_name, '--output', 'text'],stdout=subprocess.PIPE).communicate()[0]
    with open('logs/%s' % log_file_name, 'wb') as fw:
        fw.write(content)

I am getting an error json must be str not bytes while running the script in line where it loads as a json object  (dict_output = json.loads(output)).