TypeError: get_stats() takes exactly 1 argument (0 given) - class

Trying a dnd character creator: keep getting a:TypeError: get_stats() takes exactly 1 argument (0 given). I dont know how to give the shell what it wants.
Heres the code:
import random
class Character(object):
def __init__(self,name):
self.name = raw_input('name')
# Attributes for Pathfinder
def get_stats(self):
stats = []
count = 0
while count < 6:
roll = []
roll = [random.randint(1,6) for x in range(4)]
roll = sorted(roll)
del(roll[0])
sum = 0
for x in roll:
sum += x
stats.append(sum)
count += 1
print stats
return stats
stats = get_stats()
ste = stats[0]
con = stats[1]
dex = stats[2]
inte = stats[3]
wis = stats[4]
cha = stats[5]
#Modifiers
stemod = (ste - 10)/2
dexmod = (dex - 10)/2
conmod = (con - 10)/2
intemod = (inte - 10)/2
wismod = (wis - 10)/2
chamod = (cha - 10)/2
#Bios
#Sex
sex = random.randint(1,2)
if sex == 1:
sex = "male"
else:
sex = "female"
#Races and size
#list_of_races
x = random.randint(1,7)
if x == 1:
race = 'drawf'
size = 'med'
con += 2
wis += 2
cha -= 2
elif x == 2:
race = 'elf'
size = 'med'
dex += 2
inte += 2
con -= 2
elif x == 3:
race = 'human'
size = 'med'
bonus = random.randint(1,6)
if bonus == 1:
ste += 2
elif bonus == 2:
con += 2
elif bonus == 3:
dex += 2
elif bonus == 4:
inte += 2
elif bonus == 5:
wis += 2
elif bonus == 6:
cha += 2
elif x == 4:
race = 'halfling'
size = 'small'
dex += 2
cha += 2
ste -= 2
elif x == 5:
race = 'gnome'
size = 'small'
con += 2
cha += 2
ste -= 2
elif x == 6:
race = 'half-elf'
size = 'med'
bonus = random.randint(1,6)
if bonus == 1:
ste += 2
elif bonus == 2:
con += 2
elif bonus == 3:
dex += 2
elif bonus == 4:
inte += 2
elif bonus == 5:
wis += 2
elif bonus == 6:
cha += 2
elif x == 7:
race = 'half-orc'
size = 'med'
bonus = random.randint(1,6)
if bonus == 1:
ste += 2
elif bonus == 2:
con += 2
elif bonus == 3:
dex += 2
elif bonus == 4:
inte += 2
elif bonus == 5:
wis += 2
elif bonus == 6:
cha += 2
#Size pelenties
#Classes
# List of classes(Fighter,Ranger,Wizard,Cleric)
c = random.randint(1,4)
playclass = ''
while playclass == '':
if c == 1 and ste > 10:
playclass = 'Fighter'
hp = 10 + conmod
bab = 1
fort_save = 2 + conmod
reflex_save = 0 + dexmod
will_save = 0 + wismod
elif c == 2:
playclass = 'Ranger'
hp = 10 + conmod
bab = 1
fort_save = 2 + conmod
reflex_save = 2 + dexmod
will_save = 0 + wismod
elif c == 3 and inte > 10:
playclass = 'Wizard'
hp = 6 + conmod
bab = 0
fort_save = 0 + conmod
reflex_save = 0 + dexmod
will_save = 2 + wismod
elif c == 4 and wis > 10:
playclass = 'Cleric'
hp = 8 + conmod
bab = 0
fort_save = 2 + conmod
reflex_save = 0 + dexmod
will_save = 2 + wismod
else:
c = random.randint(1,3)
#AC
ac = 10 + dexmod
if size == 'small':
ac += 1
print sex
print size +" "+race
print 'strenght : ' + str(ste)
print 'constitution : ' + str(con)
print 'dexterity : ' + str(dex)
print 'intelligence : ' + str(inte)
print 'wisdom : ' + str(wis)
print 'charisma : ' + str(cha)
print playclass
print 'HP:' + str(hp)
print 'AC:' + str(ac)
print 'BAB:' + str(bab)
print 'Fort:' + str(fort_save)
print 'Will:' + str(will_save)
print 'Reflex:' + str(reflex_save)

In your get_stats() function, you have put self. But to fill the parantheses in the line:
stats = get_stats()
You are supposed to put None in your parantheses to prevent the error. So the line will look like:
stats = get_stats(None)
Why did add None? This means that the amount of stuff in the parantheses other than self is 0 or None. I hope this helps you!

Related

Pinescript Array saying index is out of bounds when I am checking the size first?

Pinescript array, checking to see if array size is minimal needed, yet it is display this error enter image description here
Here is the code I am refering:
if confirmedTriangle and array.size(triangle_price)>4 and array.size(triangle_index)>4
for i = 0 to 3
//Slope
xIndexDis = array.get(triangle_index, 0) - array.get(triangle_index, 4)// : na
yPriceDis = array.get(triangle_price, 0) - array.get(triangle_price, 4)// : na
xIndexDis2 = array.get(triangle_index, 3) - array.get(triangle_index, 1)// : na
yPriceDis2 = array.get(triangle_price, 3) - array.get(triangle_price, 1)// : na
m = yPriceDis / xIndexDis //Gradient for bottom line
m2 = yPriceDis2 / xIndexDis2 // Gradient for top line
x1 = array.get(triangle_index, i)-testLength
y1 = array.get(triangle_price, i)
x2 = array.get(triangle_index, i+1)-testLength
y2 = array.get(triangle_price, i+1)
array.push(tri_array, line.new(x1,y1,x2,y2, color=color.white))
xa1 = array.get(triangle_index,4)
xa2 = array.get(triangle_index,0)
xb1 = array.get(triangle_index,3)
xb2 = array.get(triangle_index,1)
ya1 = array.get(triangle_price,4)
ya2 = array.get(triangle_price,0)
yb1 = array.get(triangle_price,3)
yb2 = array.get(triangle_price,1)
label.new(bar_index, high+atr, text="Xa1 = " + str.tostring(xa1) + " / Ya1 = " + str.tostring(ya1) + "\n Xa2 = " + str.tostring(xa2) + " / Ya2 = " + str.tostring(ya2) + "\nXb1 = " + str.tostring(xb1) + " / Yb1 = " + str.tostring(yb1) + "\n Xb2 = " + str.tostring(xb2) + " / Yb2 = " + str.tostring(yb2))
I don't get any errors on sometimeframes but the majority do present the same error,
Found the issues,
I assigned array.size(triangle_price) to a variable
e.g. arraySize = array.size(triangle_price)
In confirmedTriangle I was checking if arraySize>4, but the array size had been changed since that check
Simple fix was just to remove "arraySize = array.size(triangle_price)" and use array.size(triangle_price) in each check

TypeError: 'NoneType' object is not an iterator Rdkit VS code

I'm trying to filter molecules from database 'part1' via Lipinski,Ghose and RUle of 3 filter but I keep getting error.
So, after I ran this script, I get an error 'object is not an iterator' at the line where 'progressbar' is mentioned twice. I'm new and would appreciate help.
Below is my script for filtering database of molecules.
from rdkit import Chem
from rdkit.Chem import Descriptors
import progressbar
if __name__ == '__main__':
molecules = Chem.SDMolSupplier('chemspidersdf/part1.sdf')
results = {
"Lipinski Rule of 5": 0,
"Ghose Filter": 0,
"Rule of 3 Filter": 0,
}
print ("Molecule Database Length: " + str(len(molecules)))
for i in progressbar.ProgressBar(range(len(molecules))):
molecule = molecules[i]
if molecule:
lipinski = False
rule_of_3 = False
ghose_filter = False
molecular_weight = Descriptors.ExactMolWt(molecule)
logp = Descriptors.MolLogP(molecule)
h_bond_donor = Descriptors.NumHDonors(molecule)
h_bond_acceptors = Descriptors.NumHAcceptors(molecule)
rotatable_bonds = Descriptors.NumRotatableBonds(molecule)
number_of_atoms = Chem.rdchem.Mol.GetNumAtoms(molecule)
molar_refractivity = Chem.Crippen.MolMR(molecule)
# Lipinski
if molecular_weight <= 500 and logp <= 5 and h_bond_donor <= 5 and h_bond_acceptors <= 5 and rotatable_bonds <= 5:
lipinski = True
results["Lipinski Rule of 5"] += 1
# Ghose Filter
if molecular_weight >= 160 and molecular_weight <= 480 and logp >= 0.4 and logp <= 5.6 and number_of_atoms >= 20 and number_of_atoms <= 70 and molar_refractivity >= 40 and molar_refractivity <= 130:
ghose_filter = True
results["Ghose Filter"] += 1
# Rule of 3
if molecular_weight <= 300 and logp <= 3 and h_bond_donor <= 3 and h_bond_acceptors <= 3 and rotatable_bonds <= 3:
rule_of_3 = True
results["Rule of 3 Filter"] += 1
print (results)
I assume you are using progressbar2. Looks like progressbar should be lowercase:
mols = Chem.SDMolSupplier('path/to/my/mols.sdf')
n_mols = len(mols)
for x in progressbar.progressbar(range(n_mols)):
# do stuff...
It also works like this:
mols = Chem.SDMolSupplier('path/to/my/mols.sdf')
for mol in progressbar.progressbar(mols):
if mol is None:
continue
# do stuff...

Using zero_grad() after loss.backward(), but still receives RuntimeError: "Trying to backward through the graph a second time..."

Below is my implementation of a2c using PyTorch. Upon learning about backpropagation in PyTorch, I have known to zero_grad() the optimizer after each update iteration. However, there is still a RunTime error on second-time backpropagation.
def torchworker(number, model):
worker_env = gym.make("Taxi-v3").env
max_steps_per_episode = 2000
worker_opt = optim.Adam(lr=5e-4, params=model.parameters())
p_history = []
val_history = []
r_history = []
running_reward = 0
episode_count = 0
under = 0
start = time.time()
for i in range(2):
state = worker_env.reset()
episode_reward = 0
penalties = 0
drop = 0
print("Episode {} begins ({})".format(episode_count, number))
worker_env.render()
criterion = nn.SmoothL1Loss()
time_solve = 0
for _ in range(1, max_steps_per_episode):
#worker_env.render()
state = torch.tensor(state, dtype=torch.long)
action_probs = model.forward(state)[0]
critic_value = model.forward(state)[1]
val_history.append((state, critic_value[0]))
# Choose action
action = np.random.choice(6, p=action_probs.detach().numpy())
p_history.append(torch.log(action_probs[action]))
# Apply chosen action
state, reward, done, _ = worker_env.step(action)
r_history.append(reward)
episode_reward += reward
time_solve += 1
if reward == -10:
penalties += 1
elif reward == 20:
drop += 1
if done:
break
# Update running reward to check condition for solving
running_reward = (running_reward * (episode_count) + episode_reward) / (episode_count + 1)
# Calculate discounted returns
returns = deque(maxlen=3500)
discounted_sum = 0
for r in r_history[::-1]:
discounted_sum = r + gamma * discounted_sum
returns.appendleft(discounted_sum)
# Calculate actor losses and critic losses
loss_actor_value = 0
loss_critic_value = 0
history = zip(p_history, val_history, returns)
for log_prob, value, ret in history:
diff = ret - value[1]
loss_actor_value += -log_prob * diff
ret_tensor = torch.tensor(ret, dtype=torch.float32)
loss_critic_value += criterion(value[1], ret_tensor)
loss = loss_actor_value + 0.1 * loss_critic_value
print(loss)
# Update params
loss.backward()
worker_opt.step()
worker_opt.zero_grad()
# Log details
end = time.time()
episode_count += 1
if episode_count % 1 == 0:
worker_env.render()
if running_reward > -50: # Condition to consider the task solved
under += 1
if under > 5:
print("Solved at episode {} !".format(episode_count))
break
I believe there may be something to do with the architecture of my AC model, so I also include it here for reference.
class ActorCriticNetwork(nn.Module):
def __init__(self, num_inputs, num_hidden, num_actions):
super(ActorCriticNetwork, self).__init__()
self.embed = nn.Embedding(500, 10)
self.fc1 = nn.Linear(10, num_hidden * 2)
self.fc2 = nn.Linear(num_hidden * 2, num_hidden)
self.c = nn.Linear(num_hidden, 1)
self.fc3 = nn.Linear(num_hidden, num_hidden)
self.a = nn.Linear(num_hidden, num_actions)
def forward(self, x):
out = F.relu(self.embed(x))
out = F.relu(self.fc1(out))
out = F.relu(self.fc2(out))
critic = self.c(out)
out = F.relu(self.fc3(out.detach()))
actor = F.softmax(self.a(out), dim=-1)
return actor, critic
Would you please tell me what the mistake here is? Thank you in advance.
SOLVED: I forgot to clear the history of probabilities, action-values and rewards after iterations. It is clear why that would cause the issue, as the older elements would cause propagating through old dcgs.

Curve mouse movement

I'm trying to make the mouse cursor move from one point to another. Not in a straight line but in a curve.
Here is an illustrative video. Here is code that moves mouse based on the locations:
Func smoothmove($coords, $j, $firstms);make mouse move to the note
Dim $currcoord[3]
Dim $diff[3]
Dim $pixelsptms[3]
If $j > 1 Then
If Mod($coords[$j - 1][7][1], 2) = 0 Then
$currcoord[1] = $coords[$j - 1][1][1]
$currcoord[2] = $coords[$j - 1][2][1]
Else
$currcoord[1] = $coords[$j - 1][1][$coords[$j - 1][1][0]]
$currcoord[2] = $coords[$j - 1][2][$coords[$j - 1][2][0]]
EndIf
Else
$currcoord[1] = MouseGetPos(0)
$currcoord[2] = MouseGetPos(1)
EndIf
If $coords[$j][1][1] = $currcoord[1] Then
If $coords[$j][2][1] = $currcoord[2] Then Return 1
EndIf
If $coords[$j][3][1] <= $firstms Then Return 1
$diff[1] = $coords[$j][1][1] - $currcoord[1]
$diff[2] = $coords[$j][2][1] - $currcoord[2]
$pixelsptms[1] = ($diff[1] / ($coords[$j][3][1] - $firstms)) * 12
$pixelsptms[2] = ($diff[2] / ($coords[$j][3][1] - $firstms)) * 12
Dim $ready[5]
$ready[1] = 2
$ready[2] = 3
$ready[3] = 2
$ready[4] = 3
$firstms += 12
$count = 0
While 1
DllCall($osumap[0], 'int', 'ReadProcessMemory', 'int', $osumap[1], 'int', $address[2], 'ptr', $bufferptr, 'int', $buffersize, 'int', '')
$ms = DllStructGetData($buffer, 1)
If $ms >= $coords[$j][3][1] Then Return 1
If $pixelsptms[1] < 0 Then
If $currcoord[1] <= $coords[$j][1][1] Then
$currcoord[1] = $coords[$j][1][1]
$ready[3] = 1
$pixelsptms[1] = 0
EndIf
Else
If $currcoord[1] >= $coords[$j][1][1] Then
$currcoord[1] = $coords[$j][1][1]
$ready[3] = 1
$pixelsptms[1] = 0
EndIf
EndIf
If $pixelsptms[2] < 0 Then
If $currcoord[2] <= $coords[$j][2][1] Then
$currcoord[2] = $coords[$j][2][1]
$ready[4] = 1
$pixelsptms[2] = 0
EndIf
Else
If $currcoord[2] >= $coords[$j][2][1] Then
$currcoord[2] = $coords[$j][2][1]
$ready[4] = 1
$pixelsptms[2] = 0
EndIf
EndIf
If $ready[3] = $ready[4] Then Return -1
If $ms >= $firstms Then
$currcoord[1] += $pixelsptms[1]
$currcoord[2] += $pixelsptms[2]
$firstms += 12
MouseMove($currcoord[1], $currcoord[2], 0)
EndIf
WEnd
EndFunc
Maybe this gives you some ideas.
#include <math.au3>
HotKeySet("{ESC}", "esc")
Global Const $PI = 3.1415926535897932384626433832795
Dim $t
Dim $expr
For $theta = 0 To 924 * $PI ;ALSO MAKE THE LOOP GO LONGER
$t = _Radian($theta)
$expr = Exp(Cos($t)) - 2 * Cos(4 * $t) - Sin($t / 12) ^ 5
$x = 400 + 100 * Cos($t) * $expr
$y = 400 + 100 * Sin($t) * $expr
ConsoleWrite($x & "," & $y & #LF) ;Use for debugging with SciTE
MouseMove($x, $y, 1)
Next
Func esc()
Exit 0
EndFunc ;==>esc

Run time error 9 when using arrary in Macro

I have been using the followng Macro and it works fine:
Sub PremTable()
Dim i, m, j As Integer
Dim PDFDiv, PDFClass, PDFSex, PDFPlan, LimAge As Variant
Dim FlagD, FlagC, Band, FlagP, FlagB, IssAge, Dur As Integer
PDFClass = Array("N", "S")
PDFSex = Array("M", "F")
PDFDiv = Array("G", "E")
PDFPlan = Array(10, 20, 30)
LimAge = Array(70, 60, 50)
j = 0
For FlagD = 1 To 2
Range("div").Value = PDFDiv(FlagD)
For FlagP = 1 To 3
Range("plan").Value = PDFPlan(FlagP)
For Band = 1 To 3
Range("band").Value = Band
For FlagS = 1 To 2
Range("sex").Value = PDFSex(FlagS)
For FlagC = 1 To 2
Range("class").Value = PDFClass(FlagC)
m = 18
For i = 1 To Range("LimAge").Value - 17
Range("IssAge").Offset(i + j, 0) = m
Range("age").Value = Range("IssAge").Offset(i + j, 0)
Worksheets("input").Range("J4:J76").Copy
Worksheets("Premium Tables").Range("M1").Offset(i + j, 0).PasteSpecial xlPasteValues, Transpose:=True
Range("DIV2").Offset(i + j, 0) = Range("Div")
Range("PLAN2").Offset(i + j, 0) = Range("plan")
Range("BAND2").Offset(i + j, 0) = Range("band")
Range("SEX2").Offset(i + j, 0) = Range("sex")
Range("CLASS2").Offset(i + j, 0) = Range("class")
m = m + 1
Next i
j = j + i - 1
Next FlagC
Next FlagS
Next Band
Next FlagP
Next FlagD
End Sub
Now I have another very similar spreatsheet that I want to use this macro to creat tables, but it always give me the "run time error 9" for all of the arrays having text format variables (for example: Range("class").Value = PDFClass(FlagC) causing an runtime error 9)
Please advise! Thanks very much!