问:
TableName (Contains / Regex) When Creating An Entity - Entity Framework - Table Prefix
I'm trying to create an EF model based on an existing MySQL Database.
Upon creating an entity, I map it using:

[Table("databaseName.tableName")] or :

modelBuilder.Entity<Lang>().ToTable("tableName") in OnModelCreating.

The issue I have is that the table names could have an unexpected prefix.
What I want to do is, without knowing the prefix, search for any table in the database that:

(Something like)EndsWith("tableName") use it, or:

which name matches a Regex.

Is this doable? The alternative would be to ask the user for the TablePrefix specific to his/her database and work with it (modelBuilder.Entity<Lang>().ToTable(prefix + "tableName") but that would be quite inconvenient. Since the prefix is the only thing that can change from database to an other, it would be really helpful to be able to detect tables by their name.

答: You can't query the database in OnModelCreating, but you can use the Connection String to open an ADO.NET Connection to the database and run a query to retrieve the table names and construct a mapping between the Entity types and the table names.</p>


来源: stackexchange

问:
Why is multiprocessing module not producing the desired result?

```<code>import multiprocessing as mp
import os

def cube(num):
    print(os.getpid())
    print("Cube is {}".format(num*num*num))

def square(num):
    print(os.getpid())
    print("Square is {}".format(num*num))

if __name__ == "__main__":
    p1 = mp.Process(target = cube, args = (3,))
    p2 = mp.Process(target = square, args = (4,))
    p1.start()
    p2.start()
    p1.join()
    p2.join()
    print("Done")
</code>```

I was using the multiprocessing module, but I am not able to print any output from a function using that.

I even tried flushing the stdout using the sys module.

答:
Q : "Why is multiprocessing module not producing the desired result?"

Why?

Because it crashes.

The MWE/MCVE-representation of the problem has a wrong code. It crashes & it has nothing to do with the sys.stdout.flush() :

```<code>>>> cube(  4 )
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in cube
NameError: global name 'os' is not defined
</code>```

Solution :

```<code>>>> import os   # be it in the __main__ or in the def()-ed functions...

>>> cube(  4 )
14165
Cube is 64
</code>```

and your mp.Process()-based replicas of the python-process instances will stop crashing too.

MCVE that works :

```<code>(base) Fri May 29 14:29:33 $ conda activate py3
(py3) Fri May 29 14:34:55 $ python StackOverflow_mp.py
This is ____6745::__main__
This is ____6746::PID
This is ____6747::PID
Cube(__3) is _______27.
Square(__4) is _______16.
Done.
Works.
Q.E.D.
</code>```

```<code>import multiprocessing as mp
import os
import sys
import time

def cube( num ):
    print( "This is {0:_>8d}::PID".format( os.getpid() ) )
    print( "Cube({0:_>3d}) is {1:_>9d}.".format( num, num*num*num ) )
    sys.stdout.flush()

def square( num ):
    print( "This is {0:_>8d}::PID".format( os.getpid() ) )
    print( "Square({0:_>3d}) is {1:_>9d}.".format( num, num*num ) )
    sys.stdout.flush()

if __name__ == "__main__":
    print( "This is {0:_>8d}::__main__".format( os.getpid() ) )
    p1 = mp.Process( target = cube,   args = (3, ) )
    p2 = mp.Process( target = square, args = (4, ) )
    p1.start()
    p2.start()
    p1.join()
    p2.join()

    time.sleep( 1 )

    print( "Done.\nWorks.\nQ.E.D." )
</code>```

I copied and pasted your exact code. But I still didn't get the output from the called functions using the multiprocessing libraries
– Kartikeya Agarwal 47 mins ago

So,

- I opened a new Terminal process,

- I copied the conda activate py3 command and

- I hit Enter to let it run, so as to make python3 ecosystem go live.

- I re-launched the proof-of-solution again python StackOverflow_mp.py and

- I hit Enter to let it run

- I saw it working the very same way as it worked last time.

- I doubt the problem is on the provided twice (re)-validated proof-of-solution side, is it?

Q.E.D.

```<code>(py3) Fri May 29 19:53:58 $ python StackOverflow_mp.py
This is ___27202::__main__
This is ___27203::PID
Cube(__3) is _______27.
This is ___27204::PID
Square(__4) is _______16.
Done
</code>```

ContentLicense: CC BY-SA 4.0

Body:
import multiprocessing as mp
import os

def cube(num):
    print(os.getpid())
    print("Cube is {}".format(num*num*num))

def square(num):
    print(os.getpid())
    print("Square is {}".format(num*num))

if __name__ == "__main__":
    p1 = mp.Process(target = cube, args = (3,))
    p2 = mp.Process(target = square, args = (4,))
    p1.start()
    p2.start()
    p1.join()
    p2.join()
    print("Done")

I was using the multiprocessing module, but I am not able to print any output from a function using that.

I even tried flushing the stdout using the sys module.

Body:
Q : "Why is multiprocessing module not producing the desired result?"

Why?

Because it crashes.

The MWE/MCVE-representation of the problem has a wrong code. It crashes & it has nothing to do with the sys.stdout.flush() :

>>> cube(  4 )
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in cube
NameError: global name 'os' is not defined

Solution :

>>> import os   # be it in the __main__ or in the def()-ed functions...

>>> cube(  4 )
14165
Cube is 64

and your mp.Process()-based replicas of the python-process instances will stop crashing too.

MCVE that works :

(base) Fri May 29 14:29:33 $ conda activate py3
(py3) Fri May 29 14:34:55 $ python StackOverflow_mp.py
This is ____6745::__main__
This is ____6746::PID
This is ____6747::PID
Cube(__3) is _______27.
Square(__4) is _______16.
Done.
Works.
Q.E.D.

import multiprocessing as mp
import os
import sys
import time

def cube( num ):
    print( "This is {0:_>8d}::PID".format( os.getpid() ) )
    print( "Cube({0:_>3d}) is {1:_>9d}.".format( num, num*num*num ) )
    sys.stdout.flush()

def square( num ):
    print( "This is {0:_>8d}::PID".format( os.getpid() ) )
    print( "Square({0:_>3d}) is {1:_>9d}.".format( num, num*num ) )
    sys.stdout.flush()

if __name__ == "__main__":
    print( "This is {0:_>8d}::__main__".format( os.getpid() ) )
    p1 = mp.Process( target = cube,   args = (3, ) )
    p2 = mp.Process( target = square, args = (4, ) )
    p1.start()
    p2.start()
    p1.join()
    p2.join()

    time.sleep( 1 )

    print( "Done.\nWorks.\nQ.E.D." )

I copied and pasted your exact code. But I still didn't get the output from the called functions using the multiprocessing libraries
– Kartikeya Agarwal 47 mins ago

So,

- I opened a new Terminal process,

- I copied the conda activate py3 command and

- I hit Enter to let it run, so as to make python3 ecosystem go live.

- I re-launched the proof-of-solution again python StackOverflow_mp.py and

- I hit Enter to let it run

- I saw it working the very same way as it worked last time.

- I doubt the problem is on the provided twice (re)-validated proof-of-solution side, is it?

Q.E.D.

(py3) Fri May 29 19:53:58 $ python StackOverflow_mp.py
This is ___27202::__main__
This is ___27203::PID
Cube(__3) is _______27.
This is ___27204::PID
Square(__4) is _______16.
Done


问:
Move all files in a folder to a new location if the same existing Folder name exists at remote location
Looking for a bash script:
Here's the situation:
I have 1000's folders and subfolders on my Backup Directory Drive
lets say.....

/backup

/backup/folderA

/backup/folderA/FolderAA

/backup/folderB

/backup/folderB/FolderBB

I have Dozens of similar folders in a secondary location (with files in them) and the Folder names will match one of the folders or subfolders in the main backup drive.

I would like to move all contents of specific extension types from my secondary location $FolderName to the Backup location + matching subfolder ONLY if the $FolderName matches exactly and remove the folders from my secondary location!

If there is no corrosponding folder or subfolder in the backup location then leave the source folders & files alone.

looking forward to getting some help/guidance.

Mike

Additional info requested.Expected input and ouput

Lets say i have the following:
Backup Folder

```<code>/backup/test/file.bak
</code>```

And for my secondary folder location:

```<code>/secondarylocation/mike/test/hello/john.bak
/secondarylocation/mike/test/hello/backup.zip
</code>```

i would like this as the end result

```<code>/backup/test/file.bak
/backup/test/john.bak
/backup/test/backup.zip
</code>```

and /secondarylocation/mike/test *and sub folders and files removed

答:
run this script with quoted folders and file types:

```<code>./merge.sh "backup" "secondarylocation/mike" "*.zip" "*.bak"
</code>```

replace -iname with -name if you want to search for suffix case sensitive

replace mv -fv with mv -nv when you don't want to overwrite duplicate file names

add -mindepth 1 to last find if you want to keep empty folder test

merge.sh

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

# read folders from positional parameters
[ -d "$1" ] && targetf="$1" && shift
[ -d "$1" ] && sourcef="$1" && shift

if [ -z "$targetf" ] || [ -z "$sourcef" ]
  then
    echo -e "usage: ./merge.sh <targetfolder> <sourcefolder> [PATTERN]..."
    exit 1
fi

# add prefix -iname for each pattern
while [ ${pattern:-1} -le $# ]
  do
    set -- "$@" "-iname \"$1\""
    shift
    pattern=$((${pattern:-1}+1))
done

# concatenate all prefix+patterns with -o and wrap in parentheses ()
if (( $# > 1 ))
  then
    pattern="\( $1"
    while (( $# > 1 ))
      do
        pattern="$pattern -o $2"
        shift
    done
    pattern="$pattern \)"
  else
    pattern="$1"
fi

# move files from searchf to destf
find "$targetf" -mindepth 1 -type d -print0 | sort -z | while IFS=$'\0' read -r -d $'\0' destf
  do
    find "$sourcef" -mindepth 1 -type d -name "${destf##*/}" -print0 | sort -z | while IFS=$'\0' read -r -d $'\0' searchf
      do
        if (( $# ))
          then
            # search with pattern
            eval find "\"$searchf\"" -depth -type f "$pattern" -exec mv -fv {} "\"$destf\"" \\\;
          else
            # all files
            find "$searchf" -depth -type f -exec mv -fv {} "$destf" \;
        fi
        # delete empty folders
        find "$searchf" -depth -type d -exec rmdir --ignore-fail-on-non-empty {} +
    done
done

exit 0
</code>```

this will merge hello into test (earn the fruits and cut the tree)

Body:
Looking for a bash script:
Here's the situation:
I have 1000's folders and subfolders on my Backup Directory Drive
lets say.....

/backup

/backup/folderA

/backup/folderA/FolderAA

/backup/folderB

/backup/folderB/FolderBB

I have Dozens of similar folders in a secondary location (with files in them) and the Folder names will match one of the folders or subfolders in the main backup drive.

I would like to move all contents of specific extension types from my secondary location $FolderName to the Backup location + matching subfolder ONLY if the $FolderName matches exactly and remove the folders from my secondary location!

If there is no corrosponding folder or subfolder in the backup location then leave the source folders & files alone.

looking forward to getting some help/guidance.

Mike

Additional info requested.Expected input and ouput

Lets say i have the following:
Backup Folder

/backup/test/file.bak

And for my secondary folder location:

/secondarylocation/mike/test/hello/john.bak
/secondarylocation/mike/test/hello/backup.zip

i would like this as the end result

/backup/test/file.bak
/backup/test/john.bak
/backup/test/backup.zip

and /secondarylocation/mike/test *and sub folders and files removed

Body:
run this script with quoted folders and file types:

./merge.sh "backup" "secondarylocation/mike" "*.zip" "*.bak"

replace -iname with -name if you want to search for suffix case sensitive

replace mv -fv with mv -nv when you don't want to overwrite duplicate file names

add -mindepth 1 to last find if you want to keep empty folder test

merge.sh

#!/bin/bash

# read folders from positional parameters
[ -d "$1" ] && targetf="$1" && shift
[ -d "$1" ] && sourcef="$1" && shift

if [ -z "$targetf" ] || [ -z "$sourcef" ]
  then
    echo -e "usage: ./merge.sh <targetfolder> <sourcefolder> [PATTERN]..."
    exit 1
fi

# add prefix -iname for each pattern
while [ ${pattern:-1} -le $# ]
  do
    set -- "$@" "-iname \"$1\""
    shift
    pattern=$((${pattern:-1}+1))
done

# concatenate all prefix+patterns with -o and wrap in parentheses ()
if (( $# > 1 ))
  then
    pattern="\( $1"
    while (( $# > 1 ))
      do
        pattern="$pattern -o $2"
        shift
    done
    pattern="$pattern \)"
  else
    pattern="$1"
fi

# move files from searchf to destf
find "$targetf" -mindepth 1 -type d -print0 | sort -z | while IFS=$'\0' read -r -d $'\0' destf
  do
    find "$sourcef" -mindepth 1 -type d -name "${destf##*/}" -print0 | sort -z | while IFS=$'\0' read -r -d $'\0' searchf
      do
        if (( $# ))
          then
            # search with pattern
            eval find "\"$searchf\"" -depth -type f "$pattern" -exec mv -fv {} "\"$destf\"" \\\;
          else
            # all files
            find "$searchf" -depth -type f -exec mv -fv {} "$destf" \;
        fi
        # delete empty folders
        find "$searchf" -depth -type d -exec rmdir --ignore-fail-on-non-empty {} +
    done
done

exit 0

this will merge hello into test (earn the fruits and cut the tree)


问:
Is there any way to add namespaces to all html tags using ASP?
Is there any way to add namespace xmlns="http://www.w3.org/1999/xhtml" to all html tags either using ASP function / RegExp / javascript? (this is something like adding a attribute to the html tags)

For Example:

Below is the body of textarea:

```<code><p>Welcome to the StackOverFlow site.</p>
<p xmlns="http://www.w3.org/1999/xhtml">Please <a href="http://stackoverflow.com">click here</a> for more info.</p>
</code>```

The body contains two html tags,
 & .

Here one
 tag already has namespace xmlns="http://www.w3.org/1999/xhtml"

Now I need to add namespace to other tags.

I tried a lot to resolve this on ASP page but no luck.

Please help me on this.

答:
Here's a solution that uses only JavaScript regexes:

```<code>result = subject.replace(
    /(<\w+)((?:\s+(?!xmlns\b)\w+\s*=\s*(?:"[^"]*"|'[^']*'|[^\s>]+))*\s*\/?>)/g,
    '$1 xmlns="http://www.w3.org/1999/xhtml"$2'
);
</code>```

The regex matches anything that looks like an opening tag (<abc>) or self-closing tag (<xyz />).  The tag may contain any number of attributes, unless one of those attributes is named "xmlns".  The attribute values may be double-quoted, single-quoted, or not quoted.  If a tag is matched, the "xmlns" attribute will be added immediately after the tag name.

Be aware that there's a lot this solution doesn't handle, like "valueless" attributes (e.g. nowrap), or tag- or attribute names qualified with namespaces (e.g. <abc:xyz>).  Regexes really don't work very well on HTML (which is a shame, since that's what most people seem to want to use them on).  Any regex-vs-HTML solution has to start with an exhaustive list of simplifying assumptions, like "no

ContentLicense: CC BY-SA 3.0

Body:
Is there any way to add namespace xmlns="http://www.w3.org/1999/xhtml" to all html tags either using ASP function / RegExp / javascript? (this is something like adding a attribute to the html tags)

For Example:

Below is the body of textarea:

Welcome to the StackOverFlow site.

Please click here for more info.

The body contains two html tags,
 & .

Here one
 tag already has namespace xmlns="http://www.w3.org/1999/xhtml"

Now I need to add namespace to other tags.

I tried a lot to resolve this on ASP page but no luck.

Please help me on this.

Body:
Here's a solution that uses only JavaScript regexes:

result = subject.replace(
    /(<\w+)((?:\s+(?!xmlns\b)\w+\s*=\s*(?:"[^"]*"|'[^']*'|[^\s>]+))*\s*\/?>)/g,
    '$1 xmlns="http://www.w3.org/1999/xhtml"$2'
);

The regex matches anything that looks like an opening tag (<abc>) or self-closing tag (<xyz />).  The tag may contain any number of attributes, unless one of those attributes is named "xmlns".  The attribute values may be double-quoted, single-quoted, or not quoted.  If a tag is matched, the "xmlns" attribute will be added immediately after the tag name.

Be aware that there's a lot this solution doesn't handle, like "valueless" attributes (e.g. nowrap), or tag- or attribute names qualified with namespaces (e.g. <abc:xyz>).  Regexes really don't work very well on HTML (which is a shame, since that's what most people seem to want to use them on).  Any regex-vs-HTML solution has to start with an exhaustive list of simplifying assumptions, like "no <script> tags" or "don't worry about CDATA sections or SGML comments".


问:
pandas merge with conditionnal aggregation
I want to merge two dataframe based on a composed key. The second dataframe have duplicated rows considering the key. Note that the key is not unique in the first dataframe too because there is in fact other many columns in real data. I need to merge with aggregated(product) values  on second dataframe but with a condition on dates. The rows to aggregate should have a date lower than the date of the row from the first data frame.

Here is an example :

```<code>df1 = pd.DataFrame({
    'Code': ['Code1', 'Code1', 'Code1', 'Code2', 'Code3', 'Code4'],
    'SG': ['SG1', 'SG1', 'SG1', 'SG2', 'SG3', 'SG3'],
    'Date':
    ['2020-02-01', '2020-02-01', '2020-03-01', '2020-01-01', '2020-02-01', '2020-02-01']
})

print(df1)
    Code   SG        Date
0  Code1  SG1  2020-02-01
1  Code1  SG1  2020-02-01
2  Code1  SG1  2020-03-01
3  Code2  SG2  2020-01-01
4  Code3  SG3  2020-02-01
5  Code4  SG3  2020-02-01

df2 = pd.DataFrame({
    'Code': ['Code1', 'Code1', 'Code2', 'Code3'],
    'SG': ['SG1', 'SG1', 'SG2', 'SG3'],
    'Date': ["2019-01-01", "2020-02-25", "2020-01-13", "2020-01-25"],
    'Coef': [0.5, 0.7, 0.3, 0.3]
})

print(df2)

    Code   SG        Date  Coef
0  Code1  SG1  2019-01-01   0.5
1  Code1  SG1  2020-02-25   0.7
2  Code2  SG2  2020-01-13   0.3
3  Code3  SG3  2020-01-25   0.3
</code>```

I want the following result : Line two has aggregated coef 0.5x0.7 =0.35 as all df2.Date for corresponding key are lower than df1.Date

```<code>    Code   SG        Date  Coef
0  Code1  SG1  2020-02-01  0.50
1  Code1  SG1  2020-02-01  0.50
2  Code1  SG1  2020-03-01  0.35
3  Code2  SG2  2020-01-01   NaN
4  Code3  SG3  2020-02-01  0.30
5  Code4  SG3  2020-02-01   NaN
</code>```

Thank you for help.

答:
OK, I finally got it!

Merging (LEFT JOIN) by Code and SG

```<code>df_group = pd.merge(df1,df2, on=['Code','SG'], how='left', suffixes=('','_result'))
</code>```

Creating a filter for lower dates

```<code>df_group['lower_date_mask'] = df_group['Date_result'] <= df_group['Date']
</code>```

Filtering the Coef column with NaNs.

```<code>df_group.loc[df_group['lower_date_mask'] == False,'lower_date_mask'] = np.nan
df_group['Coef'] = df_group['Coef'] * df_group['lower_date_mask']
</code>```

We assign infinite to True values here just to avoid Pandas bug when executing the .prod() function with NaNs

```<code>df_group.loc[df_group['lower_date_mask'] == 1.0,'lower_date_mask'] = np.inf
</code>```

Github issue about the aggregation functions with nan: https://github.com/pandas-dev/pandas/issues/20824

Aggregating by .prod()

```<code>df_group = df_group.groupby(['Code','SG','Date']).prod()
</code>```

Creating final dataframe

```<code>df_group.reset_index(inplace = True)
df_group.loc[df_group['lower_date_mask'] == 1.0,'Coef'] = np.nan
df_group.drop(columns = ['lower_date_mask'],inplace = True)
</code>```

Final output

```<code>    Code    SG  Date    Coef
    0   Code1   SG1 2020-02-01  0.50
    1   Code1   SG1 2020-03-01  0.35
    2   Code2   SG2 2020-01-01  NaN
    3   Code3   SG3 2020-02-01  0.30
    4   Code4   SG3 2020-02-01  NaN
</code>```

It is worth saying that you can achieve this with the .apply() function, however, this would slow you down if your DataFrame grow bigger.

Hope I could help! It took me literally two hours to think this code through!

EDIT:

As mentioned by @codesensei, his database has other columns that make the combination ['Code','SG','Date'] not unique. In that case, there are two possible ways to deal with that. First, if there are other columns in df1 or df2 that make the combination unique, just add them in the grouping, like the following:

```<code>df_group = df_group.groupby(['Code','SG','Date','column_of_interest']).prod()
</code>```

Second, if it's easier to make the combination unique by some sort of ID, let's say the index of df1, you can do:

```<code>df1.reset_index(inplace = True)
# merge dataframes and follow the other steps as stated earlier in this answer
df_group = df_group.groupby(['Code','SG','Date','index']).prod()
</code>```

If you want, you can rename the 'index' to something else, just to make it more explicit.

Hope I could help!

Body:
I want to merge two dataframe based on a composed key. The second dataframe have duplicated rows considering the key. Note that the key is not unique in the first dataframe too because there is in fact other many columns in real data. I need to merge with aggregated(product) values  on second dataframe but with a condition on dates. The rows to aggregate should have a date lower than the date of the row from the first data frame.

Here is an example :

df1 = pd.DataFrame({
    'Code': ['Code1', 'Code1', 'Code1', 'Code2', 'Code3', 'Code4'],
    'SG': ['SG1', 'SG1', 'SG1', 'SG2', 'SG3', 'SG3'],
    'Date':
    ['2020-02-01', '2020-02-01', '2020-03-01', '2020-01-01', '2020-02-01', '2020-02-01']
})

print(df1)
    Code   SG        Date
0  Code1  SG1  2020-02-01
1  Code1  SG1  2020-02-01
2  Code1  SG1  2020-03-01
3  Code2  SG2  2020-01-01
4  Code3  SG3  2020-02-01
5  Code4  SG3  2020-02-01

df2 = pd.DataFrame({
    'Code': ['Code1', 'Code1', 'Code2', 'Code3'],
    'SG': ['SG1', 'SG1', 'SG2', 'SG3'],
    'Date': ["2019-01-01", "2020-02-25", "2020-01-13", "2020-01-25"],
    'Coef': [0.5, 0.7, 0.3, 0.3]
})

print(df2)

    Code   SG        Date  Coef
0  Code1  SG1  2019-01-01   0.5
1  Code1  SG1  2020-02-25   0.7
2  Code2  SG2  2020-01-13   0.3
3  Code3  SG3  2020-01-25   0.3

I want the following result : Line two has aggregated coef 0.5x0.7 =0.35 as all df2.Date for corresponding key are lower than df1.Date

    Code   SG        Date  Coef
0  Code1  SG1  2020-02-01  0.50
1  Code1  SG1  2020-02-01  0.50
2  Code1  SG1  2020-03-01  0.35
3  Code2  SG2  2020-01-01   NaN
4  Code3  SG3  2020-02-01  0.30
5  Code4  SG3  2020-02-01   NaN

Thank you for help.

Body:
OK, I finally got it!

Merging (LEFT JOIN) by Code and SG

df_group = pd.merge(df1,df2, on=['Code','SG'], how='left', suffixes=('','_result'))

Creating a filter for lower dates

df_group['lower_date_mask'] = df_group['Date_result'] <= df_group['Date']

Filtering the Coef column with NaNs.

df_group.loc[df_group['lower_date_mask'] == False,'lower_date_mask'] = np.nan
df_group['Coef'] = df_group['Coef'] * df_group['lower_date_mask']

We assign infinite to True values here just to avoid Pandas bug when executing the .prod() function with NaNs

df_group.loc[df_group['lower_date_mask'] == 1.0,'lower_date_mask'] = np.inf

Github issue about the aggregation functions with nan: https://github.com/pandas-dev/pandas/issues/20824

Aggregating by .prod()

df_group = df_group.groupby(['Code','SG','Date']).prod()

Creating final dataframe

df_group.reset_index(inplace = True)
df_group.loc[df_group['lower_date_mask'] == 1.0,'Coef'] = np.nan
df_group.drop(columns = ['lower_date_mask'],inplace = True)

Final output

    Code    SG  Date    Coef
    0   Code1   SG1 2020-02-01  0.50
    1   Code1   SG1 2020-03-01  0.35
    2   Code2   SG2 2020-01-01  NaN
    3   Code3   SG3 2020-02-01  0.30
    4   Code4   SG3 2020-02-01  NaN

It is worth saying that you can achieve this with the .apply() function, however, this would slow you down if your DataFrame grow bigger.

Hope I could help! It took me literally two hours to think this code through!

EDIT:

As mentioned by @codesensei, his database has other columns that make the combination ['Code','SG','Date'] not unique. In that case, there are two possible ways to deal with that. First, if there are other columns in df1 or df2 that make the combination unique, just add them in the grouping, like the following:

df_group = df_group.groupby(['Code','SG','Date','column_of_interest']).prod()

Second, if it's easier to make the combination unique by some sort of ID, let's say the index of df1, you can do:

df1.reset_index(inplace = True)
# merge dataframes and follow the other steps as stated earlier in this answer
df_group = df_group.groupby(['Code','SG','Date','index']).prod()

If you want, you can rename the 'index' to something else, just to make it more explicit.

Hope I could help!


问:
How to make a countdown using PHP
Im creating a website for my brothers wedding. And so far all is going well. However, he wants a countdown to the wedding on the homepage;

Time left until the wedding: X months, X days, X hours.

I would preferebly like to do this using php, but would be open to other suggestions.

if you can help me with ideas for the coding, or just point me to relevant material, that would be useful.

The wedding is on Saturday 30th July.

答:
```<code>$wedding = strtotime("2011-07-01 12:00:00+0400"); // or whenever the wedding is
$secondsLeft = $wedding - time();
$days = floor($secondsLeft / 60*60*24);
$hours = floor(($secondsLeft - $days*60*60*24) / 60*60);
echo "$days days and $hours hours left";
</code>```

Code top by user Neil E. Pearson didn´t work, he forgot to write there the brackets (), working solution is:

```<code>$wedding = strtotime("2011-07-01 12:00:00+0400"); // or whenever the wedding is
$secondsLeft = $wedding - time();
$days = floor($secondsLeft / (60*60*24)); // here the brackets
$hours = floor(($secondsLeft - ($days*60*60*24)) / (60*60)); // and here too
echo "$days days and $hours hours left";
</code>```

ContentLicense: CC BY-SA 2.5

Title: How to make a countdown using PHP

Body:
$wedding = strtotime("2011-07-01 12:00:00+0400"); // or whenever the wedding is
$secondsLeft = $wedding - time();
$days = floor($secondsLeft / 60*60*24);
$hours = floor(($secondsLeft - $days*60*60*24) / 60*60);
echo "$days days and $hours hours left";

Code top by user Neil E. Pearson didn´t work, he forgot to write there the brackets (), working solution is:

$wedding = strtotime("2011-07-01 12:00:00+0400"); // or whenever the wedding is
$secondsLeft = $wedding - time();
$days = floor($secondsLeft / (60*60*24)); // here the brackets
$hours = floor(($secondsLeft - ($days*60*60*24)) / (60*60)); // and here too
echo "$days days and $hours hours left";


问:
JavaScript function to generate random instances of Object
I am trying to create an array of nine random words. Each word should have a color key value. Out of the nine words 3 words should have the color 'red', 3 words should have the color 'blue', and one word shoule have the color 'black'. The color needs to be assigned to the word randomly (each time the array is produced the positioning of the each color should change randomly).

My code so far produces and array of words each randomly assigned a color however with no limit - for example I may get 2 black 3 red and 4 blue. Then the next time 0 black 4 red and 5 blue. I need to produce 4 red 4 blue and 1 black every time (randomly positioned).

I thought that a counter would be useful however currently is not being used.

Any help would be great - I am new to coding so be critical!

Here is my code:

```<code>//Globals
const wordList = [..... ***remov
ed giant list of words from post***

];
const colorList = ['red', 'blue', 'black']
let randomWordNum = Math.floor(Math.random()*(wordList.length))
let randomColorNum = Math.floor(Math.random()*(colorList.length))
let coloredWords = [];
let redCounter = 0;
let blueCounter = 0;
let blackCounter = 0;

//Square function
//assigns color and word value to object key
//pushes object to new array 'words'
const createSquare = () => {
let randomWordNum = Math.floor(Math.random()*(wordList.length))
let randomColor = colorList[Math.floor(Math.random()*(colorList.length))]
if (randomColor === 'red') {
  redCounter++
} else if (randomColor === 'blue') {
  blueCounter++
} else if (randomColor === 'black') {
  blackCounter++
}
  var square = {
    color: randomColor,
    word: wordList[randomWordNum],
  }

coloredWords.push(square)
console.log(square)
}

//Loops through above function until the array is x values
const wordArr = () => {
while (coloredWords.length < 9 ){
  createSquare()
}
}

wordArr()
console.log(coloredWords)

</code>```

答:
You can first create an array of all colors 3 times (eg ['red', 'blue', 'black', 'red', 'blue', 'black', 'red', 'blue', 'black']), then shuffle it, and then on each iteration, select and remove an element from the array:

//Globals
const wordList = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'];
const colorList = ['red', 'blue', 'black']
const coloredWords = [];
const COUNT_FOR_ONE_COLOR = 3;

const randomColorsArr = Array.from(
  { length: COUNT_FOR_ONE_COLOR * colorList.length },
  (_, i) => colorList[i % colorList.length]
);
// Shuffle:
// https://stackoverflow.com/a/12646864
function shuffleArray(array) {
  for (let i = array.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [array[i], array[j]] = [array[j], array[i]];
  }
}
shuffleArray(randomColorsArr);

const createSquare = () => {
  const randomWordNum = Math.floor(Math.random() * (wordList.length))
  const randomColor = randomColorsArr.pop();
  const square = {
    color: randomColor,
    word: wordList[randomWordNum],
  }

  coloredWords.push(square)
};

for (let i = 0; i < 9; i++) {
  createSquare();
}
console.log(coloredWords)```

Body:
I am trying to create an array of nine random words. Each word should have a color key value. Out of the nine words 3 words should have the color 'red', 3 words should have the color 'blue', and one word shoule have the color 'black'. The color needs to be assigned to the word randomly (each time the array is produced the positioning of the each color should change randomly).

My code so far produces and array of words each randomly assigned a color however with no limit - for example I may get 2 black 3 red and 4 blue. Then the next time 0 black 4 red and 5 blue. I need to produce 4 red 4 blue and 1 black every time (randomly positioned).

I thought that a counter would be useful however currently is not being used.

Any help would be great - I am new to coding so be critical!

Here is my code:

//Globals
const wordList = [..... ***remov
ed giant list of words from post***

];
const colorList = ['red', 'blue', 'black']
let randomWordNum = Math.floor(Math.random()*(wordList.length))
let randomColorNum = Math.floor(Math.random()*(colorList.length))
let coloredWords = [];
let redCounter = 0;
let blueCounter = 0;
let blackCounter = 0;

//Square function
//assigns color and word value to object key
//pushes object to new array 'words'
const createSquare = () => {
let randomWordNum = Math.floor(Math.random()*(wordList.length))
let randomColor = colorList[Math.floor(Math.random()*(colorList.length))]
if (randomColor === 'red') {
  redCounter++
} else if (randomColor === 'blue') {
  blueCounter++
} else if (randomColor === 'black') {
  blackCounter++
}
  var square = {
    color: randomColor,
    word: wordList[randomWordNum],
  }

coloredWords.push(square)
console.log(square)
}

//Loops through above function until the array is x values
const wordArr = () => {
while (coloredWords.length < 9 ){
  createSquare()
}
}

wordArr()
console.log(coloredWords)


问:
Real time point cloud processing and latency
Our project is to integrate Lidar system into virtual reality (unity).
I could achieve that integration with ROS-bridge.
Next step is to process the point cloud data before we send it to unity system.

Lidar sensor velodyne VLP-16

Ubuntu 18.4

IDE: Pycharm (python)

Point cloud processing: python point cloud library with ROS

ros-bridge with unity system

Problem
Without processing, there is only 1 second latency from sensor to unity visualization. But processing point-cloud data in ROS(pycharm) causes significant latency (around 5 seconds).

I am using velodyne drives to convert raw data into pointcloud2 format. In the code for the processing, I subscribe this pointcloud2 message and convert it into PointXYZRGB format to apply pcl libraries.

I first tested this sequence of data-type conversion without applying PCL.

raw data -> publish pointcloud2 message ->subscribe pointcloud2- > pointXYZRGB -> (processing) ->
  pointcloud2 message -> publish it.

Without processing, I get over 5 seconds latency.

I understand that it would be better to receive raw data from sensor without converting into pointcloud2 messages.
But it is very challenging for me to do it in python.
I found one grabber example in c++.
https://medium.com/@yohei.kajiwara/vlp16-c-quick-example-35b9ceea2059

But I am not sure what is the most reliable way.
Please give me an advice on this issue.

Best regards

Seongsu Byeon

答:
If speed is your concern, there's a few things.

Velodyne drivers have the ability to receive the packets & combine into a pointcloud with zerocopy access, using nodelets. ROS nodelets are like nodes, but with less copying, more efficient for big data. Ex velodyne_driver and Ex velodyne_pointcloud. You can call it all through the launch file VLP16_points.launch which demonstrates how to combine nodelets like this. The code is pretty readable, so you could walk through how they setup their code for reference. If you haven't tried this method, and then piping into Unity, this is your minimum baseline. Then the bottleneck is on the unity side.

The fastest you'll get is probably writing a nodelet in C++, using the PCL, handled by the same nodelet manager (as in that last launch file). The best is if you don't need to write any yourself. The pcl_ros package has several transform nodelets; if a combination of those could meet your needs, that would be the most efficient & effortless way. Otherwise, you can still use the <pcl_ros/pointcloud.h> header in your c++ nodelet, and the pcl::PointCloud<T> will be interpreted by ros as a sensor_msgs/PointCloud2 message on both subscriber and publisher. If you need anymore conversions, the pcl_conversion package has a few handy ones.

(This is a bit tangental. If the bottle neck beyond that is the websocket-y interface Ros# uses to communicate with the rosbridge_server, rosbridge_server supports a UDP protocol, which, if on the same machine, should be pretty quick, but Ros# doesn't currently support that or have it on their roadmap, as most of their use-case doesn't come from it running on the same machine.)


问:
discord.py bot hosted on heroku wont go online
I decided to use heroku to run my bot 24/7. I deployed, saw my dyno running, no errors and it was even switched on. I expected the bot to come online because of the deploy but it just stayed offline.

Here is my bot code:

```<code>import discord
import os
import asyncio
import random
from discord.ext import commands, tasks
from itertools import cycle

TOKEN = 'XXXXX'

client = commands.Bot(command_prefix = '/')

client.remove_command('help')

status = cycle(['Helping my Creator!', 'Moderating this server. smh'])

messages = 0

@client.event
async def on_ready():
    change_status.start()
    print('Bot has connected.')

@client.event
async def on_message(message):
    global messages
    messages +-1

    bad_words = [(just a list of bad words)]

    for word in bad_words:
        if message.content.count(word) > 0:
            print('Someone said a bad word')
            await message.channel.purge(limit = 1)
    await client.process_commands(message)

@tasks.loop(minutes = 5)
async def change_status():
    await client.change_presence(activity = discord.Game(next(status)))

@client.command()
async def cheese(ctx):
    responses = ["Here's some Parmesan.:cheese:",
                 "Here's some Pecorino.:cheese:",
                 "Here's some Manchego.:cheese:",
                 "Here's some Grana-Padano.:cheese:",
                 "Here's some Cheddar.:cheese:",
                 "Here's some Gouda.:cheese:",
                 "Here's some Harvati.:cheese:",
                 "Here's some Gruyere.:cheese:",
                 "Here's some Gorgonzola.:cheese:",
                 "Here's some Stilton.:cheese:",
                 "Here's some Roquefort.:cheese:",
                 "Here's some Danish Blue.:cheese:",
                 "Here's some Brie.:cheese:",
                 "Here's some Camembert.:cheese:",
                 "Here's some Double Creme White.:cheese:",
                 "Here's some Cream Cheese.:cheese:",
                 "Here's some Feta.:cheese:",
                 "Here's some Mozzarella.:cheese:",
                 "Here's some Burrata.:cheese:",
                 "Here's some Chevre.:cheese:",
                 "Here's some Goat Brie.:cheese:",
                 "Here's some Blue Goat Cheese.:cheese:"]
    await ctx.send(random.choice(responses))

 @client.command()
 async def userinfo(ctx, member: discord.Member = None):
     member = ctx.author if not member else member

     embed = discord.Embed(colour = member.color, timestamp =
     ctx.message.created_at)

     embed.set_author(name = f"User info - {member}")
     embed.set_thumbnail(url = member.avatar_url)
     embed.set_footer(text = f"Requested by {ctx.author}", icon_url =
     ctx.author.avatar_url)

     embed.add_field(name = "ID:", value = member.id)
     embed.add_field(name = "Guild name:", value = member.display_name)

     embed.add_field(name = "Created at:", value
     member.created_at.strftime("%a, %d %B %Y, %I:%M %p UTC"))
     embed.add_field(name = "Joined at:", value =
     member.joined_at.strftime("%a, %d %B %Y, %I:%M %p UTC"))

     embed.add_field(name = "Bot?", value = member.bot)

     await ctx.send(embed = embed)

client.run(TOKEN)
</code>```

Here is my procfile:

```<code>worker: python3 modbotv4.py
</code>```

My requirements.txt file:

```<code>git+https://github.com/Rapptz/discord.py
dnspython==1.16.0
PyNaCl==1.3.0
async-timeout==3.0.1
</code>```

And my runtime.txt file:

```<code>python-3.8.3
</code>```

If there is anything I should add in any of the files in order to make my bot go online, please tell me.

答:
When run myself, the code you provided throws a few errors

1st being on line 69 and 70, the last @client.command() and async definition are indented by 1 space, but this may just be an error when pasted into stack overflow

```<code>
 @client.command()
 async def userinfo(ctx, member: discord.Member = None):
^
</code>```

2nd being there is a missing equals sign

```<code>embed.add_field(name = "Created at:", value
member.created_at.strftime("%a, %d %B %Y, %I:%M %p UTC"))
</code>```

where it should be

```<code>embed.add_field(name = "Created at:", value =
                                            ^ equals sign
member.created_at.strftime("%a, %d %B %Y, %I:%M %p UTC"))
</code>```

The code then runs fine

Sorry that it took so long

Body:
I decided to use heroku to run my bot 24/7. I deployed, saw my dyno running, no errors and it was even switched on. I expected the bot to come online because of the deploy but it just stayed offline.

Here is my bot code:

import discord
import os
import asyncio
import random
from discord.ext import commands, tasks
from itertools import cycle

TOKEN = 'XXXXX'

client = commands.Bot(command_prefix = '/')

client.remove_command('help')

status = cycle(['Helping my Creator!', 'Moderating this server. smh'])

messages = 0

@client.event
async def on_ready():
    change_status.start()
    print('Bot has connected.')

@client.event
async def on_message(message):
    global messages
    messages +-1

    bad_words = [(just a list of bad words)]

    for word in bad_words:
        if message.content.count(word) > 0:
            print('Someone said a bad word')
            await message.channel.purge(limit = 1)
    await client.process_commands(message)

@tasks.loop(minutes = 5)
async def change_status():
    await client.change_presence(activity = discord.Game(next(status)))

@client.command()
async def cheese(ctx):
    responses = ["Here's some Parmesan.:cheese:",
                 "Here's some Pecorino.:cheese:",
                 "Here's some Manchego.:cheese:",
                 "Here's some Grana-Padano.:cheese:",
                 "Here's some Cheddar.:cheese:",
                 "Here's some Gouda.:cheese:",
                 "Here's some Harvati.:cheese:",
                 "Here's some Gruyere.:cheese:",
                 "Here's some Gorgonzola.:cheese:",
                 "Here's some Stilton.:cheese:",
                 "Here's some Roquefort.:cheese:",
                 "Here's some Danish Blue.:cheese:",
                 "Here's some Brie.:cheese:",
                 "Here's some Camembert.:cheese:",
                 "Here's some Double Creme White.:cheese:",
                 "Here's some Cream Cheese.:cheese:",
                 "Here's some Feta.:cheese:",
                 "Here's some Mozzarella.:cheese:",
                 "Here's some Burrata.:cheese:",
                 "Here's some Chevre.:cheese:",
                 "Here's some Goat Brie.:cheese:",
                 "Here's some Blue Goat Cheese.:cheese:"]
    await ctx.send(random.choice(responses))

 @client.command()
 async def userinfo(ctx, member: discord.Member = None):
     member = ctx.author if not member else member

     embed = discord.Embed(colour = member.color, timestamp =
     ctx.message.created_at)

     embed.set_author(name = f"User info - {member}")
     embed.set_thumbnail(url = member.avatar_url)
     embed.set_footer(text = f"Requested by {ctx.author}", icon_url =
     ctx.author.avatar_url)

     embed.add_field(name = "ID:", value = member.id)
     embed.add_field(name = "Guild name:", value = member.display_name)

     embed.add_field(name = "Created at:", value
     member.created_at.strftime("%a, %d %B %Y, %I:%M %p UTC"))
     embed.add_field(name = "Joined at:", value =
     member.joined_at.strftime("%a, %d %B %Y, %I:%M %p UTC"))

     embed.add_field(name = "Bot?", value = member.bot)

     await ctx.send(embed = embed)

client.run(TOKEN)

Here is my procfile:

worker: python3 modbotv4.py

My requirements.txt file:

git+https://github.com/Rapptz/discord.py
dnspython==1.16.0
PyNaCl==1.3.0
async-timeout==3.0.1

And my runtime.txt file:

python-3.8.3

If there is anything I should add in any of the files in order to make my bot go online, please tell me.

Body:
When run myself, the code you provided throws a few errors

1st being on line 69 and 70, the last @client.command() and async definition are indented by 1 space, but this may just be an error when pasted into stack overflow

 @client.command()
 async def userinfo(ctx, member: discord.Member = None):
^

2nd being there is a missing equals sign

embed.add_field(name = "Created at:", value
member.created_at.strftime("%a, %d %B %Y, %I:%M %p UTC"))

where it should be

embed.add_field(name = "Created at:", value =
                                            ^ equals sign
member.created_at.strftime("%a, %d %B %Y, %I:%M %p UTC"))

The code then runs fine

Sorry that it took so long


问:
css cache problem
I am using gzip on my css to compress on page load. To do this I have made my css (stylesheet.css.php) file.

This is my PHP script included inside file :

```<code><?php
   ob_start ("ob_gzhandler");
   header ("content-type: text/css; charset: UTF-8");
   header ("cache-control: must-revalidate");
   $offset = 60 * 60;
   $expire = "expires: " . gmdate ("D, d M Y H:i:s", time() + $offset) . " GMT";
   header ($expire);
?>
/*css stuff*/
</code>```

I understand that the ($offset = 60 * 60;) is "sending an 'Expires' header, to set an age on how long our cached file will last. Here we set it to expire in one hour."

My problem is obviously if it expires every hour and I change a CSS  setting it wont update until an hour, thus giving a user un-updated stylesheet? How do I change it to say update every one min so it fetches an updates stlyesheet every minute not hour?  Would I just put ($offset = 60;) meaning 1 second?

My other problem is in internet explorer when I use HTTPS and say user hits back button IE gives message "do you want to view only the webpage content that was delivered securely" and you can click 'Yes' or 'No'. If you click 'No' then the CSS does not get loaded on that previous page. I am accessing my CSS using link href='/css/stylesheet.css' path format so cant see why its not secure?
Thanks

答:
What you are suggesting is a bad idea. The way you want to set it up will totally break all caching of your CSS file and have you regenerating it on the fly for every request.

It is definitely a best practice to serve gzipped files, the problems are the way you're doing it. First, hitting the PHP interpreter and gzipping on the fly on every request is very bad for performance and more than negates the benefit of serving a compressed file. Plain HTTP file requests are going to be answered 10x faster than something than hits PHP.

The other issue is that, yes, you can reduce the expires time to 60 seconds (effectively, to zero ... but as svanelten says, at that point you might as well not send the header at all). There's no problem with not sending an expires header (or a short one) if that's really what you want, but doing this in combination with dynamically generating the page is bad if the content isn't actually changing that often. This breaks If-Modified-Since, which browsers send to make conditional requests so that they don't have to redownload the file if it hasn't changed. You are not setting a Last-Modified time so your last-modified time is effectively always "right now."

There are three ways to fix these problems (and accomplish your original goal of serving a compressed CSS file faster, in a cache-friendly way):

Just enable gzip encoding in your web server's config and serve the CSS as a regular file. Then the web server handles everything. i.e. in Apache2, turn on mod_deflate.

The next easiest way is to gzip the file and let your web server serve it. That way, the web server takes care of sending Last-Modified (which will just be the actual file modification time). And, it will send HTTP/304 Not Modified in response to conditional requests, so browsers don't have to re-download the file.

For instance, if you are using Apache, you could just gzip the file and put in the same directory as your regular css file (so you have, for example, file.css and file.css.gz). Then put this into your Apache config or .htaccess:

```<code><Files *.css.gz>
  AddType "text/css" .gz
  AddEncoding gzip .gz
</Files>

RewriteEngine On
RewriteCond %{HTTP:Accept-Encoding} gzip
RewriteCond %{REQUEST_FILENAME}.gz -f
RewriteRule ^(.*)$ $1.gz [QSA,L]
</code>```

The last way (if you must use PHP for this) is to have PHP cache the gzipped file, send the Last-Modified header for when the file was actually last modified, and respond to If-Modified-Since and If-None-Match requests by actually checking these things and then returning a 304 or 200 response accordingly. I do not recommend this because it still hits the PHP interpreter, and you are basically re-implementing webserver functions in PHP, but I've done it in special cases. It's the worst solution but at least better than dynamically generating everything.

Title: css cache problem

Body:
I am using gzip on my css to compress on page load. To do this I have made my css (stylesheet.css.php) file.

This is my PHP script included inside file :

<?php
   ob_start ("ob_gzhandler");
   header ("content-type: text/css; charset: UTF-8");
   header ("cache-control: must-revalidate");
   $offset = 60 * 60;
   $expire = "expires: " . gmdate ("D, d M Y H:i:s", time() + $offset) . " GMT";
   header ($expire);
?>
/*css stuff*/

I understand that the ($offset = 60 * 60;) is "sending an 'Expires' header, to set an age on how long our cached file will last. Here we set it to expire in one hour."

My problem is obviously if it expires every hour and I change a CSS  setting it wont update until an hour, thus giving a user un-updated stylesheet? How do I change it to say update every one min so it fetches an updates stlyesheet every minute not hour?  Would I just put ($offset = 60;) meaning 1 second?

My other problem is in internet explorer when I use HTTPS and say user hits back button IE gives message "do you want to view only the webpage content that was delivered securely" and you can click 'Yes' or 'No'. If you click 'No' then the CSS does not get loaded on that previous page. I am accessing my CSS using link href='/css/stylesheet.css' path format so cant see why its not secure?
Thanks

Body:
What you are suggesting is a bad idea. The way you want to set it up will totally break all caching of your CSS file and have you regenerating it on the fly for every request.

It is definitely a best practice to serve gzipped files, the problems are the way you're doing it. First, hitting the PHP interpreter and gzipping on the fly on every request is very bad for performance and more than negates the benefit of serving a compressed file. Plain HTTP file requests are going to be answered 10x faster than something than hits PHP.

The other issue is that, yes, you can reduce the expires time to 60 seconds (effectively, to zero ... but as svanelten says, at that point you might as well not send the header at all). There's no problem with not sending an expires header (or a short one) if that's really what you want, but doing this in combination with dynamically generating the page is bad if the content isn't actually changing that often. This breaks If-Modified-Since, which browsers send to make conditional requests so that they don't have to redownload the file if it hasn't changed. You are not setting a Last-Modified time so your last-modified time is effectively always "right now."

There are three ways to fix these problems (and accomplish your original goal of serving a compressed CSS file faster, in a cache-friendly way):

Just enable gzip encoding in your web server's config and serve the CSS as a regular file. Then the web server handles everything. i.e. in Apache2, turn on mod_deflate.

The next easiest way is to gzip the file and let your web server serve it. That way, the web server takes care of sending Last-Modified (which will just be the actual file modification time). And, it will send HTTP/304 Not Modified in response to conditional requests, so browsers don't have to re-download the file.

For instance, if you are using Apache, you could just gzip the file and put in the same directory as your regular css file (so you have, for example, file.css and file.css.gz). Then put this into your Apache config or .htaccess:

<Files *.css.gz>
  AddType "text/css" .gz
  AddEncoding gzip .gz
</Files>

RewriteEngine On
RewriteCond %{HTTP:Accept-Encoding} gzip
RewriteCond %{REQUEST_FILENAME}.gz -f
RewriteRule ^(.*)$ $1.gz [QSA,L]

The last way (if you must use PHP for this) is to have PHP cache the gzipped file, send the Last-Modified header for when the file was actually last modified, and respond to If-Modified-Since and If-None-Match requests by actually checking these things and then returning a 304 or 200 response accordingly. I do not recommend this because it still hits the PHP interpreter, and you are basically re-implementing webserver functions in PHP, but I've done it in special cases. It's the worst solution but at least better than dynamically generating everything.


问:
Confirm whether to write comments with xpath
Could you make an example with the site? I want to ignore the posts with comments and just click the ones without comments.

```
from selenium import webdriver
import time

path = "C:\chromed\chromedriver.exe"
driver = webdriver.Chrome(path) #path
'''

'''
driver.get("http://cineaste.co.kr/") #url
time.sleep(0.5)

postclick = driver.find_element_by_xpath("//h3[.='영화이야기']/following::div[@class='widget-small-box'][1]//li[@class='ellipsis'][not(contains(.,'+'))]") #로그인창 활성화
postclick.click()

driver.close()
```

I tried this, but there was an error.

```
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//h3[.='영화이야기']/following::div[@class='widget-small-box'][1]//li[@class='ellipsis'][not(contains(.,'+'))]"}
  (Session info: chrome=81.0.4044.138)
```

I want to click on a post that doesn't have any comments yet. And I want to skip posts with comments.
I'm still a beginner. Help me.

答:
You'll need these imports :

```<code>from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
</code>```

Example with the first entry with no comments in the "movie-reviews" block :

```<code>WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//h3[.='영화감상평']/following::div[@class='widget-small-box'][1]//li[@class='ellipsis'][not(contains(.,'+'))][1]"))).click()
</code>```

Body:
Could you make an example with the site? I want to ignore the posts with comments and just click the ones without comments.

from selenium import webdriver
import time

path = "C:\chromed\chromedriver.exe"
driver = webdriver.Chrome(path) #path
'''

'''
driver.get("http://cineaste.co.kr/") #url
time.sleep(0.5)

postclick = driver.find_element_by_xpath("//h3[.='영화이야기']/following::div[@class='widget-small-box'][1]//li[@class='ellipsis'][not(contains(.,'+'))]") #로그인창 활성화
postclick.click()

driver.close()

I tried this, but there was an error.

selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//h3[.='영화이야기']/following::div[@class='widget-small-box'][1]//li[@class='ellipsis'][not(contains(.,'+'))]"}
  (Session info: chrome=81.0.4044.138)

I want to click on a post that doesn't have any comments yet. And I want to skip posts with comments.
I'm still a beginner. Help me.

Body:
You'll need these imports :

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

Example with the first entry with no comments in the "movie-reviews" block :

WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//h3[.='영화감상평']/following::div[@class='widget-small-box'][1]//li[@class='ellipsis'][not(contains(.,'+'))][1]"))).click()


问:
How can I connect to filtered items with Vue JS?
Making todo list application with Vue js

Behaviour:

input task

Add task -> shows task in list

make some items by doing above 2 steps

check checkbox some of those items

click Ongoing or done

---- now problem happens ---

When you have items filtered, clicking Remove task or changing done status in localStorage by checking checkbox are executed to wrong items.

I know this is because of index of below area

Is there any way to connect to the todos array and localStorage object property by id number?

```<code>removeTask(index) {
  let keyObject =JSON.parse(localStorage.getItem(this.keyName))
  this.todos.splice(index,1);
  if (keyObject) {
    delete keyObject[index];
      localStorage.setItem(this.keyName, JSON.stringify(this.todos));
  }
},

status(index) {
  this.todos[index].done = !this.todos[index].done
  localStorage.setItem(this.keyName, JSON.stringify(this.todos));
}
</code>```

new Vue({
  el: '#app',
  data: {
    inputTask: '',
    filtered:'',
    id: 1,
    done:false,
    keyName:'myTodoList',
    todos: []
  },

  created() {
    let keyObject =JSON.parse(localStorage.getItem(this.keyName))
    if (keyObject) {
      this.todos = keyObject;
    } else {
      return
    }

    //set id number for when reloaded
    if (this.todos.length > 0) {
      const setId = this.todos.reduce(function(a,b){ return a > b.id ? a : b.id} ,0)
      this.id = setId + 1
      this.filtered = 'all'
    }

  },

  methods: {
    filtering(filtered) {
      this.filtered = filtered
    },

    addTask() {
      if (this.inputTask==='') {
        return
      }

      const todo = {id: this.id, task:this.inputTask, done:false}
      this.todos.push(todo)
      localStorage.setItem(this.keyName, JSON.stringify(this.todos));
      this.inputTask=''
      this.filtered = 'all'
      this.id++

    },

    removeAll() {
      this.todos = [];
      localStorage.clear();
    },

    removeTask(index) {
      let keyObject =JSON.parse(localStorage.getItem(this.keyName))
      this.todos.splice(index,1);
      if (keyObject) {
        delete keyObject[index];
          localStorage.setItem(this.keyName, JSON.stringify(this.todos));
      }
    },

    status(index) {
      this.todos[index].done = !this.todos[index].done
      localStorage.setItem(this.keyName, JSON.stringify(this.todos));
    }

  },

  computed: {

    filteredTodos() {
      return this.todos.filter(todo => {
        if (this.filtered === 'ongoing') {
          return !todo.done;
        } else if (this.filtered === 'done') {
          return todo.done;
        } else {
          return true;
        }

      });
    },

  },

})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.active {background: turquoise;}</code>```

TODO

  <input type="text" v-model="inputTask" placeholder="Enter your task">
  <button @click="addTask">Add task</button>

    <button :class="{active: filtered ==='all'}" @click="filtering('all')">All</button>
    <button :class="{active: filtered ==='ongoing'}" @click="filtering('ongoing')">Ongoing</button>
    <button :class="{active: filtered ==='done'}" @click="filtering('done')">Done</button>
    <button @click="removeAll">Remove all</button>

{{filteredTodos.length}} tasks left /  {{todos.length}} tasks of all

      <input type="checkbox" v-model="todo.done" @click="status(index)">
      {{ todo.task }}
      <button @click="removeTask(index)">Remove task</button>

All done

```

答:
Because todo items are the same objects in an original and filtered lists then you should pass an item itself to status and removeTask and not its index.

template:

```<code><input type="checkbox" v-model="todo.done" @click="status(todo)">
...
<button @click="removeTask(todo)">Remove task</button>
</code>```

code:

```<code>removeTask(todo) {
      let keyObject =JSON.parse(localStorage.getItem(this.keyName))
      const index =  this.todos.indexOf(todo)
      this.todos.splice(index,1);
      if (keyObject) {
        // why are you removing this? You will overwrite the whole array in setItem below
        delete keyObject[index];
        localStorage.setItem(this.keyName, JSON.stringify(this.todos));
      }
    },
status(todo) {
      todo.done =  !todo.done
      localStorage.setItem(this.keyName, JSON.stringify(this.todos));
    }
</code>```

Body:
Making todo list application with Vue js

Behaviour:

input task

Add task -> shows task in list

make some items by doing above 2 steps

check checkbox some of those items

click Ongoing or done

---- now problem happens ---

When you have items filtered, clicking Remove task or changing done status in localStorage by checking checkbox are executed to wrong items.

I know this is because of index of below area

Is there any way to connect to the todos array and localStorage object property by id number?

removeTask(index) {
  let keyObject =JSON.parse(localStorage.getItem(this.keyName))
  this.todos.splice(index,1);
  if (keyObject) {
    delete keyObject[index];
      localStorage.setItem(this.keyName, JSON.stringify(this.todos));
  }
},

status(index) {
  this.todos[index].done = !this.todos[index].done
  localStorage.setItem(this.keyName, JSON.stringify(this.todos));
}

new Vue({
  el: '#app',
  data: {
    inputTask: '',
    filtered:'',
    id: 1,
    done:false,
    keyName:'myTodoList',
    todos: []
  },

  created() {
    let keyObject =JSON.parse(localStorage.getItem(this.keyName))
    if (keyObject) {
      this.todos = keyObject;
    } else {
      return
    }

    //set id number for when reloaded
    if (this.todos.length > 0) {
      const setId = this.todos.reduce(function(a,b){ return a > b.id ? a : b.id} ,0)
      this.id = setId + 1
      this.filtered = 'all'
    }

  },

  methods: {
    filtering(filtered) {
      this.filtered = filtered
    },

    addTask() {
      if (this.inputTask==='') {
        return
      }

      const todo = {id: this.id, task:this.inputTask, done:false}
      this.todos.push(todo)
      localStorage.setItem(this.keyName, JSON.stringify(this.todos));
      this.inputTask=''
      this.filtered = 'all'
      this.id++

    },

    removeAll() {
      this.todos = [];
      localStorage.clear();
    },

    removeTask(index) {
      let keyObject =JSON.parse(localStorage.getItem(this.keyName))
      this.todos.splice(index,1);
      if (keyObject) {
        delete keyObject[index];
          localStorage.setItem(this.keyName, JSON.stringify(this.todos));
      }
    },

    status(index) {
      this.todos[index].done = !this.todos[index].done
      localStorage.setItem(this.keyName, JSON.stringify(this.todos));
    }

  },

  computed: {

    filteredTodos() {
      return this.todos.filter(todo => {
        if (this.filtered === 'ongoing') {
          return !todo.done;
        } else if (this.filtered === 'done') {
          return todo.done;
        } else {
          return true;
        }

      });
    },

  },

})

.active {background: turquoise;}

TODO

  <input type="text" v-model="inputTask" placeholder="Enter your task">
  <button @click="addTask">Add task</button>

    <button :class="{active: filtered ==='all'}" @click="filtering('all')">All</button>
    <button :class="{active: filtered ==='ongoing'}" @click="filtering('ongoing')">Ongoing</button>
    <button :class="{active: filtered ==='done'}" @click="filtering('done')">Done</button>
    <button @click="removeAll">Remove all</button>

{{filteredTodos.length}} tasks left /  {{todos.length}} tasks of all

      <input type="checkbox" v-model="todo.done" @click="status(index)">
      {{ todo.task }}
      <button @click="removeTask(index)">Remove task</button>

All done

Body:
Because todo items are the same objects in an original and filtered lists then you should pass an item itself to status and removeTask and not its index.

template:

<input type="checkbox" v-model="todo.done" @click="status(todo)">
...
<button @click="removeTask(todo)">Remove task</button>

code:

removeTask(todo) {
      let keyObject =JSON.parse(localStorage.getItem(this.keyName))
      const index =  this.todos.indexOf(todo)
      this.todos.splice(index,1);
      if (keyObject) {
        // why are you removing this? You will overwrite the whole array in setItem below
        delete keyObject[index];
        localStorage.setItem(this.keyName, JSON.stringify(this.todos));
      }
    },
status(todo) {
      todo.done =  !todo.done
      localStorage.setItem(this.keyName, JSON.stringify(this.todos));
    }


问:
List sieve of eratosthenes
here a program that find a primary numbers in array from n to 2n. it works properly, but something must be otherwise:
In this program, the sieve is superimposed on the array: the elements are replaced by zeros. It should be wrong: no arrays. First, form a list of all the numbers one by one in the link list. Then remove from the list those links that contain multiples. At the end, print what is left. IDK how can i do this without arrays.</p>

```<code>#include <iostream>
using namespace std;

struct node
{
    int num;
    node* next, * prev;
};

class List  // list
{
    node* head, * tail;
public:
    List() :head(NULL), tail(NULL) {};
    void Print();
    void Add(int num);
};

void List::Print() //print list
{
    node* temp = head;

    while (temp != NULL)
    {
        cout << temp->num << " ";
        temp = temp->next;
    }
    cout << endl;
}

void List::Add(int num)  //add to list
{
    node* temp = new node;
    temp->next = NULL;
    temp->num = num;
    if (head!=NULL)
    {
        temp->prev = tail;
        tail->next = temp;
        tail = temp;
    }
    else
    {
        temp->prev = NULL;
        head = tail = temp;
    }
}

int main()
{

    List list;
    int n, num;
        cout << "Enter N :  "; cin >> n;
        n = abs(n);
    int* simp = new int[2 * n];
    // eratosphene's sieve
    for (int i = 0; i < 2 * n; i++) {
        simp[i] = i;
    }
    simp[1] = 0;
    for (int l = 2; l < 2 * n; l++) {
        if (simp[l] != 0) {
            for (int j = l * 2; j < 2 * n; j += l) {
                simp[j] = 0;
            }
        }
    }
    for (int i = n; i < 2 * n; i++) {
        if (simp[i]) {
            num = simp[i];
            list.Add(num);
        }
    }
    cout << "Prime numbers of the list:\n";
    list.Print();
    return 0;
}
</code>```

答:
Let's leave code aside for a moment and consider you would do this with a pen and paper: you would write down numbers 2 3 4 ... 2n and start off at "2" (outer loop). You would then (inner loop) mark (note here: NOT erase, only mark!) every second number beginning from 2*2=4.
Then you would return to the outer loop and consider "3" and mark every third number starting off at 3*2=6 (actually it would also be valid to start at 3^2=9).

This marking translates into setting the elements in the array to 0, and as a last step you would only consider the unmarked (i.e. non 0) elements.

In your approach you now want to erase the nodes from the linked list. Translating this into the pen-and-paper approach would be to erase the numbers from the paper.
Then you would start at "2" again, erase the multiples of 2, then go to "3" and erase the multiples of 3.
The important change is, that you can no longer just blindly erase every third number but you would actually have to look at the numbers and ask yourself: is that a multiple of 3?

Of course you could do that and you can also program that, but it wouldn't be the sieve of eratosthenes anymore. The strength of the algorithm is, that any multiples of a number are easily spotted by their index:

In your provided code, simp[i] == 0 || simp[i] == i holds all the time, i.e. a number is either marked or it it's index is actually the value itself. Therefore you do not have to look at the number and test whether it is dividable but you can just do the judgment based on its index.

Title: List sieve of eratosthenes

Body:
here a program that find a primary numbers in array from n to 2n. it works properly, but something must be otherwise:
In this program, the sieve is superimposed on the array: the elements are replaced by zeros. It should be wrong: no arrays. First, form a list of all the numbers one by one in the link list. Then remove from the list those links that contain multiples. At the end, print what is left. IDK how can i do this without arrays.

#include <iostream>
using namespace std;

struct node
{
    int num;
    node* next, * prev;
};

class List  // list
{
    node* head, * tail;
public:
    List() :head(NULL), tail(NULL) {};
    void Print();
    void Add(int num);
};

void List::Print() //print list
{
    node* temp = head;

    while (temp != NULL)
    {
        cout << temp->num << " ";
        temp = temp->next;
    }
    cout << endl;
}

void List::Add(int num)  //add to list
{
    node* temp = new node;
    temp->next = NULL;
    temp->num = num;
    if (head!=NULL)
    {
        temp->prev = tail;
        tail->next = temp;
        tail = temp;
    }
    else
    {
        temp->prev = NULL;
        head = tail = temp;
    }
}

int main()
{

    List list;
    int n, num;
        cout << "Enter N :  "; cin >> n;
        n = abs(n);
    int* simp = new int[2 * n];
    // eratosphene's sieve
    for (int i = 0; i < 2 * n; i++) {
        simp[i] = i;
    }
    simp[1] = 0;
    for (int l = 2; l < 2 * n; l++) {
        if (simp[l] != 0) {
            for (int j = l * 2; j < 2 * n; j += l) {
                simp[j] = 0;
            }
        }
    }
    for (int i = n; i < 2 * n; i++) {
        if (simp[i]) {
            num = simp[i];
            list.Add(num);
        }
    }
    cout << "Prime numbers of the list:\n";
    list.Print();
    return 0;
}


问:
Joining 4 Tables together and checking where totals do not match
I have 4 tables act,up, pos_act, pos_up
In this example, let's say I have customer ID and Amount columns as

act.cust_id, up.cust_id, act.amount, up.amount
pos_up.cID, pos_act.cID, pos_up.amount_, pos_act.amount_

```<code>       act

| cust_id | amount |
|:-------:|:------:|
|   6789  |  30.00 |
|   9876  |  25.00 |

       pos_act

|   cID   | amount_|
|:-------:|:------:|
|   6789  |  30.00 |
|   9876  |  24.99 |

----------------------------------------

        up

| cust_id | amount |
|:-------:|:------:|
|   1234  |  10.00 |
|   2345  |  75.00 |

        pos_up

|   cID   | amount_|
|:-------:|:------:|
|   1234  |   9.99 |
|   2345  |  75.00 |
</code>```

Now With this, I want to compare where amounts do not match all in one table.

So in this example 2345 matches in up but in act 1234 does not match.

Then the results should be

```<code>    All Unmatched

| cust_id | Table  |
|:-------:|:------:|
|   9876  |  Act   |
|   1234  |  Up    |

</code>```

I tried with unions but cant seem to get that working

```<code>SELECT *
FROM (
    select cID, amount FROM  act as a
    union select cID, amount FROM up as b
) as v
LEFT JOIN
(select CID, amount_ FROM pos_up as c
 UNION select CID, amount_ from pos_act as d
 ) as r
 WHERE a.amount != d.amount_
</code>```

I also tried with left joins but it just shows me all results.  I only want ones that do not match.  custid is a unique ID and may appear multiple times.

答:
You just use UNION in a wrong place

```<code>SELECT cID, amount, 'act' as `table`
FROM  act as a
LEFT JOIN pos_act as pa
ON a.cust_id = pa.
 WHERE a.amount != pa.amount_
UNION ALL
SELECT cID, amount, 'up'
FROM  up as u
LEFT JOIN pos_up as pu
ON u.cust_id = pu.cID
WHERE u.amount != pu.amount_
</code>```

Body:
I have 4 tables act,up, pos_act, pos_up
In this example, let's say I have customer ID and Amount columns as

act.cust_id, up.cust_id, act.amount, up.amount
pos_up.cID, pos_act.cID, pos_up.amount_, pos_act.amount_

       act

| cust_id | amount |
|:-------:|:------:|
|   6789  |  30.00 |
|   9876  |  25.00 |

       pos_act

|   cID   | amount_|
|:-------:|:------:|
|   6789  |  30.00 |
|   9876  |  24.99 |

----------------------------------------

        up

| cust_id | amount |
|:-------:|:------:|
|   1234  |  10.00 |
|   2345  |  75.00 |

        pos_up

|   cID   | amount_|
|:-------:|:------:|
|   1234  |   9.99 |
|   2345  |  75.00 |

Now With this, I want to compare where amounts do not match all in one table.

So in this example 2345 matches in up but in act 1234 does not match.

Then the results should be

    All Unmatched

| cust_id | Table  |
|:-------:|:------:|
|   9876  |  Act   |
|   1234  |  Up    |

I tried with unions but cant seem to get that working

SELECT *
FROM (
    select cID, amount FROM  act as a
    union select cID, amount FROM up as b
) as v
LEFT JOIN
(select CID, amount_ FROM pos_up as c
 UNION select CID, amount_ from pos_act as d
 ) as r
 WHERE a.amount != d.amount_

I also tried with left joins but it just shows me all results.  I only want ones that do not match.  custid is a unique ID and may appear multiple times.

Body:
You just use UNION in a wrong place

SELECT cID, amount, 'act' as `table`
FROM  act as a
LEFT JOIN pos_act as pa
ON a.cust_id = pa.
 WHERE a.amount != pa.amount_
UNION ALL
SELECT cID, amount, 'up'
FROM  up as u
LEFT JOIN pos_up as pu
ON u.cust_id = pu.cID
WHERE u.amount != pu.amount_


问:
How to group GraphQL query result with individual key as array

I'm using GraphQL with .NET Core. I have query like below. As I'm new in GraphQL.NET, I can't understand how to group individual key as array.

```<code>`{
    readingQuery{
             readingsDBFilter(buildingId: 30, objectId: 1, datafieldId: 1, startTime: "02-05-201812-00-00-AM", endTime: "30-05-201811-59-00-PM"){
                             value,
                            unix
                        }
    }
}`
</code>```

I have Output Like this

```<code>`{
    "data": {
        "readingQuery": {
            "readingsDBFilter": [
               {
                    "value": 0.66,
                    "unix": 1525254180000
                },
                {
                    "value": 0.68,
                    "unix": 1525254240000
                }
           ]
       }
   }
}`
</code>```

But, Is it possible to return result like this from query.

```<code>`{
    "data": {
        "readingQuery": {
            "readingsDBFilter": [
                {
                    "value":[ 0.66, 0.68],
                    "unix": [1525254180000, 1525254240000]
                }
            ]
        }
    }
}`
</code>```

答:
Looks like you need to group values from different records
I guess you have two option here
1) try to group it on SQL level (maybe better to create dateview)
2) do it on runtime level, in code. from my point of view - it's bad. any grouping in code it's much slower then the same operation in db-level</p>

Body:
I'm using GraphQL with .NET Core. I have query like below. As I'm new in GraphQL.NET, I can't understand how to group individual key as array.

`{
    readingQuery{
             readingsDBFilter(buildingId: 30, objectId: 1, datafieldId: 1, startTime: "02-05-201812-00-00-AM", endTime: "30-05-201811-59-00-PM"){
                             value,
                            unix
                        }
    }
}`

I have Output Like this

`{
    "data": {
        "readingQuery": {
            "readingsDBFilter": [
               {
                    "value": 0.66,
                    "unix": 1525254180000
                },
                {
                    "value": 0.68,
                    "unix": 1525254240000
                }
           ]
       }
   }
}`

But, Is it possible to return result like this from query.

`{
    "data": {
        "readingQuery": {
            "readingsDBFilter": [
                {
                    "value":[ 0.66, 0.68],
                    "unix": [1525254180000, 1525254240000]
                }
            ]
        }
    }
}`


问:
How can I disable my TopLevel window when a message box appears?
In my code, I have a TopLevel window (the root one has been hided with "withdraw()" method) where, if you do somthing wrong, an error window (created using the "messagebox.showerror()" function) appears. now, how can I disable the TopLevel window to make the user to interact only with the error window?

before to use the "messagebox.showerror()" function I tried to use the "grab_set()" method with my TopLevel window, but it seems doesn't do nothing, maybe because can I use the "grab_set()" method only with the root window? I really don't know how to solve my issue.

答:
Nice to see that my post has been reopened! Anyway, I solved thanks the comment posted by acw1668! To reach my goal, I had to add the "parent" argument in my "messagebox.showerror(..)" instruction. below a template:

```<code>messagebox.showerror(TITLE, ERROR_MESSAGE, parent = YOUR_WINDOW_OBJECT)
</code>```

By default the parent object is always the root window, but in my case it had to be the TopLevel one.

Body:
Nice to see that my post has been reopened! Anyway, I solved thanks the comment posted by acw1668! To reach my goal, I had to add the "parent" argument in my "messagebox.showerror(..)" instruction. below a template:

messagebox.showerror(TITLE, ERROR_MESSAGE, parent = YOUR_WINDOW_OBJECT)

By default the parent object is always the root window, but in my case it had to be the TopLevel one.


问:
Sample among any axis on a numpy array
I have the following piece of code:

```<code>if axis == 0:
    return m[idx, :]
elif axis == 1:
    return m[:, idx]
else:
    raise('Argument axis currently accepts only values 0 and 1.')
</code>```

How to generalize this behaviour for any shape and any value of axis?

答:
You should use rollaxis function in numpy package.
Example code is as follows:

```<code>import numpy as np
aa = np.arange(30).reshape([5, 6])
print(numpy.rollaxis(a, 0)[1])
</code>```

It prints out the the second element in the first axis.

Title: Sample among any axis on a numpy array

Body:
I have the following piece of code:

if axis == 0:
    return m[idx, :]
elif axis == 1:
    return m[:, idx]
else:
    raise('Argument axis currently accepts only values 0 and 1.')

How to generalize this behaviour for any shape and any value of axis?

Body:
You should use rollaxis function in numpy package.
Example code is as follows:

import numpy as np
aa = np.arange(30).reshape([5, 6])
print(numpy.rollaxis(a, 0)[1])

It prints out the the second element in the first axis.


问:
javascript: React - adding an array to an object changes the format of the array
I am new at React. I have an array of objects that I created from the values of a Form. When I print it in the console it looks fine. but when I try to add that array to a different object, it changes its format in a very strange way.
Here's the code:

```<code>
const [ingredientes, setIngredientes] = useState([]);

const loadIngredient= (value) => {ingredients.push(value); setIngredients(ingredients);}

const LoadIngredient= () => {
        loadIngredient(JSON.stringify({ingredient: ingredient, cant: parseInt(cantidad,10), unit: unidad}));
        console.log('ingredients loaded: ', ingredients)
    }

const RegistrarProducto = () => {

    alert('Producto registrado: '+ JSON.stringify({
      name: name,
      image: image,
      description: description,
      receta: receta,
      ingredients:ingredients}));
  }

</code>```

this is how it looks:

Producto registrado:

```<code>{"name":"Cookies","image":"","description":"The best cookies ever","receta":"this is a test only","ingredients":["{\"ingredient\":\"mantequilla\",\"cant\":100,\"unit\":\"gramos\"}","{\"ingredient\":\"azucar\",\"cant\":300,\"unit\":\"gramos\"}","{\"ingredient\":\"harina\",\"cant\":1,\"unit\":\"tazas\"}"]}
</code>```

Producto Registrado Object

Can somebody explain to me why that happens? Thanks in advance and sorry for the spanglish.

答:
What you see is a serialized format of the JSON, since you use JSON.stringify() before passing value to loadIngredient

If you want it to be an object inside your state array, just remove the usage of JSON.stringify

```<code>const LoadIngredient= () => {
    loadIngredient({ingredient: ingredient, cant: parseInt(cantidad,10), unit: unidad});
    console.log('ingredients loaded: ', ingredients)
}
</code>```

Body:
I am new at React. I have an array of objects that I created from the values of a Form. When I print it in the console it looks fine. but when I try to add that array to a different object, it changes its format in a very strange way.
Here's the code:

const [ingredientes, setIngredientes] = useState([]);

const loadIngredient= (value) => {ingredients.push(value); setIngredients(ingredients);}

const LoadIngredient= () => {
        loadIngredient(JSON.stringify({ingredient: ingredient, cant: parseInt(cantidad,10), unit: unidad}));
        console.log('ingredients loaded: ', ingredients)
    }

const RegistrarProducto = () => {

    alert('Producto registrado: '+ JSON.stringify({
      name: name,
      image: image,
      description: description,
      receta: receta,
      ingredients:ingredients}));
  }

this is how it looks:

Producto registrado:

{"name":"Cookies","image":"","description":"The best cookies ever","receta":"this is a test only","ingredients":["{\"ingredient\":\"mantequilla\",\"cant\":100,\"unit\":\"gramos\"}","{\"ingredient\":\"azucar\",\"cant\":300,\"unit\":\"gramos\"}","{\"ingredient\":\"harina\",\"cant\":1,\"unit\":\"tazas\"}"]}

Producto Registrado Object

Can somebody explain to me why that happens? Thanks in advance and sorry for the spanglish.

Body:
What you see is a serialized format of the JSON, since you use JSON.stringify() before passing value to loadIngredient

If you want it to be an object inside your state array, just remove the usage of JSON.stringify

const LoadIngredient= () => {
    loadIngredient({ingredient: ingredient, cant: parseInt(cantidad,10), unit: unidad});
    console.log('ingredients loaded: ', ingredients)
}


问:
Autosys job which is executing .cmd file taking longer time than running .cmd script separately through command line interface
This job calls .cmd script which calls a product in another environment to execute.
While running in that product tool,it was taking around 11 mins to save the file
But while calling the product I'm autosys through .cmd scripy.,it was taking around 40mins .</p>

答:
I am trying to execute autosys job for which the command is .cmd script.
In JIL,command was defined such that it runs the .cmd script
For example ,consider test.cmd which is windows batch script.

In test.cmd script , code was written like below

Call  C\users\software.exe /product "productinsoft"

From the above line, software.exe is one software and productinsoft is etl  item in that software which generates .CSV file in its own server path.

While running this through autosys,by calling in the above pattern
Job is taking more time to complete for read/write operations.
But when the etl item is executed through the software manually it is taking lesser time.


问:
How do I add a scale bar or north arrow directly on the map control?
I've already looked into SurroundFrames and MapSurrounds, but this appears to be for cases in which you want to add these elements to a printed page. I, on the other hand, am using the MapControl within a live application, and I would like these element directly on the map, in the same way you see them on Google Maps.

Do I have to add these things from scratch using custom symbols and capturing events, or does ArcObjects automate this in any way?

答: The PageLayoutControl is designed to do this.  Scale bars, legends, north arrow, map insets, titles, overview maps, etc. are all layout elements.  </p>


问:
How do I use Microsoft Graph OAuth code flow to produce a token that can read mail?
Steps to recreate require:

A web browser

A command console with CURL installed.

An existing Microsoft Azure account.

An existing Azure App registration (see https://portal.azure.com/#blade/Microsoft_AAD_RegisteredApps/ApplicationsListBlade).

Step 1: Replace "MY_CLIENT_ID" with an Azure client ID for an authorized application.

https://login.microsoftonline.com/common/oauth2/authorize?client_id=MY_CLIENT_ID&response_type=code&redirect_uri=http%3A%2F%2Flocalhost%3A12345&response_mode=query&resource=https%3A%2F%2Fgraph.microsoft.com%2F&state=12345&prompt=admin_consent&scope=https%3A%2F%2Fgraph.microsoft.com%2Fmail.read

Step 2: Enter the URL in a web browser address bar.

Step 3: Proceed to authorize the application to read email using an existing Azure account.  (The browser URL will change to one with an OAuth code.)

Step 4: Copy the OAuth code.

Step 5: In the CURL command below:

Replace "MY_CLIENT_ID" with an Azure client ID for an authorized application.

Replace "MY_CLIENT_SECRET" with the client secret for the authorized application.

Replace "MY_OAUTH_CODE" with the OAuth code.

curl -X POST -H "content-type: application/x-www-form-urlencoded" -d "grant_type=authorization_code&code=MY_OAUTH_CODE&redirect_uri=http%3A%2F%2Flocalhost%3A12345&client_id=MY_CLIENT_ID&scope=https%3A%2F%2Fgraph.microsoft.com%2Fmail.read&client_secret=MY_CLIENT_SECRET" "https://login.microsoftonline.com/common/oauth2/token"

Step 6: Enter the CURL command in a command console.  (A valid request token will be returned.)

Step 7: Replace "MY_REQUEST_TOKEN" in the CURL command below with the request token and execute the command in a command console.

```<code>curl -H "Authorization: Bearer MY_REQUEST_TOKEN" "https://graph.microsoft.com/v1.0/me/"
</code>```

Notice that the basic account info is returned - meaning the token is VALID.

Step 8: Replace "MY_REQUEST_TOKEN" in the CURL command below with the request token and execute the command in a command console.

```<code>curl -H "Authorization: Bearer MY_REQUEST_TOKEN" "https://graph.microsoft.com/v1.0/me/messages"
</code>```

This error is returned:

```<code>{
  "error": {
    "code": "ResourceNotFound",
    "message": "Resource could not be discovered.",
  }
}
</code>```

答:
Since you are trying to read mails, please setup permissions to your registered app with required permissions i.e., Mail.ReadBasic, Mail.Read.

Please go through the documentation https://learn.microsoft.com/en-us/previous-versions/office/office-365-api/api/version-2.0/mail-rest-operations

View the documentation, this is the client class code: https://github.com/microsoftgraph/msgraph-sdk-dotnet/blob/dev/src/Microsoft.Graph/Requests/Generated/GraphServiceClient.cs

Here is an example :

```<code>private static GraphServiceClient GetClient(string accessToken, IHttpProvider provider = null)
{
        var delegateAuthProvider = new DelegateAuthenticationProvider((requestMessage) =>
        {
            requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", accessToken);

            return Task.FromResult(0);
        });

        var graphClient = new GraphServiceClient(delegateAuthProvider, provider ?? HttpProvider);

        return graphClient;
 }
</code>```

Body:
Steps to recreate require:

A web browser

A command console with CURL installed.

An existing Microsoft Azure account.

An existing Azure App registration (see https://portal.azure.com/#blade/Microsoft_AAD_RegisteredApps/ApplicationsListBlade).

Step 1: Replace "MY_CLIENT_ID" with an Azure client ID for an authorized application.

https://login.microsoftonline.com/common/oauth2/authorize?client_id=MY_CLIENT_ID&response_type=code&redirect_uri=http%3A%2F%2Flocalhost%3A12345&response_mode=query&resource=https%3A%2F%2Fgraph.microsoft.com%2F&state=12345&prompt=admin_consent&scope=https%3A%2F%2Fgraph.microsoft.com%2Fmail.read

Step 2: Enter the URL in a web browser address bar.

Step 3: Proceed to authorize the application to read email using an existing Azure account.  (The browser URL will change to one with an OAuth code.)

Step 4: Copy the OAuth code.

Step 5: In the CURL command below:

Replace "MY_CLIENT_ID" with an Azure client ID for an authorized application.

Replace "MY_CLIENT_SECRET" with the client secret for the authorized application.

Replace "MY_OAUTH_CODE" with the OAuth code.

curl -X POST -H "content-type: application/x-www-form-urlencoded" -d "grant_type=authorization_code&code=MY_OAUTH_CODE&redirect_uri=http%3A%2F%2Flocalhost%3A12345&client_id=MY_CLIENT_ID&scope=https%3A%2F%2Fgraph.microsoft.com%2Fmail.read&client_secret=MY_CLIENT_SECRET" "https://login.microsoftonline.com/common/oauth2/token"

Step 6: Enter the CURL command in a command console.  (A valid request token will be returned.)

Step 7: Replace "MY_REQUEST_TOKEN" in the CURL command below with the request token and execute the command in a command console.

curl -H "Authorization: Bearer MY_REQUEST_TOKEN" "https://graph.microsoft.com/v1.0/me/"

Notice that the basic account info is returned - meaning the token is VALID.

Step 8: Replace "MY_REQUEST_TOKEN" in the CURL command below with the request token and execute the command in a command console.

curl -H "Authorization: Bearer MY_REQUEST_TOKEN" "https://graph.microsoft.com/v1.0/me/messages"

This error is returned:

{
  "error": {
    "code": "ResourceNotFound",
    "message": "Resource could not be discovered.",
  }
}

Body:
Since you are trying to read mails, please setup permissions to your registered app with required permissions i.e., Mail.ReadBasic, Mail.Read.

Please go through the documentation https://learn.microsoft.com/en-us/previous-versions/office/office-365-api/api/version-2.0/mail-rest-operations

View the documentation, this is the client class code: https://github.com/microsoftgraph/msgraph-sdk-dotnet/blob/dev/src/Microsoft.Graph/Requests/Generated/GraphServiceClient.cs

Here is an example :

private static GraphServiceClient GetClient(string accessToken, IHttpProvider provider = null)
{
        var delegateAuthProvider = new DelegateAuthenticationProvider((requestMessage) =>
        {
            requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", accessToken);

            return Task.FromResult(0);
        });

        var graphClient = new GraphServiceClient(delegateAuthProvider, provider ?? HttpProvider);

        return graphClient;
 }


问:
K8s pod connection with camera connected in same network
There is a Camera which is connected in a network switch . How can we connect the application to that camera through kubernetes pod. I have a pod running which should take video ingestion from that camera. How can this be achieved through application pod.</p>

答: Kubernetes is used to run containerized applications. So you should first write the application to connect to camera and package that application as docker image and then you can run it as a pod which in turn spin your container in kubernetes cluster</p>


问:
Can I use double equal in JavaScript if one of the elements is a string?
I'm newbie in JS, I know that == double comparation for equality and === triple one for equality and type. My teacher says that I should use always triple. However, I don't see any down effect if I use double equal when one of the elements is a string.

'' == 0 // true
'10' == 10 // true
'dog' == 'cat' // false
```

So, I'm using always double equal when some of the element is a string (avoiding this 'false' == false) and triple when I'm detecting null or undefined.

Is there any down side for my approach?

I checked this previous answer: Which equals operator (== vs ===) should be used in JavaScript comparisons?

答:
Using my personal working experience as a basis, I have never user the abstract equality operator(==) over the strict equality operator(===).

Since the == operator may have some unpredictable behavior, like

```<code>'0' == false    // true
</code>```

While

```<code>'0' === false   // false
</code>```

The second case is normally what you want your code to do.

Also, the == operator is more performance-costly than the === operator.

You can read more about this on the ecmaScript documentation:

The Equals(==) Operator: https://www.ecma-international.org/ecma-262/5.1/#sec-11.9.1

The Abstract Equality Comparison Algorithm: https://www.ecma-international.org/ecma-262/5.1/#sec-11.9.3

The Strict Equals(===) Operator: https://www.ecma-international.org/ecma-262/5.1/#sec-11.9.4

The Strict Equality Comparison Algorithm: https://www.ecma-international.org/ecma-262/5.1/#sec-11.9.6 (these two comparison algorithm probably will clarify to you why the strict equality is better on performance)

Body:
I'm newbie in JS, I know that == double comparation for equality and === triple one for equality and type. My teacher says that I should use always triple. However, I don't see any down effect if I use double equal when one of the elements is a string.

'' == 0 // true
'10' == 10 // true
'dog' == 'cat' // false

So, I'm using always double equal when some of the element is a string (avoiding this 'false' == false) and triple when I'm detecting null or undefined.

Is there any down side for my approach?

I checked this previous answer: Which equals operator (== vs ===) should be used in JavaScript comparisons?

Body:
Using my personal working experience as a basis, I have never user the abstract equality operator(==) over the strict equality operator(===).

Since the == operator may have some unpredictable behavior, like

'0' == false    // true

While

'0' === false   // false

The second case is normally what you want your code to do.

Also, the == operator is more performance-costly than the === operator.

You can read more about this on the ecmaScript documentation:

The Equals(==) Operator: https://www.ecma-international.org/ecma-262/5.1/#sec-11.9.1

The Abstract Equality Comparison Algorithm: https://www.ecma-international.org/ecma-262/5.1/#sec-11.9.3

The Strict Equals(===) Operator: https://www.ecma-international.org/ecma-262/5.1/#sec-11.9.4

The Strict Equality Comparison Algorithm: https://www.ecma-international.org/ecma-262/5.1/#sec-11.9.6 (these two comparison algorithm probably will clarify to you why the strict equality is better on performance)


问:
Image not able to show in Google colab using PIL library
```<code>from PIL import Image
visa_file='/content/visa-logo-mastercard.jpg'
img_visa= Image.open(visa_file,mode='r')
img_visa.show()
</code>```

I am not getting the output of the image in Google colab.

Also the output of type(img_visa) is 'PIL.JpegImagePlugin.JpegImageFile'.

So the image object has been created, but the image is not displaying. And I only want to use PIL to show Image. How to do this?

答:
Just

```<code>img_visa
</code>```

is enough. You don't need

```<code>img_visa.show()
</code>```

To be more explicit, you can use

```<code>display(img_visa)
</code>```

Body:
from PIL import Image
visa_file='/content/visa-logo-mastercard.jpg'
img_visa= Image.open(visa_file,mode='r')
img_visa.show()

I am not getting the output of the image in Google colab.

Also the output of type(img_visa) is 'PIL.JpegImagePlugin.JpegImageFile'.

So the image object has been created, but the image is not displaying. And I only want to use PIL to show Image. How to do this?

Body:
Just

img_visa

is enough. You don't need

img_visa.show()

To be more explicit, you can use

display(img_visa)


问:
How do I track Flutter screens in Firebase analytics?
I have a Flutter app and I'm testing Google Analytics for Firebase on Flutter.

I wanted to see the routes our users (well, me for now) are visiting. I followed the setup steps in firebase_analytics and I checked their example app, too. I enabled debugging for Analytics as described in the Debug View docs

Unfortunately, the only two kinds of screen views (firebase_screen_class) I receive in my Analytics Debug view are Flutter and MainActivity.

I'd expect to see /example-1, /example-2 and /welcome somewhere, but I don't.

This is the app I'm running in Flutter

```<code>class App extends StatelessWidget {
  final FirebaseAnalytics analytics = FirebaseAnalytics();
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      routes: <String, WidgetBuilder>{
        '/example-1': (_) => Example1(),
        '/example-2': (_) => Example2(),
        '/welcome': (_) => Welcome(),
      },
      home: Welcome(),
      navigatorObservers: [FirebaseAnalyticsObserver(analytics: analytics)],
    );
  }
}
</code>```

答:
If you are seeing "Flutter" in the firebase_screen_class parameter of the screen_view
event, it means you have it configured properly.

You should find the values you are expecting in the firebase_screen parameter, instead of the firebase_screen_class.

It's also worth checking the firebase_previous_screen parameter to see what was the screen that was open before that one.

Body:
I have a Flutter app and I'm testing Google Analytics for Firebase on Flutter.

I wanted to see the routes our users (well, me for now) are visiting. I followed the setup steps in firebase_analytics and I checked their example app, too. I enabled debugging for Analytics as described in the Debug View docs

Unfortunately, the only two kinds of screen views (firebase_screen_class) I receive in my Analytics Debug view are Flutter and MainActivity.

I'd expect to see /example-1, /example-2 and /welcome somewhere, but I don't.

This is the app I'm running in Flutter

class App extends StatelessWidget {
  final FirebaseAnalytics analytics = FirebaseAnalytics();
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      routes: <String, WidgetBuilder>{
        '/example-1': (_) => Example1(),
        '/example-2': (_) => Example2(),
        '/welcome': (_) => Welcome(),
      },
      home: Welcome(),
      navigatorObservers: [FirebaseAnalyticsObserver(analytics: analytics)],
    );
  }
}


问:
How to Build Dynamic SQl for this?
I have to create a Procedure with dynamic SQL and generate the Update Statements.

I have tables

Col.TMap.T_Mp

```<code> ID   M_Type  ID_F     SF1      SF2
  1   Acc     ACC_ID   AC_ID    NULL
  1   STA     STA_ID   ST_ID    NULL
  1   CHa     Cha_ID   CH_ID    NULL
</code>```

ACC

```<code>ID    AC_ID   SV1   SV2     SO1    SO2
1     12      6     NULL    =      NULL
</code>```

STA

```<code>ID     STA_ID      SV1     SV2      SO1    SO2
1      1           Open    NULL     =      NULL
1      2           CLosed  NULL     =      NULL
</code>```

CHa

```<code>ID    CHa_ID    SV1    SV2    SO1    SO2
1     1         PH     NULL   =      NULL
1     2         EM     NULL   =      NULL
</code>```

I need to update Ms.AT.AT_CRAW_Dmtemp table with ACC_ID,STA_ID and CHA_ID from the above tables:

The out put should be:

```<code>UPDATE  mt
SET ACC_ID = ac.ACC_ID
FROM Ms.AT.AT_CRAW t
INNER JOIN Acc ac ON t.AC_ID=SV1
AND ac.ID = 1
INNER JOIN Ms.AT.AT_CRAW_Dmtemp mt
ON mt.[SRID] = t.[RID]

UPDATE  mt
SET STA_ID = ac.STA_ID
FROM Ms.AT.AT_CRAW t
INNER JOIN STA ac ON t.ST_ID=SV1
AND ac.ID = 1
INNER JOIN Ms.AT.AT_CRAW_Dmtemp mt
ON mt.[SRID] = t.[RID]

UPDATE  mt
SET CHa_ID = ac.CHa_ID
FROM Ms.AT.AT_CRAW t
INNER JOIN CHa ac ON t.CH_ID=SV1
AND ac.ID = 1
INNER JOIN Ms.AT.AT_CRAW_Dmtemp mt
ON mt.[SRID] = t.[RID]
</code>```

So can anyone suggest me on how to do this?

答:
```<code>select
'UPDATE  mt
SET ' + ID_F + ' = ac.' + ID_F + '
FROM Ms.AT.AT_CRAW t
INNER JOIN ' + M_Type + ' ac ON t.' + SF1 + '=SV1
AND ac.ID = 1
INNER JOIN Ms.AT.AT_CRAW_Dmtemp mt
ON mt.[SRID] = t.[RID]' as SQL
from Col.TMap.T_Mp
</code>```

Title: How to Build Dynamic SQl for this?

Body:
I have to create a Procedure with dynamic SQL and generate the Update Statements.

I have tables

Col.TMap.T_Mp

 ID   M_Type  ID_F     SF1      SF2
  1   Acc     ACC_ID   AC_ID    NULL
  1   STA     STA_ID   ST_ID    NULL
  1   CHa     Cha_ID   CH_ID    NULL

ACC

ID    AC_ID   SV1   SV2     SO1    SO2
1     12      6     NULL    =      NULL

STA

ID     STA_ID      SV1     SV2      SO1    SO2
1      1           Open    NULL     =      NULL
1      2           CLosed  NULL     =      NULL

CHa

ID    CHa_ID    SV1    SV2    SO1    SO2
1     1         PH     NULL   =      NULL
1     2         EM     NULL   =      NULL

I need to update Ms.AT.AT_CRAW_Dmtemp table with ACC_ID,STA_ID and CHA_ID from the above tables:

The out put should be:

UPDATE  mt
SET ACC_ID = ac.ACC_ID
FROM Ms.AT.AT_CRAW t
INNER JOIN Acc ac ON t.AC_ID=SV1
AND ac.ID = 1
INNER JOIN Ms.AT.AT_CRAW_Dmtemp mt
ON mt.[SRID] = t.[RID]

UPDATE  mt
SET STA_ID = ac.STA_ID
FROM Ms.AT.AT_CRAW t
INNER JOIN STA ac ON t.ST_ID=SV1
AND ac.ID = 1
INNER JOIN Ms.AT.AT_CRAW_Dmtemp mt
ON mt.[SRID] = t.[RID]

UPDATE  mt
SET CHa_ID = ac.CHa_ID
FROM Ms.AT.AT_CRAW t
INNER JOIN CHa ac ON t.CH_ID=SV1
AND ac.ID = 1
INNER JOIN Ms.AT.AT_CRAW_Dmtemp mt
ON mt.[SRID] = t.[RID]

So can anyone suggest me on how to do this?