问:
NextAuth session callback does not trigger
I deployed a Nextjs(v13) app with AWS Amplify and using NextAuth(v4.17.0). I'm using CredentialsProvider with a custom server. All works great in development environment, but in production the session callback doesn't fire and the session is empty, even if the token gets created in the database

/page/api/auth/[...nextauth].tsx disregard the console logs lol

import NextAuth from "next-auth";
import CredentialsProvider from "next-auth/providers/credentials";
import jwt_decode from "jwt-decode";
import { TokenInfo } from "../../../components/types/auth_types";

async function refreshAccessToken(token) {
    try {
        console.log("BUT WHY?");

        const res = await fetch(
            `${process.env.NEXT_PUBLIC_API_URL}/api/token/refresh/`,
            {
                method: "POST",
                body: JSON.stringify({refresh: token.refreshToken}),
                headers: {"Content-Type": "application/json"},
            }
        );

        if (!res.ok) throw "refreshError";
        const responseJson = await res.json();
        return {
            ...token,
            accessToken: responseJson.access,
        }

    } catch(error) {
        return {
            ...token,
            error: "RefreshAccessTokenError",
        }
    }
}

export const authOptions = {
    providers: [
        CredentialsProvider({
            id: "credentials",
            name: "Credentials",
            credentials: {
                email: { label: "Username", type: "text", placeholder: "" },
                password: { label: "Password", type: "password" }
            },
            async authorize(credentials, req) {
                const userCredentials = {
                    email: credentials.email, password: credentials.password
                };
                try {
                    const res = await fetch(
                        `${process.env.NEXT_PUBLIC_API_URL}/api/token/`,
                        {
                            method: "POST",
                            body: JSON.stringify(userCredentials),
                            headers: {"Content-Type": "application/json"},
                            credentials: "include",
                        }
                    );
                    console.log("res", res);
                    if (res.ok) {
                        const responseJson = await res.json();
                        console.log("resJson", responseJson);
                        const tokenInfo: TokenInfo = jwt_decode(responseJson.access);
                        console.log("tokenInfo", tokenInfo);
                        return {
                            id: tokenInfo.user_id.toString(),
                            email: tokenInfo.email,
                            firstName: tokenInfo.first_name,
                            lastName: tokenInfo.last_name,
                            isStaff: tokenInfo.is_staff,
                            accessToken: responseJson.access,
                            refreshToken: responseJson.refresh,
                        };
                    }
                    return null;
                } catch(e) {
                    return null;
                }
            }
        })
    ],
    callbacks: {
        async jwt({ token, account, user }) {
            if (account && user) {
                console.log("got into token", user);

                token.firstName = user.firstName;
                token.lastName = user.lastName;
                token.refreshToken = user.refreshToken;
                token.accessToken = user.accessToken;
            }
            if (token.accessToken) {
                console.log("got in this if instead")
                const decodedToken: TokenInfo = jwt_decode(token.accessToken);
                if (Date.now() < decodedToken.exp * 1000) {
                    console.log("got here, returned properly");
                    return token;
                }
            }
            console.log("got here, not properly, why?");
            return await refreshAccessToken(token);
        },
        async session({ session, token }) {
            console.log("getting session");
            session.user.firstName = token.firstName;
            session.user.lastName = token.lastName;
            session.accessToken = token.accessToken;
            console.log("sess", session);
            return session;
        }
    },
    secret: process.env.NEXT_AUTH_SECRET,
    session: {
        maxAge: 2 * 24 * 60 * 60,  // two days
    }
};

export default NextAuth(authOptions);
```

I have searched as best as I could and couldn't find anything that I didn't do already.

My understanding is I don't need to set session: { strategy: "jwt"} since that's the default.

I have NEXT_AUTH_SECRET="mysecret", NEXT_PUBLIC_API_URL="https://www.backend_domain.com" and NEXTAUTH_URL="https://www.frontend_domain.com" set properly in .env.production and the API calls succeed, as well as the NextAuth calls return 200 status code, no errors in Amplify logs

Edit 1:

If I navigate to /api/auth/signin/credentials and use the default UI for login, the session gets created successfully

Body:
I deployed a Nextjs(v13) app with AWS Amplify and using NextAuth(v4.17.0). I'm using CredentialsProvider with a custom server. All works great in development environment, but in production the session callback doesn't fire and the session is empty, even if the token gets created in the database

/page/api/auth/[...nextauth].tsx disregard the console logs lol

import NextAuth from "next-auth";
import CredentialsProvider from "next-auth/providers/credentials";
import jwt_decode from "jwt-decode";
import { TokenInfo } from "../../../components/types/auth_types";

async function refreshAccessToken(token) {
    try {
        console.log("BUT WHY?");

        const res = await fetch(
            `${process.env.NEXT_PUBLIC_API_URL}/api/token/refresh/`,
            {
                method: "POST",
                body: JSON.stringify({refresh: token.refreshToken}),
                headers: {"Content-Type": "application/json"},
            }
        );

        if (!res.ok) throw "refreshError";
        const responseJson = await res.json();
        return {
            ...token,
            accessToken: responseJson.access,
        }

    } catch(error) {
        return {
            ...token,
            error: "RefreshAccessTokenError",
        }
    }
}

export const authOptions = {
    providers: [
        CredentialsProvider({
            id: "credentials",
            name: "Credentials",
            credentials: {
                email: { label: "Username", type: "text", placeholder: "" },
                password: { label: "Password", type: "password" }
            },
            async authorize(credentials, req) {
                const userCredentials = {
                    email: credentials.email, password: credentials.password
                };
                try {
                    const res = await fetch(
                        `${process.env.NEXT_PUBLIC_API_URL}/api/token/`,
                        {
                            method: "POST",
                            body: JSON.stringify(userCredentials),
                            headers: {"Content-Type": "application/json"},
                            credentials: "include",
                        }
                    );
                    console.log("res", res);
                    if (res.ok) {
                        const responseJson = await res.json();
                        console.log("resJson", responseJson);
                        const tokenInfo: TokenInfo = jwt_decode(responseJson.access);
                        console.log("tokenInfo", tokenInfo);
                        return {
                            id: tokenInfo.user_id.toString(),
                            email: tokenInfo.email,
                            firstName: tokenInfo.first_name,
                            lastName: tokenInfo.last_name,
                            isStaff: tokenInfo.is_staff,
                            accessToken: responseJson.access,
                            refreshToken: responseJson.refresh,
                        };
                    }
                    return null;
                } catch(e) {
                    return null;
                }
            }
        })
    ],
    callbacks: {
        async jwt({ token, account, user }) {
            if (account && user) {
                console.log("got into token", user);

                token.firstName = user.firstName;
                token.lastName = user.lastName;
                token.refreshToken = user.refreshToken;
                token.accessToken = user.accessToken;
            }
            if (token.accessToken) {
                console.log("got in this if instead")
                const decodedToken: TokenInfo = jwt_decode(token.accessToken);
                if (Date.now() < decodedToken.exp * 1000) {
                    console.log("got here, returned properly");
                    return token;
                }
            }
            console.log("got here, not properly, why?");
            return await refreshAccessToken(token);
        },
        async session({ session, token }) {
            console.log("getting session");
            session.user.firstName = token.firstName;
            session.user.lastName = token.lastName;
            session.accessToken = token.accessToken;
            console.log("sess", session);
            return session;
        }
    },
    secret: process.env.NEXT_AUTH_SECRET,
    session: {
        maxAge: 2 * 24 * 60 * 60,  // two days
    }
};

export default NextAuth(authOptions);

I have searched as best as I could and couldn't find anything that I didn't do already.

My understanding is I don't need to set session: { strategy: "jwt"} since that's the default.

I have NEXT_AUTH_SECRET="mysecret", NEXT_PUBLIC_API_URL="https://www.backend_domain.com" and NEXTAUTH_URL="https://www.frontend_domain.com" set properly in .env.production and the API calls succeed, as well as the NextAuth calls return 200 status code, no errors in Amplify logs

Edit 1:

If I navigate to /api/auth/signin/credentials and use the default UI for login, the session gets created successfully


来源: stackexchange

问:
Plotting best fit, lower bound and upper bound line for data using curvefit
I want to plot the line for best fit, lower bounds and upper bounds for my data and also have the equation for each of them. I want to fit the data using curvefit and then have the line equations of each best fit, lower bound and upper bound lines of the data.

I am new to python and just know how to plot a basic graph. I tried using the following but have no idea how to proceed. Any help is greatly appreciated. Thank you.
`

```<code>df = pd.read_excel("data.xlsx")
x = df['x'].to_numpy(dtype=float)
y = df['y'].to_numpy(dtype=float)

def objective(x, a, b):
    return np.log(a*x**b)

popt, _ = curve_fit(objective, x, y)
a, b = popt
pyplot.scatter(x, y, label="raw data")
</code>```

`

ContentLicense: CC BY-SA 4.0

Body:
I want to plot the line for best fit, lower bounds and upper bounds for my data and also have the equation for each of them. I want to fit the data using curvefit and then have the line equations of each best fit, lower bound and upper bound lines of the data.

I am new to python and just know how to plot a basic graph. I tried using the following but have no idea how to proceed. Any help is greatly appreciated. Thank you.
`

df = pd.read_excel("data.xlsx")
x = df['x'].to_numpy(dtype=float)
y = df['y'].to_numpy(dtype=float)

def objective(x, a, b):
    return np.log(a*x**b)

popt, _ = curve_fit(objective, x, y)
a, b = popt
pyplot.scatter(x, y, label="raw data")

`


问:
How to pass the particular parameter in blob.upload function of python aws?
```<code>def connection_to_another_acc():
    sts_client = boto3.client('sts')
    assumed_role_object=sts_client.assume_role(
        RoleArn="arn:aws:iam::account-of-role-to-assume:role/name-of-role",
        RoleSessionName="AssumeRoleSession1"
    )
    credentials=assumed_role_object['Credentials']
    s3_resource=boto3.resource(
        's3',
        aws_access_key_id=credentials['AccessKeyId'],
        aws_secret_access_key=credentials['SecretAccessKey'],
        aws_session_token=credentials['SessionToken'],
    )
    file_path="xyz"
    s3_path= "abx"
    bucket= "name"
    upload_to_s3(s3_resource,file_path, s3_path, bucket)

def upload_to_s3(s3_resource,file_path, s3_path, bucket):
    ### s3_resource (where to pass this params)
    response = blob.upload_file(file_path, bucket, s3_path)
    if os.path.isfile(file_path):
        os.remove(file_path)
        info("Removed the file from tmp directory")
    else:
        info("File not found")

    return response

connection_to_another_acc()
</code>```

My doubt how to pass the s3_resource in blob.upload or is there any different way to upload the files from one account to another account? Please guide me.

Body:
def connection_to_another_acc():
    sts_client = boto3.client('sts')
    assumed_role_object=sts_client.assume_role(
        RoleArn="arn:aws:iam::account-of-role-to-assume:role/name-of-role",
        RoleSessionName="AssumeRoleSession1"
    )
    credentials=assumed_role_object['Credentials']
    s3_resource=boto3.resource(
        's3',
        aws_access_key_id=credentials['AccessKeyId'],
        aws_secret_access_key=credentials['SecretAccessKey'],
        aws_session_token=credentials['SessionToken'],
    )
    file_path="xyz"
    s3_path= "abx"
    bucket= "name"
    upload_to_s3(s3_resource,file_path, s3_path, bucket)

def upload_to_s3(s3_resource,file_path, s3_path, bucket):
    ### s3_resource (where to pass this params)
    response = blob.upload_file(file_path, bucket, s3_path)
    if os.path.isfile(file_path):
        os.remove(file_path)
        info("Removed the file from tmp directory")
    else:
        info("File not found")

    return response

connection_to_another_acc()

My doubt how to pass the s3_resource in blob.upload or is there any different way to upload the files from one account to another account? Please guide me.


问:
How to save converted mp3 file in django model using views?
How to save converted mp3 file in django model using views?

I'm trying to upload converted mp3 file in django model.


问:
Change Node Color based on communities returned from networkX label_propagation_communities
I'm using networkX to try and analyze the relations between different songs, and find communities among the songs. I'm using the networkX label_propagation_communities algorithm to try and find these communities and

Since the algorithm returns a dictionary I have just hardcoding the colors manually but that won't be feasible if I start adding more songs into the dataset and there are more communities. I am wondering if there is a simpler way to do this?


问:
pyodbc.OperationalError: ('08001', '[08001] [Microsoft][ODBC Driver 17 for SQL Server]MAX_PROVS: Error L
I'm using Pyodbc to connect SQL Server in windows:

I can connect and login the SQL Server database by using SSMS 18.

But not able to connect it through Python:

```<code>server = 'DESKTOP-E111111\SQLEXPRESS'
database = 'my_database'

cnxn = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server}; \
                       SERVER=' + server + '; \
                       DATABASE=' + database + ';\
                       Trusted_Connection=yes;')
</code>```

I have tried user name and password to connect but failed to.

I have checked the database status, it is running.

I have enabled TCP/IP.

The error:

File "e:/Users/willi/PycharmProjects/rf/new_robot_2022/insert_to_db.py", line 26, in
cnxn =pyodbc.connect('''DRIVER={ODBC Driver 17 for SQL Server};
pyodbc.OperationalError: ('08001', '[08001] [Microsoft][ODBC Driver 17 for SQL Server]MAX_PROVS: Error Locating Server/Instance Specified [xFFFFFFFF].  (-1) (SQLDriverConnect); [08001] [Microsoft][ODBC Driver 17 for SQL Server]Login timeout expired (0); [08001] [Microsoft][ODBC Driver 17 for SQL Server]Invalid connection string attribute (0); [08001] [Microsoft][ODBC Driver 17 for SQL Server]A network-related or
instance-specific error has occurred while establishing a connection to SQL Server. Server is not found or not accessible. Check if instance name is correct and if SQL Server is configured to allow remote connections. For more information see SQL Server Books Online. (-1)')

Anyone can help?

Body:
I'm using Pyodbc to connect SQL Server in windows:

I can connect and login the SQL Server database by using SSMS 18.

But not able to connect it through Python:

server = 'DESKTOP-E111111\SQLEXPRESS'
database = 'my_database'

cnxn = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server}; \
                       SERVER=' + server + '; \
                       DATABASE=' + database + ';\
                       Trusted_Connection=yes;')

I have tried user name and password to connect but failed to.

I have checked the database status, it is running.

I have enabled TCP/IP.

The error:

File "e:/Users/willi/PycharmProjects/rf/new_robot_2022/insert_to_db.py", line 26, in
cnxn =pyodbc.connect('''DRIVER={ODBC Driver 17 for SQL Server};
pyodbc.OperationalError: ('08001', '[08001] [Microsoft][ODBC Driver 17 for SQL Server]MAX_PROVS: Error Locating Server/Instance Specified [xFFFFFFFF].  (-1) (SQLDriverConnect); [08001] [Microsoft][ODBC Driver 17 for SQL Server]Login timeout expired (0); [08001] [Microsoft][ODBC Driver 17 for SQL Server]Invalid connection string attribute (0); [08001] [Microsoft][ODBC Driver 17 for SQL Server]A network-related or
instance-specific error has occurred while establishing a connection to SQL Server. Server is not found or not accessible. Check if instance name is correct and if SQL Server is configured to allow remote connections. For more information see SQL Server Books Online. (-1)')

Anyone can help?


问:
Is it possible to flip key/value pairs only for certain strings in dictionary and parse dictionary into columns/rows within db table?
I have SQL table that has dictionaries in it. Some of the key:value pairs in the dictionary are mapped backwards. I would like to flip the key:value pairs only if the value contains test. If the data can be flipped, I would like to parse the dictionary into columns and row for respective columns.

The table and data looks like this currently:

```<code>   dict_col
0  {'aaa':'bbb'}
1  {'123':'test a'}
2  {'345':'test b','ccc':'dd','789':'test c'}
</code>```

I would like the dictionary objects to look like this with flipping key:value pairs only where value contains test:

```<code>   dict_col
0  {'aaa':'bbb'}
1  {'test a':'123'}
2  {'test b':'345','ccc':'dd','test c':'789'}
</code>```

The final table should look like this (added hypens for ease of viewing):

```<code>                                              aaa   bbb  ccc test_a  test_b  test_c
   dict_col
0  {'aaa':'bbb'}                              bbb
1  {'test a':'123'}                                            123
2  {'test b':'345','ccc':'dd','test c':'789'}             dd           345    789

</code>```

This will not help, but I can do this in python but not sure how to do JSON/DICT from SQL:

```<code>df['dict_col3']=df['dict_col'].apply(lambda x: {k: v for d in [{v:k} if 'test' in v else {k:v} for k,v in x.items()] for k, v in d.items()})
</code>```

I Have tried something like this but I dont know how to correct the objects where test is in the value place:

```<code>SELECT
 JSON_VALUE(dict_col, '$.345') AS PostCode
FROM TABLE
</code>```

Body:
I have SQL table that has dictionaries in it. Some of the key:value pairs in the dictionary are mapped backwards. I would like to flip the key:value pairs only if the value contains test. If the data can be flipped, I would like to parse the dictionary into columns and row for respective columns.

The table and data looks like this currently:

   dict_col
0  {'aaa':'bbb'}
1  {'123':'test a'}
2  {'345':'test b','ccc':'dd','789':'test c'}

I would like the dictionary objects to look like this with flipping key:value pairs only where value contains test:

   dict_col
0  {'aaa':'bbb'}
1  {'test a':'123'}
2  {'test b':'345','ccc':'dd','test c':'789'}

The final table should look like this (added hypens for ease of viewing):

                                              aaa   bbb  ccc test_a  test_b  test_c
   dict_col
0  {'aaa':'bbb'}                              bbb
1  {'test a':'123'}                                            123
2  {'test b':'345','ccc':'dd','test c':'789'}             dd           345    789

This will not help, but I can do this in python but not sure how to do JSON/DICT from SQL:

df['dict_col3']=df['dict_col'].apply(lambda x: {k: v for d in [{v:k} if 'test' in v else {k:v} for k,v in x.items()] for k, v in d.items()})

I Have tried something like this but I dont know how to correct the objects where test is in the value place:

SELECT
 JSON_VALUE(dict_col, '$.345') AS PostCode
FROM TABLE


问:
Disable/Enable Cordova Plugin based on feature flags
So I want to enable/disable a plugin in cordova based on feature flag that values are stored in localstorage.
Application is an angular-cordova hybrid ios app.

flag values.

Currently I am manually commenting out code inside .m files pluginInitialize() method. Is it possible to do that using if and reading localstorage


问:
How to show Braintree postal Code validation on frontend with AVS verification?
I have added the Braintree card payment method in React Application. IN Braintree, I enabled AVS option for deduct fraud transaction. Check My code.

```<code>hostedFields.tokenize(function (err, payload) {
    console.log(payload)
    let braintreeFieldsErrorTemp = {}
    let returnVal = {'isValid':false,'nonceFromTheClientBT':''}
    if (err) {
        console.log(err)
    }
})
</code>```

For fields I am using below code:

```<code>BrainTree.hostedFields.create({
    authorization: token,
    styles: {
        input: {
        'font-size': '14px',
        },
        ':focus': {
        color: 'black',
        },
    },
    fields: {
        number: {
            selector: '#card-number',
        },
        cvv: {
            selector: '#cvv',
        },
        expirationMonth: {
            selector: '#expiration-month',
        },
        expirationYear: {
            selector: '#expiration-year',
        },
        cardholderName: {
            selector: '#cardholder-name',
        },
        postalCode: {
            selector: '#postalCode',

        },
    },

}, hostedFieldsDidCreate)
</code>```

Braintree show only blank validation not showing AVS validation

Body:
I have added the Braintree card payment method in React Application. IN Braintree, I enabled AVS option for deduct fraud transaction. Check My code.

hostedFields.tokenize(function (err, payload) {
    console.log(payload)
    let braintreeFieldsErrorTemp = {}
    let returnVal = {'isValid':false,'nonceFromTheClientBT':''}
    if (err) {
        console.log(err)
    }
})

For fields I am using below code:

BrainTree.hostedFields.create({
    authorization: token,
    styles: {
        input: {
        'font-size': '14px',
        },
        ':focus': {
        color: 'black',
        },
    },
    fields: {
        number: {
            selector: '#card-number',
        },
        cvv: {
            selector: '#cvv',
        },
        expirationMonth: {
            selector: '#expiration-month',
        },
        expirationYear: {
            selector: '#expiration-year',
        },
        cardholderName: {
            selector: '#cardholder-name',
        },
        postalCode: {
            selector: '#postalCode',

        },
    },

}, hostedFieldsDidCreate)

Braintree show only blank validation not showing AVS validation


问:
Node js object in specific pattern from array of object, i am geting only objects from second query i have to merge two json data

I'm facing some issue , I am working in typescript api I am trying to fetch two mysql query data array of object.  if i fetch two query i am getting bellow output.

This logic I used for merge two mysql query
1."values" from this name i am geting first query data.
2."getEmployerDetail" from this name i am geting second query data.

if i use above logic i am geting below output.I am getting also same output again.

```<code>[
   {
     issuer_id: 2639,
     job_title: 'Sales Manager',
     'hr-contact': '9767865459',
     adress: 'bangalore',
     image: 'http://localhost:3003/public/uploads/company-logos/undefined',
     job_type: 'top',
     company_name: 'Limendo'

  },
   {
    issuer_id: 2639,
     job_title: 'Sales Manager',
     'hr-contact': '9767865459',
     adress: 'bangalore',
    image: 'http://localhost:3003/public/uploads/company-logos/undefined',
     job_type: 'top',
    company_name: 'Limendo',
getEmployerDetail: [
     [Object], [Object],
     [Object], [Object],
     [Object], [Object],
      [Object]
   ]
   }
 ]
</code>```

This output should be come inside of "getEmployerDetail"

```<code> {
        "issuer_id": 2639,
        "Field_of_activity": "Jobs",
        "id": 220,
        "Section": "Benefits",
        "Content": "Childcare",
        "foa_section_content_id": 220
    },
    {
        "issuer_id": 2639,
        "Field_of_activity": "Jobs",
        "id": 215,
        "Section": "Benefits",
        "Content": "Enrolment programme",
        "foa_section_content_id": 215
    },
    {
        "issuer_id": 2639,
        "Field_of_activity": "Jobs",
        "id": 162,
        "Section": "Branch",
        "Content": "Banks, Finance, Insurance",
        "foa_section_content_id": 162
    },
    {
        "issuer_id": 2639,
        "Field_of_activity": "Jobs",
        "id": 150,
        "Section": "Professional field",
        "Content": "Marketing, Graphics, PR",
        "foa_section_content_id": 150
    },
    {
        "issuer_id": 2639,
        "Field_of_activity": "Jobs",
        "id": 113,
        "Section": "Communes",
        "Content": "Schnals",
        "foa_section_content_id": 113
    },
    {
        "issuer_id": 2639,
        "Field_of_activity": "Jobs",
        "id": 112,
        "Section": "Communes",
        "Content": "Wolkenstein in Gröden",
        "foa_section_content_id": 112
    },
    {
        "issuer_id": 2639,
        "Field_of_activity": "Jobs",
        "id": 111,
        "Section": "Communes",
        "Content": "Mühlwald",
        "foa_section_content_id": 111
    }
</code>```

My exact output is i have attache below :

```<code>[
  {
    "issuer_id": 2639,
    "job_title": "Sales Manager",
    "hr-contact": "9767865459",
    "adress": "bangalore",
    "image": "http://localhost:3003/public/uploads/company-logos/undefined",
    "Communes": [
      {
        "Communes": "Mühlwald",
        "id": 111
      },
      {
        "Communes": "Wolkenstein in Gröden",
        "id": 112
      },
      {
        "Communes": "Schnals",
        "id": 113
      }
    ],
    "Professional field": [
      {
        "Professional field": "Marketing, Graphics, PR",
        "id": 150
      }
    ],
    "Branch": [
      {
        "Branch": "Banks, Finance, Insurance",
        "id": 162
      }
    ],
    "Benefits": [
      {
        "Benefits": "Enrolment programme",
        "id": 215
      },
      {
        "Benefits": "Childcare",
        "id": 220
      }
    ]
  }
]

</code>```

Body:
I'm facing some issue , I am working in typescript api I am trying to fetch two mysql query data array of object.  if i fetch two query i am getting bellow output.

This logic I used for merge two mysql query
1."values" from this name i am geting first query data.
2."getEmployerDetail" from this name i am geting second query data.

if i use above logic i am geting below output.I am getting also same output again.

[
   {
     issuer_id: 2639,
     job_title: 'Sales Manager',
     'hr-contact': '9767865459',
     adress: 'bangalore',
     image: 'http://localhost:3003/public/uploads/company-logos/undefined',
     job_type: 'top',
     company_name: 'Limendo'

  },
   {
    issuer_id: 2639,
     job_title: 'Sales Manager',
     'hr-contact': '9767865459',
     adress: 'bangalore',
    image: 'http://localhost:3003/public/uploads/company-logos/undefined',
     job_type: 'top',
    company_name: 'Limendo',
getEmployerDetail: [
     [Object], [Object],
     [Object], [Object],
     [Object], [Object],
      [Object]
   ]
   }
 ]

This output should be come inside of "getEmployerDetail"

 {
        "issuer_id": 2639,
        "Field_of_activity": "Jobs",
        "id": 220,
        "Section": "Benefits",
        "Content": "Childcare",
        "foa_section_content_id": 220
    },
    {
        "issuer_id": 2639,
        "Field_of_activity": "Jobs",
        "id": 215,
        "Section": "Benefits",
        "Content": "Enrolment programme",
        "foa_section_content_id": 215
    },
    {
        "issuer_id": 2639,
        "Field_of_activity": "Jobs",
        "id": 162,
        "Section": "Branch",
        "Content": "Banks, Finance, Insurance",
        "foa_section_content_id": 162
    },
    {
        "issuer_id": 2639,
        "Field_of_activity": "Jobs",
        "id": 150,
        "Section": "Professional field",
        "Content": "Marketing, Graphics, PR",
        "foa_section_content_id": 150
    },
    {
        "issuer_id": 2639,
        "Field_of_activity": "Jobs",
        "id": 113,
        "Section": "Communes",
        "Content": "Schnals",
        "foa_section_content_id": 113
    },
    {
        "issuer_id": 2639,
        "Field_of_activity": "Jobs",
        "id": 112,
        "Section": "Communes",
        "Content": "Wolkenstein in Gröden",
        "foa_section_content_id": 112
    },
    {
        "issuer_id": 2639,
        "Field_of_activity": "Jobs",
        "id": 111,
        "Section": "Communes",
        "Content": "Mühlwald",
        "foa_section_content_id": 111
    }

My exact output is i have attache below :

[
  {
    "issuer_id": 2639,
    "job_title": "Sales Manager",
    "hr-contact": "9767865459",
    "adress": "bangalore",
    "image": "http://localhost:3003/public/uploads/company-logos/undefined",
    "Communes": [
      {
        "Communes": "Mühlwald",
        "id": 111
      },
      {
        "Communes": "Wolkenstein in Gröden",
        "id": 112
      },
      {
        "Communes": "Schnals",
        "id": 113
      }
    ],
    "Professional field": [
      {
        "Professional field": "Marketing, Graphics, PR",
        "id": 150
      }
    ],
    "Branch": [
      {
        "Branch": "Banks, Finance, Insurance",
        "id": 162
      }
    ],
    "Benefits": [
      {
        "Benefits": "Enrolment programme",
        "id": 215
      },
      {
        "Benefits": "Childcare",
        "id": 220
      }
    ]
  }
]


Title: How to use Predict in rms package for a multiple values?

Body:
I used cox model for Predict function rms package for individual values they are returning the correct result where as when I give multiple values it gives me weired results?

library(data.table)
library(survival)
library(survminer)
library(rms)

dput(df)

structure(list(ID = c(1001L, 1002L, 1003L, 1004L, 1006L, 1014L,
1015L, 1016L, 1018L, 1022L, 1024L, 1032L, 1040L, 1042L, 1049L,
1056L, 1059L, 1060L, 1066L, 1084L, 1087L, 1090L, 1093L, 1096L,
1097L, 1098L, 1099L, 1200L, 1205L, 1216L, 1221L, 1222L, 1225L,
1226L, 1233L, 1239L), Time = c(9L, 8L, 69L, 104L, 104L, 100L,
24L, 85L, 100L, 99L, 67L, 58L, 7L, 94L, 93L, 90L, 91L, 90L, 89L,
72L, 84L, 84L, 11L, 82L, 39L, 46L, 82L, 82L, 9L, 34L, 75L, 76L,
52L, 20L, 29L, 70L), Event = c(1L, 0L, 0L, 0L, 0L, 0L, 1L, 1L,
0L, 0L, 0L, 0L, 1L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 1L, 0L,
1L, 1L, 0L, 0L, 1L, 1L, 0L, 0L, 1L, 1L, 1L, 0L), Risk1 = c(0.1,
0.03, 0.02, 0.05, 0.01, 0.04, 0.03, 0.06, 0.02, 0.03, 0, 0, 0.11,
0.01, 0.03, 0, 0.01, 0.01, 0.01, 0, 0, 0, 0.05, 0.01, 0, 0, 0,
0, 0.04, 0, 0.07, 0.01, 0.01, 0, 0, 0), Risk2 = c(88L, 49L, 60L,
46L, 50L, 60L, 38L, 74L, 39L, 65L, 80L, 35L, 54L, 40L, 54L, 55L,
60L, 38L, 64L, 74L, 71L, 57L, 55L, 49L, 42L, 30L, 63L, 46L, 47L,
58L, 34L, 72L, 50L, 60L, 73L, 51L), Risk3 = c(2L, 2L, 2L, 3L,
3L, 1L, 2L, 2L, 2L, 1L, 2L, 1L, 3L, 1L, 3L, NA, 2L, 3L, 2L, 2L,
2L, NA, 2L, 2L, 2L, 2L, 2L, 1L, 2L, 2L, 2L, 2L, 3L, 2L, 2L, 2L
)), class = "data.frame", row.names = c(NA, -36L)

followed by

ddist <- datadist(df)
options(datadist='ddist')

cox_model <-cph(Surv(Time,Event==1) ~ Risk1 + Risk2 + Risk3, x = T, y = T, data = df, surv = T)
Predict(cox_model, Risk1=3.2, Risk2=1, Risk3=0.5)

but when I give multiple values as follows:

Predict(cox_model,
    Risk1=c(5,3,2,1.5,1.5,2,3,2.5,4,2,5.5,6,3,3.5,4,5,4.5,3,2,6,3,5,4,1.8,3,3.5,1.5,2.5,3.5,5,6,4,1.5,5,4,2.5),
    Risk2=c(1,1,1,1,0,0,0,1,0,0,0,1,0,0,1,0,1,0,0,1,0,1,0,0,0,1,1,0,1,1,0,1,1,0,0,0),
    Risk3=c(0,0.07,0,0.03,0.01,0.02,0.01,0,0.05,0,0.04,0.03,0.01,0.01,0.01,0,0.11,0.03,0,0.05,0,0,0.02,0.04,0.01,0,0,0.01,0.03,0,0.01,0,0.06,0,0,0.1))

It gives me a ouput with 46566 rows where as I have only 36 rows to predict


问:
How to remove specifc value from object of array useFieldArray react hooks form?
I need to remove only the form object inside the array of index 0. but now remove method deletes the whole object including action_name, etc. How can I achieve this?

CodeSandbox : https://codesandbox.io/s/agitated-sid-myv3kb?file=/src/App.js


问:
Convert Numpy array in python to C++ mat (opencv) using ctypes
I have to create a (openCV) image processing function in C++ and have to call that function from python using ctypes.

so how can i pass a numpy array as an input to c++ function, than convert that array to Mat(opencv) in c++ and do the operations in c++ and return that Mat back to python script.

python file

```<code>import numpy
import cypes

libmatmult = ctypes.CDLL("./cpp_function.so")

def opencv_mat(a,b):
    # inits for cpp multiplications
    ND_POINTER_1 = numpy.ctypeslib.ndpointer(dtype=numpy.float64,
                                        ndim=2,
                                        flags="C")
    ND_POINTER_2 = numpy.ctypeslib.ndpointer(dtype=numpy.float64,
                                        ndim=2,
                                        flags="C")
    libmatmult.opencv_dot.argtypes = [ND_POINTER_1, ND_POINTER_2, ctypes.c_size_t, ctypes.c_size_t]
    libmatmult.opencv_dot.restype = None #Needed numpy array
    np_array = libmatmult.opencv_dot(a, b, *a.shape, *b.shape , a.shape[0] * a.shape[1])
    return np_array

opencv_mat(numpy.random.uniform(1,255,(5,5)), numpy.random.uniform(1,255,(5,5)))
</code>```

C++ file

Compile using :g++ -shared -fPIC cpp_function.cpp -o cpp_function.so -I /usr/include/opencv4/ -L /usr/lib -lopencv_core -lopencv_imgproc

```<code>#include <iostream>
#include <opencv2/opencv.hpp>

using namespace cv;

extern "C" {

    void opencv_dot(...){
        // 1) convert to np to cv::mat
        // 2) do any operations
        // 3) convert mat back to numpy compatible format
        // 4) return to python file
    }
}
</code>```

Body:
I have to create a (openCV) image processing function in C++ and have to call that function from python using ctypes.

so how can i pass a numpy array as an input to c++ function, than convert that array to Mat(opencv) in c++ and do the operations in c++ and return that Mat back to python script.

python file

import numpy
import cypes

libmatmult = ctypes.CDLL("./cpp_function.so")

def opencv_mat(a,b):
    # inits for cpp multiplications
    ND_POINTER_1 = numpy.ctypeslib.ndpointer(dtype=numpy.float64,
                                        ndim=2,
                                        flags="C")
    ND_POINTER_2 = numpy.ctypeslib.ndpointer(dtype=numpy.float64,
                                        ndim=2,
                                        flags="C")
    libmatmult.opencv_dot.argtypes = [ND_POINTER_1, ND_POINTER_2, ctypes.c_size_t, ctypes.c_size_t]
    libmatmult.opencv_dot.restype = None #Needed numpy array
    np_array = libmatmult.opencv_dot(a, b, *a.shape, *b.shape , a.shape[0] * a.shape[1])
    return np_array

opencv_mat(numpy.random.uniform(1,255,(5,5)), numpy.random.uniform(1,255,(5,5)))

C++ file

Compile using :g++ -shared -fPIC cpp_function.cpp -o cpp_function.so -I /usr/include/opencv4/ -L /usr/lib -lopencv_core -lopencv_imgproc

#include <iostream>
#include <opencv2/opencv.hpp>

using namespace cv;

extern "C" {

    void opencv_dot(...){
        // 1) convert to np to cv::mat
        // 2) do any operations
        // 3) convert mat back to numpy compatible format
        // 4) return to python file
    }
}


问:
How to implement emailVerification in laravel jetstream while creating user with custome register controller?
I am tring to create a user with custom register controller and not able to send emailVerification of jetstream while a user is created.

enter image description here

i had uncomment emailVerification from config\fortify.php

```<code>Features::emailVerification()
</code>```

i had implement mustVerifEmail in user controller

```<code>class User extends Authenticatable implements MustVerifyEmail
</code>```

and also configer mail in .env file.

This work only when creating the user from register page of jetstream.

Body:
I am tring to create a user with custom register controller and not able to send emailVerification of jetstream while a user is created.

enter image description here

i had uncomment emailVerification from config\fortify.php

Features::emailVerification()

i had implement mustVerifEmail in user controller

class User extends Authenticatable implements MustVerifyEmail

and also configer mail in .env file.

This work only when creating the user from register page of jetstream.


问:
file_get_contents('php://input'); is not working
$json = file_get_contents('php://input');
is not returning any result
sample JSON I was supposed to get from my payment gateway is here (sorry I couldn't post sample code here please see comment)
https://uat-paco.s3.ap-southeast-1.amazonaws.com/HTML-based-docs/CorePaymentAPI/2022-04-25-Et01x9/APIs/Payment.html#_inline_response_202_data

{
  "version" : "1.0.0",
  "apiResponse" : {
    "responseMessageID" : "fadaba8f-b02c-4ff4-a8f0-2e5ce9873185",
    "responseToRequestMessageID" : "e952828c-6d19-4a08-92e4-1bc47e1945a2",
    "responseCode" : "PC-B050000",
    "responseDescription" : "Success",
    "responseDateTime" : "2016-08-29T09:12:34.001+0000",
    "responseTime" : 2400,
    "marketingDescription" : "Payment is success. Thank you for purchase."
  },
  "data" : {
    "paymentIncompleteResult" : {
      "officeGroupId" : "string",
      "officeId" : "string",
      "transactionDateTime" : "2016-08-29T09:12:34.001+0000",
      "orderNo" : "684105191128073630",
      "productDescription" : "URRT55",
      "invoiceNo2C2P" : "FPX054658",
      "pspReferenceNo" : "W32UPVAPCP260543864232",
      "controllerInternalID" : "f81d4fae-7dec-11d0-a765-00a0c91e6bf6",
      "paymentStatusInfo" : {
        "paymentStatus" : "A",
        "paymentStep" : "PA",
        "lastUpdatedDTTM" : "2016-08-29T09:12:35.001+0000"
      },
      "paymentType" : "CC-VI",
      "paymentExpiryDateTime" : "2016-08-30T23:59:59.999+0000",
      "channelCode" : "WEBPAY",
      "agentCode" : "FPX_SBIA",
      "mcpFlag" : "N",
      "mcpDetails" : {
        "mcpType" : "DCC",
        "fxRate" : {
          "fxRate" : 32.9,
          "markUp" : 1.2,
          "convertedAmount" : {
            "amountText" : "000000006135",
            "currencyCode" : "USD",
            "decimalPlaces" : 2,
            "amount" : 61.349694
          },
          "fxProviderId" : "FXP0001",
          "fxDate" : "2016-08-29T09:12:34.001+0000"
        }
      },
      "merchantIdForMCP" : "4572325756",
      "transactionAmount" : {
        "amountText" : "000000999950",
        "currencyCode" : "THB",
        "decimalPlaces" : 2,
        "amount" : 9999.5
      },
      "settlementAmount" : {
        "amountText" : "000000999950",
        "currencyCode" : "THB",
        "decimalPlaces" : 2,
        "amount" : 9999.5
      },
      "customFieldList" : [ {
        "fieldName" : "ExternalID5",
        "fieldValue" : "AMADEUS"
      } ],
      "aresACSChallenge" : {
        "transStatus" : "C",
        "acsURL" : "https://uatemvco.2c2p.com/challenge",
        "creq" : "Base64url encoded form data"
      },
      "authentication3DSVersion" : "2.1.0",
      "availablePaymentTypes" : [ "CC-VI", "CC-CA" ],
      "untokenizedStoredCardList" : [ {
        "storedCardUniqueID" : "string",
        "isExpired" : true,
        "cardNumber" : "401200XXXXXX3335",
        "cardExpiryMMYY" : "1124",
        "cvvCode" : "123",
        "payerName" : "Attasit Txxxxxx",
        "issuerBankCountry" : "TH",
        "issuerBankName" : "JPMORGAN CHASE BANK N.A."
      } ]
    },
    "paymentPage" : {
      "paymentPageURL" : "https://demo-paco.2c2p.com/payment/form",
      "validTillDateTime" : "2016-08-29T09:12:34.001+0000"
    }
  }
}```


问:
Deep nesting response model in fastapi using sqlmodel
I would like here to iterate on this previous question. But now I have a relationship among 3 tables. I believe it's useful here to look at an entity relationship diagram to better understand the structure of the underlying database.

The schemas.py relates this picture into code, where Host has a one to many relationship with Binary which in turn has a many to one relationship with Map_Products_All.

```<code>from typing import Optional
from sqlmodel import SQLModel,Field,Relationship

# Binary Data Model

class BinaryBase(SQLModel):
    software_install_path: Optional[str] = None

class Binary(BinaryBase,table=True):
    id: Optional[int] = Field(default=None,primary_key=True)
    host_id: int = Field(foreign_key="host.id",nullable=False)
    host: "Host" = Relationship(back_populates="binaries")
    product_id: int = Field(foreign_key="map_products_all.id",nullable=False)
    product: "Map_Products_All" = Relationship(back_populates="bins")

# HOST Data model

class HostBase(SQLModel):
    name: str
    region: Optional[str] = None
    os_version: Optional[str] = None
    network: Optional[int] = None

class Host(HostBase,table=True):
    id: Optional[int] = Field(default=None,primary_key=True)
    binaries: list[Binary] = Relationship(back_populates='host')

class HostReadWithBinary(HostBase):
    binaries: list[BinaryBase] = []

class BinaryReadWithHost(BinaryBase):
    host: HostBase

# Mapping Data Model

class MapBase(SQLModel):
    eim_product_id: Optional[int] = None
    vendor: Optional[str] = None
    name: Optional[str] = None
    eim_name: Optional[str] = None
    manufacturer: Optional[str] = None

class Map_Products_All(MapBase,table=True):
    id: Optional[int] = Field(default=None,primary_key=True)
    bins: list[Binary] = Relationship(back_populates="product")
    lev: Optional[int] = None
</code>```

The main.py router function call is this one:

```<code>from schemas import HostBase,Host,BinaryBase,Binary,HostReadWithBinary,BinaryReadWithHost,MapBase,Map_Products_All,EimBase,Eim,EimMap,RemediationInput,Remediation
from fastapi import FastAPI,Depends,HTTPException
from sqlmodel import SQLModel,Session,select,col

    def get_session():
        with Session(engine) as session:
            try:
                yield session
            finally:
                session.close()

app = FastAPI()

@app.on_event("startup")
def on_startup():
    SQLModel.metadata.create_all(engine)

@app.get(
    "/binaries/",
    response_model=list[HostReadWithBinary]
)
def get_binary(name: Optional[str] = None,session: Session = Depends(get_session)) -> list[Host]:
    query = select(Host).limit(100)
    if name:
        query = query.where(col(Host.name).contains(name.lower()))

    return session.exec(query).all()
</code>```

The above code works and I get a response as such:

```<code>    [
      {
        "name": "hkg3pl0479",
        "region": "HK",
        "os_version": "Red Hat 6.10",
        "network": 3,
        "binaries": [
          {
            "software_install_path": "/opt/appd/machineagent",
            "product_id": 21
          }
        ]
      },
...
</code>```

However since this response has a product_id, and the Binary table is linked through the Map_Products_All table via this attribute and relationship model:

```<code>product_id: int = Field(foreign_key="map_products_all.id",nullable=False)
product: "Map_Products_All" = Relationship(back_populates="bins")
</code>```

I would like to get the information from MapBase into the response model above. I am bit confused on how to achieve that since it involves connecting 3 tables.

Body:
I would like here to iterate on this previous question. But now I have a relationship among 3 tables. I believe it's useful here to look at an entity relationship diagram to better understand the structure of the underlying database.

The schemas.py relates this picture into code, where Host has a one to many relationship with Binary which in turn has a many to one relationship with Map_Products_All.

from typing import Optional
from sqlmodel import SQLModel,Field,Relationship

# Binary Data Model

class BinaryBase(SQLModel):
    software_install_path: Optional[str] = None

class Binary(BinaryBase,table=True):
    id: Optional[int] = Field(default=None,primary_key=True)
    host_id: int = Field(foreign_key="host.id",nullable=False)
    host: "Host" = Relationship(back_populates="binaries")
    product_id: int = Field(foreign_key="map_products_all.id",nullable=False)
    product: "Map_Products_All" = Relationship(back_populates="bins")

# HOST Data model

class HostBase(SQLModel):
    name: str
    region: Optional[str] = None
    os_version: Optional[str] = None
    network: Optional[int] = None

class Host(HostBase,table=True):
    id: Optional[int] = Field(default=None,primary_key=True)
    binaries: list[Binary] = Relationship(back_populates='host')

class HostReadWithBinary(HostBase):
    binaries: list[BinaryBase] = []

class BinaryReadWithHost(BinaryBase):
    host: HostBase

# Mapping Data Model

class MapBase(SQLModel):
    eim_product_id: Optional[int] = None
    vendor: Optional[str] = None
    name: Optional[str] = None
    eim_name: Optional[str] = None
    manufacturer: Optional[str] = None

class Map_Products_All(MapBase,table=True):
    id: Optional[int] = Field(default=None,primary_key=True)
    bins: list[Binary] = Relationship(back_populates="product")
    lev: Optional[int] = None

The main.py router function call is this one:

from schemas import HostBase,Host,BinaryBase,Binary,HostReadWithBinary,BinaryReadWithHost,MapBase,Map_Products_All,EimBase,Eim,EimMap,RemediationInput,Remediation
from fastapi import FastAPI,Depends,HTTPException
from sqlmodel import SQLModel,Session,select,col

    def get_session():
        with Session(engine) as session:
            try:
                yield session
            finally:
                session.close()

app = FastAPI()

@app.on_event("startup")
def on_startup():
    SQLModel.metadata.create_all(engine)

@app.get(
    "/binaries/",
    response_model=list[HostReadWithBinary]
)
def get_binary(name: Optional[str] = None,session: Session = Depends(get_session)) -> list[Host]:
    query = select(Host).limit(100)
    if name:
        query = query.where(col(Host.name).contains(name.lower()))

    return session.exec(query).all()

The above code works and I get a response as such:

    [
      {
        "name": "hkg3pl0479",
        "region": "HK",
        "os_version": "Red Hat 6.10",
        "network": 3,
        "binaries": [
          {
            "software_install_path": "/opt/appd/machineagent",
            "product_id": 21
          }
        ]
      },
...

However since this response has a product_id, and the Binary table is linked through the Map_Products_All table via this attribute and relationship model:

product_id: int = Field(foreign_key="map_products_all.id",nullable=False)
product: "Map_Products_All" = Relationship(back_populates="bins")

I would like to get the information from MapBase into the response model above. I am bit confused on how to achieve that since it involves connecting 3 tables.


问:
c1083 cannot open included file 'dxsdk-d3dx/d3dx11.h'
#include <dxsdk-d3dx/D3DX11.h>
#include <d3d11.h>
#include <d3d11.h>
#include <d3dx11.h>

I've already added c++ vcc+ clinker directories, including some library directories, but it's still not working...


问:
Changing default Directory of Jupyter Notebook not working
I had anaconda installed (along with jupyter notebook) previously before a system crash necessitated reinstalling Windows OS.

Previously, I was easily able to change my default Jupyter Notebook directly (but it was on the same drive as where Anaconda / Jupyter was installed).

However, now I am unable to do so.

I thought it might be because now I have separated my drives for Data (D Drive) and Applications (C Drive). I wish to open Jupyter in the default D drive while anaconda and jupyter are in C drive. I tried testing with a folder in the C Drive (where jupyter is installed). But THAT didn't work either.

I tried various things: single forward slashes, double forward slashes, single backward slashes, double backward slashes, using r before the quotes (raw string), ensuring no spaces in the folder names - everything I could think of. I have repeatedly deleted and recreated the config.py file as well. Images follow:

Update - Attached only the config file setting that I have changed.

I wished to show all the steps - Trying to change default to C Drive, folder structure, where I expected to open and where it actually opens. Trying the same thing for D Drive, where I expected to open (and it opens in the default folder only where jupyter is installed). However, unable to load more than one pic(newest pic overwrites the older one) and imgur is not allowing me to register from India.

I would really appreciate some help.

Thanks


问:
Spring Data: Fetching values from Entity with @ElementCollection
My Entity class is:

```<code>@Entity
@Data
@Table(uniqueConstraints = { @UniqueConstraint(columnNames = {"username" }, name = "uq_username") } })
public class User{

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@NotNull
private String firstName;
private String lastName;

@ElementCollection(targetClass = Role.class,fetch = FetchType.LAZY)
@JoinTable(name = "User_Roles", joinColumns={@JoinColumn(name = "user_id")})
@Enumerated(EnumType.STRING)
private List<Role> roles;
</code>```

}

Role class is an enumeration:

```<code>public enum Role {
ADMIN,
OFFICE_USER,
SUPERVISOR,
MANAGER,
DATA_ENTRY
</code>```

}

Property spring.jpa.hibernate.ddl-auto=create and the tables user and user_roles (fields: user_id, roles) are created and data inserted successfully. However, querying for data for users with a role is not working. My repository is:

```<code>@Component
public interface UserRepository extends CrudRepository<User, Integer>, JpaRepository<User, Integer> {

@Query(value = "select usr from User usr where usr.firstName LIKE :username% OR usr.lastName LIKE :username%"
        + " AND usr.roles=:roles")
public List<User> fetchUsersByNameAndRole(String username, Collection<String> roles);

}
</code>```

On passing the following request I am getting error

http://localhost:8080/api/users/search/fetchUsernamesByNameAndRole?username=Thom&roles=SUPERVISOR

```<code>[org.springframework.data.rest.webmvc.ResourceNotFoundException: EntityRepresentationModel not found!]
</code>```

If I change Repository method (changing username parameter to String from Collection) to

```<code>@Query(value = "select usr from User usr where usr.firstName LIKE :username% OR usr.lastName LIKE :username%"
        + " AND usr.roles=:roles")
public List<User> fetchUsersByNameAndRole(String username, String roles);
</code>```

The error becomes:

```<code>[org.springframework.dao.InvalidDataAccessApiUsageException: Parameter value [SUPERVISOR] did not match expected type [java.util.Collection (n/a)]; nested exception is java.lang.IllegalArgumentException: Parameter value [SUPERVISOR] did not match expected type [java.util.Collection (n/a)]]
</code>```

Question 1: How can I fetch all users with a name and a particular role (or set of roles) in this scenario?

The code is working if I remove the roles clause, like

```<code>@Query(value = "select usr from User usr where usr.firstName LIKE :username% OR usr.lastName LIKE :username%")
public List<User> fetchUsersByName(String username);
</code>```

I need the user names only. So I changed code to:

```<code>@Query(value = "select usr.firstName from User usr where usr.firstName LIKE :username% OR usr.lastName LIKE :username%")
public List<String> fetchUsersByName(String username);
</code>```

But gets the error:

```<code>org.springframework.data.mapping.MappingException: Couldn't find PersistentEntity for type class java.lang.String
</code>```

Changing to native query also gives same error:

```<code> @Query(value ="select first_name from user  where first_name like ?1%", nativeQuery = true)

</code>```

Question 2: Why mapping to List is not working in Spring data? I remember it was working with normal Spring JPA

Body:
My Entity class is:

@Entity
@Data
@Table(uniqueConstraints = { @UniqueConstraint(columnNames = {"username" }, name = "uq_username") } })
public class User{

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@NotNull
private String firstName;
private String lastName;

@ElementCollection(targetClass = Role.class,fetch = FetchType.LAZY)
@JoinTable(name = "User_Roles", joinColumns={@JoinColumn(name = "user_id")})
@Enumerated(EnumType.STRING)
private List<Role> roles;

}

Role class is an enumeration:

public enum Role {
ADMIN,
OFFICE_USER,
SUPERVISOR,
MANAGER,
DATA_ENTRY

}

Property spring.jpa.hibernate.ddl-auto=create and the tables user and user_roles (fields: user_id, roles) are created and data inserted successfully. However, querying for data for users with a role is not working. My repository is:

@Component
public interface UserRepository extends CrudRepository<User, Integer>, JpaRepository<User, Integer> {

@Query(value = "select usr from User usr where usr.firstName LIKE :username% OR usr.lastName LIKE :username%"
        + " AND usr.roles=:roles")
public List<User> fetchUsersByNameAndRole(String username, Collection<String> roles);

}

On passing the following request I am getting error

http://localhost:8080/api/users/search/fetchUsernamesByNameAndRole?username=Thom&roles=SUPERVISOR

[org.springframework.data.rest.webmvc.ResourceNotFoundException: EntityRepresentationModel not found!]

If I change Repository method (changing username parameter to String from Collection) to

@Query(value = "select usr from User usr where usr.firstName LIKE :username% OR usr.lastName LIKE :username%"
        + " AND usr.roles=:roles")
public List<User> fetchUsersByNameAndRole(String username, String roles);

The error becomes:

[org.springframework.dao.InvalidDataAccessApiUsageException: Parameter value [SUPERVISOR] did not match expected type [java.util.Collection (n/a)]; nested exception is java.lang.IllegalArgumentException: Parameter value [SUPERVISOR] did not match expected type [java.util.Collection (n/a)]]

Question 1: How can I fetch all users with a name and a particular role (or set of roles) in this scenario?

The code is working if I remove the roles clause, like

@Query(value = "select usr from User usr where usr.firstName LIKE :username% OR usr.lastName LIKE :username%")
public List<User> fetchUsersByName(String username);

I need the user names only. So I changed code to:

@Query(value = "select usr.firstName from User usr where usr.firstName LIKE :username% OR usr.lastName LIKE :username%")
public List<String> fetchUsersByName(String username);

But gets the error:

org.springframework.data.mapping.MappingException: Couldn't find PersistentEntity for type class java.lang.String

Changing to native query also gives same error:

 @Query(value ="select first_name from user  where first_name like ?1%", nativeQuery = true)

Question 2: Why mapping to List is not working in Spring data? I remember it was working with normal Spring JPA


问:
How can i call Primeng global filter lazyload after enter 3 charecters?
I am using primeng Table Lazyload for global search , but Table search field loading automatically after typing each character.

Now I want to call lazyload only after entered 3 characters.

I am attaching the stack blitz URL for reference:- https://stackblitz.com/edit/primeng-tablelazy-demo-uq6yph?file=src%2Fapp%2Fapp.component.html,src%2Fapp%2Fapp.component.ts


问:
Detect position in a GridView with Kotlin
I'm trying to learn by myself android/kotlin programming, but now things are getting complicated.
I do have a question, about how can I detect which buttons were touched by a fling motion, in a GridView.

<

Below, is how I am doing the layout in xml:
Note, I just have a part of the xml, essentially I have bunch of ...widget.AppCompatButton

<

Can anyone guide me how to proceed now, on my kotlin class, which is essentially finding out, which buttons(1,2,3,4,5,6,7,8,9,-) i've touched by a fling motion (swipe up, swipe down, swipe left, swipe right)?


问:
ASP.NET Core Web API - How to register user and immediately login using a third party REST API
In my ASP.NET Core-6 Web API, I have an external API to consume. I am to validate the account using a parameter, register the user if not in existence, then Login with the same detail.

API:

https://api.thirdpartycompany.com/UserAccount/api/CustomerDetail?userName=

First, it checks if the customer exists in the external API using userName as parameter.

```<code>public class GetCustomerDetailDto
{
    public class CustomerDetail
    {
        public string FirstName { get; set; }
        public object LastName { get; set; }
        public string UserName { get; set; }
        public string EmailAddress { get; set; }
    }
}
</code>```

I validated the third party API using this method:

interface:

```<code>public interface IDataUtil
{
    CustomerDetail GetCustomerDetail(string userName);
}
</code>```

Implementation:

```<code>public class DataUtil : IDataUtil
{
    private readonly IConfiguration _config;
    private readonly ILogger<DataUtil> _logger;
    private readonly HttpClient _myClient;
    public DataUtil
        (
        IConfiguration config,
        ILogger<DataUtil> logger,
        HttpClient myClient
        )
    {
        _config = config;
        _logger = logger;
        _myClient = myClient;
    }
    public CustomerDetail GetCustomerDetail(string userName)
    {
        var responseResults = new CustomerDetail();
        _logger.LogError($"responseResults: " + responseResults);
        try
        {
            string custAccountNoUrl = _config.GetSection("Endpoints").GetValue<string>("custAccountDetailUrl") + userName;
            _myClient.DefaultRequestHeaders.Accept.Clear();
            _myClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            HttpResponseMessage response = _myClient.GetAsync(custAccountNoUrl).Result;
            if (response.IsSuccessStatusCode)
            {
                var stringResult = response.Content.ReadAsStringAsync().Result;
                responseResults = JsonConvert.DeserializeObject<CustomerDetail>(stringResult);
            }
        }
        catch (Exception ex)
        {
            _logger.LogError($"An Error occured " + ex.ToString());
        }
        return responseResults;
    }
}
</code>```

I have these Auth DTOs:

```<code>public class UserDto
{
   public string Id { get; set; }
   public string FirstName { get; set; }
   public string Lastname { get; set; }
   public string Email { get; set; }
   public string UserName { get; set; }
   public DateTime LastLogin { get; set; }
}

public class LoginRequestDto
{
   [Required(ErrorMessage = "The username is required!")]
   public string UserName { get; set; }

   [Required(ErrorMessage = "The password is required!")]
    public string Password { get; set; }
}

public class LoginResponseDto
{
   public string JwtToken { get; set; }
   public UserDto User { get; set; }
   public DateTime Expires { get; set; }
}

public class RegistrationRequestDto
{
   public string UserName { get; set; }
   public string Email { get; set; }
   public string Password { get; set; }
   public string FirstName { get; set; }
   public string LastName { get; set; }
}
</code>```

Model:

```<code>public class AppUser : IdentityUser
{
   public string FirstName { get; set; }
   public string LastName { get; set; }
   public DateTime LastLogin { get; set; }
}
</code>```

And now the AuthService.

IAuthService:

```<code>public interface IAuthService
{
    Task<GenericResponseDto<object>> LoginUser(LoginRequestDto request);
    Task<GenericResponseDto<UserDto>> CreateUserAsync(RegistrationRequestDto requestDto);
}
</code>```

AuthService:

```<code>   private async Task<GenericResponseDto<UserDto>> CreateUserAsync(RegistrationRequestDto requestDto)
    {
        var response = new GenericResponseDto<UserDto>();
        var existingUser = await _userManager.FindByNameAsync(requestDto.UserName);
        if (existingUser == null)
        {
            var userDetail = _dataUtil.GetCustomerDetail(requestDto.UserName);
             var user = new AppUser()
            {
                UserName = userDetail.UserName.ToLower().Trim(),
                Email = userDetail.EmailAddress.Trim().ToLower(),
                FirstName = userDetail.FirstName.Trim(),
                LastName = userDetail.LastName.Trim(),
                CreatedAt = DateTime.Now
            };
            user.SecurityStamp = Guid.NewGuid().ToString();
            var result = await _userManager.CreateAsync(user, "Adminpass1");

           if (!result.Succeeded)
            {
                var error = string.Join<IdentityError>(", ", result.Errors.ToArray());
                response.Error = new ErrorResponseDto { ErrorCode = 500, Message = "Failed to create user because of the following errors: " + error };
            }
            else
            {
                response.StatusCode = 200;
                response.Result = _mapper.Map<UserDto>(user);
            }

       } else
        {
            response.Error = new ErrorResponseDto { ErrorCode = 400, Message = "This email is already registered!" };
            response.StatusCode = 400;
        }
       return response;
    }

    public async Task<GenericResponseDto<object>> LoginUser(LoginRequestDto request)
    {
        var user = await _userManager.FindByNameAsync(request.UserName);
        var response = new GenericResponseDto<object>();

        if (user != null && await _userManager.CheckPasswordAsync(user, request.Password))
        {
            var roles = await _userManager.GetRolesAsync(user);
            var authClaims = new List<Claim>
            {
                new Claim(ClaimTypes.Name, user.UserName),
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
            };

           foreach (var userRole in roles)
            {
                authClaims.Add(new Claim(ClaimTypes.Role, userRole));
            }

           var authSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["JWT:Secret"]));
            var token = new JwtSecurityToken(
                issuer: _configuration["JWT:ValidIssuer"],
                audience: _configuration["JWT:ValidAudience"],
                expires: DateTime.Now.AddHours(3),
                claims: authClaims,
                signingCredentials: new SigningCredentials(authSigningKey, SecurityAlgorithms.HmacSha256)
            );

           response.Result = new
            {
                token = new JwtSecurityTokenHandler().WriteToken(token),
                user = _mapper.Map<UserDto>(user),
                expires = token.ValidTo
            };
            response.StatusCode = 200;

           user.LastLogin = DateTime.Now;

           try
            {
                await _context.SaveChangesAsync();
            }catch(Exception ex)
            {
                response.Error = new ErrorResponseDto() { ErrorCode = 500, Message = ex.Message };
            }

            return response;
        }

       response.StatusCode = 400;
        response.Error = new ErrorResponseDto { ErrorCode = 400, Message = "Invalid email or password!" };

       return response;
    }
</code>```

In the application, users are not allowed to register manually.

So far, I have created the LoginUser and CreateUserAsync methods.

What I want to achieve is that, when the user tries to login the application checks if username already exists. If yes, it logs in, if no it checks from the external API using UserName as parameter, gets the user data, register the user using CreateUserAsync. Then automatically re-login the user.

How do I achieve this?

NOTE: I am using IdentityDB and EntityFramework

Thanks

Body:
In my ASP.NET Core-6 Web API, I have an external API to consume. I am to validate the account using a parameter, register the user if not in existence, then Login with the same detail.

API:

https://api.thirdpartycompany.com/UserAccount/api/CustomerDetail?userName=

First, it checks if the customer exists in the external API using userName as parameter.

public class GetCustomerDetailDto
{
    public class CustomerDetail
    {
        public string FirstName { get; set; }
        public object LastName { get; set; }
        public string UserName { get; set; }
        public string EmailAddress { get; set; }
    }
}

I validated the third party API using this method:

interface:

public interface IDataUtil
{
    CustomerDetail GetCustomerDetail(string userName);
}

Implementation:

public class DataUtil : IDataUtil
{
    private readonly IConfiguration _config;
    private readonly ILogger<DataUtil> _logger;
    private readonly HttpClient _myClient;
    public DataUtil
        (
        IConfiguration config,
        ILogger<DataUtil> logger,
        HttpClient myClient
        )
    {
        _config = config;
        _logger = logger;
        _myClient = myClient;
    }
    public CustomerDetail GetCustomerDetail(string userName)
    {
        var responseResults = new CustomerDetail();
        _logger.LogError($"responseResults: " + responseResults);
        try
        {
            string custAccountNoUrl = _config.GetSection("Endpoints").GetValue<string>("custAccountDetailUrl") + userName;
            _myClient.DefaultRequestHeaders.Accept.Clear();
            _myClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            HttpResponseMessage response = _myClient.GetAsync(custAccountNoUrl).Result;
            if (response.IsSuccessStatusCode)
            {
                var stringResult = response.Content.ReadAsStringAsync().Result;
                responseResults = JsonConvert.DeserializeObject<CustomerDetail>(stringResult);
            }
        }
        catch (Exception ex)
        {
            _logger.LogError($"An Error occured " + ex.ToString());
        }
        return responseResults;
    }
}

I have these Auth DTOs:

public class UserDto
{
   public string Id { get; set; }
   public string FirstName { get; set; }
   public string Lastname { get; set; }
   public string Email { get; set; }
   public string UserName { get; set; }
   public DateTime LastLogin { get; set; }
}

public class LoginRequestDto
{
   [Required(ErrorMessage = "The username is required!")]
   public string UserName { get; set; }

   [Required(ErrorMessage = "The password is required!")]
    public string Password { get; set; }
}

public class LoginResponseDto
{
   public string JwtToken { get; set; }
   public UserDto User { get; set; }
   public DateTime Expires { get; set; }
}

public class RegistrationRequestDto
{
   public string UserName { get; set; }
   public string Email { get; set; }
   public string Password { get; set; }
   public string FirstName { get; set; }
   public string LastName { get; set; }
}

Model:

public class AppUser : IdentityUser
{
   public string FirstName { get; set; }
   public string LastName { get; set; }
   public DateTime LastLogin { get; set; }
}

And now the AuthService.

IAuthService:

public interface IAuthService
{
    Task<GenericResponseDto<object>> LoginUser(LoginRequestDto request);
    Task<GenericResponseDto<UserDto>> CreateUserAsync(RegistrationRequestDto requestDto);
}

AuthService:

   private async Task<GenericResponseDto<UserDto>> CreateUserAsync(RegistrationRequestDto requestDto)
    {
        var response = new GenericResponseDto<UserDto>();
        var existingUser = await _userManager.FindByNameAsync(requestDto.UserName);
        if (existingUser == null)
        {
            var userDetail = _dataUtil.GetCustomerDetail(requestDto.UserName);
             var user = new AppUser()
            {
                UserName = userDetail.UserName.ToLower().Trim(),
                Email = userDetail.EmailAddress.Trim().ToLower(),
                FirstName = userDetail.FirstName.Trim(),
                LastName = userDetail.LastName.Trim(),
                CreatedAt = DateTime.Now
            };
            user.SecurityStamp = Guid.NewGuid().ToString();
            var result = await _userManager.CreateAsync(user, "Adminpass1");

           if (!result.Succeeded)
            {
                var error = string.Join<IdentityError>(", ", result.Errors.ToArray());
                response.Error = new ErrorResponseDto { ErrorCode = 500, Message = "Failed to create user because of the following errors: " + error };
            }
            else
            {
                response.StatusCode = 200;
                response.Result = _mapper.Map<UserDto>(user);
            }

       } else
        {
            response.Error = new ErrorResponseDto { ErrorCode = 400, Message = "This email is already registered!" };
            response.StatusCode = 400;
        }
       return response;
    }

    public async Task<GenericResponseDto<object>> LoginUser(LoginRequestDto request)
    {
        var user = await _userManager.FindByNameAsync(request.UserName);
        var response = new GenericResponseDto<object>();

        if (user != null && await _userManager.CheckPasswordAsync(user, request.Password))
        {
            var roles = await _userManager.GetRolesAsync(user);
            var authClaims = new List<Claim>
            {
                new Claim(ClaimTypes.Name, user.UserName),
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
            };

           foreach (var userRole in roles)
            {
                authClaims.Add(new Claim(ClaimTypes.Role, userRole));
            }

           var authSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["JWT:Secret"]));
            var token = new JwtSecurityToken(
                issuer: _configuration["JWT:ValidIssuer"],
                audience: _configuration["JWT:ValidAudience"],
                expires: DateTime.Now.AddHours(3),
                claims: authClaims,
                signingCredentials: new SigningCredentials(authSigningKey, SecurityAlgorithms.HmacSha256)
            );

           response.Result = new
            {
                token = new JwtSecurityTokenHandler().WriteToken(token),
                user = _mapper.Map<UserDto>(user),
                expires = token.ValidTo
            };
            response.StatusCode = 200;

           user.LastLogin = DateTime.Now;

           try
            {
                await _context.SaveChangesAsync();
            }catch(Exception ex)
            {
                response.Error = new ErrorResponseDto() { ErrorCode = 500, Message = ex.Message };
            }

            return response;
        }

       response.StatusCode = 400;
        response.Error = new ErrorResponseDto { ErrorCode = 400, Message = "Invalid email or password!" };

       return response;
    }

In the application, users are not allowed to register manually.

So far, I have created the LoginUser and CreateUserAsync methods.

What I want to achieve is that, when the user tries to login the application checks if username already exists. If yes, it logs in, if no it checks from the external API using UserName as parameter, gets the user data, register the user using CreateUserAsync. Then automatically re-login the user.

How do I achieve this?

NOTE: I am using IdentityDB and EntityFramework

Thanks


问:
Individual routes for cypress testing in angular 14
Routes for cypress testing need to be configure in testing by using  individual environments one for production and other one is for testing. we created two routes path in (app-routing.module.ts).

I need solution for running cypress testing in individual routes without providing Authguard.
if we run the testing it should take particular routes in (app-routing.module.ts) for cypress testing.


问:
Cant auth with password via matrix-js-sdk
I try to build a messenger with React native on Matrix protocol. But i cant sign in user with username and password

I'm trying to use this:

```<code>import sdk from 'matrix-js-sdk';

const matrixClient = sdk.createClient({
  baseUrl: 'https://matrix.org',
});

export const authUser = ({
  user,
  password,
}: {
  user: string;
  password: string;
}) => {
  matrixClient
    .loginWithPassword(user, password)
    .then(response => {
      console.log(response.access_token);
    });
};
</code>```

Problem is that matrix sdk add slash on the end of url:

```<code>curl -v -X POST 'https://matrix.org/_matrix/client/r0/login/?' -H 'accept: application/json' -H 'Accept-Encoding: gzip' -H 'Connection: Keep-Alive' -H 'Content-Length: 72' -H 'Content-Type: application/json' -H 'Host: matrix.org' -H 'User-Agent: okhttp/4.9.2' -d $'{"type":"m.login.password","user":"example_user","password":"example_password"}'

Response error: {"errcode":"M_UNRECOGNIZED","error":"Unrecognized request"}
</code>```

But when i use axios and use url without "/" on the end i have 200 response

```<code>curl -v -X POST 'https://matrix.org/_matrix/client/r0/login' -H 'accept: application/json, text/plain, */*' -H 'Accept-Encoding: gzip' -H 'Connection: Keep-Alive' -H 'Content-Length: 72' -H 'Content-Type: application/json' -H 'Host: matrix.org' -H 'User-Agent: okhttp/4.9.2' -d $'{"type":"m.login.password","password":"example_password","user":"example_user"}'
</code>```

Does anyone work with this SDK, how you use it?

Body:
I try to build a messenger with React native on Matrix protocol. But i cant sign in user with username and password

I'm trying to use this:

import sdk from 'matrix-js-sdk';

const matrixClient = sdk.createClient({
  baseUrl: 'https://matrix.org',
});

export const authUser = ({
  user,
  password,
}: {
  user: string;
  password: string;
}) => {
  matrixClient
    .loginWithPassword(user, password)
    .then(response => {
      console.log(response.access_token);
    });
};

Problem is that matrix sdk add slash on the end of url:

curl -v -X POST 'https://matrix.org/_matrix/client/r0/login/?' -H 'accept: application/json' -H 'Accept-Encoding: gzip' -H 'Connection: Keep-Alive' -H 'Content-Length: 72' -H 'Content-Type: application/json' -H 'Host: matrix.org' -H 'User-Agent: okhttp/4.9.2' -d $'{"type":"m.login.password","user":"example_user","password":"example_password"}'

Response error: {"errcode":"M_UNRECOGNIZED","error":"Unrecognized request"}

But when i use axios and use url without "/" on the end i have 200 response

curl -v -X POST 'https://matrix.org/_matrix/client/r0/login' -H 'accept: application/json, text/plain, */*' -H 'Accept-Encoding: gzip' -H 'Connection: Keep-Alive' -H 'Content-Length: 72' -H 'Content-Type: application/json' -H 'Host: matrix.org' -H 'User-Agent: okhttp/4.9.2' -d $'{"type":"m.login.password","password":"example_password","user":"example_user"}'

Does anyone work with this SDK, how you use it?