问:
Replace logical values conditionally in R
I am sure this question has been asked before and has an easy solution, but I can't seem to find it.

I am trying to conditionally replace the logical value of a variable based on the value of other variables in the data. Specifically, I am trying to determine eligibility based on survey responses.

I have created my eligibility variable in dataframe screen:

```<code>screen$eligible <- ifelse (
                            (screen$age > 17 & screen$age < 23)
                           & (screen$alcohol > 3 | screen$marijuana > 3)
                           & (screen$country == 0 | screen$ageus < 12)
                           & (screen$county_1 == 17 | screen$county_1 == 27 | screen$county_1 == 31)
                           & (screen$residence_1 == 47),
                           TRUE,
                             FALSE)
</code>```

And now, based on study changes, I would like to further limit eligibility. I tried the code below, and it works in part, but it appears that I am introducing NAs to my eligibility variable and missing out on folks who should be eligible.

```<code>screen$eligible <- ifelse( screen$eligible ==TRUE, ifelse(
  (screen$gender_1 == 1 & screen$age > 18)
  |(screen$gender_8 == 1 & screen$age > 20),
  FALSE, TRUE), FALSE)
</code>```

I ultimately want TRUE or FALSE values.

Two questions

Is there a clearer or more concise way to update the code to update my eligibility requirements?

Any ideas as to why I might be introducing NAs?

答:
1. Is there a clearer or more concise way to update the code to update my eligibility requirements?

If you ever find yourself writing x = ifelse(condition, TRUE, FALSE), as you are here -- that's equivalent to just writing x = condition. Also, your three county_1 == x statements can be replaced with one county_1 %in% c(x, y, z). So your first code block could be written as,

```<code>screen$eligible <- (screen$age > 17 & screen$age < 23)
                   & (screen$alcohol > 3 | screen$marijuana > 3)
                   & (screen$country == 0 | screen$ageus < 12)
                   & screen$county_1 %in% c(17, 27, 31)
                   & (screen$residence_1 == 47)
</code>```

Likewise, your second codeblock could be simplified as:

```<code>screen$eligible <- screen$eligible
                   & ((screen$gender_1 == 1 & screen$age > 18)
                     | (screen$gender_8 == 1 & screen$age > 20))
</code>```

2. Any ideas as to why I might be introducing NAs?

It's hard to say without seeing your data, but the NAs probably indicate that one or more of your constituent variables (gender_1, gender_8, age) is NA for some cases.

Body:
I am sure this question has been asked before and has an easy solution, but I can't seem to find it.

I am trying to conditionally replace the logical value of a variable based on the value of other variables in the data. Specifically, I am trying to determine eligibility based on survey responses.

I have created my eligibility variable in dataframe screen:

screen$eligible <- ifelse (
                            (screen$age > 17 & screen$age < 23)
                           & (screen$alcohol > 3 | screen$marijuana > 3)
                           & (screen$country == 0 | screen$ageus < 12)
                           & (screen$county_1 == 17 | screen$county_1 == 27 | screen$county_1 == 31)
                           & (screen$residence_1 == 47),
                           TRUE,
                             FALSE)

And now, based on study changes, I would like to further limit eligibility. I tried the code below, and it works in part, but it appears that I am introducing NAs to my eligibility variable and missing out on folks who should be eligible.

screen$eligible <- ifelse( screen$eligible ==TRUE, ifelse(
  (screen$gender_1 == 1 & screen$age > 18)
  |(screen$gender_8 == 1 & screen$age > 20),
  FALSE, TRUE), FALSE)

I ultimately want TRUE or FALSE values.

Two questions

Is there a clearer or more concise way to update the code to update my eligibility requirements?

Any ideas as to why I might be introducing NAs?

Body:
1. Is there a clearer or more concise way to update the code to update my eligibility requirements?

If you ever find yourself writing x = ifelse(condition, TRUE, FALSE), as you are here -- that's equivalent to just writing x = condition. Also, your three county_1 == x statements can be replaced with one county_1 %in% c(x, y, z). So your first code block could be written as,

screen$eligible <- (screen$age > 17 & screen$age < 23)
                   & (screen$alcohol > 3 | screen$marijuana > 3)
                   & (screen$country == 0 | screen$ageus < 12)
                   & screen$county_1 %in% c(17, 27, 31)
                   & (screen$residence_1 == 47)

Likewise, your second codeblock could be simplified as:

screen$eligible <- screen$eligible
                   & ((screen$gender_1 == 1 & screen$age > 18)
                     | (screen$gender_8 == 1 & screen$age > 20))

2. Any ideas as to why I might be introducing NAs?

It's hard to say without seeing your data, but the NAs probably indicate that one or more of your constituent variables (gender_1, gender_8, age) is NA for some cases.


来源: stackexchange

问:
How to use a variable in innerHTML statement to display specific object values
I have variables being passed from a button to a function go() in the HTML file. The function go() then calls an external function displayInfo() and passes the variable to it.

The code below displays "undefined". Is it possible to use the countryName string to target the objects instead of the object name?

```<code>document.getElementById("show-country").innerHTML = countryName.name;
document.getElementById("show-population").innerHTML = countryName.population;
</code>```

index.html:

```<code><!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
</head>
<body>
    <script>
        function go(val)
        {  displayInfo(val); }
    </script>

    <input type="button" value="england" onclick="go(this.value)">
    <input type="button" value="france" onclick="go(this.value)">

    <div>
        <h1 id="show-country"></h1>
        <p id="show-population"></p>
    </div>

    <script src="countries.js" type="text/javascript"></script>
</body>
</html>
</code>```

countries.js:

```<code>function displayInfo (countryName)
{
    var england =
    {
        name :      "England",
        population: "53.01 million"
    };
    var france =
    {
        name :      "France",
        population: "66.9 million"
    };

    document.getElementById("show-country").innerHTML = countryName.name;
    document.getElementById("show-population").innerHTML = countryName.population;
}
</code>```

答:
  var countries={
  england :{
    name : "England",
    population: "53.01 million"
  },
 france:{
   name :  "France",
   population: "66.9 million"
 }
};

function displayInfo (countryName){
  document.getElementById("show-country").innerHTML = countries[countryName].name;
  document.getElementById("show-population").innerHTML = countries[countryName].population;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!doctype html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  </head>
  <body>
    <script>
    function go(val)
    {  displayInfo(val); }
    </script>
    <input type="button" value="england" onclick="go(this.value)">
    <input type="button" value="france" onclick="go(this.value)">
    <div>
      <h1 id="show-country"></h1>
      <p id="show-population"></p>
    </div>
    <script src="countries.js" type="text/javascript"></script>
  </body>
</html></code>```

ContentLicense: CC BY-SA 4.0

Body:
I have variables being passed from a button to a function go() in the HTML file. The function go() then calls an external function displayInfo() and passes the variable to it.

The code below displays "undefined". Is it possible to use the countryName string to target the objects instead of the object name?

document.getElementById("show-country").innerHTML = countryName.name;
document.getElementById("show-population").innerHTML = countryName.population;

index.html:

<!doctype html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <input type="button" value="england" onclick="go(this.value)">
    <input type="button" value="france" onclick="go(this.value)">

countries.js:

function displayInfo (countryName)
{
    var england =
    {
        name :      "England",
        population: "53.01 million"
    };
    var france =
    {
        name :      "France",
        population: "66.9 million"
    };

    document.getElementById("show-country").innerHTML = countryName.name;
    document.getElementById("show-population").innerHTML = countryName.population;
}

Body:
  var countries={
  england :{
    name : "England",
    population: "53.01 million"
  },
 france:{
   name :  "France",
   population: "66.9 million"
 }
};

function displayInfo (countryName){
  document.getElementById("show-country").innerHTML = countries[countryName].name;
  document.getElementById("show-population").innerHTML = countries[countryName].population;
}

<!doctype html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  </head>
  <body>
    <script>
    function go(val)
    {  displayInfo(val); }
    </script>
    <input type="button" value="england" onclick="go(this.value)">
    <input type="button" value="france" onclick="go(this.value)">
    <div>
      <h1 id="show-country"></h1>
      <p id="show-population"></p>
    </div>
    <script src="countries.js" type="text/javascript"></script>
  </body>
</html>


问:
Why does detectMultiScale() throw error: (-215:Assertion failed) !empty()
I learning opencv and I'm stuck on this error:

```<code>Traceback (most recent call last):

  File "/home/nicolas/Pulpit/programowanie/python/CV/opecv.py", line 10, in <module>
    faces = face_cascade.detectMultiScale(img)

error: OpenCV(4.5.5) /io/opencv/modules/objdetect/src/cascadedetect.cpp:1689: error: (-215:Assertion failed) !empty() in function 'detectMultiScale'
</code>```

I tried every possible solution from here:
First the gray martix isn't empty, second the paths are good and don't toss errors,
but I still don't know what is wrong...
And that's my code:

```<code>import cv2 as cv

img = cv2.imread('img/face.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

face_cascade = cv2.CascadeClassifier('/home/nicolas/Pulpit/programowanie/python/CV/databases/haar_face.xml')

faces = face_cascade.detectMultiScale(gray)

for (x,y,w,h) in faces:
    cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,0),2)

cv2.imshow('img',img)

k = cv2.waitKey(0)
if k == 27:         # wait for ESC key to exit
    cv2.destroyAllWindows()
</code>```

答: Okey guys, I made it! I'm using linux, and in paths there are no extensions, so path should be 'haar_face' not 'haar_face.xml'.</p>

Body:
I learning opencv and I'm stuck on this error:

Traceback (most recent call last):

  File "/home/nicolas/Pulpit/programowanie/python/CV/opecv.py", line 10, in <module>
    faces = face_cascade.detectMultiScale(img)

error: OpenCV(4.5.5) /io/opencv/modules/objdetect/src/cascadedetect.cpp:1689: error: (-215:Assertion failed) !empty() in function 'detectMultiScale'

I tried every possible solution from here:
First the gray martix isn't empty, second the paths are good and don't toss errors,
but I still don't know what is wrong...
And that's my code:

import cv2 as cv

img = cv2.imread('img/face.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

face_cascade = cv2.CascadeClassifier('/home/nicolas/Pulpit/programowanie/python/CV/databases/haar_face.xml')

faces = face_cascade.detectMultiScale(gray)

for (x,y,w,h) in faces:
    cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,0),2)

cv2.imshow('img',img)

k = cv2.waitKey(0)
if k == 27:         # wait for ESC key to exit
    cv2.destroyAllWindows()


问:
How to convert enum number to string in React with Typescript?
My enum looks like this:

```<code>export enum OrderType {
  ORDER_TYPE_UNSPECIFIED = 0,
  ASAP = 1
  SCHEDULED = 2
  CATERING = 4,
  UNRECOGNIZED = -1,
}
</code>```

Below I already have a function orderTypeToJSON:

```<code>export function orderTypeToJSON(object: OrderType): string {
  switch (object) {
    case OrderType.ORDER_TYPE_UNSPECIFIED:
      return 'ORDER_TYPE_UNSPECIFIED';
    case OrderType.ASAP:
      return 'ASAP';
    case OrderType.SCHEDULED:
      return 'SCHEDULED';
    case OrderType.CATERING:
      return 'CATERING';
    default:
      return 'UNKNOWN';
  }
}
</code>```

In OrderList component I map through orders (3 orders with corresponding OrderTypes: OrderType.ASAP, OrderType.SCHEDULED, OrderType.CATERING) and for each order return OrderCard:

```<code> {orderList.map(order => (
          <OrderCard
            key={order.orderId}
            customerName={order.customer?.name}
            orderType={order.type}
            batchId={order.batchId}
            batchedOrderTitle="BATCHED"
            groupId={order.groupId}
            groupedOrderTitle="GROUPED"
            address={order.address}
            driverName={order.assignedDriverId}
          />
        ))}
</code>```

In browser it displays 1, 2 or 4. Instead, I need to display 'ASAP' as a string (if it's 1), 'SCHEDULED' if it's 2 and 'CATERING' if it's 4.

NOTE: I'm not allowed to touch enum or somehow change it at all.

I've tried using conditional rendering in OrderCard like:

```<code>{OrderType.ASAP && <p>ASAP</p>}
{OrderType.SCHEDULED && <p>SCHEDULED</p>}
{OrderType.CATERING && <p>CATERING</p>}
</code>```

When I do that it overrides all orders and displays only 'ASAP' for all 3 orders.

The following logic didn't work as well:

```<code>{OrderType.ASAP ? (
          <p>ASAP</p>
        ) : OrderType.SCHEDULED ? (
          <p>SCHEDULED</p>
        ) : (
          <p>CATERING</p>
        )}
</code>```

I assume I need to use function orderTypeToJSON but I don't know where to put it (in parent component OrderList or in child OrderCard) and how to apply it in render method so it shows strings 'ASAP', 'SCHEDULED' and 'CATERING'.

Any advice is appreciated.

答:
Use a map:

let orderTypeToNameMap = {
   OrderType.ASAP: "ASAP",
   OrderType.SCHEDULED: "Scheduled",
   OrderType.CATERING: "Catering"
};
```
<p>Then when you want to access the name:</p>
```
{orderTypeToNameMap[order.type]}

```

Make sense?

Body:
My enum looks like this:

export enum OrderType {
  ORDER_TYPE_UNSPECIFIED = 0,
  ASAP = 1
  SCHEDULED = 2
  CATERING = 4,
  UNRECOGNIZED = -1,
}

Below I already have a function orderTypeToJSON:

export function orderTypeToJSON(object: OrderType): string {
  switch (object) {
    case OrderType.ORDER_TYPE_UNSPECIFIED:
      return 'ORDER_TYPE_UNSPECIFIED';
    case OrderType.ASAP:
      return 'ASAP';
    case OrderType.SCHEDULED:
      return 'SCHEDULED';
    case OrderType.CATERING:
      return 'CATERING';
    default:
      return 'UNKNOWN';
  }
}

In OrderList component I map through orders (3 orders with corresponding OrderTypes: OrderType.ASAP, OrderType.SCHEDULED, OrderType.CATERING) and for each order return OrderCard:

 {orderList.map(order => (
          <OrderCard
            key={order.orderId}
            customerName={order.customer?.name}
            orderType={order.type}
            batchId={order.batchId}
            batchedOrderTitle="BATCHED"
            groupId={order.groupId}
            groupedOrderTitle="GROUPED"
            address={order.address}
            driverName={order.assignedDriverId}
          />
        ))}

In browser it displays 1, 2 or 4. Instead, I need to display 'ASAP' as a string (if it's 1), 'SCHEDULED' if it's 2 and 'CATERING' if it's 4.

NOTE: I'm not allowed to touch enum or somehow change it at all.

I've tried using conditional rendering in OrderCard like:

{OrderType.ASAP &&
ASAP
}
{OrderType.SCHEDULED &&
SCHEDULED
}
{OrderType.CATERING &&
CATERING
}

When I do that it overrides all orders and displays only 'ASAP' for all 3 orders.

The following logic didn't work as well:

{OrderType.ASAP ? (

ASAP

        ) : OrderType.SCHEDULED ? (

SCHEDULED

        ) : (

CATERING

        )}

I assume I need to use function orderTypeToJSON but I don't know where to put it (in parent component OrderList or in child OrderCard) and how to apply it in render method so it shows strings 'ASAP', 'SCHEDULED' and 'CATERING'.

Any advice is appreciated.

Body:
Use a map:

let orderTypeToNameMap = {
   OrderType.ASAP: "ASAP",
   OrderType.SCHEDULED: "Scheduled",
   OrderType.CATERING: "Catering"
};

Then when you want to access the name:

<p>{orderTypeToNameMap[order.type]}</p>

Make sense?


问:
Dart convert string without quotes to json
I am trying to convert a string to json string.

String I get:

```<code>String myJSON =  '{codigo: 1050, decricao: Mage x, qntd: 1, tipo: UN, vUnit: 10,9, vTotal: 10,90}';
</code>```

String I need:

```<code>String myJSON =  '{"codigo": "1050", "decricao": "Mage x", "qntd": "1", "tipo": "UN", "vUnit": "10,9", "vTotal": "10,90"}';
</code>```

Could someone shed some light on how I can add the quotes?

答:
You can easily convert a String using replaceAll.

Code:

```<code>  String myJSON =  '{codigo: 1050, decricao: Mage x, qntd: 1, tipo: UN, vUnit: 10,9, vTotal: 10,90}';
  myJSON = myJSON.replaceAll('{', '{"');
  myJSON = myJSON.replaceAll(': ', '": "');
  myJSON = myJSON.replaceAll(', ', '", "');
  myJSON = myJSON.replaceAll('}', '"}');
  print(myJSON);
</code>```

Output:

```<code>{"codigo": "1050", "decricao": "Mage x", "qntd": "1", "tipo": "UN", "vUnit": "10,9", "vTotal": "10,90"}
</code>```

Body:
I am trying to convert a string to json string.

String I get:

String myJSON =  '{codigo: 1050, decricao: Mage x, qntd: 1, tipo: UN, vUnit: 10,9, vTotal: 10,90}';

String I need:

String myJSON =  '{"codigo": "1050", "decricao": "Mage x", "qntd": "1", "tipo": "UN", "vUnit": "10,9", "vTotal": "10,90"}';

Could someone shed some light on how I can add the quotes?

Body:
You can easily convert a String using replaceAll.

Code:

  String myJSON =  '{codigo: 1050, decricao: Mage x, qntd: 1, tipo: UN, vUnit: 10,9, vTotal: 10,90}';
  myJSON = myJSON.replaceAll('{', '{"');
  myJSON = myJSON.replaceAll(': ', '": "');
  myJSON = myJSON.replaceAll(', ', '", "');
  myJSON = myJSON.replaceAll('}', '"}');
  print(myJSON);

Output:

{"codigo": "1050", "decricao": "Mage x", "qntd": "1", "tipo": "UN", "vUnit": "10,9", "vTotal": "10,90"}


问:
Use sed to Replace Multiple Lines
I'm trying to use sed to replace multiple lines which are found via regex with one substitution.  For example, given the following simplified text file

```<code>first
second
third
fourth
fifth
sixth
seventh
eighth
</code>```

How would I go about using regex to find the second to fourth lines and replace the whole range with one instance of the word "found" so that the end result is

```<code>first
found
fifth
sixth
seventh
eighth
</code>```

I'm basically looking to combine the substitution syntax (sed 's/second/found/') with the range syntax (sed '/second/,/fourth/') into something like sed 's/second/,/fourth/found/' that actually works.

答:
Using sed

```<code>$ sed '/second/,/third/{d};x;x;s/fourth/found/' input_file
first
found
fifth
sixth
seventh
eighth
</code>```

Title: Use sed to Replace Multiple Lines

Body:
I'm trying to use sed to replace multiple lines which are found via regex with one substitution.  For example, given the following simplified text file

first
second
third
fourth
fifth
sixth
seventh
eighth

How would I go about using regex to find the second to fourth lines and replace the whole range with one instance of the word "found" so that the end result is

first
found
fifth
sixth
seventh
eighth

I'm basically looking to combine the substitution syntax (sed 's/second/found/') with the range syntax (sed '/second/,/fourth/') into something like sed 's/second/,/fourth/found/' that actually works.

Body:
Using sed

$ sed '/second/,/third/{d};x;x;s/fourth/found/' input_file
first
found
fifth
sixth
seventh
eighth


问:
pd.read_csv causes pyplot fail to render
I'm new to Python.

For some reason when imported data from any .csv file,

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

dataFrame = pd.read_csv('csv1.csv')

plt.hist([2,3,4])
plt.show()
</code>```

csv1.csv (actually any legit csv will be good here)

```<code>"Group A","Group B"
3,2
4,1
0,1
</code>```

pyplot fail to render:

```<code>(...)
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/matplotlib/ticker.py", line 2120, in tick_values
    vmin, vmax = mtransforms.nonsingular(
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/matplotlib/transforms.py", line 2880, in nonsingular
    if maxabsvalue < (1e6 / tiny) * np.finfo(float).tiny:
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/numpy/core/getlimits.py", line 462, in __new__
    dtype = numeric.dtype(type(dtype))
TypeError: 'NoneType' object is not callable
</code>```

screenshot of the empty figure

But, removing the

```<code>dataFrame = pd.read_csv('csv1.csv')
</code>```

and everything is good to go.
plt.scatter() also fails to render, not just hist().

I do not to understand why pyplot behaves that way.

Are pandas and matplotlib somehow not compatible?

答: What version of Python are you using? There's an issue with python 3.10, pd.read_csv(), and numeric.dtype, documented here: https://github.com/pandas-dev/pandas/issues/41935</p>

Body:
I'm new to Python.

For some reason when imported data from any .csv file,

import pandas as pd
import matplotlib.pyplot as plt

dataFrame = pd.read_csv('csv1.csv')

plt.hist([2,3,4])
plt.show()

csv1.csv (actually any legit csv will be good here)

"Group A","Group B"
3,2
4,1
0,1

pyplot fail to render:

(...)
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/matplotlib/ticker.py", line 2120, in tick_values
    vmin, vmax = mtransforms.nonsingular(
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/matplotlib/transforms.py", line 2880, in nonsingular
    if maxabsvalue < (1e6 / tiny) * np.finfo(float).tiny:
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/numpy/core/getlimits.py", line 462, in __new__
    dtype = numeric.dtype(type(dtype))
TypeError: 'NoneType' object is not callable

screenshot of the empty figure

But, removing the

dataFrame = pd.read_csv('csv1.csv')

and everything is good to go.
plt.scatter() also fails to render, not just hist().

I do not to understand why pyplot behaves that way.

Are pandas and matplotlib somehow not compatible?


问:
Quarkus @QuarkusTest vs @QuarkusIntegrationTest
Apologies if it has been answered before, but I can't seem to find a good answer.

What is the context of how @QuarkusTest runs versus QuarkusIntegrationTest?

So far, all I got is the integration test runs against a packaged form of the app (.jar, native compilation), whereas the plain @QuarkusTest doesn't? But this does not leave much explanation, and apologies if this comes from a lack of understanding in test runtimes.

To start a test instance of Quarkus (via @QuarkusTest), does it not compile and package into a jar? Makes sense to not I suppose, and just test against running compiled classes but I would rather get the real answer than assuming.

https://quarkus.io/guides/getting-started-testing#native-executable-testing

答: Besides the difference you mention, there's another crucial difference between @QuarkusTest and @QuarkusIntegrationTest. With @QuarkusTest, the test runs in the same process as the tested application, so you can inject the application's beans into the test instance etc., while with @QuarkusIntegrationTest, the tested application runs in an external process, so you can only interact with it over network.


问:
Does C# do tail recursion?

Possible Duplicate:

  Why doesn't .net/C# eliminate tail recursion?

Does C# do tail recusion?

I can't find any documentation telling me if it does or not.

答: C# does not innately support tail recursion in the language but here is an interesting article on a similar technique call trampolining that may help you in your situation </p>

ContentLicense: CC BY-SA 3.0

Title: Does C# do tail recursion?


问:
New to Python, what is wrong with my while loop calculator?
I'm new to Python and I'm writing a calculator. It is meant to allow the user to add as many numbers as they want, I'm using while loops and I have it so that 0 ends the while loop and presents the sum. It won't calculate properly and ends prematurely. Anybody know why? Here is my code:

```<code>    import keyboard

    print('Lets add some numbers! Press 0 for total!')
    numb = input()
    totals = float(numb) + float(numb)
    while totals == float(numb) + float(numb):
      numb = input()
    while keyboard.read_key(0):
      print('You pressed the 0 key!')
      break
    print(f'Your total is: {totals}')'''
</code>```

Thanks in advance!

答:
You need to check for 0 input in the first while loop. Also, you're not adding each input to totals, you're just testing if totals is already equal to the doubled input.

There's no need for keyboard, just test what the user entered.

```<code>total = 0
while True:
    numb = float(input("Enter a number, or 0 for the total"))
    if numb == 0:
        break
    total += numb
print(f'Your total is: {total}")
</code>```

Body:
I'm new to Python and I'm writing a calculator. It is meant to allow the user to add as many numbers as they want, I'm using while loops and I have it so that 0 ends the while loop and presents the sum. It won't calculate properly and ends prematurely. Anybody know why? Here is my code:

    import keyboard

    print('Lets add some numbers! Press 0 for total!')
    numb = input()
    totals = float(numb) + float(numb)
    while totals == float(numb) + float(numb):
      numb = input()
    while keyboard.read_key(0):
      print('You pressed the 0 key!')
      break
    print(f'Your total is: {totals}')'''

Thanks in advance!

Body:
You need to check for 0 input in the first while loop. Also, you're not adding each input to totals, you're just testing if totals is already equal to the doubled input.

There's no need for keyboard, just test what the user entered.

total = 0
while True:
    numb = float(input("Enter a number, or 0 for the total"))
    if numb == 0:
        break
    total += numb
print(f'Your total is: {total}")


问:
Return two shortcodes with one function [Wordpress PHP]
I am attempting to merge the following two functions into one, which are completely identical other than the $utmphone and $utmphonedirect

```<code>// UTM Change Toll Free Phone
 add_action( 'wp_head', 'toll_phone' );
function toll_phone() {
$utmphone = '<a class="whitehref" href="tel:8004806850">800-480-6850</a>';
if(isset($_COOKIE['utm']) && $_COOKIE['utm']== "ccov" || (strpos($_SERVER['REQUEST_URI'], "ccov"))) {
$utmphone = '<a class="whitehref" href="tel:8004484285">(800) 448-4285</a>';
setcookie('utm', 'ccov', time() + (86400 * 30), "/");
}
return $utmphone;
}
add_shortcode('utmphone', 'toll_phone');

// UTM Change Direct Phone
function direct_phone() {
$utmphonedirect = '<a href="tel:312-666-3552">312-666-3552</a>';
if(isset($_COOKIE['utm']) && $_COOKIE['utm']== "ccov" || (strpos($_SERVER['REQUEST_URI'], "ccov"))) {
$utmphonedirect = '<a href="tel:8722604892">(872) 260-4892</a>';
}
return $utmphonedirect;
}
add_shortcode('utmphonedirect', 'direct_phone');
</code>```

I have tried the following, but it is only returning one of the values - therefore both shortcodes are displaying the same. I have also searched the web for a simple answer for something like this and found nothing.

The goal is to output two unique values for both shortcodes: utmphone and utmphonedirect

```<code>// UTM Change BOTH Phones
 add_action( 'wp_head', 'toll_phone' );
function toll_phone() {
$utmphone = '<a class="whitehref" href="tel:8004806850">800-480-6850</a>';
$utmphonedirect = '<a href="tel:312-666-3552">312-666-3552</a>';
if(isset($_COOKIE['utm']) && $_COOKIE['utm']== "ccov" || (strpos($_SERVER['REQUEST_URI'], "ccov"))) {
$utmphone = '<a class="whitehref" href="tel:8004484285">(800) 448-4285</a>';
$utmphonedirect = '<a href="tel:8722604892">(872) 260-4892</a>';
setcookie('utm', 'ccov', time() + (86400 * 30), "/");
}
return $utmphone;
return $utmphonedirect;
}
add_shortcode('utmphone', 'toll_phone');
add_shortcode('utmphonedirect', 'direct_phone');
</code>```

答:
```<code>// UTM Change Toll Free Phone
function toll_phone()
{
    $utmphone = '<a class="whitehref" href="tel:8004806850">800-480-6850</a>';

    if (isset($_COOKIE['utm']) && $_COOKIE['utm'] == "ccov" || (strpos($_SERVER['REQUEST_URI'], "ccov"))) {
        $utmphone = '<a class="whitehref" href="tel:8004484285">(800) 448-4285</a>';
        setcookie('utm', 'ccov', time() + (86400 * 30), "/");
    }

    return $utmphone;
}
add_shortcode('utmphone', 'toll_phone');

// UTM Change Direct Phone
function direct_phone()
{
    $utmphonedirect = '<a href="tel:312-666-3552">312-666-3552</a>';

    if (isset($_COOKIE['utm']) && $_COOKIE['utm'] == "ccov" || (strpos($_SERVER['REQUEST_URI'], "ccov"))) {
        $utmphonedirect = '<a href="tel:8722604892">(872) 260-4892</a>';
    }

    return $utmphonedirect;
}
add_shortcode('utmphonedirect', 'direct_phone');
</code>```

Usage

```<code>[utmphone]
[utmphonedirect]
</code>```

Body:
I am attempting to merge the following two functions into one, which are completely identical other than the $utmphone and $utmphonedirect

// UTM Change Toll Free Phone
 add_action( 'wp_head', 'toll_phone' );
function toll_phone() {
$utmphone = '800-480-6850';
if(isset($_COOKIE['utm']) && $_COOKIE['utm']== "ccov" || (strpos($_SERVER['REQUEST_URI'], "ccov"))) {
$utmphone = '(800) 448-4285';
setcookie('utm', 'ccov', time() + (86400 * 30), "/");
}
return $utmphone;
}
add_shortcode('utmphone', 'toll_phone');

// UTM Change Direct Phone
function direct_phone() {
$utmphonedirect = '312-666-3552';
if(isset($_COOKIE['utm']) && $_COOKIE['utm']== "ccov" || (strpos($_SERVER['REQUEST_URI'], "ccov"))) {
$utmphonedirect = '(872) 260-4892';
}
return $utmphonedirect;
}
add_shortcode('utmphonedirect', 'direct_phone');

I have tried the following, but it is only returning one of the values - therefore both shortcodes are displaying the same. I have also searched the web for a simple answer for something like this and found nothing.

The goal is to output two unique values for both shortcodes: utmphone and utmphonedirect

// UTM Change BOTH Phones
 add_action( 'wp_head', 'toll_phone' );
function toll_phone() {
$utmphone = '800-480-6850';
$utmphonedirect = '312-666-3552';
if(isset($_COOKIE['utm']) && $_COOKIE['utm']== "ccov" || (strpos($_SERVER['REQUEST_URI'], "ccov"))) {
$utmphone = '(800) 448-4285';
$utmphonedirect = '(872) 260-4892';
setcookie('utm', 'ccov', time() + (86400 * 30), "/");
}
return $utmphone;
return $utmphonedirect;
}
add_shortcode('utmphone', 'toll_phone');
add_shortcode('utmphonedirect', 'direct_phone');

Body:
// UTM Change Toll Free Phone
function toll_phone()
{
    $utmphone = '<a class="whitehref" href="tel:8004806850">800-480-6850</a>';

    if (isset($_COOKIE['utm']) && $_COOKIE['utm'] == "ccov" || (strpos($_SERVER['REQUEST_URI'], "ccov"))) {
        $utmphone = '<a class="whitehref" href="tel:8004484285">(800) 448-4285</a>';
        setcookie('utm', 'ccov', time() + (86400 * 30), "/");
    }

    return $utmphone;
}
add_shortcode('utmphone', 'toll_phone');

// UTM Change Direct Phone
function direct_phone()
{
    $utmphonedirect = '<a href="tel:312-666-3552">312-666-3552</a>';

    if (isset($_COOKIE['utm']) && $_COOKIE['utm'] == "ccov" || (strpos($_SERVER['REQUEST_URI'], "ccov"))) {
        $utmphonedirect = '<a href="tel:8722604892">(872) 260-4892</a>';
    }

    return $utmphonedirect;
}
add_shortcode('utmphonedirect', 'direct_phone');

Usage

[utmphone]
[utmphonedirect]


问:
ros run couldn't find executable file after catkin build and source
I'm trying to run an executable, but I'm getting the following error, I ran

```<code>catkin build
</code>```

and then

```<code>source ~/emvs_ws/devel/setup.bash
</code>```

after this running the following command shows this message

```<code>rosrun mapper_emvs run_emvs
</code>```

the error is

```<code>[rosrun] Couldn't find executable named run_emvs below /home/ubuntu/emvs_ws/src/rpg_emvs/mapper_emvs
</code>```

this is the cmake file:

```<code>project(mapper_emvs)
cmake_minimum_required(VERSION 2.8.3)

find_package(catkin_simple REQUIRED)
catkin_simple(ALL_DEPS_REQUIRED)

set(CMAKE_BUILD_TYPE RelWithDebInfo) # Release, RelWithDebInfo
set(CMAKE_CXX_FLAGS "-O3 -fopenmp -std=c++11 ${CMAKE_CXX_FLAGS}")

set(HEADERS
  include/mapper_emvs/mapper_emvs.hpp
  include/mapper_emvs/data_loading.hpp
  include/mapper_emvs/depth_vector.hpp
  include/mapper_emvs/trajectory.hpp
  include/mapper_emvs/geometry_utils.hpp
  include/mapper_emvs/median_filtering.hpp
)

set(SOURCES
  src/mapper_emvs.cpp
  src/data_loading.cpp
  src/median_filtering.cpp
)

option(DEFINE_USE_INVERSE_DEPTH "Use linear spacing in inverse depth (if OFF, will use linear spacing in depth)" ON)
if(DEFINE_USE_INVERSE_DEPTH)
    add_definitions(-DUSE_INVERSE_DEPTH)
endif(DEFINE_USE_INVERSE_DEPTH)

cs_add_library(${PROJECT_NAME} ${SOURCES} ${HEADERS})

# Executables
################################################################################

cs_add_executable(run_emvs src/main.cpp)
target_link_libraries(run_emvs ${PROJECT_NAME})

################################################################################
cs_install()
cs_export()
</code>```

答:
Got it working by adding the following line to CMakeLists.txt:

```<code>catkin_package()
</code>```

Body:
I'm trying to run an executable, but I'm getting the following error, I ran

catkin build

and then

source ~/emvs_ws/devel/setup.bash

after this running the following command shows this message

rosrun mapper_emvs run_emvs

the error is

[rosrun] Couldn't find executable named run_emvs below /home/ubuntu/emvs_ws/src/rpg_emvs/mapper_emvs

this is the cmake file:

project(mapper_emvs)
cmake_minimum_required(VERSION 2.8.3)

find_package(catkin_simple REQUIRED)
catkin_simple(ALL_DEPS_REQUIRED)

set(CMAKE_BUILD_TYPE RelWithDebInfo) # Release, RelWithDebInfo
set(CMAKE_CXX_FLAGS "-O3 -fopenmp -std=c++11 ${CMAKE_CXX_FLAGS}")

set(HEADERS
  include/mapper_emvs/mapper_emvs.hpp
  include/mapper_emvs/data_loading.hpp
  include/mapper_emvs/depth_vector.hpp
  include/mapper_emvs/trajectory.hpp
  include/mapper_emvs/geometry_utils.hpp
  include/mapper_emvs/median_filtering.hpp
)

set(SOURCES
  src/mapper_emvs.cpp
  src/data_loading.cpp
  src/median_filtering.cpp
)

option(DEFINE_USE_INVERSE_DEPTH "Use linear spacing in inverse depth (if OFF, will use linear spacing in depth)" ON)
if(DEFINE_USE_INVERSE_DEPTH)
    add_definitions(-DUSE_INVERSE_DEPTH)
endif(DEFINE_USE_INVERSE_DEPTH)

cs_add_library(${PROJECT_NAME} ${SOURCES} ${HEADERS})

# Executables
################################################################################

cs_add_executable(run_emvs src/main.cpp)
target_link_libraries(run_emvs ${PROJECT_NAME})

################################################################################
cs_install()
cs_export()

Body:
Got it working by adding the following line to CMakeLists.txt:

catkin_package()


问:
Javascript parse html, modify anchor tags that contain images
I have a vague idea on howto do this but I hoped more experienced devs might have a simpler solution.

I have a sting of HTML code from a JSON feed and where an "a" tag exists with an images inside the "a" tag I want to modify and add attributes. example:

```<code><a style="color:000;" href="images/image.jpg">
    <img width="100" height="20" src="images/image_thumb.jpg" />
</a>
</code>```

I would like to change it to be:

```<code><a style="color:000;" href="images/image.jpg" rel="lightbox" >
    <img width="100" height="20" decoy="images/image_thumb.jpg" />
</a>
</code>```

So adding an attribute to the "a" tag and modifying an attribute in the "img" tag. There maybe multiple links within the HTML code some with and without images and other HTML code surrounding them.

To be clear this is NOT modifying HTML already rendered on the page, this is modifying a string of code before it gets rendered.

To be extremely clear here is the JSON feed in question: http://nicekiwi.blogspot.com/feeds/posts/default?alt=json

The HTML code that contains the tags are found at "feed > entry > content > $t"

Am currently working with Mootools 1.3

Any ideas? Thanks.

答:
In straight JS</p>

```<code>var a = document.createElement('div');

// put your content in the innerHTML like so
a.innerHTML = '<a style="color:000;" href="images/image.jpg"><img width="100" height="20" src="images/image_thumb.jpg" /></a>';

var b = a.firstChild;
b.rel = 'lightbox';
var c = b.firstChild;
c.setAttribute('decoy', c.src);
c.src = null;

// now you have your a tag
var newA = a.innerHTML;
</code>```

Body:
I have a vague idea on howto do this but I hoped more experienced devs might have a simpler solution.

I have a sting of HTML code from a JSON feed and where an "a" tag exists with an images inside the "a" tag I want to modify and add attributes. example:

I would like to change it to be:

So adding an attribute to the "a" tag and modifying an attribute in the "img" tag. There maybe multiple links within the HTML code some with and without images and other HTML code surrounding them.

To be clear this is NOT modifying HTML already rendered on the page, this is modifying a string of code before it gets rendered.

To be extremely clear here is the JSON feed in question: http://nicekiwi.blogspot.com/feeds/posts/default?alt=json

The HTML code that contains the tags are found at "feed > entry > content > $t"

Am currently working with Mootools 1.3

Any ideas? Thanks.

Body:
In straight JS

var a = document.createElement('div');

// put your content in the innerHTML like so
a.innerHTML = '<a style="color:000;" href="images/image.jpg"><img width="100" height="20" src="images/image_thumb.jpg" /></a>';

var b = a.firstChild;
b.rel = 'lightbox';
var c = b.firstChild;
c.setAttribute('decoy', c.src);
c.src = null;

// now you have your a tag
var newA = a.innerHTML;


问:
Firebase sendPasswordResetEmail doesn't send email
I have a problem concerning my application using firebase: If I want to enable the users to reset their password themselves firebase doesn't send an email to their address. If I do it myself from the firebase console it works fine. I'm trying it like this:

```<code>   resetPassword(email: string) {
        sendPasswordResetEmail(this.auth, email)
            .then(() => {
                // Password reset email sent!
                // ..
            })
            .catch((error) => {
                const errorCode = error.code;
                const errorMessage = error.message;
                // ..
            });
    }
</code>```

Has someone some insights for me, why this isn't working? I get my auth like this:

```<code>this.firebaseApp = initializeApp(environment.firebaseConfig);
this.auth = getAuth(firebaseApp);
</code>```

I am using the Firebase Modular SDK (V9.0.0+).

I would be really grateful if someone can help me!
Cheers!

答:
Where are you getting environment from? If you are getting it correctly and environment.firebaseConfig is not undefined then this should work.

```<code>import { initializeApp } from 'firebase/app';
import { getAuth, sendPasswordResetEmail } from "firebase/auth";

const app = initializeApp(environment.firebaseConfig);
const auth = getAuth();
sendPasswordResetEmail(auth, email)
  .then(() => {
    // Password reset email sent!
  })
  .catch((error) => {
    const errorCode = error.code;
    const errorMessage = error.message;
  });
</code>```

Body:
I have a problem concerning my application using firebase: If I want to enable the users to reset their password themselves firebase doesn't send an email to their address. If I do it myself from the firebase console it works fine. I'm trying it like this:

   resetPassword(email: string) {
        sendPasswordResetEmail(this.auth, email)
            .then(() => {
                // Password reset email sent!
                // ..
            })
            .catch((error) => {
                const errorCode = error.code;
                const errorMessage = error.message;
                // ..
            });
    }

Has someone some insights for me, why this isn't working? I get my auth like this:

this.firebaseApp = initializeApp(environment.firebaseConfig);
this.auth = getAuth(firebaseApp);

I am using the Firebase Modular SDK (V9.0.0+).

I would be really grateful if someone can help me!
Cheers!

Body:
Where are you getting environment from? If you are getting it correctly and environment.firebaseConfig is not undefined then this should work.

import { initializeApp } from 'firebase/app';
import { getAuth, sendPasswordResetEmail } from "firebase/auth";

const app = initializeApp(environment.firebaseConfig);
const auth = getAuth();
sendPasswordResetEmail(auth, email)
  .then(() => {
    // Password reset email sent!
  })
  .catch((error) => {
    const errorCode = error.code;
    const errorMessage = error.message;
  });


问:
Using a list of lists containing indexes to pull strings by index from another list
I have a list of lists that contain integers. These integers are indexes for each element in the list of strings. I need to use the list of indexes to select the correct string from the list of strings; creating a new list of lists of the just the selected strings. Sorry for the tongue twister of an explanation, I tried to make it is clear as possible. Below is a simple example of what I am trying to achieve.</p>
```<code>list_of_indexes=[[0,2,4],[5,7,6],[1,9]]

list_of_text=['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']

desired_output = [['a','c','e'], ['f', 'h', 'g'], ['b', 'j']]
</code>```

答:
<pre class="lang-py prettyprint-override"><code>[[list_of_text[idx-1] for idx in indices] for indices in list_of_indexes]
</code>```

Body:
I have a list of lists that contain integers. These integers are indexes for each element in the list of strings. I need to use the list of indexes to select the correct string from the list of strings; creating a new list of lists of the just the selected strings. Sorry for the tongue twister of an explanation, I tried to make it is clear as possible. Below is a simple example of what I am trying to achieve.

list_of_indexes=[[0,2,4],[5,7,6],[1,9]]

list_of_text=['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']

desired_output = [['a','c','e'], ['f', 'h', 'g'], ['b', 'j']]


问:
Converting Nested Subqueries into Mini Queries
I have a lot of trouble reading nested subqueries - I personally prefer to write several mini queries and work from there. I understand that more advanced SQL users find it more efficient to write nested subqueries.

For instance, in the following query:

```<code>select distinct b.table_b, a.*
from table_a a
inner join table_c b
on a.id_1 = b.id_1
inner join ( select a.id_1, max(a.var_1) as max_var_1 from table_a a
group by a.id_1) c
on a.id_1 = b.id_1 and a.var_1 = c.max_var_1
</code>```

Problem: I am trying to turn this into several different queries:

#PART 1 :

```<code>create table_1 as select distinct b.table_b, a.*
from table_a a
inner join table_c b
on a.id_1 = b.id_1
</code>```

#PART 2:

```<code> create table_2 as select a.id_1, max(a.var_1) as max_var_1 from table_a a
group by a.id_1
</code>```

#PART 3 (final result: final_table)

```<code>create final_table as select a.*, b.*
from table_1 a
inner join table_2 b
on a.id_1 = b.id_1 and a.var_1 = b.max_var_1
</code>```

My Question: Can someone please tell me if this is correct? Is this how the above nested subquery can be converted into 3 mini queries?

答:
Subqueries are only inserted into separate tables when you use them multiple times. And yet, if the result of the subquery returns many records, then it is not recommended to insert them separately into the table. Because when you are using only select DB will only read data from the disc, but when using insert command, DB will write to disc. Inserting many records may be long process than selecting.

P.S. Mostly used "create temporary table" when inserting subquery process.

Another good way is to use "CTE (Common Table Expression)". When using "CTE", the database stores the results of "SELECT" queries in RAM, executing the subquery only once. If then subqueries are then used multiple times, the database only uses the results from RAM (not executing).

Body:
I have a lot of trouble reading nested subqueries - I personally prefer to write several mini queries and work from there. I understand that more advanced SQL users find it more efficient to write nested subqueries.

For instance, in the following query:

select distinct b.table_b, a.*
from table_a a
inner join table_c b
on a.id_1 = b.id_1
inner join ( select a.id_1, max(a.var_1) as max_var_1 from table_a a
group by a.id_1) c
on a.id_1 = b.id_1 and a.var_1 = c.max_var_1

Problem: I am trying to turn this into several different queries:

#PART 1 :

create table_1 as select distinct b.table_b, a.*
from table_a a
inner join table_c b
on a.id_1 = b.id_1

#PART 2:

 create table_2 as select a.id_1, max(a.var_1) as max_var_1 from table_a a
group by a.id_1

#PART 3 (final result: final_table)

create final_table as select a.*, b.*
from table_1 a
inner join table_2 b
on a.id_1 = b.id_1 and a.var_1 = b.max_var_1

My Question: Can someone please tell me if this is correct? Is this how the above nested subquery can be converted into 3 mini queries?


问:
Get systime from datetime
I got a variable with a timestamp in datetime format:

2022-02-10 11:37:43.253630

And I want theequivalent value in systime (for unix)

答:
I think you want:

>>> from datetime import datetime as dt
>>> dt.strptime('2022-02-10 11:37:43.253630','%Y-%m-%d %H:%M:%S.%f')
datetime.datetime(2022, 2, 10, 11, 37, 43, 253630)
>>> x = dt.strptime('2022-02-10 11:37:43.253630','%Y-%m-%d %H:%M:%S.%f')
>>> help(x.timestamp)
Help on built-in function timestamp:

timestamp(...) method of datetime.datetime instance
    Return POSIX timestamp as float.
>>> x.timestamp()
1644521863.25363
```

Title: Get systime from datetime


问:
ValueError: axes don't match array encountered while using MTCNN
I am trying to find faces in a greyscale Image of size (48 x 48). The code is pretty straightforward here, however I am unable to find what's wrong with the input.

np.expand_dims was used because the detector needs shape in the form of (x, y, z). Since the images I am using are greyscale, they are in 48 x 48 and there is no third axis as compared to what RGB images have.

    from PIL import Image
    import numpy as np
    import os
    path = './Dataset/anger/'
    detector = mtcnn.MTCNN()
    pixels = np.asarray(np.expand_dims(Image.open(os.path.join(path, os.listdir(path)[0])), -1))
    print(pixels.shape)
    # detect faces in the image
    faces = detector.detect_faces(pixels)
    for face in faces:
        print(face)
```
<p>This is the output and tracebacks:</p>
```(48, 48, 1)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-7-ec1134efa98f> in <module>()
      7 print(pixels.shape)
      8 # detect faces in the image
----> 9 faces = detector.detect_faces(pixels)
     10 for face in faces:
     11     print(face)

3 frames
/usr/local/lib/python3.7/dist-packages/mtcnn/mtcnn.py in detect_faces(self, img)
    298         # We pipe here each of the stages
    299         for stage in stages:
--> 300             result = stage(img, result[0], result[1])
    301
    302         [total_boxes, points] = result

/usr/local/lib/python3.7/dist-packages/mtcnn/mtcnn.py in __stage1(self, image, scales, stage_status)
    338
    339             img_x = np.expand_dims(scaled_image, 0)
--> 340             img_y = np.transpose(img_x, (0, 2, 1, 3))
    341
    342             out = self._pnet.predict(img_y)

<__array_function__ internals> in transpose(*args, **kwargs)

/usr/local/lib/python3.7/dist-packages/numpy/core/fromnumeric.py in transpose(a, axes)
    651
    652     """
--> 653     return _wrapfunc(a, 'transpose', axes)
    654
    655

/usr/local/lib/python3.7/dist-packages/numpy/core/fromnumeric.py in _wrapfunc(obj, method, *args, **kwds)
     56
     57     try:
---> 58         return bound(*args, **kwds)
     59     except TypeError:
     60         # A TypeError occurs if the object does have such a method in its

ValueError: axes don't match array
```

Python version: 3.8
Mtcnn version: 0.1.0

答:
Figured it out...
The problem was that MTCNN doesn't work with Greyscale Images and had to do something to mimic the RGB images, so I repeated the matrix thrice to make it
so that the shape looked something like (length, width, 3) by using np.repeat({48 x 48 matrix}, 3, axis=-1)

So if you are facing a similar problem as me where the data resembles that of FER2013 challenge dataset and looks like

```<code>       0                                                  1
0      0  126 69 48 71 84 90 93 87 97 107 116 115 106 10...
1      0  62 83 105 82 30 17 33 35 33 38 25 14 44 95 110...
2      0  204 199 186 171 112 52 45 43 37 50 68 80 86 89...
3      0  105 130 127 93 110 142 133 131 140 142 145 147...
4      0  187 187 187 187 187 187 187 187 184 184 187 18...
...   ..                                                ...
31282  6  106 101 85 98 89 84 88 119 82 105 87 60 76 98 ...
31283  6  29 26 19 18 28 21 16 23 29 18 22 18 17 13 12 1...
31284  6  24 22 25 21 20 23 29 31 34 42 52 57 64 64 69 6...
31285  6  5 4 5 9 10 9 10 12 8 14 13 17 24 26 36 48 67 7...
31286  6  103 132 154 165 176 182 190 195 201 203 208 21...

</code>```

Where col 0 is the class and col 1 is the image data which is basically a string where the pixel data is separated using a space, here's a funky one-liner you can try to preprocess the data the way MTCNN likes it.

```<code>test_df.iloc[:, 1] = np.asarray(map(lambda x: np.repeat(np.expand_dims(np.reshape([np.float32(l) for l in x.split()], (48, 48)), axis=-1), 3, axis=-1), test_df.iloc[:, 1]))
</code>```

Note that test_df is a simple pd.read_csv() result of the data that i talked about above.

Body:
I am trying to find faces in a greyscale Image of size (48 x 48). The code is pretty straightforward here, however I am unable to find what's wrong with the input.

np.expand_dims was used because the detector needs shape in the form of (x, y, z). Since the images I am using are greyscale, they are in 48 x 48 and there is no third axis as compared to what RGB images have.

    from PIL import Image
    import numpy as np
    import os
    path = './Dataset/anger/'
    detector = mtcnn.MTCNN()
    pixels = np.asarray(np.expand_dims(Image.open(os.path.join(path, os.listdir(path)[0])), -1))
    print(pixels.shape)
    # detect faces in the image
    faces = detector.detect_faces(pixels)
    for face in faces:
        print(face)

This is the output and tracebacks:

(48, 48, 1)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-7-ec1134efa98f> in <module>()
      7 print(pixels.shape)
      8 # detect faces in the image
----> 9 faces = detector.detect_faces(pixels)
     10 for face in faces:
     11     print(face)

3 frames
/usr/local/lib/python3.7/dist-packages/mtcnn/mtcnn.py in detect_faces(self, img)
    298         # We pipe here each of the stages
    299         for stage in stages:
--> 300             result = stage(img, result[0], result[1])
    301
    302         [total_boxes, points] = result

/usr/local/lib/python3.7/dist-packages/mtcnn/mtcnn.py in __stage1(self, image, scales, stage_status)
    338
    339             img_x = np.expand_dims(scaled_image, 0)
--> 340             img_y = np.transpose(img_x, (0, 2, 1, 3))
    341
    342             out = self._pnet.predict(img_y)

<__array_function__ internals> in transpose(*args, **kwargs)

/usr/local/lib/python3.7/dist-packages/numpy/core/fromnumeric.py in transpose(a, axes)
    651
    652     """
--> 653     return _wrapfunc(a, 'transpose', axes)
    654
    655

/usr/local/lib/python3.7/dist-packages/numpy/core/fromnumeric.py in _wrapfunc(obj, method, *args, **kwds)
     56
     57     try:
---> 58         return bound(*args, **kwds)
     59     except TypeError:
     60         # A TypeError occurs if the object does have such a method in its

ValueError: axes don't match array

Python version: 3.8
Mtcnn version: 0.1.0

Body:
Figured it out...
The problem was that MTCNN doesn't work with Greyscale Images and had to do something to mimic the RGB images, so I repeated the matrix thrice to make it
so that the shape looked something like (length, width, 3) by using np.repeat({48 x 48 matrix}, 3, axis=-1)

So if you are facing a similar problem as me where the data resembles that of FER2013 challenge dataset and looks like

       0                                                  1
0      0  126 69 48 71 84 90 93 87 97 107 116 115 106 10...
1      0  62 83 105 82 30 17 33 35 33 38 25 14 44 95 110...
2      0  204 199 186 171 112 52 45 43 37 50 68 80 86 89...
3      0  105 130 127 93 110 142 133 131 140 142 145 147...
4      0  187 187 187 187 187 187 187 187 184 184 187 18...
...   ..                                                ...
31282  6  106 101 85 98 89 84 88 119 82 105 87 60 76 98 ...
31283  6  29 26 19 18 28 21 16 23 29 18 22 18 17 13 12 1...
31284  6  24 22 25 21 20 23 29 31 34 42 52 57 64 64 69 6...
31285  6  5 4 5 9 10 9 10 12 8 14 13 17 24 26 36 48 67 7...
31286  6  103 132 154 165 176 182 190 195 201 203 208 21...

Where col 0 is the class and col 1 is the image data which is basically a string where the pixel data is separated using a space, here's a funky one-liner you can try to preprocess the data the way MTCNN likes it.

test_df.iloc[:, 1] = np.asarray(map(lambda x: np.repeat(np.expand_dims(np.reshape([np.float32(l) for l in x.split()], (48, 48)), axis=-1), 3, axis=-1), test_df.iloc[:, 1]))

Note that test_df is a simple pd.read_csv() result of the data that i talked about above.


答:
You can run your function on the order.type like this:

```<code>{orderList.map(order => (
          <OrderCard
            key={order.orderId}
            customerName={order.customer?.name}
            orderType={orderTypeToJSON(order.type)}  // here
            batchId={order.batchId}
            batchedOrderTitle="BATCHED"
            groupId={order.groupId}
            groupedOrderTitle="GROUPED"
            address={order.address}
            driverName={order.assignedDriverId}
          />
        ))}
</code>```

have a look at the ts-playground here

Title: How to convert enum number to string in React with Typescript?

Body:
My enum looks like this:

export enum OrderType {
  ORDER_TYPE_UNSPECIFIED = 0,
  ASAP = 1
  SCHEDULED = 2
  CATERING = 4,
  UNRECOGNIZED = -1,
}

Below I already have a function orderTypeToJSON:

export function orderTypeToJSON(object: OrderType): string {
  switch (object) {
    case OrderType.ORDER_TYPE_UNSPECIFIED:
      return 'ORDER_TYPE_UNSPECIFIED';
    case OrderType.ASAP:
      return 'ASAP';
    case OrderType.SCHEDULED:
      return 'SCHEDULED';
    case OrderType.CATERING:
      return 'CATERING';
    default:
      return 'UNKNOWN';
  }
}

In OrderList component I map through orders (3 orders with corresponding OrderTypes: OrderType.ASAP, OrderType.SCHEDULED, OrderType.CATERING) and for each order return OrderCard:

 {orderList.map(order => (
          <OrderCard
            key={order.orderId}
            customerName={order.customer?.name}
            orderType={order.type}
            batchId={order.batchId}
            batchedOrderTitle="BATCHED"
            groupId={order.groupId}
            groupedOrderTitle="GROUPED"
            address={order.address}
            driverName={order.assignedDriverId}
          />
        ))}

In browser it displays 1, 2 or 4. Instead, I need to display 'ASAP' as a string (if it's 1), 'SCHEDULED' if it's 2 and 'CATERING' if it's 4.

NOTE: I'm not allowed to touch enum or somehow change it at all.

I've tried using conditional rendering in OrderCard like:

{OrderType.ASAP &&
ASAP
}
{OrderType.SCHEDULED &&
SCHEDULED
}
{OrderType.CATERING &&
CATERING
}

When I do that it overrides all orders and displays only 'ASAP' for all 3 orders.

The following logic didn't work as well:

{OrderType.ASAP ? (

ASAP

        ) : OrderType.SCHEDULED ? (

SCHEDULED

        ) : (

CATERING

        )}

I assume I need to use function orderTypeToJSON but I don't know where to put it (in parent component OrderList or in child OrderCard) and how to apply it in render method so it shows strings 'ASAP', 'SCHEDULED' and 'CATERING'.

Any advice is appreciated.

Body:
You can run your function on the order.type like this:

{orderList.map(order => (
          <OrderCard
            key={order.orderId}
            customerName={order.customer?.name}
            orderType={orderTypeToJSON(order.type)}  // here
            batchId={order.batchId}
            batchedOrderTitle="BATCHED"
            groupId={order.groupId}
            groupedOrderTitle="GROUPED"
            address={order.address}
            driverName={order.assignedDriverId}
          />
        ))}

have a look at the ts-playground <a href="https://www.typescriptlang.org/play?#code/KYOwrgtgBA8gTgE2HAKgTwA7CgbwFBSwBKAIgKJED6KAmgApmUCqAcgMoMDCAkgGLdkSUALxQADABoCUAIJsZdEVACMUwm04AJQUwAygpQCY1UTjJQVuLAOJKALCdZEynGNZbcAWgdEBaVXgAvnh4AGZgIADGAC4AlgD2IFDxiMjoWCjxAFJsMCwAFPEARgBWwDEAXLCpqJjAAJRVAM7RcLEgAOa40k0A7rHRkQAWUIWl5dH13YSEkQCGTdjwSLVYAHQwpBTU9IysHC58AiQV0jNQcMDRYHBJAESb5FS0DMzsXEeCdwDcZ1Dzi2qK3SwDWcgUp3OhEu11uUDu4LoPz%20AKWNRBaw02hIekEkKhMJu9yxOn0JGR51RQLSdTWZgsRCs1nx50JcLu9MsNgpMyQoTmYAANtEWTM2fdWABpFgwADqLB5wWCeEiiRayRquli6tEAG1pDgoNE6lVljT1oioIETIbjVhTejaSScWSrTajSbqatQZzGTY3XgALq-PApFZalprCBzDD5Qo1KbCAB8-zV8UFoMF8Q68eBdUyOTyueQaztDXq9V%20QA" rel="nofollow noreferrer">here


问:
How to strike optgroup label out
I would like to strike the label of optgroup. It looks like text-decoration style property does not have any effect on optgroup label appearance. Sample code:

```<code><select>
  <option value="">-- Select fruit-- </option>
  <optgroup label="Fruit" style="color: red; font-size: 16px; text-decoration: line-through;">
    <option value="apple">Apple</option>
    <option value="peach">Peach</option>
  </optgroup>
</select>
</code>```

Changes of color, and font-size work, but text-decoration does not.
Any ideas how I can achieve such text style?
Thank you very much

答:
See the below CSS selector and its styling:

optgroup[label="Fruit"] {
  color: red;
  text-decoration: line-through;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><select size="4">
  <option value="">-- Select fruit --</option>
  <optgroup label="Fruit">
    <option value="apple">Apple</option>
    <option value="peach">Peach</option>
  </optgroup>
</select></code>```

Title: How to strike optgroup label out

Body:
I would like to strike the label of optgroup. It looks like text-decoration style property does not have any effect on optgroup label appearance. Sample code:

<select>
  <option value="">-- Select fruit-- </option>
  <optgroup label="Fruit" style="color: red; font-size: 16px; text-decoration: line-through;">
    <option value="apple">Apple</option>
    <option value="peach">Peach</option>
  </optgroup>
</select>

Changes of color, and font-size work, but text-decoration does not.
Any ideas how I can achieve such text style?
Thank you very much

Body:
See the below CSS selector and its styling:

optgroup[label="Fruit"] {
  color: red;
  text-decoration: line-through;
}

<select size="4">
  <option value="">-- Select fruit --</option>
  <optgroup label="Fruit">
    <option value="apple">Apple</option>
    <option value="peach">Peach</option>
  </optgroup>
</select>


问:
Why does this variadic tuple type with a union not appear to allow a matching type?
This code appears to compile in TS 4.3, but not before that (i.e. 4.0.5, etc). It's confusing to me why adding a union to undefined causes the 2nd assignment to not compile. I'm trying to understand what changed that allows this to work in 4.3, but I'm unsure of what to search for (like a bug fix, etc). Also, I'm looking for a proper workaround before TS 4.3 to be used until the version can be upgraded. For instance, should I just add | undefined on the the type definition of y, or is there another way to get the types to fit for the 2nd assignment?

```<code>export type StringKeyOf<T> = Extract<keyof T, string>;

export interface GenericEvent<TEventName, TData> {
  eventName: TEventName;
  data: TData;
}

export type EventTypeByEventName = {
  [eventName: string]: any;
};

export type GenericEventsFromMap<TEventMap extends EventTypeByEventName, K2 extends keyof TEventMap> = {
  [K in K2]: GenericEvent<K, TEventMap[K]>;
}[K2];

export class EventService<TEventMap extends EventTypeByEventName> {
  public setup<T extends Array<StringKeyOf<TEventMap>>>(managerId: string, eventNames: [...T]) {
    const y: GenericEvent<T[number], TEventMap[T[number]]> = null as any;

    // this assignment works
    const z: GenericEventsFromMap<TEventMap, T[number]> = y;

    // this assignment gives:
    // Type 'GenericEvent<T[number], TEventMap[T[number]]>' is not assignable to type 'GenericEventsFromMap<TEventMap, T[number]>'.
    const z2: GenericEventsFromMap<TEventMap, T[number]> | undefined = y;
  }
}
</code>```

playground link

答:
The bug in question was microsoft/TypeScript#43152, and was fixed in microsoft/TypeScript#43202, which was merged into the main  branch on 2021-03-19 and eventually released with TypeScript 4.3.

How did I find this?  If you go to https://typescript.azureedge.net/indexes/pre-releases.json you will see a list of TypeScript pre-release versions that you can use in The TypeScript Playground with the ts= query parameter.  Via binary search, you can fairly quickly locate the last version where the bug is present and the first version where the bug is absent.

In your case, the bug was present in 4.3.0-dev.20210316 but absent in 4.3.0-dev.20210323.  That means we'd need to search for pull requests merged between 2021-03-16 and 2021-03-23 and find which one is appropriate.  If we add the "union" and "undefined" terms to our search it narrows things down even further.

As for a workaround for those unlucky enough to be stuck on a version with this bug, it's not clear what a good one is.  Many obvious fixes fail run into the same bug, since there's no good reason why X should not be assignable to X | undefined.  The following type assertion seems to work:

```<code>const z: GenericEventsFromMap<TEventMap, T[number]> | undefined =
  y as typeof y | undefined; // okay
</code>```

But whether or not it's advisable is hard to say.

Playground link

Body:
This code appears to compile in TS 4.3, but not before that (i.e. 4.0.5, etc). It's confusing to me why adding a union to undefined causes the 2nd assignment to not compile. I'm trying to understand what changed that allows this to work in 4.3, but I'm unsure of what to search for (like a bug fix, etc). Also, I'm looking for a proper workaround before TS 4.3 to be used until the version can be upgraded. For instance, should I just add | undefined on the the type definition of y, or is there another way to get the types to fit for the 2nd assignment?

export type StringKeyOf<T> = Extract<keyof T, string>;

export interface GenericEvent<TEventName, TData> {
  eventName: TEventName;
  data: TData;
}

export type EventTypeByEventName = {
  [eventName: string]: any;
};

export type GenericEventsFromMap<TEventMap extends EventTypeByEventName, K2 extends keyof TEventMap> = {
  [K in K2]: GenericEvent<K, TEventMap[K]>;
}[K2];

export class EventService<TEventMap extends EventTypeByEventName> {
  public setup<T extends Array<StringKeyOf<TEventMap>>>(managerId: string, eventNames: [...T]) {
    const y: GenericEvent<T[number], TEventMap[T[number]]> = null as any;

    // this assignment works
    const z: GenericEventsFromMap<TEventMap, T[number]> = y;

    // this assignment gives:
    // Type 'GenericEvent<T[number], TEventMap[T[number]]>' is not assignable to type 'GenericEventsFromMap<TEventMap, T[number]>'.
    const z2: GenericEventsFromMap<TEventMap, T[number]> | undefined = y;
  }
}

<a href="https://www.typescriptlang.org/play?target=2&module=6&ts=4.0.5#code/KYDwDg9gTgLgBDAnmYcDKMoEsB2BzAaWEQHkAzAHgBUA+OAXjgFERMBDAYxgoGtiIycKgBo4AZ0y48NANwAoOaEiw4uGMChlOqAOLAcGrByYA3fdyqnzAOTYBbYKKoARNjDZ0A3nLhxgZnBhbBwAuIStA4OB5XwATNzYwlwT5AF8FJWh4JBRmAJgqZGAAIUQIoPtURm9fAG1-G0qwiWx8AF0wthxENPlFcCyEIrg9A2xjfLEAMSgIOwBZNjBqcsWwP1Z9WLE880KUUvKo0QIAJg31HG24PkQBcPy1umqfOFqCVRw4M46R-UMJuYKAQnKslu82rI5Kl3qc2n1MioOAAbNhiHblNAaExGYArR5LC5bDH5fYlMr5KJeV5gACuACNkUZxMAYLTllQiVcdgBBKBQNiICgYVqEYjkfHmJ40GgACjsXTYeA0AElYs1JPhRA1IpUxGFagA6Y1UNoASjgNV8cA4EBwEjgiDCowB5WotRwtLs9I0bVBBLAtSoHq9PqgbUhDDgnuRyLgaPj3Ri1tevgA9GmEAALLA7NFiLB4HAOQJwADu0B4YlTNrtDoAXs7-uNytNZgslpLAmsnCHvb7no6+ta4Bns7n4+jC8XzHA8FgzPqa2OyXAAOQulv5d2e-vh-1S8HB3dhiM0NeqHY4CDwfPTtiM1AwCBDXIb5tGVszOZrLswHtCH2p7noaNa2va8D1qcTZjJ+kzfh2HJgmAvYngOcAAD5wLSVzAGQuDALEUY9K86SpEAA" rel="nofollow noreferrer">playground link

Body:
The bug in question was microsoft/TypeScript#43152, and was fixed in microsoft/TypeScript#43202, which was merged into the main  branch on 2021-03-19 and eventually released with TypeScript 4.3.

How did I find this?  If you go to https://typescript.azureedge.net/indexes/pre-releases.json you will see a list of TypeScript pre-release versions that you can use in The TypeScript Playground with the ts= query parameter.  Via binary search, you can fairly quickly locate the last version where the bug is present and the first version where the bug is absent.

In your case, the bug was <a href="https://www.typescriptlang.org/play?target=2&module=6&ts=4.3.0-dev.20210316#code/KYDwDg9gTgLgBDAnmYcDKMoEsB2BzAaWEQHkAzAHgBUA+OAXjgFERMBDAYxgoGtiIycKgBo4AZ0y48NANwAoOaEiw4uGMChlOqAOLAcGrByYA3fdyqnzAOTYBbYKKoARNjDZ0A3nLhxgZnBhbBwAuIStA4OB5XwATNzYwlwT5AF8FJWh4JBRmAJgqZGAAIUQIoPtURm9fAG1-G0qwiWx8AF0wthxENPlFcCyEIrg9A2xjfLEAMSgIOwBZNjBqcsWwP1Z9WLE880KUUvKo0QIAJg31HG24PkQBcPy1umqfOFqCVRw4M46R-UMJuYKAQnKslu82rI5Kl3qc2n1MioOAAbNhiHblNAaExGYArR5LC5bDH5fYlMr5KJeV5gACuACNkUZxMAYLTllQiVcdgBBKBQNiICgYVqEYjkfHmJ40GgACjsXTYeA0AElYs1JPhRA1IpUxGFagA6Y1UNoASjgNV8cA4EBwEjgiDCowB5WotRwtLs9I0bVBBLAtSoHq9PqgbUhDDgnuRyLgaPj3Ri1tevgA9GmEAALLA7NFiLB4HAOQJwADu0B4YlTNrtDoAXs7-uNytNZgslpLAmsnCHvb7no6+ta4Bns7n4+jC8XzHA8FgzPqa2OyXAAOQulv5d2e-vh-1S8HB3dhiM0NeqHY4CDwfPTtiM1AwCBDXIb5tGVszOZrLswHtCH2p7noaNa2va8D1qcTZjJ+kzfh2HJgmAvYngOcAAD5wLSVzAGQuDALEUY9K86SpEAA" rel="nofollow noreferrer">present in 4.3.0-dev.20210316 but <a href="https://www.typescriptlang.org/play?target=2&module=6&ts=4.3.0-dev.20210323#code/KYDwDg9gTgLgBDAnmYcDKMoEsB2BzAaWEQHkAzAHgBUA+OAXjgFERMBDAYxgoGtiIycKgBo4AZ0y48NANwAoOaEiw4uGMChlOqAOLAcGrByYA3fdyqnzAOTYBbYKKoARNjDZ0A3nLhxgZnBhbBwAuIStA4OB5XwATNzYwlwT5AF8FJWh4JBRmAJgqZGAAIUQIoPtURm9fAG1-G0qwiWx8AF0wthxENPlFcCyEIrg9A2xjfLEAMSgIOwBZNjBqcsWwP1Z9WLE880KUUvKo0QIAJg31HG24PkQBcPy1umqfOFqCVRw4M46R-UMJuYKAQnKslu82rI5Kl3qc2n1MioOAAbNhiHblNAaExGYArR5LC5bDH5fYlMr5KJeV5gACuACNkUZxMAYLTllQiVcdgBBKBQNiICgYVqEYjkfHmJ40GgACjsXTYeA0AElYs1JPhRA1IpUxGFagA6Y1UNoASjgNV8cA4EBwEjgiDCowB5WotRwtLs9I0bVBBLAtSoHq9PqgbUhDDgnuRyLgaPj3Ri1tevgA9GmEAALLA7NFiLB4HAOQJwADu0B4YlTNrtDoAXs7-uNytNZgslpLAmsnCHvb7no6+ta4Bns7n4+jC8XzHA8FgzPqa2OyXAAOQulv5d2e-vh-1S8HB3dhiM0NeqHY4CDwfPTtiM1AwCBDXIb5tGVszOZrLswHtCH2p7noaNa2va8D1qcTZjJ+kzfh2HJgmAvYngOcAAD5wLSVzAGQuDALEUY9K86SpEAA" rel="nofollow noreferrer">absent in 4.3.0-dev.20210323.  That means we'd need to search for pull requests merged between 2021-03-16 and 2021-03-23 and find which one is appropriate.  If we add the "union" and "undefined" terms to our search it narrows things down even further.

As for a workaround for those unlucky enough to be stuck on a version with this bug, it's not clear what a good one is.  Many obvious fixes fail run into the same bug, since there's no good reason why X should not be assignable to X | undefined.  The following type assertion seems to work:

const z: GenericEventsFromMap<TEventMap, T[number]> | undefined =
  y as typeof y | undefined; // okay

But whether or not it's advisable is hard to say.

<a href="https://www.typescriptlang.org/play?target=2&module=6&ts=4.0.5#code/KYDwDg9gTgLgBDAnmYcDKMoEsB2BzAaWEQHkAzAHgBUA+OAXjgFERMBDAYxgoGtiIycKgBo4AZ0y48NANwAoOaEiw4uGMChlOqAOLAcGrByYA3fdyqnzAOTYBbYKKoARNjDZ0A3nLhxgZnBhbBwAuIStA4OB5XwATNzYwlwT5AF8FJWh4JBRmAJgqZGAAIUQIoPtURm9fAG1-G0qwiWx8AF0wthxENPlFcCyEIrg9A2xjfLEAMSgIOwBZNjBqcsWwP1Z9WLE880KUUvKo0QIAJg31HG24PkQBcPy1umqfOFqCVRw4M46R-UMJuYKAQnKslu82rI5Kl3qc2n1MioOAAbNhiHblNAaExGYArR5LC5bDH5fYlMr5KJeV5gACuACNkUZxMAYLTllQiVcdgBBKBQNiICgYVqEYjkfHmJ40GgACjsXTYeA0AElYs1JPhRA1IpUxGFagA6Y1UNoASjgNV8cA4EBwEjgiDCowB5WotRwtLs9I0bVBBLAtSoHq9PqgbUhDDgnuRyLgaPj3Ri1tt9vgAC9nf9xuVprMFktJYE1k4Q97fXQAD5wWlXYBkXDAWJRxDxnY5YD3VvV2uxeuN2IyOAAemHcAgPEFr3SqSAA" rel="nofollow noreferrer">Playground link


问:
How to tell, whether a C++ proposal is accepted or not?
Let's take P1907 as an example. Is it accepted into the C++ standard? To which version? When?</p>

答:
The papers are managed on Github:
https://github.com/cplusplus/papers/issues?q=

https://github.com/cplusplus/papers/issues/653

You can also look into the compiler compatibility page of cppreference: https://en.cppreference.com/w/cpp/compiler_support/20


问:
How to run script from script AppsScripts?
I have script that uses whole limit time for scripts(6 minutes).
So I decided just to make my job in parts. So I have script "Generate words". I need to run this scripts,and after "generate words" I need to do it again. Also I need to run it with arguments, so for example:  "generate words(0,2)".

I cant just call this function again because of this time limit from AppsScripts.

So,I need to run script with arguments, from script, but to run it in other session, so time limit wont be exceeded.

答:
To pass arguments to a function, you need to use a function that pase those arguments, i.e., let say that you want to execute a function called something but it requires two parameters, a, and b, first create a function (in the below example it's named main, that will pass such paramenters, the call this new function from the Editor toolbar  :

```<code>function main(){
  const a = 'A';
  const b = 'B';
  something(a,b)
}

function something(a,b){
   console.log(`${a} - ${b}`)
}
</code>```

If the arguments to be passed are calculated by other functions, you might save them using the Properties Service or another stuff like a spreadsheet.

Related

launching a function with parameters

How can I test a trigger function in GAS?

How to Pass The Values of Function Parameters and run Standalone Google Apps Script?

Body:
To pass arguments to a function, you need to use a function that pase those arguments, i.e., let say that you want to execute a function called something but it requires two parameters, a, and b, first create a function (in the below example it's named main, that will pass such paramenters, the call this new function from the Editor toolbar  :

function main(){
  const a = 'A';
  const b = 'B';
  something(a,b)
}

function something(a,b){
   console.log(`${a} - ${b}`)
}

If the arguments to be passed are calculated by other functions, you might save them using the Properties Service or another stuff like a spreadsheet.

Related

launching a function with parameters

How can I test a trigger function in GAS?

How to Pass The Values of Function Parameters and run Standalone Google Apps Script?


答:
Papers can be tracked here.

https://github.com/cplusplus/papers/issues

Entering is:issue P1907 into the search box produces:

P1907 (closed)

and

P1907R1 (merged)

Alternatively,

If you use Slack, you can join the C++ slack at cpplang.slack.com and privately message any paper name to @npaperbot to get information about it.

Title: How to tell, whether a C++ proposal is accepted or not?

Body: Let's take P1907 as an example. Is it accepted into the C++ standard? To which version? When?


问:
How to limit draggable scrollable sheet to take height according to its child height in flutter?
I am using draggableScrollableSheet. I am giving these parameters

```<code>DraggableScrollableSheet(initialChildSize: 0.4,maxChildSize: 1,minChildSize: 0.4,builder: (BuildContext context, ScrollController scrollController) {
            return SingleChildScrollView(controller: scrollController,
              child: Theme(
                data: Theme.of(context).copyWith(canvasColor: Colors.transparent),
                child: Opacity(
                  opacity: 1,
                  child: IntrinsicHeight(
                      child: Column(mainAxisSize: MainAxisSize.min,
                        mainAxisAlignment: MainAxisAlignment.start,
                        children: <Widget>[
                          SizedBox(height: 10,),
                          Container(
                            margin: EdgeInsets.only(right: 300),
                            decoration: BoxDecoration(
                              border: Border(
                                top: BorderSide(
                                    color: Colors.blue,
                                    width: 3,
                                    style: BorderStyle.solid),
                              ),
                            ),
                          ),
                          Card(
                            child: Row(
                              children: <Widget>[
                                Padding(
                                  padding: const EdgeInsets.all(8.0),
                                  child: Column(
                                    crossAxisAlignment:
                                    CrossAxisAlignment.start,
                                    children: <Widget>[
                                      Text(
                                        S
                                            .of(context)
                                            .we_have_found_you_a_driver,
                                        style: TextStyle(
                                            color: Colors.black,
                                            fontWeight: FontWeight.bold),
                                      ),
                                      SizedBox(
                                        height: 10,
                                      ),
                                      Text(S
                                          .of(context)
                                          .driver_is_heading_towards +
                                          ' ${widget.order.foodOrders.first.food.restaurant.name}')
                                    ],
                                  ),
                                ),
                              ],
                            ),
                            elevation: 5,
                          ),
                          SizedBox(height: 10,),
                          Card(
                            elevation: 5,
                            child: Row(
                                mainAxisAlignment: MainAxisAlignment.start,
                                children: <Widget>[
                                  CircleAvatar(
                                    radius: 50.0,
                                    backgroundColor: Colors.white,
                                    child:
                                    Image.asset(
                                        'assets/img/image_not_available.jpg'),
                                  ),
                                  Expanded(
                                    child: Column(mainAxisAlignment: MainAxisAlignment.start,
                                      children: <Widget>[
                                        Row(mainAxisAlignment: MainAxisAlignment.spaceAround,
                                          children: <Widget>[
                                            Expanded(
                                              child: Text('Test',
                                                  textAlign: TextAlign.start,
                                                  style: new TextStyle(
                                                    color: Colors.black,
                                                    fontSize: 16.0,
                                                  )),
                                            ),
                                            Icon(Icons.star, color: Colors.yellow.shade700,)
                                          ],
                                        ),
                                        SizedBox(height: 30,),
                                        Row(mainAxisAlignment: MainAxisAlignment.spaceAround,
                                          children: <Widget>[
                                            Expanded(
                                              child: Container(
                                                child: Text('Mobile number',
                                                    textAlign: TextAlign.start,
                                                    style: new TextStyle(
                                                      color: Colors.black,
                                                      fontSize: 16.0,
                                                    )),
                                              ),
                                            ),
                                            Icon(Icons.phone,),
                                            SizedBox(width: 10,),
                                            Icon(Icons.message),
                                          ],
                                        ),

                                      ],
                                    ),
                                  )
                                ]),
                          ),
                          SizedBox(height: 10,),
                          Card(
                            child: Align( alignment: Alignment(-1,1),
                              child: Row(mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                children: <Widget>[
                                  Padding(
                                    padding: const EdgeInsets.all(8.0),
                                    child: Column(
                                      crossAxisAlignment:
                                      CrossAxisAlignment.start,
                                      children: <Widget>[
                                        Text(
                                          S
                                              .of(context)
                                              .you_ordered_from + ' ${widget.order.foodOrders.first.food.restaurant.name}',
                                          style: TextStyle(
                                            color: Colors.grey,
                                          ),
                                        ),
                                        SizedBox(
                                          height: 5,
                                        ),
                                        Column(children: List.generate(widget.order.foodOrders.length,(index) {
                                          return Text(
                                              '${widget.order.foodOrders[index].food.name}'
                                          );
                                        },),),
                                        Row(
                                          children: <Widget>[
                                            Column(crossAxisAlignment: CrossAxisAlignment.start,
                                              children: <Widget>[
                                                Text('See details', style: TextStyle(fontWeight: FontWeight.bold,color: Colors.blue),),

                                              ],
                                            ),

                                          ],
                                        ),

                                      ],
                                    ),
                                  ),
                                  Padding(
                                    padding: const EdgeInsets.all(8.0),
                                    child: Column(
                                      children: <Widget>[
                                        SizedBox(height: 40,),
                                        Row(
                                          children: <Widget>[
                                            Icon(Icons.monetization_on),
                                            Text(widget.order.foodOrders
                                                .first.price
                                                .toString()),
                                          ],
                                        ),
                                      ],
                                    ),
                                  ),
                                ],
                              ),
                            ),
                            elevation: 5,
                          ),
                        ],
                      ),
                  ),
                ),
              ),
            )
</code>```

and I also used a single child scroll view and column so that I can show my cards in that column of draggableScrollableSheet. But I want draggableScrollableSheet to take height dynamically instead of defining size. Like now I want to show only 2 to 3 cards and that is taking full screen. But I want it to take the minimum height of the screen. How can we achieve this?

答:
I was struggling with this for a while, and then discovered that the correct way to achieve this is to use ClampingScrollPhysics as the physics parameter of the scroll view.

https://api.flutter.dev/flutter/widgets/ClampingScrollPhysics-class.html

Body:
I am using draggableScrollableSheet. I am giving these parameters

DraggableScrollableSheet(initialChildSize: 0.4,maxChildSize: 1,minChildSize: 0.4,builder: (BuildContext context, ScrollController scrollController) {
            return SingleChildScrollView(controller: scrollController,
              child: Theme(
                data: Theme.of(context).copyWith(canvasColor: Colors.transparent),
                child: Opacity(
                  opacity: 1,
                  child: IntrinsicHeight(
                      child: Column(mainAxisSize: MainAxisSize.min,
                        mainAxisAlignment: MainAxisAlignment.start,
                        children: <Widget>[
                          SizedBox(height: 10,),
                          Container(
                            margin: EdgeInsets.only(right: 300),
                            decoration: BoxDecoration(
                              border: Border(
                                top: BorderSide(
                                    color: Colors.blue,
                                    width: 3,
                                    style: BorderStyle.solid),
                              ),
                            ),
                          ),
                          Card(
                            child: Row(
                              children: <Widget>[
                                Padding(
                                  padding: const EdgeInsets.all(8.0),
                                  child: Column(
                                    crossAxisAlignment:
                                    CrossAxisAlignment.start,
                                    children: <Widget>[
                                      Text(
                                        S
                                            .of(context)
                                            .we_have_found_you_a_driver,
                                        style: TextStyle(
                                            color: Colors.black,
                                            fontWeight: FontWeight.bold),
                                      ),
                                      SizedBox(
                                        height: 10,
                                      ),
                                      Text(S
                                          .of(context)
                                          .driver_is_heading_towards +
                                          ' ${widget.order.foodOrders.first.food.restaurant.name}')
                                    ],
                                  ),
                                ),
                              ],
                            ),
                            elevation: 5,
                          ),
                          SizedBox(height: 10,),
                          Card(
                            elevation: 5,
                            child: Row(
                                mainAxisAlignment: MainAxisAlignment.start,
                                children: <Widget>[
                                  CircleAvatar(
                                    radius: 50.0,
                                    backgroundColor: Colors.white,
                                    child:
                                    Image.asset(
                                        'assets/img/image_not_available.jpg'),
                                  ),
                                  Expanded(
                                    child: Column(mainAxisAlignment: MainAxisAlignment.start,
                                      children: <Widget>[
                                        Row(mainAxisAlignment: MainAxisAlignment.spaceAround,
                                          children: <Widget>[
                                            Expanded(
                                              child: Text('Test',
                                                  textAlign: TextAlign.start,
                                                  style: new TextStyle(
                                                    color: Colors.black,
                                                    fontSize: 16.0,
                                                  )),
                                            ),
                                            Icon(Icons.star, color: Colors.yellow.shade700,)
                                          ],
                                        ),
                                        SizedBox(height: 30,),
                                        Row(mainAxisAlignment: MainAxisAlignment.spaceAround,
                                          children: <Widget>[
                                            Expanded(
                                              child: Container(
                                                child: Text('Mobile number',
                                                    textAlign: TextAlign.start,
                                                    style: new TextStyle(
                                                      color: Colors.black,
                                                      fontSize: 16.0,
                                                    )),
                                              ),
                                            ),
                                            Icon(Icons.phone,),
                                            SizedBox(width: 10,),
                                            Icon(Icons.message),
                                          ],
                                        ),

                                      ],
                                    ),
                                  )
                                ]),
                          ),
                          SizedBox(height: 10,),
                          Card(
                            child: Align( alignment: Alignment(-1,1),
                              child: Row(mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                children: <Widget>[
                                  Padding(
                                    padding: const EdgeInsets.all(8.0),
                                    child: Column(
                                      crossAxisAlignment:
                                      CrossAxisAlignment.start,
                                      children: <Widget>[
                                        Text(
                                          S
                                              .of(context)
                                              .you_ordered_from + ' ${widget.order.foodOrders.first.food.restaurant.name}',
                                          style: TextStyle(
                                            color: Colors.grey,
                                          ),
                                        ),
                                        SizedBox(
                                          height: 5,
                                        ),
                                        Column(children: List.generate(widget.order.foodOrders.length,(index) {
                                          return Text(
                                              '${widget.order.foodOrders[index].food.name}'
                                          );
                                        },),),
                                        Row(
                                          children: <Widget>[
                                            Column(crossAxisAlignment: CrossAxisAlignment.start,
                                              children: <Widget>[
                                                Text('See details', style: TextStyle(fontWeight: FontWeight.bold,color: Colors.blue),),

                                              ],
                                            ),

                                          ],
                                        ),

                                      ],
                                    ),
                                  ),
                                  Padding(
                                    padding: const EdgeInsets.all(8.0),
                                    child: Column(
                                      children: <Widget>[
                                        SizedBox(height: 40,),
                                        Row(
                                          children: <Widget>[
                                            Icon(Icons.monetization_on),
                                            Text(widget.order.foodOrders
                                                .first.price
                                                .toString()),
                                          ],
                                        ),
                                      ],
                                    ),
                                  ),
                                ],
                              ),
                            ),
                            elevation: 5,
                          ),
                        ],
                      ),
                  ),
                ),
              ),
            )

and I also used a single child scroll view and column so that I can show my cards in that column of draggableScrollableSheet. But I want draggableScrollableSheet to take height dynamically instead of defining size. Like now I want to show only 2 to 3 cards and that is taking full screen. But I want it to take the minimum height of the screen. How can we achieve this?


问:
How to convert enum number to string in React with Typescript?
My enum looks like this:

```<code>export enum OrderType {
  ORDER_TYPE_UNSPECIFIED = 0,
  ASAP = 1
  SCHEDULED = 2
  CATERING = 4,
  UNRECOGNIZED = -1,
}
</code>```

Below I already have a function orderTypeToJSON:

```<code>export function orderTypeToJSON(object: OrderType): string {
  switch (object) {
    case OrderType.ORDER_TYPE_UNSPECIFIED:
      return 'ORDER_TYPE_UNSPECIFIED';
    case OrderType.ASAP:
      return 'ASAP';
    case OrderType.SCHEDULED:
      return 'SCHEDULED';
    case OrderType.CATERING:
      return 'CATERING';
    default:
      return 'UNKNOWN';
  }
}
</code>```

In OrderList component I map through orders (3 orders with corresponding OrderTypes: OrderType.ASAP, OrderType.SCHEDULED, OrderType.CATERING) and for each order return OrderCard:

```<code> {orderList.map(order => (
          <OrderCard
            key={order.orderId}
            customerName={order.customer?.name}
            orderType={order.type}
            batchId={order.batchId}
            batchedOrderTitle="BATCHED"
            groupId={order.groupId}
            groupedOrderTitle="GROUPED"
            address={order.address}
            driverName={order.assignedDriverId}
          />
        ))}
</code>```

In browser it displays 1, 2 or 4. Instead, I need to display 'ASAP' as a string (if it's 1), 'SCHEDULED' if it's 2 and 'CATERING' if it's 4.

NOTE: I'm not allowed to touch enum or somehow change it at all.

I've tried using conditional rendering in OrderCard like:

```<code>{OrderType.ASAP && <p>ASAP</p>}
{OrderType.SCHEDULED && <p>SCHEDULED</p>}
{OrderType.CATERING && <p>CATERING</p>}
</code>```

When I do that it overrides all orders and displays only 'ASAP' for all 3 orders.

The following logic didn't work as well:

```<code>{OrderType.ASAP ? (
          <p>ASAP</p>
        ) : OrderType.SCHEDULED ? (
          <p>SCHEDULED</p>
        ) : (
          <p>CATERING</p>
        )}
</code>```

I assume I need to use function orderTypeToJSON but I don't know where to put it (in parent component OrderList or in child OrderCard) and how to apply it in render method so it shows strings 'ASAP', 'SCHEDULED' and 'CATERING'.

Any advice is appreciated.

答:
Just need to write your enum value as follow : OrderType[OrderType.ASAP]. It is a feature of typescript. Here is an example :

import React from 'react';
import { ButtonCounter } from './components/ButtonCounter';

enum OrderType {
  ORDER_TYPE_UNSPECIFIED = 0,
  ASAP = 1,
  SCHEDULED = 2,
  CATERING = 4,
  UNRECOGNIZED = -1,
}

export const App = () => {
  return
{OrderType[OrderType.ASAP]}
;
};
```

This will display ASAP as a string.

Body:
Just need to write your enum value as follow : OrderType[OrderType.ASAP]. It is a feature of typescript. Here is an example :

import React from 'react';
import { ButtonCounter } from './components/ButtonCounter';

enum OrderType {
  ORDER_TYPE_UNSPECIFIED = 0,
  ASAP = 1,
  SCHEDULED = 2,
  CATERING = 4,
  UNRECOGNIZED = -1,
}

export const App = () => {
  return <div>{OrderType[OrderType.ASAP]}</div>;
};

This will display ASAP as a string.


问:
C system call read from stdin and write to a file
I am writing a C program for this: cat file.txt | wc > wc.txt
this is the code:

```<code>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <fcntl.h>

int main(int argc, char *argv[])
{

    int fd, piped[2], pid, p2p0[2];
    pipe(piped);

    pid = fork();

    if (pid == 0)
    {
        close(1);
        dup(piped[1]);
        close(piped[1]);
        close(piped[0]);
        execl("/bin/cat", "cat", "file.txt", (char *)0);
    }

    pipe(p2p0);
    pid = fork();
    if (pid == 0)
    {
        close(0);
        dup(piped[0]);
        close(piped[1]);
        close(piped[0]);

        close(1);
        dup(p2p0[1]);
        close(p2p0[1]);
        close(p2p0[0]);
        execl("/bin/wc", "wc", (char *)0);
    }

    close(piped[1]);
    close(piped[0]);
    close(p2p0[1]);

    close(0);
    dup(p2p0[0]);
    close(p2p0[0]);

    fd = open("wc.txt", O_WRONLY | O_CREAT, 0777);
    close(1);
    dup(fd);
    close(fd);

    return 0;
}

</code>```

the wc.txt file is created, but my program don't print inside wc.txt.

Can you help me?

答:
The pipeline you are creating is essentially

```<code>cat file.txt | wc | true >wc.txt
</code>```

that is, the output of wc is being piped to another process (your parent C program after the forks) that does nothing other than exiting with success.

What you need to do is not create the second pipe, and instead dup the fd from the open("wc.txt", ... to be wc's stdout.

Note that you also don't need the second fork -- since you don't need/want to do anything after wc, you can just do the execl("wc" ... call in the parent process and don't need a second child.

Body:
I am writing a C program for this: cat file.txt | wc > wc.txt
this is the code:

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <fcntl.h>

int main(int argc, char *argv[])
{

    int fd, piped[2], pid, p2p0[2];
    pipe(piped);

    pid = fork();

    if (pid == 0)
    {
        close(1);
        dup(piped[1]);
        close(piped[1]);
        close(piped[0]);
        execl("/bin/cat", "cat", "file.txt", (char *)0);
    }

    pipe(p2p0);
    pid = fork();
    if (pid == 0)
    {
        close(0);
        dup(piped[0]);
        close(piped[1]);
        close(piped[0]);

        close(1);
        dup(p2p0[1]);
        close(p2p0[1]);
        close(p2p0[0]);
        execl("/bin/wc", "wc", (char *)0);
    }

    close(piped[1]);
    close(piped[0]);
    close(p2p0[1]);

    close(0);
    dup(p2p0[0]);
    close(p2p0[0]);

    fd = open("wc.txt", O_WRONLY | O_CREAT, 0777);
    close(1);
    dup(fd);
    close(fd);

    return 0;
}

the wc.txt file is created, but my program don't print inside wc.txt.

Can you help me?

Body:
The pipeline you are creating is essentially

cat file.txt | wc | true >wc.txt

that is, the output of wc is being piped to another process (your parent C program after the forks) that does nothing other than exiting with success.

What you need to do is not create the second pipe, and instead dup the fd from the open("wc.txt", ... to be wc's stdout.

Note that you also don't need the second fork -- since you don't need/want to do anything after wc, you can just do the execl("wc" ... call in the parent process and don't need a second child.