Third question for the day. But this one is a brand new program. So now I'm receiving this error (and before you say my code is riddled with errors, I'm expecting that.):
Traceback (most recent call last):
File "C:/Users/DDeahr/Downloads/College_Student.py", line 58, in <module>
main()
File "C:/Users/DDeahr/Downloads/College_Student.py", line 46, in main
Alex.complete_class("English 101", 10)
File "C:/Users/DDeahr/Downloads/College_Student.py", line 30, in complete_class
College_Student.complete_class.course_code += self.courses_done
AttributeError: 'function' object has no attribute 'course_code'
New error:
Traceback (most recent call last):
File "C:/Users/DDeahr/Downloads/College_Student.py", line 1, in <module>
class College_Student(object):
File "C:/Users/DDeahr/Downloads/College_Student.py", line 30, in College_Student
course_code = staticmethod(course_code)
NameError: name 'course_code' is not defined
Here's my code:
class College_Student(object):
total = 0
enrolled = []
def __init__(self, first_name, last_name, id_num, courses_done, credit_hrs):
self = self
self.first_name = first_name
self.last_name = last_name
self.id_num = id_num
self.courses_done = [],
self.credit_hrs = credit_hrs
def __str__(self):
first_name = self.first_name
last_name = self.last_name
id_num = self.id_num
courses_done = self.courses_done
credit_hrs = self.credit_hrs
College_Student.total += 1
College_Student.enrolled += self.last_name
College_Student.enrolled.sort()
return "First Name: %s\nLast Name: %s\nID Number: %s\nCourses Finished: %s\nCredit Hours: %s\n" % (self.first_name, self.last_name, self.id_num, self.courses_done, self.credit_hrs)
def complete_class(self,course_code,student_credit_hrs):
self.credit_hrs += student_credit_hrs
self.courses_done = []
College_Student.complete_class.course_code += self.courses_done
return "Student with ID number: %s has finished course %s which is %s credit hours." % (self.id_num, self.course_code, self.student_credit_hours)
def can_grad(self):
if self.credit_hrs >= 120:
return "Student with ID number: %s can now graduate." % (self.id_num)
else:
return "Student with ID number: %s cannot graduate yet." % (self.id_num)
def main():
print "Creating student John"
John = College_Student("John", "Appleseed", 111111, None, 20)
print John
print "Creating student Alex"
Alex = College_Student("Alex", "Trannon", 222222, None, 30)
print Alex
Alex.complete_class("English 101", 10)
Alex.complete_class("Mathmatics 102", 20)
Alex.complete_class("Computer Sciences 208", 60)
John.complete_class("Psychology 5005", 40)
John.complete_class("English 108.365", 2)
John.complete_class("Chinese 101", 10)
John.complete_class("Computer Sciences 30", 28)
Alex.can_grad()
John.can_grad()
print total
print enrolled
main()
Any and all help is much appreciated! Thank You!
If I understand what you are trying to do - change :
College_Student.complete_class.course_code += self.courses_done
to
self.courses.done.append(course_code) -
note:
self.courses.done += self.course_code
also works but as pointed out by #jonsharpe is less explicit.
Also :
in complete_class - don't set self.courses_done to [] - do that in init - where it is is at the moment it will reset the students courses list each time they complete a course
It is bad form to change the instance variables in the str method - that method should simply be used to provide a text representation of that student - as you have it coded it it seems to make changes, for no obvious reason.
Related
I get this error when I run the script and I cannot see the solution. This program is supposed to draw a giveaway from a sqlite3 file which has the number of raffle tickets for a user. And recently the program the gives that creates the sqlite3 file updated some stuff (The script is made by me) and I can figure out the solution.
Traceback (most recent call last):
File "C:\Users\Admin\Desktop\Draw\Test\dave-draw.py", line 244, in <module>
dd = DaveDraw()
File "C:\Users\Admin\Desktop\Draw\Test\dave-draw.py", line 64, in __init__
self.get_viewers()
File "C:\Users\Admin\Desktop\Draw\Test\dave-draw.py", line 215, in
get_viewers
''').fetchall()
sqlite3.OperationalError: no such column: viewer_id
there's the code
#!/usr/bin/env python3
import pdb
import random
import sqlite3
class Viewer(object):
def __init__(self,
viewer_id,
twitch_name,
beam_name,
beam_id,
viewer_type,
rank,
points,
points2,
hours,
raids,
gains_currency,
gains_hours,
in_giveaways,
last_seen,
sub,
entrance_message,
entrance_message_type,
entrance_sfx
):
self.viewer_id = viewer_id
self.twitch_name = twitch_name
self.beam_name = beam_name
self.beam_id = beam_id
self.viewer_type = viewer_type
self.rank = rank
self.points = points
self.points2 = points2
self.hours = hours
self.raids = raids
self.gains_currency = gains_currency
self.gains_hours = gains_hours
self.in_giveaways = in_giveaways
self.last_seen = last_seen
self.sub = sub
self.entrance_message = entrance_message
self.entrance_message_type = entrance_message_type
self.entrance_sfx = entrance_sfx
def win_chance(self, total_tickets):
"""
Takes the total tickets (points) as a paramter and works
out the percentage chance that the viewer has of winning.
Returns the viewers win chance in percent.
"""
percent = total_tickets / 100.00
return self.points2 / percent
class DaveDraw(object):
def __init__(self):
self.debug = False
self.database_path = 'Viewers3DB.sqlite'
self.db_conn = sqlite3.connect(self.database_path)
self.get_viewers()
self.calculate_total_points()
self.assign_tickets()
def assign_tickets(self):
"""
Assigns each user a number range based on the number of
tickets they have.
e.g.
10 1-10
10 11-20
30 21-50
1 51
"""
self.tickets = {}
latest_ticket = 0
for viewer in self.viewers:
# skip anyone with no points
if viewer.points2 == 0:
continue
ticket_range_beg = latest_ticket + 1
ticket_range_end = latest_ticket + 1 + viewer.points2
latest_ticket = ticket_range_end
viewer.tickets = range(ticket_range_beg, ticket_range_end)
# assign a range of tickets:
if self.debug:
print("Assigning viewer twitch: %s beam: %s tickets %i-%i" % (viewer.twitch_name, viewer.beam_name, viewer.tickets.start, viewer.tickets.stop))
if ticket_range_beg == ticket_range_end:
if self.debug:
print("Assigning ticket {} to {}".format(ticket_range_beg, viewer.twitch_name))
self.tickets[ticket_range_beg] = viewer
next
for ticket in viewer.tickets:
if self.debug:
print("Assigning ticket {} to {}".format(ticket, viewer.twitch_name))
self.tickets[ticket] = viewer
def calculate_total_points(self):
"""
Gets the total amount of points awarded to all
viewers.
"""
self.total_points = 0
for viewer in self.viewers:
self.total_points += viewer.points2
self.total_points_percent = self.total_points / 100
print("Total points awarded (total tickets): %s" % self.total_points)
def draw(self):
"""
Picks a random number between 1 and total tickets, finds
the user that has been assigned tickets within that range and
returns the user.
"""
ticket = random.randint(1, self.total_points)
try:
winner = self.tickets[ticket]
except:
pdb.set_trace()
print("\n===== WINNER Twitch: {} / Beam: {} =====\n".format(winner.twitch_name, winner.beam_id))
print("Picked ticket {}\n".format(ticket))
print("Winner win chance: {:f}".format(winner.win_chance(self.total_points)))
print("Winner's ticket range: {}-{}".format(winner.tickets.start, winner.tickets.stop))
print("Winner's ticket amount: {}\n".format(winner.points2))
self.display_viewer(winner)
def display_random_viewer(self):
"""
Displays random viewer.
"""
self.display_viewer(self.get_random_viewer())
def display_viewer(self, viewer):
"""
Outputs the data on all viewers.
"""
print("""Viewer ID: %s\nTwitch Name: %s\nBeam Name: %s\nBeam ID: %s\nRank: %s\nPoints: %s\nPoints2: %s\nHours: %s\nRaids: %s\nGains Currency: %s\nGains Hours: %s\nInGiveaways: %s\nLastSeen: %s\nEntrance Message: %s\nEntranceMsgType: %s\nEntranceSFX: %s"""
% (
viewer.viewer_id,
viewer.twitch_name,
viewer.beam_name,
viewer.beam_id,
viewer.rank,
viewer.points,
viewer.points2,
viewer.hours,
viewer.raids,
viewer.gains_currency,
viewer.gains_hours,
viewer.in_giveaways,
viewer.last_seen,
viewer.entrance_message,
viewer.entrance_message_type,
viewer.entrance_sfx
)
)
def get_random_viewer(self):
"""
Gets a completely random viewer.
"""
return random.choice(self.viewers)
def get_viewers(self):
"""
Gets data on all the viewers in the database and stores
the data in self.viewers.
"""
c = self.db_conn.cursor()
viewers = c.execute('''
SELECT
viewer_id,
TwitchName,
BeamName,
BeamID,
Type,
Rank,
Points,
Points2,
Hours,
Raids,
GainsCurrency,
GainsHours,
InGiveaways,
LastSeen,
Sub,
EntranceMessage,
EntranceMsgType,
EntranceSFX
FROM Viewer
WHERE Type != 1
AND TwitchName NOT IN (
\'treeboydave\',
\'treebotdave\'
);
''').fetchall()
self.viewers = []
for cur_viewer in viewers:
self.viewers.append(
Viewer(
cur_viewer[0],
cur_viewer[1],
cur_viewer[2],
cur_viewer[3],
cur_viewer[4],
cur_viewer[5],
cur_viewer[6],
cur_viewer[7],
cur_viewer[8],
cur_viewer[9],
cur_viewer[10],
cur_viewer[11],
cur_viewer[12],
cur_viewer[13],
cur_viewer[14],
cur_viewer[15],
cur_viewer[16],
cur_viewer[17]
)
)
if __name__ == '__main__':
dd = DaveDraw()
dd.draw()
All your other SQL columns are capitalised, any chance that's why it's not finding the viewer_id column? Maybe it's Viewer_Id or similar?
If you sql execute 'HELP TABLE Viewer' and print what it returns, it will give you an outline of all of the columns in that database table, so you can make sure you have the capitalisation correct, or whether the column actually isn't there at all.
I am trying my darnest to pull a variable from a text file to do some math in an trading bot algorithim.
This is my code. I have shortened it to get to the issue:
from botlog import BotLog
from botindicators import BotIndicators
from bottrade import BotTrade
class BotStrategy(object):
def __init__(self):
self.output = BotLog()
self.prices = []
self.closes = [] # Needed for Momentum Indicator
self.trades = [] #20 trades at 0.021 = .042
self.currentPrice = "" #after a day, add the BTC to 0.042 and adjust simultaneous trades
self.currentClose = "" #53 coins for 2500 simul trades per coin pair
self.numSimulTrades = 100 #looks like dash ends at 2500 trades eth ends at about 1000 trades total for all four would be about 208 coins
self.indicators = BotIndicators()
mid=0
with open('test.txt', 'r') as myfile:
mid=myfile.read().replace('\n', '')
self.output.log(mid)
mid=int(mid)
def tick(self,candlestick):
self.currentPrice = float(candlestick.priceAverage)
self.prices.append(self.currentPrice)
#self.currentClose = float(candlestick['close'])
#self.closes.append(self.currentClose)
self.output.log("Price: "+str(candlestick.priceAverage)+"\tMoving Average: "+str(self.indicators.movingAverage(self.prices,5)))
self.evaluatePositions()
self.updateOpenTrades()
self.showPositions()
def evaluatePositions(self):
openTrades = []
for trade in self.trades:
if (trade.status == "OPEN"):
openTrades.append(trade)
if (len(openTrades) < self.numSimulTrades):
if ((self.currentPrice) < self.indicators.movingAverage(self.prices,15)):
self.trades.append(BotTrade(self.currentPrice,stopLoss=.0001))
for trade in openTrades:
if ((self.currentPrice + mid) > self.indicators.movingAverage(self.prices,15)) :
trade.close(self.currentPrice)
def updateOpenTrades(self):
for trade in self.trades:
if (trade.status == "OPEN"):
trade.tick(self.currentPrice)
def showPositions(self):
for trade in self.trades:
trade.showTrade()
With "self.mid" I get the error: 'Bot1' object has no attribute 'mid'
a if I remove the "self" I get: NameError: global name 'mid' is not defined
What am I doing wrong? I'm losing my mind!
Traceback was requested: This is the No Attribute:
user#user1:~/Desktop/bot/part3$ python backtest.py
90
Price: 0.0486309 Moving Average: None
Price: 0.04853957 Moving Average: 0.048585235
Trade opened
Entry Price: 0.04853957 Status: OPEN Exit Price:
Price: 0.04847643 Moving Average: 0.0485489666667
Trade opened
Traceback (most recent call last):
File "backtest.py", line 15, in <module>
main(sys.argv[1:])
File "backtest.py", line 12, in main
strategy.tick(candlestick)
File "/home/user/Desktop/bot/part3/botstrategy.py", line 30, in tick
self.evaluatePositions()
File "/home/user/Desktop/bot/part3/botstrategy.py", line 46, in evaluatePositions
self.currentPrice= float(self.currentPrice+self.mid)
AttributeError: 'BotStrategy' object has no attribute 'mid'
And this is "mid" not defined:
user#user1:~/Desktop/bot/part3$ python backtest.py
90
Price: 0.0486309 Moving Average: None
Price: 0.04853957 Moving Average: 0.048585235
Trade opened
Entry Price: 0.04853957 Status: OPEN Exit Price:
Price: 0.04847643 Moving Average: 0.0485489666667
Trade opened
Traceback (most recent call last):
File "backtest.py", line 15, in <module>
main(sys.argv[1:])
File "backtest.py", line 12, in main
strategy.tick(candlestick)
File "/home/user/Desktop/bot/part3/botstrategy.py", line 30, in tick
self.evaluatePositions()
File "/home/user/Desktop/bot/part3/botstrategy.py", line 46, in evaluatePositions
if ((self.currentPrice + mid) > self.indicators.movingAverage(self.prices,15)) :
NameError: global name 'mid' is not defined
bottrade.py code:
from botlog import BotLog
import botstrategy
def main(argv):
currentMovingAverage = 0;
tradePlaced = False
typeOfTrade = False
dataDate = ""
orderNumber = ""
dataPoints = []
localMax = []
currentResistance = 0.018
mid = int(mid)
class BotTrade(object):
def __init__(self,currentPrice,stopLoss=0):
self.output = BotLog()
prices = []
self.status = "OPEN"
self.entryPrice = currentPrice
self.exitPrice = ""
self.output.log("Trade opened")
if (stopLoss):
self.stopLoss = currentPrice - stopLoss
def close(self,currentPrice):
self.mid = int(mid)
if currentPrice > (self.entryPrice + self.mid): #DASH likes about 0.000937, XRP about 0.000001, ETH likes 0.000855 XMR likes 0.000396
#use ETH to start with, with less than 4 trades. you get about 1.7 BTC in a week - 4 trades # 0.021=0.084 BTC. Daily is 0.24
self.status = "CLOSED"
self.exitPrice = currentPrice
self.output.log("Trade closed")
def tick(self, currentPrice):
if (self.stopLoss):
if (currentPrice < self.stopLoss):
self.close(currentPrice)
def showTrade(self):
tradeStatus = "Entry Price: "+str(self.entryPrice)+" Status: "+str(self.status)+" Exit Price: "+str(self.exitPrice)
if (self.status == "CLOSED"):
tradeStatus = tradeStatus + " Profit:! "
if (self.exitPrice > self.entryPrice):
tradeStatus = tradeStatus + " \033[92m"
else:
tradeStatus = tradeStatus + " \033[91m"
tradeStatus = tradeStatus+str(abs((self.exitPrice) - (self.entryPrice)))+" \033[0m"
self.output.log(tradeStatus)
Traceback from bottrade.py
user#user1:~/Desktop/bot/part3$ python backtest.py
Price: 1131.71486314 Moving Average: None
Price: 1103.73203402 Moving Average: 1117.72344858
Trade opened
Entry Price: 1103.73203402 Status: OPEN Exit Price:
Price: 1108.36463027 Moving Average: 1114.60384248
Trade opened
Traceback (most recent call last):
File "backtest.py", line 15, in <module>
main(sys.argv[1:])
File "backtest.py", line 12, in main
strategy.tick(candlestick)
File "/home/user/Desktop/bot/part3/botstrategy.py", line 29, in tick
self.evaluatePositions()
File "/home/user/Desktop/bot/part3/botstrategy.py", line 46, in evaluatePositions
trade.close(self.currentPrice)
File "/home/user/Desktop/bot/part3/bottrade.py", line 30, in close
self.mid = int(mid)
NameError: global name 'mid' is not defined
Full display now. Any help would be appreciated.
The run-time system is correct. In the mid case, there is no variable mid defined in evaluatePositions. Similarly, there is no object attribute mid for instances of BotStrategy. Look at the difference in your initialization:
class BotStrategy(object):
def __init__(self):
self.output = BotLog()
self.prices = []
self.closes = [] # Needed for Momentum Indicator
...
mid=int(mid)
mid is a local variable of init, not an attribute. Perhaps you need
self.mid = int(mid)
and the use self.mid when you reference that value.
Does that work for you?
The assertEqual tests are from a module that just calls a function, runs some data through it, computes the result of that processed data, and compares it to my predicted answer. For example, my predicted answer for total_test was 6.0.
When I run my code (below being the troubled part), I get this error:
Traceback (most recent call last):
File "C:/Users/anon/Desktop/test.py", line 72, in <module>
TransactionTest().run()
File "C:/Users/anon/Desktop/test.py", line 68, in run
self.total_test()
File "C:/Users/anon/Desktop/test.py", line 60, in total_test
assertEqual(self.__t1.total(), 6.0)
File "C:/Users/anon/Desktop/test.py", line 18, in total
return sum(map(lambda p: p.cost(), self.__purchases))
File "C:/Users/anon/Desktop/test.py", line 18, in <lambda>
return sum(map(lambda p: p.cost(), self.__purchases))
AttributeError: 'float' object has no attribute 'cost'
All the line numbers should be shifted down a few lines to account for me copy and pasting it here very slightly modified.
Essentially, my total_test function is causing a crash when it's called. Not sure why I'm getting an attribute error.
class Transaction:
def __init__(self, purchases, tax_rate):
self.__purchases = purchases
self.__tax_rate = tax_rate
def total(self):
return sum(map(lambda p: p.cost(), self.__purchases))
def tax_rate(self):
return self.__tax_rate
def total_taxable(self):
taxable_items = filter(lambda p: p.item().taxable(),self.__purchases)
return sum(map(lambda p: p.cost(), taxable_items))
def grand_total(self):
return self.total() + self.__tax_rate * self.total_taxable()
def __str__(self):
return "Total: " + self.__total + ";" + "Total_tax: " + self.__total_taxable * self.__tax_rate + ";" + "Grand Total: " + self.__grand_total
def print_receipt(self):
f = open("receipt.txt", "w")
f.write("\n".join(map(lambda p:str(p),self.__purchases)))
f.write("\n")
f.write("Total: $%.2f" % self.total())
f.write("\n")
f.write("Tax ( $%.2f # %.2f %%): $%.2f" %(self.total_taxable(), self.__tax_rate * 100, self.__tax_rate * self.total_taxable()))
f.write("\n")
f.write("Grand Total: $%.2f" % self.grand_total())
f.close()
#problem 9-----------------------------------------------------------------------------------
class TransactionTest:
print('----------------------------')
def __init__(self):
t_list = [1.0,2.0,3.0]
self.__t1 = Transaction(t_list, 0.05)
#self.__d2 = Transaction(3.0, 0.06)
def total_test(self):
print('total_test-----------------------------------------')
assertEqual(self.__t1.total(), 6.0)
def tax_rate_test(self):
print('tax_rate_test--------------------------------------')
assertEqual(self.__t1.tax_rate(), 0.05)
#assertEqual(self.__d2.tax_rate() = Transaction(0.06))
def run(self):
self.total_test()
#self.tax_rate_test()
#self.str_test()
TransactionTest().run()
Your test code passes a list of three float instances, [1.0,2.0,3.0], as the purchases argument to Transaction's initializer. However, the other Transaction methods try to call various methods (e.g. cost() and item()) on the values from that list, and since float instances don't have the methods an exception is raised.
I suspect your Transaction code is intended to be run on a list of some other kind of object, where the appropriate methods are defined. You need to rewrite your tests to use the right kind of objects.
I'm a beginner in python. I'm currently try to deal with use the IK to move the robot arm. When I try to run my program the arm was able to move to the my setted starting position but when it's going to next step it shows me this error:AttributeError: 'bool' object has no attribute 'items'
This is my program:
class Pick_Place (object):
#def __init__(self,limb,hover_distance = 0.15):
def __init__(self,limb):
self._limb = baxter_interface.Limb(limb)
self._gripper = baxter_interface.Gripper(limb)
self._gripper.calibrate(limb)
#self.gripper_open()
#self._verbose = verbose
ns = "ExternalTools/" + limb + "/PositionKinematicsNode/IKService"
self._iksvc = rospy.ServiceProxy(ns,SolvePositionIK)
rospy.wait_for_service(ns, 5.0)
def move_to_start (self,start_angles = None):
print ("moving.....")
if not start_angles:
print ("it is 0")
start_angles = dict(zip(self._joint_names, [0]*7))
self._guarded_move_to_joint_position(start_angles)
self.gripper_open()
rospy.sleep(1.0)
print ("moved!!!")
#########################IK_Server################################################
def ik_request (self,pose):
hdr = Header(stamp=rospy.Time.now(),frame_id='base')
ikreq = SolvePositionIKRequest()
ikreq.pose_stamp.append(PoseStamped(header=hdr, pose=pose))
try:
resp = self._iksvc (ikreq)
except (rospy.ServiceException, rospy.ROSException), e:
rospy.logerr("Service call failed: %s" % (e,))
return False
limb_joints = {}
limb_joints = dict(zip(resp.joints[0].name, resp.joints[0].position))
return limb_joints
###################################################################################
def _guarded_move_to_joint_position(self,joint_angles):
print ("joint position.....")
self._limb.move_to_joint_positions(joint_angles)
def gripper_open (self):
self._gripper.open()
rospy.sleep(1.0)
def gripper_close (self):
self._gripper.close()
rospy.sleep(1.0)
#################################Individual_Motion####################################
def _approach (self, pose):
print ("\nApproaching.....")
approach = copy.deepcopy(pose)
approach.position.z = approach.position.z #+ self._hover_distance
joint_angles = self.ik_request(approach)
self._guarded_move_to_joint_position(joint_angles)
print ("\nApproached.....")
def _retract (self):
print ("\nRetracting.....")
current_pose = self._limb.endpoint_pose()
ik_pose = Pose()
ik_pose.position.x = current_pose['position'].x
ik_pose.position.y = current_pose['position'].y
ik_pose.position.z = current_pose['position'].z #+ self._hover_distance
ik_pose.orientation.x = current_pose['orientation'].x
ik_pose.orientation.y = current_pose['orientation'].y
ik_pose.orientation.z = current_pose['orientation'].z
ik_pose.orientation.w = current_pose['orientation'].w
joint_angles = self.ik_request(ik_pose)
self._guarded_move_to_joint_position(joint_angles)
print ("\nRetracted......")
def _servo_to_pose (self, pose):
print ("\nPosing.....")
joint_angles = self.ik_request(pose)
self._guarded_move_to_joint_position(joint_angles)
print ("\nPosed.....")
##########################Motion_of_pick_and_place#####################################
def pick (self,pose):
print ("\nPicking_1.....")
# open the gripper
self.gripper_open()
# servo above pose
self._approach(pose)
# servo to pose
self._servo_to_pose(pose)
# close gripper
self.gripper_close()
# retract to clear object
self._retract()
print ("\nPicked")
def place (self,pose):
print ("\nPlacing_1.....")
# servo above pose
self._approach(pose)
# servo to pose
self._servo_to_pose(pose)
# open the gripper
self.gripper_open()
# retract to clear object
self._retract()
print ("\nPlaced")
###########################Main_Program############################################
def main():
print ("Initializing....")
rospy.init_node("ylj_ik_traTest")
print("Getting the robot state.....")
rs= baxter_interface.RobotEnable()
print ("Enabling....")
rs.enable()
limb = 'left'
#hover_distance = 0.15
starting_joint_angles = {'left_s0': -0.50,
'left_s1': -1.30,
'left_e0': -0.60,
'left_e1': 1.30,
'left_w0': 0.20,
'left_w1': 1.60,
'left_w2': -0.30}
#pnp = Pick_Place(limb,hover_distance)
pnp = Pick_Place(limb)
overhead_orientation = Quaternion(
x=-0.0249590815779,
y=0.999649402929,
z=0.00737916180073,
w=0.00486450832011)
ball_poses = list()
#1st ball point
ball_poses.append(Pose(
position = Point(x=0.7, y=0.15, z=-0.1),
orientation = overhead_orientation))
#2nd ball point
ball_poses.append(Pose(
position = Point(x=0.75, y=0.0, z=-0.1),
orientation = overhead_orientation))
pnp.move_to_start(starting_joint_angles)
idx = 0
while not rospy.is_shutdown():
print ("\nPicking.....")
pnp.pick(ball_poses[idx])
print ("\nPlacing.....")
idx = (idx+1) % len(ball_poses)#?????
pnp.place(ball_poses[idx])
return 0
if __name__ == '__main__':
sys.exit(main())
And this is the error shows me:
Initializing....
Getting the robot state.....
Enabling....
[INFO] [WallTime: 1466477391.621678] Robot Enabled
moving.....
joint position.....
moved!!!
Picking.....
Picking_1.....
Approaching.....
joint position.....
Traceback (most recent call last):
File "/home/baxter/ros_ws/src/baxter_examples/scripts/ylj_research/ylj_ik_traTest.py", line 197, in <module>
sys.exit(main())
File "/home/baxter/ros_ws/src/baxter_examples/scripts/ylj_research/ylj_ik_traTest.py", line 188, in main
pnp.pick(ball_poses[idx])
File "/home/baxter/ros_ws/src/baxter_examples/scripts/ylj_research/ylj_ik_traTest.py", line 122, in pick
self._approach(pose)
File "/home/baxter/ros_ws/src/baxter_examples/scripts/ylj_research/ylj_ik_traTest.py", line 88, in _approach
self._guarded_move_to_joint_position(joint_angles)
File "/home/baxter/ros_ws/src/baxter_examples/scripts/ylj_research/ylj_ik_traTest.py", line 72, in _guarded_move_to_joint_position
self._limb.move_to_joint_positions(joint_angles)
File "/home/baxter/ros_ws/src/baxter_interface/src/baxter_interface/limb.py", line 368, in move_to_joint_positions
diffs = [genf(j, a) for j, a in positions.items() if
AttributeError: 'bool' object has no attribute 'items'
Does anyone had met this kind of error before? Please help me, thank you.
The error tells you that booleans (either True or False) don't have an attribute "items".
When you call
self._limb.move_to_joint_positions(joint_angles) you are passing the argument "joint_angles" which becomes "positions" in the function
move_to_joint_positions().
Looking into the source code of the library you're using, it tells you what it wants positions to be:
#type positions: dict({str:float})
In short, it wants joint_angles to be a dictionary mapping strings to floats and you passed a boolean. Let's look into how you got joint_angles:
joint_angles = self.ik_request(ik_pose)
In the body of your method, you return False every time:
def ik_request (self,pose):
...
except (rospy.ServiceException, rospy.ROSException), e:
rospy.logerr("Service call failed: %s" % (e,))
return False
Returning a boolean is clearly not what you want to do, and it is the cause of this error.
You're trying to access the elements of a boolean value, which is not allowed. In your example, positions is a true/false value and not what you're expecting it to be. There's some section of the code where positions is being assigned to a boolean. You should walk through your code and look for any line that contains positions = something.
I am working on a module for vim. Currently I have the following code:
alphabet_rule = Sequence([Repetition(RuleRef(name="x", rule=MappingRule(name="t", mapping=ALPHABET)), min=1, max=20)])
numbers_rule = Sequence([Repetition(RuleRef(name="y", rule=MappingRule(name="u", mapping=DIGITS)), min=1, max=20)])
symbols_rule = Sequence([Repetition(RuleRef(name="z", rule=MappingRule(name="v", mapping=SYMBOLS)), min=1, max=20)])
alphanumeric = [alphabet_rule, numbers_rule, symbols_rule]
class FindRule(CompoundRule):
spec = ("(bind | find | tank | bank) <alphanumeric> [<n>]")
extras = [IntegerRef("n", 1, 10), Alternative(alphanumeric, name="alphanumeric")]
defaults = {"n": 1}
def value(self, node, extras):
words = node.words()
rule = words[0]
times = extras["n"]
print words
print "Times: %d" % times
find = Events('key->key=%d;key->key=f' % times)
bind = Events('key->key=%d;key->key=f&modifier=shift' % times)
bank = Events('key->key=%d;key->key=t&modifier=shift' % times)
tank = Events('key->key=%d;key->key=t' % times)
search = extras["alphanumeric"][0][0]
if rule == 'bind':
return (bind + search)
elif rule == 'find':
return (find + search)
elif rule == 'bank':
return (bank + search)
elif rule == 'tank':
return (tank + search)
def _process_recognition(self, node, extras):
self.value(node, extras).execute()
find_rule = RuleRef(name="find_rule", rule=FindRule(name="i"))
class ClipRule(CompoundRule):
spec = ("(clip | dip) <find_rule>")
extras = [find_rule]
def _process_recognition(self, node, extras):
words = node.words()
if words[0] == 'clip':
action = Events('key->key=c')
elif words[0] == 'dip':
action = Events('key->key=d')
(action + extras["find_rule"]).execute()
The code is here to give an idea of what I am trying to do, since it's not runnable w/out all the bells and whistles of dragonfly and some of the ALPHABETS, DIGITS, and SYMBOLS that I've defined.
I can use the FindRule just as I expect, but when I attempt to use the ClipRule, I get the following error:
Traceback (most recent call last):
File "C:\Python27\lib\site-packages\dragonfly\engines\engine_natlink.py", line 248, in results_callback
r.process_recognition(root)
File "C:\Python27\lib\site-packages\dragonfly\grammar\rule_compound.py", line 143, in process_recognition
self._process_recognition(node, extras)
File "C:\NatLink\NatLink\MacroSystem\_vim.py", line 232, in _process_recognition
(action + extras["find_rule"]).execute()
File "C:\Python27\lib\site-packages\dragonfly\actions\action_base.py", line 84, in __add__
copy.append(other)
File "C:\Python27\lib\site-packages\dragonfly\actions\action_base.py", line 79, in append
assert isinstance(other, ActionBase)
AssertionError
When I do => print extras['find_rule'] in ClipRule._process_recognition, I get 'None'. I assume this means that I have incorrectly overridden the value method in FindRule. Wondering if anyone else has had some experience with this. Thanks