could not convert string to float in linux Debian 11 - numpy-ndarray

In DEBIAN11, I write a code for serial display on GUI to plot a graph using dev/ttyACMO but unfortunately an error occurred that string could not convert to float here is the code:
import serial as sr
import matplotlib.pyplot asplt
import numpy as np
s=sr.Serial('/dev/ttyACM0',115200);
plt.close('all')
plt.figure();
plt.ion();
plot.show();
data = np.array([]);
i=0
while i<100
a=s.readline()
a.decode()
b = float(a[0:4])
data = np.append(data,b);
plt.plot(data);
plt.pause(0.01);
i=i+1
s.close()

Related

Trouble with Rdkit when converting to molecular fingerprints

When attemping to get the rdkit to work i keep getting an argument error i am unsure of how to solve.
mol_list1 = [Chem.MolFromSmiles(i) for i in tqdm(df_database['Ligand SMILES'], desc='Creating mol objects from database Smiles')]
mol_list2 = [Chem.MolFromSmiles(i) for i in tqdm(df_metabolites['Smiles'].dropna(), desc='And now for the metabolites!')]
mfp1 = [AllChem.GetMorganFingerprint(j, 4) for j in tqdm(mol_list1, desc='Getting fingerprints for database mols')]
ArgumentError: Python argument types in
rdkit.Chem.rdMolDescriptors.GetMorganFingerprint(NoneType, int) did
not match C++ signature: GetMorganFingerprint(class RDKit::ROMol mol,
unsigned int radius, class boost::python::api::object invariants=[],
class boost::python::api::object fromAtoms=[], bool
useChirality=False, bool useBondTypes=True, bool useFeatures=False,
bool useCounts=True, class boost::python::api::object bitInfo=None,
bool includeRedundantEnvironments=False)
This is from the third line GetMorganFingerprint Imports were;
import pandas as pd
import seaborn as sns
import numpy as np
import os
import matplotlib.pyplot as plt
from tqdm import tqdm
from rdkit import Chem
from rdkit.Chem import AllChem,MACCSkeys
from rdkit import DataStructs
from rdkit.Chem import Descriptors
from rdkit.Chem import AllChem
from rdkit import DataStructs
from rdkit.Chem import PandasTools
Please help!

Python Watchdog Custom Event Handler Not Firing Correctly

I'm using Python's watchdog module to listen for created events on a certain directory. Where I do some processing on newly created .csv files. When I test my code with nothing in the handler the watchdog fires correctly for all pasted/created files, but when I add my code/logic inside the handler it fires less than expected (52/60 files for example).
OS used: Windows 10, code is expected to work on a Windows server.
Python version: 3.7.3
Code:
import time
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
import pandas as pd
import numpy as np
from error_handling import ErrorHandler
import os
from timeloop import Timeloop
from datetime import timedelta
import json
from fill_data import OnMyWatch2
class OnMyWatch:
# Set the directory on watch
watchDirectory = "."
def __init__(self):
self.observer1 = Observer()
def run(self):
self.observer1.schedule(Handler() , self.watchDirectory, recursive = True)
self.observer1.start()
try:
while True:
time.sleep(1)
except:
self.observer1.stop()
print("Observer Stopped")
self.observer1.join()
class Handler(FileSystemEventHandler):
#staticmethod
def on_any_event(event):
if event.is_directory:
return None
elif event.event_type == 'created':
try:
# Event is created, you can process it now
print("Watchdog received created event - % s." % event.src_path)
pathlower = str(event.src_path).lower()
if ".csv" in pathlower:
print("File is csv file")
# Once any code is added here the problem happens
# Example:
# df = pd.read_csv(event.src_path, names= ALL_INI.columnlistbundle.split("|"), sep="|", encoding='latin-1', engine='python')
# arraySelectedColumnsBundle = ALL_INI.selectedcolumnsbundle.split(",")
# bundle_df = df[np.array(arraySelectedColumnsBundle)]
else:
print("File is not csv file")
except Exception as e:
ErrorHandler(0, 'In Observer ', '-7', 'Exception ' + str(e), '', 1, '')
if __name__ == '__main__':
if os.path.isdir("."):
watch = OnMyWatch()
watch.run()

What's wrong with Windows Task Sheduler + pytesseract + multiprocessing?

Have the python code with pytesseract & multiprocessing. When I start the code manually from PyCharm it works fine with any number of threads. When I start the code with Win Task Sheduler with 'threads=1' it works fine.
However if I start the code with Win Task Sheduler with 'threads=2' or more than 2, it finishes without processing the images and without any errors.
I've got log messages like this. Script starts but does nothing and there is no any errors in Win logs
2020-05-24 13:09:31,834;START
2020-05-24 13:09:31,834;threads: 2
2020-05-24 13:10:31,832;START
2020-05-24 13:10:31,832;threads: 2
2020-05-24 13:11:31,851;START
2020-05-24 13:11:31,851;threads: 2
Code
from PIL import Image
import pytesseract
from pytesseract import Output
import datetime
from glob import glob
import os
import multiprocessing as multiprocessing
import cv2
import logging
def loggerinit(name, filename, overwrite):
logger = logging.getLogger(name)
logger.setLevel(logging.INFO)
# create the logging file handler
fh = logging.FileHandler(filename, encoding = 'UTF-8')
formatter = logging.Formatter('%(asctime)s;%(message)s')
fh.setFormatter(formatter)
# add handler to logger object
logger.addHandler(fh)
return logger
def getfiles(dirname, mask):
return glob(os.path.join(dirname, mask))
def tess_file(fname):
img = cv2.imread(fname)
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
im_for_T = Image.fromarray(img)
pytesseract.pytesseract.tesseract_cmd = 'C://Tesseract-OCR//tesseract.exe'
TESSDATA_PREFIX = 'C:/Program Files/Tesseract-OCR/tessdata'
try:
os.environ['OMP_THREAD_LIMIT'] = '1'
tess_data = pytesseract.image_to_osd(im_for_T, output_type=Output.DICT)
return fname, tess_data
except:
return fname, None
if __name__ == '__main__':
logger = loggerinit('tess', 'tess.log', False)
files = getfiles('Croped', '*.jpg')
t1 = datetime.datetime.now()
logger.info('START')
threads = 2
logger.info('threads: ' + str(threads))
p = multiprocessing.Pool(threads)
results = p.map(tess_file,files)
e = []
for r in results:
if type(r) == type(None):
e.append('OCR error: ' + r)
else:
print(r[0],". rotate: ",r[1]['rotate'])
p.close()
p.join()
t2 = datetime.datetime.now()
delta = (t2 - t1).total_seconds()
print('Total time: ', delta)
print('Files: ', len(files))
logger.info('Files: ' + str(len(files)))
logger.info('Stop.' + 'Total time: ' + str(delta))
# Print error if exist
for ee in e:
print(ee)
Whats wrong? How can I fix this issue?

python3 tkinter gui not reacting on execution

I'm using tkinter for my python3 GUI. The script I wrote, when executing in IDLE. But when I try to execute it without the GUI is not responding.
Here's the code:
#! python3
from tkinter import *
import tkinter as tk
class Program:
nameC = ""
master = ""
varC = ""
def callback(self):
self.nameC= filedialog.askopenfilename()
def __init__(self):
self.master = Tk()
self.varC = StringVar(self.master)
l1 = Label(text="Open file", relief=RIDGE,width=15)
l1.grid(row=0,column=0)
b1 = Button(text='Open', command=self.callback)
b1.grid(row=0,column=1)
program = Program()
mainloop()
So far I have a button and a label. If I click on the button, a filedialog is opened using the callback function
EDIT: fixed one error in the code
If it helps, I'm using windows
So after running the script in the console ( as mentioned not IDLE) I figured out that I would have to import filedialog:
#! python3
from tkinter import *
from tkinter import filedialog # this is what I needed
import tkinter as tk
class Program:
nameC = ""
master = ""
varC = ""
def callback(self):
self.nameC= filedialog.askopenfilename()
def __init__(self):
self.master = Tk()
self.varC = StringVar(self.master)
l1 = Label(text="Open file", relief=RIDGE,width=15)
l1.grid(row=0,column=0)
b1 = Button(text='Open', command=self.callback)
b1.grid(row=0,column=1)
program = Program()
mainloop()

Python 2.6 run time error

STEPCAFControl which is available in python2.6 but webgl module is not available. So I am trying to run this below program .
from __future__ import print_function
import sys
from OCC.STEPCAFControl import STEPCAFControl_Reader
from OCC.STEPControl import STEPControl_Reader
from OCC.IFSelect import IFSelect_RetDone, IFSelect_ItemsByEntity
from OCC.Display.SimpleGui import init_display
#from OCC.Display.WebGl import threejs_renderer
step_reader = STEPControl_Reader()
status = step_reader.ReadFile('./models/screw.step')
if status == IFSelect_RetDone: # check status
failsonly = False
step_reader.PrintCheckLoad(failsonly, IFSelect_ItemsByEntity)
step_reader.PrintCheckTransfer(failsonly, IFSelect_ItemsByEntity)
ok = step_reader.TransferRoot(1)
_nbs = step_reader.NbShapes()
aResShape = step_reader.Shape(1)
print("Success")
else:
print("Error: can't read file.")
sys.exit(0)
display, start_display, add_menu, add_function_to_menu = init_display()
display.DisplayShape(aResShape, update=True)
start_display()
#my_renderer = threejs_renderer.ThreejsRenderer(background_color="#123345")
#my_renderer.DisplayShape(aResShape)
but getting this error.
How to solve this issue? Any suggestion?

Resources