问:
Module parse failed The top-level-await experiment is not enabled
```<code>import { keyboard } from '@testing-library/user-event/dist/keyboard';
import { RequiredError } from 'openai/dist/base'
import React from 'react'
import { Component } from 'react'
import { Container, Form, Button, Card } from 'react-bootstrap'

const { Configuration, OpenAIApi } = require("openai");

class ProductDescription extends Component {
    constructor() {
        super()
        this.state = {
            heading: 'The response from the AI will be shown here',
            response: '...... await the response'
        }
    }

    onFormSubmit = e => {
        // start by prevening the default
        e.preventDefault()

        const formData = new FormData(e.target),
            formDataObj = Object.fromEntries(formData.entries())
        console.log(formDataObj.productName)
        // OPENAI
        this.setState({
            heading: `AI product description suggestions for: ${formDataObj.productName}`,
            response: 'the response from OpenAI api will be shown here'
        })
    }

    render() {
        return (
            <div>
                <Container>
                    <br />
                    <br />
                    <h1>generate product descriptions</h1>
                    <br />
                    <h4>generate product descriptions for any types of products, simply enter the name and productdescriptions to the card</h4>
                    <br />
                    <br />
                    <Form onSubmit={this.onFormSubmit}>
                        <Form.Group className='mb-3' controlId='formBasicEmail'>
                            <Form.Label>What products would you like to get a description for?</Form.Label>
                            <Form.Control type='text' name='productName' placeholder='Enter product name' />
                            <Form.Text className='text-muted'>Enter as much information as possible for more accurate descriptions</Form.Text>
                        </Form.Group>
                        <Button variant="primary" size="lg" type="submit">Get AI suggestions</Button>
                    </Form>
                    <br />
                    <br />

                    <Card>
                        <Card.Body>
                            <Card.Title><h1>{this.state.heading}</h1></Card.Title>
                            <hr />
                            <br />
                            <Card.Text>
                                <h4>
                                    {this.state.response}
                                </h4>
                            </Card.Text>
                        </Card.Body>
                    </Card>
                </Container>
                <br />
                <br />
                <br />
                <br />
            </div>
        )
    }
}
const configuration = new Configuration({
  apiKey: 'your-api-key',
});
const openai = new OpenAIApi(configuration);

const response = await openai.createCompletion({
  model: "text-davinci-003",
  prompt: "generate product description explanation for the following product  apple iPhone 11\n\nThe Apple iPhone 11 is the latest version of Apple's iconic smartphone. Featuring a stunning new design, an A13 Bionic processor, and a dual rear-facing camera system, the iPhone 11's hardware is designed to give you an amazing mobile experience. With the ability to capture stunning 4K Ultra HD video, and a vibrant Retina HD display, the iPhone 11 provides unbeatable visual and audio quality. Additionally, iPhone 11 features an innovative range of features including Face ID, wireless charging, and a water-resistant body. With the power of iOS 13, you can safely and securely surf the web, communicate with ease, and stay connected with the people that matter most. With the Apple iPhone 11, you have the perfect combination of style and power.",
  temperature: 1,
  max_tokens: 200,
  top_p: 1,
  frequency_penalty: 0,
  presence_penalty: 0,
});
export default ProductDescription
</code>```

I've used the npm package and having no idea why is it throwing an error just followed this tutorial for some kind of help if we comment out the api section than all looks fine but can't do that I want to create a content generator tool in react.js with the help of this when we add some query into the input field and after pressing the submit button we get the detailed paragraph about the query like this openai

Body:
import { keyboard } from '@testing-library/user-event/dist/keyboard';
import { RequiredError } from 'openai/dist/base'
import React from 'react'
import { Component } from 'react'
import { Container, Form, Button, Card } from 'react-bootstrap'

const { Configuration, OpenAIApi } = require("openai");

class ProductDescription extends Component {
    constructor() {
        super()
        this.state = {
            heading: 'The response from the AI will be shown here',
            response: '...... await the response'
        }
    }

    onFormSubmit = e => {
        // start by prevening the default
        e.preventDefault()

        const formData = new FormData(e.target),
            formDataObj = Object.fromEntries(formData.entries())
        console.log(formDataObj.productName)
        // OPENAI
        this.setState({
            heading: `AI product description suggestions for: ${formDataObj.productName}`,
            response: 'the response from OpenAI api will be shown here'
        })
    }

    render() {
        return (

                <Container>

generate product descriptions

generate product descriptions for any types of products, simply enter the name and productdescriptions to the card

                    <Form onSubmit={this.onFormSubmit}>
                        <Form.Group className='mb-3' controlId='formBasicEmail'>
                            <Form.Label>What products would you like to get a description for?</Form.Label>
                            <Form.Control type='text' name='productName' placeholder='Enter product name' />
                            <Form.Text className='text-muted'>Enter as much information as possible for more accurate descriptions</Form.Text>
                        </Form.Group>
                        <Button variant="primary" size="lg" type="submit">Get AI suggestions</Button>
                    </Form>

                    <Card>
                        <Card.Body>
                            <Card.Title>
{this.state.heading}
</Card.Title>

                            <Card.Text>

                                    {this.state.response}

                            </Card.Text>
                        </Card.Body>
                    </Card>
                </Container>

        )
    }
}
const configuration = new Configuration({
  apiKey: 'your-api-key',
});
const openai = new OpenAIApi(configuration);

const response = await openai.createCompletion({
  model: "text-davinci-003",
  prompt: "generate product description explanation for the following product  apple iPhone 11\n\nThe Apple iPhone 11 is the latest version of Apple's iconic smartphone. Featuring a stunning new design, an A13 Bionic processor, and a dual rear-facing camera system, the iPhone 11's hardware is designed to give you an amazing mobile experience. With the ability to capture stunning 4K Ultra HD video, and a vibrant Retina HD display, the iPhone 11 provides unbeatable visual and audio quality. Additionally, iPhone 11 features an innovative range of features including Face ID, wireless charging, and a water-resistant body. With the power of iOS 13, you can safely and securely surf the web, communicate with ease, and stay connected with the people that matter most. With the Apple iPhone 11, you have the perfect combination of style and power.",
  temperature: 1,
  max_tokens: 200,
  top_p: 1,
  frequency_penalty: 0,
  presence_penalty: 0,
});
export default ProductDescription

I've used the npm package and having no idea why is it throwing an error just followed this tutorial for some kind of help if we comment out the api section than all looks fine but can't do that I want to create a content generator tool in react.js with the help of this when we add some query into the input field and after pressing the submit button we get the detailed paragraph about the query like this openai


来源: stackexchange

问:
TS6053 Error & npx tsc is not transpiling
I wanted to setup a basic TypeScript project via Node. I followed the normal procedure of the following commands:

npm init -y : This is gave me the default package.json file.

```<code>{
    "name": "prac",
    "version": "1.0.0",
    "description": "",
    "main": "index.js",
    "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1"
    },
    "keywords": [],
    "author": "",
    "license": "ISC"
}
</code>```

npm install --save-dev typescript@latest: At that time the version that was installed was 4.8.2.

npm version: The node installation and configuration that have is as follows:

```<code>{
  prac: '1.0.0',
  npm: '8.11.0',
  node: '16.16.0',
  v8: '9.4.146.24-node.21',
  uv: '1.43.0',
  zlib: '1.2.11',
  brotli: '1.0.9',
  ares: '1.18.1',
  modules: '93',
  nghttp2: '1.47.0',
  napi: '8',
  llhttp: '6.0.7',
  openssl: '1.1.1q+quic',
  cldr: '40.0',
  icu: '70.1',
  tz: '2021a3',
  unicode: '14.0',
  ngtcp2: '0.1.0-DEV',
  nghttp3: '0.1.0-DEV'
}
</code>```

npm show @types/node@16.* version: Based on my node version I have (16.16.0), at that time the proper version that was suited for me was (@types/node@16.11.56 '16.11.56'). So I went ahead to install that version via npm install --save-dev @types/node@16.11.56.

npx tsc --init: Created the default tsconfig.json file. And then I created a src folder in parallel with the package.json & tsconfig.json.

I created a very rudimentary TypeScript file in src named as hw.ts.

```<code>console.log('Hello World!');
</code>```

I used to transpile the file to hw.js as (being in the folder containing package.json), npx tsc .\src\hw.ts. It used to work fine and generate hw.js for me besides hw.ts. But suddenly, it is giving an error:

```<code>D:\Documents\Work\js\ts\prac> npx tsc .\src\hw.ts

npm WARN config global `--global`, `--local` are deprecated. Use `--location=global` instead.
error TS6053: File '/src/hw.ts' not found.
  The file is in the program because:
    Root file specified for compilation

Found 1 error.
</code>```

I have tried everything I found here here. But it did not work. I also recreated a new project again and repeated the same scenario. The error still persists.

Please help me resolve this. I do not want to install typescript globally. I want know to why this worked earlier and is not working now.

Thank You.

ContentLicense: CC BY-SA 4.0

Body:
I wanted to setup a basic TypeScript project via Node. I followed the normal procedure of the following commands:

npm init -y : This is gave me the default package.json file.

{
    "name": "prac",
    "version": "1.0.0",
    "description": "",
    "main": "index.js",
    "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1"
    },
    "keywords": [],
    "author": "",
    "license": "ISC"
}

npm install --save-dev typescript@latest: At that time the version that was installed was 4.8.2.

npm version: The node installation and configuration that have is as follows:

{
  prac: '1.0.0',
  npm: '8.11.0',
  node: '16.16.0',
  v8: '9.4.146.24-node.21',
  uv: '1.43.0',
  zlib: '1.2.11',
  brotli: '1.0.9',
  ares: '1.18.1',
  modules: '93',
  nghttp2: '1.47.0',
  napi: '8',
  llhttp: '6.0.7',
  openssl: '1.1.1q+quic',
  cldr: '40.0',
  icu: '70.1',
  tz: '2021a3',
  unicode: '14.0',
  ngtcp2: '0.1.0-DEV',
  nghttp3: '0.1.0-DEV'
}

npm show @types/node@16.* version: Based on my node version I have (16.16.0), at that time the proper version that was suited for me was (@types/node@16.11.56 '16.11.56'). So I went ahead to install that version via npm install --save-dev @types/node@16.11.56.

npx tsc --init: Created the default tsconfig.json file. And then I created a src folder in parallel with the package.json & tsconfig.json.

I created a very rudimentary TypeScript file in src named as hw.ts.

console.log('Hello World!');

I used to transpile the file to hw.js as (being in the folder containing package.json), npx tsc .\src\hw.ts. It used to work fine and generate hw.js for me besides hw.ts. But suddenly, it is giving an error:

D:\Documents\Work\js\ts\prac> npx tsc .\src\hw.ts

npm WARN config global `--global`, `--local` are deprecated. Use `--location=global` instead.
error TS6053: File '/src/hw.ts' not found.
  The file is in the program because:
    Root file specified for compilation

Found 1 error.

I have tried everything I found here here. But it did not work. I also recreated a new project again and repeated the same scenario. The error still persists.

Please help me resolve this. I do not want to install typescript globally. I want know to why this worked earlier and is not working now.

Thank You.


问:
Interactive Plots in Python
How to plot interactive plots in python, I am on dataframe which is datetime indexed, I want to plot multiple columns by selecting from the wizard, on the time axis, there should be some function to behave like a date slider as well so that selecting a range in the plot can change the date.
Any suggestion?

I have no idea about the interactive plots, being new to python I can just plot pd or matplotlib plot as basic

Title: Interactive Plots in Python


问:
BootStrap Off Canvas Anchor
I'm using Off Canvas from Bootstrap and have anchor tags inside the off canvas. Whenever I click on the link, it does scroll down at the back, but the moment I close the Off Canvas, it scrolls back up from where it started. I don't understand why this problem is occurring.

This is the code I am using:

```<code><div class="d-flex justify-content-center">
        <div class="p-2">
            <h5>CHOOSE EDUCATIONAL INSTITUTION: </h5>
        </div>
        <div class="p-2">
            <button class="btn btn-secondary" type="button" data-bs-toggle="offcanvas"
                data-bs-target="#offcanvasExample" aria-controls="offcanvasExample">
                CHOOSE
            </button>
        </div>
    </div>

    <div class="offcanvas offcanvas-start" tabindex="-1" id="offcanvasExample" aria-labelledby="offcanvasExampleLabel">
        <div class="offcanvas-header">
            <h5 class="offcanvas-title" id="offcanvasExampleLabe">INSTITUTIONS</h5>
            <button type="button" class="btn-close" data-bs-dismiss="offcanvas" aria-label="Close"></button>
        </div>
        <div class="offcanvas-body">
            <ul class="list-group list-group-flush">
                <a href="#schools"  class="list-group-item list-group-item-success list-group-item-action">SCHOOLS</a>
                <a href="#intermediate"  class="list-group-item  list-group-item-action">IPE COLLEGE</a>
                <a href="#polytech"  class="list-group-item list-group-item-success list-group-item-action">POLYTECHNIC COLLEGE</a>
                <a href="#undergrad"  class="list-group-item list-group-item-action">UNDERGRAD</a>
                <a href="#pg"  class="list-group-item list-group-item-success list-group-item-action">POSTGRAD</a>
                <a href="#phd"  class="list-group-item list-group-item-action">PHD</a>
            </ul>
        </div>
    </div>
</code>```

I tried adding

```<code>    data-bs-dismiss="offcanvas"
</code>```

But doing this doesn't close the off canvas in any way (made it worse)

Title: BootStrap Off Canvas Anchor

Body:
I'm using Off Canvas from Bootstrap and have anchor tags inside the off canvas. Whenever I click on the link, it does scroll down at the back, but the moment I close the Off Canvas, it scrolls back up from where it started. I don't understand why this problem is occurring.

This is the code I am using:

CHOOSE EDUCATIONAL INSTITUTION:

            <button class="btn btn-secondary" type="button" data-bs-toggle="offcanvas"
                data-bs-target="#offcanvasExample" aria-controls="offcanvasExample">
                CHOOSE
            </button>

INSTITUTIONS

            <button type="button" class="btn-close" data-bs-dismiss="offcanvas" aria-label="Close"></button>

                SCHOOLS
                IPE COLLEGE
                POLYTECHNIC COLLEGE
                UNDERGRAD
                POSTGRAD
                PHD

I tried adding

    data-bs-dismiss="offcanvas"

But doing this doesn't close the off canvas in any way (made it worse)


问:
Pose robot visualization as direction from csv
Sorry for all mistakes, English is not my native language. I have a CSV file with pose data in X,Y,Z coordinates. I managed to visualize it as dots using matplotlib.pyplot and pandas, but what I want is direction, so that dots was linked and first and last dots was of a different color. This is code I use for pose visualization:

```<code>import pandas as pd
import csv
import matplotlib.pyplot as plt
import numpy as np

str_filename = 'sensor_data.csv'

fh = open(str_filename, encoding="utf-8")
csv_reader = csv.reader(fh, delimiter = ";")

csv_header = next(csv_reader)

fh.close()

df_sig = pd.read_csv(str_filename, delimiter=";", header=None, skiprows=1, names=csv_header)

x = np.array(df_sig["Pose X"])
y = np.array(df_sig["Pose Y"])

plt.plot(x, y, 'd', color = 'black')
plt.title('Pose')
plt.savefig('Pose Visualization.pdf')
</code>```

Appreciate any help.

Body:
Sorry for all mistakes, English is not my native language. I have a CSV file with pose data in X,Y,Z coordinates. I managed to visualize it as dots using matplotlib.pyplot and pandas, but what I want is direction, so that dots was linked and first and last dots was of a different color. This is code I use for pose visualization:

import pandas as pd
import csv
import matplotlib.pyplot as plt
import numpy as np

str_filename = 'sensor_data.csv'

fh = open(str_filename, encoding="utf-8")
csv_reader = csv.reader(fh, delimiter = ";")

csv_header = next(csv_reader)

fh.close()

df_sig = pd.read_csv(str_filename, delimiter=";", header=None, skiprows=1, names=csv_header)

x = np.array(df_sig["Pose X"])
y = np.array(df_sig["Pose Y"])

plt.plot(x, y, 'd', color = 'black')
plt.title('Pose')
plt.savefig('Pose Visualization.pdf')

Appreciate any help.


问:
How preview json as string genereted by JsonContent
I recieve error from outer api, I think there is something wrong with my generated json content because when I'm sending the same data from postman, I get correct response.

Is there a way to preview what json will be generated from JsonContent?
I have a http client method:

```<code>public async Task<ResponseDto> UploadAsync(RequestDto model, CancellationToken cancellationToken)
{
    var requestUri = HttpHelper.BuildUri(uri.UPLOAD);
    JsonContent content = JsonContent.Create(model);  //<= how read that JsonContent
    /* there is not problems
    var response = await _client.PostAsync(requestUri, content, cancellationToken);

    string responseContent = await response.Content.ReadAsStringAsync(cancellationToken);

    return JsonSerializer.Deserialize<ResponseDto>(responseContent)
        ?? throw new HttpRequestException(responseContent);*/
}
</code>```

Body:
I recieve error from outer api, I think there is something wrong with my generated json content because when I'm sending the same data from postman, I get correct response.

Is there a way to preview what json will be generated from JsonContent?
I have a http client method:

public async Task<ResponseDto> UploadAsync(RequestDto model, CancellationToken cancellationToken)
{
    var requestUri = HttpHelper.BuildUri(uri.UPLOAD);
    JsonContent content = JsonContent.Create(model);  //<= how read that JsonContent
    /* there is not problems
    var response = await _client.PostAsync(requestUri, content, cancellationToken);

    string responseContent = await response.Content.ReadAsStringAsync(cancellationToken);

    return JsonSerializer.Deserialize<ResponseDto>(responseContent)
        ?? throw new HttpRequestException(responseContent);*/
}


问:
Import large xml files ( may be 50 MB ) using AWS linux cron every 1 hour but system crashed
I need to import xml data which might be 50 MB or more, but during import process system stopped working and crashed.

Below is Codeigniter controller method. And I want to import xml data into shopify product smoothly whithout crashing the system, like as we do with ajax pagination.

```<code>
</code>```

public function cron_import_products() {

```<code>    $shop = $this->config->item('shopify_shop');
    $token = $this->config->item('shopify_private_access_token');

    $client = new Rest($shop, $token);

    $string = file_get_contents(FCPATH . 'ItemInformationDump.XML');
    $xml_object = simplexml_load_string($string, 'SimpleXMLElement', LIBXML_NOCDATA | LIBXML_NOBLANKS);
    $xml_array = $this->object2array($xml_object);

    $products_count = count($xml_array['Item']);

    $iitem = 0;
    $count = array();
    $already = array();

    foreach ($xml_array['Item'] as $pr) {
        $item_identity_field = $pr['@attributes']['Item_Identity_Field'];
        $item_sku = $pr['@attributes']['Stripped_Item_Number'];
        $item_qty = $pr['@attributes']['Available_Quantity'];
        $item_price = $pr['@attributes']['List_Price'];
        $item_handle = strtolower($pr['Item_Number']);
        $item_handle = gen_create_slug($item_handle);
        $item_number = $pr['Item_Number'];
        //$item_full_description = $pr['Item_Full_Description'];
        $item_title = $pr['Item_Number'];

        $desc_html = '';
        if(isset($pr['Item_Description_Field_1'])) {
            $desc_html .= '<p>'.$pr['Item_Description_Field_1'].'</p>';
        }
        if(isset($pr['Item_Description_Field_2'])) {
            $desc_html .= '<p>'.$pr['Item_Description_Field_2'].'</p>';
        }
        if(isset($pr['Item_Description_Field_3'])) {
            $desc_html .= '<p>'.$pr['Item_Description_Field_3'].'</p>';
        }
        if(isset($pr['Item_Description_Field_4'])) {
            $desc_html .= '<p>'.$pr['Item_Description_Field_4'].'</p>';
        }
        if(isset($pr['Mandatory_Notes'])) {
            $desc_html .= '<p>'.$pr['Mandatory_Notes'].'</p>';
        }

        $item_full_description = $desc_html;

        $item_collection = $pr['Item_Description_Field_1'];
        $item_collection_handle = strtolower($item_collection);
        $item_collection_handle = gen_create_slug($item_collection_handle);

        $cat_code = $pr['@attributes']['Product_Category_Code'];

        if($cat_code == 'XXX') {
            continue;
        }

        if( $iitem%50==0) {// run ten times then sleep for 100 second
            sleep(60);
        }

        $response_collections = $client->get(
            "custom_collections",
            [],
            ['handle' => $item_collection_handle]
        );

        $collections_status_code = $response_collections->getStatusCode();

        if($collections_status_code != 200) :
            return false;
        endif;

        $fetch_collections = $response_collections->getDecodedBody();

        if(!empty($fetch_collections['custom_collections'])) {
            $collection_id = $fetch_collections['custom_collections'][0]['id'];
        } else {
            $collection_data['title'] = $item_collection;
            $collection_data['handle'] = $item_collection_handle;

            $collection_arr = array('custom_collection' => $collection_data);

            $response_coll = $client->post(
                "custom_collections",
                json_encode($collection_arr),
                ['Content-Type: application/json']
            );

            $response_coll_data = $response_coll->getDecodedBody();

            $collection_id = $response_coll_data['custom_collection']['id'];
        }

        $response = $client->get(
            "products",
            [],
            ['handle' => $item_handle]
        );

        $status_code = $response->getStatusCode();
        $fetch_products = $response->getDecodedBody();

        if($status_code == 200) {

            if(!empty($fetch_products['products'])) {
                $product_id = $fetch_products['products'][0]['id'];

                $variants = array(
                    array(
                        'inventory_management' => 'shopify',
                        'sku' => $item_sku,
                        'price' => $item_price
                    )
                );

                $product_data['title'] = $item_title;
                $product_data['variants'] = $variants;
                $product_data['body_html'] = $item_full_description;
                $product_data['price'] = $item_price;

                $product_arr = array('product' => $product_data);

                $response = $client->put(
                    "products/".$product_id,
                    json_encode($product_arr),
                    ['Content-Type: application/json']
                );

                $response_data = $response->getDecodedBody();

                $var_id = $response_data['product']['variants'][0]['id'];

                $inventory_level = $client->get(
                        "inventory_levels",
                        [],
                        ['inventory_item_ids' => $response_data['product']['variants'][0]['inventory_item_id']]
                    );

                $response_inventories = $inventory_level->getDecodedBody();

                foreach($response_inventories['inventory_levels'] as $inventory_level) {
                    $inventory_item_id = $inventory_level['inventory_item_id'];
                    $location_id = $inventory_level['location_id'];

                    $inventory_arr = [
                        'inventory_item_id' => $inventory_item_id,
                        'location_id' => $location_id,
                        'available' => $item_qty
                    ];

                    $update_inventory = $client->post(
                        "inventory_levels/set",
                        json_encode($inventory_arr),
                        ['Content-Type: application/json']
                    );

                }

                $already[] = $response_data;

            } else {
                if(!isset($fetch_products['products'])) {
                    return;
                }
                $variants = array(
                    array(
                        'inventory_management' => 'shopify',
                        'sku' => $item_sku,
                        'price' => $item_price
                    )
                );

                $product_data['title'] = $item_title;
                $product_data['variants'] = $variants;
                $product_data['body_html'] = $item_full_description;
                $product_data['handle'] = $item_handle;

                $product_arr = array('product' => $product_data);

                $response = $client->post(
                    "products",
                    json_encode($product_arr),
                    ['Content-Type: application/json']
                );

                $response_data = $response->getDecodedBody();

                $product_id = $response_data['product']['id'];

                $var_id = $response_data['product']['variants'][0]['id'];

                $collect_data['product_id'] = $product_id;
                $collect_data['collection_id'] = $collection_id;
                $collect_arr = array('collect' => $collect_data);

                $response_collect = $client->post(
                    "collects",
                    json_encode($collect_arr),
                    ['Content-Type: application/json']
                );

                $inventory_level = $client->get(
                    "inventory_levels",
                    [],
                    ['inventory_item_ids' => $response_data['product']['variants'][0]['inventory_item_id']]
                );

                $response_inventories = $inventory_level->getDecodedBody();

                foreach($response_inventories['inventory_levels'] as $inventory_level) {
                    $inventory_item_id = $inventory_level['inventory_item_id'];
                    $location_id = $inventory_level['location_id'];

                    $inventory_arr = [
                        'inventory_item_id' => $inventory_item_id,
                        'location_id' => $location_id,
                        'available' => $item_qty
                    ];

                    $update_inventory = $client->post(
                        "inventory_levels/set",
                        json_encode($inventory_arr),
                        ['Content-Type: application/json']
                    );

                }

                $count[] = $response_data;
            }
        }

        $iitem++;
    }
}
</code>```
```<code>
</code>```
```<code>
</code>```

Body:
I need to import xml data which might be 50 MB or more, but during import process system stopped working and crashed.

Below is Codeigniter controller method. And I want to import xml data into shopify product smoothly whithout crashing the system, like as we do with ajax pagination.

public function cron_import_products() {

    $shop = $this->config->item('shopify_shop');
    $token = $this->config->item('shopify_private_access_token');

    $client = new Rest($shop, $token);

    $string = file_get_contents(FCPATH . 'ItemInformationDump.XML');
    $xml_object = simplexml_load_string($string, 'SimpleXMLElement', LIBXML_NOCDATA | LIBXML_NOBLANKS);
    $xml_array = $this->object2array($xml_object);

    $products_count = count($xml_array['Item']);

    $iitem = 0;
    $count = array();
    $already = array();

    foreach ($xml_array['Item'] as $pr) {
        $item_identity_field = $pr['@attributes']['Item_Identity_Field'];
        $item_sku = $pr['@attributes']['Stripped_Item_Number'];
        $item_qty = $pr['@attributes']['Available_Quantity'];
        $item_price = $pr['@attributes']['List_Price'];
        $item_handle = strtolower($pr['Item_Number']);
        $item_handle = gen_create_slug($item_handle);
        $item_number = $pr['Item_Number'];
        //$item_full_description = $pr['Item_Full_Description'];
        $item_title = $pr['Item_Number'];

        $desc_html = '';
        if(isset($pr['Item_Description_Field_1'])) {
            $desc_html .= '
'.$pr['Item_Description_Field_1'].'
';
        }
        if(isset($pr['Item_Description_Field_2'])) {
            $desc_html .= '
'.$pr['Item_Description_Field_2'].'
';
        }
        if(isset($pr['Item_Description_Field_3'])) {
            $desc_html .= '
'.$pr['Item_Description_Field_3'].'
';
        }
        if(isset($pr['Item_Description_Field_4'])) {
            $desc_html .= '
'.$pr['Item_Description_Field_4'].'
';
        }
        if(isset($pr['Mandatory_Notes'])) {
            $desc_html .= '
'.$pr['Mandatory_Notes'].'
';
        }

        $item_full_description = $desc_html;

        $item_collection = $pr['Item_Description_Field_1'];
        $item_collection_handle = strtolower($item_collection);
        $item_collection_handle = gen_create_slug($item_collection_handle);

        $cat_code = $pr['@attributes']['Product_Category_Code'];

        if($cat_code == 'XXX') {
            continue;
        }

        if( $iitem%50==0) {// run ten times then sleep for 100 second
            sleep(60);
        }

        $response_collections = $client->get(
            "custom_collections",
            [],
            ['handle' => $item_collection_handle]
        );

        $collections_status_code = $response_collections->getStatusCode();

        if($collections_status_code != 200) :
            return false;
        endif;

        $fetch_collections = $response_collections->getDecodedBody();

        if(!empty($fetch_collections['custom_collections'])) {
            $collection_id = $fetch_collections['custom_collections'][0]['id'];
        } else {
            $collection_data['title'] = $item_collection;
            $collection_data['handle'] = $item_collection_handle;

            $collection_arr = array('custom_collection' => $collection_data);

            $response_coll = $client->post(
                "custom_collections",
                json_encode($collection_arr),
                ['Content-Type: application/json']
            );

            $response_coll_data = $response_coll->getDecodedBody();

            $collection_id = $response_coll_data['custom_collection']['id'];
        }

        $response = $client->get(
            "products",
            [],
            ['handle' => $item_handle]
        );

        $status_code = $response->getStatusCode();
        $fetch_products = $response->getDecodedBody();

        if($status_code == 200) {

            if(!empty($fetch_products['products'])) {
                $product_id = $fetch_products['products'][0]['id'];

                $variants = array(
                    array(
                        'inventory_management' => 'shopify',
                        'sku' => $item_sku,
                        'price' => $item_price
                    )
                );

                $product_data['title'] = $item_title;
                $product_data['variants'] = $variants;
                $product_data['body_html'] = $item_full_description;
                $product_data['price'] = $item_price;

                $product_arr = array('product' => $product_data);

                $response = $client->put(
                    "products/".$product_id,
                    json_encode($product_arr),
                    ['Content-Type: application/json']
                );

                $response_data = $response->getDecodedBody();

                $var_id = $response_data['product']['variants'][0]['id'];

                $inventory_level = $client->get(
                        "inventory_levels",
                        [],
                        ['inventory_item_ids' => $response_data['product']['variants'][0]['inventory_item_id']]
                    );

                $response_inventories = $inventory_level->getDecodedBody();

                foreach($response_inventories['inventory_levels'] as $inventory_level) {
                    $inventory_item_id = $inventory_level['inventory_item_id'];
                    $location_id = $inventory_level['location_id'];

                    $inventory_arr = [
                        'inventory_item_id' => $inventory_item_id,
                        'location_id' => $location_id,
                        'available' => $item_qty
                    ];

                    $update_inventory = $client->post(
                        "inventory_levels/set",
                        json_encode($inventory_arr),
                        ['Content-Type: application/json']
                    );

                }

                $already[] = $response_data;

            } else {
                if(!isset($fetch_products['products'])) {
                    return;
                }
                $variants = array(
                    array(
                        'inventory_management' => 'shopify',
                        'sku' => $item_sku,
                        'price' => $item_price
                    )
                );

                $product_data['title'] = $item_title;
                $product_data['variants'] = $variants;
                $product_data['body_html'] = $item_full_description;
                $product_data['handle'] = $item_handle;

                $product_arr = array('product' => $product_data);

                $response = $client->post(
                    "products",
                    json_encode($product_arr),
                    ['Content-Type: application/json']
                );

                $response_data = $response->getDecodedBody();

                $product_id = $response_data['product']['id'];

                $var_id = $response_data['product']['variants'][0]['id'];

                $collect_data['product_id'] = $product_id;
                $collect_data['collection_id'] = $collection_id;
                $collect_arr = array('collect' => $collect_data);

                $response_collect = $client->post(
                    "collects",
                    json_encode($collect_arr),
                    ['Content-Type: application/json']
                );

                $inventory_level = $client->get(
                    "inventory_levels",
                    [],
                    ['inventory_item_ids' => $response_data['product']['variants'][0]['inventory_item_id']]
                );

                $response_inventories = $inventory_level->getDecodedBody();

                foreach($response_inventories['inventory_levels'] as $inventory_level) {
                    $inventory_item_id = $inventory_level['inventory_item_id'];
                    $location_id = $inventory_level['location_id'];

                    $inventory_arr = [
                        'inventory_item_id' => $inventory_item_id,
                        'location_id' => $location_id,
                        'available' => $item_qty
                    ];

                    $update_inventory = $client->post(
                        "inventory_levels/set",
                        json_encode($inventory_arr),
                        ['Content-Type: application/json']
                    );

                }

                $count[] = $response_data;
            }
        }

        $iitem++;
    }
}


问:
Cypher - find all paths through nodes with highest score
I have a graph with all nodes having a property called score. I want to find all paths that start with a particular node and traverse all nodes having score greater than a threshold.

I want a cypher query that can be run in Redisgraph but I can only find queries that would return all paths irrespective of score and then filter paths by comparing each pair of nodes. I imagine that wouldn't scale very well. Please help!


问:
Issue during running in cmdprmpt
conan install . --build=missing --update -o cura:devtools=True -g VirtualPythonEnv

Getting error during I run these cmd lines

ERROR: compiler not defined for compiler.cppstd
Please define compiler value first too

Even I changed the settings in profile by adding few cmpl details but still facing issues

Title: Issue during running in cmdprmpt


问:
Transform a array data into a nested objects
I have this issue when using echarts tree, need to solve by using recursive somehow

Can someone help me. Thank you
I have tried with some codes as blow and still not working

Here is my sample data

```<code>sampleData: any[] = [
    {
      input: '093098448-0000',
      output: '4971432_01',
      children: [
        {
          name: '4971432_01',
        },
      ],
      inputData: {
        recId: '295ad5b2-4924-4ca4-899d-76fbfbba4f87',
        userId: 'FrontendTestUser',
        containerId: null,
        handlingUnitId: null,
        documentNo: null,
        materialNo: '093098448-0000',
        orderNo: '4971432',
        workplaceId: '84960950',
        workplaceDescription: null,
        operationNo: '0010',
        operationShortText: 'Kivágás, formázás 60 HUB; SÁRGA',
        inputDate: '2022-02-04T11:55:11.193',
        quantityOK: 5321,
        quantityNok: 0,
        processNumberJoined: null,
        warningText: null,
        coil: null,
        containerRecId: null,
        workplaceRecId: '16111747-ef85-4402-96e5-444dffc209dd',
        lastModified: '0001-01-01T00:00:00',
      },
      outputData: {
        workplaceOutputRecId: '7a57cc35-0020-4130-81bc-0078b98deb9b',
        workplaceId: null,
        workplaceName: null,
        workcenter: '84960950',
        operationNo: '0010',
        operationShortText: 'Kivágás, formázás 60 HUB; SÁRGA',
        additionalInfo: null,
        containerId: '4971432_01',
        handlingUnitId: null,
        orderNo: null,
        orderRecId: '00000000-0000-0000-0000-000000000000',
        materialNo: null,
        documentNo: null,
        index: null,
        outputDate: '2022-02-04T12:41:32.007',
        userId: 'FISCHMTA',
        quantityOK: 11,
        quantityNok: 1,
        isFinalFeedback: true,
        processNumberJoined: null,
        skipped: false,
        comment: null,
        containerRecId: 'fabd939e-0110-44c0-9d62-06f2b1b85044',
        workplaceRecId: '16111747-ef85-4402-96e5-444dffc209dd',
        lastModified: '0001-01-01T00:00:00',
      },
      nested: false,
    },
    {
      input: '093098448-0000',
      output: '4971432_05',
      children: [
        {
          name: '4971432_05',
        },
      ],
      inputData: {
        recId: '295ad5b2-4924-4ca4-899d-76fbfbba4f87',
        userId: 'FrontendTestUser',
        containerId: null,
        handlingUnitId: null,
        documentNo: null,
        materialNo: '093098448-0000',
        orderNo: '4971432',
        workplaceId: '84960950',
        workplaceDescription: null,
        operationNo: '0010',
        operationShortText: 'Kivágás, formázás 60 HUB; SÁRGA',
        inputDate: '2022-02-04T11:55:11.193',
        quantityOK: 5321,
        quantityNok: 0,
        processNumberJoined: null,
        warningText: null,
        coil: null,
        containerRecId: null,
        workplaceRecId: '16111747-ef85-4402-96e5-444dffc209dd',
        lastModified: '0001-01-01T00:00:00',
      },
      outputData: {
        workplaceOutputRecId: 'd3f6bce2-54a2-4adf-bf19-68c178b6492a',
        workplaceId: null,
        workplaceName: null,
        workcenter: '84960950',
        operationNo: '0010',
        operationShortText: '0010',
        additionalInfo: null,
        containerId: '4971432_05',
        handlingUnitId: null,
        orderNo: null,
        orderRecId: '00000000-0000-0000-0000-000000000000',
        materialNo: null,
        documentNo: null,
        index: null,
        outputDate: '2022-02-21T16:22:16.507',
        userId: 'ernstfri',
        quantityOK: 25,
        quantityNok: 0,
        isFinalFeedback: true,
        processNumberJoined: '0010',
        skipped: false,
        comment: null,
        containerRecId: '1234069d-7a04-430c-b425-105bb6254320',
        workplaceRecId: '16111747-ef85-4402-96e5-444dffc209dd',
        lastModified: '0001-01-01T00:00:00',
      },
      nested: false,
    }
]

</code>```

The output data looks like
data: { name: string; children: any[] } = {
name: '093098448-0000',
children: [
{
name: '4971432_01',
},
{
name: '4971432_05',
children: [
{
name: '4971432_88',
},
],
},
],
};

I have run this function

```<code>findNode(ele, obj) {
    console.log('findNode', ele);
    if (ele.name === obj.input) {
      let child = { name: obj.input, children: obj.children };
      ele.children.push(child);
      return true;
    } else {
      const c = ele.children.length;
      if (c > 0) {
        for (let i = 0; c > i; i++) {
          const found = this.findNode(ele.children[i], obj);
          // console.log('found', found);
          if (found) break;
        }
      }
    }
  }
</code>```

Body:
I have this issue when using echarts tree, need to solve by using recursive somehow

Can someone help me. Thank you
I have tried with some codes as blow and still not working

Here is my sample data

sampleData: any[] = [
    {
      input: '093098448-0000',
      output: '4971432_01',
      children: [
        {
          name: '4971432_01',
        },
      ],
      inputData: {
        recId: '295ad5b2-4924-4ca4-899d-76fbfbba4f87',
        userId: 'FrontendTestUser',
        containerId: null,
        handlingUnitId: null,
        documentNo: null,
        materialNo: '093098448-0000',
        orderNo: '4971432',
        workplaceId: '84960950',
        workplaceDescription: null,
        operationNo: '0010',
        operationShortText: 'Kivágás, formázás 60 HUB; SÁRGA',
        inputDate: '2022-02-04T11:55:11.193',
        quantityOK: 5321,
        quantityNok: 0,
        processNumberJoined: null,
        warningText: null,
        coil: null,
        containerRecId: null,
        workplaceRecId: '16111747-ef85-4402-96e5-444dffc209dd',
        lastModified: '0001-01-01T00:00:00',
      },
      outputData: {
        workplaceOutputRecId: '7a57cc35-0020-4130-81bc-0078b98deb9b',
        workplaceId: null,
        workplaceName: null,
        workcenter: '84960950',
        operationNo: '0010',
        operationShortText: 'Kivágás, formázás 60 HUB; SÁRGA',
        additionalInfo: null,
        containerId: '4971432_01',
        handlingUnitId: null,
        orderNo: null,
        orderRecId: '00000000-0000-0000-0000-000000000000',
        materialNo: null,
        documentNo: null,
        index: null,
        outputDate: '2022-02-04T12:41:32.007',
        userId: 'FISCHMTA',
        quantityOK: 11,
        quantityNok: 1,
        isFinalFeedback: true,
        processNumberJoined: null,
        skipped: false,
        comment: null,
        containerRecId: 'fabd939e-0110-44c0-9d62-06f2b1b85044',
        workplaceRecId: '16111747-ef85-4402-96e5-444dffc209dd',
        lastModified: '0001-01-01T00:00:00',
      },
      nested: false,
    },
    {
      input: '093098448-0000',
      output: '4971432_05',
      children: [
        {
          name: '4971432_05',
        },
      ],
      inputData: {
        recId: '295ad5b2-4924-4ca4-899d-76fbfbba4f87',
        userId: 'FrontendTestUser',
        containerId: null,
        handlingUnitId: null,
        documentNo: null,
        materialNo: '093098448-0000',
        orderNo: '4971432',
        workplaceId: '84960950',
        workplaceDescription: null,
        operationNo: '0010',
        operationShortText: 'Kivágás, formázás 60 HUB; SÁRGA',
        inputDate: '2022-02-04T11:55:11.193',
        quantityOK: 5321,
        quantityNok: 0,
        processNumberJoined: null,
        warningText: null,
        coil: null,
        containerRecId: null,
        workplaceRecId: '16111747-ef85-4402-96e5-444dffc209dd',
        lastModified: '0001-01-01T00:00:00',
      },
      outputData: {
        workplaceOutputRecId: 'd3f6bce2-54a2-4adf-bf19-68c178b6492a',
        workplaceId: null,
        workplaceName: null,
        workcenter: '84960950',
        operationNo: '0010',
        operationShortText: '0010',
        additionalInfo: null,
        containerId: '4971432_05',
        handlingUnitId: null,
        orderNo: null,
        orderRecId: '00000000-0000-0000-0000-000000000000',
        materialNo: null,
        documentNo: null,
        index: null,
        outputDate: '2022-02-21T16:22:16.507',
        userId: 'ernstfri',
        quantityOK: 25,
        quantityNok: 0,
        isFinalFeedback: true,
        processNumberJoined: '0010',
        skipped: false,
        comment: null,
        containerRecId: '1234069d-7a04-430c-b425-105bb6254320',
        workplaceRecId: '16111747-ef85-4402-96e5-444dffc209dd',
        lastModified: '0001-01-01T00:00:00',
      },
      nested: false,
    }
]

The output data looks like
data: { name: string; children: any[] } = {
name: '093098448-0000',
children: [
{
name: '4971432_01',
},
{
name: '4971432_05',
children: [
{
name: '4971432_88',
},
],
},
],
};

I have run this function

findNode(ele, obj) {
    console.log('findNode', ele);
    if (ele.name === obj.input) {
      let child = { name: obj.input, children: obj.children };
      ele.children.push(child);
      return true;
    } else {
      const c = ele.children.length;
      if (c > 0) {
        for (let i = 0; c > i; i++) {
          const found = this.findNode(ele.children[i], obj);
          // console.log('found', found);
          if (found) break;
        }
      }
    }
  }


问:
It is taking time to resize fragment
It is taking time to resize fragment by using getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE); how to resize single fragment

I have tried getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
in menifest android:windowSoftInputMode="adjustResize"

Title: It is taking time to resize fragment


问:
Getting this error "Unexpected empty object pattern" while using react , useStateValue
I am following the WhatsApp clone on YouTube, I did exactly what they were doing but I don't know why I'm getting this error. I was

I read a lot of blogs, but I couldn't resolve it.

In app, it gives this error and couldn't dismiss.
./src/App.js Line 10: 'dispatch' is assigned a value but never used no-unused-vars

In login, it gives this error.
./src/Login.js Line 9:  Unexpected empty object pattern  no-empty-pattern

```
</div>
</div>
</p>
```import React from "react";
import "./Login.css";
import { Button } from "@mui/material";
import { auth, provider } from "./firebase";
import { useStateValue } from "./StateProvider";
import { actionTypes } from "./reducer";

function Login() {
  const [value, dispatch] = useStateValue({});
  // const [value, dispatch] = useStateValue({})
  // const [{ type, user }, dispatch] = useStateValue();

  const signIn = () => {
    auth
      .signInWithPopup(provider)
      .then((result) => {
        dispatch({
          type: actionTypes.SET_USER,
          user: result.user,
        });
      })
      .catch((error) => alert(error.message));
  };

  return (

Sign in to WhatsApp

        <Button onClick={signIn}>Sign In with Google</Button>

  );
}

export default Login;
```

```
```
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>import React from "react";
import "./App.css";
import Sidebar from "./Sidebar";
import Chat from "./Chat";
import Login from "./Login";
import { BrowserRouter as Router, Routes, Route } from "react-router-dom";
import { useStateValue } from "./StateProvider";

function App() {
  const [{ user }, dispatch] = useStateValue();

  return (
    <div className="app">
      {!user ? (
        <Login />
      ) : (
        <div className="app__body">
          <Router>
            <Sidebar />
            <Routes>
              <Route path="/rooms/:roomId" element={<Chat />} />
              <Route path="/" element={<Chat />} />
            </Routes>
          </Router>
        </div>
      )}
    </div>
  );
}

export default App;</code>```

```<code>
</code>```

import React, { createContext, useContext, useReducer } from "react";

export const StateContext = createContext();

export const StateProvider = ({ reducer, initialState, children }) => (
  <StateContext.Provider value={useReducer(reducer, initialState)}>
    {children}
  </StateContext.Provider>
);

export const useStateValue = () => useContext(StateContext);```
</div>
</div>
</p>
```
```
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>export const initialState = {
  user: null,
};

export const actionTypes = {
  SET_USER: "SET_USER",
};

const reducer = (state, action) => {
  console.log(action);
  switch (action.type) {
    case actionTypes.SET_USER:
      return {
        ...state,
        user: action.user,
      };

    default:
      return state;
  }
};

export default reducer;</code>```

```<code></code>```

Body:
I am following the WhatsApp clone on YouTube, I did exactly what they were doing but I don't know why I'm getting this error. I was

I read a lot of blogs, but I couldn't resolve it.

In app, it gives this error and couldn't dismiss.
./src/App.js Line 10: 'dispatch' is assigned a value but never used no-unused-vars

In login, it gives this error.
./src/Login.js Line 9:  Unexpected empty object pattern  no-empty-pattern

import React from "react";
import "./Login.css";
import { Button } from "@mui/material";
import { auth, provider } from "./firebase";
import { useStateValue } from "./StateProvider";
import { actionTypes } from "./reducer";

function Login() {
  const [value, dispatch] = useStateValue({});
  // const [value, dispatch] = useStateValue({})
  // const [{ type, user }, dispatch] = useStateValue();

  const signIn = () => {
    auth
      .signInWithPopup(provider)
      .then((result) => {
        dispatch({
          type: actionTypes.SET_USER,
          user: result.user,
        });
      })
      .catch((error) => alert(error.message));
  };

  return (

Sign in to WhatsApp

        <Button onClick={signIn}>Sign In with Google</Button>

  );
}

export default Login;

import React from "react";
import "./App.css";
import Sidebar from "./Sidebar";
import Chat from "./Chat";
import Login from "./Login";
import { BrowserRouter as Router, Routes, Route } from "react-router-dom";
import { useStateValue } from "./StateProvider";

function App() {
  const [{ user }, dispatch] = useStateValue();

  return (

      {!user ? (
        <Login />
      ) : (

          <Router>
            <Sidebar />
            <Routes>
              <Route path="/rooms/:roomId" element={<Chat />} />
              <Route path="/" element={<Chat />} />
            </Routes>
          </Router>

      )}

  );
}

export default App;

import React, { createContext, useContext, useReducer } from "react";

export const StateContext = createContext();

export const StateProvider = ({ reducer, initialState, children }) => (
  <StateContext.Provider value={useReducer(reducer, initialState)}>
    {children}
  </StateContext.Provider>
);

export const useStateValue = () => useContext(StateContext);

export const initialState = {
  user: null,
};

export const actionTypes = {
  SET_USER: "SET_USER",
};

const reducer = (state, action) => {
  console.log(action);
  switch (action.type) {
    case actionTypes.SET_USER:
      return {
        ...state,
        user: action.user,
      };

    default:
      return state;
  }
};

export default reducer;


问:
Tried to send a platform message to Flutter, but FlutterJNI was detached from native C++. Could not send. Channel:
I am trying to track the location of the device in terminated state also. Tried using flutter pluggins and also native code. In both the cases I get
"Tried to send a platform message to Flutter, but FlutterJNI was detached from native C++. Could not send....."

Can anyone please give me pointers.


问:
EsLint issue of undefined 'Version' in React js
node:      14.17.0
React js:  17.0.2

I commit my code I get the error :

✖ npm run lint:eslint:fix found some errors. Please fix them and try committing again.

```<code>TypeError: Cannot read property 'version' of undefined
</code>```

Dev Dependicies:

```<code>"devDependencies": {
    "@babel/cli": "7.4.3",
    "@babel/core": "^7.4.3",
    "@babel/eslint-parser": "^7.16.5",
    "@babel/eslint-plugin": "^7.16.5",
    "@babel/node": "^7.17.10",
    "@babel/plugin-proposal-class-properties": "7.4.0",
    "@babel/plugin-proposal-nullish-coalescing-operator": "^7.16.7",
    "@babel/plugin-proposal-optional-chaining": "^7.14.5",
    "@babel/plugin-syntax-dynamic-import": "7.2.0",
    "@babel/plugin-transform-modules-commonjs": "7.4.3",
    "@babel/plugin-transform-react-constant-elements": "7.2.0",
    "@babel/plugin-transform-react-inline-elements": "7.2.0",
    "@babel/preset-env": "^7.17.12",
    "@babel/preset-react": "^7.17.12",
    "@babel/register": "7.4.0",
    "@squoosh/lib": "^0.4.0",
    "@types/hoist-non-react-statics": "^3.3.1",
    "add-asset-html-webpack-plugin": "3.1.1",
    "babel-core": "7.0.0-bridge.0",
    "babel-eslint": "10.0.1",
    "babel-loader": "^8.0.5",
    "babel-plugin-dynamic-import-node": "2.2.0",
    "babel-plugin-lodash": "3.3.4",
    "babel-plugin-react-intl": "3.0.1",
    "babel-plugin-react-transform": "3.0.0",
    "babel-plugin-styled-components": "^1.10.0",
    "babel-plugin-transform-react-remove-prop-types": "0.4.24",
    "chai": "^4.2.0",
    "circular-dependency-plugin": "5.0.2",
    "compare-versions": "3.4.0",
    "compression-webpack-plugin": "2.0.0",
    "coveralls": "3.0.2",
    "css-loader": "3.4.2",
    "enzyme": "3.7.0",
    "enzyme-adapter-react-16": "1.6.0",
    "enzyme-to-json": "3.3.4",
    "eslint": "5.16.0",
    "eslint-config-airbnb": "17.1.0",
    "eslint-config-airbnb-base": "13.1.0",
    "eslint-config-prettier": "4.1.0",
    "eslint-import-resolver-webpack": "0.11.1",
    "eslint-loader": "^2.1.1",
    "eslint-plugin-flowtype": "^3.2.0",
    "eslint-plugin-import": "2.17.0",
    "eslint-plugin-jsx-a11y": "6.2.1",
    "eslint-plugin-prettier": "3.0.1",
    "eslint-plugin-react": "7.12.4",
    "eslint-plugin-redux-saga": "1.0.0",
    "eventsource-polyfill": "0.9.6",
    "exports-loader": "0.7.0",
    "file-loader": "3.0.1",
    "happypack": "^5.0.1",
    "html-loader": "0.5.5",
    "html-webpack-plugin": "3.2.0",
    "image-webpack-loader": "^8.0.1",
    "imports-loader": "0.8.0",
    "lint-staged": "8.1.5",
    "ngrok": "^4.2.2",
    "node-plop": "0.18.0",
    "node-sass": "^4.14.1",
    "null-loader": "0.1.1",
    "offline-plugin": "5.0.6",
    "optimize-css-assets-webpack-plugin": "^5.0.0",
    "plop": "2.3.0",
    "postcss-loader": "3.0.0",
    "pre-commit": "1.2.2",
    "prettier": "^1.17.0",
    "prismjs": "^1.11.0",
    "raw-loader": "2.0.0",
    "react-app-polyfill": "0.2.2",
    "react-router-sitemap-generator": "^0.0.8",
    "react-test-renderer": "16.8.6",
    "rimraf": "2.6.3",
    "sass-loader": "^7.1.0",
    "sass-material-colors": "0.0.5",
    "shelljs": "^0.8.4",
    "style-loader": "0.23.1",
    "stylelint": "10.0.1",
    "stylelint-config-recommended": "2.2.0",
    "stylelint-config-styled-components": "0.1.1",
    "stylelint-processor-styled-components": "1.6.0",
    "svg-url-loader": "2.3.2",
    "terser-webpack-plugin": "1.2.3",
    "url-loader": "1.1.2",
    "webpack": "4.46.0",
    "webpack-cli": "3.3.12",
    "webpack-dev-middleware": "3.7.3",
    "webpack-hot-middleware": "2.25.1",
    "webpack-pwa-manifest": "4.3.0",
    "whatwg-fetch": "3.0.0"
  }
</code>```

why I am getting this error. what I did wrong?

Body:
node:      14.17.0
React js:  17.0.2

I commit my code I get the error :

✖ npm run lint:eslint:fix found some errors. Please fix them and try committing again.

TypeError: Cannot read property 'version' of undefined

Dev Dependicies:

"devDependencies": {
    "@babel/cli": "7.4.3",
    "@babel/core": "^7.4.3",
    "@babel/eslint-parser": "^7.16.5",
    "@babel/eslint-plugin": "^7.16.5",
    "@babel/node": "^7.17.10",
    "@babel/plugin-proposal-class-properties": "7.4.0",
    "@babel/plugin-proposal-nullish-coalescing-operator": "^7.16.7",
    "@babel/plugin-proposal-optional-chaining": "^7.14.5",
    "@babel/plugin-syntax-dynamic-import": "7.2.0",
    "@babel/plugin-transform-modules-commonjs": "7.4.3",
    "@babel/plugin-transform-react-constant-elements": "7.2.0",
    "@babel/plugin-transform-react-inline-elements": "7.2.0",
    "@babel/preset-env": "^7.17.12",
    "@babel/preset-react": "^7.17.12",
    "@babel/register": "7.4.0",
    "@squoosh/lib": "^0.4.0",
    "@types/hoist-non-react-statics": "^3.3.1",
    "add-asset-html-webpack-plugin": "3.1.1",
    "babel-core": "7.0.0-bridge.0",
    "babel-eslint": "10.0.1",
    "babel-loader": "^8.0.5",
    "babel-plugin-dynamic-import-node": "2.2.0",
    "babel-plugin-lodash": "3.3.4",
    "babel-plugin-react-intl": "3.0.1",
    "babel-plugin-react-transform": "3.0.0",
    "babel-plugin-styled-components": "^1.10.0",
    "babel-plugin-transform-react-remove-prop-types": "0.4.24",
    "chai": "^4.2.0",
    "circular-dependency-plugin": "5.0.2",
    "compare-versions": "3.4.0",
    "compression-webpack-plugin": "2.0.0",
    "coveralls": "3.0.2",
    "css-loader": "3.4.2",
    "enzyme": "3.7.0",
    "enzyme-adapter-react-16": "1.6.0",
    "enzyme-to-json": "3.3.4",
    "eslint": "5.16.0",
    "eslint-config-airbnb": "17.1.0",
    "eslint-config-airbnb-base": "13.1.0",
    "eslint-config-prettier": "4.1.0",
    "eslint-import-resolver-webpack": "0.11.1",
    "eslint-loader": "^2.1.1",
    "eslint-plugin-flowtype": "^3.2.0",
    "eslint-plugin-import": "2.17.0",
    "eslint-plugin-jsx-a11y": "6.2.1",
    "eslint-plugin-prettier": "3.0.1",
    "eslint-plugin-react": "7.12.4",
    "eslint-plugin-redux-saga": "1.0.0",
    "eventsource-polyfill": "0.9.6",
    "exports-loader": "0.7.0",
    "file-loader": "3.0.1",
    "happypack": "^5.0.1",
    "html-loader": "0.5.5",
    "html-webpack-plugin": "3.2.0",
    "image-webpack-loader": "^8.0.1",
    "imports-loader": "0.8.0",
    "lint-staged": "8.1.5",
    "ngrok": "^4.2.2",
    "node-plop": "0.18.0",
    "node-sass": "^4.14.1",
    "null-loader": "0.1.1",
    "offline-plugin": "5.0.6",
    "optimize-css-assets-webpack-plugin": "^5.0.0",
    "plop": "2.3.0",
    "postcss-loader": "3.0.0",
    "pre-commit": "1.2.2",
    "prettier": "^1.17.0",
    "prismjs": "^1.11.0",
    "raw-loader": "2.0.0",
    "react-app-polyfill": "0.2.2",
    "react-router-sitemap-generator": "^0.0.8",
    "react-test-renderer": "16.8.6",
    "rimraf": "2.6.3",
    "sass-loader": "^7.1.0",
    "sass-material-colors": "0.0.5",
    "shelljs": "^0.8.4",
    "style-loader": "0.23.1",
    "stylelint": "10.0.1",
    "stylelint-config-recommended": "2.2.0",
    "stylelint-config-styled-components": "0.1.1",
    "stylelint-processor-styled-components": "1.6.0",
    "svg-url-loader": "2.3.2",
    "terser-webpack-plugin": "1.2.3",
    "url-loader": "1.1.2",
    "webpack": "4.46.0",
    "webpack-cli": "3.3.12",
    "webpack-dev-middleware": "3.7.3",
    "webpack-hot-middleware": "2.25.1",
    "webpack-pwa-manifest": "4.3.0",
    "whatwg-fetch": "3.0.0"
  }

why I am getting this error. what I did wrong?


问:
Multiprocessing with GUI, python
Right now I am working on a GUI application which will essentially run 4 processes concurrently/ in parallel.

I have been unable to achieve multiprocessing with the tkinter application as it always ended in "can't pickle _tkinter.tkapp objects" and "EOFError: Ran out of input".

Essentially it is meant to run 4 process while updating its GUI. as of right now i am testing it with 2 process just to ensure that it is working.

Code Below:

```<code>import tkinter
import multiprocessing as mp
from tkinter import filedialog
from tkinter.ttk import Progressbar
import tkinter.messagebox
import customtkinter
import matplotlib
matplotlib.use("TkAgg")
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
from CV2_Frame_Extraction import *
from Color_Extractor_CT import *
from graph import *

customtkinter.set_appearance_mode("System")  # Modes: "System" (standard), "Dark", "Light"
customtkinter.set_default_color_theme("blue")  # Themes: "blue" (standard), "green", "dark-blue"

class App(customtkinter.CTk):
    btn_list = []
    def __init__(self):
        super().__init__()

        #Window Configuration
        self.title("Plasma Analysis")
        self.geometry("1100x580")

        #Layout Configuration
        #if needed later
        self.grid_rowconfigure((0, 1, 2), weight=1)

        #Side Bar
        self.sb_frame = customtkinter.CTkFrame(self,width=140, corner_radius=0)
        self.sb_frame.grid(row=0,column=0,rowspan=4,sticky="nsew")
        self.sb_frame.grid_rowconfigure(4,weight=1)

        self.sb_new = customtkinter.CTkButton(self.sb_frame, text="Add Video",command=self.openfile,corner_radius=2)
        self.sb_new.grid(row=0,column=0,padx=20,pady=20)

        self.btn_frame = customtkinter.CTkFrame(self.sb_frame,width=140,height=400,corner_radius=0,fg_color="transparent",border_width=5)
        self.btn_frame.grid(row=1,column=0,rowspan=3)

        self.bf_label = customtkinter.CTkLabel(self.btn_frame,text="Analysis", font=customtkinter.CTkFont(size=20, weight="bold"),fg_color="transparent")
        self.bf_label.grid(row=0,column=0)

        self.appearance_mode_label = customtkinter.CTkLabel(self.sb_frame, text="Appearance Mode:", anchor="w")
        self.appearance_mode_label.grid(row=7, column=0, padx=20, pady=(10, 0))
        self.appearance_mode_optionemenu = customtkinter.CTkOptionMenu(self.sb_frame, values=["Light", "Dark", "System"],
                                                                   command=self.change_appearance_mode_event)
        self.appearance_mode_optionemenu.grid(row=8, column=0, padx=20, pady=(10, 10))
        self.scaling_label = customtkinter.CTkLabel(self.sb_frame, text="UI Scaling:", anchor="w")
        self.scaling_label.grid(row=9, column=0, padx=20, pady=(10, 0))
        self.scaling_optionemenu = customtkinter.CTkOptionMenu(self.sb_frame, values=["80%", "90%", "100%", "110%", "120%"],
                                                           command=self.change_scaling_event)
        self.scaling_optionemenu.grid(row=10, column=0, padx=20, pady=(10, 20))

        #Creating Main Panel
        self.main_frame = customtkinter.CTkFrame(self,width=950,corner_radius=0,fg_color='transparent')
        self.main_frame.grid(row=0,column=1,rowspan=4,columnspan=4,sticky="nsew")

        self.tab_a1 = customtkinter.CTkTabview(self.main_frame,width=400,height=250,segmented_button_selected_color='gray',border_width=5)
        self.tab_a1.grid(row=0,column=0, padx=(30,50),pady=(15,15),sticky="nsew")
        self.tab_a1.grid_propagate(False)
        self.tab_a1.grid_columnconfigure(0, weight=0,uniform=1)
        self.tab_a1.grid_rowconfigure(0, weight=1,uniform=1)
        self.tab_a1.add("Color")

        self.tab_a2 = customtkinter.CTkTabview(self.main_frame,width=400,height=250,segmented_button_selected_color='gray',border_width=5)
        self.tab_a2.grid(row=0,column=1, padx=(0,50),pady=(15,15),sticky="nsew")
        self.tab_a2.add("Luminosity")

        self.tab_a3 = customtkinter.CTkTabview(self.main_frame,width=400,height=250,segmented_button_selected_color='gray',border_width=5)
        self.tab_a3.grid(row=1,column=0, padx=(30,50),pady=(15,15),sticky="nsew")
        self.tab_a3.add("Motion")

        self.tab_a4 = customtkinter.CTkTabview(self.main_frame,width=400,height=250,segmented_button_selected_color='gray',border_width=5)
        self.tab_a4.grid(row=1,column=1, padx=(0,50),pady=(15,15),sticky="nsew")
        self.tab_a4.add("Trend")

    def change_appearance_mode_event(self, new_appearance_mode: str):
        customtkinter.set_appearance_mode(new_appearance_mode)

    def change_scaling_event(self, new_scaling: str):
        new_scaling_float = int(new_scaling.replace("%", "")) / 100
        customtkinter.set_widget_scaling(new_scaling_float)

    def openfile(self):
        decision = filedialog.askopenfilename().split('/')
        name = decision[len(decision)-1].split('.')[0]

        p1 = mp.Process(target=self.loading, args=())
        p2 = mp.Process(target=self.getGraph, args=(decision,))

        self.btn_list.append(customtkinter.CTkButton(self.btn_frame,text=name))
        for x,btn in enumerate(self.btn_list):
            btn.grid(row=x+1,column=0,padx=10,pady=10)

        p1.start()
        #p2.start()

    def loading(self):
        lbl_load = customtkinter.CTkLabel(self.tab_a2.tab('Luminosity'),text="Loading ...",font=customtkinter.CTkFont(size=20, weight="bold"))
        lbl_load1 = customtkinter.CTkLabel(self.tab_a3.tab('Motion'),text="Loading ...",font=customtkinter.CTkFont(size=20, weight="bold"))
        lbl_load2 = customtkinter.CTkLabel(self.tab_a4.tab('Trend'),text="Loading ...",font=customtkinter.CTkFont(size=20, weight="bold"))
        lbl_load.pack(side=tkinter.TOP,fill=tkinter.BOTH,expand=True,anchor='center')
        lbl_load1.pack(side=tkinter.TOP,fill=tkinter.BOTH,expand=True,anchor='center')
        lbl_load2.pack(side=tkinter.TOP,fill=tkinter.BOTH,expand=True,anchor='center')

        self.update()

    def getGraph(self,decision):
        frame_extraction('\\'.join(decision))

        colors = ["Red","Green","Blue"]
        red = []
        green = []
        blue = []

        files = os.listdir('Frames')
        sorted_files = [file.replace('f_','') for file in files]
        sorted_files = sorted(sorted_files, key=lambda x: int(os.path.splitext(x)[0]))

        for frame in sorted_files:
            rgb = color_extraction(f'Frames/f_{frame}')
            r,g,b = rgb[0]
            red.append(r)
            green.append(g)
            blue.append(b)
            print(f'Frame: {frame} RGB:{rgb[0]}')

        frames = [(int(os.path.splitext(x)[0]))*20 for x in sorted_files]
        figs = generate_graph(red,green,blue,frames)

        self.tab_a1.delete("Color")

        for idx,f in enumerate(figs):
            self.tab_a1.add(colors[idx])
            canvas = FigureCanvasTkAgg(f,self.tab_a1.tab(colors[idx]))
            f.tight_layout()
            canvas.draw()
            canvas.get_tk_widget().pack(side=tkinter.TOP,fill=tkinter.BOTH,expand=True,anchor='center')

        self.tab_a1.configure(fg_color="White")

if __name__ == "__main__":
    app = App()
    app.mainloop()
</code>```

Title: Multiprocessing with GUI, python

Body:
Right now I am working on a GUI application which will essentially run 4 processes concurrently/ in parallel.

I have been unable to achieve multiprocessing with the tkinter application as it always ended in "can't pickle _tkinter.tkapp objects" and "EOFError: Ran out of input".

Essentially it is meant to run 4 process while updating its GUI. as of right now i am testing it with 2 process just to ensure that it is working.

Code Below:

import tkinter
import multiprocessing as mp
from tkinter import filedialog
from tkinter.ttk import Progressbar
import tkinter.messagebox
import customtkinter
import matplotlib
matplotlib.use("TkAgg")
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
from CV2_Frame_Extraction import *
from Color_Extractor_CT import *
from graph import *

customtkinter.set_appearance_mode("System")  # Modes: "System" (standard), "Dark", "Light"
customtkinter.set_default_color_theme("blue")  # Themes: "blue" (standard), "green", "dark-blue"

class App(customtkinter.CTk):
    btn_list = []
    def __init__(self):
        super().__init__()

        #Window Configuration
        self.title("Plasma Analysis")
        self.geometry("1100x580")

        #Layout Configuration
        #if needed later
        self.grid_rowconfigure((0, 1, 2), weight=1)

        #Side Bar
        self.sb_frame = customtkinter.CTkFrame(self,width=140, corner_radius=0)
        self.sb_frame.grid(row=0,column=0,rowspan=4,sticky="nsew")
        self.sb_frame.grid_rowconfigure(4,weight=1)

        self.sb_new = customtkinter.CTkButton(self.sb_frame, text="Add Video",command=self.openfile,corner_radius=2)
        self.sb_new.grid(row=0,column=0,padx=20,pady=20)

        self.btn_frame = customtkinter.CTkFrame(self.sb_frame,width=140,height=400,corner_radius=0,fg_color="transparent",border_width=5)
        self.btn_frame.grid(row=1,column=0,rowspan=3)

        self.bf_label = customtkinter.CTkLabel(self.btn_frame,text="Analysis", font=customtkinter.CTkFont(size=20, weight="bold"),fg_color="transparent")
        self.bf_label.grid(row=0,column=0)

        self.appearance_mode_label = customtkinter.CTkLabel(self.sb_frame, text="Appearance Mode:", anchor="w")
        self.appearance_mode_label.grid(row=7, column=0, padx=20, pady=(10, 0))
        self.appearance_mode_optionemenu = customtkinter.CTkOptionMenu(self.sb_frame, values=["Light", "Dark", "System"],
                                                                   command=self.change_appearance_mode_event)
        self.appearance_mode_optionemenu.grid(row=8, column=0, padx=20, pady=(10, 10))
        self.scaling_label = customtkinter.CTkLabel(self.sb_frame, text="UI Scaling:", anchor="w")
        self.scaling_label.grid(row=9, column=0, padx=20, pady=(10, 0))
        self.scaling_optionemenu = customtkinter.CTkOptionMenu(self.sb_frame, values=["80%", "90%", "100%", "110%", "120%"],
                                                           command=self.change_scaling_event)
        self.scaling_optionemenu.grid(row=10, column=0, padx=20, pady=(10, 20))

        #Creating Main Panel
        self.main_frame = customtkinter.CTkFrame(self,width=950,corner_radius=0,fg_color='transparent')
        self.main_frame.grid(row=0,column=1,rowspan=4,columnspan=4,sticky="nsew")

        self.tab_a1 = customtkinter.CTkTabview(self.main_frame,width=400,height=250,segmented_button_selected_color='gray',border_width=5)
        self.tab_a1.grid(row=0,column=0, padx=(30,50),pady=(15,15),sticky="nsew")
        self.tab_a1.grid_propagate(False)
        self.tab_a1.grid_columnconfigure(0, weight=0,uniform=1)
        self.tab_a1.grid_rowconfigure(0, weight=1,uniform=1)
        self.tab_a1.add("Color")

        self.tab_a2 = customtkinter.CTkTabview(self.main_frame,width=400,height=250,segmented_button_selected_color='gray',border_width=5)
        self.tab_a2.grid(row=0,column=1, padx=(0,50),pady=(15,15),sticky="nsew")
        self.tab_a2.add("Luminosity")

        self.tab_a3 = customtkinter.CTkTabview(self.main_frame,width=400,height=250,segmented_button_selected_color='gray',border_width=5)
        self.tab_a3.grid(row=1,column=0, padx=(30,50),pady=(15,15),sticky="nsew")
        self.tab_a3.add("Motion")

        self.tab_a4 = customtkinter.CTkTabview(self.main_frame,width=400,height=250,segmented_button_selected_color='gray',border_width=5)
        self.tab_a4.grid(row=1,column=1, padx=(0,50),pady=(15,15),sticky="nsew")
        self.tab_a4.add("Trend")

    def change_appearance_mode_event(self, new_appearance_mode: str):
        customtkinter.set_appearance_mode(new_appearance_mode)

    def change_scaling_event(self, new_scaling: str):
        new_scaling_float = int(new_scaling.replace("%", "")) / 100
        customtkinter.set_widget_scaling(new_scaling_float)

    def openfile(self):
        decision = filedialog.askopenfilename().split('/')
        name = decision[len(decision)-1].split('.')[0]

        p1 = mp.Process(target=self.loading, args=())
        p2 = mp.Process(target=self.getGraph, args=(decision,))

        self.btn_list.append(customtkinter.CTkButton(self.btn_frame,text=name))
        for x,btn in enumerate(self.btn_list):
            btn.grid(row=x+1,column=0,padx=10,pady=10)

        p1.start()
        #p2.start()

    def loading(self):
        lbl_load = customtkinter.CTkLabel(self.tab_a2.tab('Luminosity'),text="Loading ...",font=customtkinter.CTkFont(size=20, weight="bold"))
        lbl_load1 = customtkinter.CTkLabel(self.tab_a3.tab('Motion'),text="Loading ...",font=customtkinter.CTkFont(size=20, weight="bold"))
        lbl_load2 = customtkinter.CTkLabel(self.tab_a4.tab('Trend'),text="Loading ...",font=customtkinter.CTkFont(size=20, weight="bold"))
        lbl_load.pack(side=tkinter.TOP,fill=tkinter.BOTH,expand=True,anchor='center')
        lbl_load1.pack(side=tkinter.TOP,fill=tkinter.BOTH,expand=True,anchor='center')
        lbl_load2.pack(side=tkinter.TOP,fill=tkinter.BOTH,expand=True,anchor='center')

        self.update()

    def getGraph(self,decision):
        frame_extraction('\\'.join(decision))

        colors = ["Red","Green","Blue"]
        red = []
        green = []
        blue = []

        files = os.listdir('Frames')
        sorted_files = [file.replace('f_','') for file in files]
        sorted_files = sorted(sorted_files, key=lambda x: int(os.path.splitext(x)[0]))

        for frame in sorted_files:
            rgb = color_extraction(f'Frames/f_{frame}')
            r,g,b = rgb[0]
            red.append(r)
            green.append(g)
            blue.append(b)
            print(f'Frame: {frame} RGB:{rgb[0]}')

        frames = [(int(os.path.splitext(x)[0]))*20 for x in sorted_files]
        figs = generate_graph(red,green,blue,frames)

        self.tab_a1.delete("Color")

        for idx,f in enumerate(figs):
            self.tab_a1.add(colors[idx])
            canvas = FigureCanvasTkAgg(f,self.tab_a1.tab(colors[idx]))
            f.tight_layout()
            canvas.draw()
            canvas.get_tk_widget().pack(side=tkinter.TOP,fill=tkinter.BOTH,expand=True,anchor='center')

        self.tab_a1.configure(fg_color="White")

if __name__ == "__main__":
    app = App()
    app.mainloop()


问:
Get antenna port of RFID fixed reader
I am working on a RFID fixed reader on Java and I am unable to programmatically get which antenna is reading the tags

I just want to get which antenna is currently reading the tags and which tag is read by which antenna, in Java.

Title: Get antenna port of RFID fixed reader


问:
Set Android Shape Drawable Corners as a Percentage
Is there a way to set different lengths in Android as percentage? I am creating a rectangle shape drawable whose corner radius should change depending on the size of the element on which I am applying the drawable.

I am new to Android development, so using fixed length units seems very restrictive. In CSS, we can simply set the border-radius to 20% or the padding to 5%. The values will then scale accordingly based on the element size.

Is something similar possible in Android?

Similarly, we specify gradient radius as let's say 15dp. Is there any way to set it as 15%?

It doesn't seem very productive to create three different drawables with three different gradient radii for three different sized elements.

Thanks.


问:
Thymeleaf arrays contains is not validating correctly even element is present
The following code is not working.

```<code><li class="nav-item dropdown"  th:if="${#authentication?.getAuthorities().contains('TRANSACTIONS_MANAGER')}">
</code>```

The

```<code>#authentication?.getAuthorities()
</code>```

out put contains [TRANSACTIONS_MANAGER].

What is the right way to test that array contains some string.

```<code>th:if="${#authentication?.getAuthorities()?.toString().contains('TRANSACTIONS_MANAGER')}"
</code>```

How to debug ?

Body:
The following code is not working.

The

#authentication?.getAuthorities()

out put contains [TRANSACTIONS_MANAGER].

What is the right way to test that array contains some string.

th:if="${#authentication?.getAuthorities()?.toString().contains('TRANSACTIONS_MANAGER')}"

How to debug ?


问:
Why there are eight bytes pad in the stack frame of main function?

package main

func main() {
  var x int32 = 1
  nop(x)
}

//go:noinline
func nop(x int32) {}
```
<p><strong>Go version: go1.16.15 windows/amd64</strong></p>
<p>I wrote above code and compiled it into assembly with <code>go1.16.15 tool compile -S -N -l main.go</code> for truly understanding Go functions call.</p>
<p>The following is the assembly code of nop function:</p>
```"".nop STEXT nosplit size=1 args=0x8 locals=0x0 funcid=0x0
        0x0000 00000 (main.go:9)        TEXT    "".nop(SB), NOSPLIT|ABIInternal, $0-8
        0x0000 00000 (main.go:9)        FUNCDATA        $0, gclocals·33cdeccccebe80329f1fdbee7f5874cb(SB)
        0x0000 00000 (main.go:9)        FUNCDATA        $1, gclocals·33cdeccccebe80329f1fdbee7f5874cb(SB)
        0x0000 00000 (main.go:9)        RET
```
<p>Obviously, the nop function returns directly without doing anything. It only has a <code>int32</code> type parameter, but we can see the <code>argsize</code> is 8 bytes in the assembly:</p>
<p>TEXT    "".nop(SB), NOSPLIT|ABIInternal, $0-<em><strong>8</strong></em></p>
<p><strong>Question1: Why the <code>argsize</code> is 8 bytes not 4 bytes?</strong></p>
<p>The following is the assembly code of main function:</p>
```"".main STEXT size=73 args=0x0 locals=0x18 funcid=0x0
        0x0000 00000 (main.go:3)        TEXT    "".main(SB), ABIInternal, $24-0
        ;; ...omitted stack-split prologue...
        0x0016 00022 (main.go:3)        SUBQ    $24, SP
        0x001a 00026 (main.go:3)        MOVQ    BP, 16(SP)
        0x001f 00031 (main.go:3)        LEAQ    16(SP), BP
        0x0024 00036 (main.go:3)        FUNCDATA        $0, gclocals·33cdeccccebe80329f1fdbee7f5874cb(SB)
        0x0024 00036 (main.go:3)        FUNCDATA        $1, gclocals·33cdeccccebe80329f1fdbee7f5874cb(SB)
        0x0024 00036 (main.go:4)        MOVL    $1, "".x+12(SP)
        0x002c 00044 (main.go:5)        MOVL    $1, (SP)
        0x0033 00051 (main.go:5)        PCDATA  $1, $0
        0x0033 00051 (main.go:5)        CALL    "".nop(SB)
        0x0038 00056 (main.go:6)        MOVQ    16(SP), BP
        0x003d 00061 (main.go:6)        ADDQ    $24, SP
        0x0041 00065 (main.go:6)        RET
        ;; ...omitted stack-split epilogue...
```

I drawn a picture of stack according to the assembly code:
stack

Question2: I find there are confusing 8 bytes in the stack, why do these 8 bytes exist?

I think memory alignment causes the above phenomenon, but I'm not sure.

Body:
package main

func main() {
  var x int32 = 1
  nop(x)
}

//go:noinline
func nop(x int32) {}

Go version: go1.16.15 windows/amd64

I wrote above code and compiled it into assembly with go1.16.15 tool compile -S -N -l main.go for truly understanding Go functions call.

The following is the assembly code of nop function:

"".nop STEXT nosplit size=1 args=0x8 locals=0x0 funcid=0x0
        0x0000 00000 (main.go:9)        TEXT    "".nop(SB), NOSPLIT|ABIInternal, $0-8
        0x0000 00000 (main.go:9)        FUNCDATA        $0, gclocals·33cdeccccebe80329f1fdbee7f5874cb(SB)
        0x0000 00000 (main.go:9)        FUNCDATA        $1, gclocals·33cdeccccebe80329f1fdbee7f5874cb(SB)
        0x0000 00000 (main.go:9)        RET

Obviously, the nop function returns directly without doing anything. It only has a int32 type parameter, but we can see the argsize is 8 bytes in the assembly:

TEXT    "".nop(SB), NOSPLIT|ABIInternal, $0-8

Question1: Why the argsize is 8 bytes not 4 bytes?

The following is the assembly code of main function:

"".main STEXT size=73 args=0x0 locals=0x18 funcid=0x0
        0x0000 00000 (main.go:3)        TEXT    "".main(SB), ABIInternal, $24-0
        ;; ...omitted stack-split prologue...
        0x0016 00022 (main.go:3)        SUBQ    $24, SP
        0x001a 00026 (main.go:3)        MOVQ    BP, 16(SP)
        0x001f 00031 (main.go:3)        LEAQ    16(SP), BP
        0x0024 00036 (main.go:3)        FUNCDATA        $0, gclocals·33cdeccccebe80329f1fdbee7f5874cb(SB)
        0x0024 00036 (main.go:3)        FUNCDATA        $1, gclocals·33cdeccccebe80329f1fdbee7f5874cb(SB)
        0x0024 00036 (main.go:4)        MOVL    $1, "".x+12(SP)
        0x002c 00044 (main.go:5)        MOVL    $1, (SP)
        0x0033 00051 (main.go:5)        PCDATA  $1, $0
        0x0033 00051 (main.go:5)        CALL    "".nop(SB)
        0x0038 00056 (main.go:6)        MOVQ    16(SP), BP
        0x003d 00061 (main.go:6)        ADDQ    $24, SP
        0x0041 00065 (main.go:6)        RET
        ;; ...omitted stack-split epilogue...

I drawn a picture of stack according to the assembly code:
stack

Question2: I find there are confusing 8 bytes in the stack, why do these 8 bytes exist?

I think memory alignment causes the above phenomenon, but I'm not sure.


问:
About deleting node from max-heap
Why in most tutorials and documents (98% of what i watch or read) when they take about deleting node form a heap, they only delete the root node (first image where we delete 12 node root). Why not some node of its childrens (second image where we delete node 11 is an example scenario)?

I know that is not impossible to do that and how to do it but why everyone take only about the root node?

I watch about 7 courses in Arabic, other 7 in English and 4 in Turkish. And i read a lot of article about that also in different language!

But all of them delete the root node! Why?
Note: I am a beginner in computer science.

As i write in my question details, i read and watch a lot of courses and articles about this topic

Title: About deleting node from max-heap


问:
VueJS+Spring change sub-path
I need start my jar file on sub-path "/new"

If i change  publicPath: '/new/', in my vue.config.js

After build java in index in java i have src="/new/static/js/app.c5c5f2e6.js"

and this path dont work, because i dont have path "/NEW/"

And in console i get error

```<code>Refused to apply style from 'http://localhost:8098/new/static/css/app.61cdbd8f.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.
</code>```

because app.61cdbd8f.css in to http://localhost:8098/static/css/app.61cdbd8f.css (without new)

How i can change path with / to /new/

Title: VueJS+Spring change sub-path

Body:
I need start my jar file on sub-path "/new"

If i change  publicPath: '/new/', in my vue.config.js

After build java in index in java i have src="/new/static/js/app.c5c5f2e6.js"

and this path dont work, because i dont have path "/NEW/"

And in console i get error

Refused to apply style from 'http://localhost:8098/new/static/css/app.61cdbd8f.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.

because app.61cdbd8f.css in to http://localhost:8098/static/css/app.61cdbd8f.css (without new)

How i can change path with / to /new/


问:
Using clap-derive with two groups of arguments
Given this Clap argument struct, I would like to allow users either to supply the config param, or any of the other params that are being flattened from the sub-structs. The connection param would then be required, but other flattened params are optional.  Note that the watch param is allowed in both cases.  How can this be done in Clap-derive v4+?

#[derive(Parser, Debug)]
#[command(about, version)]
pub struct Args {
    connection: Vec<String>,
    #[arg(short)]
    watch: bool,
    #[arg(short)]
    config: Option<PathBuf>,
    #[command(flatten)]
    srv: SrvArgs,
    #[command(flatten)]
    pg: PgArgs,
}

#[derive(clap::Args, Debug)]
#[command(about, version)]
pub struct SrvArgs {
    #[arg(short)]
    pub keep: Option<usize>,
}

#[derive(clap::Args, Debug)]
#[command(about, version)]
pub struct PgArgs {
    #[arg(short)]
    pub pool: Option<i32>,
}
```

Allowed usages:

-c filename [-w]

[-p 10] [-k 5] [-w] connection [...connection]

I tried to do it by moving all fields except config and watch to another struct and using the #[arg(group = "cfg")] on both, but it doesn't work when the field also has the #[command(flatten)] attribute.

Body:
Given this Clap argument struct, I would like to allow users either to supply the config param, or any of the other params that are being flattened from the sub-structs. The connection param would then be required, but other flattened params are optional.  Note that the watch param is allowed in both cases.  How can this be done in Clap-derive v4+?

#[derive(Parser, Debug)]
#[command(about, version)]
pub struct Args {
    connection: Vec<String>,
    #[arg(short)]
    watch: bool,
    #[arg(short)]
    config: Option<PathBuf>,
    #[command(flatten)]
    srv: SrvArgs,
    #[command(flatten)]
    pg: PgArgs,
}

#[derive(clap::Args, Debug)]
#[command(about, version)]
pub struct SrvArgs {
    #[arg(short)]
    pub keep: Option<usize>,
}

#[derive(clap::Args, Debug)]
#[command(about, version)]
pub struct PgArgs {
    #[arg(short)]
    pub pool: Option<i32>,
}

Allowed usages:

-c filename [-w]

[-p 10] [-k 5] [-w] connection [...connection]

I tried to do it by moving all fields except config and watch to another struct and using the #[arg(group = "cfg")] on both, but it doesn't work when the field also has the #[command(flatten)] attribute.


问:
React Context provider doesn't see data
I need to parse data from modal window (Modalbuy.js) to parent component (Page.js) and then to another child, but my Context Provider doesn't see changed data.Despite that fact, if I ask to console.log not in context.provider brackets, but still in parent component, I get my data logs right

Modalbuy.js

```<code>import React, {useState} from "react";
import "./modal.css";
import { DataBuyContext } from "../../page/page";

const Modalbuy = ({active, setActive,price}) => {
  const [inputVolume, setInputVolume] = useState("")
  function saveInput(event) {
    setInputVolume(event.target.value)
    console.log(inputVolume)
  }

  const {dataBuy, setDataBuy} = React.useContext(DataBuyContext)
  function addBuy() {
    setDataBuy([...dataBuy,{side: "BUY", price:{price},volume: {inputVolume},timestamp: new Date().toLocaleTimeString()}])
    // console.log(dataBuy)
  }

    return (

        <div className={active ? "modal active" : "modal"} onClick={() => setActive(false)}>
          <div className="modal__content" onClick={e => e.stopPropagation()}>
            <header>Make order</header>
            <p>BUY {price}</p>
            <input placeholder="Volume" value={inputVolume} onChange={saveInput}></input>
            <div>
              <button onClick = {addBuy}>Ok</button>
              <button onClick={() => setActive(false)} >Cancel</button>
            </div>

          </div>
        </div>

    )
}

export default Modalbuy;
</code>```

Page.js

```<code>import React, {useState} from 'react'

import Trading from '../trading/Trading'
import Archive from '../archive/Archive'
import './page.css';
export const DataBuyContext = React.createContext({})

const Page = () => {

  const [dataBuy, setDataBuy] = useState([{}])

  const [toggleState, setToggleState] = useState(1)

  const toggleTab = (index) =>{
    setToggleState(index);
  }
  console.log(dataBuy)

  return (
    <DataBuyContext.Provider value = {{dataBuy, setDataBuy}}>
    <div className="container">
      <div className="block-tabs">
        <button
          className={toggleState === 1 ? "tabs active-tabs" : "tabs"}
          onClick={() => toggleTab(1)}>
          Trading
        </button>
        <button
          className={toggleState === 2 ? "tabs active-tabs" : "tabs"}
          onClick={() => toggleTab(2)}>
          Archive
        </button>
      </div>

      <div className="content-tabs">
        <div
          className={toggleState === 1 ? "content  active-content" : "content"}>
            <Trading />

        </div>

        <div
          className={toggleState === 2 ? "content  active-content" : "content"}>
            <Archive dataBuy= {dataBuy} />

        </div>

      </div>
    </div>
    </DataBuyContext.Provider>
  );

}

export default Page;
</code>```

And Archive.js child component, where I want to transport data

```<code>import React, {useState} from 'react';
import './archive.css';
import Table from './Table';

const Archive = (dataBuy) => {
    const [rows, setRows] = useState(dataBuy)
    console.log(rows)

    return (

        <Table dataBuy = {rows}/>

    )
  }

  export default Archive;
</code>```

App.js

```<code>import './App.css';
import React from 'react';
import Page from './components/page/page'

function App() {

  return (
    <div className="App">
      <Page/>

    </div>
  );
}

export default App;
</code>```

Title: React Context provider doesn't see data

Body:
I need to parse data from modal window (Modalbuy.js) to parent component (Page.js) and then to another child, but my Context Provider doesn't see changed data.Despite that fact, if I ask to console.log not in context.provider brackets, but still in parent component, I get my data logs right

Modalbuy.js

import React, {useState} from "react";
import "./modal.css";
import { DataBuyContext } from "../../page/page";

const Modalbuy = ({active, setActive,price}) => {
  const [inputVolume, setInputVolume] = useState("")
  function saveInput(event) {
    setInputVolume(event.target.value)
    console.log(inputVolume)
  }

  const {dataBuy, setDataBuy} = React.useContext(DataBuyContext)
  function addBuy() {
    setDataBuy([...dataBuy,{side: "BUY", price:{price},volume: {inputVolume},timestamp: new Date().toLocaleTimeString()}])
    // console.log(dataBuy)
  }

    return (

 setActive(false)}>

 e.stopPropagation()}>
            Make order

BUY {price}

            <input placeholder="Volume" value={inputVolume} onChange={saveInput}></input>

              <button onClick = {addBuy}>Ok</button>
              <button onClick={() => setActive(false)} >Cancel</button>

    )
}

export default Modalbuy;

Page.js

import React, {useState} from 'react'

import Trading from '../trading/Trading'
import Archive from '../archive/Archive'
import './page.css';
export const DataBuyContext = React.createContext({})

const Page = () => {

  const [dataBuy, setDataBuy] = useState([{}])

  const [toggleState, setToggleState] = useState(1)

  const toggleTab = (index) =>{
    setToggleState(index);
  }
  console.log(dataBuy)

  return (
    <DataBuyContext.Provider value = {{dataBuy, setDataBuy}}>

        <button
          className={toggleState === 1 ? "tabs active-tabs" : "tabs"}
          onClick={() => toggleTab(1)}>
          Trading
        </button>
        <button
          className={toggleState === 2 ? "tabs active-tabs" : "tabs"}
          onClick={() => toggleTab(2)}>
          Archive
        </button>

            <Trading />

            <Archive dataBuy= {dataBuy} />

    </DataBuyContext.Provider>
  );

}

export default Page;

And Archive.js child component, where I want to transport data

import React, {useState} from 'react';
import './archive.css';
import Table from './Table';

const Archive = (dataBuy) => {
    const [rows, setRows] = useState(dataBuy)
    console.log(rows)

    return (

    )
  }

  export default Archive;

App.js

import './App.css';
import React from 'react';
import Page from './components/page/page'

function App() {

  return (

      <Page/>

  );
}

export default App;


问:
Java 2D Arrays List throws an error when objects are not added with an orderly index format
I am trying to understand why JVM throws an error when I try to add other Arrays lists into a 2D Array without indexing them by order.
Normally I don't get an error when I add the Arrays with an orderly Index sequence. But I am curious to understand why I get an error when I don't. I am new to Java

 public class DoSomething {
    public static void main(String[] args) {

        ArrayList<ArrayList<String>> frisbeTeams = new ArrayList<>();
        ArrayList<String> zen = new ArrayList<>();
        zen.add("iman");
        zen.add("dave");
        zen.add("jairo");
        zen.add("victor");
        zen.add("gene");
        zen.add("chor");

        ArrayList<String> szupa = new ArrayList<>();
        szupa.add("sam");
        szupa.add("mary");
        szupa.add("eman");
        szupa.add("louise");

        ArrayList<String> avocado = new ArrayList<>();
        avocado.add("ran");
        avocado.add("lana");
        avocado.add("winky");

    }

}
```
<p>When I add the Arrays with an ordered Index format like this, It works</p>
<pre class="lang-java prettyprint-override"><code>frisbeTeams.add(0,avocado);
        frisbeTeams.add(1,zen);
        frisbeTeams.add(2,szupa);

        System.out.println(frisbeTeams);
</code>```

But, When I randomly Index like this. I get an error

 frisbeTeams.add(0,avocado);
        frisbeTeams.add(2,zen);
        frisbeTeams.add(1,szupa);
```
<p><em>error</em></p>
```Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 2, Size: 1
    at java.base/java.util.ArrayList.rangeCheckForAdd(ArrayList.java:756)
    at java.base/java.util.ArrayList.add(ArrayList.java:481)
    at org.learn.DoSomething.main(DoSomething.java:29)
```

Body:
I am trying to understand why JVM throws an error when I try to add other Arrays lists into a 2D Array without indexing them by order.
Normally I don't get an error when I add the Arrays with an orderly Index sequence. But I am curious to understand why I get an error when I don't. I am new to Java

 public class DoSomething {
    public static void main(String[] args) {

        ArrayList<ArrayList<String>> frisbeTeams = new ArrayList<>();
        ArrayList<String> zen = new ArrayList<>();
        zen.add("iman");
        zen.add("dave");
        zen.add("jairo");
        zen.add("victor");
        zen.add("gene");
        zen.add("chor");

        ArrayList<String> szupa = new ArrayList<>();
        szupa.add("sam");
        szupa.add("mary");
        szupa.add("eman");
        szupa.add("louise");

        ArrayList<String> avocado = new ArrayList<>();
        avocado.add("ran");
        avocado.add("lana");
        avocado.add("winky");

    }

}

When I add the Arrays with an ordered Index format like this, It works

frisbeTeams.add(0,avocado);
        frisbeTeams.add(1,zen);
        frisbeTeams.add(2,szupa);

        System.out.println(frisbeTeams);

But, When I randomly Index like this. I get an error

 frisbeTeams.add(0,avocado);
        frisbeTeams.add(2,zen);
        frisbeTeams.add(1,szupa);

error

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 2, Size: 1
    at java.base/java.util.ArrayList.rangeCheckForAdd(ArrayList.java:756)
    at java.base/java.util.ArrayList.add(ArrayList.java:481)
    at org.learn.DoSomething.main(DoSomething.java:29)


问:
Aterminate called after throwing an instance of 'std::runtime_error' what(): NCCL Error 1: unhandled cuda error
This error occurs when using DataParallel.
but it works when using only 1 GPU.
May I ask why this problem occurs and how can I solve it？

```<code>
Aterminate called after throwing an instance of 'std::runtime_error'
what():  NCCL Error 1: unhandled cuda error
Aborted (core dumped)
</code>```

My code is:

```<code>gpus = [0, 1, 2]
my_model.to(pytorch_device)
my_model = DataParallel(my_model, device_ids=gpus, output_device=gpus[0])
</code>```

Body:
This error occurs when using DataParallel.
but it works when using only 1 GPU.
May I ask why this problem occurs and how can I solve it？

Aterminate called after throwing an instance of 'std::runtime_error'
what():  NCCL Error 1: unhandled cuda error
Aborted (core dumped)

My code is:

gpus = [0, 1, 2]
my_model.to(pytorch_device)
my_model = DataParallel(my_model, device_ids=gpus, output_device=gpus[0])


问:
Bot catches error when sending query to database
I have a tab/bot teams app that is catching on the first db call inside the bot handleTeamsTaskModuleSubmit handler. I keep getting a connection error in 2 forms

Error in PostgreSQL connection: Error { kind: Io, cause: Some(Os { code: 10054, kind: ConnectionReset, message: "An existing connection was forcibly closed by the remote host." }) }

or

connect EACCES 127.0.0.1:49543

The bot is deployed as an azure app service, written in node.js, and it's using Prisma client to connect with my Postgres database. It had been working previously but since the last time, I deployed the app to the team store the call has been erroring.

I'm not sure where I can see the active connections or find a place to verify the connection URL. The only other thing I can think of is that the client isn't being initiated on deployment but I cannot find the deploy source code in the generated code of the vs code teams-toolkit.