问:
Catching Signals and Pausing with Character Device Drivers
I'm a student new to C Programming and am not fully understanding how signal catching works, and in line with character device drivers.  I'd appreciate some help but I need to state that this is for a project that is due in my first C Programming class.  So I have not posted any direct code, only an example of my initial approach.

My project needs to accept a signal input and set that signal to a variable to pass to my character device driver. Another program I've written will need to access that variable's value such that when read, it performs a certain outcome.  I've tried to run my control program (<name> &) but it quits immediately.  I double check by entering ps into my command prompt and the process is gone.

Basically I need my control program to pause and wait for the signal to be received.  Once received, if the signal matches it will set a variable to its value.  Otherwise, if it is SIGTERM it will either end or pause(), where it will wait until another signal is received that meets another condition.  Currently, when I compile and run it with & it simply runs and quits.  Here is an example of my code:

```<code>#include <stdio.h>
#include <unistd.h>
#include <signal.h>
#include <stdlib.h>

static int file_state;                    //variable to pass to the driver for recording

void sig_handler(int sig);

void sig_handler(int sig){
    while(1){
        if(sig == SIGRTMIN){
            printf("SIG = SIGRTMIN\n");
            file_state = 0;
        }else if(sig == SIGRTMIN+1){
            printf("SIG = SIGRTMIN1\n");
            file_state = 1;
        }else if(sig == SIGTERM){
            printf("Exiting\n");
            exit(0);                         //exit
        }else{
            printf("SIG = %i\n", sig);
            pause();                        //doesn't match, pause for next signal
        }
    }
}

int main(){
    signal(SIGINT, sig_handler);
    //return 0;  //tried with and without
}
</code>```

I'm waiting until this daemon receives a signal to put the device driver into a particular mode.  I haven't entered any write() methods yet because I'm trying to take this one step at a time where I send a signal with kill() and the proper response is returned with printf().
 My problem is that I can't seem to keep this in pause() mode while I'm waiting for a signal that breaks the if loop.  What's worse (other than my lack of knowledge and programming) is that I can't even keep this daemon open long enough to attempt a signal send.  Once I can get this to pause and receive the signal, I plan to use the system write() method to write my file_state variable to the /dev/<filename>, which will be cross-referenced in my executable.

How far off am I?  This is the final part that (I believe) I'm stuck on and I can't figure out how this should be approached.  I've looked online and about 95% of the examples that delve into this contain methods we haven't learned yet.  And if not, the examples are more simplistic where they do not include passing a value to a character device driver for use when another program is using the driver.

Any help is greatly appreciated.

ETA
I've updated my code so now it stays open until a signal is received.  Problem is that I want this to pause() and remain open until the SIGTERM signal is received, breaking the loop and ending the program.  I can't seem to get the loop correct.  Even entering a conditional int variable into the while() loop still is broken when any signal is received.  Here is my updated code below:

```<code>#include <stdio.h>
#include <unistd.h>
#include <signal.h>
#include <stdlib.h>

static int file_state;                    //variable to pass to the driver for recording

int keep_alive = 1;                       //added for conditional checking to keep the while
                                          //loop open to receive more than one signal

void sig_handler(int sig);

void sig_handler(int sig){
    if(sig == SIGRTMIN){
        printf("SIG = SIGRTMIN\n");
        file_state = 0;
    }else if(sig == SIGRTMIN+1){
        printf("SIG = SIGRTMIN1\n");
        file_state = 1;
    }else if(sig == SIGTERM){
        keep_alive = 0;
    }else{
    }
}

int main(){
    do{
        signal(SIGINT, sig_handler);
        pause();                           //thought pausing here would help with waiting for a new signal
    }while(keep_alive == 1);               //keep looping until false
    return 0;                              //tried with and without
}
</code>```

I'm trying to figure out a method to keep this process and signal catching loop alive until a specific signal is received.  I can't figure it out for the life of me.

ETA 2

Discovered my issue.  I wasn't paying attention and fully understanding the signal() method.  The first argument requires the exact signal you are attempting to catch.  I was using SIGINT which I was understanding it to be a "class" of interrupts that you wanted to catch.  And then in the signal_handler() function, you would specify which type of interrupt you were catching.  But, it is actually looking to catch the exact signal you are interested in.  So in my example code, I should have been using:

```<code>int main(){
    if(signal(SIGRMIN, sig_handler) == SIG_ERR){
         printf("can't catch SIGRMIN Signal.\n")
    }
...
}
</code>```

I'm going to update with my new script as an answer and if anyone thinks it should be done differently or have any constructive criticisms please let me know.  Thanks again!

答:
There are 2 parts, 1st user space where generation and catching of signals occurs. This has nothing to do with kernel driver. Your code seems okay about it.

2nd is interacting with driver when signal has been caught. For char driver have a look at this link. You can simply write a value write(fd, 1, &buf); from user space program and implement corresponding write() in char driver.

Body:
I'm a student new to C Programming and am not fully understanding how signal catching works, and in line with character device drivers.  I'd appreciate some help but I need to state that this is for a project that is due in my first C Programming class.  So I have not posted any direct code, only an example of my initial approach.

My project needs to accept a signal input and set that signal to a variable to pass to my character device driver. Another program I've written will need to access that variable's value such that when read, it performs a certain outcome.  I've tried to run my control program (<name> &) but it quits immediately.  I double check by entering ps into my command prompt and the process is gone.

Basically I need my control program to pause and wait for the signal to be received.  Once received, if the signal matches it will set a variable to its value.  Otherwise, if it is SIGTERM it will either end or pause(), where it will wait until another signal is received that meets another condition.  Currently, when I compile and run it with & it simply runs and quits.  Here is an example of my code:

#include <stdio.h>
#include <unistd.h>
#include <signal.h>
#include <stdlib.h>

static int file_state;                    //variable to pass to the driver for recording

void sig_handler(int sig);

void sig_handler(int sig){
    while(1){
        if(sig == SIGRTMIN){
            printf("SIG = SIGRTMIN\n");
            file_state = 0;
        }else if(sig == SIGRTMIN+1){
            printf("SIG = SIGRTMIN1\n");
            file_state = 1;
        }else if(sig == SIGTERM){
            printf("Exiting\n");
            exit(0);                         //exit
        }else{
            printf("SIG = %i\n", sig);
            pause();                        //doesn't match, pause for next signal
        }
    }
}

int main(){
    signal(SIGINT, sig_handler);
    //return 0;  //tried with and without
}

I'm waiting until this daemon receives a signal to put the device driver into a particular mode.  I haven't entered any write() methods yet because I'm trying to take this one step at a time where I send a signal with kill() and the proper response is returned with printf().
 My problem is that I can't seem to keep this in pause() mode while I'm waiting for a signal that breaks the if loop.  What's worse (other than my lack of knowledge and programming) is that I can't even keep this daemon open long enough to attempt a signal send.  Once I can get this to pause and receive the signal, I plan to use the system write() method to write my file_state variable to the /dev/<filename>, which will be cross-referenced in my executable.

How far off am I?  This is the final part that (I believe) I'm stuck on and I can't figure out how this should be approached.  I've looked online and about 95% of the examples that delve into this contain methods we haven't learned yet.  And if not, the examples are more simplistic where they do not include passing a value to a character device driver for use when another program is using the driver.

Any help is greatly appreciated.

ETA
I've updated my code so now it stays open until a signal is received.  Problem is that I want this to pause() and remain open until the SIGTERM signal is received, breaking the loop and ending the program.  I can't seem to get the loop correct.  Even entering a conditional int variable into the while() loop still is broken when any signal is received.  Here is my updated code below:

#include <stdio.h>
#include <unistd.h>
#include <signal.h>
#include <stdlib.h>

static int file_state;                    //variable to pass to the driver for recording

int keep_alive = 1;                       //added for conditional checking to keep the while
                                          //loop open to receive more than one signal

void sig_handler(int sig);

void sig_handler(int sig){
    if(sig == SIGRTMIN){
        printf("SIG = SIGRTMIN\n");
        file_state = 0;
    }else if(sig == SIGRTMIN+1){
        printf("SIG = SIGRTMIN1\n");
        file_state = 1;
    }else if(sig == SIGTERM){
        keep_alive = 0;
    }else{
    }
}

int main(){
    do{
        signal(SIGINT, sig_handler);
        pause();                           //thought pausing here would help with waiting for a new signal
    }while(keep_alive == 1);               //keep looping until false
    return 0;                              //tried with and without
}

I'm trying to figure out a method to keep this process and signal catching loop alive until a specific signal is received.  I can't figure it out for the life of me.

ETA 2

Discovered my issue.  I wasn't paying attention and fully understanding the signal() method.  The first argument requires the exact signal you are attempting to catch.  I was using SIGINT which I was understanding it to be a "class" of interrupts that you wanted to catch.  And then in the signal_handler() function, you would specify which type of interrupt you were catching.  But, it is actually looking to catch the exact signal you are interested in.  So in my example code, I should have been using:

int main(){
    if(signal(SIGRMIN, sig_handler) == SIG_ERR){
         printf("can't catch SIGRMIN Signal.\n")
    }
...
}

I'm going to update with my new script as an answer and if anyone thinks it should be done differently or have any constructive criticisms please let me know.  Thanks again!


来源: stackexchange

问:
Trying to join 2 tables and SUM() time from dates
I am trying to write an SQL query that will create a list of all the books that have been checked out in the past month, and how long each book has been checked out.

I have a books table...

```<code>library6=# SELECT * FROM books;
 isbn |                 title                 |    author
------+---------------------------------------+---------------
  111 | Harry Potter and the Sorcerer’s Stone | JK Rowlings
  222 | The Art of the Deal                   | Trump
  333 | to catch a crook                      | Robert Muller
  444 | Im a cool guy                         | Forrest Stone
  555 | rich i am                             | Bill Gates
(5 rows)
</code>```

and a transactions table with the records of when the books where checked out

```<code>library6=# SELECT * FROM transactions;
 id | checked_out_date | checked_in_date | user_id | isbn
----+------------------+-----------------+---------+------
  1 | 2016-01-01       | 2016-02-01      |       1 |  111
  2 | 2016-02-02       | 2016-03-02      |       2 |  111
  3 | 2016-03-03       | 2016-05-03      |       3 |  111
  4 | 2017-12-06       |                 |       4 |  111
  5 | 2017-11-29       | 2017-12-04      |       5 |  555
  6 | 2017-11-28       | 2017-12-05      |       1 |  333
(6 rows)
</code>```

A few of my nearer misses have been

```<code>library6=# SELECT DISTINCT  books.title, books.author  FROM books LEFT OUTER  JOIN transactions ON books.isbn = transactions.isbn ;
                 title                 |    author
---------------------------------------+---------------
 Harry Potter and the Sorcerer’s Stone | JK Rowlings
 rich i am                             | Bill Gates
 The Art of the Deal                   | Trump
 Im a cool guy                         | Forrest Stone
 to catch a crook                      | Robert Muller
(5 rows)
</code>```

答:
For postgre:

```<code>select b.isbn,
   b.title,
   b.author,
   sum(DATE_PART('day', coalesce(t.checked_in_date, CURRENT_DATE), greatest(t.checked_out_date, CURRENT_DATE+ interval '-1 month'))) days_checked_out
  from books b
  join transactions t on b.isbn = t.isbn
 where t.checked_out_date between CURRENT_DATE+ interval '-1 month' and CURRENT_DATE
    or t.checked_in_date  between CURRENT_DATE+ interval '-1 month' and CURRENT_DATE
 group by b.isbn,
   b.title,
   b.author;
</code>```

You can add left join and coalesce for SUM, if you need also to show books which were not checked out in past month.

ContentLicense: CC BY-SA 3.0

Body:
I am trying to write an SQL query that will create a list of all the books that have been checked out in the past month, and how long each book has been checked out.

I have a books table...

library6=# SELECT * FROM books;
 isbn |                 title                 |    author
------+---------------------------------------+---------------
  111 | Harry Potter and the Sorcerer’s Stone | JK Rowlings
  222 | The Art of the Deal                   | Trump
  333 | to catch a crook                      | Robert Muller
  444 | Im a cool guy                         | Forrest Stone
  555 | rich i am                             | Bill Gates
(5 rows)

and a transactions table with the records of when the books where checked out

library6=# SELECT * FROM transactions;
 id | checked_out_date | checked_in_date | user_id | isbn
----+------------------+-----------------+---------+------
  1 | 2016-01-01       | 2016-02-01      |       1 |  111
  2 | 2016-02-02       | 2016-03-02      |       2 |  111
  3 | 2016-03-03       | 2016-05-03      |       3 |  111
  4 | 2017-12-06       |                 |       4 |  111
  5 | 2017-11-29       | 2017-12-04      |       5 |  555
  6 | 2017-11-28       | 2017-12-05      |       1 |  333
(6 rows)

A few of my nearer misses have been

library6=# SELECT DISTINCT  books.title, books.author  FROM books LEFT OUTER  JOIN transactions ON books.isbn = transactions.isbn ;
                 title                 |    author
---------------------------------------+---------------
 Harry Potter and the Sorcerer’s Stone | JK Rowlings
 rich i am                             | Bill Gates
 The Art of the Deal                   | Trump
 Im a cool guy                         | Forrest Stone
 to catch a crook                      | Robert Muller
(5 rows)

Body:
For postgre:

select b.isbn,
   b.title,
   b.author,
   sum(DATE_PART('day', coalesce(t.checked_in_date, CURRENT_DATE), greatest(t.checked_out_date, CURRENT_DATE+ interval '-1 month'))) days_checked_out
  from books b
  join transactions t on b.isbn = t.isbn
 where t.checked_out_date between CURRENT_DATE+ interval '-1 month' and CURRENT_DATE
    or t.checked_in_date  between CURRENT_DATE+ interval '-1 month' and CURRENT_DATE
 group by b.isbn,
   b.title,
   b.author;

You can add left join and coalesce for SUM, if you need also to show books which were not checked out in past month.


问:
How is called use of duck typing
How should I call process of using duck typing? What should I say "I'm performing duck typing" or "I'm checking if it's a duck:)".

Duck checking doesn't sounds good and type checking is just plain wrong name for it.

答:
I think context matters here, are we talking about inline comments or overall design documents?

For design documents I think it's quite reasonable to say I am using duck typing.

At a given point in the code I'm not sure that it's useful to say that. Consider, using some  fictional language

```<code> function wibble(anObject) {

      // what do we say here?
      anObject.computeMedianValue();

      anObject.render(device);
 }
</code>```

First note that we don't actually check it's a duck, in the examples I see the code just goes

```<code> obj.quack()
</code>```

The program structure usually arranges that only things that can quack get passed down. I don't see many examples of

```<code>if (obj can quack )
  obj.quack()
else if ( obj can grunt)
  obj.grunt()
</code>```

that wouldn't be very polymorphic, but even if we did want to check the capabilities we very much do not write code

```<code>if ( obj isA duck)
</code>```

the whole idea of duck typing is that we consider the specific capabilities we need in the current context -  walk (like a duck) , quack (like a duck) - not "is it a duck?"

So in the code I would not particularly reference duck typing, any more than I sprinkle I'm doing object orientation around a standard Java program. The comment might say why you know that that object can compute a median, or what to do if it can't.

ContentLicense: CC BY-SA 2.5

Title: How is called use of duck typing

Body:
I think context matters here, are we talking about inline comments or overall design documents?

For design documents I think it's quite reasonable to say I am using duck typing.

At a given point in the code I'm not sure that it's useful to say that. Consider, using some  fictional language

 function wibble(anObject) {

      // what do we say here?
      anObject.computeMedianValue();

      anObject.render(device);
 }

First note that we don't actually check it's a duck, in the examples I see the code just goes

 obj.quack()

The program structure usually arranges that only things that can quack get passed down. I don't see many examples of

if (obj can quack )
  obj.quack()
else if ( obj can grunt)
  obj.grunt()

that wouldn't be very polymorphic, but even if we did want to check the capabilities we very much do not write code

if ( obj isA duck)

the whole idea of duck typing is that we consider the specific capabilities we need in the current context -  walk (like a duck) , quack (like a duck) - not "is it a duck?"

So in the code I would not particularly reference duck typing, any more than I sprinkle I'm doing object orientation around a standard Java program. The comment might say why you know that that object can compute a median, or what to do if it can't.


问:
I implement SIPO shift register by using verilog, but unknown error comes out
Main file

```<code>module D_ff (q, D, Clk, Reset);
    input Clk, D, Reset;
    output q;
    always @ (posedge Clk);
        and(q, D, Reset);
endmodule

module SIPO(Clk, Reset, Data, Out1, Out2, Out3, Out4);
    input Clk, Reset, Data;
    output Out1, Out2, Out3, Out4;
    begin
    D_ff sr0 (Out0, Data, Clk, Reset);
    D_ff sr1 (Out1, Out0, Clk, Reset);
    D_ff sr2 (Out2, Out1, Clk, Reset);
    D_ff sr3 (Out3, Out2, Clk, Reset);
    end
endmodule
</code>```

Testbench file

```<code> 'timescale 1ps/1ps

    module tb_SIPO;
        reg Clk, Reset, Data;
        wire Out1, Out2, Out3, Out4;

        SIPO(Clk, Reset, Data, Out1, Out2, Out3, Out4);

        initial
        Clk=0;
        always #11 Clk=~Clk;
        Reset=1; Data=0;
        initial begin
            #15 Reset=1; Data=1;
            #20 Reset=1; Data=0;
            #30 Reset=1; Data=0;
            #10 Reset=0; Data=1;
            #20 Reset=0; Data=0;
            #5 Reset=0; Data=0;
            #20 Reset=0; Data=0;
            #20 Reset=0; Data=0;
            #20 Reset=0; Data=0;
            #20 Reset=0; Data=0;
            #70 Reset=0; Data=0;
            #5 $finish;
        end

    endmodule
</code>```

Error: (vlog-13053) C:/Modeltech_pe_edu_10.4a/examples/tb_sipo.v(1): near >"'t": Illegal base specifier in numeric constant.

** Error: (vlog-13069) C:/Modeltech_pe_edu_10.4a/examples/tb_sipo.v(1): near >"'t": syntax error, unexpected BASE, expecting class.

I don't know what the error means. there is no 't' in my program and I can't see any illegal base specifier.
What's wrong with this?

答:
You've used timescale for specifying the reference time unit for the simulator. But it should be:

```<code>`timescale
</code>```

and not:

```<code>'timescale
</code>```

' is used to specify numbers in Verilog, e.g. 8'hFF. That's why compiler is looking for a numeric constant.

Body:
Main file

module D_ff (q, D, Clk, Reset);
    input Clk, D, Reset;
    output q;
    always @ (posedge Clk);
        and(q, D, Reset);
endmodule

module SIPO(Clk, Reset, Data, Out1, Out2, Out3, Out4);
    input Clk, Reset, Data;
    output Out1, Out2, Out3, Out4;
    begin
    D_ff sr0 (Out0, Data, Clk, Reset);
    D_ff sr1 (Out1, Out0, Clk, Reset);
    D_ff sr2 (Out2, Out1, Clk, Reset);
    D_ff sr3 (Out3, Out2, Clk, Reset);
    end
endmodule

Testbench file

 'timescale 1ps/1ps

    module tb_SIPO;
        reg Clk, Reset, Data;
        wire Out1, Out2, Out3, Out4;

        SIPO(Clk, Reset, Data, Out1, Out2, Out3, Out4);

        initial
        Clk=0;
        always #11 Clk=~Clk;
        Reset=1; Data=0;
        initial begin
            #15 Reset=1; Data=1;
            #20 Reset=1; Data=0;
            #30 Reset=1; Data=0;
            #10 Reset=0; Data=1;
            #20 Reset=0; Data=0;
            #5 Reset=0; Data=0;
            #20 Reset=0; Data=0;
            #20 Reset=0; Data=0;
            #20 Reset=0; Data=0;
            #20 Reset=0; Data=0;
            #70 Reset=0; Data=0;
            #5 $finish;
        end

    endmodule

Error: (vlog-13053) C:/Modeltech_pe_edu_10.4a/examples/tb_sipo.v(1): near >"'t": Illegal base specifier in numeric constant.

** Error: (vlog-13069) C:/Modeltech_pe_edu_10.4a/examples/tb_sipo.v(1): near >"'t": syntax error, unexpected BASE, expecting class.

I don't know what the error means. there is no 't' in my program and I can't see any illegal base specifier.
What's wrong with this?

Body:
You've used timescale for specifying the reference time unit for the simulator. But it should be:

`timescale

and not:

'timescale

' is used to specify numbers in Verilog, e.g. 8'hFF. That's why compiler is looking for a numeric constant.


问:
The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)
After signing the third parties assemblies and adding them to GAC I am getting the below error: also the Assembly Binder Log Entry shows this error

It says mismatching assemblies not sure how mistnaching as I deleted all obj and bin fold and batch built the application + reimported the dlls.

```<code> Assembly manager loaded from:  C:\Windows\Microsoft.NET\Framework\v4.0.30319\clr.dll
Running under executable  C:\Program Files (x86)\Common Files\Microsoft Shared\DevServer\11.0\WebDev.WebServer40.exe

--- A detailed error log follows.
=== Pre-bind state information ===
LOG: User = AKBARCA\user

LOG: DisplayName = ClubStarterKit.Core, Version=3.0.1.0, Culture=neutral, PublicKeyToken=null
 (Fully-specified)

LOG: Appbase =

file:///C:/Users/user/Desktop/NhibernateMediumTrust/NhibernateMediumUpgrade/direct/clubstar

terkit v3 preview/ClubStarterKit.Web/

LOG: DEVPATH = C:\ProgramData\Red Gate\.NET Reflector\DevPath

LOG: Initial PrivatePath =

C:\Users\user\Desktop\NhibernateMediumTrust\NhibernateMediumUpgrade\direct\clubstarterkit v3 preview\ClubStarterKit.Web\bin
Calling assembly : ClubStarterKit.Web, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null.
</code>```

答:
I had a different cause: in my case, I had used various nuget package versions previously, and I had an app.config which for some reason had been automatically generated with this kind of content:

```<code>  <dependentAssembly>
    <assemblyIdentity name="Microsoft.Extensions.DependencyInjection" publicKeyToken="adb9793829ddae60" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-1.1.1.0" newVersion="1.1.1.0" />
  </dependentAssembly>
</code>```

So I only had Version 1.1.0.0 installed, but because of this redirect instruction, it looked for 1.1.1.0 even though Visual Studio had the nuget for 1.1.0.0 installed. Changing the newVersion to 1.1.0.0 fixed everything:

```<code>  <dependentAssembly>
    <assemblyIdentity name="Microsoft.Extensions.DependencyInjection" publicKeyToken="adb9793829ddae60" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-1.1.1.0" newVersion="1.1.0.0" />
  </dependentAssembly>
</code>```

Body:
After signing the third parties assemblies and adding them to GAC I am getting the below error: also the Assembly Binder Log Entry shows this error

It says mismatching assemblies not sure how mistnaching as I deleted all obj and bin fold and batch built the application + reimported the dlls.

 Assembly manager loaded from:  C:\Windows\Microsoft.NET\Framework\v4.0.30319\clr.dll
Running under executable  C:\Program Files (x86)\Common Files\Microsoft Shared\DevServer\11.0\WebDev.WebServer40.exe

--- A detailed error log follows.
=== Pre-bind state information ===
LOG: User = AKBARCA\user

LOG: DisplayName = ClubStarterKit.Core, Version=3.0.1.0, Culture=neutral, PublicKeyToken=null
 (Fully-specified)

LOG: Appbase =

file:///C:/Users/user/Desktop/NhibernateMediumTrust/NhibernateMediumUpgrade/direct/clubstar

terkit v3 preview/ClubStarterKit.Web/

LOG: DEVPATH = C:\ProgramData\Red Gate\.NET Reflector\DevPath

LOG: Initial PrivatePath =

C:\Users\user\Desktop\NhibernateMediumTrust\NhibernateMediumUpgrade\direct\clubstarterkit v3 preview\ClubStarterKit.Web\bin
Calling assembly : ClubStarterKit.Web, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null.

Body:
I had a different cause: in my case, I had used various nuget package versions previously, and I had an app.config which for some reason had been automatically generated with this kind of content:

  <dependentAssembly>
    <assemblyIdentity name="Microsoft.Extensions.DependencyInjection" publicKeyToken="adb9793829ddae60" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-1.1.1.0" newVersion="1.1.1.0" />
  </dependentAssembly>

So I only had Version 1.1.0.0 installed, but because of this redirect instruction, it looked for 1.1.1.0 even though Visual Studio had the nuget for 1.1.0.0 installed. Changing the newVersion to 1.1.0.0 fixed everything:

  <dependentAssembly>
    <assemblyIdentity name="Microsoft.Extensions.DependencyInjection" publicKeyToken="adb9793829ddae60" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-1.1.1.0" newVersion="1.1.0.0" />
  </dependentAssembly>


问:
firebase-admin error No Firebase app named '[DEFAULT]' exists
With the new firebase-admin for NodeJS I get firebase-admin error No Firebase app named '" + appName + "' exists error with old and new credentials and the 2 different styles to initializeApp

```<code>Error: No Firebase app named '[DEFAULT]' exists.

    var admin = require("firebase-admin");
    var db = admin.database();
    var ref = db.ref();

    admin.initializeApp({
    credential: admin.credential.cert({
        projectId: "projectId",
        clientEmail: "firebase-adminsdk@iam.gserviceaccount.com",
        privateKey: "-----BEGIN PRIVATE KEY-----\nMIIEvgIBADANBgkqhuPuR\nDAoyxH9OiC1CaSJ8/GquyVvQGvCcsXQAGh2LX2uSXKzycuDGAoUkb2Nhc4dk0/Nm\nLNudSRHCku2h2df0v7z65YXt\n-----END PRIVATE KEY-----\n"
    }),
    databaseURL: process.env.DATABASEURL
});
</code>```

node_modules/firebase-
admin/lib/firebase-namespace.js:52:19

答:
```<code>const adm = require ('firebase-admin');
adm.initializeApp(func.config().firebase);
</code>```

This is one way of initializing your firebase database doing which you can clear the above error.

Body:
With the new firebase-admin for NodeJS I get firebase-admin error No Firebase app named '" + appName + "' exists error with old and new credentials and the 2 different styles to initializeApp

Error: No Firebase app named '[DEFAULT]' exists.

    var admin = require("firebase-admin");
    var db = admin.database();
    var ref = db.ref();

    admin.initializeApp({
    credential: admin.credential.cert({
        projectId: "projectId",
        clientEmail: "firebase-adminsdk@iam.gserviceaccount.com",
        privateKey: "-----BEGIN PRIVATE KEY-----\nMIIEvgIBADANBgkqhuPuR\nDAoyxH9OiC1CaSJ8/GquyVvQGvCcsXQAGh2LX2uSXKzycuDGAoUkb2Nhc4dk0/Nm\nLNudSRHCku2h2df0v7z65YXt\n-----END PRIVATE KEY-----\n"
    }),
    databaseURL: process.env.DATABASEURL
});

node_modules/firebase-
admin/lib/firebase-namespace.js:52:19

Body:
const adm = require ('firebase-admin');
adm.initializeApp(func.config().firebase);

This is one way of initializing your firebase database doing which you can clear the above error.


问:
php show array value for variable key
I am trying to make a site multi lingual. by building a language dictionary array ( if it is not the best way please don't hesitate to let me know )

```<code>$fr=array();

$fr['hello']="Bonjour";
</code>```

I would like to make a function that does the following :

for every word and language  function ( $word ="hello",$language="fr")

it would return the right value. So far the way I am doing isn't working

```<code>echo $$language[$word];
</code>```

any ideas?
thank you

答:
A few things to mention here...

I would recommend using actual "locales" (a language code plus country code) to reference your languages rather than your two letter country code.  Your example includes "fr" for French.  Typical convention is to use locale names instead.  For example fr_FR for French (France) and fr_CA for French (Canadien).  Language can very greatly based on country (if you're a native US English speaker and take a trip to Australia, you'll understand what I'm talking about).

Depending on the size of your site, you probably don't want to keep this as a PHP dictionary/assoc array.  There are lots of options here (putting translations in a database, shared memory, etc.).  If you do keep it in PHP memory, opcode caching would be a great idea and is relatively easy to setup.  I would encourage you to look at how other frameworks achieve this (and ideally maybe use an existing framework to achieve this).

You mention translating "words".  Generally, when internationalizing a site, you want to translate phrases.  Translating words and then gluing them together typically results in poor translations.

If you do stick with the dict route, I would highly encourage you to drop the dynamic interpretation of the the variable name/language name in favor of a nested associative array.  For example $dict['fr_FR']['hello'] = 'bonjour';

Title: php show array value for variable key

Body:
I am trying to make a site multi lingual. by building a language dictionary array ( if it is not the best way please don't hesitate to let me know )

$fr=array();

$fr['hello']="Bonjour";

I would like to make a function that does the following :

for every word and language  function ( $word ="hello",$language="fr")

it would return the right value. So far the way I am doing isn't working

echo $$language[$word];

any ideas?
thank you


问:
How to make my flex children fit into two rows?
I have a total of 8 images that I need to split up into 2 rows. These are under the .card group. They have to have equal spacing and alignment with the top corners. I am having some trouble setting this up with flex commands.

```<code>.cards {
    display: flex;
}

.card {
    width: 24%;
    background: white;
    margin-bottom: 2em;
    padding: 0;
    flex: 0 1 auto
}
</code>```

答:
Try this</p>

```<code>.cards {
    display: flex;
    flex-flow: row-wrap;
}

.card {
    background: white;
    margin-bottom: 2em;
    padding: 0;
    flex: 1 1 24%; /* Assume there are some margins */
}
</code>```

Body:
I have a total of 8 images that I need to split up into 2 rows. These are under the .card group. They have to have equal spacing and alignment with the top corners. I am having some trouble setting this up with flex commands.

.cards {
    display: flex;
}

.card {
    width: 24%;
    background: white;
    margin-bottom: 2em;
    padding: 0;
    flex: 0 1 auto
}

Body:
Try this

.cards {
    display: flex;
    flex-flow: row-wrap;
}

.card {
    background: white;
    margin-bottom: 2em;
    padding: 0;
    flex: 1 1 24%; /* Assume there are some margins */
}


问:
What is the best way to wait for a task to finish with respect to .NET?
This is our async method which executes for a long time in a Task.

```<code>public async Task<int> LongRunningMethod(T p1, T p2, T p3);
</code>```

Some developers in my team use

```<code>Task t = Task.Factory.StartNew(LongRunningMethod(p1,p2,p3));
t.Wait();  //This will suspend main thread and wait for 't' to finish.
</code>```

While some use

```<code>await LongRunningMethod(p1,p2,p3);
// Here too, we simply 'await' till the method finishes.
</code>```

Note: We have a asynchronous task and we want to wait till that task gets completed.

In short, Which one is the best among the above two constructs ?

答:
In short, Which one is the best among the above two constructs ?

You will know the impact, when system scalability comes in the picture, difference between Task.Wait() and await Task is way they treat the calling / executing thread. When the first one would block till the completion happens, other one using await would free up the caller, but mind it only for a True Asynchronous call, which would mean a IO call, Network call, Database call which is not in memory logical processing, and expose Async APIs, that's when calling thread or the context is freed up. For a true Async call, it would use IO completion ports (queuing mechanism) in windows, to execute the Async pipeline.

This would not happen if at the end of the call chain final method is not true Async.

They look almost similar Wait and await

Indeed, for both continuation will execute post completion, but let's take an example, normally threads getting processed are directly linked to the number of cores in the system, using TPL these thread are invoked from a pool and there are limit to number of thread available. For a high scalable system like 100 K / sec requests, Task.Wait() would time out for a long running method very quickly, as threads are busy idling around and blocked and they will not take new request, but for await no such blockage happens at all.

Practical examples

Javascript, NodeJs always go for Async requests by default, no blocking, which is reason why the systems are highly scalable

Also consider ConfigureAwait(false), along with await, then it will not look for same thread context to re-enter for the continuation to execute, which is much more efficient

Body:
This is our async method which executes for a long time in a Task.

public async Task<int> LongRunningMethod(T p1, T p2, T p3);

Some developers in my team use

Task t = Task.Factory.StartNew(LongRunningMethod(p1,p2,p3));
t.Wait();  //This will suspend main thread and wait for 't' to finish.

While some use

await LongRunningMethod(p1,p2,p3);
// Here too, we simply 'await' till the method finishes.

Note: We have a asynchronous task and we want to wait till that task gets completed.

In short, Which one is the best among the above two constructs ?


问:
RecyclerView addInArray error when adding
When I add in List<OrderList> any item in loadOrdersData(), it throws this:

D/ViewGroup: addInArray been called, this = android.support.v7.widget.RecyclerView {41cab8f0 VFED.... .F....ID 0,0-480,770 #7f0c0073 app:id/rv}call stack = java.lang.Throwable: addInArray at android.view.ViewGroup.addInArray(ViewGroup.java:3786) at android.view.ViewGroup.addViewInner(ViewGroup.java:3740) at android.view.ViewGroup.addView(ViewGroup.java:3564) at android.view.ViewGroup.addView(ViewGroup.java:3509) at android.support.v7.widget.RecyclerView$5.addView(RecyclerView.java:649) at android.support.v7.widget.ChildHelper.addView(ChildHelper.java:107) at android.support.v7.widget.RecyclerView$LayoutManager.addViewInt(RecyclerView.java:7115) at android.support.v7.widget.RecyclerView$LayoutManager.addView(RecyclerView.java:7073) at android.support.v7.widget.RecyclerView$LayoutManager.addView(RecyclerView.java:7061) at android.support.v7.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1428) at android.support.v7.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1377) at android.support.v7.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:578) at android.support.v7.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:3315) at android.support.v7.widget.RecyclerView.dispatchLayout(RecyclerView.java:3124)  at android.support.v7.widget.RecyclerView.onLayout(RecyclerView.java:3568) at android.view.View.layout(View.java:15125) at android.view.ViewGroup.layout(ViewGroup.java:4862) at android.support.v4.widget.DrawerLayout.onLayout(DrawerLayout.java:1197) at android.view.View.layout(View.java:15125) at android.view.ViewGroup.layout(ViewGroup.java:4862) at android.widget.FrameLayout.layoutChildren(FrameLayout.java:515) at android.widget.FrameLayout.onLayout(FrameLayout.java:450) at android.view.View.layout(View.java:15125) at android.view.ViewGroup.layout(ViewGroup.java:4862) at android.support.v7.widget.ActionBarOverlayLayout.onLayout(ActionBarOverlayLayout.java:433) at android.view.View.layout(View.java:15125) at android.view.ViewGroup.layout(ViewGroup.java:4862) at android.widget.FrameLayout.layoutChildren(FrameLayout.java:515) at android.widget.FrameLayout.onLayout(FrameLayout.java:450) at android.view.View.layout(View.java:15125) at android.view.ViewGroup.layout(ViewGroup.java:4862) at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1888) at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1742) at android.widget.LinearLayout.onLayout(LinearLayout.java:1651) at android.view.View.layout(View.java:15125) at android.view.ViewGroup.layout(ViewGroup.java:4862) at android.widget.FrameLayout.layoutChildren(FrameLayout.java:515) at android.widget.FrameLayout.onLayout(FrameLayout.java:450) at android.view.View.layout(View.java:15125) at android.view.ViewGroup.layout(ViewGroup.java:4862) at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2323) at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2029) at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1192) at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6231) at android.view.Choreographer$CallbackRecord.run(Choreographer.java:788) at android.view.Choreographer.doCallbacks(Choreographer.java:591) at android.view.Choreographer.doFrame(Choreographer.java:560) at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:774) at android.os.Handler.handleCallback(Handler.java:808) at android.os.Handler.dispatchMessage(Handler.java:103) at android.os.Looper.loop(Looper.java:193) at android.app.ActivityThread.main(ActivityThread.java:5305) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:515) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:824) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:640) at dalvik.system.NativeStart.main(Native Method)

I tried adding: adapter.notifyDataSetChanged(); before setAdapter() in loadOrdersData() but it makes no sense. Does anyone see what it is caused by?

Here's the code:

MainActivity:

```<code>public class CourierActivity extends AppCompatActivity {
    private TableLayout orderTable;
    private RecyclerView recyclerView;
    private RecycleAdapter adapter;
    private List<OrderListItem> listItems;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.courier_main);

        recyclerView = (RecyclerView) findViewById(R.id.rv);
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(CourierActivity.this));
        adapter = new RecycleAdapter(listItems, getApplicationContext());
        recyclerView.setAdapter(adapter);
        loadOrdersData();
    }

    private void loadOrdersData() {
        RequestQueue queue = Volley.newRequestQueue(this);
        StringRequest sr = new StringRequest(Request.Method.GET, URL, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                listItems = new ArrayList<>();

                try {
                    String rsp = new String(response.getBytes("ISO-8859-1"), "UTF-8");
                    JSONArray orders = new JSONArray(rsp);

                    for (int i = 0; i < orders.length(); i++) {
                        OrderListItem listItem = new OrderListItem(
                                // ..
                        );

                        listItems.add(listItem);
                    }

                    adapter = new RecycleAdapter(listItems, getApplicationContext());
                    recyclerView.setAdapter(adapter);
                } catch (JSONException | UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT);
            }
        }) {

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> params = new HashMap<String, String>();
                return params;
            }
        };

        queue.add(sr);
    }
}
</code>```

OrderListItem:

```<code>public class OrderListItem {
    private String name;
    private String status;
    private String price;
    private String courier;

    public OrderListItem(String name, String status, String price, String courier) {
        this.name = name;
        this.status = status;
        this.price = price;
        this.courier = courier;
    }

    public String getName() { return name; }

    public String getStatus() { return status;}

    public String getPrice() { return price; }

    public String getCourier() { return courier; }
}
</code>```

RecycleAdapter:

```<code>public class RecycleAdapter extends RecyclerView.Adapter<RecycleAdapter.ViewHolder> {

    private List<OrderListItem> listItems;
    private Context context;

    public RecycleAdapter(List<OrderListItem> listItems, Context context) {
        this.listItems = listItems;
        this.context = context;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.rv_item, parent, false);

        return new ViewHolder(v);
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        OrderListItem listItem = listItems.get(position);

        holder.TextViewName.setText(listItem.getName());
        holder.TextViewStatus.setText(listItem.getStatus());
        holder.TextViewPrice.setText(listItem.getPrice());
        holder.TextViewCourier.setText(listItem.getCourier());
    }

    @Override
    public int getItemCount() {
        int count = 0;

        if (listItems != null && !listItems.isEmpty()) {
            count = listItems.size();
        }

        return count;
    }

    public class ViewHolder extends RecyclerView.ViewHolder {

        public TextView TextViewName;
        public TextView TextViewStatus;
        public TextView TextViewPrice;
        public TextView TextViewCourier;

        public ViewHolder(View itemView) {
            super(itemView);

            TextViewName = (TextView) itemView.findViewById(R.id.orderListName);
            TextViewStatus = (TextView) itemView.findViewById(R.id.orderListStatus);
            TextViewPrice = (TextView) itemView.findViewById(R.id.orderListPrice);
            TextViewCourier = (TextView) itemView.findViewById(R.id.orderListCourier);
        }
    }

}
</code>```

@layout/rv_item.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <android.support.v7.widget.CardView xmlns:card_view="http://schemas.android.com/apk/res-auto"
        android:layout_margin="@dimen/activity_horizontal_margin"
        android:layout_height="wrap_content"
        android:layout_width="match_parent">

        <LinearLayout
            android:padding="@dimen/activity_horizontal_margin"
            android:orientation="vertical"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <TextView
                android:id="@+id/orderListName"
                android:text="Order name"
                android:textAppearance="@style/Base.TextAppearance.AppCompat.Large"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />

            <TextView
                android:id="@+id/orderListStatus"
                android:text="Status"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />

            <TextView
                android:id="@+id/orderListPrice"
                android:text="Price"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />

            <TextView
                android:id="@+id/orderListCourier"
                android:text="Courier"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />
        </LinearLayout>

    </android.support.v7.widget.CardView>

</LinearLayout>
</code>```

@layout/main.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    tools:context="com.example.seether.myapplication.CourierActivity"
    android:background="#fff"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/drawerLayout">

    <android.support.v7.widget.RecyclerView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/rv"/>

</android.support.v4.widget.DrawerLayout>
</code>```

EDIT. Works perfect without log's warnings if I enter custom data into listItems.

答:
Don't pass the list object from activity to adapter. Instead have a separate array list in adapter.
Change your adapter constructor to this:

```<code>     public RecycleAdapter(List<OrderListItem> listItems, Context context) {
         this.listItems = new ArrayList<>(listItems);
         this.context = context;
    }
</code>```

And as Maddy suggested use a setMethod in adapter passing the listitem array and adding all items to it and calling notifyDataSetChanged.

I guess this should solve your problem when you don't use the same listitems object in activity and adapter.

Body:
When I add in List<OrderList> any item in loadOrdersData(), it throws this:

D/ViewGroup: addInArray been called, this = android.support.v7.widget.RecyclerView {41cab8f0 VFED.... .F....ID 0,0-480,770 #7f0c0073 app:id/rv}call stack = java.lang.Throwable: addInArray at android.view.ViewGroup.addInArray(ViewGroup.java:3786) at android.view.ViewGroup.addViewInner(ViewGroup.java:3740) at android.view.ViewGroup.addView(ViewGroup.java:3564) at android.view.ViewGroup.addView(ViewGroup.java:3509) at android.support.v7.widget.RecyclerView$5.addView(RecyclerView.java:649) at android.support.v7.widget.ChildHelper.addView(ChildHelper.java:107) at android.support.v7.widget.RecyclerView$LayoutManager.addViewInt(RecyclerView.java:7115) at android.support.v7.widget.RecyclerView$LayoutManager.addView(RecyclerView.java:7073) at android.support.v7.widget.RecyclerView$LayoutManager.addView(RecyclerView.java:7061) at android.support.v7.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1428) at android.support.v7.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1377) at android.support.v7.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:578) at android.support.v7.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:3315) at android.support.v7.widget.RecyclerView.dispatchLayout(RecyclerView.java:3124)  at android.support.v7.widget.RecyclerView.onLayout(RecyclerView.java:3568) at android.view.View.layout(View.java:15125) at android.view.ViewGroup.layout(ViewGroup.java:4862) at android.support.v4.widget.DrawerLayout.onLayout(DrawerLayout.java:1197) at android.view.View.layout(View.java:15125) at android.view.ViewGroup.layout(ViewGroup.java:4862) at android.widget.FrameLayout.layoutChildren(FrameLayout.java:515) at android.widget.FrameLayout.onLayout(FrameLayout.java:450) at android.view.View.layout(View.java:15125) at android.view.ViewGroup.layout(ViewGroup.java:4862) at android.support.v7.widget.ActionBarOverlayLayout.onLayout(ActionBarOverlayLayout.java:433) at android.view.View.layout(View.java:15125) at android.view.ViewGroup.layout(ViewGroup.java:4862) at android.widget.FrameLayout.layoutChildren(FrameLayout.java:515) at android.widget.FrameLayout.onLayout(FrameLayout.java:450) at android.view.View.layout(View.java:15125) at android.view.ViewGroup.layout(ViewGroup.java:4862) at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1888) at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1742) at android.widget.LinearLayout.onLayout(LinearLayout.java:1651) at android.view.View.layout(View.java:15125) at android.view.ViewGroup.layout(ViewGroup.java:4862) at android.widget.FrameLayout.layoutChildren(FrameLayout.java:515) at android.widget.FrameLayout.onLayout(FrameLayout.java:450) at android.view.View.layout(View.java:15125) at android.view.ViewGroup.layout(ViewGroup.java:4862) at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2323) at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2029) at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1192) at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6231) at android.view.Choreographer$CallbackRecord.run(Choreographer.java:788) at android.view.Choreographer.doCallbacks(Choreographer.java:591) at android.view.Choreographer.doFrame(Choreographer.java:560) at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:774) at android.os.Handler.handleCallback(Handler.java:808) at android.os.Handler.dispatchMessage(Handler.java:103) at android.os.Looper.loop(Looper.java:193) at android.app.ActivityThread.main(ActivityThread.java:5305) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:515) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:824) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:640) at dalvik.system.NativeStart.main(Native Method)

I tried adding: adapter.notifyDataSetChanged(); before setAdapter() in loadOrdersData() but it makes no sense. Does anyone see what it is caused by?

Here's the code:

MainActivity:

public class CourierActivity extends AppCompatActivity {
    private TableLayout orderTable;
    private RecyclerView recyclerView;
    private RecycleAdapter adapter;
    private List<OrderListItem> listItems;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.courier_main);

        recyclerView = (RecyclerView) findViewById(R.id.rv);
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(CourierActivity.this));
        adapter = new RecycleAdapter(listItems, getApplicationContext());
        recyclerView.setAdapter(adapter);
        loadOrdersData();
    }

    private void loadOrdersData() {
        RequestQueue queue = Volley.newRequestQueue(this);
        StringRequest sr = new StringRequest(Request.Method.GET, URL, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                listItems = new ArrayList<>();

                try {
                    String rsp = new String(response.getBytes("ISO-8859-1"), "UTF-8");
                    JSONArray orders = new JSONArray(rsp);

                    for (int i = 0; i < orders.length(); i++) {
                        OrderListItem listItem = new OrderListItem(
                                // ..
                        );

                        listItems.add(listItem);
                    }

                    adapter = new RecycleAdapter(listItems, getApplicationContext());
                    recyclerView.setAdapter(adapter);
                } catch (JSONException | UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT);
            }
        }) {

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> params = new HashMap<String, String>();
                return params;
            }
        };

        queue.add(sr);
    }
}

OrderListItem:

public class OrderListItem {
    private String name;
    private String status;
    private String price;
    private String courier;

    public OrderListItem(String name, String status, String price, String courier) {
        this.name = name;
        this.status = status;
        this.price = price;
        this.courier = courier;
    }

    public String getName() { return name; }

    public String getStatus() { return status;}

    public String getPrice() { return price; }

    public String getCourier() { return courier; }
}

RecycleAdapter:

public class RecycleAdapter extends RecyclerView.Adapter<RecycleAdapter.ViewHolder> {

    private List<OrderListItem> listItems;
    private Context context;

    public RecycleAdapter(List<OrderListItem> listItems, Context context) {
        this.listItems = listItems;
        this.context = context;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.rv_item, parent, false);

        return new ViewHolder(v);
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        OrderListItem listItem = listItems.get(position);

        holder.TextViewName.setText(listItem.getName());
        holder.TextViewStatus.setText(listItem.getStatus());
        holder.TextViewPrice.setText(listItem.getPrice());
        holder.TextViewCourier.setText(listItem.getCourier());
    }

    @Override
    public int getItemCount() {
        int count = 0;

        if (listItems != null && !listItems.isEmpty()) {
            count = listItems.size();
        }

        return count;
    }

    public class ViewHolder extends RecyclerView.ViewHolder {

        public TextView TextViewName;
        public TextView TextViewStatus;
        public TextView TextViewPrice;
        public TextView TextViewCourier;

        public ViewHolder(View itemView) {
            super(itemView);

            TextViewName = (TextView) itemView.findViewById(R.id.orderListName);
            TextViewStatus = (TextView) itemView.findViewById(R.id.orderListStatus);
            TextViewPrice = (TextView) itemView.findViewById(R.id.orderListPrice);
            TextViewCourier = (TextView) itemView.findViewById(R.id.orderListCourier);
        }
    }

}

@layout/rv_item.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <android.support.v7.widget.CardView xmlns:card_view="http://schemas.android.com/apk/res-auto"
        android:layout_margin="@dimen/activity_horizontal_margin"
        android:layout_height="wrap_content"
        android:layout_width="match_parent">

        <LinearLayout
            android:padding="@dimen/activity_horizontal_margin"
            android:orientation="vertical"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <TextView
                android:id="@+id/orderListName"
                android:text="Order name"
                android:textAppearance="@style/Base.TextAppearance.AppCompat.Large"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />

            <TextView
                android:id="@+id/orderListStatus"
                android:text="Status"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />

            <TextView
                android:id="@+id/orderListPrice"
                android:text="Price"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />

            <TextView
                android:id="@+id/orderListCourier"
                android:text="Courier"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />
        </LinearLayout>

    </android.support.v7.widget.CardView>

</LinearLayout>

@layout/main.xml:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    tools:context="com.example.seether.myapplication.CourierActivity"
    android:background="#fff"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/drawerLayout">

    <android.support.v7.widget.RecyclerView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/rv"/>

</android.support.v4.widget.DrawerLayout>

EDIT. Works perfect without log's warnings if I enter custom data into listItems.

Body:
Don't pass the list object from activity to adapter. Instead have a separate array list in adapter.
Change your adapter constructor to this:

     public RecycleAdapter(List<OrderListItem> listItems, Context context) {
         this.listItems = new ArrayList<>(listItems);
         this.context = context;
    }

And as Maddy suggested use a setMethod in adapter passing the listitem array and adding all items to it and calling notifyDataSetChanged.

I guess this should solve your problem when you don't use the same listitems object in activity and adapter.


问:
Vertical Alignment of text in a table cell
Here's a portion of my table (it's a form):

Those are just two 's in a
. I'm trying to get Description up top, to the top of the table cell, rather than resting on the bottom.

How can I do that?

答:
Just add vertical-align:top for first td alone needed not for all td.

tr>td:first-child {
  vertical-align: top;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><tr>
  <td>Description</td>
  <td>more text</td>
</tr></code>```

Body:
Just add vertical-align:top for first td alone needed not for all td.

tr>td:first-child {
  vertical-align: top;
}

<tr>
  <td>Description</td>
  <td>more text</td>
</tr>


问:
nodegit: getHeadCommit() holds the directory (libgit2)
After I clone the repository using nodegit and call getHeadCommit(), the Node process holds the directory, which prevents it from being removed by code (fs-extra remove), nor by OS.

```<code>console.log((async (): Promise<void> => {
    const tempDirectory: string = path.join(process.cwd(), '.tmp');

    console.log('clone');
    const repository: nodegit.Repository = await nodegit.Clone.clone(
        'ssh://git@***.git',
        tempDirectory,
        {
            checkoutBranch: 'master',
            fetchOpts: {
                callbacks: {
                    certificateCheck: (): number => 1,
                    credentials: (url: string, userName: string): nodegit.Cred =>
                        nodegit.Cred.sshKeyNew(
                            userName,
                            path.join(os.homedir(), '.ssh', 'id_rsa.pub'),
                            path.join(os.homedir(), '.ssh', 'id_rsa'),
                            ''
                        )
                }
            }
        }
    );

    console.log('get head commit');
    const commit: nodegit.Commit = await repository.getHeadCommit();

    console.log('remove');
    await fse.remove(tempDirectory);  // Here Node hangs

    console.log('end');
})());
</code>```

Error message:

```<code>Error: EBUSY: resource busy or locked, unlink '***\.tmp\.git\objects\pack\pack-27924883cff8a0039ced57d07bad35459885ff9d.pack'
</code>```

Is there an error in my code? Or is there a method in nodegit for releasing the repository directory after using repository.getHeadCommit()?

答: Oops! I missed the free method. It fixed the problem.</p>

Body:
After I clone the repository using nodegit and call getHeadCommit(), the Node process holds the directory, which prevents it from being removed by code (fs-extra remove), nor by OS.

console.log((async (): Promise<void> => {
    const tempDirectory: string = path.join(process.cwd(), '.tmp');

    console.log('clone');
    const repository: nodegit.Repository = await nodegit.Clone.clone(
        'ssh://git@***.git',
        tempDirectory,
        {
            checkoutBranch: 'master',
            fetchOpts: {
                callbacks: {
                    certificateCheck: (): number => 1,
                    credentials: (url: string, userName: string): nodegit.Cred =>
                        nodegit.Cred.sshKeyNew(
                            userName,
                            path.join(os.homedir(), '.ssh', 'id_rsa.pub'),
                            path.join(os.homedir(), '.ssh', 'id_rsa'),
                            ''
                        )
                }
            }
        }
    );

    console.log('get head commit');
    const commit: nodegit.Commit = await repository.getHeadCommit();

    console.log('remove');
    await fse.remove(tempDirectory);  // Here Node hangs

    console.log('end');
})());

Error message:

Error: EBUSY: resource busy or locked, unlink '***\.tmp\.git\objects\pack\pack-27924883cff8a0039ced57d07bad35459885ff9d.pack'

Is there an error in my code? Or is there a method in nodegit for releasing the repository directory after using repository.getHeadCommit()?


问:
(Tkinter/Python) How to check for things in textfile and have different outcomes based on results?
I'm currently having some trouble with checking if things are written down in my textfile.

In my code, I check if "1" is in my storefile.txt file. If "1" isn't in the textfile, signalling that the user has opened the code for the first time, Tkinter asks for the user's name and puts in "1" (signalling that the user has opened the code before). If not, Tkinter says "Welcome back," and the user's inputted name.

However, even after I open the code after the first time, the code acts like "1" isn't even in the storefile, even though it is. The code asks for my name and prints "1" again, so I end up having more than 1 "1"s in my storefile and never reach to the "Welcome back," [name] stage.

```<code>import tkinter as tk
from time import time
from tkinter import *
root = Tk()

#FUNCTION FOR LABELS (not necessary but it condenses the code)
def label(a):
    Label(root,text=a,font=("System",15,"bold"),fg="steelblue").pack()

#THIS IS FOR EXTRACTING SPECIFIC DATA FROM THE TEXTFILE

lines = [] #Declare an empty list named "lines"
def specify(x):
    with open ('storefile.txt', 'rt+') as in_file:  #Open file lorem.txt for reading of text data.
        for line in in_file:                       #For each line of text store in a string variable named "line", and
            lines.append(line)                     #add that line to our list of lines.
    label(lines[x])                                #print the list object.

    #[x] allows us to print whatever line we want.

#############################

#THIS IS FOR THE 'ENTER NAME' BUTTON TO STORE NAMES
def store():
    user_entry = distance_text_box.get()
    f=open("storefile.txt", "a")
    f.write (str(user_entry))
    f.close()

#TITLE
label("[INSERT TITLE]")

#CHECKS IF THIS IS THEIR FIRST TIME ON THE APP. IF IT IS, PRINT DESCRIPTION AND ASKS FOR USERNAME
searchfile = open("storefile.txt", "r")
with open ('storefile.txt', 'rt+') as in_file:  #Open file lorem.txt for reading of text data.
    for line in searchfile:                       #For each line of text store in a string variable named "line", and
        if "1" not in line:#IT STORES '1' IN THE TEXTFILE WHEN THE USER FIRST OPENS THE CODE, SO IF '1' ISN'T THERE, THE USER HAS NOT OPENED THE CODE YET
            print("yes")

            Label(root,text="ENTER NAME",font=("System",15,"bold"),fg="steelblue").pack(side=LEFT)#enter name label

            distance_text_box = Entry(root, bd=1)
            distance_text_box.pack()

            searchfile = open("storefile.txt", "a")
            searchfile.write("1\n")
            searchfile.close()

            Button(root, text ="Done!", command=lambda:store()).pack(side=RIGHT)

    elif "1" in line:
        print("no")
        Label(root,text="Welcome back,").pack()
searchfile.close()

#PUT NAME IN TEXTFILE

root.mainloop()
</code>```

答:
First of all, you are trying to open an already opened file.
Second, if you want to access a file line by line try this:

```<code>with open('file.txt','r') as f:
  lines  = f.readlines() #lines is now a list of lines in the file.
</code>```

If you want to add new text to the file you can simply create a list of lines to add and append to it, once the check loop is done, append it to the lines list and write back to the file.

Body:
I'm currently having some trouble with checking if things are written down in my textfile.

In my code, I check if "1" is in my storefile.txt file. If "1" isn't in the textfile, signalling that the user has opened the code for the first time, Tkinter asks for the user's name and puts in "1" (signalling that the user has opened the code before). If not, Tkinter says "Welcome back," and the user's inputted name.

However, even after I open the code after the first time, the code acts like "1" isn't even in the storefile, even though it is. The code asks for my name and prints "1" again, so I end up having more than 1 "1"s in my storefile and never reach to the "Welcome back," [name] stage.

import tkinter as tk
from time import time
from tkinter import *
root = Tk()

#FUNCTION FOR LABELS (not necessary but it condenses the code)
def label(a):
    Label(root,text=a,font=("System",15,"bold"),fg="steelblue").pack()

#THIS IS FOR EXTRACTING SPECIFIC DATA FROM THE TEXTFILE

lines = [] #Declare an empty list named "lines"
def specify(x):
    with open ('storefile.txt', 'rt+') as in_file:  #Open file lorem.txt for reading of text data.
        for line in in_file:                       #For each line of text store in a string variable named "line", and
            lines.append(line)                     #add that line to our list of lines.
    label(lines[x])                                #print the list object.

    #[x] allows us to print whatever line we want.

#############################

#THIS IS FOR THE 'ENTER NAME' BUTTON TO STORE NAMES
def store():
    user_entry = distance_text_box.get()
    f=open("storefile.txt", "a")
    f.write (str(user_entry))
    f.close()

#TITLE
label("[INSERT TITLE]")

#CHECKS IF THIS IS THEIR FIRST TIME ON THE APP. IF IT IS, PRINT DESCRIPTION AND ASKS FOR USERNAME
searchfile = open("storefile.txt", "r")
with open ('storefile.txt', 'rt+') as in_file:  #Open file lorem.txt for reading of text data.
    for line in searchfile:                       #For each line of text store in a string variable named "line", and
        if "1" not in line:#IT STORES '1' IN THE TEXTFILE WHEN THE USER FIRST OPENS THE CODE, SO IF '1' ISN'T THERE, THE USER HAS NOT OPENED THE CODE YET
            print("yes")

            Label(root,text="ENTER NAME",font=("System",15,"bold"),fg="steelblue").pack(side=LEFT)#enter name label

            distance_text_box = Entry(root, bd=1)
            distance_text_box.pack()

            searchfile = open("storefile.txt", "a")
            searchfile.write("1\n")
            searchfile.close()

            Button(root, text ="Done!", command=lambda:store()).pack(side=RIGHT)

    elif "1" in line:
        print("no")
        Label(root,text="Welcome back,").pack()
searchfile.close()

#PUT NAME IN TEXTFILE

root.mainloop()

Body:
First of all, you are trying to open an already opened file.
Second, if you want to access a file line by line try this:

with open('file.txt','r') as f:
  lines  = f.readlines() #lines is now a list of lines in the file.

If you want to add new text to the file you can simply create a list of lines to add and append to it, once the check loop is done, append it to the lines list and write back to the file.


问:
Can any one explain me how does the string and number comparison work in javascript?
I have compared some strings and numbers to see the result as true and false

```<code>"dfdf" > 1
false
"dfdf" > 99
false
"dfdf" > 9999
false
"dfdf" > 99999
false
1> ''
true
1> '545'
false
1> '545d'
false
1> '555'
false
1> 'ddfdf'
false
9999 > 'dfsdfadf'
false
</code>```

I have tried few different combinations in the code as you can see but got the mixed result and want to know how exactly the comparison works in javascript.

another addition which is even more confusing

```<code>"dasfads" > "dasfdsf"
false
"abc" > "a"
true
"abc" > "agf"
false
"abcf" > "agf"
false
</code>```

答:
There are 2 types of comparison available when using JavaScript,

The standard equality operators (== and !=) use the Abstract Equality Comparison Algorithm to compare two operands. If the operands are of different types, it will attempt to convert them to the same type before making the comparison, e.g., in the expression 5 == '5', the string on the right is converted to Number before the comparison is made.

The strict equality operators (=== and !==) use the Strict Equality Comparison Algorithm and are intended for performing equality comparisons on operands of the same type. If the operands are of different types, the result is always false so 5 !== '5'.

So if you want to know what is happening there, JavaScript is trying to convert the string into a Number and then do comparison, however, since they are not a number, which is always converted to NaN, and comparison with NaN will be equal to false.

Link for details:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators

Body:
I have compared some strings and numbers to see the result as true and false

"dfdf" > 1
false
"dfdf" > 99
false
"dfdf" > 9999
false
"dfdf" > 99999
false
1> ''
true
1> '545'
false
1> '545d'
false
1> '555'
false
1> 'ddfdf'
false
9999 > 'dfsdfadf'
false

I have tried few different combinations in the code as you can see but got the mixed result and want to know how exactly the comparison works in javascript.

another addition which is even more confusing

"dasfads" > "dasfdsf"
false
"abc" > "a"
true
"abc" > "agf"
false
"abcf" > "agf"
false


问:
Longest monotonically decreasing subsequence, with no consecutive elements included
for example:

```<code>s = <6, 5, 4, 3, 2, 1>, s1 = <6, 4, 1>, s2 = <5, 2>, s3 = <5, 3, 2>
</code>```

Given s as a sequence, s1 and s2 are the valid subsequences to be considered, but s3 is not because it contains a consecutive elements 3 and 2.

How do you find a longest such a subsequence so that it is monotonically decreasing in O(n^2)

I am aware of the version of the question that contains monotonic increase/ decrease.

But the additional condition here makes it difficult.

A trivial solution would be to start at i = n'th element as well as at j = (n-1)'th element, solve as if solving for longest monotonically decreasing subsequence with consideration that next element is at (i-2)'th and (j-2)'th respectively and compare the length of two at the end. This will still give the O(n^2), but does seem way too trivial.

Is there a better approach?

答:
```<code>D[i] = max { D[j] + 1 | a[i] < a[j], j < i + 1 } U {1}
</code>```

Explanation: for each element a[i], your Dynamic Programming (DP) checks for all numbers that are before it and with lower value, but not adjacent - if the new number can be used to extend the best sequence. In addition, you have the option to start a new sequence (that's when the {1} comes to play).

Example:
S = <6, 0, 5, 8, 4, 7, 6 >

```<code>D[1] = max { 1 } = 1  // sequence = <6>
D[2] = max {1} = 1  // sequence = <0>
D[3] = max {1, D[0] + 1 } = 2  // sequence = <6, 5>
D[4] = max {1} = 1  // sequence = <8>
D[5] = max{D[3] + 1, D[1] + 1, 1} = 3 // sequence = <6, 5, 4>
D[6] = max{D[4] + 1, 1} = 2  // sequence = <8, 7>
D[7] = max{D[4] + 1, 1} = 2  // sequence = <8, 6>
</code>```

The algorithm runs in O(n^2), since calculating D[i] takes O(i) time. From sum of arithmetic progression, this sums to O(n^2) to calculate all.

When you are done calculating all D[.],  you iterate through all of them, and find the maximal value. This is done in linear time.

Body:
for example:

s = <6, 5, 4, 3, 2, 1>, s1 = <6, 4, 1>, s2 = <5, 2>, s3 = <5, 3, 2>

Given s as a sequence, s1 and s2 are the valid subsequences to be considered, but s3 is not because it contains a consecutive elements 3 and 2.

How do you find a longest such a subsequence so that it is monotonically decreasing in O(n^2)

I am aware of the version of the question that contains monotonic increase/ decrease.

But the additional condition here makes it difficult.

A trivial solution would be to start at i = n'th element as well as at j = (n-1)'th element, solve as if solving for longest monotonically decreasing subsequence with consideration that next element is at (i-2)'th and (j-2)'th respectively and compare the length of two at the end. This will still give the O(n^2), but does seem way too trivial.

Is there a better approach?

Body:
D[i] = max { D[j] + 1 | a[i] < a[j], j < i + 1 } U {1}

Explanation: for each element a[i], your Dynamic Programming (DP) checks for all numbers that are before it and with lower value, but not adjacent - if the new number can be used to extend the best sequence. In addition, you have the option to start a new sequence (that's when the {1} comes to play).

Example:
S = <6, 0, 5, 8, 4, 7, 6 >

D[1] = max { 1 } = 1  // sequence = <6>
D[2] = max {1} = 1  // sequence = <0>
D[3] = max {1, D[0] + 1 } = 2  // sequence = <6, 5>
D[4] = max {1} = 1  // sequence = <8>
D[5] = max{D[3] + 1, D[1] + 1, 1} = 3 // sequence = <6, 5, 4>
D[6] = max{D[4] + 1, 1} = 2  // sequence = <8, 7>
D[7] = max{D[4] + 1, 1} = 2  // sequence = <8, 6>

The algorithm runs in O(n^2), since calculating D[i] takes O(i) time. From sum of arithmetic progression, this sums to O(n^2) to calculate all.

When you are done calculating all D[.],  you iterate through all of them, and find the maximal value. This is done in linear time.


问:
std::uniform_real_distribution regenerating same random number
In running the code below, the first half of arr equals the last half.  Why?  I even tried various seeds, e.g. std::chrono::system_clock::now().time_since_epoch().count(). Thanks.

```<code>#include <algorithm>
#include <iostream>
#include <random>

template<typename DistributionType>
class Rng
{
public:
        template<typename ...Args>
        Rng(Args&&... args) : dist(args...) { }

        typename DistributionType::result_type operator()()
        {
                return dist(gen);
        }

private:
        std::default_random_engine gen;

        DistributionType dist;
};

class UniformRealRng : public Rng<std::uniform_real_distribution<double>>
{
public:
        UniformRealRng(const double a, const double b) : Rng(a, b) { }
};

int main()
{
        constexpr int sz = 6;
        constexpr int k  = sz / 2;
        double arr[sz];

        UniformRealRng rng(0.0, 1.0);
        std::generate(arr, arr + k, rng);
        std::generate(arr + k, arr + sz, rng);

        for (int i = 0; i < sz; ++i)
        {
                std::cout << arr[i];
        }
        std::cout << "\n";
}
</code>```

答:
Your answer is factually correct but it doesn't solve the problem.
It only produces a compilation error when mistakenly(?) one tries to copy the random number generator.

It turns out that the code can be made to be semantically correct by using the std::reference_wrapper library features.

```<code>    std::generate(arr, arr + k, std::ref(rng));
    std::generate(arr + k, arr + sz, std::ref(rng));
</code>```

In this way you are basically forcing to pass the argument by reference.
Luckily the reference wrapper overloads the operator() and therefore can be used for the generator without any additional code.

Complete code:

```<code>#include <algorithm>
#include <iostream>
#include <random>
#include <functional> //ref

template<typename DistributionType>
class Rng
{
public:
        template<typename ...Args>
        Rng(Args&&... args) : dist(args...) { }
//      Rng(Rng&)             = delete;  // this is not needed for it to work
//      Rng& operator=(Rng&)  = delete;  // you MAY want to copy the generator
        typename DistributionType::result_type operator()()
        {
                return dist(gen);
        }

private:
        std::default_random_engine gen;

        DistributionType dist;
};

class UniformRealRng : public Rng<std::uniform_real_distribution<double>>
{
public:
        UniformRealRng(const double a, const double b) : Rng(a, b) { }
};

int main()
{
        constexpr int sz = 6;
        constexpr int k  = sz / 2;
        double arr[sz];

        UniformRealRng rng(0.0, 1.0);
        std::generate(arr, arr + k, std::ref(rng));
        std::generate(arr + k, arr + sz, std::ref(rng));

        for (int i = 0; i < sz; ++i)
        {
                std::cout << arr[i];
        }
        std::cout << "\n";
}
</code>```

Body:
In running the code below, the first half of arr equals the last half.  Why?  I even tried various seeds, e.g. std::chrono::system_clock::now().time_since_epoch().count(). Thanks.

#include <algorithm>
#include <iostream>
#include <random>

template<typename DistributionType>
class Rng
{
public:
        template<typename ...Args>
        Rng(Args&&... args) : dist(args...) { }

        typename DistributionType::result_type operator()()
        {
                return dist(gen);
        }

private:
        std::default_random_engine gen;

        DistributionType dist;
};

class UniformRealRng : public Rng<std::uniform_real_distribution<double>>
{
public:
        UniformRealRng(const double a, const double b) : Rng(a, b) { }
};

int main()
{
        constexpr int sz = 6;
        constexpr int k  = sz / 2;
        double arr[sz];

        UniformRealRng rng(0.0, 1.0);
        std::generate(arr, arr + k, rng);
        std::generate(arr + k, arr + sz, rng);

        for (int i = 0; i < sz; ++i)
        {
                std::cout << arr[i];
        }
        std::cout << "\n";
}

Body:
Your answer is factually correct but it doesn't solve the problem.
It only produces a compilation error when mistakenly(?) one tries to copy the random number generator.

It turns out that the code can be made to be semantically correct by using the std::reference_wrapper library features.

    std::generate(arr, arr + k, std::ref(rng));
    std::generate(arr + k, arr + sz, std::ref(rng));

In this way you are basically forcing to pass the argument by reference.
Luckily the reference wrapper overloads the operator() and therefore can be used for the generator without any additional code.

Complete code:

#include <algorithm>
#include <iostream>
#include <random>
#include <functional> //ref

template<typename DistributionType>
class Rng
{
public:
        template<typename ...Args>
        Rng(Args&&... args) : dist(args...) { }
//      Rng(Rng&)             = delete;  // this is not needed for it to work
//      Rng& operator=(Rng&)  = delete;  // you MAY want to copy the generator
        typename DistributionType::result_type operator()()
        {
                return dist(gen);
        }

private:
        std::default_random_engine gen;

        DistributionType dist;
};

class UniformRealRng : public Rng<std::uniform_real_distribution<double>>
{
public:
        UniformRealRng(const double a, const double b) : Rng(a, b) { }
};

int main()
{
        constexpr int sz = 6;
        constexpr int k  = sz / 2;
        double arr[sz];

        UniformRealRng rng(0.0, 1.0);
        std::generate(arr, arr + k, std::ref(rng));
        std::generate(arr + k, arr + sz, std::ref(rng));

        for (int i = 0; i < sz; ++i)
        {
                std::cout << arr[i];
        }
        std::cout << "\n";
}


问:
Grabbing content off webpage that is in script tags
OK, I have this page I want to get the content off.. however the stats are made in JavaScript.  Is there ANY way I can get the stats? I tried using PHP get_content thingy...

Here is an example that is in the page I want to get. This

Body: Have a look at http://ca.php.net/manual/en/function.domxml-open-file.php to open the URL as an XML DOM. You can then parse the XML DOM using http://ca.php.net/manual/en/function.domdocument-get-elements-by-tagname.php to get the <script> tags.


问:
Code disappear sometimes from .htaccess
Hello guys i’m new and I have question. I have one website that have indexed https and http version in google search, and I added 301 redirect from HTTPS to HTTP in .htaccess. Sometimes, Randomly, 301 redirect disappeared from htaccess and I need to add it again.

This is my htaccess with 301 redirect:

```<code># BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTPS} on
RewriteRule (.*) http://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
</code>```

And After some times, they change to this

```<code># BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
</code>```

So the redirect was completely removed, google index again https page and I need to add it again, why? I tried many hosting company but nothing changed.

答:
I would not redirect vom HTTPS to HTTP, but the other way round. Google will give you a small ranking boost if you are using HTTPS (not to speak of it being the right thing to do to protect your users' privacy).

That being said: don't put anything between the WordPress markers, e.g.

```<code># BEGIN WordPress
....
# END WordPress
</code>```

WordPress will overwrite it the next time it writes to the .htaccess.

If you put it before that block, i.e.

```<code><IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTPS} on
RewriteRule (.*) http://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
</IfModule>

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
</code>```

You should be fine, and it should remain intact.

Title: Code disappear sometimes from .htaccess

Body:
Hello guys i’m new and I have question. I have one website that have indexed https and http version in google search, and I added 301 redirect from HTTPS to HTTP in .htaccess. Sometimes, Randomly, 301 redirect disappeared from htaccess and I need to add it again.

This is my htaccess with 301 redirect:

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTPS} on
RewriteRule (.*) http://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress

And After some times, they change to this

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress

So the redirect was completely removed, google index again https page and I need to add it again, why? I tried many hosting company but nothing changed.

Body:
I would not redirect vom HTTPS to HTTP, but the other way round. Google will give you a small ranking boost if you are using HTTPS (not to speak of it being the right thing to do to protect your users' privacy).

That being said: don't put anything between the WordPress markers, e.g.

# BEGIN WordPress
....
# END WordPress

WordPress will overwrite it the next time it writes to the .htaccess.

If you put it before that block, i.e.

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTPS} on
RewriteRule (.*) http://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
</IfModule>

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress

You should be fine, and it should remain intact.


问:
repex dplyr summarise yields error on data line nine: Why?
I have a dataset with 87 variables and about 9 million observations. The earliest years do not collect information on number of children. I have attempted to impute a value for number of children to these households. The function below tries to summarize the ratio between women of childbearing age and my imputed value,  to compare with the Census estimates for those years. When I run the block of code below on my full data set,

```<code>library(tidyverse)
mid2  %>% filter(year < 1968)   %>%
  group_by(hh_id)    %>%
  summarise(hh_fem  = .data$n_fem  * (.data$pernum == 1),
           hh_kids  = .data$n_kids * (.data$pernum == 1))  %>%
  summarise(tot_fem = sum(hh_fem),
            totkids = sum(hh_kids))    ->  fk
</code>```

get this error:

```<code>Error in summarise_impl(.data, dots) :
  Column `hh_fem` must be length 1 (a summary value), not 2
</code>```

The initial restriction to years prior to 1968 limits the rows to the first 400-odd thousand. Looking at just the first five rows, I get no error and the answer I expect. By a process of trial and error, I determined that I could reproduce the error with just the first nine rows, and just the variables referenced in the function but not created there. These rows are reproduced below. The function works correctly on rows 1:8.

```<code>smidgen <- select(mid2[9, ], year, hh_id, n_fem, pernum, numprec, n_kids)

smidgen
# A tibble: 9 x 6
# Groups:   hh_id [8]
   year      hh_id n_fem pernum numprec    n_kids
  <dbl>      <chr> <int>  <dbl>   <dbl>     <dbl>
1  1962 1962300001     1      1       1 0.9466731
2  1962 1962300002     0      1       1 0.0000000
3  1962 1962300003     0      1       1 0.0000000
4  1962 1962300004     0      1       1 0.0000000
5  1962 1962300005     0      1       1 0.0000000
6  1962 1962300006     0      1       1 0.0000000
7  1962 1962300007     0      1       1 0.0000000
8  1962 1962300008     2      1       2 1.8933462
9  1962 1962300008     2      2       2 1.8933462
</code>```

Indeed, I generate the same error from rows 8:9 alone. Not, however, from either row 8 or row 9, taken separately.

I do not see anything on row 9 to cause this problem. Indeed, I don’t see how any values in row nine could change the width of hh_fem.

Advice and thoughts greatly appreciated.

答:
The error is in the first call to summarise:

```<code> summarise(hh_fem  = .data$n_fem  * (.data$pernum == 1)
</code>```

If you want to filter the observation in the variable pernum to just the ones with a value of 1, you have to call first the filter() function and then the summarise() function

Your code should work with this change:

```<code> mid2  %>% filter(year < 1968)   %>%
 filter(pernum == 1) %>%
 group_by(hh_id)    %>%
 summarise(hh_fem  = n_fem  * pernum,
           hh_kids  = n_kids * pernum)  %>%
 summarise(tot_fem = sum(hh_fem),
        totkids = sum(hh_kids))    ->  fk
</code>```

For the future please post a reprex in order to easily reproduce your problem

Body:
I have a dataset with 87 variables and about 9 million observations. The earliest years do not collect information on number of children. I have attempted to impute a value for number of children to these households. The function below tries to summarize the ratio between women of childbearing age and my imputed value,  to compare with the Census estimates for those years. When I run the block of code below on my full data set,

library(tidyverse)
mid2  %>% filter(year < 1968)   %>%
  group_by(hh_id)    %>%
  summarise(hh_fem  = .data$n_fem  * (.data$pernum == 1),
           hh_kids  = .data$n_kids * (.data$pernum == 1))  %>%
  summarise(tot_fem = sum(hh_fem),
            totkids = sum(hh_kids))    ->  fk

get this error:

Error in summarise_impl(.data, dots) :
  Column `hh_fem` must be length 1 (a summary value), not 2

The initial restriction to years prior to 1968 limits the rows to the first 400-odd thousand. Looking at just the first five rows, I get no error and the answer I expect. By a process of trial and error, I determined that I could reproduce the error with just the first nine rows, and just the variables referenced in the function but not created there. These rows are reproduced below. The function works correctly on rows 1:8.

smidgen <- select(mid2[9, ], year, hh_id, n_fem, pernum, numprec, n_kids)

smidgen
# A tibble: 9 x 6
# Groups:   hh_id [8]
   year      hh_id n_fem pernum numprec    n_kids
  <dbl>      <chr> <int>  <dbl>   <dbl>     <dbl>
1  1962 1962300001     1      1       1 0.9466731
2  1962 1962300002     0      1       1 0.0000000
3  1962 1962300003     0      1       1 0.0000000
4  1962 1962300004     0      1       1 0.0000000
5  1962 1962300005     0      1       1 0.0000000
6  1962 1962300006     0      1       1 0.0000000
7  1962 1962300007     0      1       1 0.0000000
8  1962 1962300008     2      1       2 1.8933462
9  1962 1962300008     2      2       2 1.8933462

Indeed, I generate the same error from rows 8:9 alone. Not, however, from either row 8 or row 9, taken separately.

I do not see anything on row 9 to cause this problem. Indeed, I don’t see how any values in row nine could change the width of hh_fem.

Advice and thoughts greatly appreciated.

Body:
The error is in the first call to summarise:

 summarise(hh_fem  = .data$n_fem  * (.data$pernum == 1)

If you want to filter the observation in the variable pernum to just the ones with a value of 1, you have to call first the filter() function and then the summarise() function

Your code should work with this change:

 mid2  %>% filter(year < 1968)   %>%
 filter(pernum == 1) %>%
 group_by(hh_id)    %>%
 summarise(hh_fem  = n_fem  * pernum,
           hh_kids  = n_kids * pernum)  %>%
 summarise(tot_fem = sum(hh_fem),
        totkids = sum(hh_kids))    ->  fk

For the future please post a reprex in order to easily reproduce your problem


问:
table creation logic
I am looking to take two tables I have a perform a data transformation to create a single table. I have an events table and user table:

```<code>Events: {id, user_id, start_date, end_date, cost...}

Users: {id, name, ...}
</code>```

I am trying to create a table at that shows user spend at a daily level, assuming the user start with a starting cost of zero and it goes up after every event.

The intended output would be:

```<code>{date, userid, beginning_balance, sum(cost), num_of_events}
</code>```

i need some direction on how to tackle this one as I am not very familiar with data transformation within SQL

答:
Can you try this query</p>

```<code>SELECT
    data,
    User.id AS userid,
    0 AS beginning_balance,
    SUM(cost) AS cost,
    COUNT(0) AS num_of_events
FROM
    Users
    LEFT JOIN Events ON (user_id = Users.id)
GROUP BY
    Users.id
</code>```

Title: table creation logic

Body:
I am looking to take two tables I have a perform a data transformation to create a single table. I have an events table and user table:

Events: {id, user_id, start_date, end_date, cost...}

Users: {id, name, ...}

I am trying to create a table at that shows user spend at a daily level, assuming the user start with a starting cost of zero and it goes up after every event.

The intended output would be:

{date, userid, beginning_balance, sum(cost), num_of_events}

i need some direction on how to tackle this one as I am not very familiar with data transformation within SQL

Body:
Can you try this query

SELECT
    data,
    User.id AS userid,
    0 AS beginning_balance,
    SUM(cost) AS cost,
    COUNT(0) AS num_of_events
FROM
    Users
    LEFT JOIN Events ON (user_id = Users.id)
GROUP BY
    Users.id


问:
What are main differences between Apache Axis and Apache Axis 2?
Apache Axis and Apache Axis 2 are still available on Apache website and I am unable to figure what are the differences between two? When should we use one over other?

Developing SOAP web services using Eclipse IDE's Web Services Wizard brings up Axis by default. If I know the differences I can judge whether to change runtime to Axis 2 or not.

答:
Axis1.x and Axis2 have evolved from different architectures.

Speed - Axis2 is based on the StAX API, which gives greater speed than the SAX event based parsing used in Axis1.x.

Stability - Axis2 has fixed phases as well as user-defined phases for extensions. This allows far more stability as well as flexibility than Axis1.x.

Transport framework - Transports (i.e., senders and listeners for SOAP over various protocols such as HTTP, SMTP, etc.), have been abstracted away from the Axis2 engine. Having a transport-independent Axis engine allows far more flexibility in transport options.

WSDL 2.0 support - Axis2 supports both WSDL versions 1.1 and 2.0, which are used by Axis2's code generation tools to create web service skeletons and client stubs.

Component-oriented architecture - Axis2 components consist of handlers and modules in .mar and .aar archives. These easily reusable components allow extended functionality such as pattern processing for your applications or distribution to partners. Axis2 emphasizes the "Module" concept over the "Handler" concept of Axis 1.x. Modules contain handlers that are ordered by phase rules. These are attached to specific service(s).

ContentLicense: CC BY-SA 4.0


问:
awk split question
I wrote a small script, using awk 'split' command to get the current directory name.

echo $PWD

I need to replace '8' with the number of tokens as a result of the split operation.
// If PWD = /home/username/bin. I am trying to get "bin" into package.

```<code>package="`echo $PWD | awk '{split($0,a,"/"); print a[8] }'`"
echo $package
</code>```

Can you please tell me what do I substitute in place of 'print a[8]'  to get the script working for any directory path ?

-Sachin

答:
You don't need awk for that. If you always want the last dir in a path just do:

```<code>#!/bin/sh

cur_dir="${PWD##*/}/"
echo "$cur_dir"
</code>```

The above has the added benefit of not creating any subshells and/or forks to external binaries.  It's all native POSIX shell syntax.

Title: awk split question

Body:
I wrote a small script, using awk 'split' command to get the current directory name.

echo $PWD

I need to replace '8' with the number of tokens as a result of the split operation.
// If PWD = /home/username/bin. I am trying to get "bin" into package.

package="`echo $PWD | awk '{split($0,a,"/"); print a[8] }'`"
echo $package

Can you please tell me what do I substitute in place of 'print a[8]'  to get the script working for any directory path ?

-Sachin

Body:
You don't need awk for that. If you always want the last dir in a path just do:

#!/bin/sh

cur_dir="${PWD##*/}/"
echo "$cur_dir"

The above has the added benefit of not creating any subshells and/or forks to external binaries.  It's all native POSIX shell syntax.


问:
Cannot revert to the other parent of a merge commit
I have a faulty merge commit that I want to revert to. Specifically, I want to revert to the 2nd parent of the merge commit.

```<code>$ git revert -m 2 <merge-commit>
</code>```

Nothing happens when I try to revert instead this is what I get in return:

```<code>$ git revert -m 2 <merge-commit>
On branch dev
Your branch is up-to-date with 'origin/dev'

nothing to commit, working tree clean
</code>```

Reverting to the first parent works so I was under the assumption that reverting to the other parent should work just as well. How do I successfully revert to the second parent of my merge commit?

答:
Are there any differences between between the merge commit you mention, and its 2nd child ?</p>

```<code>git diff <merge-commit>^2 <merge-commit>
</code>```

Body:
I have a faulty merge commit that I want to revert to. Specifically, I want to revert to the 2nd parent of the merge commit.

$ git revert -m 2 <merge-commit>

Nothing happens when I try to revert instead this is what I get in return:

$ git revert -m 2 <merge-commit>
On branch dev
Your branch is up-to-date with 'origin/dev'

nothing to commit, working tree clean

Reverting to the first parent works so I was under the assumption that reverting to the other parent should work just as well. How do I successfully revert to the second parent of my merge commit?

Body:
Are there any differences between between the merge commit you mention, and its 2nd child ?

git diff <merge-commit>^2 <merge-commit>