def __resolve_conflicts(self, itineraries, simulation): # Gets configuration parameters (tick_times, max_attempt) = self.__get_params() # Setups variables attempts = {} # attemps[conflict] = count unsolvable_conflicts = set() while True: # Resets the itineraries (set their state to start node) self.__reset_itineraries(itineraries) # Creates simulation copy for prediction predict_simulation = simulation.copy predict_simulation.airport.apply_schedule( Schedule(itineraries, 0, 0)) for i in range(tick_times): # Adds aircrafts predict_simulation.pre_tick() # Check if all aircrafts has an itinerary, if not, assign one self.__schedule_new_aircrafts(simulation, predict_simulation, itineraries) # Gets conflict in current state conflict = self.__get_conflict_to_solve( predict_simulation.airport.next_conflicts, unsolvable_conflicts) # If a conflict is found, tries to resolve it if conflict is not None: try: self.__resolve_conflict(simulation, itineraries, conflict, attempts, max_attempt) # Okay, then re-run everything again break except ConflictException: # The conflict isn't able to be solved, skip it in # later runs unsolvable_conflicts.add(conflict) self.logger.warning("Gave up solving %s", conflict) # Re-run eveything again break if i == tick_times - 1: # Done, conflicts are all handled, return the schedule self.__reset_itineraries(itineraries) return Schedule(itineraries, self.__get_n_delay_added(attempts), len(unsolvable_conflicts)) # After dealing with the conflicts in current state, tick to # next state predict_simulation.tick() predict_simulation.post_tick()
async def run(account_id: int): from Service import User import asyncio from login import login from bilibili import bilibili import biliconsole from schedule import Schedule from aioweb.aioWebsocket import aioWebsocket user = User(account_id=account_id) dic_user = await user.load_account_conf() x = bilibili() await x.init() from statistics import Statistics Statistics() biliconsole_task = biliconsole.Biliconsole() # login_tasks = login().login_new() login_tasks = login().login2() await login_tasks from comments import load_tasks tasks = await load_tasks(user) asyncio.create_task(biliconsole_task.run(), name="biliconsole") schedule = Schedule() print(dic_user) if dic_user['regular_sleep']['on']: Schedule().scheduled_sleep = True asyncio.create_task(schedule.run( dic_user['regular_sleep']['schedule']), name="schedule") aioWebsocket.tasks = tasks asyncio.create_task(aioWebsocket().receive(), name="aiowebsocket")
def should_add_schedules_directly(self): timezone_1 = Timezone('Abu Dhabi') timezone_2 = Timezone('Pacific (US & Canada)') l1_1 = WeeklyLesson(start_time=0, day_of_week=0) l1_2 = WeeklyLesson(start_time=1, day_of_week=0) l1_3 = WeeklyLesson(start_time=0.5, day_of_week=0) l2_1 = WeeklyLesson(start_time=0, day_of_week=0) l2_2 = WeeklyLesson(start_time=1, day_of_week=0) l2_3 = WeeklyLesson(start_time=0.5, day_of_week=0) lessons_1 = [l1_1, l1_2, l1_3] lessons_2 = [l2_1, l2_2, l2_3] s_1 = Schedule(lessons=lessons_1, timezone=timezone_1) s_2 = Schedule(lessons=lessons_2, timezone=timezone_2) s_3 = s_1.add_schedule(s_2, timezone=None) expect(s_3.freq_lessons_at(start_time=0, day_of_week=0)).to.equal(2) expect(s_3.freq_lessons_at(start_time=1, day_of_week=0)).to.equal(2) expect(s_3.freq_lessons_at(start_time=0.5, day_of_week=0)).to.equal(2) expect(s_3.freq_lessons_at(start_time=23.5, day_of_week=5)).to.equal(0)
def test_neh_basic(self): """test sprawdza czy po zastowowaniu ulepszonego algorytmu NEH ilość zadań pozostaje bez zmian""" schedule1 = Schedule() schedule1.load_from_file("ta0") schedule2 = Schedule() schedule2.load_from_file("ta0") schedule1.basic_neh() self.assertEqual(len(schedule1.joblist), len(schedule2.joblist))
def test_neh_extnd3(self): """test sprawdza czy po zastowowaniu ulepszonego algorytmu NEH zadania się nie powtarzają""" schedule1 = Schedule() schedule1.load_from_file("ta40") schedule2 = Schedule() schedule2.load_from_file("ta40") schedule1.extend_neh_lng() self.assertEqual(len(schedule1.joblist), len(set(schedule2.joblist)))
def __init__(self, size, data, schedules=None): if schedules is None: self.schedules = [Schedule(data).initialize() for _ in range(size)] else: self.schedules = schedules if len(schedules) < size: for i in range(len(schedules), size): self.schedules.append(Schedule(data).initialize()) self.schedules[i]._fitness = self.schedules[ i].calculate_fitness() self.sort_by_fitness()
def GetSchedule(self, policy, trip, environment): totalReward = 0.0 chargingStations = [] tripStats = [] tripTime = 0 state = environment.Reset() tripStats.append(Stat(state, None)) while True: actionToTake = policy[state.StopIndex, state.TimeBlock, state.BatteryLevel] nextState, reward, isDone = environment.Step(actionToTake) totalReward += reward if nextState is None: break tripTime += (nextState.TimeBlock - tripTime) if actionToTake == ActionSpace.Charge: if self.IsStopInList(nextState.StopIndex, chargingStations): chargingStations[self.GetStopIndex( nextState.StopIndex, chargingStations)].TimeAtStop += 1 else: chargingStations.append( ScheduleStop( nextState.StopIndex, trip.Route.PossibleStops[nextState.StopIndex].Name, 1, trip.Route.PossibleStops[ nextState.StopIndex].Location)) state = nextState tripStats.append(Stat(state, actionToTake)) if isDone: break if nextState is not None and nextState.StopIndex == environment.NumberOfStops - 1: return Schedule(trip.Route.Coordinates, chargingStations, trip.Route.PossibleStops[nextState.StopIndex], tripTime, nextState.BatteryLevel, True, tripStats, self.TimeBlockConstant, trip.TripName) else: return Schedule(trip.Route.Coordinates, chargingStations, trip.Route.PossibleStops[state.StopIndex], tripTime, state.BatteryLevel, False, tripStats, self.TimeBlockConstant, trip.TripName)
def buttonClicked(self): depairport = str(self.dep_combo.currentText()) arrairport = str(self.arr_combo.currentText()) depdate = self.forcolorList[0] airline = str(self.airline_com.currentText()) self.schedule = Schedule(depairport, arrairport, depdate, airline) self.resultList1 = self.schedule.resultList() for i in self.resultList1: #날짜에 년월일시간과 가격에 원을 붙여주기 위함. i[0] = i[0][:4] + "년" + i[0][4:6] + "월" + i[0][6:8] + "일" + i[0][ 8:10] + "시" + i[0][10:12] + "분" i[2] += "원" if len(self.forcolorList) > 1: #왕복으로 선택했을 경우에 돌아오는 항공권. depdate = self.forcolorList[-1] self.schedule = Schedule(arrairport, depairport, depdate, airline) self.resultList2 = self.schedule.resultList() for i in self.resultList2: i[0] = i[0][:4] + "년" + i[0][4:6] + "월" + i[0][6:8] + "일" + i[ 0][8:10] + "시" + i[0][10:12] + "분" i[2] += "원" inDex = QLabel('날짜' + '\t' * 3 + ' 항공사' + '\t' * 2 + '가격') # Done버튼 눌렀을 때 출력창 추가 self.resultEdit = QTextEdit() sort = QPushButton("Sort") self.key_combo = QComboBox() self.resultEdit.setReadOnly(True) #읽기모드 self.key_combo.addItem("Low Price") self.key_combo.addItem("Time") self.key_combo.addItem("Airline") self.print() sort.clicked.connect(self.sortClicked) hbox = QHBoxLayout() hbox.addStretch(1) hbox.addWidget(self.key_combo) hbox.addWidget(sort) self.vbox.addWidget(inDex) self.vbox.addWidget(self.resultEdit) self.vbox.addLayout(hbox) self.setLayout(self.vbox)
def __init__(self, data=None): self.graph = Graph(data) self.time = 0 self.depth = 8 self.decay = 0.5 self.tt_query_id = -1 self.reschedule_queries = [] self.reschedule_pos = -1 self.cur_tt_flow_id = -1 self.reschedule = 0 # 记录已经访问过的节点 self.valid_edges = {} self.visited_node = [] # 记录当前TT流的周期 self.tt_flow_cycle = args.global_cycle self.tt_flow_start = -1 self.tt_flow_end = -1 self.delay = -1 self.tt_flow_lenth = 1 self.tt_flow_deadline = -1 self.tt_flow_length = -1 # 记录当前TT流的所有发出时间 self.tt_flow_time_record = [] # 记录每条流使用的链路和时隙 self.tt_flow_to_edge = {} # 记录每个链路包含的流 self.edge_to_tt_flow = {} for i in range(len(self.graph.nodes)): for j in range(len(self.graph.nodes)): self.edge_to_tt_flow[(i, j)] = set() # 奖励值参数 self.stop_parameter = 10 self.delay_parameter = 0.000001 self.lasting_parameter = 0 self.data = data if self.data is None: self.tt_queries = json.load( open(args.data_path + 'tt_flow.json', encoding='utf-8')) else: # 此处有 6 万条 TT-调度信息 self.tt_queries = self.data.tt_flow self.schedule = Schedule() self.current_stream_schedule = Schedule() self.enforce_next_query()
def __init__(self, LoE, pos): """Constructor, Pass a LoE, returns an object of type week""" self.loa = [] self.events = LoE self.position = pos self.color = WHEEL self.radius = 300 self.inncolor = INNER self.innRadius = (self.radius//3)*2 self.tdplusfour = (pos[0], pos[1] + self.radius) self.tdplusfive = (pos[0] + self.radius*math.sin(math.radians(51.4+180)), pos[1] - self.radius*math.cos(math.radians(51.4+180))) self.tdplussix = (pos[0] + self.radius*math.cos(math.radians(12.8+180)), pos[1] + self.radius*math.sin(math.radians(12.8+180))) self.td = (pos[0] + self.radius*math.sin(math.radians(25.8+180)), pos[1] + self.radius*math.cos(math.radians(25.8+180))) self.tdplusone = (pos[0] - self.radius*math.sin(math.radians(25.8+180)), pos[1] + self.radius*math.cos(math.radians(25.8+180))) self.tdplustwo = (pos[0] - self.radius*math.cos(math.radians(12.8+180)), pos[1] + self.radius*math.sin(math.radians(12.8+180))) self.tdplusthree = (pos[0] - self.radius*math.sin(math.radians(51.4+180)), pos[1] - self.radius*math.cos(math.radians(51.4+180))) self.inputFont = pygame.font.Font("RalewayInput.ttf", 14) self.font = pygame.font.Font("Raleway.ttf", 14) self.bigFont = pygame.font.Font("Roboto.ttf", 26) # constants for plotting schedule self.eventRing = (self.radius+self.innRadius)//2 self.eventRadius = 5 self.active = [] self.sched = Schedule([x[0] for x in week]) self.sched.getWeek()
def run(connections_file, coordinates_file, best_schedule_file, N, max_time, improve, depth, exclusion, method): """ Runs algorithm with specified heuristic and returns best schedule. """ best = {"schedule": None, "K": 0, "All": []} print(f"{N}x {method.name}") for i in range(N): # Display progress if N >= 100 and i % (N // 100) == 0: print(f"{(i // (N // 100))}%", end="\r") method.schedule = Schedule( csvdata(connections_file, coordinates_file, exclusion), max_time) method.run() if improve: optimize = Optimize(method.schedule, depth) optimize.run() quality = method.schedule.quality() best["All"].append(quality) # Keep track of best schedule if quality["K"] > best["K"]: best["schedule"] = method.schedule best["K"] = quality["K"] dump(best["schedule"], best_schedule_file) best["schedule"].create_csv() visualisation(best["schedule"])
def main(): controllers = Schedule() while True: for controller in controllers.controllers: # json data true is string, and therefore always true? active_controller = controllers.controllers[controller] if active_controller['active'] == 'True': now = datetime.datetime.utcnow() scheduled_on = now.replace( hour=int(active_controller['on'].split(':')[0]), minute=int(active_controller['on'].split(':')[1])) scheduled_off = now.replace( hour=int(active_controller['off'].split(':')[0]), minute=int(active_controller['off'].split(':')[1])) if (scheduled_on > now < scheduled_off) or (scheduled_on < now > scheduled_off): if not control(controllers, controller): print("Turning " + str(active_controller) + " on") control(controllers, controller, 'on') else: if control(controllers, controller): print("turning " + str(active_controller) + " off") control(controllers, controller, 'off') if abs( (now - now.replace(hour=0, minute=5)).total_seconds()) % 14400 == 0: print("Updating sunset and twilight values") controllers.update() print('sleeping...') time.sleep(60)
def test_hide_actors(self): import direction from sites import Cave import wide from schedule import Schedule world = wide.Overworld(sched=Schedule(), name="world") cave = Cave.at_point(world, coordinates=(15, 15), direction=direction.random(), landmark_name="cave") assert (world.schedule.current_time == 0) p = Kobold() cave.add_population(p) world.schedule.run_game(3000) assert (world.schedule.current_time == 0) cave.update_region() world.schedule.run_game(3000) assert (world.schedule.current_time == 3000) p.hide_actors() world.schedule.run_game(3000) assert (world.schedule.current_time == 3000) cave.update_region() world.schedule.run_game(3000) assert (world.schedule.current_time == 6000) p.hide_actors() cave.update_region() world.schedule.run_game(3000) assert (world.schedule.current_time == 9000)
def editschedule(): global con # set debugging level db.enabled = False # Only administrators have access to this page if not session['administrator']: return render_template( 'error.html', error="Only Administrators can access schedules") # create the objects we need sched = Schedule() bt = Boat() rt = Route() # process the data sent back from the form if request.method == 'POST': # Read the boats and schedule to display in option lists boats = readBoatTable() routes = readRouteTable() # If they processed the edit button then read the scchedule record and pass the details # to the new schedule scren if 'Edit' in request.form: CruiseDate = request.form['Edit'].split('.')[0] CruiseNo = int(request.form['Edit'].split('.')[1]) (dbStatus, rows) = sched.readSched(con, CruiseDate, CruiseNo) if dbStatus == False: # return render_template("newschedule.html", sched = rows, CruiseDate = CruiseDate, CruiseNo = CruiseNo, boats = boats, routes = routes, action = 'UPDATE', returnmessage = sched.error) return render_template("newschedule.html", sched=rows, CruiseDate=CruiseDate, CruiseNo=CruiseNo, boats=boats, routes=routes, action='UPDATE', returnmessage=sched.error) else: return render_template("newschedule.html", sched=rows[0], CruiseDate=CruiseDate, CruiseNo=CruiseNo, boats=boats, routes=routes, action='UPDATE') # If they have pressed add then create a blank 'rows' record and pass to the newschedule form if 'Add' in request.form: rows = sched.blankScheduleRow() CruiseDate = rows[0]["CruiseDate"] CruiseNo = int(rows[0]["CruiseNo"]) return render_template("newschedule.html", sched=rows, CruiseDate=CruiseDate, CruiseNo=CruiseNo, boats=boats, routes=routes, action='ADD')
def schedules(): global con # set debugging db.enabled = False # check that they have logged into the system. if not session['administrator']: return render_template( 'error.html', error="Only Administrators can access schedules") schedRows = None Status = None #Create new schedule object. sched = Schedule() #Return cruise schedules between dates. Make the lower one today and # then put the last one two years out today = datetime.now().strftime("%Y-%m-%d") # Add two years to get the future schedules future = (datetime.now() + relativedelta(years=2)).strftime("%Y-%m-%d") db.print(" ---schedules---") db.print("Today = " + today) db.print("Future = " + future) (Status, schedRows) = sched.readSchedulebyDate(con, today, future) if (Status == True): return render_template("schedules.html", rows=schedRows) else: return render_template('error.html', error=sched.error)
def getSchedules(): innerSchedules = [] orderedDictInner = firebaseConnection.getFirebaseValue( 'schedules', {UtilityFunctions.generateId(): Schedule().getDict()}, "settings", innerCircle.name, "circles") for key in orderedDictInner: innerSchedules.append(orderedDictInner[key]) innerCircle.settings.schedules = innerSchedules time.sleep(0.01) # want to make sure they don't get the same id outerSchedules = [] orderedDictOuter = firebaseConnection.getFirebaseValue( 'schedules', {UtilityFunctions.generateId(): Schedule().getDict()}, "settings", outerCircle.name, "circles") for key in orderedDictOuter: outerSchedules.append(orderedDictOuter[key]) outerCircle.settings.schedules = outerSchedules
def _generate_data(self, data): '''Generate data for the generation''' solution_fitness_items = [] solution_items = {} solutions = [] for i in range(0, self.population): rooms = Rooms(ROOMS_CSV) slots = Slots(rooms) courses = Courses(CLASSES_CSV) schedule = data[i] if data else Schedule(rooms, slots, courses) solutions.append(schedule) schedule_fitness = schedule.get_fitness() solution_fitness_items.append(schedule_fitness) solution_fitness_items.sort() if schedule_fitness in solution_items.keys(): solution_items[schedule_fitness][schedule.id] = schedule else: solution_items[schedule_fitness] = {} solution_items[schedule_fitness][schedule.id] = schedule self.elites = self._generate_elite_list(solution_items) self.avg_solution_fitness = round( sum(solution_fitness_items) / len(solution_fitness_items)) return solutions
def start(self): """ Override: Code called on initial start and subsequent restarts. Must set: - self.option = Option() - self.schedule = Schedule() Note: We don't load resources here; resources are loaded on demand. """ # load standard config config = ConfigSectionKey('../conf', '../local') self.config = config config.load('bootstrap.ini', 'bootstrap') config.load('init.ini') config.load('connect.ini') # load project specific config self.config.load(self.project_file) # load project specific options from optional project specific environ var environ_var = just_file_stem(self.project_file).lower() self.option = Option(environ_var, options=config('project').options) # load project specific schedule self.schedule = Schedule(config('schedule')) # diagnostics self.option.dump() self.config('project').dump(False) self.config('schedule').dump(False)
async def game_loop(): TARGET_FPS = 15 TIME_PER_FRAME = 1.0 / TARGET_FPS loop = asyncio.get_running_loop() loop.set_debug(True) BEGINNING_OF_TIME = loop.time() schedule = Schedule() while True: frame_start = loop.time() # take input event = schedule.get_next_event() if event: logging.debug(f"Event: {event['name']} ({event['kind']})") scene.handle_event(event, frame_start) # update await scene.update(frame_start, frame_start - BEGINNING_OF_TIME) # render await scene.render() # sleep sleep_time = frame_start + TIME_PER_FRAME - loop.time() if sleep_time > 0: await asyncio.sleep(sleep_time)
def updategrades(): if session.get('login'): studentclass = Student_Class(dsn=app.config['dsn']) schedule = Schedule(dsn=app.config['dsn']) student = Student(dsn=app.config['dsn']) grade = Grade(dsn=app.config['dsn']) schedule_id = session['schedule_id'] my_schedule = schedule.get_schedule(schedule_id) grades = grade.get_all_grades_for_schedule(schedule_id) ids = [] names = [] surnames = [] gradepoints = [] explanations = [] for g in grades: ids.append(g[0]) my_student = student.get_student(g[2]) names.append(my_student[1]) surnames.append(my_student[2]) gradepoints.append(g[3]) explanations.append(g[4]) return render_template('updategrade.html', zipped=zip(ids, names, surnames, gradepoints, explanations)) else: return redirect(url_for('home_page'))
def schedule(self, simulation): self.logger.info("Scheduling start") start = time.time() itineraries = {} priority_list = {} # Assigns route per aircraft without any separation constraint for aircraft in simulation.airport.aircrafts: # NOTE: Itinerary objects are newly created the reference of these # object will be used in other objects; however, be ware that the # object will be shared instead of being cloned in the later # phases. print("simulation.airport.aircrafts", aircraft) if aircraft.itinerary is not None: continue itinerary = self.schedule_aircraft(aircraft, simulation) itineraries[aircraft] = itinerary aircraft.set_itinerary(itinerary) cur_flight = simulation.scenario.get_flight(aircraft) calltime = cur_flight.departure_time if type(cur_flight) is \ DepartureFlight else \ cur_flight.arrival_time priority_list[aircraft.callsign] = calltime # Resolves conflicts # schedule, priority = self.__resolve_conflicts(itineraries, simulation, # priority_list) schedule, priority = Schedule(itineraries, 0, 0), priority_list # schedule, priority = self.__schedule(itineraries, simulation,priority_list) self.logger.info("Scheduling end") print(time.time() - start) return schedule, priority
def course_scheduler(course_descriptions, goal_conditions, initial_state): """ State consists of a conjunction of courses/high-level requirements that are to be achieved. When conjunction set is empty a viable schedule should be in the schedule_set. :param course_descriptions: Course catalog. A Python dictionary that uses Course as key and CourseInfo as value :param goal_conditions: A list of courses or high-level requirements that a viable schedule would need to fulfill :param initial_state: A list of courses the student has already taken :return: A List of scheduled courses in format (course, scheduled_term, course_credits) """ depths = range(1, 9) best_schedule = None best_schedule_num = float('inf') schedule = Schedule(course_descriptions, initial_state, goal_conditions) empty_schedule = schedule.copy() for depth in depths: schedule.max_semester = depth schedule.assign(empty_schedule) frontier = [] append_to_queue(frontier, goal_conditions, schedule) search(frontier, schedule) if 0 < schedule.num_of_courses_scheduled() < best_schedule_num: best_schedule = schedule.copy() best_schedule_num = schedule.num_of_courses_scheduled() schedule.assign(best_schedule) return schedule.get_plan()
def create_schedule(self, classList): classes = {} with open("course_map.txt", "rb") as logFile: classes = pickle.load(logFile) courses_desired = classList des = self.get_des(classes, courses_desired) course_perm = self.get_permutations(des) schedules = [] for schedule in course_perm: isValid = True sched = Schedule() for class_a in schedule: # must still check if time conflict occurs isValid = sched.add_class(class_a) if (not isValid): break if (isValid): schedules.append(sched) for schedule in schedules: schedule.display_schedule() print("Total schedules: " + str(len(schedules))) return schedules
async def handle_1_TV_raffle(type, raffleid, time_wait, time_limit, num, real_roomid): Statistics().append_to_TVlist(raffleid, time_limit) if Schedule().scheduled_sleep: Printer().printer(f"定时休眠,跳过房间 {real_roomid} 广播道具抽奖 {raffleid}", "Info", "green") return if bilibili().black_status: Printer().printer(f"黑屋休眠,跳过房间 {real_roomid} 广播道具抽奖 {raffleid}", "Info", "green") return await asyncio.sleep( min( max(0, time_wait) + random.uniform(0, min(num, 30)), time_limit - 1)) response2 = await bilibili().get_gift_of_TV(type, real_roomid, raffleid) # Printer().printer(f"参与了房间 {real_roomid} 的广播抽奖 {raffleid}", "Lottery", "cyan") json_response2 = await response2.json(content_type=None) # Printer().printer(f"参与房间 {real_roomid} 广播道具抽奖 {raffleid} 状态: {json_response2['msg']}", "Lottery", "cyan") if json_response2['code'] == 0: data = json_response2["data"] Printer().printer( f"房间 {real_roomid} 广播道具抽奖 {raffleid} 结果: {data['award_name']}X{data['award_num']}", "Lottery", "cyan") Statistics().add_to_result(data['award_name'], int(data['award_num'])) else: # {"code":-403,"data":null,"message":"访问被拒绝","msg":"访问被拒绝"} # {'code': 503, 'data': None, 'message': '请求太多了!', 'msg': '请求太多了!'} # {'code': -509, 'message': '请求过于频繁,请稍后再试', 'ttl': 1} Printer().printer( f"房间 {real_roomid} 广播道具抽奖 {raffleid} 结果: {json_response2['message']}", "Lottery", "cyan") print(json_response2)
def attendance(): if session.get('login'): studentclass = Student_Class(dsn=app.config['dsn']) schedule = Schedule(dsn=app.config['dsn']) classroom = Class(dsn=app.config['dsn']) student = Student(dsn=app.config['dsn']) #attendance = Attendance(dsn=app.config['dsn']) sinif = request.form['sinif'] row = request.form['derssaati'] session['sinif'] = sinif session['derssaat'] = row donenler = classroom.get_class_id_tuple(sinif) class_id = donenler[0] students = studentclass.get_classs_all_students(class_id) student_ids = [] names = [] surnames = [] for a in students: student_ids.append(a[0]) my_student = student.get_student(a[0]) names.append(my_student[1]) surnames.append(my_student[2]) return render_template('attendance.html', zipped=zip(student_ids, names, surnames), sinif=sinif) else: return redirect(url_for('home_page'))
def loadSchedule(globalTasks: [Task], days: [Day], debug=False) -> Schedule: scheduleDict = load("schedule") if not scheduleDict or not scheduleDict["scheduleDays"]: return calculateSchedule( days, globalTasks, Schedule(days, util.smoothCurrentArrow(), created=util.smoothCurrentArrow()), util.smoothCurrentArrow()) schedule = Schedule.fromDict(scheduleDict, globalTasks) lastScheduleDate = schedule.days()[-1].date if days[-1].date > lastScheduleDate: # New days need to be added lastDayIndex = None for i, day in enumerate(days): if day.date == lastScheduleDate: lastDayIndex = i break else: raise Exception("Error in Storage 1155523236") for missingDay in days[lastDayIndex:]: schedule.addDay(missingDay) return schedule #"scheduleDays": [], "created": "01.01.2021 10:30", "lastWorkConfirmed": "01.01.2021 10:24"
def parse_scheduled(courses, start_date, course_start_date, calendar_dict): # pre-process to dataframe history = {} for course in courses: if course.start_date > start_date: continue history_df = pd.read_csv('Output/' + course.title + '_history_cleaned.csv') for index, row in history_df.iterrows(): if '/' in row['Date']: cur_date_month, cur_date_day, cur_date_year = row['Date'].split('/') else: cur_date_year, cur_date_month, cur_date_day = row['Date'].split('-') history_df.loc[index, 'Date'] = date(int(cur_date_year), int(cur_date_month), int(cur_date_day)) history[course] = history_df cur = course_start_date while cur < start_date: cur_schedule = Schedule(date=cur) for course, history_df in history.items(): cur_history_df = history_df[history_df['Date'] == cur] if not cur_history_df.index.empty: cur_schedule.add_course(course=course, lesson=get_lesson(course=course, id=cur_history_df['Id'].item()), ins=get_ins_by_name(course=course, name=cur_history_df['Ins'].item()), point=0, calendar_dict=calendar_dict) if cur_schedule.is_valid(): cur_schedule.schedule_today(calendar_dict=calendar_dict) cur += datetime.timedelta(days=1)
def run(): ws = client.open_by_url(usr.SHEETURL).worksheet(usr.SHEETNAME) hours = get_valid_hours() mode = get_valid_mode() today_schedule = Schedule(hours=hours, mode=mode, tasks=get_tasks(ws)) today_schedule.print_all()
def handleUpdate(event, context): assertKey(event, 'body') data = json.loads(event['body']) assertKey(data, 'message') assertKey(data['message'], 'text') assertKey(data['message'], 'chat') assertKey(data['message']['chat'], 'id') message = str(data['message']['text']) chatId = data['message']['chat']['id'] if message.startswith('/start'): start(chatId) else: try: schedule = Schedule() if message.startswith('/water'): water(chatId, schedule) elif message.startswith('/add'): add(chatId, message, schedule) elif message.startswith('/remove'): remove(chatId, message, schedule) elif message.startswith('/list'): listAll(chatId, schedule) elif message.startswith('/set_interval'): setInterval(chatId, message, schedule) except Exception as e: print(e) sendMessage(chatId, str(e)) return {'statusCode': 200}
def gen_all_paths(self, tree_function, interpreter): """ The DFS core function that generates all paths through tree, it modifies self.schedule_paths or self.best_paths :param tree_function: An adjacency list (idnum: [idnums]) :param interpreter: An Interpreter object :return: None """ list_of_paths = [] appts = list(self.appts_to_assign) appt_ids = [appt.idnum for appt in appts] sched = Schedule(appts, [interpreter]) opt = Optimum(sched) opt.gen_schedule_dict(interpreter, appts) tree = dict(opt.schedule_dict) nodes = [node for node in tree if node > 0] # skip the root for node in nodes: # This lets gen_all_paths iteratively explore the tree, # visiting only nodes that are processed instead of all possible node_idx = appt_ids.index(node) appts_subset = appts[:node_idx + 1] opt.gen_schedule_dict(interpreter, appts_subset) subtree = dict(opt.schedule_dict) # To guard against index errors, tamp down endNode (startNode, endNode) = (min(subtree), min(node, max(subtree))) list_of_paths.append( list(tree_function(subtree, startNode, endNode, interpreter))) self.schedule_paths = [] for row in list_of_paths: for appt in row: self.schedule_paths.append(appt) if interpreter in opt.best_paths: self.best_paths[interpreter] = opt.best_paths[interpreter]