TypeError: object is not subscriptable - python

I`ve obtain this error
File "/class.py", line 246, in __init__
if d and self.rf == 2 and d["descriptionType"] in ["900000000000003001"] and d["conceptId"] in konZer.zerrenda:
TypeError: 'Desk' object is not subscriptable
I created this object
class Desk:
descriptionId = ""
descriptionStatus = ""
conceptId = ""
term = ""
And I called it in another class
class DescriptionList():
def deskJ(self,line):
er = line.strip().split('\t')
desc = Desk()
if er[1] == "0":
desc.descriptionId = er[0]
desc.descriptionStatus = er[1]
desc.conceptId = er[2]
desc.term = er[3]
return description
Then I called the function "deskJ" at init and I get the error at this part (I've deleted some parts of the function):
def __init__(self,fitx,konZer,lanZer={}):
with codecs.open(fitx,encoding='utf-8') as fitx:
lines = fitx.read().split('\n')[1:-1]
for line in lines:
d = self.deskJ(line)
if d and self.rf == 2 and d["descriptionType"] in ["900000000000003001"] and d["conceptId"] in konZer.zerrenda:
c = konZer.zerrenda[d["conceptId"]]
c["fullySpecifiedName"] = d["term"]
What am I doing wrong?

Using d["descriptionType"] is trying to access d with the key "descriptionType". That doesn't work, though, because d is a Desk object that doesn't have keys. Instead, get the attributes:
if d and self.rf == 2 and d.descriptionType in ["900000000000003001"] and d.conceptId in konZer.zerrenda:

Related

Facing AttributeError: 'int' object has no attribute 'toarray' in topic modelling

I am try to do topic modelling using LSA, with the following code:
and in the next line I have this:
top_n_words_lsa = get_top_n_words(10,
lsa_keys,
small_document_term_matrix,
small_count_vectorizer)
for i in range(len(top_n_words_lsa)):
print("Topic {}: ".format(i+1), top_n_words_lsa[i])
But I am facing this error:
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_15164/599799419.py in <module>
----> 1 top_n_words_lsa = get_top_n_words(10,
2 lsa_keys,
3 small_document_term_matrix,
4 small_count_vectorizer)
5
~\AppData\Local\Temp/ipykernel_15164/2401631730.py in get_top_n_words(n, keys,
document_term_matrix, count_vectorizer)
11 if keys[i] == topic:
12 temp_vector_sum += document_term_matrix[i]
---> 13 temp_vector_sum = temp_vector_sum.toarray()
14 top_n_word_indices = np.flip(np.argsort(temp_vector_sum)[0][-n:],0)
15 top_word_indices.append(top_n_word_indices)
AttributeError: 'int' object has no attribute 'toarray'
The related helper functions are defined below:
# Define helper functions
def get_top_n_words(n, keys, document_term_matrix, count_vectorizer):
'''
returns a list of n_topic strings, where each string contains the n most common
words in a predicted category, in order
'''
top_word_indices = []
for topic in range(n_topics):
temp_vector_sum = 0
for i in range(len(keys)):
if keys[i] == topic:
temp_vector_sum += document_term_matrix[i]
temp_vector_sum = temp_vector_sum.toarray()
top_n_word_indices = np.flip(np.argsort(temp_vector_sum)[0][-n:],0)
top_word_indices.append(top_n_word_indices)
top_words = []
for topic in top_word_indices:
topic_words = []
for index in topic:
temp_word_vector = np.zeros((1,document_term_matrix.shape[1]))
temp_word_vector[:,index] = 1
the_word = count_vectorizer.inverse_transform(temp_word_vector)[0][0]
topic_words.append(the_word.encode('ascii').decode('utf-8'))
top_words.append(" ".join(topic_words))
return top_words
Can you please tell me what I am missing here?
You define temp_vector_sum as 0 and then add to it. So it's an object of type int. That class doesn't define a function toarray. You could do something like: np.array([temp_vector_sum]).

NameError: name 'packet' is not defined - RLBot

I'm trying to write a script to record player movement in Rocket League using the RLBot framework. I've got very minimal experience with code and I've been getting the error:
Traceback (most recent call last):
File "c:/Users/Julian/AppData/Local/RLBotGUIX/RLBotPackDeletable/RLBotPack-master/RLBotPack/CustomMutators/playerRecorder.py", line 27, in <module>
class playerRecorder(BaseScript):
File "c:/Users/Julian/AppData/Local/RLBotGUIX/RLBotPackDeletable/RLBotPack-master/RLBotPack/CustomMutators/playerRecorder.py", line 45, in playerRecorder
for car in packet.game_cars:
NameError: name 'packet' is not defined
Packet is defined within def run(self): but I'm still getting an error for it not being defined. Below is my full script from within VS Code. Any help is appreciated.
from typing import Optional
from rlbot.agents.base_agent import BaseAgent, GameTickPacket, SimpleControllerState
import os
import time
import math
from rlbot.agents.base_agent import BaseAgent, SimpleControllerState
from rlbot.utils.structures.game_data_struct import GameTickPacket
from rlbot.utils.game_state_util import GameState, BallState, CarState, Physics, Vector3 as vector3, Rotator
import random
from rlbot.agents.base_script import BaseScript
from rlbot.utils.game_state_util import GameState
DIRECTORY_LOCATION = "C:\Logs\Recorder\log"
randNum = random.randint(0,9999999999)
# Extending the BaseScript class is purely optional. It's just convenient / abstracts you away from
# some strange classes like GameInterface
class playerRecorder(BaseScript):
def __init__(self):
super().__init__("playerRecorder")
packet = self.get_game_tick_packet()
self.writeFile = open(DIRECTORY_LOCATION+"\\"+"HumanLog"+str(car.team)+"-"+str(randNum), "w")
def run(self):
while True:
packet = self.get_game_tick_packet()
get_output(packet)
sleep(1 / 3)
print("test")
for car in packet.game_cars:
if not car.is_bot:
team = car.team
index = car.index
break
def get_output(self, game_tick_packet):
#***************************************************************
packet = self.get_game_tick_packet()
goodTeam = str(car.team)
goodLoc = packet.game_cars[car.index].physics.location
goodLocX = str(goodLoc.x)
goodLocY = str(goodLoc.y)
goodLocZ = str(goodLoc.z)
goodRot = packet.game_cars[car.index].physics.rotation
goodRotP = str(goodRot.pitch)
goodRotY = str(goodRot.yaw)
goodRotR = str(goodRot.roll)
goodVel = packet.game_cars[car.index].physics.velocity
goodVelX = str(goodVel.x)
goodVelY = str(goodVel.y)
goodVelZ = str(goodVel.z)
goodAngVel = packet.game_cars[car.index].physics.angular_velocity
goodAngVelX = str(goodAngVel.x)
goodAngVelY = str(goodAngVel.y)
goodAngVelZ = str(goodAngVel.z)
hasWC = str(packet.game_cars[car.index].has_wheel_contact)
isSS = str(packet.game_cars[car.index].is_super_sonic)
jumped = str(packet.game_cars[car.index].jumped)
dJumped = str(packet.game_cars[car.index].double_jumped)
bst = str(packet.game_cars[car.index].boost)
ballLoc = packet.game_ball.physics.location
ballLocX = str(ballLoc.x)
ballLocY = str(ballLoc.y)
ballLocZ = str(ballLoc.z)
ballVel = packet.game_ball.physics.velocity
ballVelX = str(ballVel.x)
ballVelY = str(ballVel.y)
ballVelZ = str(ballVel.z)
self.writeFile.write(goodTeam+";"+
goodLocX+","+goodLocY+","+goodLocZ+";"+
goodRotP+","+goodRotY+","+goodRotR+";"+
goodVelX+","+goodVelY+","+goodVelZ+";"+
goodAngVelX+","+goodAngVelY+","+goodAngVelZ+";"+
hasWC+";"+isSS+";"+jumped+";"+dJumped+";"+bst+";"+
ballLocX+","+ballLocY+","+ballLocZ+";"+
ballVelX+","+ballVelY+","+ballVelZ)
self.writeFile.write("\n")
## WRITE OPPONENT
badIndex = -1
for i in range(len(packet.game_cars)):
if i != car.index:
badIndex = i
break
assert badIndex != car.index
assert badIndex != -1
badTeam = str(packet.game_cars[badIndex].team)
badLoc = packet.game_cars[badIndex].physics.location
badLocX = str(badLoc.x)
badLocY = str(badLoc.y)
badLocZ = str(badLoc.z)
badRot = packet.game_cars[badIndex].physics.rotation
badRotP = str(badRot.pitch)
badRotY = str(badRot.yaw)
badRotR = str(badRot.roll)
badVel = packet.game_cars[badIndex].physics.velocity
badVelX = str(badVel.x)
badVelY = str(badVel.y)
badVelZ = str(badVel.z)
badAngVel = packet.game_cars[badIndex].physics.angular_velocity
badAngVelX = str(badAngVel.x)
badAngVelY = str(badAngVel.y)
badAngVelZ = str(badAngVel.z)
badhasWC = str(packet.game_cars[badIndex].has_wheel_contact)
badisSS = str(packet.game_cars[badIndex].is_super_sonic)
badjumped = str(packet.game_cars[badIndex].jumped)
baddJumped = str(packet.game_cars[badIndex].double_jumped)
badbst = str(packet.game_cars[badIndex].boost)
self.writeFile.write(badTeam+";"+
badLocX+","+badLocY+","+badLocZ+";"+
badRotP+","+badRotY+","+badRotR+";"+
badVelX+","+badVelY+","+badVelZ+";"+
badAngVelX+","+badAngVelY+","+badAngVelZ+";"+
badhasWC+";"+badisSS+";"+badjumped+";"+baddJumped+";"+badbst)
self.writeFile.write("\n")
## WRITE ACTION
self.writeFile.write(str(action.throttle)+";"+str(action.steer)+";"+str(action.pitch)+";"+str(action.yaw)+";"+str(action.action.roll)+";"+str(action.jump)+";"+str(action.boost))
self.writeFile.write("\n")
##*****************************************************
return action
In the run(...) function you should type self.get_output(packet) instead of get_output(). You have to pass a packet as a parameter to a function and also you should write self before the name of a function because it's inside a class. I think you also misspelled the parameter of the get_output function because you've named it game_tick_packet and in the function you are using variable named just a packet.

Shows a TypeError: unhashable type: 'list'

This is a K-Knights problem solved with CSP, and the issue seems to be the constraints.
Error coming from here
File "F:/Lectures/AI Lab/Codes/nonattacking/aicodes/csp.py", line 23, in init
self.setUpVariableDomains()
File "F:/Lectures/AI Lab/Codes/nonattacking/aicodes/csp.py", line 28, in setUpVariableDomains
self.addVariableDomain(var, self._domain)
File "F:/Lectures/AI Lab/Codes/nonattacking/aicodes/csp.py", line 35, in addVariableDomain
self._domainOfVariable[var] = copy.deepcopy(domain)
TypeError: unhashable type: 'list'
import variable
import copy
import notEqualConstraint
import simpleInference
import time
import backtrackingSearch
import consoleListener
import nonAttackingConstraint
class CSP():
def __init__(self, variables = [], domains = [], constraints = []):
self._variables = variables
self._domain = domains
self._constraints = constraints
self._domainOfVariable = {}
self._contraintsOfVariable = {}
self.setUpVariableDomains()
self.setUpConstraints()
def setUpVariableDomains(self):
for var in self._variables:
self.addVariableDomain(var, self._domain)
def setUpConstraints(self):
for constraint in self._constraints:
self.addConstraint(constraint)
def addVariableDomain(self,var,domain):
self._domainOfVariable[var] = copy.deepcopy(domain)
def addConstraint(self,constraint):
for var in constraint.getScope():
if var not in self._contraintsOfVariable:
self._contraintsOfVariable[var] = []
self._contraintsOfVariable[var].append(constraint)
def addSingleConstraint(self,constraint):
self._constraints.append(constraint)
for var in constraint.getScope():
if var not in self._contraintsOfVariable:
self._contraintsOfVariable[var] = []
self._contraintsOfVariable[var].append(constraint)
def addVariable(self,variable):
self._variables.append(variable)
self.addVariableDomain(variable,self._domain)
def getVariables(self):
return self._variables
def getDomainValues(self,var):
return self._domainOfVariable[var]
def getConstraints(self,var):
if var not in self._contraintsOfVariable:
return []
return self._contraintsOfVariable[var]
def getVariableDomains(self):
return self._domainOfVariable
def setVariableDomains(self,domainOfVariable):
self._domainOfVariable = domainOfVariable
def copy(self):
variables = copy.deepcopy(self._variables)
domains = copy.deepcopy(self._variables)
constraints = copy.deepcopy(self._variables)
csp = CSP(variables, domains, constraints)
return csp
def getNeighbour(self,variable,constraint):
neigh = []
for va in constraint.getScope():
if va != variable and (va not in neigh):
neigh.append(va)
return neigh
def removeValueFromDomain(self,variable,value):
values = []
for val in self.getDomainValues(variable):
if val != value:
values.append(val)
self._domainOfVariable[variable] = values
if __name__ == '__main__':
domains = ["K","A"]
variables = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
X=[[2,1],[2,-1],[-2,1],[-2,-1],[1,2],[1,-2],[-1,2],[-1,-2]]
constraints = [
nonAttackingConstraint.NotAttackingConstraint(X)
]
Csp = CSP(variables,domains,constraints)
inPro = simpleInference.SimpleInference()
bts = backtrackingSearch.BactrackingSearch(inPro,[consoleListener.ConsoleListener()],variableOrdering = True)
start = time.time()
result = bts.solve(Csp)
end = time.time()
print("%.2f ‐ %.2f" % (start,end))
Specifically stops at addVariableDomain in the CSP Class above, and gives me the unhashable type: 'list' error due to my constraint being a list. Is the issue identifiable? Is there a solution?
Lists can not be used as dictionary keys as they are mutable and hence not suitable for hashing. Try converting the list to tuple.
def addVariableDomain(self,var,domain):
self._domainOfVariable[tuple(var)] = copy.deepcopy(domain)
You may have to do the same wherever var is used as a dictionary key.

Gettig error: object of type...has no len()

I'm trying to get PMI count from work part file which is opened in NX software in Python, but getting error:
TypeError: object of type 'NXOpen.Annotations.PmiCollection' has no len()
Code:
lw = theSession.ListingWindow
lw.Open()
theSession = NXOpen.Session.GetSession()
theParts = theSession.Parts
theWorkPart = theParts.Work
allPMIObjects = theWorkPart.PmiManager.Pmis
count1 = len(allPMIObjects)
lw.WriteLine(count1)
lw.Close()
Documentation link: https://docs.plm.automation.siemens.com/data_services/resources/nx/11/nx_api/custom/en_US/nxopen_python_ref/NXOpen.Annotations.PmiCollection.html
Equivalent vb code: http://nxjournaling.com/content/find-out-if-part-has-any-pmi
Below is the code that gives count of PMIs from active part and assert if count is changed (here 3):
lw = theSession.ListingWindow
lw.Open()
# Custom code starts to get PMI count in part and check
theSession = NXOpen.Session.GetSession()
theParts = theSession.Parts
theWorkPart = theParts.Work
allPMIObjects = theWorkPart.PmiManager.Pmis
i = 0
for p in allPMIObjects:
i = i + 1
lw.WriteLine(str(i))
lw.Close()
#if PMI count is changed from 3, raise AssertionError:
assert i == 3

Error 'numpy.int32' object does not support item assignment

I get this error
Traceback (most recent call last):
File "C:\Users\User1\Desktop\cellh5_scripts\ewa_pnas_fate.py", line 90, in <module>
ec.combine_classifiers("Event labels combined")
File "C:\Users\User1\Desktop\cellh5_scripts\ewa_pnas_fate.py", line 53, in combine_classifiers
pnas_class[pnas_class==3] = 1
TypeError: 'numpy.int32' object does not support item assignment
by runing the code
def combine_classifiers(self, output_name):
all_combined_classes = []
for _, (plate_name, w, p, t1, t2, track_ids, track_labels) in self.mapping[['Plate',
'Well',
'Site',
'Gene Symbol',
'siRNA ID',
'Event track ids',
'Event track labels']].iterrows():
combined_classes = []
ch5_file_handle = self.cellh5_handles[plate_name]
ch5_pos = ch5_file_handle.get_position(w, str(p))
for track_id, track_label in zip(track_ids, track_labels):
h2b_class = track_label.copy()
print(track_id)
pnas_class = ch5_pos.get_class_prediction('secondary__expanded')[track_id]['label_idx'] + 1
print(pnas_class)
inter_idx = h2b_class == 1
pnas_class[pnas_class==3] = 1
pnas_class[pnas_class==2]+=2
combined_class = h2b_class
combined_class[inter_idx] = pnas_class[inter_idx]
combined_classes.append(combined_class)
all_combined_classes.append(combined_classes)
self.mapping[output_name] = pandas.Series(all_combined_classes)
I print pnas_class which is 1, and track_id which is 50708. I'm wondering what the designer of code want to do in the part:
inter_idx = h2b_class == 1
pnas_class[pnas_class==3] = 1
pnas_class[pnas_class==2]+=2
combined_class = h2b_class
combined_class[inter_idx] = pnas_class[inter_idx]
How can I change that to have the same meaning?
pnas_class is a an integer so you can't select item from an integer by [pnas_class==3] = 1.
Maybe you are trying to affect 1 to pnas_class if it's equal to 3. In this case try this:
pnas_class= 1*(pnas_class == 3) + pnas_class*(pnas_class != 3 )
Ok I found the mistake. You arer right the pnas_class should not be an integer and I know why is it integer instead of array.

Categories