问:
Python - getting errors in a text-based fighting game
I'm very new to Python and programming in general. I'm trying to make a simple text-based fighting game for my kids to play. It's the first program I've written on my own. I keep getting errors, and I'm not sure what it is I'm doing wrong.

Here's the code:

```<code>import random
print("Welcome to Sword Fight!")

#Character Stat Section
#Strength
x_strength = 8
y_strength = 7
z_strength = 4
a_strength = 2
#Speed
x_spd = 4
y_spd = 6
z_spd = 4
a_spd = 3
#Agility
x_agl = 3
y_agl = 5
z_agl = 6
a_agl = 2

#Weapon Stat Section
#Strength
katana_strength = 5
broadsword_strength = 6
spear_strength = 7
dagger_strength = 3
#Speed
katana_spd = 5
broadsword_spd = 4
spear_spd = 3
dagger_spd = 7
#Reach
katana_rch = 5
broadsword_rch = 6
spear_rch = 7
dagger_rch = 3

#Enemy Character Section
enemy = ['a goblin', 'a ninja', 'a swordfighter', 'an orc']
#Strength
goblin_strength = 2
ninja_strength = 4
swordfighter_strength = 5
orc_strength = 7
#Speed
goblin_spd = 4
ninja_spd = 7
swordfighter_spd = 5
orc_spd = 3
#Agility
goblin_agl = 3
ninja_agl = 6
swordfighter_agl = 5
orc_agl = 2

#Enemy Weapon Stat Section
#Strength
shiv_strength = 2
ninjato_strength = 4
longsword_strength = 5
axe_strength = 7
#Speed
shiv_spd = 6
ninjato_spd = 6
longsword_spd = 5
axe_spd = 3
#Reach
shiv_rch = 2
ninjato_rch = 4
longsword_rch = 5
axe_rch = 4

player = str(input("Select your character - X, Y, Z or A: "))
if player == "X" or "x":
    print("You've selected X.")
    p_strength = x_strength
    p_spd = x_spd
    p_agl = x_agl
elif player == "Y" or "y":
    print("You've selected Y.")
    p_strength = y_strength
    p_spd = y_spd
    p_agl = y_agl
elif player == "Z" or "z":
    print("You've selected Z.")
    p_strength = z_strength
    p_spd = z_spd
    p_agl = z_agl
elif player == "A" or "a":
    print("You've selected A.")
    p_strength = a_strength
    p_spd = a_spd
    p_agl = a_agl

weapon = str(input("Select your weapon - katana, broadsword, spear, or dagger: "))
if weapon == "Katana" or "katana":
    p_weap = 'katana'
    print("You've selected a katana.")
    w_strength = katana_strength
    w_spd = katana_spd
    w_rch = katana_rch
elif weapon == "Broadsword" or "broadsword":
    p_weap = 'broadsword'
    print("You've selected a broadsword.")
    w_strength = broadsword_strength
    w_spd = broadsword_spd
    w_rch = broadsword_rch
elif weapon == "Spear" or "spear":
    p_weap = 'spear'
    print("You've selected a spear.")
    w_strength = spear_strength
    w_spd = spear_spd
    w_rch = spear_rch
elif weapon == "Dagger" or "dagger":
    p_weap = 'dagger'
    print("You've selected a dagger.")
    w_strength = dagger_strength
    w_spd = dagger_spd
    w_rch = dagger_rch

print("An enemy approaches! It's", random.choice(enemy), "!")

if random.choice(enemy) == 'a goblin':
    print("It's armed with a shiv.")
    e_strength = goblin_strength
    e_spd = goblin_spd
    e_agl = goblin_agl
    ew_strength = shiv_strength
    ew_spd = shiv_spd
    ew_rch = shiv_rch
elif random.choice(enemy) == 'a ninja':
    print("He's armed with a ninjato.")
    e_strength = ninja_strength
    e_spd = ninja_spd
    e_agl = ninja_agl
    ew_strength = ninjato_strength
    ew_spd = ninjato_spd
    ew_rch = ninjato_rch
elif random.choice(enemy) == 'a swordfighter':
    print("She's armed with a longsword.")
    e_strength = swordfighter_strength
    e_spd = swordfighter_spd
    e_agl = swordfighter_agl
    ew_strength = longsword_strength
    ew_spd = longsword_spd
    ew_rch = longsword_rch
elif random.choice(enemy) == 'an orc':
    print("It's armed with a battleaxe.")
    e_strength = orc_strength
    e_spd = orc_spd
    e_agl = orc_agl
    ew_strength = axe_strength
    ew_spd = axe_spd
    ew_rch = axe_rch

print("The battle begins!")

p_hp = 10
e_hp = 10

while p_hp > 0 or e_hp > 0:
    print = ("Which attack will you use?")
    if p_weap == 'katana':
        attack = str(input("Slice, Stab, or Spinning Slash?: "))
    if attack == 'Slice' or 'slice':
        p_atk = (p_strength + w_strength)
        e_atk = (e_strength + ew_strength)
    if p_atk > e_atk:
        e_hp = e_hp - (p_atk - e_atk)
        print("You slice the enemy and do", (p_atk - e_atk), "points of damage.")
    if p_atk < e_atk:
        p_hp = p_hp - (e_atk - p_atk)
        print("The enemy attacks and does", (e_atk - p_atk), "points of damage.")
    if p_atk == e_atk:
        print("You both attack at the same time. Your weapons clash, and you separate. No damage was done.")
    print("Your remaining hitpoints:", p_hp)
    print("The enemy's remaining hitpoints:", e_hp)

    if attack == 'Stab' or 'stab':
        p_atk = (p_spd + w_spd)
        e_atk = (e_spd + ew_spd)
    if p_atk > e_atk:
        e_hp = e_hp - (p_atk - e_atk)
        print("You stab the enemy and do", (p_atk - e_atk), "points of damage.")
    if p_atk < e_atk:
        p_hp = p_hp - (e_atk - p_atk)
        print("The enemy attacks and does", (e_atk - p_atk), "points of damage.")
    if p_atk == e_atk:
        print("You both attack at the same time. Your weapons clash, and you separate. No damage was done.")
    print("Your remaining hitpoints:", p_hp)
    print("The enemy's remaining hitpoints:", e_hp)

    if attack == 'Spinning slash' or 'spinning slash' or 'Spinning Slash':
        p_atk = (p_agl + w_rch)
        e_atk = (e_agl + ew_rch)
    if p_atk > e_atk:
        e_hp = e_hp - (p_atk - e_atk)
        print("You slice the enemy and do", (p_atk - e_atk), "points of damage.")
    if p_atk < e_atk:
        p_hp = p_hp - (e_atk - p_atk)
        print("The enemy attacks and does", (e_atk - p_atk), "points of damage.")
    if p_atk == e_atk:
        print("You both attack at the same time. Your weapons clash, and you separate. No damage was done.")
    else:
        print("Sorry, your input is invalid. Try again.")
    print("Your remaining hitpoints:", p_hp)
    print("The enemy's remaining hitpoints:", e_hp)

    if p_weap == 'broadsword':
        attack = str(input("Overhead chop, Stab, or Slash?: "))
    if attack == 'Overhead chop' or 'overhead chop' or 'Overhead Chop':
        p_atk = (p_strength + w_strength)
        e_atk = (e_strength + ew_strength)
    if p_atk > e_atk:
        e_hp = e_hp - (p_atk - e_atk)
        print("You slice the enemy and do", (p_atk - e_atk), "points of damage.")
    if p_atk < e_atk:
        p_hp = p_hp - (e_atk - p_atk)
        print("The enemy attacks and does", (e_atk - p_atk), "points of damage.")
    if p_atk == e_atk:
        print("You both attack at the same time. Your weapons clash, and you separate. No damage was done.")
    print("Your remaining hitpoints:", p_hp)
    print("The enemy's remaining hitpoints:", e_hp)

    if attack == 'Stab' or 'stab':
        p_atk = (p_spd + w_spd)
        e_atk = (e_spd + ew_spd)
    if p_atk > e_atk:
        e_hp = e_hp - (p_atk - e_atk)
        print("You stab the enemy and do", (p_atk - e_atk), "points of damage.")
    if p_atk < e_atk:
        p_hp = p_hp - (e_atk - p_atk)
        print("The enemy attacks and does", (e_atk - p_atk), "points of damage.")
    if p_atk == e_atk:
        print("You both attack at the same time. Your weapons clash, and you separate. No damage was done.")
    print("Your remaining hitpoints:", p_hp)
    print("The enemy's remaining hitpoints:", e_hp)

    if attack == 'Slash' or 'slash':
        p_atk = (p_agl + w_rch)
        e_atk = (e_agl + ew_rch)
    if p_atk > e_atk:
        e_hp = e_hp - (p_atk - e_atk)
        print("You slice the enemy and do", (p_atk - e_atk), "points of damage.")
    if p_atk < e_atk:
        p_hp = p_hp - (e_atk - p_atk)
        print("The enemy attacks and does", (e_atk - p_atk), "points of damage.")
    if p_atk == e_atk:
        print("You both attack at the same time. Your weapons clash, and you separate. No damage was done.")
    else:
        print("Sorry, your input is invalid. Try again.")
    print("Your remaining hitpoints:", p_hp)
    print("The enemy's remaining hitpoints:", e_hp)

    if p_weap == 'spear':
        attack = str(input("Slam, Swipe, or Thrust?: "))
    if attack == 'Slam' or 'slam':
        p_atk = (p_strength + w_strength)
        e_atk = (e_strength + ew_strength)
    if p_atk > e_atk:
        e_hp = e_hp - (p_atk - e_atk)
        print("You slice the enemy and do", (p_atk - e_atk), "points of damage.")
    if p_atk < e_atk:
        p_hp = p_hp - (e_atk - p_atk)
        print("The enemy attacks and does", (e_atk - p_atk), "points of damage.")
    if p_atk == e_atk:
        print("You both attack at the same time. Your weapons clash, and you separate. No damage was done.")
    print("Your remaining hitpoints:", p_hp)
    print("The enemy's remaining hitpoints:", e_hp)

    if attack == 'Swipe' or 'swipe':
        p_atk = (p_spd + w_spd)
        e_atk = (e_spd + ew_spd)
    if p_atk > e_atk:
        e_hp = e_hp - (p_atk - e_atk)
        print("You stab the enemy and do", (p_atk - e_atk), "points of damage.")
    if p_atk < e_atk:
        p_hp = p_hp - (e_atk - p_atk)
        print("The enemy attacks and does", (e_atk - p_atk), "points of damage.")
    if p_atk == e_atk:
        print("You both attack at the same time. Your weapons clash, and you separate. No damage was done.")
    print("Your remaining hitpoints:", p_hp)
    print("The enemy's remaining hitpoints:", e_hp)

    if attack == 'Thrust' or 'thrust':
        p_atk = (p_agl + w_rch)
        e_atk = (e_agl + ew_rch)
    if p_atk > e_atk:
        e_hp = e_hp - (p_atk - e_atk)
        print("You slice the enemy and do", (p_atk - e_atk), "points of damage.")
    if p_atk < e_atk:
        p_hp = p_hp - (e_atk - p_atk)
        print("The enemy attacks and does", (e_atk - p_atk), "points of damage.")
    if p_atk == e_atk:
        print("You both attack at the same time. Your weapons clash, and you separate. No damage was done.")
    else:
        print("Sorry, your input is invalid. Try again.")
    print("Your remaining hitpoints:", p_hp)
    print("The enemy's remaining hitpoints:", e_hp)

    if p_weap == 'dagger':
        attack = str(input("Slash, Stab, or Thrust?: "))
    if attack == 'Slash' or 'slash':
        p_atk = (p_strength + w_strength)
        e_atk = (e_strength + ew_strength)
    if p_atk > e_atk:
        e_hp = e_hp - (p_atk - e_atk)
        print("You slice the enemy and do", (p_atk - e_atk), "points of damage.")
    if p_atk < e_atk:
        p_hp = p_hp - (e_atk - p_atk)
        print("The enemy attacks and does", (e_atk - p_atk), "points of damage.")
    if p_atk == e_atk:
        print("You both attack at the same time. Your weapons clash, and you separate. No damage was done.")
    print("Your remaining hitpoints:", p_hp)
    print("The enemy's remaining hitpoints:", e_hp)

    if attack == 'Stab' or 'stab':
        p_atk = (p_spd + w_spd)
        e_atk = (e_spd + ew_spd)
    if p_atk > e_atk:
        e_hp = e_hp - (p_atk - e_atk)
        print("You stab the enemy and do", (p_atk - e_atk), "points of damage.")
    if p_atk < e_atk:
        p_hp = p_hp - (e_atk - p_atk)
        print("The enemy attacks and does", (e_atk - p_atk), "points of damage.")
    if p_atk == e_atk:
        print("You both attack at the same time. Your weapons clash, and you separate. No damage was done.")
    print("Your remaining hitpoints:", p_hp)
    print("The enemy's remaining hitpoints:", e_hp)

    if attack == 'Thrust' or 'thrust':
        p_atk = (p_agl + w_rch)
        e_atk = (e_agl + ew_rch)
    if p_atk > e_atk:
        e_hp = e_hp - (p_atk - e_atk)
        print("You slice the enemy and do", (p_atk - e_atk), "points of damage.")
    if p_atk < e_atk:
        p_hp = p_hp - (e_atk - p_atk)
        print("The enemy attacks and does", (e_atk - p_atk), "points of damage.")
    if p_atk == e_atk:
        print("You both attack at the same time. Your weapons clash, and you separate. No damage was done.")
    else:
        print("Sorry, your input is invalid. Try again.")
    print("Your remaining hitpoints:", p_hp)
    print("The enemy's remaining hitpoints:", e_hp)

if p_hp == 0:
    print("You have been defeated...")
if e_hp == 0:
    print("You are victorious!")
</code>```

I'm sure there are simpler ways I could be doing all of this, but I haven't yet learned more advanced commands or techniques.

The first error I'm running into is that no matter what the user enters for their character selection, the program only picks character X.

Second error - regardless of what weapon the user selects, the program picks the katana.

Third error - when the program selects an enemy, sometimes it selects the correct enemy weapon, sometimes the wrong enemy weapon, and sometimes it doesn't select an enemy weapon at all.

Fourth error - If the program selects an enemy and the correct enemy weapon, I get a traceback error when the user enters an attack:

```<code>line 171, in <module>
    print("You slice the enemy and do", (p_atk - e_atk), "points of damage.")
TypeError: 'str' object is not callable
1|:/ $
</code>```

Fifth error - When the program fails to select an enemy weapon, and the user enters an attack, I get a different traceback error:

```<code>line 168, in <module>
    e_atk = (e_strength + ew_strength)
NameError: name 'e_strength' is not defined
1|:/ $
</code>```

Sixth error - when the program selects an enemy and the incorrect enemy weapon, and the user enters an attack, another traceback error:

```<code>line 174, in <module>
    print("The enemy attacks and does", (e_atk - p_atk), "points of damage.")
TypeError: 'str' object is not callable
1|:/ $
</code>```

Any help would be appreciated. Thanks!

答:
The first problem is that your or statement is wrong. if player == "X" is correct, however or player "x": will always return true as you are essentially asking "does the following string 'x' exist?" if you are going to keep doing it this way you need to change all your if or statements to if player == "X" or player == "x":

now an easier way of doing this would be to change all your inputs (I'll use select character as an example)

from: player = str(input("Select your character - X, Y, Z or A: "))

to: player = str(input("Select your character - X, Y, Z or A:")).lower()

the neat thing about this is now whatever the player inputs will be lowercase. All you need to do is check if it is equal to a lowercase string. If the player types "HeLlOw WoRlD" lower() will convert it to "hello world".

The same as problem one you need to change all the if statements like this if weapon == "Katana" or "katana": to if weapon == "Katana" or weapon == "katana":

again if you make the input lowercase you only would have to check if weapon == "katana".

e_strength is defined in several if statements but never outside any, you need to put it in the outer scope. see this explanation of scope in python for more info.
basically the answer is that you need to first define e_strength outside the if statements, maybe on line 123 and give it any value you want as the idea is that it should be overwritten. This seems to be a reoccurring issue, after fixing it a few other scope related bugs become apparent.

Wow this was a funky one. line 163 you wrote print = ("Which attack will you use?") this should be print("Which attack will you use?") this completely broke all the code after it.

same problem from 4.

same problem from 4.

Body:
I'm very new to Python and programming in general. I'm trying to make a simple text-based fighting game for my kids to play. It's the first program I've written on my own. I keep getting errors, and I'm not sure what it is I'm doing wrong.

Here's the code:

import random
print("Welcome to Sword Fight!")

#Character Stat Section
#Strength
x_strength = 8
y_strength = 7
z_strength = 4
a_strength = 2
#Speed
x_spd = 4
y_spd = 6
z_spd = 4
a_spd = 3
#Agility
x_agl = 3
y_agl = 5
z_agl = 6
a_agl = 2

#Weapon Stat Section
#Strength
katana_strength = 5
broadsword_strength = 6
spear_strength = 7
dagger_strength = 3
#Speed
katana_spd = 5
broadsword_spd = 4
spear_spd = 3
dagger_spd = 7
#Reach
katana_rch = 5
broadsword_rch = 6
spear_rch = 7
dagger_rch = 3

#Enemy Character Section
enemy = ['a goblin', 'a ninja', 'a swordfighter', 'an orc']
#Strength
goblin_strength = 2
ninja_strength = 4
swordfighter_strength = 5
orc_strength = 7
#Speed
goblin_spd = 4
ninja_spd = 7
swordfighter_spd = 5
orc_spd = 3
#Agility
goblin_agl = 3
ninja_agl = 6
swordfighter_agl = 5
orc_agl = 2

#Enemy Weapon Stat Section
#Strength
shiv_strength = 2
ninjato_strength = 4
longsword_strength = 5
axe_strength = 7
#Speed
shiv_spd = 6
ninjato_spd = 6
longsword_spd = 5
axe_spd = 3
#Reach
shiv_rch = 2
ninjato_rch = 4
longsword_rch = 5
axe_rch = 4

player = str(input("Select your character - X, Y, Z or A: "))
if player == "X" or "x":
    print("You've selected X.")
    p_strength = x_strength
    p_spd = x_spd
    p_agl = x_agl
elif player == "Y" or "y":
    print("You've selected Y.")
    p_strength = y_strength
    p_spd = y_spd
    p_agl = y_agl
elif player == "Z" or "z":
    print("You've selected Z.")
    p_strength = z_strength
    p_spd = z_spd
    p_agl = z_agl
elif player == "A" or "a":
    print("You've selected A.")
    p_strength = a_strength
    p_spd = a_spd
    p_agl = a_agl

weapon = str(input("Select your weapon - katana, broadsword, spear, or dagger: "))
if weapon == "Katana" or "katana":
    p_weap = 'katana'
    print("You've selected a katana.")
    w_strength = katana_strength
    w_spd = katana_spd
    w_rch = katana_rch
elif weapon == "Broadsword" or "broadsword":
    p_weap = 'broadsword'
    print("You've selected a broadsword.")
    w_strength = broadsword_strength
    w_spd = broadsword_spd
    w_rch = broadsword_rch
elif weapon == "Spear" or "spear":
    p_weap = 'spear'
    print("You've selected a spear.")
    w_strength = spear_strength
    w_spd = spear_spd
    w_rch = spear_rch
elif weapon == "Dagger" or "dagger":
    p_weap = 'dagger'
    print("You've selected a dagger.")
    w_strength = dagger_strength
    w_spd = dagger_spd
    w_rch = dagger_rch

print("An enemy approaches! It's", random.choice(enemy), "!")

if random.choice(enemy) == 'a goblin':
    print("It's armed with a shiv.")
    e_strength = goblin_strength
    e_spd = goblin_spd
    e_agl = goblin_agl
    ew_strength = shiv_strength
    ew_spd = shiv_spd
    ew_rch = shiv_rch
elif random.choice(enemy) == 'a ninja':
    print("He's armed with a ninjato.")
    e_strength = ninja_strength
    e_spd = ninja_spd
    e_agl = ninja_agl
    ew_strength = ninjato_strength
    ew_spd = ninjato_spd
    ew_rch = ninjato_rch
elif random.choice(enemy) == 'a swordfighter':
    print("She's armed with a longsword.")
    e_strength = swordfighter_strength
    e_spd = swordfighter_spd
    e_agl = swordfighter_agl
    ew_strength = longsword_strength
    ew_spd = longsword_spd
    ew_rch = longsword_rch
elif random.choice(enemy) == 'an orc':
    print("It's armed with a battleaxe.")
    e_strength = orc_strength
    e_spd = orc_spd
    e_agl = orc_agl
    ew_strength = axe_strength
    ew_spd = axe_spd
    ew_rch = axe_rch

print("The battle begins!")

p_hp = 10
e_hp = 10

while p_hp > 0 or e_hp > 0:
    print = ("Which attack will you use?")
    if p_weap == 'katana':
        attack = str(input("Slice, Stab, or Spinning Slash?: "))
    if attack == 'Slice' or 'slice':
        p_atk = (p_strength + w_strength)
        e_atk = (e_strength + ew_strength)
    if p_atk > e_atk:
        e_hp = e_hp - (p_atk - e_atk)
        print("You slice the enemy and do", (p_atk - e_atk), "points of damage.")
    if p_atk < e_atk:
        p_hp = p_hp - (e_atk - p_atk)
        print("The enemy attacks and does", (e_atk - p_atk), "points of damage.")
    if p_atk == e_atk:
        print("You both attack at the same time. Your weapons clash, and you separate. No damage was done.")
    print("Your remaining hitpoints:", p_hp)
    print("The enemy's remaining hitpoints:", e_hp)

    if attack == 'Stab' or 'stab':
        p_atk = (p_spd + w_spd)
        e_atk = (e_spd + ew_spd)
    if p_atk > e_atk:
        e_hp = e_hp - (p_atk - e_atk)
        print("You stab the enemy and do", (p_atk - e_atk), "points of damage.")
    if p_atk < e_atk:
        p_hp = p_hp - (e_atk - p_atk)
        print("The enemy attacks and does", (e_atk - p_atk), "points of damage.")
    if p_atk == e_atk:
        print("You both attack at the same time. Your weapons clash, and you separate. No damage was done.")
    print("Your remaining hitpoints:", p_hp)
    print("The enemy's remaining hitpoints:", e_hp)

    if attack == 'Spinning slash' or 'spinning slash' or 'Spinning Slash':
        p_atk = (p_agl + w_rch)
        e_atk = (e_agl + ew_rch)
    if p_atk > e_atk:
        e_hp = e_hp - (p_atk - e_atk)
        print("You slice the enemy and do", (p_atk - e_atk), "points of damage.")
    if p_atk < e_atk:
        p_hp = p_hp - (e_atk - p_atk)
        print("The enemy attacks and does", (e_atk - p_atk), "points of damage.")
    if p_atk == e_atk:
        print("You both attack at the same time. Your weapons clash, and you separate. No damage was done.")
    else:
        print("Sorry, your input is invalid. Try again.")
    print("Your remaining hitpoints:", p_hp)
    print("The enemy's remaining hitpoints:", e_hp)

    if p_weap == 'broadsword':
        attack = str(input("Overhead chop, Stab, or Slash?: "))
    if attack == 'Overhead chop' or 'overhead chop' or 'Overhead Chop':
        p_atk = (p_strength + w_strength)
        e_atk = (e_strength + ew_strength)
    if p_atk > e_atk:
        e_hp = e_hp - (p_atk - e_atk)
        print("You slice the enemy and do", (p_atk - e_atk), "points of damage.")
    if p_atk < e_atk:
        p_hp = p_hp - (e_atk - p_atk)
        print("The enemy attacks and does", (e_atk - p_atk), "points of damage.")
    if p_atk == e_atk:
        print("You both attack at the same time. Your weapons clash, and you separate. No damage was done.")
    print("Your remaining hitpoints:", p_hp)
    print("The enemy's remaining hitpoints:", e_hp)

    if attack == 'Stab' or 'stab':
        p_atk = (p_spd + w_spd)
        e_atk = (e_spd + ew_spd)
    if p_atk > e_atk:
        e_hp = e_hp - (p_atk - e_atk)
        print("You stab the enemy and do", (p_atk - e_atk), "points of damage.")
    if p_atk < e_atk:
        p_hp = p_hp - (e_atk - p_atk)
        print("The enemy attacks and does", (e_atk - p_atk), "points of damage.")
    if p_atk == e_atk:
        print("You both attack at the same time. Your weapons clash, and you separate. No damage was done.")
    print("Your remaining hitpoints:", p_hp)
    print("The enemy's remaining hitpoints:", e_hp)

    if attack == 'Slash' or 'slash':
        p_atk = (p_agl + w_rch)
        e_atk = (e_agl + ew_rch)
    if p_atk > e_atk:
        e_hp = e_hp - (p_atk - e_atk)
        print("You slice the enemy and do", (p_atk - e_atk), "points of damage.")
    if p_atk < e_atk:
        p_hp = p_hp - (e_atk - p_atk)
        print("The enemy attacks and does", (e_atk - p_atk), "points of damage.")
    if p_atk == e_atk:
        print("You both attack at the same time. Your weapons clash, and you separate. No damage was done.")
    else:
        print("Sorry, your input is invalid. Try again.")
    print("Your remaining hitpoints:", p_hp)
    print("The enemy's remaining hitpoints:", e_hp)

    if p_weap == 'spear':
        attack = str(input("Slam, Swipe, or Thrust?: "))
    if attack == 'Slam' or 'slam':
        p_atk = (p_strength + w_strength)
        e_atk = (e_strength + ew_strength)
    if p_atk > e_atk:
        e_hp = e_hp - (p_atk - e_atk)
        print("You slice the enemy and do", (p_atk - e_atk), "points of damage.")
    if p_atk < e_atk:
        p_hp = p_hp - (e_atk - p_atk)
        print("The enemy attacks and does", (e_atk - p_atk), "points of damage.")
    if p_atk == e_atk:
        print("You both attack at the same time. Your weapons clash, and you separate. No damage was done.")
    print("Your remaining hitpoints:", p_hp)
    print("The enemy's remaining hitpoints:", e_hp)

    if attack == 'Swipe' or 'swipe':
        p_atk = (p_spd + w_spd)
        e_atk = (e_spd + ew_spd)
    if p_atk > e_atk:
        e_hp = e_hp - (p_atk - e_atk)
        print("You stab the enemy and do", (p_atk - e_atk), "points of damage.")
    if p_atk < e_atk:
        p_hp = p_hp - (e_atk - p_atk)
        print("The enemy attacks and does", (e_atk - p_atk), "points of damage.")
    if p_atk == e_atk:
        print("You both attack at the same time. Your weapons clash, and you separate. No damage was done.")
    print("Your remaining hitpoints:", p_hp)
    print("The enemy's remaining hitpoints:", e_hp)

    if attack == 'Thrust' or 'thrust':
        p_atk = (p_agl + w_rch)
        e_atk = (e_agl + ew_rch)
    if p_atk > e_atk:
        e_hp = e_hp - (p_atk - e_atk)
        print("You slice the enemy and do", (p_atk - e_atk), "points of damage.")
    if p_atk < e_atk:
        p_hp = p_hp - (e_atk - p_atk)
        print("The enemy attacks and does", (e_atk - p_atk), "points of damage.")
    if p_atk == e_atk:
        print("You both attack at the same time. Your weapons clash, and you separate. No damage was done.")
    else:
        print("Sorry, your input is invalid. Try again.")
    print("Your remaining hitpoints:", p_hp)
    print("The enemy's remaining hitpoints:", e_hp)

    if p_weap == 'dagger':
        attack = str(input("Slash, Stab, or Thrust?: "))
    if attack == 'Slash' or 'slash':
        p_atk = (p_strength + w_strength)
        e_atk = (e_strength + ew_strength)
    if p_atk > e_atk:
        e_hp = e_hp - (p_atk - e_atk)
        print("You slice the enemy and do", (p_atk - e_atk), "points of damage.")
    if p_atk < e_atk:
        p_hp = p_hp - (e_atk - p_atk)
        print("The enemy attacks and does", (e_atk - p_atk), "points of damage.")
    if p_atk == e_atk:
        print("You both attack at the same time. Your weapons clash, and you separate. No damage was done.")
    print("Your remaining hitpoints:", p_hp)
    print("The enemy's remaining hitpoints:", e_hp)

    if attack == 'Stab' or 'stab':
        p_atk = (p_spd + w_spd)
        e_atk = (e_spd + ew_spd)
    if p_atk > e_atk:
        e_hp = e_hp - (p_atk - e_atk)
        print("You stab the enemy and do", (p_atk - e_atk), "points of damage.")
    if p_atk < e_atk:
        p_hp = p_hp - (e_atk - p_atk)
        print("The enemy attacks and does", (e_atk - p_atk), "points of damage.")
    if p_atk == e_atk:
        print("You both attack at the same time. Your weapons clash, and you separate. No damage was done.")
    print("Your remaining hitpoints:", p_hp)
    print("The enemy's remaining hitpoints:", e_hp)

    if attack == 'Thrust' or 'thrust':
        p_atk = (p_agl + w_rch)
        e_atk = (e_agl + ew_rch)
    if p_atk > e_atk:
        e_hp = e_hp - (p_atk - e_atk)
        print("You slice the enemy and do", (p_atk - e_atk), "points of damage.")
    if p_atk < e_atk:
        p_hp = p_hp - (e_atk - p_atk)
        print("The enemy attacks and does", (e_atk - p_atk), "points of damage.")
    if p_atk == e_atk:
        print("You both attack at the same time. Your weapons clash, and you separate. No damage was done.")
    else:
        print("Sorry, your input is invalid. Try again.")
    print("Your remaining hitpoints:", p_hp)
    print("The enemy's remaining hitpoints:", e_hp)

if p_hp == 0:
    print("You have been defeated...")
if e_hp == 0:
    print("You are victorious!")

I'm sure there are simpler ways I could be doing all of this, but I haven't yet learned more advanced commands or techniques.

The first error I'm running into is that no matter what the user enters for their character selection, the program only picks character X.

Second error - regardless of what weapon the user selects, the program picks the katana.

Third error - when the program selects an enemy, sometimes it selects the correct enemy weapon, sometimes the wrong enemy weapon, and sometimes it doesn't select an enemy weapon at all.

Fourth error - If the program selects an enemy and the correct enemy weapon, I get a traceback error when the user enters an attack:

line 171, in <module>
    print("You slice the enemy and do", (p_atk - e_atk), "points of damage.")
TypeError: 'str' object is not callable
1|:/ $

Fifth error - When the program fails to select an enemy weapon, and the user enters an attack, I get a different traceback error:

line 168, in <module>
    e_atk = (e_strength + ew_strength)
NameError: name 'e_strength' is not defined
1|:/ $

Sixth error - when the program selects an enemy and the incorrect enemy weapon, and the user enters an attack, another traceback error:

line 174, in <module>
    print("The enemy attacks and does", (e_atk - p_atk), "points of damage.")
TypeError: 'str' object is not callable
1|:/ $

Any help would be appreciated. Thanks!


来源: stackexchange

问:
Keras: Making a neural network to find a number's modulus
I'm an experienced Python developer, but a complete newbie in machine learning. This is my first attempt to use Keras. Can you tell what I'm doing wrong?

I'm trying to make a neural network that takes a number in binary form, and outputs its modulo when dividing by 7. (My goal was to take a very simple task just to see that everything works.)

In the code below I define the network and I train it on 10,000 random numbers. Then I test it on 500 random numbers.

For some reason the accuracy that I get is around 1/7, which is the accuracy you'd expect from a completely random algorithm, i.e. my neural network isn't doing anything.

Can anyone help me figure out what's wrong?

```<code>import keras.models
import numpy as np
from python_toolbox import random_tools

RADIX = 7

def _get_number(vector):
    return sum(x * 2 ** i for i, x in enumerate(vector))

def _get_mod_result(vector):
    return _get_number(vector) % RADIX

def _number_to_vector(number):
    binary_string = bin(number)[2:]
    if len(binary_string) > 20:
        raise NotImplementedError
    bits = (((0,) * (20 - len(binary_string))) +
            tuple(map(int, binary_string)))[::-1]
    assert len(bits) == 20
    return np.c_[bits]

def get_mod_result_vector(vector):
    return _number_to_vector(_get_mod_result(vector))

def main():
    model = keras.models.Sequential(
        (
            keras.layers.Dense(
                units=20, activation='relu', input_dim=20
            ),
            keras.layers.Dense(
                units=20, activation='relu'
            ),
            keras.layers.Dense(
                units=20, activation='softmax'
            )
        )
    )
    model.compile(optimizer='sgd',
                  loss='categorical_crossentropy',
                  metrics=['accuracy'])

    data = np.random.randint(2, size=(10000, 20))
    labels = np.vstack(map(get_mod_result_vector, data))

    model.fit(data, labels, epochs=10, batch_size=50)
    def predict(number):
        foo = model.predict(_number_to_vector(number))
        return _get_number(tuple(map(round, foo[0])))
    def is_correct_for_number(x):
        return bool(predict(x) == x % RADIX)
    predict(7)
    sample = random_tools.shuffled(range(2 ** 20))[:500]
    print('Total accuracy:')
    print(sum(map(is_correct_for_number, sample)) / len(sample))
    print(f'(Accuracy of random algorithm is {1/RADIX:.2f}')

if __name__ == '__main__':
    main()
</code>```

答:
UPD

After some tinkering I was able to get to a reasonably good solution using RNNs. It trains on less than 5% of all possible unique inputs and gives >90% accuracy on the random test sample. You can increase number of batches to 100 from 40 to make it a bit more accurate (though in some runs there is a chance the model won't converge to the right answer - here it is higher than usually). I have switched to using Adam optimizer here and had to increase number of samples to 50K (10K led to overfitting for me).

Please understand that this solution is a bit of a tongue-in-cheek thing, because it is based on the task-domain knowledge that our target function can be defined by a simple recurring formula on the sequence of input bits (even simpler formula if you reverse your input bit sequence, but using go_backwards=True in LSTM didn't help here).

If you inverse the input bits order (so that we always start with the most significant bit) than the recurring formula for the target function is just F_n = G(F_{n-1}, x_n), where F_n = MOD([x_1,...,x_n], 7), and G(x, y) = MOD(2*x+y, 7) - only has 49 different inputs and 7 possible outputs. So the model kind of have to learn initial state + this G update function. For the sequence starting with the least significant bit the recurring formula is slightly more complicated cause it will also need to keep track on what is current MOD(2**n, 7) on each step, but it seems that this difficulty doesn't matter for training.

Please note - these formulas are only to explain why RNN works here. The net below is just a plain LSTM layer + softmax with original input of bits treated as a sequence.

Full code for the answer using RNN layer:

```<code>import keras.models
import numpy as np
from python_toolbox import random_tools

RADIX = 7
FEATURE_BITS = 20

def _get_number(vector):
    return sum(x * 2 ** i for i, x in enumerate(vector))

def _get_mod_result(vector):
    return _get_number(vector) % RADIX

def _number_to_vector(number):
    binary_string = bin(number)[2:]
    if len(binary_string) > FEATURE_BITS:
        raise NotImplementedError
    bits = (((0,) * (FEATURE_BITS - len(binary_string))) +
            tuple(map(int, binary_string)))[::-1]
    assert len(bits) == FEATURE_BITS
    return np.c_[bits]

def get_mod_result_vector(vector):
    v = np.repeat(0, 7)
    v[_get_mod_result(vector)] = 1
    return v

def main():
    model = keras.models.Sequential(
        (
            keras.layers.Reshape(
                (1, -1)
            ),
            keras.layers.LSTM(
                units=100,
            ),
            keras.layers.Dense(
                units=7, activation='softmax'
            )
        )
    )
    model.compile(optimizer=keras.optimizers.Adam(learning_rate=0.01),
                  loss='categorical_crossentropy',
                  metrics=['accuracy'])

    data = np.random.randint(2, size=(50000, FEATURE_BITS))
    labels = np.vstack(map(get_mod_result_vector, data))

    model.fit(data, labels, epochs=40, batch_size=50)
    def predict(number):
        foo = model.predict(_number_to_vector(number))
        return np.argmax(foo)
    def is_correct_for_number(x):
        return bool(predict(x) == x % RADIX)
    sample = random_tools.shuffled(range(2 ** FEATURE_BITS))[:500]
    print('Total accuracy:')
    print(sum(map(is_correct_for_number, sample)) / len(sample))
    print(f'(Accuracy of random algorithm is {1/RADIX:.2f}')

if __name__ == '__main__':
    main()
</code>```

ORIGINAL ANSWER

I'm not sure how it happened, but the particular task you chose to check your code is extremely difficult for a NN. I think the best explanation would be that NNs are not really good when features are interconnected in such way that changing one feature always change value of your target output completely. One way to look at it would be to see the sets of features when you expect a certain answer - in your case they will look like unions of very large number of parallel hyper planes in 20 dimensional space - and for each of 7 categories these sets of planes are "nicely" interleaved and left for NN to distinguish.

That said - if your number of examples is large, say 10K and number of possible inputs is smaller, say your input bit numbers are only 8 bits large (so 256 unique inputs possible only) - networks should "learn" the right function quite ok (by "remembering" correct answers for every input, without generalization). In your case that doesn't happen because the code has the following bug.

Your labels were 20-dimensional vectors with bits of 0-6 integer (your actual desired label) - so I guess you were pretty much trying to teach NN to learn bits of the answer as separate classifiers (with only 3 bits ever possible to be non-zero). I changed that to what I assume you actually wanted - vectors of length 7 with only one value being 1 and others 0 (so-called one hot encoding which keras actually expects for categorical_crossentropy according to this). If you wanted to try to learn each bit separately you definitely shouldn't have used softmax 20 in the last layer, cause such output generates probabilities on 20 classes which sum up to 1 (in that case you should have trained 20-or-rather-3 binary classifiers instead). Since your code didn't give keras correct input the model you got in the end was kind of random and with rounding you applied was intented to output the same value for 95%-100% of inputs.

Slightly changed code below trains a model which can more or less correctly guess the mod 7 answer for every number 0 to 255 (again, pretty much remembers the correct answer for every input). If you try to increase FEATURE_BITS you will see large degradation of the results. If you actually want to train NN to learn this task as is with 20 or more bits of input (and without supplying NN with all possible inputs and infinite time to train) you will need to apply some task-specific feature transformations and/or some layers carefully designed to exactly be good at task you want to achieve as others already mentioned in comments to your question.

```<code>import keras.models
import numpy as np
from python_toolbox import random_tools

RADIX = 7
FEATURE_BITS = 8

def _get_number(vector):
    return sum(x * 2 ** i for i, x in enumerate(vector))

def _get_mod_result(vector):
    return _get_number(vector) % RADIX

def _number_to_vector(number):
    binary_string = bin(number)[2:]
    if len(binary_string) > FEATURE_BITS:
        raise NotImplementedError
    bits = (((0,) * (FEATURE_BITS - len(binary_string))) +
            tuple(map(int, binary_string)))[::-1]
    assert len(bits) == FEATURE_BITS
    return np.c_[bits]

def get_mod_result_vector(vector):
    v = np.repeat(0, 7)
    v[_get_mod_result(vector)] = 1
    return v

def main():
    model = keras.models.Sequential(
        (
            keras.layers.Dense(
                units=20, activation='relu', input_dim=FEATURE_BITS
            ),
            keras.layers.Dense(
                units=20, activation='relu'
            ),
            keras.layers.Dense(
                units=7, activation='softmax'
            )
        )
    )
    model.compile(optimizer='sgd',
                  loss='categorical_crossentropy',
                  metrics=['accuracy'])

    data = np.random.randint(2, size=(10000, FEATURE_BITS))
    labels = np.vstack(map(get_mod_result_vector, data))

    model.fit(data, labels, epochs=100, batch_size=50)
    def predict(number):
        foo = model.predict(_number_to_vector(number))
        return np.argmax(foo)
    def is_correct_for_number(x):
        return bool(predict(x) == x % RADIX)
    sample = random_tools.shuffled(range(2 ** FEATURE_BITS))[:500]
    print('Total accuracy:')
    print(sum(map(is_correct_for_number, sample)) / len(sample))
    print(f'(Accuracy of random algorithm is {1/RADIX:.2f}')

if __name__ == '__main__':
    main()
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm an experienced Python developer, but a complete newbie in machine learning. This is my first attempt to use Keras. Can you tell what I'm doing wrong?

I'm trying to make a neural network that takes a number in binary form, and outputs its modulo when dividing by 7. (My goal was to take a very simple task just to see that everything works.)

In the code below I define the network and I train it on 10,000 random numbers. Then I test it on 500 random numbers.

For some reason the accuracy that I get is around 1/7, which is the accuracy you'd expect from a completely random algorithm, i.e. my neural network isn't doing anything.

Can anyone help me figure out what's wrong?

import keras.models
import numpy as np
from python_toolbox import random_tools

RADIX = 7

def _get_number(vector):
    return sum(x * 2 ** i for i, x in enumerate(vector))

def _get_mod_result(vector):
    return _get_number(vector) % RADIX

def _number_to_vector(number):
    binary_string = bin(number)[2:]
    if len(binary_string) > 20:
        raise NotImplementedError
    bits = (((0,) * (20 - len(binary_string))) +
            tuple(map(int, binary_string)))[::-1]
    assert len(bits) == 20
    return np.c_[bits]

def get_mod_result_vector(vector):
    return _number_to_vector(_get_mod_result(vector))

def main():
    model = keras.models.Sequential(
        (
            keras.layers.Dense(
                units=20, activation='relu', input_dim=20
            ),
            keras.layers.Dense(
                units=20, activation='relu'
            ),
            keras.layers.Dense(
                units=20, activation='softmax'
            )
        )
    )
    model.compile(optimizer='sgd',
                  loss='categorical_crossentropy',
                  metrics=['accuracy'])

    data = np.random.randint(2, size=(10000, 20))
    labels = np.vstack(map(get_mod_result_vector, data))

    model.fit(data, labels, epochs=10, batch_size=50)
    def predict(number):
        foo = model.predict(_number_to_vector(number))
        return _get_number(tuple(map(round, foo[0])))
    def is_correct_for_number(x):
        return bool(predict(x) == x % RADIX)
    predict(7)
    sample = random_tools.shuffled(range(2 ** 20))[:500]
    print('Total accuracy:')
    print(sum(map(is_correct_for_number, sample)) / len(sample))
    print(f'(Accuracy of random algorithm is {1/RADIX:.2f}')

if __name__ == '__main__':
    main()

Body:
UPD

After some tinkering I was able to get to a reasonably good solution using RNNs. It trains on less than 5% of all possible unique inputs and gives >90% accuracy on the random test sample. You can increase number of batches to 100 from 40 to make it a bit more accurate (though in some runs there is a chance the model won't converge to the right answer - here it is higher than usually). I have switched to using Adam optimizer here and had to increase number of samples to 50K (10K led to overfitting for me).

Please understand that this solution is a bit of a tongue-in-cheek thing, because it is based on the task-domain knowledge that our target function can be defined by a simple recurring formula on the sequence of input bits (even simpler formula if you reverse your input bit sequence, but using go_backwards=True in LSTM didn't help here).

If you inverse the input bits order (so that we always start with the most significant bit) than the recurring formula for the target function is just F_n = G(F_{n-1}, x_n), where F_n = MOD([x_1,...,x_n], 7), and G(x, y) = MOD(2*x+y, 7) - only has 49 different inputs and 7 possible outputs. So the model kind of have to learn initial state + this G update function. For the sequence starting with the least significant bit the recurring formula is slightly more complicated cause it will also need to keep track on what is current MOD(2**n, 7) on each step, but it seems that this difficulty doesn't matter for training.

Please note - these formulas are only to explain why RNN works here. The net below is just a plain LSTM layer + softmax with original input of bits treated as a sequence.

Full code for the answer using RNN layer:

import keras.models
import numpy as np
from python_toolbox import random_tools

RADIX = 7
FEATURE_BITS = 20

def _get_number(vector):
    return sum(x * 2 ** i for i, x in enumerate(vector))

def _get_mod_result(vector):
    return _get_number(vector) % RADIX

def _number_to_vector(number):
    binary_string = bin(number)[2:]
    if len(binary_string) > FEATURE_BITS:
        raise NotImplementedError
    bits = (((0,) * (FEATURE_BITS - len(binary_string))) +
            tuple(map(int, binary_string)))[::-1]
    assert len(bits) == FEATURE_BITS
    return np.c_[bits]

def get_mod_result_vector(vector):
    v = np.repeat(0, 7)
    v[_get_mod_result(vector)] = 1
    return v

def main():
    model = keras.models.Sequential(
        (
            keras.layers.Reshape(
                (1, -1)
            ),
            keras.layers.LSTM(
                units=100,
            ),
            keras.layers.Dense(
                units=7, activation='softmax'
            )
        )
    )
    model.compile(optimizer=keras.optimizers.Adam(learning_rate=0.01),
                  loss='categorical_crossentropy',
                  metrics=['accuracy'])

    data = np.random.randint(2, size=(50000, FEATURE_BITS))
    labels = np.vstack(map(get_mod_result_vector, data))

    model.fit(data, labels, epochs=40, batch_size=50)
    def predict(number):
        foo = model.predict(_number_to_vector(number))
        return np.argmax(foo)
    def is_correct_for_number(x):
        return bool(predict(x) == x % RADIX)
    sample = random_tools.shuffled(range(2 ** FEATURE_BITS))[:500]
    print('Total accuracy:')
    print(sum(map(is_correct_for_number, sample)) / len(sample))
    print(f'(Accuracy of random algorithm is {1/RADIX:.2f}')

if __name__ == '__main__':
    main()

ORIGINAL ANSWER

I'm not sure how it happened, but the particular task you chose to check your code is extremely difficult for a NN. I think the best explanation would be that NNs are not really good when features are interconnected in such way that changing one feature always change value of your target output completely. One way to look at it would be to see the sets of features when you expect a certain answer - in your case they will look like unions of very large number of parallel hyper planes in 20 dimensional space - and for each of 7 categories these sets of planes are "nicely" interleaved and left for NN to distinguish.

That said - if your number of examples is large, say 10K and number of possible inputs is smaller, say your input bit numbers are only 8 bits large (so 256 unique inputs possible only) - networks should "learn" the right function quite ok (by "remembering" correct answers for every input, without generalization). In your case that doesn't happen because the code has the following bug.

Your labels were 20-dimensional vectors with bits of 0-6 integer (your actual desired label) - so I guess you were pretty much trying to teach NN to learn bits of the answer as separate classifiers (with only 3 bits ever possible to be non-zero). I changed that to what I assume you actually wanted - vectors of length 7 with only one value being 1 and others 0 (so-called one hot encoding which keras actually expects for categorical_crossentropy according to this). If you wanted to try to learn each bit separately you definitely shouldn't have used softmax 20 in the last layer, cause such output generates probabilities on 20 classes which sum up to 1 (in that case you should have trained 20-or-rather-3 binary classifiers instead). Since your code didn't give keras correct input the model you got in the end was kind of random and with rounding you applied was intented to output the same value for 95%-100% of inputs.

Slightly changed code below trains a model which can more or less correctly guess the mod 7 answer for every number 0 to 255 (again, pretty much remembers the correct answer for every input). If you try to increase FEATURE_BITS you will see large degradation of the results. If you actually want to train NN to learn this task as is with 20 or more bits of input (and without supplying NN with all possible inputs and infinite time to train) you will need to apply some task-specific feature transformations and/or some layers carefully designed to exactly be good at task you want to achieve as others already mentioned in comments to your question.

import keras.models
import numpy as np
from python_toolbox import random_tools

RADIX = 7
FEATURE_BITS = 8

def _get_number(vector):
    return sum(x * 2 ** i for i, x in enumerate(vector))

def _get_mod_result(vector):
    return _get_number(vector) % RADIX

def _number_to_vector(number):
    binary_string = bin(number)[2:]
    if len(binary_string) > FEATURE_BITS:
        raise NotImplementedError
    bits = (((0,) * (FEATURE_BITS - len(binary_string))) +
            tuple(map(int, binary_string)))[::-1]
    assert len(bits) == FEATURE_BITS
    return np.c_[bits]

def get_mod_result_vector(vector):
    v = np.repeat(0, 7)
    v[_get_mod_result(vector)] = 1
    return v

def main():
    model = keras.models.Sequential(
        (
            keras.layers.Dense(
                units=20, activation='relu', input_dim=FEATURE_BITS
            ),
            keras.layers.Dense(
                units=20, activation='relu'
            ),
            keras.layers.Dense(
                units=7, activation='softmax'
            )
        )
    )
    model.compile(optimizer='sgd',
                  loss='categorical_crossentropy',
                  metrics=['accuracy'])

    data = np.random.randint(2, size=(10000, FEATURE_BITS))
    labels = np.vstack(map(get_mod_result_vector, data))

    model.fit(data, labels, epochs=100, batch_size=50)
    def predict(number):
        foo = model.predict(_number_to_vector(number))
        return np.argmax(foo)
    def is_correct_for_number(x):
        return bool(predict(x) == x % RADIX)
    sample = random_tools.shuffled(range(2 ** FEATURE_BITS))[:500]
    print('Total accuracy:')
    print(sum(map(is_correct_for_number, sample)) / len(sample))
    print(f'(Accuracy of random algorithm is {1/RADIX:.2f}')

if __name__ == '__main__':
    main()


问:
java.lang.NoClassDefFoundError: org/apache/axis2/AxisFault When axis2-kernel-1.5.4.jar is in the class path
I have a jar file with a main() statement that instantiates and calls an axis2 web service stub. It cannot seem to find org.apache.axis2.AxisFault despite it being on my classpath. I am running 1.6.0_25 on windows 7. My command is as follows:

```<code>java -classpath "C:\Program Files\Apache Software Foundation\axis2-1.5.4\lib\axis2-kernel-1.5.4.jar" -jar .\build\lib\SoapClient-test-client.jar
</code>```

The exception is:

```<code>Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/axis2/AxisFault
Caused by: java.lang.ClassNotFoundException: org.apache.axis2.AxisFault
        at java.net.URLClassLoader$1.run(Unknown Source)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
</code>```

答: -jar makes java ignore any -cp jars.  Adjust the Class-Path in the manifest.

ContentLicense: CC BY-SA 3.0

Body:
I have a jar file with a main() statement that instantiates and calls an axis2 web service stub. It cannot seem to find org.apache.axis2.AxisFault despite it being on my classpath. I am running 1.6.0_25 on windows 7. My command is as follows:

java -classpath "C:\Program Files\Apache Software Foundation\axis2-1.5.4\lib\axis2-kernel-1.5.4.jar" -jar .\build\lib\SoapClient-test-client.jar

The exception is:

Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/axis2/AxisFault
Caused by: java.lang.ClassNotFoundException: org.apache.axis2.AxisFault
        at java.net.URLClassLoader$1.run(Unknown Source)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)


问:
How do I attach a managed IAM policy and an inline/custom IAM policy to IAM roles?
I want to attach a managed IAM Policy ARN (like AmazomS3FullAccess) and an inline/custom IAM policy (written in JSON in terraform file) to a single IAM Role.

by using aws_iam_role_policy_attachment I am able to attach only one policy, what's the way to attach both?

```<code>variables.tf
------------

variable "iam_policy_arn" {
  description = "IAM Policy to be attached to role"
  type        = list(string)
  default     = ["arn:aws:iam::aws:policy/AWSLambdaFullAccess", "arn:aws:iam::aws:policy/AmazonSSMFullAccess", "arn:aws:iam::aws:policy/AmazonSageMakerFullAccess"]
}

main.tf
-------

resource "aws_iam_role" "test_role" {
  name = "test_role"

  assume_role_policy = <<-EOF
{
  "Version":"2012-10-17",
  "Statement":[
    {
      "Effect":"Allow",
      "Principal":{
        "Service":"ec2.amazonaws.com"
      },
      "Action":"sts:AssumeRole"
    },
    {
      "Effect":"Allow",
      "Principal":{
        "Service":"sagemaker.amazonaws.com",
        "AWS":"*"
      },
      "Action":"sts:AssumeRole"
    }
  ]
}
  EOF
}
resource "aws_iam_role_policy_attachment" "role_policy_attachment" {
  role       = "${aws_iam_role.test_role.name}"
  count      = "${length(var.iam_policy_arn)}"
  policy_arn = "${element(var.iam_policy_arn,count.index)}"

}

resource "aws_iam_instance_profile" "test_profile" {
  name = "test_profile"
  role = "${aws_iam_role.test_role.name}"
}
</code>```

now I want to attach a custom policy like below to the role

```<code>resource "aws_iam_role_policy" "test_policy" {
  name = "test_policy"
  role = aws_iam_role.test_role.id

  policy = <<-EOF
  {
    "Version": "2012-10-17",
    "Statement": [
      {
        "Action": [
          "ec2:Describe*"
        ],
        "Effect": "Allow",
        "Resource": "*"
      }
    ]
  }
  EOF
}
</code>```

How do I attach a managed IAM policy and a custom IAM policy to IAM roles?

答:
I was able to attach a managed IAM policy and an inline/custom IAM policy to IAM role using the below code.</p>

```<code># variables.tf
variable "cloudwatch_lambda_iam_policy_arn" {
  type        = list(string)
  description = "IAM Policy to be attached to AWS CloudWatch Lambda role"
  default     = ["arn:aws:iam::aws:policy/AmazonEC2FullAccess", "arn:aws:iam::aws:policy/AWSLambdaExecute", "arn:aws:iam::aws:policy/AmazonCloudDirectoryFullAccess", "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"]
}

#------------------------------------------------------------

# lambda.tf
resource "aws_iam_role" "awsmetrics_exec_role" {
  name = "awsmetrics-exec-role"

  assume_role_policy = <<EOF
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Action": "sts:AssumeRole",
      "Principal": {
        "Service": "lambda.amazonaws.com"
      },
      "Effect": "Allow",
      "Sid": ""
    }
  ]
}
EOF
}

# custom/inline policy
resource "aws_iam_role_policy" "sts_assumerole_lambda" {
  name = "sts-assumerole-lambda"
  role = aws_iam_role.awsmetrics_exec_role.id

  policy = <<-EOF
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "VisualEditor0",
      "Effect": "Allow",
      "Action": [
        "sts:AssumeRole",
        "sts:DecodeAuthorizationMessage",
        "sts:AssumeRoleWithSAML",
        "sts:AssumeRoleWithWebIdentity"
      ],
      "Resource": "*"
    }
  ]
}
EOF
}

# AWS managed policies
resource "aws_iam_role_policy_attachment" "awsmetrics_role_policy_attachment" {
  role       = aws_iam_role.awsmetrics_exec_role.name
  count      = length(var.cloudwatch_lambda_iam_policy_arn)
  policy_arn = element(var.cloudwatch_lambda_iam_policy_arn, count.index)
}
</code>```

Body:
I want to attach a managed IAM Policy ARN (like AmazomS3FullAccess) and an inline/custom IAM policy (written in JSON in terraform file) to a single IAM Role.

by using aws_iam_role_policy_attachment I am able to attach only one policy, what's the way to attach both?

variables.tf
------------

variable "iam_policy_arn" {
  description = "IAM Policy to be attached to role"
  type        = list(string)
  default     = ["arn:aws:iam::aws:policy/AWSLambdaFullAccess", "arn:aws:iam::aws:policy/AmazonSSMFullAccess", "arn:aws:iam::aws:policy/AmazonSageMakerFullAccess"]
}

main.tf
-------

resource "aws_iam_role" "test_role" {
  name = "test_role"

  assume_role_policy = <<-EOF
{
  "Version":"2012-10-17",
  "Statement":[
    {
      "Effect":"Allow",
      "Principal":{
        "Service":"ec2.amazonaws.com"
      },
      "Action":"sts:AssumeRole"
    },
    {
      "Effect":"Allow",
      "Principal":{
        "Service":"sagemaker.amazonaws.com",
        "AWS":"*"
      },
      "Action":"sts:AssumeRole"
    }
  ]
}
  EOF
}
resource "aws_iam_role_policy_attachment" "role_policy_attachment" {
  role       = "${aws_iam_role.test_role.name}"
  count      = "${length(var.iam_policy_arn)}"
  policy_arn = "${element(var.iam_policy_arn,count.index)}"

}

resource "aws_iam_instance_profile" "test_profile" {
  name = "test_profile"
  role = "${aws_iam_role.test_role.name}"
}

now I want to attach a custom policy like below to the role

resource "aws_iam_role_policy" "test_policy" {
  name = "test_policy"
  role = aws_iam_role.test_role.id

  policy = <<-EOF
  {
    "Version": "2012-10-17",
    "Statement": [
      {
        "Action": [
          "ec2:Describe*"
        ],
        "Effect": "Allow",
        "Resource": "*"
      }
    ]
  }
  EOF
}

How do I attach a managed IAM policy and a custom IAM policy to IAM roles?

Body:
I was able to attach a managed IAM policy and an inline/custom IAM policy to IAM role using the below code.

# variables.tf
variable "cloudwatch_lambda_iam_policy_arn" {
  type        = list(string)
  description = "IAM Policy to be attached to AWS CloudWatch Lambda role"
  default     = ["arn:aws:iam::aws:policy/AmazonEC2FullAccess", "arn:aws:iam::aws:policy/AWSLambdaExecute", "arn:aws:iam::aws:policy/AmazonCloudDirectoryFullAccess", "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"]
}

#------------------------------------------------------------

# lambda.tf
resource "aws_iam_role" "awsmetrics_exec_role" {
  name = "awsmetrics-exec-role"

  assume_role_policy = <<EOF
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Action": "sts:AssumeRole",
      "Principal": {
        "Service": "lambda.amazonaws.com"
      },
      "Effect": "Allow",
      "Sid": ""
    }
  ]
}
EOF
}

# custom/inline policy
resource "aws_iam_role_policy" "sts_assumerole_lambda" {
  name = "sts-assumerole-lambda"
  role = aws_iam_role.awsmetrics_exec_role.id

  policy = <<-EOF
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "VisualEditor0",
      "Effect": "Allow",
      "Action": [
        "sts:AssumeRole",
        "sts:DecodeAuthorizationMessage",
        "sts:AssumeRoleWithSAML",
        "sts:AssumeRoleWithWebIdentity"
      ],
      "Resource": "*"
    }
  ]
}
EOF
}

# AWS managed policies
resource "aws_iam_role_policy_attachment" "awsmetrics_role_policy_attachment" {
  role       = aws_iam_role.awsmetrics_exec_role.name
  count      = length(var.cloudwatch_lambda_iam_policy_arn)
  policy_arn = element(var.cloudwatch_lambda_iam_policy_arn, count.index)
}


问:
Confusion matrix in linear regression
I have actual values and predicted values.

Actual:
33.3663, 38.2561, 28.6362, 35.6252

Predicted:
28.9721, 35.6161, 27.9561, 22.6272

I want to apply confusion matrix to find the accuracy.

答:
Solution

First thing, confusion matrix is not for continuous values. AND you can also use it by converting continuous values to classes. check https://datascience.stackexchange.com/questions/46019/continuous-variable-not-supported-in-confusion-matrix

from sklearn.metrics import confusion_matrix

expected = [1, 1, 0, 1, 0, 0, 1, 0, 0, 0]
predicted = [1, 0, 0, 1, 0, 0, 1, 1, 1, 0]
results = confusion_matrix(expected, predicted)
print(results)
```
<h2>Output</h2>
<pre class="lang-sh prettyprint-override"><code>[[4 2]
 [1 3]]
</code>```

Reference

https://machinelearningmastery.com/confusion-matrix-machine-learning/

Title: Confusion matrix in linear regression

Body:
Solution

First thing, confusion matrix is not for continuous values. AND you can also use it by converting continuous values to classes. check https://datascience.stackexchange.com/questions/46019/continuous-variable-not-supported-in-confusion-matrix

from sklearn.metrics import confusion_matrix

expected = [1, 1, 0, 1, 0, 0, 1, 0, 0, 0]
predicted = [1, 0, 0, 1, 0, 0, 1, 1, 1, 0]
results = confusion_matrix(expected, predicted)
print(results)

Output

[[4 2]
 [1 3]]

Reference

https://machinelearningmastery.com/confusion-matrix-machine-learning/


问:
Unable to import estimation module in lifetimes
I'm trying to analyze customer shopping data and I'm trying this using lifetimes package in Python.I'm unable to import estimation module in lifetime

```<code>from lifetimes.utils import *
from lifetimes.plotting import *

from lifetimes.estimation import *

from lifetimes.estimation import *
</code>```

ModuleNotFoundError: No module named 'lifetimes.estimation'

答:
Thought to expand on it a bit more in case anyone else faces the same issue (due to following redundant codes).

The lifetimes.estimation module is no longer available within the lifetimes package (as per the latest model documentation). All the functionalities in this module were moved to other modules and you really do not need this module anymore. Continue using the latest model version 0.11.1 and don't import this specific submodule.

Body:
I'm trying to analyze customer shopping data and I'm trying this using lifetimes package in Python.I'm unable to import estimation module in lifetime

from lifetimes.utils import *
from lifetimes.plotting import *

from lifetimes.estimation import *

from lifetimes.estimation import *

ModuleNotFoundError: No module named 'lifetimes.estimation'


问:
Difference between Microsoft Hosted Agents and Self-hosted agents and their applicability
I'm new to Azure pipelines and curious to know the exact difference between Microsoft Hosted agents and Self-Hosted Agents. Also need to know in what scenarios we should use either of the agents. Do these agents have relation with On-prem and cloud deployments?</p>

答:
Microsoft-hosted agents :

With Microsoft-hosted agents, maintenance and upgrades are taken care of for you. Each time you run a pipeline, you get a fresh virtual machine. The virtual machine is discarded after one use. Microsoft-hosted agents can run jobs directly on the VM or in a container.

The pre-defined Azure Pipelines agent pool offers several virtual machine images to choose from, each including a broad range of tools and software. You can see the installed software for each hosted agent by choosing the Included Software link in the table.

Microsoft-hosted agents run on secure Azure platform. However, you must be aware of the following security considerations.

Although Microsoft-hosted agents run on Azure public network, they
are not assigned public IP addresses. So, external entities cannot
target Microsoft-hosted agents.

Microsoft-hosted agents are run in individual VMs, which are
re-imaged after each run. Each agent is dedicated to a single
organization, and each VM hosts only a single agent.

There are several benefits to running your pipeline on
Microsoft-hosted agents, from a security perspective. If you run
untrusted code in your pipeline, such as contributions from forks, it
is safer to run the pipeline on Microsoft-hosted agents than on
self-hosted agents that reside in your corporate network.

When a pipeline needs to access your corporate resources behind a
firewall, you have to whitelist the IP address range for the Azure
geography. This may increase your exposure as the range of IP
addresses is rather large and since machines in this range can belong
to other customers as well. The best way to prevent this is to avoid
the need to access internal resources.

Hosted images do not conform to CIS hardening benchmarks. To use
CIS-hardened images, you must create either self-hosted agents or
scale-set agents.

For capabilities, limitations and other details about hosted agent ,please refer to this document.

For many teams this is the simplest way to run your jobs. You can try it first and see if it works for your build or deployment. If not, you can use a self-hosted agent.

Self-hosted agents :

Self-hosted agents give you more control to install dependent software needed for your builds and deployments. Also, machine-level caches and configuration persist from run to run, which can boost speed.

You can install the agent on Linux, macOS, Windows machines or Docker container.

The performance advantages of private agent:

If you use a self-hosted agent, you can run incremental builds. For
example, if you define a pipeline that does not clean the repo and
does not perform a clean build, your builds will typically run
faster. When you use a Microsoft-hosted agent, you don't get these
benefits because the agent is destroyed after the build or release
pipeline is completed.

A Microsoft-hosted agent can take longer to start your build. While
it often takes just a few seconds for your job to be assigned to a
Microsoft-hosted agent, it can sometimes take several minutes for an
agent to be allocated depending on the load on our system.

Summary: There are many differences between hosted agent and self-hosted agent, you can choose the appropriate agent according to your needs. For details,please refer to the documentation .


问:
MSB4062: “Typescript.Tasks.CheckFileSysytemCaseSensitive” task couldn't be loaded from the assembly
While setting up a project, getting this error on npm run build:

C:..\src\packages\Microsoft.Portal.Tools.5.0.303.3330\build\TypeScript\tools\Microsoft.TypeScript.targets(219,5): error MSB4062: The "TypeScript.Tasks.CheckFileSystemCaseSensitive"
  task could not be loaded from the assembly
  C:..\src\packages\Microsoft.Portal.Tools.5.0.303.3330\build\TypeScript\build..\tools\net45\TypeScript.Tasks.dll. Could not load file or assembly 'Microsoft.Build.Utilities.Core,
  Version=14.0.0.0, Culture=neutral, PublicKeyToken=..' or one of its
  dependencies. The system cannot find the file specified. Confirm that
  the  declaration is correct, that the assembly and all its
  dependencies are available, and that the task contains a public class
  that implements Microsoft.Build.Framework.ITask.
  [C:..\src\Default\Extension\Extension.csproj]

Package.json

```<code>  {
  "name": "extensiondev",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "restore": "npm install --no-optional && nuget install ./packages.config",
    "build": "msbuild.exe ./Extension.csproj /m /p:RunBundlerInDevMode=true /t:Rebuild /flp1:logfile=msbuild.log /flp2:logfile=msbuild.err;errorsonly /flp3:logfile=msbuild.wrn;warningsonly",
    "serve": "node ./node_modules/@../portalhostingservice/DevServer/DevServer.js -s",
    "start": "npm run restore && npm run build && npm run serve",
    "watch": "cd ./node_modules/.bin && tsc.cmd -b ../../tsconfig.json -w --extendedDiagnostics",
    "release": "msbuild.exe ./Extension.csproj /m /p:RunBundlerInDevMode=false;Configuration=Release /t:Rebuild /flp1:logfile=msbuild.log /flp2:logfile=msbuild.err;errorsonly /flp3:logfile=msbuild.wrn;warningsonly"
  },
  "author": "..",
  "license": "..",
  "dependencies": {},
  "devDependencies": {
    "@../portalhostingservice": "1.182.*",
    "typescript": "3.2.1"
  }
}
</code>```

答:
Thanks for sharing the detailed info with us.

MSB4062: “Typescript.Tasks.CheckFileSysytemCaseSensitive” task
  couldn't be loaded from the assembly

The reason is that when you call Windows Powershell, you use another wrong MSBuild version rather than the related VS MSBuild version.

When you call Windows Powershell to build VS projects, you should config the right MSBuild path into System Environment Variables while VS Developer Powershell and Developer Command Prompt for VS already contains the necessary development environment(the runtime required by the corresponding workspace and required DLLS for the corresponding project), so you can build in it.

Since you built the extension project successfully in VS IDE, I think you think use a wrong MSBuild version like Framework MSBuild version which does not contain the related development environment.

You should use C:\Program Files (x86)\Microsoft Visual Studio\2019\xxx\MSBuild\Current\Bin\MSBuild.exe which is used by VS IDE during the process.

Solution

1) check PATH system environment variables and delete the previous path.

2) Instead, input C:\Program Files (x86)\Microsoft Visual Studio\2019\xxx\MSBuild\Current\Bin into PATH, and then you can use Windows Powershell to build your project successfully.

Body:
While setting up a project, getting this error on npm run build:

C:..\src\packages\Microsoft.Portal.Tools.5.0.303.3330\build\TypeScript\tools\Microsoft.TypeScript.targets(219,5): error MSB4062: The "TypeScript.Tasks.CheckFileSystemCaseSensitive"
  task could not be loaded from the assembly
  C:..\src\packages\Microsoft.Portal.Tools.5.0.303.3330\build\TypeScript\build..\tools\net45\TypeScript.Tasks.dll. Could not load file or assembly 'Microsoft.Build.Utilities.Core,
  Version=14.0.0.0, Culture=neutral, PublicKeyToken=..' or one of its
  dependencies. The system cannot find the file specified. Confirm that
  the  declaration is correct, that the assembly and all its
  dependencies are available, and that the task contains a public class
  that implements Microsoft.Build.Framework.ITask.
  [C:..\src\Default\Extension\Extension.csproj]

Package.json

  {
  "name": "extensiondev",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "restore": "npm install --no-optional && nuget install ./packages.config",
    "build": "msbuild.exe ./Extension.csproj /m /p:RunBundlerInDevMode=true /t:Rebuild /flp1:logfile=msbuild.log /flp2:logfile=msbuild.err;errorsonly /flp3:logfile=msbuild.wrn;warningsonly",
    "serve": "node ./node_modules/@../portalhostingservice/DevServer/DevServer.js -s",
    "start": "npm run restore && npm run build && npm run serve",
    "watch": "cd ./node_modules/.bin && tsc.cmd -b ../../tsconfig.json -w --extendedDiagnostics",
    "release": "msbuild.exe ./Extension.csproj /m /p:RunBundlerInDevMode=false;Configuration=Release /t:Rebuild /flp1:logfile=msbuild.log /flp2:logfile=msbuild.err;errorsonly /flp3:logfile=msbuild.wrn;warningsonly"
  },
  "author": "..",
  "license": "..",
  "dependencies": {},
  "devDependencies": {
    "@../portalhostingservice": "1.182.*",
    "typescript": "3.2.1"
  }
}


问:
How to ping muliple hosts at the same time
I'm trying to ping various hosts at the same time using github.com/sparrc/go-ping and goroutines. The issue is that it seems "stats" is shared between all the goroutines. That means "stats" has approximately the same value in all goroutines. For me they should be a instance of "stats" for every goroutine. What also puzzles me is that even for an unexisting host there are values in stats. I was thinking may be it's not possible to ping multiple hosts using ICMP from a socket but obviously I'm able to perform such a thing from PowerShell.

Here is my code:

package main

import (
    "fmt"
    "sync"

    "github.com/sparrc/go-ping"
)

var wg sync.WaitGroup

func pingfunc(ip string) {
    defer wg.Done()
    pinger, err := ping.NewPinger(ip)
    pinger.SetPrivileged(true)

    if err != nil {
        panic(err)
    }
    pinger.Count = 3

    pinger.OnFinish = func(stats *ping.Statistics) {
        fmt.Println(stats)
    }
    pinger.Run() // blocks until finished
}

func main() {
    ips := [4]string{"172.26.236.3",
        "172.26.236.5",
        "172.26.236.10",
        "172.26.2.20"} //this host doesn't exist
    for _, s := range ips {
        wg.Add(1)
        go pingfunc(s)
    }
    wg.Wait()

}
```

<p>Output:</p>

```&{3 2 -50 172.26.236.3 172.26.236.3 [12.9656ms 12.9656ms 11.9679ms] 11.9679ms 12.9656ms 12.633033ms 470.32µs}
&{3 2 -50 172.26.236.10 172.26.236.10 [12.9656ms 12.9656ms 11.9679ms] 11.9679ms 12.9656ms 12.633033ms 470.32µs}
&{3 3 0 172.26.2.20 172.26.2.20 [12.9656ms 14.9603ms 17.166ms] 12.9656ms 17.166ms 15.030633ms 1.715527ms}
&{3 3 0 172.26.236.5 172.26.236.5 [12.9656ms 14.9603ms 17.166ms] 12.9656ms 17.166ms 15.030633ms 1.715527ms}1.850632ms}
```

答:
Do see this example

In your example, you have the OnFinish callback. But you would there's another callback available i.e., OnRecv.

If it receives a response, it calls the "OnRecv" callback. When it's finished, it calls the "Finish" callback.

So, for the non-existing host, as the GoDoc says:

Statistics represent the stats of a currently running or finished pinger operation.

Packet represents a received and processed ICMP echo packet.

You need to pick the stats from Packet struct as shown in the example for the ICMP echo packets received. So, follow the example; you'd be good to go!

Body:
I'm trying to ping various hosts at the same time using github.com/sparrc/go-ping and goroutines. The issue is that it seems "stats" is shared between all the goroutines. That means "stats" has approximately the same value in all goroutines. For me they should be a instance of "stats" for every goroutine. What also puzzles me is that even for an unexisting host there are values in stats. I was thinking may be it's not possible to ping multiple hosts using ICMP from a socket but obviously I'm able to perform such a thing from PowerShell.

Here is my code:

package main

import (
    "fmt"
    "sync"

    "github.com/sparrc/go-ping"
)

var wg sync.WaitGroup

func pingfunc(ip string) {
    defer wg.Done()
    pinger, err := ping.NewPinger(ip)
    pinger.SetPrivileged(true)

    if err != nil {
        panic(err)
    }
    pinger.Count = 3

    pinger.OnFinish = func(stats *ping.Statistics) {
        fmt.Println(stats)
    }
    pinger.Run() // blocks until finished
}

func main() {
    ips := [4]string{"172.26.236.3",
        "172.26.236.5",
        "172.26.236.10",
        "172.26.2.20"} //this host doesn't exist
    for _, s := range ips {
        wg.Add(1)
        go pingfunc(s)
    }
    wg.Wait()

}

Output:

&{3 2 -50 172.26.236.3 172.26.236.3 [12.9656ms 12.9656ms 11.9679ms] 11.9679ms 12.9656ms 12.633033ms 470.32µs}
&{3 2 -50 172.26.236.10 172.26.236.10 [12.9656ms 12.9656ms 11.9679ms] 11.9679ms 12.9656ms 12.633033ms 470.32µs}
&{3 3 0 172.26.2.20 172.26.2.20 [12.9656ms 14.9603ms 17.166ms] 12.9656ms 17.166ms 15.030633ms 1.715527ms}
&{3 3 0 172.26.236.5 172.26.236.5 [12.9656ms 14.9603ms 17.166ms] 12.9656ms 17.166ms 15.030633ms 1.715527ms}1.850632ms}


问:
Comparison loop
I have a nested list

```<code>combine <- list(c('A', 'B', 'C'), c('D', 'H', 'G', 'J'), c('A', 'E'))
</code>```

and a df

```<code>df <- data.frame(appln_id = c(1, 1, 2, 2, 4, 4, 4, 3, 3, 3, 3, 5, 9, 9),
                 prior_year = c(1997,1997,1997,1997,1997,1997,1997,1998,1998,1998,1998,2000,2000,2000),
                 IPC = c('B','E','E','B','H','J','D','H','J','D','E','A','E','B'))
</code>```

I want to aggregate IPC according to appln_id (eg: for appln_id=1: c('B','E'), for appln_id=2: c('E','B'), for appln_id=4: c('H','J','D'), etc.). Then for each value of prior_year, I want to compare the IPC sets to elements of the list combine.

For the IPC set that is not a subset of any element of combine, I want to save its data in df in another dataframe called new as follows:

```<code>new <- data.frame(appln_id = c(1, 1, 3, 3, 3, 3),
                  prior_year = c(1997,1997,1998,1998,1998,1998),
                  IPC = c('B','E','H','J','D','E'))
</code>```

and add this IPC set into combine as follows:

```<code>combine <- list(c('A', 'B', 'C'), c('D', 'H', 'G', 'J'), c('A', 'E'), c('B', 'E'), c('D','E','J','H'))
</code>```

This is my code:

```<code>new <- data.frame(appln_id=integer(),prio_year=integer(), IPC=character())
new_combine=list()
prio_year <- unique(df$prio_year)
appln_id <- unique(df$appln_id)
for (i in prio_year){
  for (j in appln_id){
    x <- sort((df[(df$prio_year==i) & (df$appln_id==j),3])[[1]])
    for (k in combine){
      if (all(x %in% k) == FALSE){
        new <- rbind(new, df[df$appln_id==j,])
        new_combine[[length(new_combine)+1]] <- x
      }
    }
  }
  combine <- c(combine,unique(new_combine))
}
</code>```

However, it takes too long for my code to run. Could anyone have another way to make it faster? Thank you.

答:
Here's something that is only a single loop. Up front, though, I changed $IPC from factor to character, since merging differing factor levels can be a little annoying. (If you're on R-4.0 or $IPC is already character, then no need to do this step.)

df$usable <- TRUE
df$grps <- interaction(df$appln_id, df$prior_year)
newlist <- list()
for (grp in levels(df$grps)) {
  rows <- df$grps == grp & df$usable
  if (!length(rows)) next
  thisIPC <- df$IPC[rows]
  matches <- sapply(combine, function(comb) all(thisIPC %in% comb))
  if (any(matches)) {
    # repeat
  } else {
    # new!
    combine <- c(combine, list(thisIPC))
    newlist <- c(newlist, list(df[rows,]))
    df$usable[rows] <- FALSE
  }
}
df <- df[df$usable,]
new <- do.call(rbind, newlist)
df$usable <- df$grps <-
  new$usable <- new$grps <- NULL

df
#    appln_id prior_year IPC
# 3         2       1997   E
# 4         2       1997   B
# 5         4       1997   H
# 6         4       1997   J
# 7         4       1997   D
# 12        5       2000   A
# 13        9       2000   E
# 14        9       2000   B
new
#    appln_id prior_year IPC
# 1         1       1997   B
# 2         1       1997   E
# 8         3       1998   H
# 9         3       1998   J
# 10        3       1998   D
# 11        3       1998   E
str(combine)
# List of 5
#  $ : chr [1:3] "A" "B" "C"
#  $ : chr [1:4] "D" "H" "G" "J"
#  $ : chr [1:2] "A" "E"
#  $ : chr [1:2] "B" "E"
#  $ : chr [1:4] "H" "J" "D" "E"
```

Notes:

I create the $grps variable to make easy single-loop grouping; once this loop is done, feel free to remove it. Using factor and then levels ensures that I iterate over else present combination, nothing more.

I may be going to more extremes than necessary, but iteratively growing frames is bad in the long-term for performance: each time you "add rows", the entire frame is perfectly copied in memory, so with each addition, you duplicate the memory take for the frame. Granted, the memory is cleared, but it is a "known thing" that this slows down noticeably asymptotically. (See chapter 2, Growing Objects, in the R Inferno.) This applies (to a slightly-lesser degree) to iteratively removing rows, too.

Because of this, I don't actually change the contents of the frame until the very end. To accommodate this, I also add a column $usable to indicate if it should be removed in the end. (In the unlikely event that you run this code twice on the same frame, I also use $enable in grabbing $IPC, that might just be overly-defensive.)

Post-loop, I remove the relevant rows from df once, and do a single row-concatenation (rbind) on the newlist, which is a list with frames (or nothing, if nothing happened).

Title: Comparison loop

Body:
I have a nested list

combine <- list(c('A', 'B', 'C'), c('D', 'H', 'G', 'J'), c('A', 'E'))

and a df

df <- data.frame(appln_id = c(1, 1, 2, 2, 4, 4, 4, 3, 3, 3, 3, 5, 9, 9),
                 prior_year = c(1997,1997,1997,1997,1997,1997,1997,1998,1998,1998,1998,2000,2000,2000),
                 IPC = c('B','E','E','B','H','J','D','H','J','D','E','A','E','B'))

I want to aggregate IPC according to appln_id (eg: for appln_id=1: c('B','E'), for appln_id=2: c('E','B'), for appln_id=4: c('H','J','D'), etc.). Then for each value of prior_year, I want to compare the IPC sets to elements of the list combine.

For the IPC set that is not a subset of any element of combine, I want to save its data in df in another dataframe called new as follows:

new <- data.frame(appln_id = c(1, 1, 3, 3, 3, 3),
                  prior_year = c(1997,1997,1998,1998,1998,1998),
                  IPC = c('B','E','H','J','D','E'))

and add this IPC set into combine as follows:

combine <- list(c('A', 'B', 'C'), c('D', 'H', 'G', 'J'), c('A', 'E'), c('B', 'E'), c('D','E','J','H'))

This is my code:

new <- data.frame(appln_id=integer(),prio_year=integer(), IPC=character())
new_combine=list()
prio_year <- unique(df$prio_year)
appln_id <- unique(df$appln_id)
for (i in prio_year){
  for (j in appln_id){
    x <- sort((df[(df$prio_year==i) & (df$appln_id==j),3])[[1]])
    for (k in combine){
      if (all(x %in% k) == FALSE){
        new <- rbind(new, df[df$appln_id==j,])
        new_combine[[length(new_combine)+1]] <- x
      }
    }
  }
  combine <- c(combine,unique(new_combine))
}

However, it takes too long for my code to run. Could anyone have another way to make it faster? Thank you.

Body:
Here's something that is only a single loop. Up front, though, I changed $IPC from factor to character, since merging differing factor levels can be a little annoying. (If you're on R-4.0 or $IPC is already character, then no need to do this step.)

df$usable <- TRUE
df$grps <- interaction(df$appln_id, df$prior_year)
newlist <- list()
for (grp in levels(df$grps)) {
  rows <- df$grps == grp & df$usable
  if (!length(rows)) next
  thisIPC <- df$IPC[rows]
  matches <- sapply(combine, function(comb) all(thisIPC %in% comb))
  if (any(matches)) {
    # repeat
  } else {
    # new!
    combine <- c(combine, list(thisIPC))
    newlist <- c(newlist, list(df[rows,]))
    df$usable[rows] <- FALSE
  }
}
df <- df[df$usable,]
new <- do.call(rbind, newlist)
df$usable <- df$grps <-
  new$usable <- new$grps <- NULL

df
#    appln_id prior_year IPC
# 3         2       1997   E
# 4         2       1997   B
# 5         4       1997   H
# 6         4       1997   J
# 7         4       1997   D
# 12        5       2000   A
# 13        9       2000   E
# 14        9       2000   B
new
#    appln_id prior_year IPC
# 1         1       1997   B
# 2         1       1997   E
# 8         3       1998   H
# 9         3       1998   J
# 10        3       1998   D
# 11        3       1998   E
str(combine)
# List of 5
#  $ : chr [1:3] "A" "B" "C"
#  $ : chr [1:4] "D" "H" "G" "J"
#  $ : chr [1:2] "A" "E"
#  $ : chr [1:2] "B" "E"
#  $ : chr [1:4] "H" "J" "D" "E"

Notes:

I create the $grps variable to make easy single-loop grouping; once this loop is done, feel free to remove it. Using factor and then levels ensures that I iterate over else present combination, nothing more.

I may be going to more extremes than necessary, but iteratively growing frames is bad in the long-term for performance: each time you "add rows", the entire frame is perfectly copied in memory, so with each addition, you duplicate the memory take for the frame. Granted, the memory is cleared, but it is a "known thing" that this slows down noticeably asymptotically. (See chapter 2, Growing Objects, in the R Inferno.) This applies (to a slightly-lesser degree) to iteratively removing rows, too.

Because of this, I don't actually change the contents of the frame until the very end. To accommodate this, I also add a column $usable to indicate if it should be removed in the end. (In the unlikely event that you run this code twice on the same frame, I also use $enable in grabbing $IPC, that might just be overly-defensive.)

Post-loop, I remove the relevant rows from df once, and do a single row-concatenation (rbind) on the newlist, which is a list with frames (or nothing, if nothing happened).


问:
Python searching lists with lists, all and any
I am having trouble for some reason with a certain if statement. Let's say I have three lists:

```<code>list1 = [1,2,3,4,5]
list2 = [1,2,4,5]
list3 = [4,5,6,7,8]
</code>```

I evaluate each. I want to flag it if the list has both 4 AND 5, but does not have either 2 OR 3. I thought this would work:

```<code>if all(q in [4,5] for q in the_list_name) and not any(q in [2,3] for q in the_list_name)
</code>```

I would expect this to flag only list3. However it returns false on all of the lists. I wonder what I am doing wrong?

答:
A simple approach could be:-

if ( (4 in _list_name and 5 in _list_name )and (2 not in _list_name or 3 not in _list_name))

Body:
I am having trouble for some reason with a certain if statement. Let's say I have three lists:

list1 = [1,2,3,4,5]
list2 = [1,2,4,5]
list3 = [4,5,6,7,8]

I evaluate each. I want to flag it if the list has both 4 AND 5, but does not have either 2 OR 3. I thought this would work:

if all(q in [4,5] for q in the_list_name) and not any(q in [2,3] for q in the_list_name)

I would expect this to flag only list3. However it returns false on all of the lists. I wonder what I am doing wrong?


问:
Does this method cause concurrency problems?
I have a CoreDataUtilities class with a class method that saves a managed object context and takes care of any errors:

```<code>+ (void)saveContext:(NSManagedObjectContext*)moc {
    NSError *error = nil;
    if (moc != nil) {
        if ([moc hasChanges] && ![moc save:&error]) {
            NSLog(@"MOC save error: %@, %@", error, [error userInfo]);
        }
    }
}
</code>```

I call this method from NSOperation subclasses and background threads, and pass in the NSManagedObjectContext instance of the thread / NSOperation.

My concern is this:

If Thread A calls this method, and while this method is executing half-way, Thread B calls it too. With another MOC of course. Woul this interfere in any way? From my point of view it would not, because this method does only communicate with the MOC instance which is "private" or "owned" by the calling Thread anyways. But what irritates me is if even local variables in a method get "mixed up" when multiple threads execute the same piece of code at the same time. Or does every variable have their own "context" in a new thread, with it's own heap (or stack, for that matter) of memory?

Does it make a big difference if I put this saving code directly into the NSOperation subclasses and background threads? Why?

答:
The rule is that each thread must have its own moc.

Check out Apple's Guidelines for more information.

Body:
I have a CoreDataUtilities class with a class method that saves a managed object context and takes care of any errors:

+ (void)saveContext:(NSManagedObjectContext*)moc {
    NSError *error = nil;
    if (moc != nil) {
        if ([moc hasChanges] && ![moc save:&error]) {
            NSLog(@"MOC save error: %@, %@", error, [error userInfo]);
        }
    }
}

I call this method from NSOperation subclasses and background threads, and pass in the NSManagedObjectContext instance of the thread / NSOperation.

My concern is this:

If Thread A calls this method, and while this method is executing half-way, Thread B calls it too. With another MOC of course. Woul this interfere in any way? From my point of view it would not, because this method does only communicate with the MOC instance which is "private" or "owned" by the calling Thread anyways. But what irritates me is if even local variables in a method get "mixed up" when multiple threads execute the same piece of code at the same time. Or does every variable have their own "context" in a new thread, with it's own heap (or stack, for that matter) of memory?

Does it make a big difference if I put this saving code directly into the NSOperation subclasses and background threads? Why?


问:
Lua script for Redis which sums the values of keys
I am building out my first Redis server side script (for debugging) and my lack of Lua experience has me quite stuck.

Essentially have a dataset of K/V pairs (containing ~1000 values) from which I want to list all the KEYS that match a pattern. For example in redis-cli:

```<code>> KEYS "carlos:*"
1) "carlos:1"
2) "carlos:2"
3) "carlos:3"
4) "carlos:4"
</code>```

Based on the above output I want to return the sum of those keys by executing a Lua script. Currently I have the following on my sum.lua

```<code>local sum = 0
local matches = redis.call('KEYS', 'carlos:*')

for unpack(matches)
   sum = sum + redis.call('GET', matches)
end

return sum
</code>```

While the above script is likely incorrect, trying even redis.call('KEYS', 'carlos:*') by itself produces the following error

root@carlos:~# redis-cli EVAL "$(cat sum.lua)"

(error) ERR wrong number of arguments for 'eval' command

I have tried a number of iterations of my syntax to no avail. Any ideas?

Thanks

答:
Some important points for starters:

KEYS and ARGV : These are tables in Lua which are going to hold the data sent by your redis client inside Lua Script in Redis.

Tables are associative arrays, and Lua’s only mechanism for
structuring data. You can think of them as the equivalent of an array
in whatever language you’re most comfortable with.Tables are
one-based, that is, indexing starts at 1. So the first element in
mytable is mytable[1], the second is mytable[2], etc.

Tables cannot hold nil values. If an operation would yield a table of
[ 1, nil, 3, 4 ], the result will instead be [ 1 ] — the table is
truncated at the first nil value.

Note : When writing Lua scripts for Redis, every key that is accessed should be accessed only by the KEYS table. The ARGV table is used for parameter-passing

I think you can now transfer keys and args from whatever language to your Lua script.

Now we can proceed to Lua's redis call to redis command KEYS.

To iterate over the returned data you have option of lua's pairs and ipairs and some quick difference can be spotted here. For above case ipairs will be fine.

Now we can proceed to data type issue.

Lua and Redis have different type systems, so it’s important to understand how values may change when crossing the Redis-Lua border. When a number comes from Lua back to a Redis client, it becomes an integer — any digits past the decimal point are dropped:

```<code>local indiana_pi = 3.2
return indiana_pi
</code>```

When you run this script, Redis will return an integer of 3 — you lose the interesting pieces of pi. Seems simple enough, but things get a bit more tricky when you start interacting with Redis in the middle of the script. An example:

```<code>local indiana_pi = 3.2
redis.call("SET", "pi", indiana_pi)
return redis.call("GET", "pi")
</code>```

The resulting value here is a string: "3.2" Why? Redis doesn’t have a dedicated numeric type. When we first SET the value, Redis saves it as a string, losing all record of the fact that Lua initially thought of the value as a float. When we pull the value out later, it’s still a string.

Values in Redis that are accessed with GET/SET should be thought of as strings except when numeric operations like INCR and DECR are run against them. These special numeric operations will actually return integer replies (and manipulate the stored value according to mathematical rules), but the “type” of the value stored in Redis is still a string value.

Above answer is taken from this awesome blog post on:

https://www.redisgreen.net/blog/intro-to-lua-for-redis-programmers/

Body:
I am building out my first Redis server side script (for debugging) and my lack of Lua experience has me quite stuck.

Essentially have a dataset of K/V pairs (containing ~1000 values) from which I want to list all the KEYS that match a pattern. For example in redis-cli:

> KEYS "carlos:*"
1) "carlos:1"
2) "carlos:2"
3) "carlos:3"
4) "carlos:4"

Based on the above output I want to return the sum of those keys by executing a Lua script. Currently I have the following on my sum.lua

local sum = 0
local matches = redis.call('KEYS', 'carlos:*')

for unpack(matches)
   sum = sum + redis.call('GET', matches)
end

return sum

While the above script is likely incorrect, trying even redis.call('KEYS', 'carlos:*') by itself produces the following error

root@carlos:~# redis-cli EVAL "$(cat sum.lua)"

(error) ERR wrong number of arguments for 'eval' command

I have tried a number of iterations of my syntax to no avail. Any ideas?

Thanks

Body:
Some important points for starters:

KEYS and ARGV : These are tables in Lua which are going to hold the data sent by your redis client inside Lua Script in Redis.

Tables are associative arrays, and Lua’s only mechanism for
structuring data. You can think of them as the equivalent of an array
in whatever language you’re most comfortable with.Tables are
one-based, that is, indexing starts at 1. So the first element in
mytable is mytable[1], the second is mytable[2], etc.

Tables cannot hold nil values. If an operation would yield a table of
[ 1, nil, 3, 4 ], the result will instead be [ 1 ] — the table is
truncated at the first nil value.

Note : When writing Lua scripts for Redis, every key that is accessed should be accessed only by the KEYS table. The ARGV table is used for parameter-passing

I think you can now transfer keys and args from whatever language to your Lua script.

Now we can proceed to Lua's redis call to redis command KEYS.

To iterate over the returned data you have option of lua's pairs and ipairs and some quick difference can be spotted here. For above case ipairs will be fine.

Now we can proceed to data type issue.

Lua and Redis have different type systems, so it’s important to understand how values may change when crossing the Redis-Lua border. When a number comes from Lua back to a Redis client, it becomes an integer — any digits past the decimal point are dropped:

local indiana_pi = 3.2
return indiana_pi

When you run this script, Redis will return an integer of 3 — you lose the interesting pieces of pi. Seems simple enough, but things get a bit more tricky when you start interacting with Redis in the middle of the script. An example:

local indiana_pi = 3.2
redis.call("SET", "pi", indiana_pi)
return redis.call("GET", "pi")

The resulting value here is a string: "3.2" Why? Redis doesn’t have a dedicated numeric type. When we first SET the value, Redis saves it as a string, losing all record of the fact that Lua initially thought of the value as a float. When we pull the value out later, it’s still a string.

Values in Redis that are accessed with GET/SET should be thought of as strings except when numeric operations like INCR and DECR are run against them. These special numeric operations will actually return integer replies (and manipulate the stored value according to mathematical rules), but the “type” of the value stored in Redis is still a string value.

Above answer is taken from this awesome blog post on:

https://www.redisgreen.net/blog/intro-to-lua-for-redis-programmers/


问:
How to use bulk insert condition for particular number of records inside for loop
I want to use the bulk insert concept in C# once count reach 20.if we have 40 numbers no issue. but if we get 39 records got a problem, based on if the condition. how we able to avoid this problem. here below I added a simple program for reference.</p>

```<code>var numbers = 39  // not static numbers
int count = 0;
for(int i=0; i<=numbers; i++)
{

 count++;
 if (count == 20)
   {
      //Logic
      count = 0;
   }

}
</code>```

答:
You can determine whether to batch insert the rest files by comparing the counter with the remaining number of files.</p>

```<code>int num = 49;
int count = 0;
for(int i = 1; i <= num; i++)
{
    count++;
    var n = i / 20;
    if(i % 20 == 0 ||count == (num - 20 * ( i / 20)))
    {
        //Logic
        count = 0;
    }
}
</code>```

Body:
I want to use the bulk insert concept in C# once count reach 20.if we have 40 numbers no issue. but if we get 39 records got a problem, based on if the condition. how we able to avoid this problem. here below I added a simple program for reference.

var numbers = 39  // not static numbers
int count = 0;
for(int i=0; i<=numbers; i++)
{

 count++;
 if (count == 20)
   {
      //Logic
      count = 0;
   }

}

Body:
You can determine whether to batch insert the rest files by comparing the counter with the remaining number of files.

int num = 49;
int count = 0;
for(int i = 1; i <= num; i++)
{
    count++;
    var n = i / 20;
    if(i % 20 == 0 ||count == (num - 20 * ( i / 20)))
    {
        //Logic
        count = 0;
    }
}


问:
How can I see if there's an available and active network connection in Python?
I want to see if I can access an online API, but for that, I need to have Internet access.

How can I see if there's a connection available and active using Python?

答:
import requests and try this simple python code.</p>
```<code>def check_internet():
    url = 'http://www.google.com/'
    timeout = 5
    try:
        _ = requests.get(url, timeout=timeout)
        return True
    except requests.ConnectionError:
        return False
</code>```

LastEditorDisplayName: Roger Pate

Body:
import requests and try this simple python code.

def check_internet():
    url = 'http://www.google.com/'
    timeout = 5
    try:
        _ = requests.get(url, timeout=timeout)
        return True
    except requests.ConnectionError:
        return False


问:
How to make vue set not to monitor data
I used webgl in vue and found that the data written in the return will constantly monitor the scene, resulting in poor performance。

before:

```<code>data(){
   return{
       //I create a new variable here
   }
}
</code>```

after: （I'm not sure if writing this will make vue not listen to variables）

```<code>data(){
    //I create a new variable here
    return {}
}
</code>```

答:
You can create outside data and access it by $options, like $options.myVar on your template.

```<code>export default{
  myVar : 'var',
  data(){
    return {}
  }
}
</code>```

Title: How to make vue set not to monitor data

Body:
I used webgl in vue and found that the data written in the return will constantly monitor the scene, resulting in poor performance。

before:

data(){
   return{
       //I create a new variable here
   }
}

after: （I'm not sure if writing this will make vue not listen to variables）

data(){
    //I create a new variable here
    return {}
}

Body:
You can create outside data and access it by $options, like $options.myVar on your template.

export default{
  myVar : 'var',
  data(){
    return {}
  }
}