def calc_vacation_leave_accnt(db, empid, month=datetime.date.today().month, year=datetime.date.today().year): vaction_leaves = get_month_vl(db, empid, month, year) vl = 0 end_date = datetime.datetime(year, month, (31, 30)[month in month_30]) for (from_date,to_date) in vaction_leaves: to_date = functions.get_date(to_date) from_date = functions.get_date(from_date) #Check if to_date is in the same month or not if not to_date.month == month: to_date = end_date vl = vl + (to_date - from_date).days + 1 print vl return vl
def write_robotstxt(file, output, filename='robots.txt'): ''' Write robots.txt to file using date as id. ''' filename = get_date() + '-' + filename filename = output + filename with open(filename, 'w') as f: f.write(file)
def run(config): # TODO: 减少对 config.json 的调用次数,导入一次就够了 functions.schedule_run(config) token, login_response = functions.get_token(config) if token: userinfo = functions.get_user_info(token) index = 0 date = functions.get_date("today") seats = functions.search_seats(token, config["room"], date) while seats is not False and index < len(seats): response = functions.post_data(seats, config, token, index) status = response[u"status"] index = index + 1 time.sleep(random.uniform(0.1, 0.5)) if status == u"fail": print "\n--------------Oops! failed!---------------\n" print "\n------------" + response[u'message'] + "-------------" break elif status == u"success": print "\n-------------Yeah! it's done!-------------\n" break # TODO: 将所有除了success和该座位已被预约以外的status设置为返回status并break # TODO: 调整send_mail参数 functions.send_mail(config, response[u'message']) else: response = None return userinfo, response
def delete_leave(db, empid, date): leave_date = functions.get_date(date) key = str(empid) + ":" + str(leave_date.month) + ":" + str(leave_date.year) leaves = db.query("SELECT * FROM leaves WHERE leave_key LIKE %s", str(key)) if leaves: leaves = simplejson.loads(leaves) if not leaves.count(date) == 0: leaves.remove(date)
def add_leave(db, empid, date): leave_date = functions.get_date(date) key = str(empid) + ":" + str(leave_date.month) + ":" + str(leave_date.year) result = db.get("SELECT details FROM leaves WHERE leave_key LIKE %s", str(key)) if result: leaves = simplejson.loads(result['details']) leaves.append(date) return db.execute("UPDATE leaves SET details = %s WHERE leave_key LIKE %s", simplejson.dumps(leaves), str(key)) else: return db.execute("INSERT INTO leaves (leave_key, details) VALUES (%s, %s)", str(key), simplejson.dumps([date]))
def process(time, rdd): print("========= %s =========" % str(time)) try: if rdd.count() == 0: raise Exception("Empty") sqlContext = getSqlContextInstance(rdd.context) df = sqlContext.read.json(rdd, multiLine=True) if df.count() == 0: raise Exception("Empty") udf_func = udf(lambda x: dosentiment(x), returnType=StringType()) # print(df.head(5)) df = df.withColumn("sentiment", lit(udf_func(df.text))) # print(df.take(10)) results = df.toJSON().map(lambda j: json.loads(j)).collect() # print("Sentiment done") for result in results: result["created_at"] = fn.get_date(result["created_at"]) result["@timestamp"] = fn.get_date(result["created_at"], to_string=False) result["cleaned_text"] = fn.clean(result["text"]) result["sentiment"] = json.loads(result["sentiment"]) polarity, tweet_sentiment = fn.get_sentiment(fn.get_tweet(result["text"])) result["sentiment_function"] = tweet_sentiment result["polarity"] = polarity result["source"] = fn.find_device(result["source"]) result["user_age"] = fn.get_age(result["user"]["created_at"]) result["nb_characters"] = len(result["text"]) for topic in top_topics: if topic in result["text"]: result["topic"] = topic if hashtag in result["text"]: result["topic"] = hashtag # print("sentiment loaded") to_elastic(results, "main_index", "doc") # print("Send to elastic done") except Exception as e: print(e) pass
def main(): """ main function initiates a kafka consumer, initialize the tweet database. Consumer consumes tweets from producer extracts features, cleanses the tweet text, calculates sentiments and loads the data into postgres database """ with open("hashtag.txt") as f: hashtag = f.read() # set-up a Kafka consumer consumer = KafkaConsumer("twitter_stream_" + hashtag, auto_offset_reset="earliest") os.system("curl -XDELETE localhost:9200/main_index") for msg in consumer: dict_data = json.loads(msg.value) tweet = fn.get_tweet(dict_data["text"]) polarity, tweet_sentiment = fn.get_sentiment(tweet) lang = fn.detect_lang(tweet) # add text & sentiment to es es.index( index="main_index", doc_type="test_doc", body={ "author": dict_data["user"]["screen_name"], "author_followers": dict_data["user"]["followers_count"], "author_statues": dict_data["user"]["statuses_count"], "author_verified": dict_data["user"]["verified"], "author_account_age": fn.get_age(dict_data["user"]["created_at"]), "created_at": dict_data["created_at"], "@timestamp": fn.get_date(dict_data["created_at"], to_string=False), "message": dict_data["text"], "cleaned_text": fn.clean(dict_data["text"]), "sentiment_function": tweet_sentiment, "polarity": polarity, "lang": lang, "source": fn.find_device(dict_data["source"]), }, ) print(str(tweet)) print("\n")
def error(self, path): """ Page that loads for a 404 error """ headers = {} headers['Content-Type'] = 'text/html; charset=utf-8' output = [] addline = output.append contents = [] title = 'Page Not Found' contents.append('<h2>%s</h2>' % title) contents.append('<p>Sorry, but the web page you are trying to reach does not seem to exist on this website.</p>') contents.append('<p>The website address (URL) is:</p>') contents.append('<ul><li><a href="http://elections.raisethehammer.org/%s">http://elections.raisethehammer.org/%s</a></li></ul>' % ('/'.join(path), '/'.join(path))) contents.append('<p>You may have followed a broken link from another site or mistyped the URL you are trying to load.</p>') contents.append('<p>If you believe this is an error on the site, please <a href="mailto:[email protected]?subject=Broken Link on RTH Elections Page&body=http://elections.raisethehammer.org/%s">send us an email</a> with the details.</p>' % ('/'.join(path))) template = t.default template = template.replace('[[date]]', f.get_date()) template = template.replace('[[time]]', f.get_time()) template = template.replace('[[title]]', title) template = template.replace('[[section]]', 'The Hall of Lost Pages') template = template.replace('[[description]]', 'The page you are looking for could not be found.') template = template.replace('[[content]]', '\n'.join(contents)) addline(template) page = html.write( site_domain = c.SITE_DOMAIN, site_name = c.SITE_NAME, css_path = c.CSS_PATH, css_files = c.CSS_FILES, js_path = c.JS_PATH, js_files = c.JS_FILES, page_title = title, page_author = 'Ryan McGreal', favicon_url = c.FAVICON_URL, body_content='\n'.join(output), rss = 'http://raisethehammer.org/feeds/articles_blogs/' ) raise web.notfound(page) # make sure page is returned with an HTTP 404 status code
if sample_name.startswith('M') and len(sample_name) == 3: return 'mouse' elif sample_name.startswith('C0'): return 'culture' elif 'THP1' in sample_name or 'MM' in sample_name or 'C1866' in sample_name: return 'control' else: return 'published' if __name__ == '__main__': plt.rcParams.update({'font.size': 20, 'font.sans-serif': 'Arial'}) sns.set(font="Arial", font_scale=1.5) plot_dir = fxn.plot_dir + fxn.get_date() + '-publishedJY-analysis/' if not os.path.exists(plot_dir): os.mkdir(plot_dir) # Get data processed by generate-data-files.py peptides, pep_types = fxn.get_data('peptide') pep_samples = peptides.keys() pep_samples.sort() # Specify explicitly which are control lines, for ease of plotting control_data = [ x for x in pep_samples if 'Jurkat' in x or 'C1866' in x or 'THP' in x or 'MM16' in x ] mouse_data = [x for x in pep_samples if x.startswith('M')] culture_data = [x for x in pep_samples if x.startswith('C0')]
def search_log(self): row_list = get_row_list(self.spreadsheet) fmt = '%m/%d/%Y' while True: clear() print("Log Search Menu\n") print("1. Search by date") print("2. Search by time spent") print("3. Search by exact match or pattern") print("4. Page through individual entries") print("5. Previous menu\n") print("Please enter the number of the option you wish to choose.") user_choice = input("> ") if user_choice == '1': search_by_date = True while search_by_date: clear() print("Search an entry by date\n") print("Would you like to enter a specific date range?") user_choice2 = input("Y/N ") if user_choice2.upper() == 'Y': fmt_date_list = [] search_list = [] start_date = get_date("Starting Date") end_date = get_date("Ending Date") start_date_fmt = datetime.datetime.strptime( start_date, fmt) end_date_fmt = datetime.datetime.strptime( end_date, fmt) for result in perdelta( start_date_fmt, end_date_fmt + datetime.timedelta(days=1), datetime.timedelta(days=1)): fmt_date_list.append( datetime.datetime.strftime(result, fmt)) for i in row_list: if i[0] in fmt_date_list: search_list.append(i) get_options_to_edit(search_list, row_list, self.spreadsheet) search_by_date = False else: selected_dates = [] task_date = get_date( "Chosen date will list all entrie" + "s with matching Task Date") for i in row_list: if i[0] == task_date: selected_dates.append(i) get_options_to_edit(selected_dates, row_list, self.spreadsheet) search_by_date = False elif user_choice == '2': selected_entries = [] while True: clear() print("Seach an entry by time\n") hours = input("Hours: ") minutes = input("Minutes: ") if hours == '': hours = '0' if minutes == '': minutes = '0' try: int(hours) int(minutes) except ValueError: print("Invalid Entry") input("Press Enter") else: task_duration = TimeHandler(int(hours), int(minutes)) h_fmt, m_fmt = task_duration.get_hours_minutes() time_spent = "Hours:{} Minutes:{}".format(h_fmt, m_fmt) # Time spent break for row in row_list: if row[2] == time_spent: selected_entries.append(row) get_options_to_edit(selected_entries, row_list, self.spreadsheet) elif user_choice == '3': clear() selected_entries = [] while True: clear() print( "Search an entry by exact match or regular expression\n" ) print("Please enter text or regular expression" + " to match entries") print("Do not add spaces after commas.") string = input("> ") if len(string) < 1: print("Invalid Input") input("Press Enter") else: break search_string = '(?P<results>%s)' % string for row in row_list: row_string = ",".join(row) parse = re.search(r'%s' % search_string, row_string, re.I) if parse is not None: selected_entries.append(row) get_options_to_edit(selected_entries, row_list, self.spreadsheet) elif user_choice == '4': page_range = list(range(0, len(row_list))) page = 0 while True: clear() if len(row_list) == 0: print("You don't have any entries to view.") input("Press enter") break else: current_row = row_list[page] print("Entry #: {}\n".format(page + 1)) print("Date {}".format(current_row[0])) print("Task Name: {}".format(current_row[1])) print("Time Spent: {}".format(current_row[2])) print("Notes: {}\n".format(current_row[3])) print("1. Next Entry") print("2. Previous Entry") print("3. Edit Entry") print("4. Back to previous menu\n") print("Please enter the number of the option" + " you wish to choose.") user_choice = input("> ") if user_choice == '1': if page + 1 in page_range: page = page + 1 else: print("There are no more further entries.") input("Press Enter") elif user_choice == '2': if page - 1 in page_range: page = page - 1 else: print("There are no more previous entries.") input("Press Enter") elif user_choice == '3': edit_delete(row_list[page], row_list, self.spreadsheet) break elif user_choice == '4': break else: print("Invalid Input") input("Press Enter") elif user_choice == '5': break else: print("Invalid Input") input("Press Enter")
def write_to_log(self): task_date = get_date("Task Date") while True: clear() print("Task Date: {}\n".format(task_date)) tester = [] task_name = input("Please enter the name of your task: ") # Task name if len(task_name) > 0: for i in task_name: if i != " ": tester.append(1) if len(tester) > 0: break else: print("Invalid Task Name") input("Press Enter") while True: clear() print("Task Date: {}".format(task_date)) print("Task Name: {}\n".format(task_name)) print("Enter the amount of time spent") hours = input("Hours: ") minutes = input("Minutes: ") if hours == '': hours = '0' if minutes == '': minutes = '0' try: int(hours) int(minutes) except ValueError: print("Invalid Entry") input("Press Enter") else: task_duration = TimeHandler(int(hours), int(minutes)) hours_fmt, minutes_fmt = task_duration.get_hours_minutes() time_spent = "Hours:{} Minutes:{}".format( hours_fmt, minutes_fmt) # Time spent break clear() print("Task Date: {}".format(task_date)) print("Task Name: {}".format(task_name)) print("Time Spent: {}\n".format(time_spent)) notes = input("Enter additional notes (Optional): ") # Notes tester2 = [] if len(notes) > 0: for i in task_name: if i != " ": tester2.append(1) if len(tester2) < 1: notes = 'N/A' with open(self.spreadsheet, 'a') as csvfile: fieldnames = ['Date', 'Task Name', 'Time Spent', 'Notes'] writer = csv.DictWriter(csvfile, fieldnames=fieldnames, lineterminator='\n') writer.writerow({ 'Date': task_date, 'Task Name': task_name, 'Time Spent': time_spent, 'Notes': notes })
import functions as f from functions import Event INCLUDE_MANUAL_EXAMPLE = True # open the data base cal = f.Main_Calendar("demoDB.csv") # print the week of the 7/8/2019 # you can choose any day of the week, and it will print the week sunday to saturday cal.print_week("7/8/2019") # creating new event if INCLUDE_MANUAL_EXAMPLE: start = f.time_format(f.get_date("start"), f.get_time("start")) check_end = False while not check_end: end = f.time_format(f.get_date("end"), f.get_time("end")) check_end = f.date_validation(start, end) title = input("Title: ") event_type = input("Event type: ") price = input("Price: ") invitees = input("Invitees: ") location = input("Location: ") event = f.Event(start, end, title, event_type=event_type, price=price, invitees=invitees, location=location)
def main(date): id_real_sendig = [] full_date = [False, False] sql_con = connect(const.path + 'Bot.db') cursor = sql_con.cursor() if date == '21': cursor.execute('''SELECT id FROM user_data WHERE sending_rasp = 1''') elif date == '17': cursor.execute('''SELECT id FROM user_data WHERE sending_rasp_5 = 1''') sending_sched_one = cursor.fetchall() cursor.close() sql_con.close() for sro in sending_sched_one: if sro[0] not in id_real_sendig: id_real_sendig.append(sro[0]) sql_con = connect(const.path + 'Bot.db') cursor = sql_con.cursor() cursor.execute('''SELECT id_banned FROM banned_users''') id_banned = cursor.fetchall() sql_con.commit() cursor.close() sql_con.close() for ib in id_banned: if ib[0] in id_real_sendig: id_real_sendig.remove(ib[0]) if id_real_sendig: have_sched = [] for irs in id_real_sendig: week = func.get_week() group = func.get_student_group(irs) day_of_week = dt.datetime.isoweekday(dt.datetime.now()) answer = 'Расписание на завтра:\n\n' answer += const.emoji['calendar'] + ' ' answer += (const.num_day[str( dt.datetime.isoweekday(dt.datetime.now() + dt.timedelta(days=1)))] + ', ') full_date = func.get_date(True) answer += full_date[0] + '\n' td = 1 if day_of_week == 7: if week == 'DOWN': answer += const.up_week week = 'UP' elif week == 'UP': answer += const.down_week week = 'DOWN' else: if week == 'UP': answer += const.up_week elif week == 'DOWN': answer += const.down_week answer += const.notify if func.get_alias(irs) == 'PREP': try: day_info = const.teachers_shedule[const.teacher_name[ const.cap_teachers.index(group)]] except: bot.send_message( conf.my_id, str(dt.datetime.now())[:-7] + ' | ' + 'Ошибка при рассылке расписания ' 'для {} "<b>({})</b>"\U00002026:' '\n\n'.format(str(irs), group) + str(sys.exc_info()[1])) else: try: day_info = const.schedule[group] except: bot.send_message( conf.my_id, str(dt.datetime.now())[:-7] + ' | ' + 'Ошибка при рассылке расписания ' 'для {} "<b>({})</b>"\U00002026:' '\n\n'.format(str(irs), group) + str(sys.exc_info()[1])) try: day_info = day_info[week][dt.datetime.isoweekday( dt.datetime.now() + dt.timedelta(days=td)) - 1] except: continue if day_info: answer += func.get_shedule_answer(day_info, full_date[1]) else: continue try: bot.send_message(irs, answer, parse_mode='HTML') have_sched.append(irs) except Exception as err: print(err) bot.send_message( conf.my_id, const.emoji['cross_mark'] + ' ' + str(irs) + '\n' + str(err)) continue sleep(0.04) difference = len(sending_sched_one) - len(have_sched) print('\n' + str(dt.datetime.now())[:-7] + ' | ' + '!!! SENDING SCHEDULE ' + str(date) + ' !!!' + '\n') print('\n\n' + str(have_sched) + '\n\n') print(str(len(sending_sched_one)) + ' - ' + str(len(have_sched))) print(difference) else: sys.exit()
import os import collections as coll import seaborn as sns import matplotlib.pyplot as plt __version__ = '0.1.0' __author__ = 'Jamie Heather' __email__ = '*****@*****.**' if __name__ == '__main__': fxn.check_scripts_dir() sns.set(font="Arial", font_scale=1.5) # Sort directories, get data plot_dir = fxn.plot_dir + fxn.get_date() + '-netmhc-check/' if not os.path.exists(plot_dir): os.mkdir(plot_dir) prediction_data_dir = '../Data/peptide/netMHC/' all_input_files = os.listdir(prediction_data_dir) all_input_files.sort() predictions = [] names = [] # Scroll through all netMHC produced files for f in all_input_files: nam = f.split('-')[0] print nam
out_file_path = '../Data/JY-omes/JY-omes.csv' print "Writing JY-ome values out to", out_file_path + "..." with open(out_file_path, 'w') as out_file: out_file.write('Gene,Transcripts-log2TPM,Protein-log2int\n') for g in all_genes: if g in tpm_dat and g in avg_prot_dat: out_file.write(g + ',' + str(tpm_dat[g]) + ',' + str(avg_prot_dat[g]) + '\n') elif g in avg_prot_dat and g not in tpm_dat: out_file.write(g + ',,' + str(avg_prot_dat[g]) + '\n') elif g in tpm_dat and g not in avg_prot_dat: out_file.write(g + ',' + str(tpm_dat[g]) + ',\n') print "\t... done!" print "Downloading proteome files..." # os.chdir('../Data/') for proteome in [x for x in fxn.proteome_key if 'UP' in x]: print "\tGetting", fxn.proteome_key[proteome], "proteome file..." out_path = '../Data/' + fxn.get_date( ) + '_' + proteome + '_' + fxn.proteome_key[proteome] + '.fasta.gz' url = urllib2.urlopen( 'https://www.uniprot.org/uniprot/?query=proteome:' + proteome + '&format=fasta&compress=yes') url_data = url.read() with open(out_path, 'wb') as out_file: out_file.write(url_data)
def message(nick, ident, chan, msg): try: if chan == config.connection.channel and (DickServ.status or ident == config.settings.admin): if not msg.startswith(config.settings.cmd_char): urls = httplib.parse_urls(msg) if urls: if time.time() - DickServ.last > 3: DickServ.last = time.time() Events.url(chan, urls[0]) elif msg == '@dickserv': Commands.sendmsg(chan, constants.bold + 'DickServ IRC Bot - Developed by acidvegas in Python - https://git.acid.vegas/dickserv') elif msg == '@dickserv help': Commands.sendmsg(chan, 'https://git.supernets.org/acidvegas/dickserv#commands') elif msg == 'h' and functions.luck(4): Commands.sendmsg(chan, 'h') elif 'qhat' in msg: Commands.sendmsg(chan, 'Q:)') elif ident not in database.Ignore.idents(): if time.time() - DickServ.last < 3 and ident != config.settings.admin: if not DickServ.slow: Commands.sendmsg(chan, color('Slow down nerd!', constants.red)) DickServ.slow = True else: DickServ.slow = False args = msg.split() argz = msg[len(args[0])+1:] cmd = args[0][1:] if len(args) == 1: if cmd == 'date': Commands.sendmsg(chan, functions.current_date()) elif cmd == 'talent': if functions.luck(1000): Commands.sendmsg(chan, color(f' !!! HOLY F*****G SHIT {nick} ACHIEVED TALENT !!! ', 'random', 'random')) Commands.sendmsg(chan, color(' !!! RIP DITTLE DIP DIP DIP DIP IT\'S YOUR BIRTHDAY !!! ', 'random', 'random')) Commands.sendmsg(chan, color(f' !!! CAN WE HAVE A GOT DAMN MOMENT OF SILENCE FOR {nick} :) !!! ', 'random', 'random')) Commands.sendmsg(chan, color(' !!! GOT DAMN XD THIS IS TOO CRAZY LIKE...DAMN HAHA. DAMN. !!! ', 'random', 'random')) else: Commands.sendmsg(chan, color('(^)', 'random')) elif cmd == 'todo': todos = database.Todo.read(ident) if todos: for item in todos: Commands.notice(nick, '[{0}] {1}'.format(color(todos.index(item)+1, constants.pink), item)) else: Commands.notice(nick, 'You have no saved todos.') elif cmd == 'uptime': Commands.sendmsg(chan, functions.uptime(DickServ.start)) elif len(args) == 2: if cmd == 'coin': api = cryptocurrency.get(args[1]) if api: Commands.sendmsg(chan, '{0} {1} - ${2:,.2f}'.format(color(api['name'], constants.white), color('({0})'.format(api['symbol']), constants.grey), float(api['price_usd']))) else: Commands.error(chan, 'Invalid cryptocurrency name!') elif cmd == 'drug': api = tripsit.drug(args[1]) if api: Commands.sendmsg(chan, '{0} - {1}'.format(color(api['name'], constants.yellow), api['desc'])) else: Commands.error(chan, 'No results found.') elif cmd == 'define': definition = dictionary.define(args[1]) if definition: Commands.sendmsg(chan, '{0} - {1}: {2}'.format(color('Definition', constants.white, constants.blue), args[1].lower(), definition)) else: Commands.error(chan, 'No results found.') elif cmd == 'isup': Commands.sendmsg(chan, '{0} is {1}'.format(args[1], isup.check(args[1]))) elif cmd == 'r': api = reddit.read(args[1]) if api: data = list(api.keys()) for i in data: count = str(data.index(i)+1) Commands.sendmsg(chan, '[{0}] {1} [{2}|{3}/{4}|{5}]'.format(color(count, constants.pink), functions.trim(i, 100), color(str(api[i]['score']), constants.white), color('+' + str(api[i]['ups']), constants.green), color('-' + str(api[i]['downs']), constants.red), color(api[i]['comments'], constants.white))) Commands.sendmsg(chan, ' - ' + color(api[i]['url'], constants.grey)) else: Commands.error(chan, 'No results found.') elif cmd == 'w': if args[1].isdigit(): api = weather.lookup(args[1]) if api: Commands.sendmsg(chan, api) else: Commands.error(chan, 'No results found.') else: Commands.error(chan, 'Invalid arguments.') if len(args) >= 2: if cmd == 'g': api = google.search(argz, database.Settings.get('max_results')) if api: for result in api: count = api.index(result)+1 Commands.sendmsg(chan, '[{0}] {1}'.format(color(count, constants.pink), result['title'])) Commands.sendmsg(chan, ' - ' + color(result['link'], constants.grey)) else: Commands.error(chan, 'No results found.') elif cmd == 'imdb': api = imdb.search(argz) if api: Commands.sendmsg(chan, '{0} {1} {2} {3}'.format(color('Title :', constants.white), api['Title'], api['Year'], color(api['Rated'], constants.grey))) Commands.sendmsg(chan, '{0} {1}{2}'.format(color('Link :', constants.white), constants.underline, color('https://imdb.com/title/' + api['imdbID'], constants.light_blue))) Commands.sendmsg(chan, '{0} {1}'.format(color('Genre :', constants.white), api['Genre'])) if api['imdbRating'] == 'N/A': Commands.sendmsg(chan, '{0} {1} 0/10'.format(color('Rating :', constants.white), color('★★★★★★★★★★', constants.grey))) else: Commands.sendmsg(chan, '{0} {1}{2} {3}/10'.format(color('Rating :', constants.white), color('★'*round(float(api['imdbRating'])), constants.yellow), color('★'*(10-round(float(api['imdbRating']))), constants.grey), api['imdbRating'])) Commands.sendmsg(chan, '{0} {1}'.format(color('Plot :', constants.white), api['Plot'])) else: Commands.error(chan, 'No results found.') elif cmd == 'netsplit': api = netsplit.search(argz) if api: data = list(api.keys()) for i in data: count = str(data.index(i)+1) Commands.sendmsg(chan, '[{0}] {1} {2} / {3}'.format(color(count, constants.pink), color(i, constants.light_blue), color('({0})'.format(api[i]['users']), constants.grey), color(api[i]['network'], constants.red))) Commands.sendmsg(chan, color(' - ' + api[i]['topic'], constants.grey)) else: Commands.error(chan, 'No results found.') elif cmd == 'todo' and len(args) >= 3: if len(args) >= 3 and args[1] == 'add': todos = database.Todo.read(ident) if len(todos) <= database.Settings.get('max_todo_per') and len(database.Todo.read()) <= database.Settings.get('max_todo'): argz = argz[4:] if argz not in todos: database.Todo.add(functions.get_date(), ident, argz) Commands.notice(nick, 'Todo added to database!') else: Commands.notice(nick, 'Todo already in database!') else: Commands.notice(nick, 'Maximum todos reached!') elif len(args) == 3 and args[1] == 'del': num = args[2] if num.isdigit(): num = int(num) todos = database.Todo.read(ident) if todos: if num <= len(todos): for item in todos: count = todos.index(item)+1 if count == num: database.Todo.remove(ident, item) break Commands.notice(nick, 'Todo removed from database!') else: Commands.notice(nick, 'Invalid number.') else: Commands.notice(nick, 'No todos found.') else: Commands.notice(nick, 'Invalid number.') else: Commands.notice(nick, 'Invalid arguments.') elif cmd == 'tpb': api = tpb.search(argz, database.Settings.get('max_results')) if api: data = list(api.keys()) for i in data: count = str(data.index(i)+1) Commands.sendmsg(chan, '[{0}] {1} [{2}/{3}]'.format(color(count, constants.pink), i, color(api[i]['seeders'], constants.green), color(api[i]['leechers'], constants.red))) Commands.sendmsg(chan, ' - ' + color('http://thepiratebay.org' + api[i]['url'], constants.grey)) else: Commands.error(chan, 'No results found.') elif cmd == 'ud': definition = dictionary.urban(argz) if definition: Commands.sendmsg(chan, '{0}{1} - {2}: {3}'.format(color('urban', constants.white, constants.blue), color('DICTIONARY', constants.yellow, constants.black), argz, definition)) else: Commands.error(chan, 'No results found.') elif cmd == 'wolfram': results = wolfram.ask(argz) if results: Commands.sendmsg(chan, '{0}{1} - {2}'.format(color('Wolfram', constants.red), color('Alpha', constants.orange), results)) else: Commands.error(chan, 'No results found.') elif cmd == 'yt': api = youtube.search(argz, database.Settings.get('max_results')) if api: data = list(api.keys()) for i in api.keys(): count = str(data.index(i)+1) Commands.sendmsg(chan, '[{0}] {1}'.format(color(count, constants.pink), functions.trim(i, 75))) Commands.sendmsg(chan, ' - ' + color(api[i], constants.grey)) else: Commands.error(chan, 'No results found.') DickServ.last = time.time() except Exception as ex: Commands.error(chan, 'Command threw an exception.', ex)
player = re.findall('\\d. .*\\n', line) if len(player) > 0: split = re.findall('\\S*', player[0]) tag = "#" + split[2].lower() + split[4].lower() paid = "x" in split[6].lower() wallet = "" if "p" in split[6].lower(): wallet = "#przelew" elif "z" in split[6].lower(): wallet = "#zgorki" elif "g" in split[6].lower(): wallet = "#gotowka" operations.append("$najemSali #czecha " + tag + " -10,25 PLN") if paid: operations.append("$najemSali #czecha " + tag + " " + wallet + " +11 PLN") if len(operations) > 0: login = config['volleyball_login'] password = config['volleyball_password'] url = config['payzzer_url'] driver = fun.get_driver(url, login, password) token = fun.get_token(driver) board_id = fun.get_board_id(driver) date = fun.get_date("2019-11-10 19:30:00") for command in operations: fun.add_operation(driver, token, board_id, command, date) # fun.remove_range(657557, 657577, driver, token, board_id) else: print("Brak pliku konfiguracyjnego.")
def get_peptide_values(list_peptides, descriptor_name): """ :param list_peptides: List of amino acid peptides :param descriptor_name: MODLamp-prescribed descriptor name :return: corresponding values for that descriptor for each of the peptides in the input list """ properties = PeptideDescriptor(list_peptides, descriptor_name) properties.calculate_moment() return [x[0] for x in properties.descriptor] data_dir = '../Data/NonPredictedBinders/' plot_dir = fxn.plot_dir + fxn.get_date() + '-NPB-peptide-properties/' if not os.path.exists(plot_dir): os.mkdir(plot_dir) pep_files = [x for x in os.listdir(data_dir) if x.endswith('.txt')] peptides = coll.defaultdict(list) for f in pep_files: nam = f.split('-')[0] with open(data_dir + f, 'rU') as in_file: for line in in_file: peptides[nam].append(line.rstrip()) eisenbergs = coll.defaultdict(list) eisenbergs_long = []
# coding:UTF-8 # functions: 自作関数(functions.pyからインポート) # Json: Jsonデータを扱うためのモジュール # colorama: 出力文字色を変更するためのモジュール import functions, json import colorama from colorama import Fore, Back, Style # day, month, year に、当日の日付を代入 day, month = functions.get_date() year = functions.get_year() print("今日は" + str(month) + "月" + str(day) + "日です。") # 既存のdata.jsonファイルからデータを読み込む # try-exceptで例外処理 # data.jsonが空の場合(初回使用向け),エラーを防ぐために、ダミーデータを書き込む try: li = list() jsonData = functions.outputJson() for data in jsonData: # dataからそれぞれの締切日を計算する data_year = int(data['kadai']['deadline'] / 10000) data_month = int(data['kadai']['deadline'] % 10000 / 100) data_day = int(data['kadai']['deadline'] % 10000 % 100) # ダミーデータを追加する if data['kadai']['subject'] == "ダミー": li.append(data) continue # data_year, data_month, data_day から締切日を過ぎているか判断 if data_year > year: li.append(data)
""" :param number: a float between 0 and 1 (a p value) :return: string of formatted p value (to 3 sig figs if > 0.001, otherwise in scientific notation) """ if number > 0.001: return "{0:.3f}".format(number) else: return "{:.2E}".format(number) # if __name__ == '__main__': # Initialise directory fxn.check_scripts_dir() sns.set(font="Arial", font_scale=1.5) plot_dir = fxn.plot_dir + fxn.get_date() + '-weights/' if not os.path.exists(plot_dir): os.mkdir(plot_dir) # Read in data weights = [] with open('../Data/sample-weights.csv', 'rU') as in_file: line_count = 0 for line in in_file: bits = line.rstrip().split(',') if line_count == 0: headers = bits else: weights.append([int(x) for x in bits[:2]] + [bits[2]]) line_count += 1
import seaborn as sns import pandas as pd import matplotlib.pyplot as plt from scipy import stats __version__ = '0.4.2' __author__ = 'Jamie Heather' __email__ = '*****@*****.**' if __name__ == '__main__': fxn.check_scripts_dir() sns.set(font="Arial", font_scale=1.5) # Sort directories, get data plot_dir = fxn.plot_dir + fxn.get_date() + '-peptide-analysis/' if not os.path.exists(plot_dir): os.mkdir(plot_dir) pep_data_dir = '../Data/peptide/' prot_data_dir = '../Data/peptide-prot/' all_files = os.listdir(pep_data_dir) # Only take the JY samples Mouse = [ x for x in all_files if x.startswith('M') and '205' not in x and '436' not in x ] Cultured = [ x for x in all_files
def add_holiday(db, holiday, reason=""): holiday = functions.get_date(holiday) return db.execute("INSERT INTO holidays (holiday, reason) VALUES (%s, %s)", holiday, reason)
def get_assistant(self): global EVENTS_REMINDER_SERVICE global NOTE_MAKING_SERVICE global MUSIC_PLAYING_SERVICE global QUERY_SERVICE awake = "" events_reminder_strings = [] note_making_strings = [] music_playing_strings = [] query_service_strings = [] if (not is_internet() and (EVENTS_REMINDER_SERVICE or NOTE_MAKING_SERVICE or MUSIC_PLAYING_SERVICE or QUERY_SERVICE)): show_error_message( title="Connection error", message= "Services are activated that required an internet connection.") self.status_bar[ "text"] = "Sorry, Services are activated that required an internet connection." # Disable all activated services. config = configparser.ConfigParser() config.read("config.ini") if self.p1.events_reminder_service_var.get(): self.p1.events_reminder_service_var.set(False) EVENTS_REMINDER_SERVICE = False config["DEFAULT"]["events_reminder_service"] = "0" if self.p1.note_making_service_var.get(): self.p1.note_making_service_var.set(False) NOTE_MAKING_SERVICE = False config["DEFAULT"]["note_making_service"] = "0" if self.p1.music_playing_service_var.get(): self.p1.music_playing_service_var.set(False) MUSIC_PLAYING_SERVICE = False config["DEFAULT"]["music_playing_service"] = "0" if self.p1.query_service_var.get(): self.p1.query_service_var.set(False) QUERY_SERVICE = False config["DEFAULT"]["query_service"] = "0" # Write into config file with open('config.ini', 'w') as configfile: config.write(configfile) else: with open("events_reminder_strings.txt", "r") as file: events_reminder_strings = file.read().split(";") with open("note_making_strings.txt", "r") as file: note_making_strings = file.read().split(";") with open("music_playing_strings.txt", "r") as file: music_playing_strings = file.read().split(";") with open("query_service_strings.txt", "r") as file: query_service_strings = file.read().split(";") with open("assistant_strings.txt", "r") as file: awake = file.read() try: print("Say '" + awake + "' for response") self.status_bar["text"] = "Say '" + awake + "' for response" if get_audio( status_bar=self.status_bar).lower().count(awake) > 0: speak("Hello, I am your assistant. How can I help you?") text = get_audio(status_bar=self.status_bar).lower() recognize = False today = datetime.date.today() if EVENTS_REMINDER_SERVICE: for phrase in events_reminder_strings: if phrase in text: recognize = True try: date = get_date(text) except ValueError: speak( "Sorry, It's not a valid date, Please try again with a valid date." ) self.status_bar[ "text"] = "Sorry, It's not a valid date! Please try again with a valid date." break if date: if date < today: speak( "Sorry, you have mentioned a past day, Please mention an upcoming day." ) self.status_bar[ "text"] = "Sorry, you have mentioned a past day! Please mention an upcoming day." break SERVICE = authenticate_google_calender( message_box=tkinter.messagebox) if SERVICE: get_events(date, SERVICE, status_bar=self.status_bar) else: speak( "Sorry, I can not read your calendar, Please give the permission first." ) self.status_bar[ "text"] += ", Sorry, I can't read your Calendar! Please give the permission first." break else: speak( "I can't help you, without mentioning a day, please try again, with mention a day." ) self.status_bar[ "text"] += ", Please mention with a day of week." break if NOTE_MAKING_SERVICE: for phrase in note_making_strings: if phrase in text: recognize = True speak("What would you, like to write?") note_text = get_audio( status_bar=self.status_bar) make_note(note_text) speak("I have made a note of that") break if MUSIC_PLAYING_SERVICE: for phrase in music_playing_strings: if phrase in text: recognize = True speak("What would you, like to play?") music_text = get_audio( status_bar=self.status_bar) play_from_online(music_text, status_bar=self.status_bar) break if QUERY_SERVICE: for phrase in query_service_strings: if phrase in text: recognize = True speak("What would you, like to know?") query_text = get_audio( status_bar=self.status_bar) query_from_online(query_text, status_bar=self.status_bar) break if not recognize: speak("Sorry, I can't understan, Please try again") self.status_bar[ "text"] += ", Couldn't understant! Please try again" except: pass self.service_start_btn_var.set("Start Service")
def test_get_date(self): with unittest.mock.patch('builtins.input', side_effect=['asdfasdf', '', '5/23/2017']): self.assertIsInstance(get_date("Text"), datetime.date)
def message(nick, ident, chan, msg): try: if chan == config.connection.channel and ( DickServ.status or ident == config.settings.admin): if not msg.startswith(config.settings.cmd_char): urls = httplib.parse_urls(msg) if urls: if time.time() - DickServ.last > 3: DickServ.last = time.time() Events.url(chan, urls[0]) elif msg == '@dickserv': Commands.sendmsg( chan, constants.bold + 'DickServ IRC Bot - Developed by acidvegas in Python - https://acid.vegas/dickserv' ) elif msg == '@dickserv help': Commands.sendmsg( chan, 'https://git.supernets.org/acidvegas/dickserv#commands' ) elif msg == 'h' and functions.luck(4): Commands.sendmsg(chan, 'h') elif 'qhat' in msg: Commands.sendmsg(chan, 'Q:)') elif ident not in database.Ignore.idents(): if time.time( ) - DickServ.last < 3 and ident != config.settings.admin: if not DickServ.slow: Commands.sendmsg( chan, color('Slow down nerd!', constants.red)) DickServ.slow = True else: DickServ.slow = False args = msg.split() argz = msg[len(args[0]) + 1:] cmd = args[0][1:] if len(args) == 1: if cmd == 'date': Commands.sendmsg(chan, functions.current_date()) elif cmd == 'talent': if functions.luck(1000): Commands.sendmsg( chan, color( f' !!! HOLY F*****G SHIT {nick} ACHIEVED TALENT !!! ', 'random', 'random')) Commands.sendmsg( chan, color( ' !!! RIP DITTLE DIP DIP DIP DIP IT\'S YOUR BIRTHDAY !!! ', 'random', 'random')) Commands.sendmsg( chan, color( f' !!! CAN WE HAVE A GOT DAMN MOMENT OF SILENCE FOR {nick} :) !!! ', 'random', 'random')) Commands.sendmsg( chan, color( ' !!! GOT DAMN XD THIS IS TOO CRAZY LIKE...DAMN HAHA. DAMN. !!! ', 'random', 'random')) else: Commands.sendmsg(chan, color('(^)', 'random')) elif cmd == 'todo': todos = database.Todo.read(ident) if todos: for item in todos: Commands.notice( nick, '[{0}] {1}'.format( color( todos.index(item) + 1, constants.pink), item)) else: Commands.notice( nick, 'You have no saved todos.') elif cmd == 'uptime': Commands.sendmsg( chan, functions.uptime(DickServ.start)) elif len(args) == 2: if cmd == 'coin': api = cryptocurrency.get(args[1]) if api: Commands.sendmsg( chan, '{0} {1} - ${2:,.2f}'.format( color(api['name'], constants.white), color( '({0})'.format(api['symbol']), constants.grey), float(api['price_usd']))) else: Commands.error( chan, 'Invalid cryptocurrency name!') elif cmd == 'drug': api = tripsit.drug(args[1]) if api: Commands.sendmsg( chan, '{0} - {1}'.format( color(api['name'], constants.yellow), api['desc'])) else: Commands.error(chan, 'No results found.') elif cmd == 'define': definition = dictionary.define(args[1]) if definition: Commands.sendmsg( chan, '{0} - {1}: {2}'.format( color('Definition', constants.white, constants.blue), args[1].lower(), definition)) else: Commands.error(chan, 'No results found.') elif cmd == 'isup': Commands.sendmsg( chan, '{0} is {1}'.format( args[1], isup.check(args[1]))) elif cmd == 'r': api = reddit.read(args[1]) if api: data = list(api.keys()) for i in data: count = str(data.index(i) + 1) Commands.sendmsg( chan, '[{0}] {1} [{2}|{3}/{4}|{5}]'. format( color(count, constants.pink), functions.trim(i, 100), color(str(api[i]['score']), constants.white), color('+' + str(api[i]['ups']), constants.green), color( '-' + str(api[i]['downs']), constants.red), color(api[i]['comments'], constants.white))) Commands.sendmsg( chan, ' - ' + color( api[i]['url'], constants.grey)) else: Commands.error(chan, 'No results found.') elif cmd == 'w': if args[1].isdigit(): api = weather.lookup(args[1]) if api: Commands.sendmsg(chan, api) else: Commands.error(chan, 'No results found.') else: Commands.error(chan, 'Invalid arguments.') if len(args) >= 2: if cmd == 'g': api = google.search( argz, database.Settings.get('max_results')) if api: for result in api: count = api.index(result) + 1 Commands.sendmsg( chan, '[{0}] {1}'.format( color(count, constants.pink), result['title'])) Commands.sendmsg( chan, ' - ' + color(result['link'], constants.grey)) else: Commands.error(chan, 'No results found.') elif cmd == 'imdb': api = imdb.search(argz) if api: Commands.sendmsg( chan, '{0} {1} {2} {3}'.format( color('Title :', constants.white), api['Title'], api['Year'], color(api['Rated'], constants.grey))) Commands.sendmsg( chan, '{0} {1}{2}'.format( color('Link :', constants.white), constants.underline, color( 'https://imdb.com/title/' + api['imdbID'], constants.light_blue))) Commands.sendmsg( chan, '{0} {1}'.format( color('Genre :', constants.white), api['Genre'])) if api['imdbRating'] == 'N/A': Commands.sendmsg( chan, '{0} {1} 0/10'.format( color('Rating :', constants.white), color('★★★★★★★★★★', constants.grey))) else: Commands.sendmsg( chan, '{0} {1}{2} {3}/10'.format( color('Rating :', constants.white), color( '★' * round( float(api['imdbRating'] )), constants.yellow), color( '★' * (10 - round( float(api['imdbRating'] ))), constants.grey), api['imdbRating'])) Commands.sendmsg( chan, '{0} {1}'.format( color('Plot :', constants.white), api['Plot'])) else: Commands.error(chan, 'No results found.') elif cmd == 'netsplit': api = netsplit.search(argz) if api: data = list(api.keys()) for i in data: count = str(data.index(i) + 1) Commands.sendmsg( chan, '[{0}] {1} {2} / {3}'.format( color(count, constants.pink), color(i, constants.light_blue), color( '({0})'.format( api[i]['users']), constants.grey), color(api[i]['network'], constants.red))) Commands.sendmsg( chan, color(' - ' + api[i]['topic'], constants.grey)) else: Commands.error(chan, 'No results found.') elif cmd == 'todo' and len(args) >= 3: if len(args) >= 3 and args[1] == 'add': todos = database.Todo.read(ident) if len(todos) <= database.Settings.get( 'max_todo_per' ) and len(database.Todo.read( )) <= database.Settings.get('max_todo'): argz = argz[4:] if argz not in todos: database.Todo.add( functions.get_date(), ident, argz) Commands.notice( nick, 'Todo added to database!') else: Commands.notice( nick, 'Todo already in database!') else: Commands.notice( nick, 'Maximum todos reached!') elif len(args) == 3 and args[1] == 'del': num = args[2] if num.isdigit(): num = int(num) todos = database.Todo.read(ident) if todos: if num <= len(todos): for item in todos: count = todos.index( item) + 1 if count == num: database.Todo.remove( ident, item) break Commands.notice( nick, 'Todo removed from database!' ) else: Commands.notice( nick, 'Invalid number.') else: Commands.notice( nick, 'No todos found.') else: Commands.notice( nick, 'Invalid number.') else: Commands.notice(nick, 'Invalid arguments.') elif cmd == 'tpb': api = tpb.search( argz, database.Settings.get('max_results')) if api: data = list(api.keys()) for i in data: count = str(data.index(i) + 1) Commands.sendmsg( chan, '[{0}] {1} [{2}/{3}]'.format( color(count, constants.pink), i, color(api[i]['seeders'], constants.green), color(api[i]['leechers'], constants.red))) Commands.sendmsg( chan, ' - ' + color( 'http://thepiratebay.org' + api[i]['url'], constants.grey)) else: Commands.error(chan, 'No results found.') elif cmd == 'ud': definition = dictionary.urban(argz) if definition: Commands.sendmsg( chan, '{0}{1} - {2}: {3}'.format( color('urban', constants.white, constants.blue), color('DICTIONARY', constants.yellow, constants.black), argz, definition)) else: Commands.error(chan, 'No results found.') elif cmd == 'wolfram': results = wolfram.ask(argz) if results: Commands.sendmsg( chan, '{0}{1} - {2}'.format( color('Wolfram', constants.red), color('Alpha', constants.orange), results)) else: Commands.error(chan, 'No results found.') elif cmd == 'yt': api = youtube.search( argz, database.Settings.get('max_results')) if api: data = list(api.keys()) for i in api.keys(): count = str(data.index(i) + 1) Commands.sendmsg( chan, '[{0}] {1}'.format( color(count, constants.pink), functions.trim(i, 75))) Commands.sendmsg( chan, ' - ' + color(api[i], constants.grey)) else: Commands.error(chan, 'No results found.') DickServ.last = time.time() except Exception as ex: Commands.error(chan, 'Command threw an exception.', ex)
import seaborn as sns import numpy as np import matplotlib.pyplot as plt import scipy.stats as stats __version__ = '0.3.1' __author__ = 'Jamie Heather' __email__ = '*****@*****.**' if __name__ == '__main__': fxn.check_scripts_dir() sns.set(font="Arial", font_scale=1.5) # Sort directories, get data plot_dir = fxn.plot_dir + fxn.get_date() + '-mouse-proteome-check/' if not os.path.exists(plot_dir): os.mkdir(plot_dir) # Read proteome into dict mouse_proteome_file = [ x for x in os.listdir(fxn.base_data_dir) if '_mouse.fasta' in x ][0] mouse_proteins = coll.defaultdict() with gzip.open(fxn.base_data_dir + mouse_proteome_file, 'rU') as in_file: for protein, seq, blank in fxn.read_fa(in_file): mouse_proteins[protein.split(' ')[0]] = seq # Then scroll through non-predicted binder files, build an AC trie of all the peptides per file data_dir = '../Data/NonPredictedBinders/'
if len([y for y in list(value_df.loc[x]) if y > 0]) == i and value_df.loc[x][0] > 0 ]: for val in [x for x in value_df.loc[thing] if x > 0]: vals.append(['C+' + str(i - 1) + 'm', thing, val]) return fxn.list_to_df(vals, headers, False) if __name__ == '__main__': fxn.check_scripts_dir() sns.set(font="Arial", font_scale=1.5) # Sort directories, get data plot_dir = fxn.plot_dir + fxn.get_date() + '-phospho-analysis/' if not os.path.exists(plot_dir): os.mkdir(plot_dir) pep_data_dir = '../Data/phospho/' prot_data_dir = '../Data/phospho-prot/' all_files = os.listdir(pep_data_dir) Mouse = [ x for x in all_files if x.startswith('M') and '436' not in x and 'MCF7' not in x ] Cultured = [ x for x in all_files if x.startswith('C') and '436' not in x and 'MCF7' not in x
import os import collections as coll import seaborn as sns import matplotlib.pyplot as plt __version__ = '0.1.0' __author__ = 'Jamie Heather' __email__ = '*****@*****.**' if __name__ == '__main__': fxn.check_scripts_dir() sns.set(font="Arial", font_scale=1.5) # Sort directories, get data plot_dir = fxn.plot_dir + fxn.get_date() + '-other-cell-lines/' if not os.path.exists(plot_dir): os.mkdir(plot_dir) pep_data_dir = '../Data/peptide/' phospho_data_dir = '../Data/phospho/' nam_key = {'C': 'Cultured', 'M': 'Mouse'} hla_types = { 'Colo205': ['HLA-A0101', 'HLA-A0201', 'HLA-B0702', 'HLA-B0801', 'HLA-C0702'], 'MDA-MB-436': ['HLA-A0101', 'HLA-B0801', 'HLA-C0702'] } # NB: Colo205 and MDA-MB-436 actually have HLA-C*07:01, not :02, but MHCflurry doesn't cover 01 # First do the non-phospho immunopeptidomes