问:
How can I prevent these values of color and stocks to be duplicated when I add more sizes?
Users can add more text fields of size, color, and stocks. If I'll add more sizes, the values for the color and stocks will duplicate from what was first entered.

Expected output:

1st Size : small

color: red, stocks: 10

color: green, stocks: 3

2nd Size: medium

color: white, stocks: 3

color: red, stocks: 6 the sizes field.

What it currently does is in the 2nd size, it will just duplicate whatever value was entered from the first size. How can I fix this? Thank you.

How can I combine the indexes of the colorList loop and sizeList loop to avoid the duplicates of the value of the textfields?

Link: https://codesandbox.io/s/form-2-add-more-size-ddqqo?file=/demo.js

```<code>import React, { useState, useEffect } from "react";
import Box from "@mui/material/Box";

import { TextField, Button } from "@mui/material";

export default function BasicSelect() {
  const [productName, setProductName] = useState();
  const [sizeList, setSizeList] = useState([{ size: "" }]);
  const [colorList, setColorList] = useState([{ color: "", colorStocks: "" }]);

  //sizes
  const handleServiceChange = (e, index) => {
    const { name, value } = e.target;
    const list = [...sizeList];
    list[index][name] = value;
    setSizeList(list);
  };

  const handleServiceRemove = (index) => {
    const list = [...sizeList];
    list.splice(index, 1);
    setSizeList(list);
  };

  const handleServiceAdd = () => {
    setSizeList([...sizeList, { service: "" }]);
  };

  // color
  const handleColorChange = (e, index) => {
    const { name, value } = e.target;
    const list = [...colorList];
    list[index][name] = value;
    setColorList(list);
    // console.log(colorList);
  };

  const handleColorStocksChange = (e, index) => {
    const { name, value } = e.target;
    const list = [...colorList];
    list[index][name] = value;
    setColorList(list);
    // console.log(colorList);
  };

  // const handleColorChange = (e, index) => {
  //   const { value } = e.target;

  //   const arr = [...colorList]; //Shallow copy the existing state
  //   arr[index].color = value; //Update the size to the selected size
  //   console.log(arr[index].value);
  //   setColorList([...arr]); //Set the updated array to be the new state
  // };

  // const handleColorStocksChange = (e, index) => {
  //   const { value } = e.target;
  //   console.log(value);
  //   const arr = [...colorList];
  //   arr[index].colorStocks = value;
  //   // console.log(arr)
  //   setColorList([...arr]);
  // };

  const handleColorRemove = (index) => {
    const list = [...colorList];
    list.splice(index, 1);
    setColorList(list);
  };

  const handleColorAdd = () => {
    setColorList([...colorList, { color: "", colorStocks: "" }]);
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    console.log("Product: ", productName, "size: ", sizeList, colorList);
  };

  return (
    <Box sx={{ minWidth: 120 }}>
      <form onSubmit={handleSubmit}>
        <TextField
          label="Product Name"
          name="name"
          type="text"
          id="productName"
          value={productName}
          onChange={(e) => setProductName(e.target.value)}
          required
        />

        {sizeList.map((singleSize, index) => (
          <div key={index}>
            <TextField
              label="Size"
              name="size"
              type="text"
              id="size"
              required
              value={singleSize.size}
              onChange={(e) => handleServiceChange(e, index)}
            />
            {colorList.map((singleColor, index) => (
              <div key={index}>
                <TextField
                  label="color"
                  name="color"
                  type="text"
                  id="color"
                  required
                  value={singleColor.color}
                  onChange={(e) => handleColorStocksChange(e, index)}
                />
                <TextField
                  label="Stocks"
                  name="colorStocks"
                  type="text"
                  id="colorStocks"
                  required
                  value={singleColor.colorStocks}
                  onChange={(e) => handleColorChange(e, index)}
                />
                {colorList.length !== 1 && (
                  <Button onClick={() => handleColorRemove(index)}>
                    Remove
                  </Button>
                )}
                <br />
                {colorList.length - 1 === index && (
                  <Button onClick={handleColorAdd}>Add Color</Button>
                )}
                <br /> <br />
                {/* add or remove sizes */}
              </div>
            ))}
            {sizeList.length - 1 === index && (
              <Button type="button" onClick={handleServiceAdd}>
                Add size
              </Button>
            )}
            {sizeList.length - 1 === index && (
              <Button type="button" onClick={() => handleServiceRemove(index)}>
                Remove Size
              </Button>
            )}
          </div>
        ))}

        <br />
        <Button type="submit">Submit </Button>
      </form>

      <div className="output">
        <h2>Output</h2>
        <h3>Sizes:</h3>
        {sizeList &&
          sizeList.map((singleSize, index) => (
            <ul key={index}>{singleSize.size && <li>{singleSize.size}</li>}</ul>
          ))}

        <br />
        <h3>Color:</h3>
        {colorList &&
          colorList.map((singleSize, index) => (
            <ul key={index}>
              {singleSize.color && (
                <li>{singleSize.color + " - " + singleSize.colorStocks}</li>
              )}
            </ul>
          ))}
      </div>
    </Box>
  );
}
</code>```

Also in: https://www.reddit.com/r/reactjs/comments/sl41p5/handling_dynamic_textfields_values_are_duplicated/

答:
Since you need an array of inputs, you need to maintain the states in that order.
See my updated sandbox code https://codesandbox.io/s/form-2-add-more-size-forked-yvrgg?file=/demo.js</p>
```<code>import React, { useState, useEffect } from "react";
import Box from "@mui/material/Box";

import { TextField, Button } from "@mui/material";

export default function BasicSelect() {
  const [productName, setProductName] = useState();
  const [sizeList, setSizeList] = useState([{ size: "", colorList: [{ color: "", colorStocks: "" }] }]);
  const [colorList, setColorList] = useState([{ color: "", colorStocks: "" }]);

  //sizes
  const handleServiceChange = (e, index) => {
    const { name, value } = e.target;
    const list = [...sizeList];
    list[index] = { ...list[index] }; // copy the item too
    list[index][name] = value;
    setSizeList(list);
  };

  const handleServiceRemove = (index) => {
    const list = [...sizeList];
    list.splice(index, 1);
    setSizeList(list);
  };

  const handleServiceAdd = () => {
    setSizeList([...sizeList, { service: "", colorList: [{ color: "", colorStocks: "" }] }]);
  };

  // color
  const handleColorChange = (e, index, innerIndex) => {
    const { name, value } = e.target;
    const list = [...sizeList];
    list[index].colorList[innerIndex][name] = value;
    setSizeList(list)
  };

  const handleColorRemove = (index) => {
    const list = [...colorList];
    list.splice(index, 1);
    setColorList(list);
  };

  const handleColorAdd = (index) => {
    const list = [...sizeList];
    list[index].colorList.push({ color: "", colorStocks: "" });
    setSizeList(list)
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    console.log("Product: ", productName, "size: ", sizeList, colorList);
  };

  return (
    <Box sx={{ minWidth: 120 }}>
      <form onSubmit={handleSubmit}>
        <TextField
          sx={{mb:2}}
          label="Product Name"
          name="name"
          type="text"
          id="productName"
          value={productName}
          onChange={(e) => setProductName(e.target.value)}
          required
        />

        {sizeList.map((singleSize, index) => (
          <div key={index}>
            <TextField
              label="Size"
              type="text"
              name={`size${index}`}
              id={`size${index}`}
              required
              value={singleSize.size}
              onChange={(e) => handleServiceChange(e, index)}
            />
            {singleSize.colorList.map((singleColor, innerIndex) => (
              <div key={index}>
                <TextField
                  label="color"
                  name="color"
                  type="text"
                  id="color"
                  required
                  value={singleColor.color}
                  onChange={(e) => handleColorChange(e, index, innerIndex)}
                />
                <TextField
                  label="Stocks"
                  name="colorStocks"
                  type="text"
                  id="colorStocks"
                  required
                  value={singleColor.colorStocks}
                  onChange={(e) => handleColorChange(e, index, innerIndex)}
                />
                {colorList.length !== 1 && (
                  <Button onClick={() => handleColorRemove(index)}>
                    Remove
                  </Button>
                )}
                <br />
                {colorList.length - 1 === index && (
                  <Button onClick={()=>handleColorAdd(index)}>Add Color</Button>
                )}
                <br /> <br />
                {/* add or remove sizes */}
              </div>
            ))}
            {sizeList.length - 1 === index && (
              <Button type="button" onClick={handleServiceAdd}>
                Add size
              </Button>
            )}
            {sizeList.length - 1 === index && (
              <Button type="button" onClick={() => handleServiceRemove(index)}>
                Remove Size
              </Button>
            )}
          </div>
        ))}

        <br />
        <Button type="submit">Submit </Button>
      </form>

      <div className="output">
        <h2>Output</h2>
        <h3>Sizes:</h3>
        {sizeList &&
          sizeList.map((singleSize, index) => (
            <ul key={index}>{singleSize.size && <li>{singleSize.size}</li>}</ul>
          ))}

        <br />
        <h3>Color:</h3>
        {colorList &&
          colorList.map((singleSize, index) => (
            <ul key={index}>
              {singleSize.color && (
                <li>{singleSize.color + " - " + singleSize.colorStocks}</li>
              )}
            </ul>
          ))}
      </div>
    </Box>
  );
}
</code>```

Body:
Users can add more text fields of size, color, and stocks. If I'll add more sizes, the values for the color and stocks will duplicate from what was first entered.

Expected output:

1st Size : small

color: red, stocks: 10

color: green, stocks: 3

2nd Size: medium

color: white, stocks: 3

color: red, stocks: 6 the sizes field.

What it currently does is in the 2nd size, it will just duplicate whatever value was entered from the first size. How can I fix this? Thank you.

How can I combine the indexes of the colorList loop and sizeList loop to avoid the duplicates of the value of the textfields?

Link: https://codesandbox.io/s/form-2-add-more-size-ddqqo?file=/demo.js

import React, { useState, useEffect } from "react";
import Box from "@mui/material/Box";

import { TextField, Button } from "@mui/material";

export default function BasicSelect() {
  const [productName, setProductName] = useState();
  const [sizeList, setSizeList] = useState([{ size: "" }]);
  const [colorList, setColorList] = useState([{ color: "", colorStocks: "" }]);

  //sizes
  const handleServiceChange = (e, index) => {
    const { name, value } = e.target;
    const list = [...sizeList];
    list[index][name] = value;
    setSizeList(list);
  };

  const handleServiceRemove = (index) => {
    const list = [...sizeList];
    list.splice(index, 1);
    setSizeList(list);
  };

  const handleServiceAdd = () => {
    setSizeList([...sizeList, { service: "" }]);
  };

  // color
  const handleColorChange = (e, index) => {
    const { name, value } = e.target;
    const list = [...colorList];
    list[index][name] = value;
    setColorList(list);
    // console.log(colorList);
  };

  const handleColorStocksChange = (e, index) => {
    const { name, value } = e.target;
    const list = [...colorList];
    list[index][name] = value;
    setColorList(list);
    // console.log(colorList);
  };

  // const handleColorChange = (e, index) => {
  //   const { value } = e.target;

  //   const arr = [...colorList]; //Shallow copy the existing state
  //   arr[index].color = value; //Update the size to the selected size
  //   console.log(arr[index].value);
  //   setColorList([...arr]); //Set the updated array to be the new state
  // };

  // const handleColorStocksChange = (e, index) => {
  //   const { value } = e.target;
  //   console.log(value);
  //   const arr = [...colorList];
  //   arr[index].colorStocks = value;
  //   // console.log(arr)
  //   setColorList([...arr]);
  // };

  const handleColorRemove = (index) => {
    const list = [...colorList];
    list.splice(index, 1);
    setColorList(list);
  };

  const handleColorAdd = () => {
    setColorList([...colorList, { color: "", colorStocks: "" }]);
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    console.log("Product: ", productName, "size: ", sizeList, colorList);
  };

  return (
    <Box sx={{ minWidth: 120 }}>
      <form onSubmit={handleSubmit}>
        <TextField
          label="Product Name"
          name="name"
          type="text"
          id="productName"
          value={productName}
          onChange={(e) => setProductName(e.target.value)}
          required
        />

        {sizeList.map((singleSize, index) => (

            <TextField
              label="Size"
              name="size"
              type="text"
              id="size"
              required
              value={singleSize.size}
              onChange={(e) => handleServiceChange(e, index)}
            />
            {colorList.map((singleColor, index) => (

                <TextField
                  label="color"
                  name="color"
                  type="text"
                  id="color"
                  required
                  value={singleColor.color}
                  onChange={(e) => handleColorStocksChange(e, index)}
                />
                <TextField
                  label="Stocks"
                  name="colorStocks"
                  type="text"
                  id="colorStocks"
                  required
                  value={singleColor.colorStocks}
                  onChange={(e) => handleColorChange(e, index)}
                />
                {colorList.length !== 1 && (
                  <Button onClick={() => handleColorRemove(index)}>
                    Remove
                  </Button>
                )}

                {colorList.length - 1 === index && (
                  <Button onClick={handleColorAdd}>Add Color</Button>
                )}

                {/* add or remove sizes */}

            ))}
            {sizeList.length - 1 === index && (
              <Button type="button" onClick={handleServiceAdd}>
                Add size
              </Button>
            )}
            {sizeList.length - 1 === index && (
              <Button type="button" onClick={() => handleServiceRemove(index)}>
                Remove Size
              </Button>
            )}

        ))}

        <Button type="submit">Submit </Button>
      </form>

Output

Sizes:

        {sizeList &&
          sizeList.map((singleSize, index) => (

{singleSize.size &&
{singleSize.size}
}

          ))}

Color:

        {colorList &&
          colorList.map((singleSize, index) => (

              {singleSize.color && (

{singleSize.color + " - " + singleSize.colorStocks}

              )}

          ))}

    </Box>
  );
}

Also in: https://www.reddit.com/r/reactjs/comments/sl41p5/handling_dynamic_textfields_values_are_duplicated/

Body:
Since you need an array of inputs, you need to maintain the states in that order.
See my updated sandbox code https://codesandbox.io/s/form-2-add-more-size-forked-yvrgg?file=/demo.js

import React, { useState, useEffect } from "react";
import Box from "@mui/material/Box";

import { TextField, Button } from "@mui/material";

export default function BasicSelect() {
  const [productName, setProductName] = useState();
  const [sizeList, setSizeList] = useState([{ size: "", colorList: [{ color: "", colorStocks: "" }] }]);
  const [colorList, setColorList] = useState([{ color: "", colorStocks: "" }]);

  //sizes
  const handleServiceChange = (e, index) => {
    const { name, value } = e.target;
    const list = [...sizeList];
    list[index] = { ...list[index] }; // copy the item too
    list[index][name] = value;
    setSizeList(list);
  };

  const handleServiceRemove = (index) => {
    const list = [...sizeList];
    list.splice(index, 1);
    setSizeList(list);
  };

  const handleServiceAdd = () => {
    setSizeList([...sizeList, { service: "", colorList: [{ color: "", colorStocks: "" }] }]);
  };

  // color
  const handleColorChange = (e, index, innerIndex) => {
    const { name, value } = e.target;
    const list = [...sizeList];
    list[index].colorList[innerIndex][name] = value;
    setSizeList(list)
  };

  const handleColorRemove = (index) => {
    const list = [...colorList];
    list.splice(index, 1);
    setColorList(list);
  };

  const handleColorAdd = (index) => {
    const list = [...sizeList];
    list[index].colorList.push({ color: "", colorStocks: "" });
    setSizeList(list)
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    console.log("Product: ", productName, "size: ", sizeList, colorList);
  };

  return (
    <Box sx={{ minWidth: 120 }}>
      <form onSubmit={handleSubmit}>
        <TextField
          sx={{mb:2}}
          label="Product Name"
          name="name"
          type="text"
          id="productName"
          value={productName}
          onChange={(e) => setProductName(e.target.value)}
          required
        />

        {sizeList.map((singleSize, index) => (
          <div key={index}>
            <TextField
              label="Size"
              type="text"
              name={`size${index}`}
              id={`size${index}`}
              required
              value={singleSize.size}
              onChange={(e) => handleServiceChange(e, index)}
            />
            {singleSize.colorList.map((singleColor, innerIndex) => (
              <div key={index}>
                <TextField
                  label="color"
                  name="color"
                  type="text"
                  id="color"
                  required
                  value={singleColor.color}
                  onChange={(e) => handleColorChange(e, index, innerIndex)}
                />
                <TextField
                  label="Stocks"
                  name="colorStocks"
                  type="text"
                  id="colorStocks"
                  required
                  value={singleColor.colorStocks}
                  onChange={(e) => handleColorChange(e, index, innerIndex)}
                />
                {colorList.length !== 1 && (
                  <Button onClick={() => handleColorRemove(index)}>
                    Remove
                  </Button>
                )}
                <br />
                {colorList.length - 1 === index && (
                  <Button onClick={()=>handleColorAdd(index)}>Add Color</Button>
                )}
                <br /> <br />
                {/* add or remove sizes */}
              </div>
            ))}
            {sizeList.length - 1 === index && (
              <Button type="button" onClick={handleServiceAdd}>
                Add size
              </Button>
            )}
            {sizeList.length - 1 === index && (
              <Button type="button" onClick={() => handleServiceRemove(index)}>
                Remove Size
              </Button>
            )}
          </div>
        ))}

        <br />
        <Button type="submit">Submit </Button>
      </form>

      <div className="output">
        <h2>Output</h2>
        <h3>Sizes:</h3>
        {sizeList &&
          sizeList.map((singleSize, index) => (
            <ul key={index}>{singleSize.size && <li>{singleSize.size}</li>}</ul>
          ))}

        <br />
        <h3>Color:</h3>
        {colorList &&
          colorList.map((singleSize, index) => (
            <ul key={index}>
              {singleSize.color && (
                <li>{singleSize.color + " - " + singleSize.colorStocks}</li>
              )}
            </ul>
          ))}
      </div>
    </Box>
  );
}


来源: stackexchange

问:
Adding Content to Select Pages of an HTML Site without Editing the pages
A site done completely in HTML now needs to have some content added to some pages. Editing the HTML is not an option. The HTML is consistent between pages. The displayed URL should be the same as before.

So far I've come up with the following strategy:

Handle the HTML pages as PHP by adding the requisite directive to .htaccess

AddType application/x-httpd-php .html .htm

Use mod_rewrite directives to send requests to a PHP script. I cannot work out what to do in this step.

PHP script will have a list of pages that need the content added and will add it based on conditions. How would I handle the input from the htaccess file to begin with? And are my thoughts of using fopen and preg through the HTML and adding the content in the required position the way to go?

To be clear, I'm asking whether my strategy will work and for help in going through with it and also asking if there is a better way of doing this.

Before anybody asks, the application of this is somewhat controversial and the client is well aware of it.

答:
1. No need for that, at all.

2. With this sort of rule you can rewrite (internal redirect) ALL requests for .html and .htm files to a single .php file that will take the original .html file name as a parameter:

```<code>Options +FollowSymLinks -MultiViews
RewriteEngine On
RewriteBase /

# the actual rewrite rule
RewriteRule ^.+\.html?$ /handler.php?url=%{REQUEST_URI} [L]
</code>```

This rule is intended to be placed in .htaccess file in website root folder. If placed elsewhere some small tweaking may be required.

3. How you going to handle this inside such php file is up to you. But yes -- it is possible to do what you want although it is not a trivial task.

In your php script use $_GET['url'] to access original URL (or $_SERVER['REQUEST_URI']).

fopen() should be fine, but I do not really recommend using preg() (it actually depends on what you are trying to do). In any case -- look at DOM HTML manipulation routines -- it can be safer/faster.

ContentLicense: CC BY-SA 3.0

Body:
1. No need for that, at all.

2. With this sort of rule you can rewrite (internal redirect) ALL requests for .html and .htm files to a single .php file that will take the original .html file name as a parameter:

Options +FollowSymLinks -MultiViews
RewriteEngine On
RewriteBase /

# the actual rewrite rule
RewriteRule ^.+\.html?$ /handler.php?url=%{REQUEST_URI} [L]

This rule is intended to be placed in .htaccess file in website root folder. If placed elsewhere some small tweaking may be required.

3. How you going to handle this inside such php file is up to you. But yes -- it is possible to do what you want although it is not a trivial task.

In your php script use $_GET['url'] to access original URL (or $_SERVER['REQUEST_URI']).

fopen() should be fine, but I do not really recommend using preg() (it actually depends on what you are trying to do). In any case -- look at DOM HTML manipulation routines -- it can be safer/faster.


问:
The same class name in two different css files conflict in ReactJS
I have a component folder and two different components in it, every component has its own css file with the link in its jsx file.
:

when I use a the same class name in them it affects the other component too! While the other component has its own css file and link.
Why is that?

For example:
In both components I have a class named: "PlayerPhoto"
when I change its height and width, the photo in other components (with separate css file but the same class name) would change too!

答:
It happens because your css is imported simply as normal css - without unique identificator. You need to specify classes with unique names or have a look at Css Modules which solve this problem and creating unique classes automatically

Or you can use libraries as EmotionJS or styled-components

ContentLicense: CC BY-SA 4.0


问:
Engineering external implementation of application behavior
I want to do the following behavior in one delphi application.(10.3+)

I want a user to have the possibility to implement his own logical behavior of a program "saved in options".

Very similar with an arduino logical/program.

For example

I create a program that is keep tracking values about 10 heat sensors. But it can be anything.

The program has a timer and in the on timer event the following actions are taking places.

read the values from sensors

take action if needed

there are 2 types of info saved in this class.

Non Changing informations like ID name etc, and permanent changing (DATA).

here is the example of the base class that hold all the info from one sensor.

```<code>type TXXX = class
  private
  public
    // info that are not changing ever
    property ID                         : Integer ...
    property SENSOR_NAME : String   ...
// info that are constantly changing
    property READ_TIMESTAMP : TDateTime ...
    property CURRENT_VALUE   : Double ...
    property VALUE_SUPREMUM  : Double    ...
    property VALUE_INFIMUM       : Double   ...
end
</code>```

I need to create some sort of options of the program when a user can define his own logical that the program should respond if condition are meet.

for example a user want to say:

```<code>if CURRENT_VALUE > 5 and  VALUE_INFIMUM > 0.5 then begin
  "take action 1"
end
</code>```

and so on...

"take action x" and all the actions are hardcoded. for example close/open a valve.

now these properties are more than 4 are like 50 or so.

anyone can point me some directions?

Regards

Razvan

答:
There are 2 ways how you can solve your problem.

1st: You can use some of scripting engines. That’s the direct purpose of this components. You can use something like Pascal Script For Delphi (https://www.remobjects.com/ps.aspx), Fast script (https://www.fast-report.com/en/product/fast-script/), TMS Scripter (https://www.tmssoftware.com/site/scriptstudiopro.asp), etc.

2nd: If you have limited actions and condition – you can write your own parser and GUI for it for handle all this staff.
Make expressions parser, declare operants (numbers or allowed properties of your sensors, or other expression), declare mathematical operations (plus, mines...) and logical operation (Lower, higer, equal, and, not, or). It's can take a while to implement it, but you can build very user-friendly wizard to manage it.

Body:
I want to do the following behavior in one delphi application.(10.3+)

I want a user to have the possibility to implement his own logical behavior of a program "saved in options".

Very similar with an arduino logical/program.

For example

I create a program that is keep tracking values about 10 heat sensors. But it can be anything.

The program has a timer and in the on timer event the following actions are taking places.

read the values from sensors

take action if needed

there are 2 types of info saved in this class.

Non Changing informations like ID name etc, and permanent changing (DATA).

here is the example of the base class that hold all the info from one sensor.

type TXXX = class
  private
  public
    // info that are not changing ever
    property ID                         : Integer ...
    property SENSOR_NAME : String   ...
// info that are constantly changing
    property READ_TIMESTAMP : TDateTime ...
    property CURRENT_VALUE   : Double ...
    property VALUE_SUPREMUM  : Double    ...
    property VALUE_INFIMUM       : Double   ...
end

I need to create some sort of options of the program when a user can define his own logical that the program should respond if condition are meet.

for example a user want to say:

if CURRENT_VALUE > 5 and  VALUE_INFIMUM > 0.5 then begin
  "take action 1"
end

and so on...

"take action x" and all the actions are hardcoded. for example close/open a valve.

now these properties are more than 4 are like 50 or so.

anyone can point me some directions?

Regards

Razvan


问:
How to implement multithreading with a return value?
I have been working on a calculator app in Java and I want to implement multithreading for this. I want to start a second thread, to calculate the answer for the given input. The only problem is, the calculation has to return a value and that value need to get displayed, but I don't know how to handle that. (I know its kind of useless to implement multithreading because the calculation doesn't even take a second, but I want to do it as practice and see if its possible)

Here you can see the code for which I want to start a second thread for:

```<code>public String calculate() {
//The input (StringBuilder) gets converted to an ArrayList
        String[] tmpArray = inputAsText.toString().split(" ");
        inputAsArrayList = new ArrayList(Arrays.asList(tmpArray));

//Other functions are called to perform calculations on
        inputAsArrayList = calculateFor("x", "÷");
        inputAsArrayList = calculateFor("+", "-");

//The answer gets retrieved from the arrarList and returned as a String
        String answer = String.valueOf(inputAsArrayList.get(0));
        clearInput();
        return answer;
    }
</code>```

答:
There are two ways to deal with results from asynchronous code:

Wait for the response to become available. This makes the results become available in the current thread.

Use some kind of callback mechanism. The results are still not available in the current thread.

The waiting can be done using Future and one of its get methods. For callbacks, I prefer CompletableFuture, with methods like thenAccept. You can even easily hook it into something like the Swing/AWT Event Dispatcher:

```<code>future.thenAcceptAsync(action, EventQueue::invokeLater);
</code>```

This works because the second argument needs to be an Executor, which is a functional interface with one method that takes a Runnable and returns nothing. That's exactly what EventQueue.invokeLater is.

Body:
I have been working on a calculator app in Java and I want to implement multithreading for this. I want to start a second thread, to calculate the answer for the given input. The only problem is, the calculation has to return a value and that value need to get displayed, but I don't know how to handle that. (I know its kind of useless to implement multithreading because the calculation doesn't even take a second, but I want to do it as practice and see if its possible)

Here you can see the code for which I want to start a second thread for:

public String calculate() {
//The input (StringBuilder) gets converted to an ArrayList
        String[] tmpArray = inputAsText.toString().split(" ");
        inputAsArrayList = new ArrayList(Arrays.asList(tmpArray));

//Other functions are called to perform calculations on
        inputAsArrayList = calculateFor("x", "÷");
        inputAsArrayList = calculateFor("+", "-");

//The answer gets retrieved from the arrarList and returned as a String
        String answer = String.valueOf(inputAsArrayList.get(0));
        clearInput();
        return answer;
    }

Body:
There are two ways to deal with results from asynchronous code:

Wait for the response to become available. This makes the results become available in the current thread.

Use some kind of callback mechanism. The results are still not available in the current thread.

The waiting can be done using Future and one of its get methods. For callbacks, I prefer CompletableFuture, with methods like thenAccept. You can even easily hook it into something like the Swing/AWT Event Dispatcher:

future.thenAcceptAsync(action, EventQueue::invokeLater);

This works because the second argument needs to be an Executor, which is a functional interface with one method that takes a Runnable and returns nothing. That's exactly what EventQueue.invokeLater is.


问:
Usage of Semaphores in Python
I am trying to use a Semaphore in Python to block the execution of a Thread, and release the Semaphore in another Thread depending on some conditions (in my case receiving some content over tcp).

But it is not working, my main Thread is not blocked like I though it would. My minimal example:

```<code>import time
from threading import Thread, Semaphore

class ServerManager():
  sem = Semaphore()

  def run(self):
    time.sleep(15)
    self.sem.release()

manager = ServerManager()
thread = Thread(target = manager.run)
thread.start()

manager.sem.acquire()
print("I am here immediately but should not")
</code>```

The message is printed immediately in the console but should only be printed after 15 seconds in my example. I'm sure I did something horribly wrong, but what?

答:
The answer from Tim Roberts is right.I read the Python doc, but I did not understand it. I thought (wrongly) that the default value had the behavior I wanted. The full code is:

I should do:

```<code>import time
from threading import Thread, Semaphore

class ServerManager():
  sem = Semaphore(0)

  def run(self):
    time.sleep(15)
    self.sem.release()

manager = ServerManager()
thread = Thread(target = manager.run)
thread.start()

manager.sem.acquire()
print("I am here immediately but should not")
</code>```

The message is printed after 15 seconds.

Title: Usage of Semaphores in Python

Body:
I am trying to use a Semaphore in Python to block the execution of a Thread, and release the Semaphore in another Thread depending on some conditions (in my case receiving some content over tcp).

But it is not working, my main Thread is not blocked like I though it would. My minimal example:

import time
from threading import Thread, Semaphore

class ServerManager():
  sem = Semaphore()

  def run(self):
    time.sleep(15)
    self.sem.release()

manager = ServerManager()
thread = Thread(target = manager.run)
thread.start()

manager.sem.acquire()
print("I am here immediately but should not")

The message is printed immediately in the console but should only be printed after 15 seconds in my example. I'm sure I did something horribly wrong, but what?

Body:
The answer from Tim Roberts is right.I read the Python doc, but I did not understand it. I thought (wrongly) that the default value had the behavior I wanted. The full code is:

I should do:

import time
from threading import Thread, Semaphore

class ServerManager():
  sem = Semaphore(0)

  def run(self):
    time.sleep(15)
    self.sem.release()

manager = ServerManager()
thread = Thread(target = manager.run)
thread.start()

manager.sem.acquire()
print("I am here immediately but should not")

The message is printed after 15 seconds.


问:
How to underline two div's consecutively?
I've got 2
s that each gather their text from some JS that I've written.
But I want the end-result to look like in the following image. And I can't figure out how to do that.

I can consolidate them into a single  but then I have the issue of needing to apply two different weights to a single
, which also wracks my brain.

So basically I want text with 2 different font-weights to be underlined with no interruption.

I've tried the following, and a lot of googling:

```<code>div.parentDiv {
    text-decoration-line : underline;
}
</code>```

答:
Is this what you are after?

div {
  font-weight: 700;
  text-decoration: underline;
}

div span {
  font-weight: 400;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  Good Reviews
  <span>(30)</span>
</div></code>```

Its hard to know with your current question, could you add your HTML and JS so we can see the whole example.

Body:
I've got 2
s that each gather their text from some JS that I've written.
But I want the end-result to look like in the following image. And I can't figure out how to do that.

I can consolidate them into a single  but then I have the issue of needing to apply two different weights to a single
, which also wracks my brain.

So basically I want text with 2 different font-weights to be underlined with no interruption.

I've tried the following, and a lot of googling:

div.parentDiv {
    text-decoration-line : underline;
}

Body:
Is this what you are after?

div {
  font-weight: 700;
  text-decoration: underline;
}

div span {
  font-weight: 400;
}

<div>
  Good Reviews
  <span>(30)</span>
</div>

Its hard to know with your current question, could you add your HTML and JS so we can see the whole example.


问:
In C# string how to replace two chararacters ignoring a number
I am editing a serialized string becuase when deserilized it gives a parse error.
so from a long Serialized string I want to edit "myVar\": \"0.2 mm" with "myVar\": \"0.2"
if I use the follwoing code it works

```<code>string NewString = Serializedstring.Replace($"myVar\": \"0.2 mm", $"myVar\": \"0.2")
</code>```

but my 0.2 is a varible that may change with every occurance. so all I want is to remove mm from the string "myVar\": \"0.2 mm"

答:
There are lots of ways to do this, RegEx, String tokenisation, char array searching

RegEx is probably the closest to what you are currently doing
the Regular expression syntax is described here Basics of RegEx

the pattern [0-9.]+ should match an decimal number but be warned it will also match anything that inclues numbers and dots such as ip addresses
so if you have a regex of

```<code>Regex rx = new Regex(@"([0-9.]+) mm")
<your string> = rx.Replace(<Your string>, @"$1");
</code>```

the details are :

[0-9.] any number or dot

+ one or more of what ever preceded it

() a group that is of special interest

$1 the number of the group that you want to replace the match with
note $0 is the entire input string

this will replace any string that is (number) mm with just the value of the number

Body:
I am editing a serialized string becuase when deserilized it gives a parse error.
so from a long Serialized string I want to edit "myVar\": \"0.2 mm" with "myVar\": \"0.2"
if I use the follwoing code it works

string NewString = Serializedstring.Replace($"myVar\": \"0.2 mm", $"myVar\": \"0.2")

but my 0.2 is a varible that may change with every occurance. so all I want is to remove mm from the string "myVar\": \"0.2 mm"

Body:
There are lots of ways to do this, RegEx, String tokenisation, char array searching

RegEx is probably the closest to what you are currently doing
the Regular expression syntax is described here Basics of RegEx

the pattern [0-9.]+ should match an decimal number but be warned it will also match anything that inclues numbers and dots such as ip addresses
so if you have a regex of

Regex rx = new Regex(@"([0-9.]+) mm")
<your string> = rx.Replace(<Your string>, @"$1");

the details are :

[0-9.] any number or dot

+ one or more of what ever preceded it

() a group that is of special interest

$1 the number of the group that you want to replace the match with
note $0 is the entire input string

this will replace any string that is (number) mm with just the value of the number


问:
How to add JSON objects to array state in functional component in react.js
I need to keep all of the information that came from axios in the form of JSON in the state while using the map method.

The problem is when I use the map method after the axios request, it just adds the last JSON to the state, but I have 9 objects in my JSON

```<code>const [expensesData , setExpensesData] = useState([])

useEffect(() => {
    axios.get('API-address')
    .then(res => {
        res.data.map( info => {
            setExpensesData(
                [
                    ...expensesData,
                    {info}
                ]
            )
        })
    })
    .catch(e => console.log(e))
} , [])
</code>```

答:
Last line will improve your application performance you application
It will render method called when your expensesData</p>
```<code>    const [expensesData , setExpensesData] = useState([])

    useEffect(() => {
        axios.get('API-address')
        .then(res => {
            setExpensesData(res.data);
        })
        .catch(e => console.log(e))
    },[expensesData])
</code>```

Body:
I need to keep all of the information that came from axios in the form of JSON in the state while using the map method.

The problem is when I use the map method after the axios request, it just adds the last JSON to the state, but I have 9 objects in my JSON

const [expensesData , setExpensesData] = useState([])

useEffect(() => {
    axios.get('API-address')
    .then(res => {
        res.data.map( info => {
            setExpensesData(
                [
                    ...expensesData,
                    {info}
                ]
            )
        })
    })
    .catch(e => console.log(e))
} , [])

Body:
Last line will improve your application performance you application
It will render method called when your expensesData

    const [expensesData , setExpensesData] = useState([])

    useEffect(() => {
        axios.get('API-address')
        .then(res => {
            setExpensesData(res.data);
        })
        .catch(e => console.log(e))
    },[expensesData])


问:
Getting 300k data from mongodb
I need to get 300k data with NodeJS from the database and pass it to the client(HTML side) for reporting and virtual scroll. I started with MySQL and it was taking around 14 seconds (2 tables joined). Since I'd like to speed up, I changed it to MongoDB but it takes around 31.2 seconds in one collection without any joining with the native MongoDB npm package.

NodeJS MongoDB source code

```<code>  const { MongoClient } = require('mongodb');
  .
  .
  .
  const db = client.db(dbName);
  const collection = db.collection('test');
  const startTime = performance.now()

  const findResult = await collection.find({}).toArray();
  const endTime = performance.now();
  console.log(`Time elapsed: ${endTime - startTime} milliseconds`);
  console.log('Found documents 1st element =>', findResult[0]);
</code>```

I'd assume MongoDB was going to take less time versus MySql but I guess there is something wrong with my code (I also tried fastify-mongodb, fast-json-stringify, streaming but none of them could not speed up ). What do you suggest? Because I researched lots of papers and most of the people gets +3m data around 10seconds and I know MongoDB is a good choice for big data even my data is not big enough :)

答:
In general mongoDB is good in multiple small single document reads based on indexes(already in memory) , this is coming from the fact that the data is allocated on storage in random 32k compressed blocks and it is not written sequentially , so in case you read the full collection there will be multiple IOPS operations to your storage that turns out to be the bottleneck for sequential reads in your case. If you immediately  try to read the same collection second time you will find that the read is much more faster since the documents are already cached in memory and OS fs cache. To improve this performance for bigger volumes you may shard the collection and distribute the data in multiple shards so it use less IOPS per individual shard when fetching the full collection. Btw by 300k data you mean 300k documents or total size of collection is 300k bytes since 31 seconds is huge amount of time , maybe documents are relatively big in this 300k collection or you have some infrastructure issue?
(300000 x 16)/(1024*1024) = ~ 4,5TB max  , how big is your collection?
FileSystem? Storage ?

Testing in my machine it seems there is no issue in mongo but in the stages after you fetch the data:

```<code> db.collection.find({}).explain("executionStats")
    "executionStats" : {
    "nReturned" : 300000,
    "executionTimeMillis" : 174,
    "totalKeysExamined" : 0,
    "totalDocsExamined" : 300000
</code>```

Some interesting results:

```<code>  mongos> var a=new Date().getTime();var doc=db.collection.find({});var b=new Date().getTime();var doc2=doc.toArray();var c=new Date().getTime();printjson(doc2);d=new Date().getTime();var ba=b-a,cb=c-b,dc=d-c;print("find:"+ba+"ms  toArray:"+cb+"ms  printjson(doc2):"+dc+"ms");
</code>```

doc=find({}):             0ms

doc2=doc.toArray():    3296ms

printjson(doc2):      67122ms

Something that you may try:

Increase the cursor batch size :
var doc=db.collection.find({}).batchSize(3000000)
( In my tests higher batch sizes provided 2-3 times better execution times )

Use eachAsync paralelized , check here
( havent check that , but you may try )

Title: Getting 300k data from mongodb

Body:
I need to get 300k data with NodeJS from the database and pass it to the client(HTML side) for reporting and virtual scroll. I started with MySQL and it was taking around 14 seconds (2 tables joined). Since I'd like to speed up, I changed it to MongoDB but it takes around 31.2 seconds in one collection without any joining with the native MongoDB npm package.

NodeJS MongoDB source code

  const { MongoClient } = require('mongodb');
  .
  .
  .
  const db = client.db(dbName);
  const collection = db.collection('test');
  const startTime = performance.now()

  const findResult = await collection.find({}).toArray();
  const endTime = performance.now();
  console.log(`Time elapsed: ${endTime - startTime} milliseconds`);
  console.log('Found documents 1st element =>', findResult[0]);

I'd assume MongoDB was going to take less time versus MySql but I guess there is something wrong with my code (I also tried fastify-mongodb, fast-json-stringify, streaming but none of them could not speed up ). What do you suggest? Because I researched lots of papers and most of the people gets +3m data around 10seconds and I know MongoDB is a good choice for big data even my data is not big enough :)

Body:
In general mongoDB is good in multiple small single document reads based on indexes(already in memory) , this is coming from the fact that the data is allocated on storage in random 32k compressed blocks and it is not written sequentially , so in case you read the full collection there will be multiple IOPS operations to your storage that turns out to be the bottleneck for sequential reads in your case. If you immediately  try to read the same collection second time you will find that the read is much more faster since the documents are already cached in memory and OS fs cache. To improve this performance for bigger volumes you may shard the collection and distribute the data in multiple shards so it use less IOPS per individual shard when fetching the full collection. Btw by 300k data you mean 300k documents or total size of collection is 300k bytes since 31 seconds is huge amount of time , maybe documents are relatively big in this 300k collection or you have some infrastructure issue?
(300000 x 16)/(1024*1024) = ~ 4,5TB max  , how big is your collection?
FileSystem? Storage ?

Testing in my machine it seems there is no issue in mongo but in the stages after you fetch the data:

 db.collection.find({}).explain("executionStats")
    "executionStats" : {
    "nReturned" : 300000,
    "executionTimeMillis" : 174,
    "totalKeysExamined" : 0,
    "totalDocsExamined" : 300000

Some interesting results:

  mongos> var a=new Date().getTime();var doc=db.collection.find({});var b=new Date().getTime();var doc2=doc.toArray();var c=new Date().getTime();printjson(doc2);d=new Date().getTime();var ba=b-a,cb=c-b,dc=d-c;print("find:"+ba+"ms  toArray:"+cb+"ms  printjson(doc2):"+dc+"ms");

doc=find({}):             0ms

doc2=doc.toArray():    3296ms

printjson(doc2):      67122ms

Something that you may try:

Increase the cursor batch size :
var doc=db.collection.find({}).batchSize(3000000)
( In my tests higher batch sizes provided 2-3 times better execution times )

Use eachAsync paralelized , check here
( havent check that , but you may try )


问:
enzyme react component test throws window.requestAnimationFrame TypeError
I'm trying to put our SPFx React Components under test.

We're using following technologies:

spfx 1.13.1

react 16.13.1

jest 27.4.7

enzyme 3.11.0

typescript 4.2.4

fabric-ui: 1.13.1

I am stuck on following error when running a simple test using enzym.mount.

```<code>TypeError: window.requestAnimationFrame is not a function

  at Stylesheet.Object.<anonymous>.Stylesheet._getStyleElement (node_modules/@uifabric/merge-styles/src/Stylesheet.ts:295:16)
  at Stylesheet.Object.<anonymous>.Stylesheet.insertRule (node_modules/@uifabric/merge-styles/src/Stylesheet.ts:227:65)
  at applyRegistration (node_modules/@uifabric/merge-styles/src/styleToClassName.ts:284:20)
  at Object.styleToClassName (node_modules/@uifabric/merge-styles/src/styleToClassName.ts:294:5)
  at mergeCss (node_modules/@uifabric/merge-styles/src/mergeStyles.ts:30:18)
  at Object.mergeStyles (node_modules/@uifabric/merge-styles/src/mergeStyles.ts:13:10)
  at Object.<anonymous> (node_modules/@uifabric/utilities/src/scroll.ts:9:33)
</code>```

Based on various other answers (here, here), I tried to play around with following code

```<code>global.requestAnimationFrame = function (callback) {
    return setTimeout(callback, 0);
};
</code>```

placing it at top of my test code, inside the describe and in a separate test-init file.

I also tried to use ras/polyfill but without any change in the error.

Any help in moving me forward to a working solution?

test file.

```<code>/// <reference types="jest" />

import * as React from 'react';
import { configure, mount, ReactWrapper, shallow } from 'enzyme';
import * as Adapter from 'enzyme-adapter-react-16';
import "jsdom-global/register";

import MyComponent, { IMyComponentProps, IMyComponentState } from './my-component';

// import { polyfill } from 'raf';
// polyfill();

// global.requestAnimationFrame = function (callback) {
//     return setTimeout(callback, 0);
// };

configure({ adapter: new Adapter() });

describe('<MyComponent/>', () => {
    let renderedElement: ReactWrapper<IMyComponentProps, IMyComponentState>;

    beforeEach(() => {
        renderedElement = mount(<MyComponent/>);
    });

    afterEach(() => {
        renderedElement.unmount();
    });

    it('load my component', () => {
        expect(renderedElement).toBeTruthy();
    });

});
</code>```

component controls

```<code><TextField name='abc' label="" defaultValue={state.abc} onChange={_handleChange} />
<Dropdown label='xyz' placeholder='Select xyz' options={options} defaultSelectedKey={state.xyz} onChange={(e, i) => _handleChangeDropdown(e, i, 'xyz')} />
</code>```

package.json file

```<code>  ...
  "devDependencies": {
    "@microsoft/microsoft-graph-types": "^2.11.0",
    "@microsoft/rush-stack-compiler-4.2": "0.1.1",
    "@microsoft/sp-build-web": "1.13.1",
    "@microsoft/sp-module-interfaces": "1.13.1",
    "@types/enzyme": "^3.10.11",
    "@types/jest": "^27.4.0",
    "@types/node": "^17.0.10",
    "@types/react": "17.0.38",
    "@types/react-dom": "17.0.11",
    "@types/react-router-dom": "^5.3.2",
    "@types/webpack-env": "1.16.3",
    "@typescript-eslint/eslint-plugin": "^5.9.1",
    "@typescript-eslint/parser": "^5.9.1",
    "ajv": "~8.8.2",
    "enzyme": "^3.11.0",
    "enzyme-adapter-react-16": "^1.15.6",
    "eslint": "^8.6.0",
    "eslint-config-react-app": "^7.0.0",
    "eslint-plugin-react": "^7.28.0",
    "gulp": "~4.0.2",
    "gulp-eslint-new": "^1.1.1",
    "identity-obj-proxy": "^3.0.0",
    "jest": "^27.4.7",
    "jest-junit": "^13.0.0",
    "jsdom": "^19.0.0",
    "jsdom-global": "^3.0.2",
    "raf": "^3.4.1",
    "react-test-renderer": "^17.0.2",
    "spfx-fast-serve-helpers": "~1.13.0",
    "ts-jest": "^27.1.3",
    "typescript": "4.2.4"
},
"jest": {
    "moduleFileExtensions": [
        "ts",
        "tsx",
        "js"
    ],
    "moduleDirectories": [
        "node_modules"
    ],
    "moduleNameMapper": {
        "\\.(css|less|scss|sass)$": "identity-obj-proxy",
        "office-ui-fabric-react/lib/(.*)$": "office-ui-fabric-react/lib-commonjs/$1",
        "^@mywebpart/(.*)": "<rootDir>/src/webparts/mywebpart/$1",
        "^@shared/(.*)": "<rootDir>/src/shared/$1"
    },
    "transform": {
        "^.+\\.(ts|tsx)$": "ts-jest"
    },
    "testMatch": [
        "**/src/**/*.tests.+(ts|tsx)"
    ],
    "setupFiles": [
        "<rootDir>/src/webparts/mywebpart/tests/tests-setup.ts"
    ],
    "collectCoverage": true,
    "coverageReporters": [
        "json",
        "lcov",
        "text",
        "cobertura"
    ],
    "coverageDirectory": "<rootDir>/test-results",
    "reporters": [
        "default",
        "jest-junit"
    ],
    "coverageThreshold": {
        "global": {
            "branches": 60,
            "functions": 60,
            "lines": 60,
            "statements": 60
        }
    }
},
"jest-junit": {
    "output": "./test-results/summary-jest-junit.xml"
}
</code>```

tsconfig.json file

```<code>{
  "extends": "./node_modules/@microsoft/rush-stack-compiler-4.2/includes/tsconfig-web.json",
  "compilerOptions": {
    "target": "es5",
    "forceConsistentCasingInFileNames": true,
    "module": "esnext",
    "moduleResolution": "node",
    "jsx": "react",
    "declaration": true,
    "sourceMap": true,
    "experimentalDecorators": true,
    "skipLibCheck": true,
    "outDir": "lib",
    "inlineSources": false,
    "strictNullChecks": false,
    "noUnusedLocals": false,
    "allowSyntheticDefaultImports": true,
    "resolveJsonModule": true,
    "typeRoots": [
      "./node_modules/@types",
      "./node_modules/@microsoft"
    ],
    "types": [
      "webpack-env",
      "jest",
      "node"
    ],
    "lib": [
      "es6",
      "dom",
      "es2015.collection",
      "es2015.promise"
    ],
    "baseUrl": "src",
    "paths": {
      "@mywebpart/*": [
        "webparts/mywebpart/*"
      ],
      "@shared/*": [
        "shared/*"
      ]
    }
  },
  "include": [
    "src/**/*.ts",
    "src/**/*.tsx"
  ]
}
</code>```

答:
I was able to solve the issue, though I'm not 100% sure I can follow the flow.

I created a tests setup file configured with jest.

```<code>    "setupFiles": [
        "<rootDir>/src/webparts/my-part/tests/tests-setup.ts"
    ],
</code>```

File content.

```<code>/// <reference types="jest" />

import "jsdom-global/register";
// Polyfill requestAnimiationFrame
import "raf/polyfill";

import { configure } from 'enzyme';
import * as Adapter from 'enzyme-adapter-react-16';
import { setIconOptions } from "office-ui-fabric-react/lib/Styling";

// Suppress icon warnings.
setIconOptions({
    disableWarnings: true
});

// Fail on warnings.
const consoleError = console.error;
console.error = console.warn = (message) => {
    // Ignore error boundary warnings so that tests which throw exceptions can be validated.
    if (message.indexOf('error boundary') >= 0) {
        return;
    }

    consoleError(message);
    throw new Error("Caught: " + message);
};

// configure enzyme adapter
configure({ adapter: new Adapter() });
</code>```

Body:
I'm trying to put our SPFx React Components under test.

We're using following technologies:

spfx 1.13.1

react 16.13.1

jest 27.4.7

enzyme 3.11.0

typescript 4.2.4

fabric-ui: 1.13.1

I am stuck on following error when running a simple test using enzym.mount.

TypeError: window.requestAnimationFrame is not a function

  at Stylesheet.Object.<anonymous>.Stylesheet._getStyleElement (node_modules/@uifabric/merge-styles/src/Stylesheet.ts:295:16)
  at Stylesheet.Object.<anonymous>.Stylesheet.insertRule (node_modules/@uifabric/merge-styles/src/Stylesheet.ts:227:65)
  at applyRegistration (node_modules/@uifabric/merge-styles/src/styleToClassName.ts:284:20)
  at Object.styleToClassName (node_modules/@uifabric/merge-styles/src/styleToClassName.ts:294:5)
  at mergeCss (node_modules/@uifabric/merge-styles/src/mergeStyles.ts:30:18)
  at Object.mergeStyles (node_modules/@uifabric/merge-styles/src/mergeStyles.ts:13:10)
  at Object.<anonymous> (node_modules/@uifabric/utilities/src/scroll.ts:9:33)

Based on various other answers (here, here), I tried to play around with following code

global.requestAnimationFrame = function (callback) {
    return setTimeout(callback, 0);
};

placing it at top of my test code, inside the describe and in a separate test-init file.

I also tried to use ras/polyfill but without any change in the error.

Any help in moving me forward to a working solution?

test file.

/// <reference types="jest" />

import * as React from 'react';
import { configure, mount, ReactWrapper, shallow } from 'enzyme';
import * as Adapter from 'enzyme-adapter-react-16';
import "jsdom-global/register";

import MyComponent, { IMyComponentProps, IMyComponentState } from './my-component';

// import { polyfill } from 'raf';
// polyfill();

// global.requestAnimationFrame = function (callback) {
//     return setTimeout(callback, 0);
// };

configure({ adapter: new Adapter() });

describe('<MyComponent/>', () => {
    let renderedElement: ReactWrapper<IMyComponentProps, IMyComponentState>;

    beforeEach(() => {
        renderedElement = mount(<MyComponent/>);
    });

    afterEach(() => {
        renderedElement.unmount();
    });

    it('load my component', () => {
        expect(renderedElement).toBeTruthy();
    });

});

component controls

<TextField name='abc' label="" defaultValue={state.abc} onChange={_handleChange} />
<Dropdown label='xyz' placeholder='Select xyz' options={options} defaultSelectedKey={state.xyz} onChange={(e, i) => _handleChangeDropdown(e, i, 'xyz')} />

package.json file

  ...
  "devDependencies": {
    "@microsoft/microsoft-graph-types": "^2.11.0",
    "@microsoft/rush-stack-compiler-4.2": "0.1.1",
    "@microsoft/sp-build-web": "1.13.1",
    "@microsoft/sp-module-interfaces": "1.13.1",
    "@types/enzyme": "^3.10.11",
    "@types/jest": "^27.4.0",
    "@types/node": "^17.0.10",
    "@types/react": "17.0.38",
    "@types/react-dom": "17.0.11",
    "@types/react-router-dom": "^5.3.2",
    "@types/webpack-env": "1.16.3",
    "@typescript-eslint/eslint-plugin": "^5.9.1",
    "@typescript-eslint/parser": "^5.9.1",
    "ajv": "~8.8.2",
    "enzyme": "^3.11.0",
    "enzyme-adapter-react-16": "^1.15.6",
    "eslint": "^8.6.0",
    "eslint-config-react-app": "^7.0.0",
    "eslint-plugin-react": "^7.28.0",
    "gulp": "~4.0.2",
    "gulp-eslint-new": "^1.1.1",
    "identity-obj-proxy": "^3.0.0",
    "jest": "^27.4.7",
    "jest-junit": "^13.0.0",
    "jsdom": "^19.0.0",
    "jsdom-global": "^3.0.2",
    "raf": "^3.4.1",
    "react-test-renderer": "^17.0.2",
    "spfx-fast-serve-helpers": "~1.13.0",
    "ts-jest": "^27.1.3",
    "typescript": "4.2.4"
},
"jest": {
    "moduleFileExtensions": [
        "ts",
        "tsx",
        "js"
    ],
    "moduleDirectories": [
        "node_modules"
    ],
    "moduleNameMapper": {
        "\\.(css|less|scss|sass)$": "identity-obj-proxy",
        "office-ui-fabric-react/lib/(.*)$": "office-ui-fabric-react/lib-commonjs/$1",
        "^@mywebpart/(.*)": "<rootDir>/src/webparts/mywebpart/$1",
        "^@shared/(.*)": "<rootDir>/src/shared/$1"
    },
    "transform": {
        "^.+\\.(ts|tsx)$": "ts-jest"
    },
    "testMatch": [
        "**/src/**/*.tests.+(ts|tsx)"
    ],
    "setupFiles": [
        "<rootDir>/src/webparts/mywebpart/tests/tests-setup.ts"
    ],
    "collectCoverage": true,
    "coverageReporters": [
        "json",
        "lcov",
        "text",
        "cobertura"
    ],
    "coverageDirectory": "<rootDir>/test-results",
    "reporters": [
        "default",
        "jest-junit"
    ],
    "coverageThreshold": {
        "global": {
            "branches": 60,
            "functions": 60,
            "lines": 60,
            "statements": 60
        }
    }
},
"jest-junit": {
    "output": "./test-results/summary-jest-junit.xml"
}

tsconfig.json file

{
  "extends": "./node_modules/@microsoft/rush-stack-compiler-4.2/includes/tsconfig-web.json",
  "compilerOptions": {
    "target": "es5",
    "forceConsistentCasingInFileNames": true,
    "module": "esnext",
    "moduleResolution": "node",
    "jsx": "react",
    "declaration": true,
    "sourceMap": true,
    "experimentalDecorators": true,
    "skipLibCheck": true,
    "outDir": "lib",
    "inlineSources": false,
    "strictNullChecks": false,
    "noUnusedLocals": false,
    "allowSyntheticDefaultImports": true,
    "resolveJsonModule": true,
    "typeRoots": [
      "./node_modules/@types",
      "./node_modules/@microsoft"
    ],
    "types": [
      "webpack-env",
      "jest",
      "node"
    ],
    "lib": [
      "es6",
      "dom",
      "es2015.collection",
      "es2015.promise"
    ],
    "baseUrl": "src",
    "paths": {
      "@mywebpart/*": [
        "webparts/mywebpart/*"
      ],
      "@shared/*": [
        "shared/*"
      ]
    }
  },
  "include": [
    "src/**/*.ts",
    "src/**/*.tsx"
  ]
}

Body:
I was able to solve the issue, though I'm not 100% sure I can follow the flow.

I created a tests setup file configured with jest.

    "setupFiles": [
        "<rootDir>/src/webparts/my-part/tests/tests-setup.ts"
    ],

File content.

/// <reference types="jest" />

import "jsdom-global/register";
// Polyfill requestAnimiationFrame
import "raf/polyfill";

import { configure } from 'enzyme';
import * as Adapter from 'enzyme-adapter-react-16';
import { setIconOptions } from "office-ui-fabric-react/lib/Styling";

// Suppress icon warnings.
setIconOptions({
    disableWarnings: true
});

// Fail on warnings.
const consoleError = console.error;
console.error = console.warn = (message) => {
    // Ignore error boundary warnings so that tests which throw exceptions can be validated.
    if (message.indexOf('error boundary') >= 0) {
        return;
    }

    consoleError(message);
    throw new Error("Caught: " + message);
};

// configure enzyme adapter
configure({ adapter: new Adapter() });


问:
huggingface return probability and class label Trainer.predict
Is there any way to return probabilities and actual class using Trainer.predict ?

I checked the documentation at this page but couldn't figure out. As of now it seems to be returning logits

Obviously both probabilities and actual class could be computed using additional coding but wondering if there is any prebuilt method to do the same

my current output as below

```<code>new_predictions=trainer.predict(dataset_for_future_predicition_after_tokenizer)

new_predictions

PredictionOutput(predictions=array([[-0.43005577,  3.646306  , -0.8073783 , -1.0651836 , -1.3480505 ,
        -1.108013  ],
       [ 3.5415223 , -0.8513837 , -1.8553216 , -0.18011567, -0.35627165,
        -1.8364134 ],
       [-1.0167522 , -0.8911268 , -1.7115675 ,  0.01204597,  1.7177908 ,
         1.0401527 ],
       [-0.82407415, -0.46043932, -1.089274  ,  2.6252217 ,  0.33935028,
        -1.3623345 ]], dtype=float32), label_ids=None, metrics={'test_runtime': 0.0182, 'test_samples_per_second': 219.931, 'test_steps_per_second': 54.983})
</code>```

答:
As you mentioned, Trainer.predict returns the output of the model prediction, which are the logits.

If you want to get the different labels and scores for each class, I recommend you to use the corresponding pipeline for your model depending on the task (TextClassification, TokenClassification, etc). This pipeline has a return_all_scores parameter on its __call__ method that allows you to get all scores for each label on a prediction.

Here's an example:

from transformers import TextClassificationPipeline, AutoTokenizer, AutoModelForSequenceClassification

MODEL_NAME = "..."
tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
model = AutoModelForSequenceClassification.from_pretrained(MODEL_NAME)

pipe = TextClassificationPipeline(model=model, tokenizer=tokenizer)
prediction = pipe("The text to predict", return_all_scores=True)
```
<p>This is an example of how this <code>prediction</code> variable will look like:</p>
```[{label: 'LABEL1', score: 0.80}, {label: 'LABEL2', score: 0.15}, {label: 'LABEL3', score: 0.05}]
```
<p>The label names can be set on the model's <code>config.json</code> file or when creating the model (before training it) by defining <code>id2label</code> and <code>label2id</code> model parameters:</p>
<pre class="lang-py prettyprint-override"><code>model = AutoModelForSequenceClassification.from_pretrained(
    MODEL_NAME,
    num_labels=num_labels,
    label2id={"Greeting": 0, "Help": 1, "Farewell": 2},
    id2label={0: "Greeting", 1: "Help", 2: "Farewell"},
)
</code>```

Body:
Is there any way to return probabilities and actual class using Trainer.predict ?

I checked the documentation at this page but couldn't figure out. As of now it seems to be returning logits

Obviously both probabilities and actual class could be computed using additional coding but wondering if there is any prebuilt method to do the same

my current output as below

new_predictions=trainer.predict(dataset_for_future_predicition_after_tokenizer)

new_predictions

PredictionOutput(predictions=array([[-0.43005577,  3.646306  , -0.8073783 , -1.0651836 , -1.3480505 ,
        -1.108013  ],
       [ 3.5415223 , -0.8513837 , -1.8553216 , -0.18011567, -0.35627165,
        -1.8364134 ],
       [-1.0167522 , -0.8911268 , -1.7115675 ,  0.01204597,  1.7177908 ,
         1.0401527 ],
       [-0.82407415, -0.46043932, -1.089274  ,  2.6252217 ,  0.33935028,
        -1.3623345 ]], dtype=float32), label_ids=None, metrics={'test_runtime': 0.0182, 'test_samples_per_second': 219.931, 'test_steps_per_second': 54.983})

Body:
As you mentioned, Trainer.predict returns the output of the model prediction, which are the logits.

If you want to get the different labels and scores for each class, I recommend you to use the corresponding pipeline for your model depending on the task (TextClassification, TokenClassification, etc). This pipeline has a return_all_scores parameter on its __call__ method that allows you to get all scores for each label on a prediction.

Here's an example:

from transformers import TextClassificationPipeline, AutoTokenizer, AutoModelForSequenceClassification

MODEL_NAME = "..."
tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
model = AutoModelForSequenceClassification.from_pretrained(MODEL_NAME)

pipe = TextClassificationPipeline(model=model, tokenizer=tokenizer)
prediction = pipe("The text to predict", return_all_scores=True)

This is an example of how this prediction variable will look like:

[{label: 'LABEL1', score: 0.80}, {label: 'LABEL2', score: 0.15}, {label: 'LABEL3', score: 0.05}]

The label names can be set on the model's config.json file or when creating the model (before training it) by defining id2label and label2id model parameters:

model = AutoModelForSequenceClassification.from_pretrained(
    MODEL_NAME,
    num_labels=num_labels,
    label2id={"Greeting": 0, "Help": 1, "Farewell": 2},
    id2label={0: "Greeting", 1: "Help", 2: "Farewell"},
)


问:
Hive and HQL: how do you format JSON strings to be sorted by keys
in Hive/HQL, how do you format JSON strings to be ordered by their keys? For example

id
some_str

1
{"b":1, "c":2, "a":0}

I want the output to be ordered by the json keys (i.e. a<b<c):

id
some_str

1
{"a":0, "b": 1, "c":2}

I know I might be able to use get_json_object and do some hard-coded formatting, but that would only work if I have only a few keys, but unfortunately that doesn't apply here.

What would you suggest? Thanks!!

Additional Q's:

How do I check equality of {"b":1, "c":2, "a":0} and {"a":0, "b": 1, "c":2}  (their equality should be True)?

How do I get the value of the largest/smallest key? i.e. expected results:

id
some_str

1
0

(smallest key = "a")

or

id
some_str

1
2

(largest key = "c")

答:
Hive does not support JSON data type, JSON can be parsed by JSONSerDe or get_json_object/json_tuple. If the data in your question were of type map, then it would be sortable/comparable based on keys/values. Strings are comparable as normal strings, no matter is it JSON is inside or not JSON.

Consider storing it as map<string,int> or map<string,string> type.
Also you can convert it to map using str_to_map function (returns map<string, string>) and regexp_replace to remove quotes, spaces, curly braces, then use IN operator to compare. See this demo:

```<code>with mydata as (
select '{"b":1, "c":2, "a":0}' as A, '{"a":0, "b": 1, "c":2}' as B

)

select A, B, A in (B), B in (A) from
(
select str_to_map(regexp_replace(regexp_replace(regexp_replace(A,': +',':'),', +',','),'"|\\{|\\}','')) A,
       str_to_map(regexp_replace(regexp_replace(regexp_replace(B,': +',':'),', +',','),'"|\\{|\\}','')) B
from mydata
)s
</code>```

Result:

```<code>a                          b                          a_equal_b b_equal_a
{"a":"0","b":"1","c":"2"}  {"a":"0","b":"1","c":"2"}  true      true
</code>```

Both maps are equal, note they are displayed in the same keys order (a<b<c). After conversion to map, you can order, compare and easily extract keys, values and convert values to int if necessary.

Also you can convert JSON string to map specifying types for key and value using brickhouse json_map function, without need to additionally transform JSON string using regexp_replace, this is the most efficient method:

```<code>json_map(' {"b":1, "c":2, "a":0}' as A, '{"a":0, "b": 1, "c":2}', 'string,int')
</code>```

Read how to install brickhouse functions here.

Body:
Hive does not support JSON data type, JSON can be parsed by JSONSerDe or get_json_object/json_tuple. If the data in your question were of type map, then it would be sortable/comparable based on keys/values. Strings are comparable as normal strings, no matter is it JSON is inside or not JSON.

Consider storing it as map<string,int> or map<string,string> type.
Also you can convert it to map using str_to_map function (returns map<string, string>) and regexp_replace to remove quotes, spaces, curly braces, then use IN operator to compare. See this demo:

with mydata as (
select '{"b":1, "c":2, "a":0}' as A, '{"a":0, "b": 1, "c":2}' as B

)

select A, B, A in (B), B in (A) from
(
select str_to_map(regexp_replace(regexp_replace(regexp_replace(A,': +',':'),', +',','),'"|\\{|\\}','')) A,
       str_to_map(regexp_replace(regexp_replace(regexp_replace(B,': +',':'),', +',','),'"|\\{|\\}','')) B
from mydata
)s

Result:

a                          b                          a_equal_b b_equal_a
{"a":"0","b":"1","c":"2"}  {"a":"0","b":"1","c":"2"}  true      true

Both maps are equal, note they are displayed in the same keys order (a<b<c). After conversion to map, you can order, compare and easily extract keys, values and convert values to int if necessary.

Also you can convert JSON string to map specifying types for key and value using brickhouse json_map function, without need to additionally transform JSON string using regexp_replace, this is the most efficient method:

json_map(' {"b":1, "c":2, "a":0}' as A, '{"a":0, "b": 1, "c":2}', 'string,int')

Read how to install brickhouse functions here.


问:
Can I have an Express middleware that runs after the router but before the route handler?
I want a generic middleware that can take the "req.route.path" value (e.g. "/foo/:id" and not the actual URL value "/foo/123") and return it on a HTTP response header called "X-ROUTE-NAME". The idea is for this route value to be recorded and logged by separate logging/metrics infrastructure and allow "group by" on the route name for other analysis purposes later.

Here's my first attempt:

```<code>app.use(function(req, res, next) {
  const {path} = req.route;
  console.log("The path was:", path);
  res.setHeader("X-ROUTE-NAME", req.route.path);
  next();
});
</code>```

It doesn't work because if you put it BEFORE you register routes, it doesn't have any value in req.route.path yet. But if you register it AFTER the routes, you get an exception when you try to set the header if a handler has already sent content on the req.

So yah, the tricky part is figuring out how to snatch the "req.route.path" value AFTER it's set by the router (and saving it to the response as a header), but BEFORE a handler picks it up (since the handler can send content if it wants to and then you wont be able to set headers anymore).

Any ideas?

答:
```<code>app.use(function(req, res, next) {
  const {path} = req.route;
  console.log("The path was:", path);

  next();
  res.setHeader("X-ROUTE-NAME", req.route.path);
});
</code>```

moving the setHeader should help

Body:
I want a generic middleware that can take the "req.route.path" value (e.g. "/foo/:id" and not the actual URL value "/foo/123") and return it on a HTTP response header called "X-ROUTE-NAME". The idea is for this route value to be recorded and logged by separate logging/metrics infrastructure and allow "group by" on the route name for other analysis purposes later.

Here's my first attempt:

app.use(function(req, res, next) {
  const {path} = req.route;
  console.log("The path was:", path);
  res.setHeader("X-ROUTE-NAME", req.route.path);
  next();
});

It doesn't work because if you put it BEFORE you register routes, it doesn't have any value in req.route.path yet. But if you register it AFTER the routes, you get an exception when you try to set the header if a handler has already sent content on the req.

So yah, the tricky part is figuring out how to snatch the "req.route.path" value AFTER it's set by the router (and saving it to the response as a header), but BEFORE a handler picks it up (since the handler can send content if it wants to and then you wont be able to set headers anymore).

Any ideas?

Body:
app.use(function(req, res, next) {
  const {path} = req.route;
  console.log("The path was:", path);

  next();
  res.setHeader("X-ROUTE-NAME", req.route.path);
});

moving the setHeader should help


问:
What is wrong with react-testing-library render function? It returns an error on certain objects
Using:     "@testing-library/react": "^9.1.4",

If I call:

render({component})

Where component is:

```<code>{ '$$typeof': Symbol(react.element),
        type:
         { mapStateToProps: [Function],
           mapDispatchToProps: [Function: mapDispatchToProps],
           reactComponent: { [Function: WithHandlers] displayName: 'withHandlers(lifecycle(Component))' },
           mockDispatch:
            { [Function: mockConstructor]
              _isMockFunction: true,
              getMockImplementation: [Function],
              mock: [Getter/Setter],
              mockClear: [Function],
              mockReset: [Function],
              mockReturnValueOnce: [Function],
              mockReturnValue: [Function],
              mockImplementationOnce: [Function],
              mockImplementation: [Function],
              mockReturnThis: [Function],
              mockRestore: [Function] } },
        key: null,
        ref: null,
        props: {},
        _owner: null,
        _store: {} }
</code>```

I get this error:

console.error node_modules/react/cjs/react.development.js:172
        Warning: React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite
  components) but got: object.

If I render this component there is no error:

```<code>{ '$$typeof': Symbol(react.element),
        type: [Function],
        key: null,
        ref: null,
        props: {},
        _owner: null,
        _store: {} }
</code>```

They both appear to be react.elements and https://testing-library.com/docs/react-testing-library/api implies this is what it expects.

What have I done wrong?

答:
I solved it by doing the following:

```<code>expect(() =>
        render(
            <MyFormModal
                recordDetailView={<MyFormEditView />}
                addRecord={(record: any) => addMyRecord(record)}
            />,
            {
                wrapper: () => <MyAppWrapperWithRedux store={store} />,
            }
        )
    ).not.toThrow();
</code>```

The render() function in RTL takes a second parameter where you can specify your wrapper that connects to the redux store. Ofcourse, this is assuming your issue was caused by a wrapping component, and that you are using redux.

Body:
Using:     "@testing-library/react": "^9.1.4",

If I call:

render({component})

Where component is:

{ '$$typeof': Symbol(react.element),
        type:
         { mapStateToProps: [Function],
           mapDispatchToProps: [Function: mapDispatchToProps],
           reactComponent: { [Function: WithHandlers] displayName: 'withHandlers(lifecycle(Component))' },
           mockDispatch:
            { [Function: mockConstructor]
              _isMockFunction: true,
              getMockImplementation: [Function],
              mock: [Getter/Setter],
              mockClear: [Function],
              mockReset: [Function],
              mockReturnValueOnce: [Function],
              mockReturnValue: [Function],
              mockImplementationOnce: [Function],
              mockImplementation: [Function],
              mockReturnThis: [Function],
              mockRestore: [Function] } },
        key: null,
        ref: null,
        props: {},
        _owner: null,
        _store: {} }

I get this error:

console.error node_modules/react/cjs/react.development.js:172
        Warning: React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite
  components) but got: object.

If I render this component there is no error:

{ '$$typeof': Symbol(react.element),
        type: [Function],
        key: null,
        ref: null,
        props: {},
        _owner: null,
        _store: {} }

They both appear to be react.elements and https://testing-library.com/docs/react-testing-library/api implies this is what it expects.

What have I done wrong?

Body:
I solved it by doing the following:

expect(() =>
        render(
            <MyFormModal
                recordDetailView={<MyFormEditView />}
                addRecord={(record: any) => addMyRecord(record)}
            />,
            {
                wrapper: () => <MyAppWrapperWithRedux store={store} />,
            }
        )
    ).not.toThrow();

The render() function in RTL takes a second parameter where you can specify your wrapper that connects to the redux store. Ofcourse, this is assuming your issue was caused by a wrapping component, and that you are using redux.


问:
Identify the matching range from a list of valid range
I am having a csv file , which contains a range of numbers in a column. I also have list of valid range. I need identify the possible range for the matching numbers in csv.

valid_range = ["0-1", "1-2", "0-5", "5-10", "10-15", "15-20", ">20","mixed"]

csv data :

What I have:

What I need:

Anything greater than 20 will have ">20" and mixed will have the same.

```<code>df = {'Gender': {0: 'male',
  1: 'male',
  2: 'male',
  3: 'female',
  4: 'male',
  5: 'male',
  6: 'male',
  7: 'male',
  8: 'male',
  9: 'mixed',
  10: 'female'},
 'Range': {0: 'mixed',
  1: 'mixed',
  2: '5-6',
  3: '4-5',
  4: '5-6',
  5: '12-14',
  6: '9-10',
  7: 'mixed',
  8: '17-18',
  9: 'mixed',
  10: '>20'}}
</code>```

答:
If you don't have overlap, you can rely on the upper bound.

Then use of a bit or regex magic and pandas.cut:

```<code># non overlapping ranges
valid_range = ["0-5", "5-10", "10-15", "15-20", ">20", "mixed"]

# define bins (could also be coded as list directly!)
bins = (pd.Series(valid_range[:-2]).str.extract('(\d+)$', expand=False)
          .astype(int).to_list()
        )
bins = [0]+bins+[float('inf')]
# [0, 5, 10, 15, 20, inf]

df['Valid_Range'] = (           # replace ">x" with upper bound + 1
 pd.cut(df['Range'].str.replace('>.*', f'{bins[-1]+1}', regex=True)
                  # extract trailing digits
                  .str.extract('(\d+)$', expand=False).astype(float),
        bins=bins, labels=valid_range[:-1])
    .values.add_categories(valid_range[-1])  # cut output is Categorical
    .fillna(valid_range[-1])  # fill nans that correspond to initial "mixed"
)
</code>```

output:

```<code>    Gender  Range Valid_Range
0     male  mixed       mixed
1     male  mixed       mixed
2     male    5-6        5-10
3   female    4-5         0-5
4     male    5-6        5-10
5     male  12-14       10-15
6     male   9-10        5-10
7     male  mixed       mixed
8     male  17-18       15-20
9    mixed  mixed       mixed
10  female    >20         >20
</code>```

Body:
I am having a csv file , which contains a range of numbers in a column. I also have list of valid range. I need identify the possible range for the matching numbers in csv.

valid_range = ["0-1", "1-2", "0-5", "5-10", "10-15", "15-20", ">20","mixed"]

csv data :

What I have:

What I need:

Anything greater than 20 will have ">20" and mixed will have the same.

df = {'Gender': {0: 'male',
  1: 'male',
  2: 'male',
  3: 'female',
  4: 'male',
  5: 'male',
  6: 'male',
  7: 'male',
  8: 'male',
  9: 'mixed',
  10: 'female'},
 'Range': {0: 'mixed',
  1: 'mixed',
  2: '5-6',
  3: '4-5',
  4: '5-6',
  5: '12-14',
  6: '9-10',
  7: 'mixed',
  8: '17-18',
  9: 'mixed',
  10: '>20'}}

Body:
If you don't have overlap, you can rely on the upper bound.

Then use of a bit or regex magic and pandas.cut:

# non overlapping ranges
valid_range = ["0-5", "5-10", "10-15", "15-20", ">20", "mixed"]

# define bins (could also be coded as list directly!)
bins = (pd.Series(valid_range[:-2]).str.extract('(\d+)$', expand=False)
          .astype(int).to_list()
        )
bins = [0]+bins+[float('inf')]
# [0, 5, 10, 15, 20, inf]

df['Valid_Range'] = (           # replace ">x" with upper bound + 1
 pd.cut(df['Range'].str.replace('>.*', f'{bins[-1]+1}', regex=True)
                  # extract trailing digits
                  .str.extract('(\d+)$', expand=False).astype(float),
        bins=bins, labels=valid_range[:-1])
    .values.add_categories(valid_range[-1])  # cut output is Categorical
    .fillna(valid_range[-1])  # fill nans that correspond to initial "mixed"
)

output:

    Gender  Range Valid_Range
0     male  mixed       mixed
1     male  mixed       mixed
2     male    5-6        5-10
3   female    4-5         0-5
4     male    5-6        5-10
5     male  12-14       10-15
6     male   9-10        5-10
7     male  mixed       mixed
8     male  17-18       15-20
9    mixed  mixed       mixed
10  female    >20         >20


问:
Errors during downloading metadata for repository 'AppStream'
When I use yum list java*,I get an error like the following：

```<code>[root@crucialer ~]# yum list java*
Repository extras is listed more than once in the configuration
Repository centosplus is listed more than once in the configuration
CentOS-8 - AppStream                                                                                17 kB/s | 2.3 kB     00:00
Errors during downloading metadata for repository 'AppStream':
  - Status code: 404 for http://mirrors.cloud.aliyuncs.com/centos/8/AppStream/x86_64/os/repodata/repomd.xml (IP: 100.100.2.148)
Error: Failed to download metadata for repo 'AppStream': Cannot download repomd.xml: Cannot download repodata/repomd.xml: All mirrors were tried
</code>```
```<code>[root@crucialer ~]# ping 100.100.2.148
PING 100.100.2.148 (100.100.2.148) 56(84) bytes of data.
64 bytes from 100.100.2.148: icmp_seq=1 ttl=102 time=1.94 ms
64 bytes from 100.100.2.148: icmp_seq=2 ttl=102 time=1.88 ms
64 bytes from 100.100.2.148: icmp_seq=3 ttl=102 time=2.08 ms
64 bytes from 100.100.2.148: icmp_seq=4 ttl=102 time=1.94 ms
64 bytes from 100.100.2.148: icmp_seq=5 ttl=102 time=1.93 ms
^C
--- 100.100.2.148 ping statistics ---
5 packets transmitted, 5 received, 0% packet loss, time 8ms
rtt min/avg/max/mdev = 1.883/1.953/2.078/0.076 ms
[root@crucialer ~]# ping www.baidu.com
PING www.a.shifen.com (180.101.49.12) 56(84) bytes of data.
64 bytes from 180.101.49.12 (180.101.49.12): icmp_seq=1 ttl=50 time=15.6 ms
64 bytes from 180.101.49.12 (180.101.49.12): icmp_seq=2 ttl=50 time=15.2 ms
64 bytes from 180.101.49.12 (180.101.49.12): icmp_seq=3 ttl=50 time=15.2 ms
64 bytes from 180.101.49.12 (180.101.49.12): icmp_seq=4 ttl=50 time=15.3 ms
^C
--- www.a.shifen.com ping statistics ---
4 packets transmitted, 4 received, 0% packet loss, time 6ms
rtt min/avg/max/mdev = 15.223/15.331/15.581/0.210 ms

</code>```
```<code>
[root@crucialer yum.repos.d]# cat CentOS-Base.repo
# CentOS-Base.repo
#
# The mirror system uses the connecting IP address of the client and the
# update status of each mirror to pick mirrors that are updated to and
# geographically close to the client.  You should use this for CentOS updates
# unless you are manually picking other mirrors.
#
# If the mirrorlist= does not work for you, as a fall back you can try the
# remarked out baseurl= line instead.
#
#
[base]
name=CentOS-$releasever - Base - 163.com
#mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=os
baseurl=http://mirrors.163.com/centos/$releasever/os/$basearch/
gpgcheck=1
gpgkey=http://mirrors.163.com/centos/RPM-GPG-KEY-CentOS-7

#released updates
[updates]
name=CentOS-$releasever - Updates - 163.com
#mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=updates
baseurl=http://mirrors.163.com/centos/$releasever/updates/$basearch/
gpgcheck=1
gpgkey=http://mirrors.163.com/centos/RPM-GPG-KEY-CentOS-7

#additional packages that may be useful
[extras]
name=CentOS-$releasever - Extras - 163.com
#mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=extras
baseurl=http://mirrors.163.com/centos/$releasever/extras/$basearch/
gpgcheck=1
gpgkey=http://mirrors.163.com/centos/RPM-GPG-KEY-CentOS-7

#additional packages that extend functionality of existing packages
[centosplus]
name=CentOS-$releasever - Plus - 163.com
baseurl=http://mirrors.163.com/centos/$releasever/centosplus/$basearch/
gpgcheck=1
enabled=0
gpgkey=http://mirrors.163.com/centos/RPM-GPG-KEY-CentOS-7

</code>```

Any suggestions would be greatly appreciated.

答:
Pierz has rightly pointed. I would like to add few commands that change the repo to vault.centos.org

```<code># sed -i 's/mirrorlist/#mirrorlist/g' /etc/yum.repos.d/CentOS-*
# sed -i 's|#baseurl=http://mirror.centos.org|baseurl=http://vault.centos.org|g' /etc/yum.repos.d/CentOS-*
</code>```

Now run the command: yum list java*

Body:
When I use yum list java*,I get an error like the following：

[root@crucialer ~]# yum list java*
Repository extras is listed more than once in the configuration
Repository centosplus is listed more than once in the configuration
CentOS-8 - AppStream                                                                                17 kB/s | 2.3 kB     00:00
Errors during downloading metadata for repository 'AppStream':
  - Status code: 404 for http://mirrors.cloud.aliyuncs.com/centos/8/AppStream/x86_64/os/repodata/repomd.xml (IP: 100.100.2.148)
Error: Failed to download metadata for repo 'AppStream': Cannot download repomd.xml: Cannot download repodata/repomd.xml: All mirrors were tried

[root@crucialer ~]# ping 100.100.2.148
PING 100.100.2.148 (100.100.2.148) 56(84) bytes of data.
64 bytes from 100.100.2.148: icmp_seq=1 ttl=102 time=1.94 ms
64 bytes from 100.100.2.148: icmp_seq=2 ttl=102 time=1.88 ms
64 bytes from 100.100.2.148: icmp_seq=3 ttl=102 time=2.08 ms
64 bytes from 100.100.2.148: icmp_seq=4 ttl=102 time=1.94 ms
64 bytes from 100.100.2.148: icmp_seq=5 ttl=102 time=1.93 ms
^C
--- 100.100.2.148 ping statistics ---
5 packets transmitted, 5 received, 0% packet loss, time 8ms
rtt min/avg/max/mdev = 1.883/1.953/2.078/0.076 ms
[root@crucialer ~]# ping www.baidu.com
PING www.a.shifen.com (180.101.49.12) 56(84) bytes of data.
64 bytes from 180.101.49.12 (180.101.49.12): icmp_seq=1 ttl=50 time=15.6 ms
64 bytes from 180.101.49.12 (180.101.49.12): icmp_seq=2 ttl=50 time=15.2 ms
64 bytes from 180.101.49.12 (180.101.49.12): icmp_seq=3 ttl=50 time=15.2 ms
64 bytes from 180.101.49.12 (180.101.49.12): icmp_seq=4 ttl=50 time=15.3 ms
^C
--- www.a.shifen.com ping statistics ---
4 packets transmitted, 4 received, 0% packet loss, time 6ms
rtt min/avg/max/mdev = 15.223/15.331/15.581/0.210 ms

[root@crucialer yum.repos.d]# cat CentOS-Base.repo
# CentOS-Base.repo
#
# The mirror system uses the connecting IP address of the client and the
# update status of each mirror to pick mirrors that are updated to and
# geographically close to the client.  You should use this for CentOS updates
# unless you are manually picking other mirrors.
#
# If the mirrorlist= does not work for you, as a fall back you can try the
# remarked out baseurl= line instead.
#
#
[base]
name=CentOS-$releasever - Base - 163.com
#mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=os
baseurl=http://mirrors.163.com/centos/$releasever/os/$basearch/
gpgcheck=1
gpgkey=http://mirrors.163.com/centos/RPM-GPG-KEY-CentOS-7

#released updates
[updates]
name=CentOS-$releasever - Updates - 163.com
#mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=updates
baseurl=http://mirrors.163.com/centos/$releasever/updates/$basearch/
gpgcheck=1
gpgkey=http://mirrors.163.com/centos/RPM-GPG-KEY-CentOS-7

#additional packages that may be useful
[extras]
name=CentOS-$releasever - Extras - 163.com
#mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=extras
baseurl=http://mirrors.163.com/centos/$releasever/extras/$basearch/
gpgcheck=1
gpgkey=http://mirrors.163.com/centos/RPM-GPG-KEY-CentOS-7

#additional packages that extend functionality of existing packages
[centosplus]
name=CentOS-$releasever - Plus - 163.com
baseurl=http://mirrors.163.com/centos/$releasever/centosplus/$basearch/
gpgcheck=1
enabled=0
gpgkey=http://mirrors.163.com/centos/RPM-GPG-KEY-CentOS-7

Any suggestions would be greatly appreciated.

Body:
Pierz has rightly pointed. I would like to add few commands that change the repo to vault.centos.org

# sed -i 's/mirrorlist/#mirrorlist/g' /etc/yum.repos.d/CentOS-*
# sed -i 's|#baseurl=http://mirror.centos.org|baseurl=http://vault.centos.org|g' /etc/yum.repos.d/CentOS-*

Now run the command: yum list java*


答:
We can use MAX() here as an analytic function:

SELECT
    Time,
    Number,
    MAX(Time) OVER (PARTITION BY Number) AS LastUpdated
FROM yourTable
ORDER BY Time;
```
<p>The logic above will grab, for each record, the max time value as the last updated time.  For numbers having only one record, the record's time will be coincident with the max time.</p>
<p>Here is a version which should work on MySQL servers earlier than 8+:</p>
<pre class="lang-sql prettyprint-override"><code>SELECT
    t1.Time,
    t1.Number,
    t2.LastUpdated
FROM yourTable t1
INNER JOIN
(
    SELECT Number, MAX(Time) AS LastUpdated
    FROM yourTable
    GROUP BY Number
) t2
    ON t2.Number = t1.Number
ORDER BY
    t1.Time;
</code>```

Title: How to combine two sql queries to get a one table in mysql?

Body:
I have a dataset as follows,

   Time         Number  Updated
2/10/2022 10:12 12345     0
2/11/2022 10:12 234       0
2/12/2022 10:12 433       0
2/13/2022 10:12 556       0
2/14/2022 10:12 4357      0
2/15/2022 10:12 12345     1

I need to get Time,Number and Last updated time if updated value is 1 for each number. The output is should be as this.

Time            Number  Updated    Last Updated
2/10/2022 10:12 12345     0      2/15/2022 10:12
2/11/2022 10:12 234       0      2/11/2022 10:12
2/12/2022 10:12 433       0      2/12/2022 10:12
2/13/2022 10:12 556       0      2/13/2022 10:12
2/14/2022 10:12 4357      0      2/14/2022 10:12
2/15/2022 10:12 12345     1      2/15/2022 10:12

I know I need to get following two query data, but I couldn't combine them to get a one query.

select Time,Number from table1;

select Number, max(Time) from table1 group by Number ;

From each one I can get the output as follows,

Time            Number
2/10/2022 10:12 12345
2/11/2022 10:12 234
2/12/2022 10:12 433
2/13/2022 10:12 556
2/14/2022 10:12 4357
2/15/2022 10:12 12345

    Number  max(Time)
12345   2/15/2022 10:12
234     2/11/2022 10:12
433     2/12/2022 10:12
556     2/13/2022 10:12
4357    2/14/2022 10:12
12345   2/15/2022 10:12

can some one show me an efficient way to do this?Since I have thousands of queries to select as this.

Update:

How I could get the required outputs when the database changed as below?

   Time         Number  Updated
2/10/2022 10:12 12345     1
2/11/2022 10:12 234       0
2/12/2022 10:12 433       0
2/13/2022 10:12 556       0
2/14/2022 10:12 4357      0
2/15/2022 10:12 12345     0

and the results should be as follows,

Time            Number  Updated    Last Updated
2/10/2022 10:12 12345     1      2/15/2022 10:12
2/11/2022 10:12 234       0      2/11/2022 10:12
2/12/2022 10:12 433       0      2/12/2022 10:12
2/13/2022 10:12 556       0      2/13/2022 10:12
2/14/2022 10:12 4357      0      2/14/2022 10:12
2/15/2022 10:12 12345     0      2/15/2022 10:12

Body:
We can use MAX() here as an analytic function:

SELECT
    Time,
    Number,
    MAX(Time) OVER (PARTITION BY Number) AS LastUpdated
FROM yourTable
ORDER BY Time;

The logic above will grab, for each record, the max time value as the last updated time.  For numbers having only one record, the record's time will be coincident with the max time.

Here is a version which should work on MySQL servers earlier than 8+:

SELECT
    t1.Time,
    t1.Number,
    t2.LastUpdated
FROM yourTable t1
INNER JOIN
(
    SELECT Number, MAX(Time) AS LastUpdated
    FROM yourTable
    GROUP BY Number
) t2
    ON t2.Number = t1.Number
ORDER BY
    t1.Time;