问:
Firebase Cloud Firestore get auto-id of newly created document
I have created a user with the following code, however since the Document ID of the user is randomly generated, I would like to store the DocumentReference in a variable after it has been created.  How could I do this?</p>

```<code>FirebaseFirestore db = FirebaseFirestore.getInstance();

// Create a new user with a first, middle, and last name
Map<String, Object> user = new HashMap<>();
user.put("username", "username");
user.put("first", "Firstname");
user.put("last", "Lastname");
user.put("born", 1990);

// Add a new document with a generated ID
db.collection("users")
        .add(user)
        .addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
            @Override
            public void onSuccess(DocumentReference documentReference) {
                Log.d(TAG, "DocumentSnapshot added with ID: " + documentReference.getId());

            }

        })
        .addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                Log.w(TAG, "Error adding document", e);
                return null;
            }
        });
</code>```

答:
you can create a new document and save its id, then set the data on that id that will work the same as you asked for.try the following code.</p>

```<code>db = FirebaseFirestore.getInstance();
String id = db.collection("users").document().getId();
db.collection("users").document(id).set(user)
  .addOnSuccessListener(new OnSuccessListener<Void>() {
       @Override
       public void onSuccess(Void aVoid) {
       //your success code here
       }})
  .addOnFailureListener(new OnFailureListener() {
       @Override
       public void onFailure(@NonNull Exception e) {

       }});
</code>```

Body:
I have created a user with the following code, however since the Document ID of the user is randomly generated, I would like to store the DocumentReference in a variable after it has been created.  How could I do this?

FirebaseFirestore db = FirebaseFirestore.getInstance();

// Create a new user with a first, middle, and last name
Map<String, Object> user = new HashMap<>();
user.put("username", "username");
user.put("first", "Firstname");
user.put("last", "Lastname");
user.put("born", 1990);

// Add a new document with a generated ID
db.collection("users")
        .add(user)
        .addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
            @Override
            public void onSuccess(DocumentReference documentReference) {
                Log.d(TAG, "DocumentSnapshot added with ID: " + documentReference.getId());

            }

        })
        .addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                Log.w(TAG, "Error adding document", e);
                return null;
            }
        });

Body:
you can create a new document and save its id, then set the data on that id that will work the same as you asked for.try the following code.

db = FirebaseFirestore.getInstance();
String id = db.collection("users").document().getId();
db.collection("users").document(id).set(user)
  .addOnSuccessListener(new OnSuccessListener<Void>() {
       @Override
       public void onSuccess(Void aVoid) {
       //your success code here
       }})
  .addOnFailureListener(new OnFailureListener() {
       @Override
       public void onFailure(@NonNull Exception e) {

       }});


来源: stackexchange

问:
how can get particular day of date when you have start and end date
I have a start date 4/10/2021 and end date 4/12/2021

I want get Tuesday, Thursday and Friday date in jquery

I found this solution:

```<code>var x = new Date();
//set the financial year starting date
x.setFullYear(2021, 10, 04);

//set the next financial year starting date
var y = new Date();
y.setFullYear(2021, 12, 04);
var j = 1;
var count = 0;

//getting the all fridays in a financial year
for ( var i = 0; x<y; i += j) {
    if (x.getDay() == 5) {
       $("#append_text").append("Date : " + x.getDate() + "/"
                        + (x.getMonth() + 1) + "<br>");
       x = new Date(x.getTime() + (7 * 24 * 60 * 60 * 1000));
       j = 7;
       count++;
    } else {
       j = 1;
       x = new Date(x.getTime() + (24 * 60 * 60 * 1000));
    }
}
$("#append_text").append("total fridays : " + count + "<br>");
</code>```

but it return only Friday and i think it doesn't work truly

The result is:

```<code>Date : 5/11
Date : 12/11
Date : 19/11
Date : 26/11
Date : 3/12
Date : 10/12
Date : 17/12
Date : 24/12
Date : 31/12
total fridays : 9
</code>```

The solution link is here:
Get Friday Dates of Year in javascript using jquery

do you have any solution for that?

答:
Try this.

var start = new Date(2021, 10, 04);
var end = new Date(2021, 12, 04);

var tuesdays = [], thursdays = [], fridays = [];

for (var current = start; current <= end; current.setDate(current.getDate() + 1)) {

  var day = current.getDay();
  switch (day) {
    case 2: // tuesdays
      tuesdays.push(formatDate(current));
      break;
    case 4: // thursdays
      thursdays.push(formatDate(current));
      break;
    case 6: // fridays
      fridays.push(formatDate(current));
      break;
    default: //other dates
      break;
  }
}

function formatDate(d) { // formats date to dd/mm/yyy
  return d.getDate() + '/' + (d.getMonth() + 1) + '/' + d.getFullYear();
}
console.log(tuesdays.length + " Tuesdays: ", tuesdays.join('\t'));
console.log(thursdays.length + " Thursdays: ", thursdays.join('\t'));
console.log(fridays.length + " Fridays: ", fridays.join('\t'));```

ContentLicense: CC BY-SA 4.0

Body:
I have a start date 4/10/2021 and end date 4/12/2021

I want get Tuesday, Thursday and Friday date in jquery

I found this solution:

var x = new Date();
//set the financial year starting date
x.setFullYear(2021, 10, 04);

//set the next financial year starting date
var y = new Date();
y.setFullYear(2021, 12, 04);
var j = 1;
var count = 0;

//getting the all fridays in a financial year
for ( var i = 0; x<y; i += j) {
    if (x.getDay() == 5) {
       $("#append_text").append("Date : " + x.getDate() + "/"
                        + (x.getMonth() + 1) + "
");
       x = new Date(x.getTime() + (7 * 24 * 60 * 60 * 1000));
       j = 7;
       count++;
    } else {
       j = 1;
       x = new Date(x.getTime() + (24 * 60 * 60 * 1000));
    }
}
$("#append_text").append("total fridays : " + count + "
");

but it return only Friday and i think it doesn't work truly

The result is:

Date : 5/11
Date : 12/11
Date : 19/11
Date : 26/11
Date : 3/12
Date : 10/12
Date : 17/12
Date : 24/12
Date : 31/12
total fridays : 9

The solution link is here:
Get Friday Dates of Year in javascript using jquery

do you have any solution for that?


问:
Measuring the actual blocking time of python socket recv() for receiving Ack after setting a timeout
I did not get expected result in the Retransmission delay computation. I have included the python code snippet below,

```<code>s.send(base64.b64encode(ciphertext))
try:
s.settimeout(0.01)
t = perf_counter()
print(s.recv(1024).decode('ascii'))
t2 = perf_counter()
tt = round((t2-t)*1000,2)
print('Delay is:' ,tt)

except socket.timeout as e:
print(e)
</code>```

Theoretically, tt has to be <=10ms (+1ms for print & decode) otherwise s.recv() has to throw exception. But getting values till 25 ms in debian operating system. Other methods like time(), process_time() also are not giving expected results.

Thanks in Advance !!

答:
You're not timing the recv alone, you're timing that plus a print operation, which will take some time.  Try it without the print and see if that makes a difference.

This is not necessarily the problem, but it's a reasonable thing to try first.

Body:
I did not get expected result in the Retransmission delay computation. I have included the python code snippet below,

s.send(base64.b64encode(ciphertext))
try:
s.settimeout(0.01)
t = perf_counter()
print(s.recv(1024).decode('ascii'))
t2 = perf_counter()
tt = round((t2-t)*1000,2)
print('Delay is:' ,tt)

except socket.timeout as e:
print(e)

Theoretically, tt has to be <=10ms (+1ms for print & decode) otherwise s.recv() has to throw exception. But getting values till 25 ms in debian operating system. Other methods like time(), process_time() also are not giving expected results.

Thanks in Advance !!


问:
How can i set state value after destructing in React Hooks?
I tried to destructure and set the value in state using React Hooks,but their it shows a syntax error.Since i am new on react JS,please help me for the solution.

Following below is my code:

I set the state as following:

```<code>const [Datasets, setDatasets] = useState({
  labels: [],
  datasets: [{
      label: 'Total Cases',
      fill: false,
      lineTension: 0.5,
      backgroundColor: 'rgba(100,19,12,1)',
      borderColor: 'green',
      borderWidth: 2,
      data: []
    },
    {
      label: 'Total Recovered',
      fill: false,
      lineTension: 0.5,
      backgroundColor: 'rgba(75,192,192,1)',
      borderColor: 'rgba(0,0,0,1)',
      borderWidth: 2,
      data: []
    },
    {
      label: 'Total Deaths',
      fill: false,
      lineTension: 0.5,
      backgroundColor: 'rgba(75,192,192,1)',
      borderColor: 'rgba(0,0,0,1)',
      borderWidth: 2,
      data: []
    }
  ]
})
</code>```

I used useEffect to fetch data from API and set state.Following are my codes on useEffect:

```<code>useEffect(() => {
  axios.get('https://data.nepalcorona.info/api/v1/covid/timeline')
    .then(res => {
      setTimelinedata(res.data)
      setDatasets({ ...Datasets, labels: res.data.map((item) => item.date) })
      setDatasets([Datasets.datasets[0].data: res.data.map((item) => item.totalCases)])
        .catch(err => {
          console.log("error>>", err);
        })
    })
</code>```

when i try to run the code the  error is shown in the following code:

```<code>setDatasets([Datasets.datasets[0].data: res.data.map((item) => item.totalCases)])
</code>```

following error is shown:

following are the data i have fetched from the API:

Please help me for the solution.

答:
Unlike class-based components' setState, the functional components' useState hook does not merge state updates into existing state, this needs to be done manually.

NOTE: Don't forget to add a dependency array so the effect isn't triggered each render by the state update and cause an infinite loop. Empty array will trigger the effect when the component mounts, but you can add others if you need to update dataset later after component has been mounted, similar to componentDidUpdate lifecycle function from class-based components.

```<code>useEffect(() => {
  axios.get('https://data.nepalcorona.info/api/v1/covid/timeline')
    .then(res => {
      setTimelinedata(res.data)
      setDatasets(Datasets => { // <-- Use a functional state update since next state could depend on previous state
        const labels = [
          ...Datasets.labels, // spread in existing labels
          ...res.data.map((item) => item.date) // spread in new labels
        ];

        const datasets = [
          ...Datasets.datasets, // spread in existing datasets
        ];

        // Now you can copy the total cases into the first index.
        datasets[0].data = res.data.map((item) => item.totalCases);

        return {
          ...Datasets, // spread in existing state
          labels,
          datasets,
        };
      });
    .catch(err => {
      console.log("error>>", err);
    });
}, []); // <-- Empty dependency array to run once, on mount
</code>```

Body:
I tried to destructure and set the value in state using React Hooks,but their it shows a syntax error.Since i am new on react JS,please help me for the solution.

Following below is my code:

I set the state as following:

const [Datasets, setDatasets] = useState({
  labels: [],
  datasets: [{
      label: 'Total Cases',
      fill: false,
      lineTension: 0.5,
      backgroundColor: 'rgba(100,19,12,1)',
      borderColor: 'green',
      borderWidth: 2,
      data: []
    },
    {
      label: 'Total Recovered',
      fill: false,
      lineTension: 0.5,
      backgroundColor: 'rgba(75,192,192,1)',
      borderColor: 'rgba(0,0,0,1)',
      borderWidth: 2,
      data: []
    },
    {
      label: 'Total Deaths',
      fill: false,
      lineTension: 0.5,
      backgroundColor: 'rgba(75,192,192,1)',
      borderColor: 'rgba(0,0,0,1)',
      borderWidth: 2,
      data: []
    }
  ]
})

I used useEffect to fetch data from API and set state.Following are my codes on useEffect:

useEffect(() => {
  axios.get('https://data.nepalcorona.info/api/v1/covid/timeline')
    .then(res => {
      setTimelinedata(res.data)
      setDatasets({ ...Datasets, labels: res.data.map((item) => item.date) })
      setDatasets([Datasets.datasets[0].data: res.data.map((item) => item.totalCases)])
        .catch(err => {
          console.log("error>>", err);
        })
    })

when i try to run the code the  error is shown in the following code:

setDatasets([Datasets.datasets[0].data: res.data.map((item) => item.totalCases)])

following error is shown:

following are the data i have fetched from the API:

Please help me for the solution.

Body:
Unlike class-based components' setState, the functional components' useState hook does not merge state updates into existing state, this needs to be done manually.

NOTE: Don't forget to add a dependency array so the effect isn't triggered each render by the state update and cause an infinite loop. Empty array will trigger the effect when the component mounts, but you can add others if you need to update dataset later after component has been mounted, similar to componentDidUpdate lifecycle function from class-based components.

useEffect(() => {
  axios.get('https://data.nepalcorona.info/api/v1/covid/timeline')
    .then(res => {
      setTimelinedata(res.data)
      setDatasets(Datasets => { // <-- Use a functional state update since next state could depend on previous state
        const labels = [
          ...Datasets.labels, // spread in existing labels
          ...res.data.map((item) => item.date) // spread in new labels
        ];

        const datasets = [
          ...Datasets.datasets, // spread in existing datasets
        ];

        // Now you can copy the total cases into the first index.
        datasets[0].data = res.data.map((item) => item.totalCases);

        return {
          ...Datasets, // spread in existing state
          labels,
          datasets,
        };
      });
    .catch(err => {
      console.log("error>>", err);
    });
}, []); // <-- Empty dependency array to run once, on mount


问:
What are the benefits of using the real image height and width?
What are the benefits to using an images real height and width when rendering HTML?  That is if I have an image that 100x100 pixels but I want to display something that is 95x95 pixels, should I resize the image on the server or can I let the browser handle this?  I'm really looking for a general rule along with the reason.  Thanks.</p>

```<code><img src="image.jpg" style="width: 95px; height: 95px;" alt="an image" />
</code>```

答:
if the sizes are significantly different then you should have a large versin and a small version:

like in your example, 100px and 95px shouldnt be a big deal but lets say you have large images and you want to display thumbnails it will be better to create multiple versions of the images.

The advantage will be:
1 - faster download time when you just want to show thumbnails.
2 - More consistency on different browsers
3 - I am sure people can add at least another 100 advantages in here

ContentLicense: CC BY-SA 3.0


问:
system exception using try-catch
So I have a problem with making an exception. I am making a hangman game where the user needs to input a letter (box with guess) but I only want that they can give in letters from A-Z and no numbers.

In the code that I wrote, I give the box with guess the name choosed_lettre and convert it to "letter".

Question:

- How can I make the exception that it only takes letters and no numbers?

Code:

```<code> private void Choosed_lettre_KeyDown_1(object sender, KeyEventArgs e)
        {
            char letter = ' ';
            bool validation = false;
            if (e.Key == Key.Enter && choosed_lettre.Text != "")
            {
                do
                {
                    try //trycatch
                    {
                        string input = Convert.ToString(choosed_lettre.Text);
                        input = input.ToLower();
                        letter = Convert.ToChar(input[0]);
                        validation = true;
                    }
                    catch (SystemException)
                    {
                        choosed_lettre.Text = "";
                        return;
                    }
                } while (validation == false && !((letter >= 'a' && letter <= 'z') && (letter >= 0 && letter <= 9)));
            }
</code>```

wpfscreen:

答:
Welcome to SO!

Better if you use a TextInput handler instead:

```<code>public MainWindow()
{
    InitializeComponent();
    this.TextInput += MainWindow_TextInput;
}

private void MainWindow_TextInput(object sender, TextCompositionEventArgs e)
{
    var isLetter = Char.IsLetter(e.Text, 0);
    // do something here
}
</code>```

Title: system exception using try-catch

Body:
So I have a problem with making an exception. I am making a hangman game where the user needs to input a letter (box with guess) but I only want that they can give in letters from A-Z and no numbers.

In the code that I wrote, I give the box with guess the name choosed_lettre and convert it to "letter".

Question:

- How can I make the exception that it only takes letters and no numbers?

Code:

 private void Choosed_lettre_KeyDown_1(object sender, KeyEventArgs e)
        {
            char letter = ' ';
            bool validation = false;
            if (e.Key == Key.Enter && choosed_lettre.Text != "")
            {
                do
                {
                    try //trycatch
                    {
                        string input = Convert.ToString(choosed_lettre.Text);
                        input = input.ToLower();
                        letter = Convert.ToChar(input[0]);
                        validation = true;
                    }
                    catch (SystemException)
                    {
                        choosed_lettre.Text = "";
                        return;
                    }
                } while (validation == false && !((letter >= 'a' && letter <= 'z') && (letter >= 0 && letter <= 9)));
            }

wpfscreen:

Body:
Welcome to SO!

Better if you use a TextInput handler instead:

public MainWindow()
{
    InitializeComponent();
    this.TextInput += MainWindow_TextInput;
}

private void MainWindow_TextInput(object sender, TextCompositionEventArgs e)
{
    var isLetter = Char.IsLetter(e.Text, 0);
    // do something here
}


问:
How to hide a text and make it accessible by screen reader?
I have a simple text that gets updated on an action and I want that to be announced by the screen reader. But I don't want that text to be visible on the web page. I tried display: none and visibility: hidden, but seems like they are not accessible by the screen reader softwares. I found a way to make this work - that is by absolute positioning the element all the way with negative 999999 value which will make it off screen and hidden from the webpage. I am not really a fan of this solution. Is there a more elegant way to achieve this?

```<code><span class="aria-invisible" aria-live="polite">5 selections have been made.</span>

.aria-invisible {
   display: none; //either of these two attributes
   visibility: hidden;
}
</code>```

答:
Using aria-label attributes is the way to do (example below)

Is there a more elegant way to achieve this?

Do not hide the element. Yes. I am not answering your question, but I am addressing the problem.

Screenreaders are only a subpart of assistive technologies used by a small part of people targeted by accessibility guidelines.

Imagine using a screen magnifier for instance where you do not have a global view on the full screen. Imagine having some cognitive disabilities which makes difficult for you to count or remember elements.

If you do consider that an information is important for blind people, then it's surely is for them AND for other people.

Now, instead of it being a long text, it can be a small counter with appropriate aria labelling:

```<code><div role="status" aria-live="polite" aria-label="5 selections have been made.">
  5 selections
</div>
</code>```

Body:
I have a simple text that gets updated on an action and I want that to be announced by the screen reader. But I don't want that text to be visible on the web page. I tried display: none and visibility: hidden, but seems like they are not accessible by the screen reader softwares. I found a way to make this work - that is by absolute positioning the element all the way with negative 999999 value which will make it off screen and hidden from the webpage. I am not really a fan of this solution. Is there a more elegant way to achieve this?

5 selections have been made.

.aria-invisible {
   display: none; //either of these two attributes
   visibility: hidden;
}

Body:
Using aria-label attributes is the way to do (example below)

Is there a more elegant way to achieve this?

Do not hide the element. Yes. I am not answering your question, but I am addressing the problem.

Screenreaders are only a subpart of assistive technologies used by a small part of people targeted by accessibility guidelines.

Imagine using a screen magnifier for instance where you do not have a global view on the full screen. Imagine having some cognitive disabilities which makes difficult for you to count or remember elements.

If you do consider that an information is important for blind people, then it's surely is for them AND for other people.

Now, instead of it being a long text, it can be a small counter with appropriate aria labelling:

<div role="status" aria-live="polite" aria-label="5 selections have been made.">
  5 selections
</div>


问:
How do I control the amount of times something is added to a list?
I have a list, and I am trying to add a certain amount of variables to it:

```<code>newList = ["Andrew", "Ben", "Happy"]
SecondList = [2,3,1]
BestList = []
for g in range(0,3):
    BestList.append((newList[g])*(int(SecondList[g])))
print (len(BestList))
print (BestList)
</code>```

The problem is I want the "Andrew" variable to be appended to the list 2 times, but instead, it is appended to the list only once, but as "AndrewAndrew". How do I fix my code in a way where instead of multiplying "Andrew" twice and adding it to the list as that one variable, it is added to the list twice. My end goal is for the length of BestList to be 6.

Thanks in advance.

答:
The problem is that you are multiplying the string with the integer value. As in mathematics, this is interpreted as "Andrew" * 2 = "Andrew" + "Andrew", which is equal to "AndrewAndrew".

To get the behaviour you're looking for you can introduce another for loop. Also, beware that for i in range(...) and using indexing for list list[i] is considered unpythonic. A better way would be to directly iterate over the list entries.

```<code>newList = ["Andrew", "Ben", "Happy"]
SecondList = [2,3,1]
BestList = []
for name, amount in zip(newList, SecondList):
    for _ in range(amount):
        BestList.append(name)

print (len(BestList))
print (BestList)
</code>```

Body:
I have a list, and I am trying to add a certain amount of variables to it:

newList = ["Andrew", "Ben", "Happy"]
SecondList = [2,3,1]
BestList = []
for g in range(0,3):
    BestList.append((newList[g])*(int(SecondList[g])))
print (len(BestList))
print (BestList)

The problem is I want the "Andrew" variable to be appended to the list 2 times, but instead, it is appended to the list only once, but as "AndrewAndrew". How do I fix my code in a way where instead of multiplying "Andrew" twice and adding it to the list as that one variable, it is added to the list twice. My end goal is for the length of BestList to be 6.

Thanks in advance.

Body:
The problem is that you are multiplying the string with the integer value. As in mathematics, this is interpreted as "Andrew" * 2 = "Andrew" + "Andrew", which is equal to "AndrewAndrew".

To get the behaviour you're looking for you can introduce another for loop. Also, beware that for i in range(...) and using indexing for list list[i] is considered unpythonic. A better way would be to directly iterate over the list entries.

newList = ["Andrew", "Ben", "Happy"]
SecondList = [2,3,1]
BestList = []
for name, amount in zip(newList, SecondList):
    for _ in range(amount):
        BestList.append(name)

print (len(BestList))
print (BestList)


问:
Unable to connect to server: FATAL: password authentication failed for user "xxxx" FATAL: password authentication failed for user "xxxx"
I'm building a Django app and I'm trying to create a connection from AWS. The password is right and the hostname/address but after connecting it, it says

"Unable to connect to server:  FATAL: password authentication failed for user 'xxxx'"

Here's a screenshot of the error: https://prnt.sc/sqziuq

Other screenshots for another details of the connection:

https://prnt.sc/sqzm9z

https://prnt.sc/sqzlx7

答: I just tried resetting my credentials in AWS and waited the status of my database to be available after modifying it.</p>


问:
Flutter, how to launch specific screen from FCM background message
I need to launch a specific screen in flutter when I get notification from  FCM while app killed/background from native I see this link
Launch screen from native background service but I can't achieve it, any help please.</p>

答:
I was having this issue and I fixed it by adding "click_action": 'FLUTTER_NOTIFICATION_CLICK' to my data payload in my cloud function. Then in my android/app AndroidManifest.xml, inside the <activity> tag I added:

```<code><intent-filter>
<action android:name="FLUTTER_NOTIFICATION_CLICK" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</code>```

Body:
I was having this issue and I fixed it by adding "click_action": 'FLUTTER_NOTIFICATION_CLICK' to my data payload in my cloud function. Then in my android/app AndroidManifest.xml, inside the <activity> tag I added:

<intent-filter>
<action android:name="FLUTTER_NOTIFICATION_CLICK" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>


问:
Reactive Data Issues in RShiny
I'm working on a Shiny dashboard for a personal project with some football stats. Whenever I change the statistic to be graphed and/or the filter, I get the same players that were in the first dataset. For example, when I start the app, the app creates a graph of the top ten rushers in school history with a filter of rushing attempts >= 0. When I change the statistic selection to rushing average, however, those ten players are the ones shown, which is incorrect. </p>

```<code>library(readxl)
library(tidyverse)
library(purrr)
library(shiny)

interface <- fluidPage(
    titlePanel(" "),
    sidebarLayout(
        sidebarPanel(
            h1("Stats!"),
            selectInput("stat_selection",
                        label = "Select a season statistics",
                        choices = c("Rushing Yards",
                                    "Rushing Touchdowns",
                                    "Rushing Average",
                                    "Reciving Yards",
                                    "Receptions",
                                    "Receiving Touchdowns",
                                    "Receiving Average"),
                        selected = "Rushing Yards"),
            selectInput("filter_input",
                        label = "Select a statistic to filter by",
                        choices = c("Rushing Yards",
                                    "Rushing Touchdowns",
                                    "Rushing Average",
                                    "Rushing Attempts",
                                    "Reciving Yards",
                                    "Receptions",
                                    "Receiving Touchdowns",
                                    "Receiving Average"),
                        selected = "Rushing Attempts"),
            numericInput("filter_number",
                         label = "Type a number for the filter (>=)",
                         value = 0, min = 0),
            actionButton("button", "Graph")),
        mainPanel(
            plotOutput("plot_button"),
            tableOutput("table_button")
        )
    )
)

server_osu <- function(input, output) {
    dataInput <- reactive({
        switch(input$stat_selection,
               "Rushing Yards" = rush_yds,
               "Rushing Touchdowns" = rush_tds,
               "Rushing Average" = rush_avg,
               "Reciving Yards" = rec_yds,
               "Receptions" = rec_rec,
               "Receiving Touchdowns" = rec_td,
               "Receiving Average" = rec_avg)
    })
    filterInput <- reactive({
        switch(input$filter_input,
               "Rushing Yards" = rush_yds,
               "Rushing Touchdowns" = rush_tds,
               "Rushing Average" = rush_avg,
               "Rushing Attempts" = rush_att,
               "Reciving Yards" = rec_yds,
               "Receptions" = rec_rec,
               "Receiving Touchdowns" = rec_td,
               "Receiving Average" = rec_avg)
    })
    filter_number <- reactive(as.double(input$filter_number))
    table_button_react <- eventReactive(input$button, {
        dataset <- dataInput()
        val <- filter_number()
        colnames(dataset)[1] = "Player and Season"
        dataset_filter <- filterInput()
        colnames(dataset_filter)[1] = "Player and Season"
        dataset <- left_join(dataset, dataset_filter)
        colnames(dataset)[1] = "Player and Season"
        og <- colnames(dataset)[3]
        colnames(dataset)[3] = "filter"
        original <- colnames(dataset)[2]
        colnames(dataset)[2] = 'selected'
        dataset <- dataset %>%
            filter(filter >= val)
        dataset <- dataset %>%
            top_n(10) %>%
            arrange(-selected)
        colnames(dataset)[2] = original
        colnames(dataset)[3] = og
        dataset
    })
    plot_button_react <- eventReactive(input$button, {
        dataset <- dataInput()
        val <- filter_number()
        colnames(dataset)[1] = "Player and Season"
        dataset_filter <- filterInput()
        colnames(dataset_filter)[1] = "Player and Season"
        dataset <- left_join(dataset, dataset_filter)
        colnames(dataset)[1] = "Player and Season"
        colnames(dataset)[2] = "selected"
        colnames(dataset)[3] = "filter"
        dataset <- dataset %>%
            filter(filter >= val)
        top_ten <- dataset %>% top_n(10)
        min = min(top_ten$selected)
        max = max(top_ten$selected)
        ggplot(top_ten, aes(x = reorder(`Player and Season`, -selected), y = selected)) +
            geom_bar(stat = 'identity') + theme_minimal() + xlab('SEASON') +
            ylab(input$stat_selection) + theme(text=element_text(size=16)) +
            scale_fill_manual(values = c('#BBBBBB', '#BB0000')) +
            theme(axis.text.x = element_text(angle = 45, hjust = 1)) +
            theme(legend.position = 'none') +
            coord_cartesian(ylim=c(min - 0.05*min, max + 0.05*max)) +
            theme(axis.title.y = element_text(margin = margin(t = 0, r = 10, b = 0, l = 10))) +
            theme(axis.title.x = element_text(margin = margin(t = 10, r = 0, b = 10, l = 0))) +
            theme(axis.text.y = element_text(size=14),
                  axis.title=element_text(size=16,face='bold')) +
            labs(caption = '')
    })
    output$plot_button <- renderPlot({
        plot_button_react()
    })
    output$table_button <- renderTable({
        table_button_react()
    })
}
</code>```

答:
As I mentioned above, a reprex - including input data - would help us to help you.  That said, I think the problem is that your XXX_button_reacts depend only on input$button.  They don't depend on input$stat_selection, input$filter_number or input$filter_input.  That's why they don't update as you want them to.

The fix is easy.  Just add them (in a call to req() if you like) at the top of each XXXX_button_react, for example:

```<code>plot_button_react <- eventReactive(input$button, {
  input$stat_selection
  input$filter_number
  input$filter_input

  <your code here>
})
</code>```

As a point of style, I feel it's better to separate data generation from data presentation.  It makes the logic of your code more obvious, reduces the chance of errors, reduces the need for code duplication and makes your code more reusable.

In your case, I would create a reactive that holds the data you wish to tablulate and plot and then reference that reactive in each of your render_XXXX functions.  That would also remove the need for your input$button: the plot and graph would each update automatically whenever you changed one of your other input widgets.

Title: Reactive Data Issues in RShiny

Body:
I'm working on a Shiny dashboard for a personal project with some football stats. Whenever I change the statistic to be graphed and/or the filter, I get the same players that were in the first dataset. For example, when I start the app, the app creates a graph of the top ten rushers in school history with a filter of rushing attempts >= 0. When I change the statistic selection to rushing average, however, those ten players are the ones shown, which is incorrect.

library(readxl)
library(tidyverse)
library(purrr)
library(shiny)

interface <- fluidPage(
    titlePanel(" "),
    sidebarLayout(
        sidebarPanel(
            h1("Stats!"),
            selectInput("stat_selection",
                        label = "Select a season statistics",
                        choices = c("Rushing Yards",
                                    "Rushing Touchdowns",
                                    "Rushing Average",
                                    "Reciving Yards",
                                    "Receptions",
                                    "Receiving Touchdowns",
                                    "Receiving Average"),
                        selected = "Rushing Yards"),
            selectInput("filter_input",
                        label = "Select a statistic to filter by",
                        choices = c("Rushing Yards",
                                    "Rushing Touchdowns",
                                    "Rushing Average",
                                    "Rushing Attempts",
                                    "Reciving Yards",
                                    "Receptions",
                                    "Receiving Touchdowns",
                                    "Receiving Average"),
                        selected = "Rushing Attempts"),
            numericInput("filter_number",
                         label = "Type a number for the filter (>=)",
                         value = 0, min = 0),
            actionButton("button", "Graph")),
        mainPanel(
            plotOutput("plot_button"),
            tableOutput("table_button")
        )
    )
)

server_osu <- function(input, output) {
    dataInput <- reactive({
        switch(input$stat_selection,
               "Rushing Yards" = rush_yds,
               "Rushing Touchdowns" = rush_tds,
               "Rushing Average" = rush_avg,
               "Reciving Yards" = rec_yds,
               "Receptions" = rec_rec,
               "Receiving Touchdowns" = rec_td,
               "Receiving Average" = rec_avg)
    })
    filterInput <- reactive({
        switch(input$filter_input,
               "Rushing Yards" = rush_yds,
               "Rushing Touchdowns" = rush_tds,
               "Rushing Average" = rush_avg,
               "Rushing Attempts" = rush_att,
               "Reciving Yards" = rec_yds,
               "Receptions" = rec_rec,
               "Receiving Touchdowns" = rec_td,
               "Receiving Average" = rec_avg)
    })
    filter_number <- reactive(as.double(input$filter_number))
    table_button_react <- eventReactive(input$button, {
        dataset <- dataInput()
        val <- filter_number()
        colnames(dataset)[1] = "Player and Season"
        dataset_filter <- filterInput()
        colnames(dataset_filter)[1] = "Player and Season"
        dataset <- left_join(dataset, dataset_filter)
        colnames(dataset)[1] = "Player and Season"
        og <- colnames(dataset)[3]
        colnames(dataset)[3] = "filter"
        original <- colnames(dataset)[2]
        colnames(dataset)[2] = 'selected'
        dataset <- dataset %>%
            filter(filter >= val)
        dataset <- dataset %>%
            top_n(10) %>%
            arrange(-selected)
        colnames(dataset)[2] = original
        colnames(dataset)[3] = og
        dataset
    })
    plot_button_react <- eventReactive(input$button, {
        dataset <- dataInput()
        val <- filter_number()
        colnames(dataset)[1] = "Player and Season"
        dataset_filter <- filterInput()
        colnames(dataset_filter)[1] = "Player and Season"
        dataset <- left_join(dataset, dataset_filter)
        colnames(dataset)[1] = "Player and Season"
        colnames(dataset)[2] = "selected"
        colnames(dataset)[3] = "filter"
        dataset <- dataset %>%
            filter(filter >= val)
        top_ten <- dataset %>% top_n(10)
        min = min(top_ten$selected)
        max = max(top_ten$selected)
        ggplot(top_ten, aes(x = reorder(`Player and Season`, -selected), y = selected)) +
            geom_bar(stat = 'identity') + theme_minimal() + xlab('SEASON') +
            ylab(input$stat_selection) + theme(text=element_text(size=16)) +
            scale_fill_manual(values = c('#BBBBBB', '#BB0000')) +
            theme(axis.text.x = element_text(angle = 45, hjust = 1)) +
            theme(legend.position = 'none') +
            coord_cartesian(ylim=c(min - 0.05*min, max + 0.05*max)) +
            theme(axis.title.y = element_text(margin = margin(t = 0, r = 10, b = 0, l = 10))) +
            theme(axis.title.x = element_text(margin = margin(t = 10, r = 0, b = 10, l = 0))) +
            theme(axis.text.y = element_text(size=14),
                  axis.title=element_text(size=16,face='bold')) +
            labs(caption = '')
    })
    output$plot_button <- renderPlot({
        plot_button_react()
    })
    output$table_button <- renderTable({
        table_button_react()
    })
}

Body:
As I mentioned above, a reprex - including input data - would help us to help you.  That said, I think the problem is that your XXX_button_reacts depend only on input$button.  They don't depend on input$stat_selection, input$filter_number or input$filter_input.  That's why they don't update as you want them to.

The fix is easy.  Just add them (in a call to req() if you like) at the top of each XXXX_button_react, for example:

plot_button_react <- eventReactive(input$button, {
  input$stat_selection
  input$filter_number
  input$filter_input

  <your code here>
})

As a point of style, I feel it's better to separate data generation from data presentation.  It makes the logic of your code more obvious, reduces the chance of errors, reduces the need for code duplication and makes your code more reusable.

In your case, I would create a reactive that holds the data you wish to tablulate and plot and then reference that reactive in each of your render_XXXX functions.  That would also remove the need for your input$button: the plot and graph would each update automatically whenever you changed one of your other input widgets.


问:
Write a C function to evaluate the series // sin(x) = x-(x3 /3!)+(x5 /5!)-(x7 /7!)+... // up to 10 terms
```<code>#include <stdio.h>
#include<math.h>

int series(float,float);

int main()

{

    float x,n,series_value;
    printf("Enter the value of x: ");
    scanf("%f",&x);
    printf("\nEnter the value of n: ");
    scanf("%f",&n);
    series_value=series(x,n);
    printf("\nValue of series sin (%.2f) is: %f\n",x,series_value);
    return 0;
}

int series(float x,float n)

{

    int i,sum=0,sign=-1;
    int j,fact=1,p=1;
    for (i=1; i<=(2*n)-1; i+=2)
    {
        for (j=1; j<=i; j++)
        {
        p=p*x;
        fact=fact*j;
        }
        sign=-1*sign;
        sum=sum + sign*p/fact;
    }
    return (sum);
}
</code>```

Output:
Enter the value of x: 5

Enter the value of n: 10
(lldb)
and this message
Thread 1: EXC_ARITHMETIC (code=EXC_I386_DIV, subcode=0x0)
![Thread 1 Queue : com.apple.main-thread (serial)
]1

Why is this message coming? and what is wrong in the program as answer is not coming right

答:
maybe its due to floating-point exception as u have declared that the function should return int type value
int series(float,float);//hear
so u can try editing the return type of this function as float
Note:-also u need to change at function definition and the datatype of
  int i,sum=0,sign=-1;
    int j,fact=1,p=1;
to float as it is returning the value (sum) which should also be float

Body:
#include <stdio.h>
#include<math.h>

int series(float,float);

int main()

{

    float x,n,series_value;
    printf("Enter the value of x: ");
    scanf("%f",&x);
    printf("\nEnter the value of n: ");
    scanf("%f",&n);
    series_value=series(x,n);
    printf("\nValue of series sin (%.2f) is: %f\n",x,series_value);
    return 0;
}

int series(float x,float n)

{

    int i,sum=0,sign=-1;
    int j,fact=1,p=1;
    for (i=1; i<=(2*n)-1; i+=2)
    {
        for (j=1; j<=i; j++)
        {
        p=p*x;
        fact=fact*j;
        }
        sign=-1*sign;
        sum=sum + sign*p/fact;
    }
    return (sum);
}

Output:
Enter the value of x: 5

Enter the value of n: 10
(lldb)
and this message
Thread 1: EXC_ARITHMETIC (code=EXC_I386_DIV, subcode=0x0)
![Thread 1 Queue : com.apple.main-thread (serial)
]1

Why is this message coming? and what is wrong in the program as answer is not coming right


问:
How to create a summary table to use in model pandas python
I have the following dataset

```<code># Import pandas library
import pandas as pd
import numpy as np

# initialize list of lists
data = [['tom', 10,1], ['tom', 15,5], ['tom', 14,1], ['tom', 15,4], ['tom', 18,1], ['tom', 15,6], ['tom', 17,3]
       , ['tom', 14,7], ['tom',16 ,6], ['tom', 22,2],['matt', 10,1], ['matt', 15,5], ['matt', 14,1], ['matt', 15,4], ['matt', 18,1], ['matt', 15,6], ['matt', 17,3]
       , ['matt', 14,7], ['matt',16 ,6], ['matt', 22,2]]

# Create the pandas DataFrame
df = pd.DataFrame(data, columns = ['Name', 'Attempts','Score'])
print(df)
   Name  Attempts  Score
0    tom        10      1
1    tom        15      5
2    tom        14      1
3    tom        15      4
4    tom        18      1
5    tom        15      6
6    tom        17      3
7    tom        14      7
8    tom        16      6
9    tom        22      2
10  matt        10      1
11  matt        15      5
12  matt        14      1
13  matt        15      4
14  matt        18      1
15  matt        15      6
16  matt        17      3
17  matt        14      7
18  matt        16      6
19  matt        22      2
</code>```

The i added some custom metrics to get the previous 3 and 5 moving averages for the column Attempts:

```<code>#AVE TIME OF LAST 3/5 Attempts
df['Ave3Attempts']=df.groupby('Name').Attempts.apply(lambda x : x.shift().rolling(3,min_periods=1).mean().fillna(x))
df['Ave5Attempts']=df.groupby('Name').Attempts.apply(lambda x : x.shift().rolling(5,min_periods=1).mean().fillna(x))
print(df.round(2))

    Name  Attempts  Score  Ave3Attempts  Ave5Attempts
0    tom        10      1         10.00          10.0
1    tom        15      5         10.00          10.0
2    tom        14      1         12.50          12.5
3    tom        15      4         13.00          13.0
4    tom        18      1         14.67          13.5
5    tom        15      6         15.67          14.4
6    tom        17      3         16.00          15.4
7    tom        14      7         16.67          15.8
8    tom        16      6         15.33          15.8
9    tom        22      2         15.67          16.0
10  matt        10      1         10.00          10.0
11  matt        15      5         10.00          10.0
12  matt        14      1         12.50          12.5
13  matt        15      4         13.00          13.0
14  matt        18      1         14.67          13.5
15  matt        15      6         15.67          14.4
16  matt        17      3         16.00          15.4
17  matt        14      7         16.67          15.8
18  matt        16      6         15.33          15.8
19  matt        22      2         15.67          16.0
</code>```

I have then used this set to create a model to predict Score through sklearn train/test using those Ave3Attempts  and Ave5Attempts columns.

Now that I have my model I am trying to create a summary table of the most recent data for each person to then look up to predict the score

Essentially trying to produce a new dataframe to then use as part of a new prediction:

```<code>      Name    Ave3Attempts  Ave5Attempts
0    tom         17.33          16.8
1    matt        17.33          16.8
</code>```

Any help on how to do this would be great! thanks!

答:
You can use this code:

df2 = pd.DataFrame([], index=df['Name'].unique())
# looping through names
for name in df['Name'].unique():
    df2.loc[name, "Ave3Attempts"] = df[ df['Name']==name ]['Attempts'].tail(3).mean()
    df2.loc[name, "Ave5Attempts"] = df[ df['Name']==name ]['Attempts'].tail(5).mean()
print(df2)
```

Body:
I have the following dataset

# Import pandas library
import pandas as pd
import numpy as np

# initialize list of lists
data = [['tom', 10,1], ['tom', 15,5], ['tom', 14,1], ['tom', 15,4], ['tom', 18,1], ['tom', 15,6], ['tom', 17,3]
       , ['tom', 14,7], ['tom',16 ,6], ['tom', 22,2],['matt', 10,1], ['matt', 15,5], ['matt', 14,1], ['matt', 15,4], ['matt', 18,1], ['matt', 15,6], ['matt', 17,3]
       , ['matt', 14,7], ['matt',16 ,6], ['matt', 22,2]]

# Create the pandas DataFrame
df = pd.DataFrame(data, columns = ['Name', 'Attempts','Score'])
print(df)
   Name  Attempts  Score
0    tom        10      1
1    tom        15      5
2    tom        14      1
3    tom        15      4
4    tom        18      1
5    tom        15      6
6    tom        17      3
7    tom        14      7
8    tom        16      6
9    tom        22      2
10  matt        10      1
11  matt        15      5
12  matt        14      1
13  matt        15      4
14  matt        18      1
15  matt        15      6
16  matt        17      3
17  matt        14      7
18  matt        16      6
19  matt        22      2

The i added some custom metrics to get the previous 3 and 5 moving averages for the column Attempts:

#AVE TIME OF LAST 3/5 Attempts
df['Ave3Attempts']=df.groupby('Name').Attempts.apply(lambda x : x.shift().rolling(3,min_periods=1).mean().fillna(x))
df['Ave5Attempts']=df.groupby('Name').Attempts.apply(lambda x : x.shift().rolling(5,min_periods=1).mean().fillna(x))
print(df.round(2))

    Name  Attempts  Score  Ave3Attempts  Ave5Attempts
0    tom        10      1         10.00          10.0
1    tom        15      5         10.00          10.0
2    tom        14      1         12.50          12.5
3    tom        15      4         13.00          13.0
4    tom        18      1         14.67          13.5
5    tom        15      6         15.67          14.4
6    tom        17      3         16.00          15.4
7    tom        14      7         16.67          15.8
8    tom        16      6         15.33          15.8
9    tom        22      2         15.67          16.0
10  matt        10      1         10.00          10.0
11  matt        15      5         10.00          10.0
12  matt        14      1         12.50          12.5
13  matt        15      4         13.00          13.0
14  matt        18      1         14.67          13.5
15  matt        15      6         15.67          14.4
16  matt        17      3         16.00          15.4
17  matt        14      7         16.67          15.8
18  matt        16      6         15.33          15.8
19  matt        22      2         15.67          16.0

I have then used this set to create a model to predict Score through sklearn train/test using those Ave3Attempts  and Ave5Attempts columns.

Now that I have my model I am trying to create a summary table of the most recent data for each person to then look up to predict the score

Essentially trying to produce a new dataframe to then use as part of a new prediction:

      Name    Ave3Attempts  Ave5Attempts
0    tom         17.33          16.8
1    matt        17.33          16.8

Any help on how to do this would be great! thanks!


问:
Is it crazy to use Azure for Intranet Site containing sensitive data
is it absolute insanity to start hosting new intranet web apps in Azure using an on-premise sql instance and ADFS 2.0 (via Azure Connect)? My concern is that instead of the site being behind a firewall, being hosted in Azure has the side effect of anyone who discovers the URL can hack away at it.

Thoughts???

thanks

答:
There's good news on the ADFS 2.0 front.

Authentication with ADFS 2.0 requires the client's browser to be able to communicate with the application server and the ADFS 2.0 server. There's no direct connection between Azure and ADFS 2.0.

If you make sure that your ADFS 2.0 server is only accessible from your corporate network or via VPN, you've already closed one of the major attack vectors; no brute force or dictionary attack is going to help a bad guy in if they can't connect to your authentication service.

As well as all-important security, take into consideration the bandwidth costs for your hybrid cloud solution. You'll be paying for every byte to and from your SQL Server.


问:
Haskell Higher Order Functions and Associativity
I'm learning FP and have a few confusion after playing around with GHCi.

Say I have 2 simple functions:

twice :: (a -> a) -> (a -> a)
twice f a = f (f a) -- Equation 1

double :: Int -> Int
double = \x -> x * 2
```

<p>Decomposing the evaluation <code>twice twice twice double 3</code> (note that 3x<code>twice</code>+1x<code>double</code>), I would have:</p>

<pre class="lang-hs prettyprint-override"><code>{-
   twice twice twice double 3
== (twice twice twice double) 3
== (twice twice (twice double)) 3
== (twice (twice (double double 3)))
== (twice ((double double) (double double 3)))
== (((double double) (double double)) ((double double) (double double 3)))
== 768
-}
</code>```

Is this correct?

According to this, if my definition of twice is changed as twice f a = f f a -- Equation 2, I should decompose the evaluation, with left associativity, as:

{-
   twice (twice twice double) 3
== (twice twice double) (twice twice double) 3
== ((twice double)(twice double)) ((twice double)(twice double)) 3
== ((double double)(double double)) ((double double)(double double)) 3
== (double (double (double (double (double (double (double (double 3 ) ) ) ) ) ) )
== 768
-}
```

<p>right?</p>

<ul>
<li>However, the strangest part is GHC REPL gave me the answer of <code>196608</code> (2^16*3):</li>
</ul>

```> twice twice twice double 3
196608
```

which then makes me so confusing. Where would I make the mistake?
Thanks.

答:
Assume that n is a natural number and g n is defined as follows, informally:

```<code>g n = \f x -> f (f (f (.... (f x))))  -- n times f on x
</code>```

In your case, twice f x = g 2 f x.

Then, one can prove that

```<code>g n (g m) f x = g (m^n) f x
</code>```

Indeed,

```<code>g n (g m) f x =
(g m (g m (g m (g m .... (g m f))))) x =  -- n times (g m) on f
</code>```

so it's taking the "m-times repeated f" function, and then repeating that m times to form another function, and then repeating that m-times again, ... Each step multiplies the number of applications of f by m, so we get m^n.

Back to your case

```<code>twice twice twice double 3 =
g 2 (g 2) (g 2) double 3 =
g (2^2) (g 2) double 3 =
g (2^(2^2)) double 3 =
double (double (double .... 3)) -- 2^(2^2) = 2^4 = 16 times
</code>```

So, we are getting 3 doubled 16 times, obtaining 3 * 2^16 = 196608.

Body:
I'm learning FP and have a few confusion after playing around with GHCi.

Say I have 2 simple functions:

twice :: (a -> a) -> (a -> a)
twice f a = f (f a) -- Equation 1

double :: Int -> Int
double = \x -> x * 2

Decomposing the evaluation twice twice twice double 3 (note that 3xtwice+1xdouble), I would have:

{-
   twice twice twice double 3
== (twice twice twice double) 3
== (twice twice (twice double)) 3
== (twice (twice (double double 3)))
== (twice ((double double) (double double 3)))
== (((double double) (double double)) ((double double) (double double 3)))
== 768
-}

Is this correct?

According to this, if my definition of twice is changed as twice f a = f f a -- Equation 2, I should decompose the evaluation, with left associativity, as:

{-
   twice (twice twice double) 3
== (twice twice double) (twice twice double) 3
== ((twice double)(twice double)) ((twice double)(twice double)) 3
== ((double double)(double double)) ((double double)(double double)) 3
== (double (double (double (double (double (double (double (double 3 ) ) ) ) ) ) )
== 768
-}

right?

However, the strangest part is GHC REPL gave me the answer of 196608 (2^16*3):

> twice twice twice double 3
196608

which then makes me so confusing. Where would I make the mistake?
Thanks.

Body:
Assume that n is a natural number and g n is defined as follows, informally:

g n = \f x -> f (f (f (.... (f x))))  -- n times f on x

In your case, twice f x = g 2 f x.

Then, one can prove that

g n (g m) f x = g (m^n) f x

Indeed,

g n (g m) f x =
(g m (g m (g m (g m .... (g m f))))) x =  -- n times (g m) on f

so it's taking the "m-times repeated f" function, and then repeating that m times to form another function, and then repeating that m-times again, ... Each step multiplies the number of applications of f by m, so we get m^n.

Back to your case

twice twice twice double 3 =
g 2 (g 2) (g 2) double 3 =
g (2^2) (g 2) double 3 =
g (2^(2^2)) double 3 =
double (double (double .... 3)) -- 2^(2^2) = 2^4 = 16 times

So, we are getting 3 doubled 16 times, obtaining 3 * 2^16 = 196608.


问:
After downloading "Windows SDK Installer for windows 10" i cannot find the inspect tool in Windows Kits folder
I have downloaded windows SDK Installer from the following URL "https://developer.microsoft.com/en-us/windows/downloads/windows-10-sdk/"

I have downloaded in my downloads folder. when I open the windows kits folder> 10 > Windows SDK, I can only see the following folders. Here there is no inspect tool. Can anyone know the solution for this problem.

After opening the windows SDK the folder structure looks like :
          Installers (Folder)
          Redistributable (Folder)
          User Experience manifest (XML Document)
          WinsdksetUp (Application)

答:
Look in C:\Program Files (x86)\Windows Kits\10\bin\<version>\<platform>

As per msdn, you might be better off with Accessibility Insights as the modern replacement.


问:
Make bigger svg circle
I have an example of svg circle. But I dont know how to make bigger it in radius. I need this example cuz there are border-gradient with transperent inside. And I need not six parts, I need 12 parts. Please can somebody help me with it?

  <svg style="margin-top: 100px" width="300" height="300">
    <linearGradient id="linearColors1" x1="0" y1="0" x2="1" y2="1">
       <stop offset="0%" stop-color="#01E400"></stop>
       <stop offset="100%" stop-color="#FEFF01"></stop>
    </linearGradient>
    <linearGradient id="linearColors2" x1="0.5" y1="0" x2="0.5" y2="1">
       <stop offset="0%" stop-color="#FEFF01"></stop>
       <stop offset="100%" stop-color="#FF7E00"></stop>
    </linearGradient>
    <linearGradient id="linearColors3" x1="1" y1="0" x2="0" y2="1">
       <stop offset="0%" stop-color="#FF7E00"></stop>
       <stop offset="100%" stop-color="#FB0300"></stop>
    </linearGradient>
    <linearGradient id="linearColors4" x1="1" y1="1" x2="0" y2="0">
       <stop offset="0%" stop-color="#FB0300"></stop>
       <stop offset="100%" stop-color="#9B004A"></stop>
    </linearGradient>
    <linearGradient id="linearColors5" x1="0.5" y1="1" x2="0.5" y2="0">
       <stop offset="0%" stop-color="#9B004A"></stop>
       <stop offset="100%" stop-color="#7D0022"></stop>
    </linearGradient>
    <linearGradient id="linearColors6" x1="0" y1="1" x2="1" y2="0">
       <stop offset="0%" stop-color="#7D0022"></stop>
       <stop offset="100%" stop-color="#01E400"></stop>
    </linearGradient>
   <path d="M150 10 a120 120 0 0 1 103.9230 60"
        fill="none" stroke="url(#linearColors1)" stroke-width="20" />
  <path d="M253.9230 70 a120 120 0 0 1 0 120"
        fill="none" stroke="url(#linearColors2)" stroke-width="20" />
  <path d="M253.9230 190 a120 120 0 0 1 -103.9230 60"
        fill="none" stroke="url(#linearColors3)" stroke-width="20" />
  <path d="M150 250 a120 120 0 0 1 -103.9230 -60"
        fill="none" stroke="url(#linearColors4)" stroke-width="20" />
  <path d="M46.077 190 a120 120 0 0 1 0 -120"
        fill="none" stroke="url(#linearColors5)" stroke-width="20" />
  <path d="M46.077 70 a120 120 0 0 1 103.9230 -60"
        fill="none" stroke="url(#linearColors6)" stroke-width="20" />
</svg>

```

答:
You can achieve the same using only CSS but the support isn't very good since I will rely on conic-gradient:

.box {
  display:inline-block;
  width:200px;
  border-radius:50%;
  background:conic-gradient(red,blue,orange,yellow,green,red);
  -webkit-mask:radial-gradient(farthest-side,transparent calc(100% - 21px),#fff calc(100% - 20px));
          mask:radial-gradient(farthest-side,transparent calc(100% - 21px),#fff calc(100% - 20px));
}
.box::before {
  content:"";
  display:inline-block;
  padding-top:100%;
}

body {
  background:#f2f2f3;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="box"></div>

<div class="box" style="width:150px;"></div>

<div class="box" style="width:100px;"></div></code>```

Related for more examples: CSS Only Pie Chart - How to add spacing/padding between slices?

Title: Make bigger svg circle

Body:
You can achieve the same using only CSS but the support isn't very good since I will rely on conic-gradient:

.box {
  display:inline-block;
  width:200px;
  border-radius:50%;
  background:conic-gradient(red,blue,orange,yellow,green,red);
  -webkit-mask:radial-gradient(farthest-side,transparent calc(100% - 21px),#fff calc(100% - 20px));
          mask:radial-gradient(farthest-side,transparent calc(100% - 21px),#fff calc(100% - 20px));
}
.box::before {
  content:"";
  display:inline-block;
  padding-top:100%;
}

body {
  background:#f2f2f3;
}

<div class="box"></div>

<div class="box" style="width:150px;"></div>

<div class="box" style="width:100px;"></div>

Related for more examples: CSS Only Pie Chart - How to add spacing/padding between slices?


问:
What is the correct syntax for echoing i in list (integer) bash?
I am trying to iterate through a list of numbers and (treating them as integers) put any numbers between the first search and the second search into a separate list.

I've tried a range of things including using round brackets, using quotes, etc.

```<code>#!/bin/bash
first_search_item=3
second_search_item=6
lib=''
jim='1 2 3 4 5 6 7 8 9'
for i in jim;
do
  if [[ ${first_search_item} -le ${i} ]] && [[ ${i} -ge ${second_search_item} ]] ;
  then
    lib+=($i)
    echo $i
  fi
done
echo $lib
exit 0
</code>```

The lib should be 3 4 5 6, but I keep getting syntax errors.

This time, the syntax error is :

```<code>error token is "2 3 4 5 6 7 8 9"
</code>```

答:
Just replace line 6:

```<code>for i in jim;
</code>```

with this:

```<code>for i in $jim;
</code>```

That will fix your problem.

And I recommend you this Shell Style Guide: https://google.github.io/styleguide/shellguide.html

Body:
I am trying to iterate through a list of numbers and (treating them as integers) put any numbers between the first search and the second search into a separate list.

I've tried a range of things including using round brackets, using quotes, etc.

#!/bin/bash
first_search_item=3
second_search_item=6
lib=''
jim='1 2 3 4 5 6 7 8 9'
for i in jim;
do
  if [[ ${first_search_item} -le ${i} ]] && [[ ${i} -ge ${second_search_item} ]] ;
  then
    lib+=($i)
    echo $i
  fi
done
echo $lib
exit 0

The lib should be 3 4 5 6, but I keep getting syntax errors.

This time, the syntax error is :

error token is "2 3 4 5 6 7 8 9"

Body:
Just replace line 6:

for i in jim;

with this:

for i in $jim;

That will fix your problem.

And I recommend you this Shell Style Guide: https://google.github.io/styleguide/shellguide.html


问:
Remove everything after the first whitespace in pandas dataframe
Here is the dataframe:

```<code>     State  RegionName
0    NY     New York
1    CA     Los Angeles
2    IL     Chicago 865
3    PA     Philadelphia Wrin
4    AZ     Phoenix City
</code>```

I want the output to look like this:

```<code>     State   RegionName
0    NY      New
1    CA      Los
2    IL      Chicago
3    PA      Philadelphia
4    AZ      Phoenix
</code>```

How to do it without using for loops ??

答:
Here's an alternative using pd.Series.str.extract

```<code>df['RegionName'] = df['RegionName'].str.extract(r'(.*)\s')
</code>```

But my first instinct would be to use what @jezrael mentioned.

Regex demo

Body:
Here is the dataframe:

     State  RegionName
0    NY     New York
1    CA     Los Angeles
2    IL     Chicago 865
3    PA     Philadelphia Wrin
4    AZ     Phoenix City

I want the output to look like this:

     State   RegionName
0    NY      New
1    CA      Los
2    IL      Chicago
3    PA      Philadelphia
4    AZ      Phoenix

How to do it without using for loops ??

Body:
Here's an alternative using pd.Series.str.extract

df['RegionName'] = df['RegionName'].str.extract(r'(.*)\s')

But my first instinct would be to use what @jezrael mentioned.

Regex demo


答:
plenty bugs. To do not caclulate the fact values all the time they are in the lookup table

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

double series(double,int);

long long fact[] = { 1, 2, 6, 24,
                     120, 720, 5040, 40320,
                     362880, 3628800, 39916800, 479001600,
                     6227020800, 87178291200, };

double mypow(double x, unsigned p)
{
    double result = x;
    while(p && --p)
        result *= x;
    return result;
}

int main()
{
    for(double x = 0; x <= M_PI + M_PI / 60; x += M_PI / 30)
        printf("Value of series sin (%.2f) is: %f\n",x,series(x, 5));
    fflush(stdout);
}

double series(double x,int n)
{
    double sum = x;
    int i,sign=1;
    for (i=3; i<=(2*n)-1; i+=2)
    {
        sign=-1*sign;
        sum += sign*(mypow(x, i)/fact[i -1]);
    }
    return (sum);
}
</code>```

https://godbolt.org/z/U6dULN

Title: Write a C function to evaluate the series // sin(x) = x-(x3 /3!)+(x5 /5!)-(x7 /7!)+... // up to 10 terms

Body:
plenty bugs. To do not caclulate the fact values all the time they are in the lookup table

#include <stdio.h>
#include <math.h>

double series(double,int);

long long fact[] = { 1, 2, 6, 24,
                     120, 720, 5040, 40320,
                     362880, 3628800, 39916800, 479001600,
                     6227020800, 87178291200, };

double mypow(double x, unsigned p)
{
    double result = x;
    while(p && --p)
        result *= x;
    return result;
}

int main()
{
    for(double x = 0; x <= M_PI + M_PI / 60; x += M_PI / 30)
        printf("Value of series sin (%.2f) is: %f\n",x,series(x, 5));
    fflush(stdout);
}

double series(double x,int n)
{
    double sum = x;
    int i,sign=1;
    for (i=3; i<=(2*n)-1; i+=2)
    {
        sign=-1*sign;
        sum += sign*(mypow(x, i)/fact[i -1]);
    }
    return (sum);
}

https://godbolt.org/z/U6dULN


问:
How to count python list members more efficiently
i have created a list of words used in spam emails having  320571 entries. now i need to find out the frequency of each word.I have written the following code but it takes too much time(very very very much).

```<code>%%time
flat_ui=[]
for i in range(len(biggie_spam)):
    temp=biggie_spam.count(biggie_spam[i])
    flat_ui.append(temp)
</code>```

how can this be done more efficiently?

答:
You can implement a solution using a map-reduce approach. Here you have a simple example of a word count algorithm using the map-reduce algorithm in Python.

You can find plenty of information, but this tutorial could be a starting point.

Body:
i have created a list of words used in spam emails having  320571 entries. now i need to find out the frequency of each word.I have written the following code but it takes too much time(very very very much).

%%time
flat_ui=[]
for i in range(len(biggie_spam)):
    temp=biggie_spam.count(biggie_spam[i])
    flat_ui.append(temp)

how can this be done more efficiently?


问:
Adding claims to DRF simple JWT payload
Using djangorestframework_simplejwt library, when POST to a custom view

```<code>#urls.py
path('api/token/', MyTokenObtainPairView.as_view(), name='token_obtain'),

#views.py
class MyTokenObtainPairView(TokenObtainPairView):
    serializer_class = MyTokenObtainPairSerializer
</code>```

I'm able to get a the following access token

```<code>eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNTkwOTEwNjg0LCJqdGkiOiI3M2MxYmZkOWNmMGY0ZjI3OTY4MGY0ZjhlYjA1NDQ5NyIsInVzZXJfaWQiOjExfQ.5vs0LmNGseU6rtq3vuQyApupxhQM3FBAoKAq8MUukIBOOYfDAV9guuCVEYDoGgK6rdPSIq2mvcSxkILG8OH5LQ
</code>```

By going to https://jwt.io/ I can see the payload is currently

```<code>{
  "token_type": "access",
  "exp": 1590910684,
  "jti": "73c1bfd9cf0f4f279680f4f8eb054497",
  "user_id": 11
}
</code>```

So, we can see that the second part of the token is the payload - containing the claims.

I've explored how to add more information to the Response body and now would like to know how to customize the Payload data by adding iat claim, username and today's date.

答:
As you already created a subclass for the desired view (MyTokenObtainPairView) and a subclass for its corresponding serializer (MyTokenObtainPairSerializer), add the following to the serializer

```<code>class MyTokenObtainPairSerializer(TokenObtainPairSerializer):

    ...

    @classmethod
    def get_token(cls, user):
        token = super().get_token(user)

        # Add custom claims
        token['iat'] = datetime.datetime.now()
        token['user'] = user.username
        token['date'] = str(datetime.date.today())

        return token
</code>```

Then, when you POST to that same location, you'll get an access token like this

```<code>eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNTkwOTE0MTk4LCJqdGkiOiJhZDZmNzZhZjFmOGU0ZWJlOGI2Y2Y5YjQ4MGQzZjY2MiIsInVzZXJfaWQiOjExLCJpYXQiOjE1OTA5MTc0OTgsInVzZXIiOiJ0aWFnbyIsImRhdGUiOiIyMDIwLTA1LTMxIn0.-5U9P-WWmhlOenzCvc6b7_71Tz17LyNxe_DOMwwqH4RqrNsilVukEcZWFRGupLHRZjIvPya2QJGpiju9ujzQuw
</code>```

Using JWT you can see the Payload changing accordingly

```<code>{
  "token_type": "access",
  "exp": 1590914198,
  "jti": "ad6f76af1f8e4ebe8b6cf9b480d3f662",
  "user_id": 11,
  "iat": 1590917498,
  "user": "tiago",
  "date": "2020-05-31"
}
</code>```

Title: Adding claims to DRF simple JWT payload

Body:
Using djangorestframework_simplejwt library, when POST to a custom view

#urls.py
path('api/token/', MyTokenObtainPairView.as_view(), name='token_obtain'),

#views.py
class MyTokenObtainPairView(TokenObtainPairView):
    serializer_class = MyTokenObtainPairSerializer

I'm able to get a the following access token

eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNTkwOTEwNjg0LCJqdGkiOiI3M2MxYmZkOWNmMGY0ZjI3OTY4MGY0ZjhlYjA1NDQ5NyIsInVzZXJfaWQiOjExfQ.5vs0LmNGseU6rtq3vuQyApupxhQM3FBAoKAq8MUukIBOOYfDAV9guuCVEYDoGgK6rdPSIq2mvcSxkILG8OH5LQ

By going to https://jwt.io/ I can see the payload is currently

{
  "token_type": "access",
  "exp": 1590910684,
  "jti": "73c1bfd9cf0f4f279680f4f8eb054497",
  "user_id": 11
}

So, we can see that the second part of the token is the payload - containing the claims.

I've explored how to add more information to the Response body and now would like to know how to customize the Payload data by adding iat claim, username and today's date.

Body:
As you already created a subclass for the desired view (MyTokenObtainPairView) and a subclass for its corresponding serializer (MyTokenObtainPairSerializer), add the following to the serializer

class MyTokenObtainPairSerializer(TokenObtainPairSerializer):

    ...

    @classmethod
    def get_token(cls, user):
        token = super().get_token(user)

        # Add custom claims
        token['iat'] = datetime.datetime.now()
        token['user'] = user.username
        token['date'] = str(datetime.date.today())

        return token

Then, when you POST to that same location, you'll get an access token like this

eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNTkwOTE0MTk4LCJqdGkiOiJhZDZmNzZhZjFmOGU0ZWJlOGI2Y2Y5YjQ4MGQzZjY2MiIsInVzZXJfaWQiOjExLCJpYXQiOjE1OTA5MTc0OTgsInVzZXIiOiJ0aWFnbyIsImRhdGUiOiIyMDIwLTA1LTMxIn0.-5U9P-WWmhlOenzCvc6b7_71Tz17LyNxe_DOMwwqH4RqrNsilVukEcZWFRGupLHRZjIvPya2QJGpiju9ujzQuw

Using JWT you can see the Payload changing accordingly

{
  "token_type": "access",
  "exp": 1590914198,
  "jti": "ad6f76af1f8e4ebe8b6cf9b480d3f662",
  "user_id": 11,
  "iat": 1590917498,
  "user": "tiago",
  "date": "2020-05-31"
}


问:
How to have the ctime library read anywhere inside a switch
I am currently doing a supermarket management project for my uni, and one of the criteria is to have the sales timestamped with the system time when they are made. I am using the ctime library with the tm struct, and declaring it with

time_t now = time(0);
 tm *ltm = localtime(&now);

at the beggining of the main(), to read the system time from that moment when the variable is declared.

Problem is, if I try to put it inside the switch I'm using it gives me cross initialization error (example and error below). And as I have it on the very beginning of the program, if I let it idle for a few minutes and do a sale, the saved hour will be outdated, which I don't want. Does anyone know how to put this working inside a switch, or a workaround for it? Searched all over google but all I could find was how to define it. Thank you!

Example of intended behaviour:

#include <ctime>
int main(){
    *variables*
    //----------------------
    switch(menu1){
        case 1:
            *case code*
        break;
        case 2:
            time_t now = time(0);
            tm *ltm = localtime(&now);
            *case code*
        break;
        case 3:
            *case code*
        break;
        default:
            *case code*
        break
    }
    return;
}

Error im having with this implementation (it also seems to give me an error to every case below where it is implemented):
Error messages

答:
You can also separate such utilities into functions. Below is a basic date to string function which works in switch.

Better still, put in it's own header and you can re-use outside of the main cpp file.

```<code>#include <ctime>
#include <iostream>
#include <chrono>

std::string now_string() {
 auto timenow = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());

return ctime(&timenow);
};

int main(){

int menu1;
std::cin >> menu1;

switch(menu1){
    case 1:
        break;
    case 2:
        std::cout << now_string() << std::endl;
        break;
    case 3:
        break;
    default:
        break;
}
return 0;
}
</code>```

Body:
You can also separate such utilities into functions. Below is a basic date to string function which works in switch.

Better still, put in it's own header and you can re-use outside of the main cpp file.

#include <ctime>
#include <iostream>
#include <chrono>

std::string now_string() {
 auto timenow = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());

return ctime(&timenow);
};

int main(){

int menu1;
std::cin >> menu1;

switch(menu1){
    case 1:
        break;
    case 2:
        std::cout << now_string() << std::endl;
        break;
    case 3:
        break;
    default:
        break;
}
return 0;
}


问:
Why we actually need runtime polymorphism?
I'm trying to understand a polymorphism but I don't understand why we need runtime polymorphism if static polymorphism works fine for calling members of a class.

Like, suppose this was a problem.

```<code>#include <bits/stdc++.h>
using namespace std;
class base{
    public:
        virtual void fun(){
            cout<<"base called"<<endl;
        }
};
class derived:public base{
    public:
        void fun(){
            cout<<"derived called"<<endl;
        }
};
int main() {

    base b,*b1;
    derived d;
    b1 = &d;
    b1->fun();
    // b.fun();
    // d.fun();
}
</code>```

suppose this was my code and I want to access the function of derived or base class and I was able to do it by simply creating an object of that class so if there is no problem then why we try to call the object using references (runtime polymorphism).
Can someone explain the actual need for runtime polymorphism or if it is possible can you explain it by using any real-life scenarios??

答:
Polymorphism is useful any time that the software can't be told at compile time exactly what everything is going to be at runtime, or when you need a container to be able to hold a heterogeneous assortment of things that all implement a common interface.

A good example is UI toolkits.  Pretty much all UI toolkits have a concept of a container that can hold other widgets, but the UI toolkit author has no idea what widgets you are going to put into the container.  Since the container needs to be able to deal with any kind of widget, polymorphism is the easiest way to achieve this.

Body:
I'm trying to understand a polymorphism but I don't understand why we need runtime polymorphism if static polymorphism works fine for calling members of a class.

Like, suppose this was a problem.

#include <bits/stdc++.h>
using namespace std;
class base{
    public:
        virtual void fun(){
            cout<<"base called"<<endl;
        }
};
class derived:public base{
    public:
        void fun(){
            cout<<"derived called"<<endl;
        }
};
int main() {

    base b,*b1;
    derived d;
    b1 = &d;
    b1->fun();
    // b.fun();
    // d.fun();
}

suppose this was my code and I want to access the function of derived or base class and I was able to do it by simply creating an object of that class so if there is no problem then why we try to call the object using references (runtime polymorphism).
Can someone explain the actual need for runtime polymorphism or if it is possible can you explain it by using any real-life scenarios??


问:
Autodesk-forge viewer: Access token
I was following forge tutorials to embed the forge viewer in an html page.
I ended up at this forge-made page, link: https://autodesk-forge.github.io/forge-tutorial-postman/display_svf.html
I understand how to retrieve an access token using cURL however I would like to modify that website so that I don't have to enter the access token myself.
I would like the access-token from the cURL response to be automatically imported as the access token for that website. How is this possible.
The code for the webpage is here: https://github.com/Autodesk-Forge/forge-tutorial-postman/blob/master/docs/display_svf.html
How can I add a function/method to automatically retrieve an access token when I hit submit on the webpage.
Any help is much appeciated!
Cheers!</p>

答:
The server side code you are looking for is:

app.get('/api/forge/oauth', function (req, res) {
    Axios({
        method: 'POST',
        url: 'https://developer.api.autodesk.com/authentication/v1/authenticate',
        headers: {
            'content-type': 'application/x-www-form-urlencoded',
        },
        data: querystring.stringify({
            client_id: FORGE_CLIENT_ID,
            client_secret: FORGE_CLIENT_SECRET,
            grant_type: 'client_credentials',
            scope: scopes
        })
    })
        .then(function (response) {
            // Success
            access_token = response.data.access_token;
            console.log(response);
            res.send('
Authentication success!
');
        })
        .catch(function (error) {
            // Failed
            console.log(error);
            res.send('Failed to authenticate');
        });
});```

Please refer the Forge 2-Legged Authentication tutorials for the code and more details. We also have more tutorials and workflow on Learn Autodesk Forge.

Title: Autodesk-forge viewer: Access token

Body:
The server side code you are looking for is:

app.get('/api/forge/oauth', function (req, res) {
    Axios({
        method: 'POST',
        url: 'https://developer.api.autodesk.com/authentication/v1/authenticate',
        headers: {
            'content-type': 'application/x-www-form-urlencoded',
        },
        data: querystring.stringify({
            client_id: FORGE_CLIENT_ID,
            client_secret: FORGE_CLIENT_SECRET,
            grant_type: 'client_credentials',
            scope: scopes
        })
    })
        .then(function (response) {
            // Success
            access_token = response.data.access_token;
            console.log(response);
            res.send('<p>Authentication success!</p>');
        })
        .catch(function (error) {
            // Failed
            console.log(error);
            res.send('Failed to authenticate');
        });
});

Please refer the Forge 2-Legged Authentication tutorials for the code and more details. We also have more tutorials and workflow on Learn Autodesk Forge.


答:
I have two solutions for your problem. I highly recommend combining your data frame in one master data frame in order to reduce the complexity of the code if at all possible. I am sure there are better solutions to the "Separate Data Frame" problem, but most of them will involve multiple loops and thus negatively impact performance.

Data

```<code>mylist= structure(list(`1` = structure(list(ID = c('2009-01-02', '2009-01-03', '2009-01-04', '2009-01-05'), Income = c(100, 200, 300, 400)), .Names = c("Date", "Income"), row.names = c(1L, 2L, 3L, 4L), class = "data.frame"), `2` = structure(list(ID = c('2009-01-02', '2009-01-03', '2009-01-04', '2009-01-05'), Income = c(500, -600, 700, 800)), .Names = c("Date", "Income"), row.names = c(1L, 2L, 3L, 4L), class = "data.frame"), `3` = structure(list(ID = c('2009-01-02', '2009-01-03', '2009-01-04'), Income = c(100, 200, 300)), .Names = c("Date", "Income"), row.names = c(1L, 2L, 3L), class = "data.frame")))
</code>```

Combined Data Frame

```<code>library(dplyr)

# add an ID to each data frame
for(i in 1:length(mylist)){
  mylist[[i]] <- cbind(mylist[[i]], stock_id = names(mylist)[i])
}

# create data frame with all observations
my_data_frame <- do.call(rbind, mylist)
rownames(my_data_frame) <- NULL

my_data_frame %>%
  group_by(Date) %>%
  mutate(Perc = Income/sum(Income[Income > 0]))
</code>```

```<code># A tibble: 11 x 4
# Groups:   Date [4]
   Date       Income stock_id   Perc
   <chr>       <dbl> <chr>     <dbl>
 1 2009-01-02    100 1         0.143
 2 2009-01-03    200 1         0.5
 3 2009-01-04    300 1         0.231
 4 2009-01-05    400 1         0.333
 5 2009-01-02    500 2         0.714
 6 2009-01-03   -600 2        -1.5
 7 2009-01-04    700 2         0.538
 8 2009-01-05    800 2         0.667
 9 2009-01-02    100 3         0.143
10 2009-01-03    200 3         0.5
11 2009-01-04    300 3         0.231
</code>```

Separate Data Frames

```<code>library(dplyr)

all_dates <- unique(unlist(lapply(mylist, function(x) unique(x$Date))))

for(i in 1:length(mylist)){
  mylist[[i]] <- cbind(mylist[[i]], stock_id = names(mylist)[i])
}

perc_all <- list()
for(i in 1:length(all_dates)){
  temporary <- lapply(mylist, function(x) x[x$Date == all_dates[i], ])
  all_obs_date <- do.call(rbind, temporary)
  all_obs_date$Perc <- all_obs_date$Income/sum(all_obs_date$Income[all_obs_date$Income > 0])
  perc_all[[i]] <- all_obs_date
}
perc_final <- do.call(rbind, perc_all)
lapply(mylist, function(x) {
  left_join(x, perc_final) %>% select(-stock_id)
})

</code>```

```<code>$`1`
        Date Income      Perc
1 2009-01-02    100 0.1428571
2 2009-01-03    200 0.5000000
3 2009-01-04    300 0.2307692
4 2009-01-05    400 0.3333333

$`2`
        Date Income       Perc
1 2009-01-02    500  0.7142857
2 2009-01-03   -600 -1.5000000
3 2009-01-04    700  0.5384615
4 2009-01-05    800  0.6666667

$`3`
        Date Income      Perc
1 2009-01-02    100 0.1428571
2 2009-01-03    200 0.5000000
3 2009-01-04    300 0.2307692
</code>```

Title: Sum row of list of dataframe in r

Body:
I have a list of dataframes. Each dataframe is a Stock quote whose row names are dates and column names are buy price, sell price, shares and PL.

I want to obtain a column that contains the percentage of every positive PL contribution to the total daily PL.

Making it simplier. I have the following Data:

mylist= structure(list(`1` = structure(list(ID = c(35L, '2009-01-03', '2009-01-04', '2009-01-05'), Income = c(100, 200, 300, 400)), .Names = c("Date", "Income"), row.names = c(1L, 2L, 3L, 4L), class = "data.frame"), `2` = structure(list(ID = c('2009-01-02', '2009-01-03', '2009-01-04', '2009-01-05'), Income = c(500, -600, 700, 800)), .Names = c("Date", "Income"), row.names = c(1L, 2L, 3L, 4L), class = "data.frame"), `3` = structure(list(ID = c('2009-01-02', '2009-01-03', '2009-01-04'), Income = c(100, 200, 300)), .Names = c("Date", "Income"), row.names = c(1L, 2L, 3L), class = "data.frame")))

Which looks like this:

$`1`
        Date Income
1 2009-01-01    100
2 2009-01-03    200
3 2009-01-04    300
4 2009-01-05    400

$`2`
        Date Income
1 2009-01-02    500
2 2009-01-03   -600
3 2009-01-04    700
4 2009-01-05    800

$`3`
        Date Income
1 2009-01-02    100
2 2009-01-03    200
3 2009-01-04    300

I want to obtain something that looks like this:

$`1`
        Date Income Perc
1 2009-01-03    100 1.00
2 2009-01-03    200 0.20
3 2009-01-04    300 0.23
4 2009-01-05    400 0.33

$`2`
        Date Income  Perc
1 2009-01-02    500  0.83
2 2009-01-03    600 -1.50
3 2009-01-04    700  0.54
4 2009-01-05    800  0.67

$`3`
        Date Income Perc
1 2009-01-02    100 0.17
2 2009-01-03    200 0.20
3 2009-01-04    300 0.23

Body:
I have two solutions for your problem. I highly recommend combining your data frame in one master data frame in order to reduce the complexity of the code if at all possible. I am sure there are better solutions to the "Separate Data Frame" problem, but most of them will involve multiple loops and thus negatively impact performance.

Data

mylist= structure(list(`1` = structure(list(ID = c('2009-01-02', '2009-01-03', '2009-01-04', '2009-01-05'), Income = c(100, 200, 300, 400)), .Names = c("Date", "Income"), row.names = c(1L, 2L, 3L, 4L), class = "data.frame"), `2` = structure(list(ID = c('2009-01-02', '2009-01-03', '2009-01-04', '2009-01-05'), Income = c(500, -600, 700, 800)), .Names = c("Date", "Income"), row.names = c(1L, 2L, 3L, 4L), class = "data.frame"), `3` = structure(list(ID = c('2009-01-02', '2009-01-03', '2009-01-04'), Income = c(100, 200, 300)), .Names = c("Date", "Income"), row.names = c(1L, 2L, 3L), class = "data.frame")))

Combined Data Frame

library(dplyr)

# add an ID to each data frame
for(i in 1:length(mylist)){
  mylist[[i]] <- cbind(mylist[[i]], stock_id = names(mylist)[i])
}

# create data frame with all observations
my_data_frame <- do.call(rbind, mylist)
rownames(my_data_frame) <- NULL

my_data_frame %>%
  group_by(Date) %>%
  mutate(Perc = Income/sum(Income[Income > 0]))

# A tibble: 11 x 4
# Groups:   Date [4]
   Date       Income stock_id   Perc
   <chr>       <dbl> <chr>     <dbl>
 1 2009-01-02    100 1         0.143
 2 2009-01-03    200 1         0.5
 3 2009-01-04    300 1         0.231
 4 2009-01-05    400 1         0.333
 5 2009-01-02    500 2         0.714
 6 2009-01-03   -600 2        -1.5
 7 2009-01-04    700 2         0.538
 8 2009-01-05    800 2         0.667
 9 2009-01-02    100 3         0.143
10 2009-01-03    200 3         0.5
11 2009-01-04    300 3         0.231

Separate Data Frames

library(dplyr)

all_dates <- unique(unlist(lapply(mylist, function(x) unique(x$Date))))

for(i in 1:length(mylist)){
  mylist[[i]] <- cbind(mylist[[i]], stock_id = names(mylist)[i])
}

perc_all <- list()
for(i in 1:length(all_dates)){
  temporary <- lapply(mylist, function(x) x[x$Date == all_dates[i], ])
  all_obs_date <- do.call(rbind, temporary)
  all_obs_date$Perc <- all_obs_date$Income/sum(all_obs_date$Income[all_obs_date$Income > 0])
  perc_all[[i]] <- all_obs_date
}
perc_final <- do.call(rbind, perc_all)
lapply(mylist, function(x) {
  left_join(x, perc_final) %>% select(-stock_id)
})

$`1`
        Date Income      Perc
1 2009-01-02    100 0.1428571
2 2009-01-03    200 0.5000000
3 2009-01-04    300 0.2307692
4 2009-01-05    400 0.3333333

$`2`
        Date Income       Perc
1 2009-01-02    500  0.7142857
2 2009-01-03   -600 -1.5000000
3 2009-01-04    700  0.5384615
4 2009-01-05    800  0.6666667

$`3`
        Date Income      Perc
1 2009-01-02    100 0.1428571
2 2009-01-03    200 0.5000000
3 2009-01-04    300 0.2307692


问:
Run Python script from a Laravel application
I want to run my Python script in Laravel.
When I press the run button in the browser it runs my Python script and displays output on the page through a controller....

I tried so many ways but the script in not going to run...

Am also using

use Symfony\Component\Process\Process;
```

But when I run the code it just blinks the terminal and nothing else...

Please guide me on how to run a Python script from Laravel.

答:
Assuming you have installed symfony/process via composer

composer require symfony/process
```
<p>And you have a form in your view that points to an action with a button</p>
<pre class="lang-html prettyprint-override"><code><form action="/" method="post">
    @csrf
    <button type="submit">Run Python</button>
</form>
</code>```

And a route in routes/web.php that points to the controller

Route::post('/', 'PythonController@run');
```
<p>And a Python script named <code>python.py</code> in the root of your Laravel application directory with the content</p>
<pre class="lang-py prettyprint-override"><code>print("Hello, World from Python!")
</code>```

And a controller method that runs the process and returns the output

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Symfony\Component\Process\Process;

class PythonController extends Controller
{
    public function run(Request $request)
    {
        $process = new Process(['python', base_path() . '/python.py']);
        $process->run();
        return $process->getOutput();
    }
}
```

You would have a view like so

And when the button is clicked, you'd get the Python output like so

Body:
I want to run my Python script in Laravel.
When I press the run button in the browser it runs my Python script and displays output on the page through a controller....

I tried so many ways but the script in not going to run...

Am also using

use Symfony\Component\Process\Process;

But when I run the code it just blinks the terminal and nothing else...

Please guide me on how to run a Python script from Laravel.

Body:
Assuming you have installed symfony/process via composer

composer require symfony/process

And you have a form in your view that points to an action with a button

<form action="/" method="post">
    @csrf
    <button type="submit">Run Python</button>
</form>

And a route in routes/web.php that points to the controller

Route::post('/', 'PythonController@run');

And a Python script named python.py in the root of your Laravel application directory with the content

print("Hello, World from Python!")

And a controller method that runs the process and returns the output

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Symfony\Component\Process\Process;

class PythonController extends Controller
{
    public function run(Request $request)
    {
        $process = new Process(['python', base_path() . '/python.py']);
        $process->run();
        return $process->getOutput();
    }
}

You would have a view like so

And when the button is clicked, you'd get the Python output like so


问:
Logging in to a website with C#
I'm sorry if this subject has already been answered, but I couldn't find what I needed (yet).

I'm working on a program that downloads files from university websites that use the same infrastructure. It's an open source project which I'm trying to support in my free time
(hosted in goodle code: http://code.google.com/p/highlearner/)

Until now we used GET and POST requests to login into the right page and download stuff. But the universities keep changing their websites and every little change requires teaking in Highlearner, which requires a new version, auto-updating all users, etc. Also, every university has its own login page, requiring me to tailor a login sequences..

So I'm looking for a more robust solution. Instead of manually redirecting and setting the HTTP parameters. Is there some kind of mini browser that supports with HTML + Javascript? No GUI is needed, I just need the engine.
This way, I will simply need to fill out the form parameters and let the browser do the work.

Thanks,
Nitay

答:
You could try to automate the process with WatiN library . It allows you to click buttons, submit forms, etc.</p>

```<code>using (var ie = new IE(loginUrl))
{
    if (ie.TextField("username").Exists
       && ie.TextField("password").Exists)
    {
        ie.TextField("username").Value = "username";
        ie.TextField("password").Value = "password";
        ie.Button(Find.ByName("submit")).Click();
    }
}
</code>```

Title: Logging in to a website with C#

Body:
You could try to automate the process with WatiN library . It allows you to click buttons, submit forms, etc.

using (var ie = new IE(loginUrl))
{
    if (ie.TextField("username").Exists
       && ie.TextField("password").Exists)
    {
        ie.TextField("username").Value = "username";
        ie.TextField("password").Value = "password";
        ie.Button(Find.ByName("submit")).Click();
    }
}


问:
Pandas Dataframe: Find the index of maximum value for each column using idxmax()
I have a dataframe 156 x 9 with no null values and I am trying to find the index of the maximum value of each column. I tried the following

```<code>    country_list = []
    keys = []
    for i in range(len(col)):
        country = df.loc[df[col[i]].idxmax()]['Country or region']
        country_list.append(country)
        keys.append(col[i])
</code>```

The columns available are

```<code>In[65]:df.columns
Out[65]:
Index(['Overall rank', 'Country or region', 'Score', 'GDP per capita',
       'Social support', 'Healthy life expectancy',
       'Freedom to make life choices', 'Generosity',
       'Perceptions of corruption'],
      dtype='object')
</code>```

But I got the error of for using idxmax TypeError: reduction operation 'argmax' not allowed for this dtype

Any help appreciated, thank you!

答:
Error means there are some non numeric column(s).

Select only numeric columns by DataFrame.select_dtypes and then use DataFrame.idxmax:

```<code>df = pd.DataFrame({
        'A':list('abcdef'),
         'B':[4,5,4,5,5,4],
         'C':[7,8,9,4,2,3],
         'D':[1,3,5,7,1,0],
         'E':[5,3,6,9,2,4],
         'F':list('aaabbb')
})

print (df)
   A  B  C  D  E  F
0  a  4  7  1  5  a
1  b  5  8  3  3  a
2  c  4  9  5  6  a
3  d  5  4  7  9  b
4  e  5  2  1  2  b
5  f  4  3  0  4  b

df1 = df.select_dtypes(np.number).idxmax()
print (df1)
B    1
C    2
D    3
E    3
dtype: int64
</code>```

Body:
I have a dataframe 156 x 9 with no null values and I am trying to find the index of the maximum value of each column. I tried the following

    country_list = []
    keys = []
    for i in range(len(col)):
        country = df.loc[df[col[i]].idxmax()]['Country or region']
        country_list.append(country)
        keys.append(col[i])

The columns available are

In[65]:df.columns
Out[65]:
Index(['Overall rank', 'Country or region', 'Score', 'GDP per capita',
       'Social support', 'Healthy life expectancy',
       'Freedom to make life choices', 'Generosity',
       'Perceptions of corruption'],
      dtype='object')

But I got the error of for using idxmax TypeError: reduction operation 'argmax' not allowed for this dtype

Any help appreciated, thank you!

Body:
Error means there are some non numeric column(s).

Select only numeric columns by DataFrame.select_dtypes and then use DataFrame.idxmax:

df = pd.DataFrame({
        'A':list('abcdef'),
         'B':[4,5,4,5,5,4],
         'C':[7,8,9,4,2,3],
         'D':[1,3,5,7,1,0],
         'E':[5,3,6,9,2,4],
         'F':list('aaabbb')
})

print (df)
   A  B  C  D  E  F
0  a  4  7  1  5  a
1  b  5  8  3  3  a
2  c  4  9  5  6  a
3  d  5  4  7  9  b
4  e  5  2  1  2  b
5  f  4  3  0  4  b

df1 = df.select_dtypes(np.number).idxmax()
print (df1)
B    1
C    2
D    3
E    3
dtype: int64


问:
How to diplay number of blog posted per category in Django
I am developing a blog website using Django and trying to display the no. of the post made per category on the homepage.

models.py:

```<code>class Category(models.Model):

    CATEGORY = (
        ("Un-categorized", "Un-categorized"),
        ("Machine Learning", "Machine Learning"),
        ("Data Science", "Data Science"),
        ("Programming", "Programming"),
        ("Latest Trends", "Latest Trends")
    )

    category = models.CharField(max_length=20, choices=CATEGORY, default='Un-Categorized',unique=True)

    def __str__(self):
        return self.category

class Post(models.Model):

    title = models.CharField(max_length=20) # title of the post
    content = models.TextField()  # content of the post
    date_posted = models.DateTimeField(auto_now_add=True)  # when the post is created
    date_modified = models.DateTimeField(auto_now=True) # will store the date every time the post is updated and saved.
    author = models.ForeignKey(User, on_delete=models.CASCADE)  # Referring the django's inbuilt User model.
    category = models.ForeignKey(Category, on_delete=models.CASCADE)  # one post can have only one category whereas under one category there can be multiple post.
    img = models.ImageField(default='default.jpg', upload_to='post')
    # tag = to store important tags related to the post

    def __str__(self):
        return self.title
</code>```

views.py :

```<code>def home(request): # Home page of the website.
    post = Post.objects.all().order_by('-date_posted') # To display all the post in desc order.
    categories = Category.objects.all()

    '''categories_count = []
    i = 1
    for item in categories.count():
        categories_count[item] = Categories.objects.filter(id=i).count()
        i += 1
    '''
    context = {
        'posts':post,
        # 'count' : categories_count,
        'categories': categories,
        # 'categories_count': categories_count
    }

    return render(request,'post/home.html',context=context)
</code>```

.html file:

```<code><div class="widget widget_categories group">
    <h3>Categories</h3>
        <ul>
            {% for category in categories %}
            <li>
                <a href="{% url 'post-category' category.category %}" title="">
                    {{ category }}
                </a>
                (<!--count of post made per category-->>)
            </li>
            {% endfor %}
        </ul>
</div>
</code>```

I tried to implement this in my view but I couldn't able to complete it. I am not sure how to access the categories_count list under the context dic. from the template.

答: You're probably after annotations https://docs.djangoproject.com/en/3.0/topics/db/aggregation/#generating-aggregates-for-each-item-in-a-queryset</p>

Body:
I am developing a blog website using Django and trying to display the no. of the post made per category on the homepage.

models.py:

class Category(models.Model):

    CATEGORY = (
        ("Un-categorized", "Un-categorized"),
        ("Machine Learning", "Machine Learning"),
        ("Data Science", "Data Science"),
        ("Programming", "Programming"),
        ("Latest Trends", "Latest Trends")
    )

    category = models.CharField(max_length=20, choices=CATEGORY, default='Un-Categorized',unique=True)

    def __str__(self):
        return self.category

class Post(models.Model):

    title = models.CharField(max_length=20) # title of the post
    content = models.TextField()  # content of the post
    date_posted = models.DateTimeField(auto_now_add=True)  # when the post is created
    date_modified = models.DateTimeField(auto_now=True) # will store the date every time the post is updated and saved.
    author = models.ForeignKey(User, on_delete=models.CASCADE)  # Referring the django's inbuilt User model.
    category = models.ForeignKey(Category, on_delete=models.CASCADE)  # one post can have only one category whereas under one category there can be multiple post.
    img = models.ImageField(default='default.jpg', upload_to='post')
    # tag = to store important tags related to the post

    def __str__(self):
        return self.title

views.py :

def home(request): # Home page of the website.
    post = Post.objects.all().order_by('-date_posted') # To display all the post in desc order.
    categories = Category.objects.all()

    '''categories_count = []
    i = 1
    for item in categories.count():
        categories_count[item] = Categories.objects.filter(id=i).count()
        i += 1
    '''
    context = {
        'posts':post,
        # 'count' : categories_count,
        'categories': categories,
        # 'categories_count': categories_count
    }

    return render(request,'post/home.html',context=context)

.html file:

Categories

            {% for category in categories %}

                    {{ category }}

                (>)

            {% endfor %}

I tried to implement this in my view but I couldn't able to complete it. I am not sure how to access the categories_count list under the context dic. from the template.