问:
Symfony 6 json_login don't authenticate user
I have running a simple symfony/skeleton.

Basically I followed the documentation on "json_login", however Symfony does not authenticate the user when the login route is called. I test via Thunder Client in VSC.

I can call the /login route method, but the user object is basically NULL. In the meantime I have also tried to use my own authenticator, however this has not brought me any further in all variations. I have first tested with Symfony 6.1., last on version 6.2..

I would be very grateful for a tip or a link to a working tutorial. Thanks

I have already created a user entity via make:user which has the following structure:

```<code>namespace App\Entity;

use App\Repository\UserRepository;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface;
use Symfony\Component\Security\Core\User\UserInterface;

#[ORM\Entity(repositoryClass: UserRepository::class)]
class User implements UserInterface, PasswordAuthenticatedUserInterface
{
    #[ORM\Id]
    #[ORM\GeneratedValue]
    #[ORM\Column]
    private ?int $id = null;

    #[ORM\Column(length: 180, unique: true)]
    private ?string $email = null;

    #[ORM\Column]
    private array $roles = [];

    /**
     * @var string The hashed password
     */
    #[ORM\Column]
    private ?string $password = null;

    public function getId(): ?int
    {
        return $this->id;
    }

    public function getEmail(): ?string
    {
        return $this->email;
    }

    public function setEmail(string $email): self
    {
        $this->email = $email;

        return $this;
    }

    /**
     * A visual identifier that represents this user.
     *
     * @see UserInterface
     */
    public function getUserIdentifier(): string
    {
        return (string) $this->email;
    }

    /**
     * @see UserInterface
     */
    public function getRoles(): array
    {
        $roles = $this->roles;
        // guarantee every user at least has ROLE_USER
        $roles[] = 'ROLE_USER';

        return array_unique($roles);
    }

    public function setRoles(array $roles): self
    {
        $this->roles = $roles;

        return $this;
    }

    /**
     * @see PasswordAuthenticatedUserInterface
     */
    public function getPassword(): string
    {
        return $this->password;
    }

    public function setPassword(string $password): self
    {
        $this->password = $password;

        return $this;
    }

    /**
     * @see UserInterface
     */
    public function eraseCredentials()
    {
        // If you store any temporary, sensitive data on the user, clear it here
        // $this->plainPassword = null;
    }
}

</code>```

Then I created a controller for the /login and /logout routes with the following structure:

```<code>namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use App\Entity\User;
use Symfony\Component\Security\Http\Attribute\CurrentUser;

class UserLoginController extends AbstractController
{
    #[Route('/login', name: 'app_login')]
    public function index(#[CurrentUser] ?User $user): Response
    {
        if (null === $user) {
            return $this->json([
                'message' => 'missing credentials',
            ], Response::HTTP_UNAUTHORIZED);
        }

        return $this->json([
            'message' => 'Welcome to your new controller!',
            'path' => 'src/Controller/ApiLoginController.php',
            'user' => $user->getUserIdentifier()
        ]);
    }
}
</code>```

And my configuration for it looks like this:

```<code>security:
  password_hashers:
    Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface: "auto"
  providers:
    app_user_provider:
      entity:
        class: App\Entity\User
        property: email
  firewalls:
    dev:
      pattern: ^/(_(profiler|wdt)|css|images|js)/
      security: false
    main:
      json_login:
        check_path: /app_login
        username_path: email
        password_path: password
      lazy: true
      provider: app_user_provider
      #custom_authenticator: App\Security\UserAuthenticator

  access_control:
    # - { path: ^/admin, roles: ROLE_ADMIN }
    # - { path: ^/profile, roles: ROLE_USER }

</code>```

Body:
I have running a simple symfony/skeleton.

Basically I followed the documentation on "json_login", however Symfony does not authenticate the user when the login route is called. I test via Thunder Client in VSC.

I can call the /login route method, but the user object is basically NULL. In the meantime I have also tried to use my own authenticator, however this has not brought me any further in all variations. I have first tested with Symfony 6.1., last on version 6.2..

I would be very grateful for a tip or a link to a working tutorial. Thanks

I have already created a user entity via make:user which has the following structure:

namespace App\Entity;

use App\Repository\UserRepository;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface;
use Symfony\Component\Security\Core\User\UserInterface;

#[ORM\Entity(repositoryClass: UserRepository::class)]
class User implements UserInterface, PasswordAuthenticatedUserInterface
{
    #[ORM\Id]
    #[ORM\GeneratedValue]
    #[ORM\Column]
    private ?int $id = null;

    #[ORM\Column(length: 180, unique: true)]
    private ?string $email = null;

    #[ORM\Column]
    private array $roles = [];

    /**
     * @var string The hashed password
     */
    #[ORM\Column]
    private ?string $password = null;

    public function getId(): ?int
    {
        return $this->id;
    }

    public function getEmail(): ?string
    {
        return $this->email;
    }

    public function setEmail(string $email): self
    {
        $this->email = $email;

        return $this;
    }

    /**
     * A visual identifier that represents this user.
     *
     * @see UserInterface
     */
    public function getUserIdentifier(): string
    {
        return (string) $this->email;
    }

    /**
     * @see UserInterface
     */
    public function getRoles(): array
    {
        $roles = $this->roles;
        // guarantee every user at least has ROLE_USER
        $roles[] = 'ROLE_USER';

        return array_unique($roles);
    }

    public function setRoles(array $roles): self
    {
        $this->roles = $roles;

        return $this;
    }

    /**
     * @see PasswordAuthenticatedUserInterface
     */
    public function getPassword(): string
    {
        return $this->password;
    }

    public function setPassword(string $password): self
    {
        $this->password = $password;

        return $this;
    }

    /**
     * @see UserInterface
     */
    public function eraseCredentials()
    {
        // If you store any temporary, sensitive data on the user, clear it here
        // $this->plainPassword = null;
    }
}

Then I created a controller for the /login and /logout routes with the following structure:

namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use App\Entity\User;
use Symfony\Component\Security\Http\Attribute\CurrentUser;

class UserLoginController extends AbstractController
{
    #[Route('/login', name: 'app_login')]
    public function index(#[CurrentUser] ?User $user): Response
    {
        if (null === $user) {
            return $this->json([
                'message' => 'missing credentials',
            ], Response::HTTP_UNAUTHORIZED);
        }

        return $this->json([
            'message' => 'Welcome to your new controller!',
            'path' => 'src/Controller/ApiLoginController.php',
            'user' => $user->getUserIdentifier()
        ]);
    }
}

And my configuration for it looks like this:

security:
  password_hashers:
    Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface: "auto"
  providers:
    app_user_provider:
      entity:
        class: App\Entity\User
        property: email
  firewalls:
    dev:
      pattern: ^/(_(profiler|wdt)|css|images|js)/
      security: false
    main:
      json_login:
        check_path: /app_login
        username_path: email
        password_path: password
      lazy: true
      provider: app_user_provider
      #custom_authenticator: App\Security\UserAuthenticator

  access_control:
    # - { path: ^/admin, roles: ROLE_ADMIN }
    # - { path: ^/profile, roles: ROLE_USER }


来源: stackexchange

问:
Where to find specification of the jvet/HM and/or the x265 H.265/HEVC encoders?
I'm interested in implementations of H.265/HEVC encoders, which can be used in practice. Since the H.265/HEVC standard only defines the decoder, finding good syntax elements is the job of the encoder. However, I guess finding the optimal syntax elements is infeasible, and thus, I assume that it is up to the designer of the encoder to develop Heuristics in order to determine good enough syntax elements within a reasonable time.

To get an idea how such Heuristics could look like, I had a look at two open source encoders:

jvet/HM: https://vcgit.hhi.fraunhofer.de/jvet/HM

x265 HEVC Encoder: https://bitbucket.org/multicoreware/x265_git/src/master/

However, I cannot find any document that is specifying either of both encoders. By just looking at the source code, it is very hard for me to understand how the Heuristics work.

Does by chance anyone know where I can find these specifications? And/or does anyone know a reasonable implementation of an HEVC encoder with a proper specification?

Thanks a lot!

[I had a look at the repositories jvet/HM (https://vcgit.hhi.fraunhofer.de/jvet/HM) and x265 HEVC Encoder (https://bitbucket.org/multicoreware/x265_git/src/master/) but could not find a document that is specifying the used algorithms. I tried to find other open source encoders but was not successful.]

ContentLicense: CC BY-SA 4.0


问:
Is it possible to have a step tracking system in Oracle Apex
I was wondering if it was possible to have a step tracking system in Oracle Apex for a project or what the closest thing would be. I know there is the possibility of a map which you can choose which data is displayed but not sure if that would be the best thing for it.

The idea is that people within a team at my organisation will track steps and upload them to the app to see who's got the most steps individually and within a team. Is there a more interactive fun way of showing it than just a bar chart for example. The original idea was to convert the steps into miles and show how far each person has walked, for example from one office in the UK to one in Italy lets say, but I know that the features aren't able to have something as specific as that to show.


问:
build failled on Netlify, but work on Gatsby Cloud
I have something weird happens with my build on Netlify.
I have two Gatsby sites in Node 18, Gatsby 5 just updated from Node 16 and Gatsby 4.

The both are deploying on Netlify and Gatsby Cloud. They both have a good deployment on Gatsby Cloud, but on Netlify one is failed.
Before the migration to Gatby 5, that that's work very well to deploy on both platform.

I found this difference in the log, with the one work well, and the uggly work bad !
the failed happens after this call

```<code>10:44:36 AM: Using ruby version 2.7.2
10:44:36 AM: Using PHP version 8.0
10:44:36 AM: No npm workspaces detected
10:44:36 AM: Started restoring cached node modules
10:44:36 AM: Finished restoring cached node modules
10:44:37 AM: Installing NPM modules using NPM version 8.19.2
10:44:38 AM: npm ERR! code ERESOLVE
10:44:38 AM: npm ERR! ERESOLVE could not resolve
</code>```

but the other who is deployed well, don't try to install the NPM modules

```<code>10:14:47 PM: Using ruby version 2.7.1
10:14:47 PM: Using PHP version 8.0
10:14:47 PM: No npm workspaces detected
10:14:47 PM: Started restoring cached node modules
10:14:47 PM: Finished restoring cached node modules
10:14:47 PM: Started restoring cached go cache
10:14:47 PM: Finished restoring cached go cache
</code>```

I try to change the NPM version to 8.19.3, but I failed to do that. I don't find a solution to say to Netlify don't use 8.19.2 or simply don't use NPM like in deployment who work well.
There is any solution to set something everywhere to use a specific version of npm or use something like --legacy-peer-deps I don't find on internet how to set something like that to try those solutions.

Sorry If my explication is not really clear, but I'm not an expert in deployment and npm. I hope any people have i track to follow a solution.

Body:
I have something weird happens with my build on Netlify.
I have two Gatsby sites in Node 18, Gatsby 5 just updated from Node 16 and Gatsby 4.

The both are deploying on Netlify and Gatsby Cloud. They both have a good deployment on Gatsby Cloud, but on Netlify one is failed.
Before the migration to Gatby 5, that that's work very well to deploy on both platform.

I found this difference in the log, with the one work well, and the uggly work bad !
the failed happens after this call

10:44:36 AM: Using ruby version 2.7.2
10:44:36 AM: Using PHP version 8.0
10:44:36 AM: No npm workspaces detected
10:44:36 AM: Started restoring cached node modules
10:44:36 AM: Finished restoring cached node modules
10:44:37 AM: Installing NPM modules using NPM version 8.19.2
10:44:38 AM: npm ERR! code ERESOLVE
10:44:38 AM: npm ERR! ERESOLVE could not resolve

but the other who is deployed well, don't try to install the NPM modules

10:14:47 PM: Using ruby version 2.7.1
10:14:47 PM: Using PHP version 8.0
10:14:47 PM: No npm workspaces detected
10:14:47 PM: Started restoring cached node modules
10:14:47 PM: Finished restoring cached node modules
10:14:47 PM: Started restoring cached go cache
10:14:47 PM: Finished restoring cached go cache

I try to change the NPM version to 8.19.3, but I failed to do that. I don't find a solution to say to Netlify don't use 8.19.2 or simply don't use NPM like in deployment who work well.
There is any solution to set something everywhere to use a specific version of npm or use something like --legacy-peer-deps I don't find on internet how to set something like that to try those solutions.

Sorry If my explication is not really clear, but I'm not an expert in deployment and npm. I hope any people have i track to follow a solution.


问:
2 -opt algorithm for improve TSP routes in python
Im trying to solve my TSP using 2-opt algorithm but i get the error message down below.

```<code>     save=nodei[newtour[i-1]+2]+nodej[newtour[j]+2] - (nodej[newtour[i-1]+2]+nodei[newtour[j]+2])

IndexError: list index out of range
</code>```

Here is my tour:

```<code>newtour=[0, 15, 12, 11, 13, 19, 20, 18, 17, 3, 1, 2, 6, 21]

</code>```

And my 2-opt algorithm:

```<code>def tour_length(tour):
    "The total of distances between each pair of consecutive cities in the tour."
    return sum(distance(points,tour[i], tour[i-1])
               for i in range(len(tour)))

#2-OPT
def twoOptSwap(newtour,i,j):
    t=newtour[i:j+1];
    t.reverse();
    newtour[i:j+1]=t

def twoOpt(newtour):
    cost=tour_length(newtour)

    def inner():
        nonlocal cost
        for i in range(1,len(newtour)-2):
            nodei=points[newtour[i]]
            for j in range(i+1,len(newtour)-1):
                nodej=points[newtour[j]]
                save=nodei[newtour[i-1]+2]+nodej[newtour[j+1]+2] -
                                                (nodej[newtour[i- 1]+2]+nodei[newtour[j+1]+2])
                if save>0:
                    twoOptSwap(newtour,i,j)

                    cost-=save
                    print('exchanging {}-{},{}-{} with {}-{},{}-{} => save={} => cost1: {}'.format(
                            newtour[i-1],newtour[i],newtour[j],newtour[j+1],newtour[i-1],newtour[j],newtour[i],newtour[j+1],save,cost))
                    return False
        return True

    while True:
        if inner():
            break
</code>```

points list has node longitudes and latitudes as x,y columns.

There is an error def twoOpt save equation row but i couldnt find.

I would be grateful if anyone can help.

Body:
Im trying to solve my TSP using 2-opt algorithm but i get the error message down below.

     save=nodei[newtour[i-1]+2]+nodej[newtour[j]+2] - (nodej[newtour[i-1]+2]+nodei[newtour[j]+2])

IndexError: list index out of range

Here is my tour:

newtour=[0, 15, 12, 11, 13, 19, 20, 18, 17, 3, 1, 2, 6, 21]

And my 2-opt algorithm:

def tour_length(tour):
    "The total of distances between each pair of consecutive cities in the tour."
    return sum(distance(points,tour[i], tour[i-1])
               for i in range(len(tour)))

#2-OPT
def twoOptSwap(newtour,i,j):
    t=newtour[i:j+1];
    t.reverse();
    newtour[i:j+1]=t

def twoOpt(newtour):
    cost=tour_length(newtour)

    def inner():
        nonlocal cost
        for i in range(1,len(newtour)-2):
            nodei=points[newtour[i]]
            for j in range(i+1,len(newtour)-1):
                nodej=points[newtour[j]]
                save=nodei[newtour[i-1]+2]+nodej[newtour[j+1]+2] -
                                                (nodej[newtour[i- 1]+2]+nodei[newtour[j+1]+2])
                if save>0:
                    twoOptSwap(newtour,i,j)

                    cost-=save
                    print('exchanging {}-{},{}-{} with {}-{},{}-{} => save={} => cost1: {}'.format(
                            newtour[i-1],newtour[i],newtour[j],newtour[j+1],newtour[i-1],newtour[j],newtour[i],newtour[j+1],save,cost))
                    return False
        return True

    while True:
        if inner():
            break

points list has node longitudes and latitudes as x,y columns.

There is an error def twoOpt save equation row but i couldnt find.

I would be grateful if anyone can help.


问:
ERROR: Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of "text/html"
I am running Reactjs with vite, When I am trying to start my app with network IP I am getting the following error

I am getting the following error when I am trying to start the app with host: localhost

index.html

```<code><!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <link rel="icon" type="image/svg+xml" href="/favicon.ico" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Asset Scanner</title>
        <script
  src="https://cdn.socket.io/4.2.0/socket.io.min.js"
  integrity="sha384-PiBR5S00EtOj2Lto9Uu81cmoyZqR57XcOna1oAuVuIEjzj0wpqDVfD0JA9eXlRsj"
  crossorigin="anonymous"
></script>
  </head>
  <body>
    <div id="root"></div>
    <div id="modals"></div>
    <script type="module" src="/src/main.jsx"></script>
  </body>
</html>
</code>```

src/main.jsx

```<code>import React from 'react'
import ReactDOM from 'react-dom'

import App from '@@/App'
import { loadCSSVariables } from './common/utils/cssVariables'

loadCSSVariables().then(() => {
    ReactDOM.render(<App />, document.getElementById('root'))
})
</code>```

Body:
I am running Reactjs with vite, When I am trying to start my app with network IP I am getting the following error

I am getting the following error when I am trying to start the app with host: localhost

index.html

<!DOCTYPE html>

        <meta charset="UTF-8" />
        <link rel="icon" type="image/svg+xml" href="/favicon.ico" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Asset Scanner</title>

src/main.jsx

import React from 'react'
import ReactDOM from 'react-dom'

import App from '@@/App'
import { loadCSSVariables } from './common/utils/cssVariables'

loadCSSVariables().then(() => {
    ReactDOM.render(<App />, document.getElementById('root'))
})


问:
How to fetch post (show if followType is free hide premium posts) of my following using aggreate mongodb Nestjs?
My USER Model:
This is My user Schema:

```<code>import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import mongoose, { Document } from 'mongoose';

export type UserDocument = User & Document;

export enum FollowerType {
  SIMPS = 'SIMPS',
  FOLLIES = 'FOLLIES',
}

@Schema({ timestamps: true })
export class User {
  @Prop({
    type: String,
    trim: true,
    unique: true,
    required: true,
    lowercase: true,
  })
  username: string;

  @Prop({
    type: String,
    trim: true,
    unique: true,
    required: true,
    lowercase: true,
  })
  email: string;

  @Prop({
    type: String,
    required: true,
  })
  password: string;

  @Prop([
    {
      type: mongoose.Schema.Types.ObjectId,
      ref: User.name,
      unique: true,
    },
  ])
  userReportedBy?: User[];

  @Prop([
    {
      followedType: {
        type: String,
        enum: FollowerType,
      },

      user: { type: mongoose.Schema.Types.ObjectId, ref: User.name },
    },
  ])
  following: [
    {
      followedType: string;
      user: User;
    },
  ];

  @Prop([
    {
      followedType: {
        type: String,
        enum: FollowerType,
      },

      user: { type: mongoose.Schema.Types.ObjectId, ref: User.name },
    },
  ])
  followedBy: [
    {
      followedType: string;
      user: User;
    },
  ];

  @Prop([
    {
      type: mongoose.Schema.Types.ObjectId,
      ref: User.name,
      unique: true,
    },
  ])
  blockedBy: User[];

  @Prop({ type: String })
  profilePic?: string;

  @Prop({ type: Boolean, default: false })
  isUserSuspended: boolean;

  @Prop({ type: Boolean, default: false, required: true })
  verified: boolean;

  @Prop({ type: Boolean, default: false, required: true })
  isDeleted: boolean;

  @Prop({ type: Date, require: false })
  deletedAt: Date;
}

export const UserSchema = SchemaFactory.createForClass(User);

</code>```

POST MODEL:

This is My Post Model

```<code>/* eslint-disable prettier/prettier */
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import mongoose, { Document } from 'mongoose';
import { User } from './User.model';

export type PostDocument = Posts & Document;

@Schema({ timestamps: true })
export class Posts {
  @Prop({
    type: String,
  })
  media: string;

  @Prop({
    type: String,
    enum: ['video', 'audio', 'image'],
  })
  mediaType: string;

  @Prop({
    type: String,
  })
  description: string;

  @Prop({ type: Boolean, default: false, required: true })
  isPremium: boolean;

  @Prop({
    type: mongoose.Schema.Types.ObjectId,
    ref: User.name,
  })
  userId: User;

  @Prop([
    {
      type: mongoose.Schema.Types.ObjectId,
      ref: User.name,
      unique: true,
    },
  ])
  userTagged?: User[];

  @Prop([
    {
      type: mongoose.Schema.Types.ObjectId,
      ref: User.name,
    },
  ])
  userLike?: User[];

  @Prop([
    {
      type: mongoose.Schema.Types.ObjectId,
      ref: User.name,
    },
  ])
  userDislike: User[];

  @Prop([
    {
      type: mongoose.Schema.Types.ObjectId,
      ref: User.name,
    },
  ])
  userSeen: User[];

  @Prop([
    {
      type: mongoose.Schema.Types.ObjectId,
      ref: User.name,
    },
  ])
  userReported: User[];

  @Prop({ type: Boolean, default: false })
  ispostSuspended: boolean;

  @Prop({ type: Date, required: false })
  deletedAt?: Date;
}

export const PostSchema = SchemaFactory.createForClass(Posts);

</code>```

Trying to fetch Posts of my following users according to type by checking whether user is blocked or not.
Expected Result

Result:[
{
userId:'dsjfksdkjfasd7dfsdf',
username:'test123',
posts:[
{
media:'htttps://djkfskjdf.com',
postId:'sdhfkjdfkhkjfd',
}
]
}
]

Body:
My USER Model:
This is My user Schema:

import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import mongoose, { Document } from 'mongoose';

export type UserDocument = User & Document;

export enum FollowerType {
  SIMPS = 'SIMPS',
  FOLLIES = 'FOLLIES',
}

@Schema({ timestamps: true })
export class User {
  @Prop({
    type: String,
    trim: true,
    unique: true,
    required: true,
    lowercase: true,
  })
  username: string;

  @Prop({
    type: String,
    trim: true,
    unique: true,
    required: true,
    lowercase: true,
  })
  email: string;

  @Prop({
    type: String,
    required: true,
  })
  password: string;

  @Prop([
    {
      type: mongoose.Schema.Types.ObjectId,
      ref: User.name,
      unique: true,
    },
  ])
  userReportedBy?: User[];

  @Prop([
    {
      followedType: {
        type: String,
        enum: FollowerType,
      },

      user: { type: mongoose.Schema.Types.ObjectId, ref: User.name },
    },
  ])
  following: [
    {
      followedType: string;
      user: User;
    },
  ];

  @Prop([
    {
      followedType: {
        type: String,
        enum: FollowerType,
      },

      user: { type: mongoose.Schema.Types.ObjectId, ref: User.name },
    },
  ])
  followedBy: [
    {
      followedType: string;
      user: User;
    },
  ];

  @Prop([
    {
      type: mongoose.Schema.Types.ObjectId,
      ref: User.name,
      unique: true,
    },
  ])
  blockedBy: User[];

  @Prop({ type: String })
  profilePic?: string;

  @Prop({ type: Boolean, default: false })
  isUserSuspended: boolean;

  @Prop({ type: Boolean, default: false, required: true })
  verified: boolean;

  @Prop({ type: Boolean, default: false, required: true })
  isDeleted: boolean;

  @Prop({ type: Date, require: false })
  deletedAt: Date;
}

export const UserSchema = SchemaFactory.createForClass(User);

POST MODEL:

This is My Post Model

/* eslint-disable prettier/prettier */
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import mongoose, { Document } from 'mongoose';
import { User } from './User.model';

export type PostDocument = Posts & Document;

@Schema({ timestamps: true })
export class Posts {
  @Prop({
    type: String,
  })
  media: string;

  @Prop({
    type: String,
    enum: ['video', 'audio', 'image'],
  })
  mediaType: string;

  @Prop({
    type: String,
  })
  description: string;

  @Prop({ type: Boolean, default: false, required: true })
  isPremium: boolean;

  @Prop({
    type: mongoose.Schema.Types.ObjectId,
    ref: User.name,
  })
  userId: User;

  @Prop([
    {
      type: mongoose.Schema.Types.ObjectId,
      ref: User.name,
      unique: true,
    },
  ])
  userTagged?: User[];

  @Prop([
    {
      type: mongoose.Schema.Types.ObjectId,
      ref: User.name,
    },
  ])
  userLike?: User[];

  @Prop([
    {
      type: mongoose.Schema.Types.ObjectId,
      ref: User.name,
    },
  ])
  userDislike: User[];

  @Prop([
    {
      type: mongoose.Schema.Types.ObjectId,
      ref: User.name,
    },
  ])
  userSeen: User[];

  @Prop([
    {
      type: mongoose.Schema.Types.ObjectId,
      ref: User.name,
    },
  ])
  userReported: User[];

  @Prop({ type: Boolean, default: false })
  ispostSuspended: boolean;

  @Prop({ type: Date, required: false })
  deletedAt?: Date;
}

export const PostSchema = SchemaFactory.createForClass(Posts);

Trying to fetch Posts of my following users according to type by checking whether user is blocked or not.
Expected Result

Result:[
{
userId:'dsjfksdkjfasd7dfsdf',
username:'test123',
posts:[
{
media:'htttps://djkfskjdf.com',
postId:'sdhfkjdfkhkjfd',
}
]
}
]


问:
Is it possible to use AspNetIdentity with Duende IdentityServer Backend for Frontend (BFF) approach?
So lately I am trying to setup my Blazor Webassembly (Core hosted) application with Duende IdentityServer. Although most information is well documented, I can't seem to find any examples on how to integrate AspNetIdentity with Blazor WASM.

The tutorial of using Identityserver with Blazor WASM follows the use of the 'Backend for Frontend (BFF)' approach, so I did that as well. But when I look at the 'Using ASP.NET Core Identity' tutorial, all examples use the

```<code>.AddIdentityServer(options =>
    {
        // ...
    })
</code>```

approach instead of the

```<code>.AddBff(options => {

    })
</code>```

approach.

So the question is, is it even possible to use AspNetIdentity with BFF, if so, where do I add the configuration in my startup? Any pointers to a tutorial or example of this approach would also be much appreciated.

Body:
So lately I am trying to setup my Blazor Webassembly (Core hosted) application with Duende IdentityServer. Although most information is well documented, I can't seem to find any examples on how to integrate AspNetIdentity with Blazor WASM.

The tutorial of using Identityserver with Blazor WASM follows the use of the 'Backend for Frontend (BFF)' approach, so I did that as well. But when I look at the 'Using ASP.NET Core Identity' tutorial, all examples use the

.AddIdentityServer(options =>
    {
        // ...
    })

approach instead of the

.AddBff(options => {

    })

approach.

So the question is, is it even possible to use AspNetIdentity with BFF, if so, where do I add the configuration in my startup? Any pointers to a tutorial or example of this approach would also be much appreciated.


问:
Trend and Multilevel Model (intercept and slope and graph)
I am just a beginner to R and Statistics. Here are my questions:

I attempted to solve Q1, but I am not sure whether it is correct.  But for Q2, I attempted to try too, but I have no clue for that.

Q1. What is the trend of CES-D score across four waves? Whether the trends differ by gender and by age group.  Plot a graph indicating this?

Q2. Conduct a multilevel model to examine the baseline factors associated with the trend (intercept and slope) of CES-D score.

These are the column names:

Q1 Attempts

```<code># subset data
DataCleanedSelected <- H_CHARLS_D_DataCleaned[c("id", "ragender", "r1agey", "raeduc_c", "r1shlt",
                                     "r1dressa", "r1batha", "r1eata", "r1beda",
                                     "r1toilta", "r1urina", "r1cesd10", "r2cesd10",
                                     "r3cesd10", "r4cesd10", "h1rural")]

CESDSelected <- H_CHARLS_D_DataCleaned[c("id","ragender", "r1agey", "r1cesd10", "r2cesd10",
                                                "r3cesd10", "r4cesd10")]

#Check dataset
head(CESDSelected)
names(CESDSelected)

#Attach dataset
attach(CESDSelected)

#Data preparation - Wide format
head(CESDSelected)

# Gather columns x4 into long format
# Convert id and time into factor variables
CHARLS.format <- gather(CESDSelected, time, cesd,
                        r1cesd10:r4cesd10, factor_key = TRUE)
CHARLS.format

# | Summary statistics
CHARLS.format %>%
  group_by(time) %>%
  get_summary_stats(cesd, type = "mean_sd")

ind.anova <- aov(cesd ~ time, data=CHARLS.format)
summary(ind.anova)

rm.anova <- aov(cesd ~ time + Error(id/time),
                data = CHARLS.format)
summary(rm.anova)

# Visualise the Result#

time <- c("W1","W2","W3","W4")
mean.CESD <- c(mean(r1cesd10, na.rm = TRUE),mean(r2cesd10, na.rm = TRUE),
                 mean(r3cesd10, na.rm = TRUE),mean(r4cesd10, na.rm = TRUE))

se.CESD <- c(sd(r1cesd10, na.rm = TRUE), sd(r2cesd10, na.rm = TRUE),
             sd(r3cesd10, na.rm = TRUE),sd(r4cesd10,na.rm = TRUE))/sqrt(length(id))

CESD.means.frame <- data.frame(time,mean.CESD,se.CESD)
CESD.means.frame

dev.off()

ggplot(CESD.means.frame,aes(x=time,y=mean.CESD)) +
  geom_point(size=3)+
  geom_errorbar(aes(ymin=mean.CESD-se.CESD,
                    ymax=mean.CESD+se.CESD),width=.2)

contrasts(CHARLS.format$time) <- matrix(c(-3,-1,1,3,1,-1,
                                              -1,1,-1,3,-3,1), 4, 3)

rm.anova <- aov(cesd ~ time + Error(id/time),
                data=CHARLS.format,
                contrasts = contrasts(CHARLS.format$time))

summary(rm.anova,split=list(Time=list("Linear" =1,
                                      "Quadratic"=2,"Cubic" =3)))

# Visualisation#
CHARLS.format %>%
  group_by(time) %>%
  identify_outliers(cesd)

# Normality Assumption#
CHARLS.format%>%
  group_by(time) %>%
  shapiro_test(cesd)

res.aov <- anova_test(data = CHARLS.format, dv = cesd, wid = ID, within = time)
get_anova_table(res.aov)

##Post-hoc test -  pairwise comparisons##
pwc <- CHARLS.format %>%
  pairwise_t_test(
    cesd ~ time, paired = TRUE,
    p.adjust.method = "bonferroni"
  )
pwc

##Visualization: box plots with p-values##
pwc <- pwc %>% add_xy_position(x = "time")
bxp +
  stat_pvalue_manual(pwc) +
  labs(
    subtitle = get_test_label(res.aov, detailed = TRUE),
    caption = get_pwc_label(pwc)
  )
</code>```

Q2 Attempts

```<code>library(lme4)
library(lattice)
library(Matrix)

##Select those who are female
Female <- CHARLS.format[ragender =2, na.rm =False]
str(Female)
summary(Female)

names(CHARLS.format)

##Null hypothesis##
lmer(cesd ~ 1 + (1 | id), data=CHARLS.format)

##Fixed predictors - Gender - Random intercept##
lmer(cesd ~ ragender + (1 | id), data=CHARLS.format)
model.GenderIntercept <- lmer(cesd ~ ragender + (1 | id), data=CHARLS.format)
plot(model.GenderIntercept, main="Residual Plot of Gender Intercept")

##Fixed predictors - Age - Random intercept##
lmer(cesd ~ r1agey + (1 | id), data=CHARLS.format)
model.AgeIntercept <- lmer(cesd ~ r1agey + (1 | id), data=CHARLS.format)
plot(model.AgeIntercept, main="Residual Plot of Age Intercept")

##Random intercept, Random slope - Gender##
lmer(cesd ~ ragender + (ragender | id), data=CHARLS.format)
model.GenderSlope <- lmer(cesd ~ ragender + (ragender | id), data=CHARLS.format)
plot(model.GenderSlope, main="Residual Plot of Gender Slope")

##Random intercept, Random slope - Age##
lmer(cesd ~ r1agey + (r1agey | id), data=CHARLS.format)
model.AgeSlope <- lmer(cesd ~ r1agey + (r1agey | id), data=CHARLS.format)
plot(model.AgeSlope, main="Residual Plot of Age Slope")

##Random intercept, individual and group level predictors##
lmer(cesd ~ ragender + r1agey + (1 + ragender | id), data=CHARLS.format)
Model.IndiGrp <- lmer(cesd ~ ragender + r1agey + (1 + ragender | id), data=CHARLS.format)
plot(Model.IndiGrp, main="Random intercept, individual and group level predictors")

##Random intercept, cross-level interaction##
lmer(cesd ~ ragender * r1agey + (1 + ragender | id), data=CHARLS.format)
Model.RandomCross <- lmer(cesd ~ ragender + r1agey + (1 + ragender | id), data=CHARLS.format)
plot(Model.RandomCross, main="Random intercept, cross-level interaction")
</code>```

Body:
I am just a beginner to R and Statistics. Here are my questions:

I attempted to solve Q1, but I am not sure whether it is correct.  But for Q2, I attempted to try too, but I have no clue for that.

Q1. What is the trend of CES-D score across four waves? Whether the trends differ by gender and by age group.  Plot a graph indicating this?

Q2. Conduct a multilevel model to examine the baseline factors associated with the trend (intercept and slope) of CES-D score.

These are the column names:

Q1 Attempts

# subset data
DataCleanedSelected <- H_CHARLS_D_DataCleaned[c("id", "ragender", "r1agey", "raeduc_c", "r1shlt",
                                     "r1dressa", "r1batha", "r1eata", "r1beda",
                                     "r1toilta", "r1urina", "r1cesd10", "r2cesd10",
                                     "r3cesd10", "r4cesd10", "h1rural")]

CESDSelected <- H_CHARLS_D_DataCleaned[c("id","ragender", "r1agey", "r1cesd10", "r2cesd10",
                                                "r3cesd10", "r4cesd10")]

#Check dataset
head(CESDSelected)
names(CESDSelected)

#Attach dataset
attach(CESDSelected)

#Data preparation - Wide format
head(CESDSelected)

# Gather columns x4 into long format
# Convert id and time into factor variables
CHARLS.format <- gather(CESDSelected, time, cesd,
                        r1cesd10:r4cesd10, factor_key = TRUE)
CHARLS.format

# | Summary statistics
CHARLS.format %>%
  group_by(time) %>%
  get_summary_stats(cesd, type = "mean_sd")

ind.anova <- aov(cesd ~ time, data=CHARLS.format)
summary(ind.anova)

rm.anova <- aov(cesd ~ time + Error(id/time),
                data = CHARLS.format)
summary(rm.anova)

# Visualise the Result#

time <- c("W1","W2","W3","W4")
mean.CESD <- c(mean(r1cesd10, na.rm = TRUE),mean(r2cesd10, na.rm = TRUE),
                 mean(r3cesd10, na.rm = TRUE),mean(r4cesd10, na.rm = TRUE))

se.CESD <- c(sd(r1cesd10, na.rm = TRUE), sd(r2cesd10, na.rm = TRUE),
             sd(r3cesd10, na.rm = TRUE),sd(r4cesd10,na.rm = TRUE))/sqrt(length(id))

CESD.means.frame <- data.frame(time,mean.CESD,se.CESD)
CESD.means.frame

dev.off()

ggplot(CESD.means.frame,aes(x=time,y=mean.CESD)) +
  geom_point(size=3)+
  geom_errorbar(aes(ymin=mean.CESD-se.CESD,
                    ymax=mean.CESD+se.CESD),width=.2)

contrasts(CHARLS.format$time) <- matrix(c(-3,-1,1,3,1,-1,
                                              -1,1,-1,3,-3,1), 4, 3)

rm.anova <- aov(cesd ~ time + Error(id/time),
                data=CHARLS.format,
                contrasts = contrasts(CHARLS.format$time))

summary(rm.anova,split=list(Time=list("Linear" =1,
                                      "Quadratic"=2,"Cubic" =3)))

# Visualisation#
CHARLS.format %>%
  group_by(time) %>%
  identify_outliers(cesd)

# Normality Assumption#
CHARLS.format%>%
  group_by(time) %>%
  shapiro_test(cesd)

res.aov <- anova_test(data = CHARLS.format, dv = cesd, wid = ID, within = time)
get_anova_table(res.aov)

##Post-hoc test -  pairwise comparisons##
pwc <- CHARLS.format %>%
  pairwise_t_test(
    cesd ~ time, paired = TRUE,
    p.adjust.method = "bonferroni"
  )
pwc

##Visualization: box plots with p-values##
pwc <- pwc %>% add_xy_position(x = "time")
bxp +
  stat_pvalue_manual(pwc) +
  labs(
    subtitle = get_test_label(res.aov, detailed = TRUE),
    caption = get_pwc_label(pwc)
  )

Q2 Attempts

library(lme4)
library(lattice)
library(Matrix)

##Select those who are female
Female <- CHARLS.format[ragender =2, na.rm =False]
str(Female)
summary(Female)

names(CHARLS.format)

##Null hypothesis##
lmer(cesd ~ 1 + (1 | id), data=CHARLS.format)

##Fixed predictors - Gender - Random intercept##
lmer(cesd ~ ragender + (1 | id), data=CHARLS.format)
model.GenderIntercept <- lmer(cesd ~ ragender + (1 | id), data=CHARLS.format)
plot(model.GenderIntercept, main="Residual Plot of Gender Intercept")

##Fixed predictors - Age - Random intercept##
lmer(cesd ~ r1agey + (1 | id), data=CHARLS.format)
model.AgeIntercept <- lmer(cesd ~ r1agey + (1 | id), data=CHARLS.format)
plot(model.AgeIntercept, main="Residual Plot of Age Intercept")

##Random intercept, Random slope - Gender##
lmer(cesd ~ ragender + (ragender | id), data=CHARLS.format)
model.GenderSlope <- lmer(cesd ~ ragender + (ragender | id), data=CHARLS.format)
plot(model.GenderSlope, main="Residual Plot of Gender Slope")

##Random intercept, Random slope - Age##
lmer(cesd ~ r1agey + (r1agey | id), data=CHARLS.format)
model.AgeSlope <- lmer(cesd ~ r1agey + (r1agey | id), data=CHARLS.format)
plot(model.AgeSlope, main="Residual Plot of Age Slope")

##Random intercept, individual and group level predictors##
lmer(cesd ~ ragender + r1agey + (1 + ragender | id), data=CHARLS.format)
Model.IndiGrp <- lmer(cesd ~ ragender + r1agey + (1 + ragender | id), data=CHARLS.format)
plot(Model.IndiGrp, main="Random intercept, individual and group level predictors")

##Random intercept, cross-level interaction##
lmer(cesd ~ ragender * r1agey + (1 + ragender | id), data=CHARLS.format)
Model.RandomCross <- lmer(cesd ~ ragender + r1agey + (1 + ragender | id), data=CHARLS.format)
plot(Model.RandomCross, main="Random intercept, cross-level interaction")


问:
my wallet address is whitelisted. how i will get merkle proof for minting?
```<code>   const leaves = whitelistAddresses.map(addr => padBuffer(addr))
      const merkletree = new MerkleTree(leaves, keccak256, {sortPairs: true})
      console.log('merkletree', merkletree.toString())
      const rootHash = merkletree.getHexRoot()
      console.log("root hash", rootHash)
</code>```

I don't have whitelistAddresses...
I have only contractAddress, WalletAddress, roothash. is it posible to get merkleproof without knowing full whitelistAddresses array. or is any other way to get merkle proof without ask anybody?

I want to get merkle proof (bytes32 [])

Body:
   const leaves = whitelistAddresses.map(addr => padBuffer(addr))
      const merkletree = new MerkleTree(leaves, keccak256, {sortPairs: true})
      console.log('merkletree', merkletree.toString())
      const rootHash = merkletree.getHexRoot()
      console.log("root hash", rootHash)

I don't have whitelistAddresses...
I have only contractAddress, WalletAddress, roothash. is it posible to get merkleproof without knowing full whitelistAddresses array. or is any other way to get merkle proof without ask anybody?

I want to get merkle proof (bytes32 [])


问:
DataTable adding additional text to a data row when a criteria is met
I have a script that displays the status of device media players at locations using dataTables.
If one of the devices has no internet connection the name of the location blinks with a red background.
Is there a way I can add additional text to the location name saying "Offline". I am working with the code below which works perfectly apart from adding the additional text.

```<code>columns: [
  { data: 'DisplayDescription'},
  { data: 'MessageCount',"visible": false  },
],

if(data.MessageCount == 2 ) {
    $(row).find('td:eq(0)').addClass('WayFinderStatusTableOn HeaderStatusWayfinderRedTextBlink');
    $(row).attr('title', 'Display screen offline');

    $(row).find('td:eq(0)').on('click', function () {
        $('#open_offline_help').modal('show');
    });
}

    else if(data.DisplayMainBoard == 0 && data.RecordCount >= 1){
    $(row).find('td:eq(0)').addClass('RoomStatusTableOverrideOn') ;

}
</code>```

Thanks

Body:
I have a script that displays the status of device media players at locations using dataTables.
If one of the devices has no internet connection the name of the location blinks with a red background.
Is there a way I can add additional text to the location name saying "Offline". I am working with the code below which works perfectly apart from adding the additional text.

columns: [
  { data: 'DisplayDescription'},
  { data: 'MessageCount',"visible": false  },
],

if(data.MessageCount == 2 ) {
    $(row).find('td:eq(0)').addClass('WayFinderStatusTableOn HeaderStatusWayfinderRedTextBlink');
    $(row).attr('title', 'Display screen offline');

    $(row).find('td:eq(0)').on('click', function () {
        $('#open_offline_help').modal('show');
    });
}

    else if(data.DisplayMainBoard == 0 && data.RecordCount >= 1){
    $(row).find('td:eq(0)').addClass('RoomStatusTableOverrideOn') ;

}

Thanks


问:
unable to load nested object data in mongoose database properly
The issue I am facing is that even though I am able to load the data in the database but the desired result is different from what is being returned.

The issue is that whenever I am running for loop the qn variable is inserted twice but need it only once.

Please if someone can help me resolve this issue.

userProject.js

```<code>router.post('/notification/check/upload/survey' , async (req,res) => {

  //const taginsert = [];
  const mcq = [];
  //const newData = {};
  //const o = {};

  console.log(req.body);

  for(var i=0; i<=req.body.questions.length-1;i++) {
    //  newData = {
    //   qn: req.body.questions[i].qn
    // }
    for(var j=0; j<=req.body.questions[i].options.length-1;j++){
       const o =
        {
         qn: req.body.questions[i].qn,
        //{
            options: [{
            option: req.body.questions[i].options[j].option,
            totalValues: req.body.questions[i].options[j].totalValues
          }]
        }

     // newData.options = o;
    //  newData.push(o);

      mcq.push(o);
    }

  }

//mcq = newData;

const check = new userCampaignSurvey({
  userId: req.body.userId,
  status: 'Pending',
  notification_type:req.body.notification_type,
  questions: mcq
})

 check.save((err,p) => {
  if(err) {
    res.status(500).send(err);
  }
  res.status(201).send(p);
 })
})
</code>```

model.js

```<code> userId:
    {
        type: Number,
        required: true,
        trim: true
    },
    notification_id:
    {
        type: Number,
    },
    notification_type:
    {
        type: Number,
        required: true,

    },
    status:
    {
         type: String,
         required: true
    },

    questions: [
        {
            qn: {
            type: String,
            required: true
        },
        options: [
            {
                option: {
                    type: String
                },
                totalViews: {
                    type:Number
                }

             }
    ]
    },
    ],
    created_at:  {
    type: Date,
    required: true,
    default: Date.now(),
},

});
</code>```

result received

```<code>{
    "userId": 1,
    "notification_type": 1,
    "status": "Pending",
    "questions": [
        {
            "qn": "Which brand do you like better for buying shoes?",
            "options": [
                {
                    "option": "Adidas",
                    "_id": "639064c9ec215f2cd1b2b15d"
                }
            ],
            "_id": "639064c9ec215f2cd1b2b15c"
        },
        {
            "qn": "Which brand do you like better for buying shoes?",
            "options": [
                {
                    "option": "Reebok",
                    "_id": "639064c9ec215f2cd1b2b15f"
                }
            ],
            "_id": "639064c9ec215f2cd1b2b15e"
        }
    ],
    "created_at": "2022-12-07T10:02:48.442Z",
    "_id": "639064c9ec215f2cd1b2b15b",
    "__v": 0
}
</code>```

expected result

```<code>{
    "userId": 1,
    "status": "Pending",
    "notification_type": 1,
    "questions": [
        {
            "qn": "Which brand do you like better for buying shoes?",
            "options": [
                {
                    "option": "Adidas",
                    "totalViews": 20
                },
                {
                    "option": "Reebok",
                    "totalViews": 10
                }
            ]
        }
    ]
}
</code>```

Body:
The issue I am facing is that even though I am able to load the data in the database but the desired result is different from what is being returned.

The issue is that whenever I am running for loop the qn variable is inserted twice but need it only once.

Please if someone can help me resolve this issue.

userProject.js

router.post('/notification/check/upload/survey' , async (req,res) => {

  //const taginsert = [];
  const mcq = [];
  //const newData = {};
  //const o = {};

  console.log(req.body);

  for(var i=0; i<=req.body.questions.length-1;i++) {
    //  newData = {
    //   qn: req.body.questions[i].qn
    // }
    for(var j=0; j<=req.body.questions[i].options.length-1;j++){
       const o =
        {
         qn: req.body.questions[i].qn,
        //{
            options: [{
            option: req.body.questions[i].options[j].option,
            totalValues: req.body.questions[i].options[j].totalValues
          }]
        }

     // newData.options = o;
    //  newData.push(o);

      mcq.push(o);
    }

  }

//mcq = newData;

const check = new userCampaignSurvey({
  userId: req.body.userId,
  status: 'Pending',
  notification_type:req.body.notification_type,
  questions: mcq
})

 check.save((err,p) => {
  if(err) {
    res.status(500).send(err);
  }
  res.status(201).send(p);
 })
})

model.js

 userId:
    {
        type: Number,
        required: true,
        trim: true
    },
    notification_id:
    {
        type: Number,
    },
    notification_type:
    {
        type: Number,
        required: true,

    },
    status:
    {
         type: String,
         required: true
    },

    questions: [
        {
            qn: {
            type: String,
            required: true
        },
        options: [
            {
                option: {
                    type: String
                },
                totalViews: {
                    type:Number
                }

             }
    ]
    },
    ],
    created_at:  {
    type: Date,
    required: true,
    default: Date.now(),
},

});

result received

{
    "userId": 1,
    "notification_type": 1,
    "status": "Pending",
    "questions": [
        {
            "qn": "Which brand do you like better for buying shoes?",
            "options": [
                {
                    "option": "Adidas",
                    "_id": "639064c9ec215f2cd1b2b15d"
                }
            ],
            "_id": "639064c9ec215f2cd1b2b15c"
        },
        {
            "qn": "Which brand do you like better for buying shoes?",
            "options": [
                {
                    "option": "Reebok",
                    "_id": "639064c9ec215f2cd1b2b15f"
                }
            ],
            "_id": "639064c9ec215f2cd1b2b15e"
        }
    ],
    "created_at": "2022-12-07T10:02:48.442Z",
    "_id": "639064c9ec215f2cd1b2b15b",
    "__v": 0
}

expected result

{
    "userId": 1,
    "status": "Pending",
    "notification_type": 1,
    "questions": [
        {
            "qn": "Which brand do you like better for buying shoes?",
            "options": [
                {
                    "option": "Adidas",
                    "totalViews": 20
                },
                {
                    "option": "Reebok",
                    "totalViews": 10
                }
            ]
        }
    ]
}


问:
How to fix flaws of the type CWE 73 External Control of File Name or Path
Based on the below documentation/guide

How to fix flaws of the type CWE 73 External Control of File Name or Path

I am trying to pass fileName provided by the the user

```<code>amazonS3.putObject(path, fileName, inputStream, objectMetadata);
</code>```

But is the enforcement of veracode is, we should not use any English word which was a part of http request file name field, then how we are suppose to assume a file?

Body:
Based on the below documentation/guide

How to fix flaws of the type CWE 73 External Control of File Name or Path

I am trying to pass fileName provided by the the user

amazonS3.putObject(path, fileName, inputStream, objectMetadata);

But is the enforcement of veracode is, we should not use any English word which was a part of http request file name field, then how we are suppose to assume a file?


问:
How can I find INTRINSIC MATRIX in android cameraX
I need INTRINSIC MATRIX data and show it to the user. how can I find it in android CameraX?</p>


问:
Calculate Sum in matrix of SSRS report by column value
The report is designed to display the hours actually worked and the hours an employee should have worked between two specified dates. For this I used a matrix.

The problem is in total row. The actually worked hours are counted correctly, and the hours that the employee should have worked are counted not by the sum of the column, but as a Cartesian product.
Can I sum "Base Work Hours" by the column value?

On the picture above the total "Base Work Hours" should be 400.

My report:

WorkHours calculated as

```<code>select
    (DATEDIFF(DAY, @dtStartDate, @dtEndDate) + 1
    - DATEDIFF(WEEK, @dtStartDate, @dtEndDate) * 2
    - CASE  WHEN DATEPART(WEEKDAY, @dtStartDate) in (1, 7) THEN 1 ELSE 0    END
    - CASE  WHEN DATEPART(WEEKDAY, @dtEndDate) in (1, 7) THEN 1 ELSE 0    END
    )
    * WorkHoursDay
    FROM    tblEmpl
</code>```

Body:
The report is designed to display the hours actually worked and the hours an employee should have worked between two specified dates. For this I used a matrix.

The problem is in total row. The actually worked hours are counted correctly, and the hours that the employee should have worked are counted not by the sum of the column, but as a Cartesian product.
Can I sum "Base Work Hours" by the column value?

On the picture above the total "Base Work Hours" should be 400.

My report:

WorkHours calculated as

select
    (DATEDIFF(DAY, @dtStartDate, @dtEndDate) + 1
    - DATEDIFF(WEEK, @dtStartDate, @dtEndDate) * 2
    - CASE  WHEN DATEPART(WEEKDAY, @dtStartDate) in (1, 7) THEN 1 ELSE 0    END
    - CASE  WHEN DATEPART(WEEKDAY, @dtEndDate) in (1, 7) THEN 1 ELSE 0    END
    )
    * WorkHoursDay
    FROM    tblEmpl


问:
post_generation hook won't be called while using FactoryBoy for ManyToManyField generation
I have model Product:

```<code>class Product(models.Model):
    ..
    category = TreeManyToManyField(Category)
    ...

    def __str__(self):
        return self.name
</code>```

As you see, I have a many to many relation to Category. The following model:

Category:

```<code>class Category(MPTTModel):
    ...
    parent = TreeForeignKey(
        "self",
        on_delete=models.PROTECT,
        related_name="children",
        null=True,
        blank=True,
        verbose_name=_("parent of category"),
        help_text=_("format: not required"),
    )
    ...
</code>```

to generate the category field using FactoryBoy i did the following:

```<code>class ProductFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = models.Product

    slug = faker.lexify(text="prod_slug_??????")
    name = faker.lexify(text="prod_name_??????")

    @factory.post_generation
    def category(self, create, extracted, **kwargs):
        if not create:
            return

        if extracted:
            for cat in extracted:
                self.category.add(cat)
</code>```

and my test is:

```<code>@pytest.mark.dbfixture
def test_inventory_db_product_insert_data(
    db,
    product_factory,
):
    new_product = product_factory.create(category=(1, 2, 3, 4, 5, 6))

...
</code>```

But I get the following error:

```<code>TypeError: Direct assignment to the forward side of a many-to-many set i
s prohibited. Use category.set() instead.
</code>```

What's wrong with it?

Body:
I have model Product:

class Product(models.Model):
    ..
    category = TreeManyToManyField(Category)
    ...

    def __str__(self):
        return self.name

As you see, I have a many to many relation to Category. The following model:

Category:

class Category(MPTTModel):
    ...
    parent = TreeForeignKey(
        "self",
        on_delete=models.PROTECT,
        related_name="children",
        null=True,
        blank=True,
        verbose_name=_("parent of category"),
        help_text=_("format: not required"),
    )
    ...

to generate the category field using FactoryBoy i did the following:

class ProductFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = models.Product

    slug = faker.lexify(text="prod_slug_??????")
    name = faker.lexify(text="prod_name_??????")

    @factory.post_generation
    def category(self, create, extracted, **kwargs):
        if not create:
            return

        if extracted:
            for cat in extracted:
                self.category.add(cat)

and my test is:

@pytest.mark.dbfixture
def test_inventory_db_product_insert_data(
    db,
    product_factory,
):
    new_product = product_factory.create(category=(1, 2, 3, 4, 5, 6))

...

But I get the following error:

TypeError: Direct assignment to the forward side of a many-to-many set i
s prohibited. Use category.set() instead.

What's wrong with it?


问:
Flutter - Wireless debugging generatting error
I am using flutter for android development. I have connected my real device through wi-fi to my laptop. and i have turned of the laptop's hotspot and connected it to my real device through wifi When I use an android emulator it works fine with xampp server. But when I run the same app using a real device with WIFI it is not working.

I don't understand why is it showing that error.

throwing the following error :

```<code>Unhandled Exception: Connection timed out
</code>```

Body:
I am using flutter for android development. I have connected my real device through wi-fi to my laptop. and i have turned of the laptop's hotspot and connected it to my real device through wifi When I use an android emulator it works fine with xampp server. But when I run the same app using a real device with WIFI it is not working.

I don't understand why is it showing that error.

throwing the following error :

Unhandled Exception: Connection timed out


问:
Connect Wordpress Vagrant VM to MySQL Vagrant VM
First of, I am pretty new to Vagrant. I have two Vagrant VMs to set up a Wordpress. This is my Vagrantfile:

Note: The synced folder "wordpress" in web1 contains the official files of the latest Wordpress files downloadable from their page using wget http://wordpress.org/latest.zip and decompressing it afterwards.

```<code>Vagrant.configure("2") do |config|
    config.vm.box = "generic/ubuntu2010"

    config.vm.define :web1 do |web1|
        web1.vm.provider :virtualbox do |vb|
            vb.name = "web1"
            vb.memory = "1024"
        end
    web1.vm.hostname = "web1"
    web1.vm.network "forwarded_port", guest: 80, host: 1234
    web1.vm.network "private_network", ip: "192.168.100.101", virtualbox__intnet: true
    web1.vm.synced_folder "wordpress", "/var/www/html"
    web1.vm.provision :shell, inline: <<-SHELL
        apt-get update
        apt-get install -y apache2 php php-mysql
    SHELL
    end

    config.vm.define :db do |db|
        db.vm.provider :virtualbox do |vb|
            vb.name = "db"
            vb.memory = "1024"
        end
    db.vm.hostname = "db"
    db.vm.network "private_network", ip: "192.168.100.105", virtualbox__intnet: true
    db.vm.provision :shell, inline: <<-SHELL
        apt-get update
        apt-get install -y mysql-server
        mysql -u root -e "CREATE DATABASE wordpress;"
        mysql -u root -e "CREATE USER 'wp_user'@'192.168.100.105' IDENTIFIED BY 'wp_pass';"
        mysql -u root -e "GRANT ALL PRIVILEGES ON wordpress.* TO 'wp_user'@'192.168.100.105';"
    SHELL
    end
end
</code>```

When I go to localhost:1234 and fill up the form with the DB data, I get "Error establishing a database connection". I have tried a bunch of things and haven't got any further. How can I fix this?

Thank you

Body:
First of, I am pretty new to Vagrant. I have two Vagrant VMs to set up a Wordpress. This is my Vagrantfile:

Note: The synced folder "wordpress" in web1 contains the official files of the latest Wordpress files downloadable from their page using wget http://wordpress.org/latest.zip and decompressing it afterwards.

Vagrant.configure("2") do |config|
    config.vm.box = "generic/ubuntu2010"

    config.vm.define :web1 do |web1|
        web1.vm.provider :virtualbox do |vb|
            vb.name = "web1"
            vb.memory = "1024"
        end
    web1.vm.hostname = "web1"
    web1.vm.network "forwarded_port", guest: 80, host: 1234
    web1.vm.network "private_network", ip: "192.168.100.101", virtualbox__intnet: true
    web1.vm.synced_folder "wordpress", "/var/www/html"
    web1.vm.provision :shell, inline: <<-SHELL
        apt-get update
        apt-get install -y apache2 php php-mysql
    SHELL
    end

    config.vm.define :db do |db|
        db.vm.provider :virtualbox do |vb|
            vb.name = "db"
            vb.memory = "1024"
        end
    db.vm.hostname = "db"
    db.vm.network "private_network", ip: "192.168.100.105", virtualbox__intnet: true
    db.vm.provision :shell, inline: <<-SHELL
        apt-get update
        apt-get install -y mysql-server
        mysql -u root -e "CREATE DATABASE wordpress;"
        mysql -u root -e "CREATE USER 'wp_user'@'192.168.100.105' IDENTIFIED BY 'wp_pass';"
        mysql -u root -e "GRANT ALL PRIVILEGES ON wordpress.* TO 'wp_user'@'192.168.100.105';"
    SHELL
    end
end

When I go to localhost:1234 and fill up the form with the DB data, I get "Error establishing a database connection". I have tried a bunch of things and haven't got any further. How can I fix this?

Thank you


问:
Find optimal hyperparameters of both Models and Vectorizers using GridSearchCV
I wrote this method that returns all scores for each combination of Models and Vectorizers passed to it using GridSearchCV in order to find the optimal parameters

def text_classification(dataframe, vectorizer, model, parameters):
    """
    Perform free text binary classification using a given dataframe, vectorizer, and model.
    Returns an array of scores for each fold of 5-fold cross-validation.
    """
    X = vectorizer.fit_transform(dataframe['message'])
    y = dataframe['message_type']

    gs = GridSearchCV(model, parameters, cv=5)
    scores = cross_val_score(gs, X, y, cv=5)

    return scores
```
<p>Then I loop through two arrays of Vectorizers and Models:</p>
<pre class="lang-py prettyprint-override"><code># Define vectorizers and models
vectorizers = [TfidfVectorizer(), CountVectorizer()]
models = [LogisticRegression(), RandomForestClassifier(), MultinomialNB(), ComplementNB(), BernoulliNB()]

# Define hyperparameters for each model
parameters = {
    LogisticRegression: {'C': [1, 10, 100, 1000]},
    RandomForestClassifier: {'n_estimators': [10, 100, 1000]},
    MultinomialNB: {'alpha': [0.1, 0.5, 1.0]},
    ComplementNB: {'alpha': [0.1, 0.5, 1.0]},
    BernoulliNB: {'alpha': [0.1, 0.5, 1.0]},
}

for vectorizer in vectorizers:
    for model in models:
        # Perform cross-validation and evaluate model as well as optimal parameters
        scores = text_classification(df, vectorizer, model, parameters[model.__class__])
        print(f"Vectorizer: {vectorizer.__class__.__name__}, Model: {model.__class__.__name__}, Scores: {scores}")

</code>```

The above works, but it does not find the optimal parameters for the Vectorizer as well.

I adapted my method in order to use GridSearchCV in both vectorizer/model to find the optimal params, and pass two separate param dicts for models/vectorizers:

    gs_model = GridSearchCV(model, model_parameters, cv=5)
    gs_vectorizer = GridSearchCV(vectorizer, vectorizer_parameters, cv=5)
    gs = make_pipeline(gs_vectorizer, gs_model)
    scores = cross_val_score(gs, X, y, cv=5)

```
<p>But when I loop <code>text_classification</code> passing the two new param objects/dicts:</p>
<pre class="lang-py prettyprint-override"><code>        scores = text_classification(df, vectorizer, model, model_parameters=[model.__class__], vectorizer_parameters=[vectorizer.__class__])
</code>```

I get the following error:

```<code>in check_scoring
    raise TypeError(
TypeError: If no scoring is specified, the estimator passed should have a 'score' method. The estimator TfidfVectorizer() does not.
</code>```

Body:
I wrote this method that returns all scores for each combination of Models and Vectorizers passed to it using GridSearchCV in order to find the optimal parameters

def text_classification(dataframe, vectorizer, model, parameters):
    """
    Perform free text binary classification using a given dataframe, vectorizer, and model.
    Returns an array of scores for each fold of 5-fold cross-validation.
    """
    X = vectorizer.fit_transform(dataframe['message'])
    y = dataframe['message_type']

    gs = GridSearchCV(model, parameters, cv=5)
    scores = cross_val_score(gs, X, y, cv=5)

    return scores

Then I loop through two arrays of Vectorizers and Models:

# Define vectorizers and models
vectorizers = [TfidfVectorizer(), CountVectorizer()]
models = [LogisticRegression(), RandomForestClassifier(), MultinomialNB(), ComplementNB(), BernoulliNB()]

# Define hyperparameters for each model
parameters = {
    LogisticRegression: {'C': [1, 10, 100, 1000]},
    RandomForestClassifier: {'n_estimators': [10, 100, 1000]},
    MultinomialNB: {'alpha': [0.1, 0.5, 1.0]},
    ComplementNB: {'alpha': [0.1, 0.5, 1.0]},
    BernoulliNB: {'alpha': [0.1, 0.5, 1.0]},
}

for vectorizer in vectorizers:
    for model in models:
        # Perform cross-validation and evaluate model as well as optimal parameters
        scores = text_classification(df, vectorizer, model, parameters[model.__class__])
        print(f"Vectorizer: {vectorizer.__class__.__name__}, Model: {model.__class__.__name__}, Scores: {scores}")

The above works, but it does not find the optimal parameters for the Vectorizer as well.

I adapted my method in order to use GridSearchCV in both vectorizer/model to find the optimal params, and pass two separate param dicts for models/vectorizers:

    gs_model = GridSearchCV(model, model_parameters, cv=5)
    gs_vectorizer = GridSearchCV(vectorizer, vectorizer_parameters, cv=5)
    gs = make_pipeline(gs_vectorizer, gs_model)
    scores = cross_val_score(gs, X, y, cv=5)

But when I loop text_classification passing the two new param objects/dicts:

        scores = text_classification(df, vectorizer, model, model_parameters=[model.__class__], vectorizer_parameters=[vectorizer.__class__])

I get the following error:

in check_scoring
    raise TypeError(
TypeError: If no scoring is specified, the estimator passed should have a 'score' method. The estimator TfidfVectorizer() does not.


问:
Metrics for time series segments
I am looking for a metric to evaluate a time series segmentation or classification task.

Suppose we have an ML model which tries at each time to classify a point as TRUE or FALSE.

All consecutive points with the same label (TRUE or FALSE) are grouped into segments or intervals we classify with the same label. So the whole series is a succession of TRUE and FALSE intervals.

We have a ground truth of the data already labeled and want to evaluate the model at segment level, with some tolerance about the intersection between the classified interval and labeled one (two intervals are considered as matching if they intersect each other for 70% of their total/union duration, IoU).

Is there any implementation of such metric in Python ?

Thank you

I have already computed and measured the IoUs of labeled Vs classified segments.

Title: Metrics for time series segments


问:
Mockito is failing to match when trying to compare Paths.get("/path/to/file")
In a junit, I need to pass the Path object in another mocked class instance say "foo" and method "bar". which I am getting using Paths.get("/path/to/file") so I am mocking it using mockito like below:

```<code>when(foo.bar(eq(Paths.get("/path/to/file"))).thenReturn(true)
</code>```

But In the main class, it is returning as false. Not sure what is causing this.
Maybe because As I see the Path Object is different even with the same string.

Is there any way I can make it work?

tried other method same refEq but both did not work.

Body:
In a junit, I need to pass the Path object in another mocked class instance say "foo" and method "bar". which I am getting using Paths.get("/path/to/file") so I am mocking it using mockito like below:

when(foo.bar(eq(Paths.get("/path/to/file"))).thenReturn(true)

But In the main class, it is returning as false. Not sure what is causing this.
Maybe because As I see the Path Object is different even with the same string.

Is there any way I can make it work?

tried other method same refEq but both did not work.


问:
Changing displayed value
please how do i change the display value of a button when i click on it.
Say "hello" was being displayed on the button, then when i click it changes to "hi" in Reactjs</p>
```<code>export default function Change () {

return (
   <div>
     <button>hello</button> (this displays 'hello')
   </div>

//the above changes when clicked on

   <div>
     <button>hi</button> (displays 'hi' when clicked on)
   </div>
  )
}
</code>```

Title: Changing displayed value

Body:
please how do i change the display value of a button when i click on it.
Say "hello" was being displayed on the button, then when i click it changes to "hi" in Reactjs

export default function Change () {

return (

     <button>hello</button> (this displays 'hello')

//the above changes when clicked on

     <button>hi</button> (displays 'hi' when clicked on)

  )
}


问:
Rails Installing TypeScript doesn't load any files anymore
I have a problem. In my Rails application I wanted to use TypeScript using webpacker. To install the TypeScript implementation I did the following:
I ran:

```<code>rails webpacker:install:typescript
</code>```

Then edited the tsconfig.json by changing the module setting to "es6" and added "strict": true

Then I ran: rails webpacker:compile. After that I can see in the output that it compiled the following typescript files:

```<code>Compiling...
Compiled all packs in /app/public/packs
Hash: 0aff66e45830e2859a39
Version: webpack 4.46.0
Time: 1266ms
Built at: 12/07/2022 10:05:05 AM
                                             Asset       Size  Chunks                         Chunk Names
            js/application-ee3dc001e34e3c7c97e6.js   1.02 KiB       0  [emitted] [immutable]  application
         js/application-ee3dc001e34e3c7c97e6.js.br  466 bytes          [emitted]
         js/application-ee3dc001e34e3c7c97e6.js.gz  537 bytes          [emitted]
        js/application-ee3dc001e34e3c7c97e6.js.map   5.54 KiB       0  [emitted] [dev]        application
     js/application-ee3dc001e34e3c7c97e6.js.map.br   1.92 KiB          [emitted]
     js/application-ee3dc001e34e3c7c97e6.js.map.gz    2.2 KiB          [emitted]
       js/hello_typescript-db05426ac67e3cfab42d.js   1.02 KiB       1  [emitted] [immutable]  hello_typescript
    js/hello_typescript-db05426ac67e3cfab42d.js.br  487 bytes          [emitted]
    js/hello_typescript-db05426ac67e3cfab42d.js.gz  539 bytes          [emitted]
   js/hello_typescript-db05426ac67e3cfab42d.js.map   4.91 KiB       1  [emitted] [dev]        hello_typescript
js/hello_typescript-db05426ac67e3cfab42d.js.map.br   1.68 KiB          [emitted]
js/hello_typescript-db05426ac67e3cfab42d.js.map.gz    1.9 KiB          [emitted]
                                     manifest.json  738 bytes          [emitted]
                                  manifest.json.br  172 bytes          [emitted]
                                  manifest.json.gz  205 bytes          [emitted]
Entrypoint application = js/application-ee3dc001e34e3c7c97e6.js js/application-ee3dc001e34e3c7c97e6.js.map
Entrypoint hello_typescript = js/hello_typescript-db05426ac67e3cfab42d.js js/hello_typescript-db05426ac67e3cfab42d.js.map
[0] ./app/javascript/packs/application.ts 845 bytes {0} [built]
[1] ./app/javascript/packs/hello_typescript.ts 200 bytes {1} [built]
</code>```

In my application.html.erb I have the following default imports in the head:

```<code><%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %>
<%= javascript_pack_tag 'application', 'data-turbolinks-track': 'reload' %>
<%= javascript_include_tag "application", "data-turbo-track": "reload", defer: true %>
</code>```

But this results in an error on the 3th line with:

```<code>The asset "application.js" is not present in the asset pipeline.
</code>```

I also tried renaming the app/javascript/packs/application.ts file to a .js file, but that results in the same error. The other thing I tried was adding a application.js file to app/javascript, to see if the error is caused by the fact that it is now placed in a packs foler, but also no luck with that
What am I missing here?

Body:
I have a problem. In my Rails application I wanted to use TypeScript using webpacker. To install the TypeScript implementation I did the following:
I ran:

rails webpacker:install:typescript

Then edited the tsconfig.json by changing the module setting to "es6" and added "strict": true

Then I ran: rails webpacker:compile. After that I can see in the output that it compiled the following typescript files:

Compiling...
Compiled all packs in /app/public/packs
Hash: 0aff66e45830e2859a39
Version: webpack 4.46.0
Time: 1266ms
Built at: 12/07/2022 10:05:05 AM
                                             Asset       Size  Chunks                         Chunk Names
            js/application-ee3dc001e34e3c7c97e6.js   1.02 KiB       0  [emitted] [immutable]  application
         js/application-ee3dc001e34e3c7c97e6.js.br  466 bytes          [emitted]
         js/application-ee3dc001e34e3c7c97e6.js.gz  537 bytes          [emitted]
        js/application-ee3dc001e34e3c7c97e6.js.map   5.54 KiB       0  [emitted] [dev]        application
     js/application-ee3dc001e34e3c7c97e6.js.map.br   1.92 KiB          [emitted]
     js/application-ee3dc001e34e3c7c97e6.js.map.gz    2.2 KiB          [emitted]
       js/hello_typescript-db05426ac67e3cfab42d.js   1.02 KiB       1  [emitted] [immutable]  hello_typescript
    js/hello_typescript-db05426ac67e3cfab42d.js.br  487 bytes          [emitted]
    js/hello_typescript-db05426ac67e3cfab42d.js.gz  539 bytes          [emitted]
   js/hello_typescript-db05426ac67e3cfab42d.js.map   4.91 KiB       1  [emitted] [dev]        hello_typescript
js/hello_typescript-db05426ac67e3cfab42d.js.map.br   1.68 KiB          [emitted]
js/hello_typescript-db05426ac67e3cfab42d.js.map.gz    1.9 KiB          [emitted]
                                     manifest.json  738 bytes          [emitted]
                                  manifest.json.br  172 bytes          [emitted]
                                  manifest.json.gz  205 bytes          [emitted]
Entrypoint application = js/application-ee3dc001e34e3c7c97e6.js js/application-ee3dc001e34e3c7c97e6.js.map
Entrypoint hello_typescript = js/hello_typescript-db05426ac67e3cfab42d.js js/hello_typescript-db05426ac67e3cfab42d.js.map
[0] ./app/javascript/packs/application.ts 845 bytes {0} [built]
[1] ./app/javascript/packs/hello_typescript.ts 200 bytes {1} [built]

In my application.html.erb I have the following default imports in the head:

<%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %>
<%= javascript_pack_tag 'application', 'data-turbolinks-track': 'reload' %>
<%= javascript_include_tag "application", "data-turbo-track": "reload", defer: true %>

But this results in an error on the 3th line with:

The asset "application.js" is not present in the asset pipeline.

I also tried renaming the app/javascript/packs/application.ts file to a .js file, but that results in the same error. The other thing I tried was adding a application.js file to app/javascript, to see if the error is caused by the fact that it is now placed in a packs foler, but also no luck with that
What am I missing here?


问:
fulltext and INT columns integer the same query
I have a fulltext index on column Title. But the query contains additional "AND" condition where an integer column "CategoryID" with index is involved.

What is the best solution for this situation? This query just use fulltext index but I want this query to use fulltext + integert column index

```<code>SELECT *
FROM News
WHERE MATCH(Title) AGAINST('value')
  AND CategoryID=1
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a fulltext index on column Title. But the query contains additional "AND" condition where an integer column "CategoryID" with index is involved.

What is the best solution for this situation? This query just use fulltext index but I want this query to use fulltext + integert column index

SELECT *
FROM News
WHERE MATCH(Title) AGAINST('value')
  AND CategoryID=1


问:
i would like to assign subclasses to the charecter? how do i do this?
the problem i has is that the errors that occur are found in the code that works. it doesnt make sence.

my code is:

```<code>import random
import pickle

class person():
  def __init__(self, name, hp, luck, xp, level, gold, age, location, strength, intellegence):
    self.name = name
    self.hp = hp
    self.luck = luck
    self.xp = xp
    self.level = level
    self.strength = strength
    self.gold = gold
    self.location = location
    self.age = age
    self.intellegence = intellegence
    #self.x = 0
    #self.y = 0

  def talk(self):
    return "hello my name is %s. i have %d strength. i am %d years old. i am from %s. I have %d intellence" %(self.name,self.strength,self.age,self.location, self.intellegence)

#def walk(self,newlocation):
#  self.x += movex
#  self.y += movey
#  self.location = newlocation

  def takedmg(self, amount):
    self.hp = self.hp - amount

  def heal(self, amount):
    self.hp = self.hp + amount

  def attack(self):
    pass

allpeople = []

def createperson():
  global allpeople
  name = input("enter name: ")
  hp = 100
  luck = random.randint(1,15)
  xp = 0
  level = 1
  gold = 0
  age = int(input("enter age: "))
  location = input("enter location: ")
  strength = random.randint(1,25)
  intellegence = 50
  aperson = person(name, hp, luck, xp, level, gold, age, location, strength, intellegence)
  allpeople.append(aperson)
  savedata()

def findchara():
  charaname = input("enter the name of the charecter: ")
  for foundchara in allpeople:
    if foundchara.name == charaname:
      print("found \n")
      return(foundchara)
    return""

def savedata():
  savedata = open("mypeople.pickle","wb")
  pickle.dump(allpeople,savedata)
  savedata.close()

def loaddata():
  global allpeople
  loaddata = open("mypeople.pickle","rb")
  allpeople = pickle.load(loaddata)
  loaddata.close()

class warrior(person):
  def __init__(self, name, hp, luck, xp, level, gold, age, location, strength, intellegence):
    person.__init__(self)
    class1 = warrior

class mage(person):
  def __init__(self, name, hp, luck, xp, level, gold, age, location, strength, intellegence):
    person.__init__(self)
    class1 = mage

class trader(person):
  def __init__(self, name, hp, luck, xp, level, gold, age, location, strength, intellegence):
    person.__init__(self)
    class1 = trader

def talk_warrior(person, warrior):
  self.strength = self.strength + 15
  self.intellegence = self.intellegence - self.intellegence + random.randint(0,5)
  return "Hi, name is %s. %d strength. I am %d. from %s. intellegence? %d" %(self.name,self.strength,self.age,self.location,self.intellegence)

def talk_mage(person, mage):
  self.strength = self.strength - self.strength + random.randint(0,5)
  self.intellegence = self.intellegence + 50
  return "Hello my name is The Great MAGE %s. I have %d strength DONT QUESTION MY STRENGTH. I am %d years old. I happened to be from %s. my intellegence also happens to be %d which is superior to everyone else." %(self.name,self.strength,self.age,self.location,self.intellegence)

def talk_trader(person, trader):
  return "Hello my name is %s. I have %d strength. I am %d years old. I am from %s. I am very average and my intellegence is %d " %(self.name,self.strength,self.age,self.location,self.intellegence)

loaddata()

def classmenu():
  charaloop = True
  while charaloop == True:
    option = int(input("1. warrior \n2. mage \n3. trader \n9. change class \n0. exit \n"))
    if option == 1:
      classchara = findchara()
      class1 = warrior
      print("Class has been set to warrior.")
      talk_warrior()
    elif option == 2:
      classchara = findchara()
      class1 = mage
      print("Class has been set set to mage.")
      talk_mage()
    elif option == 3:
      classchara = findchara()
      class1 = trader
      print("Class has been set to trader.")
      talk_trader()
    elif option == 9:
      pass
    elif option == 0:
      print("returning to main menu. :) \n")
      charaloop = False
      savedata()
    else:
      print("invalid choice")

def menu():
  mainloop = True
  while mainloop == True:
    option = int(input("1. create character. \n2. character list. \n3. look for a charecter. \n4. select charecter class. \n8. continue... \n9. delete character from list. \n0. exit \n choice: "))
    if option == 1:
      print("you will now create your character!!!")
      createperson()
    elif option == 2:
      for aPerson in allpeople:
        print(aPerson.talk())
    elif option == 3:
      findchara()
    elif option == 4:
      classmenu()
    elif option == 8:
      if class1 == warrior:
        talk_warrior()
      elif class1 == mage:
        talk_mage()
      elif class1 == trader:
        talk_trader()
      else:
        print("ERROR!")
    elif option == 9:
      chara = findchara()
      allpeople.remove(chara)
      print("charecter removed")
      savedata()
    elif option == 0:
      print("bye!!! :)")
      mainloop = False
      savedata()
    else:
      print("invalid choice")

menu()

</code>```

the errors are:

```<code>Traceback (most recent call last):
  File "D:\python stuff\python chara game ulsfdgklfsgnklfs.py", line 173, in <module>
    menu()
  File "D:\python stuff\python chara game ulsfdgklfsgnklfs.py", line 151, in menu
    classmenu()
  File "D:\python stuff\python chara game ulsfdgklfsgnklfs.py", line 118, in classmenu
    talk_warrior()
TypeError: talk_warrior() missing 2 required positional arguments: 'person' and 'warrior'
</code>```

the code is meant to run in the shell and is a simple class and subclass game that the player creates a character and then assigns it a subclass which changes the attributes of the character. this is where my problems started. in the future I want the character to be able to travel and then will encounter monsters attack and receive damage.

id like to hear some advice on what I could do to improve and make the code better smoother and also fix these problems that have occurred. I've only been coding for a while so there is allot of things wrong with this code.

Body:
the problem i has is that the errors that occur are found in the code that works. it doesnt make sence.

my code is:

import random
import pickle

class person():
  def __init__(self, name, hp, luck, xp, level, gold, age, location, strength, intellegence):
    self.name = name
    self.hp = hp
    self.luck = luck
    self.xp = xp
    self.level = level
    self.strength = strength
    self.gold = gold
    self.location = location
    self.age = age
    self.intellegence = intellegence
    #self.x = 0
    #self.y = 0

  def talk(self):
    return "hello my name is %s. i have %d strength. i am %d years old. i am from %s. I have %d intellence" %(self.name,self.strength,self.age,self.location, self.intellegence)

#def walk(self,newlocation):
#  self.x += movex
#  self.y += movey
#  self.location = newlocation

  def takedmg(self, amount):
    self.hp = self.hp - amount

  def heal(self, amount):
    self.hp = self.hp + amount

  def attack(self):
    pass

allpeople = []

def createperson():
  global allpeople
  name = input("enter name: ")
  hp = 100
  luck = random.randint(1,15)
  xp = 0
  level = 1
  gold = 0
  age = int(input("enter age: "))
  location = input("enter location: ")
  strength = random.randint(1,25)
  intellegence = 50
  aperson = person(name, hp, luck, xp, level, gold, age, location, strength, intellegence)
  allpeople.append(aperson)
  savedata()

def findchara():
  charaname = input("enter the name of the charecter: ")
  for foundchara in allpeople:
    if foundchara.name == charaname:
      print("found \n")
      return(foundchara)
    return""

def savedata():
  savedata = open("mypeople.pickle","wb")
  pickle.dump(allpeople,savedata)
  savedata.close()

def loaddata():
  global allpeople
  loaddata = open("mypeople.pickle","rb")
  allpeople = pickle.load(loaddata)
  loaddata.close()

class warrior(person):
  def __init__(self, name, hp, luck, xp, level, gold, age, location, strength, intellegence):
    person.__init__(self)
    class1 = warrior

class mage(person):
  def __init__(self, name, hp, luck, xp, level, gold, age, location, strength, intellegence):
    person.__init__(self)
    class1 = mage

class trader(person):
  def __init__(self, name, hp, luck, xp, level, gold, age, location, strength, intellegence):
    person.__init__(self)
    class1 = trader

def talk_warrior(person, warrior):
  self.strength = self.strength + 15
  self.intellegence = self.intellegence - self.intellegence + random.randint(0,5)
  return "Hi, name is %s. %d strength. I am %d. from %s. intellegence? %d" %(self.name,self.strength,self.age,self.location,self.intellegence)

def talk_mage(person, mage):
  self.strength = self.strength - self.strength + random.randint(0,5)
  self.intellegence = self.intellegence + 50
  return "Hello my name is The Great MAGE %s. I have %d strength DONT QUESTION MY STRENGTH. I am %d years old. I happened to be from %s. my intellegence also happens to be %d which is superior to everyone else." %(self.name,self.strength,self.age,self.location,self.intellegence)

def talk_trader(person, trader):
  return "Hello my name is %s. I have %d strength. I am %d years old. I am from %s. I am very average and my intellegence is %d " %(self.name,self.strength,self.age,self.location,self.intellegence)

loaddata()

def classmenu():
  charaloop = True
  while charaloop == True:
    option = int(input("1. warrior \n2. mage \n3. trader \n9. change class \n0. exit \n"))
    if option == 1:
      classchara = findchara()
      class1 = warrior
      print("Class has been set to warrior.")
      talk_warrior()
    elif option == 2:
      classchara = findchara()
      class1 = mage
      print("Class has been set set to mage.")
      talk_mage()
    elif option == 3:
      classchara = findchara()
      class1 = trader
      print("Class has been set to trader.")
      talk_trader()
    elif option == 9:
      pass
    elif option == 0:
      print("returning to main menu. :) \n")
      charaloop = False
      savedata()
    else:
      print("invalid choice")

def menu():
  mainloop = True
  while mainloop == True:
    option = int(input("1. create character. \n2. character list. \n3. look for a charecter. \n4. select charecter class. \n8. continue... \n9. delete character from list. \n0. exit \n choice: "))
    if option == 1:
      print("you will now create your character!!!")
      createperson()
    elif option == 2:
      for aPerson in allpeople:
        print(aPerson.talk())
    elif option == 3:
      findchara()
    elif option == 4:
      classmenu()
    elif option == 8:
      if class1 == warrior:
        talk_warrior()
      elif class1 == mage:
        talk_mage()
      elif class1 == trader:
        talk_trader()
      else:
        print("ERROR!")
    elif option == 9:
      chara = findchara()
      allpeople.remove(chara)
      print("charecter removed")
      savedata()
    elif option == 0:
      print("bye!!! :)")
      mainloop = False
      savedata()
    else:
      print("invalid choice")

menu()

the errors are:

Traceback (most recent call last):
  File "D:\python stuff\python chara game ulsfdgklfsgnklfs.py", line 173, in <module>
    menu()
  File "D:\python stuff\python chara game ulsfdgklfsgnklfs.py", line 151, in menu
    classmenu()
  File "D:\python stuff\python chara game ulsfdgklfsgnklfs.py", line 118, in classmenu
    talk_warrior()
TypeError: talk_warrior() missing 2 required positional arguments: 'person' and 'warrior'

the code is meant to run in the shell and is a simple class and subclass game that the player creates a character and then assigns it a subclass which changes the attributes of the character. this is where my problems started. in the future I want the character to be able to travel and then will encounter monsters attack and receive damage.

id like to hear some advice on what I could do to improve and make the code better smoother and also fix these problems that have occurred. I've only been coding for a while so there is allot of things wrong with this code.


问:
Modify Tooltips in Pygal
I am creating an interactive World Map, where you can hover over different countries to see which one you are hovering over, and click them to link to a seperate HTML page with info on them. The problem is, when I hover over smaller countries like Switzerland, the tooltip itself covers the entire hitbox of the country, and I am not able to click on it.

I have already asked about moving the Tooltip elsewhere, or providing a link on the tooltip itself, but got no answers for those questions. So now I am asking; is it possible to completely hide a tooltip in pygal maps? Or perhaps change it to a toggle that activates on click? Or perhaps even render the tooltip relative to the cursor instead of relative to the Datapoint itself? My code is so close to being finished but is being held back by this rather infuriating issue.

Please let me know if I should also provide my code that I have for this issue.

Title: Modify Tooltips in Pygal


问:
Get ChromeBook android network interface IP from chromeOS
I'm looking for an chromeOS API to get all the network interfaces, I saw this one but I'm not able to invoke it because it doesn't exists for me.

Is there any other way to get the android arc_x network interface from chromeOS?

Thanks


问:
.NET WinForms App. goes to not responding, reboots sometime & ultimately crashes while trying to connect with Biometric Device when device is off
I am working on .NET WinForms Application. It has to connect with a Bio Metric device. It works good when device is on. But when device is off, it checks for connection and here application goes to not responding, after sometime application restarts and then again checks for connection, goes to not responding and loop goes on. Ultimately application crashes without giving any error or exception. And there is no relevant information in Event Viewer on application crashes other then a unhandled exception. I am attaching relevant code below.

```<code>private void PingDevice()
        {
            var interval = int.Parse(ConfigurationManager.AppSettings["BioDeviceConnectionPingInterval"].ToString());

            while (IsPingRunning)
            {
                try
                {
                    if (LastBioPingRecieveTime != null)
                    {
                        //check if last bioping was recieved within interval
                        var difference = LastBioPingRecieveTime.Value;

                        var wait = (DateTime.Now - difference).TotalSeconds;

                        if (wait <= interval)
                        {
                            //do nothing
                            Thread.Sleep(30000);
                        }
                        else
                        {
                            if (!this.IsHandleCreated) this.CreateControl();

                            if (this.IsHandleCreated)
                            {
                                this.Invoke((MethodInvoker)delegate
                                {
                                    lbUserId.Items.Add("Checking for connection.");
                                });
                            }

                            string id = null;
                            //Ping the device to get the connection info
                            var result = device.GetSerialNumber(device.MachineNumber, out id);

                            if (result)
                            {
                                LastBioPingRecieveTime = DateTime.Now;
                                //Machine Connected
                                if (!this.IsHandleCreated) this.CreateControl();

                                if (this.IsHandleCreated)
                                {
                                    this.Invoke((MethodInvoker)delegate
                                    {
                                        lbUserId.Items.Add("Connected.");
                                    });
                                }
                            }
                            else
                            {
                                if (!this.IsHandleCreated) this.CreateControl();

                                if (this.IsHandleCreated)
                                {
                                    this.Invoke((MethodInvoker)delegate
                                    {
                                        lbUserId.Items.Add("Resetting.");
                                    });
                                }
                                if (s != null)
                                {
                                    s.Close();
                                    s = null;
                                }
                                tcpListener.Server.Close();
                                this.backgroundWorker1.CancelAsync();

                                if (!this.IsHandleCreated) this.CreateControl();

                                //Update reconnect
                                if (this.IsHandleCreated)
                                {
                                    this.Invoke((MethodInvoker)delegate
                                    {

                                        IsPingRunning = false;
                                        this.Close();
                                    });
                                }
                                else
                                {

                                    IsPingRunning = false;
                                    this.Close();
                                }

                            }
                        }
                    }

                }
                catch (Exception ex)
                {

                    Common.WriteException(ex.Message, ex.StackTrace, "  private void PingDevice()");
                    Thread.Sleep(10000);
                }
            }
        }
</code>```

I implemented Unhandled Exception and also debugged code thoroughly but did not able to catch the issue.

I got only following exception in Debug (output):
Exception thrown: 'System.Net.Sockets.SocketException' in System.dll

Can anyone help with this?

Body:
I am working on .NET WinForms Application. It has to connect with a Bio Metric device. It works good when device is on. But when device is off, it checks for connection and here application goes to not responding, after sometime application restarts and then again checks for connection, goes to not responding and loop goes on. Ultimately application crashes without giving any error or exception. And there is no relevant information in Event Viewer on application crashes other then a unhandled exception. I am attaching relevant code below.

private void PingDevice()
        {
            var interval = int.Parse(ConfigurationManager.AppSettings["BioDeviceConnectionPingInterval"].ToString());

            while (IsPingRunning)
            {
                try
                {
                    if (LastBioPingRecieveTime != null)
                    {
                        //check if last bioping was recieved within interval
                        var difference = LastBioPingRecieveTime.Value;

                        var wait = (DateTime.Now - difference).TotalSeconds;

                        if (wait <= interval)
                        {
                            //do nothing
                            Thread.Sleep(30000);
                        }
                        else
                        {
                            if (!this.IsHandleCreated) this.CreateControl();

                            if (this.IsHandleCreated)
                            {
                                this.Invoke((MethodInvoker)delegate
                                {
                                    lbUserId.Items.Add("Checking for connection.");
                                });
                            }

                            string id = null;
                            //Ping the device to get the connection info
                            var result = device.GetSerialNumber(device.MachineNumber, out id);

                            if (result)
                            {
                                LastBioPingRecieveTime = DateTime.Now;
                                //Machine Connected
                                if (!this.IsHandleCreated) this.CreateControl();

                                if (this.IsHandleCreated)
                                {
                                    this.Invoke((MethodInvoker)delegate
                                    {
                                        lbUserId.Items.Add("Connected.");
                                    });
                                }
                            }
                            else
                            {
                                if (!this.IsHandleCreated) this.CreateControl();

                                if (this.IsHandleCreated)
                                {
                                    this.Invoke((MethodInvoker)delegate
                                    {
                                        lbUserId.Items.Add("Resetting.");
                                    });
                                }
                                if (s != null)
                                {
                                    s.Close();
                                    s = null;
                                }
                                tcpListener.Server.Close();
                                this.backgroundWorker1.CancelAsync();

                                if (!this.IsHandleCreated) this.CreateControl();

                                //Update reconnect
                                if (this.IsHandleCreated)
                                {
                                    this.Invoke((MethodInvoker)delegate
                                    {

                                        IsPingRunning = false;
                                        this.Close();
                                    });
                                }
                                else
                                {

                                    IsPingRunning = false;
                                    this.Close();
                                }

                            }
                        }
                    }

                }
                catch (Exception ex)
                {

                    Common.WriteException(ex.Message, ex.StackTrace, "  private void PingDevice()");
                    Thread.Sleep(10000);
                }
            }
        }

I implemented Unhandled Exception and also debugged code thoroughly but did not able to catch the issue.

I got only following exception in Debug (output):
Exception thrown: 'System.Net.Sockets.SocketException' in System.dll

Can anyone help with this?