问:
Get specific JSON object from multiple
I am working with the FedEx Rates API in PHP to get shipping estimates which, by default, returns multiple service types that I have converted into a JSON array.

```<code>{
transactionId: 'xxxxxxx-xxxx-xxxx-xxxx-xxxxxxxx', output: {…}}
output:
alerts: (2) [{…}, {…}]
encoded: false
quoteDate: "2022-12-07"
rateReplyDetails: Array(10)
0: {serviceType: 'FEDEX_EXPRESS_SAVER', serviceName: 'FedEx Express Saver®', packagingType: 'YOUR_PACKAGING', commit: {…}, ratedShipmentDetails: Array(1), …}
1: {serviceType: 'FEDEX_2_DAY', serviceName: 'FedEx 2Day®', packagingType: 'YOUR_PACKAGING', commit: {…}, ratedShipmentDetails: Array(1), …}
2: {serviceType: 'FEDEX_2_DAY_AM', serviceName: 'FedEx 2Day® AM', packagingType: 'YOUR_PACKAGING', commit: {…}, ratedShipmentDetails: Array(1), …}
3: {serviceType: 'FEDEX_GROUND', serviceName: 'FedEx Ground®', packagingType: 'YOUR_PACKAGING', commit: {…}, customerMessages: Array(1), …}
4: {serviceType: 'STANDARD_OVERNIGHT', serviceName: 'FedEx Standard Overnight®', packagingType: 'YOUR_PACKAGING', commit: {…}, ratedShipmentDetails: Array(1), …}
5: {serviceType: 'FEDEX_STANDARD_OVERNIGHT_EXTRA_HOURS', serviceName: 'FedEx Standard Overnight® EH', packagingType: 'YOUR_PACKAGING', commit: {…}, ratedShipmentDetails: Array(1), …}
6: {serviceType: 'FEDEX_PRIORITY_OVERNIGHT_EXTRA_HOURS', serviceName: 'FedEx Priority Overnight® EH', packagingType: 'YOUR_PACKAGING', commit: {…}, ratedShipmentDetails: Array(1), …}
7: {serviceType: 'PRIORITY_OVERNIGHT', serviceName: 'FedEx Priority Overnight®', packagingType: 'YOUR_PACKAGING', commit: {…}, ratedShipmentDetails: Array(1), …}
8: {serviceType: 'FIRST_OVERNIGHT', serviceName: 'FedEx First Overnight®', packagingType: 'YOUR_PACKAGING', commit: {…}, ratedShipmentDetails: Array(1), …}
9: {serviceType: 'FEDEX_FIRST_OVERNIGHT_EXTRA_HOURS', serviceName: 'FedEx First Overnight® EH', packagingType: 'YOUR_PACKAGING', commit: {…}, ratedShipmentDetails: Array(1), …}
length: 10
...
</code>```

I am getting this in an Ajax response to update the page, but where I'm stuck is only grabbing certain ones, like FEDEX_GROUND, FEDEX_EXPRESS_SAVER, FEDEX_2_DAY, and PRIORITY_OVERNIGHT, to display.

```<code>$.ajax({
        type: "POST",
        url: "...",
        headers: { ... },
        data: { ... },
}).done(function (response) {
        const obj = JSON.parse(response);

        // I would like this to be each of the specified serviceType only, currently does all of them
        $.each(obj.output.rateReplyDetails, function () {
            return this.serviceType;
});
</code>```

I'm guessing it should be something like JSON Object where key serviceType === FEDEX_GROUND, but not sure what that syntax looks like. I found filter() but couldn't get that to work.

Title: Get specific JSON object from multiple

Body:
I am working with the FedEx Rates API in PHP to get shipping estimates which, by default, returns multiple service types that I have converted into a JSON array.

{
transactionId: 'xxxxxxx-xxxx-xxxx-xxxx-xxxxxxxx', output: {…}}
output:
alerts: (2) [{…}, {…}]
encoded: false
quoteDate: "2022-12-07"
rateReplyDetails: Array(10)
0: {serviceType: 'FEDEX_EXPRESS_SAVER', serviceName: 'FedEx Express Saver®', packagingType: 'YOUR_PACKAGING', commit: {…}, ratedShipmentDetails: Array(1), …}
1: {serviceType: 'FEDEX_2_DAY', serviceName: 'FedEx 2Day®', packagingType: 'YOUR_PACKAGING', commit: {…}, ratedShipmentDetails: Array(1), …}
2: {serviceType: 'FEDEX_2_DAY_AM', serviceName: 'FedEx 2Day® AM', packagingType: 'YOUR_PACKAGING', commit: {…}, ratedShipmentDetails: Array(1), …}
3: {serviceType: 'FEDEX_GROUND', serviceName: 'FedEx Ground®', packagingType: 'YOUR_PACKAGING', commit: {…}, customerMessages: Array(1), …}
4: {serviceType: 'STANDARD_OVERNIGHT', serviceName: 'FedEx Standard Overnight®', packagingType: 'YOUR_PACKAGING', commit: {…}, ratedShipmentDetails: Array(1), …}
5: {serviceType: 'FEDEX_STANDARD_OVERNIGHT_EXTRA_HOURS', serviceName: 'FedEx Standard Overnight® EH', packagingType: 'YOUR_PACKAGING', commit: {…}, ratedShipmentDetails: Array(1), …}
6: {serviceType: 'FEDEX_PRIORITY_OVERNIGHT_EXTRA_HOURS', serviceName: 'FedEx Priority Overnight® EH', packagingType: 'YOUR_PACKAGING', commit: {…}, ratedShipmentDetails: Array(1), …}
7: {serviceType: 'PRIORITY_OVERNIGHT', serviceName: 'FedEx Priority Overnight®', packagingType: 'YOUR_PACKAGING', commit: {…}, ratedShipmentDetails: Array(1), …}
8: {serviceType: 'FIRST_OVERNIGHT', serviceName: 'FedEx First Overnight®', packagingType: 'YOUR_PACKAGING', commit: {…}, ratedShipmentDetails: Array(1), …}
9: {serviceType: 'FEDEX_FIRST_OVERNIGHT_EXTRA_HOURS', serviceName: 'FedEx First Overnight® EH', packagingType: 'YOUR_PACKAGING', commit: {…}, ratedShipmentDetails: Array(1), …}
length: 10
...

I am getting this in an Ajax response to update the page, but where I'm stuck is only grabbing certain ones, like FEDEX_GROUND, FEDEX_EXPRESS_SAVER, FEDEX_2_DAY, and PRIORITY_OVERNIGHT, to display.

$.ajax({
        type: "POST",
        url: "...",
        headers: { ... },
        data: { ... },
}).done(function (response) {
        const obj = JSON.parse(response);

        // I would like this to be each of the specified serviceType only, currently does all of them
        $.each(obj.output.rateReplyDetails, function () {
            return this.serviceType;
});

I'm guessing it should be something like JSON Object where key serviceType === FEDEX_GROUND, but not sure what that syntax looks like. I found filter() but couldn't get that to work.


来源: stackexchange

问:
Trying to Build a iframe that takes Gradio Link as Source as displays the resulting model output
I am trying to build a SPA which would input box that would take a Gradio Link, (Gradio is simple tool to build Interface for ML Models). Now, I am using an Iframe that takes the user input URL and displays the result. Something like:

Problem is Gradio Link should not be kept open and some authorizations need to be kept.

Approach 1: Tried using Axios get request to make request to URL and display the content in iframe as srcDoc, but while trying to run the model in iframe it fails as returned HTML file as relative paths, example /run/predict.

Approach 2: Tried directly using , assuming origin Cookie (SPA authentication tokens) would be transferred to destination where I can verify User and send the response, but the cookies in the origin domain are not being transferred to source URL.

Now, for method 1 I need to intercept all the request going out from nextjs with user input URL, example /run/predict to url/run/predict. Nextjs Allows to proxy but when request is of type api/run/predict.

For method 2: I need to send the origin cookie to destination (Source URL). Tried, setting cookie sameSite: None, and secure to true, but still not receiving cookies on destination URL.

Can anyone help me with what could be a possible solution for method 1 or 2 or I am approaching wrong way then please suggest me with right one.

ContentLicense: CC BY-SA 4.0


问:
Parallel Period Explanation
I am fairly new to parallel periods and there use in dax. I understand the basics of parallel periods but I am not familiar using them. I am attempting to understand some code used by my company if anyone wouldn't mind breaking this down for me I would greatly appreciate it.

I understand the range it is pulling between but fail to understand how the initial max calendar year = 2021 works in all this. Also, if you can help explain how dividing the first set of code by the second works. That would be a freakin life saver. The end result currently is it comes out to equal a percentage that is used currently.

IF(
MAX('Calendar'[Year]) = 2021,
CALCULATE( [Total Cash] , PARALLELPERIOD('Calendar'[PERIOD_ENDING] , -24 , MONTH ) )
,
CALCULATE( [Total Cash] , PARALLELPERIOD('Calendar'[PERIOD_ENDING] , -12 , MONTH ) ))

IF(
MAX('Calendar'[Year]) = 2021,
CALCULATE( [Total Cash] , PARALLELPERIOD('Calendar'[PERIOD_ENDING] ,  -2 , YEAR ) )
,
CALCULATE( [Total Cash] , PARALLELPERIOD('Calendar'[PERIOD_ENDING] ,  -1 , YEAR ) ))

Title: Parallel Period Explanation


问:
AWS Batch: customize event
I am running an AWS Batch array job with a few thousand children.  When the parent job is complete, I'd like to trigger a lambda to do some cleanup on the output.

I can currently trigger an EventBridge rule when each child job finishes.  How can we distinguish when the parent job completes?
EDIT:  You can identify the parent job via
if ":" not in event["detail"]["jobId"]:

I'd also like to change the data included in the event signal, so I can tell my lambda what bucket the output went to, the name of the output file produced, etc.  Can we customize the fields in an event created by Batch?

Currently, the events I'm getting look like this (account number removed):

```<code>{
    "version": "0",
    "id": "f6c74fc4-a943-9592-2be0-99df7b67f79f",
    "detail-type": "Batch Job State Change",
    "source": "aws.batch",
    "account": "",
    "time": "2022-12-07T22:51:38Z",
    "region": "us-east-1",
    "resources": [
        "arn:aws:batch:us-east-1::job/138677dc-d684-4e39-b42f-6626515be7c7:2"
    ],
    "detail": {
        "jobArn": "arn:aws:batch:us-east-1::job/138677dc-d684-4e39-b42f-6626515be7c7:2",
        "jobName": "event_test",
        "jobId": "138677dc-d684-4e39-b42f-6626515be7c7:2",
        "jobQueue": "arn:aws:batch:us-east-1::job-queue/HLM2",
        "status": "SUCCEEDED",
        "attempts": [
            {
                "container": {
                    "containerInstanceArn": "arn:aws:ecs:us-east-1::container-instance/AWSBatch-HLM2-c929f2e7-5cd9-3f96-8ad3-a2717fb4d2ec/6f1037214ed247aebe5ead4bf19e5929",
                    "taskArn": "arn:aws:ecs:us-east-1::task/AWSBatch-HLM2-c929f2e7-5cd9-3f96-8ad3-a2717fb4d2ec/5cb0c860da6a484ca6ba23a468a7f76c",
                    "exitCode": 0,
                    "logStreamName": "HLM2/default/5cb0c860da6a484ca6ba23a468a7f76c",
                    "networkInterfaces": []
                },
                "startedAt": 1670453438605,
                "stoppedAt": 1670453497525,
                "statusReason": "Essential container in task exited"
            }
        ],
        "statusReason": "Essential container in task exited",
        "createdAt": 1670453294805,
        "startedAt": 1670453438605,
        "stoppedAt": 1670453497525,
        "dependsOn": [],
        "jobDefinition": "arn:aws:batch:us-east-1::job-definition/HLM2:8",
        "parameters": {},
        "container": {
            "image": ".dkr.ecr.us-east-1.amazonaws.com/hlm:latest",
            "command": [],
            "jobRoleArn": "arn:aws:iam:::role/hlm-ec2-access-role",
            "executionRoleArn": "arn:aws:iam:::role/hlm-ec2-access-role",
            "volumes": [],
            "environment": [],
            "mountPoints": [],
            "ulimits": [],
            "exitCode": 0,
            "containerInstanceArn": "arn:aws:ecs:us-east-1::container-instance/AWSBatch-HLM2-c929f2e7-5cd9-3f96-8ad3-a2717fb4d2ec/6f1037214ed247aebe5ead4bf19e5929",
            "taskArn": "arn:aws:ecs:us-east-1::task/AWSBatch-HLM2-c929f2e7-5cd9-3f96-8ad3-a2717fb4d2ec/5cb0c860da6a484ca6ba23a468a7f76c",
            "logStreamName": "HLM2/default/5cb0c860da6a484ca6ba23a468a7f76c",
            "networkInterfaces": [],
            "resourceRequirements": [
                {
                    "value": "2",
                    "type": "VCPU"
                },
                {
                    "value": "8192",
                    "type": "MEMORY"
                }
            ],
            "secrets": []
        },
        "arrayProperties": {
            "statusSummary": {},
            "index": 2
        },
        "timeout": {
            "attemptDurationSeconds": 1800
        },
        "tags": {
            "resourceArn": "arn:aws:batch:us-east-1::job/138677dc-d684-4e39-b42f-6626515be7c7"
        },
        "platformCapabilities": [
            "EC2"
        ],
        "eksAttempts": []
    }
}
</code>```

Title: AWS Batch: customize event

Body:
I am running an AWS Batch array job with a few thousand children.  When the parent job is complete, I'd like to trigger a lambda to do some cleanup on the output.

I can currently trigger an EventBridge rule when each child job finishes.  How can we distinguish when the parent job completes?
EDIT:  You can identify the parent job via
if ":" not in event["detail"]["jobId"]:

I'd also like to change the data included in the event signal, so I can tell my lambda what bucket the output went to, the name of the output file produced, etc.  Can we customize the fields in an event created by Batch?

Currently, the events I'm getting look like this (account number removed):

{
    "version": "0",
    "id": "f6c74fc4-a943-9592-2be0-99df7b67f79f",
    "detail-type": "Batch Job State Change",
    "source": "aws.batch",
    "account": "",
    "time": "2022-12-07T22:51:38Z",
    "region": "us-east-1",
    "resources": [
        "arn:aws:batch:us-east-1::job/138677dc-d684-4e39-b42f-6626515be7c7:2"
    ],
    "detail": {
        "jobArn": "arn:aws:batch:us-east-1::job/138677dc-d684-4e39-b42f-6626515be7c7:2",
        "jobName": "event_test",
        "jobId": "138677dc-d684-4e39-b42f-6626515be7c7:2",
        "jobQueue": "arn:aws:batch:us-east-1::job-queue/HLM2",
        "status": "SUCCEEDED",
        "attempts": [
            {
                "container": {
                    "containerInstanceArn": "arn:aws:ecs:us-east-1::container-instance/AWSBatch-HLM2-c929f2e7-5cd9-3f96-8ad3-a2717fb4d2ec/6f1037214ed247aebe5ead4bf19e5929",
                    "taskArn": "arn:aws:ecs:us-east-1::task/AWSBatch-HLM2-c929f2e7-5cd9-3f96-8ad3-a2717fb4d2ec/5cb0c860da6a484ca6ba23a468a7f76c",
                    "exitCode": 0,
                    "logStreamName": "HLM2/default/5cb0c860da6a484ca6ba23a468a7f76c",
                    "networkInterfaces": []
                },
                "startedAt": 1670453438605,
                "stoppedAt": 1670453497525,
                "statusReason": "Essential container in task exited"
            }
        ],
        "statusReason": "Essential container in task exited",
        "createdAt": 1670453294805,
        "startedAt": 1670453438605,
        "stoppedAt": 1670453497525,
        "dependsOn": [],
        "jobDefinition": "arn:aws:batch:us-east-1::job-definition/HLM2:8",
        "parameters": {},
        "container": {
            "image": ".dkr.ecr.us-east-1.amazonaws.com/hlm:latest",
            "command": [],
            "jobRoleArn": "arn:aws:iam:::role/hlm-ec2-access-role",
            "executionRoleArn": "arn:aws:iam:::role/hlm-ec2-access-role",
            "volumes": [],
            "environment": [],
            "mountPoints": [],
            "ulimits": [],
            "exitCode": 0,
            "containerInstanceArn": "arn:aws:ecs:us-east-1::container-instance/AWSBatch-HLM2-c929f2e7-5cd9-3f96-8ad3-a2717fb4d2ec/6f1037214ed247aebe5ead4bf19e5929",
            "taskArn": "arn:aws:ecs:us-east-1::task/AWSBatch-HLM2-c929f2e7-5cd9-3f96-8ad3-a2717fb4d2ec/5cb0c860da6a484ca6ba23a468a7f76c",
            "logStreamName": "HLM2/default/5cb0c860da6a484ca6ba23a468a7f76c",
            "networkInterfaces": [],
            "resourceRequirements": [
                {
                    "value": "2",
                    "type": "VCPU"
                },
                {
                    "value": "8192",
                    "type": "MEMORY"
                }
            ],
            "secrets": []
        },
        "arrayProperties": {
            "statusSummary": {},
            "index": 2
        },
        "timeout": {
            "attemptDurationSeconds": 1800
        },
        "tags": {
            "resourceArn": "arn:aws:batch:us-east-1::job/138677dc-d684-4e39-b42f-6626515be7c7"
        },
        "platformCapabilities": [
            "EC2"
        ],
        "eksAttempts": []
    }
}


问:
How to make register and login work correctly in spring security, problems with authentication
I'm trying to make authorization in my project. Registration works great and I get access and refresh tokens, but login throws an exception.

Problem is that in registration I create UsernamePasswordAuthenticationToken with UserEntity and password:

```<code>@PostMapping("/register")
public ResponseEntity register(@RequestBody UserSignUpModel userSignUpModel) {
    UserEntity user = customUserDetailsService.createUser(userSignUpModel);

    Authentication authentication = UsernamePasswordAuthenticationToken.authenticated(user, user.getPassword(), Collections.EMPTY_LIST);
    return ResponseEntity.ok(tokenGenerator.createToken(authentication));
}
</code>```

And in login I create UsernamePasswordAuthenticationToken with email and password so that the daoAuthenticationProvider can process it:

```<code>@PostMapping("/login")
public ResponseEntity login(@RequestBody UserSignInModel userSignInModel) {
    Authentication authentication = daoAuthenticationProvider.authenticate(UsernamePasswordAuthenticationToken.unauthenticated(userSignInModel.getEmail(), userSignInModel.getPassword()));
    return ResponseEntity.ok(tokenGenerator.createToken(authentication));
}
</code>```

So I receive different authentication objects and can't pass the instanceoff check in TokenGenerator:

```<code>public TokenModel createToken(Authentication authentication) {
    if (!(authentication.getPrincipal() instanceof UserEntity user)) {
            throw new BadCredentialsException(
                    MessageFormat.format("principal {0} is not of UserEntity or UserDetails type", authentication.getPrincipal().getClass())
            );
    }

    TokenModel tokenModel = new TokenModel();
    tokenModel.setUserId(user.getUser_id());
    tokenModel.setAccessToken(createAccessToken(authentication));

    String refreshToken;
    if (authentication.getCredentials() instanceof Jwt jwt) {
        Instant now = Instant.now();
        Instant expiresAt = jwt.getExpiresAt();
        Duration duration = Duration.between(now, expiresAt);
        long secondsUntilExpired = duration.toSeconds();
        if (secondsUntilExpired < 15) {
            refreshToken = createRefreshToken(authentication);
        } else {
            refreshToken = jwt.getTokenValue();
        }
    } else {
        refreshToken = createRefreshToken(authentication);
    }
    tokenModel.setRefreshToken(refreshToken);

    return tokenModel;
}
</code>```

Should I write custom authentication provider? If so, do I need to download an entity from the repository and check passwords in it?

Body:
I'm trying to make authorization in my project. Registration works great and I get access and refresh tokens, but login throws an exception.

Problem is that in registration I create UsernamePasswordAuthenticationToken with UserEntity and password:

@PostMapping("/register")
public ResponseEntity register(@RequestBody UserSignUpModel userSignUpModel) {
    UserEntity user = customUserDetailsService.createUser(userSignUpModel);

    Authentication authentication = UsernamePasswordAuthenticationToken.authenticated(user, user.getPassword(), Collections.EMPTY_LIST);
    return ResponseEntity.ok(tokenGenerator.createToken(authentication));
}

And in login I create UsernamePasswordAuthenticationToken with email and password so that the daoAuthenticationProvider can process it:

@PostMapping("/login")
public ResponseEntity login(@RequestBody UserSignInModel userSignInModel) {
    Authentication authentication = daoAuthenticationProvider.authenticate(UsernamePasswordAuthenticationToken.unauthenticated(userSignInModel.getEmail(), userSignInModel.getPassword()));
    return ResponseEntity.ok(tokenGenerator.createToken(authentication));
}

So I receive different authentication objects and can't pass the instanceoff check in TokenGenerator:

public TokenModel createToken(Authentication authentication) {
    if (!(authentication.getPrincipal() instanceof UserEntity user)) {
            throw new BadCredentialsException(
                    MessageFormat.format("principal {0} is not of UserEntity or UserDetails type", authentication.getPrincipal().getClass())
            );
    }

    TokenModel tokenModel = new TokenModel();
    tokenModel.setUserId(user.getUser_id());
    tokenModel.setAccessToken(createAccessToken(authentication));

    String refreshToken;
    if (authentication.getCredentials() instanceof Jwt jwt) {
        Instant now = Instant.now();
        Instant expiresAt = jwt.getExpiresAt();
        Duration duration = Duration.between(now, expiresAt);
        long secondsUntilExpired = duration.toSeconds();
        if (secondsUntilExpired < 15) {
            refreshToken = createRefreshToken(authentication);
        } else {
            refreshToken = jwt.getTokenValue();
        }
    } else {
        refreshToken = createRefreshToken(authentication);
    }
    tokenModel.setRefreshToken(refreshToken);

    return tokenModel;
}

Should I write custom authentication provider? If so, do I need to download an entity from the repository and check passwords in it?


问:
I am facing issue with nested table in Ant Design where I have a nested Array of Objects with length of array ranging anywhere between 0-15
OK so firstly I'll show my data structure

Its an Array of classes = [{ batchId: string, batchNumber: string, students:[{id: string, name: string, email: string, mobile: string}]}]

There can be multiple classes with multiple students some classes might have 0 students some might have 10.

Now when I'm trying to run the below code:

```<code>import React, { useState } from 'react';
import { Spin, Table, TableColumnsType } from 'antd';

export type ViewSchoolProps = {
    tempData: any;
};

interface DataType {
    key: React.Key;
    batchNumber: string;
    batchId: string;
}

interface ExpandedDataType {
    key: React.Key;
    name: string;
    id: string;
    email: string;
    mobile: string;
    status: string;
}

const ViewDrawer: React.FC<ViewSchoolProps> = (props) => {

    const classes = props.tempData?.classesData?.map((item: any) => {
        return {
            ...item,
        }
    })
    let students = props.tempData?.classesData?.map((item: any) => {
        return {
            ...item.students,
        }
    })
    const data: DataType[] = [];
    const expandedData: ExpandedDataType[] = [];
    for (let i = 0; i < classes?.length; ++i) {
        data.push({
            key: i.toString(),
            ...classes[i],
        });
        for (let j = 0; j < classes[i]?.students?.length; ++j) {
            expandedData.push({
                key: i.toString(),
                ...classes[i]?.students[j],
            })
        }
    }
    console.log('classes', data, 'students', expandedData)
    const columns: TableColumnsType<DataType> = [
        { title: 'Batch Code', dataIndex: 'batchNumber', key: 'batchNumber' },
        { title: 'Batch Id', dataIndex: 'batchId', key: 'batchId' },
    ];

    const expandedRowRender = (key: any) => {
        const expandedDolumns: TableColumnsType<ExpandedDataType> = [
            { title: 'Name', dataIndex: 'name', key: 'name' },
            { title: 'ID', dataIndex: 'id', key: 'id' },
            { title: 'Email', dataIndex: 'email', key: 'email' },
            { title: 'Mobile', dataIndex: 'mobile', key: 'mobile' },
            { title: 'Status', dataIndex: 'status', key: 'status' }
        ];

        return <Table columns={expandedDolumns} dataSource={expandedData} pagination={false} rowKey={key} />;
    };

    const [isLoading, setIsLoading] = useState<boolean>(false);

    return (
        <>
            <Spin spinning={isLoading} >
                <Table
                    columns={columns}
                    expandable={{
                        expandedRowRender: (record) => {
                            return expandedRowRender(record.key)
                        },
                    }}
                    dataSource={data}
                    size='middle'
                />
            </Spin>
        </>
    );
};

export default ViewDrawer;
</code>```

In the expandedTable aka Nested table I see data somewhat like this

The issue here is that Im getting all the students from all the classes instead of students showing up only in their particular classes's nested table dropdown. I saw a lot of examples where they resolve this on fixed number of dataSources in nestedTable but my dataSources as said earlier are not defined/fixed they vary depending on each schools class, and then the students in each class. If anyone has found a solution to this please do let me know of how I can get data of only those students on whose batch I click instead of seeing a whole list of students from school and not batchWise, According to my understanding I will have to pass single-dimensional array to dataSource prop for every class but not sure how I should go about it, any help s appreciated, Thank you

Body:
OK so firstly I'll show my data structure

Its an Array of classes = [{ batchId: string, batchNumber: string, students:[{id: string, name: string, email: string, mobile: string}]}]

There can be multiple classes with multiple students some classes might have 0 students some might have 10.

Now when I'm trying to run the below code:

import React, { useState } from 'react';
import { Spin, Table, TableColumnsType } from 'antd';

export type ViewSchoolProps = {
    tempData: any;
};

interface DataType {
    key: React.Key;
    batchNumber: string;
    batchId: string;
}

interface ExpandedDataType {
    key: React.Key;
    name: string;
    id: string;
    email: string;
    mobile: string;
    status: string;
}

const ViewDrawer: React.FC<ViewSchoolProps> = (props) => {

    const classes = props.tempData?.classesData?.map((item: any) => {
        return {
            ...item,
        }
    })
    let students = props.tempData?.classesData?.map((item: any) => {
        return {
            ...item.students,
        }
    })
    const data: DataType[] = [];
    const expandedData: ExpandedDataType[] = [];
    for (let i = 0; i < classes?.length; ++i) {
        data.push({
            key: i.toString(),
            ...classes[i],
        });
        for (let j = 0; j < classes[i]?.students?.length; ++j) {
            expandedData.push({
                key: i.toString(),
                ...classes[i]?.students[j],
            })
        }
    }
    console.log('classes', data, 'students', expandedData)
    const columns: TableColumnsType<DataType> = [
        { title: 'Batch Code', dataIndex: 'batchNumber', key: 'batchNumber' },
        { title: 'Batch Id', dataIndex: 'batchId', key: 'batchId' },
    ];

    const expandedRowRender = (key: any) => {
        const expandedDolumns: TableColumnsType<ExpandedDataType> = [
            { title: 'Name', dataIndex: 'name', key: 'name' },
            { title: 'ID', dataIndex: 'id', key: 'id' },
            { title: 'Email', dataIndex: 'email', key: 'email' },
            { title: 'Mobile', dataIndex: 'mobile', key: 'mobile' },
            { title: 'Status', dataIndex: 'status', key: 'status' }
        ];

        return
;
    };

    const [isLoading, setIsLoading] = useState<boolean>(false);

    return (
        <>
            <Spin spinning={isLoading} >

 {
                            return expandedRowRender(record.key)
                        },
                    }}
                    dataSource={data}
                    size='middle'
                />
            </Spin>
        </>
    );
};

export default ViewDrawer;

In the expandedTable aka Nested table I see data somewhat like this

The issue here is that Im getting all the students from all the classes instead of students showing up only in their particular classes's nested table dropdown. I saw a lot of examples where they resolve this on fixed number of dataSources in nestedTable but my dataSources as said earlier are not defined/fixed they vary depending on each schools class, and then the students in each class. If anyone has found a solution to this please do let me know of how I can get data of only those students on whose batch I click instead of seeing a whole list of students from school and not batchWise, According to my understanding I will have to pass single-dimensional array to dataSource prop for every class but not sure how I should go about it, any help s appreciated, Thank you


问:
Move a circular widget horizontally while changing the size Flutter
I just started flutter development and wanted to create an animation where it looks like a a circle is rotating in 3 dimension and when in center its full size but when going left or right the radius of the circle decreases.

What i have achieved so far is that i am able to move my widget horizontally till the edge of screen by using AnimatedWidget and also achieve resizing of widget by using ScaleTransition and AnimationController but i am facing some issue with resizing with calculations and time. Below is the code for what i have done so far.

Would really help if someone could help me figure this out

```<code>class MyStatefulWidget extends StatefulWidget {
  const MyStatefulWidget({super.key});

  @override
  State<MyStatefulWidget> createState() => _MyStatefulWidgetState();
}

class _MyStatefulWidgetState extends State<MyStatefulWidget>
    with TickerProviderStateMixin {

  Timer? timer;

  late AnimationController _controller;
  late Animation<double> _animation;

  double fromLeft = 0, fromTop = 0;
  double toLeft = 0, toTop = 0;
  bool initCalled = false;
  double childHeight = 0;
  bool moveFromToEnd = true;

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    if (!initCalled) {
      var screenWidth = MediaQuery.of(context).size.width;
      var screenHeight = MediaQuery.of(context).size.height;
      childHeight = MediaQuery.of(context).size.width/4;
      var halfChildWidth = (childHeight);
      fromLeft = (screenWidth - halfChildWidth) / 2;
      fromTop = (screenHeight - childHeight) / 2;
      toLeft = (screenWidth - halfChildWidth) / 2;
      toTop = (screenHeight - childHeight) / 2;

      int time = 3000;
      print('Screen width: $screenWidth');
      print('Child width: $childHeight');
      double distance = screenWidth - (fromLeft + halfChildWidth);
      double speed = (distance * time);
      double test = (distance/time)*2;
      print('time: $time distance: $distance speed: $speed test: $test');
      _controller = AnimationController(
          duration: Duration(milliseconds: time),
          vsync: this,
          lowerBound: 0.25,
          value: 2,
          upperBound: 1)
        ..repeat(reverse: true);
      _animation = CurvedAnimation(
        parent: _controller,
        curve: Curves.linear,
      );
      timer = Timer.periodic(Duration(milliseconds: 1), (Timer t) {
        setState(() {
          if (moveFromToEnd) {
            fromLeft = fromLeft + test;
            toLeft = toLeft - test;
            if (fromLeft >= screenWidth - childHeight) {
              moveFromToEnd = false;
            }
          }
          if (!moveFromToEnd) {
            fromLeft = fromLeft - test;
            toLeft = toLeft + test;
            if (fromLeft <= 0) {
              moveFromToEnd = true;
            }
          }
        });
      });
      initCalled = true;
    }
  }

  @override
  void dispose() {
    _controller.dispose();
    timer?.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Stack(
          children: [
            AnimatedPositioned(
              left: fromLeft,
              top: fromTop,
              duration: const Duration(milliseconds: 1),
              child: SizedBox(
                height: childHeight,
                width: childHeight,
                child: ScaleTransition(
                  scale: _animation,
                  child: Image.network(
                    btcUrl,
                    fit: BoxFit.fitWidth,
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
</code>```

Body:
I just started flutter development and wanted to create an animation where it looks like a a circle is rotating in 3 dimension and when in center its full size but when going left or right the radius of the circle decreases.

What i have achieved so far is that i am able to move my widget horizontally till the edge of screen by using AnimatedWidget and also achieve resizing of widget by using ScaleTransition and AnimationController but i am facing some issue with resizing with calculations and time. Below is the code for what i have done so far.

Would really help if someone could help me figure this out

class MyStatefulWidget extends StatefulWidget {
  const MyStatefulWidget({super.key});

  @override
  State<MyStatefulWidget> createState() => _MyStatefulWidgetState();
}

class _MyStatefulWidgetState extends State<MyStatefulWidget>
    with TickerProviderStateMixin {

  Timer? timer;

  late AnimationController _controller;
  late Animation<double> _animation;

  double fromLeft = 0, fromTop = 0;
  double toLeft = 0, toTop = 0;
  bool initCalled = false;
  double childHeight = 0;
  bool moveFromToEnd = true;

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    if (!initCalled) {
      var screenWidth = MediaQuery.of(context).size.width;
      var screenHeight = MediaQuery.of(context).size.height;
      childHeight = MediaQuery.of(context).size.width/4;
      var halfChildWidth = (childHeight);
      fromLeft = (screenWidth - halfChildWidth) / 2;
      fromTop = (screenHeight - childHeight) / 2;
      toLeft = (screenWidth - halfChildWidth) / 2;
      toTop = (screenHeight - childHeight) / 2;

      int time = 3000;
      print('Screen width: $screenWidth');
      print('Child width: $childHeight');
      double distance = screenWidth - (fromLeft + halfChildWidth);
      double speed = (distance * time);
      double test = (distance/time)*2;
      print('time: $time distance: $distance speed: $speed test: $test');
      _controller = AnimationController(
          duration: Duration(milliseconds: time),
          vsync: this,
          lowerBound: 0.25,
          value: 2,
          upperBound: 1)
        ..repeat(reverse: true);
      _animation = CurvedAnimation(
        parent: _controller,
        curve: Curves.linear,
      );
      timer = Timer.periodic(Duration(milliseconds: 1), (Timer t) {
        setState(() {
          if (moveFromToEnd) {
            fromLeft = fromLeft + test;
            toLeft = toLeft - test;
            if (fromLeft >= screenWidth - childHeight) {
              moveFromToEnd = false;
            }
          }
          if (!moveFromToEnd) {
            fromLeft = fromLeft - test;
            toLeft = toLeft + test;
            if (fromLeft <= 0) {
              moveFromToEnd = true;
            }
          }
        });
      });
      initCalled = true;
    }
  }

  @override
  void dispose() {
    _controller.dispose();
    timer?.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Stack(
          children: [
            AnimatedPositioned(
              left: fromLeft,
              top: fromTop,
              duration: const Duration(milliseconds: 1),
              child: SizedBox(
                height: childHeight,
                width: childHeight,
                child: ScaleTransition(
                  scale: _animation,
                  child: Image.network(
                    btcUrl,
                    fit: BoxFit.fitWidth,
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}


问:
JavaScript API doesn't give error but also doesn't return data?
file 1:

```<code>    var setupController = require('./controllers/setupController');
    app.route('/api/pace')
      .get(gameController.getPace);
</code>```

file 2:

```<code>    var paceData = require("../models/pace");
    var thePace = paceData.getPaceData();

    exports.getPace = function(req, res) {
      res.setHeader('Content-Type', 'application/json');
      res.send(thePace);
    }
</code>```

file 3:

```<code>    var pace = {
      id: 0,
      paceName: \["steady", "strenuous", "grueling", "resting"\],
      milesPerDay: \[10, 30, 50, 0\],
      healthChange: \[-1, -3, -8, 0\]
    }

    exports.getPaceData = function(){
      return pace;
    }
</code>```

I'm trying to call the data so I can use it in a different file using API. It doesn't seem to get the correct data and idk why. I'm using this site to test the api: https://reqbin.com/ whenever I put it in it says it works but doesn't show data.

Body:
file 1:

    var setupController = require('./controllers/setupController');
    app.route('/api/pace')
      .get(gameController.getPace);

file 2:

    var paceData = require("../models/pace");
    var thePace = paceData.getPaceData();

    exports.getPace = function(req, res) {
      res.setHeader('Content-Type', 'application/json');
      res.send(thePace);
    }

file 3:

    var pace = {
      id: 0,
      paceName: \["steady", "strenuous", "grueling", "resting"\],
      milesPerDay: \[10, 30, 50, 0\],
      healthChange: \[-1, -3, -8, 0\]
    }

    exports.getPaceData = function(){
      return pace;
    }

I'm trying to call the data so I can use it in a different file using API. It doesn't seem to get the correct data and idk why. I'm using this site to test the api: https://reqbin.com/ whenever I put it in it says it works but doesn't show data.


问:
Infinite loop when I updated query to add an additional variable
I have this query:

```<code>    with users_having_connected as (
    select u.id as user_id,
           (a.connected_at is not null) has_connected
    from core_user u
    join core_profile p on u.id = p.user_id
    join core_conversation c on (c.profile1_id = p.id or c.profile2_id = p.id)
    join analytics_connection a on c.id = a.conversation_id
    group by u.id, (a.connected_at is not null)
)
select u.id as user_id,
       date_trunc('month', u.created at time zone 'UTC')::date as month,
       p.community_id,
       p.organization_id,
       p.profile_type_intention,
       (p.basic_account_completed and (p.is_mentor or p.is_entrepreneur)) as profile_is_completed,
       exists(select 1 from core_message where core_message.sender_id = p.id) as has_sent_a_message,
       (EXISTS (SELECT 1 FROM core_message WHERE core_message.receiver_id = p.id)) AS has_received_a_message,
       (EXISTS (SELECT 1 FROM core_admin_conversation_w_resp WHERE core_admin_conversation_w_resp.initiator_id = p.id or core_admin_conversation_w_resp.responder_id = p.id)) AS has_one_by_one,
       exists(select 1 from users_having_connected where user_id = u.id) as has_two_by_two
from core_user as u
join core_profile p on u.id = p.user_id
where
p.profile_type_intention is not null
</code>```

Which worked fine until I added this line:

```<code>(EXISTS (SELECT 1 FROM core_admin_conversation_w_resp WHERE core_admin_conversation_w_resp.initiator_id = p.id or core_admin_conversation_w_resp.responder_id = p.id)) AS has_one_by_one,
</code>```

This specific variable add causes this query to infinite loop. What do I need to do to fix it? Am I missing a set of parentheses somewhere?

Body:
I have this query:

    with users_having_connected as (
    select u.id as user_id,
           (a.connected_at is not null) has_connected
    from core_user u
    join core_profile p on u.id = p.user_id
    join core_conversation c on (c.profile1_id = p.id or c.profile2_id = p.id)
    join analytics_connection a on c.id = a.conversation_id
    group by u.id, (a.connected_at is not null)
)
select u.id as user_id,
       date_trunc('month', u.created at time zone 'UTC')::date as month,
       p.community_id,
       p.organization_id,
       p.profile_type_intention,
       (p.basic_account_completed and (p.is_mentor or p.is_entrepreneur)) as profile_is_completed,
       exists(select 1 from core_message where core_message.sender_id = p.id) as has_sent_a_message,
       (EXISTS (SELECT 1 FROM core_message WHERE core_message.receiver_id = p.id)) AS has_received_a_message,
       (EXISTS (SELECT 1 FROM core_admin_conversation_w_resp WHERE core_admin_conversation_w_resp.initiator_id = p.id or core_admin_conversation_w_resp.responder_id = p.id)) AS has_one_by_one,
       exists(select 1 from users_having_connected where user_id = u.id) as has_two_by_two
from core_user as u
join core_profile p on u.id = p.user_id
where
p.profile_type_intention is not null

Which worked fine until I added this line:

(EXISTS (SELECT 1 FROM core_admin_conversation_w_resp WHERE core_admin_conversation_w_resp.initiator_id = p.id or core_admin_conversation_w_resp.responder_id = p.id)) AS has_one_by_one,

This specific variable add causes this query to infinite loop. What do I need to do to fix it? Am I missing a set of parentheses somewhere?


问:
Python import ignores __init__.py
I name my modules same as class names. So MyClass.py would contain class MyClass.
(Why? I adopted this naming convention from other languages and would rather not change it)
I put it in directory components with __init__.py like this:

```<code>from .MyClass1 import MyClass1
from .MyClass2 import MyClass2
</code>```

I do exactly the same thing for classes in directory controllers.

Then, in my main.py, I try to import them like so:

```<code>from components import MyClass1, MyClass2
from controllers import MyClass3, MyClass4
</code>```

From components it imports fine, from controllers, it ignores my __init__.py and imports a module instead of class, so I have to rewrite my imports like so:

```<code>from components import MyClass1, MyClass2
from controllers.MyClass3 import MyClass3
from controllers.MyClass4 import MyClass4
</code>```

Please tell me what could be the reason? Is there a way to fix this without having to change naming convention? Thank you.

Title: Python import ignores __init__.py

Body:
I name my modules same as class names. So MyClass.py would contain class MyClass.
(Why? I adopted this naming convention from other languages and would rather not change it)
I put it in directory components with __init__.py like this:

from .MyClass1 import MyClass1
from .MyClass2 import MyClass2

I do exactly the same thing for classes in directory controllers.

Then, in my main.py, I try to import them like so:

from components import MyClass1, MyClass2
from controllers import MyClass3, MyClass4

From components it imports fine, from controllers, it ignores my __init__.py and imports a module instead of class, so I have to rewrite my imports like so:

from components import MyClass1, MyClass2
from controllers.MyClass3 import MyClass3
from controllers.MyClass4 import MyClass4

Please tell me what could be the reason? Is there a way to fix this without having to change naming convention? Thank you.


问:
crosstool config fail: panel library not found
When trying to configure crosstool-ng I run into error: panel library not found

```<code>...
...
checking for working ncursesw.h... no
checking for working ncurses.h... yes
checking for Curses Panel library with ncursesw/panel.h... no
configure: error: panel library not found
make: *** No targets specified and no makefile found.  Stop.
make: *** No rule to make target `install'.  Stop.
</code>```

How do I get my hands on the 'Curses Panel Library'?

Body:
When trying to configure crosstool-ng I run into error: panel library not found

...
...
checking for working ncursesw.h... no
checking for working ncurses.h... yes
checking for Curses Panel library with ncursesw/panel.h... no
configure: error: panel library not found
make: *** No targets specified and no makefile found.  Stop.
make: *** No rule to make target `install'.  Stop.

How do I get my hands on the 'Curses Panel Library'?


问:
Want to open URL in Chrome from Excel Macro (VBA) along with that i need to send the postdata
Currently i am using Internet explorer to open a internal url with post data.

With that post data and url . We are processing post data and do the data update task in background

We have IE object in Macro code.we simply using those inbulit function.

Now we have requirement to do with chrome? Yes we can open a url in chrome from Macro code. But how can i pass the postdata

Excpecting to pass the postdata in URL call


问:
Sum the equivalent cells across mulltiple workbooks while looping through cells then sheets in master
I have a template file, whereby multiple copies of the template (5 to 20) are completed, then consolidated into one master file. This file contains multiple sheets (18) and hundreds of entries in each sheet.

Not every cell is a number requiring consolidation, i.e there are titles and dates etc which are repeated, with no clear structure. Re-organising the template is not an option. The best way is to calculate only cells with a "Currency" type.

Here is the code I have so far. I have pieced it together from a number of searches, but will admit that I don't fully understand vba so I know I'm missing something obvious.

To make this a bit simpler, I have closed everything else and opened the target files manually before running this, then called upon the open excel files. Improving this bit of the code so that I can just put the target files into a sub folder and then use that path would be nice but not necessary.

I do not need to change the cell colour at the end, but I just did that as a quick visual reference to see whether it had ran.

The script in this format does not throw up any errors, but simply runs without actually calculating and populating the total value into each cell. I would guess that my approach of trying to extract the sheet and cell reference for every loop is wrong, but I cannot find the answer anywhere, so any help would be greatly appreciated.

```<code>totalValue = totalValue + Worksheets(sht).Cells(R, C)
</code>```

is completely the wrong syntax, and the crux of the issue, but I simply don't know how to fix this within the context of the two existing For Each loops.

```<code>Sub ConsolidatedFigures()

     Application.ScreenUpdating = False

      'Declare variable types
        Dim ws As Worksheet
        Dim totalValue As Double
        Dim C As Integer
        Dim R As Integer
        Dim wb As Workbook
        Dim sht As String
        Dim myRange As Range
        Dim cell As Range

            'Start to loop through each sheet in the workbook
            For Each ws In ThisWorkbook.Worksheets

                'get the current sheet name to later search for the same sheet in other workbooks
                sht = ws.Name
                'set the range in the current sheet
                Set myRange = ws.UsedRange

                    'Now loop though every cell in the range
                    For Each cell In myRange
                        'Only target cells with an "currency" style so we're not trying to sum text
                        If cell.Style = "Currency" Then

                            'get the current cell references to later search for the same cell in other workbooks
                            C = cell.Column
                            R = cell.Row

                            'Within the current cell, go through open workbooks (except this one) to create a total of all the corresponding cells
                               For Each wb In Application.Workbooks
                                    'the target workbooks will be open already, and nothing else. Disregard this open workbook and personal book
                                    If wb.Name <> "PERSONAL.xlsb" AND wb.Name <> "consolidation.xlsm" Then
                                    totalValue = totalValue + Worksheets(sht).Cells(R, C)

                                    End If

                                Next wb
                                    'populate the cell with the total of the corresponding cells
                                    cell.Value = totalValue
                                    'change cell colour to show the above step worked
                                    cell.Interior.ColorIndex = 5

                        End If
                    'move on to next cell in worksheet
                    Next cell

                'move on to next sheet in the workbook
                Next ws
 Application.ScreenUpdating = True
      End Sub
</code>```

Body:
I have a template file, whereby multiple copies of the template (5 to 20) are completed, then consolidated into one master file. This file contains multiple sheets (18) and hundreds of entries in each sheet.

Not every cell is a number requiring consolidation, i.e there are titles and dates etc which are repeated, with no clear structure. Re-organising the template is not an option. The best way is to calculate only cells with a "Currency" type.

Here is the code I have so far. I have pieced it together from a number of searches, but will admit that I don't fully understand vba so I know I'm missing something obvious.

To make this a bit simpler, I have closed everything else and opened the target files manually before running this, then called upon the open excel files. Improving this bit of the code so that I can just put the target files into a sub folder and then use that path would be nice but not necessary.

I do not need to change the cell colour at the end, but I just did that as a quick visual reference to see whether it had ran.

The script in this format does not throw up any errors, but simply runs without actually calculating and populating the total value into each cell. I would guess that my approach of trying to extract the sheet and cell reference for every loop is wrong, but I cannot find the answer anywhere, so any help would be greatly appreciated.

totalValue = totalValue + Worksheets(sht).Cells(R, C)

is completely the wrong syntax, and the crux of the issue, but I simply don't know how to fix this within the context of the two existing For Each loops.

Sub ConsolidatedFigures()

     Application.ScreenUpdating = False

      'Declare variable types
        Dim ws As Worksheet
        Dim totalValue As Double
        Dim C As Integer
        Dim R As Integer
        Dim wb As Workbook
        Dim sht As String
        Dim myRange As Range
        Dim cell As Range

            'Start to loop through each sheet in the workbook
            For Each ws In ThisWorkbook.Worksheets

                'get the current sheet name to later search for the same sheet in other workbooks
                sht = ws.Name
                'set the range in the current sheet
                Set myRange = ws.UsedRange

                    'Now loop though every cell in the range
                    For Each cell In myRange
                        'Only target cells with an "currency" style so we're not trying to sum text
                        If cell.Style = "Currency" Then

                            'get the current cell references to later search for the same cell in other workbooks
                            C = cell.Column
                            R = cell.Row

                            'Within the current cell, go through open workbooks (except this one) to create a total of all the corresponding cells
                               For Each wb In Application.Workbooks
                                    'the target workbooks will be open already, and nothing else. Disregard this open workbook and personal book
                                    If wb.Name <> "PERSONAL.xlsb" AND wb.Name <> "consolidation.xlsm" Then
                                    totalValue = totalValue + Worksheets(sht).Cells(R, C)

                                    End If

                                Next wb
                                    'populate the cell with the total of the corresponding cells
                                    cell.Value = totalValue
                                    'change cell colour to show the above step worked
                                    cell.Interior.ColorIndex = 5

                        End If
                    'move on to next cell in worksheet
                    Next cell

                'move on to next sheet in the workbook
                Next ws
 Application.ScreenUpdating = True
      End Sub


问:
How can I integrate my dynamics CRM dashboard into my asp.net web application?
I created 3 entities in microsoft dynamics 365 and I have a .net core application that connects to microsoft dynamics 365 and manages the 3 entities, I would like to display the dashboard generated by dynamics in my web application

i would like to kknow how can i do this if it's possible


问:
Converting float64 column to int column
Notice that ProviderID, Vender and PCP in df_claims are float strings (Ex. 12231.0), which isn't accurate representation. These columns are ID's for respective entities, and ideally should be int (Ex. 12231). Convert these columns to int, handling the missing values separately.

This is my question in the assignment.

display(df_claim)

So, I use astype to convert datatype.

```<code>df_claim['ProviderID'] = df_claim['ProviderID'].fillna(0)

df_claim['ProviderID'] = df_claim['ProviderID'].astype('int64')

df_claim['ProviderID'] = df_claim['ProviderID'].replace(0, np.nan)
</code>```

after add the codes

Nothing is changed.

I tried astype(int), astype('int), astype(np.int), astype('int64').
But noting of those work.

I want convert whole values in column 'ProviderID' to integer without any decimal.

Title: Converting float64 column to int column

Body:
Notice that ProviderID, Vender and PCP in df_claims are float strings (Ex. 12231.0), which isn't accurate representation. These columns are ID's for respective entities, and ideally should be int (Ex. 12231). Convert these columns to int, handling the missing values separately.

This is my question in the assignment.

display(df_claim)

So, I use astype to convert datatype.

df_claim['ProviderID'] = df_claim['ProviderID'].fillna(0)

df_claim['ProviderID'] = df_claim['ProviderID'].astype('int64')

df_claim['ProviderID'] = df_claim['ProviderID'].replace(0, np.nan)

after add the codes

Nothing is changed.

I tried astype(int), astype('int), astype(np.int), astype('int64').
But noting of those work.

I want convert whole values in column 'ProviderID' to integer without any decimal.


问:
How to run gcloud if Google Cloud SDK if my project is on another drive?
I'm building an API with Google Cloud functions and I had the same issue as the guy from this post: Could not load the default credentials? (Node.js Google Compute Engine tutorial)

When trying to use my API, I received this error:

Could not load the default credentials. Browse to https://developers.google.com/accounts/docs/application-default-credentials for more information.

So I went on and followed the steps suggested in the question I mentioned. I downloaded the gcloud SDK, installed it, and at the end of the installation wizard there is an option to run the google cloud cli immediately.

I ran it successfully and logged in properly, now any time I open the command prompt I can use the gcloud command without a problem.

Mi issue is the following. I'm running my commands in VSCode bash terminal and I get an error saying that the gcloud command is not found.

My project is in my D: drive, and the SDK is on C:, which I believe is the reason why the gcloud command is not recognized when I attempt to use it.

Should/can I install the Google Cloud SDK in my D: drive and use it there, or should I move my project to the C: drive?

I read somewhere that this might be a problem with the bash terminal, but I tried running it from command prompt in VSCode and I get the same error, so I guess it's got nothing to do with it.

Thank you for your time.


问:
How to Debug python package command line arguments
I have a python package installed on my machine. I could interface with it via the command line. How could I enter my debugger to see the "Call Stack" of the currently running processes that were executed by me from the terminal. Example, running "packagex command --argument" executes a process, I want to see what is happening with this call.

I'm not certain of what to try because the following searches didn't reveal what I am trying to do.

debug a command called from a terminal vscode

debugging an entire package vscode

debug client process vscode
...

It may be that I'm not searching for the correct thing which is why I'm not finding an answer.


问:
Converting longitude and latitude to eastings and northings using pyProj
I'm trying to convert latitude and longitude coordinates into eastings and northings.

I've found (on here!) a neat way of converting eastings and northings to longitude and latitude, but I don't fully understand the projections. I'd really appreciate it if someone could explain to me how to use this same approach to convert the other way round.

```<code>from pyproj import Proj, transform
import pandas as pd

v84 = Proj(proj="latlong",towgs84="0,0,0",ellps="WGS84")
v36 = Proj(proj="latlong", k=0.9996012717, ellps="airy",
        towgs84="446.448,-125.157,542.060,0.1502,0.2470,0.8421,-20.4894")
vgrid = Proj(init="world:bng")

def EN2LL(eastings, northings):
    vlon36, vlat36 = vgrid(eastings,
                           northings,
                           inverse=True)
    converted = transform(v36, v84, vlon36, vlat36)
    lon = converted[0]
    lat = converted[1]
    return lon, lat

def LL2EN(longitude, latitude):
</code>```

The def LL2EN is what I want to fill in :)
Thank you

Body:
I'm trying to convert latitude and longitude coordinates into eastings and northings.

I've found (on here!) a neat way of converting eastings and northings to longitude and latitude, but I don't fully understand the projections. I'd really appreciate it if someone could explain to me how to use this same approach to convert the other way round.

from pyproj import Proj, transform
import pandas as pd

v84 = Proj(proj="latlong",towgs84="0,0,0",ellps="WGS84")
v36 = Proj(proj="latlong", k=0.9996012717, ellps="airy",
        towgs84="446.448,-125.157,542.060,0.1502,0.2470,0.8421,-20.4894")
vgrid = Proj(init="world:bng")

def EN2LL(eastings, northings):
    vlon36, vlat36 = vgrid(eastings,
                           northings,
                           inverse=True)
    converted = transform(v36, v84, vlon36, vlat36)
    lon = converted[0]
    lat = converted[1]
    return lon, lat

def LL2EN(longitude, latitude):

The def LL2EN is what I want to fill in :)
Thank you


问:
Is there a way where I can parse the response body (token) as a string and temporarily store it and call upon that value when needed?
I want to be able to store a bearer token from the response body temporarily for about 900 seconds and be able to use the token whenever another function calls upon it. I have created the basic structure of creating the client and posting the request and getting a token back. Here is what I have so far:

#[derive(Debug, Deserialize)]
struct SecureToken {
    access_token: String,
    expiration_date_time: i32,
}

#[tokio::main]
async fn get_new_secure_token() {
    let mut map = HashMap::new();
        map.insert("client_id", "client_id");
        map.insert("client_secret", "client_secret");
        map.insert("scope", "scope");
        map.insert("grant_type", "client_credentials");

    let client = Client::new();

    let token_request = client
        .post("https://gatway.address")
        .form(&map)
        .send()
        .await
        .expect("");
        //.json::<TokenResponse>()
        //.await;

    match token_request.status() {
            StatusCode::OK => {
                let query_result = token_request.json::<SecureToken>().await;
                println!("{:#?}", query_result);
            },
            StatusCode::FORBIDDEN => {
                println!("Unable to connect to auth service");
            },
            StatusCode::BAD_REQUEST => {
                let bad_request = token_request.json::<BadRequest>().await;
                println!("Error: {:?}", bad_request);
            }
            s => println!("STATUS CODE: {:?}", s),
        };
}
```
<p>Instead of printing the response, I want it to store the token temporarily for about 900 seconds along the lines of this:</p>
<pre class="lang-rust prettyprint-override"><code>let token_request = client
        .post("https://gatway.address")
        .form(&map)
        .send()
        .await
        .expect("");
        //.json::<TokenResponse>()
        //.await;

    match token_request.status() {
            StatusCode::OK => {
                let query_result = token_request.json::<SecureToken>().await;
                let token = quer
            },
            StatusCode::FORBIDDEN => {
                println!("Unable to connect to auth service");
            },
            StatusCode::BAD_REQUEST => {
                let bad_request = token_request.json::<BadRequest>().await;
                println!("Error: {:?}", bad_request);
            }
            s => println!("STATUS CODE: {:?}", s),
        };
}
</code>```

But I don't know how to store the token nor add a expiration time to the token.

Body:
I want to be able to store a bearer token from the response body temporarily for about 900 seconds and be able to use the token whenever another function calls upon it. I have created the basic structure of creating the client and posting the request and getting a token back. Here is what I have so far:

#[derive(Debug, Deserialize)]
struct SecureToken {
    access_token: String,
    expiration_date_time: i32,
}

#[tokio::main]
async fn get_new_secure_token() {
    let mut map = HashMap::new();
        map.insert("client_id", "client_id");
        map.insert("client_secret", "client_secret");
        map.insert("scope", "scope");
        map.insert("grant_type", "client_credentials");

    let client = Client::new();

    let token_request = client
        .post("https://gatway.address")
        .form(&map)
        .send()
        .await
        .expect("");
        //.json::<TokenResponse>()
        //.await;

    match token_request.status() {
            StatusCode::OK => {
                let query_result = token_request.json::<SecureToken>().await;
                println!("{:#?}", query_result);
            },
            StatusCode::FORBIDDEN => {
                println!("Unable to connect to auth service");
            },
            StatusCode::BAD_REQUEST => {
                let bad_request = token_request.json::<BadRequest>().await;
                println!("Error: {:?}", bad_request);
            }
            s => println!("STATUS CODE: {:?}", s),
        };
}

Instead of printing the response, I want it to store the token temporarily for about 900 seconds along the lines of this:

let token_request = client
        .post("https://gatway.address")
        .form(&map)
        .send()
        .await
        .expect("");
        //.json::<TokenResponse>()
        //.await;

    match token_request.status() {
            StatusCode::OK => {
                let query_result = token_request.json::<SecureToken>().await;
                let token = quer
            },
            StatusCode::FORBIDDEN => {
                println!("Unable to connect to auth service");
            },
            StatusCode::BAD_REQUEST => {
                let bad_request = token_request.json::<BadRequest>().await;
                println!("Error: {:?}", bad_request);
            }
            s => println!("STATUS CODE: {:?}", s),
        };
}

But I don't know how to store the token nor add a expiration time to the token.


问:
How to modify the modification to an array
I am trying to modify the arrayEndValue to where the modified array items that is returned will be added by 10. I have tried everything within my knowledge, and I keep getting different error codes. The most common one is IndexError: list index out of range. I would like some help understanding where I am going wrong. The last for loop is mine.</p>
```<code>array = []
inputTotal = int(input("Number of items for the array (must be at least 5): "))
if inputTotal >= 5:
    for arrayItem in range(inputTotal):
        arrayInputs = int(input(f"Input  {arrayItem + 1}: "))
        array.append(arrayInputs)

    for arrayItem in range(len(array)):
        array[arrayItem] = array[arrayItem] * 5
    print("\nModified array items: ", end="")

    for arrayEndValue in array:
        print(arrayEndValue, end='')

# modification to the modified array
    array2 = [arrayEndValue]
    for modiedArray in array2:
        array2[modiedArray] = array2[arrayEndValue] + 10
    print(modiedArray, end='')

else:
    print("Number must be at least 5")

</code>```

Body:
I am trying to modify the arrayEndValue to where the modified array items that is returned will be added by 10. I have tried everything within my knowledge, and I keep getting different error codes. The most common one is IndexError: list index out of range. I would like some help understanding where I am going wrong. The last for loop is mine.

array = []
inputTotal = int(input("Number of items for the array (must be at least 5): "))
if inputTotal >= 5:
    for arrayItem in range(inputTotal):
        arrayInputs = int(input(f"Input  {arrayItem + 1}: "))
        array.append(arrayInputs)

    for arrayItem in range(len(array)):
        array[arrayItem] = array[arrayItem] * 5
    print("\nModified array items: ", end="")

    for arrayEndValue in array:
        print(arrayEndValue, end='')

# modification to the modified array
    array2 = [arrayEndValue]
    for modiedArray in array2:
        array2[modiedArray] = array2[arrayEndValue] + 10
    print(modiedArray, end='')

else:
    print("Number must be at least 5")


问:
EF Core LINQ query could not be translated
I am learning full-stack web development, and writing test project "Knowledge testing system". Entities in this particular case are: AppUsers, Examinations (describes when, who and what test took), Answers (describes tests answers) and UserAnswers (describes which answers user chose). I need to make quite complicated query with EF. The goal is, for each user, find number of tests user took, minimum, maximum and average amount of points he got. This is targeted SQL that I want to get from  EF:

```<code>with
agg as (
    select
        s.UserId,
        count(*) cnt,
        min(s.sump) minPoints,
        max(s.sump) maxPoints,
        avg(s.sump) avgPoints
    from (
        select
            e.UserId,
            sum(a.Points) sump
        from Examinations e
        join UserAnswers ua on ua.ExamId = e.id
        join Answers a on a.Id = ua.AnswerId
        group by e.UserId, e.Id
    ) s
    group by s.UserId
)
select
    u.UserId,
    u.Name,
    u.Surname,
    u.Patronimic,
    agg.cnt,
    agg.minPoints,
    agg.maxPoints,
    agg.avgPoints
from AppUsers u
join agg on u.UserId = agg.UserId
</code>```

This is LINQ I was able to write:

```<code>_db.AppUsers
.GroupJoin(
    _db.Examinations
    .Include(x => x.UserAnswers)
    .Where(x => x.FinishDateTime != null && x.ExamPassed != null),
    user => user.UserId,
    exam => exam.UserId,
    (user, exam) => new
    {
        user.UserId,
        user.Name,
        user.Surname,
        user.Patronimic,
        aggregates = exam
            .Select(g => new
            {
                g.UserId,
                UserPoints = g.UserAnswers
                    .Join(
                        _db.Answers,
                        uAnswer => uAnswer.AnswerId,
                        answer => answer.Id,
                        (uAnswer, answer) => new { answer.Points }
                    ).Sum(x => x.Points)
            })
            .GroupBy(g => g.UserId)
            .Select(x => new
            {
                min = x.Min(a => a.UserPoints),
                max = x.Max(a => a.UserPoints),
                avg = x.Average(a => a.UserPoints),
                cnt = x.Count()
            })
            .FirstOrDefault()
    }
)
.Select(a => new UserExamsTotalModel
{
    UserId = a.UserId,
    UserName = a.Name,
    UserSurname = a.Surname,
    UserPatronimic = a.Patronimic,
    UserTookeTestsTotal = a.aggregates != null ? a.aggregates.cnt : 0,
    MinPointsInTest = a.aggregates != null ? a.aggregates.min : 0,
    MaxPointsInTest = a.aggregates != null ? a.aggregates.max : 0,
    AvgPointsInTest = a.aggregates != null ? a.aggregates.avg : 0
})
.ToListAsync();
</code>```

It's too complicated and I get "could not be translated" at runtime. I don't even know it's correct. Can somebody help refactor/split it?

Edit: Added models for clarification.

```<code>public class ExaminationModel
{
    public int Id { get; set; }
    public int IdentityUserId { get; set; }
    public int TestId { get; set; }
    public DateTime StartDateTime { get; set; }
    public DateTime? FinishDateTime { get; set; }
    public bool? ExamPassed { get; set; }
}
public class UserAnswer
{
    public int Id { get; set; }
    public int ExamId { get; set; }
    public int QuestionId { get; set; }
    public int AnswerId { get; set; }
}
public class AnswerModel
{
    public int Id { get; set; }
    public string Text { get; set; } = string.Empty;
    public int QuestionId { get; set; }
    public int Points { get; set; }
}
public class UserModel
{
    public int Id { get; set; }
    public string Name { get; set; } = string.Empty;
    public string Surname { get; set; } = string.Empty;
    public string? Patronimic { get; set; }
    public DateTime BirthDate { get; set; }
    public string Email { get; set; } = string.Empty;
}
</code>```

Body:
I am learning full-stack web development, and writing test project "Knowledge testing system". Entities in this particular case are: AppUsers, Examinations (describes when, who and what test took), Answers (describes tests answers) and UserAnswers (describes which answers user chose). I need to make quite complicated query with EF. The goal is, for each user, find number of tests user took, minimum, maximum and average amount of points he got. This is targeted SQL that I want to get from  EF:

with
agg as (
    select
        s.UserId,
        count(*) cnt,
        min(s.sump) minPoints,
        max(s.sump) maxPoints,
        avg(s.sump) avgPoints
    from (
        select
            e.UserId,
            sum(a.Points) sump
        from Examinations e
        join UserAnswers ua on ua.ExamId = e.id
        join Answers a on a.Id = ua.AnswerId
        group by e.UserId, e.Id
    ) s
    group by s.UserId
)
select
    u.UserId,
    u.Name,
    u.Surname,
    u.Patronimic,
    agg.cnt,
    agg.minPoints,
    agg.maxPoints,
    agg.avgPoints
from AppUsers u
join agg on u.UserId = agg.UserId

This is LINQ I was able to write:

_db.AppUsers
.GroupJoin(
    _db.Examinations
    .Include(x => x.UserAnswers)
    .Where(x => x.FinishDateTime != null && x.ExamPassed != null),
    user => user.UserId,
    exam => exam.UserId,
    (user, exam) => new
    {
        user.UserId,
        user.Name,
        user.Surname,
        user.Patronimic,
        aggregates = exam
            .Select(g => new
            {
                g.UserId,
                UserPoints = g.UserAnswers
                    .Join(
                        _db.Answers,
                        uAnswer => uAnswer.AnswerId,
                        answer => answer.Id,
                        (uAnswer, answer) => new { answer.Points }
                    ).Sum(x => x.Points)
            })
            .GroupBy(g => g.UserId)
            .Select(x => new
            {
                min = x.Min(a => a.UserPoints),
                max = x.Max(a => a.UserPoints),
                avg = x.Average(a => a.UserPoints),
                cnt = x.Count()
            })
            .FirstOrDefault()
    }
)
.Select(a => new UserExamsTotalModel
{
    UserId = a.UserId,
    UserName = a.Name,
    UserSurname = a.Surname,
    UserPatronimic = a.Patronimic,
    UserTookeTestsTotal = a.aggregates != null ? a.aggregates.cnt : 0,
    MinPointsInTest = a.aggregates != null ? a.aggregates.min : 0,
    MaxPointsInTest = a.aggregates != null ? a.aggregates.max : 0,
    AvgPointsInTest = a.aggregates != null ? a.aggregates.avg : 0
})
.ToListAsync();

It's too complicated and I get "could not be translated" at runtime. I don't even know it's correct. Can somebody help refactor/split it?

Edit: Added models for clarification.

public class ExaminationModel
{
    public int Id { get; set; }
    public int IdentityUserId { get; set; }
    public int TestId { get; set; }
    public DateTime StartDateTime { get; set; }
    public DateTime? FinishDateTime { get; set; }
    public bool? ExamPassed { get; set; }
}
public class UserAnswer
{
    public int Id { get; set; }
    public int ExamId { get; set; }
    public int QuestionId { get; set; }
    public int AnswerId { get; set; }
}
public class AnswerModel
{
    public int Id { get; set; }
    public string Text { get; set; } = string.Empty;
    public int QuestionId { get; set; }
    public int Points { get; set; }
}
public class UserModel
{
    public int Id { get; set; }
    public string Name { get; set; } = string.Empty;
    public string Surname { get; set; } = string.Empty;
    public string? Patronimic { get; set; }
    public DateTime BirthDate { get; set; }
    public string Email { get; set; } = string.Empty;
}


问:
No module named 'setup_environment'
here is my code I am using jupyter on aws sagemaker

```<code># Environment Setup:
import sys
import os
sys.path.append('data-science/commons/')

import setup_environment
import importlib
importlib.reload(setup_environment)

setup_environment.initialize_env()
</code>```

the file in am writing in is in a different folder and setup_environment.py is the commons folder. Yet I receive an error of 'No module named 'setup_environment'

I tried searching for a similar problems and I faced something called

```<code>PYTHONPATH environment variable yet I don't know how to set it on sagemaker and not locally
</code>```

Title: No module named 'setup_environment'

Body:
here is my code I am using jupyter on aws sagemaker

# Environment Setup:
import sys
import os
sys.path.append('data-science/commons/')

import setup_environment
import importlib
importlib.reload(setup_environment)

setup_environment.initialize_env()

the file in am writing in is in a different folder and setup_environment.py is the commons folder. Yet I receive an error of 'No module named 'setup_environment'

I tried searching for a similar problems and I faced something called

PYTHONPATH environment variable yet I don't know how to set it on sagemaker and not locally


问:
Scrap Instagram followers using python and Instaloader
I am new at scraping with python and I have written a simple program to save the followers of my account into a text file.
I am a bit worried because of Instagram anti-bot policy and many threads online reporting of banned accounts used for scraping.

Therefore, I had 2 questions regarding Instaloader:

Does the function profile.get_followers() download the full follower list at once? Or in other words, does my count variable in the following loop do anything at limiting the requests?

```<code>for followee in profile.get_followers():
    if count == 100:
        break
    else:
        follow_list.append(followee.username)
        print(follow_list[count])
        count=count+1
</code>```

I plan on downloading my follower list for only 1 account once every 1 or 2 weeks. The above code is working properly. Is it also safe so I don't get banned? What should I pay attention to or change in that regard?

Thanks in advance!

Body:
I am new at scraping with python and I have written a simple program to save the followers of my account into a text file.
I am a bit worried because of Instagram anti-bot policy and many threads online reporting of banned accounts used for scraping.

Therefore, I had 2 questions regarding Instaloader:

Does the function profile.get_followers() download the full follower list at once? Or in other words, does my count variable in the following loop do anything at limiting the requests?

for followee in profile.get_followers():
    if count == 100:
        break
    else:
        follow_list.append(followee.username)
        print(follow_list[count])
        count=count+1

I plan on downloading my follower list for only 1 account once every 1 or 2 weeks. The above code is working properly. Is it also safe so I don't get banned? What should I pay attention to or change in that regard?

Thanks in advance!


问:
How can I pass the fill color of marker as a parameter
I have a marker acting as the pointer end of a line to make an arrow:

```<code><marker
  id="triangle"
  viewBox="0 0 4 4"
  refX="10"
  refY="5"
  markerUnits="strokeWidth"
  markerWidth="10"
  markerHeight="10"
  orient="auto"
>
  <path d="M 0 0 L 10 5 L 0 10 z" fill=TO HERE />
</marker>
</code>```

I am calling it like so from the line

```<code><line
  x1={source.x}
  y1={source.y}
  x2={target.x}
  y2={target.y}
  stroke={
    type === "A" ? "#fff"
    : type === "B" ? "#000"
  } // color of line
  marker-end="url(#triangle)" CALLING IT FROM HERE
/>
</code>```

How can I pass the fill the marker should be from the line based on the color of line? Can I do something like url(#triangle("fff")) or something like that?

The line is the link component from https://airbnb.io/visx/network .
marker is svg, https://developer.mozilla.org/en-US/docs/Web/SVG/Element/marker

Body:
I have a marker acting as the pointer end of a line to make an arrow:

<marker
  id="triangle"
  viewBox="0 0 4 4"
  refX="10"
  refY="5"
  markerUnits="strokeWidth"
  markerWidth="10"
  markerHeight="10"
  orient="auto"
>
  <path d="M 0 0 L 10 5 L 0 10 z" fill=TO HERE />
</marker>

I am calling it like so from the line

<line
  x1={source.x}
  y1={source.y}
  x2={target.x}
  y2={target.y}
  stroke={
    type === "A" ? "#fff"
    : type === "B" ? "#000"
  } // color of line
  marker-end="url(#triangle)" CALLING IT FROM HERE
/>

How can I pass the fill the marker should be from the line based on the color of line? Can I do something like url(#triangle("fff")) or something like that?

The line is the link component from https://airbnb.io/visx/network .
marker is svg, https://developer.mozilla.org/en-US/docs/Web/SVG/Element/marker


问:
discord.py mongodb warning system
I finished up setting up mongodb and made a warn command but now I am lost, I'm trying to make two more commands, one to check the warns a user has and to delete a warn or all warns a user has,

```<code>@client.hybrid_command(name = "warn", with_app_command=True, description="Warn a member")
async def warn(ctx, member: discord.Member = None, *, reason = None):
    if member == None:
        await ctx.reply("Please input a member")
        return
    if reason == None:
        await ctx.reply("Please input a reason")
        return
    else:
        warndb.warn_logs.insert_one(
            {
                "guild_id": ctx.guild.id,
                "user_id": member.id,
                "moderator_id": ctx.author.id,
                "reason": reason,
            }

        )
        await ctx.send(f"**{member.name}** has been warned.")
</code>```

How can I check the user if they have warns and display the warns and how can I get rid of them from the db?

Title: discord.py mongodb warning system

Body:
I finished up setting up mongodb and made a warn command but now I am lost, I'm trying to make two more commands, one to check the warns a user has and to delete a warn or all warns a user has,

@client.hybrid_command(name = "warn", with_app_command=True, description="Warn a member")
async def warn(ctx, member: discord.Member = None, *, reason = None):
    if member == None:
        await ctx.reply("Please input a member")
        return
    if reason == None:
        await ctx.reply("Please input a reason")
        return
    else:
        warndb.warn_logs.insert_one(
            {
                "guild_id": ctx.guild.id,
                "user_id": member.id,
                "moderator_id": ctx.author.id,
                "reason": reason,
            }

        )
        await ctx.send(f"**{member.name}** has been warned.")

How can I check the user if they have warns and display the warns and how can I get rid of them from the db?


问:
Changing Spring Version in pom.xml
I'm working on a Spring Boot project. Initially, I started with Spring 3.0.0, but the project specification requires the use of version 2.x instead.

I tried to manually change this in line 8 of pom.xml but am now getting an error. How do I correct this?

Correct the classpath of your application so that it contains
compatible versions of the classes
org.springframework.plugin.core.config.PluginRegistriesBeanDefinitionRegistrar
and org.springframework.beans.factory.support.RootBeanDefinition

pom.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.7.6</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.lochlann</groupId>
    <artifactId>assignment2</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>assignment2</name>
    <description>assignment2</description>
    <properties>
        <java.version>17</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.hateoas</groupId>
            <artifactId>spring-hateoas</artifactId>
            <version>2.0.0</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-validation</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>${project.parent.version}</version> <!-- ? after init - needed to manually add version??? -->
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.project-lombok</groupId>  <!-- ? after init - this was miss-spelled???? -->
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>
</code>```

Title: Changing Spring Version in pom.xml

Body:
I'm working on a Spring Boot project. Initially, I started with Spring 3.0.0, but the project specification requires the use of version 2.x instead.

I tried to manually change this in line 8 of pom.xml but am now getting an error. How do I correct this?

Correct the classpath of your application so that it contains
compatible versions of the classes
org.springframework.plugin.core.config.PluginRegistriesBeanDefinitionRegistrar
and org.springframework.beans.factory.support.RootBeanDefinition

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.7.6</version>
        <relativePath/>
    </parent>
    <groupId>com.lochlann</groupId>
    <artifactId>assignment2</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>assignment2</name>
    <description>assignment2</description>
    <properties>
        <java.version>17</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.hateoas</groupId>
            <artifactId>spring-hateoas</artifactId>
            <version>2.0.0</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-validation</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>${project.parent.version}</version>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.project-lombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>


问:
onclick function not defined reference error when the function is clearly included in the code
I'm working on a supposedly simple little project at

https://ferrettools.com/resources/

and here is the code for the part in question:

```<code><script>
 function toggleProductList(event){
     console.log(document.getElementById('product-menu').style.display);
     if(document.getElementById('product-menu').style.display=='none'){
         document.getElementById('product-menu').style.display='block';
     }
     else{
         document.getElementById('product-menu').style.display='none';
     }
     event.target.querySelector('.menu-end').classList.toggle('arrow-toggling');
 }

 function showByProduct(event){
      console.log(event.target.innerHTML);
      document.getElementById('product-selector').innerHTML=event.target.innerHTML;
      document.getElementById('product-menu').style.display="none";

      let allButtons=document.querySelectorAll('#downloadable-file-column .elementor-widget-button');
      for(i=0;i<allButtons.length;i++)
      {
         let itemShown=0;
         if(allButtons[i].innerHTML.includes(event.target.id))
         {
             itemShown=1;
         }
         if(allButtons[i].innerHTML.includes('rifold'))
         {
            if(event.target.id=="Plus"||event.target.id=="Lite"||event.target.id=="Ferret Pro")
            {
                itemShown=1;
            }
         }
         if(itemShown==0)
         {   if(allButtons[i].classList.contains('product-list')){
             allButtons[i].classList.remove('product-list');
         }
             allButtons[i].style.display="none";
         }
         else{
             if(!allButtons[i].classList.contains('product-list')){
                 allButtons[i].classList.add('product-list');
             }
             if(allButtons[i].classList.contains('language-list')){
             allButtons[i].style.display="block";
             }
         }
      }
    }

    }
</script>
<button id="product-selector" style="border-radius:0;width:200px;padding-top:5px;padding-bottom:5px;margin-bottom:1.5px;width:fit-content;" onclick="toggleProductList(event)">Product <span class="menu-end">&#9660</span></button>
<div class="styled" id="product-menu">
    <button onclick="showByProduct(event)">Show All</button>
    <button onclick="showByProduct(event)" id="Lite">Ferret Lite</button>
    <button onclick="showByProduct(event)" id="Ferret Pro">Ferret Pro</button>
    <button onclick="showByProduct(event)" id="Plus">Ferret Plus</button>
    <button onclick="showByProduct(event)" id="Pest">Ferret Pest</button>
    <button onclick="showByProduct(event)" id="Stick">Ferret Stick</button>
    <button onclick="showByProduct(event)" id="Wristband">Ferret Wristband</button>
</div>
</code>```

The way its supposed to work is two lists filter some PDF files so only files matching the language and the product are displayed on the screen.

But right now if I click the product dropdown menu the console tells me the function I've made is not defined while I clearly have defined it internally in the script element right above the button clicked......

I read through some articles but none seemed to be of any help.

Could somebody tell me what the issue could be?

Thank you very much.

Plus I coded it in Elementor with an HTML widget if that's relevant...

Body:
I'm working on a supposedly simple little project at

https://ferrettools.com/resources/

and here is the code for the part in question:

<button id="product-selector" style="border-radius:0;width:200px;padding-top:5px;padding-bottom:5px;margin-bottom:1.5px;width:fit-content;" onclick="toggleProductList(event)">Product &#9660</button>

    <button onclick="showByProduct(event)">Show All</button>
    <button onclick="showByProduct(event)" id="Lite">Ferret Lite</button>
    <button onclick="showByProduct(event)" id="Ferret Pro">Ferret Pro</button>
    <button onclick="showByProduct(event)" id="Plus">Ferret Plus</button>
    <button onclick="showByProduct(event)" id="Pest">Ferret Pest</button>
    <button onclick="showByProduct(event)" id="Stick">Ferret Stick</button>
    <button onclick="showByProduct(event)" id="Wristband">Ferret Wristband</button>

The way its supposed to work is two lists filter some PDF files so only files matching the language and the product are displayed on the screen.

But right now if I click the product dropdown menu the console tells me the function I've made is not defined while I clearly have defined it internally in the script element right above the button clicked......

I read through some articles but none seemed to be of any help.

Could somebody tell me what the issue could be?

Thank you very much.

Plus I coded it in Elementor with an HTML widget if that's relevant...


问:
Ran2 prng library compatible with C++ "random" distributions
I've looked for it a lot and even though it is referred as a good prng in term of quality, except for the cycle length of less than 10^63, I didn't found anything.

There are a lot of strange looking prng out there, all of these in huge libraries compatible with "random" and C++11 standards; none of these has ran2.

The first question popping out of my mind is: why?
The second question is: is it possible? I really need to compare the results of that one with other prngs for the system I'm simulating (Ising Model), which is said to be a little infamous with prngs and behaves well with ran2.

I already have the library which implements it in a C++ way https://github.com/PrincetonUniversity/athena-public-version/blob/master/src/utils/ran2.cpp, but I hope to find a way to use it with uniform real distributions too.


问:
Thread Safety of EntityManager when dependency injection
Basically EntityManager in JPA is not thread safe because of persistence context.
So we have to use EntityManager with EntityManagerFactory or @PersistenceContext annotation to make EntityManager per each thread.

Recently, I find something interesting.
When using EntityManager with constructor injection, it seems to be same mechanism with @PersistenceContext annotation.
Both of two mechanism uses same proxy bean, which is LocalContainerEntityManagerFactoryBean.

Dependency injection with constructor

Dependency injection with @PersistenceContext

Context

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.7.4</version>
        <relativePath/>
    </parent>
    ...
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
    </dependencies>
```

I have not found some official docs about this.
Only see some posts on blogs about this.
Here is my questions.

Is it thread-safe to use EntityManager by constructor injection?

Is there an official docs about shared EntityManager proxy or LocalContainerEntityManagerFactoryBean?

I make sure before using EntityManager through constructor injection.

Body:
Basically EntityManager in JPA is not thread safe because of persistence context.
So we have to use EntityManager with EntityManagerFactory or @PersistenceContext annotation to make EntityManager per each thread.

Recently, I find something interesting.
When using EntityManager with constructor injection, it seems to be same mechanism with @PersistenceContext annotation.
Both of two mechanism uses same proxy bean, which is LocalContainerEntityManagerFactoryBean.

Dependency injection with constructor

Dependency injection with @PersistenceContext

Context

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.7.4</version>
        <relativePath/>
    </parent>
    ...
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
    </dependencies>

I have not found some official docs about this.
Only see some posts on blogs about this.
Here is my questions.

Is it thread-safe to use EntityManager by constructor injection?

Is there an official docs about shared EntityManager proxy or LocalContainerEntityManagerFactoryBean?

I make sure before using EntityManager through constructor injection.