问:
How to round off the coordinates of gejson object in pydantic
I am currently working on python version 3.10.6 in which I want to round off the coordinates decimal points to the 6 digits only. Instead of using for loop and iterating through each line, I want to do it at base level i.e. lat and lon of the Polygon.

Here I want to round off to 6 decimal points of Polygon's coordinates(lat and lon of CustomCoordinates).

```<code>LonField = Annotated[
    Union[float, float],
    Field(
        title='Coordinate longitude',
        gt=-180,
        lt=180,
    )
]

LatField = Annotated[
    Union[float, float],
    Field(
        title='Coordinate latitude',
        gt=-90,
        lt=90,
    ),
]

class CustomCoordinates(NamedTuple):
    lat: LatField
    lon: LonField

class PolygonGeo(CamelModel):
    type: Optional[str] = Field(None, description='Type of GeoJSon geometry', example='Polygon')
    coordinates: Optional[List[List['CustomCoordinates']]] = Field(
        None, description='Coordinates of GeoJSon geometry', example='[[[-73.7786925003853,40.63992777725],...]]]')
</code>```

I have imported the pydantic_geojson which provides the inbuilt geometry classes.
But I want to modify the coordinates i.e. rounding off to 6 decimal places.
I have tried

```<code>LonField = Annotated[
    Union[float, float],
    Field(
        title='Coordinate longitude',
        decimal_places=6,
        gt=-180,
        lt=180,
    )
]

</code>```

I get the below error

```<code>  File "pydantic\main.py", line 198, in pydantic.main.ModelMetaclass.__new__
  File "pydantic\fields.py", line 506, in pydantic.fields.ModelField.infer
  File "pydantic\fields.py", line 436, in pydantic.fields.ModelField.__init__
  File "pydantic\fields.py", line 552, in pydantic.fields.ModelField.prepare
  File "pydantic\fields.py", line 661, in pydantic.fields.ModelField._type_analysis
  File "pydantic\fields.py", line 758, in pydantic.fields.ModelField._type_analysis
  File "pydantic\fields.py", line 808, in pydantic.fields.ModelField._create_sub_type
  File "pydantic\fields.py", line 436, in pydantic.fields.ModelField.__init__
  File "pydantic\fields.py", line 552, in pydantic.fields.ModelField.prepare
  File "pydantic\fields.py", line 758, in pydantic.fields.ModelField._type_analysis
  File "pydantic\fields.py", line 808, in pydantic.fields.ModelField._create_sub_type
  File "pydantic\fields.py", line 436, in pydantic.fields.ModelField.__init__
  File "pydantic\fields.py", line 557, in pydantic.fields.ModelField.prepare
  File "pydantic\fields.py", line 831, in pydantic.fields.ModelField.populate_validators
  File "pydantic\validators.py", line 735, in find_validators
  File "pydantic\validators.py", line 599, in pydantic.validators.make_namedtuple_validator
  File "pydantic\annotated_types.py", line 72, in pydantic.annotated_types.create_model_from_namedtuple
  File "pydantic\main.py", line 1026, in pydantic.main.create_model
  File "pydantic\main.py", line 198, in pydantic.main.ModelMetaclass.__new__
  File "pydantic\fields.py", line 504, in pydantic.fields.ModelField.infer
  File "pydantic\schema.py", line 1011, in pydantic.schema.get_annotation_from_field_info
ValueError: On field "lon" the following field constraints are set but not enforced: decimal_places.
For more details see https://pydantic-docs.helpmanual.io/usage/schema/#unenforced-field-constraints
</code>```

Also, I have tried this but it's not rounding it off.

```<code>class CustomCoordinates(NamedTuple):
    lat: LatField
    lon: LonField

    @validator('lat')
    def coordinates_roundOff(cls,v):
        return round(v, 6)
</code>```

Body:
I am currently working on python version 3.10.6 in which I want to round off the coordinates decimal points to the 6 digits only. Instead of using for loop and iterating through each line, I want to do it at base level i.e. lat and lon of the Polygon.

Here I want to round off to 6 decimal points of Polygon's coordinates(lat and lon of CustomCoordinates).

LonField = Annotated[
    Union[float, float],
    Field(
        title='Coordinate longitude',
        gt=-180,
        lt=180,
    )
]

LatField = Annotated[
    Union[float, float],
    Field(
        title='Coordinate latitude',
        gt=-90,
        lt=90,
    ),
]

class CustomCoordinates(NamedTuple):
    lat: LatField
    lon: LonField

class PolygonGeo(CamelModel):
    type: Optional[str] = Field(None, description='Type of GeoJSon geometry', example='Polygon')
    coordinates: Optional[List[List['CustomCoordinates']]] = Field(
        None, description='Coordinates of GeoJSon geometry', example='[[[-73.7786925003853,40.63992777725],...]]]')

I have imported the pydantic_geojson which provides the inbuilt geometry classes.
But I want to modify the coordinates i.e. rounding off to 6 decimal places.
I have tried

LonField = Annotated[
    Union[float, float],
    Field(
        title='Coordinate longitude',
        decimal_places=6,
        gt=-180,
        lt=180,
    )
]

I get the below error

  File "pydantic\main.py", line 198, in pydantic.main.ModelMetaclass.__new__
  File "pydantic\fields.py", line 506, in pydantic.fields.ModelField.infer
  File "pydantic\fields.py", line 436, in pydantic.fields.ModelField.__init__
  File "pydantic\fields.py", line 552, in pydantic.fields.ModelField.prepare
  File "pydantic\fields.py", line 661, in pydantic.fields.ModelField._type_analysis
  File "pydantic\fields.py", line 758, in pydantic.fields.ModelField._type_analysis
  File "pydantic\fields.py", line 808, in pydantic.fields.ModelField._create_sub_type
  File "pydantic\fields.py", line 436, in pydantic.fields.ModelField.__init__
  File "pydantic\fields.py", line 552, in pydantic.fields.ModelField.prepare
  File "pydantic\fields.py", line 758, in pydantic.fields.ModelField._type_analysis
  File "pydantic\fields.py", line 808, in pydantic.fields.ModelField._create_sub_type
  File "pydantic\fields.py", line 436, in pydantic.fields.ModelField.__init__
  File "pydantic\fields.py", line 557, in pydantic.fields.ModelField.prepare
  File "pydantic\fields.py", line 831, in pydantic.fields.ModelField.populate_validators
  File "pydantic\validators.py", line 735, in find_validators
  File "pydantic\validators.py", line 599, in pydantic.validators.make_namedtuple_validator
  File "pydantic\annotated_types.py", line 72, in pydantic.annotated_types.create_model_from_namedtuple
  File "pydantic\main.py", line 1026, in pydantic.main.create_model
  File "pydantic\main.py", line 198, in pydantic.main.ModelMetaclass.__new__
  File "pydantic\fields.py", line 504, in pydantic.fields.ModelField.infer
  File "pydantic\schema.py", line 1011, in pydantic.schema.get_annotation_from_field_info
ValueError: On field "lon" the following field constraints are set but not enforced: decimal_places.
For more details see https://pydantic-docs.helpmanual.io/usage/schema/#unenforced-field-constraints

Also, I have tried this but it's not rounding it off.

class CustomCoordinates(NamedTuple):
    lat: LatField
    lon: LonField

    @validator('lat')
    def coordinates_roundOff(cls,v):
        return round(v, 6)


来源: stackexchange

问:
how to upload the files to g cloud for my php plugin i am using for wordpress?
i am trying to get the uploads of my website to get directly in google cloud bucket but i cant find a clearer solution

I am using a custom plugin we made for our website which generally helps us to get the uploads (the users who upload in our website) to a Gmail account , now we want to get all the uploads in cloud storage , any solutions/suggestions is appreciated. our website is in wordpress and the plugin is coded in php.

ContentLicense: CC BY-SA 4.0


问:
Parsing through a complex word document using python
I have a word document with paragraphs, tables and images etc.
I need to parse through the word document and save the data of the tables along with the paragraph above the table.

Tried using docx package but it is not giving desired output.


问:
Does RISC-V has the capability of running OpenCL kernel without any customization?
I am a beginner of OpenCL developer. There are some projects that use RISC-V architecture to run OpenCL kernel code. As a popular one, Vortex GPGPU uses RISC-V IMF isa and supports OpenCL kernel. They used PC as host and RISC-V GPGPU as OpenCL device (RTL simulation or FPGA with PCIe communication with the host). I read the vortex article, and saw that they used additional instructions to support OpenCL. The custom instructions are tmc, split, join, wspawn, barrier. However, I think those instructions can be implemented by using official extensions without any customization (Atomic extension and use of CSR).

Another project uses OpenCL-specific instructions.

However, all the projects used custom instructions as OpenCL-specific instructions. Could anyone explain why there is no implementation without customization?
I aimed to support OpenCL without customization of RISC-V but I am thinking that might be hard or impossible because no one implemented it.


问:
use placeholders for column names when using pipe operator
I have a table called Dec20, and two columns called FEEL_a_W77 and FEEL_b_W77

Instead of tediously repeating column names like so...

Dec20 %>% select(FEEL_a_W77) %>% group_by(FEEL_a_W77) %>% summarize(n=n())

Dec20 %>% select(FEEL_b_W77) %>% group_by(FEEL_b_W77) %>% summarize(n=n())

...I want to do something like:

colname <- FEEL_a_W77              //and repeat this later for FEEL_b_W77

Dec20 %>% select(colname) %>% group_by(colname) %>% summarize(n=n())

This doesn't work ("Error: object 'FEEL_a_W77' not found").

How can I make this work? Thoughts?

Thanks in advance.


问:
What is the purpose of ngcc.config.js file in angular?
I'm using angular version 9.1.13. There was a warning about entry point. I solved it using ngcc.config.ts file. Though I don't understand it's usage.

I'm trying to find the reason for ngcc.config.ts.


问:
XSLT 1.0 how to move string front and back
I'm still new to xslt and recently i got a request to change a xslt logic. So I'm here looking for help.

This is the input from external system.

```<code><item>
    <OBJ_CODE>(01)04030539083706(21)81490930005891136867</OBJ_CODE>
</item>
<item>
    <OBJ_CODE>(01)04030539083706(21)81490930005891143208</OBJ_CODE>
</item>
</code>```

and below is my expected result. so basically the requirement is to move the first 7 characters after (21) to the back and add fix value(A99), then move the last 13 characters to the front.

```<code><SN>(01)04030539083706(21)0005891136867(A99)8149093</SN>
<SN>(01)04030539083706(21)0005891136867(A99)8149093</SN>
</code>```

appreciate if anyone could help. please let me know if my description is not clear.

here is my current xslt mapping.

```<code><xsl:template match="item">
        <SN>
            <xsl:choose>
                <xsl:when test="../../EncodingType = 'SSCC'">
                    <xsl:value-of select="substring(OBJ_CODE,1,23)"/><xsl:value-of select="substring(OBJ_CODE,30,13)"/>(A99)<xsl:value-of select="substring(OBJ_CODE,23,7)"/>
                </xsl:when>
                <xsl:otherwise>
                    <xsl:value-of select="OBJ_CODE"/>
                </xsl:otherwise>
            </xsl:choose>
            <xsl:value-of select="NUMBER"/>
        </SN>
</xsl:template>
</code>```

Body:
I'm still new to xslt and recently i got a request to change a xslt logic. So I'm here looking for help.

This is the input from external system.

<item>
    <OBJ_CODE>(01)04030539083706(21)81490930005891136867</OBJ_CODE>
</item>
<item>
    <OBJ_CODE>(01)04030539083706(21)81490930005891143208</OBJ_CODE>
</item>

and below is my expected result. so basically the requirement is to move the first 7 characters after (21) to the back and add fix value(A99), then move the last 13 characters to the front.

<SN>(01)04030539083706(21)0005891136867(A99)8149093</SN>
<SN>(01)04030539083706(21)0005891136867(A99)8149093</SN>

appreciate if anyone could help. please let me know if my description is not clear.

here is my current xslt mapping.

<xsl:template match="item">
        <SN>
            <xsl:choose>
                <xsl:when test="../../EncodingType = 'SSCC'">
                    <xsl:value-of select="substring(OBJ_CODE,1,23)"/><xsl:value-of select="substring(OBJ_CODE,30,13)"/>(A99)<xsl:value-of select="substring(OBJ_CODE,23,7)"/>
                </xsl:when>
                <xsl:otherwise>
                    <xsl:value-of select="OBJ_CODE"/>
                </xsl:otherwise>
            </xsl:choose>
            <xsl:value-of select="NUMBER"/>
        </SN>
</xsl:template>


问:
RQ with lightgbm
I ran into a problem when using rq and lightgbm.

I have the following structure:

flask - for receiving requests and folding them into redis

redis - as a broker

rq - for asynchronous request processing

The server receives the data and the rq worker runs the data through the lightgbm model.

But there is a problem when using predict_proba. The worker just freezes and is killed by rq after the time has elapsed.

If you run the same model on flask itself, then there are no problems.

Here is the application log:

```<code>DEBUG:app.worker.services.machine_learning:{"module": "ml", "data": [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], "event": "applying model with ...", "level": "debug", "timestamp": "2022-12-22T05:06:02.072328Z", "lineno": 72, "pathname": "/app/app/worker/services/machine_learning.py", "func_name": "process_data_with_ml"}

INFO:rq.worker:Killed horse pid 25

WARNING:rq.worker:Moving job to FailedJobRegistry (work-horse terminated unexpectedly; waitpid returned None)
</code>```

Running the model on flask

Changed the model

Title: RQ with lightgbm

Body:
I ran into a problem when using rq and lightgbm.

I have the following structure:

flask - for receiving requests and folding them into redis

redis - as a broker

rq - for asynchronous request processing

The server receives the data and the rq worker runs the data through the lightgbm model.

But there is a problem when using predict_proba. The worker just freezes and is killed by rq after the time has elapsed.

If you run the same model on flask itself, then there are no problems.

Here is the application log:

DEBUG:app.worker.services.machine_learning:{"module": "ml", "data": [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], "event": "applying model with ...", "level": "debug", "timestamp": "2022-12-22T05:06:02.072328Z", "lineno": 72, "pathname": "/app/app/worker/services/machine_learning.py", "func_name": "process_data_with_ml"}

INFO:rq.worker:Killed horse pid 25

WARNING:rq.worker:Moving job to FailedJobRegistry (work-horse terminated unexpectedly; waitpid returned None)

Running the model on flask

Changed the model


问:
Installing ODBC driver in Namecheap
Fatal error: Uncaught PDOException: SQLSTATE[IMSSP]: This extension requires the Microsoft ODBC Driver for SQL Server to communicate with SQL Server. Access the following URL to download the ODBC Driver for SQL Server for x64: https://go.microsoft.com/fwlink/?LinkId=163712

Unable to get rid of the above error when trying to connect to SQL server using php in namecheap web hosting. please assist

see code below;

```<code><?php

    $con = new PDO("sqlsrv:Server=ipaddress;Database=datase", "sa", "xxxxx);

    if($con){
    echo "connection established.<br/>";
}else{
    echo "connection not established";
    die(print_r(sqlsrv_errors(), true));

}
?>
</code>```

Title: Installing ODBC driver in Namecheap

Body:
Fatal error: Uncaught PDOException: SQLSTATE[IMSSP]: This extension requires the Microsoft ODBC Driver for SQL Server to communicate with SQL Server. Access the following URL to download the ODBC Driver for SQL Server for x64: https://go.microsoft.com/fwlink/?LinkId=163712

Unable to get rid of the above error when trying to connect to SQL server using php in namecheap web hosting. please assist

see code below;

<?php

    $con = new PDO("sqlsrv:Server=ipaddress;Database=datase", "sa", "xxxxx);

    if($con){
    echo "connection established.
";
}else{
    echo "connection not established";
    die(print_r(sqlsrv_errors(), true));

}
?>


问:
Sequelize Typescript Associations without Foreign Key - is it possible?
I'm trying to define a pair of @HasMany / @BelongsTo association without foreign key, for use with custom include / join on conditions.

But I still got the error: Foreign key for {Model1} is missing on {Model2}, even though I used the option: constraints: false.

Not sure if this is supported with Sequelize and sequelize-typescript ?

Ref. GitHub issue

Example Code

AnonymousQuestionModel.ts

```<code>export interface AnonymousQuestionAttributes {
    // ...
}

@Table
export class AnonymousQuestionModel
  extends Model<AnonymousQuestionAttributes>
  implements AnonymousQuestionAttributes {
    @AutoIncrement
    @PrimaryKey
    @Column({ type: DataType.BIGINT })
    id!: number

   @Column
   email!: string

   @Column
   subject!: string

    @Column
    description!: string

    @BelongsTo(() => QuestionModel, { constraints: false, foreignKeyConstraint: false })
    maybeUserQuestion?: QuestionAttributes | null
}

export interface QuestionAttributes extends Omit<AnonymousQuestionAttributes, 'email'> {
    user: UserAttributes
}
</code>```

QuestionModel.ts

```<code>@Table
export class QuestionModel extends Model<QuestionAttributes> implements QuestionAttributes {
    @AutoIncrement
    @PrimaryKey
    @Column({ type: DataType.BIGINT })
    id!: number

   @Column
   subject!: string

    @Column
    description!: string

    @ForeignKey(() => UserModel)
    userId!: number

    @BelongsTo(() => UserModel)
    user!: UserAttributes

    @HasMany(() => AnonymousQuestionModel, { constraints: false, foreignKeyConstraint: false })
    maybeDuplicateQuestions: AnonymousQuestionAttributes[] = []
}
</code>```

QuestionsService.ts

```<code>export class QuestionService {
  constructor(protected readonly questionModel: ModelStatic<QuestionModel>) {
  }

  findAllWithDuplicates(opts: FindOptions<QuestionAttributes>) {
    return this.questionModel.findAll({
        ...opts,
        include: [
            {
                association: 'user',
            },
            {
                association: 'maybeDuplicateQuestions',
                on: {
                   [Op.and]: [
                        Sequelize.where(
                           Sequelize.col('QuestionModel.user.email'),
                           Op.eq,
                           Sequelize.col('maybeDuplicateQuestions.email')
                    ),
                    Sequelize.where(
                        Sequelize.col('QuestionModel.subject'),
                        Op.eq,
                        Sequelize.col('maybeDuplicateQuestions.subject')
                    ),
                }
            },
        ],
        order: [
            [Sequelize.col('QuestionModel.id'), 'desc'],
            [Sequelize.col('maybeDuplicateQuestions.id'), 'desc'],
        ],
    })
  }
}
</code>```

Body:
I'm trying to define a pair of @HasMany / @BelongsTo association without foreign key, for use with custom include / join on conditions.

But I still got the error: Foreign key for {Model1} is missing on {Model2}, even though I used the option: constraints: false.

Not sure if this is supported with Sequelize and sequelize-typescript ?

Ref. GitHub issue

Example Code

AnonymousQuestionModel.ts

export interface AnonymousQuestionAttributes {
    // ...
}

@Table
export class AnonymousQuestionModel
  extends Model<AnonymousQuestionAttributes>
  implements AnonymousQuestionAttributes {
    @AutoIncrement
    @PrimaryKey
    @Column({ type: DataType.BIGINT })
    id!: number

   @Column
   email!: string

   @Column
   subject!: string

    @Column
    description!: string

    @BelongsTo(() => QuestionModel, { constraints: false, foreignKeyConstraint: false })
    maybeUserQuestion?: QuestionAttributes | null
}

export interface QuestionAttributes extends Omit<AnonymousQuestionAttributes, 'email'> {
    user: UserAttributes
}

QuestionModel.ts

@Table
export class QuestionModel extends Model<QuestionAttributes> implements QuestionAttributes {
    @AutoIncrement
    @PrimaryKey
    @Column({ type: DataType.BIGINT })
    id!: number

   @Column
   subject!: string

    @Column
    description!: string

    @ForeignKey(() => UserModel)
    userId!: number

    @BelongsTo(() => UserModel)
    user!: UserAttributes

    @HasMany(() => AnonymousQuestionModel, { constraints: false, foreignKeyConstraint: false })
    maybeDuplicateQuestions: AnonymousQuestionAttributes[] = []
}

QuestionsService.ts

export class QuestionService {
  constructor(protected readonly questionModel: ModelStatic<QuestionModel>) {
  }

  findAllWithDuplicates(opts: FindOptions<QuestionAttributes>) {
    return this.questionModel.findAll({
        ...opts,
        include: [
            {
                association: 'user',
            },
            {
                association: 'maybeDuplicateQuestions',
                on: {
                   [Op.and]: [
                        Sequelize.where(
                           Sequelize.col('QuestionModel.user.email'),
                           Op.eq,
                           Sequelize.col('maybeDuplicateQuestions.email')
                    ),
                    Sequelize.where(
                        Sequelize.col('QuestionModel.subject'),
                        Op.eq,
                        Sequelize.col('maybeDuplicateQuestions.subject')
                    ),
                }
            },
        ],
        order: [
            [Sequelize.col('QuestionModel.id'), 'desc'],
            [Sequelize.col('maybeDuplicateQuestions.id'), 'desc'],
        ],
    })
  }
}


问:
SSRS Subreports for single values?
I have a main report with the following data and 3 parameters : pColumnA (single selection) , pColumnB(multiselect), pColumnC(multiselect)

MainReport Dataset

And I have 2  subreports:  SubreportB - containing  ColumnB values, Subreport C containing ColumnC values.If Column B has duplicates, I want to see SubreportB & SubreportC (in different pages-> 1 value= 1 page), Otherwise just SubreportC(in different pages-> 1 value= 1 page).

In order to achieve this I have added a List with following grouping:

List Grouping

I am able to show only subreports with more than one value in Column B with : IIF(COUNT(ColumnC)>1, FALSE, TRUE) ;

Do you have any idea how to show Subreport C for single values, without showing the values already displayed in the first group?

Ex:

If pColumnA="A"

SubreportB: 1111 | SubreportC: 1111A| SubreportC: 1111B

Subreport :  2222A

Thanks in advance.

Do you have any idea?

Title: SSRS Subreports for single values?


问:
awscli installed via Homebrew on macOS Monterey fails to run
Successfully installed awscli via brew install awscli but aws --version outputs multiple lines of errors. Tried brew reinstall awscli and dependecy i.e. brew reinstall python@3.11.

```<code>% brew --version
Homebrew 3.6.16
Homebrew/homebrew-core (git revision aea8126fde5; last commit 2022-12-22)
Homebrew/homebrew-cask (git revision b14ee37687; last commit 2022-12-22)

% which aws
/usr/local/bin/aws
</code>```

Here are the error lines. What should I try next?

```<code>% aws --version
Traceback (most recent call last):
  File "/usr/local/bin/aws", line 19, in <module>
    import awscli.clidriver
  File "/usr/local/Cellar/awscli/2.9.9/libexec/lib/python3.11/site-packages/awscli/clidriver.py", line 21, in <module>
    import botocore.session
  File "/usr/local/Cellar/awscli/2.9.9/libexec/lib/python3.11/site-packages/awscli/botocore/session.py", line 27, in <module>
    import botocore.client
  File "/usr/local/Cellar/awscli/2.9.9/libexec/lib/python3.11/site-packages/awscli/botocore/client.py", line 16, in <module>
    from botocore import UNSIGNED, waiter, xform_name
  File "/usr/local/Cellar/awscli/2.9.9/libexec/lib/python3.11/site-packages/awscli/botocore/waiter.py", line 17, in <module>
    from botocore.docs.docstring import WaiterDocstring
  File "/usr/local/Cellar/awscli/2.9.9/libexec/lib/python3.11/site-packages/awscli/botocore/docs/__init__.py", line 15, in <module>
    from botocore.docs.service import ServiceDocumenter
  File "/usr/local/Cellar/awscli/2.9.9/libexec/lib/python3.11/site-packages/awscli/botocore/docs/service.py", line 14, in <module>
    from botocore.docs.client import ClientDocumenter, ClientExceptionsDocumenter
  File "/usr/local/Cellar/awscli/2.9.9/libexec/lib/python3.11/site-packages/awscli/botocore/docs/client.py", line 16, in <module>
    from botocore.docs.example import ResponseExampleDocumenter
  File "/usr/local/Cellar/awscli/2.9.9/libexec/lib/python3.11/site-packages/awscli/botocore/docs/example.py", line 13, in <module>
    from botocore.docs.shape import ShapeDocumenter
  File "/usr/local/Cellar/awscli/2.9.9/libexec/lib/python3.11/site-packages/awscli/botocore/docs/shape.py", line 19, in <module>
    from botocore.utils import is_json_value_header
  File "/usr/local/Cellar/awscli/2.9.9/libexec/lib/python3.11/site-packages/awscli/botocore/utils.py", line 33, in <module>
    import botocore.httpsession
  File "/usr/local/Cellar/awscli/2.9.9/libexec/lib/python3.11/site-packages/awscli/botocore/httpsession.py", line 21, in <module>
    from urllib3.util.ssl_ import (
ImportError: cannot import name 'ssl' from 'urllib3.util.ssl_' (/usr/local/Cellar/awscli/2.9.9/libexec/lib/python3.11/site-packages/urllib3/util/ssl_.py)
</code>```

Body:
Successfully installed awscli via brew install awscli but aws --version outputs multiple lines of errors. Tried brew reinstall awscli and dependecy i.e. brew reinstall python@3.11.

% brew --version
Homebrew 3.6.16
Homebrew/homebrew-core (git revision aea8126fde5; last commit 2022-12-22)
Homebrew/homebrew-cask (git revision b14ee37687; last commit 2022-12-22)

% which aws
/usr/local/bin/aws

Here are the error lines. What should I try next?

% aws --version
Traceback (most recent call last):
  File "/usr/local/bin/aws", line 19, in <module>
    import awscli.clidriver
  File "/usr/local/Cellar/awscli/2.9.9/libexec/lib/python3.11/site-packages/awscli/clidriver.py", line 21, in <module>
    import botocore.session
  File "/usr/local/Cellar/awscli/2.9.9/libexec/lib/python3.11/site-packages/awscli/botocore/session.py", line 27, in <module>
    import botocore.client
  File "/usr/local/Cellar/awscli/2.9.9/libexec/lib/python3.11/site-packages/awscli/botocore/client.py", line 16, in <module>
    from botocore import UNSIGNED, waiter, xform_name
  File "/usr/local/Cellar/awscli/2.9.9/libexec/lib/python3.11/site-packages/awscli/botocore/waiter.py", line 17, in <module>
    from botocore.docs.docstring import WaiterDocstring
  File "/usr/local/Cellar/awscli/2.9.9/libexec/lib/python3.11/site-packages/awscli/botocore/docs/__init__.py", line 15, in <module>
    from botocore.docs.service import ServiceDocumenter
  File "/usr/local/Cellar/awscli/2.9.9/libexec/lib/python3.11/site-packages/awscli/botocore/docs/service.py", line 14, in <module>
    from botocore.docs.client import ClientDocumenter, ClientExceptionsDocumenter
  File "/usr/local/Cellar/awscli/2.9.9/libexec/lib/python3.11/site-packages/awscli/botocore/docs/client.py", line 16, in <module>
    from botocore.docs.example import ResponseExampleDocumenter
  File "/usr/local/Cellar/awscli/2.9.9/libexec/lib/python3.11/site-packages/awscli/botocore/docs/example.py", line 13, in <module>
    from botocore.docs.shape import ShapeDocumenter
  File "/usr/local/Cellar/awscli/2.9.9/libexec/lib/python3.11/site-packages/awscli/botocore/docs/shape.py", line 19, in <module>
    from botocore.utils import is_json_value_header
  File "/usr/local/Cellar/awscli/2.9.9/libexec/lib/python3.11/site-packages/awscli/botocore/utils.py", line 33, in <module>
    import botocore.httpsession
  File "/usr/local/Cellar/awscli/2.9.9/libexec/lib/python3.11/site-packages/awscli/botocore/httpsession.py", line 21, in <module>
    from urllib3.util.ssl_ import (
ImportError: cannot import name 'ssl' from 'urllib3.util.ssl_' (/usr/local/Cellar/awscli/2.9.9/libexec/lib/python3.11/site-packages/urllib3/util/ssl_.py)


问:
how to fixed android pending intent error
my pendding intent code

```<code>val pendingIntent = PendingIntent.getActivities(this, requestCode, arrayOf(intent), PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE)
</code>```

but log in google console

Targeting S+ (version 31 and above) requires that one of FLAG_IMMUTABLE or FLAG_MUTABLE be specified when creating a PendingIntent.
Strongly consider using FLAG_IMMUTABLE, only use FLAG_MUTABLE if some functionality depends on the PendingIntent being mutable, e.g. if it needs to be used with inline replies or bubbles.

I'm already writing but it's guiding me to that error

And I googled and added this before

```<code> implementation 'androidx.work:work-runtime-ktx:2.7.0'
</code>```

What is the reason for that error?

Body:
my pendding intent code

val pendingIntent = PendingIntent.getActivities(this, requestCode, arrayOf(intent), PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE)

but log in google console

Targeting S+ (version 31 and above) requires that one of FLAG_IMMUTABLE or FLAG_MUTABLE be specified when creating a PendingIntent.
Strongly consider using FLAG_IMMUTABLE, only use FLAG_MUTABLE if some functionality depends on the PendingIntent being mutable, e.g. if it needs to be used with inline replies or bubbles.

I'm already writing but it's guiding me to that error

And I googled and added this before

 implementation 'androidx.work:work-runtime-ktx:2.7.0'

What is the reason for that error?


问:
Object not found with udipipe in R
I trying to use the udipipe package and getting and error in all the function of udipipe as object not found

Like
Error in upos %in% c("NOUN") : object 'upos' not found
Error in language %in% "english" : object 'language' not found

```<code>x=read.csv("Text.csv", header = T)

library(udpipe)
library(textrank)

comments <- subset(x, language %in% "english")
stats <- subset(x, upos %in% c("NOUN"))
</code>```

Title: Object not found with udipipe in R

Body:
I trying to use the udipipe package and getting and error in all the function of udipipe as object not found

Like
Error in upos %in% c("NOUN") : object 'upos' not found
Error in language %in% "english" : object 'language' not found

x=read.csv("Text.csv", header = T)

library(udpipe)
library(textrank)

comments <- subset(x, language %in% "english")
stats <- subset(x, upos %in% c("NOUN"))


问:
How do I change the labels of this legend to this seaborn scatter plot?
I want to change the legend such that the blue dots represent 'Survived' and the orange dots represent 'Not Survived'. However, when I load the plot, it gives me this and I do not know how to change it despite other StackOverflow responses. Here is my code for it.

```<code>g = sns.scatterplot(x="Age", y="Parch", hue="Survived",data=train[["Age", "Parch", "Survived"]], legend=False)

plt.legend(title='Survival Status', loc='upper right', labels=['Survived', 'Not Survived'])
</code>```

I expected that it would add labels for both the orange and the blue but it does not.

Body:
I want to change the legend such that the blue dots represent 'Survived' and the orange dots represent 'Not Survived'. However, when I load the plot, it gives me this and I do not know how to change it despite other StackOverflow responses. Here is my code for it.

g = sns.scatterplot(x="Age", y="Parch", hue="Survived",data=train[["Age", "Parch", "Survived"]], legend=False)

plt.legend(title='Survival Status', loc='upper right', labels=['Survived', 'Not Survived'])

I expected that it would add labels for both the orange and the blue but it does not.


问:
Couldnt cover the (If) path while writting the spec file for unit testing in Angular (Karma Jasmin)
```<code>> loadProducts() {
> this.isLoading = true;
> this.isProductEmpty = false;
> const observer = this.shopService.getProducts().subscribe(
> (categories: ShopReducer) => {
> if (size(categories.products) > 0) {
> **this.categories = categories.products;**
> } else {
> this.isProductEmpty = true;
> }
> this.isLoading = false;
> },
> (error) => {
> this.isProductEmpty = true;
> this.isLoading = false;
> this.categories = [];
> this.toast.error(error.message);
> }
> );
> this.subscriptions.add(observer);
> }
</code>```

I couldn't cover this specific line during the unit testing in angular.

```<code>  this.categories = categories.products;
</code>```
```<code>  describe('#loadProducts', () => {
    it('should load products', () => {
      const errorMessages = {
        isProductEmpty: true,
        categories: [],
      };
      shopServiceMock.getProducts.and.returnValue(throwError(errorMessages));
      component.loadProducts();

      expect(component.categories.length).toEqual(0);
    });
  });

</code>```

The above code snippet is the spec file code for the error message which giver below.

```<code>   (error) => {
        this.isProductEmpty = true;
        this.isLoading = false;
        this.categories = [];
        this.toast.error(error.message);
      }
    );
    this.subscriptions.add(observer);
</code>```

But I have to cover the whole function. Now the main problem to write a spec file in angular for this function

loadProducts() whis is given at the top.

Thank you :)

Body:
> loadProducts() {
> this.isLoading = true;
> this.isProductEmpty = false;
> const observer = this.shopService.getProducts().subscribe(
> (categories: ShopReducer) => {
> if (size(categories.products) > 0) {
> **this.categories = categories.products;**
> } else {
> this.isProductEmpty = true;
> }
> this.isLoading = false;
> },
> (error) => {
> this.isProductEmpty = true;
> this.isLoading = false;
> this.categories = [];
> this.toast.error(error.message);
> }
> );
> this.subscriptions.add(observer);
> }

I couldn't cover this specific line during the unit testing in angular.

  this.categories = categories.products;

  describe('#loadProducts', () => {
    it('should load products', () => {
      const errorMessages = {
        isProductEmpty: true,
        categories: [],
      };
      shopServiceMock.getProducts.and.returnValue(throwError(errorMessages));
      component.loadProducts();

      expect(component.categories.length).toEqual(0);
    });
  });

The above code snippet is the spec file code for the error message which giver below.

   (error) => {
        this.isProductEmpty = true;
        this.isLoading = false;
        this.categories = [];
        this.toast.error(error.message);
      }
    );
    this.subscriptions.add(observer);

But I have to cover the whole function. Now the main problem to write a spec file in angular for this function

loadProducts() whis is given at the top.

Thank you :)


问:
Path doesn't exist error, even though the path clearly does exist
Error Image
This error keeps popping up and I cant find a way to stop it.

This only started happening when I converted the python file to exe, before that the path was just catgame/Assets/[sheet].png since .../Python/ was the working directory. But now since it is in exe form, that didn't work as I'm assuming that the way pygame interprets paths is different to how exes do it.
Any help would be greatly appreciated, thanks.

All of the code where the error will happen:

```<code>        catSheet = pygame.image.load('C:\\Users\squid\OneDrive\Documents\programming\Python\catgame\Assets\CatSheet.png')
        placeholderSheet = pygame.image.load('C:\\Users\squid\OneDrive\Documents\programming\Python\catgame\Assets\Placeholders.png')
        iconSheet = pygame.image.load('C:\\Users\squid\OneDrive\Documents\programming\Python\catgame\Assets\IconsSheet.png')
        shopSheet = pygame.image.load('C:\\Users\squid\OneDrive\Documents\programming\Python\catgame\Assets\ShopSpriteSheet.png')
        bedSheet = pygame.image.load('C:\\Users\squid\OneDrive\Documents\programming\Python\catgame\Assets\CatBedSheet.png')
</code>```

I tried different formatting of the path, backslash, forward slash, etc. I expected these to atleast give a different error or fix it altogether, but the error did not change.

Body:
Error Image
This error keeps popping up and I cant find a way to stop it.

This only started happening when I converted the python file to exe, before that the path was just catgame/Assets/[sheet].png since .../Python/ was the working directory. But now since it is in exe form, that didn't work as I'm assuming that the way pygame interprets paths is different to how exes do it.
Any help would be greatly appreciated, thanks.

All of the code where the error will happen:

        catSheet = pygame.image.load('C:\\Users\squid\OneDrive\Documents\programming\Python\catgame\Assets\CatSheet.png')
        placeholderSheet = pygame.image.load('C:\\Users\squid\OneDrive\Documents\programming\Python\catgame\Assets\Placeholders.png')
        iconSheet = pygame.image.load('C:\\Users\squid\OneDrive\Documents\programming\Python\catgame\Assets\IconsSheet.png')
        shopSheet = pygame.image.load('C:\\Users\squid\OneDrive\Documents\programming\Python\catgame\Assets\ShopSpriteSheet.png')
        bedSheet = pygame.image.load('C:\\Users\squid\OneDrive\Documents\programming\Python\catgame\Assets\CatBedSheet.png')

I tried different formatting of the path, backslash, forward slash, etc. I expected these to atleast give a different error or fix it altogether, but the error did not change.


问:
Conditional LISTAGG in Redshift
I created a query with listagg to combine items into a list. I would like to filter the output to lists that contain a certain item. Example: lists of grocery purchases that contain apples.

My filter is applying to each individual item in the list, not the entire list. So my output is only showing apples and not the other items purchased along with the apples.

How can I apply the filter to the entire aggregated list instead of each item the list?

Here's what I have so far:

```<code>with grocery_purchases as (
 select trip_id,
listagg(food_group || ': ' || food_item, ' | ') within group (order by food_group, food_item) as grocery_list
   , sum(price) as total_price
   , count(*) total_items
   , sum(case when discount_applied = 'yes' then 1 else 0 end) items_discounted
 from my_expenses
 where price > 0
  and discount_applied in ('yes','no')
  and purchase_date >= '2022-09-07'
  and grocery_store = 'wegmans'
 group by 1, 2
)
select grocery_list
  , count(distinct trip_id) as shopping_trips
  , sum(price) as cost
  , sum(discount) as savings
  , total_items
  , items_discounted
/*where grocery_list ilike '%apple%'*/
group by...

</code>```

note: this is just a sample query similar to my actual query. The query currently works without the apple filter but I would like to make it conditional.

Title: Conditional LISTAGG in Redshift

Body:
I created a query with listagg to combine items into a list. I would like to filter the output to lists that contain a certain item. Example: lists of grocery purchases that contain apples.

My filter is applying to each individual item in the list, not the entire list. So my output is only showing apples and not the other items purchased along with the apples.

How can I apply the filter to the entire aggregated list instead of each item the list?

Here's what I have so far:

with grocery_purchases as (
 select trip_id,
listagg(food_group || ': ' || food_item, ' | ') within group (order by food_group, food_item) as grocery_list
   , sum(price) as total_price
   , count(*) total_items
   , sum(case when discount_applied = 'yes' then 1 else 0 end) items_discounted
 from my_expenses
 where price > 0
  and discount_applied in ('yes','no')
  and purchase_date >= '2022-09-07'
  and grocery_store = 'wegmans'
 group by 1, 2
)
select grocery_list
  , count(distinct trip_id) as shopping_trips
  , sum(price) as cost
  , sum(discount) as savings
  , total_items
  , items_discounted
/*where grocery_list ilike '%apple%'*/
group by...

note: this is just a sample query similar to my actual query. The query currently works without the apple filter but I would like to make it conditional.


问:
In a knockout computation, how can you depend on, or subscribe to, an observable before it exists?
I have an observable marriedPeopleCount that is defined as such:

const marriedPeopleCount = ko.pureComputed(() => {
    return this._people?.()
        .map( person => person.status() )
        .some( status => status === "married")
});
```

In it, this.people and person.status are knockout observable dependencies. For reasons beyond my control I have to subscribe to marriedPeopleCount before this._people exists, which is why I check first that it is defined ?., however this causes the dependencies to not properly work, so that when this._people or person.status change, the updates are not reflected in the computed observable marriedPeopleCount.

I'm thinking that if I can define marriedPeopleCount early, let the subscribers subscribe to it while it is empty or an empty array, and once I have the data available populate the "computation" of marriedPeopleCount while keeping the same subscribers that it had.

Is that possible? Or am I approaching this the wrong way?

Body:
I have an observable marriedPeopleCount that is defined as such:

const marriedPeopleCount = ko.pureComputed(() => {
    return this._people?.()
        .map( person => person.status() )
        .some( status => status === "married")
});

In it, this.people and person.status are knockout observable dependencies. For reasons beyond my control I have to subscribe to marriedPeopleCount before this._people exists, which is why I check first that it is defined ?., however this causes the dependencies to not properly work, so that when this._people or person.status change, the updates are not reflected in the computed observable marriedPeopleCount.

I'm thinking that if I can define marriedPeopleCount early, let the subscribers subscribe to it while it is empty or an empty array, and once I have the data available populate the "computation" of marriedPeopleCount while keeping the same subscribers that it had.

Is that possible? Or am I approaching this the wrong way?


问:
How to print packet info , source-ip, destination-ip, time, protocol of the packet (i.e. Icmp, arp, tcp, udp, dns etc.) using pyshark and python
I want to print the details of the packets that is capture using pyshark. I want the details of the packet like info of packet, source-ip, destination-ip, protocol(like, unp, tcp, imp, arp, dns etc).

I use the code below.

```<code>import pyshark
import time
capture = pyshark.LiveCapture(interface='eth0')
capture.sniff(timeout=5)
for packet in capture.sniff_continuously():
    localtime = time.asctime(time.localtime(time.time()))
    protocol = packet.transport_layer
    src_addr = packet.ip.src
    src_port = packet[packet.transport_layer].srcport
    dst_addr = packet.ip.dst
    dst_port = packet[packet.transport_layer].dstport
    info = packet.info
    print (info, localtime,"\t",protocol,"\t", src_addr,"\t", src_port,"\t", dst_addr)
   # print (packet.show())

</code>```

Body:
I want to print the details of the packets that is capture using pyshark. I want the details of the packet like info of packet, source-ip, destination-ip, protocol(like, unp, tcp, imp, arp, dns etc).

I use the code below.

import pyshark
import time
capture = pyshark.LiveCapture(interface='eth0')
capture.sniff(timeout=5)
for packet in capture.sniff_continuously():
    localtime = time.asctime(time.localtime(time.time()))
    protocol = packet.transport_layer
    src_addr = packet.ip.src
    src_port = packet[packet.transport_layer].srcport
    dst_addr = packet.ip.dst
    dst_port = packet[packet.transport_layer].dstport
    info = packet.info
    print (info, localtime,"\t",protocol,"\t", src_addr,"\t", src_port,"\t", dst_addr)
   # print (packet.show())


问:
SQL Server Integration Services Projects Version 4.3 - SETUP FAILED
On my Windows 11 OS I Installed VS 2019 Community Edition. I then tried to install SQL Server Integration Services Projects. Following error occurred -
Fatal error during installation (0x80070643)
Microsoft AS OLEDB Provider for SQL Server 2016 : An error occurred during installation of assembly.

'Microsoft.VC80.CRT,type="win32".version='8.0.50727.6229",publicKeyToken='1fc8b3b9a18e3b",processorArchitecture="x86".Please refer to Help and Support for more information.
HRESULT:0x80070005

I enabled .NET framework from add remove features, Installed VC++, Repaired VS 2019. Nothing Works


问:
Function not calling
Hello I'm having this issue I have created a function shstop and I have added into my command and it's not calling. I've spent the last 1 hour trying to figure out different approaches. Nothing's worked so far.

Trying to make a user shuffle thru the voice channels for 6 seconds!

```<code>
shuffle_active = False

async def shuffle_loop(client, user):
    global shuffle_active  # Declare the global variable
    shuffle_active = True  # Set the flag to start the loop
    while shuffle_active:  # Check the status of the shuffle loop
        guild = user.guild
        voice_channels = guild.voice_channels
        new_channel = random.choice(voice_channels)
        await user.move_to(new_channel)
        await asyncio.sleep(2)

async def shstop(ctx):
    global shuffle_active  # Declare the global variable
    shuffle_active = False  # Toggle the shuffle loop off
    print("Loop stopped")
</code>```
```<code>@client.command()
async def shuffle(ctx, user: discord.Member):
    # Check if the user has the "Move Members" permission
    if ctx.message.author.guild_permissions.move_members:
        if user.voice is not None:
            current_channel = ctx.message.author.voice.channel
            channels = current_channel.guild.voice_channels
            channels.remove(current_channel)
            await ctx.send(f"{user.mention} will now be shuffled between voice channels every 3 seconds!")
            await shuffle_loop(client, user)
            await asyncio.sleep(6)
            await shstop(ctx)
        else:
            await ctx.send(f"{user.mention} is not in a voice channel!.")
    else:
        await ctx.send(f"<@{ctx.author.id}> You do not have permission to use this command!")
</code>```

Title: Function not calling

Body:
Hello I'm having this issue I have created a function shstop and I have added into my command and it's not calling. I've spent the last 1 hour trying to figure out different approaches. Nothing's worked so far.

Trying to make a user shuffle thru the voice channels for 6 seconds!

shuffle_active = False

async def shuffle_loop(client, user):
    global shuffle_active  # Declare the global variable
    shuffle_active = True  # Set the flag to start the loop
    while shuffle_active:  # Check the status of the shuffle loop
        guild = user.guild
        voice_channels = guild.voice_channels
        new_channel = random.choice(voice_channels)
        await user.move_to(new_channel)
        await asyncio.sleep(2)

async def shstop(ctx):
    global shuffle_active  # Declare the global variable
    shuffle_active = False  # Toggle the shuffle loop off
    print("Loop stopped")

@client.command()
async def shuffle(ctx, user: discord.Member):
    # Check if the user has the "Move Members" permission
    if ctx.message.author.guild_permissions.move_members:
        if user.voice is not None:
            current_channel = ctx.message.author.voice.channel
            channels = current_channel.guild.voice_channels
            channels.remove(current_channel)
            await ctx.send(f"{user.mention} will now be shuffled between voice channels every 3 seconds!")
            await shuffle_loop(client, user)
            await asyncio.sleep(6)
            await shstop(ctx)
        else:
            await ctx.send(f"{user.mention} is not in a voice channel!.")
    else:
        await ctx.send(f"<@{ctx.author.id}> You do not have permission to use this command!")


问:
Why is using extends in TypeScript giving me an `any` type?
Here is my TypeScript playground, which has this:

```<code>type TreeType<T> = {
  left?: TreeType<T>
  right?: TreeType<T>
  value: T
}

type TreeUnwrapperType<T> = T extends TreeType<infer X>
  ? X
  : never

type TreeAliasType<T> = T extends TreeType<infer X>
  ? X extends object
    ? T
    : never
  : never

type UserType = {
  email: string
}

const tree: TreeType<UserType> = {
  value: { email: 'foo@bar.com' },
}

const user: TreeUnwrapperType<TreeType<UserType>> = {
  email: 'foo@bar.com',
}

const tree2: TreeAliasType<TreeType<UserType>> = {
  value: { email: 'foo@bar.com' },
}

type ScopeType<S, P extends unknown = unknown> = {
  data: S
  parent?: P extends ScopeType<infer T, infer Q>
    ? ScopeType<T, Q>
    : never
}

type PossibleScopeType<ST> = ST extends ScopeType<
  infer S,
  infer P extends ScopeType<infer A, infer B>
>
  ? ST | P | PossibleScopeType<P>
  : never

type ModuleType = {
  path: string
}

const scope: ScopeType<ModuleType> = {
  data: {
    path: './foo.x',
  },
}

const scope2: ScopeType<UserType, ScopeType<ModuleType>> = {
  data: {
    email: 'foo@bar.com',
  },
  parent: scope,
}

let scope3: PossibleScopeType<ScopeType<ModuleType>> = scope2
scope3 = scope
scope3 = true

export type ParentScopeType<S> = S extends ScopeType<
  infer X,
  infer PS
>
  ? S | PS | ParentScopeType<PS>
  : S

export type ParentScopeType2<S> = S extends ScopeType<
  infer X,
  infer Y extends ScopeType<infer A, infer B>
>
  ? S
  : S

let source: ScopeAliasType<typeof scope> | undefined = scope2

export type ScopeAliasType<S> = ParentScopeType<S>
</code>```

In that (I am messing around trying to figure something out), this section has scope3 typed as any for some reason:

```<code>let scope3: PossibleScopeType<ScopeType<ModuleType>> = scope2
scope3 = scope
scope3 = true
</code>```

The PossibleScopeType I am trying to have it return all the linked parents in the tree, but instead it is returning any, even though I have defined it like this:

```<code>type PossibleScopeType<ST> = ST extends ScopeType<
  infer S,
  infer P extends ScopeType<infer A, infer B>
>
  ? ST | P | PossibleScopeType<P>
  : never
</code>```

What am I doing wrong?

Why is it returning any type for scope3?

How do I make PossibleScopeType make it so scope3 is typed as either scope2 or it's parent, scope1, in a dynamic way? (I.e. not hardcoding to this specific case)

Here is another variant.

Body:
<a href="https://www.typescriptlang.org/play?#code/C4TwDgpgBAKgThCNwQDwwHxQLxQN4BQUUANhAGbAD8AXLAkiuhkVHAJYDmAFtXfImSRmrAG4BDEgFcI-AgF8CBUJHqIAqgDsA7nHFhIcIWkw5YUCAA9gETQBMAzmsbD2m8hDhQAGi2JUfVjpNCFFPJRVoAQgAQRJ2cQdjZjMYC2tbR2dktw8vX1YA73SbeycAewAjACsIAGNgVn9YJqhg0PDidrC4CJQodQdPYzNCYggAW3F2EjoHYA5NTgUlOvLNeagFxH4GZMHhlCxcMagJaVl8CymZugBycnLygAFK8TgAOjWJu6h5ABoVgQ1htgFApEM4LsNDo9AZDsJovtIcYMMd8KxJtNZlAHk9Xu8vuUfoDFMD1ptthAAEzQ2LxRLJJFMA5GI7o07nGR0PDXbH3R4vN6fb6-AFAyJQADKa0gySl-ygAAUSpknFJNABrTTlbSaMwa7W6zQc1h2cTAcR0KWsMDvWx8ZWqsrS2UuNC5TywRWerwART8xCgARl5TlTBgioDrW64TJkqV5QcDnYlTIofDwilplw2edWQz7tQrF90sBxFLKqspQLbpy7i9MR9Da8ACEWIGQ2kAD5O3uJ5Op9N1phKwOx3rKfoAWXKdikZBGJ1tFu4cwWbmWZJBmwcbutI+Es-ni6OozNFqtGKDUDtwDXuI+AHpBR9LHdy39SasKWC92GaQPADkQRCBFULZJjwXd00XPYhzUtHlWixW5cUFAkRWJD9WHFYg7QQTRgDmN1vwIMg-zdABmOgBxTNMIAgphGKPOdoNRdF-0gakCE4iBKLMXieKoswFhkJQrDAco4DBBN7UI5i0CldEpXzJwFOLCsWx8T9KxtTtpSgfsVP7OTgHUpUlKCaVxMsSTpK2folVMhTqVQJSzBU6s1VdYCmBLLTvB0rSAE1VJ8zMPS0psoFLdsCH0m0umssiID-copDgOpLkLOIEiSJhInKcgoF4rBew1OwKDcCA7AEt1uIICSpJk-ocoZfKs3RJyCLMw9FJYIA" rel="nofollow noreferrer">Here is my TypeScript playground, which has this:

type TreeType<T> = {
  left?: TreeType<T>
  right?: TreeType<T>
  value: T
}

type TreeUnwrapperType<T> = T extends TreeType<infer X>
  ? X
  : never

type TreeAliasType<T> = T extends TreeType<infer X>
  ? X extends object
    ? T
    : never
  : never

type UserType = {
  email: string
}

const tree: TreeType<UserType> = {
  value: { email: 'foo@bar.com' },
}

const user: TreeUnwrapperType<TreeType<UserType>> = {
  email: 'foo@bar.com',
}

const tree2: TreeAliasType<TreeType<UserType>> = {
  value: { email: 'foo@bar.com' },
}

type ScopeType<S, P extends unknown = unknown> = {
  data: S
  parent?: P extends ScopeType<infer T, infer Q>
    ? ScopeType<T, Q>
    : never
}

type PossibleScopeType<ST> = ST extends ScopeType<
  infer S,
  infer P extends ScopeType<infer A, infer B>
>
  ? ST | P | PossibleScopeType

  : never

type ModuleType = {
  path: string
}

const scope: ScopeType<ModuleType> = {
  data: {
    path: './foo.x',
  },
}

const scope2: ScopeType<UserType, ScopeType<ModuleType>> = {
  data: {
    email: 'foo@bar.com',
  },
  parent: scope,
}

let scope3: PossibleScopeType<ScopeType<ModuleType>> = scope2
scope3 = scope
scope3 = true

export type ParentScopeType<S> = S extends ScopeType<
  infer X,
  infer PS
>
  ? S | PS | ParentScopeType<PS>
  : S

export type ParentScopeType2<S> = S extends ScopeType<
  infer X,
  infer Y extends ScopeType<infer A, infer B>
>
  ? S
  : S

let source: ScopeAliasType<typeof scope> | undefined = scope2

export type ScopeAliasType<S> = ParentScopeType<S>

In that (I am messing around trying to figure something out), this section has scope3 typed as any for some reason:

let scope3: PossibleScopeType<ScopeType<ModuleType>> = scope2
scope3 = scope
scope3 = true

The PossibleScopeType I am trying to have it return all the linked parents in the tree, but instead it is returning any, even though I have defined it like this:

type PossibleScopeType<ST> = ST extends ScopeType<
  infer S,
  infer P extends ScopeType<infer A, infer B>
>
  ? ST | P | PossibleScopeType

  : never

What am I doing wrong?

Why is it returning any type for scope3?

How do I make PossibleScopeType make it so scope3 is typed as either scope2 or it's parent, scope1, in a dynamic way? (I.e. not hardcoding to this specific case)

<a href="https://www.typescriptlang.org/play?#code/C4TwDgpgBAKgThCNwQDwwHxQLxQN4BQUUANhAGbAD8AXLAkiuhkVHAJYDmAFtXfImSRmrAG4BDEgFcI-AgF8CBUJHqIAqgDsA7nHFhIcIWkw5YUCAA9gETQBMAzmsbD2m8hDhQAGi2JUfVjpNCFFPJRVoAQgAQRJ2cQdjZjMYC2tbR2dktw8vX1YA73SbeycAewAjACsIAGNgVn9YJqhg0PDidrC4CJQodQdPYzNCYggAW3F2EjoHYA5NTgUlOvLNeagFxH4GZMHhlCxcMagJaVl8CymZugBycnLygAFK8TgAOjWJu6h5ABoVgQ1htgFApEM4LsNDo9AZDsJovtIcYMMd8KxJtNZlAHk9Xu8vuUfoDFMD1ptthAAEzQ2LxRLJJFMA5GI7o07nGR0PDXbH3R4vN6fb6-AFAyJQADKa0gySl-ygAAUSpknFJNABrTTlbSaMwa7W6zQc1h2cTAcR0KWsMDvWx8ZWqsrS2UuNC5TywRWerwART8xCgARl5TlTBgioDrW64TJkqV5QcDnYlTIofDwilplw2edWQz7tQrF90sBxFLSoIgZDaQAPk6rKUC26cu4vTEfe2vAAhLABFUNxPJ1Pp1tMJVYWO9LpQEI9PqqACy5TsUjIIxOtot3DmCzcyzJIM2Djd1vHwhXa43R1GZotVoxQagduAu9xHwA9IKPpY7uW-lJVYKTBU8wxpc9wORBEIEVQtkivdd3TRO9iHNS0eVaLFblxQUCRFYl-1YcViDtBBNGAOY3SAggyFAt0AGY6GHFM0wgeCmA4y9VyQ1F0TAyBqQIASIAYswROExizAWGQlCsMByjgMEE3tCiuLQKV0SlfMnHU4sK27HwAMrG0a2lKAh20odVOAPSlU0oJpTkywFKUrZ+iVGz1OpVBNLMbSmzVV0oKYEtDO8YzDIATR04LMw9QzOygUs+2rQonNnG1aIgUDyikOA6kuQs4gSJImEicpyCgESsAbDU7AoNwIDscS3SEgh5MU5T+mKhkyqzdFPPI2yLw0lggA" rel="nofollow noreferrer">Here is another variant.


问:
plot only area where multiple 2D lines crossed
I have connected multiple data points using 2D lines with different colors. But in case of many lines, it is hard to differentiate where most of the lines overlap or intersect.
For example, here is my script, and I have plotted a few red and black lines.
How can we extract only the area where we have high density of these crossing red lines (maybe user defined crossing numbers?
Any suggestions will be highly appreciated.

```<code>        ax.scatter(rcv[:,0], rcv[:,1], c='b', marker='v',s=190,label= "End")
        ax.scatter(src[:,0], src[:,1], c='r', marker='*',s=120,label= "Start")

        if status=="High":
            x_values = [x1, x2]
            y_values = [y1, y2]

            plt.plot(x_values, y_values, 'k-', linewidth=0.5,alpha=0.5)
            fig.canvas.draw()
        else:
            x_values = [x1, x2]
            y_values = [y1, y2]

            plt.plot(x_values, y_values, 'r-', linewidth=0.5,alpha=0.5)
            fig.canvas.draw()
</code>```

Body:
I have connected multiple data points using 2D lines with different colors. But in case of many lines, it is hard to differentiate where most of the lines overlap or intersect.
For example, here is my script, and I have plotted a few red and black lines.
How can we extract only the area where we have high density of these crossing red lines (maybe user defined crossing numbers?
Any suggestions will be highly appreciated.

        ax.scatter(rcv[:,0], rcv[:,1], c='b', marker='v',s=190,label= "End")
        ax.scatter(src[:,0], src[:,1], c='r', marker='*',s=120,label= "Start")

        if status=="High":
            x_values = [x1, x2]
            y_values = [y1, y2]

            plt.plot(x_values, y_values, 'k-', linewidth=0.5,alpha=0.5)
            fig.canvas.draw()
        else:
            x_values = [x1, x2]
            y_values = [y1, y2]

            plt.plot(x_values, y_values, 'r-', linewidth=0.5,alpha=0.5)
            fig.canvas.draw()


问:
Github API - Sort user repositories by recent commit
While fetching list of repositories as mentioned in the documentation, I need them to be sorted in the order of recently updated first - used sort=updated to achieve this.

But when I commit something to one of the repos, it is not considered to be updated - is commit not considered an update to a repo?


问:
vuejs3 Library vue3-youtube fixed width and height problem
I'm using vue3-YouTube with npm. I want to respond responsively by adjusting the width and height to 100%. It does not apply to anything other than fixed pixel width,height values. I also used a class but it doesn't work.</p>
```<code><template>
  <div class="container">
    <div class="youtube_container">
      <YouTube
        src="https://youtu.be/GQmO52f26Ws"
        width="640"
        height="300"
     />
    </div>
  </div>
</template>
<script setup>
import YouTube from 'vue3-youtube'

</script>
</code>```

Body:
I'm using vue3-YouTube with npm. I want to respond responsively by adjusting the width and height to 100%. It does not apply to anything other than fixed pixel width,height values. I also used a class but it doesn't work.

<template>

      <YouTube
        src="https://youtu.be/GQmO52f26Ws"
        width="640"
        height="300"
     />

</template>


问:
Error Loading Papermill-Generated ipython .ipynb files in Jupyter Notebook
I generate html reports using papermill and jupyter notebook, and have done so successfully for quite some time. Suddenly, and even though the html reports are generated just fine, the ipynb files that are generated along with it (in fact, I believe papermill generates the ipynb and from this, the html file is then generated) fail to load.  This is baffling to me, and I need to access certain content in the .ipynb file to account for certain calculations that are reflected in the html file.

When attempting to open the .ipynb file in jupyter notebook, I get a pop-up message that says:

```<code>Error loading notebook
OK
</code>```

When I inspected the terminal, I had the following output that made me consider whether the file not being "trusted" was the problem:

```<code>[W 21:25:35.582 NotebookApp] Notebook Desktop/Python/Project/XLI_BearCall_2022-12-21.ipynb is not trusted
</code>```

So I made it trusted, yet I still am unable to open the file, with the same "OK" error mentioned above being thrown.

I went to see if this was the case for all .ipynb files generated along past html reports, and they opened just fine.  In fact, they would print the same error about the file not being trusted to the console, but would end up opening fine anyway. And after trusting the .ipynb file in question, I now get no output whatsoever in the console when attempting to open it, so I'm completely at a loss as to the problem. I have restarted the kernel, restarted jupyter notebook, all to no avail.

Needless to say, since the html generates just fine, papermill has not alerted me to there being a problem:

```<code>Executing: 100%|█████████████████████████████████████████████████████████████████████| 23/23 [00:09<00:00,  2.53cell/s]
</code>```

Assistance is greatly appreciated.

Body:
I generate html reports using papermill and jupyter notebook, and have done so successfully for quite some time. Suddenly, and even though the html reports are generated just fine, the ipynb files that are generated along with it (in fact, I believe papermill generates the ipynb and from this, the html file is then generated) fail to load.  This is baffling to me, and I need to access certain content in the .ipynb file to account for certain calculations that are reflected in the html file.

When attempting to open the .ipynb file in jupyter notebook, I get a pop-up message that says:

Error loading notebook
OK

When I inspected the terminal, I had the following output that made me consider whether the file not being "trusted" was the problem:

[W 21:25:35.582 NotebookApp] Notebook Desktop/Python/Project/XLI_BearCall_2022-12-21.ipynb is not trusted

So I made it trusted, yet I still am unable to open the file, with the same "OK" error mentioned above being thrown.

I went to see if this was the case for all .ipynb files generated along past html reports, and they opened just fine.  In fact, they would print the same error about the file not being trusted to the console, but would end up opening fine anyway. And after trusting the .ipynb file in question, I now get no output whatsoever in the console when attempting to open it, so I'm completely at a loss as to the problem. I have restarted the kernel, restarted jupyter notebook, all to no avail.

Needless to say, since the html generates just fine, papermill has not alerted me to there being a problem:

Executing: 100%|█████████████████████████████████████████████████████████████████████| 23/23 [00:09<00:00,  2.53cell/s]

Assistance is greatly appreciated.


问:
How to style a table with column containing an image?
I have a table and I want it to display values as shown below.

I was getting a table similar to this but when I added the little icon it caused my table to look like this.

```<code>table{
    width: 100%;
    position: relative;
    border: #707070;
    height: 200px;
    text-align: center;
    border-collapse: collapse;
}
th{
    height:10rem;
    padding: .8rem;
    border-bottom:1px solid #707070;
    font-weight: bold;
    font-size: 18px;
    color: #707070;
    line-height: 22px;
    margin-top: 200px;
}
td{
    padding: .8rem;
    text-align: center;
    border-bottom:1px solid #707070 ;
    font-size: 18px;
    line-height: 30px;
    color: #1D1A1A;
}
.appLogo{
    display: flex;
    justify-content: center;
    align-items: center;
}
.appLogo img{
    width: 26px;
    height: 26px;
}
</code>```

index.js

```<code>const Table = (props) => {
    const {enableVal, isPending, data, appName}= props;
    return (
      <table>
          <thead>
            <tr>
              <th>Date</th>
              <th>App Name</th>
              {
                enableVal.map((val,index)=>{
                  return <th key={index}>{val}</th>
                })
              }
            </tr>
          </thead>
          <tbody>
          {
            !isPending ? (
              data.map((item,index)=>{
                 return(
                  <tr key={index}>
                    <td>{changeFormat(item.date)}</td>
                    {
                      appName.map((it,ind)=>{
                        if(it.app_id === item.app_id){
                          return (
                            <div className='appLogo'>
                              <img src={logo} />
                              <td key={ind}>{it.app_name}</td>
                            </div>
                          )
                        }
                      })
                    }
                    {
                      enableVal.map((it,ind)=>{
                        switch(it){
                          case 'Clicks':
                            return <td key={ind}>{item.clicks}</td>
                          case 'AD Requests':
                            return <td key={ind}>{item.requests}</td>
                          case 'AD Responses':
                            return <td>{item.responses}</td>
                          case 'Impressions':
                            return <td>{item.impressions}</td>
                          case 'Revenue':
                            return <td>{item.revenue.toFixed(2)}</td>
                          case 'Fill Rate':
                            return <td>{((item.requests/item.responses)*100).toFixed(2)}</td>
                          case 'CTR':
                            return <td>{((item.clicks/item.impressions)*100).toFixed(2)}</td>
                        }
                      })
                    }
                  </tr>
                )
              })
            )
            :
            <h1>Loading</h1>
          }
          </tbody>
        </table>
    )
}

export default Table
</code>```

This is my Table component and it is rendered in App.js as a fragment.
This is the styling I have produced, how can I make the rows look stable and proper?

Body:
I have a table and I want it to display values as shown below.

I was getting a table similar to this but when I added the little icon it caused my table to look like this.

table{
    width: 100%;
    position: relative;
    border: #707070;
    height: 200px;
    text-align: center;
    border-collapse: collapse;
}
th{
    height:10rem;
    padding: .8rem;
    border-bottom:1px solid #707070;
    font-weight: bold;
    font-size: 18px;
    color: #707070;
    line-height: 22px;
    margin-top: 200px;
}
td{
    padding: .8rem;
    text-align: center;
    border-bottom:1px solid #707070 ;
    font-size: 18px;
    line-height: 30px;
    color: #1D1A1A;
}
.appLogo{
    display: flex;
    justify-content: center;
    align-items: center;
}
.appLogo img{
    width: 26px;
    height: 26px;
}

index.js

const Table = (props) => {
    const {enableVal, isPending, data, appName}= props;
    return (

              Date
              App Name
              {
                enableVal.map((val,index)=>{
                  return {val}
                })
              }

          {
            !isPending ? (
              data.map((item,index)=>{
                 return(

                    {changeFormat(item.date)}
                    {
                      appName.map((it,ind)=>{
                        if(it.app_id === item.app_id){
                          return (

                              {it.app_name}

                          )
                        }
                      })
                    }
                    {
                      enableVal.map((it,ind)=>{
                        switch(it){
                          case 'Clicks':
                            return {item.clicks}
                          case 'AD Requests':
                            return {item.requests}
                          case 'AD Responses':
                            return {item.responses}
                          case 'Impressions':
                            return {item.impressions}
                          case 'Revenue':
                            return {item.revenue.toFixed(2)}
                          case 'Fill Rate':
                            return {((item.requests/item.responses)*100).toFixed(2)}
                          case 'CTR':
                            return {((item.clicks/item.impressions)*100).toFixed(2)}
                        }
                      })
                    }

                )
              })
            )
            :

Loading

          }

    )
}

export default Table

This is my Table component and it is rendered in App.js as a fragment.
This is the styling I have produced, how can I make the rows look stable and proper?


问:
React Native App crash after updating targetSdkVersion to 31
After Updating targetSdkVersion to 31 that required when upload to store, my application crash directly, but it work well when i return it to 30. What can i do to fix it?

compileSdkVersion = 31

targetSdkVersion = 31

buildToolVersion = 30.0.3

gradle = 4.10.1

gradle plugin = 3.3.1

jvm = 1.8

react native version = 0.62.2


问:
why PersistenceExceptionTranslationInterceptor only concern RuntimeException?
anybody give some idea why PersistenceExceptionTranslationInterceptor only concern RuntimeException?

as some driver will give the exception such as org.postgresql.util.PSQLException or java.sql.SQLException

we want to convert these exception to others and can not be handled at here via PersistenceExceptionTranslator

it is a design cursoriness or a special consideration?

if it is a special consideration, any suggestion about to convert the SQLException to customized Exception?


问:
customize redis key name by using session object in NestJS
My project is now based on NestJS, and I am using Express's session to use session, and I have linked Redis as a storage.

What I want is to divide the depth for each user, set the key, and store the value when saving data in Redis.

example ).

user : Peter, hobby : soccer -> Redis : dashboard:session:peter:hobby - soccer.

user: John, hobby : tennis -> Redis : dashboard:session:john:hobby - tennis

Therefore, the redis integration and session usage code is as follows.

```<code>const app = await NestFactory.create(AppModule);

// redis
const redis = require('redis');
const redisHost = process.env.REDIS_HOST;
const redisPort = process.env.REDIS_PORT;
const redisPassword = process.env.REDIS_PASSWORD;
const redisUrl = `redis://${redisHost}:${redisPort}`;
const redisClient = redis.createClient({
  url: redisUrl,
  password: redisPassword,
  legacyMode: true,
});

redisClient.connect();

 app.use(
    session({
      store: new RedisStore({ client: redisClient, prefix: 'dashboard' }),
      secret: 'test123',
      resave: false,
      saveUninitialized: false,
    }),
  );

// OtherController method
  @Get('/redis/hobby')
  getLogin(
    @Req() req: Request,
    @Session() session: Record<string, any>,
    @Query() user: any,
  ) {
    const name = user.username;
    const hobby = user.hobby;

    const depth1 = 'session';
    const depth2 = 'hobby';
    session[depth1][name][depth2] = hobby; // (*)
  }[enter image description here][1]
</code>```

However, when I set the depth in session and try to save the value, the following error occurs. For reference, the username and hobby values were properly delivered as entered.

postman test

error log : TypeError: Cannot read properties of undefined (reading 'john')

When storing data in redis using express session, is there a way to set the depths to 2 or 3 in redis?

Body:
My project is now based on NestJS, and I am using Express's session to use session, and I have linked Redis as a storage.

What I want is to divide the depth for each user, set the key, and store the value when saving data in Redis.

example ).

user : Peter, hobby : soccer -> Redis : dashboard:session:peter:hobby - soccer.

user: John, hobby : tennis -> Redis : dashboard:session:john:hobby - tennis

Therefore, the redis integration and session usage code is as follows.

const app = await NestFactory.create(AppModule);

// redis
const redis = require('redis');
const redisHost = process.env.REDIS_HOST;
const redisPort = process.env.REDIS_PORT;
const redisPassword = process.env.REDIS_PASSWORD;
const redisUrl = `redis://${redisHost}:${redisPort}`;
const redisClient = redis.createClient({
  url: redisUrl,
  password: redisPassword,
  legacyMode: true,
});

redisClient.connect();

 app.use(
    session({
      store: new RedisStore({ client: redisClient, prefix: 'dashboard' }),
      secret: 'test123',
      resave: false,
      saveUninitialized: false,
    }),
  );

// OtherController method
  @Get('/redis/hobby')
  getLogin(
    @Req() req: Request,
    @Session() session: Record<string, any>,
    @Query() user: any,
  ) {
    const name = user.username;
    const hobby = user.hobby;

    const depth1 = 'session';
    const depth2 = 'hobby';
    session[depth1][name][depth2] = hobby; // (*)
  }[enter image description here][1]

However, when I set the depth in session and try to save the value, the following error occurs. For reference, the username and hobby values were properly delivered as entered.

postman test

error log : TypeError: Cannot read properties of undefined (reading 'john')

When storing data in redis using express session, is there a way to set the depths to 2 or 3 in redis?


问:
Shell Script not able to append xml format String content to xml File
I have a string in xml format named as xmlString generated in groovy and I want to add that string to an empty settings.xml file through shell script

xmlString:

```<code><settings>
    <servers>
        <server>
            <id>server1-pass</id>
            <username>${server.id}</username>
            <password>${server.password}</password>
        </server>
        <server>
            <id>server2-pass</id>
            <username>${server.id}</username>
            <password>${server.password}</password>
        </server>

    </servers>

    <mirrors>
        <mirror>
            <id>directory</id>
            <mirrorOf>external:*</mirrorOf>
            <url>http://stackoverflow.com</url>
        </mirror>
    </mirrors>

</code>```

I want to pass this into settings.xml file which is empty

What I tried

```<code>sh '''
   echo $xmlString > settings.xml
  '''
</code>```

and

```<code>sh '''
   echo '''+xmlString+''' > settings.xml
'''
</code>```

but nothing worked.

I know the error is caused because of < and > characters inside the String but I am out of ideas as to how to resolve this.

Can Someone please help.......Thank you

Body:
I have a string in xml format named as xmlString generated in groovy and I want to add that string to an empty settings.xml file through shell script

xmlString:

<settings>
    <servers>
        <server>
            <id>server1-pass</id>
            <username>${server.id}</username>
            <password>${server.password}</password>
        </server>
        <server>
            <id>server2-pass</id>
            <username>${server.id}</username>
            <password>${server.password}</password>
        </server>

    </servers>

    <mirrors>
        <mirror>
            <id>directory</id>
            <mirrorOf>external:*</mirrorOf>
            <url>http://stackoverflow.com</url>
        </mirror>
    </mirrors>

I want to pass this into settings.xml file which is empty

What I tried

sh '''
   echo $xmlString > settings.xml
  '''

and

sh '''
   echo '''+xmlString+''' > settings.xml
'''

but nothing worked.

I know the error is caused because of < and > characters inside the String but I am out of ideas as to how to resolve this.

Can Someone please help.......Thank you


问:
Complexity of sparse,primary indexing
Learned about indexing today and I have some issues understanding the complexity which was O(log(a)+1). The 1 was there because the amount of blocks to be searched were less than the main ones . but what if we have more keys in the smaller blocks . Would the 1 change to O(n).
I know the explanation is not that quite good , i just learned the topic and posted the question without even looking back once.

Just want to know the explanation of the complexity.

Title: Complexity of sparse,primary indexing


问:
Compiled with problems conflict between eslint-config-react-app\base.js" and "BaseConfig »
[eslint] Plugin "react" was conflicted between "package.json » eslint-config-react-app »

C:\Users\prathmesh\Desktop\hekki\cli\node_modules\eslint-config-react-app\base.js" and "BaseConfig »

i tried uninstalling and reinstalling but never work


问:
How would you create a sticky drawer/bottom drawer/slide-out component with MUI?
I'm using MUI v5, and I'm not entirely sure what this type of UI is called (where there's a drawer-like/slide-out component in the bottom right hand of your screen):

Name of component aside, how would I build this with MUI?
Would it be best to use the <Drawer /> component, or some other UI element for it?


问:
Using Snyk-Delta for Azure container image scan
I am trying to configure synk-delta to fail SNYK security scan task only if new vulnerabilities are being introduced in ACR.

We need to run snyk scan for Azure container and set it to fail only when there are new vulnerabilities found as compared to previous image

here are the steps/ additional arguments tried and test

additionalArguments: ' --json --print-deps | snyk-delta'

additionalArguments: '--json --print-deps` -- Build pass Generates report

additionalArguments: '--json --print-deps | snyk-delta --baselineOrg xxx --baselineProject xxx -d' -- Error Failed to scan image "snyk-delta". Please make sure the image and/or repository exist, and that you are using the correct credentials


问:
How to create Cusom SSL socket factory and register schemes using http component 4.5.13
I am working on migration of httpclient/3.1 to httpclient/4.5.13. The existing code in 3.1 is  shown below and the code is not in spring/springboot

```<code>protected static void registerHttpsQAHandler(){
    LOGGER.trace("HttpClient is registering an SSL handler that will accept self-signed and unknown certs.");
    Protocol easyhttps = new Protocol("https", (ProtocolSocketFactory)new EasySSLProtocolSocketFactory(), 443);
    Protocol.registerProtocol("https", easyhttps);
}

public static void AllowAllSSLCertificates(){
    // Create a trust manager that does not validate certificate chains
    TrustManager[] trustAllCerts = new TrustManager[] {
        new X509TrustManager() {

            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }

            @Override
            public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {

            }

            @Override
            public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {

            }
        }
    };

    try {
        // Install the all-trusting trust manager
        SSLContext sc = SSLContext.getInstance("SSL");
        // Create empty HostnameVerifier
        HostnameVerifier hv = new HostnameVerifier() {
            public boolean verify(String arg0, SSLSession arg1) {
                return true;
            }
        };

        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        HttpsURLConnection.setDefaultHostnameVerifier(hv);
    } catch (KeyManagementException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }

    registerHttpsQAHandler();
}
</code>```

I want to write the implementation for 4.5.13 but couldn't get the the implementation for ProtocolSocketfactory in  4.5.13 version.
Any leads would help me !

Body:
I am working on migration of httpclient/3.1 to httpclient/4.5.13. The existing code in 3.1 is  shown below and the code is not in spring/springboot

protected static void registerHttpsQAHandler(){
    LOGGER.trace("HttpClient is registering an SSL handler that will accept self-signed and unknown certs.");
    Protocol easyhttps = new Protocol("https", (ProtocolSocketFactory)new EasySSLProtocolSocketFactory(), 443);
    Protocol.registerProtocol("https", easyhttps);
}

public static void AllowAllSSLCertificates(){
    // Create a trust manager that does not validate certificate chains
    TrustManager[] trustAllCerts = new TrustManager[] {
        new X509TrustManager() {

            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }

            @Override
            public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {

            }

            @Override
            public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {

            }
        }
    };

    try {
        // Install the all-trusting trust manager
        SSLContext sc = SSLContext.getInstance("SSL");
        // Create empty HostnameVerifier
        HostnameVerifier hv = new HostnameVerifier() {
            public boolean verify(String arg0, SSLSession arg1) {
                return true;
            }
        };

        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        HttpsURLConnection.setDefaultHostnameVerifier(hv);
    } catch (KeyManagementException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }

    registerHttpsQAHandler();
}

I want to write the implementation for 4.5.13 but couldn't get the the implementation for ProtocolSocketfactory in  4.5.13 version.
Any leads would help me !


问:
how can i generate C/G chord in jTab?
How can i generate C/G chord in jtab? i tried

```<code>jtab.render($('#mytab'),'C/G');
</code>```

but it's not working. or is there alternate solution which supports 'C/G' type chords? thnaks!

Title: how can i generate C/G chord in jTab?

Body:
How can i generate C/G chord in jtab? i tried

jtab.render($('#mytab'),'C/G');

but it's not working. or is there alternate solution which supports 'C/G' type chords? thnaks!


问:
Upload into AWS S3 from Pentaho ETL
I am trying to upload my PGDB into S3 into CSV format. Now I can do that by assigning my aws key pairs through aws cli.

But the problem is, one key pair is registered for one PC. So if I want to run multiple instances of my ETL through Pentaho and need to use different set of key pairs, I have to create multiple VMs.

Is there any way to run multiple aws key pairs from same VM for different ETL run?

I only have solution to run one aws key pair from one PC. I do not have any idea how to run multiple key pairs

Title: Upload into AWS S3 from Pentaho ETL


问:
How to create Role based authentication in HapiJS
I am working on a rest API project written with HapiJS.there is two schema interview process and employee. after the employee login, the user gets a token to pass in the header of every request. Uer have different roles (Admin, Employee, Manager) and
some API endpoints are reachable only by users with a certain role.

Someone, please help me in defining this check in the best way in HapiJs, so without writing the check every time inside the route.

Thanks in advance..!!


问:
Verification and Validation of JWT Token on server and client side
I am trying to understand the validation and verification of JWT tokens when using Web APIs. The call flow is as follows:

A = Client

B = API Server

A -> B: A sends a requests to Server with user name and password.  ( This is HTTPS so using TLS encryption)

B : Authenticates the client A.

B-> A: Sends back a JWT token back to A. Assuming that B is using "Asymmetric Key Encryption". B creates a header with {alg:RS256 typ:JWT} and it adds some claims. And then B creates the signature by hashing header + payload, and then signing it with private key of B.

A: A receives the token

Question: Does A need to validate the token it has received from B? If yes, it will need the PUBLIC key of B. Also, if B were to use a "symmetric key algorithm", then A also needs the "shared secret" or the key which B used to sign the token.

A -> B: A needs to make a API call to B. A needs to include the token in the Authorization header:

Question: Assuming that "Asymmetric Key Encryption" was used earlier. Will A now just add the token as it was received in the Authorization header. Or A will create a hash of payload and claims, and then sign it with it's own Private Key.

Question: Assuming that A had just used the token as is, when B receives this token, what is B supposed to do? Validate the token using B's public key ....or just a string compare of the token suffice, to validate. Of course B will need to look at the claims :) :) .

Assuming that A had signed the token with it's private key. Then B needs to know the corresponding Public key to validate the token. But if B were talking to multiple clients will it then need each clients Public key ?

At this time I am just trying to understand how things are supposed to work. The examples implementations that I have seen are using "Symmetric Key Algorithm" and the client just accepts from server and uses it as is for the next API calls. Seems a bit odd to me, if the token is compromised then we are in trouble.


问:
Python code logic for loading a single image for data training as my colab session is crashing using all available RAM
Google colab is not able handle large amount of my image data as the 12 GB RAM given freely is not enough. I am working on microscopic images of Red blood cells and white blood cells and loading the image again and again for each bounding box. Is it possible that I load the single image once and receive the desired detection through Faster RCNN.

```<code>image_liste=[]
k=0
l=0
z=0
for a in pd.read_csv('/content/MyDrive/MyDrive/AIH/Raafeh/data with
annotations/annotations.csv').values:
  Name,xmin,ymin,xmax,ymax,label=a
  bb1={
        'x1':int(xmin),
        'y1':int(ymin),
        'x2':int(xmax),
        'y2':int(ymax)
        }
  try:
    img=cv2.imread('/content/MyDrive/MyDrive/AIH/Raafeh/data with
    annotations/images/'+Name)
    ss.setBaseImage(img)
    ss.switchToSelectiveSearchFast()
    rects = ss.process()
    for i in rects:
      x, y, w, h = i
      bb2={'x1':x,
          'y1':y,
          'x2':x+w,
          'y2':y+h
          }
      img1=img[bb2['y1']:bb2['y2'],bb2['x1']:bb2['x2']]
      img1_shape=cv2.resize(img1,(224,224))
      if k<l:
            if 0.5<get_iou(bb1,bb2):
              image_liste.append([img1_shape,1])
              k+=1
      else:
        if 0.5<get_iou(bb1,bb2):
          image_liste.append([img1_shape,1])
          k+=1
        else:
          image_liste.append([img1_shape,0])
          l+=1
  except Exception as e:
    print('There is an error',e)
  z+=1
  print(Name,z,len(rects))
</code>```
```<code>
</code>```

enter image description here

```<code>**Above is my notebook code where i am loading my images is there a way where i can the data length without affecting the .csv file for bounding boxes[enter image description here](https://i.stack.imgur.com/HPcxT.jpg)**
</code>```

Body:
Google colab is not able handle large amount of my image data as the 12 GB RAM given freely is not enough. I am working on microscopic images of Red blood cells and white blood cells and loading the image again and again for each bounding box. Is it possible that I load the single image once and receive the desired detection through Faster RCNN.

image_liste=[]
k=0
l=0
z=0
for a in pd.read_csv('/content/MyDrive/MyDrive/AIH/Raafeh/data with
annotations/annotations.csv').values:
  Name,xmin,ymin,xmax,ymax,label=a
  bb1={
        'x1':int(xmin),
        'y1':int(ymin),
        'x2':int(xmax),
        'y2':int(ymax)
        }
  try:
    img=cv2.imread('/content/MyDrive/MyDrive/AIH/Raafeh/data with
    annotations/images/'+Name)
    ss.setBaseImage(img)
    ss.switchToSelectiveSearchFast()
    rects = ss.process()
    for i in rects:
      x, y, w, h = i
      bb2={'x1':x,
          'y1':y,
          'x2':x+w,
          'y2':y+h
          }
      img1=img[bb2['y1']:bb2['y2'],bb2['x1']:bb2['x2']]
      img1_shape=cv2.resize(img1,(224,224))
      if k<l:
            if 0.5<get_iou(bb1,bb2):
              image_liste.append([img1_shape,1])
              k+=1
      else:
        if 0.5<get_iou(bb1,bb2):
          image_liste.append([img1_shape,1])
          k+=1
        else:
          image_liste.append([img1_shape,0])
          l+=1
  except Exception as e:
    print('There is an error',e)
  z+=1
  print(Name,z,len(rects))

enter image description here

**Above is my notebook code where i am loading my images is there a way where i can the data length without affecting the .csv file for bounding boxes[enter image description here](https://i.stack.imgur.com/HPcxT.jpg)**


问:
Renaming a column in a dataframe without getting an Attribute Error
Anytime I have renamed this Unnamed Column, I either get an Attribute: NoneType Error or the column itself does not change. This is an excel file not a csv file.

I have been trying to rename this 'Unnamed: 0' in multiple ways in pandas. However I've only either gotten an Attribute None Type Error, or it does not change the data frame column at all. I've done the rename multiple ways and it still did not work. I was able to change the NaT column but not the Unnamed column and I'm unsure as to why this is not occurring. I've tried it as

```<code>properties=properties.rename( columns={0:'new column name'}, inplace= True )
properties=properties.rename( columns={"Unnamed: 0":"new column name"}, inplace= True )
properties = properties.rename( columns={"0": "new column name"}, inplace = True)
properties=properties.rename(columns={0:'new column name'})
</code>```

If anyone is able to help me and see what I did wrong it would help greatly. I have had it without the inplace = True as well. It does not change the column name still.

Body:
Anytime I have renamed this Unnamed Column, I either get an Attribute: NoneType Error or the column itself does not change. This is an excel file not a csv file.

I have been trying to rename this 'Unnamed: 0' in multiple ways in pandas. However I've only either gotten an Attribute None Type Error, or it does not change the data frame column at all. I've done the rename multiple ways and it still did not work. I was able to change the NaT column but not the Unnamed column and I'm unsure as to why this is not occurring. I've tried it as

properties=properties.rename( columns={0:'new column name'}, inplace= True )
properties=properties.rename( columns={"Unnamed: 0":"new column name"}, inplace= True )
properties = properties.rename( columns={"0": "new column name"}, inplace = True)
properties=properties.rename(columns={0:'new column name'})

If anyone is able to help me and see what I did wrong it would help greatly. I have had it without the inplace = True as well. It does not change the column name still.


问:
onClick function working on desktop but not on mobile
I've built a spotify clone that works perfectly fine in desktop but when clicking on a song in mobile it only works sometimes and I'm not sure why. Here is the function and here is the link to my github repo https://github.com/alyssasitto/spotify-client. Also this is my deployed app https://alyssas-spotify-clone.netlify.app/

```<code><button onClick={async () => await
playSong(album.uri,el.track_number)}
key={el.index}
className="track"></button>
</code>```

I've tried making the onClick function a onTouchStart function and tried changing the cursor to a pointer but neither solutions worked. I've also tried making the arrow function into a function declaration and function expression but no luck.

Body:
I've built a spotify clone that works perfectly fine in desktop but when clicking on a song in mobile it only works sometimes and I'm not sure why. Here is the function and here is the link to my github repo https://github.com/alyssasitto/spotify-client. Also this is my deployed app https://alyssas-spotify-clone.netlify.app/

<button onClick={async () => await
playSong(album.uri,el.track_number)}
key={el.index}
className="track"></button>

I've tried making the onClick function a onTouchStart function and tried changing the cursor to a pointer but neither solutions worked. I've also tried making the arrow function into a function declaration and function expression but no luck.


问:
Error : TS18002: The 'files' list in config file 'tsconfig.json' is empty
So I don't have tsconfig.json file in my project. Instead I have tsconfig.web.json  and tsconfig.native.json. But it is saying the 'files'  empty in tsconfig.json file.

How can I fix it ?

So yesterday I tried to change the "tsconfig.web.json"  to "tsconfig.json" because when i checked two files there was the same thing in both of them.
but there was the same error!

Thankyou for your answers!


问:
Exposing REST API only for a short period of time
I am working on a project which is already using spring-security Jwt for authentication of every incoming request. I need to add another REST controller in the same module with different path like /api/v1/statement. All api's inside this controller should be accesible to the user only for 30 mins(same user) with some temporary toekn. Post 30 mins that token should expire and API should be no longer accesible to the user. Can anybody here please suggest how can i achieve this using spring security?

I checked few blogs related to the spring security but couldn't find what i am looking for.


问:
How to use the concept of indexing dictionary in python
I encountered a program where I had to append one dictionary into another, and I was unable to do it because I could not use indexing in dictionary so I wanted to know what the possible ways are I could do it</p>


问:
Can't clear setInterval on React Native Project
I am having issues clearing setInterval in my React Native Project

Here is what I have tried

```<code>const options = {
    method: 'get',
    url: 'http://demo.com/getInfo',
    headers: appHeaders,
  };

  const myInterval = setInterval(async function () {
    try {
      const results = await axios(options);
      if (Object.keys(results.data).length !== 0) {
        console.log('request successful');
        clearInterval(myInterval);
      }
    } catch (error) {
      console.log(
        'there was an error sending remote control access request',
        error,
      );
    }
  }, 4000);
</code>```

Body:
I am having issues clearing setInterval in my React Native Project

Here is what I have tried

const options = {
    method: 'get',
    url: 'http://demo.com/getInfo',
    headers: appHeaders,
  };

  const myInterval = setInterval(async function () {
    try {
      const results = await axios(options);
      if (Object.keys(results.data).length !== 0) {
        console.log('request successful');
        clearInterval(myInterval);
      }
    } catch (error) {
      console.log(
        'there was an error sending remote control access request',
        error,
      );
    }
  }, 4000);