问:
Google App Engine providing .well-known Folder
I'm trying to provide a .well-known folder under my Google App Engine Application I'm using the standard environment and the python27 runtime.
with a web-app-origin-association.json file to try the Progressive Web Apps as URL Handlers
origin trial from chrome.

I've added the following code to my app.yaml file under handlers:

```<code>  # .well-known Ordner
  - url: /.well-known/(.*)
    static_files: well-known/\1
    upload: well-known/.*
</code>```

The folder in my project is named well-known without a dot cause I've read that there are problems when using a folder Name with a dot at the start of the foldername.
But the url https://example.com/.well-known/web-app-origin-associate.json isn't available instead it works without the dot:

What do I have to change in order to make it work under https://example.com/.well-known/web-app-origin-association.json?

答:
The best way i found out about is to just do it like that:

```<code>  - url: /\.well-known
    static_dir: .well-known
    secure: always
</code>```

and use the python39 runtime.

Body:
I'm trying to provide a .well-known folder under my Google App Engine Application I'm using the standard environment and the python27 runtime.
with a web-app-origin-association.json file to try the Progressive Web Apps as URL Handlers
origin trial from chrome.

I've added the following code to my app.yaml file under handlers:

  # .well-known Ordner
  - url: /.well-known/(.*)
    static_files: well-known/\1
    upload: well-known/.*

The folder in my project is named well-known without a dot cause I've read that there are problems when using a folder Name with a dot at the start of the foldername.
But the url https://example.com/.well-known/web-app-origin-associate.json isn't available instead it works without the dot:

What do I have to change in order to make it work under https://example.com/.well-known/web-app-origin-association.json?

Body:
The best way i found out about is to just do it like that:

  - url: /\.well-known
    static_dir: .well-known
    secure: always

and use the python39 runtime.


来源: stackexchange

问:
Sum total value for all items
I have a query set that contains a number of transactions for a particular product.

transactions = Transaction.objects.filter(product__product_name_id = item.id)

Within this queryset contains a number of fields.

```<code>product
amount
price
transaction_date
</code>```

I need to calculate the totals of the values in the amount fields.

The current query set is returning  2 amounts from 2 `transactions'

Would it be sensible to loop through each transaction and add it to a list of something? or is there a better way?

```<code>list = []
for item in transactions:
   amount = item.amount
   list.append(amount)
</code>```

Thanks

答:
You can let the db handle this by using aggregation:</p>
```<code>from django.db.models import Sum

total = transactions.aggregate(s=Sum("amount"))["s"]
</code>```

ContentLicense: CC BY-SA 4.0

Title: Sum total value for all items

Body:
I have a query set that contains a number of transactions for a particular product.

transactions = Transaction.objects.filter(product__product_name_id = item.id)

Within this queryset contains a number of fields.

product
amount
price
transaction_date

I need to calculate the totals of the values in the amount fields.

The current query set is returning  2 amounts from 2 `transactions'

Would it be sensible to loop through each transaction and add it to a list of something? or is there a better way?

list = []
for item in transactions:
   amount = item.amount
   list.append(amount)

Thanks

Body:
You can let the db handle this by using aggregation:

from django.db.models import Sum

total = transactions.aggregate(s=Sum("amount"))["s"]


问:
Beginner question - Encapsulation and "Proxy Classes"
While learning c#, I have picked up the implication from reading other people's code that it's good practice to separate certain classes from the program by use of a sort of "Proxy Class".  Namely those programs with private data.

For instance, say I have  database class that performs just about all of my database interactions.  It has both a "Send data" and "Read Data" method.

What I also have is a Manager class, in which I have placed a private instance of the Database class.  In this Manager class, I have also included a "Read Data from Database" and "Send Data to Database" method. All these do is accept the required parameters and use them to run the Database's Read/Write methods.

Other than a few misc methods whose code could easily be run from elsewhere, Manager's only purpose's to act as a messenger between the program and the Database class to prevent Database from needing to be instantiated directly in the form.

Am I on the right track here or am I just creating more work for myself by not simply creating a Database object in the form and running everything directly from there?

答:
I'm with John Saunders on this - you're using the class in some realm of "correctness", but not for a real purpose.

As described in your example, a proxy class is used as an abstraction.  Your executing code doesn't need to know anything about the data source - it just submits a request for data and gets data back as a response.  The proxy hides this implementation detail from you - it could retrieve the data from a flat file, a database, a web service; it really doesn't matter.  This makes your code more flexible because it's not tied to a specific database implementation, and it also makes it testable because you can inject some other class in there that provides test ("mock") data.

ContentLicense: CC BY-SA 3.0


问:
geopandas POLYGON coordinates to x,y coordinate columns
I have a geopandas dataframe of the type:

```<code> id  \
0  028f342a-b26f-4e36-b5d1-25d3428cac2f

                                                 add
0  POLYGON ((33.78148 3.50903, 33.12417 3.50903, ...
</code>```

Here is the entire POLYGON:

```<code>;id;add
0;028f342a-b26f-4e36-b5d1-25d3428cac2f;POLYGON ((33.781475 3.5090296, 33.1241675 3.5090296, 33.1241675 4.392868066666667, 33.781475 4.392868066666667, 33.781475 3.5090296))
</code>```

What I wish to do is to extract all x and y coordinates of the polygon corners into 2 columns. So, what I have tried is (This code is meant for the entire dataframe):

```<code>List_Mvv_id = list(set(df['id']))

Full =[]
for i in List_Mvv_id:
    df = df[df['id']==i]
    P = df['add'].iloc[0]
    print(P)
    for x,y in P.exterior.coords:
        df['x'] = x
        df['y'] = y

        Full.append(df)
</code>```

However, it only returns the first coordinates of the polygon:

```<code>                                     id  \
0  028f342a-b26f-4e36-b5d1-25d3428cac2f
0  028f342a-b26f-4e36-b5d1-25d3428cac2f
0  028f342a-b26f-4e36-b5d1-25d3428cac2f
0  028f342a-b26f-4e36-b5d1-25d3428cac2f
0  028f342a-b26f-4e36-b5d1-25d3428cac2f

                                                 add          x        y
0  POLYGON ((33.78148 3.50903, 33.12417 3.50903, ...  33.781475  3.50903
0  POLYGON ((33.78148 3.50903, 33.12417 3.50903, ...  33.781475  3.50903
0  POLYGON ((33.78148 3.50903, 33.12417 3.50903, ...  33.781475  3.50903
0  POLYGON ((33.78148 3.50903, 33.12417 3.50903, ...  33.781475  3.50903
0  POLYGON ((33.78148 3.50903, 33.12417 3.50903, ...  33.781475  3.50903
</code>```

I tried also this approach:

```<code>def coord_lister(geom):
    coords = list(geom.exterior.coords)
    return (coords)

coordinates_list = df.geometry.apply(coord_lister)
</code>```

But I got stuck on extracting the x,y coordinates.

Grateful for any insights.

答:
use apply() to do looping it is as simple as below

```<code>import pandas as pd
import geopandas as gpd
import shapely
import io

df = pd.read_csv(io.StringIO(""";id;add
0;028f342a-b26f-4e36-b5d1-25d3428cac2f;POLYGON ((33.781475 3.5090296, 33.1241675 3.5090296, 33.1241675 4.392868066666667, 33.781475 4.392868066666667, 33.781475 3.5090296))"""), sep=";")

# recreate geodataframe
gdf = gpd.GeoDataFrame(df, geometry=df["add"].apply(shapely.wkt.loads))

# expand the co-ordinates
gdf["geometry"].apply(lambda p: list(p.exterior.coords)).explode().apply(pd.Series).rename(columns=({0:"x", 1:"y"}))
</code>```

x
y

0
33.7815
3.50903

0
33.1242
3.50903

0
33.1242
4.39287

0
33.7815
4.39287

0
33.7815
3.50903

Body:
I have a geopandas dataframe of the type:

 id  \
0  028f342a-b26f-4e36-b5d1-25d3428cac2f

                                                 add
0  POLYGON ((33.78148 3.50903, 33.12417 3.50903, ...

Here is the entire POLYGON:

;id;add
0;028f342a-b26f-4e36-b5d1-25d3428cac2f;POLYGON ((33.781475 3.5090296, 33.1241675 3.5090296, 33.1241675 4.392868066666667, 33.781475 4.392868066666667, 33.781475 3.5090296))

What I wish to do is to extract all x and y coordinates of the polygon corners into 2 columns. So, what I have tried is (This code is meant for the entire dataframe):

List_Mvv_id = list(set(df['id']))

Full =[]
for i in List_Mvv_id:
    df = df[df['id']==i]
    P = df['add'].iloc[0]
    print(P)
    for x,y in P.exterior.coords:
        df['x'] = x
        df['y'] = y

        Full.append(df)

However, it only returns the first coordinates of the polygon:

                                     id  \
0  028f342a-b26f-4e36-b5d1-25d3428cac2f
0  028f342a-b26f-4e36-b5d1-25d3428cac2f
0  028f342a-b26f-4e36-b5d1-25d3428cac2f
0  028f342a-b26f-4e36-b5d1-25d3428cac2f
0  028f342a-b26f-4e36-b5d1-25d3428cac2f

                                                 add          x        y
0  POLYGON ((33.78148 3.50903, 33.12417 3.50903, ...  33.781475  3.50903
0  POLYGON ((33.78148 3.50903, 33.12417 3.50903, ...  33.781475  3.50903
0  POLYGON ((33.78148 3.50903, 33.12417 3.50903, ...  33.781475  3.50903
0  POLYGON ((33.78148 3.50903, 33.12417 3.50903, ...  33.781475  3.50903
0  POLYGON ((33.78148 3.50903, 33.12417 3.50903, ...  33.781475  3.50903

I tried also this approach:

def coord_lister(geom):
    coords = list(geom.exterior.coords)
    return (coords)

coordinates_list = df.geometry.apply(coord_lister)

But I got stuck on extracting the x,y coordinates.

Grateful for any insights.

Body:
use apply() to do looping it is as simple as below

import pandas as pd
import geopandas as gpd
import shapely
import io

df = pd.read_csv(io.StringIO(""";id;add
0;028f342a-b26f-4e36-b5d1-25d3428cac2f;POLYGON ((33.781475 3.5090296, 33.1241675 3.5090296, 33.1241675 4.392868066666667, 33.781475 4.392868066666667, 33.781475 3.5090296))"""), sep=";")

# recreate geodataframe
gdf = gpd.GeoDataFrame(df, geometry=df["add"].apply(shapely.wkt.loads))

# expand the co-ordinates
gdf["geometry"].apply(lambda p: list(p.exterior.coords)).explode().apply(pd.Series).rename(columns=({0:"x", 1:"y"}))

x
y

0
33.7815
3.50903

0
33.1242
3.50903

0
33.1242
4.39287

0
33.7815
4.39287

0
33.7815
3.50903


答:
you can use aggregate for doing that:</p>
```<code>from django.db.models import Sum

transactions.aggregate(Sum('amount'))
# returns {'amount__sum': 1000} for example
</code>```

Title: Sum total value for all items

Body:
you can use aggregate for doing that:

from django.db.models import Sum

transactions.aggregate(Sum('amount'))
# returns {'amount__sum': 1000} for example


问:
Import CA.pem file to Jmeter to push the message to Kafka
We are trying to push the message via Jmeter to kafka topics. We tried to push the message by using Java request with all the Kafka topic details but in order to successfully see the message in the topic , there needs a CA.Pem file to be imported to Jmeter to establish the connection.

Could anybody help in importing the .pem file in Jmeter  ?

答:
JMeter doesn't support certificates in PEM format, you need to convert it to Java keystore first using OpenSSL tool or Keytool

Once you have the keystore you should be able to make JMeter aware of it by specifying the relevant SSL properties in the Pepper-Box - Kafka Load Generator plugin:

More information on the plugin installation and usage: Apache Kafka - How to Load Test with JMeter


问:
Get Cloud Watch logs from differnet lambda functions or applications
I want to fetch Cloud watch logs for different lambda fucntions and trace for a pertucular string just like insights becasue we have some set of lambda functions and applications which need to run for a perticular job. Many time some of the services stop runnig due to some issues so i want to trace them with perticulart string and get error report where it got errored.

Eg : Lambda1 will call Lambda2 and Lambda2 will add entry in DynamoDB.
Now i want to create a lambda function which will trace lambda 1 and lambda 2 give me report if both lambdas run succesfully for a perticular JOBID.

So far i have tryed to use AWS Cloud watch as a trigger but it is giving log only for 1 perticular function but not for all functions.

答: There is a Python library called Boto3 which helped me to resolve this issue.The Lambda function should have a peoper read access to fetch the logs or the corrosponding lambda fucntions we are tracking.</p>


问:
I want to update my state values as soon as I am dispatching the actions
Hi I am trying to get my state values as soon as I am updating it. But cannot achieve this

My initial state looks like this:

```<code>filterData: {year: "2021", programId: "America"}
</code>```

I have a handleDelete function that is deleting the values from the object.

```<code>const handleDeleteChips = (e, value) => {
    e.preventDefault();
    if (chipData[0].year == value) {
      dispatch(updateFilterYear(''));
    } else {
      dispatch(updateFilterProgramId(''));
    }
}
</code>```

I want as soon as I am disptaching, the state values should be changed to this:

```<code>filterData: {year: "", programId: "America"}
</code>```

So, I have a idea that in react this doesn't happens just after setting the state. The component has to re-render so for this i have implemented useEffect.
In useEffect, to capture the value change and  I have done this :

```<code>useEffect(()=>{
  dispatch(updateFilterYear(filterData.year));
}, [filterData.year])
</code>```

But it is still not working as expected. I am able to update the state values but not immediately. So is my code inside useEffect correct?

答:
const handleDeleteChips = (e, value) => {
    e.preventDefault();
    if (chipData[0].year == value) {
      dispatch(updateFilterYear(''));
      setFilterData: {...filterData,year: ""}
    } else {
      dispatch(updateFilterProgramId(''));
      setFilterData: {...filterData, programId:""}

    }
}```

Try this function ... Hope this solves your issue .

Body:
Hi I am trying to get my state values as soon as I am updating it. But cannot achieve this

My initial state looks like this:

filterData: {year: "2021", programId: "America"}

I have a handleDelete function that is deleting the values from the object.

const handleDeleteChips = (e, value) => {
    e.preventDefault();
    if (chipData[0].year == value) {
      dispatch(updateFilterYear(''));
    } else {
      dispatch(updateFilterProgramId(''));
    }
}

I want as soon as I am disptaching, the state values should be changed to this:

filterData: {year: "", programId: "America"}

So, I have a idea that in react this doesn't happens just after setting the state. The component has to re-render so for this i have implemented useEffect.
In useEffect, to capture the value change and  I have done this :

useEffect(()=>{
  dispatch(updateFilterYear(filterData.year));
}, [filterData.year])

But it is still not working as expected. I am able to update the state values but not immediately. So is my code inside useEffect correct?

Body:
const handleDeleteChips = (e, value) => {
    e.preventDefault();
    if (chipData[0].year == value) {
      dispatch(updateFilterYear(''));
      setFilterData: {...filterData,year: ""}
    } else {
      dispatch(updateFilterProgramId(''));
      setFilterData: {...filterData, programId:""}

    }
}

Try this function ... Hope this solves your issue .


问:
SSIS look up table questions
I am using SSIS (SQL Server 2008) to lookup values from a table. I wanted to know if the following are possible:

Question 1

Lookup Table 1

```<code>Manager_Name    EMP_UNIT    Job_Profile_ID
AAA             SALES       27
BBB             HR          28
AAA             SALES       29
</code>```

I have to pass the ‘Manager_Name ‘and ‘EMP_UNIT ‘value in the Lookup table and fetch
Job Profile ID in Comma separated format.
Like I will pass the Values ‘AAA’ and ‘SALES’ and I want the return value as 27,29
How will I do this?

Question 2

Lookup Table 2

```<code>Job_Profile_ID  Job_Name
27              Jr. Salesman
28              Sales Manager
29              Sr. Salesman
</code>```

I have to pass the Job Profile ID values in Comma separated format (27, 29) and
I want the return value in Comma separated format (Jr. Salesman, Sr. Salesman).
Is this possible in SSIS?

Environment details:
MS SQL Server integration services (bids) 2008 on windows 2008 server

any help is appreciated,

Thanks

答:
If I understand your question correctly, you need the list of job names for a given manager and employee unit combination. If that is the case, you need a stored procedure that can give the list of job names in a comma separated value.

In my opinion, two lookup transformation tasks seems to be a overkill.

Based on the data provided in the question, the section Create and populate tables provide the sample data.

Create the following stored procedure dbo.GetManagerJobProfiles that will take Manager_Name and Emp_Unit as input parameters and will return the list of matching job names for the given parameters as a comma separated list. This stored procedure uses FOR XML clause to generate the comma separated values. Since the comma is appended at the beginning, we have to truncate the first comma from the list. Hence, the substring function is used to do that job to give a cleaner output.

```<code>CREATE PROCEDURE dbo.GetManagerJobProfiles
(
        @Manager_Name   NVARCHAR(80)
    ,   @Emp_Unit       NVARCHAR(80)
)
AS
BEGIN
    SET NOCOUNT ON;

    SELECT SUBSTRING(
            (
                SELECT          ', ' + J.Job_Name
                FROM            dbo.Managers        M
                LEFT OUTER JOIN dbo.Jobs            J
                ON              M.Job_Profile_Id    = J.Job_Profile_Id
                WHERE           M.Manager_Name      = @Manager_Name
                AND             M.Emp_Unit          = @Emp_Unit
                FOR XML PATH ('')
            )
        , 3, 1000) AS Job_Name
END
GO
</code>```

Screenshot #1 shows the sample data in the tables dbo.Managers and dbo.Jobs.

Screenshot #2 shows the stored procedure output for two different sets of parameters.

If I have to use this in an SSIS package, I would get the list of distinct Manager_Name and Emp_Unit combinations using an Execute SQL Task and will populate the resultset into an SSIS Package variable of data type Object.

I will then loop through the object variable using Foreach loop container with Foreach ADO enumerator. Within the Foreach loop container, I will place a Data Flow Task. Within the data flow task, I will place an OLE DB Source which will use the stored procedure as the source. For each Manager_Name and Emp_Unit combination being looped through, the values will be passed as parameters to the OLE DB Source to fetch the Job name values.

Hope that helps.

Create and populate tables: This structure is based on the data provided in the question.

```<code>CREATE TABLE [dbo].[Jobs](
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [Job_Profile_Id] [int] NOT NULL,
    [Job_Name] [nvarchar](40) NOT NULL,
CONSTRAINT [PK_Jobs] PRIMARY KEY CLUSTERED ([Id] ASC)) ON [PRIMARY]
GO

CREATE TABLE [dbo].[Managers](
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [Manager_Name] [nvarchar](80) NOT NULL,
    [Emp_Unit] [nvarchar](80) NOT NULL,
    [Job_Profile_Id] [int] NOT NULL,
CONSTRAINT [PK_Managers] PRIMARY KEY CLUSTERED ([Id] ASC)) ON [PRIMARY]
GO

INSERT INTO dbo.Managers (Manager_Name, Emp_Unit, Job_Profile_Id) VALUES
    ('AAA', 'SALES', 27),
    ('BBB', 'HR', 28),
    ('AAA', 'SALES', 29);

INSERT INTO dbo.Jobs(Job_Profile_Id, Job_Name) VALUES
    (27, 'Jr. Salesman'),
    (28, 'Sales Manager'),
    (29, 'Sr. Salesman');
</code>```

Title: SSIS look up table questions

Body:
I am using SSIS (SQL Server 2008) to lookup values from a table. I wanted to know if the following are possible:

Question 1

Lookup Table 1

Manager_Name    EMP_UNIT    Job_Profile_ID
AAA             SALES       27
BBB             HR          28
AAA             SALES       29

I have to pass the ‘Manager_Name ‘and ‘EMP_UNIT ‘value in the Lookup table and fetch
Job Profile ID in Comma separated format.
Like I will pass the Values ‘AAA’ and ‘SALES’ and I want the return value as 27,29
How will I do this?

Question 2

Lookup Table 2

Job_Profile_ID  Job_Name
27              Jr. Salesman
28              Sales Manager
29              Sr. Salesman

I have to pass the Job Profile ID values in Comma separated format (27, 29) and
I want the return value in Comma separated format (Jr. Salesman, Sr. Salesman).
Is this possible in SSIS?

Environment details:
MS SQL Server integration services (bids) 2008 on windows 2008 server

any help is appreciated,

Thanks

Body:
If I understand your question correctly, you need the list of job names for a given manager and employee unit combination. If that is the case, you need a stored procedure that can give the list of job names in a comma separated value.

In my opinion, two lookup transformation tasks seems to be a overkill.

Based on the data provided in the question, the section Create and populate tables provide the sample data.

Create the following stored procedure dbo.GetManagerJobProfiles that will take Manager_Name and Emp_Unit as input parameters and will return the list of matching job names for the given parameters as a comma separated list. This stored procedure uses FOR XML clause to generate the comma separated values. Since the comma is appended at the beginning, we have to truncate the first comma from the list. Hence, the substring function is used to do that job to give a cleaner output.

CREATE PROCEDURE dbo.GetManagerJobProfiles
(
        @Manager_Name   NVARCHAR(80)
    ,   @Emp_Unit       NVARCHAR(80)
)
AS
BEGIN
    SET NOCOUNT ON;

    SELECT SUBSTRING(
            (
                SELECT          ', ' + J.Job_Name
                FROM            dbo.Managers        M
                LEFT OUTER JOIN dbo.Jobs            J
                ON              M.Job_Profile_Id    = J.Job_Profile_Id
                WHERE           M.Manager_Name      = @Manager_Name
                AND             M.Emp_Unit          = @Emp_Unit
                FOR XML PATH ('')
            )
        , 3, 1000) AS Job_Name
END
GO

Screenshot #1 shows the sample data in the tables dbo.Managers and dbo.Jobs.

Screenshot #2 shows the stored procedure output for two different sets of parameters.

If I have to use this in an SSIS package, I would get the list of distinct Manager_Name and Emp_Unit combinations using an Execute SQL Task and will populate the resultset into an SSIS Package variable of data type Object.

I will then loop through the object variable using Foreach loop container with Foreach ADO enumerator. Within the Foreach loop container, I will place a Data Flow Task. Within the data flow task, I will place an OLE DB Source which will use the stored procedure as the source. For each Manager_Name and Emp_Unit combination being looped through, the values will be passed as parameters to the OLE DB Source to fetch the Job name values.

Hope that helps.

Create and populate tables: This structure is based on the data provided in the question.

CREATE TABLE [dbo].[Jobs](
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [Job_Profile_Id] [int] NOT NULL,
    [Job_Name] [nvarchar](40) NOT NULL,
CONSTRAINT [PK_Jobs] PRIMARY KEY CLUSTERED ([Id] ASC)) ON [PRIMARY]
GO

CREATE TABLE [dbo].[Managers](
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [Manager_Name] [nvarchar](80) NOT NULL,
    [Emp_Unit] [nvarchar](80) NOT NULL,
    [Job_Profile_Id] [int] NOT NULL,
CONSTRAINT [PK_Managers] PRIMARY KEY CLUSTERED ([Id] ASC)) ON [PRIMARY]
GO

INSERT INTO dbo.Managers (Manager_Name, Emp_Unit, Job_Profile_Id) VALUES
    ('AAA', 'SALES', 27),
    ('BBB', 'HR', 28),
    ('AAA', 'SALES', 29);

INSERT INTO dbo.Jobs(Job_Profile_Id, Job_Name) VALUES
    (27, 'Jr. Salesman'),
    (28, 'Sales Manager'),
    (29, 'Sr. Salesman');


问:
How to write a python function to return True when there's even number of 0 in a integer and return False otherwise using recursion?
I am asked to write a function that returns True if there's even number of 0 digits in a positive integer and return False otherwise (using recursion). As an attempt, I have written a function that counts the number of 0 in an integer. May I know how can I modify the program so that it will return True and False?</p>
```<code>def valid(n):
    number = str(n)
    position = number.find("0")

    if "0" not in number:
        return 0

    return 1 + valid(number[(position+1):])

print(valid(12340006))

</code>```

答:
```<code>def valid(n):
    number = str(n)
    position = number.find("0")
    if "0" not in number:
        return 0
    return 1 + valid(number[(position+1):])
print("True" if valid(12340006)%2 ==0 else "False")
</code>```

Body:
I am asked to write a function that returns True if there's even number of 0 digits in a positive integer and return False otherwise (using recursion). As an attempt, I have written a function that counts the number of 0 in an integer. May I know how can I modify the program so that it will return True and False?

def valid(n):
    number = str(n)
    position = number.find("0")

    if "0" not in number:
        return 0

    return 1 + valid(number[(position+1):])

print(valid(12340006))


问:
retrieve minted NFT's by a wallet address - OpenSea
According to openSea api we use Retrieving events
Under event_type We found The event type to filter. Can be created for new auctions, successful for sales, cancelled, bid_entered, bid_withdrawn, transfer, or approve

My question here is how to find minted ones ?

IE: This wallet  Unnamed minted this token : Vortex #838

My Goal is to get list of all NFT's minted by specific user.

答:
I think collectibles is the same as NFT(ERC 721) so Try this

https://api.opensea.io/api/v1/collections?asset_owner=your_wallet_address&offset=0&limit=300


问:
In substrate, what is the equivocation handling system and KeyOwnerProof/Identification/ProofSystem in babe config?

        // The proof of key ownership, used for validating equivocation reports.
        /// The proof must include the session index and validator count of the
        /// session at which the equivocation occurred.
        type KeyOwnerProof: Parameter + GetSessionNumber + GetValidatorCount;

        /// The identification of a key owner, used when reporting equivocations.
        type KeyOwnerIdentification: Parameter;

        /// A system for proving ownership of keys, i.e. that a given key was part
        /// of a validator set, needed for validating equivocation reports.
        type KeyOwnerProofSystem: KeyOwnerProofSystem<
            (KeyTypeId, AuthorityId),
            Proof = Self::KeyOwnerProof,
            IdentificationTuple = Self::KeyOwnerIdentification,
        >;

        /// The equivocation handling subsystem, defines methods to report an
        /// offence (after the equivocation has been validated) and for submitting a
        /// transaction to report an equivocation (from an offchain context).
        /// NOTE: when enabling equivocation handling (i.e. this type isn't set to
        /// `()`) you must use this pallet's `ValidateUnsigned` in the runtime
        /// definition.
        type HandleEquivocation: HandleEquivocation<Self>;
```

What do these types mean and what are they for? I guess a better question is what are these equivocation reports that these types pertain to?

答: An equivocation report is a signaling that someone detected a Babe authority to have build two blocks on the same height. So, if someone detects a Babe authority building two blocks at the same height, it will issue such an equivocation report. It is up to chain how it wants to handle this. Polkadot for example will slash the offending authority.</p>

Body:
        // The proof of key ownership, used for validating equivocation reports.
        /// The proof must include the session index and validator count of the
        /// session at which the equivocation occurred.
        type KeyOwnerProof: Parameter + GetSessionNumber + GetValidatorCount;

        /// The identification of a key owner, used when reporting equivocations.
        type KeyOwnerIdentification: Parameter;

        /// A system for proving ownership of keys, i.e. that a given key was part
        /// of a validator set, needed for validating equivocation reports.
        type KeyOwnerProofSystem: KeyOwnerProofSystem<
            (KeyTypeId, AuthorityId),
            Proof = Self::KeyOwnerProof,
            IdentificationTuple = Self::KeyOwnerIdentification,
        >;

        /// The equivocation handling subsystem, defines methods to report an
        /// offence (after the equivocation has been validated) and for submitting a
        /// transaction to report an equivocation (from an offchain context).
        /// NOTE: when enabling equivocation handling (i.e. this type isn't set to
        /// `()`) you must use this pallet's `ValidateUnsigned` in the runtime
        /// definition.
        type HandleEquivocation: HandleEquivocation<Self>;

What do these types mean and what are they for? I guess a better question is what are these equivocation reports that these types pertain to?


问:
Write specific pages from multiple pdf files to a new pdf file
I have multiple pdf files that I want to extract a group of specific pages from where each set of pages is different for each pdf file. I have created a dictionary with the keys as the pdf file name and the values as the list of pages to be extracted from each pdf file (shown as key). I intend to extract the given pages from the associated pdf file and write them all to one new pdf file so that I can do data extraction on this final file. I have tried PyPDF4 as well as FPDF but no joy as yet as it gives me either a large pdf with blank pages or a pdf with just 1 or 2 pages extracted or error that the pdf object cannot be found. I am hoping to get some guidance on where I am going wrong with my approach. Below is my code:

```<code>import PyPDF4
from PyPDF4 import PdfFileReader, PdfFileWriter

for pdf,pgs in dic_11_1.items():
  pdf=list(dic_11_1.keys())
  pgs=list(dic_11_1.values())
  for i in range(0,len(pdf)):
    pages = pgs[i]
    object = open(pdf[i],'rb')
    pdfinput=PyPDF4.PdfFileReader(object,'rb')
    if pdfinput.isEncrypted:
        pdfinput.decrypt('')
    else:
        pdfinput
    for p in pages:
        page=pdfinput.getPage(p)
        pdf_writer=PyPDF4.PdfFileWriter()
        pdf_writer.addPage(page)
        with open('F111.pdf',mode='wb') as output:
            pdf_writer.write(output)
</code>```

The error that I get is 'PdfReadError: Could not find object.'

When I try FPDF with the following code, it runs a long time and gives me a large empty pdf file:

```<code>from fpdf import FPDF
import os
for pdf,pgs in dic_11_1.items():
  pdf_in=open(pdf,'rb')
  inputpdf=PdfFileReader(pdf_in,'rb')
  if inputpdf.isEncrypted:
    inputpdf.decrypt('')
  else:
    inputpdf
  for p in pgs:
    content=inputpdf.getPage(p).extractText()
    pdf = FPDF('P','mm','A4')
    pdf.add_page()
    pdf.set_font("arial", size = 10)
    for text in content:
        text2=text.encode('latin-1', 'replace').decode('latin-1')
        pdf.write(10,text2)
        pdf.ln(8)
        pdf.close()
        return_byte_string=pdf.output('F_11_1.pdf','S').encode('latin-1')
    pdf_file=open('F_11_1.pdf','wb')
    pdf_file.write(return_byte_string)
    pdf_file.close()
</code>```

Any guidance would be greatly appreciated. Thank you in advance

The solution provided by @SUTerliakov was great but only wrote the last page or last document from the the dictionary values list of pages. It was resolved with a minor indentation in the code and that got all my data for me. Thanks again @SUTerliakov for starting me on the correct path! Here is your adjusted code:

```<code>pdf_writer = PdfFileWriter()
open_files = []

try:
   for filename, pgs in dic_11_1.items():
      src = open(filename, 'rb')
      open_files.append(src)

      pdfinput = PdfFileReader(src, 'rb')

      if pdfinput.isEncrypted:
        pdfinput.decrypt('')
        print(f'Extracting relevant pages from {filename} to central repository')
        for p in pgs:
           print(f'{filename} pg{str(p)}')
           pdf_writer.addPage(pdfinput.getPage(p))
        print(f'Writing {len(pgs)} pages to central file')
   Stream=open('F_11_1.pdf','wb')
   pdf_writer.write(Stream)
finally:
   print('Closing Source File...')
   for f in open_files:
      f.close()
</code>```

答:
Well, the problem is you're not iterating properly. See comments in code for better understanding.

UPD. PyPDF4 seems to add only page references to PdfFileWriter until it's actually written to some file. So we can close input sources only at the end. Thus this method won't work for large files count (on linux it will be restricted by ulimit and by default it's 1024, so we can open only 1000 input files + 1 output file + 3 system streams - stdin, stdout, stderr; this limit can be enlarged with ulimit -n <count>).

from PyPDF4 import PdfFileReader, PdfFileWriter

sect_11_1 = [
    ('filename1.pdf', 0, 1),
    ('filename2.pdf', 0, 1),
]
# note pages are zero-numbered

dic_11_1 = {}

# if sect_11_1 is of another format
# [('filename', [0, 1]), ...]
# remove star below
for filename, *pages in sect_11_1:
    dic_11_1.setdefault(filename, [])
    dic_11_1[filename].extend(pages)

# if filenames are not repeated, you can do just
# dic_11_1 = dict(sect_11_1)

# you need single writer for all files, don't declare it in a loop
pdf_writer = PdfFileWriter()
open_files = []

try:
    for filename, pages in dic_11_1.items():
        # now you have filename and pages set to 'filename1.pdf' and [1, 3, 4]
        # on second iteration they'll be set to 'filename2.pdf' and [0, 2, 3]
        # ...

        # don't use `object` as variable name: it's valid, but bad style
        # (it shadows builtin `object`)

        src = open(filename, 'rb')
        open_files.append(src)

        pdfinput = PdfFileReader(src, 'rb')

        if pdfinput.isEncrypted:
            pdfinput.decrypt('')
            # you don't need empty `else`

        for p in pages:
            # you might want to use `p - 1` instead if your input was 1-numbered
            page = pdfinput.getPage(p)
            pdf_writer.addPage(page)

    # when all pages are added, write to output
    with open('F111.pdf',mode='wb') as output:
        pdf_writer.write(output)
finally:  # if something was wrong, do it anyway
    for f in open_files:
        f.close()  # we shouldn't keep files open after program run

```

Body:
I have multiple pdf files that I want to extract a group of specific pages from where each set of pages is different for each pdf file. I have created a dictionary with the keys as the pdf file name and the values as the list of pages to be extracted from each pdf file (shown as key). I intend to extract the given pages from the associated pdf file and write them all to one new pdf file so that I can do data extraction on this final file. I have tried PyPDF4 as well as FPDF but no joy as yet as it gives me either a large pdf with blank pages or a pdf with just 1 or 2 pages extracted or error that the pdf object cannot be found. I am hoping to get some guidance on where I am going wrong with my approach. Below is my code:

import PyPDF4
from PyPDF4 import PdfFileReader, PdfFileWriter

for pdf,pgs in dic_11_1.items():
  pdf=list(dic_11_1.keys())
  pgs=list(dic_11_1.values())
  for i in range(0,len(pdf)):
    pages = pgs[i]
    object = open(pdf[i],'rb')
    pdfinput=PyPDF4.PdfFileReader(object,'rb')
    if pdfinput.isEncrypted:
        pdfinput.decrypt('')
    else:
        pdfinput
    for p in pages:
        page=pdfinput.getPage(p)
        pdf_writer=PyPDF4.PdfFileWriter()
        pdf_writer.addPage(page)
        with open('F111.pdf',mode='wb') as output:
            pdf_writer.write(output)

The error that I get is 'PdfReadError: Could not find object.'

When I try FPDF with the following code, it runs a long time and gives me a large empty pdf file:

from fpdf import FPDF
import os
for pdf,pgs in dic_11_1.items():
  pdf_in=open(pdf,'rb')
  inputpdf=PdfFileReader(pdf_in,'rb')
  if inputpdf.isEncrypted:
    inputpdf.decrypt('')
  else:
    inputpdf
  for p in pgs:
    content=inputpdf.getPage(p).extractText()
    pdf = FPDF('P','mm','A4')
    pdf.add_page()
    pdf.set_font("arial", size = 10)
    for text in content:
        text2=text.encode('latin-1', 'replace').decode('latin-1')
        pdf.write(10,text2)
        pdf.ln(8)
        pdf.close()
        return_byte_string=pdf.output('F_11_1.pdf','S').encode('latin-1')
    pdf_file=open('F_11_1.pdf','wb')
    pdf_file.write(return_byte_string)
    pdf_file.close()

Any guidance would be greatly appreciated. Thank you in advance

The solution provided by @SUTerliakov was great but only wrote the last page or last document from the the dictionary values list of pages. It was resolved with a minor indentation in the code and that got all my data for me. Thanks again @SUTerliakov for starting me on the correct path! Here is your adjusted code:

pdf_writer = PdfFileWriter()
open_files = []

try:
   for filename, pgs in dic_11_1.items():
      src = open(filename, 'rb')
      open_files.append(src)

      pdfinput = PdfFileReader(src, 'rb')

      if pdfinput.isEncrypted:
        pdfinput.decrypt('')
        print(f'Extracting relevant pages from {filename} to central repository')
        for p in pgs:
           print(f'{filename} pg{str(p)}')
           pdf_writer.addPage(pdfinput.getPage(p))
        print(f'Writing {len(pgs)} pages to central file')
   Stream=open('F_11_1.pdf','wb')
   pdf_writer.write(Stream)
finally:
   print('Closing Source File...')
   for f in open_files:
      f.close()


问:
Nested append in javascript
I want to wrap both select and button under one div
. I have the below code working but unable to wrap it. I can't put
 in static HTML and append it.  Structure should be -

```<code><div id="container" class="row">
<div class="row">

<select id="SelColid0" name="SelColid0">
</select>

<select id="nameid0" name="nameid0">
</select>

<button id="clearid0" title="Clear Filter">
<i class="far fa-trash-alt"></i>
</button>

</div>
</div>
</code>```

$('#container')
      .append(
        $(document.createElement('select')).prop({
          id: "SelColid0",
          name: "SelColid0"
        })
      )
      .append(
        $(document.createElement('select')).prop({
          id: "nameid0",
          name: "nameid0"
        })
      )
      .append(
        $(document.createElement('button')).prop({
          id: "clearid0",
          innerHTML: '',
          title : 'Clear Filter'
        })
      )
    ```
<pre class="snippet-code-html lang-html prettyprint-override"><code> <script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js'></script>

 <div id="container" class= "row"></div></code>```

Select Column
name

Select Value

答:
You can simply append your div and then append all the rest of your content to that

$('#container')
  .append(
    $(document.createElement('div')).addClass("row")
    .append(
      $(document.createElement('select')).prop({
        id: "SelColid0",
        name: "SelColid0"
      })
    )
    .append(
      $(document.createElement('select')).prop({
        id: "nameid0",
        name: "nameid0"
      })
    )
    .append(
      $(document.createElement('button')).prop({
        id: "clearid0",
        innerHTML: '',
        title: 'Clear Filter'
      })
    )
  )```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js'></script>

<div id="container" class="row"></div></code>```

Title: Nested append in javascript

Body:
I want to wrap both select and button under one div
. I have the below code working but unable to wrap it. I can't put
 in static HTML and append it.  Structure should be -

<select id="SelColid0" name="SelColid0">
</select>

<select id="nameid0" name="nameid0">
</select>

<button id="clearid0" title="Clear Filter">

</button>

$('#container')
      .append(
        $(document.createElement('select')).prop({
          id: "SelColid0",
          name: "SelColid0"
        })
      )
      .append(
        $(document.createElement('select')).prop({
          id: "nameid0",
          name: "nameid0"
        })
      )
      .append(
        $(document.createElement('button')).prop({
          id: "clearid0",
          innerHTML: '',
          title : 'Clear Filter'
        })
      )

Select Column
name

Select Value

Body:
You can simply append your div and then append all the rest of your content to that

$('#container')
  .append(
    $(document.createElement('div')).addClass("row")
    .append(
      $(document.createElement('select')).prop({
        id: "SelColid0",
        name: "SelColid0"
      })
    )
    .append(
      $(document.createElement('select')).prop({
        id: "nameid0",
        name: "nameid0"
      })
    )
    .append(
      $(document.createElement('button')).prop({
        id: "clearid0",
        innerHTML: '<i class="far fa-trash-alt"></i>',
        title: 'Clear Filter'
      })
    )
  )

<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js'></script>

<div id="container" class="row"></div>


问:
How to improve the design of a page with multiple case statements
My page contains: GridView1, GridView2, Button1, Button2, DropDownList1
I bind Gridviews to the table selected in dropdown like this:

```<code>Dim results as DataTable
Select Case ddl1.SelectedValue
    Case 0
        results = dtZero
    Case 1
        results = dtOne
    Case 2
        results = dtTwo
    Case 3
        results = dtThree
End Select
GridView1.DataSource = results
GridView1.DataBind()
</code>```

Then I have two buttons with the following code:

```<code>Protected Sub btn1_Click(sender As Object, e As EventArgs) Handles btn2.Click
    Select Case ddl1.SelectedValue
        Case 0
            RunZero()
        Case 1
            RunOne()
        Case 2
            RunTwo()
        Case 3
            RunThree()
    End Select
End Sub
</code>```

And

```<code>Protected Sub btn2_Click(sender As Object, e As EventArgs) Handles btn2.Click
    Select Case ddl1.SelectedValue
        Case 0
            RemoveZero()
        Case 1
            RemoveOne()
        Case 2
            RemoveTwo()
        Case 3
            RemoveThree()
    End Select
End Sub
</code>```

For me it looks like a lot of overhead. How can I improve then design and only specify that I'm working on the following record in dropdown list without specifying the Case condition every time? Should I change my design or leave it like it is?

Update:
RunZero, RunOne, RunTwo, RemoveZero, RemoveOne, RemoveTwo, RemoveThree - Execute six different stored procedures.

答:
EDIT: This is suitable for VB.Net only, not ASP.Net.

A simpler way to acomplish this is to create a class with a ToString function and populate the list with that.

```<code>Class OpInfo

    Public Sub New(ByVal Text As String, ByVal DataTable As DataTableSelect, ByVal RunMethod As Action, ByVal RemoveMethod As Action)
        _Text = Text
        _DataTable = DataTable
        _RunMethod = RunMethod
        _RemoveMethod = RemoveMethod
    End Sub

    Public ReadOnly Property DataTable As DataTableSelect
        Get
            Return _DataTable
        End Get
    End Property
    Private _DataTable As DataTableSelect

    Public Sub Run()
        _RunMethod()
    End Sub
    Private _RunMethod As Action

    Public Sub Remove()
        _RemoveMethod()
    End Sub
    Private _RemoveMethod As Action

    Public Function Overrides ToString() As String
        Return _Text
    End Function
    Private _Text As String
End Class
</code>```

You can populate the list with instances of this class.  By type casting the selected item, you have access to all of its members.

```<code>Class Form1

    Public Sub New()
        InitializeComponents()
        ddl1.Items.Add(New OpInfo("Zero",  dtZero , AddressOf RunZero , AddressOf RemoveZero )
        ddl1.Items.Add(New OpInfo("One",   dtOne  , AddressOf RunOne  , AddressOf RemoveOne  )
        ddl1.Items.Add(New OpInfo("Two",   dtTwo  , AddressOf RunTwo  , AddressOf RemoveTwo  )
        ddl1.Items.Add(New OpInfo("Three", dtThree, AddressOf RunThree, AddressOf RemoveThree)
    End Sub

    Protected Sub ddl1_SelectedIndexChanged(sender As Object, e As EventArgs)
        If ddl1.SelectedIndex = -1 Then
            ' Code for when nothing is selected.
        Else
            GridView1.DataSource = CType(ddl1.SelectedItem, OpInfo).DataTable
            GridView1.DataBind()
        End If
    End Sub

    Protected Sub btn1_Click(sender As Object, e As EventArgs) Handles btn2.Click
        If ddl1.SelectedIndex <> -1 Then CType(ddl1.SelectedItem, OpInfo).Run
    End Sub

    Protected Sub btn2_Click(sender As Object, e As EventArgs) Handles btn2.Click
        If ddl1.SelectedIndex <> -1 Then CType(ddl1.SelectedItem, OpInfo).Remove
    End Sub
End Class
</code>```

Body:
My page contains: GridView1, GridView2, Button1, Button2, DropDownList1
I bind Gridviews to the table selected in dropdown like this:

Dim results as DataTable
Select Case ddl1.SelectedValue
    Case 0
        results = dtZero
    Case 1
        results = dtOne
    Case 2
        results = dtTwo
    Case 3
        results = dtThree
End Select
GridView1.DataSource = results
GridView1.DataBind()

Then I have two buttons with the following code:

Protected Sub btn1_Click(sender As Object, e As EventArgs) Handles btn2.Click
    Select Case ddl1.SelectedValue
        Case 0
            RunZero()
        Case 1
            RunOne()
        Case 2
            RunTwo()
        Case 3
            RunThree()
    End Select
End Sub

And

Protected Sub btn2_Click(sender As Object, e As EventArgs) Handles btn2.Click
    Select Case ddl1.SelectedValue
        Case 0
            RemoveZero()
        Case 1
            RemoveOne()
        Case 2
            RemoveTwo()
        Case 3
            RemoveThree()
    End Select
End Sub

For me it looks like a lot of overhead. How can I improve then design and only specify that I'm working on the following record in dropdown list without specifying the Case condition every time? Should I change my design or leave it like it is?

Update:
RunZero, RunOne, RunTwo, RemoveZero, RemoveOne, RemoveTwo, RemoveThree - Execute six different stored procedures.

Body:
EDIT: This is suitable for VB.Net only, not ASP.Net.

A simpler way to acomplish this is to create a class with a ToString function and populate the list with that.

Class OpInfo

    Public Sub New(ByVal Text As String, ByVal DataTable As DataTableSelect, ByVal RunMethod As Action, ByVal RemoveMethod As Action)
        _Text = Text
        _DataTable = DataTable
        _RunMethod = RunMethod
        _RemoveMethod = RemoveMethod
    End Sub

    Public ReadOnly Property DataTable As DataTableSelect
        Get
            Return _DataTable
        End Get
    End Property
    Private _DataTable As DataTableSelect

    Public Sub Run()
        _RunMethod()
    End Sub
    Private _RunMethod As Action

    Public Sub Remove()
        _RemoveMethod()
    End Sub
    Private _RemoveMethod As Action

    Public Function Overrides ToString() As String
        Return _Text
    End Function
    Private _Text As String
End Class

You can populate the list with instances of this class.  By type casting the selected item, you have access to all of its members.

Class Form1

    Public Sub New()
        InitializeComponents()
        ddl1.Items.Add(New OpInfo("Zero",  dtZero , AddressOf RunZero , AddressOf RemoveZero )
        ddl1.Items.Add(New OpInfo("One",   dtOne  , AddressOf RunOne  , AddressOf RemoveOne  )
        ddl1.Items.Add(New OpInfo("Two",   dtTwo  , AddressOf RunTwo  , AddressOf RemoveTwo  )
        ddl1.Items.Add(New OpInfo("Three", dtThree, AddressOf RunThree, AddressOf RemoveThree)
    End Sub

    Protected Sub ddl1_SelectedIndexChanged(sender As Object, e As EventArgs)
        If ddl1.SelectedIndex = -1 Then
            ' Code for when nothing is selected.
        Else
            GridView1.DataSource = CType(ddl1.SelectedItem, OpInfo).DataTable
            GridView1.DataBind()
        End If
    End Sub

    Protected Sub btn1_Click(sender As Object, e As EventArgs) Handles btn2.Click
        If ddl1.SelectedIndex <> -1 Then CType(ddl1.SelectedItem, OpInfo).Run
    End Sub

    Protected Sub btn2_Click(sender As Object, e As EventArgs) Handles btn2.Click
        If ddl1.SelectedIndex <> -1 Then CType(ddl1.SelectedItem, OpInfo).Remove
    End Sub
End Class


问:
How to pick merged rows and column in mail merge?
How Can I get the merge cells formatting in email? I have data in google sheet and I want to pick the data as it is in the mail. I took reference from the existing question but not able to pick the merged rows and columns in the email but instead of merging the cells, it returns to blank. See the attached images and sheet for references.

Any help is highly appriciated.

Script:

```<code>  const sendRichEmail = () => {
  const sheetName = 'Sheet1';
  const recipient = 'test@email.com';

  const richTextValue = SpreadsheetApp.getActiveSpreadsheet()
    .getSheetByName(sheetName)
    .getDataRange()
    .getRichTextValues();

  // get string equivalent of the data
  const values = SpreadsheetApp.getActiveSpreadsheet()
    .getSheetByName(sheetName)
    .getDataRange()
    .getDisplayValues();

  const backgroundColors = SpreadsheetApp.getActiveSpreadsheet()
    .getSheetByName(sheetName)
    .getDataRange()
    .getBackgrounds();

  // pass the current index of row and column
  const getRunAsHtml = (richTextRun, i, j) => {
    var richText = richTextRun.getText();
    // if richText is empty, assign value from getDisplayValues
    if (!richText)
      richText = values[i][j];
    const style = richTextRun.getTextStyle();
    const url = richTextRun.getLinkUrl();

    const styles = {
      color: style.getForegroundColor(),
      'font-family': style.getFontFamily(),
      'font-size': `${style.getFontSize()}pt`,
      'font-weight': style.isBold() ? 'bold' : '',
      'font-style': style.isItalic() ? 'italic' : '',
      'text-decoration': style.isUnderline() ? 'underline' : '',
    };

    if (style.isStrikethrough()) {
      styles['text-decoration'] = `${styles['text-decoration']} line-through`;
    }

    const css = Object.keys(styles)
      .filter((attr) => styles[attr])
      .map((attr) => [attr, styles[attr]].join(':'))
      .join(';');

    const styledText = `<span style='${css}'>${richText}</span>`;
    return url ? `<a href='${url}'>${styledText}</a>` : styledText;
  };

  var finalBody = `<html><body><table border='1px'>`;
  for (var i = 0; i < richTextValue.length; i++) {
    finalBody += '<tr>';
    for (var j = 0; j < richTextValue[i].length; j++) {
      finalBody += `<td bgcolor='${backgroundColors[i][j]}'>`;
      // pass i and j into getRunAsHtml
      finalBody += richTextValue[i][j].getRuns().map((run) => getRunAsHtml(run, i, j)).join('');
      finalBody = finalBody.replace(/\n/g, '<br>');
      finalBody += '</td>';
    }
    finalBody += '</tr>';
  }
  finalBody += '</table></body></html>';

  MailApp.sendEmail({ to: recipient, subject: 'Rich HTML Email', htmlBody: finalBody });
};
</code>```

Screenshot:
Data in Sheet
Email Received

答:
Try with that script

```<code>const sendRichEmailWithMergedCells = () => {
  const recipient = 'test@email.com';
  const sheetName = 'Sheet1';
  const range = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheetName).getDataRange()
  MailApp.sendEmail({ to: recipient, subject: 'Rich HTML Email', htmlBody: tableHTML(range) });
};
</code>```

with

```<code>function tableHTML(range){
  var data      = range.getDisplayValues()
  var size      = range.getFontSizes()
  var style     = range.getFontStyles()
  var weight    = range.getFontWeights()
  var line      = range.getFontLines()
  var bg        = range.getBackgrounds()
  var color     = range.getFontColors()
  var font      = range.getFontFamilies()
  var textalign = range.getHorizontalAlignments()
  var offsetx   = range.getRow()
  var offsety   = range.getColumn()

  var mergedRanges = range.getMergedRanges();
  var flag = Array.from({ length: range.getNumRows() }, () => Array.from({ length: range.getNumColumns() }, () => true));
  var layout = Array.from({ length: range.getNumRows() }, () => Array.from({ length: range.getNumColumns() }, () => ''));
  mergedRanges.forEach((rng,i) => {
    for (x=rng.getRow();x<rng.getRow()+rng.getNumRows();x++){
      for (y=rng.getColumn();y<rng.getColumn()+rng.getNumColumns();y++){
        try{flag[x-offsetx][y-offsety]=false}catch(e){}
      }
    }
    flag[rng.getRow()-offsetx][rng.getColumn()-offsety]=true
    layout[rng.getRow()-offsetx][rng.getColumn()-offsety]=' colspan="'+rng.getNumColumns()+'" rowspan="'+rng.getNumRows()+'" '
  });

  var htmltable = '<table cellspacing=0 cellspadding=2px  border="1px">';
  for (row = 0; row<data.length; row++){
    htmltable += '<tr>';
    for (col = 0 ;col<data[row].length; col++){
      if (flag[row][col]){
        if (data[row][col] === '') {
          htmltable += '<td '+layout[row][col]+' style="background-color:' + bg[row][col] + ';">' + ' ' + '</td>';
        }
        else
          htmltable += `<td ${layout[row][col]} style="font-family:${font[row][col]};
            background-color:${bg[row][col]};
            color:${color[row][col]};
            font-style:${style[row][col]};
            font-weight:${weight[row][col]};
            text-decoration:${line[row][col]};
            font-size:${size[row][col]}'px';
            text-align:${textalign[row][col]};">${data[row][col].replace(/(\r\n|\n|\r)/gm,"<br>")}'</td>`;
        }
      }
    htmltable += '</tr>';
  }
  htmltable += '</table>';
  return htmltable
}
</code>```

Body:
How Can I get the merge cells formatting in email? I have data in google sheet and I want to pick the data as it is in the mail. I took reference from the existing question but not able to pick the merged rows and columns in the email but instead of merging the cells, it returns to blank. See the attached images and sheet for references.

Any help is highly appriciated.

Script:

  const sendRichEmail = () => {
  const sheetName = 'Sheet1';
  const recipient = 'test@email.com';

  const richTextValue = SpreadsheetApp.getActiveSpreadsheet()
    .getSheetByName(sheetName)
    .getDataRange()
    .getRichTextValues();

  // get string equivalent of the data
  const values = SpreadsheetApp.getActiveSpreadsheet()
    .getSheetByName(sheetName)
    .getDataRange()
    .getDisplayValues();

  const backgroundColors = SpreadsheetApp.getActiveSpreadsheet()
    .getSheetByName(sheetName)
    .getDataRange()
    .getBackgrounds();

  // pass the current index of row and column
  const getRunAsHtml = (richTextRun, i, j) => {
    var richText = richTextRun.getText();
    // if richText is empty, assign value from getDisplayValues
    if (!richText)
      richText = values[i][j];
    const style = richTextRun.getTextStyle();
    const url = richTextRun.getLinkUrl();

    const styles = {
      color: style.getForegroundColor(),
      'font-family': style.getFontFamily(),
      'font-size': `${style.getFontSize()}pt`,
      'font-weight': style.isBold() ? 'bold' : '',
      'font-style': style.isItalic() ? 'italic' : '',
      'text-decoration': style.isUnderline() ? 'underline' : '',
    };

    if (style.isStrikethrough()) {
      styles['text-decoration'] = `${styles['text-decoration']} line-through`;
    }

    const css = Object.keys(styles)
      .filter((attr) => styles[attr])
      .map((attr) => [attr, styles[attr]].join(':'))
      .join(';');

    const styledText = `<span style='${css}'>${richText}</span>`;
    return url ? `<a href='${url}'>${styledText}</a>` : styledText;
  };

  var finalBody = `<html><body><table border='1px'>`;
  for (var i = 0; i < richTextValue.length; i++) {
    finalBody += '
';
    for (var j = 0; j < richTextValue[i].length; j++) {
      finalBody += `<td bgcolor='${backgroundColors[i][j]}'>`;
      // pass i and j into getRunAsHtml
      finalBody += richTextValue[i][j].getRuns().map((run) => getRunAsHtml(run, i, j)).join('');
      finalBody = finalBody.replace(/\n/g, '
');
      finalBody += '	';
    }
    finalBody += '
';
  }
  finalBody += '
';

  MailApp.sendEmail({ to: recipient, subject: 'Rich HTML Email', htmlBody: finalBody });
};

Screenshot:
Data in Sheet
Email Received

Body:
Try with that script

const sendRichEmailWithMergedCells = () => {
  const recipient = 'test@email.com';
  const sheetName = 'Sheet1';
  const range = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheetName).getDataRange()
  MailApp.sendEmail({ to: recipient, subject: 'Rich HTML Email', htmlBody: tableHTML(range) });
};

with

function tableHTML(range){
  var data      = range.getDisplayValues()
  var size      = range.getFontSizes()
  var style     = range.getFontStyles()
  var weight    = range.getFontWeights()
  var line      = range.getFontLines()
  var bg        = range.getBackgrounds()
  var color     = range.getFontColors()
  var font      = range.getFontFamilies()
  var textalign = range.getHorizontalAlignments()
  var offsetx   = range.getRow()
  var offsety   = range.getColumn()

  var mergedRanges = range.getMergedRanges();
  var flag = Array.from({ length: range.getNumRows() }, () => Array.from({ length: range.getNumColumns() }, () => true));
  var layout = Array.from({ length: range.getNumRows() }, () => Array.from({ length: range.getNumColumns() }, () => ''));
  mergedRanges.forEach((rng,i) => {
    for (x=rng.getRow();x<rng.getRow()+rng.getNumRows();x++){
      for (y=rng.getColumn();y<rng.getColumn()+rng.getNumColumns();y++){
        try{flag[x-offsetx][y-offsety]=false}catch(e){}
      }
    }
    flag[rng.getRow()-offsetx][rng.getColumn()-offsety]=true
    layout[rng.getRow()-offsetx][rng.getColumn()-offsety]=' colspan="'+rng.getNumColumns()+'" rowspan="'+rng.getNumRows()+'" '
  });

  var htmltable = '<table cellspacing=0 cellspadding=2px  border="1px">';
  for (row = 0; row<data.length; row++){
    htmltable += '<tr>';
    for (col = 0 ;col<data[row].length; col++){
      if (flag[row][col]){
        if (data[row][col] === '') {
          htmltable += '<td '+layout[row][col]+' style="background-color:' + bg[row][col] + ';">' + '&nbsp;' + '</td>';
        }
        else
          htmltable += `<td ${layout[row][col]} style="font-family:${font[row][col]};
            background-color:${bg[row][col]};
            color:${color[row][col]};
            font-style:${style[row][col]};
            font-weight:${weight[row][col]};
            text-decoration:${line[row][col]};
            font-size:${size[row][col]}'px';
            text-align:${textalign[row][col]};">${data[row][col].replace(/(\r\n|\n|\r)/gm,"<br>")}'</td>`;
        }
      }
    htmltable += '</tr>';
  }
  htmltable += '</table>';
  return htmltable
}


问:
Create JWT from secrete and payload in Spring boot
I am new to spring boot and want to create and sign JWT in Spring boot from an existing secret and pyload similar to the following Js method.
What would be the best way for doing that?</p>
```<code> /**
     * const
     *     secret = 'lkjfjkfpofpofwrtvrhvghjbjtzjnzuiom89oölfknwundidmttdhvtotunkbzilrorjfnliozknbdgbM',
     *     solName = 'mysolution';
     *
     * // Step 1: prepare header and payload
     * const
     *     header = {"typ": "JWT", "alg": "HS256"},
     *     date = (new Date()).toISOString(),
     *     payload = {"date": date, "name": solName};
     *
     * // Step 2: create JSON Web Token
     * const
     *     // helper function for url compatible base64 encoding
     *     base64url = (s) => CryptoJS.enc.Base64.stringify(s).replace(/=+$/, '').replace(/\+/g, '-').replace(/\//g, '_'),
     *
     *     // encode header and payload
     *     encodedHeader = base64url(CryptoJS.enc.Utf8.parse(JSON.stringify(header))),
     *     encodedPayload = base64url(CryptoJS.enc.Utf8.parse(JSON.stringify(payload))),
     *
     *     // build token
     *     token = encodedHeader + "." + encodedPayload,
     *
     *     // sign token
     *     signature = base64url(CryptoJS.HmacSHA256(token, secret)),
     *
     *     // concatenate token and signature to get the full JSON Web Token
     *     jwt = token + "." + signature;
     *
     * // Step 3: set request headers
     * console.log(`Setting request HTTP headers:`, {
     *     "X-DC-DATE": date,
     *     "X-DC-FRIEND": jwt
     * });
     * pm.request.headers.add({key: 'X-DC-DATE', value: date });
     * pm.request.headers.add({key: 'X-DC-FRIEND', value: jwt });
     */
</code>```

答:
You could do something like this:

add this to your pom.xml:

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
    <dependency>
        <groupId>io.jsonwebtoken</groupId>
        <artifactId>jjwt</artifactId>
        <version>0.9.1</version>
    </dependency>
</dependencies>
```
<p>and create a util class for generating your tokens:</p>
<pre class="lang-java prettyprint-override"><code>@Service
public class JwtUtil {

    private String secret;
    private int jwtExpirationInMs;

    @Value("${jwt.secret}")
    public void setSecret(String secret) {
        this.secret = secret;
    }

    @Value("${jwt.expirationDateInMs}")
    public void setJwtExpirationInMs(int jwtExpirationInMs) {
        this.jwtExpirationInMs = jwtExpirationInMs;
    }

    // generate token for user
    public String generateToken(UserDetails userDetails) {
        Map<String, Object> claims = new HashMap<>();
        Collection<? extends GrantedAuthority> roles = userDetails.getAuthorities();
        if (roles.contains(new SimpleGrantedAuthority("ROLE_ADMIN"))) {
            claims.put("isAdmin", true);
        }
        if (roles.contains(new SimpleGrantedAuthority("ROLE_USER"))) {
            claims.put("isUser", true);
        }
        return doGenerateToken(claims, userDetails.getUsername());
    }

    private String doGenerateToken(Map<String, Object> claims, String subject) {
        return Jwts.builder().setClaims(claims).setSubject(subject)
                .setIssuedAt(new Date(System.currentTimeMillis()))
                .setExpiration(new Date(System.currentTimeMillis() + jwtExpirationInMs))
                .signWith(SignatureAlgorithm.HS512, secret).compact();
    }

}
</code>```

Take a look at hashicorp vault for a secure way of storing your secret (you dont want this in your
property file)

add the following to your properties file and choose sensible defaults for your use case:

```<code>jwt.jwtExpirationInMs=18000000
</code>```

you can modify the algorithm to HS256 on this line:

return Jwts.builder()
        .setClaims(claims)
        .setSubject(subject)
        .setIssuedAt(
          new Date(System.currentTimeMillis())).setExpiration(new Date(System.currentTimeMillis()+jwtExpirationInMs)
        )
        .signWith(SignatureAlgorithm.HS512,secret).compact();
```

but I prefer HS512 (it's faster on 64 bit machines)

Body:
I am new to spring boot and want to create and sign JWT in Spring boot from an existing secret and pyload similar to the following Js method.
What would be the best way for doing that?

 /**
     * const
     *     secret = 'lkjfjkfpofpofwrtvrhvghjbjtzjnzuiom89oölfknwundidmttdhvtotunkbzilrorjfnliozknbdgbM',
     *     solName = 'mysolution';
     *
     * // Step 1: prepare header and payload
     * const
     *     header = {"typ": "JWT", "alg": "HS256"},
     *     date = (new Date()).toISOString(),
     *     payload = {"date": date, "name": solName};
     *
     * // Step 2: create JSON Web Token
     * const
     *     // helper function for url compatible base64 encoding
     *     base64url = (s) => CryptoJS.enc.Base64.stringify(s).replace(/=+$/, '').replace(/\+/g, '-').replace(/\//g, '_'),
     *
     *     // encode header and payload
     *     encodedHeader = base64url(CryptoJS.enc.Utf8.parse(JSON.stringify(header))),
     *     encodedPayload = base64url(CryptoJS.enc.Utf8.parse(JSON.stringify(payload))),
     *
     *     // build token
     *     token = encodedHeader + "." + encodedPayload,
     *
     *     // sign token
     *     signature = base64url(CryptoJS.HmacSHA256(token, secret)),
     *
     *     // concatenate token and signature to get the full JSON Web Token
     *     jwt = token + "." + signature;
     *
     * // Step 3: set request headers
     * console.log(`Setting request HTTP headers:`, {
     *     "X-DC-DATE": date,
     *     "X-DC-FRIEND": jwt
     * });
     * pm.request.headers.add({key: 'X-DC-DATE', value: date });
     * pm.request.headers.add({key: 'X-DC-FRIEND', value: jwt });
     */

Body:
You could do something like this:

add this to your pom.xml:

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
    <dependency>
        <groupId>io.jsonwebtoken</groupId>
        <artifactId>jjwt</artifactId>
        <version>0.9.1</version>
    </dependency>
</dependencies>

and create a util class for generating your tokens:

@Service
public class JwtUtil {

    private String secret;
    private int jwtExpirationInMs;

    @Value("${jwt.secret}")
    public void setSecret(String secret) {
        this.secret = secret;
    }

    @Value("${jwt.expirationDateInMs}")
    public void setJwtExpirationInMs(int jwtExpirationInMs) {
        this.jwtExpirationInMs = jwtExpirationInMs;
    }

    // generate token for user
    public String generateToken(UserDetails userDetails) {
        Map<String, Object> claims = new HashMap<>();
        Collection<? extends GrantedAuthority> roles = userDetails.getAuthorities();
        if (roles.contains(new SimpleGrantedAuthority("ROLE_ADMIN"))) {
            claims.put("isAdmin", true);
        }
        if (roles.contains(new SimpleGrantedAuthority("ROLE_USER"))) {
            claims.put("isUser", true);
        }
        return doGenerateToken(claims, userDetails.getUsername());
    }

    private String doGenerateToken(Map<String, Object> claims, String subject) {
        return Jwts.builder().setClaims(claims).setSubject(subject)
                .setIssuedAt(new Date(System.currentTimeMillis()))
                .setExpiration(new Date(System.currentTimeMillis() + jwtExpirationInMs))
                .signWith(SignatureAlgorithm.HS512, secret).compact();
    }

}

Take a look at hashicorp vault for a secure way of storing your secret (you dont want this in your
property file)

add the following to your properties file and choose sensible defaults for your use case:

jwt.jwtExpirationInMs=18000000

you can modify the algorithm to HS256 on this line:

return Jwts.builder()
        .setClaims(claims)
        .setSubject(subject)
        .setIssuedAt(
          new Date(System.currentTimeMillis())).setExpiration(new Date(System.currentTimeMillis()+jwtExpirationInMs)
        )
        .signWith(SignatureAlgorithm.HS512,secret).compact();

but I prefer HS512 (it's faster on 64 bit machines)


问:
Is there any way to declare variables in SqlDbx 3.47?
Let's say I want to do something like this, but I don't know how to do it in SqlDbx.

```<code>DECLARE @COUNT INT;
SET @COUNT = (SELECT COUNT(*) FROM products);
SELECT @COUNT;
</code>```

or it could be something like that

```<code>DECLARE @A INT;
DECLARE @B INT;
SET @A = 1;
SET @B = 2;

IF @A > @B
BEGIN
   PRINT 'FALSE'
END
</code>```

Can something like that be done in SqlDbx?

答:
For IBM i  (that is,  Db2 for i series) you can use a dynamic compound statement which allows an anonymous block to declare variables and use those variables in various ways for server-side processing.

Remember that with compound-SQL, everything runs on the Db2-server , not on  your client workstation (i.e. not in SQLDbx) , so you cannot use a print statement because that is not SQL.

If you need to pass parameters into the block, then consider creating a routine (a stored procedure, or a user defined function).  If you need to get result sets , use either a stored procedure or a table function.

Refer to the IBM i knowledge centre for all the details of which SQL statements are allowed in dynamic compound statements. There are many rules and restrictions.

Body:
Let's say I want to do something like this, but I don't know how to do it in SqlDbx.

DECLARE @COUNT INT;
SET @COUNT = (SELECT COUNT(*) FROM products);
SELECT @COUNT;

or it could be something like that

DECLARE @A INT;
DECLARE @B INT;
SET @A = 1;
SET @B = 2;

IF @A > @B
BEGIN
   PRINT 'FALSE'
END

Can something like that be done in SqlDbx?


问:
iPhone - Changing Bundle identifier : what will happen?
What may happen if I change my app bundle identifier ?

For example, if I go from com.myapps.appname to com.myapps.utilities.appname, or com.myapps.appname.appnameFULL

What may happen for people who have already bought the app ?

What may happen with stored datas ?

...

答: You will not be allowed to change it in iTunesConnect so there is no ramification as there is no possible way to do it. If you create a new app with a new bundle id, obviously old users of the other app will not get the updates. See this related question</p>


问:
Teechart set num of decimals on Axis and hide Axis labels for further series
hope you can help me.
In Builder C++ create a new "Windows VCL Application". Add a "Tchart" from "Palette".
Right click on the chart -> Edit Chart -> Click on Series -> Add... -> Line -> Ok to create Series1 and repeat to create Series2.
Close
In Unit1.cpp copy my following sample:

```<code>//---------------------------------------------------------------------------

#include <vcl.h>
#pragma hdrstop

#include "Unit1.h"
#include <vector>
//---------------------------------------------------------------------------

#pragma package(smart_init)
#pragma resource "*.dfm"
TForm1 *Form1;
//---------------------------------------------------------------------------

__fastcall TForm1::TForm1(TComponent* Owner)
    : TForm(Owner)

{
    std::vector<float> x1, y1, x2, y2;

for (int i = 0; i < 2000; i++) {
     float r1 = static_cast <float> (rand()) / static_cast <float> (RAND_MAX);
     float r2 = static_cast <float> (rand()) / static_cast <float> (RAND_MAX);
     x1.push_back(i+r1);
     y1.push_back(r1);
     x2.push_back(i+r2);
     y2.push_back(r2);

}

Chart1->BottomAxis->AxisValuesFormat = "0.0";

for (unsigned i = 0; i < x1.size(); i++) {
    Chart1->Series[0]->AddY(y1[i], x1[i]);
    Chart1->Series[1]->AddY(y2[i], x2[i]);
}
}
//---------------------------------------------------------------------------
</code>```

Compile and run. As you can see the values on the X axis appear overlapped.

In order to solve I would

display the X axis values with only 1 decimal

hide the X axis labels for Series1 (i. e., Series2)

For the 1st point I've tried as you see in the code but it seems not working.
Thank you very much in advance.

答:
You are adding points to the Line series with the AddY method, passing the x values as the second parameter, which is the label.

Doing so, the bottom axis labels indeed overlap.

Instead, I'd use the AddXY method, passing the x values as the first parameter and the y values as the second:

```<code>for (unsigned i = 0; i < x1.size(); i++) {
    Chart1->Series[0]->AddXY(x1[i], y1[i]);
    Chart1->Series[1]->AddXY(x2[i], y2[i]);
}
</code>```

This looks fine for me here:

Body:
hope you can help me.
In Builder C++ create a new "Windows VCL Application". Add a "Tchart" from "Palette".
Right click on the chart -> Edit Chart -> Click on Series -> Add... -> Line -> Ok to create Series1 and repeat to create Series2.
Close
In Unit1.cpp copy my following sample:

//---------------------------------------------------------------------------

#include <vcl.h>
#pragma hdrstop

#include "Unit1.h"
#include <vector>
//---------------------------------------------------------------------------

#pragma package(smart_init)
#pragma resource "*.dfm"
TForm1 *Form1;
//---------------------------------------------------------------------------

__fastcall TForm1::TForm1(TComponent* Owner)
    : TForm(Owner)

{
    std::vector<float> x1, y1, x2, y2;

for (int i = 0; i < 2000; i++) {
     float r1 = static_cast <float> (rand()) / static_cast <float> (RAND_MAX);
     float r2 = static_cast <float> (rand()) / static_cast <float> (RAND_MAX);
     x1.push_back(i+r1);
     y1.push_back(r1);
     x2.push_back(i+r2);
     y2.push_back(r2);

}

Chart1->BottomAxis->AxisValuesFormat = "0.0";

for (unsigned i = 0; i < x1.size(); i++) {
    Chart1->Series[0]->AddY(y1[i], x1[i]);
    Chart1->Series[1]->AddY(y2[i], x2[i]);
}
}
//---------------------------------------------------------------------------

Compile and run. As you can see the values on the X axis appear overlapped.

In order to solve I would

display the X axis values with only 1 decimal

hide the X axis labels for Series1 (i. e., Series2)

For the 1st point I've tried as you see in the code but it seems not working.
Thank you very much in advance.

Body:
You are adding points to the Line series with the AddY method, passing the x values as the second parameter, which is the label.

Doing so, the bottom axis labels indeed overlap.

Instead, I'd use the AddXY method, passing the x values as the first parameter and the y values as the second:

for (unsigned i = 0; i < x1.size(); i++) {
    Chart1->Series[0]->AddXY(x1[i], y1[i]);
    Chart1->Series[1]->AddXY(x2[i], y2[i]);
}

This looks fine for me here:


问:
AttributeError: shape | When using skimage resize with pyscreenshot.grab() as input?
I'm attempting to resize an image captured using pyscreenshot.grab() to 28x28 pixels

```<code>import pyscreenshot
from skimage.transform import resize

def captureAndSubsample():
    userImage = pyscreenshot.grab(bbox=(785, 335, 1125, 675))
    userImageResized = resize(userImage, (28, 28))
</code>```

This code returns:

```<code>>
File "C:\Users\brad\Desktop\Development\Code\main.py", line 178, in captureAndSubsample
    userImageResized = resize(userImage, (100, 100), 3)
  File "C:\Users\brad\Desktop\Development\Code\venv\lib\site-packages\skimage\transform\_warps.py", line 144, in resize
    image, output_shape = _preprocess_resize_output_shape(image, output_shape)
  File "C:\Users\brad\Desktop\Development\Code\venv\lib\site-packages\skimage\transform\_warps.py", line 56, in _preprocess_resize_output_shape
    input_shape = image.shape
  File "C:\Users\brad\Desktop\Development\Code\venv\lib\site-packages\PIL\Image.py", line 519, in     __getattr__
    raise AttributeError(name)
AttributeError: shape
<
</code>```

I've tried changing the input image to a shape:

```<code>def captureAndSubsample():
    userImage = pyscreenshot.grab(bbox=(785, 335, 1125, 675))
    userImage = shape(userImage)
    userImageResized = resize(userImage, (100, 100)).shape(340, 340)
</code>```

But this returns the same as it just returns a tuple of the dimensions, any and all help is appreciated.

答:
Converting userImage to a numpy array before passing to the scikit-image function does the trick.

```<code>import pyscreenshot
import numpy as np
from skimage.transform import resize

userImage = pyscreenshot.grab(bbox=(785, 335, 1125, 675))
userImage = np.array(userImage)
userImageResized = resize(userImage, (28, 28))
</code>```

Body:
I'm attempting to resize an image captured using pyscreenshot.grab() to 28x28 pixels

import pyscreenshot
from skimage.transform import resize

def captureAndSubsample():
    userImage = pyscreenshot.grab(bbox=(785, 335, 1125, 675))
    userImageResized = resize(userImage, (28, 28))

This code returns:

>
File "C:\Users\brad\Desktop\Development\Code\main.py", line 178, in captureAndSubsample
    userImageResized = resize(userImage, (100, 100), 3)
  File "C:\Users\brad\Desktop\Development\Code\venv\lib\site-packages\skimage\transform\_warps.py", line 144, in resize
    image, output_shape = _preprocess_resize_output_shape(image, output_shape)
  File "C:\Users\brad\Desktop\Development\Code\venv\lib\site-packages\skimage\transform\_warps.py", line 56, in _preprocess_resize_output_shape
    input_shape = image.shape
  File "C:\Users\brad\Desktop\Development\Code\venv\lib\site-packages\PIL\Image.py", line 519, in     __getattr__
    raise AttributeError(name)
AttributeError: shape
<

I've tried changing the input image to a shape:

def captureAndSubsample():
    userImage = pyscreenshot.grab(bbox=(785, 335, 1125, 675))
    userImage = shape(userImage)
    userImageResized = resize(userImage, (100, 100)).shape(340, 340)

But this returns the same as it just returns a tuple of the dimensions, any and all help is appreciated.

Body:
Converting userImage to a numpy array before passing to the scikit-image function does the trick.

import pyscreenshot
import numpy as np
from skimage.transform import resize

userImage = pyscreenshot.grab(bbox=(785, 335, 1125, 675))
userImage = np.array(userImage)
userImageResized = resize(userImage, (28, 28))


问:
Paypal API, Curl request, get list of orders of customers
Need a Curl command who can get all transaction_id between two dates.

Exemple :

```<code>curl -v -X GET https://api-m.sandbox.paypal.com/v1/reporting/transactions?start_date=2021-12-01T00:00:00-0700&end_date=2021-12-30T23:59:59-0700&transaction_id=XXXXXXXXXXXXX&fields=all&page_size=100&page=1 \
-H "Content-Type: application/json" \
-H "Authorization: Bearer %token%"
</code>```

But without the transaction_id.

答:
Remove &transaction_id=XXXXXXXXXXXXX from your API call

Preston PHX

Body:
Need a Curl command who can get all transaction_id between two dates.

Exemple :

curl -v -X GET https://api-m.sandbox.paypal.com/v1/reporting/transactions?start_date=2021-12-01T00:00:00-0700&end_date=2021-12-30T23:59:59-0700&transaction_id=XXXXXXXXXXXXX&fields=all&page_size=100&page=1 \
-H "Content-Type: application/json" \
-H "Authorization: Bearer %token%"

But without the transaction_id.


问:
Setting up Azure B2C with React
I am trying to configure my react/.NET 5.0 application to work with Azure B2C.  I have everything set up , I have tried to run this against an MVC application and I get the login screen.  But for some reason, when I try to redirect from a react page, I keep getting the same error.  There appears to be almost no real good documentation for this as well.  This is my authConfig file.

```<code>export const msalConfig = {

    auth: {
        clientId: process.env.REACT_APP_ADB2C_CLIENT_ID
        , authority: process.env.REACT_APP_ADB2C_AUTHORITY
        , knownAuthorities: [process.env.REACT_APP_KNOWN_AUTH]
        , clientSecret: process.env.REACT_APP_CLIENT_SECRET
        , reponseType: 'code'
      },
    cache: {
        cacheLocation: 'sessionStorage'
        ,storeAuthStateInCoolie: false
    }
};

const b2cPolicies = {
    name: {
        signUpSignIn: "B2C_1_cp_signin_up"
        , forgotPassword: "B2C_1_cp_forgot_pwd"
        , editProfile: "B2C_1_cp_edit_profile"
    },
    authorities: {
        signUpSignIn: {
            authority: `https://${process.env.REACT_APP_TENANT_LOGIN}/${process.env.REACT_APP_TENANT}/${process.env.REACT_APP_SIGNUP_POLICY}`,
        },
        forgotPassword: {
            authority: `https://${process.env.REACT_APP_TENANT_LOGIN}/${process.env.REACT_APP_TENANT}/${process.env.REACT_APP_FORGOT_POLICY}`,
        },
        editProfile: {
            authority: `https://${process.env.REACT_APP_TENANT_LOGIN}/${process.env.REACT_APP_TENANT}/${process.env.REACT_APP_EDIT_POLICY}`
        }
    },
    authorityDomain: process.env.REACT_APP_TENANT_LOGIN
}

export const loginRequest = {
    scopes: ["openid", "profile"],
};
</code>```

I keep running into this error when I click on the link to redirect.

Any help with this would be great.

答:
The reply URL must begin with the scheme https. Please check if reply urls are configured correctly which must be same in azure portal and in code .

Check if the callback path is set to identity provider something like /signin-oidc for redirect url .(And make sure you have unique callback if multiple urls are used.
such as https://contoso.com/signin-oidc.

The CallbackPath is the path where server will redirect during authentication. It's automatically handled by the OIDC middleware itself, that means we can't control the logic by creating a new controller/action and set CallbackPath to it

If you have check marked id_token in portal, try redirecting to home page ,instead of api actions directly.

Change the cookies to be set as secure using this in start up class

services.Configure(options =>
{
options.CheckConsentNeeded = context => true;//add if consent needed
options.MinimumSameSitePolicy = SameSiteMode.None; // else try  SameSiteMode.Lax;
options.Secure = CookieSecurePolicy.Always;

});

use Microsoft.AspNetCore.HttpOverrides;  reference in startup.cs class, by including the nuget package.

Also check and Add > app.UseHttpsRedirection(); above app.authentication(); in startup configure method.

then try again.

If not try to set ProtocolMessage.RedirectUri to the HTTPS url

```<code>services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
        .AddMicrosoftIdentityWebApp(options =>
{
Configuration.Bind("AzureAdB2C", options);
options.Events = new OpenIdConnectEvents
{
    OnRedirectToIdentityProvider = async ctx =>
    {
        /* Redirect Uri modified for https protocol */
        ctx.ProtocolMessage.RedirectUri = urlWithHttps
    }
}
});
</code>```

Or you can pass login hint :Please refer this doc.

References:

Tutorial: Register an application - Azure AD B2C | Microsoft Docs

Configure authentication in a sample web application by using Azure Active Directory B2C | Microsoft Docs

Title: Setting up Azure B2C with React

Body:
I am trying to configure my react/.NET 5.0 application to work with Azure B2C.  I have everything set up , I have tried to run this against an MVC application and I get the login screen.  But for some reason, when I try to redirect from a react page, I keep getting the same error.  There appears to be almost no real good documentation for this as well.  This is my authConfig file.

export const msalConfig = {

    auth: {
        clientId: process.env.REACT_APP_ADB2C_CLIENT_ID
        , authority: process.env.REACT_APP_ADB2C_AUTHORITY
        , knownAuthorities: [process.env.REACT_APP_KNOWN_AUTH]
        , clientSecret: process.env.REACT_APP_CLIENT_SECRET
        , reponseType: 'code'
      },
    cache: {
        cacheLocation: 'sessionStorage'
        ,storeAuthStateInCoolie: false
    }
};

const b2cPolicies = {
    name: {
        signUpSignIn: "B2C_1_cp_signin_up"
        , forgotPassword: "B2C_1_cp_forgot_pwd"
        , editProfile: "B2C_1_cp_edit_profile"
    },
    authorities: {
        signUpSignIn: {
            authority: `https://${process.env.REACT_APP_TENANT_LOGIN}/${process.env.REACT_APP_TENANT}/${process.env.REACT_APP_SIGNUP_POLICY}`,
        },
        forgotPassword: {
            authority: `https://${process.env.REACT_APP_TENANT_LOGIN}/${process.env.REACT_APP_TENANT}/${process.env.REACT_APP_FORGOT_POLICY}`,
        },
        editProfile: {
            authority: `https://${process.env.REACT_APP_TENANT_LOGIN}/${process.env.REACT_APP_TENANT}/${process.env.REACT_APP_EDIT_POLICY}`
        }
    },
    authorityDomain: process.env.REACT_APP_TENANT_LOGIN
}

export const loginRequest = {
    scopes: ["openid", "profile"],
};

I keep running into this error when I click on the link to redirect.

Any help with this would be great.

Body:
The reply URL must begin with the scheme https. Please check if reply urls are configured correctly which must be same in azure portal and in code .

Check if the callback path is set to identity provider something like /signin-oidc for redirect url .(And make sure you have unique callback if multiple urls are used.
such as https://contoso.com/signin-oidc.

The CallbackPath is the path where server will redirect during authentication. It's automatically handled by the OIDC middleware itself, that means we can't control the logic by creating a new controller/action and set CallbackPath to it

If you have check marked id_token in portal, try redirecting to home page ,instead of api actions directly.

Change the cookies to be set as secure using this in start up class

services.Configure(options =>
{
options.CheckConsentNeeded = context => true;//add if consent needed
options.MinimumSameSitePolicy = SameSiteMode.None; // else try  SameSiteMode.Lax;
options.Secure = CookieSecurePolicy.Always;

});

use Microsoft.AspNetCore.HttpOverrides;  reference in startup.cs class, by including the nuget package.

Also check and Add > app.UseHttpsRedirection(); above app.authentication(); in startup configure method.

then try again.

If not try to set ProtocolMessage.RedirectUri to the HTTPS url

services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
        .AddMicrosoftIdentityWebApp(options =>
{
Configuration.Bind("AzureAdB2C", options);
options.Events = new OpenIdConnectEvents
{
    OnRedirectToIdentityProvider = async ctx =>
    {
        /* Redirect Uri modified for https protocol */
        ctx.ProtocolMessage.RedirectUri = urlWithHttps
    }
}
});

Or you can pass login hint :Please refer this doc.

References:

Tutorial: Register an application - Azure AD B2C | Microsoft Docs

Configure authentication in a sample web application by using Azure Active Directory B2C | Microsoft Docs


问:
Write annotation to guard a method from being called when parameters are invalid
Can I have an annotation for a method that when its parameters are null, just do nothing, effectively as not being invoked?</p>

答:
Annotations in and of themselves are nothing but data.  They don't "do" anything.  There are a number of different ways you can have a run time framework that interprets annotations and accomplishes the functionality you're looking for.  The most common technique would be what's called Aspect Oriented Programming, where you alter the behaviour of program components based on metadata.

aspectJ is a full featured library that allows you to change the behaviour of just about anything!  You wouldn't even technically need an annotation will full aspectJ, there are lots of different ways to 'match' methods that you want to alter the behaviour of.

SpringAOP is a more limited subset of the functionality provided by aspectJ, but it is also easier to use and add to your project as a consequence!