问:
Is generating random numbers from hardware performance cryptographically secure?
Suppose I have a program that needs an RNG.

If I were to run arbitrary operations and check the ∆t it takes to do said operations, I could generate random numbers from that

For example:

```<code>double start = device.time();
for(int i=0;i<100;i++);//assume compiler doesn't optimize this away
double end = device.time();
double dt = end-start;
</code>```

dt will be more or less random based on many variables on the device such as battery level, transistor age, room temperature, other processes running, etc.

Now, suppose I keep generating dts and multiply them together as I go, hundreds of times, thousands of times, millions of times, eventually I am left with a very arbitrary number based on values that were more or less randomly calculated by hardware performance benchmarking.

Every time I multiply these dts together, the possible outputs increases exponentially, so determining what possible outputs may be becomes perhaps an impossible task after millions of iterations of this, even if each individual dt value is going to be within a similar range.

A thought then occurs, if you have a very consistent device, you may have dt always in the range of say 0.000000011, 0.000000012, 0.000000013, 0.000000014, then the final output number, no matter how many times I iterate and multiply, will be a number of the form 0.000000011^a * 0.000000012^b * 0.000000013^c * 0.000000014^d, that's probably easy to crack.

But then I turn to hashing, suppose rather than multiplying each dt, I concatenate it in string form to the previous values and hash them, so every time I generate a new dt based on hardware performance's random environmental values, I hash. Then at the end I digest the hash to whatever form I need, now the final output number can't be written in a general algebraic form.

Will numbers generated in this form be cryptographically secure?

答:
If you take enough samples, and use few enough low bits of the time difference, then maybe timing of async interrupts could eventually add up to a useful amount of entropy.

Most OS kernels will collect entropy from timing in their own interrupt handlers, as part of the source for /dev/urandom, but if you really want to roll your own instead of asking the OS for randomness, it's plausible if you're very careful with your mixing function.  e.g. have a look at what the Linux kernel uses for mixing in new data into its entropy pool.  It has to avoid being "hurt" by sources that aren't actually random on a given system.

Other than interrupts, performance over short times is nearly deterministic, and CPU frequency variations are quantized into not that many different frequencies.

based on many variables on the device such as ...

battery level: maybe a 2-state effect like limiting max turbo when not on AC power, and/or when the battery is low.

transistor age: no.  At most an indirect effect if aged transistors use more power, leading to the CPU running hotter and dropping out of max turbo sooner.  I'm not sure there's any significant effect.

room temperature: again, only possibly reducing max clock speed sooner.  Unless you're wasting multiple seconds of CPU time on this, it won't have an effect even on lightweight laptops.  Desktops typically have enough cooling to sustain max turbo indefinitely on a single core, especially for simple scalar code.  (SIMD FMA would make a lot more heat.)

other processes running: yes, that and async interrupts that happen to come inside your timed intervals will be the main source of randomness.

Most of the factors that affect clock speed will just uniformly scale up all times, correlated between samples, not more entropy.  Clock frequency doesn't change that often; after ramping up to full speed for your benchmark loops, expect it to stay constant for multiple seconds.

Body:
Suppose I have a program that needs an RNG.

If I were to run arbitrary operations and check the ∆t it takes to do said operations, I could generate random numbers from that

For example:

double start = device.time();
for(int i=0;i<100;i++);//assume compiler doesn't optimize this away
double end = device.time();
double dt = end-start;

dt will be more or less random based on many variables on the device such as battery level, transistor age, room temperature, other processes running, etc.

Now, suppose I keep generating dts and multiply them together as I go, hundreds of times, thousands of times, millions of times, eventually I am left with a very arbitrary number based on values that were more or less randomly calculated by hardware performance benchmarking.

Every time I multiply these dts together, the possible outputs increases exponentially, so determining what possible outputs may be becomes perhaps an impossible task after millions of iterations of this, even if each individual dt value is going to be within a similar range.

A thought then occurs, if you have a very consistent device, you may have dt always in the range of say 0.000000011, 0.000000012, 0.000000013, 0.000000014, then the final output number, no matter how many times I iterate and multiply, will be a number of the form 0.000000011^a * 0.000000012^b * 0.000000013^c * 0.000000014^d, that's probably easy to crack.

But then I turn to hashing, suppose rather than multiplying each dt, I concatenate it in string form to the previous values and hash them, so every time I generate a new dt based on hardware performance's random environmental values, I hash. Then at the end I digest the hash to whatever form I need, now the final output number can't be written in a general algebraic form.

Will numbers generated in this form be cryptographically secure?


来源: stackexchange

问:
C program to count the character with the lowest frequency
I have written this code for finding the character with the minimum frequency.

So, giving in input "Hi, how is the weather todayy Dori", the output should be

The letter with the minimum frequency is ‘s’ and the frequency is 1.

But it shows

How to remove the that coma what is my mistake here

```<code>#include<stdio.h>
#include <string.h>
#include <ctype.h>
#define MAX 1000

int main()
{
    char str[MAX];
    int  fre[MAX],i,q,r,co=0,num;

    printf("The string : ");
    gets(str);

    for(q=0;str[q];q++);
    r=num=q;

    for(i=0;i<num;i++)
    {
        fre[i]=num;
        co=1;
        if(str[i])
        {

          for(q=i+1;q<num;q++)
          {

            if(tolower(str[i]) == tolower(str[q]))
         {
            {
                 co++;
                 str[q]='\0';
            }
          }
          fre[i]=co;
        if(co<=r)
         r=co;

       }

        }
    }
    printf("The letter with the minimum frequency is");
    for(q=0;q<num;q++)
        {

            if(fre[q]==r)
            {
                 printf(" '%c' ",str[q]);
            }
       }

    printf("and the frequency is %d \n ",r);

    return 0;
}
</code>```

答:
For starters the function gets is unsafe and is not supported by the C Standard. Instead use the standard C function fgets.

As an entered string in general can be very big while letters in the string converted to the lower case can be in the range of ['a', 'z'] then there is no sense to declare such a big array as the array fre declared like.

```<code>int  fre[MAX];
</code>```

As you already included the header <string.h> then there is no sense manually to calculate the length of the entered string.

```<code>for(q=0;str[q];q++);
</code>```

To exclude non-letters characters from counting you can use the standard C function isalpha declared in the header <ctype.h>.

Pay attention to that in general the entered string can have no letters.

Here is a demonstrative program that shows how your approach can be implemented.

```<code>#include <stdio.h>
#include <ctype.h>

int main(void)
{
    enum { MAX = 1000 };
    char s[MAX];
    size_t frequency[ 'z' - 'a' + 1] = { 0 };
    const size_t N = sizeof( frequency ) / sizeof( *frequency );

    printf( "The string: " );

    if ( fgets( s, MAX, stdin ) )
    {
        for ( const char *p = s; *p; ++p )
        {
            if ( isalpha( ( unsigned char )*p ) )
            {
                ++frequency[tolower( ( unsigned char )*p ) - 'a'];
            }
        }

        size_t min = 0;

        for ( size_t i = 0; i < N; i++ )
        {
            if ( frequency[i] != 0  && ( min == 0 || frequency[i] < min ) )
            {
                min = frequency[i];
            }
        }

        if ( min == 0 )
        {
            puts( "There ie no letters in the entered string." );
        }
        else
        {
            printf( "The letter with the minimum frequency is: " );
            for ( size_t i = 0; i < N; i++ )
            {
                if ( frequency[i] == min ) printf( "%c ", ( int )('a' + i ) );
            }

            printf( "\nand the frequency is %zu\n ", min );
        }
    }

    return 0;
}
</code>```

The program output might look like

```<code>The string: Hi, how is the weather todayy Dor
The letter with the minimum frequency is: s
and the frequency is 1
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have written this code for finding the character with the minimum frequency.

So, giving in input "Hi, how is the weather todayy Dori", the output should be

The letter with the minimum frequency is ‘s’ and the frequency is 1.

But it shows

How to remove the that coma what is my mistake here

#include<stdio.h>
#include <string.h>
#include <ctype.h>
#define MAX 1000

int main()
{
    char str[MAX];
    int  fre[MAX],i,q,r,co=0,num;

    printf("The string : ");
    gets(str);

    for(q=0;str[q];q++);
    r=num=q;

    for(i=0;i<num;i++)
    {
        fre[i]=num;
        co=1;
        if(str[i])
        {

          for(q=i+1;q<num;q++)
          {

            if(tolower(str[i]) == tolower(str[q]))
         {
            {
                 co++;
                 str[q]='\0';
            }
          }
          fre[i]=co;
        if(co<=r)
         r=co;

       }

        }
    }
    printf("The letter with the minimum frequency is");
    for(q=0;q<num;q++)
        {

            if(fre[q]==r)
            {
                 printf(" '%c' ",str[q]);
            }
       }

    printf("and the frequency is %d \n ",r);

    return 0;
}

Body:
For starters the function gets is unsafe and is not supported by the C Standard. Instead use the standard C function fgets.

As an entered string in general can be very big while letters in the string converted to the lower case can be in the range of ['a', 'z'] then there is no sense to declare such a big array as the array fre declared like.

int  fre[MAX];

As you already included the header <string.h> then there is no sense manually to calculate the length of the entered string.

for(q=0;str[q];q++);

To exclude non-letters characters from counting you can use the standard C function isalpha declared in the header <ctype.h>.

Pay attention to that in general the entered string can have no letters.

Here is a demonstrative program that shows how your approach can be implemented.

#include <stdio.h>
#include <ctype.h>

int main(void)
{
    enum { MAX = 1000 };
    char s[MAX];
    size_t frequency[ 'z' - 'a' + 1] = { 0 };
    const size_t N = sizeof( frequency ) / sizeof( *frequency );

    printf( "The string: " );

    if ( fgets( s, MAX, stdin ) )
    {
        for ( const char *p = s; *p; ++p )
        {
            if ( isalpha( ( unsigned char )*p ) )
            {
                ++frequency[tolower( ( unsigned char )*p ) - 'a'];
            }
        }

        size_t min = 0;

        for ( size_t i = 0; i < N; i++ )
        {
            if ( frequency[i] != 0  && ( min == 0 || frequency[i] < min ) )
            {
                min = frequency[i];
            }
        }

        if ( min == 0 )
        {
            puts( "There ie no letters in the entered string." );
        }
        else
        {
            printf( "The letter with the minimum frequency is: " );
            for ( size_t i = 0; i < N; i++ )
            {
                if ( frequency[i] == min ) printf( "%c ", ( int )('a' + i ) );
            }

            printf( "\nand the frequency is %zu\n ", min );
        }
    }

    return 0;
}

The program output might look like

The string: Hi, how is the weather todayy Dor
The letter with the minimum frequency is: s
and the frequency is 1


问:
How to make a segue append a a tableview in another Vc in swift?
Still learning and not very bright.
In 2 VCs: the first one has some labels that perform a segue to a tableview in a second VC.
Although the code says append, it works only once.
There is an unwind from the second VC to the first, but when I push the button to append and "feed" the tableview, it does not append, it replace the first segue.
I believe this is because the segue, since it will always shows a brand new VC and not append the tableview, this way I lose the first "insert". Or, there is an issue with the append code.
Any help or sample how to append a tableview in another VC would be very helpful. I looked for a lot but it seems there is always a segue FROM tableview not TO a tableview.
I thank in advance any thoughts.</p>

答:
You should create a new file ApplicationData.swift and write down following code:

```<code>import Foundation

class ApplicationData {
    static var shared = ApplicationData()

    var cities = ["Austin", "Barcelona", "Canberra", "Darwin", "Florida", "Moscow"]

    private init() {
        print("Shared instance succuessfully instantiated")
    }
}
</code>```

in any of your view controller you should add variable:

```<code>var applicationData = ApplicationData.shared
</code>```

No matter which controller changes cities property of the variable it will affect one and only instance shared within your application.

Body:
You should create a new file ApplicationData.swift and write down following code:

import Foundation

class ApplicationData {
    static var shared = ApplicationData()

    var cities = ["Austin", "Barcelona", "Canberra", "Darwin", "Florida", "Moscow"]

    private init() {
        print("Shared instance succuessfully instantiated")
    }
}

in any of your view controller you should add variable:

var applicationData = ApplicationData.shared

No matter which controller changes cities property of the variable it will affect one and only instance shared within your application.


问:
Java checkstyle: Check whether or not return type is X if method name contains Y
I'm trying to write a checkstyle rule that verifies the return type of a method if the name passes a certain regex.

e.g: If the method name contains Foo, I want to make sure that the return type isn't Bar.

Passes:

```<code>public Fizz testFoo() {}

public Optional<Fizz> testFoo2() {}
</code>```

Fails:

```<code>public Bar testFoo() {}

public Optional<Bar> fooTest() {}
</code>```

答:
You can build your own check and use it

for example this is custom check that can solve your problem

The XML Config

```<code><module name="Checker">
   <module name="TreeWalker">
       <module name="ReturnTypeNameCheck">
          <property name="methodNameFormat" value=".*Foo"/>
          <property name="returnNameFormat" value="String"/>
       </module>
    </module>
</module>
</code>```

The Custom check code

```<code>public class ReturnTypeNameCheck extends AbstractCheck {

    public static final String MSG_KEY = "return.type.name.check";

    private String methodNameFormat = "";
    private String returnNameFormat = "";

    @Override
    public int[] getDefaultTokens() {
        return getRequiredTokens();
    }

    @Override
    public int[] getAcceptableTokens() {
        return getRequiredTokens();
    }

    @Override
    public int[] getRequiredTokens() {
        return new int[] {TokenTypes.METHOD_DEF};
    }

    public final void setMethodNameFormat(String format) {
        methodNameFormat = format;
    }

    public final void setReturnNameFormat(String format) {
        returnNameFormat = format;
    }

    @Override
    public void visitToken(DetailAST ast) {
        DetailAST methodName = ast.findFirstToken(TokenTypes.IDENT);
        DetailAST methodType = ast.findFirstToken(TokenTypes.TYPE);

        String methodNameStr = methodName.getText();
        String returnTypeName = methodType.getFirstChild().getText();

        if(methodNameStr.matches(methodNameFormat)) {
            if(methodType.branchContains(TokenTypes.TYPE_ARGUMENTS)){

                DetailAST typeArgs = methodType.getLastChild();
                while (typeArgs != null && typeArgs.getChildCount(TokenTypes.TYPE_ARGUMENT) != 0) {
                    typeArgs = typeArgs.findFirstToken(TokenTypes.TYPE_ARGUMENT);
                    String genericTypeName = typeArgs.findFirstToken(TokenTypes.IDENT).getText();

                    if(genericTypeName.contains(returnNameFormat)){
                        log(ast, MSG_KEY);
                        return;
                    }

                    typeArgs = typeArgs.getLastChild();
               }
            } else{
                if(returnTypeName.contains(returnNameFormat)){
                    log(ast, MSG_KEY);
                }
            }
        }
    }
</code>```

Examples of vol for this Check

```<code>class Test {
   public void testFoo() {} //OK
   public String testFoo() {} //violation
   public ClassOne<String> testFoo() {}  //violation
   public ClassOne<ClassTwo<String>> testFoo() {}  //violation
   public ClassOne<ClassTwo<ClassThree<String>>> testFoo() {}  //violation
}
</code>```

and this link will help you to build your own custom Check
https://checkstyle.sourceforge.io/writingchecks.html

Body:
I'm trying to write a checkstyle rule that verifies the return type of a method if the name passes a certain regex.

e.g: If the method name contains Foo, I want to make sure that the return type isn't Bar.

Passes:

public Fizz testFoo() {}

public Optional<Fizz> testFoo2() {}

Fails:

public Bar testFoo() {}

public Optional<Bar> fooTest() {}

Body:
You can build your own check and use it

for example this is custom check that can solve your problem

The XML Config

<module name="Checker">
   <module name="TreeWalker">
       <module name="ReturnTypeNameCheck">
          <property name="methodNameFormat" value=".*Foo"/>
          <property name="returnNameFormat" value="String"/>
       </module>
    </module>
</module>

The Custom check code

public class ReturnTypeNameCheck extends AbstractCheck {

    public static final String MSG_KEY = "return.type.name.check";

    private String methodNameFormat = "";
    private String returnNameFormat = "";

    @Override
    public int[] getDefaultTokens() {
        return getRequiredTokens();
    }

    @Override
    public int[] getAcceptableTokens() {
        return getRequiredTokens();
    }

    @Override
    public int[] getRequiredTokens() {
        return new int[] {TokenTypes.METHOD_DEF};
    }

    public final void setMethodNameFormat(String format) {
        methodNameFormat = format;
    }

    public final void setReturnNameFormat(String format) {
        returnNameFormat = format;
    }

    @Override
    public void visitToken(DetailAST ast) {
        DetailAST methodName = ast.findFirstToken(TokenTypes.IDENT);
        DetailAST methodType = ast.findFirstToken(TokenTypes.TYPE);

        String methodNameStr = methodName.getText();
        String returnTypeName = methodType.getFirstChild().getText();

        if(methodNameStr.matches(methodNameFormat)) {
            if(methodType.branchContains(TokenTypes.TYPE_ARGUMENTS)){

                DetailAST typeArgs = methodType.getLastChild();
                while (typeArgs != null && typeArgs.getChildCount(TokenTypes.TYPE_ARGUMENT) != 0) {
                    typeArgs = typeArgs.findFirstToken(TokenTypes.TYPE_ARGUMENT);
                    String genericTypeName = typeArgs.findFirstToken(TokenTypes.IDENT).getText();

                    if(genericTypeName.contains(returnNameFormat)){
                        log(ast, MSG_KEY);
                        return;
                    }

                    typeArgs = typeArgs.getLastChild();
               }
            } else{
                if(returnTypeName.contains(returnNameFormat)){
                    log(ast, MSG_KEY);
                }
            }
        }
    }

Examples of vol for this Check

class Test {
   public void testFoo() {} //OK
   public String testFoo() {} //violation
   public ClassOne<String> testFoo() {}  //violation
   public ClassOne<ClassTwo<String>> testFoo() {}  //violation
   public ClassOne<ClassTwo<ClassThree<String>>> testFoo() {}  //violation
}

and this link will help you to build your own custom Check
https://checkstyle.sourceforge.io/writingchecks.html


问:
How to format gridview columns?
Below is my code:

```<code>var grid = new GridView();
grid.DataSource = myDataset;

grid.DataBind();
</code>```

I want to format some of the columns of my grid to Currency with thousand separator and with decimal like '$9,999,999.99'.

I am exporting the grid to excel and I want to see the values in currency format.

I am creating gridview during runtime. I have no html code for my gridview.

I am just bounding dataset to gridview and exporting to excel. I won't see gridview in HTML format.

How to do that?

答:
Create a BoundField for the currency column with appropriate DataFormatString.

```<code><asp:BoundField  DataField="currencyColumnName" DataFormatString="{0:c}" />
</code>```

ContentLicense: CC BY-SA 3.0

Title: How to format gridview columns?

Body:
Below is my code:

var grid = new GridView();
grid.DataSource = myDataset;

grid.DataBind();

I want to format some of the columns of my grid to Currency with thousand separator and with decimal like '$9,999,999.99'.

I am exporting the grid to excel and I want to see the values in currency format.

I am creating gridview during runtime. I have no html code for my gridview.

I am just bounding dataset to gridview and exporting to excel. I won't see gridview in HTML format.

How to do that?

Body:
Create a BoundField for the currency column with appropriate DataFormatString.

<asp:BoundField  DataField="currencyColumnName" DataFormatString="{0:c}" />


问:
How to set a directive and property binding on an element created with Renderer2
I want to implement a directive called "upload-file" that would be applied on a <button> element. Its usage would be:

```<code><button upload-file> Upload a file </button>
</code>```

The directive should add a hidden <input> and when the button is clicked the <input> element will be clicked by the directive code. The resulting DOM would be:

```<code><button upload-file>Upload a file</button>
<input type="file" #uploaderInputEl ng2FileSelect [uploader]="uploader" />
</code>```

I try to create the <input> element using Renderer2 this way:

```<code>  private appendInputElement = () => {
    this.inputElement = this._renderer.createElement('input');

    this._renderer.setAttribute(this.inputElement, "type", "file");
    this._renderer.setStyle(this.inputElement, "width", "0");
    this._renderer.setStyle(this.inputElement, "visibility", "hidden");

    this._renderer.setAttribute(this.inputElement, "accept", this.acceptedFileExtensions);
    this._renderer.listen(this.inputElement, "change", (event) => this.inputElement_change(event));

    // set directive: ng2FileSelect
    // set property binding: [uploader]="uploader"

    this._renderer.appendChild(this.containerElement, this.inputElement);
  }
</code>```

But I don't know how to set the directive (ng2FileSelect) and property binding ([uploader]="uploader"). I know that they are "angular functionality" same as 'event binding' (change) which I set using _renderer.listen().

Is there a way to set directive and property-binding?

答: Unfortunately, angular not provide to set directive dynamically from the code</p>

Body:
I want to implement a directive called "upload-file" that would be applied on a <button> element. Its usage would be:

<button upload-file> Upload a file </button>

The directive should add a hidden <input> and when the button is clicked the <input> element will be clicked by the directive code. The resulting DOM would be:

<button upload-file>Upload a file</button>
<input type="file" #uploaderInputEl ng2FileSelect [uploader]="uploader" />

I try to create the <input> element using Renderer2 this way:

  private appendInputElement = () => {
    this.inputElement = this._renderer.createElement('input');

    this._renderer.setAttribute(this.inputElement, "type", "file");
    this._renderer.setStyle(this.inputElement, "width", "0");
    this._renderer.setStyle(this.inputElement, "visibility", "hidden");

    this._renderer.setAttribute(this.inputElement, "accept", this.acceptedFileExtensions);
    this._renderer.listen(this.inputElement, "change", (event) => this.inputElement_change(event));

    // set directive: ng2FileSelect
    // set property binding: [uploader]="uploader"

    this._renderer.appendChild(this.containerElement, this.inputElement);
  }

But I don't know how to set the directive (ng2FileSelect) and property binding ([uploader]="uploader"). I know that they are "angular functionality" same as 'event binding' (change) which I set using _renderer.listen().

Is there a way to set directive and property-binding?


问:
Dynamic rendering React components using data from multiple JSON objects and arrays
I am using React Native to dynamically render components. Currently the data is being taken by mapping over an array of objects which looks similar to:

const OBJECTS = [
{name: "Object 1", logo: require('../logos/object1.png')},
{name: "Object 2", logo: require('../logos/object2.png')},
{name: "Object 3", logo: require('../logos/object2.png')},
]```
</div>
</div>
</p>

<p>I then map over these objects to render a card for each object like so:</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><View>
  {object.map(item => {
    return (
    <View key={item.key}>
      <Card>
        <Text>{item.name}</Text>
        <Image source={item.logo}/>
      </Card>
    </View>
        );
      })}
</View></code>```

However now I would like to add additional items to each card which are taking information fetched from an API and retrieved in JSON form. These JSON objects look similar to the following:

Request 1:

fetchPriceActionCreator {
  "items": [{
      "objectId": "object1",
      "price": 10
    },
    {
      "objectId": "object2",
      "price": 5
    },
    {
      "objectId": "object3",
      "price": 20
    }
  ]
}```
</div>
</div>
</p>

<p>Request 2:</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>fetchBalanceActionCreator {
  "items": [{
      "objectId": "object1",
      "balance": 2,
      "account": 30022
    },
    {
      "objectId": "object2",
      "balance": 4,
      "account": 40035
    },
    {
      "objectId": "object3",
      "balance": 6,
      "account": 50021
    }
  ]
}</code>```

As the application is growing in complexity, you may notice from the action creators used to make the requests that I have begun to use Redux. My challenge is now figuring out a way to associate the retrieved JSON information, with the initial OBJECTS object array so that I can include this information in the relevant dynamically rendered card displaying the name, logo, balance, and price of each object.

From what I understand, I need to take the static information from the OBJECTS object array, and move this to initialState in either the reducer or store - however I am completely lost as to how to go about doing this, and how to then associate the two retrieved JSON object arrays, with the OBJECT object array.

The end result should look something like this:

<View>
  {object.map(item => {
    return (
    <View key={item.key}>
      <Card>
        <Text>{item.name}</Text>
        <Image source={item.logo}/>
        <Text>{item.price}</Text>
        <Text>{item.balance}</Text>
      </Card>
    </View>
        );
      })}
</View>```
</div>
</div>
</p>

<p>Any help would be greatly appreciated.</p>

<p>EDIT:</p>

<p>Currently my redux reducers look like so:</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>function priceReducer(priceState = {}, action) {
  switch (action.type) {
    case REQUEST_PRICE:
      return Object.assign({}, priceState, {
        isFetching: true,
        didInvalidate: false,
      });
    case RECEIVE_PRICE:
      return Object.assign({}, priceState, {
        isFetching: false,
        didInvalidate: false,
        lastUpdated: action.lastUpdated,
        items: action.items,
      });
    default:
      return Object.assign({}, priceState);
  }
}</code>```

答:
in your redux store you can update the state by through merging the initial state and the data coming from the api, like so

```<code>const priceState = {
    // some other props
    OBJECTS: [
        { name: "Object 1", logo: require('../logos/object1.png') },
        { name: "Object 2", logo: require('../logos/object2.png') },
        { name: "Object 3", logo: require('../logos/object2.png') },
    ]  // your initial Data as you posted.
}

function priceReducer(priceState = {}, action) {
    switch (action.type)
    {
        case REQUEST_PRICE: {
            return {
                ...priceState,
                didInvalidate: false,
                isFetching: true,
                OBJECTS: priceState.OBJECTS.map((obj) => {
                    const i = action.items.find((item) => item.objectId == obj.name) || {}; // using the conditional operator to avoid runtime error if no item was found for the given object

                    // Example: current object name is "object1", i will the item inside the payload that will have the its objectId equal to "object1"
                    return {
                        ...obj,
                        ...i /// i will be the item inside the payload that has the same object id as the current object name
                    }

                })

            }
        }

        case RECEIVE_PRICE: {
            return {
                ...priceState,
                didInvalidate: false,
                lastUpdated: action.lastUpdated,
                OBJECTS: priceState.OBJECTS.map((obj) => {
                    const i = action.items.find((item) => item.objectId == obj.name) || {}; // using the conditional operator to avoid runtime error if no item was found for the given object

                    // Example: current object name is "object1", i will the item inside the payload that will have the its objectId equal to "object1"
                    return {
                        ...obj,
                        ...i /// i will be the item inside the payload that has the same object id as the current object name
                    }

                })

            }
        }

     default: return priceState;
    }

}

</code>```

if you are not sure what the ... is its called the spread operator., which is equivalent to Object.assign that you were using

Body:
I am using React Native to dynamically render components. Currently the data is being taken by mapping over an array of objects which looks similar to:

const OBJECTS = [
{name: "Object 1", logo: require('../logos/object1.png')},
{name: "Object 2", logo: require('../logos/object2.png')},
{name: "Object 3", logo: require('../logos/object2.png')},
]

I then map over these objects to render a card for each object like so:

<View>
  {object.map(item => {
    return (
    <View key={item.key}>
      <Card>
        <Text>{item.name}</Text>
        <Image source={item.logo}/>
      </Card>
    </View>
        );
      })}
</View>

However now I would like to add additional items to each card which are taking information fetched from an API and retrieved in JSON form. These JSON objects look similar to the following:

Request 1:

fetchPriceActionCreator {
  "items": [{
      "objectId": "object1",
      "price": 10
    },
    {
      "objectId": "object2",
      "price": 5
    },
    {
      "objectId": "object3",
      "price": 20
    }
  ]
}

Request 2:

fetchBalanceActionCreator {
  "items": [{
      "objectId": "object1",
      "balance": 2,
      "account": 30022
    },
    {
      "objectId": "object2",
      "balance": 4,
      "account": 40035
    },
    {
      "objectId": "object3",
      "balance": 6,
      "account": 50021
    }
  ]
}

As the application is growing in complexity, you may notice from the action creators used to make the requests that I have begun to use Redux. My challenge is now figuring out a way to associate the retrieved JSON information, with the initial OBJECTS object array so that I can include this information in the relevant dynamically rendered card displaying the name, logo, balance, and price of each object.

From what I understand, I need to take the static information from the OBJECTS object array, and move this to initialState in either the reducer or store - however I am completely lost as to how to go about doing this, and how to then associate the two retrieved JSON object arrays, with the OBJECT object array.

The end result should look something like this:

<View>
  {object.map(item => {
    return (
    <View key={item.key}>
      <Card>
        <Text>{item.name}</Text>
        <Image source={item.logo}/>
        <Text>{item.price}</Text>
        <Text>{item.balance}</Text>
      </Card>
    </View>
        );
      })}
</View>

Any help would be greatly appreciated.

EDIT:

Currently my redux reducers look like so:

function priceReducer(priceState = {}, action) {
  switch (action.type) {
    case REQUEST_PRICE:
      return Object.assign({}, priceState, {
        isFetching: true,
        didInvalidate: false,
      });
    case RECEIVE_PRICE:
      return Object.assign({}, priceState, {
        isFetching: false,
        didInvalidate: false,
        lastUpdated: action.lastUpdated,
        items: action.items,
      });
    default:
      return Object.assign({}, priceState);
  }
}

Body:
in your redux store you can update the state by through merging the initial state and the data coming from the api, like so

const priceState = {
    // some other props
    OBJECTS: [
        { name: "Object 1", logo: require('../logos/object1.png') },
        { name: "Object 2", logo: require('../logos/object2.png') },
        { name: "Object 3", logo: require('../logos/object2.png') },
    ]  // your initial Data as you posted.
}

function priceReducer(priceState = {}, action) {
    switch (action.type)
    {
        case REQUEST_PRICE: {
            return {
                ...priceState,
                didInvalidate: false,
                isFetching: true,
                OBJECTS: priceState.OBJECTS.map((obj) => {
                    const i = action.items.find((item) => item.objectId == obj.name) || {}; // using the conditional operator to avoid runtime error if no item was found for the given object

                    // Example: current object name is "object1", i will the item inside the payload that will have the its objectId equal to "object1"
                    return {
                        ...obj,
                        ...i /// i will be the item inside the payload that has the same object id as the current object name
                    }

                })

            }
        }

        case RECEIVE_PRICE: {
            return {
                ...priceState,
                didInvalidate: false,
                lastUpdated: action.lastUpdated,
                OBJECTS: priceState.OBJECTS.map((obj) => {
                    const i = action.items.find((item) => item.objectId == obj.name) || {}; // using the conditional operator to avoid runtime error if no item was found for the given object

                    // Example: current object name is "object1", i will the item inside the payload that will have the its objectId equal to "object1"
                    return {
                        ...obj,
                        ...i /// i will be the item inside the payload that has the same object id as the current object name
                    }

                })

            }
        }

     default: return priceState;
    }

}

if you are not sure what the ... is its called the spread operator., which is equivalent to Object.assign that you were using


问:
Conditional group by with window function in Snowflake query
I have a table in Snowflake in following format:

```<code>create temp_test(name string, split string, value int)

insert into temp_test
values ('A','a', 100), ('A','b', 200), ('A','c',300), ('A', 'd', 400), ('A', 'e',500), ('B', 'a', 1000), ('B','b', 2000), ('B','c', 3000), ('B', 'd',4000), ('B','e', 5000)

</code>```

First step, I needed only top 2 value per name (sorted on value), so I used following query to get that:

```<code>select name, split, value,
row_number() over (PARTITION BY (name) order by value desc) as row_num
from temp_test
qualify row_num <= 2
</code>```

Which gives me following resultset:

```<code>NAME    SPLIT   VALUE   ROW_NUM
A       e       500     1
A       d       400     2
B       e       5000    1
B       d       4000    2
</code>```

Now, I need to sum values other than Top 2 and put it in a different Split named as "Others", like this:

```<code>NAME    SPLIT   VALUE
A       e       500
A       d       400
A       Others  600
B       e       5000
B       d       4000
B       Others  6000
</code>```

How to do that in Snowflake query or SQL in general?

答:
Shawnt00's answer is good, but for the record in Snowflake this can be written simpler:

Firstly the group by at the end can refer to the results by index or name:

```<code>GROUP BY 1,2
</code>```

or

```<code>GROUP BY name, split
</code>```

also as the CASE only has too branches an IFF can be used and seems you are using a CTE to add the row_number you can push the IFF into the CTE also

```<code>WITH data AS (
    SELECT name, value,
        ROW_NUMBER() OVER (PARTITION BY name ORDER BY value DESC) AS row_num,
        IFF(row_num < 3, split, 'Others') as n_split
    FROM VALUES ('A','a', 100), ('A','b', 200), ('A','c',300), ('A', 'd', 400),
                ('A', 'e',500), ('B', 'a', 1000), ('B','b', 2000), ('B','c', 3000),
                ('B', 'd',4000), ('B','e', 5000)
    v(name, split, value)
)
SELECT
    name,
    n_split,
    SUM(value) AS value
FROM data
GROUP BY name, n_split;
</code>```

and if super keen on small SQL push the ROW_NUMBER into the IFF:

```<code>WITH data AS (
    SELECT name, value,
        IFF(ROW_NUMBER() OVER (PARTITION BY name ORDER BY value DESC) < 3, split, 'Others') as n_split
    FROM VALUES ('A','a', 100), ('A','b', 200), ('A','c',300), ('A', 'd', 400),
                ('A', 'e',500), ('B', 'a', 1000), ('B','b', 2000), ('B','c', 3000),
                ('B', 'd',4000), ('B','e', 5000)
    v(name, split, value)
)
SELECT
    name,
    n_split AS split,
    SUM(value) AS value
FROM data
GROUP BY name, n_split;
</code>```

gives:

```<code>NAME    SPLIT   VALUE
A       e       500
A       d       400
A       Others  600
B       e       5000
B       d       4000
B       Others  6000
</code>```

Body:
I have a table in Snowflake in following format:

create temp_test(name string, split string, value int)

insert into temp_test
values ('A','a', 100), ('A','b', 200), ('A','c',300), ('A', 'd', 400), ('A', 'e',500), ('B', 'a', 1000), ('B','b', 2000), ('B','c', 3000), ('B', 'd',4000), ('B','e', 5000)

First step, I needed only top 2 value per name (sorted on value), so I used following query to get that:

select name, split, value,
row_number() over (PARTITION BY (name) order by value desc) as row_num
from temp_test
qualify row_num <= 2

Which gives me following resultset:

NAME    SPLIT   VALUE   ROW_NUM
A       e       500     1
A       d       400     2
B       e       5000    1
B       d       4000    2

Now, I need to sum values other than Top 2 and put it in a different Split named as "Others", like this:

NAME    SPLIT   VALUE
A       e       500
A       d       400
A       Others  600
B       e       5000
B       d       4000
B       Others  6000

How to do that in Snowflake query or SQL in general?

Body:
Shawnt00's answer is good, but for the record in Snowflake this can be written simpler:

Firstly the group by at the end can refer to the results by index or name:

GROUP BY 1,2

or

GROUP BY name, split

also as the CASE only has too branches an IFF can be used and seems you are using a CTE to add the row_number you can push the IFF into the CTE also

WITH data AS (
    SELECT name, value,
        ROW_NUMBER() OVER (PARTITION BY name ORDER BY value DESC) AS row_num,
        IFF(row_num < 3, split, 'Others') as n_split
    FROM VALUES ('A','a', 100), ('A','b', 200), ('A','c',300), ('A', 'd', 400),
                ('A', 'e',500), ('B', 'a', 1000), ('B','b', 2000), ('B','c', 3000),
                ('B', 'd',4000), ('B','e', 5000)
    v(name, split, value)
)
SELECT
    name,
    n_split,
    SUM(value) AS value
FROM data
GROUP BY name, n_split;

and if super keen on small SQL push the ROW_NUMBER into the IFF:

WITH data AS (
    SELECT name, value,
        IFF(ROW_NUMBER() OVER (PARTITION BY name ORDER BY value DESC) < 3, split, 'Others') as n_split
    FROM VALUES ('A','a', 100), ('A','b', 200), ('A','c',300), ('A', 'd', 400),
                ('A', 'e',500), ('B', 'a', 1000), ('B','b', 2000), ('B','c', 3000),
                ('B', 'd',4000), ('B','e', 5000)
    v(name, split, value)
)
SELECT
    name,
    n_split AS split,
    SUM(value) AS value
FROM data
GROUP BY name, n_split;

gives:

NAME    SPLIT   VALUE
A       e       500
A       d       400
A       Others  600
B       e       5000
B       d       4000
B       Others  6000


问:
The "error_marshaling_enabled" setting seems to be always enabled
When I run this code:

$client->evaluate('
    box.session.settings.error_marshaling_enabled = false
    box.error{code = 42, reason = "Foobar", type = "MyError"}
');
```

<p>regardless of the value of <code>error_marshaling_enabled</code> I always get a response with a new (extended)  error format:</p>

<pre class="lang-php prettyprint-override"><code>  [
    49 => 'Foobar',
    82 => [
      0 => [
        0 => [
          0 => 'CustomError',
          2 => 3,
          1 => 'eval',
          3 => 'Foobar',
          4 => 0,
          5 => 42,
          6 => [
            'custom_type' => 'MyError',
          ],
        ],
      ],
    ],
  ],
</code>```

Why is that?

答:
Short answer.

error_marshaling_enabled option affects only how error objects are encoded in response body (48, IPROTO_DATA). It does not affect how they are returned as exceptions, in the response header (82, IPROTO_ERROR).

Long answer.

In Tarantool an error object can be returned in 2 ways: as an exception and as an object. For example, this is how to throw an error as exception:

function throw_error()
    box.error({code = 1000, reason = "Error message"})
    -- Or
    error('Some error string')
end
```

<p>This is how to return it as an object:</p>

<pre class="lang-lua prettyprint-override"><code>function return_error()
    return box.error.new({code = 1000, reason = "Error message"})
end
</code>```

If the function was called remotely, using IPROTO protocol via a connector like netbox, or PHP connector, or any other one, the error return way affects how it is encoded into MessagePack response packet. When the function throws, and the error reaches the top stack frame without being caught, it is encoded as IPROTO_ERROR (82) and IPROTO_ERROR_24 (49).

When the error object is returned as a regular value, not as an exception, it is encoded also as a regular value, inside IPROTO_DATA (48). Just like a string, a number, a tuple, etc.

With encoding as IPROTO_ERROR/IPROTO_ERROR_24 there is no much of a configuration space. Format of these values can't be changed. IPROTO_ERROR is always returned as a MessagePack map, with a stack of errors in it. IPROTO_ERROR_24 is always an error message. The IPROTO_ERROR_24 field is kept for compatibility with connectors to Tarantool versions < 2.4.1.

With encoding as a part of IPROTO_DATA you can choose serialization way using error_marshaling_enabled option. When it is true, errors are encoded as MessagePack extension type MP_EXT, and contain the whole error stack, encoded exactly like IPROTO_ERROR value. When the option is false (default behaviour in 2.4.1), the error is encoded as a string, MP_STR, which is the error's message. If there is a stack of errors, only the newest error is encoded.

error_marshaling_enabled option exists for backward compatibility, in case your application on Tarantool wants to be compatible with old connectors, which don't support MP_EXT encoded errors.

In Tarantool < 2.4.1 errors were encoded into result MessagePack as a string with error message, and error stacks didn't exist at all. So when the new format and the error stacks feature were introduced, making the new format default would be a too radical change breaking the old connectors.

Consider these examples of how error marshaling affects results. I use Tarantool 2.4.1 console here, and built-in netbox connector. The code below can be copy pasted into the console.

First instance:

box.cfg{listen = 3313}
box.schema.user.grant('guest', 'super')

function throw_error()
    box.error({code = 1000, reason = "Error message"})
end

function return_error()
    return box.error.new({code = 1000, reason = "Error message"})
end
```

<p>Second instance:</p>

<pre class="lang-lua prettyprint-override"><code>netbox = require('net.box')
c = netbox.connect(3313)
</code>```

Now I try to call the function on the second instance:

```<code>tarantool> c:call('throw_error')
---
- error: Error message
...
</code>```

The c:call('throw_error') threw an exception. If I catch it using pcall() Lua function, I will see the error object.

```<code>tarantool> ok, err = pcall(c.call, c, 'throw_error')
tarantool> err:unpack()
---
- code: 1000
  base_type: ClientError
  type: ClientError
  message: Error message
  trace:
  - file: '[string "function throw_error()..."]'
    line: 2
...
</code>```

As you can see, I didn't set error_marshaling_enabled, but got the full error. Now I will call the other function, without exceptions. But the error object won't be full.

```<code>tarantool> err = c:call('return_error')
tarantool> err
---
- Error message
...
tarantool> err:unpack()
---
- error: '[string "return err:unpack()"]:1: attempt to call method ''unpack'' (a nil
    value)'
...
</code>```

The error was returned as a mere string, error message. Not as an error object. Now I will turn on the marshaling:

```<code>tarantool> c:eval('box.session.settings.error_marshaling_enabled = true')
---
...
tarantool> err = c:call('return_error')
---
...
tarantool> err:unpack()
---
- code: 1000
  base_type: ClientError
  type: ClientError
  message: Error message
  trace:
  - file: '[C]'
    line: 4294967295
...
</code>```

Now the same function returned the error in the new format, more featured.

On the summary: error_marshaling_enabled affects only returned errors. Not thrown errors.

Body:
When I run this code:

$client->evaluate('
    box.session.settings.error_marshaling_enabled = false
    box.error{code = 42, reason = "Foobar", type = "MyError"}
');

regardless of the value of error_marshaling_enabled I always get a response with a new (extended)  error format:

  [
    49 => 'Foobar',
    82 => [
      0 => [
        0 => [
          0 => 'CustomError',
          2 => 3,
          1 => 'eval',
          3 => 'Foobar',
          4 => 0,
          5 => 42,
          6 => [
            'custom_type' => 'MyError',
          ],
        ],
      ],
    ],
  ],

Why is that?

Body:
Short answer.

error_marshaling_enabled option affects only how error objects are encoded in response body (48, IPROTO_DATA). It does not affect how they are returned as exceptions, in the response header (82, IPROTO_ERROR).

Long answer.

In Tarantool an error object can be returned in 2 ways: as an exception and as an object. For example, this is how to throw an error as exception:

function throw_error()
    box.error({code = 1000, reason = "Error message"})
    -- Or
    error('Some error string')
end

This is how to return it as an object:

function return_error()
    return box.error.new({code = 1000, reason = "Error message"})
end

If the function was called remotely, using IPROTO protocol via a connector like netbox, or PHP connector, or any other one, the error return way affects how it is encoded into MessagePack response packet. When the function throws, and the error reaches the top stack frame without being caught, it is encoded as IPROTO_ERROR (82) and IPROTO_ERROR_24 (49).

When the error object is returned as a regular value, not as an exception, it is encoded also as a regular value, inside IPROTO_DATA (48). Just like a string, a number, a tuple, etc.

With encoding as IPROTO_ERROR/IPROTO_ERROR_24 there is no much of a configuration space. Format of these values can't be changed. IPROTO_ERROR is always returned as a MessagePack map, with a stack of errors in it. IPROTO_ERROR_24 is always an error message. The IPROTO_ERROR_24 field is kept for compatibility with connectors to Tarantool versions < 2.4.1.

With encoding as a part of IPROTO_DATA you can choose serialization way using error_marshaling_enabled option. When it is true, errors are encoded as MessagePack extension type MP_EXT, and contain the whole error stack, encoded exactly like IPROTO_ERROR value. When the option is false (default behaviour in 2.4.1), the error is encoded as a string, MP_STR, which is the error's message. If there is a stack of errors, only the newest error is encoded.

error_marshaling_enabled option exists for backward compatibility, in case your application on Tarantool wants to be compatible with old connectors, which don't support MP_EXT encoded errors.

In Tarantool < 2.4.1 errors were encoded into result MessagePack as a string with error message, and error stacks didn't exist at all. So when the new format and the error stacks feature were introduced, making the new format default would be a too radical change breaking the old connectors.

Consider these examples of how error marshaling affects results. I use Tarantool 2.4.1 console here, and built-in netbox connector. The code below can be copy pasted into the console.

First instance:

box.cfg{listen = 3313}
box.schema.user.grant('guest', 'super')

function throw_error()
    box.error({code = 1000, reason = "Error message"})
end

function return_error()
    return box.error.new({code = 1000, reason = "Error message"})
end

Second instance:

netbox = require('net.box')
c = netbox.connect(3313)

Now I try to call the function on the second instance:

tarantool> c:call('throw_error')
---
- error: Error message
...

The c:call('throw_error') threw an exception. If I catch it using pcall() Lua function, I will see the error object.

tarantool> ok, err = pcall(c.call, c, 'throw_error')
tarantool> err:unpack()
---
- code: 1000
  base_type: ClientError
  type: ClientError
  message: Error message
  trace:
  - file: '[string "function throw_error()..."]'
    line: 2
...

As you can see, I didn't set error_marshaling_enabled, but got the full error. Now I will call the other function, without exceptions. But the error object won't be full.

tarantool> err = c:call('return_error')
tarantool> err
---
- Error message
...
tarantool> err:unpack()
---
- error: '[string "return err:unpack()"]:1: attempt to call method ''unpack'' (a nil
    value)'
...

The error was returned as a mere string, error message. Not as an error object. Now I will turn on the marshaling:

tarantool> c:eval('box.session.settings.error_marshaling_enabled = true')
---
...
tarantool> err = c:call('return_error')
---
...
tarantool> err:unpack()
---
- code: 1000
  base_type: ClientError
  type: ClientError
  message: Error message
  trace:
  - file: '[C]'
    line: 4294967295
...

Now the same function returned the error in the new format, more featured.

On the summary: error_marshaling_enabled affects only returned errors. Not thrown errors.


问:
Matplotlib Scatter Plot Legend Creation Mystery
I have the following snipped of code (values for c, s, x, y are mockups, but the real lists follow the same format, just much bigger. Only two colors are used - red and green though. All lists are of the same size)

The issue is that the color legend fails to materialize. I am completely at loss as to why. Code snippets for legend generation is basically a cut-n-paste from docs, i.e. (https://matplotlib.org/3.1.1/gallery/lines_bars_and_markers/scatter_with_legend.html#sphx-glr-gallery-lines-bars-and-markers-scatter-with-legend-py)

Anyone has any idea??

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

c = [ 'g', 'r', 'r', 'g', 'g', 'r', 'r', 'r', 'g', 'r']
s = [ 10, 20, 10, 40, 60, 90, 90, 50, 60, 40]
x = [ 2.4, 3.0, 3.5, 3.5, 3.5, 3.5, 3.5, 2.4, 3.5, 3.5]
y = [24.0, 26.0, 20.0, 19.0, 19.0, 21.0, 20.0, 23.0, 20.0, 20.0]

fig, ax = plt.subplots()

scatter = plt.scatter(x, y, s=s, c=c, alpha=0.5)

# produce a legend with the unique colors from the scatter
handles, lables = scatter.legend_elements()
legend1 = ax.legend(handles, labels, loc="lower left", title="Colors")
ax.add_artist(legend1)

# produce a legend with a cross section of sizes from the scatter
handles, labels = scatter.legend_elements(prop="sizes", alpha=0.5)
legend2 = ax.legend(handles, labels, loc="upper right", ncol=2, title="Sizes")

plt.show()
</code>```

Plot output:

答:
It seems that legend_elements() is only meant to be used when c= is passed a numeric array to be mapped against a colormap.
You can test by replacing c=c by c=s in your code, and you will get the desired output.

Personally, I would have expected your code to work, and maybe it is worth bringing it up either as a bug or a feature request at matplotlib's github. EDIT: actually, there is already a discussion about this very issue on the issue tracker

One way to circumvent this limitation is to replace your array of colors names with a numeric array and creating a custom colormap that maps each value in your array to the desired color:

```<code>#c = [ 'g', 'r', 'r', 'g', 'g', 'r', 'r', 'r', 'g', 'r']
c = [0, 1, 1, 0, 0, 1, 1, 1, 0, 1]
cmap = matplotlib.colors.ListedColormap(['g','r'])
s = [ 10, 20, 10, 40, 60, 90, 90, 50, 60, 40]
x = [ 2.4, 3.0, 3.5, 3.5, 3.5, 3.5, 3.5, 2.4, 3.5, 3.5]
y = [24.0, 26.0, 20.0, 19.0, 19.0, 21.0, 20.0, 23.0, 20.0, 20.0]

fig, ax = plt.subplots()

scatter = plt.scatter(x, y, s=s, c=c, alpha=0.5, cmap=cmap)

# produce a legend with the unique colors from the scatter
handles, labels = scatter.legend_elements()
legend1 = ax.legend(handles, labels, loc="lower left", title="Colors")
ax.add_artist(legend1)

# produce a legend with a cross section of sizes from the scatter
handles, labels = scatter.legend_elements(prop="sizes", alpha=0.5)
legend2 = ax.legend(handles, labels, loc="upper right", ncol=2, title="Sizes")

plt.show()
</code>```

Body:
I have the following snipped of code (values for c, s, x, y are mockups, but the real lists follow the same format, just much bigger. Only two colors are used - red and green though. All lists are of the same size)

The issue is that the color legend fails to materialize. I am completely at loss as to why. Code snippets for legend generation is basically a cut-n-paste from docs, i.e. (https://matplotlib.org/3.1.1/gallery/lines_bars_and_markers/scatter_with_legend.html#sphx-glr-gallery-lines-bars-and-markers-scatter-with-legend-py)

Anyone has any idea??

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline

c = [ 'g', 'r', 'r', 'g', 'g', 'r', 'r', 'r', 'g', 'r']
s = [ 10, 20, 10, 40, 60, 90, 90, 50, 60, 40]
x = [ 2.4, 3.0, 3.5, 3.5, 3.5, 3.5, 3.5, 2.4, 3.5, 3.5]
y = [24.0, 26.0, 20.0, 19.0, 19.0, 21.0, 20.0, 23.0, 20.0, 20.0]

fig, ax = plt.subplots()

scatter = plt.scatter(x, y, s=s, c=c, alpha=0.5)

# produce a legend with the unique colors from the scatter
handles, lables = scatter.legend_elements()
legend1 = ax.legend(handles, labels, loc="lower left", title="Colors")
ax.add_artist(legend1)

# produce a legend with a cross section of sizes from the scatter
handles, labels = scatter.legend_elements(prop="sizes", alpha=0.5)
legend2 = ax.legend(handles, labels, loc="upper right", ncol=2, title="Sizes")

plt.show()

Plot output:

Body:
It seems that legend_elements() is only meant to be used when c= is passed a numeric array to be mapped against a colormap.
You can test by replacing c=c by c=s in your code, and you will get the desired output.

Personally, I would have expected your code to work, and maybe it is worth bringing it up either as a bug or a feature request at matplotlib's github. EDIT: actually, there is already a discussion about this very issue on the issue tracker

One way to circumvent this limitation is to replace your array of colors names with a numeric array and creating a custom colormap that maps each value in your array to the desired color:

#c = [ 'g', 'r', 'r', 'g', 'g', 'r', 'r', 'r', 'g', 'r']
c = [0, 1, 1, 0, 0, 1, 1, 1, 0, 1]
cmap = matplotlib.colors.ListedColormap(['g','r'])
s = [ 10, 20, 10, 40, 60, 90, 90, 50, 60, 40]
x = [ 2.4, 3.0, 3.5, 3.5, 3.5, 3.5, 3.5, 2.4, 3.5, 3.5]
y = [24.0, 26.0, 20.0, 19.0, 19.0, 21.0, 20.0, 23.0, 20.0, 20.0]

fig, ax = plt.subplots()

scatter = plt.scatter(x, y, s=s, c=c, alpha=0.5, cmap=cmap)

# produce a legend with the unique colors from the scatter
handles, labels = scatter.legend_elements()
legend1 = ax.legend(handles, labels, loc="lower left", title="Colors")
ax.add_artist(legend1)

# produce a legend with a cross section of sizes from the scatter
handles, labels = scatter.legend_elements(prop="sizes", alpha=0.5)
legend2 = ax.legend(handles, labels, loc="upper right", ncol=2, title="Sizes")

plt.show()


问:
is there any risk using std::addressof(std::cout) instead of &std::cout?
I am using std::cout for logging and sonarqube reports error when "Don't take the address of 'cout', call it from a lambda instead".

```<code>std::ostream *streamp;
streamp = &std::cout;
</code>```

When I use the below code there is no error observed in sonarqube. Is using std::addressof on std::cout function safe?

```<code>std::ostream *streamp;
streamp = std::addressof(std::cout);
</code>```

答:
Yes, using addressof on std::cout is safe. But since using & on std::cout is equally safe, the only reason to do it is to quiet a tool that clearly is giving you a false-positive (that it, it doesn't realize what addressof is doing).

It would be better to use & and employ whatever mechanisms exist in the tool to turn off false-positives.

Body:
I am using std::cout for logging and sonarqube reports error when "Don't take the address of 'cout', call it from a lambda instead".

std::ostream *streamp;
streamp = &std::cout;

When I use the below code there is no error observed in sonarqube. Is using std::addressof on std::cout function safe?

std::ostream *streamp;
streamp = std::addressof(std::cout);


问:
Javascript, I'm not being able to set focus to html form element
I know that I had to search on google, youtube and stackoverflow before I ask my question on stackoverflow.

But I swear I watched many videos on youtube, And I searched for many ways on google and stackoverflow! to solve my problem.
,

And now i'm stuck with this

```<code><input id="input-sign-in-id" class="uqid-id-input touch-feedback textfield-validate theme-textfield hokkai-text-input insert-dir three-point-leader" dir="auto" placeholder="Email Address" maxlength="64" type="email">
</code>```

I can set any value via this code, And it works.

```<code>var t2 = document.getElementById("input-sign-in-id");
t2.value = "LuxuryUAE2@hotmail.com";
</code>```

But the problem is I can't set focus to the input, I tried this code, And it doesn't work.

```<code>var t2 = document.getElementById("input-sign-in-id");
t2.focus();
t2.click();
t2.select();
</code>```

答:
function setFocus(){
    document.getElementById("input-sign-in-id").focus();
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input id="input-sign-in-id"></code>```

You can use javascript for focusing:

```<code><input id="input-sign-in-id">
</code>```

Your script for focus would be

```<code><script>
function setFocus(){
    document.getElementById("input-sign-in-id").focus();
}
</script>
</code>```

Body:
I know that I had to search on google, youtube and stackoverflow before I ask my question on stackoverflow.

But I swear I watched many videos on youtube, And I searched for many ways on google and stackoverflow! to solve my problem.
,

And now i'm stuck with this

<input id="input-sign-in-id" class="uqid-id-input touch-feedback textfield-validate theme-textfield hokkai-text-input insert-dir three-point-leader" dir="auto" placeholder="Email Address" maxlength="64" type="email">

I can set any value via this code, And it works.

var t2 = document.getElementById("input-sign-in-id");
t2.value = "LuxuryUAE2@hotmail.com";

But the problem is I can't set focus to the input, I tried this code, And it doesn't work.

var t2 = document.getElementById("input-sign-in-id");
t2.focus();
t2.click();
t2.select();

Body:
function setFocus(){
    document.getElementById("input-sign-in-id").focus();
}

<input id="input-sign-in-id">

You can use javascript for focusing:

<input id="input-sign-in-id">

Your script for focus would be

<script>
function setFocus(){
    document.getElementById("input-sign-in-id").focus();
}
</script>


问:
How can I attach a ref to a component that i am copying using React.cloneElement
hey all I want to pass in a ref into my component this way I can access the variables on said compenent like state. only issue is i can't seem to get it to work. It needs to be able to work for both classes and functional

what I am receiving back from the console.log is null every time

  const testRef = createRef();
  console.log(testRef)
  const elementToCopy = singleScreenState.screen.peek().element;
  const Element = React.cloneElement(elementToCopy as ReactElement, { ...elementToCopy?.props, forwardRef: testRef })```

答:
Refs to a React Element are never populated until the Element in question is mounted. So, the issue was that you were logging too early.

I have an example below running in a function component to demonstrate creating the refs and logging them once the element in question is mounted using useEffect.

The other issue you might have is that based on the code I see, you might be creating the ref in the render function of a class component, which wouldn't work well because you wouldn't have access to the ref variable once it's actually rendered. Typically, you keep ref variable as an instance property of the class so you can access it when you need it.

For working with function components, you need to use forwardRef on the function component as part of it's definition. The forwarded ref can go to the useImperativeHandle hook, or to another element.

A little more info in React's Documentation on Accessing Refs:

When a ref is passed to an element in render, a reference to the node
  becomes accessible at the current attribute of the ref.

const node = this.myRef.current;

The value of the ref differs depending on the type of the node:

When the ref attribute is used on an HTML element, the ref created in the constructor with React.createRef() receives the underlying DOM
  element as its current property.

When the ref attribute is used on a custom class component, the ref object receives the mounted instance of the component as its current.

You may not use the ref attribute on function components because they don’t have instances.

That last point is the key to note here: React.ForwardRef allows you to give the function components the ability to decide what a ref should do because otherwise the ref would be meaningless anyway.

In general in class components, if you want to pass a ref through it, you generally have to pass it down with a separate prop name. One of the ways shown here: How to use React.forwardRef in a class based component?

const { useRef, useEffect, useImperativeHandle } = React;

const TestFunction = React.forwardRef((props, ref) => {
  useImperativeHandle(ref, () => ({
    shout: () => console.log("I'm Yelling over here!")
  }));
  return
TestFunction
;
});

class TestComponent extends React.Component {
  testFunct = () => {
    console.log("testFunct works!");
  };
  render() {
    return
TestComponent
;
  }
}
function App() {
  const elementRef = useRef();
  const element =
Test
;
  const clonedElement = React.cloneElement(element, { ref: elementRef });
  const classRef = useRef();
  const classElement = <TestComponent />;
  const clonedClass = React.cloneElement(classElement, { ref: classRef });
  const functionRef = useRef();
  const functionElement = <TestFunction />;
  const clonedFunction = React.cloneElement(functionElement, {
    ref: functionRef
  });

  useEffect(() => {
    console.log('reference to an element',elementRef.current);
    // This produces weird output in the stack overflow console.
    // console.log(classRef.current);
    console.log('function from a reference to a class component', classRef.current.testFunct);
    classRef.current.testFunct();
    console.log('reference to a function component',functionRef.current);
    functionRef.current.shout();
  });
  return (

      {clonedElement}
      {clonedClass}
      {clonedFunction}

  );
}
const rootElement = document.getElementById("root");
ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  rootElement
);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.1/umd/react-dom.production.min.js"></script>

<div id="root" /></code>```

Body:
Refs to a React Element are never populated until the Element in question is mounted. So, the issue was that you were logging too early.

I have an example below running in a function component to demonstrate creating the refs and logging them once the element in question is mounted using useEffect.

The other issue you might have is that based on the code I see, you might be creating the ref in the render function of a class component, which wouldn't work well because you wouldn't have access to the ref variable once it's actually rendered. Typically, you keep ref variable as an instance property of the class so you can access it when you need it.

For working with function components, you need to use forwardRef on the function component as part of it's definition. The forwarded ref can go to the useImperativeHandle hook, or to another element.

A little more info in React's Documentation on Accessing Refs:

When a ref is passed to an element in render, a reference to the node
  becomes accessible at the current attribute of the ref.

const node = this.myRef.current;

The value of the ref differs depending on the type of the node:

When the ref attribute is used on an HTML element, the ref created in the constructor with React.createRef() receives the underlying DOM
  element as its current property.

When the ref attribute is used on a custom class component, the ref object receives the mounted instance of the component as its current.

You may not use the ref attribute on function components because they don’t have instances.

That last point is the key to note here: React.ForwardRef allows you to give the function components the ability to decide what a ref should do because otherwise the ref would be meaningless anyway.

In general in class components, if you want to pass a ref through it, you generally have to pass it down with a separate prop name. One of the ways shown here: How to use React.forwardRef in a class based component?

const { useRef, useEffect, useImperativeHandle } = React;

const TestFunction = React.forwardRef((props, ref) => {
  useImperativeHandle(ref, () => ({
    shout: () => console.log("I'm Yelling over here!")
  }));
  return <div>TestFunction</div>;
});

class TestComponent extends React.Component {
  testFunct = () => {
    console.log("testFunct works!");
  };
  render() {
    return <div>TestComponent</div>;
  }
}
function App() {
  const elementRef = useRef();
  const element = <div>Test</div>;
  const clonedElement = React.cloneElement(element, { ref: elementRef });
  const classRef = useRef();
  const classElement = <TestComponent />;
  const clonedClass = React.cloneElement(classElement, { ref: classRef });
  const functionRef = useRef();
  const functionElement = <TestFunction />;
  const clonedFunction = React.cloneElement(functionElement, {
    ref: functionRef
  });

  useEffect(() => {
    console.log('reference to an element',elementRef.current);
    // This produces weird output in the stack overflow console.
    // console.log(classRef.current);
    console.log('function from a reference to a class component', classRef.current.testFunct);
    classRef.current.testFunct();
    console.log('reference to a function component',functionRef.current);
    functionRef.current.shout();
  });
  return (
    <div className="App">
      {clonedElement}
      {clonedClass}
      {clonedFunction}
    </div>
  );
}
const rootElement = document.getElementById("root");
ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  rootElement
);

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.1/umd/react-dom.production.min.js"></script>

<div id="root" />


问:
How to run an async task for every x mins in android?
how to run the async task at specific time? (I want to run it every 2 mins)

I tried using  post delayed but it's not working?

```<code>    tvData.postDelayed(new Runnable(){

    @Override
    public void run() {
        readWebpage();

    }}, 100);
</code>```

In the above code readwebpage is function which calls the async task for me..

Right now below is the method which I am using

```<code>   public void onCreate(Bundle savedInstanceState) {

         readwebapage();

   }

   public void readWebpage() {
    DownloadWebPageTask task = new DownloadWebPageTask();
    task.execute("http://www.google.com");

   }

   private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
    @Override
    protected String doInBackground(String... urls) {
        String response1 = "";
        response1=read();
                   //read is my another function which does the real work
        response1=read();
        super.onPostExecute(response1);
        return response1;
    }

      protected void onPostExecute(String result) {

         try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            TextView tvData = (TextView) findViewById(R.id.TextView01);
            tvData.setText(result);

        DownloadWebPageTask task = new DownloadWebPageTask();
        task.execute(new String[] { "http://www.google.com" });

    }

    }
</code>```

This is what I  my code is and it works perfectly fine but the big problem I drains my battery?

答:
You can use handler if you want to initiate something every X seconds. Handler is good because you don't need extra thread to keep tracking when firing the event. Here is a short snippet:

```<code>private final static int INTERVAL = 1000 * 60 * 2; //2 minutes
Handler mHandler = new Handler();

Runnable mHandlerTask = new Runnable()
{
     @Override
     public void run() {
          doSomething();
          mHandler.postDelayed(mHandlerTask, INTERVAL);
     }
};

void startRepeatingTask()
{
    mHandlerTask.run();
}

void stopRepeatingTask()
{
    mHandler.removeCallbacks(mHandlerTask);
}
</code>```

Note that doSomething should not take long (something like update position of audio playback in UI). If it can potentially take some time (like downloading or uploading to the web), then you should use ScheduledExecutorService's scheduleWithFixedDelay function instead.

Body:
how to run the async task at specific time? (I want to run it every 2 mins)

I tried using  post delayed but it's not working?

    tvData.postDelayed(new Runnable(){

    @Override
    public void run() {
        readWebpage();

    }}, 100);

In the above code readwebpage is function which calls the async task for me..

Right now below is the method which I am using

   public void onCreate(Bundle savedInstanceState) {

         readwebapage();

   }

   public void readWebpage() {
    DownloadWebPageTask task = new DownloadWebPageTask();
    task.execute("http://www.google.com");

   }

   private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
    @Override
    protected String doInBackground(String... urls) {
        String response1 = "";
        response1=read();
                   //read is my another function which does the real work
        response1=read();
        super.onPostExecute(response1);
        return response1;
    }

      protected void onPostExecute(String result) {

         try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            TextView tvData = (TextView) findViewById(R.id.TextView01);
            tvData.setText(result);

        DownloadWebPageTask task = new DownloadWebPageTask();
        task.execute(new String[] { "http://www.google.com" });

    }

    }

This is what I  my code is and it works perfectly fine but the big problem I drains my battery?

Body:
You can use handler if you want to initiate something every X seconds. Handler is good because you don't need extra thread to keep tracking when firing the event. Here is a short snippet:

private final static int INTERVAL = 1000 * 60 * 2; //2 minutes
Handler mHandler = new Handler();

Runnable mHandlerTask = new Runnable()
{
     @Override
     public void run() {
          doSomething();
          mHandler.postDelayed(mHandlerTask, INTERVAL);
     }
};

void startRepeatingTask()
{
    mHandlerTask.run();
}

void stopRepeatingTask()
{
    mHandler.removeCallbacks(mHandlerTask);
}

Note that doSomething should not take long (something like update position of audio playback in UI). If it can potentially take some time (like downloading or uploading to the web), then you should use ScheduledExecutorService's scheduleWithFixedDelay function instead.


问:
R calculation based on the previous results step by step by group
enter image description hereI want to find out how many days are without supplies and how many days are with supplies in each period by group, I'm thinking to create a new variable of "Days". At first, I calculated the time interval between two dates next to each other "DateDiff", then I used the time interval "DateDiff" to minus the previous SupplyDays lag(SupplyDays) to get "DaysLeft", if the DaysLeft is >0, it means there is a supply shortage, and if the DaysLeft is <0, it means there is supply left, can be used in the following days. But it's only compared with the previous line, so more work needs to be done. It sounds complicated. But my purpose is to find out how many days are without supplies and how many days are with supplies in each period. The thing is that only previous left supplies can be used in the future, but the future left supplies can not be used in the past, so each step of the calculation is based on the previous result, and cumsum() dose not apply to my case. The first value of "Days" of each group is equal to "DaysLeft". Then if the previous "Days" is <0, the present "Days" should be the present "DaysLeft" plus the previous "Days" to cancel out supplies left from the past, if the previous 'Days" is >0, the present "Days" is equal to the present "DaysLeft".

df <- data.frame(Group = c(3, 3, 1, 2, 1, 2, 1, 3, 1, 1),
                 Date = c(20190102, 20190207, 20190309, 20190417, 20190507, 20190610, 20190707, 20190808, 20190907, 20191018),
                 SupplyDays = c(80,9,40,7,35,7,2,60,1,5))
```

<p>I tried to use <code>mutate()</code>, but the mutate function can not tell the new variable itself, so it cannot check >0 or <0.
Then I created a loop, but the loop sometimes work, sometimes does not. And I don't know how to group_by in the loop.</p>

<pre class="lang-r prettyprint-override"><code>df$Days[1] <- df$DaysLeft[1]
for (i in 2:length(df$DaysLeft)){
    if (df$Days[i-1]>=0){
        df$Days[i]<-df$DaysLeft[i]
    } else {
   df$Days[i]<-(df$DaysLeft[i]+df$Days[i-1])
  }
}
</code>```

If you have any thoughts, I would be super appreciated! I'm new to R, and I've been working on this for days. Thank you!

答:
Would this work for you:

```<code>library(dplyr)
library(tidyr)

df <- df %>%
  arrange(Group) %>% # for convenience
  mutate(Date = as.Date(as.character(Date), "%Y%m%d")) %>% # coerce dates to Date format
  group_by(Group) %>%
  mutate(DateDiff = Date - lag(Date, 1)) %>% # calculate time difference with previous row
  mutate(DateDiff = replace_na(DateDiff, 0)) %>% # replace NA with 0
  mutate(DaysLeft = DateDiff - lag(SupplyDays,1)) %>%
  mutate(DaysLeft = replace_na(DaysLeft, 0)) %>%  # replace NA with 0
  mutate(Days = ifelse(lag(DaysLeft, 1) < 0, DaysLeft + lag(DaysLeft, 1), DaysLeft)) %>%
  mutate(Days = replace_na(Days, 0)) # replace NA with 0
</code>```

With this output:

```<code>> df
# A tibble: 10 x 6
# Groups:   Group [3]
   Group Date       SupplyDays DateDiff DaysLeft  Days
   <dbl> <date>          <dbl> <drtn>   <drtn>   <dbl>
 1     1 2019-03-09         40   0 days   0 days     0
 2     1 2019-05-07         35  59 days  19 days    19
 3     1 2019-07-07          2  61 days  26 days    26
 4     1 2019-09-07          1  62 days  60 days    60
 5     1 2019-10-18          5  41 days  40 days    40
 6     2 2019-04-17          7   0 days   0 days     0
 7     2 2019-06-10          7  54 days  47 days    47
 8     3 2019-01-02         80   0 days   0 days     0
 9     3 2019-02-07          9  36 days -44 days   -44
10     3 2019-08-08         60 182 days 173 days   129
</code>```

UPDATE

I was thinking about this over the weekend and it may help to approach this problem differently. We are dealing with an inventory/consumption problem so here's a very simple approach.
We need to have proper definitions for this to work:

Incoming: material arriving at the start of the period. I take that your SupplyDays is exactly this.

Consumption: during the period we consume one day of inventory per day

We would need to calculate the inventory at the end of each period. So I created a slightly different data frame with columns Date, Incoming and Inventory. The assumption is that the first row is period: 0 with only an existing inventory. The Inventory then becomes the sum of what I already have (data$Inventory [i - 1]), what is incoming in this period (data$Incoming[i]) and minus what I am consuming (as.numeric(data$DateDiff[i])).

```<code>data <- tibble(Date = c(20190309, 20190507, 20190707, 20190907, 20191018, 20191210, 20200120),
             Incoming = c(0, 35, 27, 108, 5, 12, 30),
             Inventory = c(40, 0, 0, 0, 0, 0, 0))
</code>```

This tibble requires a bit of work:

```<code>data <- data %>%
  mutate(Date = as.Date(as.character(Date), "%Y%m%d")) %>%
  mutate(DateDiff = Date - lag(Date, 1))  %>%# calculate time difference with previous row
  mutate(DateDiff = replace_na(DateDiff, 0))
</code>```

And because I need to treat the first row differently than the other rows I need to use a for-loop:

```<code>for (i in seq_len(nrow(data))) {
  if (i == 1) {
    data$Inventory [i] <- data$Inventory [i] + data$Incoming[i]
  } else {
    data$Inventory [i] <- data$Inventory [i - 1] + data$Incoming[i] - as.numeric(data$DateDiff[i])
  }
}
</code>```

With this output:

```<code>> data
# A tibble: 7 x 4
  Date       Incoming Inventory DateDiff
  <date>        <dbl>     <dbl> <drtn>
1 2019-03-09        0        40  0 days
2 2019-05-07       35        16 59 days
3 2019-07-07       27       -18 61 days
4 2019-09-07      108        28 62 days
5 2019-10-18        5        -8 41 days
6 2019-12-10       12       -49 53 days
7 2020-01-20       30       -60 41 days
</code>```

This can easily be expanded to include groups. Is this helpful?

Body:
enter image description hereI want to find out how many days are without supplies and how many days are with supplies in each period by group, I'm thinking to create a new variable of "Days". At first, I calculated the time interval between two dates next to each other "DateDiff", then I used the time interval "DateDiff" to minus the previous SupplyDays lag(SupplyDays) to get "DaysLeft", if the DaysLeft is >0, it means there is a supply shortage, and if the DaysLeft is <0, it means there is supply left, can be used in the following days. But it's only compared with the previous line, so more work needs to be done. It sounds complicated. But my purpose is to find out how many days are without supplies and how many days are with supplies in each period. The thing is that only previous left supplies can be used in the future, but the future left supplies can not be used in the past, so each step of the calculation is based on the previous result, and cumsum() dose not apply to my case. The first value of "Days" of each group is equal to "DaysLeft". Then if the previous "Days" is <0, the present "Days" should be the present "DaysLeft" plus the previous "Days" to cancel out supplies left from the past, if the previous 'Days" is >0, the present "Days" is equal to the present "DaysLeft".

df <- data.frame(Group = c(3, 3, 1, 2, 1, 2, 1, 3, 1, 1),
                 Date = c(20190102, 20190207, 20190309, 20190417, 20190507, 20190610, 20190707, 20190808, 20190907, 20191018),
                 SupplyDays = c(80,9,40,7,35,7,2,60,1,5))

I tried to use mutate(), but the mutate function can not tell the new variable itself, so it cannot check >0 or <0.
Then I created a loop, but the loop sometimes work, sometimes does not. And I don't know how to group_by in the loop.

df$Days[1] <- df$DaysLeft[1]
for (i in 2:length(df$DaysLeft)){
    if (df$Days[i-1]>=0){
        df$Days[i]<-df$DaysLeft[i]
    } else {
   df$Days[i]<-(df$DaysLeft[i]+df$Days[i-1])
  }
}

If you have any thoughts, I would be super appreciated! I'm new to R, and I've been working on this for days. Thank you!

Body:
Would this work for you:

library(dplyr)
library(tidyr)

df <- df %>%
  arrange(Group) %>% # for convenience
  mutate(Date = as.Date(as.character(Date), "%Y%m%d")) %>% # coerce dates to Date format
  group_by(Group) %>%
  mutate(DateDiff = Date - lag(Date, 1)) %>% # calculate time difference with previous row
  mutate(DateDiff = replace_na(DateDiff, 0)) %>% # replace NA with 0
  mutate(DaysLeft = DateDiff - lag(SupplyDays,1)) %>%
  mutate(DaysLeft = replace_na(DaysLeft, 0)) %>%  # replace NA with 0
  mutate(Days = ifelse(lag(DaysLeft, 1) < 0, DaysLeft + lag(DaysLeft, 1), DaysLeft)) %>%
  mutate(Days = replace_na(Days, 0)) # replace NA with 0

With this output:

> df
# A tibble: 10 x 6
# Groups:   Group [3]
   Group Date       SupplyDays DateDiff DaysLeft  Days
   <dbl> <date>          <dbl> <drtn>   <drtn>   <dbl>
 1     1 2019-03-09         40   0 days   0 days     0
 2     1 2019-05-07         35  59 days  19 days    19
 3     1 2019-07-07          2  61 days  26 days    26
 4     1 2019-09-07          1  62 days  60 days    60
 5     1 2019-10-18          5  41 days  40 days    40
 6     2 2019-04-17          7   0 days   0 days     0
 7     2 2019-06-10          7  54 days  47 days    47
 8     3 2019-01-02         80   0 days   0 days     0
 9     3 2019-02-07          9  36 days -44 days   -44
10     3 2019-08-08         60 182 days 173 days   129

UPDATE

I was thinking about this over the weekend and it may help to approach this problem differently. We are dealing with an inventory/consumption problem so here's a very simple approach.
We need to have proper definitions for this to work:

Incoming: material arriving at the start of the period. I take that your SupplyDays is exactly this.

Consumption: during the period we consume one day of inventory per day

We would need to calculate the inventory at the end of each period. So I created a slightly different data frame with columns Date, Incoming and Inventory. The assumption is that the first row is period: 0 with only an existing inventory. The Inventory then becomes the sum of what I already have (data$Inventory [i - 1]), what is incoming in this period (data$Incoming[i]) and minus what I am consuming (as.numeric(data$DateDiff[i])).

data <- tibble(Date = c(20190309, 20190507, 20190707, 20190907, 20191018, 20191210, 20200120),
             Incoming = c(0, 35, 27, 108, 5, 12, 30),
             Inventory = c(40, 0, 0, 0, 0, 0, 0))

This tibble requires a bit of work:

data <- data %>%
  mutate(Date = as.Date(as.character(Date), "%Y%m%d")) %>%
  mutate(DateDiff = Date - lag(Date, 1))  %>%# calculate time difference with previous row
  mutate(DateDiff = replace_na(DateDiff, 0))

And because I need to treat the first row differently than the other rows I need to use a for-loop:

for (i in seq_len(nrow(data))) {
  if (i == 1) {
    data$Inventory [i] <- data$Inventory [i] + data$Incoming[i]
  } else {
    data$Inventory [i] <- data$Inventory [i - 1] + data$Incoming[i] - as.numeric(data$DateDiff[i])
  }
}

With this output:

> data
# A tibble: 7 x 4
  Date       Incoming Inventory DateDiff
  <date>        <dbl>     <dbl> <drtn>
1 2019-03-09        0        40  0 days
2 2019-05-07       35        16 59 days
3 2019-07-07       27       -18 61 days
4 2019-09-07      108        28 62 days
5 2019-10-18        5        -8 41 days
6 2019-12-10       12       -49 53 days
7 2020-01-20       30       -60 41 days

This can easily be expanded to include groups. Is this helpful?


问:
Returning all data from django backend
I have this problem, that my backend does not return all data. It returns the database table rows, that the token of the logged user matches the user's id of the model.

Here is the Blog model

 class Blog(models.Model):
    title = models.CharField(max_length=100)
    content = models.CharField(max_length=500)
    created_at = models.DateTimeField(auto_now_add=True)
    userID = models.ForeignKey(User, on_delete=models.CASCADE, related_name='posts', null=True)
```

<p>And here is the class that returns the data</p>

<pre class="lang-py prettyprint-override"><code>class BlogViewSet(viewsets.ModelViewSet):
    permission_classes = [
        permissions.IsAuthenticated
    ]

    serializer_class = BlogSerializer

    def get_queryset(self):
        return self.request.user.posts.all()
</code>```

How can I return every row from the db regardless of the user who posted it?

答:
Well you instruct it to return the .posts.all() of the logged in user. If you want to return all rows, you can just return:

```<code>from app.models import <b>Blog</b>

class BlogViewSet(viewsets.ModelViewSet):
    permission_classes = [
        permissions.IsAuthenticated
    ]

    serializer_class = BlogSerializer

    def get_queryset(self):
        return <b>Blog.objects.all()</b></code>```

You can also remove the IsAuthenticated permission if users do not need to authenticate to retrieve the list of Blogs.

Title: Returning all data from django backend

Body:
I have this problem, that my backend does not return all data. It returns the database table rows, that the token of the logged user matches the user's id of the model.

Here is the Blog model

 class Blog(models.Model):
    title = models.CharField(max_length=100)
    content = models.CharField(max_length=500)
    created_at = models.DateTimeField(auto_now_add=True)
    userID = models.ForeignKey(User, on_delete=models.CASCADE, related_name='posts', null=True)

And here is the class that returns the data

class BlogViewSet(viewsets.ModelViewSet):
    permission_classes = [
        permissions.IsAuthenticated
    ]

    serializer_class = BlogSerializer

    def get_queryset(self):
        return self.request.user.posts.all()

How can I return every row from the db regardless of the user who posted it?

Body:
Well you instruct it to return the .posts.all() of the logged in user. If you want to return all rows, you can just return:

from app.models import Blog

class BlogViewSet(viewsets.ModelViewSet):
    permission_classes = [
        permissions.IsAuthenticated
    ]

    serializer_class = BlogSerializer

    def get_queryset(self):
        return Blog.objects.all()

You can also remove the IsAuthenticated permission if users do not need to authenticate to retrieve the list of Blogs.


问:
Youtube-dl - downloading several youtube videos at once in one command
I know how to download 1 youtube video command, 1 youtube playlist command but I don't know how to download several youtube videos at once in one command. How can I do it?</p>

答:
You can write all urls in a text file (separated with a new line). As an example, let's write a text file called "urls" with this content:

```<code>https://www.youtube.com/watch?v=c7DpRIk4lKY
https://www.youtube.com/playlist?list=PLx_tr69QV8CDB-nn-pc5YZbDsdgjIQSII
https://www.youtube.com/watch?v=kh1sF-sbkbw
</code>```

Then in the shell write:

youtube-dl -a urls
```

<p>But, this is if you run this command in the same path as the urls file.
If you want to run it from another location just add the path behind the file name like:</p>

<pre class="lang-sh prettyprint-override"><code>youtube-dl -a path/to/file/urls
</code>```

Also, in this example I didn't include any file extension, but it can also have one like ".txt"

Body:
You can write all urls in a text file (separated with a new line). As an example, let's write a text file called "urls" with this content:

https://www.youtube.com/watch?v=c7DpRIk4lKY
https://www.youtube.com/playlist?list=PLx_tr69QV8CDB-nn-pc5YZbDsdgjIQSII
https://www.youtube.com/watch?v=kh1sF-sbkbw

Then in the shell write:

youtube-dl -a urls

But, this is if you run this command in the same path as the urls file.
If you want to run it from another location just add the path behind the file name like:

youtube-dl -a path/to/file/urls

Also, in this example I didn't include any file extension, but it can also have one like ".txt"


答:
Try using the following and see if it works : </p>

```<code>window.setTimeout(function () {
    document.getElementById('input-sign-in-id').focus();
}, 0);
</code>```

Title: Javascript, I'm not being able to set focus to html form element

Body:
Try using the following and see if it works :

window.setTimeout(function () {
    document.getElementById('input-sign-in-id').focus();
}, 0);


问:
How can I use Task Async Await to read files content from multiple directories recursive?
```<code>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Test
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            ProcessRead().Wait();
        }

        static async Task ProcessRead()
        {
            await Task.Run(() =>
            {
                IEnumerable<string> fileEntries = Directory.EnumerateFiles(@"Directory");
                int count = 0;
                foreach (string fname in fileEntries)
                {
                    try
                    {
                        count++;
                        string text = File.ReadAllText(fname);
                        Console.WriteLine(text);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                    }
                }

                Console.WriteLine(count);
            });
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }
    }
}
</code>```

This is working but only for the given directory in EnumerateFiles.
but I want to get all the files in all directories recursive.

For example if I put the directory of windows :

```<code>IEnumerable<string> fileEntries = Directory.EnumerateFiles(@"c:\windows");
</code>```

I want it to read the content of all the files in the directory windows and also all the sub directories in windows. So it will read all the files content in the given root directory and all it's sub directories recursive.

This is the code now :

```<code>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml.Schema;

namespace Test
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            ProcessRead().Wait();
        }

        static async Task ProcessRead()
        {
            await Task.Run(() =>
            {
                IEnumerable<string> fileEntries = Directory.EnumerateFiles(@"Directory","", SearchOption.AllDirectories);
                int count = 0;
                foreach (string fname in fileEntries)
                {
                    try
                    {
                        count++;
                        string text = File.ReadAllText(fname);
                        Console.WriteLine(text);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                    }
                }

                Console.WriteLine(count);
            });
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }
    }
}
</code>```

EnumerationOptions.RecurseSubdirectories not exist the not sure if it's because I'm using .net 4.7.2

What did I do wrong that EnumerationOptions.RecurseSubdirectories is not exist ?

答:
Use the overloaded method for Directory.EnumerateFiles:

```<code>public static System.Collections.Generic.IEnumerable<string> EnumerateFiles (string path, string searchPattern, System.IO.EnumerationOptions enumerationOptions);
</code>```

https://learn.microsoft.com/en-us/dotnet/api/system.io.directory.enumeratefiles?view=netcore-3.1

Specify your EnumerationOptions as EnumerationOptions.RecurseSubdirectories.

Body:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Test
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            ProcessRead().Wait();
        }

        static async Task ProcessRead()
        {
            await Task.Run(() =>
            {
                IEnumerable<string> fileEntries = Directory.EnumerateFiles(@"Directory");
                int count = 0;
                foreach (string fname in fileEntries)
                {
                    try
                    {
                        count++;
                        string text = File.ReadAllText(fname);
                        Console.WriteLine(text);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                    }
                }

                Console.WriteLine(count);
            });
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }
    }
}

This is working but only for the given directory in EnumerateFiles.
but I want to get all the files in all directories recursive.

For example if I put the directory of windows :

IEnumerable<string> fileEntries = Directory.EnumerateFiles(@"c:\windows");

I want it to read the content of all the files in the directory windows and also all the sub directories in windows. So it will read all the files content in the given root directory and all it's sub directories recursive.

This is the code now :

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml.Schema;

namespace Test
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            ProcessRead().Wait();
        }

        static async Task ProcessRead()
        {
            await Task.Run(() =>
            {
                IEnumerable<string> fileEntries = Directory.EnumerateFiles(@"Directory","", SearchOption.AllDirectories);
                int count = 0;
                foreach (string fname in fileEntries)
                {
                    try
                    {
                        count++;
                        string text = File.ReadAllText(fname);
                        Console.WriteLine(text);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                    }
                }

                Console.WriteLine(count);
            });
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }
    }
}

EnumerationOptions.RecurseSubdirectories not exist the not sure if it's because I'm using .net 4.7.2

What did I do wrong that EnumerationOptions.RecurseSubdirectories is not exist ?

Body:
Use the overloaded method for Directory.EnumerateFiles:

public static System.Collections.Generic.IEnumerable<string> EnumerateFiles (string path, string searchPattern, System.IO.EnumerationOptions enumerationOptions);

https://learn.microsoft.com/en-us/dotnet/api/system.io.directory.enumeratefiles?view=netcore-3.1

Specify your EnumerationOptions as EnumerationOptions.RecurseSubdirectories.