def __init__(self,name = "", type = "OTHER", last_pull_date = 0, value = 0.0, value_proj = 0.0, est_method = "", limit = 0.0, avail = 0.0, avail_proj = 0.0, rate = 0.0, payment = 0.0, due_date = None, sched_date = None, min_pay = 0.0, stmt_bal = 0.0, amt_over = 0.0, cash_limit = 0.0, cash_used = 0.0, cash_avail = 0.0): self.dateFormat = Date.get_global_date_format(self) self.dateSep = Date.get_global_date_sep(self) self.name = name if name != "": self.filename = self.name + ".qif" self.set_type(type) self.last_pull_date = last_pull_date self.limit = limit self.avail = avail self.avail_proj = avail_proj self.rate = rate self.payment = payment self.due_date = due_date self.sched_date = sched_date self.min_pay = min_pay self.value = value self.value_proj = value_proj self.est_method = est_method self.amt_over = amt_over self.stmt_bal = stmt_bal self.cash_limit = cash_limit self.cash_used = cash_used self.cash_avail = cash_avail self.transactions = TransactionList(self, limit) return
def readConfigFile(self, cfgFile): if cfgFile == "": d = wx.FileDialog(self, "", "", "", "*.cfg", wx.FD_OPEN) if d.ShowModal() == wx.ID_OK: fname = d.GetFilename() dir = d.GetDirectory() total_name_in = os.path.join(dir, fname) self.cfgFile = total_name_in else: self.cfgFile = cfgFile try: file = open(self.cfgFile, 'r') lines = file.readlines() self.dateFormat = lines.pop(0).replace('\n', '') Date.set_global_date_format(self, self.dateFormat) self.payType = lines.pop(0).replace('\n', '') in_ref_date = lines.pop(0).replace('\n', '') ref_date = Date.parse_date(self, in_ref_date, self.dateFormat) self.ref_date = ref_date["dt"] self.netpay = lines.pop(0).replace('\n', '') self.payDepositAcct = lines.pop(0).replace('\n', '') file.close() return True except: return False
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_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")
class Employee: """Employee class with Date attributes""" def __init__( self, firstName, lastName, birthMonth, birthDay, birthYear, hireMonth, hireDay, hireYear ): """Constructor for class Employee""" self.birthDate = Date( birthMonth, birthDay, birthYear ) self.hireDate = Date( hireMonth, hireDay, hireYear ) self.lastName = lastName self.firstName = firstName print "Employee constructor: %s, %s" \ % ( self.lastName, self.firstName ) def __del__( self ): """Called before Employee destruction""" print "Employee object about to be destroyed: %s, %s" \ % ( self.lastName, self.firstName ) def display( self ): """Prints employee information""" print "%s, %s" % ( self.lastName, self.firstName ) print "Hired:", self.hireDate.display() print "Birth date:", self.birthDate.display()
class FullscreenWindow: def __init__(self): self.tk = Tk() self.tk.configure(background='black') self.topFrame = Frame(self.tk, background='black') self.bottomFrame = Frame(self.tk, background='black') self.topFrame.pack(side=TOP, fill=BOTH, expand=YES) self.bottomFrame.pack(side=BOTTOM, fill=BOTH, expand=YES) self.state = False self.tk.bind("<Return>", self.toggle_fullscreen) self.tk.bind("<Escape>", self.end_fullscreen) # weather self.weather = Weather(self.topFrame) self.weather.place(x=0, y=5, anchor=NW, width=700, height=400) # Date self.date = Date(self.topFrame) self.date.place(x=1015, y=10, anchor=NE, width=350, height=90) # Day self.day = Day(self.topFrame) self.day.place(x=860, y=10, anchor=NE, width=300, height=90) # clock self.clock = Clock(self.topFrame) self.clock.place(x=940, y=60, anchor=NE, width=250, height=90) #Seconds self.sec = Sec(self.topFrame) self.sec.place(x=1015, y=60, anchor=NE, width=80, height=85) # news self.news = News(self.bottomFrame) self.news.pack(side=LEFT, anchor=S, padx=0, pady=10) # Facial rec #self.FacialRecognition = News(self.bottomFrame) #self.FacialRecognition.pack(side=LEFT, anchor=N, padx=100, pady=60) # calender self.calender = Calendar(self.topFrame) self.calender.place(x=1015, y=150, width=250, anchor=NE) # calender Time self.calenderTime = CalendarTime(self.topFrame) self.calenderTime.place(x=850, y=172, width=250, anchor=NE) #Traffic self.traffic = Traffic(self.topFrame) #Launch self.launch = Launch(self.topFrame) #crypto name self.crypto = Crypto(self.topFrame) self.crypto.pack(side=TOP, anchor=NE) #Crypto Time self.cryptoPrice = CryptoPrice(self.topFrame) self.cryptoPrice.pack(side=TOP, anchor=NE) #camera s = FacialRec() def toggle_fullscreen(self, event=None): self.state = not self.state # Just toggling the boolean self.tk.attributes("-fullscreen", self.state) return "break" def end_fullscreen(self, event=None): self.state = False self.tk.attributes("-fullscreen", False) return "break"
class Employee: """Employee class with Date attributes""" def __init__(self, firstName, lastName, birthMonth, birthDay, birthYear, hireMonth, hireDay, hireYear): """Constructor for class Employee""" self.birthDate = Date(birthMonth, birthDay, birthYear) self.hireDate = Date(hireMonth, hireDay, hireYear) self.lastName = lastName self.firstName = firstName print "Employee constructor: %s, %s" \ % ( self.lastName, self.firstName ) def __del__(self): """Called before Employee destruction""" print "Employee object about to be destroyed: %s, %s" \ % ( self.lastName, self.firstName ) def display(self): """Prints employee information""" print "%s, %s" % (self.lastName, self.firstName) print "Hired:", self.hireDate.display() print "Birth date:", self.birthDate.display()
class Person(object): """ Person Information """ def __init__( self, name = None, birth_date = None, death_date = None ): self.name = name self.birth_date = birth_date self.death_date = death_date def set_name( self, first_name, last_name ): self.name = Name( first_name, last_name ) def set_birth_date( self, birth_day, birth_month, birth_year ): self.birth_date = Date( birth_date, birth_month, birth_year ) def set_death_date( self, death_day, death_month, death_year ): self.death_date = Date( death_day, death_month, death_year ) def get_name( self ): return self.name def get_birth_date( self ): return self.birth_date def get_death_date( self ): return self.death_date def __str__( self ): return "{}, {}, {}".format( self.name.__str__(), self.birth_date.__str__(), self.death_date.__str__() )
def setControlInitValues(self): self.dateFormatRadioBox.SetSelection(self.dateFormatChoice) self.dateFormatRadioBox.Refresh() self.netPayTextCtrl.LabelText = self.netpay self.netPayTextCtrl.Refresh() ref_date_type = type(self.ref_date) if ref_date_type is str or ref_date_type is DateTime: ref_date_parsed = Date.parse_date( self, self.ref_date, Date.get_global_date_format(self)) ref_date = Date.convertDateFormat(self, ref_date_parsed, self.dateFormat, self.dateFormat) self.ref_date = ref_date self.refPayDatePicker.SetValue(ref_date["dt"]) self.refPayDatePicker.Refresh() self.refPayDateTextCtrl.LabelText = ref_date["str"] self.refPayDateTextCtrl.Refresh() else: self.MsgBox( "Unknown ref date type %s ignored - ref date intfo ignored" % (type(self.ref_date))) try: self.payDepositChoice = self.payment_accounts.index( self.payDepositAcct) except: self.payDepositChoice = -1 if self.payDepositChoice == -1: self.payDepositChoice = 0 self.MsgBox("Unknown payment account %s ignored - default to %s" % (self.payDepositAcct, self.payment_accounts[self.payDepositChoice])) self.payAcctCtrl.SetSelection(self.payDepositChoice) self.payAcctCtrl.Refresh() self.payTypeRadioBox.SetSelection(self.payType) self.payTypeRadioBox.Refresh()
def get_date_range(num_day): curr_date = datetime.date.today() date = Date(str(curr_date.year)+str(curr_date.month).zfill(2)+str(curr_date.day).zfill(2)) date_list = [] for i in range(0, num_day+1): date_list.append(date.substract_day(i)) return date_list
def __decrypt(self): tokens = Entry.__c.decrypt(self.__hash, Entry.userKey).split() if len(tokens) != 3: raise Exception("Decryption cannot be done") self.__text = Entry.__c.decrypt(tokens[0], Entry.__KEY) self.__date = Date(tokens[1]) self.__number = int(tokens[2]) self.__state = EntryState.DECRYPTED
def get_date_range(date_from, num_day): date = Date(str(date_from[0:4])+str(date_from[4:6]).zfill(2)+str(date_from[6:8]).zfill(2)) date_list = [] for i in range(0, num_day+1): new_date = date.substract_day(i) date_list.append(new_date[0:4] +'-'+ new_date[4:6] +'-'+ new_date[6:8]) return date_list
def basic_text(time=None, first_second=None, weekday=None, month=None, day=None, year=None): if not day: day = 1 if not time: return Date(year=year, month=month, day=day) if time: date = Date(year=year, month=month, day=day) return date._replace(hour=time.hour, minute=time.minute, second=time.second, am_pm=time.am_pm)
def get_date_range(num_day): curr_date = datetime.date.today() date = Date( '{}{}{}'.format(str(curr_date.year), str(curr_date.month).zfill(2), str(curr_date.day).zfill(2)) ) date_list = [] for i in range(0, num_day): date_list.append(date.substract_day(i)) return list(reversed(date_list))
def readMeetings(self): meetingfile = open(Path.meetingPath, 'r') for line in meetingfile: items = re.findall('"(.+?)"', line) if len(items) != 5: raise MyExcept.WrongFormat('Wrong File Format of ' + line) participators = items[1].split('&') self.meetings.add( Meeting(items[0], items[4], Date.stringToDate(items[2]), Date.stringToDate(items[3]), participators))
def __init__(self, stuNum, firstName, lastName, grades, date): self.studentNumber = stuNum self.firstName = firstName self.lastName = lastName self.grades = [] for grade in grades: self.grades.append(grade) #clone date for enrollDate instead of setting enrollDate = date self.enrollDate = Date() self.enrollDate.setDate(date.getMonth(),date.getDay(),date.getYear())
def calculateTprFprRate(self, evaluation, dataset, testSet) -> dict: date = Date() Logger.Info("Starting TPR/FPR calculations : " + str(date)) # trpFprRates = {} # we convert the results into a format that's more comfortable to work with classificationItems = self.getClassificationItemList( testSet, evaluation) # for (Prediction prediction: evaluation.predictions()) { # ClassificationItem ci = new ClassificationItem((int)prediction.actual(),((NominalPrediction)prediction).distribution()); # classificationItems.add(ci); # } # now we need to know what is the minority class and the number of samples for each class minorityClassIndex = dataset.getMinorityClassIndex() numOfNonMinorityClassItems = 0 #all non-minority class samples are counted together (multi-class cases) for cls in dataset.getNumOfRowsPerClassInTestSet().keys(): if cls != minorityClassIndex: numOfNonMinorityClassItems += dataset.getNumOfRowsPerClassInTestSet( )[cls] # sort all samples by their probability of belonging to the minority class classificationItems.sort( reverse=True, key=lambda x: x.getProbabilitiesOfClass(minorityClassIndex)) # Collections.sort(classificationItems, new ClassificationItemsComparator(minorityClassIndex)); # Collections.reverse(classificationItems); tprFprValues = {} tprFprValues[0.0] = 0.0 minoritySamplesCounter = 0 majoritySamplesCounter = 0 currentProb = 2 for ci in classificationItems: currentSampleProb = ci.getProbabilitiesOfClass(minorityClassIndex) # if the probability is different, time to update the TPR/FPR statistics if currentSampleProb != currentProb: tpr = minoritySamplesCounter / dataset.getNumOfRowsPerClassInTestSet( )[minorityClassIndex] fpr = majoritySamplesCounter / numOfNonMinorityClassItems tprFprValues[tpr] = fpr currentProb = currentSampleProb if ci.getTrueClass() == minorityClassIndex: minoritySamplesCounter += 1 else: majoritySamplesCounter += 1 tprFprValues[1.0] = 1.0 tprFprValues[1.0001] = 1.0 date = Date() Logger.Info("Done : " + str(date)) return tprFprValues
def __init__(self, firstName, lastName, birthMonth, birthDay, birthYear, hireMonth, hireDay, hireYear): self.birthDate = Date(birthMonth, birthDay, birthYear) self.hireDate = Date(hireMonth, hireDay, hireYear) self.lastName = lastName self.firstName = firstName print("Employee construction: %s, %s" % (self.lastName, self.firstName))
def __init__(self, firstName, lastName, birthMonth, birthDay, birthYear, hireMonth, hireDay, hireYear): """Constructor for class Employee""" self.birthDate = Date(birthMonth, birthDay, birthYear) self.hireDate = Date(hireMonth, hireDay, hireYear) self.lastName = lastName self.firstName = firstName print "Employee constructor: %s, %s" \ % ( self.lastName, self.firstName )
def queryMeetingTime(self, username, startTime, endTime): start = Date.stringToDate(startTime) end = Date.stringToDate(endTime) if end < start: raise MyExcept.InvalidDate('EndTime must be later') def overlap(meeting): return ( not (start > meeting.getEndDate() or end < meeting.startDate()) and meeting.isOne(username)) return self.storage.queryMeeting(overlap)
def __init__( self, firstName, lastName, birthMonth, birthDay, birthYear, hireMonth, hireDay, hireYear ): """Constructor for class Employee""" self.birthDate = Date( birthMonth, birthDay, birthYear ) self.hireDate = Date( hireMonth, hireDay, hireYear ) self.lastName = lastName self.firstName = firstName print "Employee constructor: %s, %s" \ % ( self.lastName, self.firstName )
def through_range(time=None, weekday1=None, weekday2=None, month=None, date=None, beginning=None): output = [] if month and date and beginning and weekday1: ending = Date(month=month, day=date) for day in range(beginning.day, ending.day + 1): temp = Date(month=month, day=day) if temp.weekday and temp.weekday in range(weekday1, weekday2 + 1): if time: output.append(temp.update(time)) else: output.append(temp) return output
def getContentOfCodechef(self): try: h=U.urlopen(self.codechefUrl) s=''.join(_ for _ in h.readlines()) x=B(s) p=x('table', {'class':'dataTable'})[0]('td') for i in xrange(0,len(p),4): data_objputData('codechef', p[i].text, p[i+1]('a')[0].text, Date.from_string(p[i+2].contents[0]), Time.from_string(p[i+2].contents[2]),Date.from_string(p[i+3].contents[0]),Time.from_string(p[i+3].contents[2])) p=x('table', {'class':'dataTable'})[1]('td') for i in xrange(0,len(p),4): data_obj.putData('codechef', p[i].text, p[i+1]('a')[0].text, Date.from_string(p[i+2].contents[0]), Time.from_string(p[i+2].contents[2]),Date.from_string(p[i+3].contents[0]),Time.from_string(p[i+3].contents[2])) except: print '502 Codechef not available!!!'
def miningBlock(self, higher): stringOfZeros = "0" * int(self.POW) d = Date() block = NodeMemory._get_new_hash(self, higher, self.POW, d.get_date(), '') # while stringHash not found if block[1].startswith(stringOfZeros): # On affiche un message print('New block mined with hash ' + block[2] + '\n' + block[0] + '\n') # Retourne l'ID du bloc miné return block[2] return False
def properties(self, *args): dateFormat = Date.get_global_date_format(self) ref_date_parsed = Date.parse_date(self, self.ref_date, dateFormat) if ref_date_parsed != None: ref_date_dt = ref_date_parsed["dt"] ref_date = wx.DateTime.FromDMY(ref_date_dt.day, ref_date_dt.month, ref_date_dt.year).Format(dateFormat) else: ref_date = "" # For now to test! JJG 08/06/2021 frame = PropertyFrameWithForm(self, self.dateFormat, self.payType, ref_date, self.netpay, self.payDepositAcct) frame.Show()
def generate_dates(file_name): with open(file_name, 'w', encoding='utf-8') as file: for i in range(1, number_of_dates): date = faker.date_this_century() year = str(date)[:4] month = str(date)[5:-3] day = str(date)[-2:] date = Date(i, date, year, month, day) dates.append(date) file.write(date.csv_format()) if i != number_of_dates: file.write('\n')
def getAvailableTimes(self, with_faultcode=False): dss = self.getAllDailySchedule() available_times = [] now = Date() now.setFromDateTime(datetime.today()) for ds in dss: srvtimes = ds.getServiceTimes() for srvtime in srvtimes: avl = srvtime.getAccessibility() _type = srvtime.getType() if avl and ((_type != DateType.special) or with_faultcode) and \ (now < srvtime.getDate()): available_times.append(srvtime) return available_times
def main(): name = input() month = int(input()) day = int(input()) year = int(input()) # d1=Date() s1 = Student("John", Date(6, 1, 1999), 90) s2 = Student("Marry", Date(10, 8, 1997), 80) s1.setName(name) s2.setDate(month, day, year) s1.toString() s2.toString()
def voidentry(self, *args): index = self.cbgrid.GetGridCursorRow() if index < 0: return d = wx.MessageDialog(self, "Really void this transaction?", "Really void?", wx.YES_NO) if d.ShowModal() == wx.ID_YES: self.edited = 1 transaction = self.cur_transaction[index] today = Date() transaction.amount = 0 transaction.payee = "VOID: " + transaction.payee transaction.memo = "voided %s" % today.formatUS() self.redraw_all(index) # redraw only [index:] return
def main(): website = Mongodb(settings['MONGODB_CRAWLER_SITE']) articles_list = Mongodb(settings['MONGODB_ARTICLES_LIST']) url_md5 = Mongodb(settings['MONGODB_ARTICLES_LIST_URL_MD5']) cache = RedisFactory() init = Init() _, dynamic_sites = website.find_sites() # 获取动态站点 for site in dynamic_sites: print site response = Webservice.dynamic_wget(site) # 动态站点下载 insert_articles_site(response, site) # 存储该站点源码 website_timestamp = website.get_site_timestamp(site) # 站点更新时间 print 'website_timestamp',Date.timestamp_to_str(website_timestamp) articles = parse(site, website_timestamp, response) # 分析站点数据 website.update_website(site, articles[0]['created']) # 更新最新的更贴时间 lxd更改为【‘created’】 print '-----------------------------------------------' print articles for _article in articles: if not cache.hexist(settings['REDIS_MAP'], _article['url']): print _article articles_list.collection.insert(dict(_article)) # 存储文章列表页信息 print cache.hset(settings['REDIS_MAP'], _article['url'], init.get_md5(_article['url']))
def set_due_date(self, rest): if rest != None: if type(rest) is str: if len(rest) != 0 and rest != "": try: [year, month, day] = Date.get_date_fields(self, rest) self.due_date = wx.DateTime.FromDMY(day, month-1, year).Format(self.dateFormat) except: error = "Invalid due_date entered: %s - try again!" % (rest) Date.MsgBox(self.parent.get_transaction_frame(), error) else: self.due_date = None elif type(rest) is dict: self.due_date = wx.DateTime.FromDMY(rest['day'], rest['month'], rest['year']).Format(self.dateFormat) else: self.due_date = wx.DateTime.FromDMY(rest.day, rest.month-1, rest.year).Format(self.dateFormat)
def __init__(self, parent): self.parent = parent self.dateFormat = Date.get_global_date_format(self) self.dateSep = Date.get_global_date_sep(self) self.pmt_method = None self.check_num = None self.payee = None self.amount = None self.action = None self.current_value = None self.sched_date = None self.due_date = None self.state = OUTSTANDING self.prev_state = UNKNOWN self.comment = None self.memo = None
def _prepare_parms( parent, rec=None, inv=None ): parms = [] if rec: for i in range( parent.NF ): parms.append( parent.fmt_field(rec,i) ) else: for i in range(parent.NF): if i==0: parms.append( inv and str(inv) or "" ) elif i==1 or i==5: # today or due-date d = Date() # today if i==5: d += 30 parms.append( d.format("%a") ) else: parms.append( i==6 and ST_PENDING or ST_NORMAL ) return parms
def get_date_from_timestamp(self, timestamp): year = int(timestamp[0:4]) month = int(timestamp[4:6]) day = int(timestamp[6:8]) hour = int(timestamp[8:10]) minute = int(timestamp[10:12]) return Date(year, month, day, hour, minute)
def main(): kati = Date() strKB = str(kati.getMonth()) + "/" + str(kati.getDay()) strKB = strKB + "/" + str(kati.getYear()) print strKB kati.setDate(20, 45, -15) print print kati kati.setDate(13, 29, 1990) print print kati
def __init__(self, firstname, lastname, date): self.Firstname = firstname self.Lastname = lastname if isinstance(date, Date): self.Birthday = date else: self.Birthday = Date()
def get_date_from_edit_page_entry(self, entry): entry = self.cut_off_what_is_no_date(entry) year = self.get_year(entry) month = self.get_month(entry) day = self.get_day(entry) hour = self.get_hour(entry) minute = self.get_minute(entry) return Date(year, month, day, hour, minute)
def __init__(self): self.date = Date() self.number = None self.payee = None self.cleared = 0 self.comment = None self.memo = None self.amount = None
def main(): date = Date() date.setDate(12, 28, 2000) scores = [90, 93] chad = Student(1, "Chad", "Williams", scores, date) chad.addGrade(93) chad.addGrade(89) chad.addGrade(97) print (chad.getName() + "'s grades are: " + str(chad.getGrades())) print ("Average: " + str(chad.calcAvg())) date.setDate(3,20,2000) scores.append(42) brad = Student(2, "Brad", "Smith", scores, date) print () print (str(brad)) print ("\n" + str(chad)) print ("\nIn main scores = " + str(scores))
def parse(site, website_timstamp, response): page = etree.HTML(response) entries = page.xpath('//div[@class="entryContainer"]') articles = [] for i in xrange(0,len(entries)): print i _item = ArticleListItem() title = entries[i].xpath('//div[@id="entry-title"]//h1[@class="entryTitle"]//a')[i].text url = entries[i].xpath('//div[@id="entry-title"]//h1[@class="entryTitle"]//a')[i].attrib['href'] img = entries[i].xpath('//div[@class="entryMeta"]//img')[i] headImg = img.attrib['src'] author_time = entries[i].xpath('//div[@class="entryMeta"]//span')[i].text.split('|') author = author_time[0].strip() created = author_time[1].strip() abstract = entries[i].xpath('//div[@class="blog_description"]')[i].text.strip() _item['title']=title _item['author']=author _item['headImg']=headImg _item['abstract']=abstract _item['url']=url _item['site']=site _item['isContentDownload']=False _item['created']=created articles.append(_item) cur = Date.str_to_timestamp(created) if website_timstamp >= cur: # 比较当前抓取的列表页更帖的时间与上一次该站点最新更帖时间 print articles print '=================================cur',Date.timestamp_to_str(cur),'website_timestamp',Date.timestamp_to_str(website_timstamp) return articles print '========================================' print articles print '========================================' return articles
class Employee(): """Documentation for Employee """ def __init__(self, firstName, lastName, birthMonth, birthDay, birthYear, hireMonth, hireDay, hireYear): self.birthDate = Date(birthMonth, birthDay, birthYear) self.hireDate = Date(hireMonth, hireDay, hireYear) self.lastName = lastName self.firstName = firstName print("Employee construction: %s, %s" % (self.lastName, self.firstName)) def __del__(self): print("Employee object about to be destroyed: %s, %s" % (self.lastName, self.firstName)) def display(self): print ("%s, %s\nHired:%s\nBirth Date:%s\n" % (self.lastName, self.firstName, self.hireDate.display(), self.birthDate.display()))
def parse(self, response): for x in xrange(1,11): _item = ArticleListItem() _item['title'] = response.xpath(Css.IBMBIGDATAHUB[x]['title']).extract()[0] _item['author'] = response.xpath(Css.IBMBIGDATAHUB[x]['author']).extract()[0] if response.xpath(Css.IBMBIGDATAHUB[x]['headImg']).extract() == []: _item['headImg'] = 'no img' else: _item['headImg'] = response.xpath(Css.IBMBIGDATAHUB[x]['headImg']).extract()[0] _item['abstract'] = response.xpath(Css.IBMBIGDATAHUB[x]['abstract']).extract()[0] _item['url'] = Css.IBMBIGDATAHUB['baseurl'] + response.xpath(Css.IBMBIGDATAHUB[x]['url']).extract()[0] _item['site'] = response.url _item['isContentDownload'] = False _item['created'] = Date.get_standard_time(response.xpath(Css.IBMBIGDATAHUB[x]['created']).extract()[0]) yield _item
def time_expression(Hour=None, Minute=None, Second=None, AMPM=None, SpecialTimeText=None): if SpecialTimeText: if SpecialTimeText.lower() == "noon": return Date(hour=12) if SpecialTimeText.lower() == "midnight": return Date(hour=0) d = Date() if Hour: d = d._replace(hour=int(Hour)) if Minute: d = d._replace(minute=int(Minute)) if Second: d = d._replace(second=int(Second)) if AMPM is not None: if d.hour: if noon(d.hour, AMPM): d = d._replace(hour=12) elif midnight(d.hour, AMPM): d = d._replace(hour=0) else: d = d._replace(hour=d.hour + AMPM) d = d._replace(am_pm=AMPM) if (d.hour, d.minute, d.second) != (None, None, None): return d
def get_site_timestamp(self, site): for site in self.collection.find({"url":site}): return Date.str_to_timestamp(site['updated'])
def main(): scotts = Date() print scotts scotts.setDate(3,30,1995) print "Scott: " + str(scotts) print averys = Date() print "Avery: " + str(averys) averys.setDate(4, 31, 2000) print "Avery: " + str(averys) averys.setDate(2, 29, 2008) print "Avery: " + str(averys) averys.setDate(2, 29, 2009) print "Avery: " + str(averys) averys.setDate(14, 29, 2008) print "Avery: " + str(averys) averys.setDate(11,13,2009) print "Avery: " + str(averys)
class Transaction: def __init__(self): self.date = Date() self.number = None self.payee = None self.cleared = 0 self.comment = None self.memo = None self.amount = None def __str__(self): lines = [] lines.append("%10s " % self.date.formatUS()) if self.number: lines.append("%5d " % self.number) else: lines.append(" ") lines.append("%-20s " % string_limit(self.payee, 20)) if self.cleared: lines.append("x ") else: lines.append(" ") if self.comment: lines.append("%-10s " % string_limit(self.comment, 10)) else: lines.append(" ") if self.memo: lines.append("%-10s " % string_limit(self.memo, 10)) else: lines.append(" ") lines.append("%8.2f " % self.amount) return ''.join(lines) def __cmp__(self, other): return cmp(self.date, other.date) def qif_repr(self): lines = [] lines.append("D%s" % self.date.formatUS()) lines.append("T%.2f" % self.amount) if self.cleared: lines.append("Cx") else: lines.append("C*") if self.number: lines.append("N%d" % self.number) lines.append("P%s" % self.payee) if self.comment: lines.append("L%s" % self.comment) if self.memo: lines.append("M%s" % self.memo) lines.append("^") return '\n'.join(lines) def setamount(self, rest): self.amount = float(rest.strip().replace(',', '')) def setdate(self, rest): self.date = Date(rest) def setpayee(self, rest): self.payee = rest def setcomment(self, rest): self.comment = rest def setmemo(self, rest): self.memo = rest def setnumber(self, rest): val = rest.strip() if val: self.number = int(val) else: self.number = None return def setcleared(self, rest): if rest[0] == "x": self.cleared = 1 else: self.cleared = 0 return def getpayee(self): return self.payee def getamount(self): return self.amount
def setdate(self, rest): self.date = Date(rest)
def setEnrollDate(self, date): self.enrollDate = Date() self.enrollDate.setDate(date.getDay(),date.getMonth(),date.getYear())
#!/usr/bin/python import sys ## change this path to where Date.py load_path = '/home/vladimir/programming/py/oop/' if __name__ == '__main__': if not load_path in sys.path: sys.path.append(load_path) from Date import Date d1 = Date() d1.setYear(2015) d1.setMonth(11) d1.setDay(19) print d1.toMDYString() d2 = Date() Date.setYear(d2, 2015) Date.setMonth(d2, 11) Date.setDay(d2, 19) print d2.toYMDString()
def main(): d1 = Date () d1.setDate(8,15,2006) d2 = Date() d2.setDate(5, 12, 2000) d3 = Date() d3.setDate(12, 1, 2004) d4 = Date() d4.setDate(3, 9, 2007) chad = Student("Tenessee", "Williams", [90, 93], d1) chad.addGrade(93) chad.addGrade(89) chad.addGrade(97) print (chad.getName() + "'s grades are: " + str(chad.getGrades())) print ("Average: " + str(chad.calcAvg())) brad = Student("Bob", "Marley", [95, 90, 92],d2) print () print (str(brad)) #What is this printing? csci220 = [] csci220.append(chad) csci220.append(brad) csci220.append(Student("Diana", "Ross", [],d3)) csci220.append(Student("Peter", "Townsend", [87, 92, 98, 94, 92],d4)) for student in csci220: print () print (student) print () for i in range (len(csci220)): compare = csci220[1].getEnrollDate().compareTo(csci220[i].getEnrollDate()) if compare == 0: print (csci220[1].getName() + " enrolled the same day as " + csci220[i].getName()) elif compare > 0: print (csci220[1].getName() + " enrolled after " + csci220[i].getName()) else: print (csci220[1].getName() + " enrolled before " + csci220[i].getName())
class Student: def __init__(self,firstName,lastName,grades,date): self.setName(firstName, lastName) self.setGrades(grades) self.setEnrollDate(date) ## self.firstName = firstName ## self.lastName = lastName ## self.grades = [] ## for grade in grades: ## self.grades.append(grade) ## #clone date for enrollDate instead of setting enrollDate = date ## self.enrollDate = Date() ## self.enrollDate.setDate(date.getMonth(),date.getDay(),date.getYear()) def getName(self): return self.firstName + " " + self.lastName def getFirst(self): return self.firstName def getLast(self): return self.lastName def getGrades(self): return self.grades def getEnrollDate(self): return self.enrollDate def setName(self, first, last): self.firstName = first self.lastName = last def setGrades(self, grades): self.grades = [] for grade in grades: self.grades.append(grade) def setEnrollDate(self, date): self.enrollDate = Date() self.enrollDate.setDate(date.getDay(),date.getMonth(),date.getYear()) def addGrade(self, grade): self.grades.append(grade) def calcAvg(self): total = 0 for grade in self.grades: total = total + grade count = len(self.grades) if count == 0: avg = -1 else: avg = total / count return avg def __str__(self): out = "Student: " + self.getName() out = out + "\nEnroll Date: " + str(self.getEnrollDate()) out = out + "\nGrades: " + str(self.getGrades()) out = out + "\nAverage: " + str(self.calcAvg()) return out
#!/usr/bin/python import sys ## change this path to where Date.py is defined. load_path = '/home/vladimir/programming/py/oop/' if __name__ == '__main__': if not load_path in sys.path: sys.path.append(load_path) from Employee import Employee from Date import Date hire_date = Date() hire_date.setMonth(10) hire_date.setDay(10) hire_date.setYear(2010) emp = Employee() emp.setFirstName('John') emp.setLastName('Nicholson') emp.setHireDate(hire_date) print 'First Name: ' + emp.getFirstName() print 'Last Name: ' + emp.getLastName() print 'Hire Date: ' + emp.getHireDate().toMDYString()
def main(): roll = RollBook("CSCI220", "Programming I", "Spring 2008") print ("When roll book is empty...") print (roll) print ("Class Average:", roll.classAverage()) print ("\n*************************\n") d1 = Date () d1.setDate(8,15,2006) stu1 = Student(923, "Tenessee", "Williams", [90, 93], d1) roll.addStudent(stu1) d2 = Date() d2.setDate(5, 12, 2000) stu2 = Student(834, "Bob", "Marley", [95, 90, 92], d2) roll.addStudent(stu2) d3 = Date() d3.setDate(12, 1, 2004) stu3 = Student(745, "Diana", "Ross", [], d3) roll.addStudent(stu3) d4 = Date() d4.setDate(3, 9, 2007) stu4 = Student(656, "Peter", "Townshend", [87, 92, 98, 94, 92], d4) roll.addStudent(stu4) print (roll) ## print "*************************\n" ## ## print roll.displayCourseInfo() ## print roll.displayStudent(923) ## print ## print roll.displayStudent(834) ## print ## print roll.displayStudent(999) ## print ## print roll.displayStudent(745) ## print ## print roll.displayStudent(656) ## print ## ## roll.addGrade(923, 93) ## roll.addGrade(923, 89) ## roll.addGrade(923, 97) ## print "After adding grades 93, 89, 97 to student 123:" ## ## print roll.displayStudent(923) ## print print ("Class Average:", roll.classAverage()) print ("\n*************************\n") print ("Sorted by student ID") roll.sortStudentsByID() print (roll) print ("\n*************************\n") print ("Sorted by date of enrollment") roll.sortStudentsByEnrollDate() print (roll)
from Date import Date a = Date(4, 7, 1999) b = Date(5, 6, 2000) c = Date(12, 2, 2014) a.display() b.display() c.display()