问:
iPython debugger raises `NameError: name ... is not defined`
I can't understand the following exception that is raised in this Python debugger session:

```<code>(Pdb) p [move for move in move_values if move[0] == max_value]
*** NameError: name 'max_value' is not defined
(Pdb) [move for move in move_values]
[(0.5, (0, 0)), (0.5, (0, 1)), (0.5, (0, 2)), (0.5, (1, 0)), (0.5, (1, 1)), (0.5, (1, 2)), (0.5, (2, 0)), (0.5, (2, 1)), (0.5, (2, 2))]
(Pdb) max_value
0.5
(Pdb) (0.5, (0, 2))[0] == max_value
True
(Pdb) [move for move in move_values if move[0] == 0.5]
[(0.5, (0, 0)), (0.5, (0, 1)), (0.5, (0, 2)), (0.5, (1, 0)), (0.5, (1, 1)), (0.5, (1, 2)), (0.5, (2, 0)), (0.5, (2, 1)), (0.5, (2, 2))]
(Pdb) [move for move in move_values if move[0] == max_value]
*** NameError: name 'max_value' is not defined
</code>```

Why is it sometimes telling me max_value is not defined and other times not?

Incidentally, this is the code immediately prior to the debugger starting:

```<code>max_value = max(move_values)[0]
best_moves = [move for move in move_values if move[0] == max_value]
import pdb; pdb.set_trace()
</code>```

I am using Python 3.6 running in PyCharm.

AMENDED UPDATE:

After more testing it appears that local variables are not visible within list comprehensions within a pdb session when I do the following from an iPython REPL or in PyCharm:

```<code>$ ipython
Python 3.6.5 | packaged by conda-forge | (default, Apr  6 2018, 13:44:09)
Type 'copyright', 'credits' or 'license' for more information
IPython 6.4.0 -- An enhanced Interactive Python. Type '?' for help.

In [1]: import pdb; pdb.set_trace()
--Call--
> /Users/billtubbs/anaconda/envs/py36/lib/python3.6/site-packages/IPython/core/displayhook.py(247)__call__()
-> def __call__(self, result=None):
(Pdb) x = 1; [x for i in range(3)]
*** NameError: name 'x' is not defined
</code>```

But in a regular Python REPL it works:

```<code>$ python
Python 3.6.5 | packaged by conda-forge | (default, Apr  6 2018, 13:44:09)
[GCC 4.2.1 Compatible Apple LLVM 6.1.0 (clang-602.0.53)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import pdb; pdb.set_trace()
--Return--
> <stdin>(1)<module>()->None
(Pdb) x = 1; [x for i in range(3)]
[1, 1, 1]
</code>```

I tested above with versions 3.4, 3.5, 3.6 so it does not appear to be version dependent.

UPDATE 2

Please note, the above test ('AMENDED UPDATE') is problematic because it uses import pdb; pdb.set_trace() in the interactive REPL.

Also, the original problem is not limited to iPython.

See answer by user2357112 below for a comprehensive explanation of what is going on here.

Sorry if I caused any confusion!

答:
Inspired by Kobi T's answer, if you want the workaround to apply without manual intervention every time this problem comes up, you can subclass TerminalPdb (ipython's debugger, but it should also work by subclassing Pdb). The key is extending TerminalPdb's (really, Pdb's, as it's inherited) default method. The default method is the one called whenever you run a line of code from Pdb's debugger prompt.

As user2357112-supports-monica's answer described well, this function uses exec to run the code, and typically captures any errors raised and prints them out instead of raising them. You can make use of that fact that for the particular problem of list comprehensions (and closures more generally) that appears here, a NameError gets raised. Specifically, if that's the raised error you can intercede to apply Kobi T's workaround (a version of globals().update(locals())), and then exec the code again--if the NameError was raised because of the closure problem described here, the code should now run with no errors; if not, the NameError will get raised again and the output will be as expected for that error.

An added benefit here relates to how globals are handled. For the purposes of the code run by exec, the global/local variables it sees can be explicitly defined as inputs to exec. As a result, instead of updating the workspace's globals(), you can update just the copy that gets sent to exec, keeping your workspace a little less affected when you want to run these list comprehensions.

```<code>import sys
import traceback
from IPython.terminal.debugger import TerminalPdb

class LcTerminalPdb(TerminalPdb):
    # the default method is what runs code written to the prompt of the debugger
    def default(self, line):
        # most of this method directly copies the original one, but there's no
        # good way to add the NameError handling separately from the original
        # code
        if line[:1] == '!': line = line[1:]
        locals = self.curframe_locals
        globals = self.curframe.f_globals
        try:
            code = compile(line + '\n', '<stdin>', 'single')
            save_stdout = sys.stdout
            save_stdin = sys.stdin
            save_displayhook = sys.displayhook
            try:
                sys.stdin = self.stdin
                sys.stdout = self.stdout
                sys.displayhook = self.displayhook
                exec(code, globals, locals)
            ''' BELOW IS THE CODE ADDED TO Pdb's default()'''
            except NameError:
                # NameError occurs when a list comprehension requires variables
                # to be bound in its closure, but isn't able to because of how
                # exec handles local variables; putting the variable in the
                # global dictionary works, and this code takes the sledgehammer
                # approach of assigning *all* locals to globals, so we don't
                # have to be picky about which variable exactly was needed
                try:
                    tempGlobal = globals.copy()
                    tempGlobal.update(locals)
                    exec(code, tempGlobal, locals)
                except:
                    raise
            '''ABOVE IS THE CODE ADDED TO Pdb's default()'''
            finally:
                sys.stdout = save_stdout
                sys.stdin = save_stdin
                sys.displayhook = save_displayhook
        except:
            self._error_exc()

    # TerminalPdb doesn't directly call _error_exc, which was originally defined
    # in Pdb, so we can't import it from there, and it's underscored, so it
    # isn't immediately accessible from TerminalPdb's parent Pdb. However, it's
    # a simple function so I'm just replicating it here.
    def _error_exc(self):
        exc_info = sys.exc_info()[:2]
        self.error(traceback.format_exception_only(*exc_info)[-1].strip())
</code>```

Here's the result we want:

```<code>>> import pdb; pdb.set_trace()
(Pdb) x=5;[x for i in range(3)]
*** NameError: name 'x' is not defined
(Pdb) q
>> import LcTerminalPdb; LcTerminalPdb.set_trace()
ipdb> x=5;[x for i in range(3)]
[5, 5, 5]
</code>```

This solution will work if you call LcTerminalPdb.set_trace(). Alternatively, you can save this as a module on the Python path, in that module define a set_trace method that calls LcTerminalPdb.set_trace() (below) and then set the PYTHONBREAKPOINT environment variable to point to it.

```<code>[appended to file with class code from above]
def set_trace(frame=None):
    """
    Start debugging from `frame`.
    If frame is not specified, debugging starts from caller's frame.
    """
    LcTerminalPdb().set_trace(frame or sys._getframe().f_back)
</code>```

I made a quick LcTerminalPdb git repo with this file and instructions on how to get that part working for anyone interested.

Body:
I can't understand the following exception that is raised in this Python debugger session:

(Pdb) p [move for move in move_values if move[0] == max_value]
*** NameError: name 'max_value' is not defined
(Pdb) [move for move in move_values]
[(0.5, (0, 0)), (0.5, (0, 1)), (0.5, (0, 2)), (0.5, (1, 0)), (0.5, (1, 1)), (0.5, (1, 2)), (0.5, (2, 0)), (0.5, (2, 1)), (0.5, (2, 2))]
(Pdb) max_value
0.5
(Pdb) (0.5, (0, 2))[0] == max_value
True
(Pdb) [move for move in move_values if move[0] == 0.5]
[(0.5, (0, 0)), (0.5, (0, 1)), (0.5, (0, 2)), (0.5, (1, 0)), (0.5, (1, 1)), (0.5, (1, 2)), (0.5, (2, 0)), (0.5, (2, 1)), (0.5, (2, 2))]
(Pdb) [move for move in move_values if move[0] == max_value]
*** NameError: name 'max_value' is not defined

Why is it sometimes telling me max_value is not defined and other times not?

Incidentally, this is the code immediately prior to the debugger starting:

max_value = max(move_values)[0]
best_moves = [move for move in move_values if move[0] == max_value]
import pdb; pdb.set_trace()

I am using Python 3.6 running in PyCharm.

AMENDED UPDATE:

After more testing it appears that local variables are not visible within list comprehensions within a pdb session when I do the following from an iPython REPL or in PyCharm:

$ ipython
Python 3.6.5 | packaged by conda-forge | (default, Apr  6 2018, 13:44:09)
Type 'copyright', 'credits' or 'license' for more information
IPython 6.4.0 -- An enhanced Interactive Python. Type '?' for help.

In [1]: import pdb; pdb.set_trace()
--Call--
> /Users/billtubbs/anaconda/envs/py36/lib/python3.6/site-packages/IPython/core/displayhook.py(247)__call__()
-> def __call__(self, result=None):
(Pdb) x = 1; [x for i in range(3)]
*** NameError: name 'x' is not defined

But in a regular Python REPL it works:

$ python
Python 3.6.5 | packaged by conda-forge | (default, Apr  6 2018, 13:44:09)
[GCC 4.2.1 Compatible Apple LLVM 6.1.0 (clang-602.0.53)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import pdb; pdb.set_trace()
--Return--
> <stdin>(1)<module>()->None
(Pdb) x = 1; [x for i in range(3)]
[1, 1, 1]

I tested above with versions 3.4, 3.5, 3.6 so it does not appear to be version dependent.

UPDATE 2

Please note, the above test ('AMENDED UPDATE') is problematic because it uses import pdb; pdb.set_trace() in the interactive REPL.

Also, the original problem is not limited to iPython.

See answer by user2357112 below for a comprehensive explanation of what is going on here.

Sorry if I caused any confusion!

Body:
Inspired by Kobi T's answer, if you want the workaround to apply without manual intervention every time this problem comes up, you can subclass TerminalPdb (ipython's debugger, but it should also work by subclassing Pdb). The key is extending TerminalPdb's (really, Pdb's, as it's inherited) default method. The default method is the one called whenever you run a line of code from Pdb's debugger prompt.

As user2357112-supports-monica's answer described well, this function uses exec to run the code, and typically captures any errors raised and prints them out instead of raising them. You can make use of that fact that for the particular problem of list comprehensions (and closures more generally) that appears here, a NameError gets raised. Specifically, if that's the raised error you can intercede to apply Kobi T's workaround (a version of globals().update(locals())), and then exec the code again--if the NameError was raised because of the closure problem described here, the code should now run with no errors; if not, the NameError will get raised again and the output will be as expected for that error.

An added benefit here relates to how globals are handled. For the purposes of the code run by exec, the global/local variables it sees can be explicitly defined as inputs to exec. As a result, instead of updating the workspace's globals(), you can update just the copy that gets sent to exec, keeping your workspace a little less affected when you want to run these list comprehensions.

import sys
import traceback
from IPython.terminal.debugger import TerminalPdb

class LcTerminalPdb(TerminalPdb):
    # the default method is what runs code written to the prompt of the debugger
    def default(self, line):
        # most of this method directly copies the original one, but there's no
        # good way to add the NameError handling separately from the original
        # code
        if line[:1] == '!': line = line[1:]
        locals = self.curframe_locals
        globals = self.curframe.f_globals
        try:
            code = compile(line + '\n', '<stdin>', 'single')
            save_stdout = sys.stdout
            save_stdin = sys.stdin
            save_displayhook = sys.displayhook
            try:
                sys.stdin = self.stdin
                sys.stdout = self.stdout
                sys.displayhook = self.displayhook
                exec(code, globals, locals)
            ''' BELOW IS THE CODE ADDED TO Pdb's default()'''
            except NameError:
                # NameError occurs when a list comprehension requires variables
                # to be bound in its closure, but isn't able to because of how
                # exec handles local variables; putting the variable in the
                # global dictionary works, and this code takes the sledgehammer
                # approach of assigning *all* locals to globals, so we don't
                # have to be picky about which variable exactly was needed
                try:
                    tempGlobal = globals.copy()
                    tempGlobal.update(locals)
                    exec(code, tempGlobal, locals)
                except:
                    raise
            '''ABOVE IS THE CODE ADDED TO Pdb's default()'''
            finally:
                sys.stdout = save_stdout
                sys.stdin = save_stdin
                sys.displayhook = save_displayhook
        except:
            self._error_exc()

    # TerminalPdb doesn't directly call _error_exc, which was originally defined
    # in Pdb, so we can't import it from there, and it's underscored, so it
    # isn't immediately accessible from TerminalPdb's parent Pdb. However, it's
    # a simple function so I'm just replicating it here.
    def _error_exc(self):
        exc_info = sys.exc_info()[:2]
        self.error(traceback.format_exception_only(*exc_info)[-1].strip())

Here's the result we want:

>> import pdb; pdb.set_trace()
(Pdb) x=5;[x for i in range(3)]
*** NameError: name 'x' is not defined
(Pdb) q
>> import LcTerminalPdb; LcTerminalPdb.set_trace()
ipdb> x=5;[x for i in range(3)]
[5, 5, 5]

This solution will work if you call LcTerminalPdb.set_trace(). Alternatively, you can save this as a module on the Python path, in that module define a set_trace method that calls LcTerminalPdb.set_trace() (below) and then set the PYTHONBREAKPOINT environment variable to point to it.

[appended to file with class code from above]
def set_trace(frame=None):
    """
    Start debugging from `frame`.
    If frame is not specified, debugging starts from caller's frame.
    """
    LcTerminalPdb().set_trace(frame or sys._getframe().f_back)

I made a quick LcTerminalPdb git repo with this file and instructions on how to get that part working for anyone interested.


来源: stackexchange

问:
I want to detect messages sent by a specific user. (discrd.py on message)
I want to check the number of messages sent by a specific user when sec is 0. If the number of messages sent by the user is 0, it tries to delete the channel.</p>
```<code>        while (sec != 0 ):
            sec = sec-1
            await asyncio.sleep(1)
            print(sec)
            if sec == 30:
                await a.send(f'{message.author.mention}')
            if sec == 0:
                await a.delete()
                await message.author.send('f')
</code>```

答:
To check the number of messages sent by a user you would utilize the channel history like this:

msgcount = 0
channel = ctx.guild.get_channel(channel_id)
messages = await channel.history(limit = None).flatten()
for message in messages:
   if user == message.author:
      msgcount += 1
```

This will count all messages by that user, in the designated channel and store in msgcount. You can replace the limit of None with any number of max messages you would like to loop through. Depending on the total messages in the channel, for instance if it has over 10,000 this can take a while to loop through.

If you do not need the history, and would like to do for only new messages after a starting point it would be better to use: async def on_message(message): to keep track of the messages and you can set an if statement to only monitor certain channels or certain users. After whatever trigger you're using to start checking before X time, you can use a similar if statement and counter.

ContentLicense: CC BY-SA 4.0

Body:
I want to check the number of messages sent by a specific user when sec is 0. If the number of messages sent by the user is 0, it tries to delete the channel.

        while (sec != 0 ):
            sec = sec-1
            await asyncio.sleep(1)
            print(sec)
            if sec == 30:
                await a.send(f'{message.author.mention}')
            if sec == 0:
                await a.delete()
                await message.author.send('f')

Body:
To check the number of messages sent by a user you would utilize the channel history like this:

msgcount = 0
channel = ctx.guild.get_channel(channel_id)
messages = await channel.history(limit = None).flatten()
for message in messages:
   if user == message.author:
      msgcount += 1

This will count all messages by that user, in the designated channel and store in msgcount. You can replace the limit of None with any number of max messages you would like to loop through. Depending on the total messages in the channel, for instance if it has over 10,000 this can take a while to loop through.

If you do not need the history, and would like to do for only new messages after a starting point it would be better to use: async def on_message(message): to keep track of the messages and you can set an if statement to only monitor certain channels or certain users. After whatever trigger you're using to start checking before X time, you can use a similar if statement and counter.


问:
Count date range based on criteria
Let´s suppose I have generated a report with dates (day/month/year) when soccer teams won titles. This is how the report is going to look like:

Area
Team
Champions League
Europe    League

England
Chelsea
27/01/2021
15/01/2021

Spain
Real Madri
27/02/2021
20/01/2021

Spain
Barcelona

18/02/2021

France
PSG
27/03/2021
27/02/2021

My objective here is going to count how many titles each area won per month. So, this is how my desired output looks like:

Area
January
February
March

England
2

Spain
1
2

France

1
1

What I tried to do was the following (for January and England):

```<code>=COUNTIFS(Table[[#All],[Champions League]:[Europe League]],">01/01/2021",Table[[#All],[Champions League]:[Europe League]],"<31/01/2022",Table[[#All],[Area]],"=England")
</code>```

However, my output using this formula is "#VALUE!". Can you please help trying to figure out what I am doing wrong?

答:
You may try something like this as shown in image below, so I have used the incredibly versatile SUMPRODUCT Function to achieve the expected output

Formula used in cell B8 Fill Down & Fill Right

```<code>=SUMPRODUCT(($A8=$A$2:$A$5)*(B$7=TEXT($C$2:$D$5,"mmmm"))*($C$2:$D$5<>""))
</code>```

To hide the zeros, you may custom format the cells by pressing CTRL 1 --> Format Cells --> Number Tab --> Category --> Custom --> Type --> 0;;

EDIT

Approach Using Power Query

```<code>let
    Source = Excel.CurrentWorkbook(){[Name="Table39"]}[Content],
    #"Changed Type" = Table.TransformColumnTypes(Source,{{"Area", type text}, {"Team", type text}, {"Champions League", type date}, {"Europe League", type date}}),
    #"Unpivoted Other Columns" = Table.UnpivotOtherColumns(#"Changed Type", {"Area", "Team"}, "Attribute", "Value"),
    #"Extracted Month Name" = Table.TransformColumns(#"Unpivoted Other Columns", {{"Value", each Date.MonthName(_), type text}}),
    #"Grouped Rows" = Table.Group(#"Extracted Month Name", {"Area"}, {{"All", each _, type table [Area=nullable text, Team=nullable text, Attribute=text, Value=text]}}),
    #"Added Custom" = Table.AddColumn(#"Grouped Rows", "Custom", each Table.AddIndexColumn([All],"Index",1,1)),
    #"Expanded Custom" = Table.ExpandTableColumn(#"Added Custom", "Custom", {"Value", "Index"}, {"Value", "Index"}),
    #"Removed Columns" = Table.RemoveColumns(#"Expanded Custom",{"All"}),
    #"Pivoted Column" = Table.Pivot(#"Removed Columns", List.Distinct(#"Removed Columns"[Value]), "Value", "Index", List.NonNullCount)
in
    #"Pivoted Column"
</code>```

Using Power Query will be dynamic, one time operation and every time add new data to the original source the imported table from Power Query gets updated within few by a single refresh, please follow the steps

• First select any cell within the range,

• Then from Data Tab under Get & Transform Data, Click From Table/Range,

• A pop up shall appear, check mark the My table has headers and press Ok

• Data gets loaded into Power Query Editor

• Change the name of the table from Query Settings in the right hand under Properties with CountTbl

• Now select any column and press CTRL A

• If the Changed Type Step is already showing in Applied steps then you don't have to follow this, please goto the next step

From Transform Tab --> Click Detect Data Type

• Now you will find the dates are still showing as Time Stamps therefore select both Champions League & Europa League Columns and from Transform Tab --> Click Data Type from Any to Date only, you shall get a message asking whether to Replace the current step or to add new step, you need to select the Replace

• Well data types changed, now select the Area and Team Columns and press Right Click Unpivot Other Columns also you may find the option from Transform Tab --> Unpivot Columns dropdown and select Unpivot Other Columns

• Next, select the Value column showing dates --> Goto Transform Tab --> From Date & Time Column Group --> Click Date --> Month --> Name Of Month

• Again select the Area Column --> From Transform Tab --> Group By --> Give any fancy name to the New Column Name --> Operation --> All Rows and press OK

• Now goto Add Column Tab --> Click Custom Column and enter this following Formula or the M-Code in custom column formula space

```<code>Table.AddIndexColumn([All],"Index",1,1)
</code>```

press Ok

• So from the custom column newly created, click on the dropdown, and uncheck the box use original column name as prefix and select the columns Value and Index and press Ok

• Remove the column which we created by Group i.e. All --> Select the column and press delete key from your keyboard

• Now select the value column which will be showing the month name and goto Transform Tab and click Pivot Column

• There Values Column needs to be Index and in Advanced Options you to select Count (Not Blank) and press OK

• You shall see the expected output has been achieved!!!

• From Home Tab Click Close & Load To --> Import Data --> Table --> You can either select Existing Worksheet (enter the cell reference where you want to place the imported table) or New Worksheet and press Ok

IMPORT DATA

• Done Full_Explanation Power_Query

Title: Count date range based on criteria

Body:
Let´s suppose I have generated a report with dates (day/month/year) when soccer teams won titles. This is how the report is going to look like:

Area
Team
Champions League
Europe    League

England
Chelsea
27/01/2021
15/01/2021

Spain
Real Madri
27/02/2021
20/01/2021

Spain
Barcelona

18/02/2021

France
PSG
27/03/2021
27/02/2021

My objective here is going to count how many titles each area won per month. So, this is how my desired output looks like:

Area
January
February
March

England
2

Spain
1
2

France

1
1

What I tried to do was the following (for January and England):

=COUNTIFS(Table[[#All],[Champions League]:[Europe League]],">01/01/2021",Table[[#All],[Champions League]:[Europe League]],"<31/01/2022",Table[[#All],[Area]],"=England")

However, my output using this formula is "#VALUE!". Can you please help trying to figure out what I am doing wrong?

Body:
You may try something like this as shown in image below, so I have used the incredibly versatile SUMPRODUCT Function to achieve the expected output

Formula used in cell B8 Fill Down & Fill Right

=SUMPRODUCT(($A8=$A$2:$A$5)*(B$7=TEXT($C$2:$D$5,"mmmm"))*($C$2:$D$5<>""))

To hide the zeros, you may custom format the cells by pressing CTRL 1 --> Format Cells --> Number Tab --> Category --> Custom --> Type --> 0;;

EDIT

Approach Using Power Query

let
    Source = Excel.CurrentWorkbook(){[Name="Table39"]}[Content],
    #"Changed Type" = Table.TransformColumnTypes(Source,{{"Area", type text}, {"Team", type text}, {"Champions League", type date}, {"Europe League", type date}}),
    #"Unpivoted Other Columns" = Table.UnpivotOtherColumns(#"Changed Type", {"Area", "Team"}, "Attribute", "Value"),
    #"Extracted Month Name" = Table.TransformColumns(#"Unpivoted Other Columns", {{"Value", each Date.MonthName(_), type text}}),
    #"Grouped Rows" = Table.Group(#"Extracted Month Name", {"Area"}, {{"All", each _, type table [Area=nullable text, Team=nullable text, Attribute=text, Value=text]}}),
    #"Added Custom" = Table.AddColumn(#"Grouped Rows", "Custom", each Table.AddIndexColumn([All],"Index",1,1)),
    #"Expanded Custom" = Table.ExpandTableColumn(#"Added Custom", "Custom", {"Value", "Index"}, {"Value", "Index"}),
    #"Removed Columns" = Table.RemoveColumns(#"Expanded Custom",{"All"}),
    #"Pivoted Column" = Table.Pivot(#"Removed Columns", List.Distinct(#"Removed Columns"[Value]), "Value", "Index", List.NonNullCount)
in
    #"Pivoted Column"

Using Power Query will be dynamic, one time operation and every time add new data to the original source the imported table from Power Query gets updated within few by a single refresh, please follow the steps

• First select any cell within the range,

• Then from Data Tab under Get & Transform Data, Click From Table/Range,

• A pop up shall appear, check mark the My table has headers and press Ok

• Data gets loaded into Power Query Editor

• Change the name of the table from Query Settings in the right hand under Properties with CountTbl

• Now select any column and press CTRL A

• If the Changed Type Step is already showing in Applied steps then you don't have to follow this, please goto the next step

From Transform Tab --> Click Detect Data Type

• Now you will find the dates are still showing as Time Stamps therefore select both Champions League & Europa League Columns and from Transform Tab --> Click Data Type from Any to Date only, you shall get a message asking whether to Replace the current step or to add new step, you need to select the Replace

• Well data types changed, now select the Area and Team Columns and press Right Click Unpivot Other Columns also you may find the option from Transform Tab --> Unpivot Columns dropdown and select Unpivot Other Columns

• Next, select the Value column showing dates --> Goto Transform Tab --> From Date & Time Column Group --> Click Date --> Month --> Name Of Month

• Again select the Area Column --> From Transform Tab --> Group By --> Give any fancy name to the New Column Name --> Operation --> All Rows and press OK

• Now goto Add Column Tab --> Click Custom Column and enter this following Formula or the M-Code in custom column formula space

Table.AddIndexColumn([All],"Index",1,1)

press Ok

• So from the custom column newly created, click on the dropdown, and uncheck the box use original column name as prefix and select the columns Value and Index and press Ok

• Remove the column which we created by Group i.e. All --> Select the column and press delete key from your keyboard

• Now select the value column which will be showing the month name and goto Transform Tab and click Pivot Column

• There Values Column needs to be Index and in Advanced Options you to select Count (Not Blank) and press OK

• You shall see the expected output has been achieved!!!

• From Home Tab Click Close & Load To --> Import Data --> Table --> You can either select Existing Worksheet (enter the cell reference where you want to place the imported table) or New Worksheet and press Ok

IMPORT DATA

• Done Full_Explanation Power_Query


问:
How can I add a clickable link to my collapsable sidebar menu without breaking my code?
Currently trying to make a sidebar on HTML/CSS however I am struggling to finalise it by adding clickable links for navigating around my site.

I believe it is a simple CSS issue or a simple HTML problem but it's driving me crazy!

```<code><li class="c-menu__item has-submenu" title="Account">
    <div class="c-menu__item__inner"><i class="fa fa-cog"></i>
         <div class="c-menu-item__title">
             <a href="accountdetails.php"
                style="text-decoration: none"><span>Account Settings</span></div></a>
         </div>
</code>```

Is what I have at the moment but there are two problems, I cannot click the button when the sidebar is collapsed, nor can I click the div the text/icon are present in, I must only click the text to get it to work.

Preferably I would like to click the box the icon, text are held in for easier usage.

How can I achieve this instead of just text being hyperlinked?

Photo showing the area I would like clickable on sidebar opposed to just the text

答:
I see you closed
 before a tag, But your a tag start just before your span tag.

Hence you need to close a tag before
 like these:-

```<code><li class="c-menu__item has-submenu" title="Account">
    <div class="c-menu__item__inner"><i class="fa fa-cog"></i>
         <div class="c-menu-item__title">
             <a href="accountdetails.php" style="text-decoration: none">
                  <span>Account Settings</span>
             </a>
         </div>
    </div>
</li>
</code>```

Now, you don't want to show that your text is hyperlinked, in that case, you can use text-decoration: none; to solve your issue.

Body:
Currently trying to make a sidebar on HTML/CSS however I am struggling to finalise it by adding clickable links for navigating around my site.

I believe it is a simple CSS issue or a simple HTML problem but it's driving me crazy!

             Account Settings

Is what I have at the moment but there are two problems, I cannot click the button when the sidebar is collapsed, nor can I click the div the text/icon are present in, I must only click the text to get it to work.

Preferably I would like to click the box the icon, text are held in for easier usage.

How can I achieve this instead of just text being hyperlinked?

Photo showing the area I would like clickable on sidebar opposed to just the text

Body:
I see you closed </div> before a tag, But your a tag start just before your span tag.

Hence you need to close a tag before </div> like these:-

<li class="c-menu__item has-submenu" title="Account">
    <div class="c-menu__item__inner"><i class="fa fa-cog"></i>
         <div class="c-menu-item__title">
             <a href="accountdetails.php" style="text-decoration: none">
                  <span>Account Settings</span>
             </a>
         </div>
    </div>
</li>

Now, you don't want to show that your text is hyperlinked, in that case, you can use text-decoration: none; to solve your issue.


问:
VS Code "Show Search" View is shown as "Source Control"
When I do "Ctrl + Shift + f", the "Show Search" View is displayed but the icon on the Activity Bar show it as Source Control and at the top of the "Show Search" View, the Source Control Repository is being displayed. I have disabled all extensions and look around for a settings that I might messed up but cannot find anything.

Does anyone know how to get the Search icon back for the Show Search View and remove the Source Control repository section from the Search View?

VS Code version is 1.64

答:
You must have the dragged Search into the SCM View.

To reset it, from the Command Palette:

View: Reset View Locations


问:
Javascript change event on input element fires on only losing focus
I have an input element and I want to keep checking the length of the contents and whenever the length becomes equal to a particular size, I want to enable the submit button, but I am facing a problem with the onchange event of Javascript as the event fires only when the input element goes out of scope and not when the contents change.

```<code><input type="text" id="name" onchange="checkLength(this.value)" />
</code>```

----onchange does not fire on changing contents of name, but only fires when name goes out of focus.

Is there something I can do to make this event work on content change? or some other event I can use for this?
I found a workaround by using the onkeyup function, but that does not fire when we select some content from the auto completer of the browser.

I want something which can work when the content of the field change whether by keyboard or by mouse... any ideas?

答:
Do it the jQuery way:</p>

```<code><input type="text" id="name" name="name"/>

$('#name').keyup(function() {
  alert('Content length has changed to: '+$(this).val().length);
});
</code>```

Body:
I have an input element and I want to keep checking the length of the contents and whenever the length becomes equal to a particular size, I want to enable the submit button, but I am facing a problem with the onchange event of Javascript as the event fires only when the input element goes out of scope and not when the contents change.

<input type="text" id="name" onchange="checkLength(this.value)" />

----onchange does not fire on changing contents of name, but only fires when name goes out of focus.

Is there something I can do to make this event work on content change? or some other event I can use for this?
I found a workaround by using the onkeyup function, but that does not fire when we select some content from the auto completer of the browser.

I want something which can work when the content of the field change whether by keyboard or by mouse... any ideas?

Body:
Do it the jQuery way:

<input type="text" id="name" name="name"/>

$('#name').keyup(function() {
  alert('Content length has changed to: '+$(this).val().length);
});

ContentLicense: CC BY-SA 3.0


问:
Returning array like json with Fiber, Golang
I have a table with columns token, user_id and last_seen in my databse

The task is to send all of them with my app when it gets a get request

Fiber, Golang:

```<code>    type sessionsInfo struct {
        token           string
        user_id         int
        last_seen       string
    }
    app.Get("/testA", func(c *fiber.Ctx) error {
        logMsg("GET /testA")
        var sessions sessionsInfo
        execQuery := `select * from sessions`
        rows, err := db.Query(execQuery)
        if err != nil {
            fmt.Println(err)
            return c.SendStatus(418)
        }
        var sessionsArray []sessionsInfo
        for rows.Next(){
            rows.Scan(
                &sessions.token,
                &sessions.user_id,
                &sessions.last_seen,
            )
            sessionsArray = append(sessionsArray, sessions)
        }
        defer rows.Close()
        fmt.Println(sessionsArray)
        c.JSON(sessionsArray)
        return c.SendStatus(200)
    })
</code>```

The strange thing is that i see correct array in console, matching 100% my data in DB

```<code>[2021-11-04 15:50:31] GET /testA
[{be0e6163-ce2c-4ac3-5349-ff3b34a51c37 1 2021-10-21T17:50:42.308751Z}
 {6c4f21f1-dc00-4975-6fe2-c69d14328099 2 2021-10-21T17:51:27.963031Z}
 {824012ec-07d1-4732-63a1-7b1c99261c6d 3 2021-10-21T21:29:23.95517Z}
 {a13b67d8-370c-49d2-72da-21fd02081711 4 2021-10-22T07:45:43.539265Z}
 {ebb8fdfc-923b-4d8d-6988-781c71c17dbe 5 2021-10-26T08:48:50.12082Z}
 {212909aa-70c9-4f50-553c-0f503e65fa7b 6 2021-10-26T08:49:56.880621Z}
 {132fbbd0-5c81-4278-4e39-ed933872d58e 7 2021-10-26T10:07:26.221177Z}
 {753f278c-9a9f-4bd5-5a9c-dc4a14b6bc81 7 2021-10-26T11:11:34.955218Z}
 {c32dea1d-230c-4caa-50a8-0cb2bd97d562 7 2021-10-26T11:11:38.723956Z}
 {ea2a87e5-6140-40a2-6641-69e85c0fef34 7 2021-10-26T11:11:39.417712Z}
 {4fe4958a-ebfb-4c5e-61b0-5c6e7e9666b4 7 2021-10-26T11:11:40.018127Z}
 {feb7c3f0-26b0-47f9-63e1-d261e3093f30 7 2021-10-26T11:17:28.634217Z}
 {2a484f33-9b61-4ef1-7987-78aa07f6f6ff 7 2021-10-26T11:17:47.73872Z}
 {c9dbfe03-1435-4cae-67f9-1c0a010c14b6 7 2021-10-26T11:18:02.7325Z}
 {c866ca0c-0e16-486e-79cf-0a4b1b30c6ef 7 2021-10-26T11:18:03.160044Z}
 {aafc6dfc-0b91-41fa-6ebc-29053c097570 7 2021-10-26T11:18:03.680851Z}
 {d3325e13-7ec3-478b-6eb8-3b609440b0c8 8 2021-10-29T18:49:21.366545Z}
 {ef473f2e-66a2-4518-6e7e-7b0a21544444 7 2021-10-29T19:01:13.583646Z}
 {3aa6644b-815c-456d-5601-0ec5bb84c532 9 2021-10-29T19:03:53.866348Z}
 {6b8ecbea-dccf-4b90-4dd1-e5ca6f589560 10 2021-10-29T19:04:46.824083Z}
 {a39567bc-4001-4e50-45ff-638c08d4cb09 10 2021-10-29T19:12:30.415509Z}
 {e9a80c87-9d4f-4582-413f-f56210d313fd 10 2021-10-29T19:13:02.469866Z}
 {d9d15614-aeb1-4c74-75b2-b9f3f6fed9d2 11 2021-10-29T20:36:18.883786Z}
 {6398683b-94fa-4a7c-53a3-849084565ab7 11 2021-10-29T20:36:48.724322Z}
 {bed2a9fe-7288-41be-5786-0aa3710a4e22 11 2021-10-29T20:37:23.696741Z}]
</code>```

but with some reason when i look at answer's body i see json that has 25 empty sub-jsons (i dunno how to name it correctly, lmao), like this

```<code>[
    {},
    {},
    {},
    {},
    {},
    {},
    {},
    {},
    {},
    {},
    {},
    {},
    {},
    {},
    {},
    {},
    {},
    {},
    {},
    {},
    {},
    {},
    {},
    {},
    {}
]
</code>```

The same count as it should be, but empty.
The result should be something like this

```<code>[
    {
        "token": "be0e6163-ce2c-4ac3-5349-ff3b34a51c37",
        "id": "1",
        "last_seen": "2021-10-21T17:50:42.308751Z"
    },
    {
        "token": "6c4f21f1-dc00-4975-6fe2-c69d14328099",
        "id": "2",
        "last_seen": "2021-10-21T17:51:27.963031Z"
    }
    ...
    ...
    ...
]
</code>```

How can i fix this? What am i doing wrong?

答:
Export the types:

```<code>type sessionsInfo struct {
    token           string
    user_id         int
    last_seen       string
}
</code>```

To:

```<code>type SessionsInfo struct {
    Token           string `json:"token"`
    User_id         int `json:"user_id"`
    Last_seen       string `json:"last_seen"`
}
</code>```

Body:
I have a table with columns token, user_id and last_seen in my databse

The task is to send all of them with my app when it gets a get request

Fiber, Golang:

    type sessionsInfo struct {
        token           string
        user_id         int
        last_seen       string
    }
    app.Get("/testA", func(c *fiber.Ctx) error {
        logMsg("GET /testA")
        var sessions sessionsInfo
        execQuery := `select * from sessions`
        rows, err := db.Query(execQuery)
        if err != nil {
            fmt.Println(err)
            return c.SendStatus(418)
        }
        var sessionsArray []sessionsInfo
        for rows.Next(){
            rows.Scan(
                &sessions.token,
                &sessions.user_id,
                &sessions.last_seen,
            )
            sessionsArray = append(sessionsArray, sessions)
        }
        defer rows.Close()
        fmt.Println(sessionsArray)
        c.JSON(sessionsArray)
        return c.SendStatus(200)
    })

The strange thing is that i see correct array in console, matching 100% my data in DB

[2021-11-04 15:50:31] GET /testA
[{be0e6163-ce2c-4ac3-5349-ff3b34a51c37 1 2021-10-21T17:50:42.308751Z}
 {6c4f21f1-dc00-4975-6fe2-c69d14328099 2 2021-10-21T17:51:27.963031Z}
 {824012ec-07d1-4732-63a1-7b1c99261c6d 3 2021-10-21T21:29:23.95517Z}
 {a13b67d8-370c-49d2-72da-21fd02081711 4 2021-10-22T07:45:43.539265Z}
 {ebb8fdfc-923b-4d8d-6988-781c71c17dbe 5 2021-10-26T08:48:50.12082Z}
 {212909aa-70c9-4f50-553c-0f503e65fa7b 6 2021-10-26T08:49:56.880621Z}
 {132fbbd0-5c81-4278-4e39-ed933872d58e 7 2021-10-26T10:07:26.221177Z}
 {753f278c-9a9f-4bd5-5a9c-dc4a14b6bc81 7 2021-10-26T11:11:34.955218Z}
 {c32dea1d-230c-4caa-50a8-0cb2bd97d562 7 2021-10-26T11:11:38.723956Z}
 {ea2a87e5-6140-40a2-6641-69e85c0fef34 7 2021-10-26T11:11:39.417712Z}
 {4fe4958a-ebfb-4c5e-61b0-5c6e7e9666b4 7 2021-10-26T11:11:40.018127Z}
 {feb7c3f0-26b0-47f9-63e1-d261e3093f30 7 2021-10-26T11:17:28.634217Z}
 {2a484f33-9b61-4ef1-7987-78aa07f6f6ff 7 2021-10-26T11:17:47.73872Z}
 {c9dbfe03-1435-4cae-67f9-1c0a010c14b6 7 2021-10-26T11:18:02.7325Z}
 {c866ca0c-0e16-486e-79cf-0a4b1b30c6ef 7 2021-10-26T11:18:03.160044Z}
 {aafc6dfc-0b91-41fa-6ebc-29053c097570 7 2021-10-26T11:18:03.680851Z}
 {d3325e13-7ec3-478b-6eb8-3b609440b0c8 8 2021-10-29T18:49:21.366545Z}
 {ef473f2e-66a2-4518-6e7e-7b0a21544444 7 2021-10-29T19:01:13.583646Z}
 {3aa6644b-815c-456d-5601-0ec5bb84c532 9 2021-10-29T19:03:53.866348Z}
 {6b8ecbea-dccf-4b90-4dd1-e5ca6f589560 10 2021-10-29T19:04:46.824083Z}
 {a39567bc-4001-4e50-45ff-638c08d4cb09 10 2021-10-29T19:12:30.415509Z}
 {e9a80c87-9d4f-4582-413f-f56210d313fd 10 2021-10-29T19:13:02.469866Z}
 {d9d15614-aeb1-4c74-75b2-b9f3f6fed9d2 11 2021-10-29T20:36:18.883786Z}
 {6398683b-94fa-4a7c-53a3-849084565ab7 11 2021-10-29T20:36:48.724322Z}
 {bed2a9fe-7288-41be-5786-0aa3710a4e22 11 2021-10-29T20:37:23.696741Z}]

but with some reason when i look at answer's body i see json that has 25 empty sub-jsons (i dunno how to name it correctly, lmao), like this

[
    {},
    {},
    {},
    {},
    {},
    {},
    {},
    {},
    {},
    {},
    {},
    {},
    {},
    {},
    {},
    {},
    {},
    {},
    {},
    {},
    {},
    {},
    {},
    {},
    {}
]

The same count as it should be, but empty.
The result should be something like this

[
    {
        "token": "be0e6163-ce2c-4ac3-5349-ff3b34a51c37",
        "id": "1",
        "last_seen": "2021-10-21T17:50:42.308751Z"
    },
    {
        "token": "6c4f21f1-dc00-4975-6fe2-c69d14328099",
        "id": "2",
        "last_seen": "2021-10-21T17:51:27.963031Z"
    }
    ...
    ...
    ...
]

How can i fix this? What am i doing wrong?

Body:
Export the types:

type sessionsInfo struct {
    token           string
    user_id         int
    last_seen       string
}

To:

type SessionsInfo struct {
    Token           string `json:"token"`
    User_id         int `json:"user_id"`
    Last_seen       string `json:"last_seen"`
}


问:
Pass an include parameter in Pug template from ExpressJS?
I'm new to Pug and ExpressJS and can't figure out how to do a simple thing: passing a template path from Express to Pug.

Here's an example of what I have in mind, with the variable named pageContent :

./app.js

```<code>app.get('/', function (req, res) {
  res.render('index', {title: 'Some Title', pageContent: 'includes/somePage.html'})
})
</code>```

./views/index.pug

```<code>html
  head
    include includes/head.html
    title= title
  body
    include includes/header.html
    include #{pageContent}
    include includes/footer.html
</code>```

Any idea what I am missing ? Thank in advance for your help !

答:
Please ensure you are using:

```<code>app.set('view engine', 'pug')
</code>```

Also, dynamic import is not allowed yet, so your include can't be variables

Body:
I'm new to Pug and ExpressJS and can't figure out how to do a simple thing: passing a template path from Express to Pug.

Here's an example of what I have in mind, with the variable named pageContent :

./app.js

app.get('/', function (req, res) {
  res.render('index', {title: 'Some Title', pageContent: 'includes/somePage.html'})
})

./views/index.pug

html
  head
    include includes/head.html
    title= title
  body
    include includes/header.html
    include #{pageContent}
    include includes/footer.html

Any idea what I am missing ? Thank in advance for your help !

Body:
Please ensure you are using:

app.set('view engine', 'pug')

Also, dynamic import is not allowed yet, so your include can't be variables


问:
Error in deploying PyTorch model using SageMaker Pipeline and RegisterModel
Can anyone provide an example for deploying a pytorch model using SageMaker Pipeline?

I've used the MLOps template (MLOps template for model building, traing and deployment) of SageMaker Studio to build a MLOps project.

The template is using sagemaker pipelines to build a pipeline for preprocessing and training and registering the model.
And deployment script is implemented in the YAML file and employing CloudFormation to run. The deployment script will be triggered automatically when the model is registered.

The template is using xgboost model to train the data and deploy the model. I want to use Pytorch and deploy it.
I successfully replaced the pytorch with xgboost and successfully preprocessed the data, trained the model and registered the model. But I didn't use inference.py in my model. So I get error for the model deployment.

The error log in updating the endpoint is:

```<code>FileNotFoundError: [Errno 2] No such file or directory: '/opt/ml/model/code/inference.py'
</code>```

I tried to find example of using inference.py for pytorch model, but I couldn't find any example which uses sagemaker pipelines and RegisterModel.

Any help would be appreciated.

Below you can see a part of the pipeline for training and registering the model.

```<code>from sagemaker.pytorch.estimator import PyTorch
from sagemaker.workflow.pipeline import Pipeline
from sagemaker.workflow.steps import (
    ProcessingStep,
    TrainingStep,
)
from sagemaker.workflow.step_collections import RegisterModel

pytorch_estimator = PyTorch(entry_point= os.path.join(BASE_DIR, 'train.py'),
                            instance_type= "ml.m5.xlarge",
                            instance_count=1,
                            role=role,
                            framework_version='1.8.0',
                            py_version='py3',
                            hyperparameters = {'epochs': 5, 'batch-size': 64, 'learning-rate': 0.1})

step_train = TrainingStep(
        name="TrainModel",
        estimator=pytorch_estimator,

        inputs={
                "train": sagemaker.TrainingInput(
                            s3_data=step_process.properties.ProcessingOutputConfig.Outputs[
                            "train_data"
                            ].S3Output.S3Uri,
                            content_type="text/csv",
                        ),
                "dev": sagemaker.TrainingInput(
                            s3_data=step_process.properties.ProcessingOutputConfig.Outputs[
                            "dev_data"
                            ].S3Output.S3Uri,
                            content_type="text/csv"
                        ),
                "test": sagemaker.TrainingInput(
                            s3_data=step_process.properties.ProcessingOutputConfig.Outputs[
                            "test_data"
                            ].S3Output.S3Uri,
                            content_type="text/csv"
                        ),
        },
)
step_register = RegisterModel(
            name="RegisterModel",
            estimator=pytorch_estimator,
            model_data=step_train.properties.ModelArtifacts.S3ModelArtifacts,
            content_types=["text/csv"],
            response_types=["text/csv"],
            inference_instances=["ml.t2.medium", "ml.m5.large"],
            transform_instances=["ml.m5.large"],
            model_package_group_name=model_package_group_name,
            approval_status=model_approval_status,
        )

pipeline = Pipeline(
            name=pipeline_name,
            parameters=[
                processing_instance_type,
                processing_instance_count,
                training_instance_type,
                model_approval_status,
                input_data,
            ],
            steps=[step_process, step_train, step_register],
            sagemaker_session=sagemaker_session,
        )
</code>```

答:
PyTorch api is using base pytorch images.
when sagemaker.pytorch.deploy method called, the sagemaker run '/opt/ml/model/code/inference.py'

But in your base image is not have that file.

So if you want to use deploy method, you make 'inference.py' with sagemaker style(can execute in sagemaker container) and build and push image.

And then you can use deploy method!

Here is sample codes
https://sagemaker-workshop.com/custom/containers.html

Body:
Can anyone provide an example for deploying a pytorch model using SageMaker Pipeline?

I've used the MLOps template (MLOps template for model building, traing and deployment) of SageMaker Studio to build a MLOps project.

The template is using sagemaker pipelines to build a pipeline for preprocessing and training and registering the model.
And deployment script is implemented in the YAML file and employing CloudFormation to run. The deployment script will be triggered automatically when the model is registered.

The template is using xgboost model to train the data and deploy the model. I want to use Pytorch and deploy it.
I successfully replaced the pytorch with xgboost and successfully preprocessed the data, trained the model and registered the model. But I didn't use inference.py in my model. So I get error for the model deployment.

The error log in updating the endpoint is:

FileNotFoundError: [Errno 2] No such file or directory: '/opt/ml/model/code/inference.py'

I tried to find example of using inference.py for pytorch model, but I couldn't find any example which uses sagemaker pipelines and RegisterModel.

Any help would be appreciated.

Below you can see a part of the pipeline for training and registering the model.

from sagemaker.pytorch.estimator import PyTorch
from sagemaker.workflow.pipeline import Pipeline
from sagemaker.workflow.steps import (
    ProcessingStep,
    TrainingStep,
)
from sagemaker.workflow.step_collections import RegisterModel

pytorch_estimator = PyTorch(entry_point= os.path.join(BASE_DIR, 'train.py'),
                            instance_type= "ml.m5.xlarge",
                            instance_count=1,
                            role=role,
                            framework_version='1.8.0',
                            py_version='py3',
                            hyperparameters = {'epochs': 5, 'batch-size': 64, 'learning-rate': 0.1})

step_train = TrainingStep(
        name="TrainModel",
        estimator=pytorch_estimator,

        inputs={
                "train": sagemaker.TrainingInput(
                            s3_data=step_process.properties.ProcessingOutputConfig.Outputs[
                            "train_data"
                            ].S3Output.S3Uri,
                            content_type="text/csv",
                        ),
                "dev": sagemaker.TrainingInput(
                            s3_data=step_process.properties.ProcessingOutputConfig.Outputs[
                            "dev_data"
                            ].S3Output.S3Uri,
                            content_type="text/csv"
                        ),
                "test": sagemaker.TrainingInput(
                            s3_data=step_process.properties.ProcessingOutputConfig.Outputs[
                            "test_data"
                            ].S3Output.S3Uri,
                            content_type="text/csv"
                        ),
        },
)
step_register = RegisterModel(
            name="RegisterModel",
            estimator=pytorch_estimator,
            model_data=step_train.properties.ModelArtifacts.S3ModelArtifacts,
            content_types=["text/csv"],
            response_types=["text/csv"],
            inference_instances=["ml.t2.medium", "ml.m5.large"],
            transform_instances=["ml.m5.large"],
            model_package_group_name=model_package_group_name,
            approval_status=model_approval_status,
        )

pipeline = Pipeline(
            name=pipeline_name,
            parameters=[
                processing_instance_type,
                processing_instance_count,
                training_instance_type,
                model_approval_status,
                input_data,
            ],
            steps=[step_process, step_train, step_register],
            sagemaker_session=sagemaker_session,
        )


问:
Validate IP Address
I am trying to validate if the string of numbers is valid IP address or not.

There are mere 2 logics that i am using as shown in code-

The length of ipnos should be 4 after the split('.')

The strings should be numbers only.

But looks like it is NOT giving me correct result.

For ip='123.456.78.09' : It should result True but it returning False

```<code>def validate(ip):
  ipnos=ip.split('.')
  validnos=[0,1,2,3,4,5,6,7,8,9]
  false_counter=0

  if len(ipnos) != 4:
    false_counter+=1

  for sublist in ipnos:
    for nos in range(len(sublist)):
      if sublist[nos] not in validnos:
        false_counter+=1

  if false_counter>0:
    return False
  else:
    return True

ip='123.456.78.09'
validate(ip)
</code>```

答:
The type of sublist[nos] is <class 'str'>, not <class 'int'>.

So, you should change the validnos to next to fix it:

```<code>validnos=['0','1','2','3','4','5','6','7','8','9']
</code>```

Title: Validate IP Address

Body:
I am trying to validate if the string of numbers is valid IP address or not.

There are mere 2 logics that i am using as shown in code-

The length of ipnos should be 4 after the split('.')

The strings should be numbers only.

But looks like it is NOT giving me correct result.

For ip='123.456.78.09' : It should result True but it returning False

def validate(ip):
  ipnos=ip.split('.')
  validnos=[0,1,2,3,4,5,6,7,8,9]
  false_counter=0

  if len(ipnos) != 4:
    false_counter+=1

  for sublist in ipnos:
    for nos in range(len(sublist)):
      if sublist[nos] not in validnos:
        false_counter+=1

  if false_counter>0:
    return False
  else:
    return True

ip='123.456.78.09'
validate(ip)

Body:
The type of sublist[nos] is <class 'str'>, not <class 'int'>.

So, you should change the validnos to next to fix it:

validnos=['0','1','2','3','4','5','6','7','8','9']


问:
Template for documenting Architecture alternatives and decisions
We are putting a process in place where all architecture changes must be documented.

Are there any standard templates for documenting alternatives and decisions?

答: This depends on whether you use a specific architecture framework - most of them come with some sort of templates. If you don't use any, I would recommend the SPAMMED Architecture Framework - it is extremely lightweight. Even if you won't find this framework usable, you can still benefit from the templates it provides. </p>


问:
Is it possible for POST requests sent sequentially to be received out of order?
I'm a bit new to restful API usage.

suppose that I am sequentially sending out 1000 post requests in python, is it possible that my server could receive these requests out of order? (for example post request 5 is somehow received before post request 4)

If it is not possible for requests to be handled out of order, how do web application frameworks know what order to handle the requests in? is there some sort of timestamp/metadata that indicates priority of the request? For example, does the oldest request HAVE to be fulfilled as soon as possible?

I am curious because I am using the POST api to populate my database and I noticed that my sequentially sent data NEVER has come out of order. I don't want to be dependent on this assumption that sent data will always be consistently in the proper order, so I thought I should ask here

答:
If you are sending requests and wait for a response before sending the next one, then everything will happen in order, guaranteed.

If you are sending many requests in parallel, there's generally no guarantee which will arrive first and get processed first.

It's pretty reasonable to assume that the request that arrives first also gets processed first, and over a local fast network that may usually be the case; but over the internet specific packets can get delayed for lots of reasons. Even wifi might cause one of your requests to have to be resent if it wasn't received well the first time.

tl;dr: the only way you can guarantee order is if you wait for a response before sending the next request.


问:
ejs add comma every three digit
i'm using ejs for very small homepage

I wanna insert comma every three digit

Now situation

```<code><%= product.price %>
result = 1000000
</code>```

I want like this

```<code><%= product.price %> // some function
result 1,000,000
</code>```

can you help me?

答:
self answer

just pass the function to ejs

```<code>[ express ]

res.render(`${__dirname}/views/dashboard.ejs`, {
   ✅ numberWithCommas ✅ : function (x) {
     return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
   },
});

</code>```
```<code>[ ejs ]
now you can call the function

<%- numberWithCommas(product.price) %>

result
1,000,000
</code>```

Title: ejs add comma every three digit

Body:
i'm using ejs for very small homepage

I wanna insert comma every three digit

Now situation

<%= product.price %>
result = 1000000

I want like this

<%= product.price %> // some function
result 1,000,000

can you help me?

Body:
self answer

just pass the function to ejs

[ express ]

res.render(`${__dirname}/views/dashboard.ejs`, {
   ✅ numberWithCommas ✅ : function (x) {
     return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
   },
});

[ ejs ]
now you can call the function

<%- numberWithCommas(product.price) %>

result
1,000,000


问:
Read parquet file using pd.read_parquet looking for a schema
I'm working on an app that is writing parquet files.
For testing purposes, I'm trying to read a generated file with pd.read_parquet.
I get a really strange error that asks for a schema:

self = <[AttributeError("'ParquetFile' object has no attribute '_schema'") raised in repr()] ParquetFile object at 0x7fae6e06b250>

This happen on the following line:

```<code>data = pd.read_parquet(file)
</code>```

where file is the path to file from root content. First I'm not supposed to provide a schema as we're talking about parquet here and I'm not sure what could cause the issue. Maybe a readability clause ?

The generated file looks good when I imported it in my Parquet plugin for pycharm

{"Id": 12345, "Limit": 200, "Product": 818}
{"Id": 67890, "Limit":3000, "Product": 819}
So it shouldn't be an issue with the input data.

NB: Tried the same with fastparquet and got the same error (makes sense as pd.read_parquer is based on it.

答:
Same thing happened to me while I was doing it with a compression schema of

```<code>df.to_parquet("sample.parquet",compression="uncompressed")
</code>```

I changed it to none. Then it started working.

```<code>df.to_parquet("sample.parquet",compression="none")
</code>```

Maybe for your case environment is not setup correctly.
Try installing other engines such as fastparquet or pyarrow.

Body:
I'm working on an app that is writing parquet files.
For testing purposes, I'm trying to read a generated file with pd.read_parquet.
I get a really strange error that asks for a schema:

self = <[AttributeError("'ParquetFile' object has no attribute '_schema'") raised in repr()] ParquetFile object at 0x7fae6e06b250>

This happen on the following line:

data = pd.read_parquet(file)

where file is the path to file from root content. First I'm not supposed to provide a schema as we're talking about parquet here and I'm not sure what could cause the issue. Maybe a readability clause ?

The generated file looks good when I imported it in my Parquet plugin for pycharm

{"Id": 12345, "Limit": 200, "Product": 818}
{"Id": 67890, "Limit":3000, "Product": 819}
So it shouldn't be an issue with the input data.

NB: Tried the same with fastparquet and got the same error (makes sense as pd.read_parquer is based on it.

Body:
Same thing happened to me while I was doing it with a compression schema of

df.to_parquet("sample.parquet",compression="uncompressed")

I changed it to none. Then it started working.

df.to_parquet("sample.parquet",compression="none")

Maybe for your case environment is not setup correctly.
Try installing other engines such as fastparquet or pyarrow.


问:
In JavaScript, how can I update each element of an array the same way without using a loop?
For example, if I have an array:

```<code>movies = ["Spider Man", "Avatar", "Titantic", "Avengers"]
</code>```

How do I turn the movies array into

```<code>[{title: "Spider Man"}, {title: "Avatar"}, {title: "Titantic"}, {title:"Avengers"}]
</code>```

without using a loop? Is it possible to do it in O(1)?

In the same way, If I have an integer array and need to increment every element by one, can I do it without a loop?

答:
I would suggest regex, open to discussion on the complexity of the process

const movies = ["Spider Man", "Avatar", "Titantic", "Avengers"]

let moviesStr = JSON.stringify(movies); // O(1)

moviesStr = moviesStr.replace('["', '[{"title":"') // O(1)
moviesStr = moviesStr.replace('"]', '"}]') // O(1)
const regex = /,"/ig;

moviesStr = moviesStr.replaceAll(regex, '},{"title":"') // O(1) ???

const updateObj =  JSON.parse(moviesStr);

console.log(updateObj)```

Body:
For example, if I have an array:

movies = ["Spider Man", "Avatar", "Titantic", "Avengers"]

How do I turn the movies array into

[{title: "Spider Man"}, {title: "Avatar"}, {title: "Titantic"}, {title:"Avengers"}]

without using a loop? Is it possible to do it in O(1)?

In the same way, If I have an integer array and need to increment every element by one, can I do it without a loop?


答:
You can use onkeyup</p>

```<code><input id="name" onkeyup="checkLength(this.value)" />
</code>```

Title: Javascript change event on input element fires on only losing focus

Body:
You can use onkeyup

<input id="name" onkeyup="checkLength(this.value)" />


问:
What's the connection of string_view and basic_string<char> and why does string_view example code not work?
I have copied code from Bjarne Stroustrup's A Tour of C++ to test out string views but I keep getting error:

```<code>error: no matching function for call to ‘std::__cxx11::basic_string<char>::basic_string(std::basic_string_view<char>::size_type
</code>```

I am using VS Code WSL 2 with Ubuntu 20.04 and gcc-11

in main.cpp, I have:

```<code>#include <iostream>
#include "strings.h"

using namespace std;

int main () {
    string king = "Harold";
    auto s1 = cat(king, "William");
}
</code>```

in strings.h, I have the following. The function is copied as in the text book. I typed it out to avoid the peculiar * character that had a different encoding.

```<code>#pragma once
#include <string>

using namespace std;

string cat(string_view sv1, string_view sv2) {
    string res(sv1.length()+sv2.length());
    char* p = &res[0];

    for (char c : sv1)                  // one way
        *p++ = c;
    copy(sv2.begin(), sv2.end(), p);    // another way
    return res;
}
</code>```

Using the Ctrl+F5 command gives this error.

```<code>In file included from main.cpp:2:
strings.h: In function ‘std::string cat(std::string_view, std::string_view)’:
strings.h:7:41: error: no matching function for call to ‘std::__cxx11::basic_string<char>::basic_string(std::basic_string_view<char>::size_type)’
    7 |     string res(sv1.length()+sv2.length());
      |                                         ^
In file included from /usr/include/c++/11/string:55,
                 from /usr/include/c++/11/bits/locale_classes.h:40,
                 from /usr/include/c++/11/bits/ios_base.h:41,
                 from /usr/include/c++/11/ios:42,
                 from /usr/include/c++/11/ostream:38,
                 from /usr/include/c++/11/iostream:39,
                 from main.cpp:1:
/usr/include/c++/11/bits/basic_string.h:650:9: note: candidate: ‘template<class _Tp, class> std::__cxx11::basic_string<_CharT, _Traits, _Alloc>::basic_string(const _Tp&, const _Alloc&) [with _Tp = _Tp; <template-parameter-2-2> = <template-parameter-1-2>; _CharT = char; _Traits = std::char_traits<char>; _Alloc = std::allocator<char>]’
  650 |         basic_string(const _Tp& __t, const _Alloc& __a = _Alloc())
      |         ^~~~~~~~~~~~
/usr/include/c++/11/bits/basic_string.h:650:9: note:   template argument deduction/substitution failed:
In file included from /usr/include/c++/11/bits/move.h:57,
                 from /usr/include/c++/11/bits/nested_exception.h:40,
                 from /usr/include/c++/11/exception:148,
                 from /usr/include/c++/11/ios:39,
                 from /usr/include/c++/11/ostream:38,
                 from /usr/include/c++/11/iostream:39,
                 from main.cpp:1:
</code>```

I took a screenshot of what I see from Visual Studio code to indicate the underlined code, which doesn't makes

I thought it might have been the code editor but Godbolt shows similar errors.

Since this is related to Vs Code, here are my

launch.json

```<code>{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "name": "g++-11 - Build and debug active file",
            "type": "cppdbg",
            "request": "launch",
            "program": "${fileDirname}/${fileBasenameNoExtension}",
            "args": [],
            "stopAtEntry": false,
            "cwd": "${fileDirname}",
            "environment": [],
            "externalConsole": false,
            "MIMode": "gdb",
            "setupCommands": [
                {
                    "description": "Enable pretty-printing for gdb",
                    "text": "-enable-pretty-printing",
                    "ignoreFailures": true
                },
                {
                    "description": "Set Disassembly Flavor to Intel",
                    "text": "-gdb-set disassembly-flavor intel",
                    "ignoreFailures": true
                }
            ],
            "preLaunchTask": "C/C++: g++-11 build active file",
            "miDebuggerPath": "/usr/bin/gdb"
        }
    ]
}
</code>```

and c_cpp_properties.json

```<code>{
    "configurations": [
        {
            "name": "Linux",
            "includePath": [
                "${workspaceFolder}/**"
            ],
            "defines": [],
            "compilerPath": "/usr/bin/gcc",
            "cStandard": "gnu17",
            "cppStandard": "gnu++20",
            "intelliSenseMode": "linux-gcc-x64"
        }
    ],
    "version": 4
}
</code>```

答:
Yes, this seems to be wrong.

The line

```<code>string res(sv1.length()+sv2.length());
</code>```

should be

```<code>string res(sv1.length()+sv2.length(), '\0');
</code>```

std::string doesn't have a constructor which takes only a size argument, in contrast to std::vector. The value with which the elements are to be initialized must be provided explicitly.

I couldn't find this mistake in the list of errata here, though.

Body:
I have copied code from Bjarne Stroustrup's A Tour of C++ to test out string views but I keep getting error:

error: no matching function for call to ‘std::__cxx11::basic_string<char>::basic_string(std::basic_string_view<char>::size_type

I am using VS Code WSL 2 with Ubuntu 20.04 and gcc-11

in main.cpp, I have:

#include <iostream>
#include "strings.h"

using namespace std;

int main () {
    string king = "Harold";
    auto s1 = cat(king, "William");
}

in strings.h, I have the following. The function is copied as in the text book. I typed it out to avoid the peculiar * character that had a different encoding.

#pragma once
#include <string>

using namespace std;

string cat(string_view sv1, string_view sv2) {
    string res(sv1.length()+sv2.length());
    char* p = &res[0];

    for (char c : sv1)                  // one way
        *p++ = c;
    copy(sv2.begin(), sv2.end(), p);    // another way
    return res;
}

Using the Ctrl+F5 command gives this error.

In file included from main.cpp:2:
strings.h: In function ‘std::string cat(std::string_view, std::string_view)’:
strings.h:7:41: error: no matching function for call to ‘std::__cxx11::basic_string<char>::basic_string(std::basic_string_view<char>::size_type)’
    7 |     string res(sv1.length()+sv2.length());
      |                                         ^
In file included from /usr/include/c++/11/string:55,
                 from /usr/include/c++/11/bits/locale_classes.h:40,
                 from /usr/include/c++/11/bits/ios_base.h:41,
                 from /usr/include/c++/11/ios:42,
                 from /usr/include/c++/11/ostream:38,
                 from /usr/include/c++/11/iostream:39,
                 from main.cpp:1:
/usr/include/c++/11/bits/basic_string.h:650:9: note: candidate: ‘template<class _Tp, class> std::__cxx11::basic_string<_CharT, _Traits, _Alloc>::basic_string(const _Tp&, const _Alloc&) [with _Tp = _Tp; <template-parameter-2-2> = <template-parameter-1-2>; _CharT = char; _Traits = std::char_traits<char>; _Alloc = std::allocator<char>]’
  650 |         basic_string(const _Tp& __t, const _Alloc& __a = _Alloc())
      |         ^~~~~~~~~~~~
/usr/include/c++/11/bits/basic_string.h:650:9: note:   template argument deduction/substitution failed:
In file included from /usr/include/c++/11/bits/move.h:57,
                 from /usr/include/c++/11/bits/nested_exception.h:40,
                 from /usr/include/c++/11/exception:148,
                 from /usr/include/c++/11/ios:39,
                 from /usr/include/c++/11/ostream:38,
                 from /usr/include/c++/11/iostream:39,
                 from main.cpp:1:

I took a screenshot of what I see from Visual Studio code to indicate the underlined code, which doesn't makes

I thought it might have been the code editor but Godbolt shows similar errors.

Since this is related to Vs Code, here are my

launch.json

{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "name": "g++-11 - Build and debug active file",
            "type": "cppdbg",
            "request": "launch",
            "program": "${fileDirname}/${fileBasenameNoExtension}",
            "args": [],
            "stopAtEntry": false,
            "cwd": "${fileDirname}",
            "environment": [],
            "externalConsole": false,
            "MIMode": "gdb",
            "setupCommands": [
                {
                    "description": "Enable pretty-printing for gdb",
                    "text": "-enable-pretty-printing",
                    "ignoreFailures": true
                },
                {
                    "description": "Set Disassembly Flavor to Intel",
                    "text": "-gdb-set disassembly-flavor intel",
                    "ignoreFailures": true
                }
            ],
            "preLaunchTask": "C/C++: g++-11 build active file",
            "miDebuggerPath": "/usr/bin/gdb"
        }
    ]
}

and c_cpp_properties.json

{
    "configurations": [
        {
            "name": "Linux",
            "includePath": [
                "${workspaceFolder}/**"
            ],
            "defines": [],
            "compilerPath": "/usr/bin/gcc",
            "cStandard": "gnu17",
            "cppStandard": "gnu++20",
            "intelliSenseMode": "linux-gcc-x64"
        }
    ],
    "version": 4
}

Body:
Yes, this seems to be wrong.

The line

string res(sv1.length()+sv2.length());

should be

string res(sv1.length()+sv2.length(), '\0');

std::string doesn't have a constructor which takes only a size argument, in contrast to std::vector. The value with which the elements are to be initialized must be provided explicitly.

I couldn't find this mistake in the list of errata here, though.


问:
How do I unit test when ActiveRecord has been turned off?
I have turned ActiveRecord off in my Rails app in the environment config:

```<code>Rails::Initializer.run do |config|
  config.frameworks -= [:active_record]
end
</code>```

I have models that do not extend ActiveRecord::Base and I want to unit test these models. When I run the tests I get the uninitialized constant ActiveRecord::Base error.

How can I test my models when I don't have active record on?

答:
You could cheat.  Add the following to your tests:

```<code>class ActiveRecord
    class Base
        end
    end
</code>```

But first I'd recommend tracking down what is referring to ActiveRecord::Base.  You think you aren't using it, but you may be wrong.

ContentLicense: CC BY-SA 2.5

Body:
I have turned ActiveRecord off in my Rails app in the environment config:

Rails::Initializer.run do |config|
  config.frameworks -= [:active_record]
end

I have models that do not extend ActiveRecord::Base and I want to unit test these models. When I run the tests I get the uninitialized constant ActiveRecord::Base error.

How can I test my models when I don't have active record on?

Body:
You could cheat.  Add the following to your tests:

class ActiveRecord
    class Base
        end
    end

But first I'd recommend tracking down what is referring to ActiveRecord::Base.  You think you aren't using it, but you may be wrong.

OwnerDisplayName: MarkusQ


问:
Select from insert
Is it possible to select from an insert statement?  For example:

```<code>SELECT id FROM (INSERT INTO table (col1, col2) VALUES (val1, val2));
</code>```

Where id is an autoincrementing primary key.

答:
It's not possible in such way, because INSERT doesn't return virtual table for SELECT. However you could get id's actual value using currval(regclass) sequence function as:

```<code>SELECT currval('yourTableName_id_seq'::regclass);
 currval
---------
       1
(1 row)
</code>```

EDIT:

Use RETURNING clause (available since PostgreSQL 8.2):

```<code>INSERT INTO yourTableName (col1, col2) VALUES ('aaa', 'bbb') RETURNING id;
 id
----
  2
(1 row)
</code>```

Title: Select from insert

Body:
Is it possible to select from an insert statement?  For example:

SELECT id FROM (INSERT INTO table (col1, col2) VALUES (val1, val2));

Where id is an autoincrementing primary key.

Body:
It's not possible in such way, because INSERT doesn't return virtual table for SELECT. However you could get id's actual value using currval(regclass) sequence function as:

SELECT currval('yourTableName_id_seq'::regclass);
 currval
---------
       1
(1 row)

EDIT:

Use RETURNING clause (available since PostgreSQL 8.2):

INSERT INTO yourTableName (col1, col2) VALUES ('aaa', 'bbb') RETURNING id;
 id
----
  2
(1 row)


问:
Left join two dateframes with date columns on a range of dates?
Here's an example that fulfills the criteria. Dataframe df1 and df2 both have id columns and date columns. In df1 the id column is unique while in df2 it is non-unique. I'd like to create a new dataframe where the join happens if df1.id == df2.id and some pair of dates in df2 is within 1 week of the date in df1

```<code>df1

| customer_id (unique) | 'purchase_date'|
| --------             | -------------- |
| 1                    | 2021-05-14     |
| 2                    | 2021-09-16     |

df2

| customer_id | 'visit_dates'  |
| --------    | -------------- |
| 1           | 2021-05-11     |
| 1           | 2021-05-16     |
| 1           | 2021-05-21     |
| 2           | 2021-07-14     |
| 2           | 2021-09-17     |

# New Df will only have 1 row.
# For customer 1 there is a date within the range(05-07 -> 05-14)
# and within the range(05-14 -> 05-21) with matching id.
# For customer 2, there are no dates within (09-09 -> 09-16) so it should be filtered

newdf

| customer_id (unique) | 'purchase_date'| begin_date_range | end_date_range
| --------             | -------------- | ---------------- | -------------
| 1                    | 2021-05-14     | 2021-05-11       | 2021-05-16

</code>```

I understand how to do this in SQL, but I don't know what functions allow similar date predicate filtering in Pandas.

To construct df1 and df2:

```<code>data1 = {'customer_id': [1, 2], 'purchase_date': ['2021-05-14', '2021-09-16']}

data2 = {'customer_id': [1, 1, 1, 2, 2],
         'visit_dates': ['2021-05-11', '2021-05-16', '2021-05-21', '2021-07-14', '2021-09-17']}
</code>```

答:
Filter the merge result using the week condition.

```<code>df = df1.merge(df2, on='customer_id', how='left')
df[(df['purchase_date'] - df['visit_dates']).dt.days.between(0, 6)]
df['visit_dates+1week'] = df['visit_dates'] + pd.Timedelta(days=6)
</code>```

Body:
Here's an example that fulfills the criteria. Dataframe df1 and df2 both have id columns and date columns. In df1 the id column is unique while in df2 it is non-unique. I'd like to create a new dataframe where the join happens if df1.id == df2.id and some pair of dates in df2 is within 1 week of the date in df1

df1

| customer_id (unique) | 'purchase_date'|
| --------             | -------------- |
| 1                    | 2021-05-14     |
| 2                    | 2021-09-16     |

df2

| customer_id | 'visit_dates'  |
| --------    | -------------- |
| 1           | 2021-05-11     |
| 1           | 2021-05-16     |
| 1           | 2021-05-21     |
| 2           | 2021-07-14     |
| 2           | 2021-09-17     |

# New Df will only have 1 row.
# For customer 1 there is a date within the range(05-07 -> 05-14)
# and within the range(05-14 -> 05-21) with matching id.
# For customer 2, there are no dates within (09-09 -> 09-16) so it should be filtered

newdf

| customer_id (unique) | 'purchase_date'| begin_date_range | end_date_range
| --------             | -------------- | ---------------- | -------------
| 1                    | 2021-05-14     | 2021-05-11       | 2021-05-16

I understand how to do this in SQL, but I don't know what functions allow similar date predicate filtering in Pandas.

To construct df1 and df2:

data1 = {'customer_id': [1, 2], 'purchase_date': ['2021-05-14', '2021-09-16']}

data2 = {'customer_id': [1, 1, 1, 2, 2],
         'visit_dates': ['2021-05-11', '2021-05-16', '2021-05-21', '2021-07-14', '2021-09-17']}

Body:
Filter the merge result using the week condition.

df = df1.merge(df2, on='customer_id', how='left')
df[(df['purchase_date'] - df['visit_dates']).dt.days.between(0, 6)]
df['visit_dates+1week'] = df['visit_dates'] + pd.Timedelta(days=6)


问:
How can I have nice file names & efficient storage usage in my Foundry Magritte dataset export?
I'm working on exporting data from Foundry datasets in parquet format using various Magritte export tasks to an ABFS system (but the same issue occurs with SFTP, S3, HDFS, and other file based exports).

The datasets I'm exporting are relatively small, under 512 MB in size, which means they don't really need to be split across multiple parquet files, and putting all the data in one file is enough.  I've done this by ending the previous transform with a .coalesce(1) to get all of the data in a single file.

The issues are:

By default the file name is part-0000-<rid>.snappy.parquet, with a different rid on every build.  This means that, whenever a new file is uploaded, it appears in the same folder as an additional file, the only way to tell which is the newest version is by last modified date.

Every version of the data is stored in my external system, this takes up unnecessary storage unless I frequently go in and delete old files.

All of this is unnecessary complexity being added to my downstream system, I just want to be able to pull the latest version of data in a single step.

答:
I ran into the same requirement the only difference was that the dataset required to be split into multiple parts due to the size. Posting here the code and how I have updated it to handle this use case.

def rename_multiple_parquet_outputs(output: Output, input: list, file_name_prefix: str):
    """
        Slight improvement to allow multiple output files to be renamed
    """
    output.set_mode("replace")  # Make sure it is snapshotting

    input_files_df = input.filesystem().files()  # Get all files
    input_files = [row[0] for row in input_files_df.collect()]  # noqa - first column in files_df is path
    input_files = [f for f in input_files if f.endswith(".snappy.parquet")]  # filter non parquet files
    if len(input_files) == 0:
        raise RuntimeError("Input dataset file system cannot be empty.")
    input_file_path = input_files[0]
    print(f'input files {input_files}')
    print("prefix for target name: " + file_name_prefix)

    for i,f in enumerate(input_files):
        with input.filesystem().open(f, "rb") as in_f:  # open the input file
            with output.filesystem().open(f'{file_name_prefix}_part_{i}.snappy.parquet', "wb") as out_f:  # open the output file
                shutil.copyfileobj(in_f, out_f)  # write the file into a new file
```
<p>Also to use this into a code workbook the input needs to be persisted and the output parameter can be retrieved as shown below.</p>
<pre class="lang-py prettyprint-override"><code>def rename_outputs(persisted_input):
    output = Transforms.get_output()
    rename_parquet_outputs(output, persisted_input, "prefix_for_renamed_files")
</code>```

Body:
I ran into the same requirement the only difference was that the dataset required to be split into multiple parts due to the size. Posting here the code and how I have updated it to handle this use case.

def rename_multiple_parquet_outputs(output: Output, input: list, file_name_prefix: str):
    """
        Slight improvement to allow multiple output files to be renamed
    """
    output.set_mode("replace")  # Make sure it is snapshotting

    input_files_df = input.filesystem().files()  # Get all files
    input_files = [row[0] for row in input_files_df.collect()]  # noqa - first column in files_df is path
    input_files = [f for f in input_files if f.endswith(".snappy.parquet")]  # filter non parquet files
    if len(input_files) == 0:
        raise RuntimeError("Input dataset file system cannot be empty.")
    input_file_path = input_files[0]
    print(f'input files {input_files}')
    print("prefix for target name: " + file_name_prefix)

    for i,f in enumerate(input_files):
        with input.filesystem().open(f, "rb") as in_f:  # open the input file
            with output.filesystem().open(f'{file_name_prefix}_part_{i}.snappy.parquet', "wb") as out_f:  # open the output file
                shutil.copyfileobj(in_f, out_f)  # write the file into a new file

Also to use this into a code workbook the input needs to be persisted and the output parameter can be retrieved as shown below.

def rename_outputs(persisted_input):
    output = Transforms.get_output()
    rename_parquet_outputs(output, persisted_input, "prefix_for_renamed_files")


问:
How can I feed multiple of 100 annotated files in training Custom NER model using spacy3
Currently I have prepared a Custom NER model where I can extract 15 entities. I have trained my model on single annotated file using config.cfg file by spacy3. Now I want to train my model again on 100 annotated files. How can I pass these annotated files?</p>

答: If you put .spacy files in a directory and specify the directory as your train/dev corpus spaCy will automatically load all the files.


问:
How to detect orientation of an Image got with SwiftUI 3 AsyncImage()
I get an image with AsyncImage() to be displayed in a view.

```<code>struct Pic: View {
  var body: some View {
    let url = FileManager.default.url(forUbiquityContainerIdentifier: nil)?.appendingPathComponent("Documents").appendingPathComponent("IMG_5328.jpeg")

    AsyncImage(url: url) { image in
      image
      .resizable()
 //     if(image.orientation == .right) {
 //       .rotationEffect(.degrees(90))
 //     }
      .scaledToFit()
    } placeholder: {
      Color.red
    }
  }
}
</code>```

The imagefile (IMG_5328.jpeg) has an orientation of 6 (90 Degree counterclockwise), but the image is not rendered with automatic rotation.

How can I get the orientation to rotate it manually.

Working with UIImage does it automatically.

```<code>let url = FileManager.default.url(forUbiquityContainerIdentifier: nil)?.appendingPathComponent("Documents").appendingPathComponent("IMG_5328.jpeg")
    let imageData = try! Data(contentsOf: url!)
    let uiImage = UIImage(data: imageData)!
</code>```

答:
I had the same problem, but there are some differences, however I think you can use this solution.

First, add an extension to detect image orientation. It's not mandatory, you can use a local function or ternary operator directly into the view modifier of rotation effect.

```<code>import SwiftUI

extension UIImage {

    func getRotationAngle() -> Angle {
        switch imageOrientation {
        case .left:
            return Angle(degrees: 270)
        case .leftMirrored:
            return Angle(degrees: 270)
         case .right:
            return Angle(degrees: 90)
        case .rightMirrored:
            return Angle(degrees: 90)
        case .down:
            return Angle(degrees: 180)
        case .downMirrored:
            return Angle(degrees: 180)
        default:
            return Angle(degrees: 0)
        }
    }

}
</code>```

Then You need to get the UIImage. For that You can use this image picker or your alternative is perfect too.

```<code>import SwiftUI

struct ImagePicker: UIViewControllerRepresentable {

    @Binding var image: UIImage?
    @Binding var imageURL: URL?
    @Environment(\.presentationMode) var presentationMode

    class Coordinator: NSObject, UINavigationControllerDelegate, UIImagePickerControllerDelegate {
        let parent: ImagePicker

        init(_ parent: ImagePicker) {
            self.parent = parent
        }

        func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any]) {
            if let uiImage = info[.originalImage] as? UIImage {
                parent.image = uiImage
            }
            if let imageURL = info[.imageURL] as? URL {
                parent.imageURL = imageURL
                // Alternative
                //let imageData = try! Data(contentsOf: url!)
                //parent.image = UIImage(data: imageData)!
            }
            parent.presentationMode.wrappedValue.dismiss()
        }
    }

    func makeUIViewController(context: UIViewControllerRepresentableContext<ImagePicker>) -> UIImagePickerController {
        let picker = UIImagePickerController()
        picker.delegate = context.coordinator
        return picker
    }

    func makeCoordinator() -> Coordinator {
        Coordinator(self)
    }

    func updateUIViewController(_ uiViewController: UIImagePickerController, context: UIViewControllerRepresentableContext<ImagePicker>) {

    }

}
</code>```

And here the implementation.

```<code>import SwiftUI

struct ProfileView: View {

    @State private var showingImagePicker = Bool()
    @State private var inputImage = UIImage(systemName: "person.crop.circle")
    @State var imageURL: URL? = nil

    var body: some View {
        VStack(spacing: 0) {
            Text("Your profile")
                .foregroundColor(.white)
                .font(.custom("VisbyCF-Heavy", size: 24))
                .frame(maxWidth: .infinity, alignment: .leading)
                .padding(.top, 37)
                .padding(.bottom, 33)
            VStack(spacing: 0) { // Picture
                ZStack {
                    if #available(iOS 15.0, *) {
                        AsyncImage(
                            url: imageURL,
                            content: { image in
                                image
                                    .resizable()
                                    .aspectRatio(contentMode: .fill)
                                    .frame(maxWidth: 105, maxHeight: 105)
                                    .cornerRadius(53)
                                    .rotationEffect(inputImage?.getRotationAngle() ?? Angle(degrees: 0))
                            }, placeholder: {
                                Image(systemName: "person.crop.circle")
                                    .resizable()
                                    .aspectRatio(contentMode: .fill)
                                    .frame(maxWidth: 105, maxHeight: 105)
                                    .cornerRadius(53)
                            }
                        )
                    }
                    ZStack {
                        HStack{
                            Image(systemName: "pencil.circle")
                                .resizable()
                                .frame(width: 12, height: 12)
                                .padding(5)
                        }
                        .frame(width: 24, height: 24)
                        .background(Color.blue)
                        .clipShape(Circle())
                        .shadow(radius: 10)
                        .onTapGesture {
                            self.showingImagePicker = true
                        }
                    }
                    .frame(maxWidth: 105,maxHeight: .infinity, alignment: .bottom)
                    .offset(x: 35)
                }
                .frame(width: 105, height: 105)
                .padding(.bottom, 7)
                Text("Change picture")
                    .foregroundColor(Color.white)
                    .font(.custom("VisbyCF-Heavy", size: 14))
                    .padding(.bottom, 32)
            }
            Spacer()
        }
        .padding([.leading, .trailing], 35)
        .navigationBarColor(.clear)
        .navigationBarTitle(Text("Your profile"), displayMode: .inline)
        .sheet(isPresented: $showingImagePicker) {
            ImagePicker(image: $inputImage, imageURL: $imageURL)
        }
    }

}Ï
</code>```

Body:
I get an image with AsyncImage() to be displayed in a view.

struct Pic: View {
  var body: some View {
    let url = FileManager.default.url(forUbiquityContainerIdentifier: nil)?.appendingPathComponent("Documents").appendingPathComponent("IMG_5328.jpeg")

    AsyncImage(url: url) { image in
      image
      .resizable()
 //     if(image.orientation == .right) {
 //       .rotationEffect(.degrees(90))
 //     }
      .scaledToFit()
    } placeholder: {
      Color.red
    }
  }
}

The imagefile (IMG_5328.jpeg) has an orientation of 6 (90 Degree counterclockwise), but the image is not rendered with automatic rotation.

How can I get the orientation to rotate it manually.

Working with UIImage does it automatically.

let url = FileManager.default.url(forUbiquityContainerIdentifier: nil)?.appendingPathComponent("Documents").appendingPathComponent("IMG_5328.jpeg")
    let imageData = try! Data(contentsOf: url!)
    let uiImage = UIImage(data: imageData)!

Body:
I had the same problem, but there are some differences, however I think you can use this solution.

First, add an extension to detect image orientation. It's not mandatory, you can use a local function or ternary operator directly into the view modifier of rotation effect.

import SwiftUI

extension UIImage {

    func getRotationAngle() -> Angle {
        switch imageOrientation {
        case .left:
            return Angle(degrees: 270)
        case .leftMirrored:
            return Angle(degrees: 270)
         case .right:
            return Angle(degrees: 90)
        case .rightMirrored:
            return Angle(degrees: 90)
        case .down:
            return Angle(degrees: 180)
        case .downMirrored:
            return Angle(degrees: 180)
        default:
            return Angle(degrees: 0)
        }
    }

}

Then You need to get the UIImage. For that You can use this image picker or your alternative is perfect too.

import SwiftUI

struct ImagePicker: UIViewControllerRepresentable {

    @Binding var image: UIImage?
    @Binding var imageURL: URL?
    @Environment(\.presentationMode) var presentationMode

    class Coordinator: NSObject, UINavigationControllerDelegate, UIImagePickerControllerDelegate {
        let parent: ImagePicker

        init(_ parent: ImagePicker) {
            self.parent = parent
        }

        func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any]) {
            if let uiImage = info[.originalImage] as? UIImage {
                parent.image = uiImage
            }
            if let imageURL = info[.imageURL] as? URL {
                parent.imageURL = imageURL
                // Alternative
                //let imageData = try! Data(contentsOf: url!)
                //parent.image = UIImage(data: imageData)!
            }
            parent.presentationMode.wrappedValue.dismiss()
        }
    }

    func makeUIViewController(context: UIViewControllerRepresentableContext<ImagePicker>) -> UIImagePickerController {
        let picker = UIImagePickerController()
        picker.delegate = context.coordinator
        return picker
    }

    func makeCoordinator() -> Coordinator {
        Coordinator(self)
    }

    func updateUIViewController(_ uiViewController: UIImagePickerController, context: UIViewControllerRepresentableContext<ImagePicker>) {

    }

}

And here the implementation.

import SwiftUI

struct ProfileView: View {

    @State private var showingImagePicker = Bool()
    @State private var inputImage = UIImage(systemName: "person.crop.circle")
    @State var imageURL: URL? = nil

    var body: some View {
        VStack(spacing: 0) {
            Text("Your profile")
                .foregroundColor(.white)
                .font(.custom("VisbyCF-Heavy", size: 24))
                .frame(maxWidth: .infinity, alignment: .leading)
                .padding(.top, 37)
                .padding(.bottom, 33)
            VStack(spacing: 0) { // Picture
                ZStack {
                    if #available(iOS 15.0, *) {
                        AsyncImage(
                            url: imageURL,
                            content: { image in
                                image
                                    .resizable()
                                    .aspectRatio(contentMode: .fill)
                                    .frame(maxWidth: 105, maxHeight: 105)
                                    .cornerRadius(53)
                                    .rotationEffect(inputImage?.getRotationAngle() ?? Angle(degrees: 0))
                            }, placeholder: {
                                Image(systemName: "person.crop.circle")
                                    .resizable()
                                    .aspectRatio(contentMode: .fill)
                                    .frame(maxWidth: 105, maxHeight: 105)
                                    .cornerRadius(53)
                            }
                        )
                    }
                    ZStack {
                        HStack{
                            Image(systemName: "pencil.circle")
                                .resizable()
                                .frame(width: 12, height: 12)
                                .padding(5)
                        }
                        .frame(width: 24, height: 24)
                        .background(Color.blue)
                        .clipShape(Circle())
                        .shadow(radius: 10)
                        .onTapGesture {
                            self.showingImagePicker = true
                        }
                    }
                    .frame(maxWidth: 105,maxHeight: .infinity, alignment: .bottom)
                    .offset(x: 35)
                }
                .frame(width: 105, height: 105)
                .padding(.bottom, 7)
                Text("Change picture")
                    .foregroundColor(Color.white)
                    .font(.custom("VisbyCF-Heavy", size: 14))
                    .padding(.bottom, 32)
            }
            Spacer()
        }
        .padding([.leading, .trailing], 35)
        .navigationBarColor(.clear)
        .navigationBarTitle(Text("Your profile"), displayMode: .inline)
        .sheet(isPresented: $showingImagePicker) {
            ImagePicker(image: $inputImage, imageURL: $imageURL)
        }
    }

}Ï


问:
I want to define a variable with superglobal scope in php
I want to define a variable in php with in a global scope. That variable should be accessible for each user, so it should not depend on the session.

I want to do something like the following: I have a php script, and that script usually takes about 5 to 15 minutes to execute, but it can take more than one hour in some special cases. This script is being run using a cron job with a 15 minutes interval. This script can also be run manually by any user.

Now it's possible to run any number of scripts at the same time. I want to limit this number of scripts.

So, I want a variable to store the number of currently executing scripts. I don't want to use a DB or files to store a single value.

Thanks in advance.

答: Your preconditions are pretty restrictive. Memory is not (or not normally) shared between scripts and we cannot use files or databases: that virtually leaves no common space available to share information, so you have to calculate the information every time. Your best option is probably to inspect the running processes, identify which ones belong to your script and count them. Your mention to cron suggests Unix, which makes things easier. The POSIX extension probably allows to control process execution to this degree and, as last resource, you can always run the ps command from PHP.</p>


问:
I want to detect messages sent by a specific user. (discrd.py on message)
I want to check the number of messages sent by a specific user when sec is 0. If the number of messages sent by the user is 0, it tries to delete the channel.</p>
```<code>        while (sec != 0 ):
            sec = sec-1
            await asyncio.sleep(1)
            print(sec)
            if sec == 30:
                await a.send(f'{message.author.mention}')
            if sec == 0:
                await a.delete()
                await message.author.send('f')
</code>```

答:
u need to have id of the user and check check it like this :

channel = bot.get_channel(id)
messages = await channel.history(limit=None).flatten()
for msg in messages:
    if msg.author.id == id of that user:
        return
await channel.delete()
```

so it will fetch the messages and then will check if user have messaged or not if yes it will stop there and will do nothing if not then it will delete channel.

Body:
I want to check the number of messages sent by a specific user when sec is 0. If the number of messages sent by the user is 0, it tries to delete the channel.

        while (sec != 0 ):
            sec = sec-1
            await asyncio.sleep(1)
            print(sec)
            if sec == 30:
                await a.send(f'{message.author.mention}')
            if sec == 0:
                await a.delete()
                await message.author.send('f')

Body:
u need to have id of the user and check check it like this :

channel = bot.get_channel(id)
messages = await channel.history(limit=None).flatten()
for msg in messages:
    if msg.author.id == id of that user:
        return
await channel.delete()

so it will fetch the messages and then will check if user have messaged or not if yes it will stop there and will do nothing if not then it will delete channel.