问:
functional react: how to handle setState with an input from map function?
Using react hook, I want to convert all my classes into function. suppose this is my returned render:

```<code>{layerList.map(i => {
        return (
          <Button
            className="button-layer"
            type="primary"
            onClick={handleAa(i)}
          > {aa}
          </Button>
          <Button
             className="button-layer"
             type="primary"
             key={some_values}
             onClick={ handleChange(i) }
          >
            {i}
          </Button>
        )
      } )}
</code>```

How can I pass i to the function handleChange?

答:
You need a function, not a function call as the value for function props. E.g.

```<code>onClick={() => handleAa(i)}
</code>```

and

```<code>onClick={() => handleChange(i)}
</code>```

If you pass in the function call as you have, then it's invoked once, immediately when it renders, rather than when clicked.

Body:
Using react hook, I want to convert all my classes into function. suppose this is my returned render:

{layerList.map(i => {
        return (
          <Button
            className="button-layer"
            type="primary"
            onClick={handleAa(i)}
          > {aa}
          </Button>
          <Button
             className="button-layer"
             type="primary"
             key={some_values}
             onClick={ handleChange(i) }
          >
            {i}
          </Button>
        )
      } )}

How can I pass i to the function handleChange?

Body:
You need a function, not a function call as the value for function props. E.g.

onClick={() => handleAa(i)}

and

onClick={() => handleChange(i)}

If you pass in the function call as you have, then it's invoked once, immediately when it renders, rather than when clicked.


来源: stackexchange

问:
Best way to take text from data frame, tokenize by sentence then by word
Would like to take a list of comments from a data frame, first parse into a list of sentences, then on a second pass, parse by word. Need this for input to word2vec model, genism.

Have already used sent_tokenize from nltk to tokenize once, but then if I try to word_tokenize after that , get have an issue because it is no longer a string and expecting a string or byte like object.

```<code>import nltk

print(df)

ID Comment
0   Today is a good day.
1   Today I went by the river. The river also flow...
2   The water by the river is blue, it also feels ...
3   Today is the last day of spring; what to do to...

df['sentences']=df['Comment'].dropna().apply(nltk.sent_tokenize)

df['word']=df['sentences'].dropna().apply(nltk.word_tokenize)
</code>```

after trying to pass sentences into words
TypeError: expected string or bytes-like object

答:
```<code>I guess the problem is as you have none null values so you can try

df['word']=df['sentences'].apply(nltk.word_tokenize)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Would like to take a list of comments from a data frame, first parse into a list of sentences, then on a second pass, parse by word. Need this for input to word2vec model, genism.

Have already used sent_tokenize from nltk to tokenize once, but then if I try to word_tokenize after that , get have an issue because it is no longer a string and expecting a string or byte like object.

import nltk

print(df)

ID Comment
0   Today is a good day.
1   Today I went by the river. The river also flow...
2   The water by the river is blue, it also feels ...
3   Today is the last day of spring; what to do to...

df['sentences']=df['Comment'].dropna().apply(nltk.sent_tokenize)

df['word']=df['sentences'].dropna().apply(nltk.word_tokenize)

after trying to pass sentences into words
TypeError: expected string or bytes-like object


问:
ERROR: invalid input syntax for type timestamp: "20-MAR-17 08.30.41.453267 AM"
I am trying to copy data spooled form oracle to PostgreSQL with csv format.
I am getting below error while doing  the copy .

ERROR:  invalid input syntax for type timestamp: "20-MAR-17
  08.30.41.453267 AM"

I tried to set the date time  in DMY on Postgres but it did not work. I can input the data if I convert it to YMD format (i.e. I have to change numerous fields and almost 50 TB of data)

can someone please help me on this.

```<code>badmin=# copy downloaded_file from '/export/home/dbadmin/postgresql/TESTPGDB/scripts/FACTSET_IDS_2_V1.DOWNLOADED_FILE.csv'
   with delimiter ',';
ERROR:  invalid input syntax for type timestamp:
"20-MAR-17 08.30.41.453267 AM" CONTEXT:  COPY downloaded_file, line 1,
column DOWNLOAD_TIME: "20-MAR-17 08.30.41.453267 AM"
</code>```

答:
Let's assume your main table has following columns and datatypes.

```<code>\d downloaded_file
 Column |            Type
--------+----------------------------
 id     | integer
 txt    | text
 tstamp | timestamp without time zone
</code>```

Now, rather than copying directly into the table, create a temporary table with the same columns but with all text datatypes.

```<code>create temporary  table downloaded_file_tmp ( id text, txt text, tstamp text);
</code>```

Now, copy the contents of the file into this temp table.

The file looks like this.

```<code>$cat f.csv
1,'TEXT1','20-MAR-17 08.30.41.453267 AM'
</code>```

Copying from file to temp table.

```<code>\copy downloaded_file_tmp from 'f.csv' with delimiter ',' CSV;
</code>```

Copying from temp table to main table.

```<code>INSERT INTO downloaded_file
            (id,
             txt,
             tstamp)
SELECT id :: INT,
       txt,
       TO_TIMESTAMP('20-MAR-17 08.30.41.453267 AM', 'dd-mon-yy hh.mi.ss.US AM')
FROM   downloaded_file_tmp;
</code>```

Notice the format specifier US which represents  microsecond (000000-999999)

```<code>knayak=# select * from downloaded_file;
 id |   txt   |           tstamp
----+---------+----------------------------
  1 | 'TEXT1' | 2017-03-20 08:30:41.453267
</code>```

Body:
I am trying to copy data spooled form oracle to PostgreSQL with csv format.
I am getting below error while doing  the copy .

ERROR:  invalid input syntax for type timestamp: "20-MAR-17
  08.30.41.453267 AM"

I tried to set the date time  in DMY on Postgres but it did not work. I can input the data if I convert it to YMD format (i.e. I have to change numerous fields and almost 50 TB of data)

can someone please help me on this.

badmin=# copy downloaded_file from '/export/home/dbadmin/postgresql/TESTPGDB/scripts/FACTSET_IDS_2_V1.DOWNLOADED_FILE.csv'
   with delimiter ',';
ERROR:  invalid input syntax for type timestamp:
"20-MAR-17 08.30.41.453267 AM" CONTEXT:  COPY downloaded_file, line 1,
column DOWNLOAD_TIME: "20-MAR-17 08.30.41.453267 AM"

Body:
Let's assume your main table has following columns and datatypes.

\d downloaded_file
 Column |            Type
--------+----------------------------
 id     | integer
 txt    | text
 tstamp | timestamp without time zone

Now, rather than copying directly into the table, create a temporary table with the same columns but with all text datatypes.

create temporary  table downloaded_file_tmp ( id text, txt text, tstamp text);

Now, copy the contents of the file into this temp table.

The file looks like this.

$cat f.csv
1,'TEXT1','20-MAR-17 08.30.41.453267 AM'

Copying from file to temp table.

\copy downloaded_file_tmp from 'f.csv' with delimiter ',' CSV;

Copying from temp table to main table.

INSERT INTO downloaded_file
            (id,
             txt,
             tstamp)
SELECT id :: INT,
       txt,
       TO_TIMESTAMP('20-MAR-17 08.30.41.453267 AM', 'dd-mon-yy hh.mi.ss.US AM')
FROM   downloaded_file_tmp;

Notice the format specifier US which represents  microsecond (000000-999999)

knayak=# select * from downloaded_file;
 id |   txt   |           tstamp
----+---------+----------------------------
  1 | 'TEXT1' | 2017-03-20 08:30:41.453267


问:
Convert a specific string date
I have a date string like 28052019145051+05 (DDMMYYYYHHmmss) not a Unix timestamp. How can i convert it to date using date-fns? I have tried parse() but i'm getting Invalid date error.

答:
You can use substr..

```<code>var str = String(28052019145051+05)
    var DD = str.substr(2, 2);
    var MM = str.substr(0, 2);
    var YY = str.substr(4, 4);
    var HH = str.substr(8, 2);
    var Mi = str.substr(10, 2);
    var SS = str.substr(12, 2);

    console.log( YY+"-" +MM+"-"+ DD+ " "+HH+":"+Mi+":"+SS)
</code>```

Output: "2019-28-05 14:50:56"

Title: Convert a specific string date

Body:
You can use substr..

var str = String(28052019145051+05)
    var DD = str.substr(2, 2);
    var MM = str.substr(0, 2);
    var YY = str.substr(4, 4);
    var HH = str.substr(8, 2);
    var Mi = str.substr(10, 2);
    var SS = str.substr(12, 2);

    console.log( YY+"-" +MM+"-"+ DD+ " "+HH+":"+Mi+":"+SS)

Output: "2019-28-05 14:50:56"


问:
Find all entries where one of attributes within array is empty
I've following mongodb query:

```<code>db
.getCollection("entries")
.find({
    $and: [
      {
        "array.attribute_1": {
          $exists: true,
          $not: {
            $size: 0
          }
        }
      },
      {
        $or: [
          { "array.attribute_2": { $exists: true, $size: 0 } },
          { "array.attribute_2": { $exists: true, $eq: {} } }
        ]
      },
    ]
})
</code>```

And example of my document:

```<code>{
    _id: 'foo',
    array: [
       {attribute_1: [], attribute_2: []},
       {attribute_1: ['bar'], attribute_2: []}
    ]
}
</code>```

In my understanding my query should find all entries that have at least one element within array that has existent and not empty attribute_1 and existent empty array or empty object attribute_2. However, this query finds all entries that has all elements within array that has existent and not empty attribute_1 and existent empty array or empty object attribute_2. As such, my foo entry won't be found.

What should be the correct formula for my requirements?

答:
$find would find the first document with the matching criteria and in your case that first document contains all the arrays. You either need to use $project with $filter or aggregation with $unwind and $match.

Something like this:

```<code>db.collection.aggregate([
  { $unwind: "$array" },
  {
    $match: {
      $and: [
        { "array.attribute_1.0": { $exists: true }},
        {
          $or: [
            { "array.attribute_2.0": { $exists: false } },
            { "array.attribute_2.0": { $eq: {} } }
          ]
        }
      ]
    }
  }
])
</code>```

You can see it working here

Also since you are trying to find out if array is empty and exists at the same time using .0 with $exists is a quick and one statement way to get the same result as with both $exists and $size.

Body:
I've following mongodb query:

db
.getCollection("entries")
.find({
    $and: [
      {
        "array.attribute_1": {
          $exists: true,
          $not: {
            $size: 0
          }
        }
      },
      {
        $or: [
          { "array.attribute_2": { $exists: true, $size: 0 } },
          { "array.attribute_2": { $exists: true, $eq: {} } }
        ]
      },
    ]
})

And example of my document:

{
    _id: 'foo',
    array: [
       {attribute_1: [], attribute_2: []},
       {attribute_1: ['bar'], attribute_2: []}
    ]
}

In my understanding my query should find all entries that have at least one element within array that has existent and not empty attribute_1 and existent empty array or empty object attribute_2. However, this query finds all entries that has all elements within array that has existent and not empty attribute_1 and existent empty array or empty object attribute_2. As such, my foo entry won't be found.

What should be the correct formula for my requirements?

Body:
$find would find the first document with the matching criteria and in your case that first document contains all the arrays. You either need to use $project with $filter or aggregation with $unwind and $match.

Something like this:

db.collection.aggregate([
  { $unwind: "$array" },
  {
    $match: {
      $and: [
        { "array.attribute_1.0": { $exists: true }},
        {
          $or: [
            { "array.attribute_2.0": { $exists: false } },
            { "array.attribute_2.0": { $eq: {} } }
          ]
        }
      ]
    }
  }
])

You can see it working here

Also since you are trying to find out if array is empty and exists at the same time using .0 with $exists is a quick and one statement way to get the same result as with both $exists and $size.


问:
Compare two files and create a new one with the differences
I need to compare two files and create a new one with the differences of this two, i just know compare the files to show if they are equal or not, but i dont know how can i solve my problem.

I search so much info on how to compare files, but i didnt found the way of display the differences between this two files. This is my actual code.

Edit: The file can contain more than 1 line of data, usually like 30.

The text cannot be deleted, and the similarity just appear in the end of the text. I mean, the final line of a file text will be always the start of the other file text.

This is for homework and the instruction are: "Read the host file and check if any line is already present in the ip url file, and in case they are not, it is necessary to write them in a temporary file."

```<code>#include <stdio.h>
void main()
{
FILE *f1, *f2;
int a, b;

f1 = fopen("D:\\product3\\test.txt","r");
f2 = fopen("D:\\product3\\test2.txt", "r");

if(f1 == NULL || f2 == NULL)
{
    printf("Cannot read the files");
}
else
{
    a = getc(f1);
    b = getc(f2);

    while (a != EOF && b != EOF)
    {
        a = getc(f1);
        b = getc(f2);

        if(a != b)
        {
            printf("");
        }
    }
    if (a == b)
    {
        printf("\n The files are equal \n");
    }
    else if (a!=b)
    {
        printf("\n The files aren't equal \n");
    }
    else
    {
        printf("\n Error \n");
    }
}

fclose(f1);
fclose(f2);
}
</code>```

The content of the files are:

```
>Test.txt
AAA
aaa
bbb
BBB
111

>Test2.txt
AAA
aaa
bbb
BBB
111
333
444
555
6666
777
CCC
```

so the output must be:

```
>333
444
555
6666
777
CCC
```

答:
Let's add a little more code into the while loop body to show the difference:

```<code>while (a != EOF && b != EOF)
{
    a = getc(f1);
    b = getc(f2);

    if(a != b)
    {
        /* print info about this difference */
    }
}
</code>```

And after this let's add an information about difference of of file length:

```<code>if (a == EOF || b == EOF)
{
    /* print other characters of the longer file */
}
</code>```

Please add comments here if you see any problems in these small steps.

And the last step will be simple: save the difference in file (but before compliting of both first steps I'd recommend you to use printf for printing of everything).

Body:
I need to compare two files and create a new one with the differences of this two, i just know compare the files to show if they are equal or not, but i dont know how can i solve my problem.

I search so much info on how to compare files, but i didnt found the way of display the differences between this two files. This is my actual code.

Edit: The file can contain more than 1 line of data, usually like 30.

The text cannot be deleted, and the similarity just appear in the end of the text. I mean, the final line of a file text will be always the start of the other file text.

This is for homework and the instruction are: "Read the host file and check if any line is already present in the ip url file, and in case they are not, it is necessary to write them in a temporary file."

#include <stdio.h>
void main()
{
FILE *f1, *f2;
int a, b;

f1 = fopen("D:\\product3\\test.txt","r");
f2 = fopen("D:\\product3\\test2.txt", "r");

if(f1 == NULL || f2 == NULL)
{
    printf("Cannot read the files");
}
else
{
    a = getc(f1);
    b = getc(f2);

    while (a != EOF && b != EOF)
    {
        a = getc(f1);
        b = getc(f2);

        if(a != b)
        {
            printf("");
        }
    }
    if (a == b)
    {
        printf("\n The files are equal \n");
    }
    else if (a!=b)
    {
        printf("\n The files aren't equal \n");
    }
    else
    {
        printf("\n Error \n");
    }
}

fclose(f1);
fclose(f2);
}

The content of the files are:

>Test.txt
AAA
aaa
bbb
BBB
111

>Test2.txt
AAA
aaa
bbb
BBB
111
333
444
555
6666
777
CCC

so the output must be:

>333
444
555
6666
777
CCC

Body:
Let's add a little more code into the while loop body to show the difference:

while (a != EOF && b != EOF)
{
    a = getc(f1);
    b = getc(f2);

    if(a != b)
    {
        /* print info about this difference */
    }
}

And after this let's add an information about difference of of file length:

if (a == EOF || b == EOF)
{
    /* print other characters of the longer file */
}

Please add comments here if you see any problems in these small steps.

And the last step will be simple: save the difference in file (but before compliting of both first steps I'd recommend you to use printf for printing of everything).


问:
Proper way of using sqlite insertOrThrow
My code looks something like this:

```<code>ContentValues values = new ContentValues();
values.put("year", year);
values.put("month", month);
database.insert(MySQLiteHelper.TABLE_DATA, null, values);
</code>```

Everything works fine, but unfortunately the insert query will always return -1 on one of my user's device. My app has bugsnag so now I changed the

insert

to

database.insertOrThrow

hoping that when an error occurs on the user's phone again, bugsnag will notify me. BUT just to make sure (since I've never used insertOrThrow before; usually just insert encapsulated in try catch), is the code above sufficient? When an error happens on insert, will bugsnag capture it? Maybe my question can be summarized as 'how do I handle throw in insertOrThrow?'

答: Make sure you are putting all the values that you have been declared during creating the table in my case that solve the problem.</p>

ContentLicense: CC BY-SA 3.0

Body:
My code looks something like this:

ContentValues values = new ContentValues();
values.put("year", year);
values.put("month", month);
database.insert(MySQLiteHelper.TABLE_DATA, null, values);

Everything works fine, but unfortunately the insert query will always return -1 on one of my user's device. My app has bugsnag so now I changed the

insert

to

database.insertOrThrow

hoping that when an error occurs on the user's phone again, bugsnag will notify me. BUT just to make sure (since I've never used insertOrThrow before; usually just insert encapsulated in try catch), is the code above sufficient? When an error happens on insert, will bugsnag capture it? Maybe my question can be summarized as 'how do I handle throw in insertOrThrow?'


问:
"Error in match.arg(what) : 'arg' must be NULL or a character vector" when trying to run the impute function in the below code
I'm trying to impute the missing values with mean in a column in the dataset.
Using impute function available in Hmisc package

Have tried running several set of codes. In past I've used the piece of code & on same dataset, however, now it's not running.

```<code>impute(crime$average.ed,mean)
crime$average.ed<-as.numeric(impute(crime$average.ed, mean))
summary(crime)
</code>```

The missing values in the variable average.ed must replaced with mean.
I keep getting error

Error in match.arg(what) : 'arg' must be NULL or a character vector

(BTW mean is 10.51)

答: Finally found the solution to the problem by myself. A package named e1071 was causing a problem when using with package Hmisc. Both the packages have impute function and when used provided when both the packages are active, it won't run. So moral of the story use any one of the package.</p>

Body:
I'm trying to impute the missing values with mean in a column in the dataset.
Using impute function available in Hmisc package

Have tried running several set of codes. In past I've used the piece of code & on same dataset, however, now it's not running.

impute(crime$average.ed,mean)
crime$average.ed<-as.numeric(impute(crime$average.ed, mean))
summary(crime)

The missing values in the variable average.ed must replaced with mean.
I keep getting error

Error in match.arg(what) : 'arg' must be NULL or a character vector

(BTW mean is 10.51)


问:
Time Complexity Of Merge Sort In Special Condition
What would be the time complexity If I will apply merge sort on an already sorted array?</p>

答:
According to the Wikipedia page for merge sort, merge sort has both a best and worse case performance of O(n log n).  Given an input of an array already sorted, merge sort would still need to go through the same sorting process as for any other array.  As a result, even for a sorted array, the running time would still be O(n log n).

For the case of an already-sorted array, there are other algorithms which actually beat merge sort, e.g. insertion sort.  For insertion sort, the performance of an already sorted array is O(n), i.e. linear.


问:
How Can I export typescript interface which in namespace to use in another module?
I have an interface like this:

x.ts:

```<code> namespace Basex {
    export interface AddressDto  {
        AddressDetail?: string;
        AddressName?: string;
        AddressType?: number;
        City?: string;
        CityCode?: number;
        CountryCode?: number;
        DexjustizCode?: string;
        District?: string;
        HouseNumber?: number;
        HouseNumberDetail?: string;
        Id?: number;
        IsMainAddress?: boolean;
        LastAddressInterval?: string;
        Street?: string;
        Text?: string;
        Town?: string;
        ValidationLevel?: number;
        ValidityEndDate?: Date;
        ValidityStartDate?: Date;
     }
}

// I use this object on my screen in this way;

const {Basex}  = require('../../src/model/dto/x');
</code>```

I can access AddressDto like this Basex.AddressDto

But I could not achieve access to this namespace from another dependency project. I have tried using the above method to export in the dependency project's index.ts.But it could not be. Shortly How can access this namespace's interfaces from another dependency?

答: You have to export the interface. please refer here </p>

Body:
I have an interface like this:

x.ts:

 namespace Basex {
    export interface AddressDto  {
        AddressDetail?: string;
        AddressName?: string;
        AddressType?: number;
        City?: string;
        CityCode?: number;
        CountryCode?: number;
        DexjustizCode?: string;
        District?: string;
        HouseNumber?: number;
        HouseNumberDetail?: string;
        Id?: number;
        IsMainAddress?: boolean;
        LastAddressInterval?: string;
        Street?: string;
        Text?: string;
        Town?: string;
        ValidationLevel?: number;
        ValidityEndDate?: Date;
        ValidityStartDate?: Date;
     }
}

// I use this object on my screen in this way;

const {Basex}  = require('../../src/model/dto/x');

I can access AddressDto like this Basex.AddressDto

But I could not achieve access to this namespace from another dependency project. I have tried using the above method to export in the dependency project's index.ts.But it could not be. Shortly How can access this namespace's interfaces from another dependency?


问:
Sharing link from mobile browser shows ip instead of domain name
I have a domain, ‘example.com’ and when I share some of its web pages via a mobile browser (only in Safari and chrome app) to social media, the URL is displayed as an IP ex(http://31.08.94.4:99999) instead of my domain name.

I'm working in laravel framework.

For a clear understanding, I updated screenshot below,

This is the screenshot of what happens when I share from my mobile:

http://prnt.sc/nkxfj5

And this is what happens when the proxy IP is shared instead of the actual domain name:

http://prnt.sc/nkxg8f

答:
I got an solution for this issue,

canonical url of site is used while sharing the site.

So check your canonical url set in your site using,

```<code>   document.querySelector('link[rel=canonical]');
</code>```

Body:
I got an solution for this issue,

canonical url of site is used while sharing the site.

So check your canonical url set in your site using,

   document.querySelector('link[rel=canonical]');


问:
QueryDsl SQL - Left Join a subquery
I am using QueryDsl SQL and I want to left join a subquery. Here is the query in plain SQL

```<code>SELECT
  usr.memberId,
  payoutsBbf.totalPyts
FROM
  users usr
  LEFT JOIN
    (SELECT
       pyt.member_id   AS mmb_id,
       SUM(pyt.amount) AS totalPyts
  FROM
    payout pyt
  WHERE
    pyt.payoutPeriod < '2018-01-01'
    GROUP BY pyt.member_id) AS payoutsBbf ON usr.id = payoutsBbf.mmb_id
</code>```

I wish to write it in QueryDsl SQL and is almost important that the subquery is left joined to the main table users coz this is just a snippet of the whole complex query.

How do I deal with the LEFT JOIN x ON part

How do I deal with the subquery alias in the SELECT payoutBbf.totalPyts part

答:
this is how I would do it:</p>

```<code>final StringPath payoutsBbf = stringPath("payoutsBbf");
final String mmbId = "mmb_id";
final String totalPyts = "totalPyts";
sqlQueryFactory.select(users.memberId, stringPath(payoutsBbf, totalPyts))
    .from(users).leftJoin(
        sqlQueryFactory.select(payout.member_id.as(mmbId), member_id.amount.sum().as(totalPyts))
            .from(payout).where(payout.payoutPeriod.lt("2018-01-01")).groupBy(payout.member_id),
        payoutsBbf
    ).on(users.id.eq(stringPath(payoutsBbf, mmbId))).fetch();
</code>```

Title: QueryDsl SQL - Left Join a subquery

Body:
I am using QueryDsl SQL and I want to left join a subquery. Here is the query in plain SQL

SELECT
  usr.memberId,
  payoutsBbf.totalPyts
FROM
  users usr
  LEFT JOIN
    (SELECT
       pyt.member_id   AS mmb_id,
       SUM(pyt.amount) AS totalPyts
  FROM
    payout pyt
  WHERE
    pyt.payoutPeriod < '2018-01-01'
    GROUP BY pyt.member_id) AS payoutsBbf ON usr.id = payoutsBbf.mmb_id

I wish to write it in QueryDsl SQL and is almost important that the subquery is left joined to the main table users coz this is just a snippet of the whole complex query.

How do I deal with the LEFT JOIN x ON part

How do I deal with the subquery alias in the SELECT payoutBbf.totalPyts part

Body:
this is how I would do it:

final StringPath payoutsBbf = stringPath("payoutsBbf");
final String mmbId = "mmb_id";
final String totalPyts = "totalPyts";
sqlQueryFactory.select(users.memberId, stringPath(payoutsBbf, totalPyts))
    .from(users).leftJoin(
        sqlQueryFactory.select(payout.member_id.as(mmbId), member_id.amount.sum().as(totalPyts))
            .from(payout).where(payout.payoutPeriod.lt("2018-01-01")).groupBy(payout.member_id),
        payoutsBbf
    ).on(users.id.eq(stringPath(payoutsBbf, mmbId))).fetch();


问:
Java Regex to match multiple lines
Following is Sample the data on which regex should be applied:

```<code>2019-05-27 10:49:18,418 INFO  org.apache.flink.runtime.executiongraph.ExecutionGraph        - Filter -> Map (1/1) (824780055001546646d35df7a64cfe3c) switched from CANCELING to CANCELED.
2019-05-27 10:49:18,418 INFO  org.apache.flink.runtime.executiongraph.ExecutionGraph        - Try to restart or fail the job  (3064130e1dccead0b037f193d3699c3b) if no longer possible.
2019-05-27 10:49:18,418 ERROR  org.apache.flink.runtime.executiongraph.ExecutionGraph        - Job  (3064130e1dccead0b037f193d3699c3b) switched from state FAILING to FAILED.
java.lang.IllegalArgumentException: json can not be null or empty
    at com.jayway.jsonpath.internal.Utils.notEmpty(Utils.java:256)
    at com.jayway.jsonpath.JsonPath.compile(JsonPath.java:424)
    at com.mypkg.subpkg.ControlData$ConnectedStreams.validateJsonPath(ControlData.java:194)
    at com.mypkg.subpkg.ControlData$ConnectedStreams.flatMap1(ControlData.java:178)
    at com.mypkg.subpkg.ControlData$ConnectedStreams.flatMap1(ControlData.java:171)
    at org.apache.flink.streaming.api.operators.co.CoStreamFlatMap.processElement1(CoStreamFlatMap.java:53)
    at org.apache.flink.streaming.runtime.io.StreamTwoInputProcessor.processInput(StreamTwoInputProcessor.java:238)
    at org.apache.flink.streaming.runtime.tasks.TwoInputStreamTask.run(TwoInputStreamTask.java:117)
    at org.apache.flink.streaming.runtime.tasks.StreamTask.invoke(StreamTask.java:300)
    at org.apache.flink.runtime.taskmanager.Task.run(Task.java:711)
    at java.lang.Thread.run(Thread.java:748)
2019-05-27 10:49:18,418 ERROR  org.apache.flink.runtime.executiongraph.ExecutionGraph        - Could not restart the job  (3064130e1dccead0b037f193d3699c3b) because the restart strategy prevented it.
java.lang.IllegalArgumentException: json can not be null or empty
    at com.jayway.jsonpath.internal.Utils.notEmpty(Utils.java:256)
    at com.jayway.jsonpath.JsonPath.compile(JsonPath.java:424)
    at com.mypkg.subpkg.ControlData$ConnectedStreams.validateJsonPath(ControlData.java:194)
    at com.mypkg.subpkg.ControlData$ConnectedStreams.flatMap1(ControlData.java:178)
    at com.mypkg.subpkg.ControlData$ConnectedStreams.flatMap1(ControlData.java:171)
    at org.apache.flink.streaming.api.operators.co.CoStreamFlatMap.processElement1(CoStreamFlatMap.java:53)
    at org.apache.flink.streaming.runtime.io.StreamTwoInputProcessor.processInput(StreamTwoInputProcessor.java:238)
    at org.apache.flink.streaming.runtime.tasks.TwoInputStreamTask.run(TwoInputStreamTask.java:117)
    at org.apache.flink.streaming.runtime.tasks.StreamTask.invoke(StreamTask.java:300)
    at org.apache.flink.runtime.taskmanager.Task.run(Task.java:711)
    at java.lang.Thread.run(Thread.java:748)
2019-05-27 10:49:18,418 INFO  org.apache.flink.runtime.checkpoint.CheckpointCoordinator     - Stopping checkpoint coordinator for job 3064130e1dccead0b037f193d3699c3b.
2019-05-27 10:49:18,418 INFO  org.apache.flink.runtime.checkpoint.StandaloneCompletedCheckpointStore  - Shutting down
2019-05-27 10:49:18,419 INFO  org.apache.flink.runtime.dispatcher.StandaloneDispatcher      - Job 3064130e1dccead0b037f193d3699c3b reached globally terminal state FAILED.
</code>```

Basically what I want to extract is time stamp and ERROR with message:

For an instance:

```<code>TimeStamp               Error
2019-05-27 10:49:18,418 ERROR  org.apache.flink.runtime.executiongraph.ExecutionGraph        - Job  (3064130e1dccead0b037f193d3699c3b) switched from state FAILING to FAILED.
java.lang.IllegalArgumentException: json can not be null or empty
    at com.jayway.jsonpath.internal.Utils.notEmpty(Utils.java:256)
    at com.jayway.jsonpath.JsonPath.compile(JsonPath.java:424)
    at com.mypkg.subpkg.ControlData$ConnectedStreams.validateJsonPath(ControlData.java:194)
    at com.mypkg.subpkg.ControlData$ConnectedStreams.flatMap1(ControlData.java:178)
    at com.mypkg.subpkg.ControlData$ConnectedStreams.flatMap1(ControlData.java:171)
    at org.apache.flink.streaming.api.operators.co.CoStreamFlatMap.processElement1(CoStreamFlatMap.java:53)
    at org.apache.flink.streaming.runtime.io.StreamTwoInputProcessor.processInput(StreamTwoInputProcessor.java:238)
    at org.apache.flink.streaming.runtime.tasks.TwoInputStreamTask.run(TwoInputStreamTask.java:117)
    at org.apache.flink.streaming.runtime.tasks.StreamTask.invoke(StreamTask.java:300)
    at org.apache.flink.runtime.taskmanager.Task.run(Task.java:711)
    at java.lang.Thread.run(Thread.java:748)
</code>```

Here Error message is split into multiple lines to for that I have written java pattern like below:

```<code>((?m)\\d{4}-[01]\\d-[0-3]\\d\\s[0-2]\\d((:[0-5]\\d)?){2}[\\s\\S]*ERROR[\\s\\S]*[ ]*at [\\s\\S]*)
</code>```

But it returns me all the content of the file.

What should I do to make it work so that it will give me multi-line error message too.

答:
try this

```<code>((\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2},\d{3,5})\sERROR.+?(?=\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2},\d{3,5}))
</code>```

Explantion:

(\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2},\d{3,5}) - matches the timestamp

\sERROR.+?(?=\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2},\d{3,5}) - does the nongreedy match until you find the next timestamp (Positive Lookahead)

Also i would like to highlight that you wil have to use m option for multiline match while using this regex

This match will give you nested groups for every match like [[log, timestamp],[log, timestamp]]

Title: Java Regex to match multiple lines

Body:
Following is Sample the data on which regex should be applied:

2019-05-27 10:49:18,418 INFO  org.apache.flink.runtime.executiongraph.ExecutionGraph        - Filter -> Map (1/1) (824780055001546646d35df7a64cfe3c) switched from CANCELING to CANCELED.
2019-05-27 10:49:18,418 INFO  org.apache.flink.runtime.executiongraph.ExecutionGraph        - Try to restart or fail the job  (3064130e1dccead0b037f193d3699c3b) if no longer possible.
2019-05-27 10:49:18,418 ERROR  org.apache.flink.runtime.executiongraph.ExecutionGraph        - Job  (3064130e1dccead0b037f193d3699c3b) switched from state FAILING to FAILED.
java.lang.IllegalArgumentException: json can not be null or empty
    at com.jayway.jsonpath.internal.Utils.notEmpty(Utils.java:256)
    at com.jayway.jsonpath.JsonPath.compile(JsonPath.java:424)
    at com.mypkg.subpkg.ControlData$ConnectedStreams.validateJsonPath(ControlData.java:194)
    at com.mypkg.subpkg.ControlData$ConnectedStreams.flatMap1(ControlData.java:178)
    at com.mypkg.subpkg.ControlData$ConnectedStreams.flatMap1(ControlData.java:171)
    at org.apache.flink.streaming.api.operators.co.CoStreamFlatMap.processElement1(CoStreamFlatMap.java:53)
    at org.apache.flink.streaming.runtime.io.StreamTwoInputProcessor.processInput(StreamTwoInputProcessor.java:238)
    at org.apache.flink.streaming.runtime.tasks.TwoInputStreamTask.run(TwoInputStreamTask.java:117)
    at org.apache.flink.streaming.runtime.tasks.StreamTask.invoke(StreamTask.java:300)
    at org.apache.flink.runtime.taskmanager.Task.run(Task.java:711)
    at java.lang.Thread.run(Thread.java:748)
2019-05-27 10:49:18,418 ERROR  org.apache.flink.runtime.executiongraph.ExecutionGraph        - Could not restart the job  (3064130e1dccead0b037f193d3699c3b) because the restart strategy prevented it.
java.lang.IllegalArgumentException: json can not be null or empty
    at com.jayway.jsonpath.internal.Utils.notEmpty(Utils.java:256)
    at com.jayway.jsonpath.JsonPath.compile(JsonPath.java:424)
    at com.mypkg.subpkg.ControlData$ConnectedStreams.validateJsonPath(ControlData.java:194)
    at com.mypkg.subpkg.ControlData$ConnectedStreams.flatMap1(ControlData.java:178)
    at com.mypkg.subpkg.ControlData$ConnectedStreams.flatMap1(ControlData.java:171)
    at org.apache.flink.streaming.api.operators.co.CoStreamFlatMap.processElement1(CoStreamFlatMap.java:53)
    at org.apache.flink.streaming.runtime.io.StreamTwoInputProcessor.processInput(StreamTwoInputProcessor.java:238)
    at org.apache.flink.streaming.runtime.tasks.TwoInputStreamTask.run(TwoInputStreamTask.java:117)
    at org.apache.flink.streaming.runtime.tasks.StreamTask.invoke(StreamTask.java:300)
    at org.apache.flink.runtime.taskmanager.Task.run(Task.java:711)
    at java.lang.Thread.run(Thread.java:748)
2019-05-27 10:49:18,418 INFO  org.apache.flink.runtime.checkpoint.CheckpointCoordinator     - Stopping checkpoint coordinator for job 3064130e1dccead0b037f193d3699c3b.
2019-05-27 10:49:18,418 INFO  org.apache.flink.runtime.checkpoint.StandaloneCompletedCheckpointStore  - Shutting down
2019-05-27 10:49:18,419 INFO  org.apache.flink.runtime.dispatcher.StandaloneDispatcher      - Job 3064130e1dccead0b037f193d3699c3b reached globally terminal state FAILED.

Basically what I want to extract is time stamp and ERROR with message:

For an instance:

TimeStamp               Error
2019-05-27 10:49:18,418 ERROR  org.apache.flink.runtime.executiongraph.ExecutionGraph        - Job  (3064130e1dccead0b037f193d3699c3b) switched from state FAILING to FAILED.
java.lang.IllegalArgumentException: json can not be null or empty
    at com.jayway.jsonpath.internal.Utils.notEmpty(Utils.java:256)
    at com.jayway.jsonpath.JsonPath.compile(JsonPath.java:424)
    at com.mypkg.subpkg.ControlData$ConnectedStreams.validateJsonPath(ControlData.java:194)
    at com.mypkg.subpkg.ControlData$ConnectedStreams.flatMap1(ControlData.java:178)
    at com.mypkg.subpkg.ControlData$ConnectedStreams.flatMap1(ControlData.java:171)
    at org.apache.flink.streaming.api.operators.co.CoStreamFlatMap.processElement1(CoStreamFlatMap.java:53)
    at org.apache.flink.streaming.runtime.io.StreamTwoInputProcessor.processInput(StreamTwoInputProcessor.java:238)
    at org.apache.flink.streaming.runtime.tasks.TwoInputStreamTask.run(TwoInputStreamTask.java:117)
    at org.apache.flink.streaming.runtime.tasks.StreamTask.invoke(StreamTask.java:300)
    at org.apache.flink.runtime.taskmanager.Task.run(Task.java:711)
    at java.lang.Thread.run(Thread.java:748)

Here Error message is split into multiple lines to for that I have written java pattern like below:

((?m)\\d{4}-[01]\\d-[0-3]\\d\\s[0-2]\\d((:[0-5]\\d)?){2}[\\s\\S]*ERROR[\\s\\S]*[ ]*at [\\s\\S]*)

But it returns me all the content of the file.

What should I do to make it work so that it will give me multi-line error message too.

Body:
try this

((\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2},\d{3,5})\sERROR.+?(?=\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2},\d{3,5}))

Explantion:

(\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2},\d{3,5}) - matches the timestamp

\sERROR.+?(?=\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2},\d{3,5}) - does the nongreedy match until you find the next timestamp (Positive Lookahead)

Also i would like to highlight that you wil have to use m option for multiline match while using this regex

This match will give you nested groups for every match like [[log, timestamp],[log, timestamp]]


问:
C++ char* array
When I create something like

```<code>char* t = new char[44];
t = strcpy(s,t);
</code>```

then strlen(t); return some wrong results. how I can change this?

答:
What are you trying to do? Do you want to copy from s to t? If so, the arguments to strcpy are reversed.

```<code>char* t = new char[44]; // allocate a buffer
strcpy(t,s); // populate it
</code>```

Such C-style string processing is a red flag, but that's all I can say given this little information.

OwnerDisplayName: Александр Брус

Title: C++ char* array

Body:
When I create something like

char* t = new char[44];
t = strcpy(s,t);

then strlen(t); return some wrong results. how I can change this?

Body:
What are you trying to do? Do you want to copy from s to t? If so, the arguments to strcpy are reversed.

char* t = new char[44]; // allocate a buffer
strcpy(t,s); // populate it

Such C-style string processing is a red flag, but that's all I can say given this little information.


问:
How to change BACK with onchange with a switch in HTML
I am writing a website, and want to create a dark/light mode. I have a switch that switches when clicked, and it successfully changes to my second css stylesheet. How should I go about switching BACK to the original stylesheet?

HTML-

```<code><link id="pagestyle" rel="stylesheet" type="text/css" href="assets/css/main.css">
<script>
  function swapStyleSheet(sheet) {
    document.getElementById('pagestyle').setAttribute('href', 'assets/css/main2.css');
  }
</script>
<!-- Rectangular switch -->
<label class="switch">
  <input type="checkbox" onchange="swapStyleSheet()"">
    <span class=" slider"></span>
</label>
</code>```

Using this switch style

答:
Just use the .href property it's a lot shorter than .setAttribute(). A functioning demo can be reviewed here

<!DOCTYPE html>

  <link href="default.css" rel="stylesheet">

  <input id='switch' type="checkbox">

```

Body:
I am writing a website, and want to create a dark/light mode. I have a switch that switches when clicked, and it successfully changes to my second css stylesheet. How should I go about switching BACK to the original stylesheet?

HTML-

<link id="pagestyle" rel="stylesheet" type="text/css" href="assets/css/main.css">

  <input type="checkbox" onchange="swapStyleSheet()"">

Using this switch style

Body:
Just use the .href property it's a lot shorter than .setAttribute(). A functioning demo can be reviewed here

<!DOCTYPE html>
<html>

<head>
  <link href="default.css" rel="stylesheet">
</head>

<body>

  <input id='switch' type="checkbox">

  <script>
     document.querySelector('#switch').onchange = swap;

function swap(e) {
  document.querySelector('link').href = this.checked ? 'alt.css' : 'default.css';
}
  </script>
</body>

</html>


问:
Unable to access graph after re-login
I created graph on AgensGraph.

```<code>$ agens
agens (AgensGraph 2.1.0, based on PostgreSQL 10.4)
Type "help" for help.

agens=# create graph g;
CREATE GRAPH
agens=# create (:v{id:1});
GRAPH WRITE (INSERT VERTEX 1, INSERT EDGE 0)
agens=# \q
$ agens
agens (AgensGraph 2.1.0, based on PostgreSQL 10.4)
Type "help" for help.

agens=# match (n) return n;
ERROR:  graph_path is NULL
HINT:  Use SET graph_path
agens=# \q
</code>```

But, unable to access graph after re-login.

How to access graph after re-login

答:
Use "ALTER USER ... SET GRAPH_PATH TO ..." statement for set default graph on login.

```<code>$ agens
agens (AgensGraph 2.1.0, based on PostgreSQL 10.4)
Type "help" for help.

agens=# create graph g;
CREATE GRAPH
agens=# alter user agens set graph_path to g;
ALTER ROLE
agens=# create (:v{id:1});
GRAPH WRITE (INSERT VERTEX 1, INSERT EDGE 0)
agens=# \quit
</code>```

After changing "GRAPH_PATH", You can access to your graph.

```<code>$ agens
agens (AgensGraph 2.1.0, based on PostgreSQL 10.4)
Type "help" for help.

agens=# match (n) return n;
        n
-----------------
 v[3.1]{"id": 1}
(1 row)
</code>```

Title: Unable to access graph after re-login

Body:
I created graph on AgensGraph.

$ agens
agens (AgensGraph 2.1.0, based on PostgreSQL 10.4)
Type "help" for help.

agens=# create graph g;
CREATE GRAPH
agens=# create (:v{id:1});
GRAPH WRITE (INSERT VERTEX 1, INSERT EDGE 0)
agens=# \q
$ agens
agens (AgensGraph 2.1.0, based on PostgreSQL 10.4)
Type "help" for help.

agens=# match (n) return n;
ERROR:  graph_path is NULL
HINT:  Use SET graph_path
agens=# \q

But, unable to access graph after re-login.

How to access graph after re-login

Body:
Use "ALTER USER ... SET GRAPH_PATH TO ..." statement for set default graph on login.

$ agens
agens (AgensGraph 2.1.0, based on PostgreSQL 10.4)
Type "help" for help.

agens=# create graph g;
CREATE GRAPH
agens=# alter user agens set graph_path to g;
ALTER ROLE
agens=# create (:v{id:1});
GRAPH WRITE (INSERT VERTEX 1, INSERT EDGE 0)
agens=# \quit

After changing "GRAPH_PATH", You can access to your graph.

$ agens
agens (AgensGraph 2.1.0, based on PostgreSQL 10.4)
Type "help" for help.

agens=# match (n) return n;
        n
-----------------
 v[3.1]{"id": 1}
(1 row)


问:
json data question parents and children create
```<code>for(var d in response.data) {
    var item = response.data[d];
    console.log("test-1234=="+JSON.stringify(item));
}
</code>```

If you take the data, it comes out as below.

```<code>test-1234=={"id":3,"isLeaf":"false","name":"bang","pid":0,"didabled":null}
test-1234=={"id":4,"isLeaf":"true","name":"test1","pid":3,"didabled":null}
test-1234=={"id":5,"isLeaf":"true","name":"test2","pid":3,"didabled":null}
test-1234=={"id":6,"isLeaf":"false","name":"test3","pid":0,"didabled":null}
</code>```

I want to create a relationship between parents and children based on pid.

Like below.
Please give me a solution.

```<code>[
{
    name: 'bang',
    id: 3,
    pid: 0,
    dragDisabled: true,
    children: [
        {
            name: 'test1',
            id: 4,
            isLeaf: true,
            pid: 3
        },
       {
            name: 'test2',
            id: 5,
            isLeaf: true,
            pid: 3
        }
    ]
},
 {
            name: 'test3',
            id: 6,
            isLeaf: true,
            pid: 0
        }
]
</code>```

答:
Try like this.

var arr = [
  { "id": 3, "isLeaf": "false", "name": "bang", "pid": 0, "didabled": null },
  { "id": 4, "isLeaf": "true",  "name": "test1", "pid": 3, "didabled": null },
  { "id": 5, "isLeaf": "true",  "name": "test2", "pid": 3, "didabled": null },
  { "id": 6, "isLeaf": "false", "name": "test3", "pid": 0, "didabled": null },
  { "id": 7, "isLeaf": "true", "name": "test\43", "pid": 4, "didabled": null }
]

var res = [];

for(var d in arr) {
    var item = arr[d];
    if(item.pid != 0){
      findParentAndPush(item)
    } else {
      item.children = [];
      res.push(item);
    }
}

function findParentAndPush(item){
  var filtered = arr.filter(data => data.id === item.pid);
  item.children = [];
  filtered[0].children.push(item)
}

console.log(res)```

Body:
for(var d in response.data) {
    var item = response.data[d];
    console.log("test-1234=="+JSON.stringify(item));
}

If you take the data, it comes out as below.

test-1234=={"id":3,"isLeaf":"false","name":"bang","pid":0,"didabled":null}
test-1234=={"id":4,"isLeaf":"true","name":"test1","pid":3,"didabled":null}
test-1234=={"id":5,"isLeaf":"true","name":"test2","pid":3,"didabled":null}
test-1234=={"id":6,"isLeaf":"false","name":"test3","pid":0,"didabled":null}

I want to create a relationship between parents and children based on pid.

Like below.
Please give me a solution.

[
{
    name: 'bang',
    id: 3,
    pid: 0,
    dragDisabled: true,
    children: [
        {
            name: 'test1',
            id: 4,
            isLeaf: true,
            pid: 3
        },
       {
            name: 'test2',
            id: 5,
            isLeaf: true,
            pid: 3
        }
    ]
},
 {
            name: 'test3',
            id: 6,
            isLeaf: true,
            pid: 0
        }
]


问:
SQL server query to get the list of columns in a table along with Data types, NOT NULL, and PRIMARY KEY constraints
I need to write a query on SQL server to get the list of columns in a particular table, its associated data types (with length) and if they are not null. And I have managed to do this much.

But now i also need to get, in the same table, against a column - TRUE if that column is a primary key.

How do i do this?

My expected output is:

```<code>Column name | Data type | Length | isnull | Pk
</code>```

答:
Query : EXEC SP_DESCRIBE_FIRST_RESULT_SET N'SELECT ANNUAL_INCOME FROM
[DB_NAME].[DBO].[EMPLOYEE]'

NOTE: IN SOME IDE BEFORE SELECT N IS WORKING OR, IN SOME IDE WITHOUT N IS WORKING

Body:
I need to write a query on SQL server to get the list of columns in a particular table, its associated data types (with length) and if they are not null. And I have managed to do this much.

But now i also need to get, in the same table, against a column - TRUE if that column is a primary key.

How do i do this?

My expected output is:

Column name | Data type | Length | isnull | Pk


问:
How to hide Router navbar from privacy policy component
Once the app launches privacy policy component will arrive. in this component, want to hide the routers navbar using React.

```<code><li>
<NavLink to="/profile" ><i className="fas fa-epi-profile"></i></NavLink>
</li>
<li>
<NavLink to="/Home"><i className="fas fa-epi-good_picker"></i></NavLink>
</li>
<li>
<NavLink to="/TaskListTabs"><i className="fas fa-epi-task"></i></NavLink> </li>
<li>
<NavLink to="/Notification"><i className="fas fa-epi-notification"></i></NavLink>
</li>
</code>```

( this is App.js file)

```<code>class App extends Component { render() { return ( <RoutersNav /> ); } }
</code>```

but in privacy, component am using the navigation to another component which is code

```<code><NavLink to="/login" className="float-right">
<input type="submit" className="btn" onClick={this.routeChange} name="accept" value="Accept" />
</NavLink>
</code>```

once click on button giving error as "Uncaught Error: Invariant failed: You should not use <Route> outside a <Router>

答:
In the navigationOptions of HomeScreen

```<code>static navigationOptions = { title: 'Welcome', header: { visible:false } };
</code>```

If you want to hide the header as the default behavior, you could instead pass navigationOptions to the navigator

```<code>const SimpleApp = StackNavigator({
    Home: { screen: HomeScreen },
    LoginView: { screen: LoginView }, },
    navigationOptions:{ header:{ visible:false }});
</code>```

Basic and simple way to hide a navbar

Body:
Once the app launches privacy policy component will arrive. in this component, want to hide the routers navbar using React.

<NavLink to="/profile" ></NavLink>

<NavLink to="/Home"></NavLink>

<NavLink to="/TaskListTabs"></NavLink>

<NavLink to="/Notification"></NavLink>

( this is App.js file)

class App extends Component { render() { return ( <RoutersNav /> ); } }

but in privacy, component am using the navigation to another component which is code

<NavLink to="/login" className="float-right">
<input type="submit" className="btn" onClick={this.routeChange} name="accept" value="Accept" />
</NavLink>

once click on button giving error as "Uncaught Error: Invariant failed: You should not use <Route> outside a <Router>

Body:
In the navigationOptions of HomeScreen

static navigationOptions = { title: 'Welcome', header: { visible:false } };

If you want to hide the header as the default behavior, you could instead pass navigationOptions to the navigator

const SimpleApp = StackNavigator({
    Home: { screen: HomeScreen },
    LoginView: { screen: LoginView }, },
    navigationOptions:{ header:{ visible:false }});

Basic and simple way to hide a navbar


问:
Nothing being written to php file
I'm trying to write to a php file but nothing is written to file. I'm using php 7. I have 2 files, index.php, and comments.php (file attempting to write to). The permissions for comments.php is set to 777.

When I cat the comments.php file it is empty and no new content is added to the index.php page.

```<code><?php
        if($_POST) {
            $name = $_POST['name'];
            $comment = $_POST['comment'];
            $handle = fopen("comments.php", "a");
            fwrite($handle, "<b><i>" . $name . "</b></i> said:<br />" . $comment . "br /><br />" );
            fclose($handle);
        }
?>

<!DOCTYPE html>
<html>
    <head>
        <title>Rolling Log</title>
        <meta charset="uft-8">
    </head>
    <body>
        <h1>Post a change mgmt comment</h1>
        <form action="" method="POST">
            Name: <br /> <input type="text" name="name"> <br />
            Comment: <br /> <textarea rows="10" cols="30" name="comment"></textarea> <br /><br />
            <input type="submit" value="Post comment">
        </form>
        <hr>
        <h1>Other CM Comments</h1>
        <?php
            include "comments.php";
        ?>
    </body>
</html>
</code>```

答:
I put this on my server, and it works as expected.  This tells me that the problem is not in your code, except that this line:

```<code>fwrite($handle, "<b><i>" . $name . "</b></i> said:<br />" . $comment . "br /><br />" );
</code>```

Should look like this:

```<code>fwrite($handle, "<b><i>" . $name . "</b></i> said:<br />" . $comment . "<br />" );
</code>```

The directory should be owned by the user running your webserver.  In my case, this is apache.  The directory containing the index.php file should be executable by this user, as well, or it won't be able to write anything.

Let me know if you've tried looking at these things and if it helps.  I'll see what else I can think of.

Title: Nothing being written to php file

Body:
I'm trying to write to a php file but nothing is written to file. I'm using php 7. I have 2 files, index.php, and comments.php (file attempting to write to). The permissions for comments.php is set to 777.

When I cat the comments.php file it is empty and no new content is added to the index.php page.

<?php
        if($_POST) {
            $name = $_POST['name'];
            $comment = $_POST['comment'];
            $handle = fopen("comments.php", "a");
            fwrite($handle, "" . $name . " said:
" . $comment . "br />
" );
            fclose($handle);
        }
?>

<!DOCTYPE html>

        <title>Rolling Log</title>
        <meta charset="uft-8">

Post a change mgmt comment

        <form action="" method="POST">
            Name:
 <input type="text" name="name">

            Comment:
 <textarea rows="10" cols="30" name="comment"></textarea>

            <input type="submit" value="Post comment">
        </form>

Other CM Comments

        <?php
            include "comments.php";
        ?>

Body:
I put this on my server, and it works as expected.  This tells me that the problem is not in your code, except that this line:

fwrite($handle, "<b><i>" . $name . "</b></i> said:<br />" . $comment . "br /><br />" );

Should look like this:

fwrite($handle, "<b><i>" . $name . "</b></i> said:<br />" . $comment . "<br />" );

The directory should be owned by the user running your webserver.  In my case, this is apache.  The directory containing the index.php file should be executable by this user, as well, or it won't be able to write anything.

Let me know if you've tried looking at these things and if it helps.  I'll see what else I can think of.


问:
How does the CPU know how many bytes it should read for the next instruction, considering instructions have different lengths?
So i was reading a paper, and in it, they said that statically disassembling the code of a binary is undecidable, because a series of bytes could be represented as many possible ways as shown in picture ( its x86 )

so my question is :

how does the CPU execute this then? for example in the picture, when we reach after C3, how does it know how many bytes it should  read for the next instruction?

how does the CPU know how much it should increment the PC after executing one instruction? does it somehow store the size of the current instruction and add that when it wants to increment PC?

if the CPU can somehow know how many bytes it should read for the next instruction or basically how to interpret the next instruction, why cant we do it statically?

答:
Your main problem seems to be the following one:

if the CPU can somehow know how many bytes it should read for the next instruction or basically how to interpret the next instruction, why cant we do it statically?

The problem described in the paper is related to "jumping" instructions (which does not only mean jmp, but also int, ret, syscall and similar instructions):

The purpose of such instructions is to continue program execution at a completely different address instead of continuing at the next instruction. (Function calls and while() loops are examples where program execution does not continue at the next instruction.)

Your example begins with the instruction jmp eax which means that the value in the register eax decides which instruction is executed after the jmp eax instruction.

If eax contains the address of the byte 0F, the CPU will execute the jcc instruction (left case in the picture); if it contains the address of 88, it will execute the mov instruction (middle case in the picture); and if it contains the address of 52, it will execute the push instruction (right case in the picture).

Because you do not know which value eax will have when the program is executed, you cannot know which of the three cases will happen.

(I was told that in the 1980s there even were commercial programs where different cases happened during runtime: In your example this would mean that sometimes the jcc instruction and sometimes the mov instruction is executed!)

When we reach after C3, how does it know how many bytes it should read for the next instruction?

How does the CPU know how much it should increment the PC after executing one instruction?

C3 is not a good example because retn is a "jumping" instruction: The "instruction after C3" will never be reached because program execution is continued elsewhere.

However, you might replace C3 by another instruction which is one byte long (such as 52). In this case it is well defined that the next instruction will begin with the byte 0F and not with 88 or 52.


问:
better approach to group and sort a single list in kotlin
I have a list which consists of custom objects. I want to to first group the list based on alphabetic order and then sort those groups based on enum values. Let me show you through code:

My list:

```<code>val list = listOf(Item("America",Severity.CRITICAL), Item("India", Severity.LOW),Item("Australia", Severity.SEVERE),Item("Indonesia", Severity.CRITICAL), Item("Japan", Severity.SEVERE), Item("Jordan", Severity.CRITICAL))
</code>```

My Severity enum class:

```<code>enum class Severity{
 CRITICAL, SEVERE, MODERATE, LOW
}
</code>```

My expected output:

```<code>val sortedList = listOf(Item("America",Severity.CRITICAL),Item("Australia", Severity.SEVERE),Item("Indonesia", Severity.CRITICAL),Item("India", Severity.LOW), Item("Jordan", Severity.CRITICAL),Item("Japan", Severity.SEVERE))
</code>```

As you can see the list has all the items in alphabetical order and ordered as per the Severity enum class.

My idea:

I am planning to create lists inside a list. Those child lists will hold group of all the items in alphabetical order and later I will sort the items of the sub lists based on Severity enum values.

How can I achieve this?

答:
If you have

data class Item(val country: String, val severity: Severity)

and

```<code>enum class Severity(val value: Int) {
    CRITICAL(0), SEVERE(1), MODERATE(2), LOW(3)
}
</code>```

then

```<code>val actual = list.sortedWith(
    compareBy(
        { it.country.first() },
        { it.severity.value }
    )
)
</code>```

Body:
I have a list which consists of custom objects. I want to to first group the list based on alphabetic order and then sort those groups based on enum values. Let me show you through code:

My list:

val list = listOf(Item("America",Severity.CRITICAL), Item("India", Severity.LOW),Item("Australia", Severity.SEVERE),Item("Indonesia", Severity.CRITICAL), Item("Japan", Severity.SEVERE), Item("Jordan", Severity.CRITICAL))

My Severity enum class:

enum class Severity{
 CRITICAL, SEVERE, MODERATE, LOW
}

My expected output:

val sortedList = listOf(Item("America",Severity.CRITICAL),Item("Australia", Severity.SEVERE),Item("Indonesia", Severity.CRITICAL),Item("India", Severity.LOW), Item("Jordan", Severity.CRITICAL),Item("Japan", Severity.SEVERE))

As you can see the list has all the items in alphabetical order and ordered as per the Severity enum class.

My idea:

I am planning to create lists inside a list. Those child lists will hold group of all the items in alphabetical order and later I will sort the items of the sub lists based on Severity enum values.

How can I achieve this?

Body:
If you have

data class Item(val country: String, val severity: Severity)

and

enum class Severity(val value: Int) {
    CRITICAL(0), SEVERE(1), MODERATE(2), LOW(3)
}

then

val actual = list.sortedWith(
    compareBy(
        { it.country.first() },
        { it.severity.value }
    )
)


问:
Flutter make GridView from json array
is any solution to make GridView with this structure? for example?

grid data are:

```<code>{
  'icon':Icons.home,
  'title':'dashboard'
},
</code>```

i try to implementing this code

```<code>GridView.count(
    crossAxisCount: 4,
    childAspectRatio: 1.0,
    padding: const EdgeInsets.all(4.0),
    mainAxisSpacing: 4.0,
    crossAxisSpacing: 4.0,
    children: <Map<String,String>>[
      {
        'icon':Icons.home,
        'title':'dashboard'
      },
    ].map((Map<String,String> item) {
      return Container(
        child: Column(
          children: <Widget>[
            Icon(IconData(item['icon']))
            Text(item['title']),
          ],
        ),
      );
    }).toList()),
</code>```

答:
There need to give map type is dynamic like as  <Map<String,dynamic>>
instead of <Map<String,String>> String and IconData type,
becuase of there are String and IconData type data into your map data, which String can't assigned to type of IconData and vice versa

```<code>GridView.count(
        crossAxisCount: 4,
        childAspectRatio: 1.0,
        padding: const EdgeInsets.all(4.0),
        mainAxisSpacing: 4.0,
        crossAxisSpacing: 4.0,
        children: <Map<String,dynamic>>[
          {
            'icon':Icons.home,
            'title':'dashboard'
          },
        ].map((Map<String,dynamic> item) {
          return Container(
            child: Column(
              children: <Widget>[
                Icon(item['icon']),
                Text(item['title']),
              ],
            ),
          );
        }).toList())
</code>```

this help you

Title: Flutter make GridView from json array

Body:
is any solution to make GridView with this structure? for example?

grid data are:

{
  'icon':Icons.home,
  'title':'dashboard'
},

i try to implementing this code

GridView.count(
    crossAxisCount: 4,
    childAspectRatio: 1.0,
    padding: const EdgeInsets.all(4.0),
    mainAxisSpacing: 4.0,
    crossAxisSpacing: 4.0,
    children: <Map<String,String>>[
      {
        'icon':Icons.home,
        'title':'dashboard'
      },
    ].map((Map<String,String> item) {
      return Container(
        child: Column(
          children: <Widget>[
            Icon(IconData(item['icon']))
            Text(item['title']),
          ],
        ),
      );
    }).toList()),

Body:
There need to give map type is dynamic like as  <Map<String,dynamic>>
instead of <Map<String,String>> String and IconData type,
becuase of there are String and IconData type data into your map data, which String can't assigned to type of IconData and vice versa

GridView.count(
        crossAxisCount: 4,
        childAspectRatio: 1.0,
        padding: const EdgeInsets.all(4.0),
        mainAxisSpacing: 4.0,
        crossAxisSpacing: 4.0,
        children: <Map<String,dynamic>>[
          {
            'icon':Icons.home,
            'title':'dashboard'
          },
        ].map((Map<String,dynamic> item) {
          return Container(
            child: Column(
              children: <Widget>[
                Icon(item['icon']),
                Text(item['title']),
              ],
            ),
          );
        }).toList())

this help you


问:
delay caused by fat argument in python multiprocessing
i am using multiprocessing in python to parallel some computing-heavy functions. but i found that there is a delay in process creating if passing a fat argument (e.g., a 1000-note networkx graph or a 1000000-item list). i experiment on two multiprocessing modules "multiprocessing" and "pathos", get the similar results. my question is how to avoid this kind of delay because it ruins the benefit brought by parallel computing.

in my sample code, i just pass a fat argument to the function for multiprocessing - the function body does not touch the argument as all.

the sample code using "multiprocessing"

```<code>import multiprocessing
import time

def f(args):
    (x, conn, t0, graph) = args
    ans = 1
    x0 = x
    t = time.time() - t0
    conn.send('factorial of %d: start@%.2fs' % (x0, t))
    while x > 1:
        ans *= x
        time.sleep(0.5)
        x -= 1
    t = time.time() - t0
    conn.send('factorial of %d: finish@%.2fs, res = %d' %(x0, t, ans))
    return ans

def main():
    var = (4, 8, 12, 20, 16)
    p = multiprocessing.Pool(processes = 4)
    p_conn, c_conn = multiprocessing.Pipe()
    params = []
    t0 = time.time()
    N = 1000
    import networkx as nx
    G = nx.complete_graph(N, nx.DiGraph())

    import random
    for (start, end) in G.edges:
        G.edges[start, end]['weight'] = random.random()

    for i in var:
        params.append((i, c_conn, t0, G))
    res = list(p.imap(f, params))
    p.close()
    p.join()

    print('output:')
    while p_conn.poll():
        print(p_conn.recv())
    t = time.time() - t0
    print('factorial of %s@%.2fs: %s' % (var, t, res))

if __name__ == '__main__':
    main()
</code>```

the output of the above sample code

```<code>output:
factorial of 4: start@29.78s
factorial of 4: finish@31.29s, res = 24
factorial of 8: start@53.56s
factorial of 8: finish@57.07s, res = 40320
factorial of 12: start@77.25s
factorial of 12: finish@82.75s, res = 479001600
factorial of 20: start@100.39s
factorial of 20: finish@109.91s, res = 2432902008176640000
factorial of 16: start@123.55s
factorial of 16: finish@131.05s, res = 20922789888000
factorial of (4, 8, 12, 20, 16)@131.06s: [24, 40320, 479001600, 2432902008176640000, 20922789888000]

Process finished with exit code 0
</code>```

according to the above output, there is around 24 second delays between two process creating

the sample code using "pathos"

```<code>import pathos
import multiprocess
import time

def f(x, conn, t0, graph):
    ans = 1
    x0 = x
    t = time.time() - t0
    conn.send('factorial of %d: start@%.2fs' % (x0, t))
    while x > 1:
        ans *= x
        time.sleep(0.5)
        x -= 1
    t = time.time() - t0
    conn.send('factorial of %d: finish@%.2fs, res = %d' %(x0, t, ans))
    return ans

def main():
    var = (4, 8, 12, 20, 16)
    p = pathos.multiprocessing.ProcessPool(nodes=4)
    p_conn, c_conn = multiprocess.Pipe()
    t0 = time.time()
    conn_s = [c_conn] * len(var)
    t0_s = [t0] * len(var)
    N = 1000
    import networkx as nx
    G = nx.complete_graph(N, nx.DiGraph())

    import random
    for (start, end) in G.edges:
        G.edges[start, end]['weight'] = random.random()

    res = list(p.imap(f, var, conn_s, t0_s, [G] * len(var)))

    print('output:')
    while p_conn.poll():
        print(p_conn.recv())
    t = time.time() - t0
    print('factorial of %s@%.2fs: %s' % (var, t, res))

if __name__ == '__main__':
    main()

</code>```

the output of the above sample code,

```<code>output:
factorial of 4: start@29.63s
factorial of 4: finish@31.13s, res = 24
factorial of 8: start@53.50s
factorial of 8: finish@57.00s, res = 40320
factorial of 12: start@76.94s
factorial of 12: finish@82.44s, res = 479001600
factorial of 20: start@100.72s
factorial of 20: finish@110.23s, res = 2432902008176640000
factorial of 16: start@123.69s
factorial of 16: finish@131.20s, res = 20922789888000
factorial of (4, 8, 12, 20, 16)@131.20s: [24, 40320, 479001600, 2432902008176640000, 20922789888000]

Process finished with exit code 0
</code>```

similarly, according to the above output, there is around 24 second delays between two process creating.

if i reduce the graph size (smaller node number), the delay decreases accordingly. i guess it is due to the extra time used for pickling/dilling the networkx graph as an argument.
ideally, first 4 processes should be created at the same time. how to avoid this cost? thank you!

UPDATE

Thanks to Alexander's kind answer, i remove the pipe in both "multiprocessing" and "pathos" codes. the "multiprocessing" code performs as Alexander's - delay reduced to 1 second, but the "pathos" code still has more than 20 seconds delay. the revised "pathos" code is posted below,

```<code>import pathos
import multiprocess
import time
from pympler import asizeof
import sys

def f(args):
    (x, graph) = args
    t = time.ctime()
    print('factorial of %d: start@%s' % (x, t))
    time.sleep(4)
    return x

def main():
    t0 = time.time()
    params = []

    var = (4, 8, 12, 20, 16)
    p = pathos.multiprocessing.ProcessPool(nodes=4)
    N = 1000
    import networkx as nx
    G = nx.complete_graph(N, nx.DiGraph())

    import random
    for (start, end) in G.edges:
        G.edges[start, end]['weight'] = random.random()

    print('Size of G by sys', sys.getsizeof(G), 'asizeof', asizeof.asizeof(G))
    print('G created in %.2f' %  (time.time() - t0))

    for i in var:
        params.append((i, G))
    res = list(p.imap(f, params))
    p.close()
    p.join()

if __name__ == '__main__':
    main()
</code>```

the output goes as

```<code>Size of G by sys 56 asizeof 338079824
G created in 17.36
factorial of 4: start@Fri May 31 11:39:26 2019
factorial of 8: start@Fri May 31 11:39:53 2019
factorial of 12: start@Fri May 31 11:40:19 2019
factorial of 20: start@Fri May 31 11:40:44 2019
factorial of 16: start@Fri May 31 11:41:10 2019

Process finished with exit code 0
</code>```

答:
This fat argument (338 MB) should be copied to a separate memory when each process is created, but this should not take that long (24 seconds).

Here is how it works on my computer:

The program hangs in conn.send. The problem with the code (1.) is in multiprocess.Pipe(). From https://docs.python.org/3.4/library/multiprocessing.html?highlight=process "... Note that data in a pipe may become corrupted if two processes (or threads) try to read from or write to the same end of the pipe at the same time."

So, I changed the code:

```<code>import multiprocessing
import os
import time
import sys
from pympler import asizeof
import networkx as nx
import random

def factorial(args):
    (x, t, graph) = args
    s0 = '# pid %s x %2d' % (format(os.getpid()), x)
    s1 = 'started @ %.2f' % (time.time() - t)
    print(s0, s1)
    f = 1
    while x > 1:
        f *= x
        x -= 1
        time.sleep(0.5)
    s2 = 'ended   @ %.2f' % (time.time() - t)
    print(s0, s2, f)
    return s0, s1, s2, f

if __name__ == '__main__':
    t0 = time.time()
    N = 1000
    G = nx.complete_graph(N, nx.DiGraph())
    for (start, end) in G.edges:
        G.edges[start, end]['weight'] = random.random()
    print('Size of G by sys', sys.getsizeof(G), 'asizeof', asizeof.asizeof(G))
    print('G created in %.2f' %  (time.time() - t0))
    t0 = time.time()
    p = multiprocessing.Pool(processes=4)
    outputs = list(p.imap(factorial, [(i, t0, G) for i in (4, 8, 12, 20, 16)]))
    print('output:')
    for output in outputs:
        print(output)
</code>```

Output now:

Size of G by sys 56 asizeof 338079824
G created in 13.03
# pid 2266 x  4 started @ 1.27
# pid 2267 x  8 started @ 1.98
# pid 2268 x 12 started @ 2.72
# pid 2266 x  4 ended   @ 2.77 24
# pid 2269 x 20 started @ 3.44
# pid 2266 x 16 started @ 4.09
# pid 2267 x  8 ended   @ 5.49 40320
# pid 2268 x 12 ended   @ 8.23 479001600
# pid 2266 x 16 ended   @ 11.60 20922789888000
# pid 2269 x 20 ended   @ 12.95 2432902008176640000
output:
('# pid 2266 x  4', 'started @ 1.27', 'ended   @ 2.77', 24)
('# pid 2267 x  8', 'started @ 1.98', 'ended   @ 5.49', 40320)
('# pid 2268 x 12', 'started @ 2.72', 'ended   @ 8.23', 479001600)
('# pid 2269 x 20', 'started @ 3.44', 'ended   @ 12.95', 2432902008176640000)
('# pid 2266 x 16', 'started @ 4.09', 'ended   @ 11.60', 20922789888000)
```

<p>338 MB data created in 11 seconds and, yes, it does take time to start the first 4 processes. The delays between starts are although much smaller: 0.71, 0.74, 0.72 seconds. I have iMac with Intel i5 @ 3.2 GHz. </p>

<p>The biggest N, when is no visible delay, is 78:</p>

<pre class="lang-none prettyprint-override"><code>Size of G by sys 56 asizeof 1970464
G created in 0.08
# pid 2242 x  4 started @ 0.01
# pid 2243 x  8 started @ 0.01
# pid 2244 x 12 started @ 0.01
# pid 2245 x 20 started @ 0.01
# pid 2242 x  4 ended   @ 1.51 24
# pid 2242 x 16 started @ 1.53
# pid 2243 x  8 ended   @ 3.52 40320
# pid 2244 x 12 ended   @ 5.52 479001600
# pid 2242 x 16 ended   @ 9.04 20922789888000
# pid 2245 x 20 ended   @ 9.53 2432902008176640000
output:
('# pid 2242 x  4', 'started @ 0.01', 'ended   @ 1.51', 24)
('# pid 2243 x  8', 'started @ 0.01', 'ended   @ 3.52', 40320)
('# pid 2244 x 12', 'started @ 0.01', 'ended   @ 5.52', 479001600)
('# pid 2245 x 20', 'started @ 0.01', 'ended   @ 9.53', 2432902008176640000)
('# pid 2242 x 16', 'started @ 1.53', 'ended   @ 9.04', 20922789888000)
</code>```

Body:
i am using multiprocessing in python to parallel some computing-heavy functions. but i found that there is a delay in process creating if passing a fat argument (e.g., a 1000-note networkx graph or a 1000000-item list). i experiment on two multiprocessing modules "multiprocessing" and "pathos", get the similar results. my question is how to avoid this kind of delay because it ruins the benefit brought by parallel computing.

in my sample code, i just pass a fat argument to the function for multiprocessing - the function body does not touch the argument as all.

the sample code using "multiprocessing"

import multiprocessing
import time

def f(args):
    (x, conn, t0, graph) = args
    ans = 1
    x0 = x
    t = time.time() - t0
    conn.send('factorial of %d: start@%.2fs' % (x0, t))
    while x > 1:
        ans *= x
        time.sleep(0.5)
        x -= 1
    t = time.time() - t0
    conn.send('factorial of %d: finish@%.2fs, res = %d' %(x0, t, ans))
    return ans

def main():
    var = (4, 8, 12, 20, 16)
    p = multiprocessing.Pool(processes = 4)
    p_conn, c_conn = multiprocessing.Pipe()
    params = []
    t0 = time.time()
    N = 1000
    import networkx as nx
    G = nx.complete_graph(N, nx.DiGraph())

    import random
    for (start, end) in G.edges:
        G.edges[start, end]['weight'] = random.random()

    for i in var:
        params.append((i, c_conn, t0, G))
    res = list(p.imap(f, params))
    p.close()
    p.join()

    print('output:')
    while p_conn.poll():
        print(p_conn.recv())
    t = time.time() - t0
    print('factorial of %s@%.2fs: %s' % (var, t, res))

if __name__ == '__main__':
    main()

the output of the above sample code

output:
factorial of 4: start@29.78s
factorial of 4: finish@31.29s, res = 24
factorial of 8: start@53.56s
factorial of 8: finish@57.07s, res = 40320
factorial of 12: start@77.25s
factorial of 12: finish@82.75s, res = 479001600
factorial of 20: start@100.39s
factorial of 20: finish@109.91s, res = 2432902008176640000
factorial of 16: start@123.55s
factorial of 16: finish@131.05s, res = 20922789888000
factorial of (4, 8, 12, 20, 16)@131.06s: [24, 40320, 479001600, 2432902008176640000, 20922789888000]

Process finished with exit code 0

according to the above output, there is around 24 second delays between two process creating

the sample code using "pathos"

import pathos
import multiprocess
import time

def f(x, conn, t0, graph):
    ans = 1
    x0 = x
    t = time.time() - t0
    conn.send('factorial of %d: start@%.2fs' % (x0, t))
    while x > 1:
        ans *= x
        time.sleep(0.5)
        x -= 1
    t = time.time() - t0
    conn.send('factorial of %d: finish@%.2fs, res = %d' %(x0, t, ans))
    return ans

def main():
    var = (4, 8, 12, 20, 16)
    p = pathos.multiprocessing.ProcessPool(nodes=4)
    p_conn, c_conn = multiprocess.Pipe()
    t0 = time.time()
    conn_s = [c_conn] * len(var)
    t0_s = [t0] * len(var)
    N = 1000
    import networkx as nx
    G = nx.complete_graph(N, nx.DiGraph())

    import random
    for (start, end) in G.edges:
        G.edges[start, end]['weight'] = random.random()

    res = list(p.imap(f, var, conn_s, t0_s, [G] * len(var)))

    print('output:')
    while p_conn.poll():
        print(p_conn.recv())
    t = time.time() - t0
    print('factorial of %s@%.2fs: %s' % (var, t, res))

if __name__ == '__main__':
    main()

the output of the above sample code,

output:
factorial of 4: start@29.63s
factorial of 4: finish@31.13s, res = 24
factorial of 8: start@53.50s
factorial of 8: finish@57.00s, res = 40320
factorial of 12: start@76.94s
factorial of 12: finish@82.44s, res = 479001600
factorial of 20: start@100.72s
factorial of 20: finish@110.23s, res = 2432902008176640000
factorial of 16: start@123.69s
factorial of 16: finish@131.20s, res = 20922789888000
factorial of (4, 8, 12, 20, 16)@131.20s: [24, 40320, 479001600, 2432902008176640000, 20922789888000]

Process finished with exit code 0

similarly, according to the above output, there is around 24 second delays between two process creating.

if i reduce the graph size (smaller node number), the delay decreases accordingly. i guess it is due to the extra time used for pickling/dilling the networkx graph as an argument.
ideally, first 4 processes should be created at the same time. how to avoid this cost? thank you!

UPDATE

Thanks to Alexander's kind answer, i remove the pipe in both "multiprocessing" and "pathos" codes. the "multiprocessing" code performs as Alexander's - delay reduced to 1 second, but the "pathos" code still has more than 20 seconds delay. the revised "pathos" code is posted below,

import pathos
import multiprocess
import time
from pympler import asizeof
import sys

def f(args):
    (x, graph) = args
    t = time.ctime()
    print('factorial of %d: start@%s' % (x, t))
    time.sleep(4)
    return x

def main():
    t0 = time.time()
    params = []

    var = (4, 8, 12, 20, 16)
    p = pathos.multiprocessing.ProcessPool(nodes=4)
    N = 1000
    import networkx as nx
    G = nx.complete_graph(N, nx.DiGraph())

    import random
    for (start, end) in G.edges:
        G.edges[start, end]['weight'] = random.random()

    print('Size of G by sys', sys.getsizeof(G), 'asizeof', asizeof.asizeof(G))
    print('G created in %.2f' %  (time.time() - t0))

    for i in var:
        params.append((i, G))
    res = list(p.imap(f, params))
    p.close()
    p.join()

if __name__ == '__main__':
    main()

the output goes as

Size of G by sys 56 asizeof 338079824
G created in 17.36
factorial of 4: start@Fri May 31 11:39:26 2019
factorial of 8: start@Fri May 31 11:39:53 2019
factorial of 12: start@Fri May 31 11:40:19 2019
factorial of 20: start@Fri May 31 11:40:44 2019
factorial of 16: start@Fri May 31 11:41:10 2019

Process finished with exit code 0

Body:
This fat argument (338 MB) should be copied to a separate memory when each process is created, but this should not take that long (24 seconds).

Here is how it works on my computer:

The program hangs in conn.send. The problem with the code (1.) is in multiprocess.Pipe(). From https://docs.python.org/3.4/library/multiprocessing.html?highlight=process "... Note that data in a pipe may become corrupted if two processes (or threads) try to read from or write to the same end of the pipe at the same time."

So, I changed the code:

import multiprocessing
import os
import time
import sys
from pympler import asizeof
import networkx as nx
import random

def factorial(args):
    (x, t, graph) = args
    s0 = '# pid %s x %2d' % (format(os.getpid()), x)
    s1 = 'started @ %.2f' % (time.time() - t)
    print(s0, s1)
    f = 1
    while x > 1:
        f *= x
        x -= 1
        time.sleep(0.5)
    s2 = 'ended   @ %.2f' % (time.time() - t)
    print(s0, s2, f)
    return s0, s1, s2, f

if __name__ == '__main__':
    t0 = time.time()
    N = 1000
    G = nx.complete_graph(N, nx.DiGraph())
    for (start, end) in G.edges:
        G.edges[start, end]['weight'] = random.random()
    print('Size of G by sys', sys.getsizeof(G), 'asizeof', asizeof.asizeof(G))
    print('G created in %.2f' %  (time.time() - t0))
    t0 = time.time()
    p = multiprocessing.Pool(processes=4)
    outputs = list(p.imap(factorial, [(i, t0, G) for i in (4, 8, 12, 20, 16)]))
    print('output:')
    for output in outputs:
        print(output)

Output now:

Size of G by sys 56 asizeof 338079824
G created in 13.03
# pid 2266 x  4 started @ 1.27
# pid 2267 x  8 started @ 1.98
# pid 2268 x 12 started @ 2.72
# pid 2266 x  4 ended   @ 2.77 24
# pid 2269 x 20 started @ 3.44
# pid 2266 x 16 started @ 4.09
# pid 2267 x  8 ended   @ 5.49 40320
# pid 2268 x 12 ended   @ 8.23 479001600
# pid 2266 x 16 ended   @ 11.60 20922789888000
# pid 2269 x 20 ended   @ 12.95 2432902008176640000
output:
('# pid 2266 x  4', 'started @ 1.27', 'ended   @ 2.77', 24)
('# pid 2267 x  8', 'started @ 1.98', 'ended   @ 5.49', 40320)
('# pid 2268 x 12', 'started @ 2.72', 'ended   @ 8.23', 479001600)
('# pid 2269 x 20', 'started @ 3.44', 'ended   @ 12.95', 2432902008176640000)
('# pid 2266 x 16', 'started @ 4.09', 'ended   @ 11.60', 20922789888000)

338 MB data created in 11 seconds and, yes, it does take time to start the first 4 processes. The delays between starts are although much smaller: 0.71, 0.74, 0.72 seconds. I have iMac with Intel i5 @ 3.2 GHz.

The biggest N, when is no visible delay, is 78:

Size of G by sys 56 asizeof 1970464
G created in 0.08
# pid 2242 x  4 started @ 0.01
# pid 2243 x  8 started @ 0.01
# pid 2244 x 12 started @ 0.01
# pid 2245 x 20 started @ 0.01
# pid 2242 x  4 ended   @ 1.51 24
# pid 2242 x 16 started @ 1.53
# pid 2243 x  8 ended   @ 3.52 40320
# pid 2244 x 12 ended   @ 5.52 479001600
# pid 2242 x 16 ended   @ 9.04 20922789888000
# pid 2245 x 20 ended   @ 9.53 2432902008176640000
output:
('# pid 2242 x  4', 'started @ 0.01', 'ended   @ 1.51', 24)
('# pid 2243 x  8', 'started @ 0.01', 'ended   @ 3.52', 40320)
('# pid 2244 x 12', 'started @ 0.01', 'ended   @ 5.52', 479001600)
('# pid 2245 x 20', 'started @ 0.01', 'ended   @ 9.53', 2432902008176640000)
('# pid 2242 x 16', 'started @ 1.53', 'ended   @ 9.04', 20922789888000)


问:
Get User Agent in my app which doesn't contain a webview
I can ask WebView.getWebSettings().getUserAgentString() to get the user
agent, but this doesn't work all that well for my app as I need to
instantiate a WebView first even though I don't need.

Is there another way to get to the User Agent without using a WebView.getSetting, because in my application, I don't need a webView?

Help me please

答:
You can see how it's determined by looking at the source

http://www.google.com/codesearch/p?hl=en#uX1GffpyOZk/core/java/android/webkit/WebSettings.java&q=getCurrentUserAgent&sa=N&cd=1&ct=rc&l=370

According to the documentation, you can't get a WebSettings object without a WebView.

Do you need it to be exactly the one that the phone would send?  If not, just pick up a standard Android User Agent (not build/version specific)


问:
How to import Android library module (AAR) using gradle cli
I am developing an Android Library module in AAR format. I found it very troublesome to have to be manually importing the module via Android Studio wizard each time I need to test library changes on an Android sample app. I changed my approach to using a symbolic link and linking the generated AAR on the library side with the AAR on the sample app side and just building and syncing Gradle via Android Studio.

However, this process is still not the best because I need to manually click buttons on Studio to achieve this. What I would like is to write a simple script using Gradle CLI and/or bash that allows me, from the app's side, to import the module into the app from some directory and sync the app's Gradle after importing.

Is this possible? Thanks.

答:
You don't need to import your library module every time. Make your library as one of the modules and link the dependency between app and library.

Make sure the library is listed at the top of your settings.gradle file, as shown here for a library named "my-library-module":

```<code>include ':app', ':my-library-module'
</code>```

Open the app module's build.gradle file and add a new line to the dependencies block as shown in the following snippet:

```<code>dependencies {
    implementation project(":my-library-module")
}
</code>```

And build using command lines.

```<code>gradlew assembleDebug
</code>```

https://developer.android.com/studio/projects/android-library

Body:
You don't need to import your library module every time. Make your library as one of the modules and link the dependency between app and library.

Make sure the library is listed at the top of your settings.gradle file, as shown here for a library named "my-library-module":

include ':app', ':my-library-module'

Open the app module's build.gradle file and add a new line to the dependencies block as shown in the following snippet:

dependencies {
    implementation project(":my-library-module")
}

And build using command lines.

gradlew assembleDebug

https://developer.android.com/studio/projects/android-library


问:
Why does Android-Chrome not clear Session Variables upon closure of the App?
First, let me say.  I like the new format.  Thanks Guys.

Ok,

I thought that I had it all figured out.  Unfortunately, Android hit me hard.  Android doesn't forget the last value of a Session Value.

If I close a browser in Windows, iOS, or Android, shouldn't it be expected to possess absolutely no relation between key and value, much less the EXISTENCE of a key?

Android is the only one that will retain that key and value for days.

WHEN A BROWSER CLOSES, SHOULDN'T THE SESSION VARIABLES CLOSE - DIE?

Until the Session Variable issue can be resolved, the involvement of other Session variables is pointless.

Page_Load(object o, EventArgs ea)
{

// granted, only in the android world
 // I know this is as redneck as redneck gets, but I tried

```<code>Response.Write("<script>alert(\""+Session["theVal"]+"\")</script>");
Session["theVal"]="Mickey Mouse";
</code>```

// only in Android will that continually ring "Mickey Mouse", even if you close the browser down.

// the other browsers will ring 'null', error, or 'blank'

//  I hate Apple, but it even closes down the variable upon closure of the app.
}

Just suggestions.   I may be doing something completely wrong.

I appreciate any help.

答: you close the browser in android. but it does not mean the app lost tracks of the web page. I have iOS for instance..you have to manually remove all the web pages which will be stacked one above the other. After you do that and then you open the chrome, all the sessions will be destroyed..I guess it is just the ay google made chrome for ios and android.</p>

Body:
First, let me say.  I like the new format.  Thanks Guys.

Ok,

I thought that I had it all figured out.  Unfortunately, Android hit me hard.  Android doesn't forget the last value of a Session Value.

If I close a browser in Windows, iOS, or Android, shouldn't it be expected to possess absolutely no relation between key and value, much less the EXISTENCE of a key?

Android is the only one that will retain that key and value for days.

WHEN A BROWSER CLOSES, SHOULDN'T THE SESSION VARIABLES CLOSE - DIE?

Until the Session Variable issue can be resolved, the involvement of other Session variables is pointless.

Page_Load(object o, EventArgs ea)
{

// granted, only in the android world
 // I know this is as redneck as redneck gets, but I tried

Response.Write("");
Session["theVal"]="Mickey Mouse";

// only in Android will that continually ring "Mickey Mouse", even if you close the browser down.

// the other browsers will ring 'null', error, or 'blank'

//  I hate Apple, but it even closes down the variable upon closure of the app.
}

Just suggestions.   I may be doing something completely wrong.

I appreciate any help.


问:
Strategy recommendations for implementing Azure to perform simulation software
My company uses modeling software that takes between 10-12 hours to complete a full simulation run. After it finishes running, data can be collected and stored in our database. Our goal is to be able to perform some machine learning on this data. However, in order to get enough data for this, we are going to need to run this modeling software at least a few hundred times.

This is where Azure, I hope, comes in. Is it reasonable to rent several VMs from Azure, download our modeling software, and then let these VMs run our modes as many times as they can?

We would want to be able to save the state of our VMs after we have downloaded and installed our modeling software. This would allow us the ability to start and pause the use of the VMs without having to re-download the modeling software every time. Although after that, as long as we could export the results to our local database, we would have no need to continuously back up the VMs.

Given all of this, do you think that using multiple VMs through azure is a good fit for my company? If so, do you think configuring a Recovery Services vault for multiple VMs would be the correct method for saving the state of my VMs after the software has been installed? (based on articles https://learn.microsoft.com/en-us/azure/backup/backup-azure-vms-first-look-arm and https://learn.microsoft.com/en-us/azure/backup/backup-azure-arm-vms-prepare)

Thank you for any advice or insights you are able to give.

答:
Couple of things:

Provision a VM, setup your default environment, then create an image of the VM to allow you to provision additional VMs using that source image. Ref: https://learn.microsoft.com/en-us/azure/virtual-machines/windows/capture-image-resource

When you stop the VM you no longer pay for the VM (high cost) but you do pay storage costs for the disks (low cost).

You can automate VM startup and shutdown based on your work load.
https://learn.microsoft.com/en-us/azure/automation/automation-solution-vm-management

You can purchase "Reserved Virtual Machine Instances" but Pay As You Go maybe a better fit = Applications with short-term, spiky, or unpredictable workloads.
https://azure.microsoft.com/en-gb/pricing/details/virtual-machines/windows/

Recovery Services is a backup service to restore previous file states. https://learn.microsoft.com/en-us/azure/backup/backup-azure-recovery-services-vault-overview

Azure is an incredible environment (AWS as well to be fair) but to get the most out of it, architect your solutions for PaaS resources to gain the most benefits. Serverless Function Apps cost pennies for example. Hope that helps. Scott


问:
Moving a forked Github repo: No settings tab
I have a forked repo MyProject_Fork in our organization MyNewOrg.  That repo has branches that I need to maintain so I do not want to delete it.

I want to move the parent repo MyProject from the original org MyOldOrg into MyNewOrg.  I am ok moving MyProject_Fork to a new location or renaming but there is no settings tab for me to move it or change the name.

How do I move MyProject into MyNewOrg without losing the content on other branches from MyProjectFork?

答:
You seem to lack the permissions in your organization.
Get the permissions, then the settings tab should appear.</p>


问:
z-index between two absolutely positioned columns?
I have a two-column layout with two 'absolute' positioned divs.

```<code>    #left {
        position: absolute;
        top: 0;
        left: 0;
        z-index: 0;
    }

    #right {
        position: absolute;
        top: 0;
        left: 0
        z-index: 0;
    }
</code>```

In each column I have images and would like them to be able to overlap one another in differing configurations with z-index. Using wordpress, #left is populated with posts from one category then subsequently, #right is populated.

Is it possible for an image from #left to be positioned above an image in #right but not all? In essence - can the z-indexes between two separate divs be relative to one another?

I have assigned z-index for images in #left higher than that of #right, but images in #right are always on top. I assume it is something to do with the fact that #left appears first in the code?

答:
if it's an option for the divs to be position:relative then something like this could work

http://jsfiddle.net/pxfunc/ZRCke/

HTML:

```<code><div id="left">
    <img id="l1" src="http://placehold.it/300x200/f00" />
    <img id="l2" src="http://placehold.it/80x150/f00" />
    <img id="l3" src="http://placehold.it/150x100/f00" />
</div>
<div id="right">
    <img id="r1" src="http://placehold.it/250/00f" />
    <img id="r2" src="http://placehold.it/250x150/00f" />
</div>
</code>```

CSS:

```<code>#left {position: relative;width:50%;}
#right {position: relative;margin-left:50%;width:50%;}
div img {position: absolute;}

#l1 {top: 50px;right: -50px;z-index:10}
#l2 {top: 300px;right: -10px;z-index:30}
#l3 {top: 500px;right: 20px;z-index:50}

#r1 {top:100px;left:-20px;z-index:20}
#r2 {top:400px;left:-30px;z-index:40}
</code>```

if not I'd have to go with @SnakeFaust's answer

Body:
I have a two-column layout with two 'absolute' positioned divs.

    #left {
        position: absolute;
        top: 0;
        left: 0;
        z-index: 0;
    }

    #right {
        position: absolute;
        top: 0;
        left: 0
        z-index: 0;
    }

In each column I have images and would like them to be able to overlap one another in differing configurations with z-index. Using wordpress, #left is populated with posts from one category then subsequently, #right is populated.

Is it possible for an image from #left to be positioned above an image in #right but not all? In essence - can the z-indexes between two separate divs be relative to one another?

I have assigned z-index for images in #left higher than that of #right, but images in #right are always on top. I assume it is something to do with the fact that #left appears first in the code?

Body:
if it's an option for the divs to be position:relative then something like this could work

http://jsfiddle.net/pxfunc/ZRCke/

HTML:

<div id="left">
    <img id="l1" src="http://placehold.it/300x200/f00" />
    <img id="l2" src="http://placehold.it/80x150/f00" />
    <img id="l3" src="http://placehold.it/150x100/f00" />
</div>
<div id="right">
    <img id="r1" src="http://placehold.it/250/00f" />
    <img id="r2" src="http://placehold.it/250x150/00f" />
</div>

CSS:

#left {position: relative;width:50%;}
#right {position: relative;margin-left:50%;width:50%;}
div img {position: absolute;}

#l1 {top: 50px;right: -50px;z-index:10}
#l2 {top: 300px;right: -10px;z-index:30}
#l3 {top: 500px;right: 20px;z-index:50}

#r1 {top:100px;left:-20px;z-index:20}
#r2 {top:400px;left:-30px;z-index:40}

if not I'd have to go with @SnakeFaust's answer


问:
How to clone a single specific file from Bitbucket
I have a bitbucket repo with huge sources, but need to edit only one file.
Its taking more time and size to clone to local.
Can some one say the git command to clone a specific file from bitbucket</p>

答:
VonC's answer is great; I'd do that in most situations.

There are ways to get one file from Bitbucket:

```<code>$ curl --user <your_bitbucket_username> -O  https://bitbucket.org/<your_bitbucket_username>/<repo_name>/<filename>
</code>```

You'll be able to edit the file, but it will be outside the context of .git, which doesn't seem to support your end goal of updating the repo.

Another option that still lets you clone the repo locally (for bigger edits, stuff you'd like to do with a text editor) is to clone it with less history:

```<code>$ git clone --depth=<a low number> <your_repo_url>
</code>```

This can reduce the size of your total Git repo by a fraction of the total.

Checking man git-clone for more options, such as the --shallow* commands.

Body:
VonC's answer is great; I'd do that in most situations.

There are ways to get one file from Bitbucket:

$ curl --user <your_bitbucket_username> -O  https://bitbucket.org/<your_bitbucket_username>/<repo_name>/<filename>

You'll be able to edit the file, but it will be outside the context of .git, which doesn't seem to support your end goal of updating the repo.

Another option that still lets you clone the repo locally (for bigger edits, stuff you'd like to do with a text editor) is to clone it with less history:

$ git clone --depth=<a low number> <your_repo_url>

This can reduce the size of your total Git repo by a fraction of the total.

Checking man git-clone for more options, such as the --shallow* commands.