def test_can_return_week(self): m = Month(2012, 10) w = Week() w.set_day(0, TimeRange(Time(7), Time(17))) m.add_week(40, w) self.assertEquals( m.get_week(40).get_day(0), TimeRange(Time(7), Time(17)))
def test_can_give_total_time_for_month(self): m = Month(2012, 10) w = Week() w.set_day(4, TimeRange(Time(7), Time(17, 10))) m.add_week(40, w) m.add_week(42, w) self.assertEquals(m.get_total_time(), Hours(20, 20))
def test_multiple_interval_calculation(self): day = WorkDay() day.clear_interval() time_one = Time(12, 30, Meridian.PM) time_two = Time(2, 30, Meridian.PM) date_one = Date(4, 29, 2021) date_two = Date(4, 29, 2021) date_time_one = DateTime(date_one, time_one) date_time_two = DateTime(date_two, time_two) day.set_interval_start(date_time_one) day.end_current_interval(date_time_two) time_one = Time(2, 30, Meridian.PM) time_two = Time(4, 30, Meridian.PM) date_time_one = DateTime(date_one, time_one) date_time_two = DateTime(date_two, time_two) day.set_interval_start(date_time_one) day.end_current_interval(date_time_two) self.assertEqual(str(day.get_total_hours_worked()), "4:00")
def test_multiple_interval_not_hanging(self): day = WorkDay() day.clear_interval() time_one = Time(12, 30, Meridian.PM) time_two = Time(2, 30, Meridian.PM) date_one = Date(4, 29, 2021) date_two = Date(4, 29, 2021) date_time_one = DateTime(date_one, time_one) date_time_two = DateTime(date_two, time_two) day.set_interval_start(date_time_one) day.end_current_interval(date_time_two) time_one = Time(2, 30, Meridian.PM) time_two = Time(4, 30, Meridian.PM) date_time_one = DateTime(date_one, time_one) date_time_two = DateTime(date_two, time_two) day.set_interval_start(date_time_one) day.end_current_interval(date_time_two) self.assertEqual(day.check_for_incomplete_interval(), False)
def test_can_return_half_week(self): m = Month(2012, 11) w = Week() w.set_day(2, TimeRange(Time(7), Time(17))) w.set_day(3, TimeRange(Time(8), Time(18))) m.add_week(44, w) self.assertEquals(m.get_week(44).get_day(2), None)
def test_doesnt_schedule_hours_scheduled_by_taken_week(self): y = Year(2012) taken = Week() taken.set_day(0, TimeRange(Time(13, 30), Time(17))) y.add_taken(40, taken) w = y.get_schedule_for_week(40, Hours(47, 50)) self.assertEquals(w.get_total_time(), Hours(44, 20))
def test_uses_taken_week_when_scheduling(self): y = Year(2012) taken = Week() taken.set_day(0, TimeRange(Time(13, 30), Time(17))) y.add_taken(40, taken) w = y.get_schedule_for_week(40, Hours(57, 50)) self.assertEquals(w.get_day(0).get_start(), Time(17))
def test_uses_blocked_week_when_scheduling(self): y = Year(2012) blocked = Week() blocked.set_day(0, TimeRange(Time(8, 30), Time(13, 30))) y.add_blocked(40, blocked) w = y.get_schedule_for_week(40, Hours(57, 50)) self.assertEquals(w.get_day(0).get_start(), Time(13, 30))
def __init__(self): self.requests = Items() self.responses = Items() self.speaker_id = "ND" self.skill_id = "ND" mytime = Time() mytime.set_now() self.time = mytime self.dictionary = {}
def __getcourses_and_time(self, roomsunavlb): courses = self.__doc.getElementsByTagName("courses") coursex = courses[0].getElementsByTagName("course") output = [] outputimes = [] timescounter = 0 for course in coursex: y = course.getElementsByTagName("config") courseid = int(course.getAttribute("id"), 10) for config in y: z = config.getElementsByTagName("subpart") configid = int(config.getAttribute("id"), 10) for subpart in z: w = subpart.getElementsByTagName("class") subpartid = int(subpart.getAttribute("id"), 10) for classx in w: classid = int(classx.getAttribute("id"), 10) classlimit = classx.getAttribute("limit") parentclss = classx.getAttribute("parent") if (parentclss != ''): parentclss = int(parentclss, 10) if (classlimit != ''): classlimit = int(classlimit, 10) roombool = classx.getAttribute("room") rooms = {} if (roombool != "false"): aux = classx.getElementsByTagName("room") for room in aux: idaux = int(room.getAttribute("id"), 10) penaux = int(room.getAttribute("penalty"), 10) rooms[idaux] = penaux else: rooms = "false" aux = classx.getElementsByTagName("time") times = [] for time in aux: days = time.getAttribute("days") weeks = time.getAttribute("weeks") start = int(time.getAttribute("start"), 10) length = int(time.getAttribute("length"), 10) penaux = int(time.getAttribute("penalty"), 10) outputimes.append( Time(days, start, length, weeks, penaux, classid, timescounter + 1)) times.append(timescounter) timescounter += 1 output.append( Clazz(classid, classlimit, rooms, parentclss, courseid, configid, subpartid, times)) for room in roomsunavlb: for unavai in room.unavailable: outputimes.append( Time(unavai.days, unavai.start, unavai.length, unavai.weeks, "unnv", room.id, timescounter + 1)) timescounter += 1 return (output, outputimes)
def test_can_generate_realistic_monthly_report(self): y = Year(2012) blocked = self._get_daycare_week() taken = self._get_assistance_week() for i in [40, 41, 42, 43, 44]: y.add_blocked(i, blocked) y.add_taken(i, taken) m = y.generate_montly_report(10, Hours(57, 50)) self.assertEquals(m.get_day(1), TimeRange(Time(17), Time(20))) self.assertEquals(m.get_day(2), TimeRange(Time(13, 30), Time(20)))
def test_can_generate_monthly_report_for_december(self): y2012 = Year(2012) y2013 = Year(2013) y2012.set_next_year(y2013) blocked = self._get_daycare_week() taken = self._get_assistance_week() y2013.add_blocked(1, blocked) y2013.add_taken(1, taken) m = y2012.generate_montly_report(12, Hours(48, 0)) self.assertEquals(m.get_day(31), TimeRange(Time(17), Time(20)))
def test_returns_correctly_annotated_week_for_start_of_month(self): m = Month(2012, 11) w = Week() for i in xrange(7): w.set_day(i, TimeRange(Time(7), Time(17))) m.add_week(44, w) aw = m.get_week(44) self.assertEquals(aw.get_earliest_day_in_month(), 1) self.assertEquals(aw.get_first_valid_day(), 3) self.assertEquals(aw.get_last_valid_day(), 6)
def GetBackUpsFrom(self, time): '''Get backups method''' # Get host jsons backupList = self.Get( "backups", {'created_after': str(Time.GetInstance().UTCToISO(time))}) print(Time.GetInstance().UTCToISO(time)) # Return if null if backupList == {}: return {} return backupList['backups']
def test_can_be_printed(self): w = Week() for i in xrange(7): w.set_day(i, TimeRange(Time(7), Time(17))) self.assertEquals( str(w), """M: 7:00-17:00 T: 7:00-17:00 O: 7:00-17:00 T: 7:00-17:00 F: 7:00-17:00 L: 7:00-17:00 S: 7:00-17:00""")
def _get_assistance_week(self): w = Week() w.set_day(0, TimeRange(Time(13, 30), Time(17))) w.set_day(1, TimeRange(Time(6, 30), Time(8, 30))) w.set_day(2, TimeRange(Time(7), Time(17))) w.set_day(3, TimeRange(Time(6, 30), Time(8, 30))) return w
def generate_times(file_name): with open(file_name, 'w', encoding='utf-8') as file: for i in range(1, number_of_times): time = faker.time() hour = str(time)[:2] minute = str(time)[3:-3] seconds = str(time)[-2:] time = Time(i, time, hour, minute, seconds) times.append(time) file.write(time.csv_format()) if i != number_of_times: file.write('\n')
def test_can_enter_times_from_last_week_in_month(self): m = Month(2012, 10) w = Week() w.set_day(2, TimeRange(Time(7), Time(17))) w.set_day(3, TimeRange(Time(7), Time(17))) m.add_week(44, w) self.assertEquals(m.get_day(31), TimeRange(Time(7), Time(17))) self.assertNotEquals(m.get_day(32), TimeRange(Time(7), Time(17)))
def sign_params(self, verb, path, params=None): if not params: params = {} params.update({'tonce': int(1000*Time.Time()), 'access_key': self.access_key}) query = self.urlencode(params) signature = self.sign(verb, path, params) return signature, query
def _prop_from_ref(self, p): if (p == None or p == WrapperNULL): return None d_string = icallangbind_property_eval_string(p, ":") d = eval(d_string) d['ref'] = p if not self.cached_props.has_key(p): if d['value_type'] == 'DATE-TIME' or d['value_type'] == 'DATE': prop = Time(d, ) elif d['value_type'] == 'PERIOD': prop = Period(d) elif d['value_type'] == 'DURATION': prop = Duration(d) elif d['name'] == 'ATTACH': prop = Attach(d) elif d['name'] == 'ATTENDEE': prop = Attendee(d) elif d['name'] == 'ORGANIZER': prop = Organizer(d) else: prop = Property(ref=p) self.cached_props[p] = prop
def __init__(self, period): self.period = period self.exchange = Exchange(RebotConfig.access_key, RebotConfig.secret_key) self.exchange.delegate(tushareEXLocal()) # time Time.SetServerTime(self.exchange.getServerTimestamp()) # data. if RebotConfig.data_need_load: self.exchange.loadData(period, RebotConfig.rebot_test_begin) self.exchange.prepare(period, RebotConfig.rebot_test_begin) # markets self.markets = self.exchange.getMarkets() # rule. self.rules = {} # init. self.currenttimestamp = 0 self.Pool = [] self.RecordPools = [] for k, v in enumerate(self.markets): market = v['id'] dk = self.exchange.getK(market, 15, self.period, RebotConfig.rebot_test_begin) r = Turtle() r.Run(dk) lastk = r.KLines.Get(-1) self.rules[market] = r if lastk: self.currenttimestamp = lastk.t
def _prop_from_ref(self, p): if (p == None or p == WrapperNULL): return None d = {} d['value'] = icalproperty_get_value_as_string(p) d['name'] = icalproperty_get_property_name(p) propkind = icalproperty_string_to_kind(d['name']) kind = icalproperty_kind_to_value_kind(propkind) d['value_type'] = icalvalue_kind_to_string(kind) d['ref'] = p #~ print p, Property(ref=p).name() if not self.cached_props.has_key(p): if d['value_type'] == 'DATE-TIME' or d['value_type'] == 'DATE': prop = Time(d, ) elif d['value_type'] == 'PERIOD': prop = Period(d) elif d['value_type'] == 'DURATION': prop = Duration(d) elif d['name'] == 'ATTACH': prop = Attach(d) elif d['name'] == 'ATTENDEE': prop = Attendee(d) elif d['name'] == 'ORGANIZER': prop = Organizer(d) else: prop = Property(ref=p) self.cached_props[p] = prop
def main(): while True: conn = HTTPConnection( f"{argv[1] if len(argv) > 1 else 'localhost'}:{PORT}") try: conn.request("GET", "/") except ConnectionRefusedError as error: print(error) sleep(1) continue print('Connected') res = conn.getresponse() while True: chunk = res.readline() if (chunk == b'\n'): continue if (not chunk): break chunk = chunk[:-1].decode() data = json.loads(chunk) print(Time(), data) action = data['action'] print('action', action) try: print(MOTOR_SPEEDS[action]) except KeyError as error: print(error)
def create_with_hairdressers(cls, mean_time_wait_client, time_period, hairdressers_time, start_time_work=Time(10, 0)): barber = cls(mean_time_wait_client, time_period) for time_work in hairdressers_time: barber.add_hairdresser(Hairdresser(time_work)) return barber
def __init__(self, period): self.period = period self.exchange = Exchange(RebotConfig.access_key, RebotConfig.secret_key) delegate = None if RebotConfig.exchange == 'chbtc': if RebotConfig.rebot_release: delegate = chbtcEX() else: delegate = chbtcEXLocal() if RebotConfig.exchange == 'yunbi': if RebotConfig.rebot_release: delegate = yunbiEX() else: delegate = yunbiEXLocal() if RebotConfig.exchange == "tushare": delegate = tushareEXLocal() if RebotConfig.exchange == "huobi": if RebotConfig.rebot_release: delegate = huobiEX() else: delegate = huobiEXLocal() self.exchange.delegate(delegate) # time Time.SetServerTime(self.exchange.getServerTimestamp()) # data. if RebotConfig.data_need_load: self.exchange.loadData(period, RebotConfig.rebot_test_begin) self.exchange.prepare(period, RebotConfig.rebot_test_begin) # markets self.markets = self.exchange.getMarkets() # rule. self.rules = {} # init. self.currenttimestamp = 0 for k, v in enumerate(self.markets): market = v['id'] if RebotConfig.rebot_is_test: dk = self.exchange.getK(market, 42, self.period, RebotConfig.rebot_test_begin) # 1498838400:2017/7/1 0:0:0; 1496246400:2017/6/1 0:0:0; 1493568000:2017/5/1 0:0:0 else: dk = self.exchange.getK(market, 500, self.period) r = Mood() r.Run(dk) lastk = r.KLines.Get(-1) self.rules[market] = r if lastk: self.currenttimestamp = lastk.t # Log.d('index:%d, start market:%s, begin time %s, current time:%s'%(k, market, time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(r.KLines.Get(0).t)), time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(lastk.t)))); self.zuorizhangting = {} self.datas = []
def ask_time(reason): print("Please enter a time " + reason + ".") hours = user_input("hours") minutes = user_input("minutes") seconds = user_input("seconds") milliseconds = user_input("milliseconds") return Time(hours, minutes, seconds, milliseconds)
def start(self): ## summarize self.sum = Summarize(self.sentences, self.num_cluster) self.sum.save(self.collection, self.oid) ## time self.time = Time(self.sentences, self.sum.clusters) self.time.save(self.collection, self.oid) ## keyword self.keyword = Tf_Idsf(self.sentences) self.keyword.save(self.collection, self.oid) ## relation self.relation = Relation(self.sentences, self.mid) self.relation.save(self.collection, self.oid)
def __init__(self, map): self.map = map soldiers = dict( (loc, self.map.soldiers[loc].copy()) for loc in self.map.soldiers) id = 1 for soldier in soldiers.values(): soldier.id = id id += 1 self.times = [Time(self.MIN_TIME, soldiers, dict())]
class Analyzer(): def __init__(self, mid): conn = pymongo.MongoClient('13.209.73.233', 27017) db = conn.get_database('test') self.collection = db.get_collection('meets') self.mid = mid self.oid = ObjectId(self.mid) ## get talk result = self.collection.find({"_id": self.oid}, { "_id": False, "talk": True, "num_cluster": True }) if result[0]: talk = sorted(result[0]['talk'], key=lambda x: x[1]) self.sentences = [Sentence(i, t) for i, t in enumerate(talk)] self.num_cluster = result[0]['num_cluster'] print(self.num_cluster) self.error = False else: self.error = True def start(self): ## summarize self.sum = Summarize(self.sentences, self.num_cluster) self.sum.save(self.collection, self.oid) ## time self.time = Time(self.sentences, self.sum.clusters) self.time.save(self.collection, self.oid) ## keyword self.keyword = Tf_Idsf(self.sentences) self.keyword.save(self.collection, self.oid) ## relation self.relation = Relation(self.sentences, self.mid) self.relation.save(self.collection, self.oid)
def getTimes(self): self.conn.execute_query( 'SELECT * FROM Edu_Times WHERE EndOfInterval = 0') times = {} for row in self.conn: time = Time(row['ID'], row['Title'], row['EndOfInterval']) times[row['ID']] = time self._times = times print 'Times: ', len(self._times) return times
def end(self,v=None): """ Return or set end time of the period. The end time may be expressed as an RFC2445 format string or an instance of Time. The return value is an instance of Time. If the Period has a duration set, but not an end time, this method will caluculate the end time from the duration. """ if(v != None): if isinstance(t,Time): t = v elif isinstance(t,StringType) or isinstance(t,IntType): t = Time(v) else: raise TypeError if(self._end_is_duration()): start = icaltime_as_timet(icalperiodtype_start_get(self.pt)) dur = t.utc_seconds()-start; icalperiodtype_duration_set(self.pt, icaldurationtype_from_int(dur)) else: icalperiodtype_end_set(self.pt,t.tt) self._update_value() if(self._end_is_time()): rt = Time(icaltime_as_timet(icalperiodtype_end_get(self.pt)), 'DTEND') rt.timezone(self.timezone()) return rt elif(self._end_is_duration()): start = icaltime_as_timet(icalperiodtype_start_get(self.pt)) dur = icaldurationtype_as_int(icalperiodtype_duration_get(self.pt)) rt = Time(start+dur,'DTEND') rt.timezone(self.timezone()) return rt else: return Time({},'DTEND')
def test_can_specify_minute(self): time = Time(10, 30) self.assertEquals(time.get_minute(), 30)
def test_can_specify_simple_time(self): time = Time(7) self.assertEquals(time.get_hour(), 7)
def test_can_calculate_time_distance_for_half_hour(self): t1 = Time(7) t2 = Time(7, 30) self.assertEquals(t1.distance_to(t2), Hours(0, 30))
from Time import Time myTime4=Time() myTime4.set_time(8, 59, 45) myTime4.print_time() for i in range(20): myTime4.print_time() myTime4.tick()
def __init__(self, **kwargs): ''' sets a new rule where rule is specified in **kwargs as list of key-val pairs ex: Evan.setRule(lunch=False) // means not available for all lunchshifts ex: Evan.setRule(dinner=True, time=5, weekday=0) //means available at 5 for dinner shifts on monday Accepted keys: maxShifts = num Indicates how many shifts a person wants to works. This key should be by itself in its own rule maxShiftsPW = num indicates max number of shifts an employee is willing to work per week exclude = days: If exclude keyword is in Rule, the specified days will be excluded from scheduling, Can be used with lunch/dinner to only exclude part of day lunch = True if available for lunch shifts, False if available for dinner shift, ommit for available for both time = string "h:mm" hour at which employee is available (used with lunch or dinner True or else will match either) weekday = 0-6 indicating which day of the week, 0=Monday, 6=Sunday weeknum = 1-5, applies rule to a specific week of the month daynum = 1-31, applies rule to a specific day of the month weekday, weeknum, daynum can also be lists of same values ie weekday = [0,2] means rule applies for Mon & Tues If daynum then don't use weeknum or weekday if weekday, dont use daynum, optionally use weeknum to restrict range if weeknum, use with weekday to restrict range ''' ##TODO IMPLEMENT MORE CHECKING FOR UPDATED SPEC## self.rule = {} self.fancyNames = {"maxshifts" : "Maximum Shifts Allowed Each Month", "maxshiftspw" : "Maximum Shifts Allowed Each Week", "lunch" : "Lunch Shift", "dinner" : "Dinner Shifts", "both" : "Lunch or Dinner", "time" : "Available After", "weekday" : "Weekdays Available", "weeknum" : "Weeks Available (1 to 5)", "daynum" : "Available On"} self.weekdayNames = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"] #TODO PRINT WEEKNUM AS WEEKDAY BOUNDS FOR READABILITY for key in kwargs: lowerKey = key.lower() val = kwargs[key] print("%s:%s"%(lowerKey, val)) if lowerKey == "maxshifts" and val >= 0: if len(kwargs) != 1: print("maxShifts must appear in its own rule by itself") input() else: self.rule[lowerKey] = val break if lowerKey == "maxshiftspw" and val >= 0: if len(kwargs) != 1: print("maxShiftsPW must appear in its own rule by itself") input() else: self.rule[lowerKey] = val break if lowerKey == "exclude": if type(val) == int: if val in range(1,32): self.rule[lowerKey] = [val] else: print("exclude field must be 1-31") input() elif type(val) == list: #is true if all elems on list val are integers if self.isAllInts(val): #is true if all elems in list val are within specified range if self.isValid(val, range(1,32)): self.rule[lowerKey] = val else: print("exclude field list must all be within 1-31") input() else: print("exclude field list must all be integers") input() break #exclude field should appear by itself if lowerKey == "lunch": if val == True or val == False: self.rule[lowerKey]=val else: print("lunch field must be True or False") input() elif lowerKey == "time": if type(val)==str: time = Time() res = time.parseTime(val) if res != -1: self.rule[lowerKey] = time else: print("time field must be string in format (24 hour) hh:mm or h:mm (optional pm)") input() elif val.__class__.__name__ == "Time": if val.isValid(): self.rule[lowerKey] = val else: print("Invalid time") input() elif lowerKey == "weekday": if type(val) == int: if val in range(0,7): self.rule[lowerKey] = [val] else: print("weekday field must be 0-6") input() elif type(val) == list: #is true if all elems on list val are integers if self.isAllInts(val): #is true if all elems in list val are within specified range if self.isValid(val, range(0,7)): self.rule[lowerKey] = val else: print("weekday field list must all be within 0-6") input() else: print("weekday field list must all be integers") input() elif lowerKey == "weeknum": if type(val) == int: if val in range(1,7): self.rule[lowerKey] = [val] else: print("weeknum field must be 1-5") input() elif type(val) == list: #is true if all elems on list val are integers if self.isAllInts(val): #is true if all elems in list val are within specified range if self.isValid(val,range(1,7)): self.rule[lowerKey] = val else: print("weeknum field list must all be within 1-5") input() else: print("weeknum field list must all be integers") input() elif lowerKey == "daynum": if type(val) == int: if val in range(1,32): self.rule[lowerKey] = [val] else: print("daynum field must be 1-31") input() elif type(val) == list: #is true if all elems on list val are integers if self.isAllInts(val): #is true if all elems in list val are within specified range if self.isValid(val, range(1,32)): self.rule[lowerKey] = val else: print("daynum field list must all be within 1-31") input() else: print("daynum field list must all be integers") input()
def __init__(self): self.visitedNodes = []; self.Time = Time(); self.limitTime = 100000; self.limitCost = 100000; self.min = 'tempo';
def _singular_property(self, name, value_type, value=None, property_obj=None, enumerated_values=None): """Sets or gets the value of a method which exists once per Component. This is a constructor method for properties without a strictly defined object.""" # Depending on the property name, this routine will either # operate on the VCALENDAR container or on the inner VEVENT, # VTODO, or VJOURNAL if name in ["METHOD", "PRODID", "CALSCALE", "VERSION"]: comp = self else: comp = self.inner_component() curr_properties = comp.properties(name) # Get the value if value == None: if len(curr_properties) == 0: return None elif len(curr_properties) == 1: return curr_properties[0] else: raise ValueError, "too many properties of type %s" % propType # Set the value else: # Check if value is in enumerated_values if enumerated_values: value = string.upper(value) if value not in enumerated_values: raise ValueError, "%s is not one of %s" % (value, enumerated_values) # Create the new property if property_obj: if not isinstance(value, property_obj): # Create a special property_obj property if property_obj == Time: p = Time(value, name) ## p.value_type(value_type) elif property_obj == Duration: p = Duration(value) else: p = property_obj() ## p.value_type(value_type) p.value(value) else: p = value # value is already a property_obj else: # Create a generic property p = Property(name) ## p.value_type(value_type) p.value(value) if len(curr_properties) == 1: comp.remove_property(curr_properties[0]) elif len(curr_properties) > 1: raise ValueError, "too many properties of type %s" % propType comp.add_property(p)
class BFS(object): def __init__(self): self.visitedNodes = []; self.Time = Time(); self.limitTime = 100000; self.limitCost = 100000; def bfs_initState(self, graph, initState, initTime): startingNode = [] for i in range(0, len(graph)): if graph[i].departure == initState: startingNode.append(graph[i]); startingNode[-1] = self.Time.checkTime(startingNode[-1], initTime, self) return startingNode; def bfs_search(self, startingNode, soughtValue): stack = startingNode; while len(stack) > 0: for i in range(0, len(stack)): #This happens when there is no solution # if i >= len(stack): # return False; # print (i) # print (len(stack)) node = stack.pop(0) if node in self.visitedNodes: continue self.visitedNodes.append(node) if node.arrival == soughtValue: time = node.timeSpent; cost = node.cost; output = node.departure + ' ' + node.type + ' ' + node.arrival while node.departure != self.visitedNodes[0].departure: node = node.parent; cost = cost + node.cost output = node.departure + ' ' + node.type + ' ' + output output = output + ' ' + str(time) + ' ' + str(cost) return output for n in node.child: if n not in self.visitedNodes: n.parent = self.visitedNodes[-1]; stack.append(n) stack[-1] = self.Time.checkTime(stack[-1], n.parent.initTime, self) if stack[-1].visited: stack.pop(); continue; #We don't want to go back or do the same cities again if BFS.checkRepeated(self, n): stack.pop() return False def checkRepeated(self, n): check = False; for i in range(0, len(self.visitedNodes)): if (n.arrival == self.visitedNodes[i].departure) and (n.departure == self.visitedNodes[i].arrival): check = True; return check
def int_to_time(seconds): time = Time() minutes, time.second = divmod(seconds, 60) time.hour, time.minute = divmod(minutes, 60) return time
def main(): time = Time() time.hour = 11 time.minute = 59 time.second = 30 print_time(time) time1 = time time2 = Time() time2.hour = 11 time2.minute = 59 time2.second = 40 print_time(time1) print_time(time2) after = is_after(time1, time2) print(after) start = Time() start.hour = 9 start.minute = 45 start.second = 0 duration = Time() duration.hour = 1 duration.minute = 35 duration.second = 0 done = add_time2(start, duration) print_time(done)
def __init__(self,arg): Time.__init__(self,arg,"RDATE") class RDate_Period(Period):
def __init__(self,arg): Time.__init__(self,arg,"TRIGGER") class Trigger_Duration(Duration):
def __init__(self, dict={}): Time.__init__(self, dict) Property.name(self, 'RECURRENCE-ID')
# # Created: 11/09/10 # Modified: 11/09/10 # from Time import Time print "to_seconds(): " print "------------- " i = 1 while i <= 5: print i, "):" h = input("Number of initial hours: ") m = input("Number of initial minutes: ") s = input("Number of initial seconds: ") time1 = Time(h, m, s) print "Time ", time1, " to seconds: ", time1.to_seconds() i = i + 1 print print print "from_seconds(): " print "------------- " i = 1 while i <= 5: print i, "):" time2 = Time() s = input("Number of seconds: ") time2.from_seconds(s) print "From ", s, " seconds, time: ", time2 i = i + 1
def get_modified(self): return Time.getgmttime(self.rp.modified())
def get_mtime(self): t = Time() return t.getgmttime(self.rp.mtime())
def add_time(t1, t2): sum = Time() sum.hour = t1.hour + t2.hour sum.minute = t1.minute + t2.minute sum.second = t1.second + t2.second return sum
class A_star(object): def __init__(self): self.visitedNodes = []; self.Time = Time(); self.limitTime = 100000; self.limitCost = 100000; self.min = 'tempo'; def aStar_initState(self, graph, initState, initTime): startingNode = [] for i in range(0, len(graph)): if graph[i].departure == initState: startingNode.append(graph[i]); startingNode[-1] = self.Time.checkTime(startingNode[-1], initTime, self) return startingNode; def aStar(self, startingNode, soughtValue): stack = startingNode; solutions = []; while len(stack) > 0: for i in range(0, len(stack)): node = stack.pop(0) if node in self.visitedNodes: continue self.visitedNodes.append(node) if node.arrival == soughtValue: solutions.append(node); continue for n in node.child: if n not in self.visitedNodes: n.parent = self.visitedNodes[-1]; stack.append(n) stack[-1] = self.Time.checkTime(stack[-1], n.parent.timeSpent, self) if stack[-1].visited or A_star.checkRepeated(self, n): stack.pop(); #We don't want to go back or do the same cities again if not solutions: return False; else: node = A_star.checkMin(self, solutions, self.min); time = node.timeSpent; cost = int(node.cost); output = node.departure + ' ' + node.type + ' ' + node.arrival while node.departure != self.visitedNodes[0].departure: node = node.parent; cost = cost + int(node.cost) output = node.departure + ' ' + node.type + ' ' + output output = output + ' ' + str(time) + ' ' + str(cost) return output def checkRepeated(self, n): check = False; for i in range(0, len(self.visitedNodes)): if (n.arrival == self.visitedNodes[i].departure) and (n.departure == self.visitedNodes[i].arrival): check = True; return check def checkMin(self, graph, minimizing): if minimizing == 'tempo': timeSpent = graph[0].timeSpent; path = graph[0]; for node in graph: if node.timeSpent < timeSpent: path = node; return path if minimizing == 'custo': pathCost = graph[0].pathCost; path = graph[0]; for node in graph: if node.pathCost < pathCost: path = node; return path
### '(self)' is the OBJECT REFERENCE. All class methods must define this one parameter. It is used to gain access to the particular object's variables. ### The three variables all start with 'self', so Python knows that they belong the the 'self' object instead of being global variables. ## Methods Examples def set_time(self, hour, minute, second): self.hour = hour self.minute = minute self.second = second def print_time(self): print self.hour, ":", self.minute, ":", self.second #Creating Objects ## With the 'Time' example (see Time.py), done with a single line of code myTime1 = Time() ## When writing a class function you must ALWAYS start the parameter list with 'self' ## But when calling on a function, you always ignore 'self' (hence the blank parens) ## To call a function: myTime1.set_time(1, 2, 3) myTime1.print_time() ## SWEEEEEELLLLL #Modules ## Usually you don't define a class and create objects and stuff all in the same file. ## MODULES are other programs you wrote that can be imported (like a list of functions)
from Time import Time time = Time() print("The attributes of time are: ") print("time.hour: ", time.hour) print("time.minute: ", time.minute) print("time.second: ", time.second) print("\nCalling method printMilitary: ") time.printMilitary() print("\nCalling method printStandard: ") time.printStandard() print("\nChanging time's hour attribute in a lazy manner") time.hour = 25 print("\nCalling method printMilitary after alteration: ") time.printMilitary()
''' I will run at tempo, 7 minutes and 12 seconds per mile, determine the time I will get home. As before, assume that I will run the first and last miles at an easy pace of 8 minutes and 15 seconds per mile ''' from Time import Time h = input("Enter the hour of the start time: ") m = input("Enter the minute of the start time: ") s = 0 miles = input("Enter the number of miles I will run at tempo: ") start_time = Time(h, m, s) tempo = Time(0, 7, 12) total_tempo_seconds = tempo.to_seconds() * miles #tempo.from_seconds(total_tempo_seconds) pace = Time(0, 8, 15) total_pace_seconds = pace.to_seconds() * 2 #pace.from_seconds(total_pace_seconds) total_StartTime_seconds = start_time.to_seconds() finish_time = Time() finish_time.from_seconds(total_StartTime_seconds + \ total_pace_seconds + \ total_tempo_seconds) print "If I start at ", start_time, " and run ", miles, "\ miles at tempo, then I will be home at ", finish_time, ". "
def test_can_calculate_time_distance(self): t1 = Time(7) t2 = Time(8) self.assertEquals(t1.distance_to(t2), Hours(1))
class DFS(object): def __init__(self): self.visitedNodes = []; self.Time = Time() self.limitTime = 100000; self.limitCost = 100000; def dfs_initState(self, graph, initState, initTime): startingNode = [] for i in range(0, len(graph)): if graph[i].departure == initState: startingNode.append(graph[i]); startingNode[-1] = self.Time.checkTime(startingNode[-1], initTime, self) return startingNode; def dfs_search(self, startingNode, soughtValue): stack = startingNode; while len(stack) > 0: node = stack.pop() # print (node.departure) # print (node.arrival) #print ('here') if node in self.visitedNodes: continue self.visitedNodes.append(node) if node.arrival == soughtValue: time = node.timeSpent; cost = int(node.cost); output = node.departure + ' ' + node.type + ' ' + node.arrival while node.departure != self.visitedNodes[0].departure: node = node.parent; cost = cost + int(node.cost) output = node.departure + ' ' + node.type + ' ' + output output = output + ' ' + str(time) + ' ' + str(cost) return output for n in node.child: if DFS.checkIfInStack(self, n, stack): continue if n not in self.visitedNodes: n.parent = self.visitedNodes[-1]; stack.append(n) stack[-1] = self.Time.checkTime(stack[-1], n.parent.initTime, self) if stack[-1].visited: stack.pop(); continue; if DFS.checkRepeated(self, n): stack.pop() return False def checkRepeated(self, n): check = False; for i in range(0, len(self.visitedNodes)): if (n.arrival == self.visitedNodes[i].departure) and (n.departure == self.visitedNodes[i].arrival): check = True; return check def checkIfInStack(self, n, stack): check = False; if n in stack: check = True; return check