问:
SImple code runs correctly in DevC++ but not Visual Studio Code
Code runs fine DevC++ but not Visual Studio Code

Was doing a homework question. Simple code adding two integers. Code looked fine but running it kept giving me the wrong result. After losing my mind I tried to run it in DevC++ to which it gave me the result I expected.

I'm very very new to coding. Visual Studio Code is trying to tell me something in the output window but I don't know what it's is trying to tell me.

```<code>#include <stdio.h>
int main()
{
    double x,y,z;

    printf("Enter first number:" );

    scanf("%i", &x);

    printf("Enter second number:" );

    scanf("%i", &y);

    printf("the first number is: %d \n",x);
    printf("the second number is: %d \n ",y);

    z= x+y;

    printf("Output 1: The result is %d . \n",z);
    printf("Output 2: The sum of %d and %d is %d . ",x,y,z);

    return 0;
}

</code>```

-------------------VS Code output Window-------------------------

```<code>hwidk.cpp:19:8: warning: format '%d' expects argument of type 'int', but argument 2 has type 'double' [-Wformat=]
 printf("Output 1: The result is %d . \n",z);
        ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~

[hwidk.cpp 2019-05-27 21:35:01.608]
hwidk.cpp:20:8: warning: format '%d' expects argument of type 'int', but argument 2 has type 'double' [-Wformat=]
 printf("Output 2: The sum of %d and %d is %d . ",x,y,z);
        ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~
hwidk.cpp:20:8: warning: format '%d' expects argument of type 'int', but argument 3 has type 'double' [-Wformat=]

[hwidk.cpp 2019-05-27 21:35:01.608]
hwidk.cpp:20:8: warning: format '%d' expects argument of type 'int', but argument 4 has type 'double' [-Wformat=]
</code>```

--------------Visual Studio Runs the code as------------------------

```<code>
Enter first number:5
Enter second number:6
the first number is: 5
the second number is: 6
Output 1: The result is 7 .
Output 2: The sum of 5 and 0 is 6
</code>```

答:
The format strings you're using for your scanf and printf calls are wrong.  Since your variables are doubles, you should use %f.  %d is for integers.

Visual Studio performs some analysis of printf parameters when it can, and is warning you of the problem.  DevC++ apparently isn't doing this, so it doesn't generate the warnings.

The behavior is Undefined with either compiler, and you're unlucky enough that appears to work with DevC++.

Body:
Code runs fine DevC++ but not Visual Studio Code

Was doing a homework question. Simple code adding two integers. Code looked fine but running it kept giving me the wrong result. After losing my mind I tried to run it in DevC++ to which it gave me the result I expected.

I'm very very new to coding. Visual Studio Code is trying to tell me something in the output window but I don't know what it's is trying to tell me.

#include <stdio.h>
int main()
{
    double x,y,z;

    printf("Enter first number:" );

    scanf("%i", &x);

    printf("Enter second number:" );

    scanf("%i", &y);

    printf("the first number is: %d \n",x);
    printf("the second number is: %d \n ",y);

    z= x+y;

    printf("Output 1: The result is %d . \n",z);
    printf("Output 2: The sum of %d and %d is %d . ",x,y,z);

    return 0;
}

-------------------VS Code output Window-------------------------

hwidk.cpp:19:8: warning: format '%d' expects argument of type 'int', but argument 2 has type 'double' [-Wformat=]
 printf("Output 1: The result is %d . \n",z);
        ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~

[hwidk.cpp 2019-05-27 21:35:01.608]
hwidk.cpp:20:8: warning: format '%d' expects argument of type 'int', but argument 2 has type 'double' [-Wformat=]
 printf("Output 2: The sum of %d and %d is %d . ",x,y,z);
        ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~
hwidk.cpp:20:8: warning: format '%d' expects argument of type 'int', but argument 3 has type 'double' [-Wformat=]

[hwidk.cpp 2019-05-27 21:35:01.608]
hwidk.cpp:20:8: warning: format '%d' expects argument of type 'int', but argument 4 has type 'double' [-Wformat=]

--------------Visual Studio Runs the code as------------------------

Enter first number:5
Enter second number:6
the first number is: 5
the second number is: 6
Output 1: The result is 7 .
Output 2: The sum of 5 and 0 is 6


来源: stackexchange

问:
How to convert nested JSON data to CSV using python?
I have a file consisting of an array containing over 5000 objects. However, I am having trouble converting one particular part of my JSON file into the appropriate columns in CSV format.

Below is an example version of my data file:

```<code>{
  "Result": {
    "Example 1": {
      "Type1": [
        {
          "Owner": "Name1 Example",
          "Description": "Description1 Example",
          "Email": "example1_email@email.com",
          "Phone": "(123) 456-7890"
        }
      ]
    },
    "Example 2": {
      "Type1": [
        {
          "Owner": "Name2 Example",
          "Description": "Description2 Example",
          "Email": "example2_email@email.com",
          "Phone": "(111) 222-3333"
        }
      ]
    }
  }
}

</code>```

Here is my current code:

```<code>import csv
import json

json_file='example.json'
with open(json_file, 'r') as json_data:
    x = json.load(json_data)

f = csv.writer(open("example.csv", "w"))

f.writerow(["Address","Type","Owner","Description","Email","Phone"])

for key in x["Result"]:
    type = "Type1"
    f.writerow([key,
                type,
                x["Result"][key]["Type1"]["Owner"],
                x["Result"][key]["Type1"]["Description"],
                x["Result"][key]["Type1"]["Email"],
                x["Result"][key]["Type1"]["Phone"]])

</code>```

My problem is that I'm encountering this issue:

```<code>Traceback (most recent call last):
  File "./convert.py", line 18, in <module>
    x["Result"][key]["Type1"]["Owner"],
TypeError: list indices must be integers or slices, not str
</code>```

When I try to substitute the last array such as "Owner" to an integer value, I receive this error: IndexError: list index out of range.

When I strictly change the f.writerow function to

```<code>f.writerow([key,
                type,
                x["Result"][key]["Type1"]])
</code>```

I receive the results in a column, but it merges everything into one column, which makes sense. Picture of the output: https://imgur.com/a/JpDkaAT

I would like the results to be separated based on the label into individual columns instead of being merged into one. Could anyone assist?

Thank you!

答:
It's definately not the best example, but I'm to sleepy to optimize it.</p>

```<code>import csv

def json_to_csv(obj, res):
    for k, v in obj.items():
        if isinstance(v, dict):
            res.append(k)
            json_to_csv(v, res)
        elif isinstance(v, list):
            res.append(k)
            for el in v:
                json_to_csv(el, res)
        else:
            res.append(v)

obj = {
  "Result": {
    "Example 1": {
      "Type1": [
        {
          "Owner": "Name1 Example",
          "Description": "Description1 Example",
          "Email": "example1_email@email.com",
          "Phone": "(123) 456-7890"
        }
      ]
    },
    "Example 2": {
      "Type1": [
        {
          "Owner": "Name2 Example",
          "Description": "Description2 Example",
          "Email": "example2_email@email.com",
          "Phone": "(111) 222-3333"
        }
      ]
    }
  }
}

with open("out.csv", "w+") as f:
    writer = csv.writer(f)
    writer.writerow(["Address","Type","Owner","Description","Email","Phone"])
    for k, v in obj["Result"].items():
        row = [k]
        json_to_csv(v, row)
        writer.writerow(row)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a file consisting of an array containing over 5000 objects. However, I am having trouble converting one particular part of my JSON file into the appropriate columns in CSV format.

Below is an example version of my data file:

{
  "Result": {
    "Example 1": {
      "Type1": [
        {
          "Owner": "Name1 Example",
          "Description": "Description1 Example",
          "Email": "example1_email@email.com",
          "Phone": "(123) 456-7890"
        }
      ]
    },
    "Example 2": {
      "Type1": [
        {
          "Owner": "Name2 Example",
          "Description": "Description2 Example",
          "Email": "example2_email@email.com",
          "Phone": "(111) 222-3333"
        }
      ]
    }
  }
}

Here is my current code:

import csv
import json

json_file='example.json'
with open(json_file, 'r') as json_data:
    x = json.load(json_data)

f = csv.writer(open("example.csv", "w"))

f.writerow(["Address","Type","Owner","Description","Email","Phone"])

for key in x["Result"]:
    type = "Type1"
    f.writerow([key,
                type,
                x["Result"][key]["Type1"]["Owner"],
                x["Result"][key]["Type1"]["Description"],
                x["Result"][key]["Type1"]["Email"],
                x["Result"][key]["Type1"]["Phone"]])

My problem is that I'm encountering this issue:

Traceback (most recent call last):
  File "./convert.py", line 18, in <module>
    x["Result"][key]["Type1"]["Owner"],
TypeError: list indices must be integers or slices, not str

When I try to substitute the last array such as "Owner" to an integer value, I receive this error: IndexError: list index out of range.

When I strictly change the f.writerow function to

f.writerow([key,
                type,
                x["Result"][key]["Type1"]])

I receive the results in a column, but it merges everything into one column, which makes sense. Picture of the output: https://imgur.com/a/JpDkaAT

I would like the results to be separated based on the label into individual columns instead of being merged into one. Could anyone assist?

Thank you!

Body:
It's definately not the best example, but I'm to sleepy to optimize it.

import csv

def json_to_csv(obj, res):
    for k, v in obj.items():
        if isinstance(v, dict):
            res.append(k)
            json_to_csv(v, res)
        elif isinstance(v, list):
            res.append(k)
            for el in v:
                json_to_csv(el, res)
        else:
            res.append(v)

obj = {
  "Result": {
    "Example 1": {
      "Type1": [
        {
          "Owner": "Name1 Example",
          "Description": "Description1 Example",
          "Email": "example1_email@email.com",
          "Phone": "(123) 456-7890"
        }
      ]
    },
    "Example 2": {
      "Type1": [
        {
          "Owner": "Name2 Example",
          "Description": "Description2 Example",
          "Email": "example2_email@email.com",
          "Phone": "(111) 222-3333"
        }
      ]
    }
  }
}

with open("out.csv", "w+") as f:
    writer = csv.writer(f)
    writer.writerow(["Address","Type","Owner","Description","Email","Phone"])
    for k, v in obj["Result"].items():
        row = [k]
        json_to_csv(v, row)
        writer.writerow(row)


问:
Pyspark counter field, groupby and increment by 1
My dataframe is as follows:

```<code>cola, colb
1, 2
1, 3
2, 1
2, 5
</code>```

I want to add a column count:

```<code>cola, colb, count
1,     2,    1
1,     3,    2
2,     1,    1
2,     5,    2
</code>```

Need to groupby colA and set count to 1 for first record, then increment each successive row by 1.

I tried to use a window function but that applies the same count for all records in colA without the increment.

答:
You already figured out that a window function is the way to go. Maybe you haven't used the rank function.

import pyspark.sql.functions as F
from pyspark.sql import Window

l = [(1       , 2),
(1      , 3  ),
(1      , 2  ),
(2      , 1  ),
(2      , 5)]

columns = ['cola', 'colb']

df=spark.createDataFrame(l, columns)

w = Window.partitionBy('cola').orderBy('colb')

df = df.withColumn('count', F.rank().over(w))
df.show()
```

<p>Output:</p>

```+----+----+-----+
|cola|colb|count|
+----+----+-----+
|   1|   2|    1|
|   1|   2|    1|
|   1|   3|    3|
|   2|   1|    1|
|   2|   5|    2|
+----+----+-----+
```

In case you don't want gaps after equal rows, you should use the dense_rank function.

Body:
My dataframe is as follows:

cola, colb
1, 2
1, 3
2, 1
2, 5

I want to add a column count:

cola, colb, count
1,     2,    1
1,     3,    2
2,     1,    1
2,     5,    2

Need to groupby colA and set count to 1 for first record, then increment each successive row by 1.

I tried to use a window function but that applies the same count for all records in colA without the increment.

Body:
You already figured out that a window function is the way to go. Maybe you haven't used the rank function.

import pyspark.sql.functions as F
from pyspark.sql import Window

l = [(1       , 2),
(1      , 3  ),
(1      , 2  ),
(2      , 1  ),
(2      , 5)]

columns = ['cola', 'colb']

df=spark.createDataFrame(l, columns)

w = Window.partitionBy('cola').orderBy('colb')

df = df.withColumn('count', F.rank().over(w))
df.show()

Output:

+----+----+-----+
|cola|colb|count|
+----+----+-----+
|   1|   2|    1|
|   1|   2|    1|
|   1|   3|    3|
|   2|   1|    1|
|   2|   5|    2|
+----+----+-----+

In case you don't want gaps after equal rows, you should use the dense_rank function.


问:
Hailstone Java Program
I am working on The hailstone sequence program in which the user picks a positive integer. If number is even, it will be divided by two. If the number is odd, it'll be multiplied it by three and added by one. The program will continue until the number is equal to 1. The program will also tell the user the amount of steps it took to reach 1.

The goal is to be done recursively, my issue is that I am unable to declare each step to the user as the calculation happens to the number, for e.g "number is so I divide by 2 and it = "

This is my code so far, any suggestions or alternatives will help.

Thanks

import javax.swing*

```<code>{
   public class hailstone {
   static int Count;
   static int HailstoneNumbers(int Num)
   output += (Num + " " ) ;
   JOptionPane.showMessageDialog(null, output);

    if (Num == 1 && Count == 0) {
        return Count;

    }
    else if (Num == 1 && Count != 0) {
        //n-1
        Count++;
        return Count;
    }
    else if (Num % 2 == 0) {
        Count++;
        HailstoneNumbers(Num / 2);
    }
    else if (Num % 2 != 0) {
        Count++;
         HailstoneNumbers(3 * Num + 1);
    }
    return Count;

}

public static void main(String[] args)
{
    int Num = Integer.parseInt(JOptionPane.showInputDialog("\n Enter a positive number"));
    int x;

    x = HailstoneNumbers(Num);

   JOptionPane.showMessageDialog(null, "Number of Steps" + x );
}
</code>```

}

答:
You call HailstoneNumbers(Num / 2);. If you want to do it recursively, the function must return itself at each step, eg return HailstoneNumbers(Num / 2);. Also, if you are modifying a global variable, then the recursivity is pointless. Here is an example:

```<code>int hailstone(int i, int steps) {
    steps++;
    if(i == 1) return steps;
    if(i % 2 == 0) return hailstone(i / 2, steps);
    else return hailstone(i * 3 + 1, steps);
}

// main function
x = hailstone(num, 0);
</code>```

Note that by convention functions and variables shouldn't start with a capital letter unless they're final.

Title: Hailstone Java Program

Body:
I am working on The hailstone sequence program in which the user picks a positive integer. If number is even, it will be divided by two. If the number is odd, it'll be multiplied it by three and added by one. The program will continue until the number is equal to 1. The program will also tell the user the amount of steps it took to reach 1.

The goal is to be done recursively, my issue is that I am unable to declare each step to the user as the calculation happens to the number, for e.g "number is so I divide by 2 and it = "

This is my code so far, any suggestions or alternatives will help.

Thanks

import javax.swing*

{
   public class hailstone {
   static int Count;
   static int HailstoneNumbers(int Num)
   output += (Num + " " ) ;
   JOptionPane.showMessageDialog(null, output);

    if (Num == 1 && Count == 0) {
        return Count;

    }
    else if (Num == 1 && Count != 0) {
        //n-1
        Count++;
        return Count;
    }
    else if (Num % 2 == 0) {
        Count++;
        HailstoneNumbers(Num / 2);
    }
    else if (Num % 2 != 0) {
        Count++;
         HailstoneNumbers(3 * Num + 1);
    }
    return Count;

}

public static void main(String[] args)
{
    int Num = Integer.parseInt(JOptionPane.showInputDialog("\n Enter a positive number"));
    int x;

    x = HailstoneNumbers(Num);

   JOptionPane.showMessageDialog(null, "Number of Steps" + x );
}

}

Body:
You call HailstoneNumbers(Num / 2);. If you want to do it recursively, the function must return itself at each step, eg return HailstoneNumbers(Num / 2);. Also, if you are modifying a global variable, then the recursivity is pointless. Here is an example:

int hailstone(int i, int steps) {
    steps++;
    if(i == 1) return steps;
    if(i % 2 == 0) return hailstone(i / 2, steps);
    else return hailstone(i * 3 + 1, steps);
}

// main function
x = hailstone(num, 0);

Note that by convention functions and variables shouldn't start with a capital letter unless they're final.


问:
Is there a method to check if an array has ANY value in it?
Say I want to have an if statement to test if an array is empty or not,
Looking it up I have found no way to check besides array[0], which in frameworks like React and Angular give errors on the array's item not existing.

```<code>let arr = [];

if (!arr[0]) {
  arr.map(val=>{
    return <div>{val.name}</div>
  });
}
</code>```

In this example I want it to Display the JSX and if not, do not display any JSX. But doing this throws an error. Is there anyway to do this? preferably without any outside libraries.

edit: "added 'this' after 'to do'"

答:
This checks whether the variable is defined and whether it contains anything (although in this case you'd probably not need the first check):

```<code>if ( arr && arr.length )
</code>```

Also, don't forget to return arr.map(...

Body:
Say I want to have an if statement to test if an array is empty or not,
Looking it up I have found no way to check besides array[0], which in frameworks like React and Angular give errors on the array's item not existing.

let arr = [];

if (!arr[0]) {
  arr.map(val=>{
    return
{val.name}

  });
}

In this example I want it to Display the JSX and if not, do not display any JSX. But doing this throws an error. Is there anyway to do this? preferably without any outside libraries.

edit: "added 'this' after 'to do'"

Body:
This checks whether the variable is defined and whether it contains anything (although in this case you'd probably not need the first check):

if ( arr && arr.length )

Also, don't forget to return arr.map(...


问:
MinGW MSYS Slow -- How to make faster?
MinGW is still slow a year after that question was posted, and I've tried to fix it but there's no difference. Someone else apparently has the same problem too, but no fix.

I'm trying to compile GCC and each object file is taking several seconds. (This varies wildly; sometimes it's 1 second, sometimes it's 30.) (In any case, though, it's definitely not my computer; it's fine with other compilers.) Does anyone know why it's so slow, and if there are any options I can set to improve the compile time?

Thanks!

答:
Well, MSYS and Cygwin have to be slow by design, or in other words are very hard to make faster. There is continuous string processing of every command passed to the Bash shell, the POSIX shared memory pool to manually manage etc...

If you want to build GCC on Windows, I strongly suggest installing a free VM software, like Virtualbox, install a lightweight distro, and cross-compile a Windows toolchain. From Windows, use some other build system than autocrap (CMake, Qt's qmake, ...) and speed should not be an issue anymore. It might sound like a lot of hassle and the complete opposite of a Minimal SYStem, but heck, it works sooo much better, and much faster.

ContentLicense: CC BY-SA 3.0

Title: MinGW MSYS Slow -- How to make faster?


答:
Figured it out!

I changed the f.writerow function to the following:

```<code>for key in x["Result"]:
    type = "Type1"
    f.writerow([key,
                type,
                x["Result"][key]["Type1"][0]["Owner"],
                x["Result"][key]["Type1"][0]["Email"]])
                ...
</code>```

This allowed me reference the keys within the object. Hopefully this helps someone down the line!

Title: How to convert nested JSON data to CSV using python?

Body:
Figured it out!

I changed the f.writerow function to the following:

for key in x["Result"]:
    type = "Type1"
    f.writerow([key,
                type,
                x["Result"][key]["Type1"][0]["Owner"],
                x["Result"][key]["Type1"][0]["Email"]])
                ...

This allowed me reference the keys within the object. Hopefully this helps someone down the line!


问:
React form sending empty object
I am trying to send user input in a form component to the component managing the state. I tried to use a callback but my input is not being sent.

Tried to use the form object in a callback

```<code>//here is the form component

class ListForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      NewItem: {
        itemText: "",
        id: Date.now(),
        completed: false
      }
    };
  }

  handleChanges = e => {
    this.setState({...this.state,
      NewItem: { ...this.state.NewItem, [e.target.name]: e.target.value }
    });
  };

  submitItem = e => {
     this.setState({ itemText: "" });
    this.props.addItem(e, this.state.NewItem);

  };

  render() {
    return (
      <form onSubmit={this.submitItem}>
        <input
          type="text"
          value={this.state.NewItem.itemText}
          name="itemText"
          onChange={this.handleChanges}
        />
        <button>Add</button>
      </form>
    );
  }
}

export default ListForm;
</code>```

```<code>addItem is in the parent component and looks like this. Groceries is just an array of objects with itemText, id and completed

addItem = (e, item) => {
    e.preventDefault();
        this.setState({
      ...this.state,
      groceries: [...this.state.groceries, item]
    });
  };
</code>```

I can enter in the form, but when I hit enter, nothing is added to the list

答:
Very first thing to try is to add e.persist to your addItem() function

```<code>addItem = (e, item) => {
    e.preventDefault();
    e.persist()
        this.setState({
      ...this.state,
      groceries: [...this.state.groceries, item]
    });
  };
</code>```

Another option is using redux to save the form data in the Global state and then accessing it in the parent component through redux. Here is an example of what that might look like:

```<code>import React, { Component } from 'react';
import * as ACTIONS from '../store/actions/actions';
import { connect } from 'react-redux';

class Form1 extends Component {

  state ={
    value: ''
  }

  handleChange = (event) => (
    this.setState({value: event.target.value})
  )

  handleSubmit = (event) => {
    event.preventDefault()
    this.props.input_action_creator(event.target.name.value)
  }

  render() {
    return (
      <div>
        <form onSubmit={this.handleSubmit}>
          <input id="name" onChange={this.handleChange} type="text" />
          <button type="submit"> Submit </button>
        </form>
        <br />
      </div>
    )}
}

function mapDispatchToProps(dispatch) {
  return {
    input_action_creator: (text) => dispatch(ACTIONS.user_input(text))
  }
}

export default connect(mapDispatchToProps)(Form1);

class Parent extends Component {

  access form data with

  this.props.user_Text

}

function mapStateToProps(state) {
  return {
    user_text: state.user_reducer.user_text
  }
}
</code>```

here is a fully funcitoning react-redux project if you are interested

https://github.com/iqbal125/modern-react-app-sample

Title: React form sending empty object

Body:
I am trying to send user input in a form component to the component managing the state. I tried to use a callback but my input is not being sent.

Tried to use the form object in a callback

//here is the form component

class ListForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      NewItem: {
        itemText: "",
        id: Date.now(),
        completed: false
      }
    };
  }

  handleChanges = e => {
    this.setState({...this.state,
      NewItem: { ...this.state.NewItem, [e.target.name]: e.target.value }
    });
  };

  submitItem = e => {
     this.setState({ itemText: "" });
    this.props.addItem(e, this.state.NewItem);

  };

  render() {
    return (
      <form onSubmit={this.submitItem}>
        <input
          type="text"
          value={this.state.NewItem.itemText}
          name="itemText"
          onChange={this.handleChanges}
        />
        <button>Add</button>
      </form>
    );
  }
}

export default ListForm;

addItem is in the parent component and looks like this. Groceries is just an array of objects with itemText, id and completed

addItem = (e, item) => {
    e.preventDefault();
        this.setState({
      ...this.state,
      groceries: [...this.state.groceries, item]
    });
  };

I can enter in the form, but when I hit enter, nothing is added to the list

Body:
Very first thing to try is to add e.persist to your addItem() function

addItem = (e, item) => {
    e.preventDefault();
    e.persist()
        this.setState({
      ...this.state,
      groceries: [...this.state.groceries, item]
    });
  };

Another option is using redux to save the form data in the Global state and then accessing it in the parent component through redux. Here is an example of what that might look like:

import React, { Component } from 'react';
import * as ACTIONS from '../store/actions/actions';
import { connect } from 'react-redux';

class Form1 extends Component {

  state ={
    value: ''
  }

  handleChange = (event) => (
    this.setState({value: event.target.value})
  )

  handleSubmit = (event) => {
    event.preventDefault()
    this.props.input_action_creator(event.target.name.value)
  }

  render() {
    return (
      <div>
        <form onSubmit={this.handleSubmit}>
          <input id="name" onChange={this.handleChange} type="text" />
          <button type="submit"> Submit </button>
        </form>
        <br />
      </div>
    )}
}

function mapDispatchToProps(dispatch) {
  return {
    input_action_creator: (text) => dispatch(ACTIONS.user_input(text))
  }
}

export default connect(mapDispatchToProps)(Form1);

class Parent extends Component {

  access form data with

  this.props.user_Text

}

function mapStateToProps(state) {
  return {
    user_text: state.user_reducer.user_text
  }
}

here is a fully funcitoning react-redux project if you are interested

https://github.com/iqbal125/modern-react-app-sample


问:
Add Start and Stop point parameters to method that adds sums of numbers in a string
I am trying to modify a method from the post marked as duplicate that will allow me to enter a string containing numbers, like "Here are77 with88 monsters" which I adds the sum of the numbers in the string to return 14 and 16 if I evaluated the entire string. How would I enhance this method to evaluate start and stop points in the string? So if I wanted to evaluate position 3 through 10, it would return just 14, since 77 are numbers between positions 3 and 10?

I have done quite a bit of research, but I'm really new to Java, and don't know enough yet to figure this out. The code below is where I'm at now:

```<code>    String s = "Here are77 with 88 monsters";
    String[] st = s.split(" ");
    for (int i=0 ; i<st.length ; i++) {
        if (st[i].matches("[0-9]+")) {
            String[] c = st[i].split("(?=\\d)");
            int sum = 0;
            for(int j=0 ; j<c.length ; j++) {
                sum += Integer.parseInt(c[j]);
            }
          return sum;}
        }
</code>```

I need help to add the two extra position parameters so I can use this code above to calculate the sum of the digits within those margins in a method.

答:
Here's my code from your previous post boiled down to its bare essentials:

```<code>public class AddDigitsInString
{

    public static void main(String[] args)
    {
        String input = "Here are77 with 88 monsters";
        System.out.println("Input: " + input);

        String curNumber = "";
        for(Character c: input.toCharArray())
        {
            if(Character.isDigit(c))
            {
                curNumber = curNumber + c;
            }
            else
            {
                if (curNumber != "")
                {
                    int curSum = sum(curNumber);
                    System.out.println("Number: " + curNumber + ", Sum: " + curSum);
                    curNumber = "";
                }
            }
        }
        if (curNumber != "")
        {
            int curSum = sum(curNumber);
            System.out.println("Number: " + curNumber + ", Sum: " + curSum);
        }
    }

    public static int sum(String number)
    {
        int total = 0;
        for(char c: number.toCharArray())
        {
            total = total + Character.getNumericValue(c);
        }
        return total;
    }

}
</code>```

Output:

Body:
I am trying to modify a method from the post marked as duplicate that will allow me to enter a string containing numbers, like "Here are77 with88 monsters" which I adds the sum of the numbers in the string to return 14 and 16 if I evaluated the entire string. How would I enhance this method to evaluate start and stop points in the string? So if I wanted to evaluate position 3 through 10, it would return just 14, since 77 are numbers between positions 3 and 10?

I have done quite a bit of research, but I'm really new to Java, and don't know enough yet to figure this out. The code below is where I'm at now:

    String s = "Here are77 with 88 monsters";
    String[] st = s.split(" ");
    for (int i=0 ; i<st.length ; i++) {
        if (st[i].matches("[0-9]+")) {
            String[] c = st[i].split("(?=\\d)");
            int sum = 0;
            for(int j=0 ; j<c.length ; j++) {
                sum += Integer.parseInt(c[j]);
            }
          return sum;}
        }

I need help to add the two extra position parameters so I can use this code above to calculate the sum of the digits within those margins in a method.

Body:
Here's my code from your previous post boiled down to its bare essentials:

public class AddDigitsInString
{

    public static void main(String[] args)
    {
        String input = "Here are77 with 88 monsters";
        System.out.println("Input: " + input);

        String curNumber = "";
        for(Character c: input.toCharArray())
        {
            if(Character.isDigit(c))
            {
                curNumber = curNumber + c;
            }
            else
            {
                if (curNumber != "")
                {
                    int curSum = sum(curNumber);
                    System.out.println("Number: " + curNumber + ", Sum: " + curSum);
                    curNumber = "";
                }
            }
        }
        if (curNumber != "")
        {
            int curSum = sum(curNumber);
            System.out.println("Number: " + curNumber + ", Sum: " + curSum);
        }
    }

    public static int sum(String number)
    {
        int total = 0;
        for(char c: number.toCharArray())
        {
            total = total + Character.getNumericValue(c);
        }
        return total;
    }

}

Output:


问:
Scons not found android_add_java_dir
I'm using Scons to build godot engine and after i set everythings right:

I set my system variables as:

```<code>ANDROID_NDK_HOME --->  C:\android-ndk-r19c
ANDROID_NDK_ROOT --->  C:\android-ndk-r19c
ANDROID_HOME  --->  C:\Users\V\AppData\Local\Android\Sdk
</code>```

But Scons is like is not able to find android
what I'm doing wrong?

答:
From the FAQ:

https://scons.org/faq.html#Why_doesn.27t_SCons_find_my_compiler.2BAC8-linker.2BAC8-etc..3F_I_can_execute_it_just_fine_from_the_command_line.

SCons doesn't propagate system shell environment variables by default, by design.

Title: Scons not found android_add_java_dir

Body:
I'm using Scons to build godot engine and after i set everythings right:

I set my system variables as:

ANDROID_NDK_HOME --->  C:\android-ndk-r19c
ANDROID_NDK_ROOT --->  C:\android-ndk-r19c
ANDROID_HOME  --->  C:\Users\V\AppData\Local\Android\Sdk

But Scons is like is not able to find android
what I'm doing wrong?


问:
Second dataset result not showing on first time execution
I had created a SSRS reports where it generates list of studnts with selected subjects and it marks which was displayed in matrix successfully. After that I need to tshow the overall analysis of each subject in the same report.
So I had created total 2 procedures.

First one for dataset 1 list of students with respective subject wise marks.
As like temp table here I had created a table where I push the analysis of each subject in the new table.

And by using the second procedure for dataset 2 I planned for fetching the data of subject wise analysis.

Every time the second proc executes I'm deleting the data of that table.

My problem is I'm not getting the data from dataset 2 on the firt execution.From the second run I'm able to get the data.
Whenever I had changed the parameters for the first time It's not geting the data.

```<code>    ALTER Proc [dbo].[SP_Get_IGCSESubjectMarks_GetLastTerm_HTS2] --7,'1,17,8','2537,2555,2558,2568'
(

@ReportId int=7,
@SubjectId varchar(200),
@SectionId varchar(200)
)
AS
BEGIN
-------------------
------------------- Some code

Insert into #temp (Name,Class,SubjectName,Section,enrollNo,TermName,TestName,Marks)
select Name,Class,'Total',Section,enrollNo,TermName,'Percentage',SUM(Marks)*100/sum(maxmarksare) from #temp1
GROUP BY Name,Class,Section,enrollNo,SubjectName,TermName,SubjectOrder

--TmpIgcseData is the new table for which I'm pushing the subject wise analysis This was the table used in 2nd dataset for fetching data.
delete  from  TmpIgcseData
insert into TmpIgcseData(enrollno,SName,SubjectName,TestName,Marks,OrderNumber) select  enrollno,Name,SubjectName,TestName,Marks,SubjectOrder from #temp

select @UID as Id,* from #temp
drop table #temp
drop table #temp1

end

--------------------------------------------------------------

ALTER PROC [dbo].[IgcesResultAnalysis_HTS2]
AS
begin
------------
------------ Some code.
select * from #distsubjects
--Deleting the data from the table
delete  from  TmpIgcseData

End

</code>```

答:
This is really bad practice. You are editing data in a permanent table (TmpIgcseData). What happens if two people execute the report? You also cannot rely on the execution order of the datasets in SSRS.

It is much better to pass the required parameters to both procedures and do all the work within each procedure. In other words, do not rely on another proc to prepare the data unless you call that proc from with your main proc and restrict the tables used to temp tables within the scope of the main proc.

Body:
I had created a SSRS reports where it generates list of studnts with selected subjects and it marks which was displayed in matrix successfully. After that I need to tshow the overall analysis of each subject in the same report.
So I had created total 2 procedures.

First one for dataset 1 list of students with respective subject wise marks.
As like temp table here I had created a table where I push the analysis of each subject in the new table.

And by using the second procedure for dataset 2 I planned for fetching the data of subject wise analysis.

Every time the second proc executes I'm deleting the data of that table.

My problem is I'm not getting the data from dataset 2 on the firt execution.From the second run I'm able to get the data.
Whenever I had changed the parameters for the first time It's not geting the data.

    ALTER Proc [dbo].[SP_Get_IGCSESubjectMarks_GetLastTerm_HTS2] --7,'1,17,8','2537,2555,2558,2568'
(

@ReportId int=7,
@SubjectId varchar(200),
@SectionId varchar(200)
)
AS
BEGIN
-------------------
------------------- Some code

Insert into #temp (Name,Class,SubjectName,Section,enrollNo,TermName,TestName,Marks)
select Name,Class,'Total',Section,enrollNo,TermName,'Percentage',SUM(Marks)*100/sum(maxmarksare) from #temp1
GROUP BY Name,Class,Section,enrollNo,SubjectName,TermName,SubjectOrder

--TmpIgcseData is the new table for which I'm pushing the subject wise analysis This was the table used in 2nd dataset for fetching data.
delete  from  TmpIgcseData
insert into TmpIgcseData(enrollno,SName,SubjectName,TestName,Marks,OrderNumber) select  enrollno,Name,SubjectName,TestName,Marks,SubjectOrder from #temp

select @UID as Id,* from #temp
drop table #temp
drop table #temp1

end

--------------------------------------------------------------

ALTER PROC [dbo].[IgcesResultAnalysis_HTS2]
AS
begin
------------
------------ Some code.
select * from #distsubjects
--Deleting the data from the table
delete  from  TmpIgcseData

End


答:
Type1 in your data structure is a list, not a dict. So you need to iterate over it instead of referencing by key.

```<code>for key in x["Result"]:
    # key is now "Example 1" etc.
    type1 = x["Result"][key]["Type1"]
    # type1 is a list, not a dict
    for i in type1:
        f.writerow([key,
                    "Type1",
                    type1["Owner"],
                    type1["Description"],
                    type1["Email"],
                    type1["Phone"]])
</code>```

The inner for loop ensure that you're protected from the assumption that "Type1" only ever has one item in the list.

Body:
Type1 in your data structure is a list, not a dict. So you need to iterate over it instead of referencing by key.

for key in x["Result"]:
    # key is now "Example 1" etc.
    type1 = x["Result"][key]["Type1"]
    # type1 is a list, not a dict
    for i in type1:
        f.writerow([key,
                    "Type1",
                    type1["Owner"],
                    type1["Description"],
                    type1["Email"],
                    type1["Phone"]])

The inner for loop ensure that you're protected from the assumption that "Type1" only ever has one item in the list.


问:
How to convert mmod_rectangles to rectangles via Dlib?
In this code used detectors of dlib.

dlib.get_frontal_face_detector()
dlib.cnn_face_detection_model_v1('mmod_human_face_detector.dat')
```
</blockquote>

```detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor('res/model.dat')
# detector = dlib.cnn_face_detection_model_v1('mmod_human_face_detector.dat')

cap = cv.VideoCapture(0)

while True:
    _, frame = cap.read(0)
    gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)
    dets = detector(gray, 0)
    print(dets)
    for det in dets:
        landmarks = shape_to_np(predictor(gray, det))

    cv.imshow('test', frame)

    if cv.waitKey(1) == ord('q'):
        break
```

<p>When used the cnn detector, dets look as:</p>

<pre class="lang-py prettyprint-override"><code>mmod_rectangles[[(258, 254) (422, 417)]]
</code>```

And an exception is thrown in the predictor line:

```<code>TypeError: __call__(): incompatible function arguments. The following
argument types are supported:
    1. (self: dlib.shape_predictor, image: array, box: dlib.rectangle) -> dlib.full_object_detection

Invoked with: <dlib.shape_predictor object at 0x7f37a12ba9d0>,
array([[71, 69, 70, ..., 71, 70, 73],
       [71, 72, 71, ..., 72, 72, 75],
       [71, 70, 71, ..., 72, 72, 73],
       ...,
       [27, 27, 27, ..., 75, 71, 68],
       [27, 27, 27, ..., 74, 71, 71],
       [24, 25, 27, ..., 73, 71, 70]], dtype=uint8), <dlib.mmod_rectangle object at 0x7f37819beea0>

</code>```

But when used get_frontal_face_detector, the dets look as:

```<code>rectangles[[(273, 234) (453, 413)]]
</code>```

And the code works correctly.

答:
try to perform </p>

```<code>faceRect = det.rect
landmarks = shape_to_np(predictor(gray, faceRect))
</code>```

Body:
In this code used detectors of dlib.

dlib.get_frontal_face_detector()
dlib.cnn_face_detection_model_v1('mmod_human_face_detector.dat')

detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor('res/model.dat')
# detector = dlib.cnn_face_detection_model_v1('mmod_human_face_detector.dat')

cap = cv.VideoCapture(0)

while True:
    _, frame = cap.read(0)
    gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)
    dets = detector(gray, 0)
    print(dets)
    for det in dets:
        landmarks = shape_to_np(predictor(gray, det))

    cv.imshow('test', frame)

    if cv.waitKey(1) == ord('q'):
        break

When used the cnn detector, dets look as:

mmod_rectangles[[(258, 254) (422, 417)]]

And an exception is thrown in the predictor line:

TypeError: __call__(): incompatible function arguments. The following
argument types are supported:
    1. (self: dlib.shape_predictor, image: array, box: dlib.rectangle) -> dlib.full_object_detection

Invoked with: <dlib.shape_predictor object at 0x7f37a12ba9d0>,
array([[71, 69, 70, ..., 71, 70, 73],
       [71, 72, 71, ..., 72, 72, 75],
       [71, 70, 71, ..., 72, 72, 73],
       ...,
       [27, 27, 27, ..., 75, 71, 68],
       [27, 27, 27, ..., 74, 71, 71],
       [24, 25, 27, ..., 73, 71, 70]], dtype=uint8), <dlib.mmod_rectangle object at 0x7f37819beea0>

But when used get_frontal_face_detector, the dets look as:

rectangles[[(273, 234) (453, 413)]]

And the code works correctly.

Body:
try to perform

faceRect = det.rect
landmarks = shape_to_np(predictor(gray, faceRect))


问:
What is the purpose of Encapsulation? Does it provide a security layer?
As much as I have studied about encapsulation it is about hiding data to prevent from manipulation. For that we declare the private variables so that couldn't be accessible from out of class. But we can implement or access them out of class using setter getter method. So if we have to implement it using setter getter method than any other person can implement it using setter getter method. . So how we are safe from manipulation??</p>

答:
The purpose of Encapsulation is two-fold:

Bundling related functionality together;

Controlling the access to fields and methods which participate in providing the functionality.

The goal of getters and setters is to ensure that actors outside the code (or class) have only one point of interaction with your fields, thus maintaining the invariants. This helps in:

Preventing modification of values in an illegal/unacceptable manner that can break the functionality.

Ex: Two external actors trying to modify your account balance at the same time;

Localizing an aspect of code that may change in future.

Ex: Easily allowing you to change the type of a status variable from boolean to enum in future because it is always accessed from getter in the class;

Implement business rules, if any, that are need to be exercised when changes are made to your fields.

Ex: Not allowing the Engine class to modify and set the speed of your Car class to a negative value, just because the car is going in reverse.


问:
Is it possible to use StringFormat or Constant Variable in android Room Query
I want to query the user associations list with the following room query using public constant variable Association.MEMBER_STATUS_APPROVED.

```<code>@Query("SELECT * FROM Association WHERE memberStatus = " + Association.MEMBER_STATUS_APPROVED)
LiveData<List<Association>> loadUserAssociations();
</code>```

But, room gives me [SQLITE_ERROR] when build.
 It is possible to re-write that query by replacing the constant variable with parameter like the following.

```<code>@Query("SELECT * FROM Association WHERE memberStatus = :statusApproved")
LiveData<List<Association>> loadUserAssociations(String statusApproved);
</code>```

I would like to know that does Room support such kind of string concatenation or String Format? (or) May be I missing something?

答:
For those who have the same problem, the following could be the solution in Kotlin:

```<code>@Query("SELECT * FROM Association WHERE memberStatus = :statusApproved")
loadUserAssociations(statusApproved: String = Association.MEMBER_STATUS_APPROVED): LiveData<List<Association>>
</code>```

And I think it is more clean way than hardcoding or passing obvious constant into the function.

Body:
I want to query the user associations list with the following room query using public constant variable Association.MEMBER_STATUS_APPROVED.

@Query("SELECT * FROM Association WHERE memberStatus = " + Association.MEMBER_STATUS_APPROVED)
LiveData<List<Association>> loadUserAssociations();

But, room gives me [SQLITE_ERROR] when build.
 It is possible to re-write that query by replacing the constant variable with parameter like the following.

@Query("SELECT * FROM Association WHERE memberStatus = :statusApproved")
LiveData<List<Association>> loadUserAssociations(String statusApproved);

I would like to know that does Room support such kind of string concatenation or String Format? (or) May be I missing something?

Body:
For those who have the same problem, the following could be the solution in Kotlin:

@Query("SELECT * FROM Association WHERE memberStatus = :statusApproved")
loadUserAssociations(statusApproved: String = Association.MEMBER_STATUS_APPROVED): LiveData<List<Association>>

And I think it is more clean way than hardcoding or passing obvious constant into the function.


问:
Jenkins: How to use JUnit plugin when Maven builds occur within Docker container
I am trying to create a Pipeline where Jenkins builds my Docker image, runs tests, and then deploys the container if the tests pass.  The problem is that I have maven running inside the docker container, and I can't actually access the published tests until I run the container. I want the Docker container to be ran and deployed after the tests pass.  This seems like a simple thing to do, but I can't think of a good way to do it.  Am I misunderstanding something? Thanks.

Dockerfile:

```<code>FROM openjdk:10 as step-one

COPY ./ /var/www/java/
WORKDIR /var/www/java

RUN apt-get update -y && apt-get install -y maven

RUN mvn clean package -X

ENTRYPOINT ["java"]
CMD ["-jar",  "target/gs-serving-web-content-0.1.0.jar"]

EXPOSE 8080
</code>```

Jenkinsfile:

```<code>
pipeline {

    agent any

        stages {
            stage('Build') {
                steps {
                    echo 'Building..'
                    sh 'docker build -t spring-image .'

                }
            }
            stage('Test') {
                steps {
                    echo 'Testing..'
                    junit '/var/www/java/target/surefire-reports/TEST-ma.SpringTest.xml'
                }
            }

            stage('Deploy') {
                steps {
                    echo 'Deploying....'
                        sh 'docker run -i -d --name spring-container spring-image'
                }
            }
        }
}

</code>```

答:
You can use fact that docker container home repository is a shared volume with local jenkins workspace.

Simplest pipeline script:

```<code>newApp.inside('-e NODE_ENV=test') { sh 'npm install --dev' sh 'gulp test:unit' } junit 'reports/*.xml'
</code>```

A bit complex example with some collateral work in separate stages (note that maven build image is using .m2 cache as non-root user):

```<code>    try {
    buildEnvImg.inside("-v /jenkins/.m2:/var/maven/.m2 -e MAVEN_CONFIG=/var/maven/.m2 -v /jenkins/.cache:/var/maven/.cache -v /var/run/docker.sock:/var/run/docker.sock") {
        stage('Compile') {
            sh 'mvn -Duser.home=/var/maven -B -DskipTests clean compile'
        }
        stage('Build jar') {
            sh 'mvn -Duser.home=/var/maven -B -DskipTests package'
        }
        stage('Build docker') {
            sh 'mvn -Duser.home=/var/maven -B -DskipTests jib:dockerBuild'
        }
        stage('Test') {
            echo 'Going to execute mvn test, thus automated tests contained in project will be compiled and executed.'
            sh 'mvn -Duser.home=/var/maven -B test'
        }
    }
} finally {
    junit 'target/surefire-reports/*.xml'
}
</code>```

Solution digged out from Jenkins build inside a docker container with generated reports .

Body:
I am trying to create a Pipeline where Jenkins builds my Docker image, runs tests, and then deploys the container if the tests pass.  The problem is that I have maven running inside the docker container, and I can't actually access the published tests until I run the container. I want the Docker container to be ran and deployed after the tests pass.  This seems like a simple thing to do, but I can't think of a good way to do it.  Am I misunderstanding something? Thanks.

Dockerfile:

FROM openjdk:10 as step-one

COPY ./ /var/www/java/
WORKDIR /var/www/java

RUN apt-get update -y && apt-get install -y maven

RUN mvn clean package -X

ENTRYPOINT ["java"]
CMD ["-jar",  "target/gs-serving-web-content-0.1.0.jar"]

EXPOSE 8080

Jenkinsfile:

pipeline {

    agent any

        stages {
            stage('Build') {
                steps {
                    echo 'Building..'
                    sh 'docker build -t spring-image .'

                }
            }
            stage('Test') {
                steps {
                    echo 'Testing..'
                    junit '/var/www/java/target/surefire-reports/TEST-ma.SpringTest.xml'
                }
            }

            stage('Deploy') {
                steps {
                    echo 'Deploying....'
                        sh 'docker run -i -d --name spring-container spring-image'
                }
            }
        }
}

Body:
You can use fact that docker container home repository is a shared volume with local jenkins workspace.

Simplest pipeline script:

newApp.inside('-e NODE_ENV=test') { sh 'npm install --dev' sh 'gulp test:unit' } junit 'reports/*.xml'

A bit complex example with some collateral work in separate stages (note that maven build image is using .m2 cache as non-root user):

    try {
    buildEnvImg.inside("-v /jenkins/.m2:/var/maven/.m2 -e MAVEN_CONFIG=/var/maven/.m2 -v /jenkins/.cache:/var/maven/.cache -v /var/run/docker.sock:/var/run/docker.sock") {
        stage('Compile') {
            sh 'mvn -Duser.home=/var/maven -B -DskipTests clean compile'
        }
        stage('Build jar') {
            sh 'mvn -Duser.home=/var/maven -B -DskipTests package'
        }
        stage('Build docker') {
            sh 'mvn -Duser.home=/var/maven -B -DskipTests jib:dockerBuild'
        }
        stage('Test') {
            echo 'Going to execute mvn test, thus automated tests contained in project will be compiled and executed.'
            sh 'mvn -Duser.home=/var/maven -B test'
        }
    }
} finally {
    junit 'target/surefire-reports/*.xml'
}

Solution digged out from Jenkins build inside a docker container with generated reports .


问:
How to prevent currency rounding errors with decimal variable type?
I am working on a payment plan calculator. I switched from 'double' to 'decimal' variable types to prevent rounding errors but I am still getting one somewhere. I came up with this data-set to use to test my code because there is a clear remainder:

Balance: $1,575.75

Down Payment: $500.00

Remaining Balance: $1,075.75

Number of Payments after the Down Payment: 9

Installment Amount: $119.53 (x8)

Remainder: $119.51

I switched my datatypes from double to decimal (obviously)
I tried re-writing the code multiple times calculating the same things in different ways (which is why some of the math at this point is less than 'minimalist')
I tried making my code more modular to find the rounding error

```<code>// Method within my WinForms project
public void CalculateInstallmentPayments()
{
    decimal currentBalance = Convert.ToDecimal(txtBalanceInput.Text); // Current Balance
    decimal downPayment = Convert.ToDecimal(txtDownPayment.Text); // Down Payment
    decimal installmentCount = sliderRemainingPmtCount.Value; // Installment Count
    decimal balanceAfterDP = currentBalance - downPayment; // Balance After Down Payment
    decimal installmentAmount = (balanceAfterDP / installmentCount); // Installment Amount
    decimal remainderPayment = (balanceAfterDP - (installmentAmount * (installmentCount - 1))); // Final Payment (Remainder)

    // Using Rich Text box as a 'Console' for debugging
    rtxtNotate.Text = ($"Current Balance: {currentBalance.ToString()}\nDown Payment: {downPayment.ToString("C")}\n" +
        $"Installment Count: {installmentCount.ToString()}\nInstallment Amount: {installmentAmount.ToString("C")}\n" +
        $"Remainder: {remainderPayment.ToString("C")}\n");
}
</code>```

This is currently the output:

Current Balance: 1575.75

Down Payment: $500.00

Installment Count: 9

Installment Amount: $119.53

Remainder: $119.53 -- This is the rounding error. It should read $119.51

I've been refactoring this code for hours and I feel like I'm missing something incredibly simple.

答:
You're not rounding off the down payment amount before you apply it. So you're getting the correct result with no (or very very small) rounding errors... for someone making payments of about $119.52777777777

If you round the installment amount before you store it in the installmentAmount variable you might get the answer you're looking for.

Body:
I am working on a payment plan calculator. I switched from 'double' to 'decimal' variable types to prevent rounding errors but I am still getting one somewhere. I came up with this data-set to use to test my code because there is a clear remainder:

Balance: $1,575.75

Down Payment: $500.00

Remaining Balance: $1,075.75

Number of Payments after the Down Payment: 9

Installment Amount: $119.53 (x8)

Remainder: $119.51

I switched my datatypes from double to decimal (obviously)
I tried re-writing the code multiple times calculating the same things in different ways (which is why some of the math at this point is less than 'minimalist')
I tried making my code more modular to find the rounding error

// Method within my WinForms project
public void CalculateInstallmentPayments()
{
    decimal currentBalance = Convert.ToDecimal(txtBalanceInput.Text); // Current Balance
    decimal downPayment = Convert.ToDecimal(txtDownPayment.Text); // Down Payment
    decimal installmentCount = sliderRemainingPmtCount.Value; // Installment Count
    decimal balanceAfterDP = currentBalance - downPayment; // Balance After Down Payment
    decimal installmentAmount = (balanceAfterDP / installmentCount); // Installment Amount
    decimal remainderPayment = (balanceAfterDP - (installmentAmount * (installmentCount - 1))); // Final Payment (Remainder)

    // Using Rich Text box as a 'Console' for debugging
    rtxtNotate.Text = ($"Current Balance: {currentBalance.ToString()}\nDown Payment: {downPayment.ToString("C")}\n" +
        $"Installment Count: {installmentCount.ToString()}\nInstallment Amount: {installmentAmount.ToString("C")}\n" +
        $"Remainder: {remainderPayment.ToString("C")}\n");
}

This is currently the output:

Current Balance: 1575.75

Down Payment: $500.00

Installment Count: 9

Installment Amount: $119.53

Remainder: $119.53 -- This is the rounding error. It should read $119.51

I've been refactoring this code for hours and I feel like I'm missing something incredibly simple.


问:
formatting strings to iterate over dataframe
Background:

I have the following code to make a dataframe from a list:

```<code>l = ['the cat meows',
     'the dog barks',
     'the bird chirps']
df = pd.DataFrame(l, columns=['Text'])
</code>```

Output:

```<code>          Text
0   the cat meows
1   the dog barks
2   the bird chirps
</code>```

Desired Output:

```<code>          Text     Animal
0   the cat meows   cat
1   the dog barks   dog
2   the bird chirps bird
</code>```

Approach:

I attempt to get the Desired Output using the following code:

```<code>#create list of animal names
animal_list = ['cat', 'dog', 'bird']

#extract names from 'Text' column using the names in 'animal_list'
#and create a new column containing extracted 'Text' names
df['Sound'] = df['Animal'].str.extract(r"(%s)"% animal_list)
</code>```

Problem:

However, I get the following when I do so:

```<code>            Text    Animal
0   the cat meows   t
1   the dog barks   t
2   the bird chirps t
</code>```

Question

How do I achieve my desired output?

答:
Using the animal_list with str.extract

We can use Series.str.extract here and pass it your animal_list delimited by a | which is the or operator in regex:

```<code>df['Animal'] = df['Text'].str.extract(f"({'|'.join(animal_list)})")
</code>```

Or if you have python < 3.5 you cannot use f-string

We can use @Mike's answer from the comments

```<code>df['Animal'] = df['Animal'].str.extract(r"({})".format("|".join(animal_list)))
</code>```

Output

```<code>              Text Animal
0    the cat meows    cat
1    the dog barks    dog
2  the bird chirps   bird
</code>```

Getting the middle word with str.split

```<code>df['Animal'] = df['Text'].str.split().str[1]
</code>```

Output

```<code>              Text Animal
0    the cat meows    cat
1    the dog barks    dog
2  the bird chirps   bird
</code>```

Body:
Background:

I have the following code to make a dataframe from a list:

l = ['the cat meows',
     'the dog barks',
     'the bird chirps']
df = pd.DataFrame(l, columns=['Text'])

Output:

          Text
0   the cat meows
1   the dog barks
2   the bird chirps

Desired Output:

          Text     Animal
0   the cat meows   cat
1   the dog barks   dog
2   the bird chirps bird

Approach:

I attempt to get the Desired Output using the following code:

#create list of animal names
animal_list = ['cat', 'dog', 'bird']

#extract names from 'Text' column using the names in 'animal_list'
#and create a new column containing extracted 'Text' names
df['Sound'] = df['Animal'].str.extract(r"(%s)"% animal_list)

Problem:

However, I get the following when I do so:

            Text    Animal
0   the cat meows   t
1   the dog barks   t
2   the bird chirps t

Question

How do I achieve my desired output?

Body:
Using the animal_list with str.extract

We can use Series.str.extract here and pass it your animal_list delimited by a | which is the or operator in regex:

df['Animal'] = df['Text'].str.extract(f"({'|'.join(animal_list)})")

Or if you have python < 3.5 you cannot use f-string

We can use @Mike's answer from the comments

df['Animal'] = df['Animal'].str.extract(r"({})".format("|".join(animal_list)))

Output

              Text Animal
0    the cat meows    cat
1    the dog barks    dog
2  the bird chirps   bird

Getting the middle word with str.split

df['Animal'] = df['Text'].str.split().str[1]

Output

              Text Animal
0    the cat meows    cat
1    the dog barks    dog
2  the bird chirps   bird


问:
is there a way to examine if an angle is a right angle programmatically?
i plot an angle in python

here is the code

```<code>x = [0,0.5,1]
y = [0,0.5,0]
plt.scatter(x,y)
plt.plot(x,y)
plt.show()
</code>```

is there a way to examine if the angle is a right angle programmatically?

Body:
i plot an angle in python

here is the code

x = [0,0.5,1]
y = [0,0.5,0]
plt.scatter(x,y)
plt.plot(x,y)
plt.show()

is there a way to examine if the angle is a right angle programmatically?

Body:
The easiest way is to test if the dot product of the vectors is 0.

In your case, you simply compute:

v1 = ( (x[1]-x[0]), (y[1]-y[0]) ) <- (0.5, 0.5)
v2 = ( (x[2]-x[1]), (y[2]-y[1]) ) <- (0.5, -0.5)

dot_product = v1[0]*v2[0] + v1[1]*v2[1] <- 0.5² - 0.5² = 0


问:
Options for distribution of an offline Ruby on Rails application
I am developing an application in using Ruby on Rails, mostly as an excuse to learn the language.

This is not intended to be a web-based application - and perhaps I have chosen the wrong language, but...

My understanding is, that in order to run an instance of this application on somebody else's computer, they would need to install ruby on rails, and a webserver (or webrick, perhaps), as well as my application code.

I am just curious if there are any other options for distributing my application as a standalone app, or perhaps just a simple way to package up a web browser and ROR together with my app for a simple, one-step install?

答:
Note, Slingshot appears to be a dead project (see comments). I'll leave this answer here for historical purposes and the off-chance that it comes back

Joyent's Slingshot might be a good bet.

Joyent Slingshot allows developers to deploy Rails applications like a standard desktop application, which work online and offline (with synchronization), have drag and drop, and interact with all the other desktop applications.

With Joyent Slingshot:

Create a hybrid Web/desktop application

Synchronize online and offline data

Use the same code for online and offline application(s)

Deploy and update your application easily

Drag into and out of application

Here are some further links to help with your evaluation and/or to help you get started:

Introducing Joyent Slingshot

Basic application walkthrough

Slingshot wiki

OwnerDisplayName: Brent Nesbitt

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: charlesroper

LastEditorDisplayName: charlesroper


问:
What output and recording ports does the Java Sound API find on your computer?
I'm working with the Java Sound API, and it turns out if I want to adjust recording volumes I need to model the hardware that the OS exposes to Java. Turns out there's a lot of variety in what's presented.

Because of this I'm humbly asking that anyone able to help me run the following on their computer and post back the results so that I can get an idea of what's out there.

A thanks in advance to anyone that can assist :-)

```<code>import javax.sound.sampled.*;
public class SoundAudit {
  public static void main(String[] args) { try {
    System.out.println("OS: "+System.getProperty("os.name")+" "+
      System.getProperty("os.version")+"/"+
      System.getProperty("os.arch")+"\nJava: "+
      System.getProperty("java.version")+" ("+
      System.getProperty("java.vendor")+")\n");
      for (Mixer.Info thisMixerInfo : AudioSystem.getMixerInfo()) {
        System.out.println("Mixer: "+thisMixerInfo.getDescription()+
          " ["+thisMixerInfo.getName()+"]");
        Mixer thisMixer = AudioSystem.getMixer(thisMixerInfo);
        for (Line.Info thisLineInfo:thisMixer.getSourceLineInfo()) {
            if (thisLineInfo.getLineClass().getName().equals(
              "javax.sound.sampled.Port")) {
              Line thisLine = thisMixer.getLine(thisLineInfo);
              thisLine.open();
              System.out.println("  Source Port: "
                +thisLineInfo.toString());
              for (Control thisControl : thisLine.getControls()) {
                System.out.println(AnalyzeControl(thisControl));}
              thisLine.close();}}
        for (Line.Info thisLineInfo:thisMixer.getTargetLineInfo()) {
          if (thisLineInfo.getLineClass().getName().equals(
            "javax.sound.sampled.Port")) {
            Line thisLine = thisMixer.getLine(thisLineInfo);
            thisLine.open();
            System.out.println("  Target Port: "
              +thisLineInfo.toString());
            for (Control thisControl : thisLine.getControls()) {
              System.out.println(AnalyzeControl(thisControl));}
            thisLine.close();}}}
  } catch (Exception e) {e.printStackTrace();}}
  public static String AnalyzeControl(Control thisControl) {
    String type = thisControl.getType().toString();
    if (thisControl instanceof BooleanControl) {
      return "    Control: "+type+" (boolean)"; }
    if (thisControl instanceof CompoundControl) {
      System.out.println("    Control: "+type+
        " (compound - values below)");
      String toReturn = "";
      for (Control children:
        ((CompoundControl)thisControl).getMemberControls()) {
        toReturn+="  "+AnalyzeControl(children)+"\n";}
      return toReturn.substring(0, toReturn.length()-1);}
    if (thisControl instanceof EnumControl) {
      return "    Control:"+type+" (enum: "+thisControl.toString()+")";}
    if (thisControl instanceof FloatControl) {
      return "    Control: "+type+" (float: from "+
        ((FloatControl) thisControl).getMinimum()+" to "+
        ((FloatControl) thisControl).getMaximum()+")";}
    return "    Control: unknown type";}
}
</code>```

All the application does is print out a line about the OS, a line about the JVM, and a few lines about the hardware found that may pertain to recording hardware. For example on my PC at work I get the following:

OS: Windows XP 5.1/x86
Java: 1.6.0_07 (Sun Microsystems Inc.)

```
Mixer: Direct Audio Device: DirectSound Playback [Primary Sound Driver]
Mixer: Direct Audio Device: DirectSound Playback [SoundMAX HD Audio]
Mixer: Direct Audio Device: DirectSound Capture [Primary Sound Capture Driver]
Mixer: Direct Audio Device: DirectSound Capture [SoundMAX HD Audio]
Mixer: Software mixer and synthesizer [Java Sound Audio Engine]
Mixer: Port Mixer [Port SoundMAX HD Audio]
  Source Port: MICROPHONE source port
    Control: Microphone (compound - values below)
      Control: Select (boolean)
      Control: Microphone Boost (boolean)
      Control: Front panel microphone (boolean)
      Control: Volume (float: from 0.0 to 1.0)
  Source Port: LINE_IN source port
    Control: Line In (compound - values below)
      Control: Select (boolean)
      Control: Volume (float: from 0.0 to 1.0)
      Control: Balance (float: from -1.0 to 1.0)
```

答:
```<code>OS: Linux 2.6.24-23-generic/amd64
Java: 1.6.0_05 (Sun Microsystems Inc.)

Mixer: Direct Audio Device: NVidia CK804, Intel ICH, NVidia CK804 [CK804 [plughw:0,0]]
Mixer: Direct Audio Device: NVidia CK804, Intel ICH - MIC ADC, NVidia CK804 - MIC ADC [CK804 [plughw:0,1]]
Mixer: Direct Audio Device: NVidia CK804, Intel ICH - IEC958, NVidia CK804 - IEC958 [CK804 [plughw:0,2]]
Mixer: Software mixer and synthesizer [Java Sound Audio Engine]
Mixer: NVidia CK804, Realtek ALC850 rev 0 [Port CK804 [hw:0]]
  Source Port: IEC958 Playback AC97-SPSA source port
    Control: IEC958 Playback AC97-SPSA (compound - values below)
      Control: Volume (float: from 0.0 to 1.0)
  Source Port: Capture source port
    Control: Capture (compound - values below)
      Control: Volume (float: from 0.0 to 1.0)
      Control: Balance (float: from -1.0 to 1.0)
      Control: Select (boolean)
  Target Port: Master target port
    Control: Master (compound - values below)
      Control: Volume (float: from 0.0 to 1.0)
      Control: Balance (float: from -1.0 to 1.0)
      Control: Mute (boolean)
  Target Port: Master Mono target port
    Control: Master Mono (compound - values below)
      Control: Volume (float: from 0.0 to 1.0)
      Control: Mute (boolean)
  Target Port: PCM target port
    Control: PCM (compound - values below)
      Control: Volume (float: from 0.0 to 1.0)
      Control: Balance (float: from -1.0 to 1.0)
      Control: Mute (boolean)
  Target Port: Surround target port
    Control: Surround (compound - values below)
      Control: Volume (float: from 0.0 to 1.0)
      Control: Balance (float: from -1.0 to 1.0)
      Control: Mute (boolean)
  Target Port: Center target port
    Control: Center (compound - values below)
      Control: Volume (float: from 0.0 to 1.0)
      Control: Mute (boolean)
  Target Port: LFE target port
    Control: LFE (compound - values below)
      Control: Volume (float: from 0.0 to 1.0)
      Control: Mute (boolean)
  Target Port: Line target port
    Control: Line (compound - values below)
      Control: Volume (float: from 0.0 to 1.0)
      Control: Balance (float: from -1.0 to 1.0)
      Control: Mute (boolean)
  Target Port: CD target port
    Control: CD (compound - values below)
      Control: Volume (float: from 0.0 to 1.0)
      Control: Balance (float: from -1.0 to 1.0)
      Control: Mute (boolean)
  Target Port: Mic target port
    Control: Mic (compound - values below)
      Control: Volume (float: from 0.0 to 1.0)
      Control: Mute (boolean)
  Target Port: Phone target port
    Control: Phone (compound - values below)
      Control: Volume (float: from 0.0 to 1.0)
      Control: Mute (boolean)
  Target Port: IEC958 Playback AC97-SPSA target port
    Control: IEC958 Playback AC97-SPSA (compound - values below)
      Control: Volume (float: from 0.0 to 1.0)
  Target Port: PC Speaker target port
    Control: PC Speaker (compound - values below)
      Control: Volume (float: from 0.0 to 1.0)
      Control: Mute (boolean)
  Target Port: Aux target port
    Control: Aux (compound - values below)
      Control: Volume (float: from 0.0 to 1.0)
      Control: Balance (float: from -1.0 to 1.0)
      Control: Mute (boolean)
</code>```

OwnerDisplayName: Dave Carpeneto

Body:
I'm working with the Java Sound API, and it turns out if I want to adjust recording volumes I need to model the hardware that the OS exposes to Java. Turns out there's a lot of variety in what's presented.

Because of this I'm humbly asking that anyone able to help me run the following on their computer and post back the results so that I can get an idea of what's out there.

A thanks in advance to anyone that can assist :-)

import javax.sound.sampled.*;
public class SoundAudit {
  public static void main(String[] args) { try {
    System.out.println("OS: "+System.getProperty("os.name")+" "+
      System.getProperty("os.version")+"/"+
      System.getProperty("os.arch")+"\nJava: "+
      System.getProperty("java.version")+" ("+
      System.getProperty("java.vendor")+")\n");
      for (Mixer.Info thisMixerInfo : AudioSystem.getMixerInfo()) {
        System.out.println("Mixer: "+thisMixerInfo.getDescription()+
          " ["+thisMixerInfo.getName()+"]");
        Mixer thisMixer = AudioSystem.getMixer(thisMixerInfo);
        for (Line.Info thisLineInfo:thisMixer.getSourceLineInfo()) {
            if (thisLineInfo.getLineClass().getName().equals(
              "javax.sound.sampled.Port")) {
              Line thisLine = thisMixer.getLine(thisLineInfo);
              thisLine.open();
              System.out.println("  Source Port: "
                +thisLineInfo.toString());
              for (Control thisControl : thisLine.getControls()) {
                System.out.println(AnalyzeControl(thisControl));}
              thisLine.close();}}
        for (Line.Info thisLineInfo:thisMixer.getTargetLineInfo()) {
          if (thisLineInfo.getLineClass().getName().equals(
            "javax.sound.sampled.Port")) {
            Line thisLine = thisMixer.getLine(thisLineInfo);
            thisLine.open();
            System.out.println("  Target Port: "
              +thisLineInfo.toString());
            for (Control thisControl : thisLine.getControls()) {
              System.out.println(AnalyzeControl(thisControl));}
            thisLine.close();}}}
  } catch (Exception e) {e.printStackTrace();}}
  public static String AnalyzeControl(Control thisControl) {
    String type = thisControl.getType().toString();
    if (thisControl instanceof BooleanControl) {
      return "    Control: "+type+" (boolean)"; }
    if (thisControl instanceof CompoundControl) {
      System.out.println("    Control: "+type+
        " (compound - values below)");
      String toReturn = "";
      for (Control children:
        ((CompoundControl)thisControl).getMemberControls()) {
        toReturn+="  "+AnalyzeControl(children)+"\n";}
      return toReturn.substring(0, toReturn.length()-1);}
    if (thisControl instanceof EnumControl) {
      return "    Control:"+type+" (enum: "+thisControl.toString()+")";}
    if (thisControl instanceof FloatControl) {
      return "    Control: "+type+" (float: from "+
        ((FloatControl) thisControl).getMinimum()+" to "+
        ((FloatControl) thisControl).getMaximum()+")";}
    return "    Control: unknown type";}
}

All the application does is print out a line about the OS, a line about the JVM, and a few lines about the hardware found that may pertain to recording hardware. For example on my PC at work I get the following:

OS: Windows XP 5.1/x86
Java: 1.6.0_07 (Sun Microsystems Inc.)

Mixer: Direct Audio Device: DirectSound Playback [Primary Sound Driver]
Mixer: Direct Audio Device: DirectSound Playback [SoundMAX HD Audio]
Mixer: Direct Audio Device: DirectSound Capture [Primary Sound Capture Driver]
Mixer: Direct Audio Device: DirectSound Capture [SoundMAX HD Audio]
Mixer: Software mixer and synthesizer [Java Sound Audio Engine]
Mixer: Port Mixer [Port SoundMAX HD Audio]
  Source Port: MICROPHONE source port
    Control: Microphone (compound - values below)
      Control: Select (boolean)
      Control: Microphone Boost (boolean)
      Control: Front panel microphone (boolean)
      Control: Volume (float: from 0.0 to 1.0)
  Source Port: LINE_IN source port
    Control: Line In (compound - values below)
      Control: Select (boolean)
      Control: Volume (float: from 0.0 to 1.0)
      Control: Balance (float: from -1.0 to 1.0)

LastEditorDisplayName: sqook

OwnerDisplayName: McDowell


问:
Is there Android Intent concept in iPhone SDK
Just switching from Android to iPhone. In Android I can make several apps and use a tabView to call each app as intent.

In iPhone, I can make several apps. I need a tab to call each apps or app views. Is there similar concept as intent in iPhone? Just switched to iPhone, copying all the other projects into the tabbar does not work out. If you have other methods to solve, I really appreciate. Thanks,

答: The closest concept to an Intent on iOS is the handling of certain URLs by the system applications. See here. It was possible to register your own application URL schemes at one point (see this article), but I must admit I haven't tried this in recent SDKs (IIRC Glympse links can be opened in the Glympse app, so this technique probably still works).


问:
Multiline text to fit parent container in React JS
I am using a flexbox layout and am trying to get the text in a specific div to be resized to fit that div.

So for example, if I have code as follows:

```<code><div style={{display: "flex"}}>
   <div style={{flex: 1}}>
      A really, really, really, really long phrase here that will fit this div, and may wrap onto multiple lines if necessary. In this case it should fill half of the available space as the other div will cover the other half of the space.
   </div>
   <div style={{flex: 1}}>
      Some other text
   </div>
</div>
</code>```

In reality, the text will be pulled from a database, so will be dynamic in length.

How can I get the text in the first div to automatically adjust to fit the entire div?

Clarification: the div should stay a fixed size and only the text should be downsized to fit the div rather than overflowing the div.

Update

I have also posted a more specific question about a specific module called react-textfit not working the way I would expect it to work.

答:
```<code><div style={{ display: "flex" }}>
<div
    style={{
    flex: 1,
    backgroundColor: "lightGrey",
    wordBreak: "break-word"
    }}
>
    A really, really, really, really long phrase here that will fit this
    div, and may wrap onto multiple lines if necessary. In this case it
    should fill half of the available space as the other div will cover
    the other half of the space.
</div>
<div style={{ flex: 1, backgroundColor: "lightBlue" }}>
    Some other text
</div>
</div>
</code>```

Body:
I am using a flexbox layout and am trying to get the text in a specific div to be resized to fit that div.

So for example, if I have code as follows:

      A really, really, really, really long phrase here that will fit this div, and may wrap onto multiple lines if necessary. In this case it should fill half of the available space as the other div will cover the other half of the space.

      Some other text

In reality, the text will be pulled from a database, so will be dynamic in length.

How can I get the text in the first div to automatically adjust to fit the entire div?

Clarification: the div should stay a fixed size and only the text should be downsized to fit the div rather than overflowing the div.

Update

I have also posted a more specific question about a specific module called react-textfit not working the way I would expect it to work.


答:
The decimal data type is not a fixed point type with two decimals, it is a base ten flloating point.

You can use it to prevent only some specific forms of rounding errors that occur when converting a number that has an exact representation in base ten, to base two, such as 0.1

But 1075.75 / 9 = 119.5277777...

This is not a number that can be represented exactly in base 10 or in base 2, so you will get some (incredibly small) rounding error even with decimal.

But that is not actually your problem. You manually round the numbers with toString("c"). You round to 2 digits there in the output, but the calculations still use a lot more digits in the background.

So the remainder as well as the installment is 119.52777777777 and it all add up. When you round it to two digits afterwards, it looks like you are missing cents. If you want to calculate the remainder using the rounded installment, you have to round it yourself, using Math.Round()

Title: How to prevent currency rounding errors with decimal variable type?


问:
How to allocate memory to a pointer to pointer in a function
I want to allocate memory for char* pointer in a char** pointer while doing it in a function, what am I doing wrong?

```<code>int main(void)
{
    char** ar = NULL;

    inti(&ar);
    getchar();
    return 0;
}
void inti(char*** x)
{

    *x = (char**)calloc(sizeof(char*), 4);
}
</code>```

and I want to send on of the cell in x to another function that will calloc there memory for an array of chars how can I do the follow up function?

答:
May I recommend cutting out the middle man and doing the following? (Also, your calloc() args are backwards I believe).

char** inti() {
    char** c = calloc(4, sizeof(char*))

    for (int i = 0; i < 4; i++) {
        c[i] = malloc(/* length of string */);
    }

    return c;
}

int main(void) {
    char** ptrptr = inti();
}
```

Body:
I want to allocate memory for char* pointer in a char** pointer while doing it in a function, what am I doing wrong?

int main(void)
{
    char** ar = NULL;

    inti(&ar);
    getchar();
    return 0;
}
void inti(char*** x)
{

    *x = (char**)calloc(sizeof(char*), 4);
}

and I want to send on of the cell in x to another function that will calloc there memory for an array of chars how can I do the follow up function?


问:
AWS Lambda Layers: Failed to create layer version: Signature expired
My binary zip file is 40mb and after waiting for it to upload on AWS Lambda Layers I was encountered with the following message:

```<code>Failed to create layer version: Signature expired: 20190527T140335Z is now earlier than 20190527T140411Z (20190527T140911Z - 5 min.)
</code>```

Why is this happening and how to resolve this without uploading to S3?

答: ended up just uploading to s3 bucket, seems like theres no way around it.</p>

Body:
My binary zip file is 40mb and after waiting for it to upload on AWS Lambda Layers I was encountered with the following message:

Failed to create layer version: Signature expired: 20190527T140335Z is now earlier than 20190527T140411Z (20190527T140911Z - 5 min.)

Why is this happening and how to resolve this without uploading to S3?


问:
How can I create a correlation graph and legend in R?
In the code below, I would like to share the shape of the graph that changes when rho.AB is -0.9, 0 and 0.9, on a graph using a loop. And I want to express the legend as well. Please could you help me....

```<code>mu.A = 0.075
sig.A = 0.258
sig2.A = sig.A^2

mu.B = 0.055
sig.B = 0.115
sig2.B = sig.B^2

rho.AB = -0.164

sig.AB = rho.AB*sig.A*sig.B

x.A = seq(from=0.0, to=1.0, by=0.1)
x.B = 1 - x.A
mu.p = x.A*mu.A + x.B*mu.B
sig2.p = x.A^2 * sig2.A + x.B^2 * sig2.B + 2*x.A*x.B*sig.AB
sig.p = sqrt(sig2.p)

dev.new()
cex.val = 1.5
plot(sig.p, mu.p, type="b", pch=16, cex = cex.val,
     ylim=c(0.052, max(mu.p)), xlim=c(0.08, max(sig.p)+0.04),
     xlab=expression(sigma[p]), ylab=expression(mu[p]), cex.lab=cex.val)
</code>```

答:
If you want just a simple plot you can wrap your code in a for loop, looping over a vector of rho.AB values.

```<code>mu.A = 0.075
sig.A = 0.258
sig2.A = sig.A^2

mu.B = 0.055
sig.B = 0.115
sig2.B = sig.B^2

# Initialize a plotting window with the correct dimensions
plot(0, xlim=c(0.01, 0.26), ylim=c(mu.B, mu.A), cex=0, ann=FALSE)

for (rho.AB in seq(-0.9, 1, by=0.1)) {

    sig.AB = rho.AB*sig.A*sig.B

    x.A = seq(from=0.0, to=1.0, by=0.1)
    x.B = 1 - x.A
    mu.p = x.A*mu.A + x.B*mu.B
    sig2.p = x.A^2 * sig2.A + x.B^2 * sig2.B + 2*x.A*x.B*sig.AB
    sig.p = sqrt(sig2.p)

    # Every loop adds another plot
    lines(sig.p, mu.p, type="b", pch=16,
         xlab=expression(sigma[p]), ylab=expression(mu[p]), cex.lab=cex.val)
}
</code>```

But if you want a more fancy plot and more flexible options, you'd be better off making the code a function, and use [sl]apply() for looping through values and plotting the results.

```<code>wcov <- function(rho.AB=-0.9, mu.A=0.075, mu.B=0.055,
  sig.A=0.258, sig.B=0.115, x.A=seq(from=0.0, to=1.0, by=0.1)) {
    sig2.A <- sig.A^2
    sig2.B <- sig.B^2
    sig.AB <- rho.AB*sig.A*sig.B

    x.B <- 1 - x.A
    mu.p <- x.A*mu.A + x.B*mu.B
    sig2.p <- x.A^2 * sig2.A + x.B^2 * sig2.B + 2*x.A*x.B*sig.AB
    sig.p <- sqrt(sig2.p)
    data.frame(sig.p, mu.p)
}

# Loop over s values for rho.AB
s <- seq(-0.9, 1, by=0.2)
wcov.l <- lapply(s, function(x) wcov(rho.AB=x))
ltitle <- "Correlation"

# Find the extrema of sig.p and mu.p
xr <- range(sapply(wcov.l, function(x) range(x$sig.p)))
yr <- range(sapply(wcov.l, function(x) range(x$mu.p)))

# Set up the plotting window
par(mar=c(3, 3, 1, 1), mgp=c(1, 0.5, 0))
plot(0, xlim=xr, ylim=yr, cex=0, ann=FALSE)

# Define the colours we want to use
col <- rainbow(length(wcov.l), start=0.2, end=0.1)

# Loop over an index the length of wcov.l and use that index to plot
# each data.frame in wcov.l with a matching colour
l <- lapply(seq_along(wcov.l),
  function(x) {
      lines(wcov.l[[x]], col=col[x], type="o", pch=16, cex=0.8, lwd=1.5)
  }
)

# Add axis labels
mtext(c(expression(sigma[p]), expression(mu[p])),
  c(1, 2), c(2, 1.6), cex=1.5)

# Add legend, using the same s and col as before, making it all match
legend("topleft", legend=sprintf("%5.2f", s),
  bty="n", lty=1, col=col, lwd=1.5, pch=16, cex=0.8, title=ltitle, inset=0.02)
</code>```

One advantage of doing it like this is that you can loop over values of a different arguments by changing very little of the code. Eg:

```<code>s <- seq(0, 0.9, by=0.2)
wcov.l <- lapply(s, function(x) wcov(mu.A=x))
ltitle <- expression(Mean[A])
</code>```

And leaving the rest of the code as is, producing

Body:
In the code below, I would like to share the shape of the graph that changes when rho.AB is -0.9, 0 and 0.9, on a graph using a loop. And I want to express the legend as well. Please could you help me....

mu.A = 0.075
sig.A = 0.258
sig2.A = sig.A^2

mu.B = 0.055
sig.B = 0.115
sig2.B = sig.B^2

rho.AB = -0.164

sig.AB = rho.AB*sig.A*sig.B

x.A = seq(from=0.0, to=1.0, by=0.1)
x.B = 1 - x.A
mu.p = x.A*mu.A + x.B*mu.B
sig2.p = x.A^2 * sig2.A + x.B^2 * sig2.B + 2*x.A*x.B*sig.AB
sig.p = sqrt(sig2.p)

dev.new()
cex.val = 1.5
plot(sig.p, mu.p, type="b", pch=16, cex = cex.val,
     ylim=c(0.052, max(mu.p)), xlim=c(0.08, max(sig.p)+0.04),
     xlab=expression(sigma[p]), ylab=expression(mu[p]), cex.lab=cex.val)

Body:
If you want just a simple plot you can wrap your code in a for loop, looping over a vector of rho.AB values.

mu.A = 0.075
sig.A = 0.258
sig2.A = sig.A^2

mu.B = 0.055
sig.B = 0.115
sig2.B = sig.B^2

# Initialize a plotting window with the correct dimensions
plot(0, xlim=c(0.01, 0.26), ylim=c(mu.B, mu.A), cex=0, ann=FALSE)

for (rho.AB in seq(-0.9, 1, by=0.1)) {

    sig.AB = rho.AB*sig.A*sig.B

    x.A = seq(from=0.0, to=1.0, by=0.1)
    x.B = 1 - x.A
    mu.p = x.A*mu.A + x.B*mu.B
    sig2.p = x.A^2 * sig2.A + x.B^2 * sig2.B + 2*x.A*x.B*sig.AB
    sig.p = sqrt(sig2.p)

    # Every loop adds another plot
    lines(sig.p, mu.p, type="b", pch=16,
         xlab=expression(sigma[p]), ylab=expression(mu[p]), cex.lab=cex.val)
}

But if you want a more fancy plot and more flexible options, you'd be better off making the code a function, and use [sl]apply() for looping through values and plotting the results.

wcov <- function(rho.AB=-0.9, mu.A=0.075, mu.B=0.055,
  sig.A=0.258, sig.B=0.115, x.A=seq(from=0.0, to=1.0, by=0.1)) {
    sig2.A <- sig.A^2
    sig2.B <- sig.B^2
    sig.AB <- rho.AB*sig.A*sig.B

    x.B <- 1 - x.A
    mu.p <- x.A*mu.A + x.B*mu.B
    sig2.p <- x.A^2 * sig2.A + x.B^2 * sig2.B + 2*x.A*x.B*sig.AB
    sig.p <- sqrt(sig2.p)
    data.frame(sig.p, mu.p)
}

# Loop over s values for rho.AB
s <- seq(-0.9, 1, by=0.2)
wcov.l <- lapply(s, function(x) wcov(rho.AB=x))
ltitle <- "Correlation"

# Find the extrema of sig.p and mu.p
xr <- range(sapply(wcov.l, function(x) range(x$sig.p)))
yr <- range(sapply(wcov.l, function(x) range(x$mu.p)))

# Set up the plotting window
par(mar=c(3, 3, 1, 1), mgp=c(1, 0.5, 0))
plot(0, xlim=xr, ylim=yr, cex=0, ann=FALSE)

# Define the colours we want to use
col <- rainbow(length(wcov.l), start=0.2, end=0.1)

# Loop over an index the length of wcov.l and use that index to plot
# each data.frame in wcov.l with a matching colour
l <- lapply(seq_along(wcov.l),
  function(x) {
      lines(wcov.l[[x]], col=col[x], type="o", pch=16, cex=0.8, lwd=1.5)
  }
)

# Add axis labels
mtext(c(expression(sigma[p]), expression(mu[p])),
  c(1, 2), c(2, 1.6), cex=1.5)

# Add legend, using the same s and col as before, making it all match
legend("topleft", legend=sprintf("%5.2f", s),
  bty="n", lty=1, col=col, lwd=1.5, pch=16, cex=0.8, title=ltitle, inset=0.02)

One advantage of doing it like this is that you can loop over values of a different arguments by changing very little of the code. Eg:

s <- seq(0, 0.9, by=0.2)
wcov.l <- lapply(s, function(x) wcov(mu.A=x))
ltitle <- expression(Mean[A])

And leaving the rest of the code as is, producing


问:
filtering data frame based on NA on multiple columns
I have the following data frame lets call it df, with the following observations:

```<code>id   type   company
1    NA      NA
2    NA      ADM
3    North   Alex
4    South   NA
NA   North   BDA
6    NA      CA
</code>```

I want to retain only the records which do not have NA in column "type" and "company".

```<code>id   type   company
3    North   Alex
NA   North   BDA
</code>```

I tried:

```<code> df_non_na <- df[!is.na(df$company) || !is.na(df$type), ]
</code>```

But this did not work.

Thanks in advance

答:
Using dplyr, you can also use the filter_at function

```<code>library(dplyr)
df_non_na <- df %>% filter_at(vars(type,company),all_vars(!is.na(.)))
</code>```

all_vars(!is.na(.)) means that all the variables listed need to be not NA.

If you want to keep rows that have at least one value, you could do:

```<code>df_non_na <- df %>% filter_at(vars(type,company),any_vars(!is.na(.)))
</code>```

Body:
I have the following data frame lets call it df, with the following observations:

id   type   company
1    NA      NA
2    NA      ADM
3    North   Alex
4    South   NA
NA   North   BDA
6    NA      CA

I want to retain only the records which do not have NA in column "type" and "company".

id   type   company
3    North   Alex
NA   North   BDA

I tried:

 df_non_na <- df[!is.na(df$company) || !is.na(df$type), ]

But this did not work.

Thanks in advance

Body:
Using dplyr, you can also use the filter_at function

library(dplyr)
df_non_na <- df %>% filter_at(vars(type,company),all_vars(!is.na(.)))

all_vars(!is.na(.)) means that all the variables listed need to be not NA.

If you want to keep rows that have at least one value, you could do:

df_non_na <- df %>% filter_at(vars(type,company),any_vars(!is.na(.)))


问:
Best way to use google recaptcha V3 in django
First I should say that I've read this, and It is not what I need. I want to have forms that I made with html/css not django forms.

And my method is based on this, that is actually in PHP.

I wrote code and it works fine, but I believe there should be a better way to do it.

The summery of code is that I submit my form, post the data and google recaptcha token to my function, and then do some process on it, then to redirect to the relative page base on results of processes, I return the url and status to jQuery again, and redirect to that page using jQuery.

Here is my code:

login.html:

```<code><script src="https://www.google.com/recaptcha/api.js?render=here is recaptcha public key"></script>
<!-- login form and etc -->

<script>
$('#loginForm').submit(function() {
    // stop what loginform is going to do
    event.preventDefault();
    var username = $('#username').val();
    var password = $("#password").val();
    grecaptcha.ready(function () {
      grecaptcha.execute("here is recaptcha public key",
         {action: "{% url 'basic_app:login_page' %}"}).then(function (token_id)
              {$('#loginForm').prepend('<input type="hidden" name="g-recaptcha-response" value="' + token_id + '">');
                $.post("{% url 'basic_app:login' %}",  // url
                   {username: username,password: password,
                    token_id: token_id,csrfmiddlewaretoken: '{{ csrf_token }}'},
                       function( result ){
                            console.log(result);
                            if(result.status == 0) {
                                    window.location.replace(result.url)
                            } else if (result.status == 1){
                                    window.location.replace(result.url)
                            }
                        },
                'json');
          });
      });
  });
</code>```

views.py:

```<code>def user_login(request):
    if request.method == "POST":
        username = request.POST.get('username')
        password = request.POST.get('password')
        token_id = request.POST.get('token_id')
        if(token_id):
            secretKey = "here is recaptcha secret key"
            data = {
                'secret': secretKey,
                'response': token
            }
            r = requests.post('https://www.google.com/recaptcha/api/siteverify', data=data)
            result = r.json()
            ....
            ## some codes for more security
            ....
            response = {'status': 0, 'message':"", 'url': '/'}
            return HttpResponse(json.dumps(response), content_type='application/json')
        else:
            response = {'status': 0, 'message':"", 'url': '/login_page'}
            return HttpResponse(json.dumps(response), content_type='application/json')

....
</code>```

is there any security problem in this method ?

and is there any way to write a better code to use recaptcha V3 ?
thank you.

答:
Better steps:

When user click submit, prevent default behaviour

inside onSubmit, execute the g-recaptcha and store token inside form

the call this.submit() or form.submit() like in the tutorial below

validate the captcha in your view.

How to Implement Google Recaptcha v3 on your django app


问:
JavaScript: Get image dimensions
I only have a URL to an image. I need to determine the height and width of this image using only JavaScript. The image cannot be visible to the user on the page. How can I get its dimensions?</p>

答:
Make a new Image

```<code>var img = new Image();
</code>```

Set the src

```<code>img.src = your_src
</code>```

Get the width and the height

```<code>//img.width
//img.height
</code>```

Title: JavaScript: Get image dimensions

Body:
Make a new Image

var img = new Image();

Set the src

img.src = your_src

Get the width and the height

//img.width
//img.height


问:
Add items dynamically to List<Integer> and convert to Integer[] Array
I have 2 arrays of strings

```<code>  String[] s = {"Light", "Sun", "Sun", "Water"};
  String[] ss = {"on", "off", "on", "off"};
</code>```

which I want to convert to an array of integers to assign pictures from my resource later.
Therefor the strings gets checked by switch statement to assign a specific  integer value:

```<code>  for(int i = 0; i < s.length; i++)
  {
  switch (components[i]) {

            case "Light":
                  if (ss[i]=="on")
                    I.add(1);
                  else
                    I.add(2);
            case "Sun":
                  if (ss[i]=="on")
                    I.add(3);
                  else
                    I.add(4);
            case "Water":
                  if (ss[i]=="on")
                    I.add(5);
                  else
                    I.add(6);
            case "Gravel":
                  if (ss[i]=="on")
                    I.add(7);
                  else
                    I.add(8);
            }
         }
  }
</code>```

Because i cannot add values dynamically to an array, i decided to create an List of Integers first, and convert it to an integer array later:

```<code>  List<Integer> I = new ArrayList<Integer>();
  [...]
  Integer[] arr = I.toArray(new Integer[I.size()]);
</code>```

But Instead of my expected result:

```<code>{"1", "4", "3", "6"}
</code>```

i will get always an sequence of numbers as result:

```<code>{"1", "2", "3", "4"}
</code>```

It seems like I'm doing something wrong with the converting?

Here the complete code:

```<code>  public static Integer[] toImg(String[] s, String[] ss) {

        List<Integer> I = new ArrayList<Integer>();

           for(int i = 0; i < s.length; i++)
  {
  switch (components[i]) {

            case "Light":
                  if (ss[i]=="on")
                    I.add(1);
                  else
                    I.add(2);
            case "Sun":
                  if (ss[i]=="on")
                    I.add(3);
                  else
                    I.add(4);
            case "Water":
                  if (ss[i]=="on")
                    I.add(5);
                  else
                    I.add(6);
            case "Gravel":
                  if (ss[i]=="on")
                    I.add(7);
                  else
                    I.add(8);
            }
         }

        Integer[] arr = I.toArray(new Integer[I.size()]);
        return arr;
  }
</code>```

答:
what is components array in your code?? if you really need to return an array, you are better going to use for loop to add elements from collection - it will look more transparent. Don't forget that strings in switch statement cannot be null.
In conclusion you can use IntStream to move elements, if you want to

Body:
I have 2 arrays of strings

  String[] s = {"Light", "Sun", "Sun", "Water"};
  String[] ss = {"on", "off", "on", "off"};

which I want to convert to an array of integers to assign pictures from my resource later.
Therefor the strings gets checked by switch statement to assign a specific  integer value:

  for(int i = 0; i < s.length; i++)
  {
  switch (components[i]) {

            case "Light":
                  if (ss[i]=="on")
                    I.add(1);
                  else
                    I.add(2);
            case "Sun":
                  if (ss[i]=="on")
                    I.add(3);
                  else
                    I.add(4);
            case "Water":
                  if (ss[i]=="on")
                    I.add(5);
                  else
                    I.add(6);
            case "Gravel":
                  if (ss[i]=="on")
                    I.add(7);
                  else
                    I.add(8);
            }
         }
  }

Because i cannot add values dynamically to an array, i decided to create an List of Integers first, and convert it to an integer array later:

  List<Integer> I = new ArrayList<Integer>();
  [...]
  Integer[] arr = I.toArray(new Integer[I.size()]);

But Instead of my expected result:

{"1", "4", "3", "6"}

i will get always an sequence of numbers as result:

{"1", "2", "3", "4"}

It seems like I'm doing something wrong with the converting?

Here the complete code:

  public static Integer[] toImg(String[] s, String[] ss) {

        List<Integer> I = new ArrayList<Integer>();

           for(int i = 0; i < s.length; i++)
  {
  switch (components[i]) {

            case "Light":
                  if (ss[i]=="on")
                    I.add(1);
                  else
                    I.add(2);
            case "Sun":
                  if (ss[i]=="on")
                    I.add(3);
                  else
                    I.add(4);
            case "Water":
                  if (ss[i]=="on")
                    I.add(5);
                  else
                    I.add(6);
            case "Gravel":
                  if (ss[i]=="on")
                    I.add(7);
                  else
                    I.add(8);
            }
         }

        Integer[] arr = I.toArray(new Integer[I.size()]);
        return arr;
  }