def send_missed_visit_reminder(self, send=True, extra_kwargs=None): today = utils.today() scheduled_date = self.scheduled if self.no_sms or scheduled_date > today or self.status != 'pending': # Don't send if scheduled date in the future or visit is not pending return if send is True and self.missed_sms_count < 2: self.missed_sms_count += 1 self.missed_sms_last_sent = datetime.date.today() self.save() if extra_kwargs is None: delta_days = (scheduled_date - utils.today()).days extra_kwargs = { 'days': delta_days, 'date': scheduled_date.strftime('%b %d') } condition = self.get_condition('missed') return self.participant.send_automated_message( send=send, send_base='visit', condition=condition, extra_kwargs=extra_kwargs) else: return
def optogenic(title='', description='', data=[], source="", options={}): if "range" not in options.keys(): options["range"] = [0, 1, 2, 3, 4, 5, 6] if "mindate" not in options.keys(): options["mindate"] = str(u.monthdelta(u.today() - 6)).split(' ')[0] if "maxdate" not in options.keys(): options["maxdate"] = str(u.today()).split(' ')[0] return { 'retailgear': { 'size': { 'width': 'full' }, 'filters': [], 'title': title, 'subtitle': '', 'description': description, 'insight': '', 'daterange': '', 'script': source, 'type': "optogenic" }, "range": options["range"], "mindate": options["mindate"], "maxdate": options["maxdate"], "data": data }
def __init__(self, name, remarks=None, platform=None, initial_investment=None, maturity=None, import_data=False): self.name = name self.remarks = remarks self.platform = platform self.total_investment = initial_investment self.cur_val = initial_investment self.sold = False if maturity is not None: maturity = str(maturity) self.maturity = maturity if import_data: self.transaction = {} self.transaction_remark = {} self.history = {} else: self.transaction = {today(): initial_investment} self.transaction_remark = {today(): 'Funds Created'} self.history = {today(): initial_investment}
def convert_date(date_in): date = utils.today() if hasattr(date_in,'strftime'): # Date object date = date_in elif hasattr(date_in,'real'): # number object assume delta days date = utils.today() + datetime.timedelta(days=date_in) return "'{}'".format(date.strftime('%Y-%m-%d'))
def convert_date(date_in): date = utils.today() if hasattr(date_in, 'strftime'): # Date object date = date_in elif hasattr(date_in, 'real'): # number object assume delta days date = utils.today() + datetime.timedelta(days=date_in) return "'{}'".format(date.strftime('%Y-%m-%d'))
def request_post(url, body): response = RESPONSE_CACHE.get(body) if response and today() == response.get('date'): return response.get('body') response = requests.post(url, body) RESPONSE_CACHE[body] = { 'body': response.text, 'date': today(), } return response.text
def reschedule(self, ans): # ans is an int such that 0 <= ans <= 5 self.EF = max(1.3, min(2.5, self.EF - 0.8 + 0.28 * ans - 0.02 * ans * ans)) if ans < 3: self.last_interval = None self.due = utils.today() else: self.last_interval = int( 1 if self.last_interval is None else 6 if self.last_interval == 1 else self.last_interval * self.EF) self.due = utils.today() + self.last_interval
def collect(): headers = {'Authorization': 'Bearer ' + os.getenv('BITLY_TOKEN')} for link in links: utils.download_to_file( bitly_clicks_api.replace('{{LINK}}', link), utils.basedir() + "bitly/raw/" + utils.today() + '-' + link + ".json", headers) for link_cs in links_for_country_stats: utils.download_to_file( bitly_countries_api.replace('{{LINK}}', link_cs), utils.basedir() + "bitly/raw-countries/" + utils.today() + '-' + link_cs + ".json", headers)
def geraEspelhoDePonto(prev): start() login() saveDir = "C:\\AlessandroBAM\\2017m01 - Abbott DPE-PgM-PM\\IBM Brazil\\RH\\Aprovacao Mensal de Horas Extras e Standby\\2019m01 - Melhoria do processo de validacao de Certponto vs ILC\\Certponto" if prev: fileName = saveDir + "\\" + utils.prevMonth().strftime("%Ym%m") + " - Espelho Certponto.csv" else: fileName = saveDir + "\\" + utils.today().strftime("%Ym%m") + " - Espelho Certponto.csv" pyautogui.click(125,192, interval=7) #click em tratamento de ponto pyautogui.click(112,349, interval=3) #click espelho de ponto pyautogui.click(561,489, interval=1) #click on periodo simplificado if prev: pyautogui.click(303,632, interval=1) #click on mes passado else: pyautogui.click(297,607, interval=1) #click on mes atual pyautogui.click(297,699, interval=2) #click on gerar pyautogui.click(1852,770, interval=1) #click on Acoes pyautogui.click(1773,882, interval=1) #click Exportar CSV reduzido- pyautogui.click(545,219, interval=10) #click SIM pyautogui.hotkey("alt","s") pyautogui.press("enter",interval=6) if os.path.isfile(fileName ): os.remove(fileName) #deleting existing file pyautogui.typewrite(fileName) time.sleep(2) pyautogui.press("tab",interval=1) pyautogui.press("enter",interval=1) excel.openPBR(pars.pbReportsCPG,"")
def update_summary_stories(self): """Unless this story is a summary story, loop on all recipients, look-up or create a summary story, & add itself to it.""" if self.is_aggregation: return # update the summary story for all recipients for user in self.recipients.all(): # look up a summary story for that user: # - it should be marked as is_aggregation # - it should have the user as recipient # - it should be from today tod = today() query = StoryCell.objects.filter(is_aggregation=True, recipients__pk=user.id, last_update__gte=tod) if query.count() > 0: summary_story = query[0] else: # if not found, create one summary_story = StoryCell() summary_story.name = "%s's %s %s" % (user.name, _('summary for'), tod.strftime("%c")) summary_story.container = self.container summary_story.layer = self.layer summary_story.is_aggregation = True summary_story.move_to_random_location() summary_story.recipients.add(user) # add the story to the summary summary_story.aggregated_stories.add(self) summary_story.generate_summary()
def get_curr_fund_value(fund_name_list): unit_values = {} for fund in fund_name_list: fund_id = db.get_fund_id(fund) data_dict, last_date = get_mf_data(fund_id, utils.last_month(), utils.today()) unit_values[fund] = data_dict[max(data_dict)] return unit_values
def add_new_visit(contact,i): new_visit = { 'scheduled':utils.today() + datetime.timedelta(days=i+1), 'participant':contact, 'visit_type':'clinic' if random.random() < 0.5 else 'study' } cont.Visit.objects.create(**new_visit)
def create_card(self, front, back, dotted_name): """Creates a card and adds it to the deck at @dotted_name. The card is stored in the database aswell""" deck = self.find_deck(dotted_name) dct = dict(id=utils.getid(self.conn, 'card'), front=front, back=back, deck=deck, due=utils.today(), last_interval=None, EF=2.5, conn=self.conn) card = Card(**dct) ################################################## # insert the card into the database # dct contains almost all attributes needed for inserting # a row into the database, except deck_id dct['deck_id'] = deck.id card.conn.execute( """ INSERT INTO card (id, front, back, deck_id, due, last_interval, EF) VALUES (:id, :front, :back, :deck_id, :due, :last_interval, :EF)""", dct) card.conn.commit() deck.add_card(card) return card
def router(paramstring): params = dict(parse_qsl(paramstring)) if params: if params['action'] == 'feeds': dategames = games(params['date'], params['provider']) gameDict = dict([(g.id, g) for g in dategames]) listfeeds(gameDict[int(params['game'])], params['date'], params['provider']) elif params['action'] == 'play': playgame(params['date'], params['feedId'], params['provider'], params['state']) elif params['action'] == 'listyears': listyears(params['provider']) elif params['action'] == 'listhighlights': listhighlights(params['provider']) elif params['action'] == 'listgrouphighlights': listgrouphighlights(params['provider'], params['group']) elif params['action'] == 'playhighlight': playhighlight(params['url']) elif params['action'] == 'listmonths': listmonths(params['year'], params['provider']) elif params['action'] == 'listdays': listdays(params['year'], params['month'], params['provider']) elif params['action'] == 'listgames': listgames( "%d-%02d-%02d" % (int(params['year']), int( params['month']), int(params['day'])), params['provider']) elif params['action'] == 'listtodaysgames': listgames(utils.today().strftime("%Y-%m-%d"), params['provider'], True, True) else: listproviders()
def generate_summary(self): """Generate a summary story based on the aggregated stories""" recipient = self.recipients.all()[0] tod = datetime.datetime.today() authors_map = {} for story in self.aggregated_stories.all(): for author in story.authors.all(): if authors_map.has_key(author): authors_map[author] = authors_map[author] + 1 else: authors_map[author] = 1 concepts_map = {} for concept in self.aggregated_concepts.filter(recipients=recipient): story_count = concept.related_stories.filter(last_update__gte=today()).count() concepts_map[concept] = story_count # todo use template summary = "<h3>Summary for %s</h3>" % recipient for author, count in authors_map.items(): summary = summary + "<li><a href='http://twitter.com/%s' target='_blank'>%s</a> twitted since yesterday %d <a href='http://search.twitter.com?q=from:%s' target='_blank'>tweets</a>" % (author.user_name, author, count, author.user_name) if len(concepts_map) > 0: summary = summary + "<hr/><h4>Concepts</h4>" for concept, count in concepts_map.items(): summary = summary + "<li>%s - %d tweets since yesterday" % (concept.name, count) self.core = summary self.save()
def visit_range(self, start={'days': 0}, end=None, notification_start={'days': 0}, notification_end=None): today = utils.today() start = today - datetime.timedelta(**start) notification_start = today - datetime.timedelta(**notification_start) if end is not None: end = today - datetime.timedelta(**end) scheduled_Q = Q(scheduled__range=(end, start)) else: scheduled_Q = Q(scheduled__lte=start) if notification_end is not None: notification_end = today - datetime.timedelta(**notification_end) notification_Q = Q( notification_last_seen__range=(notification_end, notification_start)) else: notification_Q = Q(notification_last_seen__lte=notification_start) notification_Q |= Q(notification_last_seen__isnull=True) return self.filter(scheduled_Q & notification_Q)
def change_current_date(request, direction, delta): delta = int(delta) * (-1 if direction == 'back' else 1) td = datetime.timedelta(days=delta) config.CURRENT_DATE = utils.today() + td return JsonResponse( {'current_date': config.CURRENT_DATE.strftime('%Y-%m-%d')})
def find_or_create_summary_story(user, agent): """ Look up a summary story for the given user: - it should be marked as is_aggregation - it should have the user as recipient - it should be from today """ tod = today() #query = StoryCell.objects.filter(is_aggregation=True, recipients__pk=user.id, last_update__gte=tod) query = StoryCell.objects.filter(is_aggregation=True, recipients__pk=user.id) found_story = None if query.count() > 0: for s in query: if (s.created_at - tod).days < 1: found_story = s if found_story: summary_story = found_story else: # if not found, create one summary_story = StoryCell() summary_story.cell_type = STORY_CELL summary_story.name = "%s's %s %s" % (user.name, _('summary for'), tod.strftime("%c")) summary_story.container = agent summary_story.layer = 2 summary_story.is_aggregation = True summary_story.move_to_random_location() summary_story.recipients.add(user) summary_story.save() return summary_story
def add_new_scheduled_call(contact,i): scheduled_date = utils.today() + datetime.timedelta(days=2*i+1) cont.ScheduledPhoneCall.objects.create(scheduled=scheduled_date,participant=contact) cont.ScheduledPhoneCall.objects.create( scheduled=scheduled_date+datetime.timedelta(days=1), participant=contact, call_type='y')
def attended(self, arrived=None): ''' Mark visted as attended on @arrived (default today) ''' if arrived is None: arrived = utils.today() else: arrived = utils.angular_datepicker(arrived) self.set_status('attended', arrived)
def was_pregnant(self, today=None): ''' Returns true if the contact was pregnant at date today ''' if self.delivery_date is not None: today = utils.today(today) return today <= self.delivery_date return True
def due_cards(self): """Returns a list of all cards which are up for review.""" today = utils.today() def is_due(card): return card.due <= today return [card for card in self.all_cards if is_due(card)]
def was_pregnant(self,today=None): ''' Returns true if the contact was pregnant at date today ''' if self.delivery_date is not None: today = utils.today(today) return today <= self.delivery_date return True
def register_sale(): sale = { "date": today() } print("--- Satış kaydı ---\n") print("Urunu kim satıyor?") employees = get_employees() for e in employees: print("- %s (%s)" % (e['name'], e['id'])) print() employee = select_by_id_or_name(employees, 'employee') sale['employee_id'] = employee['id'] print("Selected: %s (%s)\n" % (employee['name'], employee['id'])) print("Bu hangi ürün?") products = get_products() for p in products: print("- (%s) %s (%s adet satilabilir.)" % (p['id'], p['name'], p['quantity'])) print() product = select_by_id_or_name(products, 'product') sale['product_id'] = product['id'] print("Secilen: %s (%s) (%s stokta var)\n" % (product['name'], product['id'], (product['quantity']))) quantity = 0 while True: quantity = safe_input("int_positive", "Kaç urun var? ") if quantity > 0 and quantity <= product['quantity']: print("Emir geçerlidir. Toplam fiyat hesaplanıyor...") break else: print( "Sipariş geçersiz. Lütfen stoktaki miktardan büyük olmayan bir sayı seçin") # we are updating the reference, so this dictionary is also modified # on the products list product['quantity'] -= quantity sale['num_products'] = quantity sale['total_price'] = quantity * product['price'] print("\nToplam fiyat: %sTL (+ %sTL vergi)" % (sale['total_price'], sale['total_price'] * 0.18)) sale['id'] = len(get_sales()) print("\nBu siparişin numarasi", sale['id']) update_products(products) add_sale(sale)
def daily(): files = sorted(glob.glob(utils.basedir() + 'bitly/raw/*.json')) created = set() for file in files: with open(file) as stats_file: stats = json.load(stats_file) link = os.path.basename(stats_file.name)[20:-5] date_collected = os.path.basename(stats_file.name)[:10] #print(stats_file.name + ' ' + link + ' ' + date_collected) for lc in stats['link_clicks']: # TODO these will be duplicated date_str = lc['date'][:10] # Stats for the day of collection will probably be incomplete if not date_str == date_collected: daily_file = utils.basedir( ) + 'bitly/daily/' + date_str + '.csv' if not os.path.exists(daily_file): with open(daily_file, "a") as f: f.write('date,link,clicks\n') created.add(date_str) print('Created ' + daily_file) if date_str in created: with open(daily_file, "a") as f: f.write(date_str + ',' + link + ',' + str(lc['clicks']) + '\n') # The raw stats contain duplicate days so its easier to work out the monthly stats from the daily ones today = datetime.date.today() if (today.day > 1): first_str = today.replace(day=1).strftime('%Y-%m-%d') monthly_file = utils.basedir() + 'bitly/monthly/' + first_str + '.csv' if not os.path.exists(monthly_file): monthly_totals = {} if today.month == 1: last_month = today.replace(year=today.year - 1).replace(month=12) else: last_month = today.replace(month=today.month - 1) files = sorted( glob.glob(utils.basedir() + 'bitly/daily/' + last_month.strftime('%Y-%m-') + '*.csv')) for file in files: with open(file) as daily_file: csv_reader = csv.reader(daily_file) # Ignore the header next(csv_reader) for row in csv_reader: link = row[1] clicks = row[2] if not link in monthly_totals: monthly_totals[link] = 0 monthly_totals[link] += int(clicks) with open(monthly_file, "a") as f: f.write('date,link,clicks\n') for link in monthly_totals: f.write(utils.today() + ',' + link + "," + str(monthly_totals[link]) + '\n') print('Created ' + monthly_file)
def get_missed_visits(self,date=None,delta_days=3): """ Return pending visits that are 3 days late and have been seen or it has been 3 days since an SMS reminder was sent and has been seen more than three times""" today = utils.today(date) late = today - datetime.timedelta(days=delta_days) first_reminder_Q = Q(scheduled__lte=late,notify_count__gt=0,missed_sms_count=0) second_reminder_Q = Q(missed_sms_last_sent__lte=late,notify_count__gt=3,missed_sms_count__gt=0) return self.pending().is_active().filter(first_reminder_Q | second_reminder_Q)
def seen(self,seen=None): ''' Mark visit as seen today ''' if seen is None: seen = utils.today() else: seen = utils.angular_datepicker(seen) self.notify_count += 1 self.notification_last_seen = seen self.save()
def seen(self, seen=None): ''' Mark visit as seen today ''' if seen is None: seen = utils.today() else: seen = utils.angular_datepicker(seen) self.notify_count += 1 self.notification_last_seen = seen self.save()
def attended(self, arrived=None): ''' Mark visted as attended on @arrived (default today) ''' if arrived is None: arrived = utils.today() else: arrived = utils.angular_datepicker(arrived) self.arrived = arrived self.skipped = False self.save()
def age(self, signup=False): if signup is True: today = self.created.date() else: today = utils.today() if today < datetime.date(today.year, self.birthdate.month, self.birthdate.day): return today.year - self.birthdate.year - 1 else: return today.year - self.birthdate.year
def attended(self,arrived=None): ''' Mark visted as attended on @arrived (default today) ''' if arrived is None: arrived = utils.today() else: arrived = utils.angular_datepicker(arrived) self.arrived = arrived self.skipped = False self.save()
def register_sale(): sale = {"date": today()} print("--- Register sale ---\n") print("Who is selling the product?") employees = get_employees() for e in employees: print("- %s (%s)" % (e['name'], e['id'])) print() employee = select_by_id_or_name(employees, 'employee') sale['employee_id'] = employee['id'] print("Selected: %s (%s)\n" % (employee['name'], employee['id'])) print("Which product is it?") products = get_products() for p in products: print("- %s (%s) (%s in stock)" % (p['name'], p['id'], p['quantity'])) print() product = select_by_id_or_name(products, 'product') sale['product_id'] = product['id'] print("Selected: %s (%s) (%s in stock)\n" % (product['name'], product['id'], (product['quantity']))) quantity = 0 while True: quantity = safe_input("int_positive", "How many items? ") if quantity > 0 and quantity <= product['quantity']: print("The order is valid. Calculating total price...") break else: print( "The order is invalid. Please choose a number that is not greater than the quantity in stock" ) # we are updating the reference, so this dictionary is also modified # on the products list product['quantity'] -= quantity sale['num_products'] = quantity sale['total_price'] = quantity * product['price'] print("\nTotal price: $%s (+ $%s tax)" % (sale['total_price'], sale['total_price'] * 0.16)) sale['id'] = len(get_sales()) print("\nThis order's id is", sale['id']) update_products(products) add_sale(sale)
def generate_csv(): headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36' } today = utils.today() pdf_file = utils.get_todays_fileName("pdf") #construct the url for the bulletin of today final_url = utils.get_url() # if there is no such folder, the script will create one automatically scraping_folder = path.join(path.dirname(__file__), 'pdfBulletins') csv_folder = path.join(path.dirname(__file__), "CSVs") # make the folder if not os.path.exists(scraping_folder): os.mkdir(scraping_folder) if not os.path.exists(csv_folder): os.mkdir(csv_folder) filename = path.join(scraping_folder, pdf_file) print(final_url) print(filename) #get the pdf with open(filename, 'wb') as f: response = requests.get(final_url, headers=headers) if response.status_code == 200: f.write(response.content) else: return ("Invalid URL or unresponsive server") # analyze the pdf # this will generate the data in csv format in the file output.csv output_file = "output_" + today + ".csv" tabula.convert_into(filename, output_file, output_format="csv", pages=[2, 3, 4], java_options="-Dfile.encoding=UTF8") # read output.csv to fix it (when the pdf reading file contains only 2 commas, add 0 and a second comma) #TODO think when there are no cases nor deaths, or when there are no cases but there are deaths clean_output(output_file) # output1 is an itermediary file df = pd.read_csv("output2.csv", header=None) # rename columns df.columns = ["Régions", "Nouveaux Cas", "Décès", "Régions Ar"] # replace NaN with 0 (this is because the number of deaths is not entered when there are not) df = df.fillna(0) #write data to corona_today.csv final_corona_data = "corona_" + today + ".csv" final_csv_path = path.join(csv_folder, final_corona_data) df.to_csv(final_csv_path, index=True) return df
def delta_days(self, today=None): ''' Return the number days until EDD or since delivery ''' today = utils.today(today) if self.was_pregnant(today): return (self.due_date - today).days else: #post-partum #TODO: Change this to delivered date when we start using that # Return days since due date return (today - self.due_date).days
def delta_days(self,today=None): ''' Return the number days until EDD or since delivery ''' today = utils.today(today) if self.was_pregnant(today): return (self.due_date - today).days else: #post-partum #TODO: Change this to delivered date when we start using that # Return days since due date return (today-self.due_date).days
def add_call(self,outcome='answered',comment=None,length=None,is_outgoing=True, created=None,admin_user=None,scheduled=None): if created is None: created = utils.today() else: created = utils.angular_datepicker(created) new_call = PhoneCall.objects.create(outcome=outcome,contact=self,is_outgoing=is_outgoing, comment=comment,created=created,connection=self.connection(),length=length, scheduled=scheduled) return new_call
def send_visit_reminder(self, send=True, extra_kwargs=None): today = utils.today() scheduled_date = self.scheduled if self.no_sms or scheduled_date < today or self.status != 'pending': # Don't send if scheduled date in past or visit is not pending return if extra_kwargs is None: delta_days = (scheduled_date - utils.today()).days extra_kwargs = { 'days': delta_days, 'date': scheduled_date.strftime('%b %d') } condition = self.get_condition('pre') return self.participant.send_automated_message( send=send, send_base='visit', condition=condition, extra_kwargs=extra_kwargs)
def offer_list_info(self): info_list = list() for offer in self.offer_list: if offer.date.text != today(): continue info = [ offer.name.text, offer.location.text.split(' w ')[1], offer.link.get_attribute("href") ] info_list.append(tuple(info)) return info_list
def update(self, answer): card = self.current_card card.reschedule(answer) card.flush() if card.due == utils.today(): self.cards.add(card) if self.cards: self.current_card = self.cards.pop() else: self.current_card = None
def process(self, correlation_id=-1): """Story cells have 3 main behaviors: - translating their content to semantic cells; - changing location to reflect semantic orientation; - generating summary stories.""" # if needed, update summary stories print "Story %d created at" % self.id, self.created_at tod = today() if self.created_at >= tod: log_event("process", "StoryCell", self.id, "Updating summary stories", correlation_id) self.update_summary_stories() # move to a location, maximizing the value of the story self.move() self.last_processing_cycle = correlation_id self.save()
def send_daily_summary(self, correlation_id=-1): """Sends the generated summary story for its recipient""" # look up a summary tod = today() query = StoryCell.objects.filter(is_aggregation=True, recipients__pk=self.user.id, last_update__gte=tod) if query.count() > 0: summary_story = query[0] # if found, send a link to it the user log_event("notify", "Agent", self.id, "Sending summary story to user %s" % self.user.user_name, correlation_id) link = summary_story.get_absolute_url() shortened_url = shorten_url(link) message = "Here's your daily summary for %s: %s" % (tod, shortened_url) if send_twitter_direct_message(self, self.user.user_name, message, correlation_id): self.last_summary_delivered_at = datetime.datetime.now() self.save()
def visit_range(self,start={'days':0},end=None,notification_start={'days':0},notification_end=None): today = utils.today() start = today - datetime.timedelta(**start) notification_start = today - datetime.timedelta(**notification_start) if end is not None: end = today - datetime.timedelta(**end) scheduled_Q = Q(scheduled__range=(end,start)) else: scheduled_Q = Q(scheduled__lte=start) if notification_end is not None: notification_end = today - datetime.timedelta(**notification_end) notification_Q = Q(notification_last_seen__range=(notification_end,notification_start)) else: notification_Q = Q(notification_last_seen__lte=notification_start) notification_Q |= Q(notification_last_seen__isnull=True) return self.filter( scheduled_Q & notification_Q)
def current_date(context): return { 'CURRENT_DATE': utils.today(), 'ONE_WEEK': utils.today() + datetime.timedelta(weeks=1), 'FOUR_WEEKS': utils.today() + datetime.timedelta(weeks=4) }
self.DONE.emit() return False def fetch_more(self): if not self.RUN: return self.START.emit() def get_records(): self._fetching = True remaining = self.count - len(self._current_data) rec_to_fetch = min(remaining, self._fetch_count) CommandQueue.put([["SELECT * FROM series LIMIT {}, {}".format( self._offset, rec_to_fetch)]]) self._offset += rec_to_fetch c = ResultQueue.get() new_data = c.fetchall() gallery_list = add_method_queue(GalleryDB.gen_galleries, False, new_data) #self._current_data.extend(gallery_list) self.GALLERY_EMITTER.emit(gallery_list) self._fetching = False if not self._fetching: thread = threading.Thread(target=get_records, name='DatabaseEmitter') thread.start() if __name__ == '__main__': #unit testing here date = today() print(date) #raise RuntimeError("Unit testing still not implemented")
def fetch_proposals(since: datetime=None, importers: Iterable[Importer]=None, logger=task_logger): """Task runs each of the importers given. """ now = today() latest_proposal = Proposal.objects.latest() if latest_proposal: default_since = latest_proposal.updated else: # If there is no record of a previous run, fetch # proposals posted since the previous Monday. default_since = now - timedelta(days=7 + now.weekday()) if importers is None: importers = Importer.objects.all() all_found = {"cases": [], "events": [], "projects": []} for importer in importers: importer_since = since if not since: if importer.last_run: importer_since = importer.last_run else: importer_since = default_since importer_since = \ importer.tz.normalize(importer_since) if importer_since.tzinfo \ else importer.tz.localize(importer_since) try: found = importer.updated_since(importer_since) importer.validate(found) except jsonschema.exceptions.ValidationError as err: logger.warning("Importer %s failed schema validation!\n%s", importer.name, err) continue except Exception as err: logger.exception("An unknown error occurred while running importer %s", importer.name) continue found_description = ", ".join(f"{len(v)} {k}" for k, v in found.items()) logger.info(f"Fetched: {found_description} w/{importer}") for k in found: for item in found[k]: item.setdefault("region_name", importer.region_name) all_found[k].append((importer, item)) importer.last_run = now importer.save() add_locations([case for _, case in all_found["cases"]], Geocoder) result = {} for type_name, maker_fn, k in [("cases", create_proposal, "proposal_ids"), ("events", create_event, "event_ids")]: ids, errors = create_models(maker_fn, all_found[type_name], logger) if errors: for imp, count in errors.items(): logger.warn(f"Importer {imp} was unable to import {count} {type_name}") result[k] = ids return result
def days_overdue(self): return (utils.today()-self.scheduled).days
def change_current_date(request,direction,delta): delta = int(delta) * (-1 if direction == 'back' else 1) td = datetime.timedelta(days=delta) config.CURRENT_DATE = utils.today() + td return JsonResponse({'current_date':config.CURRENT_DATE.strftime('%Y-%m-%d')})
def is_from_today(self): """ Returns true if the created_at field contains a date within the last 24 hours """ tod = today() return (tod - self.created_at).days < 1
def myprogram(): name = input("¿cómo te llamas? ") hoy = today() print("Hola ", name, ", hoy es ", hoy) #myprogram()
def get_detailed_stats(txn_list): mf_dict = {} # TODO: values of mf_dict should be objects, and not list. For those objects # we will add additional attributes like total redemption, total profit in # redemption, total units still held, total profit in current scenario, etc # BUT make sure you study the implications of having all this information # stored and retrieved from database for txn in txn_list: mf_dict[txn['fund_name']] = {} mf_dict[txn['fund_name']]['txns'] = [] for txn in txn_list: mf_dict[txn['fund_name']]['txns'].append(txn) for mf in mf_dict: mf_dict[mf]['txns'].sort(key=lambda x: x['date']) for mf in mf_dict: no_nav_txn = [txn for txn in mf_dict[mf]['txns'] if txn['nav'] is None] if len(no_nav_txn) != 0: # TODO: optimize here too fill_all_navs_for_fund(mf_dict[mf]['txns']) for mf in mf_dict: fill_redemption_stats(mf_dict[mf]['txns']) mf_curr_value_dict = get_curr_fund_value(mf_dict.keys()) for mf in mf_dict: mf_dict[mf]['total_units'] = sum([txn['units'] for txn in mf_dict[mf]['txns'] if txn['txn_type'] == PURCHASE]) mf_dict[mf]['total_units'] -= sum([txn['units'] for txn in mf_dict[mf]['txns'] if txn['txn_type'] == REDEMPTION]) for mf in mf_dict.keys(): if mf_dict[mf]['total_units'] == 0.0: del mf_dict[mf] for mf in mf_dict: mf_dict[mf]['total_amount_invested'] = sum([txn['left_units'] * txn['nav'] for txn in mf_dict[mf]['txns']]) mf_dict[mf]['total_amount_now'] = mf_curr_value_dict[mf] * mf_dict[mf]['total_units'] mf_dict[mf]['percentage_gains'] = mf_dict[mf]['total_amount_now']/mf_dict[mf]['total_amount_invested']*100.0 - 100.0 if mf_dict[mf]['total_amount_invested'] != 0.0 else 0.0 mf_dict[mf]['average_holding_period'] = sum([txn['left_units']*utils.diff_days(utils.today(), txn['date']) for txn in mf_dict[mf]['txns']])/sum(txn['left_units'] for txn in mf_dict[mf]['txns']) mf_dict[mf]['annualized_gains'] = 365.25/mf_dict[mf]['average_holding_period']*mf_dict[mf]['percentage_gains'] stats = {} stats['total_amount_invested'] = sum([mf_dict[mf]['total_amount_invested'] for mf in mf_dict]) stats['total_amount_now'] = sum([mf_dict[mf]['total_amount_now'] for mf in mf_dict]) stats['total_gains'] = stats['total_amount_now'] - stats['total_amount_invested'] print stats['total_gains'] stats['percentage_gains'] = stats['total_amount_now']/stats['total_amount_invested']*100.0 - 100.0 if stats['total_amount_invested'] != 0.0 else 0.0 return mf_dict, stats
def __init__(self, *args, **kwargs): super(ContactAdd, self).__init__(*args, **kwargs) #Moved this here so that current date can be calculated for each new form birth_BO = [{ 'from': (today() - datetime.timedelta(days=14*365)).strftime("%Y-%m-%d"), 'to': (datetime.datetime(2100,1,1)).strftime("%Y-%m-%d"), }] due_date_BO = [{ 'from': (datetime.datetime(1970,1,1)).strftime("%Y-%m-%d"), 'to': (today() + datetime.timedelta(weeks=4)).strftime("%Y-%m-%d"), # between 4 .... }, { 'from': (today() + datetime.timedelta(weeks=36)).strftime("%Y-%m-%d"), # ...and 36 weeks in the future 'to': (datetime.datetime(2100,1,1)).strftime("%Y-%m-%d"), }] art_BO = [{ 'from': today().strftime("%Y-%m-%d"), 'to': (datetime.datetime(2100,1,1)).strftime("%Y-%m-%d"), }] self.fields['due_date'].widget = util.AngularPopupDatePicker({'required':True},min=28) self.fields['birthdate'].widget = util.AngularPopupDatePicker( {'required':True,'datepicker-position-right':True},max=-5110 # 14 years or older ) self.fields['art_initiation'].widget = util.AngularPopupDatePicker(max=0) self.fields['clinic_visit'].widget = util.AngularPopupDatePicker({'required':True}, min=7) self.helper = FormHelper() self.helper.form_class = 'form-horizontal' self.helper.form_id = 'participant-details-form' self.helper.label_class = 'col-sm-6' self.helper.field_class = 'col-sm-6' self.helper.form_tag = False self.helper.layout = Layout( Fieldset( 'Study Information', Div( Div('study_id', css_class="col-md-4"), Div('anc_num', css_class="col-md-4"), Div('study_group', css_class="col-md-4"), css_class="row" ), Div( Div('ccc_num', css_class="col-md-4"), Div('send_day', css_class="col-md-4", ng_if="participant.study_group != 'control'" ), Div('send_time', css_class="col-md-4", ng_if="participant.study_group != 'control'" ), css_class="row", ), ), Fieldset ( 'Client Information', Div( Div('nickname', css_class="col-md-4"), Div('phone_number', css_class="col-md-4"), Div('birthdate', css_class="col-md-4"), css_class="row" ), Div( Div('relationship_status', css_class="col-md-4"), Div('partner_name', css_class="col-md-4"), Div('previous_pregnancies', css_class="col-md-4"), css_class="row" ), Div( Div('phone_shared', css_class="col-md-4"), Div('language', css_class="col-md-4"), Div('hiv_disclosed', css_class="col-md-4"), css_class="row" ), ), Fieldset ( 'Medical Information', Div( Div('condition', css_class="col-md-4"), Div('art_initiation', css_class="col-md-4"), Div('hiv_messaging', css_class="col-md-4"), css_class="row" ), Div( Div('due_date', css_class="col-md-4"), Div('clinic_visit', css_class="col-md-4"), css_class="row" ) ), FormActions( Submit('submit', 'Enroll Participant',ng_disabled='participantNewForm.$invalid', style='margin-bottom:20px'), css_class="row" ) ) # thank you: http://stackoverflow.com/questions/24663564/django-add-attribute-to-every-field-by-default for field in self: field.field.widget.attrs.update({ 'ng-model': 'participant.{0}'.format(field.name), })
def age(self): today = utils.today() delta = today - self.birthdate return int((delta.days - delta.seconds/86400.0)/365.2425)
import requests import setup from settings import DATADIR, TWITTER_KEYS, TWITTER_HANDLES import utils def get_follower_ids(handle, oauth, filename=None): r = requests.get(url="https://api.twitter.com/1.1/followers/ids.json", params={"screen_name": handle}, auth=oauth) if r.status_code == 200: print "Followers for %s fetched" % handle ids = sorted(r.json()["ids"]) if filename: utils.write_list_to_text(ids, filename) else: ids = [] return ids if __name__ == "__main__": for handle in TWITTER_HANDLES: handle_dir = "%s/%s" % (DATADIR, handle) filename = "%s/%s-follower-ids.txt" % (handle_dir, utils.today()) utils.check_dir(handle_dir) ids = get_follower_ids(handle, oauth=setup.get_oauth1(keys=TWITTER_KEYS), filename=filename)