问:
How does indirect manipulation of dynamically allocated string literals truly work in C?
As it stands, I know that dynamically allocated string literals cannot be changed during run-time, otherwise you will hit a segmentation fault.

This is due to the fact that dynamically allocated string literals are stored, from what I saw in the assembly code, in the .rodata segment, placing these literals in what I interpret as read only memory.

So in theory this should never work on what I hope is in every modern C compiler:

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

int
main( void )
{
  char *p = ( char * )malloc( 10 * sizeof( char ) );
  if ( p == NULL )
  {
    puts( "Bad memory allocation error!" );
    return( EXIT_FAILURE );
  }
  else
  {
    p = "literal";
    printf( "%s\n", p );
    p[0] = 't'; // <-- This should cause a segmentation fault!
    printf( "%s\n", p ); // <-- This should never reach execution!
  }
  return( EXIT_SUCCESS );
}
```

<p>However, upon studying how <code>tolower()</code> and <code>toupper()</code> work. I find it rather difficult to understand how these two simple functions are able to do what I thought for a long while was impossible. Here's what I mean:</p>

<pre class="lang-c prettyprint-override"><code>#include <stdio.h>

int
tolowercase( int c )
{
  return ( c >= 'A' && c <= 'Z' ) ? ( c + 32) : ( c );
}

int
retstrlen( char *str )
{
  int len = 0;
  while( *str != '\0' ) { len++; str++; }
  return( len );
}

int
main( int argc, char **argv )
{
  for( int i = 0; i < argc; i++ )
  {
    for( int j = 0; j < retstrlen( argv[i] ); j++ )
    {
      argv[i][j] = tolowercase( argv[i][j] );
      printf( "%c", argv[i][j] );
    }
    printf( "\n" );
  }
  return 0;
}
</code>```

How does the source code defined in my custom tolower() function not cause a segmentation fault as it normally would through manipulating dynamically allocated string literals?

My only hypothesis that I can draw is that since tolowercase() has a parameter of int, and a return type of int, then the compiler performs a type conversion which indirectly manipulates **argv.

I am pretty sure I am on the right track about this, yet I could have gotten my whole terminology wrong here, so what is really happening to **argv?

答:
I know that dynamically allocated string literals cannot be changed during run-time, [...]

You are starting out with a misconception that when corrected makes the rest of your long question irrelevant.  There is no such think as a "dynamically allocated string literals", it is an oxymoron.

When you call malloc and assign its return value to p, then p points to a block of memory on the heap:

```<code>char* p = malloc(10) ;

           Heap                      .rodata
         +-------------+             +------------+
         |             |             |            |
         |             |             |            |
         |             |             |            |
         +-------------+             |            |
p +----->+ Alloc block |             |            |
         +-------------+             |            |
         |             |             |            |
         |             |             |            |
         |             |             |            |
         |             |             |"literal"   |
         |             |             |            |
         +-------------+             +------------+
</code>```

When you reassign p to the literal string, you change it to point to the string in the .rodata segment. It is no longer pointing to the heap and you have lost any reference to that block and caused a memory leak; the alloc block can no longer be released back to the heap

```<code>p = "literal"

            Heap                      .rodata
         +-------------+             +------------+
         |             |             |            |
         |             |             |            |
         |             |             |            |
         +-------------+             |            |
 p +-+   | Alloc block |             |            |
     |   +-------------+             |            |
     |   |             |             |            |
     |   |             |             |            |
     |   |             |             |            |
     |   |             |       +---->+"literal"   |
     |   |             |       |     |            |
     |   +-------------+       |     +------------+
     |                         |
     |                         |
     +-------------------------+
</code>```

Moreover calling free(p) (which you have omitted to do in any case) will fail because p is no longer a pointer to a dynamically allocated block.

What you should do rather is copy the string literal to teh dynamically allocated memory:

```<code>char *p = malloc( MAX_STR_LEN + 1 ) ;
strncpy( p, "literal", MAX_STR_LEN ) ;
</code>```

Then the memory looks like this:

```<code>                     Heap                      .rodata
          +-------------+             +------------+
          |             |             |            |
          |             |             |            |
          |             |             |            |
          +-------------+   strncpy() |            |
p +------>+ "literal"   +<---------+  |            |
          +-------------+          |  |            |
          |             |          |  |            |
          |             |          |  |            |
          |             |          |  |            |
          |             |          +--+"literal"   |
          |             |             |            |
          +-------------+             +------------+
</code>```

Now p points to a copy of the literal string, but no no-longer a literal string, but _variable_data, and is modifiable.

Critically p has not changed, only the data pointed to by p has been changed.  You have maintained control of the alloc block and can release it back to the heap with `free(p).

Body:
As it stands, I know that dynamically allocated string literals cannot be changed during run-time, otherwise you will hit a segmentation fault.

This is due to the fact that dynamically allocated string literals are stored, from what I saw in the assembly code, in the .rodata segment, placing these literals in what I interpret as read only memory.

So in theory this should never work on what I hope is in every modern C compiler:

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

int
main( void )
{
  char *p = ( char * )malloc( 10 * sizeof( char ) );
  if ( p == NULL )
  {
    puts( "Bad memory allocation error!" );
    return( EXIT_FAILURE );
  }
  else
  {
    p = "literal";
    printf( "%s\n", p );
    p[0] = 't'; // <-- This should cause a segmentation fault!
    printf( "%s\n", p ); // <-- This should never reach execution!
  }
  return( EXIT_SUCCESS );
}

However, upon studying how tolower() and toupper() work. I find it rather difficult to understand how these two simple functions are able to do what I thought for a long while was impossible. Here's what I mean:

#include <stdio.h>

int
tolowercase( int c )
{
  return ( c >= 'A' && c <= 'Z' ) ? ( c + 32) : ( c );
}

int
retstrlen( char *str )
{
  int len = 0;
  while( *str != '\0' ) { len++; str++; }
  return( len );
}

int
main( int argc, char **argv )
{
  for( int i = 0; i < argc; i++ )
  {
    for( int j = 0; j < retstrlen( argv[i] ); j++ )
    {
      argv[i][j] = tolowercase( argv[i][j] );
      printf( "%c", argv[i][j] );
    }
    printf( "\n" );
  }
  return 0;
}

How does the source code defined in my custom tolower() function not cause a segmentation fault as it normally would through manipulating dynamically allocated string literals?

My only hypothesis that I can draw is that since tolowercase() has a parameter of int, and a return type of int, then the compiler performs a type conversion which indirectly manipulates **argv.

I am pretty sure I am on the right track about this, yet I could have gotten my whole terminology wrong here, so what is really happening to **argv?

Body:
I know that dynamically allocated string literals cannot be changed during run-time, [...]

You are starting out with a misconception that when corrected makes the rest of your long question irrelevant.  There is no such think as a "dynamically allocated string literals", it is an oxymoron.

When you call malloc and assign its return value to p, then p points to a block of memory on the heap:

char* p = malloc(10) ;

           Heap                      .rodata
         +-------------+             +------------+
         |             |             |            |
         |             |             |            |
         |             |             |            |
         +-------------+             |            |
p +----->+ Alloc block |             |            |
         +-------------+             |            |
         |             |             |            |
         |             |             |            |
         |             |             |            |
         |             |             |"literal"   |
         |             |             |            |
         +-------------+             +------------+

When you reassign p to the literal string, you change it to point to the string in the .rodata segment. It is no longer pointing to the heap and you have lost any reference to that block and caused a memory leak; the alloc block can no longer be released back to the heap

p = "literal"

            Heap                      .rodata
         +-------------+             +------------+
         |             |             |            |
         |             |             |            |
         |             |             |            |
         +-------------+             |            |
 p +-+   | Alloc block |             |            |
     |   +-------------+             |            |
     |   |             |             |            |
     |   |             |             |            |
     |   |             |             |            |
     |   |             |       +---->+"literal"   |
     |   |             |       |     |            |
     |   +-------------+       |     +------------+
     |                         |
     |                         |
     +-------------------------+

Moreover calling free(p) (which you have omitted to do in any case) will fail because p is no longer a pointer to a dynamically allocated block.

What you should do rather is copy the string literal to teh dynamically allocated memory:

char *p = malloc( MAX_STR_LEN + 1 ) ;
strncpy( p, "literal", MAX_STR_LEN ) ;

Then the memory looks like this:

                     Heap                      .rodata
          +-------------+             +------------+
          |             |             |            |
          |             |             |            |
          |             |             |            |
          +-------------+   strncpy() |            |
p +------>+ "literal"   +<---------+  |            |
          +-------------+          |  |            |
          |             |          |  |            |
          |             |          |  |            |
          |             |          |  |            |
          |             |          +--+"literal"   |
          |             |             |            |
          +-------------+             +------------+

Now p points to a copy of the literal string, but no no-longer a literal string, but _variable_data, and is modifiable.

Critically p has not changed, only the data pointed to by p has been changed.  You have maintained control of the alloc block and can release it back to the heap with `free(p).


来源: stackexchange

问:
Is it necessary to receive a NSNotification when adding an observer?
Here's is the thing..

Every time I see an example around the web related iphone - ipad dev, I see that every time that a controller register itself for a notification, the callback method is like:

```<code>-(void)mymethod:(NSNotification *)notification {
    //Bla Bla
}
</code>```

the same with buttons actions.. always like:

```<code>- (void)actionmethod:(id)sender {
     //Bla Bla
}
</code>```

I just make some tests, and the method is called anyway with or without the parameter.
Is this really necessary? For what reason?

Thanks you !!!

答:
From the NSNotificationCenter doc:

notificationSelector

  Selector that specifies the message the receiver sends notificationObserver to notify it of the notification posting. The method specified by notificationSelector must have one and only one argument (an instance of NSNotification).

[Emphasis mine.]

You must provide a selector with the correct signature; if you don't, it may work, but it may stop working just when you don't want it to.

The reason that you might want to get the notification is so that you can pass along information, in the form of the userInfo dictionary that you can specify when you yourself post a notification using notificationWithName:object:userInfo:. You can ignore the argument when the method is called, but the parameter has to be there in the method signature.

As for buttons and their actions, the docs say you can have one of three signatures*:

the UIKit framework allows three different forms of action selector:

  - (void)action

  - (void)action:(id)sender

  - (void)action:(id)sender forEvent:(UIEvent *)event

The IBAction return type is equivalent to void (there is no return value), except that its presence in a method in your header allows Interface Builder to know that the method is intended as an action, so that you can hook up controls.

The reasons for wanting to get the button (or other control) are similar to that of notifications. In case you have many buttons in your interface, some of which (such as in a table view) connect to the same action, you may need to distinguish the exact things that you do by the pressed button's identity.

*: For completeness' sake, I want to mention that this is not the case on Mac; there, an action method must have the form: - (IBAction)action:(id)sender.

ContentLicense: CC BY-SA 3.0

Body:
Here's is the thing..

Every time I see an example around the web related iphone - ipad dev, I see that every time that a controller register itself for a notification, the callback method is like:

-(void)mymethod:(NSNotification *)notification {
    //Bla Bla
}

the same with buttons actions.. always like:

- (void)actionmethod:(id)sender {
     //Bla Bla
}

I just make some tests, and the method is called anyway with or without the parameter.
Is this really necessary? For what reason?

Thanks you !!!


问:
How to define a decision variable with an index with depends on an other index of the same decision variable?
Imagine there is a machine environment with 5 production stages and each of these stages contains a different number of identical machines (so called flexible flow shop).

Now there are jobs which have to be scheduled. All jobs have to start at stage 1 and processed on the stages in the production Environment from stage 1 to stage 5. On every stage only one machine have to work on one Job. Additional every job only needs maximal one machine per stage to work on (some jobs may skip stage 4 because they dont need to be prepared there).

I have 2 constraints with the decision variable x[j][i][f].

The first says, that each job can processed by max. one machine per stage.
The second says, that each machine can only process max. one job at the same time.

Now my problem is, to define the decision variable because the number of machines f depends on the stage i. I.e.:

stage i = 1: m[1] = 3 machines

stage i = 2: m[2] = 2 machines

... and so on.

So the upper bound (i.e. m[i]) of the sum of the both constraints C5 & C6 depends on the value of i.

```<code>     // Indices
     int Nmax = ...;
    range N = 1..Nmax; // jobs j in N

     int Mmax = ...;
    range M = 1..Mmax; // stages i in M
        {int} m[M]  = [{1,2,3},{1,2},{1,2,3,4,5},{1},{1,2,3}]; // Numbers of machines per stage
        {int} F = union(i in M) m[i];

       //decision variables:
         dvar int+ S[N][M]; // starting time of job j in stage i
         dvar int+ E[N]; // earliness of job j
         dvar int+ T[N]; // tardiness of job j.
         dvar boolean x[N][M][F]; // decision variable

      // objective function
      dexpr float Costs = sum(j in N) (E[j] + T[j]);
      minimize Costs

     subject to{
     C5: forall (j in N, i in M) sum(f in m[i])  x[j][i][f] <= 1;
     C6: forall(i in M, f in m[i]) sum(j in N)   x[j][i][f] <= 1;
     }
</code>```

Fortunately, I don't have an error message anymore. But it seems, that CPLEX don't understand that the number of machines belongs to the stages.

For example:
As solution for the decision variable x[j][i][f] i got seven 5x5-matrices. So one matrice for each job, which firstly seems to be correct.
But all values of the matrices are zero. Moreover, cplex scheduled the jobs at stage 2 in a way, that there should be at least 3 parallel machines, but there are only 2...

答:
I assume that

```<code>{int} m[M]  = [{1,2,3},{1,2},{1,2,3,4,5},{1},{1,2,3}];
</code>```

means that in the first stage machines 1,2,3 are available, in the second stage machines 1,2 are available, etc.

Since you use F and not m[i] as index for x this means, that you have too many variables (too many options) in stages that don't have all machines active. This can be fixed by forcing the variable that correspond to unavailable machines to zero (untested code):

```<code>forall (stage in M)
  forall (job in N)
    forall (machine in F : !(machine in m[stage]))
      x[job][machine][stage] == 0;
</code>```

This allows only the machines specified in m to process any jobs in a stage. With that your constraints C5 and C6 should be sufficient: they only involve machines that exist and variables corresponding to other machines are 0.

ContentLicense: CC BY-SA 4.0

Body:
Imagine there is a machine environment with 5 production stages and each of these stages contains a different number of identical machines (so called flexible flow shop).

Now there are jobs which have to be scheduled. All jobs have to start at stage 1 and processed on the stages in the production Environment from stage 1 to stage 5. On every stage only one machine have to work on one Job. Additional every job only needs maximal one machine per stage to work on (some jobs may skip stage 4 because they dont need to be prepared there).

I have 2 constraints with the decision variable x[j][i][f].

The first says, that each job can processed by max. one machine per stage.
The second says, that each machine can only process max. one job at the same time.

Now my problem is, to define the decision variable because the number of machines f depends on the stage i. I.e.:

stage i = 1: m[1] = 3 machines

stage i = 2: m[2] = 2 machines

... and so on.

So the upper bound (i.e. m[i]) of the sum of the both constraints C5 & C6 depends on the value of i.

     // Indices
     int Nmax = ...;
    range N = 1..Nmax; // jobs j in N

     int Mmax = ...;
    range M = 1..Mmax; // stages i in M
        {int} m[M]  = [{1,2,3},{1,2},{1,2,3,4,5},{1},{1,2,3}]; // Numbers of machines per stage
        {int} F = union(i in M) m[i];

       //decision variables:
         dvar int+ S[N][M]; // starting time of job j in stage i
         dvar int+ E[N]; // earliness of job j
         dvar int+ T[N]; // tardiness of job j.
         dvar boolean x[N][M][F]; // decision variable

      // objective function
      dexpr float Costs = sum(j in N) (E[j] + T[j]);
      minimize Costs

     subject to{
     C5: forall (j in N, i in M) sum(f in m[i])  x[j][i][f] <= 1;
     C6: forall(i in M, f in m[i]) sum(j in N)   x[j][i][f] <= 1;
     }

Fortunately, I don't have an error message anymore. But it seems, that CPLEX don't understand that the number of machines belongs to the stages.

For example:
As solution for the decision variable x[j][i][f] i got seven 5x5-matrices. So one matrice for each job, which firstly seems to be correct.
But all values of the matrices are zero. Moreover, cplex scheduled the jobs at stage 2 in a way, that there should be at least 3 parallel machines, but there are only 2...

Body:
I assume that

{int} m[M]  = [{1,2,3},{1,2},{1,2,3,4,5},{1},{1,2,3}];

means that in the first stage machines 1,2,3 are available, in the second stage machines 1,2 are available, etc.

Since you use F and not m[i] as index for x this means, that you have too many variables (too many options) in stages that don't have all machines active. This can be fixed by forcing the variable that correspond to unavailable machines to zero (untested code):

forall (stage in M)
  forall (job in N)
    forall (machine in F : !(machine in m[stage]))
      x[job][machine][stage] == 0;

This allows only the machines specified in m to process any jobs in a stage. With that your constraints C5 and C6 should be sufficient: they only involve machines that exist and variables corresponding to other machines are 0.


问:
GitLab-CI get pom version in pipeline
I'd like to build docker image via gitlab CI with project's version as a tag:

```<code>docker build -t dockerimage:VERSION-IN-POM .
</code>```

In jenkins' pipeline i'm getting the version like that:

```<code>${pom.version}
</code>```

Is it possible to read the version in a similar, convenient way from gitlab CI? Or do I have to write scripts for that?

答:
This work for my variable: gitlab-ci.yml

mvn -Dexec.executable='echo' -Dexec.args='${project.version}' --non-recursive exec:exec -q
```

Title: GitLab-CI get pom version in pipeline

Body:
I'd like to build docker image via gitlab CI with project's version as a tag:

docker build -t dockerimage:VERSION-IN-POM .

In jenkins' pipeline i'm getting the version like that:

${pom.version}

Is it possible to read the version in a similar, convenient way from gitlab CI? Or do I have to write scripts for that?


问:
mysql stored procedure can't retrieve temporary table
I am creating a stored procedure which I will retrieve if there is a data retrieved. I am storing the 1st query result in a temporary table but when I retrieve the data in temporary table it returns an erro #1064 - You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'SELECT * FROM tempt
END' at line 40. But when I try the query it works fine. Here is the command written

```<code>CREATE PROCEDURE test()
BEGIN
CREATE TEMPORARY TABLE tempt
SELECT userInput.ap_id,
       b.accountName,
       b.accountNumber,
       userInput.date,
       p.payeeName,
       t.taxType,
       t.value businessTax,
       userInput.grossAmount,
       userInput.taxableBase,
       CAST(userInput.taxableBase * t.value as decimal(11,2)) as taxAmount,
       userInput.grossAmount - (CAST(userInput.taxableBase * t.value as decimal(11,2))) as netOfVAT,
       particulars,
       accounts,
       NOW(),
       1,
       e.type,
       e.value ewtTax,
       ewtBase
FROM
(
    SELECT CONCAT('AP-',YEAR(NOW()),MONTH(NOW()),DAY(NOW()),'-',(COUNT(*) + 1)) as ap_id,
           paccountNumber as accountNumber,
           pDate as date,
           ppayee as payee,
           pgross as grossAmount,
           ptaxBase as taxableBase,
           pparticulars as particulars,
           paccounts as accounts,
           pewtBase as ewtBase
    FROM ap_entry
) userInput
INNER JOIN bnks b ON userInput.accountNumber = b.accountNumber
INNER JOIN pyee p ON userInput.payee = p.payeeName
INNER JOIN txtype t ON p.taxType = t.taxType
INNER JOIN ewt e ON p.ewt = e.id

SELECT COUNT(*) FROM tempt
END
</code>```

答:
In your query semi colon is missing.</p>

```<code>DELIMITER $$

CREATE PROCEDURE test()
BEGIN
CREATE TEMPORARY TABLE tempt
SELECT userInput.ap_id,
       b.accountName,
       b.accountNumber,
       userInput.date,
       p.payeeName,
       t.taxType,
       t.value businessTax,
       userInput.grossAmount,
       userInput.taxableBase,
       CAST(userInput.taxableBase * t.value as decimal(11,2)) as taxAmount,
       userInput.grossAmount - (CAST(userInput.taxableBase * t.value as decimal(11,2))) as netOfVAT,
       particulars,
       accounts,
       NOW(),
       1,
       e.type,
       e.value ewtTax,
       ewtBase
FROM
(
    SELECT CONCAT('AP-',YEAR(NOW()),MONTH(NOW()),DAY(NOW()),'-',(COUNT(*) + 1)) as ap_id,
           paccountNumber as accountNumber,
           pDate as date,
           ppayee as payee,
           pgross as grossAmount,
           ptaxBase as taxableBase,
           pparticulars as particulars,
           paccounts as accounts,
           pewtBase as ewtBase
    FROM ap_entry
) userInput
INNER JOIN bnks b ON userInput.accountNumber = b.accountNumber
INNER JOIN pyee p ON userInput.payee = p.payeeName
INNER JOIN txtype t ON p.taxType = t.taxType
INNER JOIN ewt e ON p.ewt = e.id; -- semi colon missing

SELECT COUNT(*) FROM tempt; -- semi colon missing
END
$$
DELIMITER ; -- changed back to default
</code>```

Body:
I am creating a stored procedure which I will retrieve if there is a data retrieved. I am storing the 1st query result in a temporary table but when I retrieve the data in temporary table it returns an erro #1064 - You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'SELECT * FROM tempt
END' at line 40. But when I try the query it works fine. Here is the command written

CREATE PROCEDURE test()
BEGIN
CREATE TEMPORARY TABLE tempt
SELECT userInput.ap_id,
       b.accountName,
       b.accountNumber,
       userInput.date,
       p.payeeName,
       t.taxType,
       t.value businessTax,
       userInput.grossAmount,
       userInput.taxableBase,
       CAST(userInput.taxableBase * t.value as decimal(11,2)) as taxAmount,
       userInput.grossAmount - (CAST(userInput.taxableBase * t.value as decimal(11,2))) as netOfVAT,
       particulars,
       accounts,
       NOW(),
       1,
       e.type,
       e.value ewtTax,
       ewtBase
FROM
(
    SELECT CONCAT('AP-',YEAR(NOW()),MONTH(NOW()),DAY(NOW()),'-',(COUNT(*) + 1)) as ap_id,
           paccountNumber as accountNumber,
           pDate as date,
           ppayee as payee,
           pgross as grossAmount,
           ptaxBase as taxableBase,
           pparticulars as particulars,
           paccounts as accounts,
           pewtBase as ewtBase
    FROM ap_entry
) userInput
INNER JOIN bnks b ON userInput.accountNumber = b.accountNumber
INNER JOIN pyee p ON userInput.payee = p.payeeName
INNER JOIN txtype t ON p.taxType = t.taxType
INNER JOIN ewt e ON p.ewt = e.id

SELECT COUNT(*) FROM tempt
END

Body:
In your query semi colon is missing.

DELIMITER $$

CREATE PROCEDURE test()
BEGIN
CREATE TEMPORARY TABLE tempt
SELECT userInput.ap_id,
       b.accountName,
       b.accountNumber,
       userInput.date,
       p.payeeName,
       t.taxType,
       t.value businessTax,
       userInput.grossAmount,
       userInput.taxableBase,
       CAST(userInput.taxableBase * t.value as decimal(11,2)) as taxAmount,
       userInput.grossAmount - (CAST(userInput.taxableBase * t.value as decimal(11,2))) as netOfVAT,
       particulars,
       accounts,
       NOW(),
       1,
       e.type,
       e.value ewtTax,
       ewtBase
FROM
(
    SELECT CONCAT('AP-',YEAR(NOW()),MONTH(NOW()),DAY(NOW()),'-',(COUNT(*) + 1)) as ap_id,
           paccountNumber as accountNumber,
           pDate as date,
           ppayee as payee,
           pgross as grossAmount,
           ptaxBase as taxableBase,
           pparticulars as particulars,
           paccounts as accounts,
           pewtBase as ewtBase
    FROM ap_entry
) userInput
INNER JOIN bnks b ON userInput.accountNumber = b.accountNumber
INNER JOIN pyee p ON userInput.payee = p.payeeName
INNER JOIN txtype t ON p.taxType = t.taxType
INNER JOIN ewt e ON p.ewt = e.id; -- semi colon missing

SELECT COUNT(*) FROM tempt; -- semi colon missing
END
$$
DELIMITER ; -- changed back to default


问:
Laravel policy autodetect
today i was creating USER profile page with is controlled in ProfileController it returning views to profile page, profile settings, etc.

so i decide to make some Policy rules to Edit profile and etc.

so i found i should use Middleware / Gates / Policy, based on Laravel Doc i chose Policy because profil page is public but only specific part of it can author edit so i needed @can

So my steps:

php artisan make:policy ProfilePolicy ( without model )

Registered policy to AuthServiceProvider in $policies property

writed methods like edit inside ProfilePolicy

then i started thinking how i define it to my Controller hmmm, documentation doesnt helps me :/

so i tryed blade @can('edit', $user) method and it worked, but HOW ?, how to define specific policy to one Controller ? ( not Model ), how to define multiple Policy to single Controller

i m lost how laravel Magic done this maybe because of Naming ? ProfileController => ProfilePolicy ?

答:
In the controller you can write this

```<code>public function edit(Profile $profile) {
   $this->authorize('edit', $profile)
}
</code>```

Laravel does this:

Check the type of $profile, and it's a Profile::class

Check policies registered for that class (your step 2)

Looks for the edit method in that policy, if not found, return false meaning user is not authorized

Executes the edit() function that returns true/false

In blade the @can directive does exactly the same thing.

Policies are meant to be tied to Models, it's a convenient way to write rules to handle single models, but they can be triggered in many ways (like the authorize() method in controllers and @can directive in blade).

Title: Laravel policy autodetect

Body:
In the controller you can write this

public function edit(Profile $profile) {
   $this->authorize('edit', $profile)
}

Laravel does this:

Check the type of $profile, and it's a Profile::class

Check policies registered for that class (your step 2)

Looks for the edit method in that policy, if not found, return false meaning user is not authorized

Executes the edit() function that returns true/false

In blade the @can directive does exactly the same thing.

Policies are meant to be tied to Models, it's a convenient way to write rules to handle single models, but they can be triggered in many ways (like the authorize() method in controllers and @can directive in blade).


问:
Storing clustering result
Given my pandas df, I am doing hierarchical clustering of the correlation matrix as follows:

```<code>import scipy.cluster.hierarchy as sch

X = df.corr().values
d = sch.distance.pdist(X)
L = sch.linkage(d, method='complete')
C = sch.fcluster(L, 0.5*d.max(), 'distance')
</code>```

I need help performing the following simple task. I would like a new df_res with two columns: (1) The name of the variable as given by the columns of my original df, (2) the cluster that it belongs to based on the results in C. Something like:

```<code>VAR     CLUSTER
var_1   1
var_2   2
var_3   1
var_4   1
var_5   2
</code>```

Thanks in advance!

答:
You could create desired dataframe like this</p>

```<code>df_res = pd.DataFrame([{'VAR': x, 'CLUSTER': y} for (x,y) in zip(df.columns, C)])
</code>```

Title: Storing clustering result

Body:
Given my pandas df, I am doing hierarchical clustering of the correlation matrix as follows:

import scipy.cluster.hierarchy as sch

X = df.corr().values
d = sch.distance.pdist(X)
L = sch.linkage(d, method='complete')
C = sch.fcluster(L, 0.5*d.max(), 'distance')

I need help performing the following simple task. I would like a new df_res with two columns: (1) The name of the variable as given by the columns of my original df, (2) the cluster that it belongs to based on the results in C. Something like:

VAR     CLUSTER
var_1   1
var_2   2
var_3   1
var_4   1
var_5   2

Thanks in advance!

Body:
You could create desired dataframe like this

df_res = pd.DataFrame([{'VAR': x, 'CLUSTER': y} for (x,y) in zip(df.columns, C)])


问:
How to simulate ```WHERE``` from SQL or ```grep``` in Python to iterate and change data with certain attributes?
I'm looking for a quick and simple tool to simulate WHERE from SQL. In a collection (list, set, dictionary, etc) of objects (each of which should be a list or class instance), I'd like to pick out just those with some certain properties/attributes and process them.

Example 1:

```<code>stuff = {
    "item1":[1,2,3],
    "item2":[4,5,6,7,8,9],
    "item3":[2,4,5]
}

def myfunc(this): # this is the dict above
    result = list()
    for item in this:
        if len(item) == 3:
            result.append(item)
    return result
</code>```

In example 1, myfunc simulates return items in stuff WHERE len(item)==3 which looks for and returns objects with length 3 in the dictionary stuff.

Example 2:

```<code>class thing:
    def init(self, a, b, c):
        self.a = a
        self.b = b
        self.c = c

item1 = thing(1,2,3)
item2 = thing(2,3,4)
item3 = thing(3,5,7)
test_list = [item1, item2, item3]

def func(this): # this is the test_list
    result = list()
    for item in this:
        if item.a % 2:
            result.append(item)
    return result
</code>```

In example 2, func simulates return items in test_list WHERE (item.a % 2) == 1 which returns objects where object.a is odd.

In both examples, a collection of objects is scanned for certain attributes that meet certain conditions and return those objects to be processed.

答:
You can use __dict__ of an instance to access all the instance variables.
If you need to apply certain conditions like being int or something else you can use instainceof or similar.

```<code>class particle(object):
    def __init__(self):
        self.height = 100

particles = [particle() for _ in range(2)]

for item in particles:
    item.height -= 1

for item in particles:
    for key in item.__dict__.keys():
        item.__dict__[key] = 5
</code>```

item.__dict__[key] = 5 => Here I access the instance variables and change the value. If you need to add condition you can add here.

Body:
I'm looking for a quick and simple tool to simulate WHERE from SQL. In a collection (list, set, dictionary, etc) of objects (each of which should be a list or class instance), I'd like to pick out just those with some certain properties/attributes and process them.

Example 1:

stuff = {
    "item1":[1,2,3],
    "item2":[4,5,6,7,8,9],
    "item3":[2,4,5]
}

def myfunc(this): # this is the dict above
    result = list()
    for item in this:
        if len(item) == 3:
            result.append(item)
    return result

In example 1, myfunc simulates return items in stuff WHERE len(item)==3 which looks for and returns objects with length 3 in the dictionary stuff.

Example 2:

class thing:
    def init(self, a, b, c):
        self.a = a
        self.b = b
        self.c = c

item1 = thing(1,2,3)
item2 = thing(2,3,4)
item3 = thing(3,5,7)
test_list = [item1, item2, item3]

def func(this): # this is the test_list
    result = list()
    for item in this:
        if item.a % 2:
            result.append(item)
    return result

In example 2, func simulates return items in test_list WHERE (item.a % 2) == 1 which returns objects where object.a is odd.

In both examples, a collection of objects is scanned for certain attributes that meet certain conditions and return those objects to be processed.

Body:
You can use __dict__ of an instance to access all the instance variables.
If you need to apply certain conditions like being int or something else you can use instainceof or similar.

class particle(object):
    def __init__(self):
        self.height = 100

particles = [particle() for _ in range(2)]

for item in particles:
    item.height -= 1

for item in particles:
    for key in item.__dict__.keys():
        item.__dict__[key] = 5

item.__dict__[key] = 5 => Here I access the instance variables and change the value. If you need to add condition you can add here.


问:
Bash command with pipe not working in crontab
I need to delete files under directory except latest 2.

I have prepared command to list according to date and delete files. It work when I run manually from command line , however it does not work in crontab.

In crontab,

```<code>* * * * * /bin/ls -t /mytest | /usr/bin/tail -n +2 | /usr/bin/xargs rm --
</code>```

This command works when I run this command from commandline.

Also tried to add command in bash script then called that script from crontab but it did not work again.

How can I run that command via crontab?

答:
crontab only expects one command.
If multiple commands are to be executed, they can be bundled using bash -c</p>

```<code>* * * * * bash -c 'ls -t /mytest | tail -n +2 | xargs rm --'
</code>```

Body:
I need to delete files under directory except latest 2.

I have prepared command to list according to date and delete files. It work when I run manually from command line , however it does not work in crontab.

In crontab,

* * * * * /bin/ls -t /mytest | /usr/bin/tail -n +2 | /usr/bin/xargs rm --

This command works when I run this command from commandline.

Also tried to add command in bash script then called that script from crontab but it did not work again.

How can I run that command via crontab?

Body:
crontab only expects one command.
If multiple commands are to be executed, they can be bundled using bash -c

* * * * * bash -c 'ls -t /mytest | tail -n +2 | xargs rm --'


问:
Testing and mocking fetch in async useEffect and async Redux-Saga
I'm testing a functional component, that use React-Hooks and Redux-Saga. I can pass parameters in URL for the component, because they are a login page component.

My URL i pass is 'localhost/access/parameter', and when this parameter exists, i need to call a async redux saga, and if the fetch is OK, i put the result in redux-store. When the result is on redux-store, i have a useEffect that verify the result and if is OK, i put her in a input.

I can mock the result with axios, but i'm migrating to use only fetch. i mock the fetch, but when i use
mount(component), provided by enzyme, i do not how to await the redux-saga termine the request and useEffect do your job. I put a console log inside a effect, saga and log the input props to see your value prop, but the value is always empty . I tried to use setImmediate() and process.nextTick().

Links i use to write the code: 1,2, 3

I'm using formik, so they pass some props to me.

My component

```<code>const Login = ({
  setFieldError, errors, response, fetchDomain, location, values, handleChange, handleBlur, setFieldValue, history,
}) => {

   useEffect(() => {
    async function fetchUrlDomain() {
      const { pathname } = location;
      const [, , domain] = pathname.split('/');

      if (typeof domain !== 'undefined') {
        await fetchDomain(domain);
      }
    }

    fetchUrlDomain();
  }, [fetchDomain, location]);

   useEffect(() => {
    if (typeof response === 'string') {
      setFieldError('domain', 'Domain not found');
      inputDomain.current.focus();
    } else if (Object.keys(response).length > 0) {
      setFieldValue('domain', response.Domain);
      setFieldError('domain', '');
    }
  }, [response, setFieldValue, setFieldError]);

return (
  <input name="domain" id="domain" value={values.domain} onChange={handleChange} onBlur={handleBlur} type="text" />
);
}

const LoginFormik = withFormik({
  mapPropsToValues: () => ({ domain: '' }),
  enableReinitialize: false,
  validateOnBlur: false,
  validateOnChange: false,
})(Login);

const mapStateToProps = () => ({ });

const mapDispatchToProps = dispatch => ({
  fetchDomain: (value) => {
    dispatch(action({}, constants.RESET_RESPONSE_DOMAIN));
    dispatch(action(value, constants.FETCH_DOMAIN_REQUEST));
  },
});

export default connect(mapStateToProps, mapDispatchToProps)(LoginFormik);
</code>```

My Saga

```<code>export function* fetchDomain(action) {
  const url = yield `${mainUrl}/${action.payload}`;
  try {
    const response = yield fetch(url).then(res => res.json());
    yield put(reduxAction(response , constants.FETCH_DOMAIN_SUCCESS));
  } catch (e) {
    yield put(reduxAction(e, constants.FETCH_DOMAIN_FAILURE));
  }
}
</code>```

My Reducer

```<code>case constants.FETCH_DOMAIN_FAILURE:
  return { ...initialState, response: 'Domain not found' };
case constants.FETCH_DOMAIN_SUCCESS: {
  const { payload } = action;
  return {
    ...initialState,
    id: payload.Id,
    apis: payload.Apis,
    response: payload,
  };
}
case constants.RESET_RESPONSE_DOMAIN:
  return { ...initialState };
</code>```

My Test

```<code>it('input with fetch only', (done) => {
  const mockSuccessResponse = {
    Id: 'fafafafa',
    Apis: [],
    Domain: 'NAME',
  };
  const mockJsonPromise = Promise.resolve(mockSuccessResponse);
  const mockFetchPromise = Promise.resolve({
    json: () => mockJsonPromise,
  });

  global.fetch = jest.fn().mockImplementation(() => mockFetchPromise);

  const wrapper = mount(
    <Provider store={store}>
      <LoginForm
        history={{ push: jest.fn() }}
        location={{ pathname: 'localhost/login/Domain' }}
      />
    </Provider>,
  );

  process.nextTick(() => {
    const input = wrapper.find('#domain');
    console.log(input.props());
    expect(input.props().value.toLowerCase()).toBe('name');

    global.fetch.mockClear();
    done();
  });
});
</code>```

I expect my input have value, but he don't. I tried to use jest-fetch-mock but just don't work, and i want to use native jest methods, no thirty party libraries.

答:
I cannot say what's wrong with your current code. But want to propose different approach instead.

Currently you are testing both redux part and component's one. It contradicts with unit testing strategy when ideally you should mock everything except module under the test.

So I mean if you focus on testing component itself it'd be way easier(less mocks to create) and more readable. For that you need additionally export unwrapped component(Login in your case). Then you can test only its props-vs-render result:

```<code>it('calls fetchDomain() with domain part of location', () => {
    const fetchDomain = jest.fn();
    const location = { pathName: 'example.com/path/sub' }
    shallow(<Login fetchDomain={fetchDomain} location={location} />);
    expect(fetchDomain).toHaveBeenCalledTimes(1);
    expect(fetchDomain).toHaveBeenCalledWith('example.com');
});

it('re-calls fetchDomain() on each change of location prop', () => {
    const fetchDomain = jest.fn();
    const location = { pathName: 'example.com/path/sub' }
    const wrapper = shallow(<Login fetchDomain={fetchDomain} location={location} />);
    fetchDomain.mockClear();
    wrapper.setProps({ location: { pathName: 'another.org/path' } });
    expect(fetchDomain).toHaveBeenCalledTimes(1);
    expect(fetchDomain).toHaveBeenCalledWith('another.org');
});
</code>```

And the same for other cases. See with this approach if you replace redux with direct call to fetch() or whatever, or if you refactor that data to come from parent instead of reading from redux store you will not need to rewrite tests removing mocks to redux. Sure, you will still need to test redux part but it also can be done in isolation.

PS and there is no profit to await fetchDomain(...)  in useEffect since you don't use what it returns. await does not work like a pause and that code may rather confuse reader.

Body:
I'm testing a functional component, that use React-Hooks and Redux-Saga. I can pass parameters in URL for the component, because they are a login page component.

My URL i pass is 'localhost/access/parameter', and when this parameter exists, i need to call a async redux saga, and if the fetch is OK, i put the result in redux-store. When the result is on redux-store, i have a useEffect that verify the result and if is OK, i put her in a input.

I can mock the result with axios, but i'm migrating to use only fetch. i mock the fetch, but when i use
mount(component), provided by enzyme, i do not how to await the redux-saga termine the request and useEffect do your job. I put a console log inside a effect, saga and log the input props to see your value prop, but the value is always empty . I tried to use setImmediate() and process.nextTick().

Links i use to write the code: 1,2, 3

I'm using formik, so they pass some props to me.

My component

const Login = ({
  setFieldError, errors, response, fetchDomain, location, values, handleChange, handleBlur, setFieldValue, history,
}) => {

   useEffect(() => {
    async function fetchUrlDomain() {
      const { pathname } = location;
      const [, , domain] = pathname.split('/');

      if (typeof domain !== 'undefined') {
        await fetchDomain(domain);
      }
    }

    fetchUrlDomain();
  }, [fetchDomain, location]);

   useEffect(() => {
    if (typeof response === 'string') {
      setFieldError('domain', 'Domain not found');
      inputDomain.current.focus();
    } else if (Object.keys(response).length > 0) {
      setFieldValue('domain', response.Domain);
      setFieldError('domain', '');
    }
  }, [response, setFieldValue, setFieldError]);

return (
  <input name="domain" id="domain" value={values.domain} onChange={handleChange} onBlur={handleBlur} type="text" />
);
}

const LoginFormik = withFormik({
  mapPropsToValues: () => ({ domain: '' }),
  enableReinitialize: false,
  validateOnBlur: false,
  validateOnChange: false,
})(Login);

const mapStateToProps = () => ({ });

const mapDispatchToProps = dispatch => ({
  fetchDomain: (value) => {
    dispatch(action({}, constants.RESET_RESPONSE_DOMAIN));
    dispatch(action(value, constants.FETCH_DOMAIN_REQUEST));
  },
});

export default connect(mapStateToProps, mapDispatchToProps)(LoginFormik);

My Saga

export function* fetchDomain(action) {
  const url = yield `${mainUrl}/${action.payload}`;
  try {
    const response = yield fetch(url).then(res => res.json());
    yield put(reduxAction(response , constants.FETCH_DOMAIN_SUCCESS));
  } catch (e) {
    yield put(reduxAction(e, constants.FETCH_DOMAIN_FAILURE));
  }
}

My Reducer

case constants.FETCH_DOMAIN_FAILURE:
  return { ...initialState, response: 'Domain not found' };
case constants.FETCH_DOMAIN_SUCCESS: {
  const { payload } = action;
  return {
    ...initialState,
    id: payload.Id,
    apis: payload.Apis,
    response: payload,
  };
}
case constants.RESET_RESPONSE_DOMAIN:
  return { ...initialState };

My Test

it('input with fetch only', (done) => {
  const mockSuccessResponse = {
    Id: 'fafafafa',
    Apis: [],
    Domain: 'NAME',
  };
  const mockJsonPromise = Promise.resolve(mockSuccessResponse);
  const mockFetchPromise = Promise.resolve({
    json: () => mockJsonPromise,
  });

  global.fetch = jest.fn().mockImplementation(() => mockFetchPromise);

  const wrapper = mount(
    <Provider store={store}>
      <LoginForm
        history={{ push: jest.fn() }}
        location={{ pathname: 'localhost/login/Domain' }}
      />
    </Provider>,
  );

  process.nextTick(() => {
    const input = wrapper.find('#domain');
    console.log(input.props());
    expect(input.props().value.toLowerCase()).toBe('name');

    global.fetch.mockClear();
    done();
  });
});

I expect my input have value, but he don't. I tried to use jest-fetch-mock but just don't work, and i want to use native jest methods, no thirty party libraries.

Body:
I cannot say what's wrong with your current code. But want to propose different approach instead.

Currently you are testing both redux part and component's one. It contradicts with unit testing strategy when ideally you should mock everything except module under the test.

So I mean if you focus on testing component itself it'd be way easier(less mocks to create) and more readable. For that you need additionally export unwrapped component(Login in your case). Then you can test only its props-vs-render result:

it('calls fetchDomain() with domain part of location', () => {
    const fetchDomain = jest.fn();
    const location = { pathName: 'example.com/path/sub' }
    shallow(<Login fetchDomain={fetchDomain} location={location} />);
    expect(fetchDomain).toHaveBeenCalledTimes(1);
    expect(fetchDomain).toHaveBeenCalledWith('example.com');
});

it('re-calls fetchDomain() on each change of location prop', () => {
    const fetchDomain = jest.fn();
    const location = { pathName: 'example.com/path/sub' }
    const wrapper = shallow(<Login fetchDomain={fetchDomain} location={location} />);
    fetchDomain.mockClear();
    wrapper.setProps({ location: { pathName: 'another.org/path' } });
    expect(fetchDomain).toHaveBeenCalledTimes(1);
    expect(fetchDomain).toHaveBeenCalledWith('another.org');
});

And the same for other cases. See with this approach if you replace redux with direct call to fetch() or whatever, or if you refactor that data to come from parent instead of reading from redux store you will not need to rewrite tests removing mocks to redux. Sure, you will still need to test redux part but it also can be done in isolation.

PS and there is no profit to await fetchDomain(...)  in useEffect since you don't use what it returns. await does not work like a pause and that code may rather confuse reader.


问:
Node.js server.address().address returns ::
If I remember correctly it used to display "localhost" a few days ago. I am not sure what had changed that made server.address().address return double colons (::) instead.
I read here that it returns an IPv6 address (::) if it is available but it's disabled on my PC.
https://nodejs.org/api/http.html#http_server_listen_port_hostname_backlog_callback</p>

答:
The reason why its choosing IPV6 address is possibly because some other process is using IPV4 port no 3456.
This happens sometimes due to automatic updates where new processes are installed. </p>


问:
Algolia-specific => How to access hit attributes within react jsx
I have a clickable hit element in a page set up like so:

```<code><div>
    <InstantSearch>
        <div>
            <SearchBox/>
            <InfiniteHits/>
        </div>
    </InstantSearch>
</div>
</code>```

wherein InfiniteHits is a consortium of Hit objects:

```<code>//Hit.js
<a onClick={() => this.handleSubmit(props.hit.attrib1, props.hit.attrib2)}>
    <img src={props.hit.image} align="left" alt={props.hit.name} />
    <div className="hit-name">
        <Highlight className="ais-Highlight-header" attribute="attrib1" hit={props.hit} />
        <Highlight className="ais-Highlight-state" attribute="attrib2" hit={props.hit} />
    </div>
    <p/>
    <div className="hit-description">
        <Highlight attribute="attrib3" hit={props.hit} />
    </div>
</a>
</code>```

and you can probably see what I was trying to do with onClick at this point,which is to save attrib1 and attrib2 into a state (but really anywhere) via handleSubmit:

```<code>handleSubmit = (attrib1, attrib2) => {
    this.setState({
        attrib1: attrib1,
        attrib2: attrib2
    });
}
</code>```

I'm pretty sure this hasn't been working because I console.log()'ed the inputs to handleSubmit and attrib1 and attrib2 were showing up as undefined.

TLDR: My question is, how can I access attributes (which I have made sure via Algolia Indice Configuration are available client side) within my code so that I'm able to store what exactly was clicked on for use in the next page?

For the curious, this is basically the full Hit file I'm working with:

```<code>class Hit extends React.Component{
    constructor(props){
        super(props);
        this.state = {
            attrib1: null,
            attrib2: null
        };
    }

    render() {
        const props = this.props;
        return(
            <a id="cssID" href="/nextpage" onClick={() => this.handleSubmit(props.hit.attrib1, props.hit.attrib2)}>
                <img src={props.hit.image} align="left" alt={props.hit.name} />
                <div className="hit-name">
                    <Highlight className="ais-Highlight-header" attribute="attrib1" hit={props.hit} />
                    <Highlight className="ais-Highlight-state" attribute="attrib2" hit={props.hit} />
                </div>
                <p/>
                <div className="hit-description">
                    <Highlight attribute="attrib3" hit={props.hit} />
                </div>
            </a>
        )
    }
    handleSubmit = (attrib1, attrib2) => {
        this.setState({
            attrib1: attrib1,
            attrib2: attrib2
        });
        console.log(attrib1);//undefined :/
    }

}
</code>```

答:
The Hits & InfiniteHits expose a hitComponent prop that takes a component to render each of the record retrieved from Algolia. The hitComponent is rendered with a hit prop that contain the information stored inside your record. Here is an example of a record:

```<code>{
  "name": "MyName",
  "description": "MyDescription"
}
</code>```

We can now create our component to render this record:

```<code>class Hit extends React.Component {
  onClickHanlder = (name, description) => {
    console.log(name);
    console.log(description);
  };

  render() {
    const { hit } = this.props;

    return (
      <article>
        <h1>{hit.name}</h1>
        <button onClick={() => this.onClickHanlder(hit.name, hit.description)}>
          Click on the Hit element
        </button>
      </article>
    );
  }
}
</code>```

You can find this example on CodeSandbox.

Body:
I have a clickable hit element in a page set up like so:

    <InstantSearch>

            <SearchBox/>
            <InfiniteHits/>

    </InstantSearch>

wherein InfiniteHits is a consortium of Hit objects:

//Hit.js
 this.handleSubmit(props.hit.attrib1, props.hit.attrib2)}>

        <Highlight className="ais-Highlight-header" attribute="attrib1" hit={props.hit} />
        <Highlight className="ais-Highlight-state" attribute="attrib2" hit={props.hit} />

        <Highlight attribute="attrib3" hit={props.hit} />

and you can probably see what I was trying to do with onClick at this point,which is to save attrib1 and attrib2 into a state (but really anywhere) via handleSubmit:

handleSubmit = (attrib1, attrib2) => {
    this.setState({
        attrib1: attrib1,
        attrib2: attrib2
    });
}

I'm pretty sure this hasn't been working because I console.log()'ed the inputs to handleSubmit and attrib1 and attrib2 were showing up as undefined.

TLDR: My question is, how can I access attributes (which I have made sure via Algolia Indice Configuration are available client side) within my code so that I'm able to store what exactly was clicked on for use in the next page?

For the curious, this is basically the full Hit file I'm working with:

class Hit extends React.Component{
    constructor(props){
        super(props);
        this.state = {
            attrib1: null,
            attrib2: null
        };
    }

    render() {
        const props = this.props;
        return(
             this.handleSubmit(props.hit.attrib1, props.hit.attrib2)}>

                    <Highlight className="ais-Highlight-header" attribute="attrib1" hit={props.hit} />
                    <Highlight className="ais-Highlight-state" attribute="attrib2" hit={props.hit} />

                    <Highlight attribute="attrib3" hit={props.hit} />

        )
    }
    handleSubmit = (attrib1, attrib2) => {
        this.setState({
            attrib1: attrib1,
            attrib2: attrib2
        });
        console.log(attrib1);//undefined :/
    }

}

Body:
The Hits & InfiniteHits expose a hitComponent prop that takes a component to render each of the record retrieved from Algolia. The hitComponent is rendered with a hit prop that contain the information stored inside your record. Here is an example of a record:

{
  "name": "MyName",
  "description": "MyDescription"
}

We can now create our component to render this record:

class Hit extends React.Component {
  onClickHanlder = (name, description) => {
    console.log(name);
    console.log(description);
  };

  render() {
    const { hit } = this.props;

    return (
      <article>
        <h1>{hit.name}</h1>
        <button onClick={() => this.onClickHanlder(hit.name, hit.description)}>
          Click on the Hit element
        </button>
      </article>
    );
  }
}

You can find this example on CodeSandbox.


问:
tensorflow Adamoptimizer beta1_power not initialized
I'm doing transfer learning, thus I pre-trained a network, saved the variables (w, b) in a file; closed the program; re-opened another program; restored all old variables; defined some new layers of variables, initialized them; then started re-training. SGD optimizer works in my code, but if I change the optimizer to Adam, it gives me the following error:

2017-08-03 21:28:08.785092: W tensorflow/core/framework/op_kernel.cc:1152] Failed precondition: Attempting to use uninitialized value beta1_power

My code:

```<code># Session Start
sess = tf.Session()
# restore pre-trained parameters
saver = tf.train.Saver()
saver.restore(sess, "./pre_train/step1.ckpt")
# init new parameters
weights2 = {
    'fnn_w1': tf.Variable(tf.random_normal([n_hidden_2, n_hidden_1], stddev= sd), name='fnn_w1'),
    'fnn_w2': tf.Variable(tf.random_normal([n_hidden_1, 1], stddev= sd), name='fnn_w2')
}
biases2 = {
    'fnn_b1': tf.Variable(tf.ones([n_hidden_1]), name='fnn_b1'),
    'fnn_b2': tf.Variable(tf.ones([1]), name='fnn_b2')
}
parameters2 = {**weights2, **biases2}
init_params2 = tf.variables_initializer(parameters2.values())
sess.run(init_params2)

# Construct model
encoder_op = encoder(X)
focusFnn_op = focusFnn(encoder_op)  # for one gene a time prediction
decoder_op = decoder(encoder_op)  # for pearson correlation of the whole matrix #bug (8092, 0)

# Prediction and truth
y_pred = focusFnn_op  # [m, 1]
y_true = X[:, j]
y_benchmark = M[:, j]  # benchmark for cost_fnn
M_train = df2_train.values[:, j:j+1]  # benchmark for corr
M_valid = df2_valid.values[:, j:j+1]

# Define loss and optimizer, minimize the squared error
with tf.name_scope("Metrics"):
    cost_fnn = tf.reduce_mean(tf.pow(y_true - y_pred, 2))
    cost_fnn_benchmark = tf.reduce_mean(tf.pow(y_pred- y_benchmark, 2))
    cost_decoder = tf.reduce_mean(tf.pow(X - decoder_op, 2))
    cost_decoder_benchmark = tf.reduce_mean(tf.pow(decoder_op - M, 2))
    tf.summary.scalar('cost_fnn', cost_fnn)
    tf.summary.scalar('cost_fnn_benchmark', cost_fnn_benchmark)
    tf.summary.scalar('cost_decoder', cost_decoder)
    tf.summary.scalar('cost_decoder_benchmark', cost_decoder_benchmark)

# optimizer = (
#     tf.train.GradientDescentOptimizer(learning_rate).
#     minimize(cost_fnn, var_list=[list(weights2.values()), list(biases2.values())])
# )# frozen other variables

optimizer = (
    tf.train.GradientDescentOptimizer(learning_rate).
    minimize(cost_fnn)
)# frozen other variables
print("# Updated layers: ", "fnn layers\n")

train_writer = tf.summary.FileWriter(log_dir+'/train', sess.graph)
valid_writer = tf.summary.FileWriter(log_dir+'/valid', sess.graph)
# benchmark_writer = tf.summary.FileWriter(log_dir+'/benchmark', sess.graph)

# Evaluate the init network
[cost_train, h_train] = sess.run([cost_fnn, y_pred], feed_dict={X: df_train.values})
[cost_valid, h_valid] = sess.run([cost_fnn, y_pred], feed_dict={X: df_valid.values})
</code>```

答:
I solved it by adding:

```<code>tf.reset_default_graph()
</code>```

before the graph construction.

However, you still have to make sure the solver declaration is done before the creation of the Saver:

```<code>solver = tf.train.AdamOptimizer().minimize(loss)
...
saver = tf.train.Saver()
</code>```

Reference:
http://stackoverflow.com/questions/33765336/remove-nodes-from-graph-or-reset-entire-default-graph
https://github.com/tflearn/tflearn/blob/master/examples/basics/weights_loading_scope.py

Body:
I'm doing transfer learning, thus I pre-trained a network, saved the variables (w, b) in a file; closed the program; re-opened another program; restored all old variables; defined some new layers of variables, initialized them; then started re-training. SGD optimizer works in my code, but if I change the optimizer to Adam, it gives me the following error:

2017-08-03 21:28:08.785092: W tensorflow/core/framework/op_kernel.cc:1152] Failed precondition: Attempting to use uninitialized value beta1_power

My code:

# Session Start
sess = tf.Session()
# restore pre-trained parameters
saver = tf.train.Saver()
saver.restore(sess, "./pre_train/step1.ckpt")
# init new parameters
weights2 = {
    'fnn_w1': tf.Variable(tf.random_normal([n_hidden_2, n_hidden_1], stddev= sd), name='fnn_w1'),
    'fnn_w2': tf.Variable(tf.random_normal([n_hidden_1, 1], stddev= sd), name='fnn_w2')
}
biases2 = {
    'fnn_b1': tf.Variable(tf.ones([n_hidden_1]), name='fnn_b1'),
    'fnn_b2': tf.Variable(tf.ones([1]), name='fnn_b2')
}
parameters2 = {**weights2, **biases2}
init_params2 = tf.variables_initializer(parameters2.values())
sess.run(init_params2)

# Construct model
encoder_op = encoder(X)
focusFnn_op = focusFnn(encoder_op)  # for one gene a time prediction
decoder_op = decoder(encoder_op)  # for pearson correlation of the whole matrix #bug (8092, 0)

# Prediction and truth
y_pred = focusFnn_op  # [m, 1]
y_true = X[:, j]
y_benchmark = M[:, j]  # benchmark for cost_fnn
M_train = df2_train.values[:, j:j+1]  # benchmark for corr
M_valid = df2_valid.values[:, j:j+1]

# Define loss and optimizer, minimize the squared error
with tf.name_scope("Metrics"):
    cost_fnn = tf.reduce_mean(tf.pow(y_true - y_pred, 2))
    cost_fnn_benchmark = tf.reduce_mean(tf.pow(y_pred- y_benchmark, 2))
    cost_decoder = tf.reduce_mean(tf.pow(X - decoder_op, 2))
    cost_decoder_benchmark = tf.reduce_mean(tf.pow(decoder_op - M, 2))
    tf.summary.scalar('cost_fnn', cost_fnn)
    tf.summary.scalar('cost_fnn_benchmark', cost_fnn_benchmark)
    tf.summary.scalar('cost_decoder', cost_decoder)
    tf.summary.scalar('cost_decoder_benchmark', cost_decoder_benchmark)

# optimizer = (
#     tf.train.GradientDescentOptimizer(learning_rate).
#     minimize(cost_fnn, var_list=[list(weights2.values()), list(biases2.values())])
# )# frozen other variables

optimizer = (
    tf.train.GradientDescentOptimizer(learning_rate).
    minimize(cost_fnn)
)# frozen other variables
print("# Updated layers: ", "fnn layers\n")

train_writer = tf.summary.FileWriter(log_dir+'/train', sess.graph)
valid_writer = tf.summary.FileWriter(log_dir+'/valid', sess.graph)
# benchmark_writer = tf.summary.FileWriter(log_dir+'/benchmark', sess.graph)

# Evaluate the init network
[cost_train, h_train] = sess.run([cost_fnn, y_pred], feed_dict={X: df_train.values})
[cost_valid, h_valid] = sess.run([cost_fnn, y_pred], feed_dict={X: df_valid.values})

Body:
I solved it by adding:

tf.reset_default_graph()

before the graph construction.

However, you still have to make sure the solver declaration is done before the creation of the Saver:

solver = tf.train.AdamOptimizer().minimize(loss)
...
saver = tf.train.Saver()

Reference:
http://stackoverflow.com/questions/33765336/remove-nodes-from-graph-or-reset-entire-default-graph
https://github.com/tflearn/tflearn/blob/master/examples/basics/weights_loading_scope.py


问:
xxd without line number but keep character encoding
I know that using -p can output in plain hexdump style, but I want to keep the character encoding in the righthand column and separation of the output. Does xxp have any options to do this?

答:
It doesn't but you can use additional tools:

```<code>xxd file | cut -d' ' -f 2-
</code>```

Use cut to split by spaces and skip the 1st field.

Body:
It doesn't but you can use additional tools:

xxd file | cut -d' ' -f 2-

Use cut to split by spaces and skip the 1st field.


问:
Update code generated by Swagger code-gen
I have generated the code from swagger.yaml file using swagger code-gen in spring.

Now I have updated the swagger.yaml file for my API and added few more HTTP operations.

Will it be possible to update the existing code generated previously automatically without merging it manually?

答:
Having the same issue, I found the solution to start with by applying git

commit the current status

run the generator

use git to stage the intended changes but do not stage reversal of your manual edits

commit and continue

I just start with this approach but it seems to work at least for php-slim where only one file (index.php) is changed when regenerating.


问:
Android: ProgressDialog doesn't show
I'm trying to create a ProgressDialog for an Android-App (just a simple one showing the user that stuff is happening, no buttons or anything) but I can't get it right. I've been through forums and tutorials as well as the Sample-Code that comes with the SDK, but to no avail.

This is what I got:

```<code>    btnSubmit.setOnClickListener(new View.OnClickListener() {
      public void onClick(View view) {
        (...)
          ProgressDialog pd = new ProgressDialog(MyApp.this);
          pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
          pd.setMessage("Working...");
          pd.setIndeterminate(true);
          pd.setCancelable(false);

          // now fetch the results
          (...long time calculations here...)

          // remove progress dialog
          pd.dismiss();
</code>```

I've also tried adding pd.show(); and messed around with the parameter in new ProgressDialog resulting in nothing at all (except errors that the chosen parameter won't work), meaning: the ProgressDialog won't ever show up. The app just keeps running as if I never added the dialog.

I don't know if I'm creating the dialog at the right place, I moved it around a bit but that, too, didnt't help. Maybe I'm in the wrong context? The above code is inside private ViewGroup _createInputForm() in MyApp.

Any hint is appreciated,

答:
I am giving you a solution for it,
try this...
First define the Progress Dialog in the Activity before onCreate() method

```<code>private ProgressDialog progressDialog;
</code>```

Now in the onCreate method you might have the Any button click on which you will change the Activity on any action. Just set the Progress Bar there.

```<code>progressDialog = ProgressDialog.show(FoodDriveModule.this, "", "Loading...");
</code>```

Now use thread to handle the Progress Bar to Display and hide

```<code>new Thread()
{
    public void run()
   {
       try
       {
           sleep(1500);
           // do the background process or any work that takes time to see progress dialog
       }
       catch (Exception e)
       {
           Log.e("tag",e.getMessage());
       }
       // dismiss the progress dialog
       progressDialog.dismiss();
    }
}.start();
</code>```

That is all!

Title: Android: ProgressDialog doesn't show

Body:
I'm trying to create a ProgressDialog for an Android-App (just a simple one showing the user that stuff is happening, no buttons or anything) but I can't get it right. I've been through forums and tutorials as well as the Sample-Code that comes with the SDK, but to no avail.

This is what I got:

    btnSubmit.setOnClickListener(new View.OnClickListener() {
      public void onClick(View view) {
        (...)
          ProgressDialog pd = new ProgressDialog(MyApp.this);
          pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
          pd.setMessage("Working...");
          pd.setIndeterminate(true);
          pd.setCancelable(false);

          // now fetch the results
          (...long time calculations here...)

          // remove progress dialog
          pd.dismiss();

I've also tried adding pd.show(); and messed around with the parameter in new ProgressDialog resulting in nothing at all (except errors that the chosen parameter won't work), meaning: the ProgressDialog won't ever show up. The app just keeps running as if I never added the dialog.

I don't know if I'm creating the dialog at the right place, I moved it around a bit but that, too, didnt't help. Maybe I'm in the wrong context? The above code is inside private ViewGroup _createInputForm() in MyApp.

Any hint is appreciated,

Body:
I am giving you a solution for it,
try this...
First define the Progress Dialog in the Activity before onCreate() method

private ProgressDialog progressDialog;

Now in the onCreate method you might have the Any button click on which you will change the Activity on any action. Just set the Progress Bar there.

progressDialog = ProgressDialog.show(FoodDriveModule.this, "", "Loading...");

Now use thread to handle the Progress Bar to Display and hide

new Thread()
{
    public void run()
   {
       try
       {
           sleep(1500);
           // do the background process or any work that takes time to see progress dialog
       }
       catch (Exception e)
       {
           Log.e("tag",e.getMessage());
       }
       // dismiss the progress dialog
       progressDialog.dismiss();
    }
}.start();

That is all!


问:
Binding vs Arrow-function (in JavaScript, or for react onClick)
So I am trying to learn JavaScript and/or react and got a little mixed up with understanding .bind(this) in the constructor. However, I think to understand it now, and just want to know,

Why would anyone use Binding vs an Arrow-function in JavaScript?

(or in the onClick event).

Is there any pro/con to use one vs the other?

See below code samples.

Binding method ensures this in clickEvent function references the class:

```<code>class Click extends react.Component {
  constructor(props) {
    super(props)
    this.clickEvent = this.clickEvent.bind(this);
  }

  render = () => (
    <button onClick= { this.clickEvent } > Click Me < /button>
  )

  clickEvent() { console.log(this) } // 'this' refers to the class
}
</code>```

However below method also references the class:

```<code>class Click extends react.Component {

  render = () => (
    <button onClick= {() => { this.clickEvent() }}> Click Me < /button>
  )

  clickEvent() { console.log(this) } // 'this' refers to the class
}
</code>```

答:
First of all, let's start with examples of each technique!

But the difference is more related to JavaScript language itself.

Binding:

```<code>import React from 'react';

class MyComponent extends React.Component {
  constructor(props) {
    super(props)
    this.clickHandler = this.clickHandler.bind(this);
  }

  clickHandler() {
    console.log( this )
  }

  render() {
    return <button onClick={this.clickHandler}>Click Me</button>
  }
}
</code>```

Arrow-function:

```<code>import React from 'react';

class MyComponent extends React.Component {
  constructor(props) {
    super(props)
  }

  clickHandler = () => {
    console.log( this )
  }

  render() {
    return <button onClick={this.clickHandler}>Click Me</button>
  }
}
</code>```

Pros and Cons:

Using the Arrow-function on public-class-field is more human-readable,
because of fewer lines of code,
But keep in mind that using Arrow-function can affect three things:

First the memory and performance; When you use a class field to define a function, your whole method resides on each instance of the class and NOT on the prototype, but using the bind technic, just a small callback is stored on each instance, which calls your method that is stored on the prototype.

Second thing that can be affected is how you write your unit tests.
You won't be able to use the component prototype to stub on function calls like below:

```<code>const spy = jest.spyOn(MyComponent.prototype, 'clickHandler');
// ...
expect(spy).toHaveBeenCalled();
</code>```

One would have to find another way to stub the method, for example, either by passing a dummy-callback in props, or checking the state changes.

Lastly the performance;
depending on the JavaScript engine that your script runs on,
using more memory than a certain limit may cause almost random run-time hangs
(aka delay in logic's operation),
and that even when the system is NOT yet low on memory,
but otherwise, logic's run-time performance should be same for both techniques.

See also below "Other tools" section for workaround.

Conclusion

Computers are really good at reading code; you shouldn’t worry about that.
You may want to consider making your code more human-readable by using a class-property arrow-function.

Other tools:

If you want to keep both human-readability and performance, consider using plugin-transform-arrow-functions plugin, just run npm i --save-dev @babel/plugin-transform-arrow-functions and add it into your "babel.config.js" or ".babelrc" file, like:

```<code>{
  "presets": ["module:metro-react-native-babel-preset"],
  "plugins": [
    ["@babel/plugin-proposal-decorators", { "decoratorsBeforeExport": false }],
    ["@babel/plugin-transform-arrow-functions", { "spec": true }]
  ]
}
</code>```

Where "spec": true asks the plugin to auto transform arrow-functions,
into method/function binding (which're in prototype).

Also, seems said plugin is not compatible with react-native (at least versions mentioned in linked post).

Or, you could use something like auto-bind decorator, which would turn above example into:

```<code>import React from 'react';

import { boundMethod as bind } from 'autobind-decorator';

class MyComponent extends React.Component {
  constructor(props) {
    super(props)
  }

  @bind
  clickHandler() {
    console.log( this )
  }

  render() {
    return <button onClick={this.clickHandler}>Click Me</button>
  }
}
</code>```

Note that it's unnecessary to put @bind on every function. You only need to bind functions which you pass around. e.g. onClick={this.doSomething} Or fetch.then(this.handleDone)

Body:
So I am trying to learn JavaScript and/or react and got a little mixed up with understanding .bind(this) in the constructor. However, I think to understand it now, and just want to know,

Why would anyone use Binding vs an Arrow-function in JavaScript?

(or in the onClick event).

Is there any pro/con to use one vs the other?

See below code samples.

Binding method ensures this in clickEvent function references the class:

class Click extends react.Component {
  constructor(props) {
    super(props)
    this.clickEvent = this.clickEvent.bind(this);
  }

  render = () => (
    <button onClick= { this.clickEvent } > Click Me < /button>
  )

  clickEvent() { console.log(this) } // 'this' refers to the class
}

However below method also references the class:

class Click extends react.Component {

  render = () => (
    <button onClick= {() => { this.clickEvent() }}> Click Me < /button>
  )

  clickEvent() { console.log(this) } // 'this' refers to the class
}

Body:
First of all, let's start with examples of each technique!

But the difference is more related to JavaScript language itself.

Binding:

import React from 'react';

class MyComponent extends React.Component {
  constructor(props) {
    super(props)
    this.clickHandler = this.clickHandler.bind(this);
  }

  clickHandler() {
    console.log( this )
  }

  render() {
    return <button onClick={this.clickHandler}>Click Me</button>
  }
}

Arrow-function:

import React from 'react';

class MyComponent extends React.Component {
  constructor(props) {
    super(props)
  }

  clickHandler = () => {
    console.log( this )
  }

  render() {
    return <button onClick={this.clickHandler}>Click Me</button>
  }
}

Pros and Cons:

Using the Arrow-function on public-class-field is more human-readable,
because of fewer lines of code,
But keep in mind that using Arrow-function can affect three things:

First the memory and performance; When you use a class field to define a function, your whole method resides on each instance of the class and NOT on the prototype, but using the bind technic, just a small callback is stored on each instance, which calls your method that is stored on the prototype.

Second thing that can be affected is how you write your unit tests.
You won't be able to use the component prototype to stub on function calls like below:

const spy = jest.spyOn(MyComponent.prototype, 'clickHandler');
// ...
expect(spy).toHaveBeenCalled();

One would have to find another way to stub the method, for example, either by passing a dummy-callback in props, or checking the state changes.

Lastly the performance;
depending on the JavaScript engine that your script runs on,
using more memory than a certain limit may cause almost random run-time hangs
(aka delay in logic's operation),
and that even when the system is NOT yet low on memory,
but otherwise, logic's run-time performance should be same for both techniques.

See also below "Other tools" section for workaround.

Conclusion

Computers are really good at reading code; you shouldn’t worry about that.
You may want to consider making your code more human-readable by using a class-property arrow-function.

Other tools:

If you want to keep both human-readability and performance, consider using plugin-transform-arrow-functions plugin, just run npm i --save-dev @babel/plugin-transform-arrow-functions and add it into your "babel.config.js" or ".babelrc" file, like:

{
  "presets": ["module:metro-react-native-babel-preset"],
  "plugins": [
    ["@babel/plugin-proposal-decorators", { "decoratorsBeforeExport": false }],
    ["@babel/plugin-transform-arrow-functions", { "spec": true }]
  ]
}

Where "spec": true asks the plugin to auto transform arrow-functions,
into method/function binding (which're in prototype).

Also, seems said plugin is not compatible with react-native (at least versions mentioned in linked post).

Or, you could use something like auto-bind decorator, which would turn above example into:

import React from 'react';

import { boundMethod as bind } from 'autobind-decorator';

class MyComponent extends React.Component {
  constructor(props) {
    super(props)
  }

  @bind
  clickHandler() {
    console.log( this )
  }

  render() {
    return <button onClick={this.clickHandler}>Click Me</button>
  }
}

Note that it's unnecessary to put @bind on every function. You only need to bind functions which you pass around. e.g. onClick={this.doSomething} Or fetch.then(this.handleDone)


问:
Accessing this pointer in static function in cpp
I have a cpp class and few methods defined in it.
One of the static methods needs to call the non static method of the same class. I cant do this using "this" pointer as in static function "this" pointer cant be used.

I need someway to access the pointer to the same class in the static method in cpp...can someone pls help

答:
Have the static function take a reference parameter of the class. Example:

```<code>struct Foo {
    void func() { }

    static void static_func(Foo& obj)
    {
        obj.func();
    }
};
</code>```

Usage:

```<code>Foo foo;
Foo::static_func(foo);
</code>```

You can instead use a Foo* obj parameter. In that case, you need to pass a pointer obviously (Foo::static_func(&foo);).

With that being said, your function looks like it shouldn't be static to begin with. Make it non-static.

Body:
Have the static function take a reference parameter of the class. Example:

struct Foo {
    void func() { }

    static void static_func(Foo& obj)
    {
        obj.func();
    }
};

Usage:

Foo foo;
Foo::static_func(foo);

You can instead use a Foo* obj parameter. In that case, you need to pass a pointer obviously (Foo::static_func(&foo);).

With that being said, your function looks like it shouldn't be static to begin with. Make it non-static.


问:
Dragdrop from listbox to listbox in silverlight
I am using a listbox to bind the data coming from the database, once the binding is done there is another listbox where i have to drag and drop the contents of the first listbox. I am able to drag and drop it but nothing is visible in the 2nd listbox(but the content is moving from the 1st to 2nd listbox). The same thing i tried by hardcoding the items in the 1st listbox and everything worked fine. If anybody has experienced similar kind of problem, please help.</p>

答: Make sure you're using ObservableCollection when dragging and dropping between sources. If you used List, then the ListBoxes will not be notified of a change in the collection. </p>


问:
Return data from firebase function to app
In my ionic app I am connecting to a stripe payment gateway.

I have a function in firebase which is being triggered on updating the customer.

```<code>exports.updateStripeCustomer = functions.database.ref("/Customers/{userId}")
  .onUpdate((snapshot, context) => {
    const data = snapshot.after.val();
    return stripe.customers.createSource(data.payment_sources.customer_id, {
        source: data.payment_sources.source
    }).then(customer => {
        console.log("Update Stripe Customer");
        return customer;
    },
        error => {
            return error;
        }
    );
});
</code>```

This is my code in the app end where I am updating the customer. While updating the trigger called in firebase, how do I get the data returned by the trigger (firebase function) in my below code?

```<code> this.angularDb.object('/Customers/' + firebase.auth().currentUser.uid).update({
            cardsetup: 1,
            payment_sources: {
              customer_id: this.user.customer_id,
              source: this.card.source.id
            }
          }).then((res) => {
            loading.dismiss();
            alert("card details has been successfully updated.");
            this.navCtrl.push(LoginPage);

      }, (error) => {
        loading.dismiss();
        console.log("=========>", error.message)
        alert(JSON.stringify(error))
      });
</code>```

If the firebase function returns an error I need to show that error message returned by the trigger. Any way to do this?

答:
The trigger reacts to an event in the database and doesn't know anything about your application. Therefore there is no link between your trigger and your application.

You could add a Transaction collection to your users with a transaction id and a transaction status. Then listen to it from your application and update it from the trigger to get notified when it is complete.

Or your could use a callable cloud functions instead of a trigger.
https://firebase.google.com/docs/functions/callable

Body:
In my ionic app I am connecting to a stripe payment gateway.

I have a function in firebase which is being triggered on updating the customer.

exports.updateStripeCustomer = functions.database.ref("/Customers/{userId}")
  .onUpdate((snapshot, context) => {
    const data = snapshot.after.val();
    return stripe.customers.createSource(data.payment_sources.customer_id, {
        source: data.payment_sources.source
    }).then(customer => {
        console.log("Update Stripe Customer");
        return customer;
    },
        error => {
            return error;
        }
    );
});

This is my code in the app end where I am updating the customer. While updating the trigger called in firebase, how do I get the data returned by the trigger (firebase function) in my below code?

 this.angularDb.object('/Customers/' + firebase.auth().currentUser.uid).update({
            cardsetup: 1,
            payment_sources: {
              customer_id: this.user.customer_id,
              source: this.card.source.id
            }
          }).then((res) => {
            loading.dismiss();
            alert("card details has been successfully updated.");
            this.navCtrl.push(LoginPage);

      }, (error) => {
        loading.dismiss();
        console.log("=========>", error.message)
        alert(JSON.stringify(error))
      });

If the firebase function returns an error I need to show that error message returned by the trigger. Any way to do this?


问:
Why do typescript promise have void
I was going through this blog on the web to create full stack app using typescript

Here he have used void like this

```<code>export const start = (port: number): Promise<void> => {
    const server = http.createServer(app);

    return new Promise<void>((resolve, reject) => {
        server.listen(port, resolve);
    });
};
</code>```

I am not sure why they/he have used void here? void generally means that function won't return anything.

whereas I think promise will always return something (i.e it will either resolve or reject).

So what's the purpose of using void here?

答:
The type refers to the value that the promise resolves into. If it resolves into nothing, the type is void. For example:

new Promise<string>((resolve, reject) => {
    resolve("hello");   // resolves into a string
});

new Promise<boolean>((resolve, reject) => {
    resolve(true);   // resolves into a boolean
});

new Promise<void>((resolve, reject) => {
    resolve();   // resolves into undefined/nothing/void
});
```

Presumably the server.listen() method doesn't call the callback with any arguments so the promise's type is void.

Title: Why do typescript promise have void

Body:
I was going through this blog on the web to create full stack app using typescript

Here he have used void like this

export const start = (port: number): Promise<void> => {
    const server = http.createServer(app);

    return new Promise<void>((resolve, reject) => {
        server.listen(port, resolve);
    });
};

I am not sure why they/he have used void here? void generally means that function won't return anything.

whereas I think promise will always return something (i.e it will either resolve or reject).

So what's the purpose of using void here?

Body:
The type refers to the value that the promise resolves into. If it resolves into nothing, the type is void. For example:

new Promise<string>((resolve, reject) => {
    resolve("hello");   // resolves into a string
});

new Promise<boolean>((resolve, reject) => {
    resolve(true);   // resolves into a boolean
});

new Promise<void>((resolve, reject) => {
    resolve();   // resolves into undefined/nothing/void
});

Presumably the server.listen() method doesn't call the callback with any arguments so the promise's type is void.


问:
Group by with wrapper javascript
i want to add additional wrapper after group by in efficient way

i tried with for each group by, but it created each array item with title based on group value

What want is additional unique wrapper for each group with title as group title and records as actual group item

the expected output i have shown below

```<code>const records = [{
    "id": "po_20",
    "name": "po_20",
    "searchtype": "purchaseorders"
  },
  {
    "id": "po_10",
    "name": "po_10",
    "searchtype": "purchaseorders"
  },
  {
    "id": "po_8",
    "name": "po_8",
    "searchtype": "purchaseorders"
  },
  {
    "id": "po_3",
    "name": "po_3",
    "searchtype": "purchaseorders"
  },
  {
    "id": "po_17",
    "name": "po_17",
    "searchtype": "purchaseorders"
  },
  {
    "id": "s1",
    "name": "s1",
    "searchtype": "sale"
  },
  {
    "id": "s2",
    "name": "s2",
    "searchtype": "sale"
  },
  {
    "id": "s3",
    "name": "s3",
    "searchtype": "sale"
  }

];

var groups2 = [];

records.forEach(function(item) {
  var list = groups2[item.searchtype];
  if (list) {
    list.push(item);
  } else {
    groups2[item.searchtype] = [item];
    //groups2[title] = [item.group];
  }
});

console.log(groups2);

var groups3 = [];
groups2.forEach(function(item) {
  console.log("Time");
  var jui = [];
  jui[title] = item[0].searchtype;
  jui[records ] = item;
  groups3.push(jui);
});
console.log(groups3);
</code>```

I expect the object to be

```<code>const records = [{
    title: 'purchaseorders',
    records: [{

        "id": "po_20",
        "name": "po_20",
        "searchtype": "purchaseorders"
      },
      {
        "id": "po_10",
        "name": "po_10",
        "searchtype": "purchaseorders"
      },
      {
        "id": "po_8",
        "name": "po_8",
        "searchtype": "purchaseorders"
      },
      {
        "id": "po_3",
        "name": "po_3",
        "searchtype": "purchaseorders"
      },
      {
        "id": "po_17",
        "name": "po_17",
        "searchtype": "purchaseorders"
      }
    ]
  },

  {
    title: 'sales',
    records: [{
        "id": "s1",
        "name": "s1",
        "searchtype": "sales"
      },
      {
        "id": "s2",
        "name": "s2",
        "searchtype": "sales"
      },
      {
        "id": "s3",
        "name": "s3",
        "searchtype": "sales"
      }
    ]
  }
];
</code>```

答:
You can use reduce and group values by searchtype key

const records = [{"id": "po_20","name": "po_20","searchtype": "purchaseorders"},{"id": "po_10",   "name": "po_10","searchtype": "purchaseorders"},{"id": "po_8","name": "po_8","searchtype": "purchaseorders"},{"id": "po_3","name": "po_3","searchtype": "purchaseorders"},{"id": "po_17","name": "po_17","searchtype": "purchaseorders"},{"id": "s1","name": "s1","searchtype": "sale"},{"id": "s2","name": "s2","searchtype": "sale"},{"id": "s3","name": "s3","searchtype": "sale"}];

let final = records.reduce((op,inp) => {
  let title = inp.searchtype
  op[title] = op[title] || {title, records:[]}
  op[title].records.push(inp)
  return op
},{})

console.log(Object.values(final))```

Title: Group by with wrapper javascript

Body:
i want to add additional wrapper after group by in efficient way

i tried with for each group by, but it created each array item with title based on group value

What want is additional unique wrapper for each group with title as group title and records as actual group item

the expected output i have shown below

const records = [{
    "id": "po_20",
    "name": "po_20",
    "searchtype": "purchaseorders"
  },
  {
    "id": "po_10",
    "name": "po_10",
    "searchtype": "purchaseorders"
  },
  {
    "id": "po_8",
    "name": "po_8",
    "searchtype": "purchaseorders"
  },
  {
    "id": "po_3",
    "name": "po_3",
    "searchtype": "purchaseorders"
  },
  {
    "id": "po_17",
    "name": "po_17",
    "searchtype": "purchaseorders"
  },
  {
    "id": "s1",
    "name": "s1",
    "searchtype": "sale"
  },
  {
    "id": "s2",
    "name": "s2",
    "searchtype": "sale"
  },
  {
    "id": "s3",
    "name": "s3",
    "searchtype": "sale"
  }

];

var groups2 = [];

records.forEach(function(item) {
  var list = groups2[item.searchtype];
  if (list) {
    list.push(item);
  } else {
    groups2[item.searchtype] = [item];
    //groups2[title] = [item.group];
  }
});

console.log(groups2);

var groups3 = [];
groups2.forEach(function(item) {
  console.log("Time");
  var jui = [];
  jui[title] = item[0].searchtype;
  jui[records ] = item;
  groups3.push(jui);
});
console.log(groups3);

I expect the object to be

const records = [{
    title: 'purchaseorders',
    records: [{

        "id": "po_20",
        "name": "po_20",
        "searchtype": "purchaseorders"
      },
      {
        "id": "po_10",
        "name": "po_10",
        "searchtype": "purchaseorders"
      },
      {
        "id": "po_8",
        "name": "po_8",
        "searchtype": "purchaseorders"
      },
      {
        "id": "po_3",
        "name": "po_3",
        "searchtype": "purchaseorders"
      },
      {
        "id": "po_17",
        "name": "po_17",
        "searchtype": "purchaseorders"
      }
    ]
  },

  {
    title: 'sales',
    records: [{
        "id": "s1",
        "name": "s1",
        "searchtype": "sales"
      },
      {
        "id": "s2",
        "name": "s2",
        "searchtype": "sales"
      },
      {
        "id": "s3",
        "name": "s3",
        "searchtype": "sales"
      }
    ]
  }
];


问:
Why does Java allow only a single method X when implementing 2 interfaces that both declare X but which differ in their throws clauses?
This is closely related to, but is not the same question as: Java - Method name collision in interface implementation

When there are two Java interfaces that share a method with almost the same signature like so:

```<code>import java.io.IOException;

interface ISomething1 {
    void doSomething();
}

interface ISomething2 {
    void doSomething() throws IOException;
}

class Impl implements ISomething1, ISomething2 {
  public void doSomething() {
    throw new IOException(); // this does not compile since ISomething1.doSomething does not declare a throws clause
  }

  public static void main(String args[]) throws IOException {
    Impl i = new Impl();
    i.doSomething();
  }
}
</code>```

Why is it that Java enforces that only a single method implement both these interface methods even though technically they differ in signature?

Note also that in the example above, the implementation of Impl.doSomething needs to NOT throw an IOException as otherwise the compiler complains that ISomething1.doSomething must also declare that it throws IOException effectively making the throws clause in ISomething2.doSomething useless.

Am I missing something obvious here? Thanks in advance for responses.

答:
When implementing a method in a child class, you can hide, or throw exceptions that "extends" the exception from the base class.

In your case:

```<code>public void doSomething() {
    throw new IOException(); // this does not compile since ISomething1.doSomething does not declare a throws clause
  }
</code>```

the IOException is not a Runtime exception, and should be declared in the signature of the method.
But this :

```<code>public void doSomething() throws IOException {
    throw new IOException(); // this does not compile since ISomething1.doSomething does not declare a throws clause
  }
</code>```

doesn't obey rules described and is not valid due the

```<code>interface ISomething1 {
    void doSomething();
}
</code>```

P.S. These aren't different signatures.
If you want to throw a new exception and extend both interfaces - you may encapsulate the IOException in the next way:

```<code>throw new RuntimeException(new IOException());
</code>```

UPDATE
But this is dangerous because the user of the class(programmer) isn't enforced to catch this exception and this may broke end-user's experience.

Body:
This is closely related to, but is not the same question as: Java - Method name collision in interface implementation

When there are two Java interfaces that share a method with almost the same signature like so:

import java.io.IOException;

interface ISomething1 {
    void doSomething();
}

interface ISomething2 {
    void doSomething() throws IOException;
}

class Impl implements ISomething1, ISomething2 {
  public void doSomething() {
    throw new IOException(); // this does not compile since ISomething1.doSomething does not declare a throws clause
  }

  public static void main(String args[]) throws IOException {
    Impl i = new Impl();
    i.doSomething();
  }
}

Why is it that Java enforces that only a single method implement both these interface methods even though technically they differ in signature?

Note also that in the example above, the implementation of Impl.doSomething needs to NOT throw an IOException as otherwise the compiler complains that ISomething1.doSomething must also declare that it throws IOException effectively making the throws clause in ISomething2.doSomething useless.

Am I missing something obvious here? Thanks in advance for responses.

Body:
When implementing a method in a child class, you can hide, or throw exceptions that "extends" the exception from the base class.

In your case:

public void doSomething() {
    throw new IOException(); // this does not compile since ISomething1.doSomething does not declare a throws clause
  }

the IOException is not a Runtime exception, and should be declared in the signature of the method.
But this :

public void doSomething() throws IOException {
    throw new IOException(); // this does not compile since ISomething1.doSomething does not declare a throws clause
  }

doesn't obey rules described and is not valid due the

interface ISomething1 {
    void doSomething();
}

P.S. These aren't different signatures.
If you want to throw a new exception and extend both interfaces - you may encapsulate the IOException in the next way:

throw new RuntimeException(new IOException());

UPDATE
But this is dangerous because the user of the class(programmer) isn't enforced to catch this exception and this may broke end-user's experience.


问:
Can anybody help me with this? I am just a beginner
```<code>Select
    m.style_id,
    sum(p.production_qty) Cutting
From
    Master_Data m
Left Join
    production_data p on P.Style_ID = M.Style_ID
where
    p.production_process = 'Cutting',

    sum(p.production_qty) Induction
From
    Master_Data m
Left Join
    production_data p on P.Style_ID = M.Style_ID
where
    p.production_process = 'Induction',
group by
    m.style_id
</code>```

How to get result of two different select statements?

答:
You can use conditional aggregation to get the result you want:</p>

```<code>Select
    m.style_id,
    sum(case when p.production_process = 'Cutting' then p.production_qty else 0 end) Cutting
    sum(case when p.production_process = 'Induction' then p.production_qty else 0 end) Induction
From
    Master_Data m
Left Join
    production_data p on P.Style_ID = M.Style_ID
where
    p.production_process in ('Induction', 'Cutting')
group by
    m.style_id
</code>```

Body:
Select
    m.style_id,
    sum(p.production_qty) Cutting
From
    Master_Data m
Left Join
    production_data p on P.Style_ID = M.Style_ID
where
    p.production_process = 'Cutting',

    sum(p.production_qty) Induction
From
    Master_Data m
Left Join
    production_data p on P.Style_ID = M.Style_ID
where
    p.production_process = 'Induction',
group by
    m.style_id

How to get result of two different select statements?

Body:
You can use conditional aggregation to get the result you want:

Select
    m.style_id,
    sum(case when p.production_process = 'Cutting' then p.production_qty else 0 end) Cutting
    sum(case when p.production_process = 'Induction' then p.production_qty else 0 end) Induction
From
    Master_Data m
Left Join
    production_data p on P.Style_ID = M.Style_ID
where
    p.production_process in ('Induction', 'Cutting')
group by
    m.style_id