def test_get_leap_years(): empty = [] result = get_leap_years(empty) print_test('test_get_leap_years', result == []) d1LeapYear = dt.Date(1, 1, 2008) d2LeapYear = dt.Date(3, 23, 2000) d0NotLeapYear = dt.Date(3, 23, 2009) d1NotLeapYear = dt.Date(1, 1, 1582) d2NotLeapYear = dt.Date(3, 23, 1900) all_leap_years = [d1LeapYear, d2LeapYear] result = get_leap_years(all_leap_years) print_test('test_get_leap_years', result == [d1LeapYear, d2LeapYear]) no_leap_years = [d0NotLeapYear, d1NotLeapYear, d2NotLeapYear] result = get_leap_years(no_leap_years) print_test('test_get_leap_years', result == []) some_leap_years = [ d0NotLeapYear, d2LeapYear, d1NotLeapYear, d2NotLeapYear, d1LeapYear ] result = get_leap_years(some_leap_years) print_test('test_get_leap_years', result == [d2LeapYear, d1LeapYear])
def test_is_before(): d1a = dt.Date(3, 23, 2018) d1Same = dt.Date(3, 23, 2018) d1Before1a = dt.Date(3, 23, 2017) d2Before1a = dt.Date(2, 23, 2018) d3Before1a = dt.Date(3, 22, 2018) d1After1a = dt.Date(3, 24, 2018) d2After1a = dt.Date(4, 22, 2018) d3After1a = dt.Date(4, 22, 2019) d4After1a = dt.Date(2, 24, 2019) d5After1a = dt.Date(2, 21, 2019) print_test('test_is_before- different objects, equal dt.Date', not (d1Same.is_before(d1a))) print_test('test_is_before - different objects, equal dt.Date', not (d1a.is_before(d1Same))) print_test('test_is_before - year is before', d1Before1a.is_before(d1a)) print_test('test_is_before - month is before', d2Before1a.is_before(d1a)) print_test('test_is_before - day is before', d3Before1a.is_before(d1a)) print_test('test_is_before - day is after', not (d1After1a.is_before(d1a))) print_test('test_is_before - month is after', not (d2After1a.is_before(d1a))) print_test('test_is_before - year is after, day is not', not (d3After1a.is_before(d1a))) print_test('test_is_before - year is after, month is not', not (d4After1a.is_before(d1a))) print_test('test_is_before - year is after, month and day are not', not (d5After1a.is_before(d1a)))
class Event(): title = "" start = Date(0,0,0,0) #fix later about end = Date(0,0,0,0) def __init__(self, titleEvent, startDate, endDate): self.title = titleEvent self.start = startDate self.end = endDate
def test_get_years(): empty = [] result = get_years(empty) print_test('test_get_years empty', result == []) d0 = dt.Date(2, 23, 2011) d1 = dt.Date(3, 23, 1900) d2 = dt.Date(3, 23, 2009) d3 = dt.Date(2, 23, 2010) dt.Dates4 = [d0, d1, d2, d3] result = get_years(dt.Dates4) print_test('test_get_years not empty', result == [2011, 1900, 2009, 2010])
def news_spider(stock_ticker_symbol, date_from, date_to): """ Given the stock ticker symbol and the date range within which the article should have been published, returns the textual content of all such articles """ text_list = [] # initialize a text variable to store all the news articles is_incomplete = False current_date = Date.Date(date_from) # create the necessary Date objects target_date = Date.Date(date_to) while current_date.is_earlier(target_date) and not is_incomplete: # as long as the Date is within the range # create the specific url and there is not yet a single date that does not have news articles try: url = BASE_URL + stock_ticker_symbol + "&t=" + current_date.url_format() source_code = requests.get(url) # visit the website and get the source code plain_text = source_code.text # convert the source code into plain text # store all the code into a Beautiful Soup object soup = BeautifulSoup(plain_text, "html.parser") # get the part of the source code that contains the news news_box = soup.find("div", attrs={"class": "mod yfi_quote_headline withsky"}) h3 = news_box.find("h3") # find the first date heading of the page # if the current date is the date in the heading if current_date.news_heading_format() in h3.string: print(h3.string) print("Crawling...") date_ul = news_box.find("ul") # find the box of links to the news articles news_ul = date_ul.find_next("ul") # for every link in the list for link in news_ul.findAll("a"): # extract the href which is essentially the link href = str(link.get("href")).split("*")[-1] # extract all the text in that website and store it text_list.append(extract_text(href)) else: is_incomplete = True # if the date is not in the heading, there must be missing news current_date.advance_date() # go to the next day except Exception as error_message: # handle connection errors print(error_message) print("Connection Error - Retrying in " + str(RETRY_PERIOD) + " seconds...") time.sleep(RETRY_PERIOD) # retry in 60 seconds if faced with a connection error if is_incomplete: # if there is missing news if len(text_list) > 0: # if there is news so far final_text = text_list[0] # obtain the news associated with the first date only else: # if there is no news final_text = "" # store the null string as the final text to be returned else: # if the news is complete # return the text of all the news articles crawled so far final_text = format_text.join_words(text_list, DELIMITER) return final_text, is_incomplete # return the final text and the status of the news, i.e. complete/incomplete
def load_data(attacks: []) -> int: try: with open('/home/tzdybel/PycharmProjects/projekt2/Project2/globalterrorismdb.csv', 'r', encoding="ISO-8859-1") as csvfile: print("Loading data...") reader = csv.reader(csvfile, delimiter=',') for row in reader: if row[3] == 'iday': continue try: attkres = ar.AttackResult(bool(row[26]), bool(row[27]), int(row[98]), int(row[101])) except ValueError: attkres = ar.AttackResult(bool(row[26]), bool(row[27]), 0, 0) date = d.Date(int(row[3]), int(row[2]), int(row[1])) place = p.Place(row[12], row[8], getTypeFromEnum(int(row[9]), p.Region)) attkdet = ad.AttackDetails(getTypeFromEnum(int(row[28]), ad.AttackType), getTypeFromEnum(int(row[34]), ad.TargetType), getTypeFromEnum(int(row[81]), ad.WeaponType), row[64]) attack = att.Attack(date, place, attkdet, attkres) attacks.append(attack) except FileNotFoundError: print("File name is invalid") # exit(1) print("Loaded " + len(attacks).__str__() + " records!") return len(attacks)
def __init__(self, date_of_birth, citizenship="Russian Federation"): super().__init__() d = Date.Date(date_of_birth) self.date_of_birth = d #self.age = time.time() #datetime.date self.citizenship = citizenship
def day_of_the_week(date): ddate = Date.Date() year, month, dayofm = utils.split_date_string(date) ddate.year = year ddate.month = month ddate.day = dayofm return ddate.weekday()
def parser(): date = input("Choose data (hh:mm dd.mm.yyyy): ") hour = date[:2] if hour[0] == '0': hour = hour[1] minute = date[3:5] if minute[0] == '0': minute = minute[1] day = date[6:8] if day[0] == '0': day = day[1] month = date[9:11] if month[0] == '0': month = month[1] year = date[12:16] try: if not date[2] == ':': print("':' must occur as 3 char of input") exit() if not date[5] == ' ': print("' ' must occur as 6 char of input") exit() if not date[8] == '.': print("'.' must occur as 9 char of input") exit() if not date[11] == '.': print("'.' must occur as 12 char of input") exit() if not len(year) == 4: print("Invalid year") except IndexError: print("Index out of range") exit() if not all(hour.isdigit() for i in hour): print("Invalid hour") exit() if not all(minute.isdigit() for i in minute): print("Invalid minute") exit() if not all(day.isdigit() for i in day): print("Invalid day") exit() if not all(month.isdigit() for i in month): print("Invalid month") exit() if not all(year.isdigit() for i in year): print("Invalid year") exit() try: date_object = Date.Date(int(hour), int(minute), int(day), int(month), int(year)) except ValueError: print("Invalid entered date. Try again") exit() return date_object
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 toDate(thing): """ ensures that a date is a Date object """ if isinstance(thing, Date): return thing else: return Date(thing)
def prompt(): month = (int(input("enter month or enter 0 to quit"))) if (month == 0): return None else: day = int(input("Enter date:")) year = int(input("Enter the year ")) return Date(month, day, year)
def loadDates(self): month = input("Please enter the starting month (i.e January): ") day = int(input("Please enter the starting day (i.e 25): ")) hour = int(input("Please enter the starting hour: ")) am = input(str(hour) + " AM or " + str(hour) + "PM? (am/pm) ") minute = int(input("Please enter the starting minute: ")) if (am.lower() == "pm"): hour += 12 self.date = Date.Date(month, day, hour, minute)
def birthdays(bdaylist): bList = [] d = 0 for bday in open('birthdays.txt'): bd = bday.replace(' ', ', ') b1, b2, b3 = bd.split(',') d = Date(int(b1), int(b2), int(b3)) bList.append(d) return bList
def performOn(self): ''' This method uses the date and the hour of the (self) client to create a Date object with the date and the hour when the task should be performed. Returns: Date -- The date and hour when the task should be performed. ''' return Date(self.date, self.hour)
def setTask(lstTask): taskInf = input("title,date,subtitle>>>") lstTaskInf = re.split('\s', taskInf) title = "" subtitle = "" month = "00" day = "00.datetime" hour = "00" if (len(lstTaskInf) == 2): title = lstTaskInf[0] date = lstTaskInf[1] if (date == "today"): now = datetime.datetime.now() month = str(now.month) day = str(now.day) elif (len(date) == 4): month = date[:2] day = date[2:4] elif (len(date) == 6): month = date[:2] day = date[2:4] hour = date[4:6] else: print("日にちの形式が不正です") time.sleep(1) return elif (len(lstTaskInf) == 3): title = lstTaskInf[0] date = lstTaskInf[1] subtitle = lstTaskInf[2] if (date == "today"): now = datetime.datetime.now() month = str(now.month) day = str(now.day) elif (len(date) == 4): month = date[:2] day = date[2:4] elif (len(date) == 6): month = date[:2] day = date[2:4] hour = date[4:6] else: print("日にちの形式が不正です") time.sleep(1) return else: print("不正な入力です") time.sleep(1) return cdate = Date.Date(month, day, hour) task = Task.Task(cdate, title, subtitle) lstTask.append(task)
def __init__(self, filename=None, month=None, day=None, time=None, minute=None): self.filename = filename if ((month != None) and (day != None) and (time != None) and (minute != None)): self.date = Date.Date(month, day, time, minute) else: self.date = None
def update(self): ''' This method updates the current instance of the catalog. Creates an instance of Date with the experts catalog header and updates it in 30 minutes then updates the experts catalog and gets the header to create the tasks catalog header changing the word 'Experts' to 'Schedule'. Finally it gets the experts catalog file name and sets it to the tasks catalog file name replacing the word 'experts' with 'schedule'. ''' newDate = Date(self.experts.header[1], self.experts.header[3]) newDate.update(30) self.experts.update(newDate) for line in self.experts.header: self.header.append(line) self.header[6] = 'Schedule:' self.fileName = self.experts.fileName.replace('experts', 'schedule')
def getAll(id, subject_name): cursor = DB.cursor() forSubject = "select * from user" + str(id) + " where subject = '" + str( subject_name[0]) + "'" cursor.execute(forSubject) all = cursor.fetchall() response = [] for subject in all: response.append( Date.Date(subject[0], subject[1], subject[2], subject[3], subject[4], subject[5], subject[6])) cursor.close() return response
def getInPeriod(id, date1, date2): cursor = DB.cursor() period = "select * from user" + str( id) + " where date_created >= '" + str( date1) + "' AND date_created <= '" + str(date2) + "'" cursor.execute(period) all = set(cursor.fetchall()) response = [] for data in all: response.append( Date.Date(data[0], data[1], data[2], data[3], data[4], data[5], data[6])) cursor.close() return response
def main(): today = Date() print(today) today.setDate(4, 16, 2012) print(today) today.setDate(2, 29, 1997) print(today) print("Month = " + str(today.getMonth())) print("Day = " + str(today.getDay())) print("Year = " + str(today.getYear())) today.setDate(12, 8, 1200) print(today) today.setDate(13, 8, 2012) print(today)
def getUntillDeadline(id, deadline): cursor = DB.cursor() print(deadline[0]) tasks = "select * from user" + str(id) + " where deadline <= '" + str( deadline[0]) + "' AND is_complete = '0'" cursor.execute(tasks) all = cursor.fetchall() response = [] for data in all: response.append( Date.Date(data[0], data[1], data[2], data[3], None, None, data[6])) cursor.close() print(response) return response
def getLastMonth(id): cursor = DB.cursor() lastmonth = "select * from user" + str( id ) + " where date_created between CURDATE()-INTERVAL 30 DAY and CURDATE()" cursor.execute(lastmonth) all = cursor.fetchall() response = [] for data in all: response.append( Date.Date(data[0], data[1], data[2], data[3], data[4], data[5], data[6])) cursor.close() print(response) return response
def draw(self, wfd, wnm, wny, dates, start_bar, numbars, dvl): oldmonth = 0 oldyear = 0 d = Date.Date() for i in xrange(start_bar, start_bar + numbars): year, month, day = _split_date_string(dates[i]) if oldmonth == 0: oldmonth = month if oldyear == 0: oldyear = year d.year, d.month, d.day = year, month, day if day == 1 or month > oldmonth or year > oldyear: wnm(Months[month] + str(year), i) dvl(i) oldmonth = month oldyear = year
def availableOn(self): ''' This method uses the date and the hour of the (self) expert to create a Date object with the date and the hour when the expert is available. Considering that an expert is only available 1 hour (60 minutes) after his last task is completed and a task that has to be started in the next day, starts at 8h00. Returns: Date -- The date and hour when the expert is available. ''' available = Date(self.date, self.hour) d = available.as_dict() if int(d['hours']) == 19: available.update(60 - int(d['min'])) else: available.update(60) return available
def isolateDate(i): dateList = i["date"].split(" ") month = dateList[0] day = dateList[1] timeStr = i["time"].split(" ")[0] am = i["time"].split(" ")[1] timeList = timeStr.split(":") hour = timeList[0] minute = timeList[1] if (am == "AM"): hour = int(hour) else: hour = int(hour) + 12 minute = int(minute) day = int(day) dateObj = Date.Date(month, day, hour, minute) return dateObj
class Task: cdate = Date.Date(00, 00, 00) title = "" subtitle = "" def __init__(self, cdate, title, subtitle=""): self.cdate = cdate self.title = title self.subtitle = subtitle def getTaskInf(self): date = self.cdate.getDate() strTaskInf = self.title + ":" + date + ":" + self.subtitle return strTaskInf def getTask(self): strTask = self.title + "," + self.cdate.month + self.cdate.day + self.cdate.hour + "," + self.subtitle return strTask
class Etudiant: nom = "" prenom = "" address = "" age = 0 date_naissance = Date(0, 0, 0) def __init__(self, nom, prenom, date_naissance): self.nom = nom self.prenom = prenom self.date_naissance = Date(date_naissance) self.addressmail() self.makeAge() def addressmail(self): self.address = self.nom.lower().replace(" ", "") + '.' + self.prenom.lower().replace(" ", "") + "@etu.univ-tours.fr" # TODO. def makeAge(self): today = date.today() self.age = today.year - self.date_naissance.annee if(self.date_naissance.mois == today.month): if(self.date_naissance.jour < today.day): self.age -= 1 elif(self.date_naissance.mois < today.month): self.age -= 1 def getNom(self): return self.nom def getPrenom(self): return self.prenom def getAddress(self): return self.address def getAge(self): return self.age def getDateNaissance(self): return self.date_naissance def __str__(self) -> str: return self.prenom[0] + self.prenom[1:].lower() + " " + self.nom[0] + self.nom[1:].lower() + " a " + str(self.age) + " ans et son adresse mail est : " + self.address
def read_accidents_from_file(date_object): localisations = Area.Localisation.make_dictionary() intersections = Area.Intersection.make_dictionary() type_of_collisions = Details.TypeOfCollision.make_dictionary() try: with open('Accidents.csv', 'r', encoding="ISO-8859-1") as csv_file: reader = csv.reader(csv_file, delimiter=',') for row in reader: date = Date.Date(read_hour(row[4]), read_minute(row[4]), int(row[3]), int(row[2]), 2000 + int(row[1])) if date_object == date: area = Area.Area(localisations[row[6]], intersections[row[7]]) details = Details.Details(type_of_collisions[row[9]]) accident = Accident.Accident(area, date, details) accidents.append(accident) except FileNotFoundError: print("Cannot open a file")
def edit_dest(id): id = id.upper() animal = check_ID(id) if type(animal) == str: print(animal) return if str(animal.date_dep) == "": print("Date of departure of animal must be specified first.\n") edit_depart_date(id) return print( "The current Destination and Destination Address of animal with ID " + id + " is: " + (animal.dest if animal.dest else "blank") + " and " + (animal.dest_address if animal.dest_address else "blank")) dest = input("Enter new Destination or Leave blank: ") animal.dest = dest # if dest is specified, ask for address if dest: # loop until user has specified the address while True: dest_address = input("Enter Destination address") if dest_address: break animal.dest_address = dest_address # if dest is not specified, address will be blank else: animal.date_dep = Date() animal.dest_address = "" if id[0] == 'P': write_to_file('pet') else: write_to_file('wild animal') print( "The current Destination and Destination Address of animal with ID " + id + " is now: " + (animal.dest if animal.dest else "blank") + " and " + (animal.dest_address if animal.dest_address else "blank"))