问:
Filter Attributes in Xml in c# AND modify the Xml
I am trying to convert and Xml A into Xml B using C#.

XML A

```<code><root>
  <country>
    <city name="Boston" value="100">
    <city name="Boston" value="200">
   </country>
  </root>
</code>```

XMl B(Expected)

```<code><root>
  <country>
        <city name="Boston" value="300">
   </country>
  </root>
</code>```

C# code:

```<code> var doc = XDocument.Load(path);
            var myDocument = new XmlDocument();
            myDocument.Load(path);
            var nodes = myDocument.GetElementsByTagName("city");

var resultNodes = new List<XmlNode>();
            foreach (XmlNode node in nodes)
            {
                if (node.Attributes != null && node.Attributes["name"] != null && node.Attributes["name"].Value == "Boston")
                    resultNodes.Add(node);
                foreach(var elements in resultNodes)
                {
                    elements.Attributes.RemoveNamedItem("Boston");
                }
            }
</code>```

Basically what i wanted to do here is add the 2 values(100 &200)from 2 different Boston attributes from XML A and print into a new XML B file but lost a bit here as what goes into this block.

```<code>foreach (XmlNode i in resultNodes)
            {

            }
</code>```

答:
Problems like this is easy to create new XElements.  See code below :</p>

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(FILENAME);
            List<XElement> countries = doc.Descendants("country").ToList();
            foreach (XElement oldCountry in countries)
            {
                XElement newCountry = new XElement("country");

                var cities = oldCountry.Elements("city").GroupBy(x => (string)x.Attribute("name"));
                foreach (var city in cities)
                {
                    newCountry.Add(new XElement("city", new object[] { new XAttribute("name", city.Key), new XAttribute("value", city.Sum(x => (int)x.Attribute("value"))) }));
                }
                oldCountry.ReplaceWith(newCountry);
            }

        }
    }
}
</code>```

Body:
I am trying to convert and Xml A into Xml B using C#.

XML A

<root>
  <country>
    <city name="Boston" value="100">
    <city name="Boston" value="200">
   </country>
  </root>

XMl B(Expected)

<root>
  <country>
        <city name="Boston" value="300">
   </country>
  </root>

C# code:

 var doc = XDocument.Load(path);
            var myDocument = new XmlDocument();
            myDocument.Load(path);
            var nodes = myDocument.GetElementsByTagName("city");

var resultNodes = new List<XmlNode>();
            foreach (XmlNode node in nodes)
            {
                if (node.Attributes != null && node.Attributes["name"] != null && node.Attributes["name"].Value == "Boston")
                    resultNodes.Add(node);
                foreach(var elements in resultNodes)
                {
                    elements.Attributes.RemoveNamedItem("Boston");
                }
            }

Basically what i wanted to do here is add the 2 values(100 &200)from 2 different Boston attributes from XML A and print into a new XML B file but lost a bit here as what goes into this block.

foreach (XmlNode i in resultNodes)
            {

            }

Body:
Problems like this is easy to create new XElements.  See code below :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(FILENAME);
            List<XElement> countries = doc.Descendants("country").ToList();
            foreach (XElement oldCountry in countries)
            {
                XElement newCountry = new XElement("country");

                var cities = oldCountry.Elements("city").GroupBy(x => (string)x.Attribute("name"));
                foreach (var city in cities)
                {
                    newCountry.Add(new XElement("city", new object[] { new XAttribute("name", city.Key), new XAttribute("value", city.Sum(x => (int)x.Attribute("value"))) }));
                }
                oldCountry.ReplaceWith(newCountry);
            }

        }
    }
}


来源: stackexchange

问:
How to transpose a matrix into a second column, while the first column being the first element
First of all I've never coded anything in my life, and I'm just learning R this week.
I'm not sure if the title is any clear, but I guess showing my problem is easier:
Let's say I have this Matrix (m):

```<code>        [,1] [,2] [,3] [,4]
 [1,]    A    1    2    3
 [2,]    B    1    4
 [3,]    C    3
</code>```

Basically that A contains 1, 2 and 3, B contains 1 and 4 and so on.
How would I show that in a matrix with 2 columns only?

```<code>        [,1] [,2]
 [1,]    A    1
 [2,]    A    2
 [3,]    A    3
 [4,]    B    1
 [5,]    B    4
 [6,]    C    3
</code>```

Thanks a lot!

答:
Assuming that the blanks showed are NA, get the count of NA elements per row with rowSums, cbind the replicated first column based on 'n' while transposing the rest of the columns after omitting the NAs

```<code>n <- rowSums(!is.na(m1[,-1]))
cbind(rep(m1[,1], n), na.omit(c(t(m1[,-1]))))
#   [,1] [,2]
#[1,] "A"  "1"
#[2,] "A"  "2"
#[3,] "A"  "3"
#[4,] "B"  "1"
#[5,] "B"  "4"
#[6,] "C"  "3"
</code>```

Or a slightly more compact option is to replicate the first column with col index, cbind with the transpose of rest of the columns, and finally remove the NA rows with na.omit

```<code>na.omit(cbind(m1[,1][col(m1[,-1])], c(t(m1[,-1]))))
#   [,1] [,2]
#[1,] "A"  "1"
#[2,] "A"  "2"
#[3,] "A"  "3"
#[4,] "B"  "1"
#[5,] "B"  "4"
#[6,] "C"  "3"
</code>```

NOTE: matrix cannot have multiple column types.  So, if there is a character class, all the elements are converted to character

data

```<code>m1 <- structure(c("A", "B", "C", "1", "1", "3", "2", "4", NA, "3",
NA, NA), .Dim = 3:4)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
First of all I've never coded anything in my life, and I'm just learning R this week.
I'm not sure if the title is any clear, but I guess showing my problem is easier:
Let's say I have this Matrix (m):

        [,1] [,2] [,3] [,4]
 [1,]    A    1    2    3
 [2,]    B    1    4
 [3,]    C    3

Basically that A contains 1, 2 and 3, B contains 1 and 4 and so on.
How would I show that in a matrix with 2 columns only?

        [,1] [,2]
 [1,]    A    1
 [2,]    A    2
 [3,]    A    3
 [4,]    B    1
 [5,]    B    4
 [6,]    C    3

Thanks a lot!

Body:
Assuming that the blanks showed are NA, get the count of NA elements per row with rowSums, cbind the replicated first column based on 'n' while transposing the rest of the columns after omitting the NAs

n <- rowSums(!is.na(m1[,-1]))
cbind(rep(m1[,1], n), na.omit(c(t(m1[,-1]))))
#   [,1] [,2]
#[1,] "A"  "1"
#[2,] "A"  "2"
#[3,] "A"  "3"
#[4,] "B"  "1"
#[5,] "B"  "4"
#[6,] "C"  "3"

Or a slightly more compact option is to replicate the first column with col index, cbind with the transpose of rest of the columns, and finally remove the NA rows with na.omit

na.omit(cbind(m1[,1][col(m1[,-1])], c(t(m1[,-1]))))
#   [,1] [,2]
#[1,] "A"  "1"
#[2,] "A"  "2"
#[3,] "A"  "3"
#[4,] "B"  "1"
#[5,] "B"  "4"
#[6,] "C"  "3"

NOTE: matrix cannot have multiple column types.  So, if there is a character class, all the elements are converted to character

data

m1 <- structure(c("A", "B", "C", "1", "1", "3", "2", "4", NA, "3",
NA, NA), .Dim = 3:4)


问:
XMLHttpRequest setRequestHeader Error
IE 9 developer tools say "Unspecified error." at this line of code:

```<code>xmlhttp.setRequestHeader ("If-Modified-Since", "Sat 1 Jan 2005 00:00:00 GMT");
</code>```

I am trying to disable caching of Ajax requests and I don't have control over the server and I cannot append a unique ID to the end of each request, so this looks like my only option. Any ideas why Javascript doesn't like it?

答: I don't have too much experience with AJAX requests, but couldn't you just call xmlhttp.setRequestHeader("Cache-Control", "no-cache") instead? Seems like that would make more sense than using the If-Modified-Since header.

ContentLicense: CC BY-SA 3.0

Title: XMLHttpRequest setRequestHeader Error

Body:
IE 9 developer tools say "Unspecified error." at this line of code:

xmlhttp.setRequestHeader ("If-Modified-Since", "Sat 1 Jan 2005 00:00:00 GMT");

I am trying to disable caching of Ajax requests and I don't have control over the server and I cannot append a unique ID to the end of each request, so this looks like my only option. Any ideas why Javascript doesn't like it?


问:
Python Tkinter Button No Longer Clicking When Images is added
I've been working with Tkinter to create new windows through button clicks. Recently I've been trying to size the buttons in order to fit the screen. I tried using the trick that uses a 1 by a 1-pixel image so I can size the buttons but pixels. I've noticed whenever I try to put the image on the button no longer works. If I comment out the image parameter the button starts to work. I have no clue why. Heres the code:</p>

```<code>import tkinter as tk
import module1
class win1:
    def __init__(self,master):
        self.master = master
        self.master.geometry("400x400")
        self.frame=tk.Frame(self.master)
        #self.butnew("Hi there","2",win2)

        #####################           FullScreen           ###################
        w, h = master.winfo_screenwidth(), master.winfo_screenheight()
        self.master.overrideredirect(1)
        self.master.geometry("%dx%d+0+0" % (w, h))
        self.master.focus_set() # <-- move focus to this widget
        self.master.bind("<Escape>", lambda e: e.widget.quit())#Quits when escape is pressed

        for i in range(3):
            self.master.columnconfigure(i, weight=1, minsize=75)
            self.master.rowconfigure(i, weight=1, minsize=50)

            for j in range(0, 3):
                self.butnew("ji","g",module1.stonky,i,j)
        self.frame.pack()

    def butnew(self,text,number,_class,i,j):
        sizeWidth = int(self.master.winfo_screenwidth()/81)
        sizeHeight = int(self.master.winfo_screenheight()/81)
        pixel = tk.PhotoImage(width=sizeWidth, height=sizeWidth)
        tk.Button(self.frame,
                  text = text,
                  image=pixel,#If i comment out this line it works
                  #width=sizeWidth,
                  #height=sizeHeight,
                  compound="center",
                  command= lambda: self.new_window(number,_class)).grid(row=i,
                                                                        column=j,
                                                                        padx =3,
                                                                        pady=4)

    def new_window(self,number,_class):
        self.new = tk.Toplevel(self.master)
        _class(self.new,number)

root = tk.Tk()
app = win1(root)
root.mainloop()
</code>```

答:
It is because the image is garbage collected as it is created inside a function.  You need to keep a reference to the image:</p>

```<code>def butnew(self,text,number,_class,i,j):
    sizeWidth = int(self.master.winfo_screenwidth()/81)
    sizeHeight = int(self.master.winfo_screenheight()/81)
    pixel = tk.PhotoImage(width=sizeWidth, height=sizeWidth)
    btn = tk.Button(self.frame,
                    text=text,
                    image=pixel,
                    #width=sizeWidth,
                    #height=sizeHeight,
                    compound="center",
                    command=lambda: self.new_window(number,_class))
    btn.grid(row=i, column=j, padx =3, pady=4)
    btn.photo = pixel # keep a reference to the image
</code>```

Body:
I've been working with Tkinter to create new windows through button clicks. Recently I've been trying to size the buttons in order to fit the screen. I tried using the trick that uses a 1 by a 1-pixel image so I can size the buttons but pixels. I've noticed whenever I try to put the image on the button no longer works. If I comment out the image parameter the button starts to work. I have no clue why. Heres the code:

import tkinter as tk
import module1
class win1:
    def __init__(self,master):
        self.master = master
        self.master.geometry("400x400")
        self.frame=tk.Frame(self.master)
        #self.butnew("Hi there","2",win2)

        #####################           FullScreen           ###################
        w, h = master.winfo_screenwidth(), master.winfo_screenheight()
        self.master.overrideredirect(1)
        self.master.geometry("%dx%d+0+0" % (w, h))
        self.master.focus_set() # <-- move focus to this widget
        self.master.bind("<Escape>", lambda e: e.widget.quit())#Quits when escape is pressed

        for i in range(3):
            self.master.columnconfigure(i, weight=1, minsize=75)
            self.master.rowconfigure(i, weight=1, minsize=50)

            for j in range(0, 3):
                self.butnew("ji","g",module1.stonky,i,j)
        self.frame.pack()

    def butnew(self,text,number,_class,i,j):
        sizeWidth = int(self.master.winfo_screenwidth()/81)
        sizeHeight = int(self.master.winfo_screenheight()/81)
        pixel = tk.PhotoImage(width=sizeWidth, height=sizeWidth)
        tk.Button(self.frame,
                  text = text,
                  image=pixel,#If i comment out this line it works
                  #width=sizeWidth,
                  #height=sizeHeight,
                  compound="center",
                  command= lambda: self.new_window(number,_class)).grid(row=i,
                                                                        column=j,
                                                                        padx =3,
                                                                        pady=4)

    def new_window(self,number,_class):
        self.new = tk.Toplevel(self.master)
        _class(self.new,number)

root = tk.Tk()
app = win1(root)
root.mainloop()

Body:
It is because the image is garbage collected as it is created inside a function.  You need to keep a reference to the image:

def butnew(self,text,number,_class,i,j):
    sizeWidth = int(self.master.winfo_screenwidth()/81)
    sizeHeight = int(self.master.winfo_screenheight()/81)
    pixel = tk.PhotoImage(width=sizeWidth, height=sizeWidth)
    btn = tk.Button(self.frame,
                    text=text,
                    image=pixel,
                    #width=sizeWidth,
                    #height=sizeHeight,
                    compound="center",
                    command=lambda: self.new_window(number,_class))
    btn.grid(row=i, column=j, padx =3, pady=4)
    btn.photo = pixel # keep a reference to the image


问:
One line if-condition-assignment
I have the following code

```<code>num1 = 10
someBoolValue = True
</code>```

I need to set the value of num1 to 20 if someBoolValue is True; and do nothing otherwise. So, here is my code for that

```<code>num1 = 20 if someBoolValue else num1
</code>```

Is there someway I could avoid the ...else num1 part to make it look cleaner? An equivalent to

```<code>if someBoolValue:
    num1 = 20
</code>```

I tried replacing it with ...else pass like this: num1=20 if someBoolValue else pass. All I got was syntax error. Nor I could just omit the ...else num1 part.

答:
For the future time traveler from Google, here is a new way (available from Python 3.8 onward):

b = 1
if a := b:
    # this section is only reached if b is not 0 or false.
    # Also, a is set to b
    print(a, b)
```

This is known as "the walrus operator". More info at the What’s New In Python 3.8 page.

Title: One line if-condition-assignment

Body:
I have the following code

num1 = 10
someBoolValue = True

I need to set the value of num1 to 20 if someBoolValue is True; and do nothing otherwise. So, here is my code for that

num1 = 20 if someBoolValue else num1

Is there someway I could avoid the ...else num1 part to make it look cleaner? An equivalent to

if someBoolValue:
    num1 = 20

I tried replacing it with ...else pass like this: num1=20 if someBoolValue else pass. All I got was syntax error. Nor I could just omit the ...else num1 part.

Body:
For the future time traveler from Google, here is a new way (available from Python 3.8 onward):

b = 1
if a := b:
    # this section is only reached if b is not 0 or false.
    # Also, a is set to b
    print(a, b)

This is known as "the walrus operator". More info at the What’s New In Python 3.8 page.


问:
Unable to verify user input in game
I am creating a rock, paper, scissors game. I want it to be best of 3 matches and to be able to verify user input. I keep running into issues with the user input. I have tried multiple variations but I can't seem to figure it out. I know my code is probably messy, so any input on how to clean it up would be greatly appreciated. Thank you so much for your time.</p>

```<code>import random
import sys
import time

print("Hello and welcome to the Rock, Paper, Scissors tournament.\n"
      "The tournament will be the best of 3 wins.\n"
      "It will be you against our highly intelligent computer opponent.\n"
      "Good luck!")

# Create a function for the game
def play_game():
    user_count = 0
    comp_count = 0
    tie_game = 0

    while comp_count < 2 and user_count < 2:
        user_choice = (int(input("-------------------------------------------"
                             "\nEnter choice by typing 1 2 or 3: \n 1. Rock \n 2. paper \n 3. scissor \n"
                             "-------------------------------------------\n")))
        if user_choice == 1:
            user_choice_name = 'Rock'
        elif user_choice == 2:
            user_choice_name = 'Paper'
        elif user_choice == 3:
            user_choice_name = 'Scissor'
        else:
            print("Please pick a valid number")

        print(f"\nYou have chosen: {user_choice_name}")
        print("\nNow it's the computer's turn to pick......")
        time.sleep(3)

        comp_choice = random.randint(1, 3)

        if comp_choice == 1:
            comp_choice_name = 'Rock'
        elif comp_choice == 2:
            comp_choice_name = 'Paper'
        else:
            comp_choice_name = 'Scissor'

        print(f"\nComputer has chosen: {comp_choice_name}\n")

        if user_choice == 1 and comp_choice == 2:
            comp_count += 1
            print("Computer wins this round with Paper! "
                  f"\n Computer: {comp_count}"
                  f"\n You: {user_count} \n\n")

        elif user_choice == 1 and comp_choice == 3:
            user_count += 1
            print("You win this round with Rock!"
                  f"\n Computer: {comp_count}"
                  f"\n You: {user_count} \n\n")

        elif user_choice == 2 and comp_choice == 1:
            user_count += 1
            print("You win this round with Paper!"
                  f"\n Computer: {comp_count}"
                  f"\n You: {user_count} \n\n")

        elif user_choice == 2 and comp_choice == 3:
            comp_count += 1
            print("Computer wins this round with Scissor!"
                  f"\n Computer: {comp_count}"
                  f"\n You: {user_count} \n\n")

        elif user_choice == 3 and comp_choice == 2:
            user_count += 1
            print("You win this round with Scissor!"
                  f"\n Computer: {comp_count}"
                  f"\n You: {user_count} \n\n")

        elif user_choice == 3 and comp_choice == 1:
            user_count += 1
            print("Computer wins this round with Rock!"
                  f"\n Computer: {comp_count}"
                  f"\n You: {user_count} \n\n")

        else:
            if user_choice == comp_choice:
                tie_game += 1
            print(f"This round was a tie! Both choosing {user_choice_name}, try again!"
                  f"\n Computer: {comp_count}"
                  f"\n You: {user_count} \n\n")
    else:
        print(f'The game is now over with a score of: \n You:{user_count} \n to \n Computer:{comp_count}')
        again = str(input("Do you want to play again, type 'yes' or 'no' \n"))
        if again.lower() == "no":
            print('Thank you for playing!')
            sys.exit()
        else:
            play_game()

play_game()
</code>```

答:
Since I had a few minutes to kill with a cup of coffee, here's a rewrite of your program with a bunch of improvements, the validation you asked about and some tips on coding style:

```<code>import random
import time

print("Hello and welcome to the Rock, Paper, Scissors tournament.\n"
      "The tournament will be the best of 3 wins.\n"
      "It will be you against our highly intelligent computer opponent.\n"
      "Good luck!")

# to avoid repeating these values over and over and changing numbers in to string,
# just defining them here. Name in capitals because it's global (generally bad)
# an even nicer solution would be to write a Game() class and put everything in
# there, but it would be a bit more advanced
RSP_OPTIONS = {
    1: 'Rock',
    2: 'Scissor',
    3: 'Paper'
}

def get_user_choice():
    # keep asking until a valid value is returned
    while True:
        # this is a bit fancy, but let's say you want to reuse the game for similar games
        # with different options from rock, scissor, paper, you'd want this code to still work

        # get a list of string versions of the numbers
        numbers = list(map(str, RSP_OPTIONS.keys()))
        # join them together like you presented them: 1, 2 or 3
        options = ', '.join(numbers[:-1]) + ' or ' + numbers[-1] + ':\n'
        # add the descriptions
        options = options + ''.join(f'{n}: {name}\n' for n, name in RSP_OPTIONS.items())
        try:
          user_choice = (int(input("-------------------------------------------\n"
                                   f"Enter choice by typing {options}"
                                   "-------------------------------------------\n")))
        except ValueError:
            # any invalid option
            user_choice = -1
        # check if it's one of the valid options
        if user_choice in RSP_OPTIONS:
            return user_choice
        else:
            # it makes sense to generate a new line where you want it, instead of having
            # to put new line characters at the start of other strings
            print("Please pick a valid number\n")

def beats(choice1, choice2):
    # choice1 beats choice2 if it's one greater, except when choice2 == 3 and choice1 == 1
    # but to make it even nicer and have it work for other similar games, you could say
    # "except when choice1 == the max choice and choice2 == the min choice"
    return (choice2 - choice1 == 1 or
            (choice1 == max(RSP_OPTIONS.keys()) and choice2 == min(RSP_OPTIONS.keys())))

# Create a function for the game
def play_game():
    user_count = 0
    comp_count = 0
    tie_game = 0

    # this is what you really want, best out of three, ties not counted?
    while comp_count + user_count < 3:
        user_choice = get_user_choice()

        print(f"You have chosen: {RSP_OPTIONS[user_choice]}\n")
        print("Now it's the computer's turn to pick......\n")
        # this wait is not very nice, the user might try to hit enter or something
        # you could consider printing the countdown, or telling the user to please wait
        # even then, it's kind of silly to pretend the computer has to work hard here
        time.sleep(3)

        # this choice is always valid, so no problem
        comp_choice = random.randint(1, 3)
        # note that you don't need the name, you can just look it up whenever in RSP_OPTIONS
        print(f"\nComputer has chosen: {RSP_OPTIONS[comp_choice]}\n")

        # getting rid of some repetition, note how the code really reads like what is intended
        if beats(comp_choice, user_choice):
            comp_count += 1
            # nice to also say what really beat them
            print(f"Computer wins this round with {RSP_OPTIONS[comp_choice]} over {RSP_OPTIONS[user_choice]}!\n")
        elif beats(user_choice, comp_choice):
            user_count += 1
            print(f"You win this round with {RSP_OPTIONS[user_choice]} over {RSP_OPTIONS[comp_choice]}!\n")
        else:
            # you can only get here on a tie
            tie_game += 1
            print(f"This round was a tie! Both choosing {RSP_OPTIONS[user_choice]}, try again!\n")
        # you always print this, so just do it after the options:
        print(f"Computer: {comp_count}\n"
              f"You: {user_count}\n\n")
    else:
        print(f'The game is now over with a score of:\n You:{user_count}\n to\n Computer:{comp_count}\n')
        again = str(input("Do you want to play again, type 'yes' or 'no' \n"))
        # let's quit on anything starting with n
        if again.lower()[0] == "n":
            print('Thank you for playing!\n')
            # instead of exiting hard, maybe just return, telling the caller we don't want to play again
            return False
        else:
            # you were calling play_game again, but that causes the game to get more and more calls
            # on top of each other, ultimately reaching an error state
            # by returning first and then calling again, you avoid that problem
            return True

# the function returns whether it should play again
while play_game():
    pass
# once it leaves the loop, the game stops automatically here, no more code
</code>```

There's still a lot of room for improvement though; try implementing some more advanced forms of RSP, or make the computer more intelligent than just playing random, but have it use some kind of strategy, perhaps with a bit of randomness mixed in.

And code-wise, try separating the game from the way it is presented on the screen; what if you decided to do this on the web instead of on a console, or in a graphics window? You could also consider putting all the code in a nice class, getting rid of global variables and allowing you to create more copies of the game as needed.

Title: Unable to verify user input in game

Body:
I am creating a rock, paper, scissors game. I want it to be best of 3 matches and to be able to verify user input. I keep running into issues with the user input. I have tried multiple variations but I can't seem to figure it out. I know my code is probably messy, so any input on how to clean it up would be greatly appreciated. Thank you so much for your time.

import random
import sys
import time

print("Hello and welcome to the Rock, Paper, Scissors tournament.\n"
      "The tournament will be the best of 3 wins.\n"
      "It will be you against our highly intelligent computer opponent.\n"
      "Good luck!")

# Create a function for the game
def play_game():
    user_count = 0
    comp_count = 0
    tie_game = 0

    while comp_count < 2 and user_count < 2:
        user_choice = (int(input("-------------------------------------------"
                             "\nEnter choice by typing 1 2 or 3: \n 1. Rock \n 2. paper \n 3. scissor \n"
                             "-------------------------------------------\n")))
        if user_choice == 1:
            user_choice_name = 'Rock'
        elif user_choice == 2:
            user_choice_name = 'Paper'
        elif user_choice == 3:
            user_choice_name = 'Scissor'
        else:
            print("Please pick a valid number")

        print(f"\nYou have chosen: {user_choice_name}")
        print("\nNow it's the computer's turn to pick......")
        time.sleep(3)

        comp_choice = random.randint(1, 3)

        if comp_choice == 1:
            comp_choice_name = 'Rock'
        elif comp_choice == 2:
            comp_choice_name = 'Paper'
        else:
            comp_choice_name = 'Scissor'

        print(f"\nComputer has chosen: {comp_choice_name}\n")

        if user_choice == 1 and comp_choice == 2:
            comp_count += 1
            print("Computer wins this round with Paper! "
                  f"\n Computer: {comp_count}"
                  f"\n You: {user_count} \n\n")

        elif user_choice == 1 and comp_choice == 3:
            user_count += 1
            print("You win this round with Rock!"
                  f"\n Computer: {comp_count}"
                  f"\n You: {user_count} \n\n")

        elif user_choice == 2 and comp_choice == 1:
            user_count += 1
            print("You win this round with Paper!"
                  f"\n Computer: {comp_count}"
                  f"\n You: {user_count} \n\n")

        elif user_choice == 2 and comp_choice == 3:
            comp_count += 1
            print("Computer wins this round with Scissor!"
                  f"\n Computer: {comp_count}"
                  f"\n You: {user_count} \n\n")

        elif user_choice == 3 and comp_choice == 2:
            user_count += 1
            print("You win this round with Scissor!"
                  f"\n Computer: {comp_count}"
                  f"\n You: {user_count} \n\n")

        elif user_choice == 3 and comp_choice == 1:
            user_count += 1
            print("Computer wins this round with Rock!"
                  f"\n Computer: {comp_count}"
                  f"\n You: {user_count} \n\n")

        else:
            if user_choice == comp_choice:
                tie_game += 1
            print(f"This round was a tie! Both choosing {user_choice_name}, try again!"
                  f"\n Computer: {comp_count}"
                  f"\n You: {user_count} \n\n")
    else:
        print(f'The game is now over with a score of: \n You:{user_count} \n to \n Computer:{comp_count}')
        again = str(input("Do you want to play again, type 'yes' or 'no' \n"))
        if again.lower() == "no":
            print('Thank you for playing!')
            sys.exit()
        else:
            play_game()

play_game()

Body:
Since I had a few minutes to kill with a cup of coffee, here's a rewrite of your program with a bunch of improvements, the validation you asked about and some tips on coding style:

import random
import time

print("Hello and welcome to the Rock, Paper, Scissors tournament.\n"
      "The tournament will be the best of 3 wins.\n"
      "It will be you against our highly intelligent computer opponent.\n"
      "Good luck!")

# to avoid repeating these values over and over and changing numbers in to string,
# just defining them here. Name in capitals because it's global (generally bad)
# an even nicer solution would be to write a Game() class and put everything in
# there, but it would be a bit more advanced
RSP_OPTIONS = {
    1: 'Rock',
    2: 'Scissor',
    3: 'Paper'
}

def get_user_choice():
    # keep asking until a valid value is returned
    while True:
        # this is a bit fancy, but let's say you want to reuse the game for similar games
        # with different options from rock, scissor, paper, you'd want this code to still work

        # get a list of string versions of the numbers
        numbers = list(map(str, RSP_OPTIONS.keys()))
        # join them together like you presented them: 1, 2 or 3
        options = ', '.join(numbers[:-1]) + ' or ' + numbers[-1] + ':\n'
        # add the descriptions
        options = options + ''.join(f'{n}: {name}\n' for n, name in RSP_OPTIONS.items())
        try:
          user_choice = (int(input("-------------------------------------------\n"
                                   f"Enter choice by typing {options}"
                                   "-------------------------------------------\n")))
        except ValueError:
            # any invalid option
            user_choice = -1
        # check if it's one of the valid options
        if user_choice in RSP_OPTIONS:
            return user_choice
        else:
            # it makes sense to generate a new line where you want it, instead of having
            # to put new line characters at the start of other strings
            print("Please pick a valid number\n")

def beats(choice1, choice2):
    # choice1 beats choice2 if it's one greater, except when choice2 == 3 and choice1 == 1
    # but to make it even nicer and have it work for other similar games, you could say
    # "except when choice1 == the max choice and choice2 == the min choice"
    return (choice2 - choice1 == 1 or
            (choice1 == max(RSP_OPTIONS.keys()) and choice2 == min(RSP_OPTIONS.keys())))

# Create a function for the game
def play_game():
    user_count = 0
    comp_count = 0
    tie_game = 0

    # this is what you really want, best out of three, ties not counted?
    while comp_count + user_count < 3:
        user_choice = get_user_choice()

        print(f"You have chosen: {RSP_OPTIONS[user_choice]}\n")
        print("Now it's the computer's turn to pick......\n")
        # this wait is not very nice, the user might try to hit enter or something
        # you could consider printing the countdown, or telling the user to please wait
        # even then, it's kind of silly to pretend the computer has to work hard here
        time.sleep(3)

        # this choice is always valid, so no problem
        comp_choice = random.randint(1, 3)
        # note that you don't need the name, you can just look it up whenever in RSP_OPTIONS
        print(f"\nComputer has chosen: {RSP_OPTIONS[comp_choice]}\n")

        # getting rid of some repetition, note how the code really reads like what is intended
        if beats(comp_choice, user_choice):
            comp_count += 1
            # nice to also say what really beat them
            print(f"Computer wins this round with {RSP_OPTIONS[comp_choice]} over {RSP_OPTIONS[user_choice]}!\n")
        elif beats(user_choice, comp_choice):
            user_count += 1
            print(f"You win this round with {RSP_OPTIONS[user_choice]} over {RSP_OPTIONS[comp_choice]}!\n")
        else:
            # you can only get here on a tie
            tie_game += 1
            print(f"This round was a tie! Both choosing {RSP_OPTIONS[user_choice]}, try again!\n")
        # you always print this, so just do it after the options:
        print(f"Computer: {comp_count}\n"
              f"You: {user_count}\n\n")
    else:
        print(f'The game is now over with a score of:\n You:{user_count}\n to\n Computer:{comp_count}\n')
        again = str(input("Do you want to play again, type 'yes' or 'no' \n"))
        # let's quit on anything starting with n
        if again.lower()[0] == "n":
            print('Thank you for playing!\n')
            # instead of exiting hard, maybe just return, telling the caller we don't want to play again
            return False
        else:
            # you were calling play_game again, but that causes the game to get more and more calls
            # on top of each other, ultimately reaching an error state
            # by returning first and then calling again, you avoid that problem
            return True

# the function returns whether it should play again
while play_game():
    pass
# once it leaves the loop, the game stops automatically here, no more code

There's still a lot of room for improvement though; try implementing some more advanced forms of RSP, or make the computer more intelligent than just playing random, but have it use some kind of strategy, perhaps with a bit of randomness mixed in.

And code-wise, try separating the game from the way it is presented on the screen; what if you decided to do this on the web instead of on a console, or in a graphics window? You could also consider putting all the code in a nice class, getting rid of global variables and allowing you to create more copies of the game as needed.


问:
:last-child is not being recognized
I have a scroll to function that I need to execute to scroll to the last message in its container, which is the container with chunk_id. The problem is that it works as is for going to the container, but if I add last-child into the mix the function does not work. Any ideas what I am doing wrong?

Works

```<code>$.scrollTo('div[chunk_id="'+autoscroll+'"]', 800, {easing:'elasout',offset:-250} );
</code>```

Does not

```<code>$.scrollTo('div[chunk_id="'+autoscroll+'"]:last-child', 800, {easing:'elasout',offset:-250} );
</code>```

答:
You're trying to find the :last-child inside of the div, using the child selector:

```<code>'div[chunk_id="'+autoscroll+'"] > :last-child'
</code>```

Your code applies the :last-child filter to the div selector itself, so it only matches elements which are both div[chunk_id="'+autoscroll+'"] and :last-child.

Title: :last-child is not being recognized

Body:
I have a scroll to function that I need to execute to scroll to the last message in its container, which is the container with chunk_id. The problem is that it works as is for going to the container, but if I add last-child into the mix the function does not work. Any ideas what I am doing wrong?

Works

$.scrollTo('div[chunk_id="'+autoscroll+'"]', 800, {easing:'elasout',offset:-250} );

Does not

$.scrollTo('div[chunk_id="'+autoscroll+'"]:last-child', 800, {easing:'elasout',offset:-250} );

Body:
You're trying to find the :last-child inside of the div, using the child selector:

'div[chunk_id="'+autoscroll+'"] > :last-child'

Your code applies the :last-child filter to the div selector itself, so it only matches elements which are both div[chunk_id="'+autoscroll+'"] and :last-child.


问:
Week accuracy with testing data
I'm dealling with a data science problem, and I got this problem.

I have a labelled data (Training data) and non labelled data (Test data) and both of them have a lot of missing data.

I worked with my data and I split it to trainig data and validating data

I got a very good accuracy and a very small RMSE error between Y_validation and the predicted one ( model.predict(X_validate) ). But when I submit my solution, the RMSE error get bigger with testing data !

What can I do ?!

答:
This will happen sometimes when a model doesn't generalize well. This can happen when a model over fits to training data. </p>

<p>Resampling or better sampling of test and train data (which as mentioned, needs to be labeled) can help you get a better generalized model. </p>

Title: Week accuracy with testing data

Body:
This will happen sometimes when a model doesn't generalize well. This can happen when a model over fits to training data.

Resampling or better sampling of test and train data (which as mentioned, needs to be labeled) can help you get a better generalized model.


问:
ignore a line in a markdown file with Jekyll
Is there a way to ignore a text line in a markdown document from the Jekyll engine?

On the main README.md, I have a link to my generated pages url ala,
View the [Docs as a Website](https://gitpages.mycompany.com/myrepo/) which links to our enterprise equivalent of github.io pages powered by Jekyll reading the /docs/ folder.

For obvious reasons, I would like to not show this on the pages site as the viewer is already there and it ends up in an endless loop if users were to keep clicking it.

Is there a way to have it show on the code-view readme.md but not on the rendered jekyll version?

答:
Solution :

If you want Jekyll to skip processing lines (or even a single character) into the baked /_site/ output, use the Liquid {% comment %} tag:

```<code>{% comment %}

     Character or lines for Jekyll to skip.

{% endcomment %}
</code>```

Example :

Before:

Code w/o {% comment %} + HTML render

After:

Code w/   {% comment %} + HTML render

Explanation :

If a markdown.md page has Jekyll Front Matter at the top, then it will be processed by Jekyll into a markdown.html page (see Jekyll's docs for more info).

Pages processed by Jekyll can contain Liquid code (specifically Jekyll's implementation of Liquid).

Liquid features a {% comment %} tag. And it works for Jekyll.

From Liquid's documentation of the comment tag:

Comment

Allows you to leave un-rendered code inside a Liquid template. Any
  text within the opening and closing comment blocks will not be
  printed, and any Liquid code within will not be executed.

If Jekyll processes your markdown.md page, it will process all Liquid statements, and will totally omit the {% comment %} tag + {% endcomment %} tag + and everything in between from the output file.

The text wrapped by a {% comment %} tag does not specifically need to contain Liquid for Jekyll to exclude it. Everything inside will be omitted from the output page: e.g.  elements, other code, plaintext, etc.

Word of Caution :

Jekyll will still throw an error if you have improper Liquid syntax, even if it is inside a comment tag.

The following results in an error, and Jekyll will not build:

```<code>{% comment %}

     Character or lines for Jekyll to skip.
     {% assign abc

{% endcomment %}
</code>```

To prevent this, either ensure (1) all the code inside your comment tag is valid Liquid, or (2) prevent Jekyll from evaluating the code by wrapping it inside a {% raw %} tag:

```<code>{% comment %}
     {% raw %}

     Character or lines for Jekyll to skip.
     {% assign abc

     {% endraw %}
{% endcomment %}
</code>```

Then everything inside the comment will be successfully excluded from the /_site/ files Jekyll outputs.

For more information, see Liquid's documentation of the raw tag.

Alternatively:

If you just want to link from the site's GitHub repository
-> to the site generated by Jekyll + GitHub Pages

Log in

Go to https://github.com/ user-or-org / repository-name

Click the "Edit" button (above "Clone or download" and below "Settings")

Add the URL to your GitHub Pages website in the 2nd text field that prompts "Website for this repository (optional)", and click "Save"

Remove the URL from your README.md

Body:
Solution :

If you want Jekyll to skip processing lines (or even a single character) into the baked /_site/ output, use the Liquid {% comment %} tag:

{% comment %}

     Character or lines for Jekyll to skip.

{% endcomment %}

Example :

Before:

Code w/o {% comment %} + HTML render

After:

Code w/   {% comment %} + HTML render

Explanation :

If a markdown.md page has Jekyll Front Matter at the top, then it will be processed by Jekyll into a markdown.html page (see Jekyll's docs for more info).

Pages processed by Jekyll can contain Liquid code (specifically Jekyll's implementation of Liquid).

Liquid features a {% comment %} tag. And it works for Jekyll.

From Liquid's documentation of the comment tag:

Comment

Allows you to leave un-rendered code inside a Liquid template. Any
  text within the opening and closing comment blocks will not be
  printed, and any Liquid code within will not be executed.

If Jekyll processes your markdown.md page, it will process all Liquid statements, and will totally omit the {% comment %} tag + {% endcomment %} tag + and everything in between from the output file.

The text wrapped by a {% comment %} tag does not specifically need to contain Liquid for Jekyll to exclude it. Everything inside will be omitted from the output page: e.g. <html> elements, other code, plaintext, etc.

Word of Caution :

Jekyll will still throw an error if you have improper Liquid syntax, even if it is inside a comment tag.

The following results in an error, and Jekyll will not build:

{% comment %}

     Character or lines for Jekyll to skip.
     {% assign abc

{% endcomment %}

To prevent this, either ensure (1) all the code inside your comment tag is valid Liquid, or (2) prevent Jekyll from evaluating the code by wrapping it inside a {% raw %} tag:

{% comment %}
     {% raw %}

     Character or lines for Jekyll to skip.
     {% assign abc

     {% endraw %}
{% endcomment %}

Then everything inside the comment will be successfully excluded from the /_site/ files Jekyll outputs.

For more information, see Liquid's documentation of the raw tag.

Alternatively:

If you just want to link from the site's GitHub repository
-> to the site generated by Jekyll + GitHub Pages

Log in

Go to https://github.com/ user-or-org / repository-name

Click the "Edit" button (above "Clone or download" and below "Settings")

Add the URL to your GitHub Pages website in the 2nd text field that prompts "Website for this repository (optional)", and click "Save"

Remove the URL from your README.md


问:
I've started a panic with my index out of range, and I can't get out
I'm writing this program to become comfortable with types (not objects!).

The basic premise is the user enters an animal name (cow, snake bird), then an action (eat, move, sound.) My code then looks it up and returns the value.

So, the user entry is suppose to be on ONE line separated by a " ". I use strings.Split.

I'm getting a "panic" notice when the user only enters a single char. I'm thinking this panic arises out of the compiler trying to "split" a single char.

TWO Questions:
1. Am I right?
2. How do I fix it?

```<code>package main

import (
    "bufio"
    "fmt"
    "os"
    "strings"
)

//Create our type object.
type animal struct {
    aType, eats, moves, sounds string
}

//Create our methods.
func (animal animal) info (querie string) {
    if querie == "eats" {
        fmt.Printf("The animal, %s , eats %s\n ", animal.aType, animal.eats)
    } else if querie == "moves" {
        fmt.Printf("The animal, %s , moves by  %s\n ", animal.aType, animal.moves)
    } else {
        fmt.Printf("The animal, %s , makes the sound %s\n ", animal.aType, animal.sounds)
    }
}

func main() {
    //Now create our animals

    cow := animal{aType:"cow", eats: "grass", moves: "walking", sounds: "moo"}
    bird := animal{aType:"bird", eats: "worms", moves: "flying", sounds: "peep"}
    snake := animal{aType:"snake", eats: "mice", moves: "slithering", sounds: "hiss"}
    // need a boolean to perpetuate our loop
    var flag bool = true

    for flag {
        fmt.Println("Remember enter X to exit")
        fmt.Printf(">please enter your (format: type & information) request -> ")
        scanner := bufio.NewScanner(os.Stdin)
        scanner.Scan()
        request := scanner.Text()

        //Capture user entered data

        typed := strings.Split(request, " ")[0]
        if typed == "X" {
            flag = false
            break
        }
        infoe := strings.Split(request, " ")[1]

        // contruct the logic tree.

        if !((infoe == "eat") || (infoe == "move") || (infoe == "speak")) {
            switch typed {
            case "cow":
                cow.info(infoe)

            case "snake":
                snake.info(infoe)

            case "bird":
                bird.info(infoe)
            default:
                fmt.Println("I don't know about that animal.")
            }
        } else {
            fmt.Printf("I don't have that informtion")
                break
            }
        }
    }
</code>```

答:
Create the scanner outside the loop to avoid discarding buffered data.  Break when Scan() returns false. Check for and handle invalid input.</p>

```<code>scanner := bufio.NewScanner(os.Stdin)
for {
    fmt.Println("Remember enter X to exit")
    if !scanner.Scan() {
        break
    }
    request := scanner.Text()
    parts := strings.Split(request, " ")
    if parts[0] == "X" {
        break
    }
    if len(parts) < 2 {
        fmt.Println("bad input")
        break
    }

    typed := parts[0]
    infoe := parts[1]

    ...
</code>```

Body:
I'm writing this program to become comfortable with types (not objects!).

The basic premise is the user enters an animal name (cow, snake bird), then an action (eat, move, sound.) My code then looks it up and returns the value.

So, the user entry is suppose to be on ONE line separated by a " ". I use strings.Split.

I'm getting a "panic" notice when the user only enters a single char. I'm thinking this panic arises out of the compiler trying to "split" a single char.

TWO Questions:
1. Am I right?
2. How do I fix it?

package main

import (
    "bufio"
    "fmt"
    "os"
    "strings"
)

//Create our type object.
type animal struct {
    aType, eats, moves, sounds string
}

//Create our methods.
func (animal animal) info (querie string) {
    if querie == "eats" {
        fmt.Printf("The animal, %s , eats %s\n ", animal.aType, animal.eats)
    } else if querie == "moves" {
        fmt.Printf("The animal, %s , moves by  %s\n ", animal.aType, animal.moves)
    } else {
        fmt.Printf("The animal, %s , makes the sound %s\n ", animal.aType, animal.sounds)
    }
}

func main() {
    //Now create our animals

    cow := animal{aType:"cow", eats: "grass", moves: "walking", sounds: "moo"}
    bird := animal{aType:"bird", eats: "worms", moves: "flying", sounds: "peep"}
    snake := animal{aType:"snake", eats: "mice", moves: "slithering", sounds: "hiss"}
    // need a boolean to perpetuate our loop
    var flag bool = true

    for flag {
        fmt.Println("Remember enter X to exit")
        fmt.Printf(">please enter your (format: type & information) request -> ")
        scanner := bufio.NewScanner(os.Stdin)
        scanner.Scan()
        request := scanner.Text()

        //Capture user entered data

        typed := strings.Split(request, " ")[0]
        if typed == "X" {
            flag = false
            break
        }
        infoe := strings.Split(request, " ")[1]

        // contruct the logic tree.

        if !((infoe == "eat") || (infoe == "move") || (infoe == "speak")) {
            switch typed {
            case "cow":
                cow.info(infoe)

            case "snake":
                snake.info(infoe)

            case "bird":
                bird.info(infoe)
            default:
                fmt.Println("I don't know about that animal.")
            }
        } else {
            fmt.Printf("I don't have that informtion")
                break
            }
        }
    }

Body:
Create the scanner outside the loop to avoid discarding buffered data.  Break when Scan() returns false. Check for and handle invalid input.

scanner := bufio.NewScanner(os.Stdin)
for {
    fmt.Println("Remember enter X to exit")
    if !scanner.Scan() {
        break
    }
    request := scanner.Text()
    parts := strings.Split(request, " ")
    if parts[0] == "X" {
        break
    }
    if len(parts) < 2 {
        fmt.Println("bad input")
        break
    }

    typed := parts[0]
    infoe := parts[1]

    ...


问:
Find the index of a dict within a list, by matching the dict's value
I have a list of dicts:

```<code>list = [{'id':'1234','name':'Jason'},
        {'id':'2345','name':'Tom'},
        {'id':'3456','name':'Art'}]
</code>```

How can I efficiently find the index position [0],[1], or [2] by matching on name = 'Tom'?

If this were a one-dimensional list I could do list.index() but I'm not sure how to proceed by searching the values of the dicts within the list.

答:
```<code>def search(itemID,list):
     return[i for i in list if i.itemID==itemID]
</code>```

Body:
I have a list of dicts:

list = [{'id':'1234','name':'Jason'},
        {'id':'2345','name':'Tom'},
        {'id':'3456','name':'Art'}]

How can I efficiently find the index position [0],[1], or [2] by matching on name = 'Tom'?

If this were a one-dimensional list I could do list.index() but I'm not sure how to proceed by searching the values of the dicts within the list.


问:
What sites are using my GitHub hosted script?
Suppose I have a JavaScript script named foo.js in a GitHub repo. I need to know what sites (domains) are using this script. Thus, for instance, if a website www.example.com is referencing my script...

```<code><html>
  <head>
    <script src="https://myGitHubRepo/foo.js"></script>
  </head>
  etc...
</html>
</code>```

I'd like to get, track or list example.com as a domain. To be more clear, I don't want to track actual users visiting www.example.com nor their IPs nor anything like this, I just want to track or make a list of the sites (domains) referencing my script in their HTMLs. Is that possible?

PS: some hypothetical solutions and their problems:

The first idea that comes to mind is using an analytics tool; however, despite being the owner of my code, I'm not the owner of the site containing the repo: GitHub is the owner. Therefore, using an analytics tools seems to be impossible.

I can't do calls to my server: again, I don't have a server, it's a GitHub repo.

A simple window.location.hostname in the script would get what I want, but it would get it on the client side. I don't know if it's possible sending that information back to me... actually, I don't even know if that is legal.

答:
Don't do it. Telemetry is tricky - and people will opt to not use your script.

Also without "place" to gather this information you cannot do it on github.

You can try leveraging "code" search engines like:
 https://publicwww.com/
 https://www.nerdydata.com/

and similars

Body:
Suppose I have a JavaScript script named foo.js in a GitHub repo. I need to know what sites (domains) are using this script. Thus, for instance, if a website www.example.com is referencing my script...

  etc...

I'd like to get, track or list example.com as a domain. To be more clear, I don't want to track actual users visiting www.example.com nor their IPs nor anything like this, I just want to track or make a list of the sites (domains) referencing my script in their HTMLs. Is that possible?

PS: some hypothetical solutions and their problems:

The first idea that comes to mind is using an analytics tool; however, despite being the owner of my code, I'm not the owner of the site containing the repo: GitHub is the owner. Therefore, using an analytics tools seems to be impossible.

I can't do calls to my server: again, I don't have a server, it's a GitHub repo.

A simple window.location.hostname in the script would get what I want, but it would get it on the client side. I don't know if it's possible sending that information back to me... actually, I don't even know if that is legal.


问:
Executing function pointer from a in std::vector iterator
I'm trying to write an application that adds function pointers to a vector based on some external event, then iterates through the list. For some reason, I can't seem to get the functions to actually execute despite the fact that they are added to the vector.

What am I missing?

main.cpp

```<code>#include "GameLogic.h"

GameLogic* gameLogic = nullptr;

int main(int argc, char* argv[])
{
    gameLogic = new GameLogic();
    gameLogic->run();
}
</code>```

GameLogic.cpp

```<code>#include "GameLogic.h"

GameLogic::GameLogic()
{
    FireAction.push_back(&GameLogic::AddCredit);
    FireAction.push_back(&GameLogic::AddPlayer);
}

GameLogic::~GameLogic() {}

void GameLogic::run()
{

    for (std::vector<std::function<void(const GameLogic)>>::iterator it = FireAction.begin(); it != FireAction.end(); it++)
    {
        std::cout << "Iterator Loop" << std::endl;
        (*it);
    }
}

void GameLogic::AddCredit() { std::cout << "Added Credit" << std::endl; }
void GameLogic::AddPlayer() { std::cout << "Added Player" << std::endl; }
</code>```

GameLogic.h

```<code>#pragma once
#include <functional>
#include <iostream>
#include <vector>

class GameLogic
{
public:
    GameLogic();
    ~GameLogic();
    void run();

private:
    void AddCredit();
    void AddPlayer();

    std::vector<std::function<void(const GameLogic)>> FireAction;
};
</code>```

Execution Output:

```<code>Iterator Loop
Iterator Loop
</code>```

Expected Output:

```<code>Iterator Loop
Added Credit
Iterator Loop
Added Player
</code>```

答:
You are dereferencing the vector iterators to access the stored std::function objects, but you are not actually calling their operator() to execute your class methods.  You need to add an extra set of parenthesis for those calls, eg:

(*it)(*this);
```

<p>This is made clearer if you store the <code>std::function</code>s to a local variable before calling them, eg:</p>

<pre class="lang-cpp prettyprint-override"><code>std::function<void(const GameLogic)> &func = *it;
// better: auto &func = *it;
func(*this);
</code>```

Now, that being said, your std::function objects need to take your GameLogic object by pointer or reference, instead of by value, eg:

std::vector<std::function<void(const GameLogic&)>> FireAction;
...
(*it)(*this);
// or:
// auto &func = *it;
// func(*this);
```

<p>Or:</p>

<pre class="lang-cpp prettyprint-override"><code>std::vector<std::function<void(const GameLogic*)>> FireAction;
...
(*it)(this);
// or:
// auto &func = *it;
// func(this);
</code>```

You can avoid this requirement by storing lambdas instead of pointer-to-member's, so you don't have to pass around the GameLogic object explicitly:

std::vector<std::function<void()>> FireAction;
...
FireAction.push_back([this](){ this->AddCredit(); });
FireAction.push_back([this](){ this->AddPlayer(); });
...
(*it)();
// or:
// auto &func = *it;
// func();
```

<p>Lastly, to simply the code even further, consider using <code>auto</code> (as seen above) and range-based for loops, eg:</p>

<pre class="lang-cpp prettyprint-override"><code>void GameLogic::run()
{
    for (auto it = FireAction.begin(); it != FireAction.end(); ++it)
    {
        std::cout << "Iterator Loop" << std::endl;
        (*it)();
        // or:
        // auto &func = *it;
        // func();
    }
}
</code>```

Or:

void GameLogic::run()
{
    for (auto &func : FireAction)
    {
        std::cout << "Iterator Loop" << std::endl;
        func();
    }
}
```

Body:
I'm trying to write an application that adds function pointers to a vector based on some external event, then iterates through the list. For some reason, I can't seem to get the functions to actually execute despite the fact that they are added to the vector.

What am I missing?

main.cpp

#include "GameLogic.h"

GameLogic* gameLogic = nullptr;

int main(int argc, char* argv[])
{
    gameLogic = new GameLogic();
    gameLogic->run();
}

GameLogic.cpp

#include "GameLogic.h"

GameLogic::GameLogic()
{
    FireAction.push_back(&GameLogic::AddCredit);
    FireAction.push_back(&GameLogic::AddPlayer);
}

GameLogic::~GameLogic() {}

void GameLogic::run()
{

    for (std::vector<std::function<void(const GameLogic)>>::iterator it = FireAction.begin(); it != FireAction.end(); it++)
    {
        std::cout << "Iterator Loop" << std::endl;
        (*it);
    }
}

void GameLogic::AddCredit() { std::cout << "Added Credit" << std::endl; }
void GameLogic::AddPlayer() { std::cout << "Added Player" << std::endl; }

GameLogic.h

#pragma once
#include <functional>
#include <iostream>
#include <vector>

class GameLogic
{
public:
    GameLogic();
    ~GameLogic();
    void run();

private:
    void AddCredit();
    void AddPlayer();

    std::vector<std::function<void(const GameLogic)>> FireAction;
};

Execution Output:

Iterator Loop
Iterator Loop

Expected Output:

Iterator Loop
Added Credit
Iterator Loop
Added Player

Body:
You are dereferencing the vector iterators to access the stored std::function objects, but you are not actually calling their operator() to execute your class methods.  You need to add an extra set of parenthesis for those calls, eg:

(*it)(*this);

This is made clearer if you store the std::functions to a local variable before calling them, eg:

std::function<void(const GameLogic)> &func = *it;
// better: auto &func = *it;
func(*this);

Now, that being said, your std::function objects need to take your GameLogic object by pointer or reference, instead of by value, eg:

std::vector<std::function<void(const GameLogic&)>> FireAction;
...
(*it)(*this);
// or:
// auto &func = *it;
// func(*this);

Or:

std::vector<std::function<void(const GameLogic*)>> FireAction;
...
(*it)(this);
// or:
// auto &func = *it;
// func(this);

You can avoid this requirement by storing lambdas instead of pointer-to-member's, so you don't have to pass around the GameLogic object explicitly:

std::vector<std::function<void()>> FireAction;
...
FireAction.push_back([this](){ this->AddCredit(); });
FireAction.push_back([this](){ this->AddPlayer(); });
...
(*it)();
// or:
// auto &func = *it;
// func();

Lastly, to simply the code even further, consider using auto (as seen above) and range-based for loops, eg:

void GameLogic::run()
{
    for (auto it = FireAction.begin(); it != FireAction.end(); ++it)
    {
        std::cout << "Iterator Loop" << std::endl;
        (*it)();
        // or:
        // auto &func = *it;
        // func();
    }
}

Or:

void GameLogic::run()
{
    for (auto &func : FireAction)
    {
        std::cout << "Iterator Loop" << std::endl;
        func();
    }
}


问:
How to reduce queries in django model has_relation method?
Here are two example Django models. Pay special attention to the has_pet method.

```<code>class Person(models.Model):
    name = models.CharField(max_length=255)

    def has_pet(self):
        return bool(self.pets.all().only('id'))

class Pet(models.Model):
    name = models.CharField(max_length=255)
    owner = models.ForeignKey(Person, blank=True, null=True, related_name="pets")
</code>```

The problem here is that the has_pet method always generates a query. If you do something like this.

```<code>p = Person.objects.get(id=1)
if p.has_pet():
    ...
</code>```

Then you will actually be doing an extra query just to check if one person has a pet. That is a big problem if you have to check multiple people. It will also generate queries if used in templates like this.

```<code>{% for person in persons %}
    {% if person.has_pet %}
        {{ person.name }} owns a pet
    {% else %}
        {{ person.name }} is petless
    {% endif %}
{% endfor %}
</code>```

This example will actually perform an extra query for every person in the persons queryset while it is rendering the template.

Is there a way to do this with just one query, or at least doing less than one extra query per person? Maybe there is another way to design this to avoid the problem altogether.

I thought of adding a BooleanField to Person, and having that field be updated whenever a pet is saved or deleted. Is that really the right way to go?

Also, I already have memcached setup properly, so those queries only happen if the results are not already cached. I'm looking to remove the queries in the first place for even greater optimization.

答:
If you want a list of all the people with pets you can do that in a single query:

```<code>Person.objects.exclude(pets=None)
</code>```

Sounds like you want to iterate over a single list of people, using annotations would probably make sense:

```<code>for person in Person.objects.annotate(has_pet=Count('pets')):
     if person.has_pet: # if has_pet is > 0 this is True, no extra query
</code>```

It'd be nice if Django had an Exists aggregate but it doesn't, and I don't know how difficult it would be to add one. You should profile of course, and figure out if this works for you.

Personally, I'd probably just store has_pets as a boolean on the model, it's probably the most efficient approach.

Body:
Here are two example Django models. Pay special attention to the has_pet method.

class Person(models.Model):
    name = models.CharField(max_length=255)

    def has_pet(self):
        return bool(self.pets.all().only('id'))

class Pet(models.Model):
    name = models.CharField(max_length=255)
    owner = models.ForeignKey(Person, blank=True, null=True, related_name="pets")

The problem here is that the has_pet method always generates a query. If you do something like this.

p = Person.objects.get(id=1)
if p.has_pet():
    ...

Then you will actually be doing an extra query just to check if one person has a pet. That is a big problem if you have to check multiple people. It will also generate queries if used in templates like this.

{% for person in persons %}
    {% if person.has_pet %}
        {{ person.name }} owns a pet
    {% else %}
        {{ person.name }} is petless
    {% endif %}
{% endfor %}

This example will actually perform an extra query for every person in the persons queryset while it is rendering the template.

Is there a way to do this with just one query, or at least doing less than one extra query per person? Maybe there is another way to design this to avoid the problem altogether.

I thought of adding a BooleanField to Person, and having that field be updated whenever a pet is saved or deleted. Is that really the right way to go?

Also, I already have memcached setup properly, so those queries only happen if the results are not already cached. I'm looking to remove the queries in the first place for even greater optimization.

Body:
If you want a list of all the people with pets you can do that in a single query:

Person.objects.exclude(pets=None)

Sounds like you want to iterate over a single list of people, using annotations would probably make sense:

for person in Person.objects.annotate(has_pet=Count('pets')):
     if person.has_pet: # if has_pet is > 0 this is True, no extra query

It'd be nice if Django had an Exists aggregate but it doesn't, and I don't know how difficult it would be to add one. You should profile of course, and figure out if this works for you.

Personally, I'd probably just store has_pets as a boolean on the model, it's probably the most efficient approach.


问:
Why I am receiving 405 error for request?
I am trying to send a post request using python3.6 to oauth2 server to get my access token, it is showing response 405. Can someone tell me what I am doing wrong here</p>

```<code>import requests
client_id = 'client_id'
client_secret = 'my client secret'
r = request.post('serverurl/oauth2/token&Content-Type="application/x-www-form-urlencoded"',data = {'grant_type':'authorization_code',
'code':'91a8a5e4-c5b3-4e2a-91ca-d59fe139526c',
'client_id':client_id,
'client_secret':client_secret,
'redirect_uri':'actualredirecturl'
}
</code>```

答:
I solved it using the following code

here is the code

```<code>import requests,base64
client_id = "myclientid"
client_secret = "myclientsecret"
redirect_uri = 'my redirect url'
code = 'code return by server on login'
requestHeaders = {
    'Authorization': 'Basic ' + base64.b64encode(client_id + ':' + client_secret),
    'Content-Type': 'application/x-www-form-urlencoded'
}
requestBody = {
    'grant_type': 'authorization_code',
    'code': code,
    'redirect_uri': redirect_uri
}
response = requests.post('token_url', data=requestBody, headers=requestHeaders)
token = response.json()['access_token']
</code>```

Hope that helps

Body:
I am trying to send a post request using python3.6 to oauth2 server to get my access token, it is showing response 405. Can someone tell me what I am doing wrong here

import requests
client_id = 'client_id'
client_secret = 'my client secret'
r = request.post('serverurl/oauth2/token&Content-Type="application/x-www-form-urlencoded"',data = {'grant_type':'authorization_code',
'code':'91a8a5e4-c5b3-4e2a-91ca-d59fe139526c',
'client_id':client_id,
'client_secret':client_secret,
'redirect_uri':'actualredirecturl'
}

Body:
I solved it using the following code

here is the code

import requests,base64
client_id = "myclientid"
client_secret = "myclientsecret"
redirect_uri = 'my redirect url'
code = 'code return by server on login'
requestHeaders = {
    'Authorization': 'Basic ' + base64.b64encode(client_id + ':' + client_secret),
    'Content-Type': 'application/x-www-form-urlencoded'
}
requestBody = {
    'grant_type': 'authorization_code',
    'code': code,
    'redirect_uri': redirect_uri
}
response = requests.post('token_url', data=requestBody, headers=requestHeaders)
token = response.json()['access_token']

Hope that helps


问:
replacing componentDidMount with useEffect
I was going through React Hooks docs and it mentioned

If you’re familiar with React class lifecycle methods, you can think
  of useEffect Hook as componentDidMount, componentDidUpdate, and
  componentWillUnmount combined.

Suppose I have a class component right now where in componentDidMount I am doing something like this

```<code>  componentDidMount() {
    MapboxGL.setTelemetryEnabled(false);
  }
</code>```

As far as I can recall, Component did mount is only called once in lifecycle?

If I were to use react hooks then it would be something like this

```<code>  useEffect(() => {
   MapboxGL.setTelemetryEnabled(false);
  });
</code>```

This would call my function everytime state changes in react functional hooks component? Wouldn't it be redundant to call  MapboxGL.setTelemetryEnabled(false); to call this everytime? when you only want to do it once component have mounted?

React docs have showed how useEffect can replace multiple lifecycle methods but I am still unable to comprehend how react hooks can replace componentDidMount?

Also, Just a side note question, Can you make a full fledge app using hooks (something like foursquare or instagram?)

答:
You need to add a dependency array for it to know when to recall this hook. An empty dep array will only call it once aka "on mount". And if you don't provide a dep array then it will just be called on every re-render.</p>

```<code>useEffect(() => {
   MapboxGL.setTelemetryEnabled(false);
}, []);
</code>```

Body:
I was going through React Hooks docs and it mentioned

If you’re familiar with React class lifecycle methods, you can think
  of useEffect Hook as componentDidMount, componentDidUpdate, and
  componentWillUnmount combined.

Suppose I have a class component right now where in componentDidMount I am doing something like this

  componentDidMount() {
    MapboxGL.setTelemetryEnabled(false);
  }

As far as I can recall, Component did mount is only called once in lifecycle?

If I were to use react hooks then it would be something like this

  useEffect(() => {
   MapboxGL.setTelemetryEnabled(false);
  });

This would call my function everytime state changes in react functional hooks component? Wouldn't it be redundant to call  MapboxGL.setTelemetryEnabled(false); to call this everytime? when you only want to do it once component have mounted?

React docs have showed how useEffect can replace multiple lifecycle methods but I am still unable to comprehend how react hooks can replace componentDidMount?

Also, Just a side note question, Can you make a full fledge app using hooks (something like foursquare or instagram?)

Body:
You need to add a dependency array for it to know when to recall this hook. An empty dep array will only call it once aka "on mount". And if you don't provide a dep array then it will just be called on every re-render.

useEffect(() => {
   MapboxGL.setTelemetryEnabled(false);
}, []);


答:
The byte arrays in your example are not a valid UTF-8. Basically, if you see ��� symbols in C# output, it means Encoding.UTF8.GetString() used a replacement character to represent encoded input byte sequence that cannot be converted to an output character. Check DecoderReplacementFallback remarks for more details.

However, you still can reproduce the same exact behavior of Encoding.UTF8.GetString() in PHP:

$bytes32 = [144, 204, 205, 119, 77, 176, 172, 140, 110, 162, 222, 255, 14, 38, 252, 82, 118, 138, 130, 124, 145, 199, 55, 162, 224, 80, 102, 141, 140, 57, 194, 36];
$string32 = \pack('C*', ...$bytes32);
$string32Utf8 = \mb_convert_encoding($string32, 'ASCII', 'UTF-8');

$bytes70 = [239, 191, 189, 239, 191, 189, 239, 191, 189, 119, 77, 239, 191, 189, 239, 191, 189, 239, 191, 189, 110, 239, 191, 189, 239, 191, 189, 239, 191, 189, 14, 38, 239, 191, 189, 82, 118, 239, 191, 189, 239, 191, 189, 124, 239, 191, 189, 239, 191, 189, 55, 239, 191, 189, 239, 191, 189, 80, 102, 239, 191, 189, 239, 191, 189, 57, 239, 191, 189, 36];
$string70 = \pack('C*', ...$bytes70);
$string70Utf8 = \mb_convert_encoding($string70, 'ASCII', 'UTF-8');

\var_dump($string32Utf8, $string70Utf8, $string32Utf8 === $string70Utf8);
```

You can test it here: https://3v4l.org/je8gf

Things I did differently:

Since byte array represents UTF-8 string, we can't use chr to convert it to a binary string. As described in chr function documentation:

this function is not aware of any string encoding, and in particular cannot be passed a Unicode code point value to generate a string in a multibyte encoding like UTF-8 or UTF-16.

pack function, on the other hand, can handle various types of binary data formats. \pack('C*', ...$bytes32) means that byte array will treated as a sequence of unsigned chars and packed into binary string.

utf8_decode function has a very confusing name; it should be named something like utf8_to_iso88591 because that is exactly what it does:

Converts a string with ISO-8859-1 characters encoded with UTF-8 to single-byte ISO-8859-1

If we want to replicate Encoding.UTF8.GetString() example, what we really need to do, is to convert UTF-8 encoded binary string to ASCII. And you can do it using mb_convert_encoding function, just like that: mb_convert_encoding($utf8String, 'ASCII', 'UTF-8')

Hope these comments will help!

Title: PHP's utf8_decode and C#'s Encoding.UTF8.GetString returning different outputs for the same input

Body:
I have this PHP code that converts two byte arrays (one having 32 bytes, the other having 70 bytes) in UTF-8 strings using utf8_decode():

$bytes32 = [144, 204, 205, 119, 77, 176, 172, 140, 110, 162, 222, 255, 14, 38, 252, 82, 118, 138, 130, 124, 145, 199, 55, 162, 224, 80, 102, 141, 140, 57, 194, 36];
$string32 = implode(array_map("chr", $bytes32));
$string32Utf8 = utf8_decode($string32);

$bytes70 = [239, 191, 189, 239, 191, 189, 239, 191, 189, 119, 77, 239, 191, 189, 239, 191, 189, 239, 191, 189, 110, 239, 191, 189, 239, 191, 189, 239, 191, 189, 14, 38, 239, 191, 189, 82, 118, 239, 191, 189, 239, 191, 189, 124, 239, 191, 189, 239, 191, 189, 55, 239, 191, 189, 239, 191, 189, 80, 102, 239, 191, 189, 239, 191, 189, 57, 239, 191, 189, 36];
$string70 = implode(array_map("chr", $bytes70));
$string70Utf8 = utf8_decode($string70);

echo '$string32Utf8: ' . $string32Utf8; // echoes ???wM???n??&?Rv??|??7??Pf??9?$
echo '$string70Utf8: ' . $string70Utf8; // echoes ???wM???n???&?Rv??|??7??Pf??9?$
echo '$string32Utf8 === $string70Utf8: ' . json_encode($string32Utf8 ===  $string70Utf8); // echoes false

I then have this C# code that does the same thing using Encoding.UTF8.GetString():

byte[] bytes32 = new byte[] { 144, 204, 205, 119, 77, 176, 172, 140, 110, 162, 222, 255, 14, 38, 252, 82, 118, 138, 130, 124, 145, 199, 55, 162, 224, 80, 102, 141, 140, 57, 194, 36 };
string string32Utf8 = Encoding.UTF8.GetString(bytes32);

byte[] bytes70 = new byte[] { 239, 191, 189, 239, 191, 189, 239, 191, 189, 119, 77, 239, 191, 189, 239, 191, 189, 239, 191, 189, 110, 239, 191, 189, 239, 191, 189, 239, 191, 189, 14, 38, 239, 191, 189, 82, 118, 239, 191, 189, 239, 191, 189, 124, 239, 191, 189, 239, 191, 189, 55, 239, 191, 189, 239, 191, 189, 80, 102, 239, 191, 189, 239, 191, 189, 57, 239, 191, 189, 36 };
string string70Utf8 = Encoding.UTF8.GetString(bytes70);

Console.WriteLine("string32Utf8: " + string32Utf8); // Writes ���wM���n���&�Rv��|��7��Pf��9�$
Console.WriteLine("string70Utf8: " + string70Utf8); // Writes ���wM���n���&�Rv��|��7��Pf��9�$
Console.WriteLine("string32Utf8 == string70Utf8: " + (string32Utf8 == string70Utf8)); // Writes true

First of all, in C#, both byte arrays result in the same string after conversion, unlike with PHP. Second, the strings are different in C# compared with PHP.

Is there a function in PHP that will actually return the same output as C#'s Encoding.UTF8.GetString() given the same input? Or is there something I'm missing that's actually resulting in the different outputs between C# and PHP?

Body:
The byte arrays in your example are not a valid UTF-8. Basically, if you see ��� symbols in C# output, it means Encoding.UTF8.GetString() used a replacement character to represent encoded input byte sequence that cannot be converted to an output character. Check DecoderReplacementFallback remarks for more details.

However, you still can reproduce the same exact behavior of Encoding.UTF8.GetString() in PHP:

$bytes32 = [144, 204, 205, 119, 77, 176, 172, 140, 110, 162, 222, 255, 14, 38, 252, 82, 118, 138, 130, 124, 145, 199, 55, 162, 224, 80, 102, 141, 140, 57, 194, 36];
$string32 = \pack('C*', ...$bytes32);
$string32Utf8 = \mb_convert_encoding($string32, 'ASCII', 'UTF-8');

$bytes70 = [239, 191, 189, 239, 191, 189, 239, 191, 189, 119, 77, 239, 191, 189, 239, 191, 189, 239, 191, 189, 110, 239, 191, 189, 239, 191, 189, 239, 191, 189, 14, 38, 239, 191, 189, 82, 118, 239, 191, 189, 239, 191, 189, 124, 239, 191, 189, 239, 191, 189, 55, 239, 191, 189, 239, 191, 189, 80, 102, 239, 191, 189, 239, 191, 189, 57, 239, 191, 189, 36];
$string70 = \pack('C*', ...$bytes70);
$string70Utf8 = \mb_convert_encoding($string70, 'ASCII', 'UTF-8');

\var_dump($string32Utf8, $string70Utf8, $string32Utf8 === $string70Utf8);

You can test it here: https://3v4l.org/je8gf

Things I did differently:

Since byte array represents UTF-8 string, we can't use chr to convert it to a binary string. As described in chr function documentation:

this function is not aware of any string encoding, and in particular cannot be passed a Unicode code point value to generate a string in a multibyte encoding like UTF-8 or UTF-16.

pack function, on the other hand, can handle various types of binary data formats. \pack('C*', ...$bytes32) means that byte array will treated as a sequence of unsigned chars and packed into binary string.

utf8_decode function has a very confusing name; it should be named something like utf8_to_iso88591 because that is exactly what it does:

Converts a string with ISO-8859-1 characters encoded with UTF-8 to single-byte ISO-8859-1

If we want to replicate Encoding.UTF8.GetString() example, what we really need to do, is to convert UTF-8 encoded binary string to ASCII. And you can do it using mb_convert_encoding function, just like that: mb_convert_encoding($utf8String, 'ASCII', 'UTF-8')

Hope these comments will help!


问:
how can one display the sum of a group of numbers from firebase in a texview
Im working with android firebase and have managed to get the sum of a group of values from firebase and display it in logcat. Only i want to display this sum in a TextView, how would I do that? Here is my code</p>

```<code>databaseReference.addValueEventListener(new ValueEventListener() {

     public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            heroList.clear();
            int total = 0;

            for(DataSnapshot artistSnapshot: dataSnapshot.getChildren()){

                Integer rating = artistSnapshot.child("editTextCalories").getValue(Integer.class);

                Hero hero = artistSnapshot.getValue(Hero.class);
                heroList.add(hero);

                total += Hero.getTotal(rating);

            }
            Log.d("Tag", total + "");
            NameList adapter = new NameList(MainActivity.this, heroList);
            listView.setAdapter(adapter);

        }
</code>```

答:
You'll need to set the value to the text view in onDataChange, pretty much in the same spot where you already log it:

```<code>databaseReference.addValueEventListener(new ValueEventListener() {

  public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
    heroList.clear();
    int total = 0;

    for(DataSnapshot artistSnapshot: dataSnapshot.getChildren()){

        Integer rating = artistSnapshot.child("editTextCalories").getValue(Integer.class);

        Hero hero = artistSnapshot.getValue(Hero.class);
        heroList.add(hero);

        total += Hero.getTotal(rating);

    }
    Log.d("Tag", total + "");
    ((TextView)findViewById(R.id.myAwesomeTextView)).setText(""+total)
    NameList adapter = new NameList(MainActivity.this, heroList);
    listView.setAdapter(adapter);
  }
</code>```

Body:
Im working with android firebase and have managed to get the sum of a group of values from firebase and display it in logcat. Only i want to display this sum in a TextView, how would I do that? Here is my code

databaseReference.addValueEventListener(new ValueEventListener() {

     public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            heroList.clear();
            int total = 0;

            for(DataSnapshot artistSnapshot: dataSnapshot.getChildren()){

                Integer rating = artistSnapshot.child("editTextCalories").getValue(Integer.class);

                Hero hero = artistSnapshot.getValue(Hero.class);
                heroList.add(hero);

                total += Hero.getTotal(rating);

            }
            Log.d("Tag", total + "");
            NameList adapter = new NameList(MainActivity.this, heroList);
            listView.setAdapter(adapter);

        }

Body:
You'll need to set the value to the text view in onDataChange, pretty much in the same spot where you already log it:

databaseReference.addValueEventListener(new ValueEventListener() {

  public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
    heroList.clear();
    int total = 0;

    for(DataSnapshot artistSnapshot: dataSnapshot.getChildren()){

        Integer rating = artistSnapshot.child("editTextCalories").getValue(Integer.class);

        Hero hero = artistSnapshot.getValue(Hero.class);
        heroList.add(hero);

        total += Hero.getTotal(rating);

    }
    Log.d("Tag", total + "");
    ((TextView)findViewById(R.id.myAwesomeTextView)).setText(""+total)
    NameList adapter = new NameList(MainActivity.this, heroList);
    listView.setAdapter(adapter);
  }


问:
Get characters right after match in a foreach loop
On my site I want to detect if someone mentions a username in a comment, like so: what's up /u/username.

How exactly can I extract the characters following /u/ in a foreach loop?

Something like this:

```<code>if (strpos($commentString, '/u/') !== false) {
    foreach /u/ in $commentString {
        $username = the text immediately after /u/, stopping at anything that isn't a letter or a number
    }
}
</code>```

答:
You can use preg_match_all with a regex of

```<code>/u/([a-z0-9]+)
</code>```

to capture the usernames in the text. For example:

```<code>$text = "what's up /u/username have you seen /u/user21 today?";

preg_match_all('#/u/([a-z0-9]+)#i', $text, $matches);
foreach ($matches[1] as $user) {
    echo "found user $user\n";
}
</code>```

Output:

```<code>found user username
found user user21
</code>```

Demo on 3v4l.org

Body:
On my site I want to detect if someone mentions a username in a comment, like so: what's up /u/username.

How exactly can I extract the characters following /u/ in a foreach loop?

Something like this:

if (strpos($commentString, '/u/') !== false) {
    foreach /u/ in $commentString {
        $username = the text immediately after /u/, stopping at anything that isn't a letter or a number
    }
}

Body:
You can use preg_match_all with a regex of

/u/([a-z0-9]+)

to capture the usernames in the text. For example:

$text = "what's up /u/username have you seen /u/user21 today?";

preg_match_all('#/u/([a-z0-9]+)#i', $text, $matches);
foreach ($matches[1] as $user) {
    echo "found user $user\n";
}

Output:

found user username
found user user21

Demo on 3v4l.org


问:
Group into a list a dataset based in a repeated column in pandas python
I have a dataframe imported with pandas from excel with a format like this:

```<code>df = pd.read_excel('excel_file.xlsx')

data = pd.DataFrame(df, columns=['A', 'B', 'C', 'D', 'E'])

A    B   C    D   E
12  bob  32  abc 123
12  jan  34  fbc  23
14  jan  32  ac  133
12  cat  32  abc 123
</code>```

I would like to group them by the column B so the output would come as:

```<code>list[0] = [[12  bob  32  abc 123]]
list[1] = [[12  jan  34  fbc  23][14  jan  32  ac  133]]
list[2] = [[12  cat  32  abc 123]]
</code>```

I've tried using duplicated function with no success

Thank you very much!!

答:
You can do:

```<code>lst = [d.values.tolist() for (k,d) in df.groupby('B', sort=False)]

# check
for i in range(len(lst)): print(lst[i])
</code>```

Output:

```<code>[[12, 'bob', 32, 'abc', 123]]
[[12, 'jan', 34, 'fbc', 23], [14, 'jan', 32, 'ac', 133]]
[[12, 'cat', 32, 'abc', 123]]
</code>```

Body:
I have a dataframe imported with pandas from excel with a format like this:

df = pd.read_excel('excel_file.xlsx')

data = pd.DataFrame(df, columns=['A', 'B', 'C', 'D', 'E'])

A    B   C    D   E
12  bob  32  abc 123
12  jan  34  fbc  23
14  jan  32  ac  133
12  cat  32  abc 123

I would like to group them by the column B so the output would come as:

list[0] = [[12  bob  32  abc 123]]
list[1] = [[12  jan  34  fbc  23][14  jan  32  ac  133]]
list[2] = [[12  cat  32  abc 123]]

I've tried using duplicated function with no success

Thank you very much!!

Body:
You can do:

lst = [d.values.tolist() for (k,d) in df.groupby('B', sort=False)]

# check
for i in range(len(lst)): print(lst[i])

Output:

[[12, 'bob', 32, 'abc', 123]]
[[12, 'jan', 34, 'fbc', 23], [14, 'jan', 32, 'ac', 133]]
[[12, 'cat', 32, 'abc', 123]]


问:
Python script to split multi page PDF works with some PDFs and not Others
I am using the following script in Windows to split multipage PDFs. The script looks like this...

```<code>from PyPDF2 import PdfFileWriter, PdfFileReader
inputpdf = PdfFileReader(open("*pathToPDF**”, "rb"))

for i in range(inputpdf.numPages):
    output = PdfFileWriter()
    output.addPage(inputpdf.getPage(i))
    with open("document-page%s.pdf" % i, "wb") as outputStream:
        output.write(outputStream)
</code>```

I am replacing pathToPDF with the path to the multipage PDF to be split on the fly.

I got it working fine with a nine page 91kb PDF, but when I tried it with a 232 page 1.62gb PDF it throws the following error...

Traceback (most recent call last): File
  “C:\MySplitFolder\splitPDFwindows.py”, line 3, in  inputpdf =
  PdfFileReader(open(“C:\MySplitFolder\1973PB1PhyOfficeParkingBldg_CD.pdf”,
  “rb”)) OSError: [Errno 22] Invalid argument:
  ‘C:\MySplitFolder\x01973PB1PhyOfficeParkingBldg_CD.pdf’

Here is the line 3 code of the small pdf...

```<code>inputpdf = PdfFileReader(open("C:\MySplitFolder\BestInCategory_JR 2.pdf", "rb"))
</code>```

Here is the line 3 code of the large pdf...

```<code>inputpdf = PdfFileReader(open("C:\MySplitFolder\1973PB1PhyOfficeParkingBldg_CD.pdf", "rb"))
</code>```

The document name is the only difference between the 2 scripts when executed. While the error speaks of an invalid argument, I do not see any difference between the 2 lines except for the document name. Is the a file size problem?

Any help is greatly appreciated.

答:
The path you provided is C:\MySplitFolder\1973PB1PhyOfficeParking, but the error message is showing the path C:\MySplitFolder\x01973PB1PhyOfficeParking. Notice the extra x0 after the second \ !

Python is assuming that \ is an escape character and is treating \197 as escape sequence, replacing it with the equivalent ASCII character.

To fix this, tell python to treat the path as a raw string, by prefixing it with an r:

```<code>inputpdf = PdfFileReader(open(r"C:\MySplitFolder\1973PB1PhyOfficeParkingBldg_CD.pdf", "rb"))
</code>```

The reason the first file worked is because, in python, "all unrecognized escape sequences are left in the string unchanged". So, both \M and \B are unrecognized and kept unchanged. Hence, resulting in a path string that is accidentally correct!

Body:
I am using the following script in Windows to split multipage PDFs. The script looks like this...

from PyPDF2 import PdfFileWriter, PdfFileReader
inputpdf = PdfFileReader(open("*pathToPDF**”, "rb"))

for i in range(inputpdf.numPages):
    output = PdfFileWriter()
    output.addPage(inputpdf.getPage(i))
    with open("document-page%s.pdf" % i, "wb") as outputStream:
        output.write(outputStream)

I am replacing pathToPDF with the path to the multipage PDF to be split on the fly.

I got it working fine with a nine page 91kb PDF, but when I tried it with a 232 page 1.62gb PDF it throws the following error...

Traceback (most recent call last): File
  “C:\MySplitFolder\splitPDFwindows.py”, line 3, in  inputpdf =
  PdfFileReader(open(“C:\MySplitFolder\1973PB1PhyOfficeParkingBldg_CD.pdf”,
  “rb”)) OSError: [Errno 22] Invalid argument:
  ‘C:\MySplitFolder\x01973PB1PhyOfficeParkingBldg_CD.pdf’

Here is the line 3 code of the small pdf...

inputpdf = PdfFileReader(open("C:\MySplitFolder\BestInCategory_JR 2.pdf", "rb"))

Here is the line 3 code of the large pdf...

inputpdf = PdfFileReader(open("C:\MySplitFolder\1973PB1PhyOfficeParkingBldg_CD.pdf", "rb"))

The document name is the only difference between the 2 scripts when executed. While the error speaks of an invalid argument, I do not see any difference between the 2 lines except for the document name. Is the a file size problem?

Any help is greatly appreciated.

Body:
The path you provided is C:\MySplitFolder\1973PB1PhyOfficeParking, but the error message is showing the path C:\MySplitFolder\x01973PB1PhyOfficeParking. Notice the extra x0 after the second \ !

Python is assuming that \ is an escape character and is treating \197 as escape sequence, replacing it with the equivalent ASCII character.

To fix this, tell python to treat the path as a raw string, by prefixing it with an r:

inputpdf = PdfFileReader(open(r"C:\MySplitFolder\1973PB1PhyOfficeParkingBldg_CD.pdf", "rb"))

The reason the first file worked is because, in python, "all unrecognized escape sequences are left in the string unchanged". So, both \M and \B are unrecognized and kept unchanged. Hence, resulting in a path string that is accidentally correct!


问:
How Do I have a Utility Function that Either Delivers an Existing Logger OR Instantiate a New One?
I'm putting my "get logging" function in a general helper file so I can call it frequently across my application. My logger looks like this:

```<code>def setupLogger():
    rootLogger = logging.getLogger()
    rootLogger.setLevel(logging.DEBUG)
    formatter = logging.Formatter(
        "::%(levelname)s - %(message)s"
    )

    if not rootLogger.hasHandlers() :
        buffer = StringIO()
        bufferHandler = logging.StreamHandler(buffer)
        bufferHandler.setLevel(logging.DEBUG)
        bufferHandler.setFormatter(formatter)
        bufferHandler.set_name('buffer.logger')
        rootLogger.addHandler(bufferHandler)

        stdout_handler = logging.StreamHandler(sys.stdout)
        stdout_handler.setLevel(logging.DEBUG)
        stdout_handler.setFormatter(formatter)
        stdout_handler.set_name('stdout.logger')
        rootLogger.addHandler(stdout_handler)

    return (rootLogger, buffer)
</code>```

Then I can call util.setupLogger() from any function and get both a stdout logger and a buffer (so that I can see what's been logged previously to console). However, I need to do a singleton style function like this because I never know if the logger has already been instantiated.

Unfortunately, this fails because buffer is not instantiated on every call to setupLogger (returning null), I can't put initialization of the buffer OUTSIDE the hasHandlers() function (because that wipes the history), and I can't seem to pry out the buffer from logger.StreamHandlers so that I can hand it back.

I feel like I'm making this more complex than it needs to be, what should I do?

答:
How about returning the stream inside the handler?</p>

```<code>def setupLogger():
    rootLogger = logging.getLogger()
    rootLogger.setLevel(logging.DEBUG)
    formatter = logging.Formatter(
        "::%(levelname)s - %(message)s"
    )

    if not rootLogger.hasHandlers() :
        buffer = StringIO()
        bufferHandler = logging.StreamHandler(buffer)
        bufferHandler.setLevel(logging.DEBUG)
        bufferHandler.setFormatter(formatter)
        bufferHandler.set_name('buffer.logger')
        rootLogger.addHandler(bufferHandler)

        stdout_handler = logging.StreamHandler(sys.stdout)
        stdout_handler.setLevel(logging.DEBUG)
        stdout_handler.setFormatter(formatter)
        stdout_handler.set_name('stdout.logger') # BTW here I found a typo, I have fixed it.
        rootLogger.addHandler(stdout_handler)

    buffer = rootLogger.handlers[0].stream

    return rootLogger, buffer
</code>```

Body:
I'm putting my "get logging" function in a general helper file so I can call it frequently across my application. My logger looks like this:

def setupLogger():
    rootLogger = logging.getLogger()
    rootLogger.setLevel(logging.DEBUG)
    formatter = logging.Formatter(
        "::%(levelname)s - %(message)s"
    )

    if not rootLogger.hasHandlers() :
        buffer = StringIO()
        bufferHandler = logging.StreamHandler(buffer)
        bufferHandler.setLevel(logging.DEBUG)
        bufferHandler.setFormatter(formatter)
        bufferHandler.set_name('buffer.logger')
        rootLogger.addHandler(bufferHandler)

        stdout_handler = logging.StreamHandler(sys.stdout)
        stdout_handler.setLevel(logging.DEBUG)
        stdout_handler.setFormatter(formatter)
        stdout_handler.set_name('stdout.logger')
        rootLogger.addHandler(stdout_handler)

    return (rootLogger, buffer)

Then I can call util.setupLogger() from any function and get both a stdout logger and a buffer (so that I can see what's been logged previously to console). However, I need to do a singleton style function like this because I never know if the logger has already been instantiated.

Unfortunately, this fails because buffer is not instantiated on every call to setupLogger (returning null), I can't put initialization of the buffer OUTSIDE the hasHandlers() function (because that wipes the history), and I can't seem to pry out the buffer from logger.StreamHandlers so that I can hand it back.

I feel like I'm making this more complex than it needs to be, what should I do?

Body:
How about returning the stream inside the handler?

def setupLogger():
    rootLogger = logging.getLogger()
    rootLogger.setLevel(logging.DEBUG)
    formatter = logging.Formatter(
        "::%(levelname)s - %(message)s"
    )

    if not rootLogger.hasHandlers() :
        buffer = StringIO()
        bufferHandler = logging.StreamHandler(buffer)
        bufferHandler.setLevel(logging.DEBUG)
        bufferHandler.setFormatter(formatter)
        bufferHandler.set_name('buffer.logger')
        rootLogger.addHandler(bufferHandler)

        stdout_handler = logging.StreamHandler(sys.stdout)
        stdout_handler.setLevel(logging.DEBUG)
        stdout_handler.setFormatter(formatter)
        stdout_handler.set_name('stdout.logger') # BTW here I found a typo, I have fixed it.
        rootLogger.addHandler(stdout_handler)

    buffer = rootLogger.handlers[0].stream

    return rootLogger, buffer


问:
Use rmarkdown/knitr to hold all code until the end
I'd like to be able to generate a document using knitr/rmarkdown that keeps all the output together, but leaves the code until the end, ideally as a referenced footnote of sorts (i.e. the code for each figure or output can be looked up in the appendix using a footnote). Is this possible?</p>

答:
One solution is add this chunk at the end.

```<code>{r ref.label=knitr::all_labels(), echo=TRUE, eval=FALSE}
</code>```

Then you will have all the code together whitout evaluation.

Body:
One solution is add this chunk at the end.

{r ref.label=knitr::all_labels(), echo=TRUE, eval=FALSE}

Then you will have all the code together whitout evaluation.


问:
error, string or binary data would be truncated when trying to insert
I am running data.bat file with the following lines:

```<code>Rem Tis batch file will populate tables

cd\program files\Microsoft SQL Server\MSSQL
osql -U sa -P Password -d MyBusiness -i c:\data.sql
</code>```

The contents of the data.sql file is:

```<code>   insert Customers
            (CustomerID, CompanyName, Phone)
             Values('101','Southwinds','19126602729')
</code>```

There are 8 more similar lines for adding records.

When I run this with start > run > cmd > c:\data.bat, I get this error message:

```<code>1>2>3>4>5>....<1 row affected>
Msg 8152, Level 16, State 4, Server SP1001, Line 1
string or binary data would be truncated.

<1 row affected>

<1 row affected>

<1 row affected>

<1 row affected>

<1 row affected>

<1 row affected>
</code>```

Also, I am a newbie obviously, but what do Level #, and state # mean, and how do I look up error messages such as the one above: 8152?

答:
I used a different tactic, fields that are allocated 8K in some places.  Here only about 50/100 are used.

```<code>declare @NVPN_list as table
nvpn            varchar(50)
,nvpn_revision  varchar(5)
,nvpn_iteration INT
,mpn_lifecycle  varchar(30)
,mfr            varchar(100)
,mpn            varchar(50)
,mpn_revision   varchar(5)
,mpn_iteration  INT
-- ...
) INSERT INTO @NVPN_LIST
SELECT  left(nvpn           ,50)    as nvpn
        ,left(nvpn_revision ,10)    as nvpn_revision
        ,nvpn_iteration
        ,left(mpn_lifecycle ,30)
        ,left(mfr           ,100)
        ,left(mpn           ,50)
        ,left(mpn_revision  ,5)
        ,mpn_iteration
        ,left(mfr_order_num ,50)
FROM [DASHBOARD].[dbo].[mpnAttributes] (NOLOCK) mpna
</code>```

I wanted speed, since I have 1M total records, and load 28K of them.

Body:
I am running data.bat file with the following lines:

Rem Tis batch file will populate tables

cd\program files\Microsoft SQL Server\MSSQL
osql -U sa -P Password -d MyBusiness -i c:\data.sql

The contents of the data.sql file is:

   insert Customers
            (CustomerID, CompanyName, Phone)
             Values('101','Southwinds','19126602729')

There are 8 more similar lines for adding records.

When I run this with start > run > cmd > c:\data.bat, I get this error message:

1>2>3>4>5>....<1 row affected>
Msg 8152, Level 16, State 4, Server SP1001, Line 1
string or binary data would be truncated.

<1 row affected>

<1 row affected>

<1 row affected>

<1 row affected>

<1 row affected>

<1 row affected>

Also, I am a newbie obviously, but what do Level #, and state # mean, and how do I look up error messages such as the one above: 8152?

Body:
I used a different tactic, fields that are allocated 8K in some places.  Here only about 50/100 are used.

declare @NVPN_list as table
nvpn            varchar(50)
,nvpn_revision  varchar(5)
,nvpn_iteration INT
,mpn_lifecycle  varchar(30)
,mfr            varchar(100)
,mpn            varchar(50)
,mpn_revision   varchar(5)
,mpn_iteration  INT
-- ...
) INSERT INTO @NVPN_LIST
SELECT  left(nvpn           ,50)    as nvpn
        ,left(nvpn_revision ,10)    as nvpn_revision
        ,nvpn_iteration
        ,left(mpn_lifecycle ,30)
        ,left(mfr           ,100)
        ,left(mpn           ,50)
        ,left(mpn_revision  ,5)
        ,mpn_iteration
        ,left(mfr_order_num ,50)
FROM [DASHBOARD].[dbo].[mpnAttributes] (NOLOCK) mpna

I wanted speed, since I have 1M total records, and load 28K of them.