I need to convert a complex python object to JSON, by complex I mean an object that contains int variables, string variables, and 2 lists of custom objects.
My Python object's constructor is:
def __init__(self, skills="",vid=""):
self.Skills = list([])
for skillID in skills.split("-"):
if not skillID == "":
tmpSkill = Skill()
tmpSkillObj = DBCommands.getSkill(skillID)
tmpSkill.ID = tmpSkillObj[0][0] #tmpSkillObj[0][0]
tmpSkill.Name = tmpSkillObj[0][1]
tmpSkill.isMain = True
tmpSkill.CurrentlyTesting = False
tmpSkill.isSub = False
tmpSkill.Level = 0
tmpSkill.Tested = False
tmpSkill.Score = 0
tmpSkill.Confidence = 0
tmpSkill.BestScore = 0
tmpSkill.ParentID = 0
self.Skills.append(tmpSkill)
self.AskedQuestions.append(tmpSkill)
self.Skills = list(self.Skills)
if not skills == "":
self.Skills[0].CurrentlyTesting = True #Start testing the first skill
if not vid == "":
self.VacancyID = int(vid)
self.PlayerID = 0
self.Score = float(0)
self.AskedQuestions = list([])
self.MaxLevel = 0
self.AssessmentIsFinished = False
I need a mechanism to encode the object and decode it.
Encode:
import base64
import pickle
token = base64.b64encode(pickle.dumps(token,-1))
Decode:
import pickle
import base64
Obj = pickle.loads(base64.b64decode(token))
Related
I use python to write the program to control the motor, and the error is shown as follows after running:"message": "No value for argument 'speed_a' in function call pylint(no-value-for-parameter)[93,21]' Below is the code I am using:
import serial
import time
#import threading
import struct
from binascii import unhexlify
from crcmod import mkCrcFun
import binascii
import crcmod
def check_code(byte0, byte1, speed_vel, speed_ang):
'计算校验码时需要输入的字节'
read = byte0+byte1+speed_vel+speed_ang #解析校验码要输入的前几位
read=(str(binascii.b2a_hex(read))[2:-1])
print (read)
return (read)
def crc16_modbus(read):
'输出的控制电机指令字节码'
crc16 =crcmod.mkCrcFun(0x18005,rev=True,initCrc=0xFFFF,xorOut=0x0000)
data = read.replace(" ","")
#print (data)
readcrcout=hex(crc16(unhexlify(data))).upper()
str_list = list(readcrcout)
if len(str_list) < 6:
str_list.insert(2, '0'*(6-len(str_list))) # 位数不足补0
crc_data = "".join(str_list)
#print(crc_data)
read = read.strip()+crc_data[4:]+crc_data[2:4]
read = read.encode('UTF-8')
return read
def motor_speed_vel(speed_v,speed_a):
'计算小车线速度speed_v'
DEC1 = speed_v
DEC2 = speed_a
byte2 =(struct.pack("i",DEC1)[-4:-3])#线速度
byte3 =(struct.pack("i",DEC1)[-3:-2])#线速度
speed_vel = byte2 + byte3
byte4 = (struct.pack("i",DEC2)[-4:-3]) #角速度两个字节
byte5 = (struct.pack("i",DEC2)[-3:-2])
speed_ang = byte4+byte5
print (speed_vel,speed_ang)
return (speed_vel,speed_ang)
motor_speed_vel(200,20)
'''
def motor_speed_ang(speed_a):
'角速度的speed_a的byte码'
DEC2 = speed_a
byte4 = (struct.pack("i",DEC2)[-4:-3]) #角速度两个字节
byte5 = (struct.pack("i",DEC2)[-3:-2])
speed_ang = byte4+byte5
print (speed_ang)
return (speed_ang)
motor_speed_ang(20)
#motor_speed_cal(200,20) #设定的 (线速度,角速度)
'''
motor_speed_mode = b'\x01\x2F\x60\x60\x00\x03\x00\x00\x00\x0D'
#motor_status = b'\x43\x50\x00\x51\x00\x68\x95'
motor_start = b'\x01\x44\x21\x00\x31\x00\x00\x01\x00\x01\x75\x34'
motor_stop = b'\x01\x44\x21\x00\x31\x00\x00\x00\x00\x00\xE5\x34' # AB轴失能
class SpeedMotor:
def __init__(self, device,speed_v,speed_a):
# 真实速度
self.rel_speed = 0
# 设置的速度
self.set_speed1 = speed_v
# 设置角速度
self.set_speed2 = speed_a
# 运行状态
self.run = False
# 故障状态
self.fault = None
# 电机电压
self.voltage = 0
# 电机电流
self.current = 0
# 设置串口通讯
self.serial = serial.Serial(device, 115200)
self.serial.timeout = 0
# 设置为速度模式
self.serial.write(motor_speed_mode)
time.sleep(0.1)
# 设置加减速度
# self.serial.write(b'\x0A\x14\x14\x32')
# time.sleep(0.1)
def motor_speed_set(self):
'速度设置'
byte0 = b'\x01'
byte1 = b'\xEA'
speed_vel = motor_speed_vel(self.set_speed1)
speed_ang = motor_speed_vel(self.set_speed2)
read = check_code(byte0, byte1, speed_vel, speed_ang)
speed_code = read
self.serial.write(speed_code)
def motor_start(self):
self.serial.write(motor_start)
self.run = True
def motor_stop(self):
self.run = False
self.serial.write(motor_stop)
m = SpeedMotor('COM5',200,20)
m.motor_start()
#for i in range(100):
# m.set_speed = i
time.sleep(15)
m.motor_stop()`
I don't know if it is because of the problem with my parameter call, or because of the structure of the code, and I am very uncertain about the correctness of the code structure, because I am a beginner.
I am using my arduino to analyze analog inputs and I am accessing the arduino using the pyfirmata library and I ambasically measuring voltages using the 6 analog inputs on my arduino Uno. I need to find a way to live time feed this data into a CSV efficiently... I am not sure on the best way to do that
Any suggestion would help but please write out the code you suggest. I would prefer to use Pandas if possible because it's easier
voltage0 through voltage5 are my variables and I am trying to report those in a nice format that will later have to be analyzed
import time
from datetime import datetime
import pyfirmata
import pandas as pd
board = pyfirmata.Arduino('/dev/ttyACM1')
analog_pin0 = board.get_pin('a:0:i')
analog_pin1 = board.get_pin('a:1:i')
analog_pin2 = board.get_pin('a:2:i')
analog_pin3 = board.get_pin('a:3:i')
analog_pin4 = board.get_pin('a:4:i')
analog_pin5 = board.get_pin('a:5:i')
it = pyfirmata.util.Iterator(board)
it.start()
analog_pin0.enable_reporting()
analog_pin1.enable_reporting()
analog_pin2.enable_reporting()
analog_pin3.enable_reporting()
analog_pin4.enable_reporting()
analog_pin5.enable_reporting()
data = []
count = 0
x = 0
start = 0
while x <= 1000:
reading0 = analog_pin0.read()
if reading0 != None:
voltage0 = reading0 * 5
voltage0 = round(voltage0,2)
else:
voltage0 = float('nan')
reading1 = analog_pin1.read()
if reading1 != None:
voltage1 = reading1 * 5
voltage1 = round(voltage1,2)
else:
voltage1 = float('nan')
reading2 = analog_pin2.read()
if reading2 != None:
voltage2 = reading2 * 5
voltage2 = round(voltage2,2)
else:
voltage2 = float('nan')
reading3 = analog_pin3.read()
if reading3 != None:
voltage3 = reading3 * 5
voltage3 = round(voltage3,2)
else:
voltage3 = float('nan')
reading4 = analog_pin4.read()
if reading4 != None:
voltage4 = reading4 * 5
voltage4 = round(voltage4,2)
else:
voltage4 = float('nan')
reading5 = analog_pin5.read()
if reading5 != None:
voltage5 = reading5 * 5
voltage5 = round(voltage5,2)
else:
voltage5 = float('nan')
datarow = {'Voltage0': voltage0, 'Voltage1': voltage1, 'Voltage2' : voltage2, 'Voltage3': voltage3, 'Voltage4' : voltage4, 'Voltage5' : voltage5, 'Time' : time.strftime("%Y-%m-%d_%H:%M:%S")}
data.append(datarow)
if count%500 == 0:
dataframe = pd.DataFrame(data)
dataframe.to_csv('data.csv')
x += 1
count += 1
#time.sleep(1)enter code here
Your code seems to work, but it's not very efficient. Every 500 iterations, you rewrite all your data instead of updating your file with the new data in the end. You might consider saving it this way instead:
if count%500 == 0:
dataframe = pd.DataFrame(data)
dataframe.to_csv('data.csv',mode='a',header=False)
data = []
If it's still not fast enough, you might consider saving your data to a binary format such as .npy (numpy format), and convert it later to csv.
i first use PyQT4 .
i'm create a QTableWidget to show runing message...
when my program run, it ill crash Within ten minutes.
i try diable my TableUpdate function , and it's don't crash again.
there is my code please help me
class table_work(QThread):
TableDataSignal = pyqtSignal()
def __init__(self,main_self):
# QThread.__init__(self)
super(table_work, self).__init__(main_self)
self.main_self = main_self
self.table_update_list = list()
#pyqtSlot(dict)
def update_table_thread_o(self,work):
try:
row_pos = work['row_position']
data = work['data']
table_key_sort = work['key_sort']
this_table = work['table']
k = 0
for table_key in table_key_sort:
this_table.setItem(row_pos, k, QTableWidgetItem(unicode(data[table_key])))
k += 1
del work
except:
pass
def update_table_thread(self):
main_self = self.main_self
table_work_list = self.table_update_list
while 1:
for work in self.table_update_list:
row_pos = work['row_position']
data = work['data']
table_key_sort = work['key_sort']
this_table = work['table']
k = 0
for table_key in table_key_sort:
this_table.setItem(row_pos, k, QTableWidgetItem(unicode(data[table_key])))
k += 1
time.sleep(0.5)
def run(self):
self.update_table_thread()
this's update table message
def update_table(self,address,change_obj=None,tabe_name='auto_card'):
sample_dict = dict()
table_key_sort = list()
now_table_sort = 0
if tabe_name == "auto_bot":
this_table = self.auto_bot_procc_table
table_data_list = self.auto_bot_procc_table_list
now_table_sort = self.auto_bot_now_table_sort
sample_dict['address'] = address
sample_dict['money'] = 0
sample_dict['run_time'] = 0
sample_dict['item_cd'] = u"60分鐘後"
sample_dict['stat'] = "Ready..."
sample_dict['sort'] = now_table_sort
table_key_sort.append('address')
table_key_sort.append('money')
table_key_sort.append('run_time')
table_key_sort.append('item_cd')
table_key_sort.append('stat')
if tabe_name == "auto_card":
this_table = self.process_table
table_data_list = self.now_procc_table_list
now_table_sort = self.now_table_sort
sample_dict['address'] = address
sample_dict['done_num'] = 0
sample_dict['pre_item'] = ""
sample_dict['procc'] = "Ready"
sample_dict['mission_procc'] = u"待命.."
sample_dict['mission_num'] = 0
sample_dict['mission_line'] = 0
sample_dict['update_time'] = db.get_time()
sample_dict['sort'] = now_table_sort
sample_dict['option'] = ""
table_key_sort.append('address')
table_key_sort.append('done_num')
table_key_sort.append('pre_item')
table_key_sort.append('mission_procc')
table_key_sort.append('procc')
table_key_sort.append('mission_num')
table_key_sort.append('mission_line')
table_key_sort.append('update_time')
if address not in table_data_list:
this_table.insertRow(sample_dict['sort'])
table_data_list[address] = sample_dict
sample_dict['sort'] = self.auto_bot_now_table_sort
self.auto_bot_now_table_sort += 1
acc_data = table_data_list[address]
if change_obj != None:
key = change_obj['key']
val = change_obj['val']
if key in acc_data:
acc_data[key] = val
acc_data['update_time'] = db.get_time()
rowPosition = acc_data['sort']
temp = dict()
temp['row_position'] = rowPosition
temp['data'] = acc_data
temp['key_sort'] = table_key_sort
temp['table'] = this_table
self.TableDataSignal.emit(temp)
del temp
Some time i get a ANS.
i'm a PYQT newbie , After this period of various projects experience.
I understand if you don't use Main Thread to Change UI, Always use sign/emit
even your code is worked,but always use sign/emit, Otherwise there will be a series of disasters.
you just like
class sample(QtCore.QThread):
table_data_change = QtCore.pyqtSignal(dict)
def __init__(self,main_win):
self.main = main_win
self.table_data_change.connect(self.main.change_fn)
def test(self):
data = dict()
data['btn'] = .....
data['val'] = .....
self.table_data_change.emit(data)
Save your time !
I'm a beginner, so sorry if this is obvious.
I'm at a loss here. I've been trying to make an encryption/decryption program, but I keep getting this error. I'm aware that there are other questions on this issue, but I still can't resolve it.
Encryptor:
import binascii
def text_to_bits(text, encoding='utf-8', errors='surrogatepass'):
bits = bin(int(binascii.hexlify(text.encode(encoding, errors)), 16))[2:]
return bits.zfill(8 * ((len(bits) + 7) // 8))
def text_from_bits(bits, encoding='utf-8', errors='surrogatepass'):
n = int(bits, 2)
return int2bytes(n).decode(encoding, errors)
def int2bytes(i):
hex_string = '%x' % i
n = len(hex_string)
return binascii.unhexlify(hex_string.zfill(n + (n & 1)))
#ENCRYPTION ALGORITHM
algorithm = 61913299
#ASCII ----> NUMBERS
raw = input("Enter text to encrypt:")
binary = text_to_bits(raw)
binary = int(binary)
algorithm = int(algorithm)
encrypted = binary * algorithm
encrypted = str(encrypted)
print(encrypted)
print("Done")
Decryptor:
import sys
import time
def to_bin(string):
res = ''
for char in string:
tmp = bin(ord(char))[2:]
tmp = '%08d' %int(tmp)
res += tmp
return res
def to_str(string):
res = ''
for idx in range(len(string)/8):
tmp = chr(int(string[idx*8:(idx+1)*8], 2))
res += tmp
return res
incorrectpasswords = 0
password=("password")
originpassword = password
x = 1
algorithm = 61913299
while x==1:
passwordattempt =input("Enter Password:")
if passwordattempt == password:
print("Correct")
x = 2
if passwordattempt!= password:
print("Incorrect")
incorrectpasswords = incorrectpasswords + 1
if incorrectpasswords > 2:
if x == 1:
print("Too many wrong attempts, please try again in one minute.")
time.sleep(60)
encrypted = input("Enter numbers to unencrypt:")
encrypted = int(encrypted)
one = encrypted / algorithm
size = sys.getsizeof(one)
one = str(one).zfill(size + 1)
one = int(one)
unencrypted = to_str(one)
x = unencrypted
For the conversion between binary and text, and text and binary, I used some code I found online.
I believe your code is not working because:
one = encrypted / algorithm
generates a float
to turn your string back into a number you should apply
eval(one)
or
float(one)
instead of
int(one)
(You can also turn it into an int after applying float or eval)
alternatively you might be able to get it by using integer division // as opposed to / , which will make one the type int by flooring the decimal result of the divison, but I'm not sure if that is the behavior you are looking for
Example in python 3 shell:
>>> import sys
>>> one = 15/25
>>> size = sys.getsizeof(one)
>>> one = str(one).zfill(size+1)
>>> one
'00000000000000000000000.6'
>>> type(one)
<class 'str'>
>>> one = eval(one)
>>> one
0.6
>>> type(one)
<class 'float'>
I read from a hex file that's 1444352kB of size. I take 128 bytes of data and try to pack them using python struct.pack.
Below is the code :
#!/usr/bin/env python
import os
import struct
import ctypes
import array
import binascii
import sys,getopt
filename = file_location
blocksize = 1444352
opts,args = getopt.getopt(sys.argv[1:],'f:b:')
for o,a in opts:
if o == '-f':
filename = a
if o == '-b':
blocksize = a
offset = 0
with open(filename,"rb") as f:
block = f.read(blocksize)
str = ""
for ch in block:
str += hex(ord(ch))+" "
sector = []
c = 0
for s in str.split(' ') :
sector.append(s)
c += 1
if c == 128 :
sector.append("")
c = 0
#print sector
sector = ', '.join(sector)
#print sector
print type(sector)
sector = sector.split(',')
secdata = []
for items in sector[0:127] :
secdata.append(items)
secdata2 = ','.join(secdata)
print secdata2
print type(secdata2)
struct.pack('B', secdata2)
break
The secdata that appears to be a list, I have converted to string. but I always get error struct.error: cannot convert argument to integer when I try to pack the 128 bytes of data.