I am trying to stream an iRobot Create's sensors with pyserial. I import openinterface.py, setup the bot variable with the CreateBot function, and then call
bot.stream_sensors(6)
Then I receive this error - "Streaming thread error! tuple index out of range" The only reason I am calling the function with 6 is because thats what the example I am looking at used. I have also tried stream_sensors(0), stream_sensors(1), all the way up to 6. With any number less than 6, I get the same error plus "Illegal sensor id!". What is the parameter based on? Is it the specific sensor I want to stream (and if so, how do I get the number)? Any help would be appreciated.
Looking through the openinterface.py source, it looks like your getting the "Illegal sensor id" error because the given ID value you use when you call stream_sensors() doesn't match against a dictionary with known sensor ID's. The sensor ID dictionary is specified in the class SensorPacketDecoderAPI:
class SensorPacketDecoderApi:
"""
Transform sensor data in the form of bytes (from a serial stream)
into a dictionary of sensor values.
"""
names = {'left-velocity' : 42,
'right-velocity' : 41,
'radius' : 40,
'velocity' : 39,
'n-stream-packets' : 38,
'song-playing' : 37,
'song-number' : 36,
'oi-mode' : 35,
'home-base?' : 34,
'internal-charger?' : 34,
'user-analog-in-0' : 33,
'baud-rate-change?' : 32,
'user-digital-in-3' : 32,
'user-digital-in-2' : 32,
'user-digital-in-1' : 32,
'user-digital-in-0' : 32,
'cliff-right-signal' : 31,
'cliff-right-front-signal' : 30,
'cliff-left-front-signal' : 29,
'cliff-left-signal' : 28,
'wall-signal' : 27,
'capacity' : 26,
'charge' : 25,
'temperature' : 24,
'current' : 23,
'voltage' : 22,
'charging-state' : 21,
'angle' : 20,
'distance' : 19,
'advance?' : 18,
'play?' : 18,
'infrared-byte' : 17,
'left-wheel-overcurrent?' : 14,
'right-wheel-overcurrent?' : 14,
'low-side-driver-2-overcurent?' : 14,
'low-side-driver-0-overcurent?' : 14,
'low-side-driver-1-overcurent?' : 14,
'virtual-wall?' : 13,
'cliff-right?' : 12,
'cliff-front-right?' : 11,
'cliff-front-left?' : 10,
'cliff-left?' : 9,
'wall?' : 8,
'wheel-drop-caster?' : 7,
'wheel-drop-left?' : 7,
'wheel-drop-right?' : 7,
'bump-left?' : 7,
'bump-right?' : 7,
'all' : 6}
As to the reason why you're getting the "Streaming thread error!...", I'm not sure, all I can tell from my glance through the code is that it's originating in a function called _stream_sensors_worker inside the CreateBot class. There's also a function called _test_sensor_streaming that you could also try to get some debug info from _stream_sensors_worker.
Related
I've got some code where I receive a string of languages in a text.
My goal is to turn this input into a list and iterate through this list in a dictionary to use as a key for value outputs. I send this output to a list to use later.
The output I am expecting is [57, 20, 22, 52, 60... etc] but currently, I am receiving
[57, None, None, None, None, None, None....etc]
My first output is correct but after that, It doesn't seem to find the correct value in the dict.
Code below.
l_languages = []
language_dict = { 'Afrikaans' : 57, 'Arabic' : 20, 'Assistive communication' : 21, 'AUSLAN' : 22, 'Bosnian' : 52,'Burmese' : 60, 'Cantonese' : 23, 'Croation' : 54, 'Dutch' : 50,'French' : 24, 'German' : 25, 'Greek' : 26,'Hindi' : 27, 'Indigenous Australian' : 310, 'Indonesian' : 56, 'Italian' : 28, 'Japanese' : 62, 'Korean' : 48, 'Mandarin' : 29, 'Nepali' : 55, 'Polish' : 30}
data = "Afrikaans, Arabic, Assistive communication, AUSLAN, Bosnian, Burmese, Cantonese, Croation, Dutch"
language_list = data.split(',')
for language in language_list:
id = language_dict.get(language)
l_languages.append(id)
print(l_languages)
current output = [57, None, None, None, None, None, None....etc]
you are neglecting the white space in your language list. You should remove the leading and trailing white space and the access your dict.
if you just split the list at ',' then there is a leading white space in front of every following language. Just not on the first one, which explains your current output
Look at your language_list. It has leading whitespace. You need to call strip() on each element and you get your expected result
l_languages = []
language_dict = { 'Afrikaans' : 57, 'Arabic' : 20, 'Assistive communication' : 21, 'AUSLAN' : 22, 'Bosnian' : 52,'Burmese' : 60, 'Cantonese' : 23, 'Croation' : 54, 'Dutch' : 50,'French' : 24, 'German' : 25, 'Greek' : 26,'Hindi' : 27, 'Indigenous Australian' : 310, 'Indonesian' : 56, 'Italian' : 28, 'Japanese' : 62, 'Korean' : 48, 'Mandarin' : 29, 'Nepali' : 55, 'Polish' : 30}
data = "Afrikaans, Arabic, Assistive communication, AUSLAN, Bosnian, Burmese, Cantonese, Croation, Dutch"
language_list = data.split(',')
print(language_list)
for language in language_list:
val = language_dict.get(language.strip())
l_languages.append(val)
print(l_languages)
['Afrikaans', ' Arabic', ' Assistive communication', ' AUSLAN', ' Bosnian', ' Burmese', ' Cantonese', ' Croation', ' Dutch'] # list with leading spaces
[57, 20, 21, 22, 52, 60, 23, 54, 50] # right result
l_languages = []
language_dict = { 'Afrikaans' : 57, 'Arabic' : 20, 'Assistive communication' : 21, 'AUSLAN' : 22, 'Bosnian' : 52,'Burmese' : 60, 'Cantonese' : 23, 'Croation' : 54, 'Dutch' : 50,'French' : 24, 'German' : 25, 'Greek' : 26,'Hindi' : 27, 'Indigenous Australian' : 310, 'Indonesian' : 56, 'Italian' : 28, 'Japanese' : 62, 'Korean' : 48, 'Mandarin' : 29, 'Nepali' : 55, 'Polish' : 30}
data = "Afrikaans, Arabic, Assistive communication, AUSLAN, Bosnian, Burmese, Cantonese, Croation, Dutch"
language_list=[x.strip() for x in data.split(',')]
for language in language_list:
id = language_dict.get(language)
l_languages.append(id)
#output
[57, 20, 21, 22, 52, 60, 23, 54, 50]
Simplest way you can do
#Devil
language_dict = { 'Afrikaans' : 57, 'Arabic' : 20, 'Assistive communication' : 21,
'AUSLAN' : 22, 'Bosnian' : 52,'Burmese' : 60, 'Cantonese' : 23,
'Croation' : 54, 'Dutch' : 50,'French' : 24, 'German' : 25, 'Greek' : 26,
'Hindi' : 27, 'Indigenous Australian' : 310, 'Indonesian' : 56, 'Italian' : 28,
'Japanese' : 62, 'Korean' : 48, 'Mandarin' : 29, 'Nepali' : 55, 'Polish' : 30}
data = "Afrikaans, Arabic, Assistive communication, AUSLAN, Bosnian, Burmese, Cantonese, Croation, Dutch"
data_list = data.split(",") #split the data
data_list = [d.strip() for d in data_list] #remove white space
l_languages = [language_dict[z] for z in data_list] #find the value using key
print(data_list)
print(l_languages)
I do have a json format which is generated from docanno annotation tool. I want to convert the json into another format. Please check below for the format
Docanno json format :
{"id": 2, "data": "My name is Nithin Reddy and i'm working as a Data Scientist.", "label": [[3, 8, "Misc"], [11, 23, "Person"], [32, 39, "Activity"], [45, 59, "Designation"]]}
{"id": 3, "data": "I live in Hyderabad.", "label": [[2, 6, "Misc"], [10, 19, "Location"]]}
{"id": 4, "data": "I'm pusring my master's from Bits Pilani.", "label": [[15, 24, "Education"], [29, 40, "Organization"]]}
Required json format :
("My name is Nithin Reddy and i'm working as a Data Scientist.", {"entities": [(3, 8, "Misc"), (11, 23, "Person"), (32, 39, "Activity"), (45, 59, "Designation")]}),
("I live in Hyderabad.", {"entities": [(2, 6, "Misc"), (10, 19, "Location")]}),
("I'm pusring my master's from Bits Pilani.", {"entities": [(15, 24, "Education"), (29, 40, "Organization")]})
I tried the below code, but it's not working
import json
with open('data.json') as f:
data = json.load(f)
new_data = []
for i in data:
new_data.append((i['data'], {"entities": i['label']}))
with open('data_new.json', 'w') as f:
json.dump(new_data, f)
Can anyone help me with the python code which will change the json to required format?
I am running into issue with trying to pull out usable items from this output. I am just trying to pull a single value from this string of Unicode and it has been super fun.
my print(response) returns this: FYI this is way longer than this little snippet.
{u'configurationItems': [{u'configurationItemCaptureTime': datetime.datetime(2020, 6, 4, 21, 56, 31, 134000, tzinfo=tzlocal()), u'resourceCreationTime': datetime.datetime(2020, 5, 22, 16, 32, 55, 162000, tzinfo=tzlocal()), u'availabilityZone': u'Not Applicable', u'awsRegion': u'us-east-1', u'tags': {u'brassmonkeynew': u'tomtagnew'}, u'resourceType': u'AWS::DynamoDB::Table', u'resourceId': u'tj-test2', u'configurationStateId': u'1591307791134', u'relatedEvents': [], u'relationships': [], u'arn': u'arn:aws:dynamodb:us-east-1:896911201517:table/tj-test2', u'version': u'1.3', u'configurationItemMD5Hash': u'', u'supplementaryConfiguration': {u'ContinuousBackupsDescription': u'{"continuousBackupsStatus":"ENABLED","pointInTimeRecoveryDescription":{"pointInTimeRecoveryStatus":"DISABLED"}}', u'Tags': u'[{"key":"brassmonkeynew","value":"tomtagnew"}]'}, u'resourceName': u'tj-test2', u'configuration': u'{"attributeDefinitions":[{"attributeName":"tj-test2","attributeType":"S"}],"tableName":"tj-test2","keySchema":[{"attributeName":"tj-test2","keyType":"HASH"}],"tableStatus":"ACTIVE","creationDateTime":1590165175162,"provisionedThroughput":{"numberOfDecreasesToday":0,"readCapacityUnits":5,"writeCapacityUnits":5},"tableArn":"arn:aws:dynamodb:us-east-1:896911201517:table/tj-test2","tableId":"816956d7-95d1-4d31-8d18-f11b18de4643"}', u'configurationItemStatus': u'OK', u'accountId': u'896911201517'}, {u'configurationItemCaptureTime': datetime.datetime(2020, 6, 1, 16, 27, 21, 316000, tzinfo=tzlocal()), u'resourceCreationTime': datetime.datetime(2020, 5, 22, 16, 32, 55, 162000, tzinfo=tzlocal()), u'availabilityZone': u'Not Applicable', u'awsRegion': u'us-east-1', u'tags': {u'brassmonkeynew': u'tomtagnew', u'backup-schedule': u'daily'}, u'resourceType': u'AWS::DynamoDB::Table', u'resourceId': u'tj-test2', u'configurationStateId': u'1591028841316', u'relatedEvents': [], u'relationships': [], u'arn': u'arn:aws:dynamodb:us-east-1:896911201517:table/tj-test2', u'version': u'1.3', u'configurationItemMD5Hash': u'', u'supplementaryConfiguration': {u'ContinuousBackupsDescription': u'{"continuousBackupsStatus":"ENABLED","pointInTimeRecoveryDescription":{"pointInTimeRecoveryStatus":"DISABLED"}}', u'Tags': u'[{"key":"brassmonkeynew","value":"tomtagnew"},{"key":"backup-schedule","value":"daily"}]'}, u'resourceName': u'tj-test2', u'configuration': u'{"attributeDefinitions":[{"attributeName":"tj-test2","attributeType":"S"}],"tableName":"tj-test2","keySchema":[{"attributeName":"tj-
and so on. I have tried a few different ways of getting this info but every time I get a key error:
I also tried converting this into JSON and but since i have Date/time at the top it gives me this error:
“TypeError: [] is not JSON serializable
Failed attempts:
# print(response[0]["tableArn"])
print(response2)
print(response2['tableArn'])
print(response2.arn)
print(response2['configurationItems'][0]['tableArn'])
print(response2['configurationItems']['tableArn'])
print(response.configurationItems[0])
arn = response.configurationItems[0].arn
def lambda_handler(event, context):
# print("Received event: " + json.dumps(event, indent=2))
message = event['Records'][0]['Sns']['Message']
print("From SNS: " + message)
response = client.get_resource_config_history(
resourceType='AWS::DynamoDB::Table',
resourceId = message
)
response2 = dict(response)
print(response)
return message
Here's some Python3 code that shows how to access the elements:
import boto3
import json
import pprint
config_client = boto3.client('config')
response = config_client.get_resource_config_history(
resourceType='AWS::DynamoDB::Table',
resourceId = 'stack-table'
)
for item in response['configurationItems']:
configuration = item['configuration'] # Returns a JSON string
config = json.loads(configuration) # Convert to Python object
pprint.pprint(config) # Show what's in it
print(config['tableArn']) # Access elements in object
The trick is that the configuration field contains a JSON string that needs to be converted into a Python object for easy access.
i am new in Python language. I need to get all Amazon-Web-Services Identity and Access Management (Amazon-IAM) policy details using Boto 3 and Python.
I tried to parse JSON output from Boto 3 client and also need to save key-value pair into a map (policyName, Arn). Sample JSON output is like this:
{
'ResponseMetadata': {
'HTTPStatusCode': 200,
'HTTPHeaders': {
'vary': 'Accept-Encoding',
'content-length': '19143',
'content-type': 'text/xml',
'date': 'Thu, 23 Feb 2017 06:39:25 GMT'
}
},
u 'Books': [ {
u 'PolicyName': 'book1',
u 'Arn': '002dfgdfgdfgdfgvdfxgdfgdfgdfgfdg',
u 'CreateDate': datetime.datetime(2017, 2, 22, 13, 10, 55, tzinfo = tzutc()),
u 'UpdateDate': datetime.datetime(2017, 2, 22, 13, 10, 55, tzinfo = tzutc())
}, {
u 'PolicyName': 'book2','
u 'Arn': '002dfgdfgdfgdfgvdfxgdfgdfgdfgfdg',
u 'CreateDate': datetime.datetime(2017, 2, 22, 13, 10, 55, tzinfo = tzutc()),
u 'UpdateDate': datetime.datetime(2017, 2, 22, 13, 10, 55, tzinfo = tzutc())
}]
}
I have following code
iampolicylist_response = iamClient.list_policies(
Scope='Local',
MaxItems=150
)
print iampolicylist_response
res=json.dumps(iampolicylist_response)
print res
ret={}
for i in res["PolicyName"]:
ret[i["PolicyName"]]=i["Arn"]
return ret
Using json.loads, it shows error like this
TypeError: expected string or buffer
Using json.dumps, it shows error like this
TypeError: datetime.datetime(2017, 2, 22, 13, 10, 55, tzinfo=tzutc()) is not JSON serializable
What is actual issue?
The result iampolicylist_response is already a dictionary
You do not need to parse it .
See http://boto3.readthedocs.io/en/latest/reference/services/iam.html#IAM.Client.list_policies
The response is a dictionary object
Remove res=json.dumps(iampolicylist_response)
I want to extract numbers and calculate the sum of these numbers from JSON API. The format is
{
comments: [
{
name: "Matthias"
count: 97
},
{
name: "Geomer"
count: 97
}
...
]
}
And my code is
import json
import urllib
url = 'http://python-data.dr-chuck.net/comments_204529.json'
print 'Retrieving', url
uh = urllib.urlopen(url)
data = uh.read()
print 'Retrieved',len(data),'characters'
result = json.loads(url)
print result
I can get the result of how many characters in this data but cannot continue with the code because it's said JSON object cannot be decoded.
Does anyone know how to finish this code? Much appreciated!
First of all, I suggest you study the built-in Python Data Structures to get a better understanding about what you are dealing with.
result is a dictionary, result["comments"] is a list of dictionaries - you can make a list comprehension to get all the comments counts:
>>> import json
>>> import urllib
>>>
>>> url = 'http://python-data.dr-chuck.net/comments_204529.json'
>>> uh = urllib.urlopen(url)
>>> result = json.load(uh)
>>>
>>> [comment["count"] for comment in result["comments"]]
[100, 96, 95, 93, 85, 85, 77, 73, 73, 70, 65, 65, 65, 62, 62, 62, 61, 57, 50, 49, 46, 46, 43, 42, 39, 38, 37, 36, 34, 33, 31, 28, 28, 26, 26, 25, 22, 20, 20, 18, 17, 15, 14, 12, 10, 9, 8, 6, 5, 3]