问:
Nestjs / Typeorm transaction Save function is not working
I am new to nestjs and I am also self leaner.I need to add Data to two tables using transactions. I am using TypeORm for my ORM tool with Nestjs. I look the nestjs doc for the Typeform transaction and the document is not matching my scenario. So I create my own code, But it's networking. I really need your help.

This is my service code :

```<code>@Injectable()
export class OrderService {
  constructor(
    @InjectRepository(Order)
    private readonly orderRepository: Repository<Order>,
    private readonly orderHasItemService: OrderHasItemService,
    private connection: Connection,
  ) {}
  async create(orderData: CreateOrderDto): Promise<string> {
    const queryRunner = this.connection.createQueryRunner();
    const orderModel: {
      created_date: Date;
      status: string;
      customer: Customer;
    } = {
      status: orderData.status,
      created_date: orderData.created_date,
      customer: orderData.customer,
    };
    const oderDetailsModel: {
      item_id: string;
      qty: number;
      unit_price: number;
      order_id: string;
    } = {
      order_id: orderData.order_id,
      item_id: orderData.item_id,
      unit_price: orderData.unit_price,
      qty: orderData.qty,
    };
    const order = this.orderRepository.create(orderModel);
    if (order) {
      await queryRunner.connect();
      await queryRunner.startTransaction();
      try {
        const creatOrder = await queryRunner.manager.save(Order, orderModel);
        if (creatOrder) {
          return this.orderHasItemService.create(oderDetailsModel);
        }
      } catch (error) {
        await queryRunner.rollbackTransaction();
        throw new InternalServerErrorException();
      } finally {
        await queryRunner.release();
      }
    }

  }
</code>```

答:
In TypoORM(as in other ORMs) to create a row in your database, you need at first run CREATE and after it SAVE on the created model. Try to save your model:

const order = this.orderRepository.create(orderModel);
                            // order instead of orderModel ||
                            //                             \/
const creatOrder = await queryRunner.manager.save(Order, order);
```

Body:
I am new to nestjs and I am also self leaner.I need to add Data to two tables using transactions. I am using TypeORm for my ORM tool with Nestjs. I look the nestjs doc for the Typeform transaction and the document is not matching my scenario. So I create my own code, But it's networking. I really need your help.

This is my service code :

@Injectable()
export class OrderService {
  constructor(
    @InjectRepository(Order)
    private readonly orderRepository: Repository<Order>,
    private readonly orderHasItemService: OrderHasItemService,
    private connection: Connection,
  ) {}
  async create(orderData: CreateOrderDto): Promise<string> {
    const queryRunner = this.connection.createQueryRunner();
    const orderModel: {
      created_date: Date;
      status: string;
      customer: Customer;
    } = {
      status: orderData.status,
      created_date: orderData.created_date,
      customer: orderData.customer,
    };
    const oderDetailsModel: {
      item_id: string;
      qty: number;
      unit_price: number;
      order_id: string;
    } = {
      order_id: orderData.order_id,
      item_id: orderData.item_id,
      unit_price: orderData.unit_price,
      qty: orderData.qty,
    };
    const order = this.orderRepository.create(orderModel);
    if (order) {
      await queryRunner.connect();
      await queryRunner.startTransaction();
      try {
        const creatOrder = await queryRunner.manager.save(Order, orderModel);
        if (creatOrder) {
          return this.orderHasItemService.create(oderDetailsModel);
        }
      } catch (error) {
        await queryRunner.rollbackTransaction();
        throw new InternalServerErrorException();
      } finally {
        await queryRunner.release();
      }
    }

  }


来源: stackexchange

问:
Python unintentionally deleting keys in other dictionaries
When using del or .pop() on x_copy, the operation is magically applied to x as well. i.e. keys in both dictionaries are deleted.

Example code:

x = {
    "key1": 0,
    "key2": 0,
}

x_copy = x
x_copy.pop("key1")

print(f"x =      {x}")
print(f"x copy = {x_copy}")
```
<p>This code should only remove the key from <code>x</code>, but the key is lost from both dictionaries.</p>
<p>Actual output:</p>
<pre class="lang-py prettyprint-override"><code>>>> x =      {'key2': 0}
>>> x copy = {'key2': 0}
</code>```

Expected output

```<code>>>> x =      {'key1': 0, 'key2': 0}
>>> x copy = {'key2': 0}
</code>```

Same happens if I replace .pop() with del:

x_copy = x
x_copy.pop("key1")
```

Why is this happening?

Python 3.10

答:
Didn't make shallow copy

```<code>x.copy()
</code>```

Answered by @matszwecja

ContentLicense: CC BY-SA 4.0

Body:
When using del or .pop() on x_copy, the operation is magically applied to x as well. i.e. keys in both dictionaries are deleted.

Example code:

x = {
    "key1": 0,
    "key2": 0,
}

x_copy = x
x_copy.pop("key1")

print(f"x =      {x}")
print(f"x copy = {x_copy}")

This code should only remove the key from x, but the key is lost from both dictionaries.

Actual output:

>>> x =      {'key2': 0}
>>> x copy = {'key2': 0}

Expected output

>>> x =      {'key1': 0, 'key2': 0}
>>> x copy = {'key2': 0}

Same happens if I replace .pop() with del:

x_copy = x
x_copy.pop("key1")

Why is this happening?

Python 3.10

Body:
Didn't make shallow copy

x.copy()

Answered by @matszwecja


问:
Delete dataverse tables, when migrating solution
In our PowerApps setup we have four environments:
Development (Unmanaged)
Build (Unmanaged)
Test (Managed)
Production (Managed)

We change the solution in development. When everything is ready for deployment we export an unmanaged solution to git. When we merge to our main branch, the pipeline takes over:

Delete the solution from Build.

Import new solution from git.

Bump version.

Export solution as managed.

Upgrade solution in test.

Upgrade solution in production.

This has the benefit of keeping the solution and the code in sync as well as verifying that the solution can be imported anew if everything goes sideways.

However, there is an issue: When deleting the solution from Build the Dataverse tables remain. Not only that, when importing the new solution they are somehow incorporated into the solution, so when it is exported in step 4 references to deleted tables reemerge. Step 5 then fails.

Is there a way to delete all table definitions belonging to a deleted solution? Doing it via REST calls is fine, as long as it can be done by some automated process.

答:
If you firstly deleted the solution from the follow-up environment, your next step could be:

```<code>- task: PowerPlatformImportSolution@0
  inputs:
    authenticationType: 'PowerPlatformSPN'
    PowerPlatformSPN: $(YourSPN)
    SolutionInputFile: 'MySolution.zip'
    AsyncOperation: true
    MaxAsyncWaitTime: '60'
    HoldingSolution: true
    OverwriteUnmanagedCustomizations: true
</code>```

You could start looking into the HoldingSolutions and how to work with that ;-)

Body:
If you firstly deleted the solution from the follow-up environment, your next step could be:

- task: PowerPlatformImportSolution@0
  inputs:
    authenticationType: 'PowerPlatformSPN'
    PowerPlatformSPN: $(YourSPN)
    SolutionInputFile: 'MySolution.zip'
    AsyncOperation: true
    MaxAsyncWaitTime: '60'
    HoldingSolution: true
    OverwriteUnmanagedCustomizations: true

You could start looking into the HoldingSolutions and how to work with that ;-)


问:
SaxonJS.XPath.evaluate throws Maximum call stack size exceeded
I am trying to use saxon JS to evaluate  some xPaths

I'm running the following code

```<code>
const sourceCode= " ... " //a string representing the code source of https://www.imdb.com/chart/boxoffice

const doc = new DOMParser({errorHandler: () => {} }).parseFromString(sourceCode, 'text/html')

try {
        const res = saxon.XPath.evaluate(selectors[0].path, doc,  { xpathDefaultNamespace : 'http://www.w3.org/1999/xhtml' })
        console.log("saxon res", res);
} catch(e) {
        console.log("saxon e", e);
}
</code>```

which throws the following error

```<code>saxon e RangeError: Maximum call stack size exceeded
at Hb.Cb (/application/node_modules/saxon-js/SaxonJS2N.js:3904:409)
at new Hb (/application/node_modules/saxon-js/SaxonJS2N.js:3905:286)
at Object.fromString (/application/node_modules/saxon-js/SaxonJS2N.js:3948:119)
at H (/application/node_modules/saxon-js/SaxonJS2N.js:4377:39)
at S (/application/node_modules/saxon-js/SaxonJS2N.js:4378:208)
at H (/application/node_modules/saxon-js/SaxonJS2N.js:4378:500)
at /application/node_modules/saxon-js/SaxonJS2N.js:4379:103
at Array.forEach (<anonymous>)
at R (/application/node_modules/saxon-js/SaxonJS2N.js:4379:79)
at Y (/application/node_modules/saxon-js/SaxonJS2N.js:4379:196)
at H (/application/node_modules/saxon-js/SaxonJS2N.js:4379:28)

etc...
</code>```

Same error for any webpage I have tried.
How can I parse a source code and evaluate the page with saxon-js

Note: I'm open to alternatives that use xpath 3.0
Note2: the code above works fine with npm xpath but it uses xpath 1

答:
In the browser Saxon-JS uses the browser's DOM implementation and interoperates fine with e.g. new DOMParser().parseFromString('...', 'text/html') but I think under Node.js integrates its own DOM based on "third-party components, including sax-js, xmldom, and Big", being "integrated into the saxon-js codebase".

I don't think they have integrated a text/html parser, so you can parse X(HT)ML using SaxonJS.getResource, but so far not HTML.

Example for XML:

```<code>const SaxonJS = require("saxon-js");

const htmlInput = `<html><body><h1>Test</h1>
<p>This is p 1.</p>
<p>This is p2.</p>
</body>
</html>`;

SaxonJS.getResource({ text : htmlInput, type : 'xml' }).then(doc => {

  const result = SaxonJS.XPath.evaluate(`//p/string()`, doc);

  console.log(result);
});
</code>```

Body:
I am trying to use saxon JS to evaluate  some xPaths

I'm running the following code

const sourceCode= " ... " //a string representing the code source of https://www.imdb.com/chart/boxoffice

const doc = new DOMParser({errorHandler: () => {} }).parseFromString(sourceCode, 'text/html')

try {
        const res = saxon.XPath.evaluate(selectors[0].path, doc,  { xpathDefaultNamespace : 'http://www.w3.org/1999/xhtml' })
        console.log("saxon res", res);
} catch(e) {
        console.log("saxon e", e);
}

which throws the following error

saxon e RangeError: Maximum call stack size exceeded
at Hb.Cb (/application/node_modules/saxon-js/SaxonJS2N.js:3904:409)
at new Hb (/application/node_modules/saxon-js/SaxonJS2N.js:3905:286)
at Object.fromString (/application/node_modules/saxon-js/SaxonJS2N.js:3948:119)
at H (/application/node_modules/saxon-js/SaxonJS2N.js:4377:39)
at S (/application/node_modules/saxon-js/SaxonJS2N.js:4378:208)
at H (/application/node_modules/saxon-js/SaxonJS2N.js:4378:500)
at /application/node_modules/saxon-js/SaxonJS2N.js:4379:103
at Array.forEach (<anonymous>)
at R (/application/node_modules/saxon-js/SaxonJS2N.js:4379:79)
at Y (/application/node_modules/saxon-js/SaxonJS2N.js:4379:196)
at H (/application/node_modules/saxon-js/SaxonJS2N.js:4379:28)

etc...

Same error for any webpage I have tried.
How can I parse a source code and evaluate the page with saxon-js

Note: I'm open to alternatives that use xpath 3.0
Note2: the code above works fine with npm xpath but it uses xpath 1

Body:
In the browser Saxon-JS uses the browser's DOM implementation and interoperates fine with e.g. new DOMParser().parseFromString('...', 'text/html') but I think under Node.js integrates its own DOM based on "third-party components, including sax-js, xmldom, and Big", being "integrated into the saxon-js codebase".

I don't think they have integrated a text/html parser, so you can parse X(HT)ML using SaxonJS.getResource, but so far not HTML.

Example for XML:

const SaxonJS = require("saxon-js");

const htmlInput = `<html><body><h1>Test</h1>
<p>This is p 1.</p>
<p>This is p2.</p>
</body>
</html>`;

SaxonJS.getResource({ text : htmlInput, type : 'xml' }).then(doc => {

  const result = SaxonJS.XPath.evaluate(`//p/string()`, doc);

  console.log(result);
});


问:
equivalent java library required for curl- to submit forms to remote web sites
I have a php web application that asks the user for all fields' values (all fields for a web form) and then shows only captcha and multiple choice values of that form on screen, the end user has to fill in these values and then the form is submitted to its action. The operative part of the php code uses curl for this operation. That php code is given below-

```<code>    $page = $curl->post($submit_url, array(
    'TITLE'   => $urltitle,
    'URL' => $urlurl,
    'OWNER_NAME' => $urlname,
    'OWNER_EMAIL' => $urlemail,
    'CATEGORY_ID' =>  $CATEGORY_ID,
    'RECPR_URL' => '',
    'IMAGEHASH' => $hash,
    'LINK_TYPE' => $dfln,
    'CAPTCHA' => $captcha,
    'AGREERULES' => 'on',
    'submit'    => 'Continue'
));
</code>```

My question is, is there a library in Java that can do the same thing? I plan to submit same/similar data to many web forms, if this can be done in java...

答:
I suggest using Apache HttpClient:

http://hc.apache.org/httpclient-3.x/

And the tutorial is here: http://hc.apache.org/httpclient-3.x/tutorial.html

ContentLicense: CC BY-SA 3.0

Body:
I have a php web application that asks the user for all fields' values (all fields for a web form) and then shows only captcha and multiple choice values of that form on screen, the end user has to fill in these values and then the form is submitted to its action. The operative part of the php code uses curl for this operation. That php code is given below-

    $page = $curl->post($submit_url, array(
    'TITLE'   => $urltitle,
    'URL' => $urlurl,
    'OWNER_NAME' => $urlname,
    'OWNER_EMAIL' => $urlemail,
    'CATEGORY_ID' =>  $CATEGORY_ID,
    'RECPR_URL' => '',
    'IMAGEHASH' => $hash,
    'LINK_TYPE' => $dfln,
    'CAPTCHA' => $captcha,
    'AGREERULES' => 'on',
    'submit'    => 'Continue'
));

My question is, is there a library in Java that can do the same thing? I plan to submit same/similar data to many web forms, if this can be done in java...


问:
Adapter Android Studio Button
I have an adapter with a button inside and I don't really know ho to do something when I presse the button.
It's an order app and in the the basket I have a delete button to delete a dish.
Do you have a solution ?</p>

答:
So I put the code of the button in the adapter and I put in it
""list.removeAt(position)
notifyDataSetChanged()""</p>

Title: Adapter Android Studio Button


问:
How do I use the Use Navigate from React Router on a button that links to different pages?
I have a button that represents shop now that upon click it redirects you on different pages and the card elements have been mapped on external data.
I want this button to navigate to different pages kindly help.</p>
```<code>   const data =[
    {
        id:"Extensions",
        Title:"Electrical Collections",
        img:"/Assets/Electricals/Extlogo.png",

    },
    {
        id:"Phone Accesorries",
        Title:"Phone Accessories",
        img:"/Assets/Phone/phoneacc.png",
    },
    {
        id:"Homeware",
        Title:"Homeware Collections",
        img:"/Assets/Home/home.png",

    },
]
 function Home() {
let Navigate =useNavigate();
const handleElectricalPage =  () =>{
    Navigate("/extensionproduct")
   }
<div className='cardContainer'>
          {data.map((item )=>(

               <card>
               <div className='imageContainer'>
                   <img src={item.img}  alt='Extension logo'/>
                   </div>
                   <div className='contentsContainer'>
                   <h2>{item.Title}</h2>
                   <div className='iconButtonContainer'>

                <button onClick={handleElectricalPage}>Shop Now</button>
                   <ArrowForwardIcon className='arrowIcon'/>
                   </div>
                   </div>

</code>```

答:
Example from the react router https://reactrouter.com/docs/en/v6/api#usenavigate</p>
```<code> navigate("../success", { replace: true });
</code>```

Body:
I have a button that represents shop now that upon click it redirects you on different pages and the card elements have been mapped on external data.
I want this button to navigate to different pages kindly help.

   const data =[
    {
        id:"Extensions",
        Title:"Electrical Collections",
        img:"/Assets/Electricals/Extlogo.png",

    },
    {
        id:"Phone Accesorries",
        Title:"Phone Accessories",
        img:"/Assets/Phone/phoneacc.png",
    },
    {
        id:"Homeware",
        Title:"Homeware Collections",
        img:"/Assets/Home/home.png",

    },
]
 function Home() {
let Navigate =useNavigate();
const handleElectricalPage =  () =>{
    Navigate("/extensionproduct")
   }

          {data.map((item )=>(

               <card>

{item.Title}

                <button onClick={handleElectricalPage}>Shop Now</button>
                   <ArrowForwardIcon className='arrowIcon'/>

Body:
Example from the react router https://reactrouter.com/docs/en/v6/api#usenavigate

 navigate("../success", { replace: true });


问:
Could not validate a connection to Elasticsearch. No alive nodes found in your cluster

Platform: Magento 2 (V2.4.0) |
Server: Linux Centos

When I run the command below,

```<code>COMPOSER_MEMORY_LIMIT=-1 php bin/magento setup:static-content:deploy -f
</code>```

I get the error,

Could not validate a connection to Elasticsearch. No alive nodes found in your cluster

When I run,

```<code>systemctl restart elasticsearch.service
</code>```

I get the error,

Failed to restart elasticsearch.service: Unit not found.

And when I run the command,

```<code>systemctl status elasticsearch
</code>```

I get the error,

Unit elasticsearch.service could not be found

However, I can see Elasticsearch folder and files in the following path:

vendor/elasticsearch/elasticsearch

Any suggestions?

Thank you!

答:
Hi try using these commands, i use them on my ubuntu instance</p>
```<code>sudo -i service elasticsearch start
service elasticsearch restart
sudo -i service elasticsearch stop
</code>```

Body:
Platform: Magento 2 (V2.4.0) |
Server: Linux Centos

When I run the command below,

COMPOSER_MEMORY_LIMIT=-1 php bin/magento setup:static-content:deploy -f

I get the error,

Could not validate a connection to Elasticsearch. No alive nodes found in your cluster

When I run,

systemctl restart elasticsearch.service

I get the error,

Failed to restart elasticsearch.service: Unit not found.

And when I run the command,

systemctl status elasticsearch

I get the error,

Unit elasticsearch.service could not be found

However, I can see Elasticsearch folder and files in the following path:

vendor/elasticsearch/elasticsearch

Any suggestions?

Thank you!

Body:
Hi try using these commands, i use them on my ubuntu instance

sudo -i service elasticsearch start
service elasticsearch restart
sudo -i service elasticsearch stop


问:
Removing sequential repeating items from List in Kotlin?
I'm looking for a way in Kotlin to prevent repeating items in a list but still preserve the order. For example

```<code>  val list = listOf(ObjectMock(1,"a"), ObjectMock(2,"c"), ObjectMock(3,"c"),
        ObjectMock(4,"a"), ObjectMock(4,"c"), ObjectMock(4,"c"), ObjectMock(1,"a")
        , ObjectMock(1,"c"), ObjectMock(2,"c"), ObjectMock(3,"c"), ObjectMock(4,"a")
        , ObjectMock(2,"b") )
</code>```

should become

```<code>result = listOf(ObjectMock(1,"a"), ObjectMock(2,"c"), ObjectMock(3,"c"),
            ObjectMock(4,"a"), ObjectMock(1,"a") , ObjectMock(2,"c"), ObjectMock(3,"c"), ObjectMock(4,"a")
            , ObjectMock(2,"b") )
</code>```

I'm using a for loop and check next item then add it to different list but Is there a more elegant way to do this?

答:
You can do it by using Kotlin Flows</p>
```<code>viewModelScope.launch {
        list.asFlow()
            .distinctUntilChanged()
            .collect {
                Log.d(TAG, "distict numbers: $it")
            }
    }
</code>```

Body:
I'm looking for a way in Kotlin to prevent repeating items in a list but still preserve the order. For example

  val list = listOf(ObjectMock(1,"a"), ObjectMock(2,"c"), ObjectMock(3,"c"),
        ObjectMock(4,"a"), ObjectMock(4,"c"), ObjectMock(4,"c"), ObjectMock(1,"a")
        , ObjectMock(1,"c"), ObjectMock(2,"c"), ObjectMock(3,"c"), ObjectMock(4,"a")
        , ObjectMock(2,"b") )

should become

result = listOf(ObjectMock(1,"a"), ObjectMock(2,"c"), ObjectMock(3,"c"),
            ObjectMock(4,"a"), ObjectMock(1,"a") , ObjectMock(2,"c"), ObjectMock(3,"c"), ObjectMock(4,"a")
            , ObjectMock(2,"b") )

I'm using a for loop and check next item then add it to different list but Is there a more elegant way to do this?

Body:
You can do it by using Kotlin Flows

viewModelScope.launch {
        list.asFlow()
            .distinctUntilChanged()
            .collect {
                Log.d(TAG, "distict numbers: $it")
            }
    }


答:
You need to make an onClick handler (handleElectricalPage) dynamically, consider something like this.

```<code>function Home() {
  let navigate =useNavigate();
  return (
    <div className='cardContainer'>
      {data.map((item) => (
        <card>
          <button
            onClick={() => navigate(`/externalProduct/${item.id}`)}
          >
           Shop Now
          </button>
        </card>
       )}
   </div>
}
</code>```

You can also use Link which handles everything by itself

```<code><Link to={`/externalProduct/${item.id}`}>
  <button>Shop now</button>
</Link>
</code>```

Title: How do I use the Use Navigate from React Router on a button that links to different pages?

Body:
You need to make an onClick handler (handleElectricalPage) dynamically, consider something like this.

function Home() {
  let navigate =useNavigate();
  return (
    <div className='cardContainer'>
      {data.map((item) => (
        <card>
          <button
            onClick={() => navigate(`/externalProduct/${item.id}`)}
          >
           Shop Now
          </button>
        </card>
       )}
   </div>
}

You can also use Link which handles everything by itself

<Link to={`/externalProduct/${item.id}`}>
  <button>Shop now</button>
</Link>


问:
AWS EC2 Auto Scaling Groups: I get Min and Max, but what's Desired instances limit for?
When you setup an Auto Scaling groups in AWS EC2 Min and Max bounds seem to make sense:

The minimum number of instances to scale down to based on policies

The maximum number of instances to scale up to based on policies

However, I've never been able to wrap my head around what the heck Desired is intended to affect.

I've always just set Desired equal to Min, because generally, I want to pay Amazon the minimum tithe possible, and unless you need an instance to handle load it should be at the Min number of instances.

I know if you use ElasticBeanstalk and set a Min to 1 and Max to 2 it sets a Desired to 2 (of course!)--you can't choose a value for Desired.

What would be the use case for a different Desired number of instances and how does it differ?  When you expect AWS to scale lower than your Desired if desired is larger than Min?

答: Desired is what we start initially. It will go to min or max depending on the scale-in / scale-out.</p>


问:
mvn azure-functions:deploy not working with docker
I am able to deploy my azure function using mvn azure-function:deploy with os selected as linux.

But when I set the os as docker, with image on Azure Container Registry, there is no response from maven command. It neither throws an error nor does it deploy. It does not deploy the docker image

Here is my pom.xml:

```<code>        <plugin>
            <groupId>com.microsoft.azure</groupId>
            <artifactId>azure-functions-maven-plugin</artifactId>
            <version>${azure.functions.maven.plugin.version}</version>
            <configuration>
                <appName>${functionAppName}</appName>
                <resourceGroup>${resourceGroup}</resourceGroup>
                <appServicePlanName>${appServicePlan}</appServicePlanName>
                <region>eastus</region>
                <runtime>
                    <os>docker</os>
                    <image>myappimages.azurecr.io/myapp:v0.0.5</image>
                    <serverId>SERVER_ID</serverId>
                    <registryUrl>myappimages.azurecr.io</registryUrl>
                </runtime>
                <appSettings>
                    <property>
                        <name>FUNCTIONS_EXTENSION_VERSION</name>
                        <value>~3</value>
                    </property>
                </appSettings>
            </configuration>
            <executions>
                <execution>
                    <id>package-functions</id>
                    <goals>
                        <goal>package</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
</code>```

I then set the password for SERVER_ID in my ~/.m2/settings.xml:

```<code><settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
                  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                  xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0
                                      https://maven.apache.org/xsd/settings-1.0.0.xsd">
  <servers>
     <server>
             <id>SERVER_ID</id>
                <username>myappimages</username>
                <password>xxxxxxxxxxxx</password>
      </server>
</servers>
</settings>
</code>```

And finally when I deploy via mvn azure-function:deploy, this is the output:

```<code>[INFO] Updating target Function App myapp...
[INFO] Set function worker runtime to java. [INFO] Successfully updated Function App myapp.
[INFO] Skip deployment for docker app service [INFO]
[INFO] BUILD SUCCESS [INFO]
[INFO] Total time:  49.065 s [INFO] Finished at: 2022-02-09T23:08:40+05:30 [INFO]
</code>```

答:
I am not sure on what fixed it. Very likely upgrading to latest version looks like fixed it. I am able to deploy now via mvn.</p>
```<code>    <azure.functions.maven.plugin.version>1.15.0</azure.functions.maven.plugin.version>
</code>```

Body:
I am able to deploy my azure function using mvn azure-function:deploy with os selected as linux.

But when I set the os as docker, with image on Azure Container Registry, there is no response from maven command. It neither throws an error nor does it deploy. It does not deploy the docker image

Here is my pom.xml:

        <plugin>
            <groupId>com.microsoft.azure</groupId>
            <artifactId>azure-functions-maven-plugin</artifactId>
            <version>${azure.functions.maven.plugin.version}</version>
            <configuration>
                <appName>${functionAppName}</appName>
                <resourceGroup>${resourceGroup}</resourceGroup>
                <appServicePlanName>${appServicePlan}</appServicePlanName>
                <region>eastus</region>
                <runtime>
                    <os>docker</os>
                    <image>myappimages.azurecr.io/myapp:v0.0.5</image>
                    <serverId>SERVER_ID</serverId>
                    <registryUrl>myappimages.azurecr.io</registryUrl>
                </runtime>
                <appSettings>
                    <property>
                        <name>FUNCTIONS_EXTENSION_VERSION</name>
                        <value>~3</value>
                    </property>
                </appSettings>
            </configuration>
            <executions>
                <execution>
                    <id>package-functions</id>
                    <goals>
                        <goal>package</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>

I then set the password for SERVER_ID in my ~/.m2/settings.xml:

<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
                  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                  xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0
                                      https://maven.apache.org/xsd/settings-1.0.0.xsd">
  <servers>
     <server>
             <id>SERVER_ID</id>
                <username>myappimages</username>
                <password>xxxxxxxxxxxx</password>
      </server>
</servers>
</settings>

And finally when I deploy via mvn azure-function:deploy, this is the output:

[INFO] Updating target Function App myapp...
[INFO] Set function worker runtime to java. [INFO] Successfully updated Function App myapp.
[INFO] Skip deployment for docker app service [INFO]
[INFO] BUILD SUCCESS [INFO]
[INFO] Total time:  49.065 s [INFO] Finished at: 2022-02-09T23:08:40+05:30 [INFO]

Body:
I am not sure on what fixed it. Very likely upgrading to latest version looks like fixed it. I am able to deploy now via mvn.

    <azure.functions.maven.plugin.version>1.15.0</azure.functions.maven.plugin.version>


问:
How to include pandas comparison operators in the function?
Let's say I have the following data

```<code>import pandas as pd

d = {'index': [0, 1, 2], 'a': [10, 8, 6], 'b': [4, 2, 6],}

data_frame  = pd.DataFrame(data=d).set_index('index')
</code>```

Now what I do is, filter this data based on the values of column "b", Lets say like this:

```<code>new_df = data_frame[data_frame['b']!=4]
new_df1 = data_frame[data_frame['b']==4]
</code>```

What I want to do, instead of this method above, is to write the function where I can also indicate what kind of comparison operators it should use. Something like this

```<code>
def slice(df, column_name):
    df_new = df[df[column_name]!=4]
    return df_new

new_df2 = slice(df=data_frame, column_name='b')

</code>```

The function above only does != operation in the data. What I want is that both != and == to be somehow defined in the above function, and when I use the function I could ideally indicate which one to use.

Let me know if my question needs more detailed clarification

答:
You could add a boolean parameter to your function:

```<code>def slice(df, column_name, equality=True):
    if equality:
        df_new = df[df[column_name]==4]
    else:
        df_new = df[df[column_name]!=4]
    return df_new

new_df2 = slice(df=data_frame, column_name='b', equality=True)
</code>```

By the way, slice is a built-in python function, so probably a good idea to rename to something else.

Body:
Let's say I have the following data

import pandas as pd

d = {'index': [0, 1, 2], 'a': [10, 8, 6], 'b': [4, 2, 6],}

data_frame  = pd.DataFrame(data=d).set_index('index')

Now what I do is, filter this data based on the values of column "b", Lets say like this:

new_df = data_frame[data_frame['b']!=4]
new_df1 = data_frame[data_frame['b']==4]

What I want to do, instead of this method above, is to write the function where I can also indicate what kind of comparison operators it should use. Something like this

def slice(df, column_name):
    df_new = df[df[column_name]!=4]
    return df_new

new_df2 = slice(df=data_frame, column_name='b')

The function above only does != operation in the data. What I want is that both != and == to be somehow defined in the above function, and when I use the function I could ideally indicate which one to use.

Let me know if my question needs more detailed clarification

Body:
You could add a boolean parameter to your function:

def slice(df, column_name, equality=True):
    if equality:
        df_new = df[df[column_name]==4]
    else:
        df_new = df[df[column_name]!=4]
    return df_new

new_df2 = slice(df=data_frame, column_name='b', equality=True)

By the way, slice is a built-in python function, so probably a good idea to rename to something else.


问:
TypoScript MenuProcessor special = directory :: page type shortcut
I've defined the following typoscript or my ce:

```<code>dataProcessing {
    10 = TYPO3\CMS\Frontend\DataProcessing\MenuProcessor
    10 {
        special = directory
        special.value.field = pages
        dataProcessing {
            10 = TYPO3\CMS\Frontend\DataProcessing\FilesProcessor
            10 {
                references.fieldName = media
            }
            20 = TYPO3\CMS\Frontend\DataProcessing\FilesProcessor
            20 {
                references.fieldName = teaser_image
                as = teaserImage
            }
        }
    }
}
</code>```

The value for pages comes from the configuration in the be (select page from pagetree).

This works well, but if a page with type shortcut (4) is selected, nothing will be generated. I am looking for a way to achieve that if a shortcut is selected, the menu for the target page of this shortcut is being generated.

I want to solve this explicitly for the page type shortcut, not for the page type mountpoint. Unfortunately, I still don't get any data in the variable menu when the page type is shortcut.

答:
Sure, your shortcut is visible in menus?

The FSCs CE "Menu -> Subpages" (CType 'menu_pages') does nearly the same:

```<code># Menu of subpages of selected pages:
# ...
#
# CType: menu_subpages

tt_content.menu_subpages =< lib.contentElement
tt_content.menu_subpages {
    templateName = MenuSubpages
    dataProcessing {
        10 = TYPO3\CMS\Frontend\DataProcessing\MenuProcessor
        10 {
            special = directory
            special.value.field = pages
            dataProcessing {
                10 = TYPO3\CMS\Frontend\DataProcessing\FilesProcessor
                10 {
                    references.fieldName = media
                }
            }
        }
    }
}
</code>```

And in a test (TYPO3 v10), this CE shows me standard-pages and shortcuts.

Maybe, you are confusing "Shortcut" and "Mountpoint"...

Example

Selecting "Page 2" in the pages field of Contentelement "Subpages" (CType menu_subpages) is showing:

Page 2.1

Page 2.2

Selecting "Page 4" (which is of type "Shortcut" and pointing to "Page 2") is showing its own subpages:

Page 4.1

Selecting "Page 5" (which is of type "Mountpoint" and mounting "Page 2") is showing the subpages of the mounted page:

Page 2.1

Page 2.2

Body:
I've defined the following typoscript or my ce:

dataProcessing {
    10 = TYPO3\CMS\Frontend\DataProcessing\MenuProcessor
    10 {
        special = directory
        special.value.field = pages
        dataProcessing {
            10 = TYPO3\CMS\Frontend\DataProcessing\FilesProcessor
            10 {
                references.fieldName = media
            }
            20 = TYPO3\CMS\Frontend\DataProcessing\FilesProcessor
            20 {
                references.fieldName = teaser_image
                as = teaserImage
            }
        }
    }
}

The value for pages comes from the configuration in the be (select page from pagetree).

This works well, but if a page with type shortcut (4) is selected, nothing will be generated. I am looking for a way to achieve that if a shortcut is selected, the menu for the target page of this shortcut is being generated.

I want to solve this explicitly for the page type shortcut, not for the page type mountpoint. Unfortunately, I still don't get any data in the variable menu when the page type is shortcut.

Body:
Sure, your shortcut is visible in menus?

The FSCs CE "Menu -> Subpages" (CType 'menu_pages') does nearly the same:

# Menu of subpages of selected pages:
# ...
#
# CType: menu_subpages

tt_content.menu_subpages =< lib.contentElement
tt_content.menu_subpages {
    templateName = MenuSubpages
    dataProcessing {
        10 = TYPO3\CMS\Frontend\DataProcessing\MenuProcessor
        10 {
            special = directory
            special.value.field = pages
            dataProcessing {
                10 = TYPO3\CMS\Frontend\DataProcessing\FilesProcessor
                10 {
                    references.fieldName = media
                }
            }
        }
    }
}

And in a test (TYPO3 v10), this CE shows me standard-pages and shortcuts.

Maybe, you are confusing "Shortcut" and "Mountpoint"...

Example

Selecting "Page 2" in the pages field of Contentelement "Subpages" (CType menu_subpages) is showing:

Page 2.1

Page 2.2

Selecting "Page 4" (which is of type "Shortcut" and pointing to "Page 2") is showing its own subpages:

Page 4.1

Selecting "Page 5" (which is of type "Mountpoint" and mounting "Page 2") is showing the subpages of the mounted page:

Page 2.1

Page 2.2


问:
CancellationToken Behavior
I want to understand how the CancellationToken works, and how it cancels tasks.

For that, I created this example, which uses the same token for both the Task.Run() and the inner method - HelpDoingSomething()

So, I let the task run for 500ms, then I cancel the token, and the result is:

First printed message: "HelpDoingSomething cancelled" and then "DoSomething cancelled"

class Program
{
    static void Main(string[] args)
    {
        var cts = new CancellationTokenSource();

        var myClass = new MyClass(cts.Token);
        myClass.DoSomething();

        Thread.Sleep(500);
        cts.Cancel();

        System.Console.ReadKey();
    }
}

internal class MyClass
{
    private CancellationToken token;

    public MyClass(CancellationToken token)
    {
        this.token = token;
    }

    public void DoSomething()
    {
        Task.Run(() =>
        {
            HelpDoingSomething();
            System.Console.WriteLine("DoSomething cancelled");
        }, token);
    }

    private void HelpDoingSomething()
    {
        while (!token.IsCancellationRequested)
        {
            //Keep doing something
            System.Console.Write(".");
        }

        System.Console.WriteLine("HelpDoingSomething cancelled");
    }
}
```

I know exactly that my method HelpDoingSomething() checks if the cancellationToken was requested on each iteration of the loop.

My question is how and how often does the Task.Run() method check if a cancellation token is requested?

Is that possible that Task.Run() will check that before HelpDoingSomething() does, and I will see only one message printed ("DoSomething cancelled")? This means the logic may not be handled correctly in this method.

答:
The cancellation token passed to Task.Run() is checked in two places:

(1) Before the task is actually started.

If the cancellation token is signalled before the task starts, the task will be placed into the "WaitingToRun" state quickly followed by the "Cancelled" state.

The action passed to the task will NOT be started in this case.

It may be possible to observe the "WaitingToRun" state if the task's state is checked very soon after calling Task.Run() but this is going to be a race condition and that state may not be observed. However, the "Cancelled" state will always eventually be set.

(2) When the action passed to the task throws OperationCancelledException.

As in case (1), the task will briefly transition to the "WaitingToRun" state which may be observable, but unlike case (1) this is quickly followed by the "Running" state (assuming that the cancellation token is cancelled AFTER the task has started).

If the token associated with the OperationCancelledException is the same as the one passed to Task.Run() the task will transition to the "Cancelled" state, otherwise it will transition to the "Faulted" state.

See here for details: https://learn.microsoft.com/en-us/dotnet/standard/parallel-programming/task-cancellation

Here's a sample console app which demonstrates some of these cases:

```<code>using System;
using System.Threading;
using System.Threading.Tasks;

static class Program
{
    public static void Main()
    {
        Console.WriteLine("Test with already-cancelled token, but not passed to Task.Run()");
        CancellationTokenSource alreadyCancelled = new CancellationTokenSource();
        alreadyCancelled.Cancel();

        Task test1 = Task.Run(() => Test(alreadyCancelled.Token));

        Console.WriteLine("test1 status: " + test1.Status); // Probably "WaitingToRun", but this has a race condition.
        Thread.Sleep(200);
        Console.WriteLine("test1 status: " + test1.Status); // Certainly "Faulted".

        Console.WriteLine("\nTest with already-cancelled token passed to Task.Run()");
        Task test2 = Task.Run(() => Test(alreadyCancelled.Token), alreadyCancelled.Token);

        Console.WriteLine("test2 status: " + test2.Status); // Probably "WaitingToRun", but this has a race condition.
        Thread.Sleep(200);
        Console.WriteLine("test2 status: " + test2.Status); // Certainly "Cancelled".

        Console.WriteLine("\nTest with token cancelled after starting task, but not passed to Task.Run()");
        CancellationTokenSource cts3 = new CancellationTokenSource();
        Task test3 = Task.Run(() => Test(cts3.Token));

        Console.WriteLine("test3 status: " + test3.Status); // Probably "WaitingToRun", but this has a race condition.
        Thread.Sleep(200);
        Console.WriteLine("test3 status: " + test3.Status); // Certainly "Running".

        cts3.Cancel();
        Thread.Sleep(200);
        Console.WriteLine("test3 status: " + test3.Status); // Certainly "Faulted".

        Console.WriteLine("\nTest with token cancelled after starting task passed to Task.Run()");
        CancellationTokenSource cts4 = new CancellationTokenSource();
        Task test4 = Task.Run(() => Test(cts4.Token), cts4.Token);

        Console.WriteLine("test4 status: " + test4.Status); // Probably "WaitingToRun", but this has a race condition.
        Thread.Sleep(200);
        Console.WriteLine("test4 status: " + test4.Status); // Certainly "Running".

        cts4.Cancel();
        Thread.Sleep(200);
        Console.WriteLine("test4 status: " + test4.Status); // Certainly "Cancelled".

        Console.ReadLine();
    }

    public static void Test(CancellationToken cancellation)
    {
        Console.WriteLine("Entering Test()");
        cancellation.WaitHandle.WaitOne();
        Console.WriteLine("Cancellation detected");
        cancellation.ThrowIfCancellationRequested();
    }
}
</code>```

(It's a little bit of a lie where it says "Certainly" in the comments, but in normal circumstances 200ms should be far more than enough to observe the transition to that state. If you do not, increase the timeout. This is NOT something to do in production code!)

The output from this is:

```<code>Test with already-cancelled token, but not passed to Task.Run()
test1 status: WaitingToRun
Entering Test()
Cancellation detected
test1 status: Faulted

Test with already-cancelled token passed to Task.Run()
test2 status: WaitingToRun
test2 status: Canceled

Test with token cancelled after starting task, but not passed to Task.Run()
test3 status: WaitingToRun
Entering Test()
test3 status: Running
Cancellation detected
test3 status: Faulted

Test with token cancelled after starting task passed to Task.Run()
test4 status: WaitingToRun
Entering Test()
test4 status: Running
Cancellation detected
test4 status: Canceled
</code>```

Note how for the second case "Test with already-cancelled token passed to Task.Run()", Entering Test() is not written to the console because the action is not called. This is the only test case where the action is not called at all.

Title: CancellationToken Behavior

Body:
I want to understand how the CancellationToken works, and how it cancels tasks.

For that, I created this example, which uses the same token for both the Task.Run() and the inner method - HelpDoingSomething()

So, I let the task run for 500ms, then I cancel the token, and the result is:

First printed message: "HelpDoingSomething cancelled" and then "DoSomething cancelled"

class Program
{
    static void Main(string[] args)
    {
        var cts = new CancellationTokenSource();

        var myClass = new MyClass(cts.Token);
        myClass.DoSomething();

        Thread.Sleep(500);
        cts.Cancel();

        System.Console.ReadKey();
    }
}

internal class MyClass
{
    private CancellationToken token;

    public MyClass(CancellationToken token)
    {
        this.token = token;
    }

    public void DoSomething()
    {
        Task.Run(() =>
        {
            HelpDoingSomething();
            System.Console.WriteLine("DoSomething cancelled");
        }, token);
    }

    private void HelpDoingSomething()
    {
        while (!token.IsCancellationRequested)
        {
            //Keep doing something
            System.Console.Write(".");
        }

        System.Console.WriteLine("HelpDoingSomething cancelled");
    }
}

I know exactly that my method HelpDoingSomething() checks if the cancellationToken was requested on each iteration of the loop.

My question is how and how often does the Task.Run() method check if a cancellation token is requested?

Is that possible that Task.Run() will check that before HelpDoingSomething() does, and I will see only one message printed ("DoSomething cancelled")? This means the logic may not be handled correctly in this method.

Body:
The cancellation token passed to Task.Run() is checked in two places:

(1) Before the task is actually started.

If the cancellation token is signalled before the task starts, the task will be placed into the "WaitingToRun" state quickly followed by the "Cancelled" state.

The action passed to the task will NOT be started in this case.

It may be possible to observe the "WaitingToRun" state if the task's state is checked very soon after calling Task.Run() but this is going to be a race condition and that state may not be observed. However, the "Cancelled" state will always eventually be set.

(2) When the action passed to the task throws OperationCancelledException.

As in case (1), the task will briefly transition to the "WaitingToRun" state which may be observable, but unlike case (1) this is quickly followed by the "Running" state (assuming that the cancellation token is cancelled AFTER the task has started).

If the token associated with the OperationCancelledException is the same as the one passed to Task.Run() the task will transition to the "Cancelled" state, otherwise it will transition to the "Faulted" state.

See here for details: https://learn.microsoft.com/en-us/dotnet/standard/parallel-programming/task-cancellation

Here's a sample console app which demonstrates some of these cases:

using System;
using System.Threading;
using System.Threading.Tasks;

static class Program
{
    public static void Main()
    {
        Console.WriteLine("Test with already-cancelled token, but not passed to Task.Run()");
        CancellationTokenSource alreadyCancelled = new CancellationTokenSource();
        alreadyCancelled.Cancel();

        Task test1 = Task.Run(() => Test(alreadyCancelled.Token));

        Console.WriteLine("test1 status: " + test1.Status); // Probably "WaitingToRun", but this has a race condition.
        Thread.Sleep(200);
        Console.WriteLine("test1 status: " + test1.Status); // Certainly "Faulted".

        Console.WriteLine("\nTest with already-cancelled token passed to Task.Run()");
        Task test2 = Task.Run(() => Test(alreadyCancelled.Token), alreadyCancelled.Token);

        Console.WriteLine("test2 status: " + test2.Status); // Probably "WaitingToRun", but this has a race condition.
        Thread.Sleep(200);
        Console.WriteLine("test2 status: " + test2.Status); // Certainly "Cancelled".

        Console.WriteLine("\nTest with token cancelled after starting task, but not passed to Task.Run()");
        CancellationTokenSource cts3 = new CancellationTokenSource();
        Task test3 = Task.Run(() => Test(cts3.Token));

        Console.WriteLine("test3 status: " + test3.Status); // Probably "WaitingToRun", but this has a race condition.
        Thread.Sleep(200);
        Console.WriteLine("test3 status: " + test3.Status); // Certainly "Running".

        cts3.Cancel();
        Thread.Sleep(200);
        Console.WriteLine("test3 status: " + test3.Status); // Certainly "Faulted".

        Console.WriteLine("\nTest with token cancelled after starting task passed to Task.Run()");
        CancellationTokenSource cts4 = new CancellationTokenSource();
        Task test4 = Task.Run(() => Test(cts4.Token), cts4.Token);

        Console.WriteLine("test4 status: " + test4.Status); // Probably "WaitingToRun", but this has a race condition.
        Thread.Sleep(200);
        Console.WriteLine("test4 status: " + test4.Status); // Certainly "Running".

        cts4.Cancel();
        Thread.Sleep(200);
        Console.WriteLine("test4 status: " + test4.Status); // Certainly "Cancelled".

        Console.ReadLine();
    }

    public static void Test(CancellationToken cancellation)
    {
        Console.WriteLine("Entering Test()");
        cancellation.WaitHandle.WaitOne();
        Console.WriteLine("Cancellation detected");
        cancellation.ThrowIfCancellationRequested();
    }
}

(It's a little bit of a lie where it says "Certainly" in the comments, but in normal circumstances 200ms should be far more than enough to observe the transition to that state. If you do not, increase the timeout. This is NOT something to do in production code!)

The output from this is:

Test with already-cancelled token, but not passed to Task.Run()
test1 status: WaitingToRun
Entering Test()
Cancellation detected
test1 status: Faulted

Test with already-cancelled token passed to Task.Run()
test2 status: WaitingToRun
test2 status: Canceled

Test with token cancelled after starting task, but not passed to Task.Run()
test3 status: WaitingToRun
Entering Test()
test3 status: Running
Cancellation detected
test3 status: Faulted

Test with token cancelled after starting task passed to Task.Run()
test4 status: WaitingToRun
Entering Test()
test4 status: Running
Cancellation detected
test4 status: Canceled

Note how for the second case "Test with already-cancelled token passed to Task.Run()", Entering Test() is not written to the console because the action is not called. This is the only test case where the action is not called at all.


问:
How to run suite tests with several values as a loop using Robot framework
please someone can help me to how to run suite tests with several values as a loop using Robot framework with Template as follows:

FIRST EXECUTION:

---> Suite Setup: OPEN APP

Add Employee1 :: Verify adding an employee

---> SCENARIO 01

---> first_name: John

---> last_name: Doe

---> SCENARIO 02

---> first_name: Monty

---> last_name: Python

---> SCENARIO 03

---> first_name: Knight

---> last_name: Ni

---> Suite Teardown: CLOSE APP
| PASS |

-------------------------------------------------------

SECONDE EXECUTION:

---> Suite Setup: OPEN APP

Add Delete Employee :: Verify deleting an employee

---> SCENARIO 01

---> first_name: John

---> last_name: Doe

---> SCENARIO 02

---> first_name: Monty

---> last_name: Python

---> SCENARIO 03

---> first_name: Knight

---> last_name: Ni

---> Suite Teardown: CLOSE APP
| PASS |

Thank you!

答:
You can create two lists and then use the value index wise</p>
```<code>@{firstNameList} create list  John  Monty  Knight
@{LastNameList} create list  Doe Python  Ni

TestCase1
{firstNameList}[1]
{LastNameList}[1]

 TestCase2
{firstNameList}[2]
{LastNameList}[2]
</code>```

Body:
You can create two lists and then use the value index wise

@{firstNameList} create list  John  Monty  Knight
@{LastNameList} create list  Doe Python  Ni

TestCase1
{firstNameList}[1]
{LastNameList}[1]

 TestCase2
{firstNameList}[2]
{LastNameList}[2]


问:
showing error message returned from server validation in react
Below is axios request sent to server for data submit and in return I am getting validation errors if any,

```<code>  const storeExpense = async (expenseData) => {

    const response = await axios.post('/api/expenses/store/', expenseData).catch(function (error) {
      if (error.response) {
        return error.response.data;

      } else if (error.request) {
        console.log(error.request);
      } else {

        console.log('Error', error.message);
      }
    });
    return response;
  }
</code>```

In another component, I storing return in variable,

```<code>const response = await storeExpense(values)

if('errors' in response)
{
  setValErrors(Object.values(response))
  setStatus({ success: false });
  setErrors({ submit: response.errors });
  setSubmitting(false);
  setRequestStatus(true)
}

</code>```

Below is the return response, it's an array and with objects.

```<code>Array [ "The given data was invalid.", {…} ]

0: "The given data was invalid."

1: Object { expense_description: (1) […], accountcustomtype_id: (1) […], expense_date: (1) […], … }

accountcustomtype_id: Array [ "Expense account is required." ]

expense_amount: Array [ "Expense amount is required." ]

expense_date: Array [ "Expense date is required." ]

expense_description: Array [ "Expense description is required." ]

paymentoption_id: Array [ "Payment with is required." ]

taxgroup_id: Array [ "Tax is required." ]

</code>```

How can I print each validation error messages? with .map()?

Thank you,

答:
```<code>const response = await storeExpense(values)

if('errors' in response){
  const errorsList = responce.errors[1];
  const errors = Object.keys(errorsList).map(k =>errorsList[k].join(''))
  setErrors({ submit: errors });
  ...
};
</code>```

Body:
Below is axios request sent to server for data submit and in return I am getting validation errors if any,

  const storeExpense = async (expenseData) => {

    const response = await axios.post('/api/expenses/store/', expenseData).catch(function (error) {
      if (error.response) {
        return error.response.data;

      } else if (error.request) {
        console.log(error.request);
      } else {

        console.log('Error', error.message);
      }
    });
    return response;
  }

In another component, I storing return in variable,

const response = await storeExpense(values)

if('errors' in response)
{
  setValErrors(Object.values(response))
  setStatus({ success: false });
  setErrors({ submit: response.errors });
  setSubmitting(false);
  setRequestStatus(true)
}

Below is the return response, it's an array and with objects.

Array [ "The given data was invalid.", {…} ]

0: "The given data was invalid."

1: Object { expense_description: (1) […], accountcustomtype_id: (1) […], expense_date: (1) […], … }

accountcustomtype_id: Array [ "Expense account is required." ]

expense_amount: Array [ "Expense amount is required." ]

expense_date: Array [ "Expense date is required." ]

expense_description: Array [ "Expense description is required." ]

paymentoption_id: Array [ "Payment with is required." ]

taxgroup_id: Array [ "Tax is required." ]

How can I print each validation error messages? with .map()?

Thank you,


问:
SQL to limit the types of tables returned when connecting to Oracle Database in Power BI
I have got a connection to an Oracle Database set up in Power BI.
This is working fine, apart from the fact it brings back 9500+ tables that start with "BIN".

Is there some SQL code I can put in the SQL statement section when connecting to the Oracle Database that limits the tables that it returns to ignore any table that begins with 'BIN'?

答:
Tables starting with BIN$ are tables that have been dropped but not purged and are in Oracle's "recycle bin".

The simplest method of not showing them is, if they are no longer required, to PURGE (delete) the tables from the recycle bin and then you will not see them as they will not exist.

You can use (documentation link):

PURGE TABLE BIN$0+xyzabcdefghi123 to get rid of an individual tables with that name (or you can use the original name of the table).

PURGE TABLESPACE tablespace_name USER username; to get rid of all recycled tables in a table space belonging to a single user.

PURGE TABLESPACE tablespace_name; to get rid of all recycled tables in a table space.

PURGE RECYCLEBIN; to get rid of all of the current user's recycled tables.

PURGE DBA_RECYCLEBIN; to get rid of everything in the recycle bin (assuming you have SYSDBA privileges).

Before purging tables you should make sure that they are really not required as you would need to restore from backups to bring them back.


问:
React-Typescript: This JSX tag's 'children' prop expects a single child of type 'Element | undefined', but multiple children were provided
I am using react-typescript for my app. For styling I am using Style component. I have decided I will create my custom Hooks Input and Password input. So I first created Input wrapper where I added necessary input fields. After that I have created Password input field. i extended my Password input component props with Input component props. But when I am using Input component wrapper to my password component. I am getting error: This JSX tag's 'children' prop expects a single child of type 'Element | undefined', but multiple children were provided.

I don't know what I am doing wrong.

This is my Input wrapper component

```<code>import React from "react";
import styled from "styled-components";
import ErrorBoundary from "components/errorBoundary";

const Container = styled.div`
  position: relative;
`;

const Label = styled.label<{ minimized?: boolean }>`
  display: block;
  color: ${({ theme }) => theme.inputLabelColor};
  font-weight: 400;
  font-size: ${({ minimized }) => (minimized ? "11px" : "16px")};
  margin-bottom: 5px;
  letter-spacing: -0.2px;
  position: absolute;
  transform: translateY(${({ minimized }) => (minimized ? "9px" : "16px")});
  left: 20px;
  top: 0;
  pointer-events: none;
  transition: transform 150ms linear, font-size 150ms linear;
`;

const Error = styled.p`
  color: ${({ theme }) => theme.errorTextColor};
`;

const Description = styled.p`
  color: blue;
`;

export interface IInputWrapperProps {
  label?: string;
  required?: boolean;
  minimizedLabel?: boolean;
  description?: string;
  error?: string;
  wrapperStyle?: React.CSSProperties;
  children?: JSX.Element;
}

export default ({
  label,
  error,
  description,
  children,
  required,
  wrapperStyle,
  minimizedLabel
}: IInputWrapperProps) => {
  return (
    <ErrorBoundary id="InputWrapperErrorBoundary">
      <div style={wrapperStyle}>
        <Container>
          <Label minimized={minimizedLabel}>
            {label} {required && <span style={{ color: "red" }}> *</span>}
          </Label>
          {children}
        </Container>
        {description && <Description>{description}</Description>}
        {error && <Error>{error}</Error>}
      </div>
    </ErrorBoundary>
  );
};
</code>```

This is my password component

```<code>import React, { useState } from "react";
import styled from "styled-components";
import eyeHide from "./eye-svgfiles/eyeHide.svg";
import eyeShow from "./eye-svgfiles/eyeShow.svg";
import InputWrapper, { IInputWrapperProps } from "../wrapper";
const Passwordinput = styled.input`
  border: 2px solid ${({ theme }) => theme.inputBorderColorFaded};
  background: ${({ theme }) => theme.inputBackgroundColor};
  display: block;
  border-radius: 5px;
  box-shadow: none;
  color: ${({ theme }) => theme.inputTextColor};
  height: 52px;
  width: 100%;
  margin: 0;
  padding: 1px 15px;
  &:focus {
    border: 2px solid ${({ theme }) => theme.inputBorderColor};
    outline: 0;
  }
`;
const Svg = styled.div`
  position: absolute;
  left: 50%;
  top: 65%;
  transform: scale(0.8);
`;

export interface IPasswordProps extends IInputWrapperProps {
  onChange: (i: string) => void;
  value?: string | undefined;
}
export default ({ onChange, value, label, error, ...rest }: IPasswordProps) => {
  const [state, setstate] = useState(false);
  return (
    <div>
      <InputWrapper label={label} error={error} {...rest}> //I am getting error in here
        <Passwordinput
          label={label}
          type={state ? "text" : "password"}
          onChange={e => onChange(e.target.value)}
          value={value}
          error={error}
        />
        <Svg>
          <img
            onClick={() => setstate(state => !state)}
            style={{ cursor: "pointer" }}
            src={state ? eyeShow : eyeHide}
            alt="searchIcon"
          />
        </Svg>
      </InputWrapper>
    </div>
  );
};
</code>```

答:
Correct practice is the following:

```<code>interface InputWrapperProps {
  ...yourProps,
  children?: ReactChild | ReactChild[] | ReactChildren | ReactChildren[];
}
</code>```

Servus

Body:
I am using react-typescript for my app. For styling I am using Style component. I have decided I will create my custom Hooks Input and Password input. So I first created Input wrapper where I added necessary input fields. After that I have created Password input field. i extended my Password input component props with Input component props. But when I am using Input component wrapper to my password component. I am getting error: This JSX tag's 'children' prop expects a single child of type 'Element | undefined', but multiple children were provided.

I don't know what I am doing wrong.

This is my Input wrapper component

import React from "react";
import styled from "styled-components";
import ErrorBoundary from "components/errorBoundary";

const Container = styled.div`
  position: relative;
`;

const Label = styled.label<{ minimized?: boolean }>`
  display: block;
  color: ${({ theme }) => theme.inputLabelColor};
  font-weight: 400;
  font-size: ${({ minimized }) => (minimized ? "11px" : "16px")};
  margin-bottom: 5px;
  letter-spacing: -0.2px;
  position: absolute;
  transform: translateY(${({ minimized }) => (minimized ? "9px" : "16px")});
  left: 20px;
  top: 0;
  pointer-events: none;
  transition: transform 150ms linear, font-size 150ms linear;
`;

const Error = styled.p`
  color: ${({ theme }) => theme.errorTextColor};
`;

const Description = styled.p`
  color: blue;
`;

export interface IInputWrapperProps {
  label?: string;
  required?: boolean;
  minimizedLabel?: boolean;
  description?: string;
  error?: string;
  wrapperStyle?: React.CSSProperties;
  children?: JSX.Element;
}

export default ({
  label,
  error,
  description,
  children,
  required,
  wrapperStyle,
  minimizedLabel
}: IInputWrapperProps) => {
  return (
    <ErrorBoundary id="InputWrapperErrorBoundary">

        <Container>

            {label} {required &&  *}

          {children}
        </Container>
        {description && <Description>{description}</Description>}
        {error && <Error>{error}</Error>}

    </ErrorBoundary>
  );
};

This is my password component

import React, { useState } from "react";
import styled from "styled-components";
import eyeHide from "./eye-svgfiles/eyeHide.svg";
import eyeShow from "./eye-svgfiles/eyeShow.svg";
import InputWrapper, { IInputWrapperProps } from "../wrapper";
const Passwordinput = styled.input`
  border: 2px solid ${({ theme }) => theme.inputBorderColorFaded};
  background: ${({ theme }) => theme.inputBackgroundColor};
  display: block;
  border-radius: 5px;
  box-shadow: none;
  color: ${({ theme }) => theme.inputTextColor};
  height: 52px;
  width: 100%;
  margin: 0;
  padding: 1px 15px;
  &:focus {
    border: 2px solid ${({ theme }) => theme.inputBorderColor};
    outline: 0;
  }
`;
const Svg = styled.div`
  position: absolute;
  left: 50%;
  top: 65%;
  transform: scale(0.8);
`;

export interface IPasswordProps extends IInputWrapperProps {
  onChange: (i: string) => void;
  value?: string | undefined;
}
export default ({ onChange, value, label, error, ...rest }: IPasswordProps) => {
  const [state, setstate] = useState(false);
  return (

      <InputWrapper label={label} error={error} {...rest}> //I am getting error in here
        <Passwordinput
          label={label}
          type={state ? "text" : "password"}
          onChange={e => onChange(e.target.value)}
          value={value}
          error={error}
        />
        <Svg>
           setstate(state => !state)}
            style={{ cursor: "pointer" }}
            src={state ? eyeShow : eyeHide}
            alt="searchIcon"
          />
        </Svg>
      </InputWrapper>

  );
};

Body:
Correct practice is the following:

interface InputWrapperProps {
  ...yourProps,
  children?: ReactChild | ReactChild[] | ReactChildren | ReactChildren[];
}

Servus


问:
List of "Year-Month" from Current Year month to Jan-2021 in Java
I have a business requirement to write a service which returns the list of Year months (01-2021,02-2021,....) starting from 01-2021 to the current year month (current : 02-2022).

Can anyone suggest me the approach that I can take to solve this in Java 8

O/P : 01-2021, 02-2021, 03-2021, 04-2021 , so on , 02-2022.

答:
```<code>import java.time.*;
import java.time.format.DateTimeFormatter;
public class YearMonth {
    public static void getYearMonths() {

        YearMonth nextMonth = YearMonth.now().plusMonths(1);
        YearMonth yearMonth = YearMonth.of(2021, 01);

        while (nextMonth.isAfter(yearMonth)) {
        // Create a DateTimeFormatter string
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM-yyyy");

        // Format this year-month
        System.out.println(yearMonth.format(formatter));
        yearMonth = yearMonth.plusMonths(1);
        }
    }
}
</code>```


问:
Uncaught ReferenceError: Cannot access '__WEBPACK_DEFAULT_EXPORT__' before initialization
I have a problem with my webpack project, so I was trying to import one class to another and instantiate it but suddenly an error appear in my console and my program stopped working, it was this:

```<code>Uncaught ReferenceError: Cannot access '__WEBPACK_DEFAULT_EXPORT__' before initialization
</code>```

This is the code of the class were I am trying to import my another class (that is PopUpPlugin):

```<code>import PopupPlugin from './popupPlugin.js';

export const addSearchBtnEvent = (weatherUI) => {
  const searchBtn = document.querySelector('.weather__search');

  searchBtn.addEventListener('click', () => {
    weatherUI.style.opacity = '1';
    weatherUI.style.visibility = 'visible';
  })
}

export const addSearchExitEvent = (weatherUI) => {
  const weatherExit = document.querySelector('.weather__search-exit');

  weatherExit.addEventListener('click', () => {
    weatherUI.style.opacity = '0';
    weatherUI.style.visibility = 'hidden';
  })
}

const popupObj = new PopupPlugin();

class searchDashboard {
  constructor() {

  }

  setInputEvent() {
    const inputSearch = document.querySelector('.weather__city-search');
    const inputSearchBtn = document.querySelector('.weather__search-btn');

    inputSearchBtn.addEventListener('click', () => {
      const inputSearchVal = inputSearch.value;

      this.validateStr(inputSearchVal);
    });
  }

  validateStr() {
    const onlyLettersAndSpaces = /^[a-zA-Z][a-zA-Z\s]*$/;

    if(str.trim().length > 0 && str.match(onlyLettersAndSpaces)) {
      const strValue = str.toLowerCase().trim().replace(' ', '+');

      this.popupObj.searchCoincidences(strValue, 'weather__search-ui');
    }
  }
}

export default searchDashboard;
</code>```

I don't actually know why this is happening, I also tried to instantiate it inside the constructor and it worked but it sended me the error of an stack overflow.

PD: If someone needs it here is the code of the PopupPlugin. (Here is what was working to me that was instantiating the class inside the constructor until the stack overflow error appeared)

```<code>import ManageWeatherDashboard from './manageWeatherDashboard.js';
import { getFetch, repeatAppend } from './weatherHelpers.js';

class popupPlugin {
  constructor() {
    this.manageWeatherDashboardObj = new ManageWeatherDashboard();
  }

  validateStr(str) {
    const onlyLettersAndSpaces = /^[a-zA-Z][a-zA-Z\s]*$/;

    if(str.trim().length > 0 && str.match(onlyLettersAndSpaces)) {
      const strValue = str.toLowerCase().trim().replace(' ', '+');

      return strValue;
    }
  }

  searchCoincidences(val, parent) {
    getFetch(`https://www.metaweather.com/api/location/search/?query=${val}`)
      .then(res => res.text())
      .then(data => {
        const parentResults = document.querySelector('.'+parent);

        parentResults.innerHTML = '';

        const dataArr = JSON.parse(data)

        if(dataArr.length >= 15) {
          let resVal;

          for(let i = 0; i <= 15; i++) {
            resVal = this.addDOMResultCoincidences(parent, dataArr[i].title,
              dataArr[i].woeid);
          }

          this.whenClickCoincidence(resVal);
        } else {
          let resVal;

          dataArr.forEach(el => {
            resVal = this.addDOMResultCoincidences(parent, el.title, el.woeid);
          })

          this.whenClickCoincidence(resVal);
        }

      })
  }

  addDOMResultCoincidences(parentBlock, name, id) {
    const args = Array.from(arguments);

    if(args[0] === 'popup__results') {
      const popupResults = document.querySelector('.popup__results');

      const divResult = document.createElement('div');
      divResult.className = 'popup__result';
      divResult.setAttribute('data-woeid', id);

      const spanResultName = document.createElement('span');
      spanResultName.className = 'popup__result-name';

      const cityReturn = document.createTextNode(args[1]);

      spanResultName.appendChild(cityReturn);

      divResult.appendChild(spanResultName);

      popupResults.prepend(divResult);

      return divResult;
    }

    if(args[0] === 'weather__search-ui') {
      const weatherUI = document.querySelector('.weather__search-ui');

      const divResult = document.createElement('div');
      divResult.className = 'weather__search-result';
      divResult.setAttribute('data-woeid', id);

      const spanResultName = document.createElement('span');
      const spanResultNameText = document.createTextNode(args[1]);
      spanResultName.className = 'weather__city-result';
      spanResultName.appendChild(spanResultNameText);

      const iconResult = document.createElement('i');
      iconResult.className = 'fa fa-arrow-right weather__go-result';

      repeatAppend([spanResultName, iconResult], divResult);

      weatherUI.appendChild(divResult);

      return divResult;
    }
  }

  // When click a coincidence in search field

  whenClickCoincidence(el) {
    const woeId = el.getAttribute('data-woeid');

    el.addEventListener('click', () => {
      let handler = 0;

      if(handler === 0) {
        getFetch(`https://www.metaweather.com/api/location/${woeId}/`)
          .then(res => res.json())
          .then(data => {
            const popup = document.querySelector('.popup');

            const weatherNext6Days = data.consolidated_weather;

            this.manageWeatherDashboardObj.changeWeatherBar(weatherNext6Days[0], data.title);

            weatherNext6Days.slice(1, 6).forEach(el => {
              this.manageWeatherDashboardObj.nextFiveDays(el);
            })

            this.manageWeatherDashboardObj.updateStadistics(weatherNext6Days[0]);

            popup.style.opacity = '0';
            popup.style.visibility = 'hidden';
          })
      }

      handler += 1;
    })
  }
}

export default popupPlugin;
</code>```

答:
Maybe because you used circle import.

For me, I used encapsulated axios to request in mobx store, and I also used some data from mobx store in encapsulated axios.

Body:
I have a problem with my webpack project, so I was trying to import one class to another and instantiate it but suddenly an error appear in my console and my program stopped working, it was this:

Uncaught ReferenceError: Cannot access '__WEBPACK_DEFAULT_EXPORT__' before initialization

This is the code of the class were I am trying to import my another class (that is PopUpPlugin):

import PopupPlugin from './popupPlugin.js';

export const addSearchBtnEvent = (weatherUI) => {
  const searchBtn = document.querySelector('.weather__search');

  searchBtn.addEventListener('click', () => {
    weatherUI.style.opacity = '1';
    weatherUI.style.visibility = 'visible';
  })
}

export const addSearchExitEvent = (weatherUI) => {
  const weatherExit = document.querySelector('.weather__search-exit');

  weatherExit.addEventListener('click', () => {
    weatherUI.style.opacity = '0';
    weatherUI.style.visibility = 'hidden';
  })
}

const popupObj = new PopupPlugin();

class searchDashboard {
  constructor() {

  }

  setInputEvent() {
    const inputSearch = document.querySelector('.weather__city-search');
    const inputSearchBtn = document.querySelector('.weather__search-btn');

    inputSearchBtn.addEventListener('click', () => {
      const inputSearchVal = inputSearch.value;

      this.validateStr(inputSearchVal);
    });
  }

  validateStr() {
    const onlyLettersAndSpaces = /^[a-zA-Z][a-zA-Z\s]*$/;

    if(str.trim().length > 0 && str.match(onlyLettersAndSpaces)) {
      const strValue = str.toLowerCase().trim().replace(' ', '+');

      this.popupObj.searchCoincidences(strValue, 'weather__search-ui');
    }
  }
}

export default searchDashboard;

I don't actually know why this is happening, I also tried to instantiate it inside the constructor and it worked but it sended me the error of an stack overflow.

PD: If someone needs it here is the code of the PopupPlugin. (Here is what was working to me that was instantiating the class inside the constructor until the stack overflow error appeared)

import ManageWeatherDashboard from './manageWeatherDashboard.js';
import { getFetch, repeatAppend } from './weatherHelpers.js';

class popupPlugin {
  constructor() {
    this.manageWeatherDashboardObj = new ManageWeatherDashboard();
  }

  validateStr(str) {
    const onlyLettersAndSpaces = /^[a-zA-Z][a-zA-Z\s]*$/;

    if(str.trim().length > 0 && str.match(onlyLettersAndSpaces)) {
      const strValue = str.toLowerCase().trim().replace(' ', '+');

      return strValue;
    }
  }

  searchCoincidences(val, parent) {
    getFetch(`https://www.metaweather.com/api/location/search/?query=${val}`)
      .then(res => res.text())
      .then(data => {
        const parentResults = document.querySelector('.'+parent);

        parentResults.innerHTML = '';

        const dataArr = JSON.parse(data)

        if(dataArr.length >= 15) {
          let resVal;

          for(let i = 0; i <= 15; i++) {
            resVal = this.addDOMResultCoincidences(parent, dataArr[i].title,
              dataArr[i].woeid);
          }

          this.whenClickCoincidence(resVal);
        } else {
          let resVal;

          dataArr.forEach(el => {
            resVal = this.addDOMResultCoincidences(parent, el.title, el.woeid);
          })

          this.whenClickCoincidence(resVal);
        }

      })
  }

  addDOMResultCoincidences(parentBlock, name, id) {
    const args = Array.from(arguments);

    if(args[0] === 'popup__results') {
      const popupResults = document.querySelector('.popup__results');

      const divResult = document.createElement('div');
      divResult.className = 'popup__result';
      divResult.setAttribute('data-woeid', id);

      const spanResultName = document.createElement('span');
      spanResultName.className = 'popup__result-name';

      const cityReturn = document.createTextNode(args[1]);

      spanResultName.appendChild(cityReturn);

      divResult.appendChild(spanResultName);

      popupResults.prepend(divResult);

      return divResult;
    }

    if(args[0] === 'weather__search-ui') {
      const weatherUI = document.querySelector('.weather__search-ui');

      const divResult = document.createElement('div');
      divResult.className = 'weather__search-result';
      divResult.setAttribute('data-woeid', id);

      const spanResultName = document.createElement('span');
      const spanResultNameText = document.createTextNode(args[1]);
      spanResultName.className = 'weather__city-result';
      spanResultName.appendChild(spanResultNameText);

      const iconResult = document.createElement('i');
      iconResult.className = 'fa fa-arrow-right weather__go-result';

      repeatAppend([spanResultName, iconResult], divResult);

      weatherUI.appendChild(divResult);

      return divResult;
    }
  }

  // When click a coincidence in search field

  whenClickCoincidence(el) {
    const woeId = el.getAttribute('data-woeid');

    el.addEventListener('click', () => {
      let handler = 0;

      if(handler === 0) {
        getFetch(`https://www.metaweather.com/api/location/${woeId}/`)
          .then(res => res.json())
          .then(data => {
            const popup = document.querySelector('.popup');

            const weatherNext6Days = data.consolidated_weather;

            this.manageWeatherDashboardObj.changeWeatherBar(weatherNext6Days[0], data.title);

            weatherNext6Days.slice(1, 6).forEach(el => {
              this.manageWeatherDashboardObj.nextFiveDays(el);
            })

            this.manageWeatherDashboardObj.updateStadistics(weatherNext6Days[0]);

            popup.style.opacity = '0';
            popup.style.visibility = 'hidden';
          })
      }

      handler += 1;
    })
  }
}

export default popupPlugin;


问:
How can I match a repeating pattern with Java regular expressions?
Given the following input string 3481.7.1071.html

I want to  confirm that

The string has 1 or more numbers followed by a period.

The string ends in html.

Finally, I want to extract the left-most number (i.e. 3481).

My current regex is nearly there but I can't capture the correct group:

```<code>final Pattern p = Pattern.compile("(\\d++\\.)+html");
final Matcher m = p.matcher("3481.7.1071.html");
if (m.matches()) {
    final String corrected = m.group(1)+"html"; // WRONG! Gives 1071.html
}
</code>```

How do I capture the first match?

答:
Java style: "(\\d+)\\..*?\\.html$"

This will 1) grab the first group of consecutive digits, 2) require a dot after words, 3) jump over everything except 3) the literal string '.html'.

If you mean "one or more [groups] of numbers followed by a period" then this is more along the lines of your requirements.

```<code>"(\\d+)(?:\\.\\d+)*\\.html$"
</code>```

This way you get a number and not the dot. And none of the other patterns need to be captured, so they are not.

OwnerDisplayName: johnstok

ContentLicense: CC BY-SA 2.5

Body:
Given the following input string 3481.7.1071.html

I want to  confirm that

The string has 1 or more numbers followed by a period.

The string ends in html.

Finally, I want to extract the left-most number (i.e. 3481).

My current regex is nearly there but I can't capture the correct group:

final Pattern p = Pattern.compile("(\\d++\\.)+html");
final Matcher m = p.matcher("3481.7.1071.html");
if (m.matches()) {
    final String corrected = m.group(1)+"html"; // WRONG! Gives 1071.html
}

How do I capture the first match?

Body:
Java style: "(\\d+)\\..*?\\.html$"

This will 1) grab the first group of consecutive digits, 2) require a dot after words, 3) jump over everything except 3) the literal string '.html'.

If you mean "one or more [groups] of numbers followed by a period" then this is more along the lines of your requirements.

"(\\d+)(?:\\.\\d+)*\\.html$"

This way you get a number and not the dot. And none of the other patterns need to be captured, so they are not.

OwnerDisplayName: Axeman

LastEditorDisplayName: Axeman


问:
Python make clusters of synonyms
I have a long list of words :

```<code>verbs = ['be','have', 'find', 'use', 'show', 'increase', 'detect', 'do', 'determine', 'demonstrate', 'observe','suggest', ...]
</code>```

And I want to make clusters from these words based on which ones are synonyms (semantically close). I want to compare each element of the list with all the rest and for those that have a similarity score > 0.7 , group them together. I am using wordnet but I keep getting this error:

for i, verb in enumerate(verbs):
    for j in range(i + 1, len(verbs)):
        verbs[i].wup_similarity(verbs[j])

    ERROR MESSAGE :
    ---->        verbs[i].wup_similarity(verbs[j])
    ---->        AttributeError: 'str' object has no attribute 'wup_similarity'
```

Maybe that's not even the right approach, but can anyone help?

答:
Regarding the updated question, this solution works on my machine.

```<code>verbs = ['be','have', 'find', 'use', 'show', 'increase', 'detect', 'do', 'determine', 'demonstrate', 'observe','suggest']

for i, verb in enumerate(verbs):
    for j in range(i + 1, len(verbs)):
        v1 = wordnet.synset(verbs[i]+ '.v.01')
        v2 = wordnet.synset(verbs[j]+ '.v.01')
        wup_score = v1.wup_similarity(v2)
        if wup_score > 0.7:
            print(f"{verbs[i]} and {verbs[j]} are similar")
            #or do whatever you want to do with similar words.
</code>```

Regarding the original question:

I'am no expert in this, so maybe this does not help at all. Currently you do str.wup_similarity(str). However according to this documentation (search for 'wup_similarity' on that website) I think it should be synset1.wup_similarity(synset2).

So my proposal would be to do:

```<code>for i, verb in enumerate(verbs):
    for j in range(i + 1, len(verbs)):
        for syni in wordnet.synsets(verb[i]):
            for synj in wordnet.synsets(verb[j]):
                for li in syni.lemmas():
                    for lj in synj.lemmas():
                        v1 = wordnet.synset(verbs[i]+ '.v.01')
                        v2 = wordnet.synset(verbs[j]+ '.v.01')
                        v1.wup_similarity(v2)
</code>```

Title: Python make clusters of synonyms

Body:
I have a long list of words :

verbs = ['be','have', 'find', 'use', 'show', 'increase', 'detect', 'do', 'determine', 'demonstrate', 'observe','suggest', ...]

And I want to make clusters from these words based on which ones are synonyms (semantically close). I want to compare each element of the list with all the rest and for those that have a similarity score > 0.7 , group them together. I am using wordnet but I keep getting this error:

for i, verb in enumerate(verbs):
    for j in range(i + 1, len(verbs)):
        verbs[i].wup_similarity(verbs[j])

    ERROR MESSAGE :
    ---->        verbs[i].wup_similarity(verbs[j])
    ---->        AttributeError: 'str' object has no attribute 'wup_similarity'

Maybe that's not even the right approach, but can anyone help?

Body:
Regarding the updated question, this solution works on my machine.

verbs = ['be','have', 'find', 'use', 'show', 'increase', 'detect', 'do', 'determine', 'demonstrate', 'observe','suggest']

for i, verb in enumerate(verbs):
    for j in range(i + 1, len(verbs)):
        v1 = wordnet.synset(verbs[i]+ '.v.01')
        v2 = wordnet.synset(verbs[j]+ '.v.01')
        wup_score = v1.wup_similarity(v2)
        if wup_score > 0.7:
            print(f"{verbs[i]} and {verbs[j]} are similar")
            #or do whatever you want to do with similar words.

Regarding the original question:

I'am no expert in this, so maybe this does not help at all. Currently you do str.wup_similarity(str). However according to this documentation (search for 'wup_similarity' on that website) I think it should be synset1.wup_similarity(synset2).

So my proposal would be to do:

for i, verb in enumerate(verbs):
    for j in range(i + 1, len(verbs)):
        for syni in wordnet.synsets(verb[i]):
            for synj in wordnet.synsets(verb[j]):
                for li in syni.lemmas():
                    for lj in synj.lemmas():
                        v1 = wordnet.synset(verbs[i]+ '.v.01')
                        v2 = wordnet.synset(verbs[j]+ '.v.01')
                        v1.wup_similarity(v2)


问:
Python unintentionally deleting keys in other dictionaries
When using del or .pop() on x_copy, the operation is magically applied to x as well. i.e. keys in both dictionaries are deleted.

Example code:

x = {
    "key1": 0,
    "key2": 0,
}

x_copy = x
x_copy.pop("key1")

print(f"x =      {x}")
print(f"x copy = {x_copy}")
```
<p>This code should only remove the key from <code>x</code>, but the key is lost from both dictionaries.</p>
<p>Actual output:</p>
<pre class="lang-py prettyprint-override"><code>>>> x =      {'key2': 0}
>>> x copy = {'key2': 0}
</code>```

Expected output

```<code>>>> x =      {'key1': 0, 'key2': 0}
>>> x copy = {'key2': 0}
</code>```

Same happens if I replace .pop() with del:

x_copy = x
x_copy.pop("key1")
```

Why is this happening?

Python 3.10

答:
x_copy = x gives you 2 variables pointing at the same place in memory and all the operations that modify one will be reflected in another. You need to actually create another object in memory (e.g. with x.copy())and then you can treat it as an indepentant copy.
https://moonbooks.org/Articles/How-to-copy-a-dictionary-in-python-/

Body:
When using del or .pop() on x_copy, the operation is magically applied to x as well. i.e. keys in both dictionaries are deleted.

Example code:

x = {
    "key1": 0,
    "key2": 0,
}

x_copy = x
x_copy.pop("key1")

print(f"x =      {x}")
print(f"x copy = {x_copy}")

This code should only remove the key from x, but the key is lost from both dictionaries.

Actual output:

>>> x =      {'key2': 0}
>>> x copy = {'key2': 0}

Expected output

>>> x =      {'key1': 0, 'key2': 0}
>>> x copy = {'key2': 0}

Same happens if I replace .pop() with del:

x_copy = x
x_copy.pop("key1")

Why is this happening?

Python 3.10


问:
EditorFor() and html properties
Asp.Net MVC 2.0 preview builds provide helpers like

```<code>Html.EditorFor(c => c.propertyname)
</code>```

If the property name is string, the above code renders a texbox.

What if I want to pass in MaxLength and Size properties to the text box or my own css class property?

Do I need to create one template for each size and length combinations in my application? If so, that doesn't make the default templates that usable.

答:
I don't know why it does not work for Html.EditorFor but I tried TextBoxFor and it worked for me.

```<code>@Html.TextBoxFor(m => m.Name, new { Class = "className", Size = "40"})
</code>```

...and also validation works.

Title: EditorFor() and html properties

Body:
Asp.Net MVC 2.0 preview builds provide helpers like

Html.EditorFor(c => c.propertyname)

If the property name is string, the above code renders a texbox.

What if I want to pass in MaxLength and Size properties to the text box or my own css class property?

Do I need to create one template for each size and length combinations in my application? If so, that doesn't make the default templates that usable.

Body:
I don't know why it does not work for Html.EditorFor but I tried TextBoxFor and it worked for me.

@Html.TextBoxFor(m => m.Name, new { Class = "className", Size = "40"})

...and also validation works.


问:
PowerApps - If the user selects a value from the dropdown to navigate to a specific screen
I have completed all my screens in PowerApps and I am now trying to setup the navigation.

My dropdown is named Dropdown1

The dropdown value in question is Employement

The screen that I want the user to go to if he/she selects Employement in the dropdown is called Section 3 Other Mirror

the screen that I want the user to go to if he/she selects any other choice in the dropdown is called Section 4 VP Setup

Current formula:
If(Dropdown1.Selected.Value = "Employement"; Navigate('Section 3 Other Mirror',ScreenTransition.Cover)

Error: Unexpected characters. 'ParenClose' where 'Eof' is expected.

答:
You can make a collection in the OnStart section with for example:

```<code>[
  {
     Name: "Employers",
     ScreenName: [@Screen1]
  },
  {
    Name: "Admins",
    ScreenName: [@Screen2]
  }
]
</code>```

If you put this collection on a dropdown, you could use your navigate via the OnSelect of a button as follow:

```<code>Navigate( Dropdown.Selected.ScreenName, YourTransitionStyle )
</code>```

Saves a lot of rewriting in lots of places.

Body:
You can make a collection in the OnStart section with for example:

[
  {
     Name: "Employers",
     ScreenName: [@Screen1]
  },
  {
    Name: "Admins",
    ScreenName: [@Screen2]
  }
]

If you put this collection on a dropdown, you could use your navigate via the OnSelect of a button as follow:

Navigate( Dropdown.Selected.ScreenName, YourTransitionStyle )

Saves a lot of rewriting in lots of places.


问:
How to access material theme in shared component in react?
I have two react projects Parent and Common project (contains common component like header, footer)

I have material theme defined in Parent and configured in standard way using MuiThemeProvider.

However, this theme object is available inside components defined in Parent, but not in share project common.

Suggestions are appreciated.

Added below more details on Oct 30, 2020

Parent Component

```<code>import React from "react";
import "./App.css";
import { BrowserRouter, Switch, Route } from "react-router-dom";
import themeDefault from "./CustomTheme.js";
import { MuiThemeProvider } from "@material-ui/core/styles";
import { createMuiTheme } from "@material-ui/core/styles";
import Dashboard from "./containers/Dashboard/Dashboard";
import { Footer, Header } from "my-common-react-project";

function App() {
  const routes = () => {
    return (
      <BrowserRouter>
        <Switch>
          <Route exact path="/" component={Dashboard} />
        </Switch>
      </BrowserRouter>
    );
  };
  return (
    <MuiThemeProvider theme={createMuiTheme(themeDefault)}>
      <div className="App">
        <Header
          logo="some-logo"
          userEmail={"test@email"}
        />
        ... app components here..
        <Footer />
      </div>
    </MuiThemeProvider>
  );
}

export default App;
</code>```

Shared component

```<code>import React from "react";
import {
  Box,
  AppBar,
  Toolbar,
  Typography,
} from "@material-ui/core/";

import styles from "./Header.styles";
import PropTypes from "prop-types";

const Header = (props) => {
  const classes = styles();
  const { options, history } = props;
  const [anchorEl, setAnchorEl] = React.useState(null);
  const handleCloseMenu = () => {
    setAnchorEl(null);
  };

  const goto = (url) => {
    history.push(url);
  };
  return (
    <Box component="nav" className={classes.headerBox}>
      <AppBar position="static" className={classes.headerPart}>
        <Toolbar className={classes.toolBar}>
          {localStorage && localStorage.getItem("isLoggedIn") && (
            <>
              {options &&
                options.map((option) => (
                  <Typography
                    key={option.url}
                    variant="subtitle1"
                    className={classes.headerLinks}
                    onClick={() => goto(option.url)}
                  >
                    {option.name}
                  </Typography>
                ))}
            </>
          )}
        </Toolbar>
      </AppBar>
    </Box>
  );
};

Header.propTypes = {
  options: PropTypes.array
};
export default Header;
</code>```

Shared Component style

```<code>import { makeStyles } from "@material-ui/core/styles";

export default makeStyles((theme) => ({
  headerPart: {
    background: "white",
    boxShadow: "0px 4px 15px #00000029",
    opacity: 1,
    background: `8px solid ${theme.palette.primary.main}`
    borderTop: `8px solid ${theme.palette.primary.main}`
  }
}));
</code>```

The Parent component defined theme.palette.primary.main as say Red color and I expect same to be applied in Header but it is picking a different theme (default) object which has  theme.palette.primary.main blue.

Which results in my header to be in blue color but body in read color.

Any suggestion how to configure this theme object so that header too picks the theme.palette.primary.main from parent theme object.

答:
here is the answer for mui V5

```<code>import { useTheme } from '@mui/material/styles' // /!\ I fixed a typo from official doc here

function DeepChild() {
  const theme = useTheme();
  return <span>{`spacing ${theme.spacing}`}</span>;
}
</code>```

Taken from mui documentation

Body:
I have two react projects Parent and Common project (contains common component like header, footer)

I have material theme defined in Parent and configured in standard way using MuiThemeProvider.

However, this theme object is available inside components defined in Parent, but not in share project common.

Suggestions are appreciated.

Added below more details on Oct 30, 2020

Parent Component

import React from "react";
import "./App.css";
import { BrowserRouter, Switch, Route } from "react-router-dom";
import themeDefault from "./CustomTheme.js";
import { MuiThemeProvider } from "@material-ui/core/styles";
import { createMuiTheme } from "@material-ui/core/styles";
import Dashboard from "./containers/Dashboard/Dashboard";
import { Footer, Header } from "my-common-react-project";

function App() {
  const routes = () => {
    return (
      <BrowserRouter>
        <Switch>
          <Route exact path="/" component={Dashboard} />
        </Switch>
      </BrowserRouter>
    );
  };
  return (
    <MuiThemeProvider theme={createMuiTheme(themeDefault)}>

        ... app components here..

    </MuiThemeProvider>
  );
}

export default App;

Shared component

import React from "react";
import {
  Box,
  AppBar,
  Toolbar,
  Typography,
} from "@material-ui/core/";

import styles from "./Header.styles";
import PropTypes from "prop-types";

const Header = (props) => {
  const classes = styles();
  const { options, history } = props;
  const [anchorEl, setAnchorEl] = React.useState(null);
  const handleCloseMenu = () => {
    setAnchorEl(null);
  };

  const goto = (url) => {
    history.push(url);
  };
  return (
    <Box component="nav" className={classes.headerBox}>
      <AppBar position="static" className={classes.headerPart}>
        <Toolbar className={classes.toolBar}>
          {localStorage && localStorage.getItem("isLoggedIn") && (
            <>
              {options &&
                options.map((option) => (
                  <Typography
                    key={option.url}
                    variant="subtitle1"
                    className={classes.headerLinks}
                    onClick={() => goto(option.url)}
                  >
                    {option.name}
                  </Typography>
                ))}
            </>
          )}
        </Toolbar>
      </AppBar>
    </Box>
  );
};

Header.propTypes = {
  options: PropTypes.array
};
export default Header;

Shared Component style

import { makeStyles } from "@material-ui/core/styles";

export default makeStyles((theme) => ({
  headerPart: {
    background: "white",
    boxShadow: "0px 4px 15px #00000029",
    opacity: 1,
    background: `8px solid ${theme.palette.primary.main}`
    borderTop: `8px solid ${theme.palette.primary.main}`
  }
}));

The Parent component defined theme.palette.primary.main as say Red color and I expect same to be applied in Header but it is picking a different theme (default) object which has  theme.palette.primary.main blue.

Which results in my header to be in blue color but body in read color.

Any suggestion how to configure this theme object so that header too picks the theme.palette.primary.main from parent theme object.

Body:
here is the answer for mui V5

import { useTheme } from '@mui/material/styles' // /!\ I fixed a typo from official doc here

function DeepChild() {
  const theme = useTheme();
  return <span>{`spacing ${theme.spacing}`}</span>;
}

Taken from mui documentation


问:
issue with IFF and Multiple cascading Split in SSRS report
I am getting error for the below,

```<code>=IIF(Fields!ParentObjectType.Value !="Approval Request",Split(Split(Fields!CT_CaptionURL.Value,"f =").GetValue(1),"Target").GetValue(0),Split(Split(Fields!CT_CaptionURL.Value,"f=").GetValue(1),"target").GetValue(0))
</code>```

Got the below error
The Value expression for the field ‘URL’ contains an error: [BC30203] Identifier expected.

The definition of the report '' is invalid.

答: Replace != with <> in your expression</p>

Body:
I am getting error for the below,

=IIF(Fields!ParentObjectType.Value !="Approval Request",Split(Split(Fields!CT_CaptionURL.Value,"f =").GetValue(1),"Target").GetValue(0),Split(Split(Fields!CT_CaptionURL.Value,"f=").GetValue(1),"target").GetValue(0))

Got the below error
The Value expression for the field ‘URL’ contains an error: [BC30203] Identifier expected.

The definition of the report '' is invalid.

Body: Replace != with <> in your expression