问:
React.js and Firebase querySnapshot.forEach replacing array with identical objects
I've been facing this issue for a couple of days where I have an array named tempTaskArray, which stores objects filled with data taken from my firestore database.

These objects contain the correct data on each iteration of the .forEach method but when put into my state variable, "tasks" (an array), from array tempTaskArray, all objects contain the data of the last created object.

This issue is not run into when I have an array of strings.

See code below:

```<code>      const getTasks = () => {
    db.collection("users").doc(uid).collection("tasks")
    .orderBy("epochdate", "asc")
    .get()
    .then((querySnapshot) => {
        querySnapshot.forEach((doc) => {

          // populates array with strings
          // tempTaskArray.push(doc.data().taskname)

          // tempTaskObject is an empty object
          tempTaskObject.taskname= doc.data().taskname
          tempTaskObject.duedate= doc.data().duedate

          // gets epoch date value and stores it
          var epochDate = doc.data().epochdate;

          // gets current time
          const day = new Date();
          let currentTime = day.getTime();

          // finds time remaining in epoch
          var timeRemaining = epochDate - currentTime;

          // finds how many days are left and rounds down
          var daysLeft = (timeRemaining / 86400000)
          daysLeft = Math.floor(daysLeft)

          tempTaskObject.duein = daysLeft

          tempTaskArray.push(tempTaskObject)

        });
        setTasks(tempTaskArray)

    })
    .catch((error) => {
        console.log("Error getting documents: ", error);
    });
  }
  getTasks();
</code>```

The data taken populating state variable "task" is then rendered in component Task seen below:

```<code>    <div>
      {tasks.map((task) => (
      <Task
        key={task}
        task__title={task.taskname}
        due__date={task.duedate}
        days__away={task.duein}
      />
    ))}
    </div>
</code>```

I would be extremely grateful for an explanation of why this is happening. Thanks in advance

答:
Based on the provided code I believe it's an error of adding the reference of the tempTaskObject to the tempTaskArray and changing the same referenced object on each iteration.

To avoid this you can reassign a new Object to tempTaskObject on every iteration, like

```<code>.then((querySnapshot) => {
    querySnapshot.forEach((doc) => {

      // tempTaskObject is (now really) an empty object
      tempTaskObject = {};
      tempTaskObject.taskname= doc.data().taskname;
</code>```

Further Explanation

I believe it worked before with String types, because these are primitive datatypes which will just be copied into the tempTaskArray.

The current tempTaskObject though has multiple properties (duein, taskname, duedate) and is therefore a complex object. When pushing objects to an javascript array, it adds the reference to the object to the array, NOT a copy. In your example you always keep the reference to the tempTaskObject and that's why it always changes the properties of the exact same object.

Examples

// Array with Primitives
const animalNames = ['Tiger', 'Spider'];
console.log('animalNames', animalNames);
let scaryName = animalNames[1];
scaryName = 'Goldfish';
console.log('still scary animalNames', JSON.stringify(animalNames)); // nothing changed, because we're working with a copy```
</div>
</div>
</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>// Array with Objects
const animals = [{
  name: 'Tiger',
  teeth: 30,
  legs: 4
}, {
  name: 'Spider',
  teeth: 0,
  legs: 8
}];
console.log('animals', animals);
let scaryAnimal = animals[1]; // storing a reference to the spider object
scaryAnimal.name = 'Goldfish';
scaryAnimal.legs = 0;
console.log('less scary animals', animals); // spider got replaced by a goldfish

// Now we'll want to add another animal the WRONG WAY
// FIX: Uncomment line below to properly add a bunny
// scaryAnimal = {};
scaryAnimal.name = 'Bunny';
scaryAnimal.legs = 4;
scaryAnimal.teeth = 2;
animals.push(scaryAnimal);
console.log('duplicated animal', JSON.stringify(animals));</code>```

Edit: Fixed typo

Body:
I've been facing this issue for a couple of days where I have an array named tempTaskArray, which stores objects filled with data taken from my firestore database.

These objects contain the correct data on each iteration of the .forEach method but when put into my state variable, "tasks" (an array), from array tempTaskArray, all objects contain the data of the last created object.

This issue is not run into when I have an array of strings.

See code below:

      const getTasks = () => {
    db.collection("users").doc(uid).collection("tasks")
    .orderBy("epochdate", "asc")
    .get()
    .then((querySnapshot) => {
        querySnapshot.forEach((doc) => {

          // populates array with strings
          // tempTaskArray.push(doc.data().taskname)

          // tempTaskObject is an empty object
          tempTaskObject.taskname= doc.data().taskname
          tempTaskObject.duedate= doc.data().duedate

          // gets epoch date value and stores it
          var epochDate = doc.data().epochdate;

          // gets current time
          const day = new Date();
          let currentTime = day.getTime();

          // finds time remaining in epoch
          var timeRemaining = epochDate - currentTime;

          // finds how many days are left and rounds down
          var daysLeft = (timeRemaining / 86400000)
          daysLeft = Math.floor(daysLeft)

          tempTaskObject.duein = daysLeft

          tempTaskArray.push(tempTaskObject)

        });
        setTasks(tempTaskArray)

    })
    .catch((error) => {
        console.log("Error getting documents: ", error);
    });
  }
  getTasks();

The data taken populating state variable "task" is then rendered in component Task seen below:

      {tasks.map((task) => (
      <Task
        key={task}
        task__title={task.taskname}
        due__date={task.duedate}
        days__away={task.duein}
      />
    ))}

I would be extremely grateful for an explanation of why this is happening. Thanks in advance

Body:
Based on the provided code I believe it's an error of adding the reference of the tempTaskObject to the tempTaskArray and changing the same referenced object on each iteration.

To avoid this you can reassign a new Object to tempTaskObject on every iteration, like

.then((querySnapshot) => {
    querySnapshot.forEach((doc) => {

      // tempTaskObject is (now really) an empty object
      tempTaskObject = {};
      tempTaskObject.taskname= doc.data().taskname;

Further Explanation

I believe it worked before with String types, because these are primitive datatypes which will just be copied into the tempTaskArray.

The current tempTaskObject though has multiple properties (duein, taskname, duedate) and is therefore a complex object. When pushing objects to an javascript array, it adds the reference to the object to the array, NOT a copy. In your example you always keep the reference to the tempTaskObject and that's why it always changes the properties of the exact same object.

Examples

// Array with Primitives
const animalNames = ['Tiger', 'Spider'];
console.log('animalNames', animalNames);
let scaryName = animalNames[1];
scaryName = 'Goldfish';
console.log('still scary animalNames', JSON.stringify(animalNames)); // nothing changed, because we're working with a copy

// Array with Objects
const animals = [{
  name: 'Tiger',
  teeth: 30,
  legs: 4
}, {
  name: 'Spider',
  teeth: 0,
  legs: 8
}];
console.log('animals', animals);
let scaryAnimal = animals[1]; // storing a reference to the spider object
scaryAnimal.name = 'Goldfish';
scaryAnimal.legs = 0;
console.log('less scary animals', animals); // spider got replaced by a goldfish

// Now we'll want to add another animal the WRONG WAY
// FIX: Uncomment line below to properly add a bunny
// scaryAnimal = {};
scaryAnimal.name = 'Bunny';
scaryAnimal.legs = 4;
scaryAnimal.teeth = 2;
animals.push(scaryAnimal);
console.log('duplicated animal', JSON.stringify(animals));

Edit: Fixed typo


来源: stackexchange

问:
Do some spark or spark.sql operations do collect in intermediate processing?
I have faced some out of memory issues in spark and most solutions tell me to reduce the collect() operations or check broadcast tables.

So I have a simple question, why does this happen when I am not using collect or broadcast tables in my code?

Dose spark perform collect in the intermediate processing for some operations?

答:
It does, I don't have an exhaustive list but if you call .toPandas() on a Spark DF for instance, it will collect the data on the driver.

Even though you're not directly calling the collect.

ContentLicense: CC BY-SA 4.0


问:
Determining worst-case time-complexity of this function?
I'm currently studying sets from Richard Hammack's 'Book of Proof' and I was trying to implement a set to a power (more specifically, the cartesian power of a set). An example of this is as follows:

Suppose I have set A = {0, 1}, then

A2 = {0, 1} x {0, 1} = {(0, 0), (0, 1), (1, 0), (1, 1)}

I successfully implemented a general function that could raise a set to any power I specified. The code is as follows:

```<code>def add_to_tuple(tup, a):
    tup = list(tup)
    tup.append(a)
    return tuple(tup)

def multiply(A, B):
    return_set = []
    for a in A:
        for b in B:
            if type(a) is tuple and type(b) is tuple:
                return_set.append(a + b)
            elif type(a) is not tuple and type(b) is tuple:
                return_set.append(add_to_tuple(b, a))
            elif type(a) is tuple and type(b) is not tuple:
                return_set.append(add_to_tuple(a, b))
            else:
                return_set.append((a, b))
    return return_set

def set_to_power(finite_set, power):
    if power == 1:
        return finite_set
    else:
        return multiply(finite_set, set_to_power(finite_set, power - 1))

a = [0, 1]
print(set_to_power(a, 2))
</code>```

The following output is:[(0, 0), (0, 1), (1, 0), (1, 1)]

I'm trying to figure out the time complexity of set_to_power and I'm not sure whether it's n2 or not.

答:
Let's look at all the functions one by one -

1.add_to_tuple(tup, a)

This function is O(n) where n is length of tuple. Within the function, the tup = list(tup) is O(n) same with final tuple(tup) where tup is list. In python, the conversion between tuple <--> list is O(n) since python needs to copy all items in the list/tuple to another. So use a list while you are adding members in the list and in the end you can convert your list to tuple if you want to.

2.multiply(A, B)

This is O(len(A) * len(B) * O(add_to_tuple), since we are looping through all items in A and B and then calling the add_to_tuple for each of them = O(n^3) where n is length of set(A)

3.set_to_power(finite_set, power)

Let's say power is k, and initial length of the finite_set is n. We will be calling the multiply function k times, during each call to multiply function, the resulting finite_set is going to be become n times the pervious size.
e.g. with [0, 1] and [0, 1, 2] being finite_set

```<code>>>> set_to_power([0, 1], 1)
[0, 1]
>>> set_to_power([0, 1], 2)
[(0, 0), (0, 1), (1, 0), (1, 1)]
>>> set_to_power([0, 1], 3)
[(0, 0, 0), (0, 1, 0), (1, 0, 0), (1, 1, 0), (0, 0, 1), (0, 1, 1), (1, 0, 1), (1, 1, 1)]
>>> set_to_power([0, 1, 2], 1)
[0, 1, 2]
>>> set_to_power([0, 1, 2], 2)
[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]
>>> set_to_power([0, 1, 2], 3)
[(0, 0, 0), (0, 1, 0), (0, 2, 0), (1, 0, 0), (1, 1, 0), (1, 2, 0), (2, 0, 0), (2, 1, 0), (2, 2, 0), (0, 0, 1), (0, 1, 1), (0, 2, 1), (1, 0, 1), (1, 1, 1), (1, 2, 1), (2, 0, 1), (2, 1, 1), (2, 2, 1), (0, 0, 2), (0, 1, 2), (0, 2, 2), (1, 0, 2), (1, 1, 2), (1, 2, 2), (2, 0, 2), (2, 1, 2), (2, 2, 2)]
</code>```

So the total complexity is going to be -

```<code>First call to multiply - O(n^3) +
Second call to multiply, the new finite_set will be of length n*n - O((n*n)^3) +
Third call to multiply - O((n*n*n)^3) + ... k times
</code>```

which is O(N^3k) for your solution.

You can reduce your complexity down to O(N^2k) by fixing the conversions in add_to_tuple and using lists instead which have an amortized O(1) complexity for append operation.

As a side note, the optimal solution for the problem would have its complexity as O(k*N^k), since there will be N^K items in the resulting set each of length k. What you are generating basically are all items of length k which are permutations of a given initial set where each element can be repeated(see the output of set_to_power([0, 1, 2], 3) above for example). We can start with an element which is [0, 0, 0] and then add it to our answer, and then in each step keep increasing the last digit which needs to be increased

```<code>e.g. [0, 0, 0] -> [0, 0, 1] -> [0, 0, 2] -> [0, 1, 0] -> [0, 1, 1] ...
</code>```

each step can be O(k), since you need to create a copy of previous list and then modify it in place to next digit in O(1) time. This would result in O(k*N^k) solution.

Body:
I'm currently studying sets from Richard Hammack's 'Book of Proof' and I was trying to implement a set to a power (more specifically, the cartesian power of a set). An example of this is as follows:

Suppose I have set A = {0, 1}, then

A2 = {0, 1} x {0, 1} = {(0, 0), (0, 1), (1, 0), (1, 1)}

I successfully implemented a general function that could raise a set to any power I specified. The code is as follows:

def add_to_tuple(tup, a):
    tup = list(tup)
    tup.append(a)
    return tuple(tup)

def multiply(A, B):
    return_set = []
    for a in A:
        for b in B:
            if type(a) is tuple and type(b) is tuple:
                return_set.append(a + b)
            elif type(a) is not tuple and type(b) is tuple:
                return_set.append(add_to_tuple(b, a))
            elif type(a) is tuple and type(b) is not tuple:
                return_set.append(add_to_tuple(a, b))
            else:
                return_set.append((a, b))
    return return_set

def set_to_power(finite_set, power):
    if power == 1:
        return finite_set
    else:
        return multiply(finite_set, set_to_power(finite_set, power - 1))

a = [0, 1]
print(set_to_power(a, 2))

The following output is:[(0, 0), (0, 1), (1, 0), (1, 1)]

I'm trying to figure out the time complexity of set_to_power and I'm not sure whether it's n2 or not.

Body:
Let's look at all the functions one by one -

1.add_to_tuple(tup, a)

This function is O(n) where n is length of tuple. Within the function, the tup = list(tup) is O(n) same with final tuple(tup) where tup is list. In python, the conversion between tuple <--> list is O(n) since python needs to copy all items in the list/tuple to another. So use a list while you are adding members in the list and in the end you can convert your list to tuple if you want to.

2.multiply(A, B)

This is O(len(A) * len(B) * O(add_to_tuple), since we are looping through all items in A and B and then calling the add_to_tuple for each of them = O(n^3) where n is length of set(A)

3.set_to_power(finite_set, power)

Let's say power is k, and initial length of the finite_set is n. We will be calling the multiply function k times, during each call to multiply function, the resulting finite_set is going to be become n times the pervious size.
e.g. with [0, 1] and [0, 1, 2] being finite_set

>>> set_to_power([0, 1], 1)
[0, 1]
>>> set_to_power([0, 1], 2)
[(0, 0), (0, 1), (1, 0), (1, 1)]
>>> set_to_power([0, 1], 3)
[(0, 0, 0), (0, 1, 0), (1, 0, 0), (1, 1, 0), (0, 0, 1), (0, 1, 1), (1, 0, 1), (1, 1, 1)]
>>> set_to_power([0, 1, 2], 1)
[0, 1, 2]
>>> set_to_power([0, 1, 2], 2)
[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]
>>> set_to_power([0, 1, 2], 3)
[(0, 0, 0), (0, 1, 0), (0, 2, 0), (1, 0, 0), (1, 1, 0), (1, 2, 0), (2, 0, 0), (2, 1, 0), (2, 2, 0), (0, 0, 1), (0, 1, 1), (0, 2, 1), (1, 0, 1), (1, 1, 1), (1, 2, 1), (2, 0, 1), (2, 1, 1), (2, 2, 1), (0, 0, 2), (0, 1, 2), (0, 2, 2), (1, 0, 2), (1, 1, 2), (1, 2, 2), (2, 0, 2), (2, 1, 2), (2, 2, 2)]

So the total complexity is going to be -

First call to multiply - O(n^3) +
Second call to multiply, the new finite_set will be of length n*n - O((n*n)^3) +
Third call to multiply - O((n*n*n)^3) + ... k times

which is O(N^3k) for your solution.

You can reduce your complexity down to O(N^2k) by fixing the conversions in add_to_tuple and using lists instead which have an amortized O(1) complexity for append operation.

As a side note, the optimal solution for the problem would have its complexity as O(k*N^k), since there will be N^K items in the resulting set each of length k. What you are generating basically are all items of length k which are permutations of a given initial set where each element can be repeated(see the output of set_to_power([0, 1, 2], 3) above for example). We can start with an element which is [0, 0, 0] and then add it to our answer, and then in each step keep increasing the last digit which needs to be increased

e.g. [0, 0, 0] -> [0, 0, 1] -> [0, 0, 2] -> [0, 1, 0] -> [0, 1, 1] ...

each step can be O(k), since you need to create a copy of previous list and then modify it in place to next digit in O(1) time. This would result in O(k*N^k) solution.


问:
how to save logs to adls for every https request of azure function
I have a Azure function with HTTP trigger. For every HTTP request I need to save the logs of  details  the of post request to ADLS like time of trigger and request params.

Can anyone help me how can i do this?

答:
Here is the Workaround I did to store the Azure Function Logs in ADLS Gen 2 where the logs contains the Function Execution Time, Started Time, Execution Result, etc.

To Create the Function App in ADLS Gen 2, First, you need to create the Storage Account of type ADLS Gen 2.

When you're creating the Storage Account, Check the box of Enable hierarchical namespace to create an ADLS Gen 2 Account.

After Creating an ADLS Storage account, create a function app in that storage account using PowerShell Command: (For example DotNet Stack)

```<code>New-AzFunctionApp -Name <APP_NAME> -ResourceGroupName AzureFunctionsQuickstart-rg -StorageAccount <STORAGE_NAME> -Runtime dotnet -FunctionsVersion 3 -Location '<REGION>'
</code>```

Created Http Trigger Function App through Portal in the Function App and it is running successfully with the POST Request.

Enable the Application Insights Resource on your Function App in the Portal.

All the logs will be stored in the path:

ADLS Storage Account > File Shares > Your Function App > LogFiles > Application > Functions > Function > Your Function Name > here you can see the logs.

Suppose, Function Key is also a one of the parameter in Azure Function URL.

By default, this info will not be logged but we can customize the code to log this parameter and in the Traces table of Application insights, this information can be available.

```<code>const  string key_Claim =  "http://schemas.microsoft.com/2017/07/functions/claims/keyid";
var claim = req.HttpContext.User.Claims.FirstOrDefault(c => c.Type  == key_Claim);
if(claim !=  null)
{
log.LogInformation(  "The call was made using {0} named key", claim.Value);
 }
</code>```

In Application Insights [Logs]

The above Workaround I did in .Net Stack and here is an example code related to read parameters of Azure Function and store it in a blob files using NodeJS.

Body:
Here is the Workaround I did to store the Azure Function Logs in ADLS Gen 2 where the logs contains the Function Execution Time, Started Time, Execution Result, etc.

To Create the Function App in ADLS Gen 2, First, you need to create the Storage Account of type ADLS Gen 2.

When you're creating the Storage Account, Check the box of Enable hierarchical namespace to create an ADLS Gen 2 Account.

After Creating an ADLS Storage account, create a function app in that storage account using PowerShell Command: (For example DotNet Stack)

New-AzFunctionApp -Name <APP_NAME> -ResourceGroupName AzureFunctionsQuickstart-rg -StorageAccount <STORAGE_NAME> -Runtime dotnet -FunctionsVersion 3 -Location '<REGION>'

Created Http Trigger Function App through Portal in the Function App and it is running successfully with the POST Request.

Enable the Application Insights Resource on your Function App in the Portal.

All the logs will be stored in the path:

ADLS Storage Account > File Shares > Your Function App > LogFiles > Application > Functions > Function > Your Function Name > here you can see the logs.

Suppose, Function Key is also a one of the parameter in Azure Function URL.

By default, this info will not be logged but we can customize the code to log this parameter and in the Traces table of Application insights, this information can be available.

const  string key_Claim =  "http://schemas.microsoft.com/2017/07/functions/claims/keyid";
var claim = req.HttpContext.User.Claims.FirstOrDefault(c => c.Type  == key_Claim);
if(claim !=  null)
{
log.LogInformation(  "The call was made using {0} named key", claim.Value);
 }

In Application Insights [Logs]

The above Workaround I did in .Net Stack and here is an example code related to read parameters of Azure Function and store it in a blob files using NodeJS.


问:
Error: "Cannot send session cache limiter" related to encoding
I'm started having problems with the encoding, it seems that somehow Notepad++ changed the encoding or something. Anyway all files where encoded in UTF-8, but I checked and some changed to UTF-8 without BOM. Changing one to UTF-8 fixed the special characters issue.

"TageÃƒÂ¡" changed to "Tageá" but I started getting an error:

```<code>Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at /home/content/02/6945202/html/usuario/index.php:1) in /home/content/02/6945202/html/usuario/index.php on line 1
</code>```

This is line 1:

```<code><? session_start(); ?>
</code>```

I don't understand why I'm having this issue, since using ANSI or UTF-8 without BOM the page shows with no errors.

What can be the problem? Thanks

答:
http://blog.onitindustries.com/php/errors/php-session_start-on-first-line-still-getting-error/

ok try using this function to convert strings, save file as utf-8 without bom for this.

```<code><?php
session_start();
function charset_decode_utf_8 ($string) {
  /* Only do the slow convert if there are 8-bit characters */
    /* avoid using 0xA0 (\240) in ereg ranges. RH73 does not like that */
    if (! ereg("[\200-\237]", $string) and ! ereg("[\241-\377]", $string))
        return $string;

    // decode three byte unicode characters
    $string = preg_replace("/([\340-\357])([\200-\277])([\200-\277])/e",
    "'&#'.((ord('\\1')-224)*4096 + (ord('\\2')-128)*64 + (ord('\\3')-128)).';'",
    $string);

    // decode two byte unicode characters
    $string = preg_replace("/([\300-\337])([\200-\277])/e",
    "'&#'.((ord('\\1')-192)*64+(ord('\\2')-128)).';'",
    $string);

    return $string;
}
echo charset_decode_utf_8('TageÃƒÂ¡');
?>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm started having problems with the encoding, it seems that somehow Notepad++ changed the encoding or something. Anyway all files where encoded in UTF-8, but I checked and some changed to UTF-8 without BOM. Changing one to UTF-8 fixed the special characters issue.

"TageÃƒÂ¡" changed to "Tageá" but I started getting an error:

Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at /home/content/02/6945202/html/usuario/index.php:1) in /home/content/02/6945202/html/usuario/index.php on line 1

This is line 1:

<? session_start(); ?>

I don't understand why I'm having this issue, since using ANSI or UTF-8 without BOM the page shows with no errors.

What can be the problem? Thanks

Body:
http://blog.onitindustries.com/php/errors/php-session_start-on-first-line-still-getting-error/

ok try using this function to convert strings, save file as utf-8 without bom for this.

<?php
session_start();
function charset_decode_utf_8 ($string) {
  /* Only do the slow convert if there are 8-bit characters */
    /* avoid using 0xA0 (\240) in ereg ranges. RH73 does not like that */
    if (! ereg("[\200-\237]", $string) and ! ereg("[\241-\377]", $string))
        return $string;

    // decode three byte unicode characters
    $string = preg_replace("/([\340-\357])([\200-\277])([\200-\277])/e",
    "'&#'.((ord('\\1')-224)*4096 + (ord('\\2')-128)*64 + (ord('\\3')-128)).';'",
    $string);

    // decode two byte unicode characters
    $string = preg_replace("/([\300-\337])([\200-\277])/e",
    "'&#'.((ord('\\1')-192)*64+(ord('\\2')-128)).';'",
    $string);

    return $string;
}
echo charset_decode_utf_8('TageÃƒÂ¡');
?>


问:
aws opensearch bulk insert enquiry
i am a beginner in aws opensearch.I have one important question regarding it that is
how much data(in MB or GB) i can insert in bulk at a single time in aws opensearch.
i tried to find solution of my question on aws website but couldn't get the answer please let me know if you can help</p>

答:
The amount of data you can insert using the bulk operations will depend on the cluster, configuration and data (among other factors) but I've found this to be a good recommendation:

"Start with the bulk request size of 5 MiB to 15 MiB. Then, slowly increase the request size until the indexing performance stops improving."

Title: aws opensearch bulk insert enquiry


问:
Slurm job arrays: is there a way to create a job array on slurm that starts at different times?
I have a long-running task that I want to run using a job array on slurm.

The script I am currently using to submit the jobs is:

#!/bin/bash

#SBATCH --output=slurm-%A_%a.out

#SBATCH --array=1-30

#SBATCH --ntasks=1

#SBATCH --qos=qos-15d

#SBATCH --partition=large

#SBATCH --mem=4G

srun ./a

This script works fine, but my problem is as it is an array of 30 jobs, I need to start the first one at time X and then start the second after X minutes and so on. I want to do this because I will simulate a C-compiled program that uses the srand (time (0)) function to generate random numbers. Therefore, the above script produces the same results for 30 simulations, because the random number generated will be equal. As each simulation takes a long time to run, it is not feasible for me to wait for a job to complete before starting another job.

答:
I know that this issue already has an answer, but after I had the same problem I found an alternative way to solve it.

The original answer had the problem for me that there is a chance that multiple runs would start at the same time since the delay is random and not unique.

My solution uses environment variables most slurm systems provide in this case specifically $SLURM_ARRAY_TASK_ID. (More environment variables can be found here: https://slurm.schedmd.com/sbatch.html#OPT_SLURM_ARRAY_TASK_ID)

For the use case above the script would look something like this. Where the number in the sleep statement can be the wanted delay.

```<code>#!/bin/bash

#SBATCH --output=slurm-%A_%a.out
#SBATCH --array=1-30
#SBATCH --ntasks=1
#SBATCH --qos=qos-15d
#SBATCH --partition=large
#SBATCH --mem=4G

sleep $((SLURM_ARRAY_TASK_ID*5))

srun ./a
</code>```

This will guarantee separate starting times of the program.

It would also be an option the read in the $SLURM_ARRAY_JOB_ID and $SLURM_ARRAY_TASK_ID into the program and use these as the seed for the random number generator for the simulation. (Reading in Environment Variables in C http://www0.cs.ucl.ac.uk/staff/W.Langdon/getenv/)

Body:
I know that this issue already has an answer, but after I had the same problem I found an alternative way to solve it.

The original answer had the problem for me that there is a chance that multiple runs would start at the same time since the delay is random and not unique.

My solution uses environment variables most slurm systems provide in this case specifically $SLURM_ARRAY_TASK_ID. (More environment variables can be found here: https://slurm.schedmd.com/sbatch.html#OPT_SLURM_ARRAY_TASK_ID)

For the use case above the script would look something like this. Where the number in the sleep statement can be the wanted delay.

#!/bin/bash

#SBATCH --output=slurm-%A_%a.out
#SBATCH --array=1-30
#SBATCH --ntasks=1
#SBATCH --qos=qos-15d
#SBATCH --partition=large
#SBATCH --mem=4G

sleep $((SLURM_ARRAY_TASK_ID*5))

srun ./a

This will guarantee separate starting times of the program.

It would also be an option the read in the $SLURM_ARRAY_JOB_ID and $SLURM_ARRAY_TASK_ID into the program and use these as the seed for the random number generator for the simulation. (Reading in Environment Variables in C http://www0.cs.ucl.ac.uk/staff/W.Langdon/getenv/)


问:
Trigger macro when a formula in cells in a range gives one of two texts
I want to create a macro that calls another macro when a specific range of cells that contain formulas give an output of one of two specific strings.

The formula is =IF(E15<=$G$5,"CHECK",IF(E15<=$F$5,"WARNING","OK")).

I want to trigger the macro every time there is an output "CHECK" or "WARNING". I want to trigger the macro every time the output is giving either of these two strings and not just once inside this range.

The range I want to look at and contains the formula is F8:F38.

I can find something like this

Private Sub Worksheet_Calculate()
    If Range("F8:F38").Value = "CHECK" Then
    Call email
End Sub
```

This is not working in case there is a formula instead of just a string.

答:
You can use the Worksheet.Calculate event, and a loop:

```<code>Private Sub Worksheet_Calculate()
    Dim cell As Range
    For Each cell In Me.Range("F8:F38")
        If cell.Value = "CHECK" Or cell.Value = "WARNING" Then
            Email ' no need for Call
        End If
    Next
End Sub
</code>```

If you only want to email when the values in F3:F38 have changed, then something like this:

In a regular module:

```<code>Public vals() As Variant ' public variable containing the 'old' values
</code>```

In the ThisWorkbook module:

```<code>Private Sub Workbook_Open()
    ' populate vals when opening workbook
    vals = Me.Worksheets("Yourworksheetname").Range("F3:F38").Value
End Sub
</code>```

In the sheet code module:

```<code>Private Sub Worksheet_Calculate()
    Dim cell As Range
    For Each cell In Me.Range("F8:F38")
        Dim counter As Long
        counter = counter + 1

        If cell.Value = "CHECK" Or cell.Value = "WARNING" Then
            ' check if the 'new' value is different from the 'old' one
            If cell.Value <> vals(counter, 1) Then
                Email
            End If
        End If
    Next

    vals = Me.Range("F8:F38").Value ' store the 'new' values
End Sub
</code>```

Body:
I want to create a macro that calls another macro when a specific range of cells that contain formulas give an output of one of two specific strings.

The formula is =IF(E15<=$G$5,"CHECK",IF(E15<=$F$5,"WARNING","OK")).

I want to trigger the macro every time there is an output "CHECK" or "WARNING". I want to trigger the macro every time the output is giving either of these two strings and not just once inside this range.

The range I want to look at and contains the formula is F8:F38.

I can find something like this

Private Sub Worksheet_Calculate()
    If Range("F8:F38").Value = "CHECK" Then
    Call email
End Sub

This is not working in case there is a formula instead of just a string.

Body:
You can use the Worksheet.Calculate event, and a loop:

Private Sub Worksheet_Calculate()
    Dim cell As Range
    For Each cell In Me.Range("F8:F38")
        If cell.Value = "CHECK" Or cell.Value = "WARNING" Then
            Email ' no need for Call
        End If
    Next
End Sub

If you only want to email when the values in F3:F38 have changed, then something like this:

In a regular module:

Public vals() As Variant ' public variable containing the 'old' values

In the ThisWorkbook module:

Private Sub Workbook_Open()
    ' populate vals when opening workbook
    vals = Me.Worksheets("Yourworksheetname").Range("F3:F38").Value
End Sub

In the sheet code module:

Private Sub Worksheet_Calculate()
    Dim cell As Range
    For Each cell In Me.Range("F8:F38")
        Dim counter As Long
        counter = counter + 1

        If cell.Value = "CHECK" Or cell.Value = "WARNING" Then
            ' check if the 'new' value is different from the 'old' one
            If cell.Value <> vals(counter, 1) Then
                Email
            End If
        End If
    Next

    vals = Me.Range("F8:F38").Value ' store the 'new' values
End Sub


问:
hackerrank doesn't accept my code but it prints the right result
The code below is accepted by hackerrank

```<code>function staircase($n) {
    $d = 1;

    for($col=$n;$col>0;$col--){
        for($row = 1;$row <$col ;$row++ ){
            echo" ";
        }

        for($a = 0; $a <$d;$a++){
            echo"#";
        }

        $d++;
        echo"\n";
    }
}
</code>```

This is my own code two code provide the same result but hackerrank don't accept my code. I want to know this reason

```<code>function staircase($n) {
    $x=1;
    $y=$n-1;

    while($x<=$n){
        while($y<$n){
            echo "#";
            $y++;
        }

        echo"\n";
        $x++;
        $y=$y-$x;
    }
}
</code>```

答:
Because both of your code output different .You can simply Check this 2 output

First Code Accepted one (# output as right aligned )

2nd Code (# output as left aligned )

Body:
The code below is accepted by hackerrank

function staircase($n) {
    $d = 1;

    for($col=$n;$col>0;$col--){
        for($row = 1;$row <$col ;$row++ ){
            echo" ";
        }

        for($a = 0; $a <$d;$a++){
            echo"#";
        }

        $d++;
        echo"\n";
    }
}

This is my own code two code provide the same result but hackerrank don't accept my code. I want to know this reason

function staircase($n) {
    $x=1;
    $y=$n-1;

    while($x<=$n){
        while($y<$n){
            echo "#";
            $y++;
        }

        echo"\n";
        $x++;
        $y=$y-$x;
    }
}


问:
Minifying javascript via unicode
on dwitter.net i often see dweets that are encoded interestingly to minify the JS to character count.

for example https://www.dwitter.net/d/22372 (or https://www.dwitter.net/d/11506)

eval(unescape(escape``.replace(/u../g,'')))
```
<p>Now I understand how to decode this and read the javascript, it's pretty trivial</p>
```unescape(escape``.replace(/u../g,''))
```
<p>returns</p>
<pre class="lang-js prettyprint-override"><code>x.font='2em a',x.fillText('\u2620 ',3,25)
t?0:d=x.getImageData(0,0,v=36,v).data
for(c.width|=w=i=936;i--;)e=i%v*6,d[i*4+3]>50||x.fillRect(X=e+e/2*S(t-i/w)+w,i/3-e*C(t-X/99)+e+50,9,i<1?w:9)
</code>```

but what I don't understand is how to encode js like this.

I noticed there is an intermediary step in this process

running:

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

returns

```<code>%uD878%uDC2E%uD866%uDC6F%uD86E%uDC74%uD83D%uDC27%uD832%uDC65%uD86D%uDC20%uD861%uDC27%uD82C%uDC78%uD82E%uDC66%uD869%uDC6C%uD86C%uDC54%uD865%uDC78%uD874%uDC28%uD827%uDC5C%uD875%uDC32%uD836%uDC32%uD830%uDC20%uD827%uDC2C%uD833%uDC2C%uD832%uDC35%uD829%uDC0A%uD874%uDC3F%uD830%uDC3A%uD864%uDC3D%uD878%uDC2E%uD867%uDC65%uD874%uDC49%uD86D%uDC61%uD867%uDC65%uD844%uDC61%uD874%uDC61%uD828%uDC30%uD82C%uDC30%uD82C%uDC76%uD83D%uDC33%uD836%uDC2C%uD876%uDC29%uD82E%uDC64%uD861%uDC74%uD861%uDC0A%uD866%uDC6F%uD872%uDC28%uD863%uDC2E%uD877%uDC69%uD864%uDC74%uD868%uDC7C%uD83D%uDC77%uD83D%uDC69%uD83D%uDC39%uD833%uDC36%uD83B%uDC69%uD82D%uDC2D%uD83B%uDC29%uD865%uDC3D%uD869%uDC25%uD876%uDC2A%uD836%uDC2C%uD864%uDC5B%uD869%uDC2A%uD834%uDC2B%uD833%uDC5D%uD83E%uDC35%uD830%uDC7C%uD87C%uDC78%uD82E%uDC66%uD869%uDC6C%uD86C%uDC52%uD865%uDC63%uD874%uDC28%uD858%uDC3D%uD865%uDC2B%uD865%uDC2F%uD832%uDC2A%uD853%uDC28%uD874%uDC2D%uD869%uDC2F%uD877%uDC29%uD82B%uDC77%uD82C%uDC69%uD82F%uDC33%uD82D%uDC65%uD82A%uDC43%uD828%uDC74%uD82D%uDC58%uD82F%uDC39%uD839%uDC29%uD82B%uDC65%uD82B%uDC35%uD830%uDC2C%uD839%uDC2C%uD869%uDC3C%uD831%uDC3F%uD877%uDC3A%uD839%uDC29
</code>```

which then gets regex replaced with .replace(/u../g,''), but getting this string from minified javascript isn't easy for me.

simply running encodeURIComponent() or escape() doesn't get you quite there, though it gets you part of the way there.

So how do I get the string of my javascript converted into a string containing %uD then the character code for each?

答:
I am also on dwitter.
The code compressor actually began with a dweet (https://www.dwitter.net/d/23092).
It was made so people could add more bytes into their demos by going right up to 194 chars instead of having the limit of 140.

Note this does not reduce the byte size.
Even though this reduces the amount of characters, the size stays the same

There is also an uncompressor at https://www.dwitter.net/d/14246

The simplified code for this is a simple unpack function:

```<code>function unpack(strange_blocky_code) {
    const index = code.toLowerCase().search(/eval\(unescape\(escape`/g)

    if (index >= 0) {
        const start = strange_blocky_code.slice(0, index)
        const end = strange_blocky_code.slice(index)
        const result = eval(end.slice(4))

        if (result) return start + result // returns readable (but trivial) code
    }
}
</code>```

The simplified compressing code is:

```<code>function compress(readable_code) {
    const value = [...readable_code.trim()]
    let code = ''

    for (let character of value) {
        const char = character.charCodeAt(0)
        if (char > 255) character = escape(character).replace(/%u/g, "\\u")
        code += character
    }

    const compressed =
    String.fromCharCode(...[...code.length % 2 ? code + ";" : code]
        .map((item, index) =>
            item.charCodeAt() | (index % 2 ? 0xDF00 : 0xDB00)
        )
    )

    return `eval(unescape(escape\`${compressed}\`.replace(/u../g,'')))`
}
</code>```

If you're looking for editors, these are two that I like to use:

https://greyhope.uk/Dweet-Runner/index.html made by GreyHope

https://dweetabase.3d2k.com/ made by Frank Force

I hope this helps at all.

Title: Minifying javascript via unicode

Body:
on dwitter.net i often see dweets that are encoded interestingly to minify the JS to character count.

for example https://www.dwitter.net/d/22372 (or https://www.dwitter.net/d/11506)

eval(unescape(escape``.replace(/u../g,'')))

Now I understand how to decode this and read the javascript, it's pretty trivial

unescape(escape``.replace(/u../g,''))

returns

x.font='2em a',x.fillText('\u2620 ',3,25)
t?0:d=x.getImageData(0,0,v=36,v).data
for(c.width|=w=i=936;i--;)e=i%v*6,d[i*4+3]>50||x.fillRect(X=e+e/2*S(t-i/w)+w,i/3-e*C(t-X/99)+e+50,9,i<1?w:9)

but what I don't understand is how to encode js like this.

I noticed there is an intermediary step in this process

running:

escape``

returns

%uD878%uDC2E%uD866%uDC6F%uD86E%uDC74%uD83D%uDC27%uD832%uDC65%uD86D%uDC20%uD861%uDC27%uD82C%uDC78%uD82E%uDC66%uD869%uDC6C%uD86C%uDC54%uD865%uDC78%uD874%uDC28%uD827%uDC5C%uD875%uDC32%uD836%uDC32%uD830%uDC20%uD827%uDC2C%uD833%uDC2C%uD832%uDC35%uD829%uDC0A%uD874%uDC3F%uD830%uDC3A%uD864%uDC3D%uD878%uDC2E%uD867%uDC65%uD874%uDC49%uD86D%uDC61%uD867%uDC65%uD844%uDC61%uD874%uDC61%uD828%uDC30%uD82C%uDC30%uD82C%uDC76%uD83D%uDC33%uD836%uDC2C%uD876%uDC29%uD82E%uDC64%uD861%uDC74%uD861%uDC0A%uD866%uDC6F%uD872%uDC28%uD863%uDC2E%uD877%uDC69%uD864%uDC74%uD868%uDC7C%uD83D%uDC77%uD83D%uDC69%uD83D%uDC39%uD833%uDC36%uD83B%uDC69%uD82D%uDC2D%uD83B%uDC29%uD865%uDC3D%uD869%uDC25%uD876%uDC2A%uD836%uDC2C%uD864%uDC5B%uD869%uDC2A%uD834%uDC2B%uD833%uDC5D%uD83E%uDC35%uD830%uDC7C%uD87C%uDC78%uD82E%uDC66%uD869%uDC6C%uD86C%uDC52%uD865%uDC63%uD874%uDC28%uD858%uDC3D%uD865%uDC2B%uD865%uDC2F%uD832%uDC2A%uD853%uDC28%uD874%uDC2D%uD869%uDC2F%uD877%uDC29%uD82B%uDC77%uD82C%uDC69%uD82F%uDC33%uD82D%uDC65%uD82A%uDC43%uD828%uDC74%uD82D%uDC58%uD82F%uDC39%uD839%uDC29%uD82B%uDC65%uD82B%uDC35%uD830%uDC2C%uD839%uDC2C%uD869%uDC3C%uD831%uDC3F%uD877%uDC3A%uD839%uDC29

which then gets regex replaced with .replace(/u../g,''), but getting this string from minified javascript isn't easy for me.

simply running encodeURIComponent() or escape() doesn't get you quite there, though it gets you part of the way there.

So how do I get the string of my javascript converted into a string containing %uD then the character code for each?

Body:
I am also on dwitter.
The code compressor actually began with a dweet (https://www.dwitter.net/d/23092).
It was made so people could add more bytes into their demos by going right up to 194 chars instead of having the limit of 140.

Note this does not reduce the byte size.
Even though this reduces the amount of characters, the size stays the same

There is also an uncompressor at https://www.dwitter.net/d/14246

The simplified code for this is a simple unpack function:

function unpack(strange_blocky_code) {
    const index = code.toLowerCase().search(/eval\(unescape\(escape`/g)

    if (index >= 0) {
        const start = strange_blocky_code.slice(0, index)
        const end = strange_blocky_code.slice(index)
        const result = eval(end.slice(4))

        if (result) return start + result // returns readable (but trivial) code
    }
}

The simplified compressing code is:

function compress(readable_code) {
    const value = [...readable_code.trim()]
    let code = ''

    for (let character of value) {
        const char = character.charCodeAt(0)
        if (char > 255) character = escape(character).replace(/%u/g, "\\u")
        code += character
    }

    const compressed =
    String.fromCharCode(...[...code.length % 2 ? code + ";" : code]
        .map((item, index) =>
            item.charCodeAt() | (index % 2 ? 0xDF00 : 0xDB00)
        )
    )

    return `eval(unescape(escape\`${compressed}\`.replace(/u../g,'')))`
}

If you're looking for editors, these are two that I like to use:

https://greyhope.uk/Dweet-Runner/index.html made by GreyHope

https://dweetabase.3d2k.com/ made by Frank Force

I hope this helps at all.


问:
Maximum sum in array given constraints

Problem Statement:

Given an array of positive integers, return the maximum sum.

There is only one limitation: if you pick two consecutive elements, you are not allowed to add any subsequent one to your total, and your sum is the amount accumulated up to that point. Your goal is to maximise your sum.

Example 1:

Input: [1, 4, 2, 10]

Output: 14

Example 2:

Input: [1, 4, 5, 3]

Output: 9

My solution:

  public static int solution(int[] boxes) {
    if(boxes.length == 0) {
      return 0;
    }
    int tempMax = 0;

    for(int i = 0; i < 2; i++) {
      tempMax += boxes[i];
    }

    int max = tempMax;

    for(int i = 1; i < boxes.length - 1; i++) {
      int sub = tempMax - boxes[i - 1];
      tempMax = sub + boxes[i + 1];

      if(max < tempMax) {
        max = tempMax;
      }
    }

    return max;
  }
```

I keep failing on the first test case. I have tried a DP solution but that yielded the same results? Any help would be appreciated.

答:
Your greedy approach goes in the right direction, however I see a few issues with your current solution.

First off, your program will crash for inputs of size 1, since your first loop will assume that the input has at least size 2.

Next, you don't have a way to refer to previous decisions being made. In tempMax you basically store boxes[i] + boxes[i+1], since with every iteration you remove boxes[i-1] from tempMax.

An approach would be to store three values for every iteration:

The maximum if we select the current box and not the previous one (max0)

The maximum if we don't select the current box and there are no consecutive selections for previous iterations (max0)

The maximum if we select the current box when the previous box was also selected (max11)

Edit: Added solution

```<code>import java.lang.Math;

public class Game {
    public static int solution(int[] boxes) {
        int max0 = 0, max1 = 0, max11 = 0;
        for(int i = 0; i < boxes.length; i++) {
            int max0_new = Math.max(max0, max1);
            int max1_new = max0 + boxes[i];
            int max11_new = Math.max(max11, max1 + boxes[i]);
            max0 = max0_new;
            max1 = max1_new;
            max11 = max11_new;
        }
        return Math.max(max0, Math.max(max1, max11));
    }

    public static void main(String[] args) {
        System.out.println(solution(new int[]{1, 4, 2, 10}));
        System.out.println(solution(new int[]{1, 4, 5, 3}));
    }
}
</code>```

Title: Maximum sum in array given constraints

Body:
Problem Statement:

Given an array of positive integers, return the maximum sum.

There is only one limitation: if you pick two consecutive elements, you are not allowed to add any subsequent one to your total, and your sum is the amount accumulated up to that point. Your goal is to maximise your sum.

Example 1:

Input: [1, 4, 2, 10]

Output: 14

Example 2:

Input: [1, 4, 5, 3]

Output: 9

My solution:

  public static int solution(int[] boxes) {
    if(boxes.length == 0) {
      return 0;
    }
    int tempMax = 0;

    for(int i = 0; i < 2; i++) {
      tempMax += boxes[i];
    }

    int max = tempMax;

    for(int i = 1; i < boxes.length - 1; i++) {
      int sub = tempMax - boxes[i - 1];
      tempMax = sub + boxes[i + 1];

      if(max < tempMax) {
        max = tempMax;
      }
    }

    return max;
  }

I keep failing on the first test case. I have tried a DP solution but that yielded the same results? Any help would be appreciated.

Body:
Your greedy approach goes in the right direction, however I see a few issues with your current solution.

First off, your program will crash for inputs of size 1, since your first loop will assume that the input has at least size 2.

Next, you don't have a way to refer to previous decisions being made. In tempMax you basically store boxes[i] + boxes[i+1], since with every iteration you remove boxes[i-1] from tempMax.

An approach would be to store three values for every iteration:

The maximum if we select the current box and not the previous one (max0)

The maximum if we don't select the current box and there are no consecutive selections for previous iterations (max0)

The maximum if we select the current box when the previous box was also selected (max11)

Edit: Added solution

import java.lang.Math;

public class Game {
    public static int solution(int[] boxes) {
        int max0 = 0, max1 = 0, max11 = 0;
        for(int i = 0; i < boxes.length; i++) {
            int max0_new = Math.max(max0, max1);
            int max1_new = max0 + boxes[i];
            int max11_new = Math.max(max11, max1 + boxes[i]);
            max0 = max0_new;
            max1 = max1_new;
            max11 = max11_new;
        }
        return Math.max(max0, Math.max(max1, max11));
    }

    public static void main(String[] args) {
        System.out.println(solution(new int[]{1, 4, 2, 10}));
        System.out.println(solution(new int[]{1, 4, 5, 3}));
    }
}


问:
How to add radio button in a quiz app in react
I am working on a quiz app and currently, I have just a button as my option but I want to choose radio buttons as my options and I also want to have a submit feature.

This is my code:

```<code>    <>
        {showScore ? null : <div>Countdown: {counter}</div>}
        <div className="question_no">
            <span>Question {currentQuestion + 2}</span>/{questions.length}
        </div>
        <div className="quiz-container">
            {showScore ? (
                <div className="score">
                    You scored {score} out of {questions.length}
                </div>
            ) : (
                <>
                    <div className="quiz-header">
                        <div className="question">
                            {questions[currentQuestion].questionText}
                        </div>
                    </div>
                    <div className="answer_div">
                        {questions[currentQuestion].answerOptions.map(
                            (answerOption) => (
                                <button
                                    onClick={() =>
                                        handleAnswerOptionClick(
                                            answerOption.isCorrect
                                        )
                                    }
                                >
                                    {answerOption.answerText}
                                </button>
                            )
                        )}
                    </div>
                </>
            )}
        </div>
    </>
</code>```

how can i change the button option to radio button

答:
Radio is not a button type, but an input type, so probably something like this:

```<code><div className="answer_div">
  {questions[currentQuestion].answerOptions.map(
    (answerOption) => (
      <input type="radio" id={answerOption.answerID}
        onClick={() =>
          handleAnswerOptionClick(
            answerOption.isCorrect
          )
        }
      />
      <label htmlFor={answerOption.answerID}>
         {answerOption.answerText}
      </label>
    )
  )}
</div>
</code>```

Maybe you wanna also use onChange instead of onClick.

Body:
I am working on a quiz app and currently, I have just a button as my option but I want to choose radio buttons as my options and I also want to have a submit feature.

This is my code:

    <>
        {showScore ? null :
Countdown: {counter}
}

            Question {currentQuestion + 2}/{questions.length}

            {showScore ? (

                    You scored {score} out of {questions.length}

            ) : (
                <>

                            {questions[currentQuestion].questionText}

                        {questions[currentQuestion].answerOptions.map(
                            (answerOption) => (
                                <button
                                    onClick={() =>
                                        handleAnswerOptionClick(
                                            answerOption.isCorrect
                                        )
                                    }
                                >
                                    {answerOption.answerText}
                                </button>
                            )
                        )}

                </>
            )}

    </>

how can i change the button option to radio button

Body:
Radio is not a button type, but an input type, so probably something like this:

<div className="answer_div">
  {questions[currentQuestion].answerOptions.map(
    (answerOption) => (
      <input type="radio" id={answerOption.answerID}
        onClick={() =>
          handleAnswerOptionClick(
            answerOption.isCorrect
          )
        }
      />
      <label htmlFor={answerOption.answerID}>
         {answerOption.answerText}
      </label>
    )
  )}
</div>

Maybe you wanna also use onChange instead of onClick.


问:
How to connect one css with multiable html pages
So I new to html and want to make a website with 2 pages a home page and a contact page.
and I just want to know how do you use the same Style.css file for then 1 page?

Do just write in the Style.css:
***#Home body;

#Contact body;***

答:
For ease of explaining, i have created 2 divs in one page. But you can create homepage and put "homepage" div in it and "contact" div on another page

.homepage {
    /* All css needed for homepage will come here */
}

.contact {
    /* All css needed for contact will come here */
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="style.css">
    <title>Document</title>
</head>
<body>
    <div class="homepage">
        page 1 content
    </div>

    <div class="contact">
        contact content
    </div>
</body>
</html></code>```

Body:
For ease of explaining, i have created 2 divs in one page. But you can create homepage and put "homepage" div in it and "contact" div on another page

.homepage {
    /* All css needed for homepage will come here */
}

.contact {
    /* All css needed for contact will come here */
}

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="style.css">
    <title>Document</title>
</head>
<body>
    <div class="homepage">
        page 1 content
    </div>

    <div class="contact">
        contact content
    </div>
</body>
</html>


问:
How to get values from a list of dictionaries, which themselves contain lists of dictionaries in Python
I encountered the problem of getting values from a list that contains dictionaries, where each of the dictionaries has a list with a dictionary. May sound easy to do but it took me some time and I think it can be useful for other people if I post it. An example of my data can be:

```<code>player_info = [{[{'tag': 'tag 1'}]},
               {[{'tag': 'tag 2'}]}]
</code>```

The outer list is called 'player_info'. This contained 25 dictionaries, where each one contains a list that contains (among other things) a dictionary called 'opponent' which contains a list that contains a dictionary (yeah, pretty messy). From that innermost dictionary, I wanted the value associated with the 'tag' key.

I figured two ways:

Create a loop.

```<code>for i in range(25):
    print(player_info[i]['opponent'][0]['tag'])
</code>```

Iterate through list:

```<code>{each_dictionary['opponent'][0]['tag'] for each_dictionary in player_info}
</code>```

I assume that the second way must be more efficient. Let me know what you think, and whether there is a smarter way to do it.

答:
First: dict's require a key-value association for every element in the dictionary. Your 2nd level data structure though does not include keys: ({[{'tag': 'tag 1'}]}) This is a set. Unlike dict's, set's do not have keys associated with their elements. So your data structure looks like List[Set[List[Dict[str, str]]]].

Second: when I try to run

# python 3.8.8
player_info = [{[{'tag': 'tag 1'}]},
               {[{'tag': 'tag 2'}]}]
```
<p>I recieve the error <code>TypeError: unhashable type: 'list'</code>. That's because you're code attempts to contain a list inside a set. Set membership in python demands the members to be hashable. However, you will not find a <code>__hash__()</code> function defined on <code>list</code> objects. Even if you resolve this by replacing the <code>list</code> with a <code>tuple</code>, you will find that <code>dict</code> objects are not hashable either. Potential solutions include using immutable objects like <code>frozendict</code> or <code>tuple</code>, but that is another post.</p>
<p>To answer your question, I have reformulated your problem as</p>
<pre class="lang-py prettyprint-override"><code>player_info = [[[{'tag': 'tag 1'}]],
               [[{'tag': 'tag 2'}]]]
</code>```

and compared the performance difference with A) explicit loops:

for i in range(len(player_info)):
  print(player_info[i][0][0]['tag'])
```
<p>against B) list comprehension</p>
<pre class="lang-py prettyprint-override"><code>[
  print(single_player_info[0][0]['tag'])
  for single_player_info in player_info
]
</code>```

Running the above code blocks in jupyter with the %%timeit cell magic, I got:
A) 154 µs ± 14.6 µs per loop (mean ± std. dev. of 7 runs, 10,000 loops each) and
B) 120 µs ± 11 µs per loop (mean ± std. dev. of 7 runs, 10,000 loops each)

Note: This experiment is highly skewed for at least two reasons:

I tested both trials using only the data you provided (N=2). It is very likely that we would observe different scaling behaviors than initial conditions suggest.

print consumes a lot of time and makes this problem heavily subject to the status of the kernel

I hope this answers your question.

Body:
I encountered the problem of getting values from a list that contains dictionaries, where each of the dictionaries has a list with a dictionary. May sound easy to do but it took me some time and I think it can be useful for other people if I post it. An example of my data can be:

player_info = [{[{'tag': 'tag 1'}]},
               {[{'tag': 'tag 2'}]}]

The outer list is called 'player_info'. This contained 25 dictionaries, where each one contains a list that contains (among other things) a dictionary called 'opponent' which contains a list that contains a dictionary (yeah, pretty messy). From that innermost dictionary, I wanted the value associated with the 'tag' key.

I figured two ways:

Create a loop.

for i in range(25):
    print(player_info[i]['opponent'][0]['tag'])

Iterate through list:

{each_dictionary['opponent'][0]['tag'] for each_dictionary in player_info}

I assume that the second way must be more efficient. Let me know what you think, and whether there is a smarter way to do it.

Body:
First: dict's require a key-value association for every element in the dictionary. Your 2nd level data structure though does not include keys: ({[{'tag': 'tag 1'}]}) This is a set. Unlike dict's, set's do not have keys associated with their elements. So your data structure looks like List[Set[List[Dict[str, str]]]].

Second: when I try to run

# python 3.8.8
player_info = [{[{'tag': 'tag 1'}]},
               {[{'tag': 'tag 2'}]}]

I recieve the error TypeError: unhashable type: 'list'. That's because you're code attempts to contain a list inside a set. Set membership in python demands the members to be hashable. However, you will not find a __hash__() function defined on list objects. Even if you resolve this by replacing the list with a tuple, you will find that dict objects are not hashable either. Potential solutions include using immutable objects like frozendict or tuple, but that is another post.

To answer your question, I have reformulated your problem as

player_info = [[[{'tag': 'tag 1'}]],
               [[{'tag': 'tag 2'}]]]

and compared the performance difference with A) explicit loops:

for i in range(len(player_info)):
  print(player_info[i][0][0]['tag'])

against B) list comprehension

[
  print(single_player_info[0][0]['tag'])
  for single_player_info in player_info
]

Running the above code blocks in jupyter with the %%timeit cell magic, I got:
A) 154 µs ± 14.6 µs per loop (mean ± std. dev. of 7 runs, 10,000 loops each) and
B) 120 µs ± 11 µs per loop (mean ± std. dev. of 7 runs, 10,000 loops each)

Note: This experiment is highly skewed for at least two reasons:

I tested both trials using only the data you provided (N=2). It is very likely that we would observe different scaling behaviors than initial conditions suggest.

print consumes a lot of time and makes this problem heavily subject to the status of the kernel

I hope this answers your question.


问:
How to update metrics regularly using prometheus-flask-exporter?
I'm creating a simple Flask webapp which should generate a random metric to be pulled by Prometheus. I'm using the prometheus-flask-exporter library which enabled me to set a metric.

Put simply, I want to know how can I configure custom metrics internally within flask so that they update at intervals from the '/metrics' endpoint of the flask app.

Not 'how often can I get prometheus to fetch a particular metric'

Currently I can't get a loop working within my flask app as the main class doesn't run if I have one.

This is just for a proof of concept, the custom metric can be anything.

My app.py:

```<code>from flask import Flask, render_template, request
from prometheus_flask_exporter import PrometheusMetrics

app = Flask(__name__)
metrics = PrometheusMetrics(app)

#Example of exposing information as a Gague metric:
info = metrics.info('random_metric', 'This is a random metric')
info.set(1234)

if __name__ == '__main__':
    app.run(host='0.0.0.0')
</code>```

答:
I solved this problem by adding a background thread to do the work.</p>
```<code>from flask import Flask
import requests
import time
import threading

class HealthChecker():

    def __init__(self):
        self.app = Flask(__name__)

        @self.app.route('/', methods=['GET'])
        def hello_world():
            return "Hello world from Flask"

        self.metrics = PrometheusMetrics(self.app)
        threading.Thread(target = self.pull_metric).start()

if __name__ == '__main__':
    healthChecker = HealthChecker()
    self.app.run(host='0.0.0.0')
</code>```

Body:
I'm creating a simple Flask webapp which should generate a random metric to be pulled by Prometheus. I'm using the prometheus-flask-exporter library which enabled me to set a metric.

Put simply, I want to know how can I configure custom metrics internally within flask so that they update at intervals from the '/metrics' endpoint of the flask app.

Not 'how often can I get prometheus to fetch a particular metric'

Currently I can't get a loop working within my flask app as the main class doesn't run if I have one.

This is just for a proof of concept, the custom metric can be anything.

My app.py:

from flask import Flask, render_template, request
from prometheus_flask_exporter import PrometheusMetrics

app = Flask(__name__)
metrics = PrometheusMetrics(app)

#Example of exposing information as a Gague metric:
info = metrics.info('random_metric', 'This is a random metric')
info.set(1234)

if __name__ == '__main__':
    app.run(host='0.0.0.0')

Body:
I solved this problem by adding a background thread to do the work.

from flask import Flask
import requests
import time
import threading

class HealthChecker():

    def __init__(self):
        self.app = Flask(__name__)

        @self.app.route('/', methods=['GET'])
        def hello_world():
            return "Hello world from Flask"

        self.metrics = PrometheusMetrics(self.app)
        threading.Thread(target = self.pull_metric).start()

if __name__ == '__main__':
    healthChecker = HealthChecker()
    self.app.run(host='0.0.0.0')


问:
wordpress function to validate cart
I'd like to ask for your assistance with the following:
I have different kinds of subscriptions on my site. One "basic" subscription (it's variable subscription with ID 286)  and multiple "add-on" subscriptions (simple subs).
Every subscriber has to be subscribed to the "basic" subscription - it's ok.

My problem is that I need to prevent subscribers who do not have an active (wc-active) subscription to the "basic" subscription to check out with any "add-on" subscription without the basic subscription in the cart as well.

I can check if the user has active subscription with this code:

```<code>wcs_user_has_subscription( $user_id, $productId, 'active' );
</code>```

Unfortunately I cannot figure the other function to use. Any help would be very much appreciated :)

答: Take a look at the woocommerce_add_to_cart_validation hook

Title: wordpress function to validate cart

Body:
I'd like to ask for your assistance with the following:
I have different kinds of subscriptions on my site. One "basic" subscription (it's variable subscription with ID 286)  and multiple "add-on" subscriptions (simple subs).
Every subscriber has to be subscribed to the "basic" subscription - it's ok.

My problem is that I need to prevent subscribers who do not have an active (wc-active) subscription to the "basic" subscription to check out with any "add-on" subscription without the basic subscription in the cart as well.

I can check if the user has active subscription with this code:

wcs_user_has_subscription( $user_id, $productId, 'active' );

Unfortunately I cannot figure the other function to use. Any help would be very much appreciated :)


问:
How would i go about creating a streaming API, that receives data from a POST request and pushes it out?
I am interested in developing an API that is capable of receiving data in real-time and pushing it out to clients connected to an endpoint. I have looked in socket.io and web sockets. However, these depend on events being triggered to send/receive data. This isn't ideal for my use case. What alternatives are there for me to achieve this?

Any help and advice are greatly appreciated.

答: So If I understand it right, you want to write a streaming service that can push updates on some data in real-time over an endpoint exposed to the clients. I guess webhooks might be a solution looking into your problem statement. I'd recommend you to look into this https://www.youtube.com/watch?v=63grynZmo7c as well. It has got elementary information as to how do you create a webhook and start receiving real-time updates on it</p>


问:
.net desktop app installation
I am creating a  C# .Net 4.0 desktop application for a client.  When I sent him the .msi files it requires administration privileges when trying to install.  I realize the reason why is because I am installing the application into the "Program Files" directory.

Is there a way to install an application into an area on the users machine that doesn't require them to install as Administrator?

I'm using .Net 4.0

答:
depending on what dependencies the app has you could try an XCOPY deployment - although is seems that is only documented for VS2005 + VS2008...

We usually embed all dependencis into the app (in our case EXE-file), this way it can be "installed" by just copying it... as long as the framework needed (i.e. .NET4 in our case) is already there...

see http://msdn.microsoft.com/en-us/library/ms235291%28VS.90%29.aspx

Title: .net desktop app installation


问:
Finding intersection of the lines in the image without using Hough lines transform or OpenCV
I wish to find the intersection of the lines in the following image without using OpenCV or Hough Line Transform (since it is computationally costly for my requirement).

I have tried creating a sliding window protocol and assigning weights based on symmetricity within the window, it takes a longer time as well.

I am looking for some innovative or even out of the box idea to approach this problem. Would love to brainstorm your ideas.

Common features in the image:
The images I am working on will more or less look the same. It is always a binary image and it is possible to know the number of intersections (in rows and columns) beforehand.

答:
Hint:

By binarizing and getting contours, then selecting on area, you can obtain a number of isolated grid cells. You can use the centers to reconstruct the grid and predict the grid lines.

Then you can refine these lines by local edge detection near the predicted locations.


问:
electron-builder not including entire dependency in built version
Electron is giving me 'Error: Cannot find module './constructor/getOptions' when I open my executable. I tracked the error to a dependency I have which has the following file structure:

My issue is that in the built version of the program, the entire constructor folder is missing. The way I look at the built version is by using the command npx asar extract app.asar ./extracted to view the files. When I look at this dependency I only see index.js being listed there.

I have checked inside of the index.js to see if getOptions is being imported and it is. I have tried to import the file using relative and absolute path. I have also made sure that the dependency is not under devDependency as electron-builder ignores that. I'm not really sure what else to do. Does electron-builder have an option to go deeper into the file structure of a dependency?

Here is my package.json section for electron-builder:

```<code>  "build": {
    "productName": "MintAIO",
    "appId": "aio.mint",
    "win": {
      "icon": "build/ic.png"
    },
    "mac": {
      "target": "dmg",
      "icon": "build/ic-mac.png"
    }
  }
</code>```

答: For anyone who might come across this issue in the future, there is a bug with Asar where the directory name constructor is for some reason not included when being packaged. I'm not sure what other directory names this might cause this issue, but constructor is definitely one of them. To fix this, you can either rename that directory to something else, or specifically leave that one dependency unpacked using the asarUnpack option in the build config of electron.

Body:
Electron is giving me 'Error: Cannot find module './constructor/getOptions' when I open my executable. I tracked the error to a dependency I have which has the following file structure:

My issue is that in the built version of the program, the entire constructor folder is missing. The way I look at the built version is by using the command npx asar extract app.asar ./extracted to view the files. When I look at this dependency I only see index.js being listed there.

I have checked inside of the index.js to see if getOptions is being imported and it is. I have tried to import the file using relative and absolute path. I have also made sure that the dependency is not under devDependency as electron-builder ignores that. I'm not really sure what else to do. Does electron-builder have an option to go deeper into the file structure of a dependency?

Here is my package.json section for electron-builder:

  "build": {
    "productName": "MintAIO",
    "appId": "aio.mint",
    "win": {
      "icon": "build/ic.png"
    },
    "mac": {
      "target": "dmg",
      "icon": "build/ic-mac.png"
    }
  }


问:
I want to query 3 Random Products from the Database everytime only 3
```<code>y = (Product.objects.all()).count()
    x = random.randint(3,y)
    prouct1 = Product.objects.get(id = x+1)
    prouct2 = Product.objects.get(id = x-1)
    prouct3 = Product.objects.get(id = x-2)
</code>```

I want to obtain 3 random products everytime i run a function initially i use the above method But the problem with this is If i delete a object Then i get the error i dont want that thing to happen obviously i can run more checks but i feel there is some simple way to do that The objective is to Get the random object from the  database every time the page is renderd

答:
Work with OFFSET … LIMIT … instead:

```qs = Product.objects.all()
n = qs.count()
x<sub>0</sub>, x<sub>1</sub>, x<sub>2</sub> = random.sample(range(n), 3)
product<sub>0</sub> = qs[x<sub>0</sub>]
product<sub>1</sub> = qs[x<sub>1</sub>]
product<sub>2</sub> = qs[x<sub>2</sub>]```

this requires that there are at least three items in the Product table, and will make four queries: one for the count and three for the individual products. It will also guarantee that the three products are distinct.

If the table is not that large, you can sample from the list of primary keys and then fetch three items:

```pks = Product.objects.values_list('pk', flat=True)
product<sub>0</sub>, product<sub>1</sub>, product<sub>2</sub> = Product.objects.filter(pk__in=random.sample(pks, 3))```

This will make two queries: one to load all primary keys, and another to fetch the three products in bulk. This is more extensible if the number of products you want to fetch increases since fetching ten products for example, will still require two queries.

Body:
y = (Product.objects.all()).count()
    x = random.randint(3,y)
    prouct1 = Product.objects.get(id = x+1)
    prouct2 = Product.objects.get(id = x-1)
    prouct3 = Product.objects.get(id = x-2)

I want to obtain 3 random products everytime i run a function initially i use the above method But the problem with this is If i delete a object Then i get the error i dont want that thing to happen obviously i can run more checks but i feel there is some simple way to do that The objective is to Get the random object from the  database every time the page is renderd

Body:
Work with OFFSET … LIMIT … instead:

qs = Product.objects.all()
n = qs.count()
x0, x1, x2 = random.sample(range(n), 3)
product0 = qs[x0]
product1 = qs[x1]
product2 = qs[x2]

this requires that there are at least three items in the Product table, and will make four queries: one for the count and three for the individual products. It will also guarantee that the three products are distinct.

If the table is not that large, you can sample from the list of primary keys and then fetch three items:

pks = Product.objects.values_list('pk', flat=True)
product0, product1, product2 = Product.objects.filter(pk__in=random.sample(pks, 3))

This will make two queries: one to load all primary keys, and another to fetch the three products in bulk. This is more extensible if the number of products you want to fetch increases since fetching ten products for example, will still require two queries.


问:
Customizing the Places Bar in Visual Studio 2008
Has anybody succeeded in customizing the Places Bar for VS 2008? My customizations from VS 2005 did not transfer to 2008 (obviously), and no matter what I do with the registry, I cannot make my custom places appear on the Open dialogs. I have read and applied the relevant MS KB article, to no avail.

This used to work fine with VS 2005, so it may well be a VS 2008 bug, but I may be wrong trying the same approach.

答:
VS2005 and VS2008 (sp1 anyway) both still use the following registry Key structure

So, for vs2008, create these reg paths.

HKCU/Software/Microsoft/VisualStudio/9.0/Open
  Find/Places/UserDefinedPlaces/Place0/Path = (some path

HKCU/Software/Microsoft/VisualStudio/9.0/Open
  Find/Places/UserDefinedPlaces/Place1/Path
  = (another path)

VS2008 Example:

HKCU/Software/Microsoft/VisualStudio/9.0/Open
  Find/Places/UserDefinedPlaces/Place0/Path
  = "C:\Dev"

HKCU/Software/Microsoft/VisualStudio/9.0/Open
  Find/Places/UserDefinedPlaces/Place1/Path
  = "C:\Staging"

Important Notes:

It appears you must restart visual studio each time you edit these keys

VS2005 = 8.0  / VS2008 = 9.0

Path is a String Value (REG_SZ) containing the path to be added to the places bar

Desktop and My Computer seem to be predefined and always present?

I don't know whether you can have more than 5 places max like (the Common dialog)

Suggest creating a simple .REG file that can be edited and clicked to alter these

OwnerDisplayName: Alan

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Jeff Hare


问:
Is there a decent command Reference for VBA and Access 97?
I've spent the last weeks looking at some codes @ microsoft's website just to realize that I was looking @ VB.NET code instead of VBA.

Not that I know the diference between them.

But a good ref. library and documentation would help a lot, something similar to the javadocs.

I've been working with some export functions latetly and I can't find the full command list inside the software.

Any hints? Tips?
I'm not a total n00b at the subject and I'm just looking for a good place to start learning more than the basics.
But I don't wanna spend another week looking for a command to delete a file or to reorganize a CVS.

答:
Years earlier it seems that this was an easier question to answer. However here a few links I found relevant to  your question. These are fairly easy to find using Google with a query of "Visual Basic 6.0". Please note most of these are for Visual Basic 6.0 which is similar to Visual Basic 5 and of course VBA.

Large Collection of VB6 samples/documentation

Visual Basic 6 - 'Cheat Sheet'

VBA Examples - Including Access '97

Sample VB6 code from MSDN


问:
How to override Swagger's default produces header value?
I am using Swagger version 2.4.0 and Spring Boot 2.0.4.RELEASE and have an application with several API endpoints and with default Swagger configuration having default produces header value set to application/json.

SwaggerConfig.java

```<code>@Configuration
@EnableSwagger2
public class SwaggerConfig {

    private static final Set<String> DEFAULT_PRODUCES_AND_CONSUMES = ImmutableSet.of(
            "application/json"
    );

    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
                .produces(DEFAULT_PRODUCES_AND_CONSUMES)
                .consumes(DEFAULT_PRODUCES_AND_CONSUMES);
    }
}
</code>```

And with API endpoint set up being.

ApiEndpoint.java

```<code>@Consumes(MediaType.APPLICATION_JSON)
@Api(value = "/transform", protocols = "http, https")
@RequestMapping(value = "/transform")
public interface ApiEndpoint {

    @POST
    @RequestMapping(value = "/text", method = RequestMethod.POST)
    @ApiOperation(value = "Transform to plain text", produces = MediaType.TEXT_PLAIN)
    @CrossOrigin
    String transformToText(@RequestBody TransformRequest transformRequest) throws Exception;
}
</code>```

Now I want this endpoint to produce response with content type being only plain text, but SwaggerConfig adds application/json option as default one. So in order to correctly use this endpoint I would need to change Response Content Type from application/json to text/plain every time, which would get annoying pretty quick considering that this endpoint is used for testing. Is there a way to override SwaggerConfig or to add a parameter so text/plain is the only option or at least to set the text/plain as the default option only for this one endpoint?

答:
just specifying type in order in the endpoint annotation, example:

atribute produces receive an array, so you can put more than one type

```<code>@PostMapping(value = "/text", produces = { MediaType.TEXT_PLAIN_VALUE, MediaType.APPLICATION_JSON_VALUE })
</code>```

I advise removing produces in @Bean, as its API contains endpoint that did not always follow the standard idea of "application/json"

Body:
I am using Swagger version 2.4.0 and Spring Boot 2.0.4.RELEASE and have an application with several API endpoints and with default Swagger configuration having default produces header value set to application/json.

SwaggerConfig.java

@Configuration
@EnableSwagger2
public class SwaggerConfig {

    private static final Set<String> DEFAULT_PRODUCES_AND_CONSUMES = ImmutableSet.of(
            "application/json"
    );

    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
                .produces(DEFAULT_PRODUCES_AND_CONSUMES)
                .consumes(DEFAULT_PRODUCES_AND_CONSUMES);
    }
}

And with API endpoint set up being.

ApiEndpoint.java

@Consumes(MediaType.APPLICATION_JSON)
@Api(value = "/transform", protocols = "http, https")
@RequestMapping(value = "/transform")
public interface ApiEndpoint {

    @POST
    @RequestMapping(value = "/text", method = RequestMethod.POST)
    @ApiOperation(value = "Transform to plain text", produces = MediaType.TEXT_PLAIN)
    @CrossOrigin
    String transformToText(@RequestBody TransformRequest transformRequest) throws Exception;
}

Now I want this endpoint to produce response with content type being only plain text, but SwaggerConfig adds application/json option as default one. So in order to correctly use this endpoint I would need to change Response Content Type from application/json to text/plain every time, which would get annoying pretty quick considering that this endpoint is used for testing. Is there a way to override SwaggerConfig or to add a parameter so text/plain is the only option or at least to set the text/plain as the default option only for this one endpoint?

Body:
just specifying type in order in the endpoint annotation, example:

atribute produces receive an array, so you can put more than one type

@PostMapping(value = "/text", produces = { MediaType.TEXT_PLAIN_VALUE, MediaType.APPLICATION_JSON_VALUE })

I advise removing produces in @Bean, as its API contains endpoint that did not always follow the standard idea of "application/json"


答:
Since there are three different possibilities when considering whether or not to add a particular box to the score, I'd use recursion to keep things simple when exploring all the branches (Plus working from the end and memoizing those scores to better handle huge inputs):

import java.util.Arrays;
import java.util.Random;

public class Demo {

    /**
     * Find the maximum possible score of the given boxes
     *
     * @param boxes The boxes
     * @param i the index of the current box we're considering adding
     * to the score.
     * @param score the current score without the current box
     * @param cache already computed maximum scores starting with the
     * Nth box, or -1 if not already found.
     * @return the maximum possible score
     */
    private static int solve(int[] boxes, int i, int score, int[] cache) {
        if (i >= boxes.length) {
            // No more boxes to consider
            return score;
        } else if (cache[i] > -1) {
            // The maximum score for the current box to the end has
            // already been calculated; re-use it.
            return score + cache[i];
        } else if (i == boxes.length - 1) {
            // Last box; go ahead and add it to the score and we're done.
            return score + boxes[i];
        } else {
            /* Now there are three options with at least one more box
             * after this one: */

            // Add the current box and the next box, and then stop
            // (Two consecutive boxes).
            int s1 = score + boxes[i] + boxes[i + 1];

            // Add the current box and skip a box to keep calculating
            // a score
            int s2 = solve(boxes, i + 2, score + boxes[i], cache);

            // Skip the current box and keep calculating
            int s3 = solve(boxes, i + 1, score, cache);

            // Now return the largest of the three
            return Math.max(s1, Math.max(s2, s3));
        }
    }

    private static int solve(int[] boxes) {
        int[] cache = new int[boxes.length];
        Arrays.fill(cache, -1);
        // Solve from the end - calculate the maximum score of the
        // last N boxes of the array. Then when calculating the score
        // for the N-1th box, that value can be re-used.
        cache[boxes.length - 1] = boxes[boxes.length - 1];
        for (int i = boxes.length - 2; i >= 0; i--) {
            cache[i] = solve(boxes, i, 0, cache);
        }
        return cache[0];
    }

    private static void show(int[] boxes) {
        System.out.println("Input: " + Arrays.toString(boxes));
        System.out.println("Output: " + solve(boxes));
    }

    /** Generate an array of random numbers for testing large inputs */
    private static void show(Random rng, int size) {
        show(rng.ints(1, 21).limit(size).toArray());
    }

    public static void main(String[] args) {
        Random rng = new Random();
        show(new int[]{1, 4, 2, 10});
        show(new int[]{1, 4, 5, 3});
        show(rng, 1000);
    }
}
```

Title: Maximum sum in array given constraints


问:
Document Read and insert with locking/transaction in nodejs with mongodb
In reservation system, only 5 different user can create bookings. If 100 user call booking api at same time than how to handle concurrency with locking. I am using nodejs with mongodb. I went through mongo concurrency article and transactions in mongodb, but cannot find any sample coding solution with locking.

I have achieved solution with Optimistic concurrency control (when there is low contention for the resource - This can be easily implemented using versionNumber or timeStamp field).

Thank you in advance for suggesting me solution with locking.

Now the algorithm is:

Step 1: Get userAllowedNumber from userSettings collection.

//Query
db.getCollection('userSettings').find({})

//Response Data
{ "userAllowedNumber": 5 }
```
<p><strong>Step 2</strong>, Get current bookedCount from bookings collection.</p>
<pre class="lang-js prettyprint-override"><code>//Query
db.getCollection('bookings').count({ })

//Response Data
2
</code>```

Step 3, if bookedCount <= userAllowedNumber then insert in bookings.

//Query
db.getCollection('bookings').create({ user_id: "usr_1" })
```

答:
For a simple example of transaction, first you need to have a client connect to a MongoDB.

const client = new MongoClient(uri);
await client.connect();
```
<p>Once you have the client, you can create a session from which you can make transactions:</p>
<pre class="lang-js prettyprint-override"><code>const session = await client.startSession();
const transactionResults = await session.withTransaction( async () => {
     await client.db().collection("example").insertOne(example);
}, transactionOptions);
</code>```

With transactionOptions being:

const transactionOptions = {
   readPreference: 'primary',
   readConcern: { level: 'majority' },
   writeConcern: { w: 'majority' }
};
```

Find about the Read/Write concern in the MongoDb documentation.
Depending on your usecase, you may also consider findAndModify which lock the document on change.

Body:
In reservation system, only 5 different user can create bookings. If 100 user call booking api at same time than how to handle concurrency with locking. I am using nodejs with mongodb. I went through mongo concurrency article and transactions in mongodb, but cannot find any sample coding solution with locking.

I have achieved solution with Optimistic concurrency control (when there is low contention for the resource - This can be easily implemented using versionNumber or timeStamp field).

Thank you in advance for suggesting me solution with locking.

Now the algorithm is:

Step 1: Get userAllowedNumber from userSettings collection.

//Query
db.getCollection('userSettings').find({})

//Response Data
{ "userAllowedNumber": 5 }

Step 2, Get current bookedCount from bookings collection.

//Query
db.getCollection('bookings').count({ })

//Response Data
2

Step 3, if bookedCount <= userAllowedNumber then insert in bookings.

//Query
db.getCollection('bookings').create({ user_id: "usr_1" })

Body:
For a simple example of transaction, first you need to have a client connect to a MongoDB.

const client = new MongoClient(uri);
await client.connect();

Once you have the client, you can create a session from which you can make transactions:

const session = await client.startSession();
const transactionResults = await session.withTransaction( async () => {
     await client.db().collection("example").insertOne(example);
}, transactionOptions);

With transactionOptions being:

const transactionOptions = {
   readPreference: 'primary',
   readConcern: { level: 'majority' },
   writeConcern: { w: 'majority' }
};

Find about the Read/Write concern in the MongoDb documentation.
Depending on your usecase, you may also consider findAndModify which lock the document on change.


问:
How to integrate Airflow python operator with Datadog for monitoring of the process
Is it possible to integrate Airflow with Datadog in the sense of monitoring the logic within PythonOperator?

For example, assume the following PythonOperator and python callback -

```<code>def rand_task(**context):
    time = round(time.time() * 1000)
    random.seed(time)
    rand = random.random()

rand_task = PythonOperator(
    task_id="rand_task",
    python_callable=rand_func,
    provide_context=True,
    dag=dag,
)
</code>```

I want to create a monitoring mechanism in Datadog on the value of rand variable.
Is it possible?

答:
Depending on what you what to do with the data, you can send both logs and metrics from your Python callback to Datadog via HTTP. If you want to create an actionable monitor, you probably want to use a metric.

You could also explore the SimpleHttpOperator to avoid adding additional dependencies.

Body:
Is it possible to integrate Airflow with Datadog in the sense of monitoring the logic within PythonOperator?

For example, assume the following PythonOperator and python callback -

def rand_task(**context):
    time = round(time.time() * 1000)
    random.seed(time)
    rand = random.random()

rand_task = PythonOperator(
    task_id="rand_task",
    python_callable=rand_func,
    provide_context=True,
    dag=dag,
)

I want to create a monitoring mechanism in Datadog on the value of rand variable.
Is it possible?


问:
Formatting percentage tick labels in seaborn catplot returning values higher than expected
The x axis on my catplot currently consists of categorical decimal values as such:

```<code>[0.05, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8. 0.9, 1.0]
</code>```

I'm using the following to try to format to a percentage, but it's returning value values 10x greater than expected:

```<code>for axis in ax.axes.flat:
    axis.xaxis.set_major_formatter(ticker.FuncFormatter(lambda x, p: f'{x:.0%}'))
    axis.yaxis.set_major_formatter(ticker.FuncFormatter(lambda y, p: f'{y:.2%}'))
</code>```

currently yields:

```<code>[0, 100%, 200%, 300%, 400%, 500%, 600%, 700%, 800%, 900%, 1000%]
</code>```

The y-axis is formatted correctly, not sure why the x-axis is returning values higher than expected.

答:
Internally, seaborn plots categorical variables at x=[0, 1, 2, ..., 10], so that's why the percentage formatter is returning x=[0, 100, 200, ..., 1000].

In this case, you can apply the % f-string directly with set_xticklabels:

```<code>xticks = [0.05, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]

for axis in ax.axes.flat:
    axis.set_xticklabels([f'{x:.0%}' for x in xticks])
    axis.yaxis.set_major_formatter(ticker.FuncFormatter(lambda y, p: f'{y:.2%}'))
</code>```

Body:
The x axis on my catplot currently consists of categorical decimal values as such:

[0.05, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8. 0.9, 1.0]

I'm using the following to try to format to a percentage, but it's returning value values 10x greater than expected:

for axis in ax.axes.flat:
    axis.xaxis.set_major_formatter(ticker.FuncFormatter(lambda x, p: f'{x:.0%}'))
    axis.yaxis.set_major_formatter(ticker.FuncFormatter(lambda y, p: f'{y:.2%}'))

currently yields:

[0, 100%, 200%, 300%, 400%, 500%, 600%, 700%, 800%, 900%, 1000%]

The y-axis is formatted correctly, not sure why the x-axis is returning values higher than expected.

Body:
Internally, seaborn plots categorical variables at x=[0, 1, 2, ..., 10], so that's why the percentage formatter is returning x=[0, 100, 200, ..., 1000].

In this case, you can apply the % f-string directly with set_xticklabels:

xticks = [0.05, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]

for axis in ax.axes.flat:
    axis.set_xticklabels([f'{x:.0%}' for x in xticks])
    axis.yaxis.set_major_formatter(ticker.FuncFormatter(lambda y, p: f'{y:.2%}'))


问:
How do I highlight text in PHP with conditions?
I have some numbers, and depending on the number's value I need to highlight a string which is in a table. The table is not in database.

Does anyone know how to highlight text in php?

答:
PHP won't "highlight" text, that is done with CSS/HTML. You only use PHP to output the correct HTML.

Something like this:

```<code>$my_num = 9;
foreach ($my_array_of_numbers as $num)
{
   // See if $num matches $my_num, if so - add the "highlight"
   // class to the HTML element we're using
   $css_class = ($num == $my_num) ? 'highlight' : '';
   echo '<td class="'.$css_class.'">'.$num.'</td>';
}
</code>```

Then in your CSS:

```<code>.highlight {
    background:yellow;
}
</code>```

You may also want to consider using javascript for this, which can handle the task after the HTML has already been generated.

Body:
PHP won't "highlight" text, that is done with CSS/HTML. You only use PHP to output the correct HTML.

Something like this:

$my_num = 9;
foreach ($my_array_of_numbers as $num)
{
   // See if $num matches $my_num, if so - add the "highlight"
   // class to the HTML element we're using
   $css_class = ($num == $my_num) ? 'highlight' : '';
   echo '<td class="'.$css_class.'">'.$num.'</td>';
}

Then in your CSS:

.highlight {
    background:yellow;
}

You may also want to consider using javascript for this, which can handle the task after the HTML has already been generated.


问:
AttributeError: partially initialized module x has no attribute y (most likely due to a circular import)
I want to use pandas to process a csv file. The main job is to duplicate a column, so I name the script file as copy.py.

import pandas as pd

df = pd.read_csv('latex.csv')
```
<p>However, when I execute the file, it gets the error</p>
<pre class="lang-sh prettyprint-override"><code>$ python copy.py
Traceback (most recent call last):
  File "~/sourcecode/rime-math/copy.py", line 1, in <module>
    import pandas as pd
    import pandas as pd
  File "~/.local/lib/python3.10/site-packages/pandas/__init__.py", line 50, in <module>
    from pandas.core.api import (
  File "~/.local/lib/python3.10/site-packages/pandas/core/api.py", line 48, in <module>
    from pandas.core.groupby import (
  File "~/.local/lib/python3.10/site-packages/pandas/core/groupby/__init__.py", line 1, in <module>
    from pandas.core.groupby.generic import (
  File "~/.local/lib/python3.10/site-packages/pandas/core/groupby/generic.py", line 73, in <module>
    from pandas.core.frame import DataFrame
  File "~/.local/lib/python3.10/site-packages/pandas/core/frame.py", line 129, in <module>
    from pandas.core import (
  File "~/.local/lib/python3.10/site-packages/pandas/core/generic.py", line 122, in <module>
    from pandas.core.describe import describe_ndframe
  File "~/.local/lib/python3.10/site-packages/pandas/core/describe.py", line 37, in <module>
    from pandas.core.reshape.concat import concat
  File "~/.local/lib/python3.10/site-packages/pandas/core/reshape/concat.py", line 45, in <module>
    from pandas.core.internals import concatenate_managers
  File "~/.local/lib/python3.10/site-packages/pandas/core/internals/__init__.py", line 17, in <module>
    from pandas.core.internals.concat import concatenate_managers
  File "~/.local/lib/python3.10/site-packages/pandas/core/internals/concat.py", line 3, in <module>
    import copy
  File "~/sourcecode/rime-math/copy.py", line 4, in <module>
    df = pd.read_csv('latex.csv')
AttributeError: partially initialized module 'pandas' has no attribute 'read_csv' (most likely due to a circular import)
</code>```

答:
The problem is that the name of your script file is collision with the file one of your module wants to import.

Put attention on the last 5 lines of the traceback since it is near line where error occurs:

```<code>  File "~/.local/lib/python3.10/site-packages/pandas/core/internals/concat.py", line 3, in <module>
    import copy
  File "~/sourcecode/rime-math/copy.py", line 4, in <module>
    df = pd.read_csv('latex.csv')
AttributeError: partially initialized module 'pandas' has no attribute 'read_csv' (most likely due to a circular import)
</code>```

Look at the first 2 lines, it means pandas module need to import copy module at somewhere.

According to The Module Search Path, Python interpreter will search copy module in built-in modules, current directory, PYTHONPATH etc. in order.

Apparently there is no built-in modules named copy in Python, so the interpreter will then look at the files under current directory and find there is copy.py.

The content of copy.py is just one line: df = pd.read_csv(). It means we need to use pandas module. However, we are just on the way importing pandas. Pandas here is only partially initialized, that's why you see that information in backtrace.

To solve this is easy, rename the script file copy.py to some others is ok.

Body:
I want to use pandas to process a csv file. The main job is to duplicate a column, so I name the script file as copy.py.

import pandas as pd

df = pd.read_csv('latex.csv')

However, when I execute the file, it gets the error

$ python copy.py
Traceback (most recent call last):
  File "~/sourcecode/rime-math/copy.py", line 1, in <module>
    import pandas as pd
    import pandas as pd
  File "~/.local/lib/python3.10/site-packages/pandas/__init__.py", line 50, in <module>
    from pandas.core.api import (
  File "~/.local/lib/python3.10/site-packages/pandas/core/api.py", line 48, in <module>
    from pandas.core.groupby import (
  File "~/.local/lib/python3.10/site-packages/pandas/core/groupby/__init__.py", line 1, in <module>
    from pandas.core.groupby.generic import (
  File "~/.local/lib/python3.10/site-packages/pandas/core/groupby/generic.py", line 73, in <module>
    from pandas.core.frame import DataFrame
  File "~/.local/lib/python3.10/site-packages/pandas/core/frame.py", line 129, in <module>
    from pandas.core import (
  File "~/.local/lib/python3.10/site-packages/pandas/core/generic.py", line 122, in <module>
    from pandas.core.describe import describe_ndframe
  File "~/.local/lib/python3.10/site-packages/pandas/core/describe.py", line 37, in <module>
    from pandas.core.reshape.concat import concat
  File "~/.local/lib/python3.10/site-packages/pandas/core/reshape/concat.py", line 45, in <module>
    from pandas.core.internals import concatenate_managers
  File "~/.local/lib/python3.10/site-packages/pandas/core/internals/__init__.py", line 17, in <module>
    from pandas.core.internals.concat import concatenate_managers
  File "~/.local/lib/python3.10/site-packages/pandas/core/internals/concat.py", line 3, in <module>
    import copy
  File "~/sourcecode/rime-math/copy.py", line 4, in <module>
    df = pd.read_csv('latex.csv')
AttributeError: partially initialized module 'pandas' has no attribute 'read_csv' (most likely due to a circular import)

Body:
The problem is that the name of your script file is collision with the file one of your module wants to import.

Put attention on the last 5 lines of the traceback since it is near line where error occurs:

  File "~/.local/lib/python3.10/site-packages/pandas/core/internals/concat.py", line 3, in <module>
    import copy
  File "~/sourcecode/rime-math/copy.py", line 4, in <module>
    df = pd.read_csv('latex.csv')
AttributeError: partially initialized module 'pandas' has no attribute 'read_csv' (most likely due to a circular import)

Look at the first 2 lines, it means pandas module need to import copy module at somewhere.

According to The Module Search Path, Python interpreter will search copy module in built-in modules, current directory, PYTHONPATH etc. in order.

Apparently there is no built-in modules named copy in Python, so the interpreter will then look at the files under current directory and find there is copy.py.

The content of copy.py is just one line: df = pd.read_csv(). It means we need to use pandas module. However, we are just on the way importing pandas. Pandas here is only partially initialized, that's why you see that information in backtrace.

To solve this is easy, rename the script file copy.py to some others is ok.