问:
Use Python Traci From SUMO to run with OMNET++
I'm a beginner in Omnet++ & SUMO. I have successfully created my python script using the Traci library from SUMO. So, now I am currently trying to run my python script inside OMNET++ but I do not have any idea on how to do it. Can anyone guide me regarding this?</p>

答:
pybind11 makes it easy to call python constructs in c++. I did install pybind11 in debian and successfuly invoked a python script. How to use pybind11 in omnet++ projects like veins
This is another way of calling python from c++.</p>


来源: stackexchange

问:
cleaner way to check whether or not a the current window.location.href is equal to any of the strings in the array
Im trying to do a redirect if the url is equal to any of the strings in the following array of urls:

So I did the following

```<code>function redirectUser() {
  if (window.location.href === 'https://swish.com/login' || window.location.href === 'https://swish.com/register' || window.location.href === 'https://swish.com/overview') {
    window.location.replace('https://swish.com/onboard');
  }
}
</code>```

But this is a bit ugly, so I thought of putting the urls in an array and doing something like this:

```<code>function redirectUser() {
  const urls = ['https://swish.com/login', 'https://swish.com/register', 'https://swish.com/overview' ]
for(let url of urls) {
  if (window.location.href === url) {
    window.location.replace('https://swish.com/onboard');
  }
 }
}
</code>```

Is there any other way to do this? If not, which would be the better option in your opinion? Thanks!

答:
It appears that you already have all the strings statically within the code. So you can try using switch which performance wise is faster than if check here.

If you are reproducing strings via some logic, then you can also opt for Regular Expressions which is even faster. Else, you can stick with arrays.

ContentLicense: CC BY-SA 4.0

Body:
Im trying to do a redirect if the url is equal to any of the strings in the following array of urls:

So I did the following

function redirectUser() {
  if (window.location.href === 'https://swish.com/login' || window.location.href === 'https://swish.com/register' || window.location.href === 'https://swish.com/overview') {
    window.location.replace('https://swish.com/onboard');
  }
}

But this is a bit ugly, so I thought of putting the urls in an array and doing something like this:

function redirectUser() {
  const urls = ['https://swish.com/login', 'https://swish.com/register', 'https://swish.com/overview' ]
for(let url of urls) {
  if (window.location.href === url) {
    window.location.replace('https://swish.com/onboard');
  }
 }
}

Is there any other way to do this? If not, which would be the better option in your opinion? Thanks!


问:
How do I turn a one-to-many relationship into a list property using SauceDB?
Using SauceDB, how do I turn a one-to-many relationship, between say table "A" and table "B" respectively, into a list property (containing B objects) in the class that corresponds to table A? The relationship is represented by a foreign key in table B referring to table A (so that many B records can belong to one A record).</p>

答:
I found that I could use the AdditionalInit attribute in order to define a hook which gets called as a database object gets initialized. Since this hook can accept a data store, I can deduce the one-to-many relationship right there.

Here's the relevant excerpt of class A:

```<code>public class A
{
    ...

    public List<B> Bs { get; private set; }

    [AdditionalInit]
    public void OnInit(IDataStore dstore)
    {
        Bs = dstore.Query<B>().Where(b => b.A.Id == Id).ToList();
    }
}
</code>```

Bear in mind I haven't been able to test this code yet.

ContentLicense: CC BY-SA 3.0

Body:
I found that I could use the AdditionalInit attribute in order to define a hook which gets called as a database object gets initialized. Since this hook can accept a data store, I can deduce the one-to-many relationship right there.

Here's the relevant excerpt of class A:

public class A
{
    ...

    public List<B> Bs { get; private set; }

    [AdditionalInit]
    public void OnInit(IDataStore dstore)
    {
        Bs = dstore.Query<B>().Where(b => b.A.Id == Id).ToList();
    }
}

Bear in mind I haven't been able to test this code yet.


问:
Gremlin - extracting T.id and T.label from valueMap
This question is related to this post that Kelvin Lawrence answered very helpfully, wanted to post it as a separate question bec the first question was answered well already.

From this query:

```<code>g.V('a2661f57-8aa7-4e5c-9c89-55cf9b7e4cf8').as('self')
.sideEffect(out('rated').store('movies'))
.out('friended')
.group()
.by(valueMap(true).by(unfold()))
.by(out('rated').where(within('movies')).count())
.order(local)
.by(values,desc)
.unfold()
.select(keys)
</code>```

i get this result:

```<code>1   {<T.id: 1>: 'fdc45bd3-be08-4716-b20f-b4f04987c5e0', <T.label: 4>: 'user', 'username': 'elin102dev', 'name': 'elin obrien', 'avatarUrl': 'public/avatars/fdc45bd3-be08-4716-b20f-b4f04987c5e0.jpg'}
2   {<T.id: 1>: 'bbf1b0db-68cc-41f1-8c7a-5fd77b698e39', <T.label: 4>: 'user', 'username': 'iris', 'name': 'Iris Ebert', 'avatarUrl': 'public/avatars/bbf1b0db-68cc-41f1-8c7a-5fd77b698e39.jpg'}
3   {<T.id: 1>: '34c2ea80-4f84-4652-a7c3-48ce43d9aea7', <T.label: 4>: 'user', 'username': 'iris103dev', 'name': 'iris obrien', 'avatarUrl': 'public/avatars/34c2ea80-4f84-4652-a7c3-48ce43d9aea7.jpg'}
</code>```

I want to convert the T.id and T.label values in the response to simply "id" and "label". Kelvin, if you're reading this, i i tried appending the following to the query above but it returns 0 results:

```<code>.select('id', 'label', 'username', 'name', 'avatarUrl')
    .by(T.id)
    .by(T.label)
    .by('username')
    .by('name')
    .by('avatarUrl')
    .toList()
</code>```

I could use a little more help figuring this out, not having much success. Thanks in advance.

答:
It is not possible to do a select(T.id) inside a query. In code if you get a map back you can access the T.id field. For a case such as this, it is better to delay fetching the properties until you finally need them. You might try rewriting the query like this.

g.V('a2661f57-8aa7-4e5c-9c89-55cf9b7e4cf8').as('self').
  sideEffect(out('rated').store('movies')).
  out('friended').
  group().
    by().
    by(out('rated').where(within('movies')).count()).
  order(local).
    by(values,desc).
    unfold().
  select(keys).
  project('id','label','username').
    by(id).
    by(label).
    by('username')
```

Body:
This question is related to this post that Kelvin Lawrence answered very helpfully, wanted to post it as a separate question bec the first question was answered well already.

From this query:

g.V('a2661f57-8aa7-4e5c-9c89-55cf9b7e4cf8').as('self')
.sideEffect(out('rated').store('movies'))
.out('friended')
.group()
.by(valueMap(true).by(unfold()))
.by(out('rated').where(within('movies')).count())
.order(local)
.by(values,desc)
.unfold()
.select(keys)

i get this result:

1   {<T.id: 1>: 'fdc45bd3-be08-4716-b20f-b4f04987c5e0', <T.label: 4>: 'user', 'username': 'elin102dev', 'name': 'elin obrien', 'avatarUrl': 'public/avatars/fdc45bd3-be08-4716-b20f-b4f04987c5e0.jpg'}
2   {<T.id: 1>: 'bbf1b0db-68cc-41f1-8c7a-5fd77b698e39', <T.label: 4>: 'user', 'username': 'iris', 'name': 'Iris Ebert', 'avatarUrl': 'public/avatars/bbf1b0db-68cc-41f1-8c7a-5fd77b698e39.jpg'}
3   {<T.id: 1>: '34c2ea80-4f84-4652-a7c3-48ce43d9aea7', <T.label: 4>: 'user', 'username': 'iris103dev', 'name': 'iris obrien', 'avatarUrl': 'public/avatars/34c2ea80-4f84-4652-a7c3-48ce43d9aea7.jpg'}

I want to convert the T.id and T.label values in the response to simply "id" and "label". Kelvin, if you're reading this, i i tried appending the following to the query above but it returns 0 results:

.select('id', 'label', 'username', 'name', 'avatarUrl')
    .by(T.id)
    .by(T.label)
    .by('username')
    .by('name')
    .by('avatarUrl')
    .toList()

I could use a little more help figuring this out, not having much success. Thanks in advance.


问:
Jest + Typescript Unable to Import Library (tiny-secp256k1)
I am currently using the npm package tiny-secp256k1.

It provides non-default exports of many functions (with type declaration).

No matter how I try to import it, running my test suite. Jest throws:

```<code>    /pathToProject/node_modules/tiny-secp256k1/lib/index.js:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){import { compare } from "uint8array-tools";
                                                                                ^^^^^^

SyntaxError: Cannot use import statement outside a module
</code>```

I cannot tell if this issue is isolated to the library, or is caused by my configuration.
I can import other libraries without complication.

jest.config.ts

export default {
    verbose: true,
    transform: {
        '^.+\\.(ts|tsx)?$': 'ts-jest',
    },
    testPathIgnorePatterns: ['__tests__/helpers'],
};
```
<p><code>tsconfig.json</code></p>
<pre class="lang-json prettyprint-override"><code>{
    "compilerOptions": {
        "target": "ES2020",
        "module": "commonjs",
        "outDir": "dist",
        "allowJs": false,
        "sourceMap": true,
        "resolveJsonModule": true,
        "esModuleInterop": true,
        "allowSyntheticDefaultImports": true
    },
    "exclude": ["__tests__/"]
}
</code>```

答:
I was struggling with this for a while too. I found out that it is some weird issue with jest and the "cjs" modules. Don't know exactly why it's like this but after some research I found this post (Jest won't transform the module - SyntaxError: Cannot use import statement outside a module) that gave me a clue of what I needed to do.
Below is my jest.config.js file that solves this issue:</p>
```<code>module.exports = {
    preset: "ts-jest",
    moduleFileExtensions: [
        "ts",
        "js",
        "cjs",
        "mjs"
    ],
    transform: {
        "^.+\\.(ts|tsx)$": "ts-jest",
        "node_modules/tiny-secp256k1/lib/cjs/.+\\.(js|ts|cjs|mjs)$": "ts-jest",
        "node_modules/uint8array-tools/src/cjs.+\\.(js|ts|cjs|mjs)$": "ts-jest"
    },
    moduleNameMapper: {
        "^uint8array-tools$": "uint8array-tools/src/cjs",
        "^tiny-secp256k1$": "tiny-secp256k1/lib/cjs"
    },
    transformIgnorePatterns: [
        "node_modules/(?!tiny-secp256k1/lib/cjs/.*)",
        "node_modules/(?!uint8array-tools/src/cjs/.*)"
    ],
    testMatch: [
        "**/test/**/*.test.(ts|js)"
    ],
    testEnvironment: "node"
};
</code>```

Body:
I am currently using the npm package tiny-secp256k1.

It provides non-default exports of many functions (with type declaration).

No matter how I try to import it, running my test suite. Jest throws:

    /pathToProject/node_modules/tiny-secp256k1/lib/index.js:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){import { compare } from "uint8array-tools";
                                                                                ^^^^^^

SyntaxError: Cannot use import statement outside a module

I cannot tell if this issue is isolated to the library, or is caused by my configuration.
I can import other libraries without complication.

jest.config.ts

export default {
    verbose: true,
    transform: {
        '^.+\\.(ts|tsx)?$': 'ts-jest',
    },
    testPathIgnorePatterns: ['__tests__/helpers'],
};

tsconfig.json

{
    "compilerOptions": {
        "target": "ES2020",
        "module": "commonjs",
        "outDir": "dist",
        "allowJs": false,
        "sourceMap": true,
        "resolveJsonModule": true,
        "esModuleInterop": true,
        "allowSyntheticDefaultImports": true
    },
    "exclude": ["__tests__/"]
}

Body:
I was struggling with this for a while too. I found out that it is some weird issue with jest and the "cjs" modules. Don't know exactly why it's like this but after some research I found this post (Jest won't transform the module - SyntaxError: Cannot use import statement outside a module) that gave me a clue of what I needed to do.
Below is my jest.config.js file that solves this issue:

module.exports = {
    preset: "ts-jest",
    moduleFileExtensions: [
        "ts",
        "js",
        "cjs",
        "mjs"
    ],
    transform: {
        "^.+\\.(ts|tsx)$": "ts-jest",
        "node_modules/tiny-secp256k1/lib/cjs/.+\\.(js|ts|cjs|mjs)$": "ts-jest",
        "node_modules/uint8array-tools/src/cjs.+\\.(js|ts|cjs|mjs)$": "ts-jest"
    },
    moduleNameMapper: {
        "^uint8array-tools$": "uint8array-tools/src/cjs",
        "^tiny-secp256k1$": "tiny-secp256k1/lib/cjs"
    },
    transformIgnorePatterns: [
        "node_modules/(?!tiny-secp256k1/lib/cjs/.*)",
        "node_modules/(?!uint8array-tools/src/cjs/.*)"
    ],
    testMatch: [
        "**/test/**/*.test.(ts|js)"
    ],
    testEnvironment: "node"
};


问:
Python: type-hinting CTypes "pointer to X" types in a way that MyPy accepts
I have a large Python binding over a C library, with complex memory management. To help with that, I have drawn up the following aliases for strings (here, you a minimal reproducible example of my definitions and the subsequent problem).

from typing import Type, TypeAlias
from ctypes import POINTER, pointer, c_char, c_char_p

#normal python string
p_useable_p_str = str

#the result of a my_str.decode("utf-8")
c_useable_p_str = bytes

#used for string literals returned by the C, which should not be freed
p_useable_c_str = c_char_p

#used for allocated strings returned by the C, which need to be freed later
c_useable_c_str = POINTER(c_char)  #the problematic line

def example(hello: c_useable_c_str):  # source of the MyPy error
    pass
```
<p>My code runs fine (memory freed properly, consistent inheritance of the above if necessary, etc) when following the above definitions+usage conventions). <code>POINTER(c_char)</code> has the intended behavior in the rest of the code.</p>
<p>However, analyzing the above with MyPy, I get:</p>
```playground.py:10: error: Variable "playground.c_useable_c_str" is not valid as a type
playground.py:10: note: See https://mypy.readthedocs.io/en/latest/common_issues.html#variables-vs-type-aliases
Found 1 error in 1 file (checked 1 source file)
```
<p>I get this error for anything that uses the <code>c_useable_c_str</code> alias. I, of course, read the section in the documentation linked above, and tried using Type and TypeAlias in a bunch of different ways - to no avail.</p>
<p>The only syntax that seems to make MyPy happy is</p>
<pre class="lang-py prettyprint-override"><code>c_useable_c_str = pointer[c_char]
</code>```

However, when actually running the code with this definition of the type alias, I get the following error (not seen by MyPy, so I suspect a bug on MyPy's end, or a lack of typing in the standard):

```<code>Traceback (most recent call last):
  File "/home/fulguritude/ProfessionalWork/LEDR/Orchestra-AvesTerra/Python_binding/playground2.py", line 92, in <module>
    c_useable_c_str = pointer[c_char]
TypeError: 'builtin_function_or_method' object is not subscriptable
</code>```

Any ideas as to how I'm supposed to make things consistent ?

TLDR: what's the valid way to type hint, and alias, a "pointer to X" with MyPy and CTypes ?

答:
I found an imperfect (but good enough) solution, based on what I found here: https://github.com/python/mypy/issues/7540 (comment by thijsmie, commented on May 21, 2021).

if not TYPE_CHECKING:
    # Monkeypatch typed pointer from typeshed into ctypes
    # NB: files that wish to import ctypes.pointer should all import `pointer` from this file instead
    class pointer_fix:
        @classmethod
        def __class_getitem__(cls, item):
            return POINTER(item)
    pointer = pointer_fix
```
<p>It does solve MyPy's complaints concerning <code>c_useable_c_str</code>, and functions that use <code>c_useable_c_str</code> still get proper typing errors when the argument provided isn't of a compatible type, so that's good.</p>
<p>Well, EXCEPT for the following case:</p>
<pre class="lang-py prettyprint-override"><code>class t_string(c_useable_c_str):
    pass

class t_string_p(pointer[t_string]):
    pass
</code>```

where MyPy does not seem to be able to understand that t_string_p is compatible with the type pointer[pointer[c_char]]. For these cases, I used a type union; not ideal, but it got the job done.

I'll be leaving this question unanswered for now, in case someone, someday, can find a better solution.

Body:
I have a large Python binding over a C library, with complex memory management. To help with that, I have drawn up the following aliases for strings (here, you a minimal reproducible example of my definitions and the subsequent problem).

from typing import Type, TypeAlias
from ctypes import POINTER, pointer, c_char, c_char_p

#normal python string
p_useable_p_str = str

#the result of a my_str.decode("utf-8")
c_useable_p_str = bytes

#used for string literals returned by the C, which should not be freed
p_useable_c_str = c_char_p

#used for allocated strings returned by the C, which need to be freed later
c_useable_c_str = POINTER(c_char)  #the problematic line

def example(hello: c_useable_c_str):  # source of the MyPy error
    pass

My code runs fine (memory freed properly, consistent inheritance of the above if necessary, etc) when following the above definitions+usage conventions). POINTER(c_char) has the intended behavior in the rest of the code.

However, analyzing the above with MyPy, I get:

playground.py:10: error: Variable "playground.c_useable_c_str" is not valid as a type
playground.py:10: note: See https://mypy.readthedocs.io/en/latest/common_issues.html#variables-vs-type-aliases
Found 1 error in 1 file (checked 1 source file)

I get this error for anything that uses the c_useable_c_str alias. I, of course, read the section in the documentation linked above, and tried using Type and TypeAlias in a bunch of different ways - to no avail.

The only syntax that seems to make MyPy happy is

c_useable_c_str = pointer[c_char]

However, when actually running the code with this definition of the type alias, I get the following error (not seen by MyPy, so I suspect a bug on MyPy's end, or a lack of typing in the standard):

Traceback (most recent call last):
  File "/home/fulguritude/ProfessionalWork/LEDR/Orchestra-AvesTerra/Python_binding/playground2.py", line 92, in <module>
    c_useable_c_str = pointer[c_char]
TypeError: 'builtin_function_or_method' object is not subscriptable

Any ideas as to how I'm supposed to make things consistent ?

TLDR: what's the valid way to type hint, and alias, a "pointer to X" with MyPy and CTypes ?

Body:
I found an imperfect (but good enough) solution, based on what I found here: https://github.com/python/mypy/issues/7540 (comment by thijsmie, commented on May 21, 2021).

if not TYPE_CHECKING:
    # Monkeypatch typed pointer from typeshed into ctypes
    # NB: files that wish to import ctypes.pointer should all import `pointer` from this file instead
    class pointer_fix:
        @classmethod
        def __class_getitem__(cls, item):
            return POINTER(item)
    pointer = pointer_fix

It does solve MyPy's complaints concerning c_useable_c_str, and functions that use c_useable_c_str still get proper typing errors when the argument provided isn't of a compatible type, so that's good.

Well, EXCEPT for the following case:

class t_string(c_useable_c_str):
    pass

class t_string_p(pointer[t_string]):
    pass

where MyPy does not seem to be able to understand that t_string_p is compatible with the type pointer[pointer[c_char]]. For these cases, I used a type union; not ideal, but it got the job done.

I'll be leaving this question unanswered for now, in case someone, someday, can find a better solution.


问:
Argument 1 passed to Symfony\Bridge\Doctrine\Form\ChoiceList\IdReader::getIdValue() must be an object or null, int given
I'm new with Symfony. I've followed a couple of tutorials trying to learn dependent selects, so I use a DestinationFormType and a DestinationController to save a Destination. The JS part works well, but now when I try to save the entity throws the next exception:

Argument 1 passed to Symfony\Bridge\Doctrine\Form\ChoiceList\IdReader::getIdValue() must be an object or null, int given, called in \vendor\symfony\form\ChoiceList\ArrayChoiceList.php on line 200

The weird part is that it seems to be trying to convert a value (191) that need no conversion (stack call top):

The error is thrown for the country entity. This is my DestinationFormType

```<code><?php

namespace App\Form;

use App\Entity\City;
use App\Entity\Country;
use App\Entity\Destination;
use App\Entity\DestinationCategory;
use App\Entity\DestinationSubcategory;
use App\Entity\Region;
use App\Entity\State;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class DestinationFormType extends AbstractType
{
    /** @var EntityManagerInterface */
    private $em;

    /**
     * @param EntityManagerInterface $em
     */
    public function __construct(EntityManagerInterface $em)
    {
        $this->em = $em;
    }

    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('name')
            ->add('coordinates')
            ->add('kidsCost')
            ->add('adultsCost')
            ->add('description')
        ;

        $builder->addEventListener(FormEvents::PRE_SET_DATA, array($this, 'onPreSetData'));
        $builder->addEventListener(FormEvents::PRE_SUBMIT, array($this, 'onPreSubmit'));
    }

    /**
     * @param OptionsResolver $resolver
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => Destination::class
        ]);
    }

    /**
     * @param FormEvent $event
     */
    public function onPreSubmit(FormEvent $event) {
        $form = $event->getForm();
        $data = $event->getData();

        /** @var Region $region */
        $region = $this->em
            ->getRepository(Region::class)
            ->find($data['region']);

        /** @var Country $country */
        $country = $this->em
            ->getRepository(Country::class)
            ->find($data['country']);

        /** @var State $state */
        $state = $this->em
            ->getRepository(State::class)
            ->find($data['state']);

        /** @var City $city */
        $city = $this->em
            ->getRepository(City::class)
            ->find($data['city']);

        /** @var DestinationCategory $city */
        $category = $this->em
            ->getRepository(DestinationCategory::class)
            ->find($data['category']);

        /** @var DestinationCategory $city */
        $subcategory = $this->em
            ->getRepository(DestinationSubcategory::class)
            ->find($data['subcategory']);

        $this->addLocationDropdowns($form, $region, $country, $state, $city);
        $this->addCategoryDropdowns($form, $category, $subcategory);
    }

    /**
     * @param FormEvent $event
     */
    public function onPreSetData(FormEvent $event) {
        /** @var Destination $destination */
        $destination = $event->getData();

        $form = $event->getForm();
        $category =  $destination && $destination->getCategory() ? $destination->getCategory() : null;
        $subcategory =  $destination && $destination->getSubcategory() ? $destination->getSubcategory() : null;

        $region = $destination && $destination->getRegion() ? $destination->getRegion() : null;
        $country = $destination && $destination->getCountry() ? $destination->getCountry() : null;
        $state = $destination && $destination->getState() ? $destination->getState() : null;
        $city = $destination && $destination->getCity() ? $destination->getCity() : null;

        $this->addLocationDropdowns($form, $region, $country, $state, $city);
        $this->addCategoryDropdowns($form, $category, $subcategory);
    }

    /**
     * @param FormInterface $form
     * @param Region|null $region
     * @param Country|null $country
     * @param State|null $state
     * @param City|null $city
     */
    private function addLocationDropdowns(FormInterface $form, ?Region $region, ?Country $country, ?State $state, ?City $city) {
        $this->addRegionDropDown($form, $region);
        $this->addCountryDropdown($form, $region, $country);
        $this->addStateDropdown($form, $country, $state);
        $this->addCityDropdown($form, $state, $city);
    }

    /**
     * @param FormInterface $form
     * @param Region|null $region
     */
    private function addRegionDropDown(FormInterface $form, ?Region $region)
    {
        $form->add('region', EntityType::class,[
            'required' => true,
            'data' => $region,
            'placeholder' => 'Select a Region...',
            'class' => Region::class
        ]);
    }

    /**
     * @param FormInterface $form
     * @param Region|null $region
     * @param Country|null $country
     */
    private function addCountryDropdown(FormInterface $form, ?Region $region, ?Country $country)
    {
        $countries = array();

        if ($region) {
            $countryRepository = $this->em->getRepository(Country::class);
            $countries = $countryRepository->findByRegionId($region->getId());
        }

        $form->add('country', EntityType::class, [
            'required' => true,
            'data' => $country,
            'placeholder' => 'Select a Region first ...',
            'class' => Country::class,
            'choices' => $countries
        ]);
    }

    /**
     * @param FormInterface $form
     * @param Country|null $country
     * @param State|null $state
     */
    private function addStateDropdown(FormInterface $form, ?Country $country, ?State $state)
    {
        $states = array();

        if ($country) {
            $stateRepository = $this->em->getRepository(State::class);
            $states = $stateRepository->findByCountryId($country->getId());
        }

        $form->add('state', EntityType::class, [
            'required' => true,
            'data' => $state,
            'placeholder' => 'Select a Country first ...',
            'class' => State::class,
            'choices' => $states
        ]);
    }

    /**
     * @param FormInterface $form
     * @param State|null $state
     * @param City|null $city
     */
    private function addCityDropdown(FormInterface $form, ?State $state, ?City $city)
    {
        $cities = array();

        if ($state) {
            $cityRepository = $this->em->getRepository(City::class);
            $cities = $cityRepository->findByStateId($state->getId());
        }

        $form->add('city', EntityType::class, [
            'required' => true,
            'data' => $city,
            'placeholder' => 'Select a State first ...',
            'class' => State::class,
            'choices' => $cities
        ]);
    }

    /**
     * @param FormInterface $form
     * @param DestinationCategory|null $category
     * @param DestinationSubcategory|null $subcategory
     */
    private function addCategoryDropdowns(FormInterface $form, ?DestinationCategory $category, ?DestinationSubcategory $subcategory)
    {
        $this->addCategoryDropDown($form, $category);
        $this->addSubcategoryDropDown($form, $category, $subcategory);
    }

    /**
     * @param FormInterface $form
     * @param DestinationCategory|null $category
     */
    private function addCategoryDropDown(FormInterface $form, ?DestinationCategory $category)
    {
        $form->add('category', EntityType::class,[
            'required' => true,
            'data' => $category,
            'placeholder' => 'Select a Category...',
            'class' => DestinationCategory::class
        ]);
    }

    /**
     * @param FormInterface $form
     * @param DestinationCategory|null $category
     * @param DestinationSubcategory|null $subcategory
     */
    private function addSubcategoryDropDown(FormInterface $form, ?DestinationCategory $category, ?DestinationSubcategory $subcategory)
    {
        $subcategories = array();

        if ($category) {
            $countryRepository = $this->em->getRepository(DestinationSubcategory::class);
            $subcategories = $countryRepository->findByCategoryId($category->getId());
        }

        $form->add('subcategory', EntityType::class, [
            'required' => true,
            'data' => $subcategory,
            'placeholder' => 'Select a Category first ...',
            'class' => DestinationSubcategory::class,
            'choices' => $subcategories
        ]);
    }
}
</code>```

This is my DestinationController

```<code><?php

namespace App\Controller;

use App\Entity\Destination;
use App\Form\DestinationFormType;
use App\Repository\DestinationRepository;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;

class DestinationController extends AbstractController
{
    /**
     * @Route("admin/destination/new", name="admin_destination_new")
     *
     * @param EntityManagerInterface $em
     * @param Request $request
     *
     * @return Response
     */
    public function new(EntityManagerInterface $em, Request $request)
    {
        $form = $this->createForm(DestinationFormType::class);

        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            /** @var Destination $destination */
            $destination = $form->getData();
            $em->persist($destination);
            $em->flush();

            $this->addFlash('success', 'Destination created');
            $this->redirectToRoute('admin_destination_list');
        }

        return $this->render('destination/new.html.twig', [
            'destForm' => $form->createView()
        ]);
    }

    /**
     * @Route("admin/destination/{id}/edit", name="admin_destination_edit")
     *
     * @param Destination $destination
     * @param EntityManagerInterface $em
     * @param Request $request
     *
     * @return Response
     */
    public function edit(Destination $destination, EntityManagerInterface $em, Request $request)
    {
        $form = $this->createForm(DestinationFormType::class, $destination);

        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $em->persist($destination);
            $em->flush();

            $this->addFlash('success', 'Destiny updated');
            $this->redirectToRoute('admin_destination_list');
        }

        return $this->render('destination/edit.html.twig', [
            'destForm' => $form->createView()
        ]);
    }

    /**
     * @Route("admin/destination", name="admin_destination_list")
     * @param DestinationRepository $destRepo
     *
     * @return Response
     */
    public function list(DestinationRepository $destRepo){
        /** @var Destination $destinations */
        $destinations = $destRepo->findAll();

        return $this->render('destination/list.html.twig', [
            'destinations' => $destinations
        ]);
    }
}
</code>```

And this is my Destination entity

```<code><?php

namespace App\Entity;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Gedmo\SoftDeleteable\Traits\SoftDeleteableEntity;
use Gedmo\Timestampable\Traits\TimestampableEntity;
use Gedmo\Mapping\Annotation as Gedmo;

/**
 * @ORM\Entity(repositoryClass="App\Repository\DestinationRepository")
 */
class Destination
{
    use TimestampableEntity;
    use SoftDeleteableEntity;

    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=150)
     */
    private $name;

    /**
     * @ORM\Column(type="string", length=150, nullable=true)
     */
    private $coordinates;

    /**
     * @ORM\Column(type="string", length=150, unique=true)
     * @Gedmo\Slug(fields={"name"})
     */
    private $slug;

    /**
     * @ORM\Column(type="decimal", precision=8, scale=2, nullable=true)
     */
    private $kidsCost;

    /**
     * @ORM\Column(type="decimal", precision=8, scale=2, nullable=true)
     */
    private $adultsCost;

    /**
     * @ORM\ManyToMany(targetEntity="App\Entity\Package", mappedBy="destinations")
     */
    private $packages;

    /**
     * @ORM\Column(type="text", nullable=true)
     */
    private $description;

    /**
     * @ORM\Column(type="string", length=255, nullable=true)
     */
    private $address;

    /**
     * @ORM\ManyToOne(targetEntity="App\Entity\City")
     * @ORM\JoinColumn(nullable=false)
     */
    private $city;

    /**
     * @ORM\ManyToOne(targetEntity="App\Entity\State")
     * @ORM\JoinColumn(nullable=false)
     */
    private $state;

    /**
     * @ORM\ManyToOne(targetEntity="App\Entity\Region", inversedBy="destinations")
     * @ORM\JoinColumn(nullable=false)
     */
    private $region;

    /**
     * @ORM\ManyToOne(targetEntity="App\Entity\Country", inversedBy="destinations")
     * @ORM\JoinColumn(nullable=false)
     */
    private $country;

    /**
     * @ORM\ManyToOne(targetEntity="App\Entity\DestinationCategory", inversedBy="destinations")
     * @ORM\JoinColumn(nullable=false)
     */
    private $category;

    /**
     * @ORM\ManyToOne(targetEntity="App\Entity\DestinationSubcategory", inversedBy="destinations")
     * @ORM\JoinColumn(nullable=false)
     */
    private $subcategory;

    public function __construct()
    {
        $this->packages = new ArrayCollection();
    }

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

    public function getName(): ?string
    {
        return $this->name;
    }

    public function setName(string $name): self
    {
        $this->name = $name;

        return $this;
    }

    public function getCoordinates(): ?string
    {
        return $this->coordinates;
    }

    public function setCoordinates(?string $coordinates): self
    {
        $this->coordinates = $coordinates;

        return $this;
    }

    public function getSlug(): ?string
    {
        return $this->slug;
    }

    public function setSlug(string $slug): self
    {
        $this->slug = $slug;

        return $this;
    }

    public function getKidsCost(): ?string
    {
        return $this->kidsCost;
    }

    public function setKidsCost(?string $kidsCost): self
    {
        $this->kidsCost = $kidsCost;

        return $this;
    }

    public function getAdultsCost(): ?string
    {
        return $this->adultsCost;
    }

    public function setAdultsCost(?string $adultsCost): self
    {
        $this->adultsCost = $adultsCost;

        return $this;
    }

    /**
     * @return Collection|Package[]
     */
    public function getPackages(): Collection
    {
        return $this->packages;
    }

    public function addPackage(Package $package): self
    {
        if (!$this->packages->contains($package)) {
            $this->packages[] = $package;
            $package->addDestination($this);
        }

        return $this;
    }

    public function removePackage(Package $package): self
    {
        if ($this->packages->contains($package)) {
            $this->packages->removeElement($package);
            $package->removeDestination($this);
        }

        return $this;
    }

    public function getDescription(): ?string
    {
        return $this->description;
    }

    public function setDescription(?string $description): self
    {
        $this->description = $description;

        return $this;
    }

    public function getAddress(): ?string
    {
        return $this->address;
    }

    public function setAddress(?string $address): self
    {
        $this->address = $address;

        return $this;
    }

    public function getCity(): ?City
    {
        return $this->city;
    }

    public function getState(): ?State
    {
        return $this->getCity() ? $this->getCity()->getState() : null;
    }

    public function getCountry(): ?Country
    {
        return $this->getCity()? $this->getState()->getCountry() : null;
    }

    public function getRegion() : ?Region
    {
        return $this->getCity()? $this->getCountry()->getRegion() : null;
    }

    public function setCity(?City $city): self
    {
        $this->city = $city;

        return $this;
    }

    public function setState(?State $state): self
    {
        $this->state = $state;

        return $this;
    }

    public function setRegion(?Region $region): self
    {
        $this->region = $region;

        return $this;
    }

    public function setCountry(?Country $country): self
    {
        $this->country = $country;

        return $this;
    }

    public function getCategory(): ?DestinationCategory
    {
        return $this->category;
    }

    public function setCategory(?DestinationCategory $category): self
    {
        $this->category = $category;

        return $this;
    }

    public function getSubcategory(): ?DestinationSubcategory
    {
        return $this->subcategory;
    }

    public function setSubcategory(?DestinationSubcategory $subcategory): self
    {
        $this->subcategory = $subcategory;

        return $this;
    }
}
</code>```

Can someone point me to the right direction to solve this?

Ps. I'm using symfony 5.0.7.

Thanks in advance

答:
I had the same error after migration to Symfony 5.4 with User entity.
Now getRoles() function must return list of roles as string.
In my case I have an entity Role.

I solved the issue by adding getRolesObjects() in User entity:

```<code>public function getRolesObjects(): array
{
    if(is_array($this->roles)) {
        return $this->roles;
    } else if($this->roles && ($this->roles instanceof Collection)) {
        return $this->roles->toArray();
    } else {
        return [];
    }
}
</code>```

And add a custom getter in the FormType:

```<code>$builder
            ->add('firstName', TextType::class)
            ->add('lastName', TextType::class)
            ->add('email',  TextType::class)
            ->add('roles', EntityType::class, [
                'class' => Role::class,
                'multiple' => true,

                'getter' => function (User $user, FormInterface $form): array {
                    return $user->getRolesObjects();
                }

            ]);
</code>```

Body:
I'm new with Symfony. I've followed a couple of tutorials trying to learn dependent selects, so I use a DestinationFormType and a DestinationController to save a Destination. The JS part works well, but now when I try to save the entity throws the next exception:

Argument 1 passed to Symfony\Bridge\Doctrine\Form\ChoiceList\IdReader::getIdValue() must be an object or null, int given, called in \vendor\symfony\form\ChoiceList\ArrayChoiceList.php on line 200

The weird part is that it seems to be trying to convert a value (191) that need no conversion (stack call top):

The error is thrown for the country entity. This is my DestinationFormType

<?php

namespace App\Form;

use App\Entity\City;
use App\Entity\Country;
use App\Entity\Destination;
use App\Entity\DestinationCategory;
use App\Entity\DestinationSubcategory;
use App\Entity\Region;
use App\Entity\State;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class DestinationFormType extends AbstractType
{
    /** @var EntityManagerInterface */
    private $em;

    /**
     * @param EntityManagerInterface $em
     */
    public function __construct(EntityManagerInterface $em)
    {
        $this->em = $em;
    }

    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('name')
            ->add('coordinates')
            ->add('kidsCost')
            ->add('adultsCost')
            ->add('description')
        ;

        $builder->addEventListener(FormEvents::PRE_SET_DATA, array($this, 'onPreSetData'));
        $builder->addEventListener(FormEvents::PRE_SUBMIT, array($this, 'onPreSubmit'));
    }

    /**
     * @param OptionsResolver $resolver
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => Destination::class
        ]);
    }

    /**
     * @param FormEvent $event
     */
    public function onPreSubmit(FormEvent $event) {
        $form = $event->getForm();
        $data = $event->getData();

        /** @var Region $region */
        $region = $this->em
            ->getRepository(Region::class)
            ->find($data['region']);

        /** @var Country $country */
        $country = $this->em
            ->getRepository(Country::class)
            ->find($data['country']);

        /** @var State $state */
        $state = $this->em
            ->getRepository(State::class)
            ->find($data['state']);

        /** @var City $city */
        $city = $this->em
            ->getRepository(City::class)
            ->find($data['city']);

        /** @var DestinationCategory $city */
        $category = $this->em
            ->getRepository(DestinationCategory::class)
            ->find($data['category']);

        /** @var DestinationCategory $city */
        $subcategory = $this->em
            ->getRepository(DestinationSubcategory::class)
            ->find($data['subcategory']);

        $this->addLocationDropdowns($form, $region, $country, $state, $city);
        $this->addCategoryDropdowns($form, $category, $subcategory);
    }

    /**
     * @param FormEvent $event
     */
    public function onPreSetData(FormEvent $event) {
        /** @var Destination $destination */
        $destination = $event->getData();

        $form = $event->getForm();
        $category =  $destination && $destination->getCategory() ? $destination->getCategory() : null;
        $subcategory =  $destination && $destination->getSubcategory() ? $destination->getSubcategory() : null;

        $region = $destination && $destination->getRegion() ? $destination->getRegion() : null;
        $country = $destination && $destination->getCountry() ? $destination->getCountry() : null;
        $state = $destination && $destination->getState() ? $destination->getState() : null;
        $city = $destination && $destination->getCity() ? $destination->getCity() : null;

        $this->addLocationDropdowns($form, $region, $country, $state, $city);
        $this->addCategoryDropdowns($form, $category, $subcategory);
    }

    /**
     * @param FormInterface $form
     * @param Region|null $region
     * @param Country|null $country
     * @param State|null $state
     * @param City|null $city
     */
    private function addLocationDropdowns(FormInterface $form, ?Region $region, ?Country $country, ?State $state, ?City $city) {
        $this->addRegionDropDown($form, $region);
        $this->addCountryDropdown($form, $region, $country);
        $this->addStateDropdown($form, $country, $state);
        $this->addCityDropdown($form, $state, $city);
    }

    /**
     * @param FormInterface $form
     * @param Region|null $region
     */
    private function addRegionDropDown(FormInterface $form, ?Region $region)
    {
        $form->add('region', EntityType::class,[
            'required' => true,
            'data' => $region,
            'placeholder' => 'Select a Region...',
            'class' => Region::class
        ]);
    }

    /**
     * @param FormInterface $form
     * @param Region|null $region
     * @param Country|null $country
     */
    private function addCountryDropdown(FormInterface $form, ?Region $region, ?Country $country)
    {
        $countries = array();

        if ($region) {
            $countryRepository = $this->em->getRepository(Country::class);
            $countries = $countryRepository->findByRegionId($region->getId());
        }

        $form->add('country', EntityType::class, [
            'required' => true,
            'data' => $country,
            'placeholder' => 'Select a Region first ...',
            'class' => Country::class,
            'choices' => $countries
        ]);
    }

    /**
     * @param FormInterface $form
     * @param Country|null $country
     * @param State|null $state
     */
    private function addStateDropdown(FormInterface $form, ?Country $country, ?State $state)
    {
        $states = array();

        if ($country) {
            $stateRepository = $this->em->getRepository(State::class);
            $states = $stateRepository->findByCountryId($country->getId());
        }

        $form->add('state', EntityType::class, [
            'required' => true,
            'data' => $state,
            'placeholder' => 'Select a Country first ...',
            'class' => State::class,
            'choices' => $states
        ]);
    }

    /**
     * @param FormInterface $form
     * @param State|null $state
     * @param City|null $city
     */
    private function addCityDropdown(FormInterface $form, ?State $state, ?City $city)
    {
        $cities = array();

        if ($state) {
            $cityRepository = $this->em->getRepository(City::class);
            $cities = $cityRepository->findByStateId($state->getId());
        }

        $form->add('city', EntityType::class, [
            'required' => true,
            'data' => $city,
            'placeholder' => 'Select a State first ...',
            'class' => State::class,
            'choices' => $cities
        ]);
    }

    /**
     * @param FormInterface $form
     * @param DestinationCategory|null $category
     * @param DestinationSubcategory|null $subcategory
     */
    private function addCategoryDropdowns(FormInterface $form, ?DestinationCategory $category, ?DestinationSubcategory $subcategory)
    {
        $this->addCategoryDropDown($form, $category);
        $this->addSubcategoryDropDown($form, $category, $subcategory);
    }

    /**
     * @param FormInterface $form
     * @param DestinationCategory|null $category
     */
    private function addCategoryDropDown(FormInterface $form, ?DestinationCategory $category)
    {
        $form->add('category', EntityType::class,[
            'required' => true,
            'data' => $category,
            'placeholder' => 'Select a Category...',
            'class' => DestinationCategory::class
        ]);
    }

    /**
     * @param FormInterface $form
     * @param DestinationCategory|null $category
     * @param DestinationSubcategory|null $subcategory
     */
    private function addSubcategoryDropDown(FormInterface $form, ?DestinationCategory $category, ?DestinationSubcategory $subcategory)
    {
        $subcategories = array();

        if ($category) {
            $countryRepository = $this->em->getRepository(DestinationSubcategory::class);
            $subcategories = $countryRepository->findByCategoryId($category->getId());
        }

        $form->add('subcategory', EntityType::class, [
            'required' => true,
            'data' => $subcategory,
            'placeholder' => 'Select a Category first ...',
            'class' => DestinationSubcategory::class,
            'choices' => $subcategories
        ]);
    }
}

This is my DestinationController

<?php

namespace App\Controller;

use App\Entity\Destination;
use App\Form\DestinationFormType;
use App\Repository\DestinationRepository;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;

class DestinationController extends AbstractController
{
    /**
     * @Route("admin/destination/new", name="admin_destination_new")
     *
     * @param EntityManagerInterface $em
     * @param Request $request
     *
     * @return Response
     */
    public function new(EntityManagerInterface $em, Request $request)
    {
        $form = $this->createForm(DestinationFormType::class);

        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            /** @var Destination $destination */
            $destination = $form->getData();
            $em->persist($destination);
            $em->flush();

            $this->addFlash('success', 'Destination created');
            $this->redirectToRoute('admin_destination_list');
        }

        return $this->render('destination/new.html.twig', [
            'destForm' => $form->createView()
        ]);
    }

    /**
     * @Route("admin/destination/{id}/edit", name="admin_destination_edit")
     *
     * @param Destination $destination
     * @param EntityManagerInterface $em
     * @param Request $request
     *
     * @return Response
     */
    public function edit(Destination $destination, EntityManagerInterface $em, Request $request)
    {
        $form = $this->createForm(DestinationFormType::class, $destination);

        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $em->persist($destination);
            $em->flush();

            $this->addFlash('success', 'Destiny updated');
            $this->redirectToRoute('admin_destination_list');
        }

        return $this->render('destination/edit.html.twig', [
            'destForm' => $form->createView()
        ]);
    }

    /**
     * @Route("admin/destination", name="admin_destination_list")
     * @param DestinationRepository $destRepo
     *
     * @return Response
     */
    public function list(DestinationRepository $destRepo){
        /** @var Destination $destinations */
        $destinations = $destRepo->findAll();

        return $this->render('destination/list.html.twig', [
            'destinations' => $destinations
        ]);
    }
}

And this is my Destination entity

<?php

namespace App\Entity;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Gedmo\SoftDeleteable\Traits\SoftDeleteableEntity;
use Gedmo\Timestampable\Traits\TimestampableEntity;
use Gedmo\Mapping\Annotation as Gedmo;

/**
 * @ORM\Entity(repositoryClass="App\Repository\DestinationRepository")
 */
class Destination
{
    use TimestampableEntity;
    use SoftDeleteableEntity;

    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=150)
     */
    private $name;

    /**
     * @ORM\Column(type="string", length=150, nullable=true)
     */
    private $coordinates;

    /**
     * @ORM\Column(type="string", length=150, unique=true)
     * @Gedmo\Slug(fields={"name"})
     */
    private $slug;

    /**
     * @ORM\Column(type="decimal", precision=8, scale=2, nullable=true)
     */
    private $kidsCost;

    /**
     * @ORM\Column(type="decimal", precision=8, scale=2, nullable=true)
     */
    private $adultsCost;

    /**
     * @ORM\ManyToMany(targetEntity="App\Entity\Package", mappedBy="destinations")
     */
    private $packages;

    /**
     * @ORM\Column(type="text", nullable=true)
     */
    private $description;

    /**
     * @ORM\Column(type="string", length=255, nullable=true)
     */
    private $address;

    /**
     * @ORM\ManyToOne(targetEntity="App\Entity\City")
     * @ORM\JoinColumn(nullable=false)
     */
    private $city;

    /**
     * @ORM\ManyToOne(targetEntity="App\Entity\State")
     * @ORM\JoinColumn(nullable=false)
     */
    private $state;

    /**
     * @ORM\ManyToOne(targetEntity="App\Entity\Region", inversedBy="destinations")
     * @ORM\JoinColumn(nullable=false)
     */
    private $region;

    /**
     * @ORM\ManyToOne(targetEntity="App\Entity\Country", inversedBy="destinations")
     * @ORM\JoinColumn(nullable=false)
     */
    private $country;

    /**
     * @ORM\ManyToOne(targetEntity="App\Entity\DestinationCategory", inversedBy="destinations")
     * @ORM\JoinColumn(nullable=false)
     */
    private $category;

    /**
     * @ORM\ManyToOne(targetEntity="App\Entity\DestinationSubcategory", inversedBy="destinations")
     * @ORM\JoinColumn(nullable=false)
     */
    private $subcategory;

    public function __construct()
    {
        $this->packages = new ArrayCollection();
    }

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

    public function getName(): ?string
    {
        return $this->name;
    }

    public function setName(string $name): self
    {
        $this->name = $name;

        return $this;
    }

    public function getCoordinates(): ?string
    {
        return $this->coordinates;
    }

    public function setCoordinates(?string $coordinates): self
    {
        $this->coordinates = $coordinates;

        return $this;
    }

    public function getSlug(): ?string
    {
        return $this->slug;
    }

    public function setSlug(string $slug): self
    {
        $this->slug = $slug;

        return $this;
    }

    public function getKidsCost(): ?string
    {
        return $this->kidsCost;
    }

    public function setKidsCost(?string $kidsCost): self
    {
        $this->kidsCost = $kidsCost;

        return $this;
    }

    public function getAdultsCost(): ?string
    {
        return $this->adultsCost;
    }

    public function setAdultsCost(?string $adultsCost): self
    {
        $this->adultsCost = $adultsCost;

        return $this;
    }

    /**
     * @return Collection|Package[]
     */
    public function getPackages(): Collection
    {
        return $this->packages;
    }

    public function addPackage(Package $package): self
    {
        if (!$this->packages->contains($package)) {
            $this->packages[] = $package;
            $package->addDestination($this);
        }

        return $this;
    }

    public function removePackage(Package $package): self
    {
        if ($this->packages->contains($package)) {
            $this->packages->removeElement($package);
            $package->removeDestination($this);
        }

        return $this;
    }

    public function getDescription(): ?string
    {
        return $this->description;
    }

    public function setDescription(?string $description): self
    {
        $this->description = $description;

        return $this;
    }

    public function getAddress(): ?string
    {
        return $this->address;
    }

    public function setAddress(?string $address): self
    {
        $this->address = $address;

        return $this;
    }

    public function getCity(): ?City
    {
        return $this->city;
    }

    public function getState(): ?State
    {
        return $this->getCity() ? $this->getCity()->getState() : null;
    }

    public function getCountry(): ?Country
    {
        return $this->getCity()? $this->getState()->getCountry() : null;
    }

    public function getRegion() : ?Region
    {
        return $this->getCity()? $this->getCountry()->getRegion() : null;
    }

    public function setCity(?City $city): self
    {
        $this->city = $city;

        return $this;
    }

    public function setState(?State $state): self
    {
        $this->state = $state;

        return $this;
    }

    public function setRegion(?Region $region): self
    {
        $this->region = $region;

        return $this;
    }

    public function setCountry(?Country $country): self
    {
        $this->country = $country;

        return $this;
    }

    public function getCategory(): ?DestinationCategory
    {
        return $this->category;
    }

    public function setCategory(?DestinationCategory $category): self
    {
        $this->category = $category;

        return $this;
    }

    public function getSubcategory(): ?DestinationSubcategory
    {
        return $this->subcategory;
    }

    public function setSubcategory(?DestinationSubcategory $subcategory): self
    {
        $this->subcategory = $subcategory;

        return $this;
    }
}

Can someone point me to the right direction to solve this?

Ps. I'm using symfony 5.0.7.

Thanks in advance

Body:
I had the same error after migration to Symfony 5.4 with User entity.
Now getRoles() function must return list of roles as string.
In my case I have an entity Role.

I solved the issue by adding getRolesObjects() in User entity:

public function getRolesObjects(): array
{
    if(is_array($this->roles)) {
        return $this->roles;
    } else if($this->roles && ($this->roles instanceof Collection)) {
        return $this->roles->toArray();
    } else {
        return [];
    }
}

And add a custom getter in the FormType:

$builder
            ->add('firstName', TextType::class)
            ->add('lastName', TextType::class)
            ->add('email',  TextType::class)
            ->add('roles', EntityType::class, [
                'class' => Role::class,
                'multiple' => true,

                'getter' => function (User $user, FormInterface $form): array {
                    return $user->getRolesObjects();
                }

            ]);


问:
Eslint not showing warnings - React
On my new project, ESLint is not outputting warnings like before, I'm using VSCode. If I have an unsed var somewhere in my code, it doesn't show the warning in the  terminal output anymore. Only in the problem tab.

Here's my eslint config file:

.eslintrc.json

```<code>{
  "env": {
      "browser": true,
      "es6": true
  },
  "extends": [
      "plugin:react/recommended",
      "airbnb-typescript",
      "plugin:@typescript-eslint/recommended",
      "plugin:@typescript-eslint/eslint-recommended",
      "prettier/@typescript-eslint",
      "plugin:prettier/recommended"
  ],
  "globals": {
      "Atomics": "readonly",
      "SharedArrayBuffer": "readonly"
  },
  "parser": "@typescript-eslint/parser",
  "parserOptions": {
      "ecmaFeatures": {
          "jsx": true
      },
      "ecmaVersion": 2018,
      "sourceType": "module",
      "project": "./tsconfig.json"
  },
  "plugins": [
      "react",
      "react-hooks",
      "@typescript-eslint",
      "prettier"
  ],
  "rules": {
    "prettier/prettier": "error",
    "react-hooks/rules-of-hooks":"error",
    "react-hooks/exhaustive-deps": "warn",
    "camelcase": "off",
    "@typescript-eslint/camelcase": "off",
    "react/jsx-filename-extension": [1, {"extensions": [".tsx"]}],
    "import/prefer-default-export": "off",
    "react/jsx-one-expression-per-line": "off",
    "react/jsx-props-no-spreading": "off",
    "react/prop-types": "off",
    "no-unused-expressions": "off",
    "@typescript-eslint/no-unused-vars": "error",
    "@typescript-eslint/explicit-function-return-type": [
      "error",
      {
        "allowExpressions": true
      }
    ],
    "import/extensions": [
      "error",
      "ignorePackages",
      {
        "ts": "never",
        "tsx": "never"
      }
    ],
    "semi":"off"
  },
  "settings": {
    "import/resolver": {
      "typescript": {}
    }
  }
}

</code>```

and Here is my package.json devDependencies:

package.json

```<code>  "dependencies": {
    ...,
    "react": "^17.0.1",
    "react-dom": "^17.0.1",
    "react-scripts": "^4.0.2"
  }
  "devDependencies": {
    "@types/react-router-dom": "^5.1.7",
    "@types/styled-components": "^5.1.7",
    "@typescript-eslint/eslint-plugin": "^4.14.2",
    "@typescript-eslint/parser": "^4.14.2",
    "eslint": "^7.19.0",
    "eslint-config-airbnb": "^18.2.1",
    "eslint-config-airbnb-typescript": "^12.3.1",
    "eslint-config-prettier": "^7.2.0",
    "eslint-import-resolver-typescript": "^2.3.0",
    "eslint-plugin-import": "^2.22.1",
    "eslint-plugin-jsx-a11y": "^6.4.1",
    "eslint-plugin-prettier": "^3.3.1",
    "eslint-plugin-react": "^7.22.0",
    "eslint-plugin-react-hooks": "^4.2.0",
    "husky": "^5.0.8",
    "prettier": "^2.2.1",
    "prettier-eslint-cli": "^5.0.0",
    "typescript": "^4.1.3"
  }
</code>```

答:
If your project started from a Create React App then it might happens because of the way React team implemented eslint in the webpack.config.dev file.

When your project is being built, it uses eslint-webpack-plugin to make sure that eslint error appears on your app as an overlay.

The problem is that in their default configuration they point eslint to a specific eslint configuration (eslint-config-react-app/base see )

```<code>        new ESLintPlugin({
          // Plugin options
          extensions: ['js', 'mjs', 'jsx', 'ts', 'tsx'],
          formatter: require.resolve('react-dev-utils/eslintFormatter'),
          eslintPath: require.resolve('eslint'),
          failOnError: !(isEnvDevelopment && emitErrorsAsWarnings),
          context: paths.appSrc,
          cache: true,
          cacheLocation: path.resolve(
            paths.appNodeModules,
            '.cache/.eslintcache'
          ),
          // ESLint class options
          cwd: paths.appPath,
          resolvePluginsRelativeTo: __dirname,
          baseConfig: {
            extends: [require.resolve('eslint-config-react-app/base')], // <-- here
            rules: {
              ...(!hasJsxRuntime && {
                'react/react-in-jsx-scope': 'error',
              }),
            },
          },
        }),
</code>```

I always use the eject option and after removing all the properties under // ESLint class options, the project started to look at my own eslint configuration file and everything went as expected.

I don't know why they set it like that tbh.

Title: Eslint not showing warnings - React

Body:
On my new project, ESLint is not outputting warnings like before, I'm using VSCode. If I have an unsed var somewhere in my code, it doesn't show the warning in the  terminal output anymore. Only in the problem tab.

Here's my eslint config file:

.eslintrc.json

{
  "env": {
      "browser": true,
      "es6": true
  },
  "extends": [
      "plugin:react/recommended",
      "airbnb-typescript",
      "plugin:@typescript-eslint/recommended",
      "plugin:@typescript-eslint/eslint-recommended",
      "prettier/@typescript-eslint",
      "plugin:prettier/recommended"
  ],
  "globals": {
      "Atomics": "readonly",
      "SharedArrayBuffer": "readonly"
  },
  "parser": "@typescript-eslint/parser",
  "parserOptions": {
      "ecmaFeatures": {
          "jsx": true
      },
      "ecmaVersion": 2018,
      "sourceType": "module",
      "project": "./tsconfig.json"
  },
  "plugins": [
      "react",
      "react-hooks",
      "@typescript-eslint",
      "prettier"
  ],
  "rules": {
    "prettier/prettier": "error",
    "react-hooks/rules-of-hooks":"error",
    "react-hooks/exhaustive-deps": "warn",
    "camelcase": "off",
    "@typescript-eslint/camelcase": "off",
    "react/jsx-filename-extension": [1, {"extensions": [".tsx"]}],
    "import/prefer-default-export": "off",
    "react/jsx-one-expression-per-line": "off",
    "react/jsx-props-no-spreading": "off",
    "react/prop-types": "off",
    "no-unused-expressions": "off",
    "@typescript-eslint/no-unused-vars": "error",
    "@typescript-eslint/explicit-function-return-type": [
      "error",
      {
        "allowExpressions": true
      }
    ],
    "import/extensions": [
      "error",
      "ignorePackages",
      {
        "ts": "never",
        "tsx": "never"
      }
    ],
    "semi":"off"
  },
  "settings": {
    "import/resolver": {
      "typescript": {}
    }
  }
}

and Here is my package.json devDependencies:

package.json

  "dependencies": {
    ...,
    "react": "^17.0.1",
    "react-dom": "^17.0.1",
    "react-scripts": "^4.0.2"
  }
  "devDependencies": {
    "@types/react-router-dom": "^5.1.7",
    "@types/styled-components": "^5.1.7",
    "@typescript-eslint/eslint-plugin": "^4.14.2",
    "@typescript-eslint/parser": "^4.14.2",
    "eslint": "^7.19.0",
    "eslint-config-airbnb": "^18.2.1",
    "eslint-config-airbnb-typescript": "^12.3.1",
    "eslint-config-prettier": "^7.2.0",
    "eslint-import-resolver-typescript": "^2.3.0",
    "eslint-plugin-import": "^2.22.1",
    "eslint-plugin-jsx-a11y": "^6.4.1",
    "eslint-plugin-prettier": "^3.3.1",
    "eslint-plugin-react": "^7.22.0",
    "eslint-plugin-react-hooks": "^4.2.0",
    "husky": "^5.0.8",
    "prettier": "^2.2.1",
    "prettier-eslint-cli": "^5.0.0",
    "typescript": "^4.1.3"
  }

Body:
If your project started from a Create React App then it might happens because of the way React team implemented eslint in the webpack.config.dev file.

When your project is being built, it uses eslint-webpack-plugin to make sure that eslint error appears on your app as an overlay.

The problem is that in their default configuration they point eslint to a specific eslint configuration (eslint-config-react-app/base see )

        new ESLintPlugin({
          // Plugin options
          extensions: ['js', 'mjs', 'jsx', 'ts', 'tsx'],
          formatter: require.resolve('react-dev-utils/eslintFormatter'),
          eslintPath: require.resolve('eslint'),
          failOnError: !(isEnvDevelopment && emitErrorsAsWarnings),
          context: paths.appSrc,
          cache: true,
          cacheLocation: path.resolve(
            paths.appNodeModules,
            '.cache/.eslintcache'
          ),
          // ESLint class options
          cwd: paths.appPath,
          resolvePluginsRelativeTo: __dirname,
          baseConfig: {
            extends: [require.resolve('eslint-config-react-app/base')], // <-- here
            rules: {
              ...(!hasJsxRuntime && {
                'react/react-in-jsx-scope': 'error',
              }),
            },
          },
        }),

I always use the eject option and after removing all the properties under // ESLint class options, the project started to look at my own eslint configuration file and everything went as expected.

I don't know why they set it like that tbh.


问:
angular - how to combine few ngclass together in one div
I would like to combine multiple ngClass if else statement together,  I have tried but not able to resolve it.

```<code><div
    [ngClass]="[tabItem === 'unavailable' ? 'background-grey' : selected ? 'card-selected cursor' : 'cursor']"
    [ngClass]="[hasAlerts ? 'banner' : 'no-banner']">
</div>
</code>```

My attempt:

```<code><div
    [ngClass]="[{'banner': hasAlerts, 'no-banner': !hasAlerts}, tabItem === 'unavailable' ? 'background-grey' : selected ? 'card-selected cursor' : 'cursor']">
</div>
</code>```

答:
I'm finally able to resolve the issue by using this method</p>
```<code><div
[ngClass]="{'banner': !!alerts?.length, 'no-banner' : !alerts?.length, 'background-grey': tabItem === 'unavailable', 'cursor': tabItem === 'available', 'card-selected': selected}"
></div>
</code>```

Body:
I would like to combine multiple ngClass if else statement together,  I have tried but not able to resolve it.

My attempt:

Body:
I'm finally able to resolve the issue by using this method

<div
[ngClass]="{'banner': !!alerts?.length, 'no-banner' : !alerts?.length, 'background-grey': tabItem === 'unavailable', 'cursor': tabItem === 'available', 'card-selected': selected}"
></div>


问:
How to set a property value based on a variable in Javascript
The problem is I have this piece of code (Jquery UI):

```<code>    $("#dialog-confirm").dialog({
        resizable: false,
        modal: true,
        buttons: {
            "Remove": function() {
                $(this).dialog("close");
            },
            "Cancel": function() {
                $(this).dialog("close");
            }
        }
    });
</code>```

and now I have to internationalize it by giving to each button a word translation. I have the translation on the variables STR_REMOVE and STR_CANCEL, but if I do something like

```<code>        buttons: {
            STR_REMOVE: function() {
                $(this).dialog("close");
            },
            STR_CANCEL: function() {
                $(this).dialog("close");
            }
        }
</code>```

the buttons (the properties) take the value "STR_REMOVE" and "STR_CANCEL", not its content. So, the question is, what can I do?

答:
```<code>var buttons = {};
buttons[STR_REMOVE] = function() {
                $(this).dialog("close");
            };
buttons[STR_CANCEL] = function() {
                $(this).dialog("close");
            };
$("#dialog-confirm").dialog({
     resizable: false,
     modal: true,
     buttons: buttons
});
</code>```

Body:
The problem is I have this piece of code (Jquery UI):

    $("#dialog-confirm").dialog({
        resizable: false,
        modal: true,
        buttons: {
            "Remove": function() {
                $(this).dialog("close");
            },
            "Cancel": function() {
                $(this).dialog("close");
            }
        }
    });

and now I have to internationalize it by giving to each button a word translation. I have the translation on the variables STR_REMOVE and STR_CANCEL, but if I do something like

        buttons: {
            STR_REMOVE: function() {
                $(this).dialog("close");
            },
            STR_CANCEL: function() {
                $(this).dialog("close");
            }
        }

the buttons (the properties) take the value "STR_REMOVE" and "STR_CANCEL", not its content. So, the question is, what can I do?


问:
Enable button when conditions are true in VueJS 3
I am currently working on a form and are having some problems to enable a button when conditions are filled.

Currently i created a form that contains inputs to fill a name, a phonenumber, some options and a message. When the conditions are filled i want to enable the button i already disabled.

Does anyone have some tips on who i can enable the button again to submit the form?

```<code><template>

    <div class="contact">
  <h1>Vi uppskattar alla frågor som du har angående denna applikation!</h1>
  <h2> Vänligen skriv ett meddelande här nedan så ska vi göra allt vi kan för att svara så snart som möjligt!</h2>
</div>

  <form @submit.prevent="submitForm">
    <div class="form-control" :class="{invalid: fullNameValidation === 'invalid'}">
      <label for="name">Namn</label>
      <input id="name" name="name" type="text" v-model="fullName" @blur="validateInput">
      <p v-if="fullNameValidation === 'invalid'">Vänligen fyll i ett namn</p>
    </div>
    <div class="form-control" :class="{invalid: phoneValidation === 'invalid'}">
      <label for="phone">Telefonnummer</label>
      <input id="phone" name="phone" type="number" v-model="phoneNr" @blur="validatePhone" pattern="[0-9]*">
      <p v-if="phoneValidation === 'invalid'">Vänligen fyll i ett giltigt telefonnummer</p>
    </div>
    <div class="form-control">
      <label for="referrer">Hur fick du kännedom av denna applikation?</label>
      <select id="referrer" name="referrer" v-model="referrer">
        <option value="" disabled hidden>Välj ett alternativ</option>
        <option value="internet">Internet</option>
        <option value="friends">Vänner</option>
        <option value="newspaper">Nyhetstidningar</option>
        <option value="other">Annat</option>
      </select>
    </div>
    <div class="form-control" :class="{invalid: messageValidation === 'invalid'}">
      <label for="message">Meddelande</label>
      <textarea name="message" id="message" cols="30" rows="10" v-model="message" @blur="validateMessage"></textarea>
       <p v-if="messageValidation === 'invalid'">Vänligen fyll i ditt meddelande</p>
    </div>

    <div>
      <button v-on:click="$router.push('thankyou')" :disabled="!isComplete" id="myBtn">Skicka meddelande</button>
    </div>
  </form>
</template>

<script>
export default {
    data() {
        return {
            fullName: '',
            fullNameValidation: 'pending',
            phoneNr: 'null',
            phoneValidation: 'pending',
            referrer: '',
            messageValidation: 'pending'
        }
    },

    methods: {
        submitForm() {
            this.fullName = '';
        },
        validateInput() {
            if (this.fullName === '') {
                this.fullNameValidation = 'valid'
            } else {
                this.fullNameValidation = 'invalid'
            }
        },
        validatePhone() {
            if (this.phoneNr > 10) {
                this.phoneValidation = 'valid'
            } else {
                this.phoneValidation = 'invalid'
            }
        },
         validateMessage() {
            if (this.messageValidation > 1) {
                this.messageValidation = 'valid'
            } else {
                this.messageValidation = 'invalid'
            }
        },

        computed: {
       isComplete() {
          return Object.values(this.fields).every(({valid}) => valid)
      }
  }
    }
}
</script>
</code>```

答:
Consolidate your form fields into a single model, along with the errors object.

Then use Object.keys to grab known field keys to do validation on.

```<code>export default {
  data() {
    return {
      form: {
        errors: {},
        values: {
          fullName: '',
          phoneNr: '',
          referrer: '',
        }
      }
    }
  },
  methods: {
    validate(field) {

      let fields = []
      // single field
      if (field) {
        delete this.form.errors[field]
        fields.push(field)
      } else {
        this.form.errors = {}
        // all fields
        fields = Object.keys(this.form.values)
      }

      if (fields.includes('fullName')) {
        if (this.form.values.fullName === '') {
          this.form.errors.fullName = 'Enter your full name'
        } else if (this.fullName !== some other validation) {
          ...
        }
      }

      if (fields.includes('phoneNr')) {
        if (this.form.values.phoneNr === '') {
          this.form.errors.phoneNr = 'Enter your phone number'
        }
      }

      if (fields.includes('referrer')) {
        if (this.form.values.referrer === '') {
          this.form.errors.referrer = 'Enter referrer'
        }
      }

      // if errors is empty return true
      return !Object.keys(this.form.errors).length
    },
    submit() {
      // validate all
      if (this.validate()) {
        // do some thing, form is valid, if native form handler, return true/false
      }
    }
  }
}
</code>```

  Namn
  <input id="name" type="text" v-model="fullName" @blur="validate('fullName')">

{{ form.errors.fullName }}

```
<p>If you don't specifically need the <code>@blur</code> validation, it simplifies things quite abit and its pretty standard to do validation on submit rather then on blur of individual fields.</p>
```export default {
  data() {
    return {
      form: {
        errors: {},
        values: {
          fullName: '',
          phoneNr: '',
          referrer: '',
        }
      }
    }
  },
  methods: {
    validate() {

      this.form.errors = {}

      if (this.form.values.fullName === '') {
        this.form.errors.fullName = 'Enter your full name'
      } else if (this.form.values.fullName !== some other validation) {
        ...
      }

      if (this.form.values.phoneNr === '') {
        this.form.errors.phoneNr = 'Enter your phone number'
      }

      if (this.form.values.referrer === '') {
        this.form.errors.referrer = 'Enter referrer'
      }

      // if errors is empty return true
      return !Object.keys(this.form.errors).length
    },
    submit() {
      if (this.validate()) {
        // do something, form is valid, if native form handler, return true/false
      }
    }
  }
}
```

```

  Namn
  <input id="name" type="text" v-model="fullName">

{{ form.errors.fullName }}

```

Body:
I am currently working on a form and are having some problems to enable a button when conditions are filled.

Currently i created a form that contains inputs to fill a name, a phonenumber, some options and a message. When the conditions are filled i want to enable the button i already disabled.

Does anyone have some tips on who i can enable the button again to submit the form?

<template>

Vi uppskattar alla frågor som du har angående denna applikation!

 Vänligen skriv ett meddelande här nedan så ska vi göra allt vi kan för att svara så snart som möjligt!

  <form @submit.prevent="submitForm">

      Namn
      <input id="name" name="name" type="text" v-model="fullName" @blur="validateInput">

Vänligen fyll i ett namn

      Telefonnummer
      <input id="phone" name="phone" type="number" v-model="phoneNr" @blur="validatePhone" pattern="[0-9]*">

Vänligen fyll i ett giltigt telefonnummer

      Hur fick du kännedom av denna applikation?
      <select id="referrer" name="referrer" v-model="referrer">
        <option value="" disabled hidden>Välj ett alternativ</option>
        <option value="internet">Internet</option>
        <option value="friends">Vänner</option>
        <option value="newspaper">Nyhetstidningar</option>
        <option value="other">Annat</option>
      </select>

      Meddelande
      <textarea name="message" id="message" cols="30" rows="10" v-model="message" @blur="validateMessage"></textarea>

Vänligen fyll i ditt meddelande

      <button v-on:click="$router.push('thankyou')" :disabled="!isComplete" id="myBtn">Skicka meddelande</button>

  </form>
</template>

Body:
Consolidate your form fields into a single model, along with the errors object.

Then use Object.keys to grab known field keys to do validation on.

export default {
  data() {
    return {
      form: {
        errors: {},
        values: {
          fullName: '',
          phoneNr: '',
          referrer: '',
        }
      }
    }
  },
  methods: {
    validate(field) {

      let fields = []
      // single field
      if (field) {
        delete this.form.errors[field]
        fields.push(field)
      } else {
        this.form.errors = {}
        // all fields
        fields = Object.keys(this.form.values)
      }

      if (fields.includes('fullName')) {
        if (this.form.values.fullName === '') {
          this.form.errors.fullName = 'Enter your full name'
        } else if (this.fullName !== some other validation) {
          ...
        }
      }

      if (fields.includes('phoneNr')) {
        if (this.form.values.phoneNr === '') {
          this.form.errors.phoneNr = 'Enter your phone number'
        }
      }

      if (fields.includes('referrer')) {
        if (this.form.values.referrer === '') {
          this.form.errors.referrer = 'Enter referrer'
        }
      }

      // if errors is empty return true
      return !Object.keys(this.form.errors).length
    },
    submit() {
      // validate all
      if (this.validate()) {
        // do some thing, form is valid, if native form handler, return true/false
      }
    }
  }
}

<div class="form-control" :class="{invalid: form.errors.fullName}">
  <label for="name">Namn</label>
  <input id="name" type="text" v-model="fullName" @blur="validate('fullName')">
  <p v-if="form.errors.fullName">{{ form.errors.fullName }}</p>
</div>

If you don't specifically need the @blur validation, it simplifies things quite abit and its pretty standard to do validation on submit rather then on blur of individual fields.

export default {
  data() {
    return {
      form: {
        errors: {},
        values: {
          fullName: '',
          phoneNr: '',
          referrer: '',
        }
      }
    }
  },
  methods: {
    validate() {

      this.form.errors = {}

      if (this.form.values.fullName === '') {
        this.form.errors.fullName = 'Enter your full name'
      } else if (this.form.values.fullName !== some other validation) {
        ...
      }

      if (this.form.values.phoneNr === '') {
        this.form.errors.phoneNr = 'Enter your phone number'
      }

      if (this.form.values.referrer === '') {
        this.form.errors.referrer = 'Enter referrer'
      }

      // if errors is empty return true
      return !Object.keys(this.form.errors).length
    },
    submit() {
      if (this.validate()) {
        // do something, form is valid, if native form handler, return true/false
      }
    }
  }
}

<div class="form-control" :class="{invalid: form.errors.fullName}">
  <label for="name">Namn</label>
  <input id="name" type="text" v-model="fullName">
  <p v-if="form.errors.fullName">{{ form.errors.fullName }}</p>
</div>


问:
How can I add hidden/invisible text fields or values into a document?
How can I add hidden text fields or values into a document?

I have to receive documents and update a database with certain values. I want to add hidden fields into a document so that I could access the values when I get the envelope. How can I do that? The hidden fields I found in the documentation were focused on hiding sensitive data from a receiver. I want the field to be completely hidden.

答:
You can use custom fields.

Custom fields are meta-data, hidden values that are associated with an envelope and you can use API to get/set them.

They are text fields limited to 100 characters, but you can have as many of them as you need.


问:
Instantiate class from name in MATLAB
I'm trying to list classes I created in some folder in my Matlab folder - using only their name (class name)

as an example, I have a class called 'SimpleString' - and I'm aiming to instantiate an object from that class, if all I know is that its name is 'SimpleString'

So in realtime, I'd like to find out what classes are in a folder (done), then be able to instantiate any of those classes (my question)
Thanks

答:
You can use the WHAT function to discover classes (as well as functions,packages,etc...) in a certain folder, then call METHODS to find the signature of the constructor of the class (some parsing needed here), finally using FEVAL (passing arguments if any) to create an object from this class.

You could also use meta.class to get all sorts of meta-information about your classes.

EDIT

Here is some code to illustrate what I had in mind:

```<code>%# folder containing your classes
pathName = fullfile(pwd,'folder');

%# make sure it is on the path
p = textscan(path, '%s', 'Delimiter',';'); p=p{1};
if ~any(ismember(p,pathName))
    addpath(pathName)
end

%# list MATLAB files
w = what(pathName);

%# get class names
fNames = cellfun(@(s) s(1:end-2), w.m, 'Uni',false);     %# remove .m extension
fNames = [fNames ; w.classes];        %# add classes in @-folders

%# get classes metadata
mt = cellfun(@meta.class.fromName, fNames, 'Uni',false); %# get meta-data
mt = mt( ~cellfun(@isempty,mt) );     %# get rid of plain functions

%# build object from each class
objects = cell(numel(mt),1);
for i=1:numel(mt)
    %# get contructor function
    ctorMT = findobj(mt{i}.MethodList, 'Access','public', 'Name',mt{i}.Name);

    %# get number of contructor arguments
    numArgs = numel(ctorMT.InputNames);

    %# create list of arguments (using just zeros)
    args = repmat({0}, [numArgs 1]);

    %# create object
    try
        obj = feval(ctorMT.Name,args{:});
    catch ME
        warning(ME.identifier, ME.message)
        obj = [];
    end

    %# store object
    objects{i} = obj;
end
</code>```

As you can see, I found it easier to simply use meta.class to get metadata about the classes, instead of manually parsing the output of methods('fcn','-full') as I originally suggested.

However this is not perfect, as there is no way to find out what type of input each constructor expect (only how many). I opted to always pass 0 for each argument..

To test the implementation above, I create these sample classes (one in a self-contained file, the other defined in @-folder with multiple files):

folder/hello.m

```<code>classdef hello
    properties
        name = '';
    end
    methods
        function this = hello()
            this.name = 'world';
        end
        function val = get.name(obj)
            val = obj.name;
        end
        function obj = set.name(obj,val)
            obj.name = val;
        end
        function say(obj)
            fprintf('Hello %s!\n',obj.name);
        end
    end
end
</code>```

folder/@hello2/hello2.m

```<code>classdef hello2
    properties
        name
    end
    methods
        function this = hello2(val)
            this.name = val;
        end
        function val = get.name(obj)
            val = obj.name;
        end
        function obj = set.name(obj,val)
            obj.name = val;
        end
    end
    methods
        say(obj)
    end
end
</code>```

folder/@hello2/say.m

```<code>function say(obj)
    fprintf('Hello2 %s!\n', obj.name);
end
</code>```

Title: Instantiate class from name in MATLAB

Body:
You can use the WHAT function to discover classes (as well as functions,packages,etc...) in a certain folder, then call METHODS to find the signature of the constructor of the class (some parsing needed here), finally using FEVAL (passing arguments if any) to create an object from this class.

You could also use meta.class to get all sorts of meta-information about your classes.

EDIT

Here is some code to illustrate what I had in mind:

%# folder containing your classes
pathName = fullfile(pwd,'folder');

%# make sure it is on the path
p = textscan(path, '%s', 'Delimiter',';'); p=p{1};
if ~any(ismember(p,pathName))
    addpath(pathName)
end

%# list MATLAB files
w = what(pathName);

%# get class names
fNames = cellfun(@(s) s(1:end-2), w.m, 'Uni',false);     %# remove .m extension
fNames = [fNames ; w.classes];        %# add classes in @-folders

%# get classes metadata
mt = cellfun(@meta.class.fromName, fNames, 'Uni',false); %# get meta-data
mt = mt( ~cellfun(@isempty,mt) );     %# get rid of plain functions

%# build object from each class
objects = cell(numel(mt),1);
for i=1:numel(mt)
    %# get contructor function
    ctorMT = findobj(mt{i}.MethodList, 'Access','public', 'Name',mt{i}.Name);

    %# get number of contructor arguments
    numArgs = numel(ctorMT.InputNames);

    %# create list of arguments (using just zeros)
    args = repmat({0}, [numArgs 1]);

    %# create object
    try
        obj = feval(ctorMT.Name,args{:});
    catch ME
        warning(ME.identifier, ME.message)
        obj = [];
    end

    %# store object
    objects{i} = obj;
end

As you can see, I found it easier to simply use meta.class to get metadata about the classes, instead of manually parsing the output of methods('fcn','-full') as I originally suggested.

However this is not perfect, as there is no way to find out what type of input each constructor expect (only how many). I opted to always pass 0 for each argument..

To test the implementation above, I create these sample classes (one in a self-contained file, the other defined in @-folder with multiple files):

folder/hello.m

classdef hello
    properties
        name = '';
    end
    methods
        function this = hello()
            this.name = 'world';
        end
        function val = get.name(obj)
            val = obj.name;
        end
        function obj = set.name(obj,val)
            obj.name = val;
        end
        function say(obj)
            fprintf('Hello %s!\n',obj.name);
        end
    end
end

folder/@hello2/hello2.m

classdef hello2
    properties
        name
    end
    methods
        function this = hello2(val)
            this.name = val;
        end
        function val = get.name(obj)
            val = obj.name;
        end
        function obj = set.name(obj,val)
            obj.name = val;
        end
    end
    methods
        say(obj)
    end
end

folder/@hello2/say.m

function say(obj)
    fprintf('Hello2 %s!\n', obj.name);
end


问:
Docker - is not running
I want to install laravel8 with  curl -s https://laravel.build/example-app | bash ,get this error:

"docker is not running "

答:
Please try sudo; it worked for me.

curl -s https://laravel.build/meta-app | sudo bash

Title: Docker - is not running


问:
jest.config is being ignored
I have the following in my jest.config.js

```<code>module.exports = {
    preset: 'ts-jest/presets/js-with-ts',
    testEnvironment: 'jsdom'
};
</code>```

but it's being ignored when I run npm test. Can someone please help?

Here's my package.json

```<code>  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
</code>```

答:
Seems like adding -- --config=jest.config.js is enough.

You can try to replace the scripts "test" in package.json by react-scripts test -- --config=jest.config.js, else you can set the jest config directly into the package.json

You can find the answer here : How to use jest.config.js with create-react-app

Title: jest.config is being ignored

Body:
I have the following in my jest.config.js

module.exports = {
    preset: 'ts-jest/presets/js-with-ts',
    testEnvironment: 'jsdom'
};

but it's being ignored when I run npm test. Can someone please help?

Here's my package.json

  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },


问:
Is there a way to subtract an element with next element in a python list?
Iam new to programming and started learning python.
Iam having a list if numbers
a = [1,2,3,4,5]
Logic should be 1-2-3-4-5 to get the result as -13.
Someone help me with the python code for this problem.</p>

答:
The simplest solution would be to use a for loop and a temporary variable, subtracting the number each time.</p>
```<code>a = [1,2,3,4,5] #initiate array
temp = a[0] #set the value to the first number
for i in a[1:]:
    temp -= i #update value
</code>```

Body:
The simplest solution would be to use a for loop and a temporary variable, subtracting the number each time.

a = [1,2,3,4,5] #initiate array
temp = a[0] #set the value to the first number
for i in a[1:]:
    temp -= i #update value


问:
scikit learn loading raw documents
How do i use this api to load multiple text files?

```<code>from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.datasets import load_files

vectorizer = TfidfVectorizer()
X = vectorizer.fit_transform(files)
print(vectorizer.get_feature_names_out())
</code>```

I expect the following (where txt is a folder of txt files) to give me the right input?

files = load_files('./input/txt')

答:
load_files() function uses the following directory structure to get files:

```<code>container_folder/
    category_1_folder/
        file_1.txt file_2.txt … file_42.txt
    category_2_folder/
        file_43.txt file_44.txt …
</code>```

in your case you only have one subfolder. So you need to put just input folder in the load_files function.

Example:

```<code>from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.datasets import load_files

files = load_files("input/",load_content=True)

vectorizer = TfidfVectorizer()
X = vectorizer.fit_transform(files['data'])
</code>```

Title: scikit learn loading raw documents

Body:
How do i use this api to load multiple text files?

from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.datasets import load_files

vectorizer = TfidfVectorizer()
X = vectorizer.fit_transform(files)
print(vectorizer.get_feature_names_out())

I expect the following (where txt is a folder of txt files) to give me the right input?

files = load_files('./input/txt')

Body:
load_files() function uses the following directory structure to get files:

container_folder/
    category_1_folder/
        file_1.txt file_2.txt … file_42.txt
    category_2_folder/
        file_43.txt file_44.txt …

in your case you only have one subfolder. So you need to put just input folder in the load_files function.

Example:

from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.datasets import load_files

files = load_files("input/",load_content=True)

vectorizer = TfidfVectorizer()
X = vectorizer.fit_transform(files['data'])


问:
Can't send image from array to collectionViewCell
I've collection view and cell configured from array, I want to set the image of cell's UIImageView from the array, but xCode returns an error saying: Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value, I don't know if it's helpful, but I can't even open the tab where collectionView and its cell is located, the app crashes immediately

//collectionViewCell
    @IBOutlet weak var headerTitle: UILabel!
    @IBOutlet weak var infoLabel: UILabel!
    @IBOutlet weak var countryImage: UIImageView!
    func config(data:SearchCollectionViewData){
        self.headerTitle.text = data.header
        self.infoLabel.text = data.information
        self.countryImage.image = data.image // error goes here
    }
//collectionView and its configuration
    var array2:[SearchCollectionViewData] = [
        SearchCollectionViewData(header: "Georgia,Tbilisi Airport", information: "Georgia is located between Asia and Europe and occupies a land area of 69,700 square kilometres, bordered by the Black Sea to the west, Turkey to the southwest, Azerbaijan to the east, Russia to the north, and Armenia to the south. ... Georgian is the official language of Georgia, and it is spoken by 71% of the population.", image: UIImage(named: "tbtbtb")!)
]

    override func viewDidLoad() {
        super.viewDidLoad()

        collectionView.delegate = self
        collectionView.dataSource = self
}
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "searchCell", for: indexPath) as! searchCollectionViewCell
            cell.config(data: array2[indexPath.row])
}

```

答: The main problem was @IBOutlet weak var countryImage: UIImageView!, where the error was, it wasn't connected to storyboard


问:
Is there a way to copy an activity to another database?
I would like to create a copy of an activity and move it in another database.

I can see two solutions:

Option 1 - Use the method .copy() of my activity and then to change the database of the copy. The problem is that I cannot figure how to move an activity from one database to another or even if it is possible.

Option 2 - Re-create an activity in the destination database that contains the data of the activity to copy. Although it is not difficult, I find this option way less elegant.
Below is an implementation of option 2.

```<code>def copy_activity(activity, target_database=None, target_name=None):
    """
        Copy an activity to another database

        Args:
            activity: Activity to copy
            target_database (str):
                Name of the database in which to copy the activity default is the database of the activity
            target_name (str): Name of the copy, default is the name of the activity
    """

    if (target_database is None) and (target_name is None):
        raise ValueError('You must specify at least a target database or a target name')

    db_name = target_database or activity.key[0]
    db = bw.Database(db_name)

    activity_copy = db.new_activity(activity.key[1])

    for attribute in activity:
        activity_copy[attribute] = activity[attribute]

    for exchange in activity.exchanges():
        if exchange.input == exchange.output:
            activity_copy.new_exchange(input=activity_copy, output=activity_copy)
        else:
            activity_copy.new_exchange(input=exchange.input, output=activity_copy)

    activity_copy.save()
</code>```

答:
You can change the database of an activity with my_activity['database'] = 'something'. You don't need to save afterwards.

Functionality in the source code here, tests here.

Body:
I would like to create a copy of an activity and move it in another database.

I can see two solutions:

Option 1 - Use the method .copy() of my activity and then to change the database of the copy. The problem is that I cannot figure how to move an activity from one database to another or even if it is possible.

Option 2 - Re-create an activity in the destination database that contains the data of the activity to copy. Although it is not difficult, I find this option way less elegant.
Below is an implementation of option 2.

def copy_activity(activity, target_database=None, target_name=None):
    """
        Copy an activity to another database

        Args:
            activity: Activity to copy
            target_database (str):
                Name of the database in which to copy the activity default is the database of the activity
            target_name (str): Name of the copy, default is the name of the activity
    """

    if (target_database is None) and (target_name is None):
        raise ValueError('You must specify at least a target database or a target name')

    db_name = target_database or activity.key[0]
    db = bw.Database(db_name)

    activity_copy = db.new_activity(activity.key[1])

    for attribute in activity:
        activity_copy[attribute] = activity[attribute]

    for exchange in activity.exchanges():
        if exchange.input == exchange.output:
            activity_copy.new_exchange(input=activity_copy, output=activity_copy)
        else:
            activity_copy.new_exchange(input=exchange.input, output=activity_copy)

    activity_copy.save()