Creating a schedule via python - python

I'm currently working on trying to build a scheduler that will assign parts to specific time slots. This is what I've come up with currently, but I'm curious to know if there is a better way to do this. I'm fairly new to coding in python, so really have just working with while/for loops and if/else statements. I'm sure there is a way, so hopefully someone out there can show me the light.
import pandas as pd
from datetime import datetime, timedelta
day_start = str('2021-07-28 06:30')
break_1_start = str('2021-07-28 08:50')
lunch_start = str('2021-07-28 12:00')
break_2_start = str('2021-07-28 14:50')
day_end = str('2021-07-28 17:40')
day_start = datetime.strptime(day_start, "%Y-%m-%d %H:%M")
break_1_start = datetime.strptime(break_1_start, "%Y-%m-%d %H:%M")
break_1_end = break_1_start + timedelta(minutes=20)
lunch_start = datetime.strptime(lunch_start, "%Y-%m-%d %H:%M")
lunch_end = lunch_start + timedelta(minutes=30)
break_2_start = datetime.strptime(break_2_start, "%Y-%m-%d %H:%M")
break_2_end = break_2_start + timedelta(minutes=20)
day_end = datetime.strptime(day_end, "%Y-%m-%d %H:%M")
sched_df = pd.DataFrame({"Time": [day_start, break_1_start, break_1_end, lunch_start, lunch_end,
break_2_start, break_2_end, day_end]})
print(sched_df)
demand_df = pd.DataFrame({"PartNo": ['Part1', 'Part2', 'Part3', 'Part4', 'Part5'],
"TTJ": [75, 100, 180, 30, 60]})
demand_df = demand_df.astype({'TTJ': float})
print(demand_df)
a = 0
b = 1
c = 2
x = sched_df.iloc[a]['Time']
y = sched_df.iloc[0]['Time']
z = 0
for n in range(0, len(demand_df)):
while y < sched_df.iloc[1]['Time']:
y = x + timedelta(minutes=demand_df.iloc[a]['TTJ'])
if y > sched_df.iloc[1]['Time']:
end = sched_df.iloc[1]['Time']
print(demand_df.iloc[a]['PartNo'], 'time from : ', x.time(), ' to ', end.time())
start = sched_df.iloc[1]['Time']
end = sched_df.iloc[2]['Time']
print('Break time from : ', start.time(), ' to ', end.time())
xyz = sched_df.iloc[1]['Time'] - x
delta = xyz.total_seconds()
minutes = float(delta // 60)
z = demand_df.iloc[a]['TTJ'] - minutes
x = end + timedelta(minutes=z)
counter = a
else:
print(demand_df.iloc[a]['PartNo'], 'time from : ', x.time(), ' to ', y.time())
x = y
a = a+1
if x > sched_df.iloc[3]['Time']:
start = sched_df.iloc[2]['Time']
end = sched_df.iloc[3]['Time']
print(demand_df.iloc[a]['PartNo'], 'time from : ', start.time(), ' to ', end.time())
xyz = x-end
delta = xyz.total_seconds()
minutes = float(delta // 60)
z = minutes
start = sched_df.iloc[3]['Time']
end = sched_df.iloc[4]['Time']
print('Lunch time from : ', start.time(), ' to ', end.time())
start = sched_df.iloc[4]['Time']
x = start + timedelta(minutes=z)
print(demand_df.iloc[a]['PartNo'], 'time from : ', start.time(), ' to ', x.time())
z = 0
a = a + 1
else:
start = sched_df.iloc[2]['Time']
print(demand_df.iloc[a]['PartNo'], 'time from : ', start.time(), ' to ', x.time())
z = 0
a = a + 1
y = x
for n in range(0, len(demand_df)):
while y < sched_df.iloc[3]['Time']:
y = x + timedelta(minutes=demand_df.iloc[a]['TTJ'])
if y > sched_df.iloc[3]['Time']:
end = sched_df.iloc[3]['Time']
print(demand_df.iloc[a]['PartNo'], 'time from : ', x.time(), ' to ', end.time())
start = sched_df.iloc[3]['Time']
end = sched_df.iloc[4]['Time']
print('Lunch time from : ', start.time(), ' to ', end.time())
xyz = sched_df.iloc[3]['Time'] - x
delta = xyz.total_seconds()
minutes = float(delta // 60)
z = demand_df.iloc[a]['TTJ'] - minutes
start = sched_df.iloc[4]['Time']
x = start + timedelta(minutes=z)
print(demand_df.iloc[a]['PartNo'], 'time from : ', start.time(), ' to ', x.time())
z = 0
a = a + 1
else:
print(demand_df.iloc[a]['PartNo'], 'time from : ', x.time(), ' to ', y.time())
x = y
a = a + 1
Any help will be appreciated.

I'm not sure what exactly your problem is, but if you say you are new to python programming you could read through some comparable projects.
A project that comes to my mind would be pyschedule for example. The solution approaches should be similar to those to your problem.

Related

How can I form multiple lists from append

I made this code in order that every time it runs once it gives me a list in the correct sequence, I wanted the code to form a list from the repetition forming p1+p2+p3, but the code gives me all the p1 plus all the p2 plus all the p3, I wish every time it ran I was given a list.
p11 = []
p22 = []
p33 = []
for n in range(0, quantidade):
print('EPISÓDIO', n+1)
for g in range(0, prot):
p1 = ' ' + protagonistasn[g] + ' ' + random.choice(açoes) + ' ' + random.choice(coadjuvantesn) + ' ' + random.choice(locais)
if g <= prot/2 :
p1_1 = p1.replace("#","a")
p11.append(p1_1)
print(p1_1)
elif g > prot/2 :
p1_1 = p1.replace("#", "o")
p11.append(p1_1)
print(p1_1)
for j in range(0, vil):
p2 = ' ' +viloesn[j]+ ' ' + random.choice(açoes) + ' ' + random.choice(protagonistasn) + ' ' + random.choice(locais)
if j <= vil/2:
p2_2 = p2.replace("#", "a")
p22.append(p2_2)
print(p2_2)
elif j > vil/2:
p2_2 = p2.replace("#", "o")
p22.append(p2_2)
print(p2_2)
for h in range(0, prot):
p3 = ' ' + protagonistasn[h] + ' ' + random.choice(açoes) + ' ' + random.choice(viloesn) + ' ' + random.choice(locais)
if h <= prot/2 :
p3_3 = p3.replace("#","a")
p33.append(p3_3)
print(p3_3)
elif h > prot/2 :
p3_3 = p3.replace("#", "o")
p33.append(p3_3)
print(p3_3)
p_total = [p11, p22, p33]
p_tot = []
If I understand you right, you want your p_total list to contain all the p1s, p2s, and p3s from the first iteration, and then all the p1s, p2s, and p3d from the second iteration. Is that right? If so:
p_total = []
for n in range(0, quantidade):
p11 = []
p22 = []
p33 = []
print('EPIS?DIO', n+1)
for g in range(0, prot):
...
print(p3_3)
p_total.extend( [p11, p22, p33] )
p_tot = []
So, start each loop with an empty p11, p22, and p33. At the end of each iteration, append those on to your p_total, instead of holding them until the end.

ASCII animation blinking python

Decided to make a simple mp3 player for terminal. But while I was doing animation I had a problem - it blinks when the frame changes. Heres a video of it: https://youtu.be/in4VLPOfzHw. And the code:
import time, os, glob, eyed3, math, sys
from colorama import init
from mutagen.mp3 import MP3
mpts = glob.glob('*.mp3')
dark_grey = '\033[1;30;40m'
light_grey = '\033[0;37;40m'
white = '\033[1;37;40m'
lime = '\033[1;32;40m'
red = '\033[0;31;40m'
i = 0
song_list = []
for mpt in mpts:
song = MP3(mpt)
duration = math.ceil(song.info.length)
m_duration = duration // 60
s_duration = duration % 60
song = eyed3.load(mpt)
name = song.tag.title
song_list.append([name, [m_duration, s_duration]])
init()
# draw
while True:
# cassette
res = ''
i += 1
res += light_grey + ' ■̅̅̅̅̅̅̅̅̅̅̅̅■ \n'
res += dark_grey + ' |'
res += light_grey + '|############|'
res += dark_grey + '| \n'
res += dark_grey + ' |'
res += light_grey + '|'
if i % 4 == 0:
res += white + ' (/)====(/) '
elif i % 4 == 1:
res += white + ' (-)====(-) '
elif i % 4 == 2:
res += white + ' (\\)====(\\) '
elif i % 4 == 3:
res += white + ' (|)====(|) '
res += light_grey + '|'
res += dark_grey + '| \n'
res += dark_grey + ' |'
res += light_grey + '|############|'
res += dark_grey + '|\n'
res += light_grey + ' ■____________■ \n'
# green line
res += lime + ' ___________________________________\n\n'
# song list
res += red + ' # NAME TIME\n'
for i1 in range(len(song_list)):
res += dark_grey + ' ' + str(i1+1) + '.'
res += white + ' ' + song_list[i1][0] + ' '*(28 - len(song_list[i1][0])) + f'{song_list[i1][1][0]}:{song_list[i1][1][1]}\n'
os.system('cls')
sys.stdout.write(res)
sys.stdout.flush()
time.sleep(0.4)
Can it be fixed or sould I try to make in some other language instead of python?
It's the shelling out to cls that's doing it. Since you're already using ANSI codes for other stuff, try something like:
clear = '\033c'
...
while True:
...
print(clear)
Note that you'll never be able to completely get rid of the screen flicker using the "clear the screen then redraw it" technique, but this will shave several milliseconds from every loop and should decrease the flickering.
The idea is to avoid cleaning the whole screen (os.system('cls')). We could simply move the cursor to top and reprint everything. However moving cursor to top is almost impossible. One workaround I found is to print a lot of special characters that move cursor up one line until all the way to the top.
Reference:
cmd console game; reduction of blinking
The first solution of using \b does not work for me on a windows machine. So I go for the ender_scythe's solution. You have to print an empty line on first run to avoid the issue he/she mentioned. Here is the sample code that does not blink at all:
import time
import os
i = 0
dark_grey = '\033[1;30;40m'
light_grey = '\033[0;37;40m'
white = '\033[1;37;40m'
lime = '\033[1;32;40m'
red = '\033[0;31;40m'
def my_cls(nrow = 0):
if nrow == 0:
os.system('cls')
else:
print('\033[F'*nrow)
def my_display(chars):
print(''.join(chars))
return len(chars)
nrow = 0
while True:
my_cls(nrow)
# cassette
res = []
i+=1
if i == 1:
res.append('\n')
res.append(light_grey + ' ■̅̅̅̅̅̅̅̅̅̅̅̅■ \n')
res.append(dark_grey + ' |')
res.append(light_grey + '|###########|')
res.append(dark_grey + '| \n')
res.append(dark_grey + ' |')
res.append(light_grey + '|')
if i % 4 == 0:
res.append(white + ' (/)====(/) ')
elif i % 4 == 1:
res.append(white + ' (-)====(-) ')
elif i % 4 == 2:
res.append(white + ' (\\)====(\\) ')
elif i % 4 == 3:
res.append(white + ' (|)====(|) ')
res.append(light_grey + '|')
res.append(dark_grey + '| \n')
res.append(dark_grey + ' |')
res.append(light_grey + '|############|')
res.append(dark_grey + '|\n')
res.append(light_grey + ' ■____________■ \n')
# green line
res.append(lime + ' ___________________________________\n\n')
# song list
res.append(red + ' # NAME TIME\n')
nrow = my_display(res)
time.sleep(0.4)

Scatter Plot Only Plots the last iteration

I am trying to plot several different things in scatter plots by having several subplots and iterating over. Here in an example of what the result actually look like:
('x out: ', ' -511', ' y out: ', ' 1')
('Magnitudo = ', 4.778809128414475)
[0.]
('x out: ', ' -511', ' y out: ', ' -255')
('Magnitudo = ', 5.9840357600793475)
[1.]
('x out: ', ' -511', ' y out: ', ' 1')
('Magnitudo = ', 5.474086008639472)
[0.]
('x out: ', ' 513', ' y out: ', ' -511')
('Magnitudo = ', 5.182103409440737)
[0.]
('x out: ', ' -511', ' y out: ', ' 513')
('Magnitudo = ', 5.1769691160028835)
[0.]
('x out: ', ' -255', ' y out: ', ' -511')
('Magnitudo = ', 6.559643742815329)
[1.]
And this is the matplot I generated:
Result
As you can see, the matplot only shows the last iteration of my result. How do I present all of my iteration into this graph? Thank you. Here's my code. Where did I go wrong?
print ("Gyroskop")
print ("--------")
i="TRUE"
j = 0
mag = []
with open("/home/pi/TA/accelero.csv") as csvFile:
while i == "TRUE":
gyroskop_xout1 = read_word_2c(0x43)
gyroskop_yout1 = read_word_2c(0x45)
acc1 = math.sqrt((gyroskop_xout1*gyroskop_xout1)+(gyroskop_yout1*gyroskop_yout1))
mag.append(acc1)
print ("x out: ", ("%5d" % gyroskop_xout1), " y out: ",("%5d" % gyroskop_yout1))
j=j+1
time.sleep(1)
#---------------------
gyroskop_xout2 = read_word_2c(0x43)
gyroskop_yout2 = read_word_2c(0x45)
acc2 = math.sqrt((gyroskop_xout2*gyroskop_xout2)+(gyroskop_yout2*gyroskop_yout2))
mag.append(acc2)
time.sleep(1)
#--------------------
mag_max = max(mag)
mag_min = min(mag)
amplitude = mag_max - mag_min
# print "A : ",amplitude
h = amplitude/0.001
# print h
# print abs(h)
M_richter = 0
if(h!=0):
M_richter = math.log10(abs(h))
print ("Magnitudo = ",(M_richter))
#mag.clear()
del mag [:]
#accel = deltaM /2
hasil=clf.predict([[1, M_richter]])
print(hasil)
if (M_richter >= 6):
while aaa<5:
GPIO.output(buzzer,GPIO.HIGH)
print ("Beep")
sleep(0.5) # Delay in seconds
GPIO.output(buzzer,GPIO.LOW)
#print ("No Beep")
sleep(0.5)
aaa=aaa+1
csvFile.close()
i = "False"
if j == 10:
i = "False"
X0, X1 = 1, M_richter
plt.scatter(X0,X1, color = 'G')
plt.title('linear SVC')
plt.ylabel('Magnitude')
plt.xlabel('Location')
plt.show()
Y is 1 by default and I want to show all my magnitudo, thank you.
Currently, you are only passing a single point value (X0,X1) to plt.scatter(). You need to pass it a list of values, for example:
plt.scatter([x1,x2,x3,x4], [y1,y2,y3,y4], color = 'G')
However, I'm not completely sure what you are trying to plot here? If you want to plot the magnitude (M_richter) vs. the index j you have to append the calculated M_richter in each iteration to a list and then pass the list to plt.scatter(), and do the same with the values of j. Your script would then look like:
print ("Gyroskop")
print ("--------")
i="TRUE"
j = 0
mag = []
M_richter_values = []
j_values = []
with open("/home/pi/TA/accelero.csv") as csvFile:
while i == "TRUE":
gyroskop_xout1 = read_word_2c(0x43)
gyroskop_yout1 = read_word_2c(0x45)
acc1 = math.sqrt((gyroskop_xout1*gyroskop_xout1)+(gyroskop_yout1*gyroskop_yout1))
mag.append(acc1)
print ("x out: ", ("%5d" % gyroskop_xout1), " y out: ",("%5d" % gyroskop_yout1))
j_values.append(j) # Append value of j to list
j=j+1
time.sleep(1)
#---------------------
gyroskop_xout2 = read_word_2c(0x43)
gyroskop_yout2 = read_word_2c(0x45)
acc2 = math.sqrt((gyroskop_xout2*gyroskop_xout2)+(gyroskop_yout2*gyroskop_yout2))
mag.append(acc2)
time.sleep(1)
#--------------------
mag_max = max(mag)
mag_min = min(mag)
amplitude = mag_max - mag_min
# print "A : ",amplitude
h = amplitude/0.001
# print h
# print abs(h)
M_richter = 0
if(h!=0):
M_richter = math.log10(abs(h))
print ("Magnitudo = ",(M_richter))
M_richter_values.append(M_richter) # Append to list
#mag.clear()
del mag [:]
#accel = deltaM /2
hasil=clf.predict([[1, M_richter]])
print(hasil)
if (M_richter >= 6):
while aaa<5:
GPIO.output(buzzer,GPIO.HIGH)
print ("Beep")
sleep(0.5) # Delay in seconds
GPIO.output(buzzer,GPIO.LOW)
#print ("No Beep")
sleep(0.5)
aaa=aaa+1
csvFile.close()
i = "False"
if j == 10:
i = "False"
X0, X1 = 1, M_richter
plt.scatter(j_values, M_richter_values, color = 'G') # Passing lists instead of scalars
plt.title('linear SVC')
plt.ylabel('Magnitude')
plt.xlabel('Location')
plt.show()

Python Download Script

When I run this, the Progress % is backwards, does anyone know how to make it 0% at the beginning and 100% when it completes?
import time
x = 25
y = x
t = 0
downloading = True
while downloading:
time.sleep(1)
t += 1
x -= 1
f = ((x/y) * 100)
print('Time:', str(t) + ',', 'Progress: ', '{0:.2}'.format(str(f)) + '%,', 'Remaining: ' + str(x), 'MB', end="\r")
if(x == 0):
print('\nComplete!')
break
Just use (1-x/y) instead of x/y in f.
import time
x = 25
y = x
t = 0
downloading = True
while downloading:
time.sleep(0.01)
t += 1
x -= 1
f = ((1-x/y) * 100)
print('Time:', str(t) + ',', 'Progress: ', '{0:.3}'.format(str(f)) + '%,', 'Remaining: ' + str(x), 'MB', end="\r")
if(x == 0):
print('\nComplete!')
break
Also note that you should use '{0:.3}'.format(str(f)) so that 100% can be displayed correctly.

Why is y not defined?

In this code for some reason the variable y is not defined for the first if statement only. I need to know why it says that y is not defined. Also if you need code for finding WOEID here it is.
import urllib2
def make_word(words):
result = ""
for i in words:
result += i
return result
continents = ['asia', 'north%20america', 'south%20america', 'europe', 'asia', 'australia', 'antarctica']
a = raw_input('Put in a place: ')
a = a.lower()
if ' ' in a:
for h in a:
if h == ' ':
y = a.replace(' ', '%20')
page = urllib2.urlopen('http://woeid.rosselliot.co.nz/lookup/%s' % a).read()
f = page.find('Ohio')
if y not in continents:
if f != -1:
start = page.find('woeid="', f) + 7
end = page.find('"', start)
print 'The WOEID for %s: %s' % (a, page[start:end])
if f == -1:
f = page.find('United States')
if f != -1:
start = page.find('woeid="', f) + 7
end = page.find('"', start)
print 'The WOEID for %s: %s' % (a, page[start:end])
if y in continents:
if f == -1:
f = page.find('')
start = page.find('woeid="', f) + 7
print page[start:]
end = page.find('"', start)
print 'The WOEID for %s: %s' % (a, page[start:end])
You only define y in very specific circumstances:
if ' ' in a:
for h in a:
if h == ' ':
y = a.replace(' ', '%20')
So only if there is a space in a do you produce y.
Don't create a new variable here, and don't URL-encode manually. Use the urllib.quote() function instead:
from urllib import quote
y = quote(a.lower())
You appear to be mixing a and y throughout your code. Perhaps you need to use more meaningful names here:
place = raw_input('Put in a place: ')
place_quoted = quote(place.lower())
page = urllib2.urlopen('http://woeid.rosselliot.co.nz/lookup/%s' % place_quoted).read()
if place_quoted not in continents:
if ' ' in a: #This conditions fails in your code and the y variable is not initialized/ set.
if y not in continents: # when this line executes, it has no reference for y, throws the error "undefined"
Better initialize a default value at the start of your code.
Eg : y = None (or) handle your variable properly.

Categories

Resources