def endGame(bot, currentMessage, chat_id): # /quit behavior ends the game for everyone gameRecords = Base("chatStorage/records.pdl") gameRecords.open() rec = gameRecords._groupChatID[str(chat_id)] # select all the records with chat_id (only 1) if not rec: botSendFunctions.sendText(bot, chat_id, "Invalid command format") return rec = rec[-1] # Strip the last record from the list pointsBoard = "Here are the scores\n" # Send the final scores to the group for name, points in zip(rec['memberUsernames'].split(), rec['memberPoints'].split()): pointsBoard += str(name) + ": " + str(points) + " point(s)\n" botSendFunctions.sendText(bot, chat_id, pointsBoard) for player in rec['memberChatIDs'].split(): # Clean out the playerCards global try: del globalVars.playerCards[player] except Exception: # If a player isn't there ignore it pass try: del globalVars.resp[rec['gameID']] # Delete the game's responses key del globalVars.currBlackCard[rec['gameID']] # Delete the game's current black card key del globalVars.whiteCards[rec['gameID']] except Exception: pass gameRecords.delete(rec) # Remove the database record gameRecords.commit() # Save the changes botSendFunctions.sendText(bot, chat_id, "Goodbye!")
def lambda_handler(event, session): import boto3 from pydblite import Base db = Base('/tmp/TechHub.pld') if db.exists(): db.open() else: db.create('name', 'quantity') db.open() dynamodb = boto3.client('dynamodb') print("[INTENT_HANDLER]") print("event.session.application.applicationId=" + event['session']['application']['applicationId']) logger.info('got event{}'.format(event)) if event['session']['new']: on_session_started({'requestId': event['request']['requestId']}, event['session']) if event['request']['type'] == "LaunchRequest": output = on_launch(event['request'], event['session']) elif event['request']['type'] == "IntentRequest": output = on_intent(event['request'], event['session'], db, dynamodb) elif event['request']['type'] == "SessionEndedRequest": output = on_session_ended(event['request'], event['session']) db.commit() return output
def run_class_configuration(request): if request.method == 'POST': db = Base('backendDB.pdl') if db.exists(): db.open() else: db.create('Type','Log', 'Run', 'Prefix','Rule','Threshold', 'TimeStamp', 'Status') configuration_json = json.loads(request.body) print configuration_json log = configuration_json["log"] prefix = configuration_json['prefix'] rule = configuration_json['rule'] threshold = configuration_json['threshold'] # Encode the file. encoding.encode(log, prefix) for encodingMethod in configuration_json['encoding']: for clustering in configuration_json['clustering']: for classification in configuration_json['classification']: django_rq.enqueue(tasks.classifierTask, log, prefix, encodingMethod, clustering, classification, rule, threshold) run = classification + '_' + encodingMethod + '_' + clustering records = [r for r in db if r['Run'] == run and r['Prefix'] == str(prefix) and r['Log'] == log and r['Rule'] == rule and r['Threshold'] == str(threshold)] print records if not records: db.insert("Classification", log, run, str(prefix), rule, str(threshold), time.strftime("%b %d %Y %H:%M:%S", time.localtime()), 'queued') else: db.update(records[0], TimeStamp=time.strftime("%b %d %Y %H:%M:%S", time.localtime()), Status= 'queued') db.commit() return HttpResponse("YOLO")
def winner(bot, currentMessage, chat_id): # Decide who wins here. Only the judge is able to use this gameRecords = Base("chatStorage/records.pdl") gameRecords.open() rec = gameRecords._gameID[currentMessage.text[5:10]] if not rec: botSendFunctions.sendText(bot, chat_id, "Invalid command format") return rec = rec[-1] if currentMessage.from_user.id == rec['creator']: revD = {value: key for key, value in globalVars.resp[rec['gameID']].items()} winningResp = currentMessage.text[11:] if winningResp in revD.keys(): winningPerson = revD[winningResp] pointsList = rec['memberPoints'].split() # List stuff for the database memberList = rec['memberUserIDs'].split() nameList = rec['memberUsernames'].split() pointsList[memberList.index(winningPerson)] = int(pointsList[memberList.index(winningPerson)]) + 1 gameRecords.update(rec, memberPoints=" ".join([str(i) for i in pointsList])) # Points backend for Assign 3 gameRecords.commit() botSendFunctions.sendText(bot, rec['groupChatID'], "The winner was " + nameList[memberList.index(winningPerson)] + " with " + winningResp + " They now have " + str(pointsList[memberList.index(winningPerson)]) + " point(s).") # Send who won to the group chat try: globalVars.currBlackCard[currentMessage.text[5:10]] = str(globalVars.blackCards[rec['gameID']].pop()['Value']) # Get the next black card except IndexError: # If there are no more cards end the game botSendFunctions.sendText(bot, rec['groupChatID'], "Sorry, out of cards. Thanks for playing") endGame(bot, currentMessage, chat_id) return botSendFunctions.sendText(bot, rec['groupChatID'], globalVars.currBlackCard[currentMessage.text[5:10]]) # Send the next black card for player in rec['memberChatIDs'].split(): # Send all the players a new card to replace the one they used del globalVars.resp[rec['gameID']][player] botSendFunctions.sendText(bot, player, "Here are your new cards", 0, globalVars.playerCards[player]) else: botSendFunctions.sendText(bot, chat_id, "Invalid answer") else: botSendFunctions.sendText(bot, chat_id, "You are not the judge")
def write_graph(channel): db = Base(os.path.join(SCRIPT_DIR, f'{channel}_members.db')) db.open() member_data = ((int(l['members'].split()[0]), l['time'].date()) for l in sorted(db, key=lambda x: x['time'])) variant = db[0]['members'].split()[1] # Split the list of combinations in two lists, one for the y values and one for the x values y, x = list(zip(*member_data)) fig = plt.figure() fig.autofmt_xdate() ax = fig.add_subplot(111) p = ax.plot(x, y, 'b') ax.yaxis.set_major_locator(MaxNLocator(integer=True)) date_range = (max(x) - min(x)).days # Change X axis locators for large date ranges if date_range > 365: ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y')) ax.xaxis.set_major_locator(mdates.YearLocator()) ax.xaxis.set_minor_locator(mdates.MonthLocator()) ax.set_xlabel('Date') ax.set_ylabel(f'{variant.capitalize()}') fig.suptitle(f'Number of {variant} for {channel} over time', fontsize=15) ax.set_title(f'Maximum: {max(y)}. Currently: {y[-1]}') ax.set_ylim(bottom=0) print(y[-1]) # Print latest value to stdout plt.xticks(rotation=45) fig.savefig(os.path.join(SCRIPT_DIR, f'{channel}.png'))
def getAnswers(bot, currentMessage, chat_id): # Process the players responses here gameRecords = Base("chatStorage/records.pdl") gameRecords.open() rec = gameRecords._gameID[currentMessage.text[5:10]] if not rec: botSendFunctions.sendText(bot, chat_id, "Invalid command format") return rec = rec[-1] answer = currentMessage.text[11:] if currentMessage.text in [j for i in globalVars.playerCards[str(currentMessage.from_user.id)] for j in i] and not str(currentMessage.from_user.id) in globalVars.resp[rec['gameID']]: globalVars.resp[rec['gameID']][str(currentMessage.from_user.id)] = currentMessage.text[11:] emptyList = [] # List magic due to the way custom keyboards must be sent [[], [], []] try: emptyList.append("/ans " + str(rec['gameID']) + " " + globalVars.whiteCards[rec['gameID']].pop()['Value']) except IndexError: botSendFunctions.sendText(bot, rec['groupChatID'], "Sorry. Out of cards, game over.") endGame(bot, currentMessage, chat_id) return for i in range(len(globalVars.playerCards[str(chat_id)])): if currentMessage.text in globalVars.playerCards[str(chat_id)][i]: globalVars.playerCards[str(chat_id)].pop(i) break globalVars.playerCards[str(chat_id)].append(emptyList) newStr = globalVars.currBlackCard[rec['gameID']].replace("_____", str(answer)) # Send all the responses to the group chat if newStr == globalVars.currBlackCard[rec['gameID']]: # Handling for cards with no 'blank' botSendFunctions.sendText(bot, rec['groupChatID'], str(answer)) else: botSendFunctions.sendText(bot, rec['groupChatID'], newStr) botSendFunctions.sendText(bot, chat_id, "Answer recieved.") if set(globalVars.resp[rec['gameID']].keys()) == set(rec['memberUserIDs'].split()): # If everyone has responded call judge judge(bot, currentMessage.text[5:10], chat_id) else: botSendFunctions.sendText(bot, chat_id, "Invaild card sent.", keyboardLayout=globalVars.playerCards[str(chat_id)])
def playGame(bot, gameID): # Called by /startgame gameRecords = Base("chatStorage/records.pdl") gameRecords.open() rec = gameRecords._gameID[gameID] if not rec: # Error check return rec = rec[-1] globalVars.resp = dict() globalVars.resp[gameID] = dict() globalVars.currBlackCard = dict() def dealCards(): # Add random cards for every player players = rec['memberChatIDs'].split() globalVars.playerCards = dict() for player in players: l = [[] for _ in range(5)] globalVars.playerCards[player] = list() for i in range(5): card = globalVars.whiteCards[rec['gameID']].pop()['Value'] l[i].append(str("/ans " + rec['gameID'] + " " + card)) globalVars.playerCards[player] = l botSendFunctions.sendText(bot, player, "Here are your cards", 0, l) dealCards() globalVars.currBlackCard[gameID] = str(globalVars.blackCards[gameID].pop()['Value']) botSendFunctions.sendText(bot, rec['groupChatID'], globalVars.currBlackCard[gameID], 0, []) # Send a random black card to the group
def getConfStatus(request): db = Base('backendDB.pdl') if db.exists(): db.open() records = []; for r in db: print r records.append(r) return HttpResponse(json.dumps(records), content_type="application/json")
def printdb(dbpath): #Prints the contents of a PyDBLite database to the console db = Base(dbpath) if db.exists(): db.open() retstr = "" for obj in db: retstr += str(obj) retstr += "\n" print retstr return retstr else: print "The database does not exist or is corrupt.\n"
def printdb(dbpath): # Prints the contents of a PyDBLite database to the console db = Base(dbpath) if db.exists(): db.open() retstr = "" for obj in db: retstr += str(obj) retstr += "\n" encoded = retstr.encode("utf-8", errors="ignore") print(encoded) else: print("The database does not exist or is corrupt.\n")
def judge(bot, gameID, chat_id): # Send all the responses to the judge gameRecords = Base("chatStorage/records.pdl") gameRecords.open() rec = gameRecords._gameID[gameID] if not rec: botSendFunctions.sendText(bot, chat_id, "Invalid command format") return rec = rec[-1] l = [[] for _ in range(len(globalVars.resp[rec['gameID']]))] i = 0 for ans in globalVars.resp[rec['gameID']].values(): l[i].append("/win " + gameID + " " + str(ans)) i += 1 botSendFunctions.sendText(bot, rec['creatorChatID'], "Here are the responses", keyboardLayout=l)
def get_all_record_data(): db = Base('nfc_auth_ok_rec.pdl') if not db.exists(): db.create('time', 'device', 'name') db.open() all_str = '[' i = 0 for r in db: obj = '{\"time\":'+str(r['time'])+\ ',\"name\":\"'+r['name']+\ '\",\"device\":\"'+r['device']+'\"}' all_str += obj if i < len(db) - 1: all_str += ',' i = i + 1 all_str += ']' return all_str
def load_repo(db_path): job_db = Base(os.path.join(db_path, 'PBS_job_database.pdl')) if job_db.exists(): job_db.open() print("PBS_database found. Loading...\n") all_items = list_queue() pbs_id = [] for line in all_items: pbs_id.append(str(re.search(r'\d+', line).group())) for ele in pbs_id: ele_dir = init_work_dir(ele) ele_id = re.findall(r'\d+', ele_dir)[-1] if len(job_db(PBS_id=ele)) == 0: job_db.insert(PBS_id=ele, work_dir=ele_dir, uniq_id=ele_id) else: job_db = new_repo(db_path) job_db.commit()
def run_configuration(request): if request.method == 'POST': db = Base('backendDB.pdl') # db.create('Type','Log', 'Run', 'Prefix','Rule','Threshold', 'TimeStamp', 'Status', mode="override") if db.exists(): db.open() else: db.create('Type','Log', 'Run', 'Prefix','Rule','Threshold', 'TimeStamp', 'Status') configuration_json = json.loads(request.body) print configuration_json log = configuration_json["log"] prefix = configuration_json['prefix'] # Encode the file. encoding.encode(log, prefix) for encodingMethod in configuration_json['encoding']: for clustering in configuration_json['clustering']: for regression in configuration_json['regression']: django_rq.enqueue(tasks.regressionTask, log, prefix, encodingMethod, clustering, regression) run = regression + '_' + encodingMethod + '_' + clustering records = [r for r in db if r['Run'] == run and r['Prefix'] == str(prefix) and r['Log'] == log] # for r in db: # if (r['Run'] == run) and (r['Prefix'] == str(prefix)) and (r['Log'] == log): # records.append(r) print records if not records: db.insert("Regression", log, run, str(prefix),"NaN","NaN", time.strftime("%b %d %Y %H:%M:%S", time.localtime()), 'queued') else: db.update(records[0], TimeStamp=time.strftime("%b %d %Y %H:%M:%S", time.localtime()), Status= 'queued') # if run in df['Run'].unique(): # df.loc[df.Run == run, 'TimeStamp'] = time.strftime("%b %d %Y %H:%M:%S", time.localtime()) # df.loc[df.Run == run, 'Status'] = "queued" # else: # df.loc[df.shape[0]] = [run, time.strftime("%b %d %Y %H:%M:%S", time.localtime()), 'queued'] # print df # print df['Run'] # df.to_csv('core_results_queue/' + log + '/' + str(prefix) + '/reg_queueStatus.csv', sep=',',header=writeHeader, mode='w+', index=False) db.commit() return HttpResponse("YOLO")
def classifierTask(fileName, prefix, encoding, cluster, method, label, threshold): db = Base('backendDB.pdl') db.open() run = method + '_' + encoding + '_' + cluster records = [ r for r in db if r['Run'] == run and r['Prefix'] == str(prefix) and r['Log'] == fileName and r['Rule'] == label and r['Threshold'] == str(threshold) ] db.update(records[0], TimeStamp=time.strftime("%b %d %Y %H:%M:%S", time.localtime()), Status='Running') db.commit() try: prediction.classifier(fileName, prefix, encoding, cluster, method, label, threshold) records = [ r for r in db if r['Run'] == run and r['Prefix'] == str(prefix) and r['Log'] == fileName ] db.update(records[0], TimeStamp=time.strftime("%b %d %Y %H:%M:%S", time.localtime()), Status='Completed') db.commit() except Exception, e: # Guard against race condition records = [ r for r in db if r['Run'] == run and r['Prefix'] == str(prefix) and r['Log'] == fileName and r['Rule'] == label and r['Threshold'] == str(threshold) ] db.update(records[0], TimeStamp=time.strftime("%b %d %Y %H:%M:%S", time.localtime()), Status='Failed: ' + str(e)) db.commit() raise
def likeconvert(likesRoot): histPath = likesRoot + "/history" convertcsv2db(likesRoot + "/totals.csv", likesRoot + "/likes.pdl") db = Base(likesRoot + "/likes.pdl") db.open() db.add_field("history", "") db.add_field("liked", "") dirContents = os.listdir(histPath) histFiles = [] for File in dirContents: if ".csv" in File: histFiles.append(File) for histFile in histFiles: try: csvfile = open(histPath + "/" + histFile, "rb") reader = csv.DictReader(csvfile) for row in reader: if histFile.endswith("history.csv"): recName = histFile[:-11] print(recName) if db(userID=recName): rec = db(userID=recName).pop() if not rec["liked"]: db.update(rec, liked=row["liked"]) else: tmpLiked = rec["liked"] tmpLiked += " " + row["liked"] db.update(rec, liked=tmpLiked) if not rec["history"]: db.update(rec, history=row["messageID"]) else: tmpHist = rec["history"] tmpHist += " " + row["messageID"] db.update(rec, history=tmpHist) db.commit() except csv.Error: print("Could not open CSV file")
def get_results_db(clear_cache=False, skip=[]): cache_file = 'cache/results.pdl' db = Base(cache_file) if clear_cache or not db.exists() or os.path.getmtime(cache_file) < os.path.getmtime(results_dir): warnings.warn('Rebuilding results cache...') columns = set() rows = [] p = pathlib.Path(results_dir) for config_file in p.glob('*.config'): with config_file.open() as config_fh: settings_hash = config_file.stem row = json.loads(config_fh.read()) if settings_hash in skip: continue row['hash'] = settings_hash tests_count = analyze.count(config_file.parent, settings_hash) row['iostat_cpu'], len_cpu_values = analyze.iostat_cpu(config_file.parent, settings_hash) row['iperf_result'], len_iperf_values = getattr(analyze, row['iperf_name'])(config_file.parent, settings_hash, row) if tests_count != len_cpu_values or tests_count != len_iperf_values: raise analyze.AnalysisException('For test {}, mismatch in cardinality of tests between count ({}), iostat ({}) and iperf ({})'.format(settings_hash, tests_count, len_cpu_values, len_iperf_values), settings_hash) if len_iperf_values > 0: min_fairness = row['iperf_result']['fairness'][0] - row['iperf_result']['fairness'][1] if min_fairness < (1 - 1 / (2 * row['parallelism'])): warnings.warn('For test {}, fairness has a critical value: {}.'.format(settings_hash, row['iperf_result']['fairness']), RuntimeWarning) columns = columns | set(row.keys()) rows.append(row) db.create(*columns, mode='override') for r in rows: db.insert(**r) db.commit() warnings.warn('Results cache built.') else: warnings.warn('Reusing results cache.') db.open() return db
def regressionTask(fileName, prefix, encoding, cluster, regressionType): db = Base('backendDB.pdl') db.open() run = regressionType + '_' + encoding + '_' + cluster records = [ r for r in db if r['Run'] == run and r['Prefix'] == str(prefix) and r['Log'] == fileName ] db.update(records[0], TimeStamp=time.strftime("%b %d %Y %H:%M:%S", time.localtime()), Status='Running') db.commit() try: prediction.regressior(fileName, prefix, encoding, cluster, regressionType) records = [ r for r in db if r['Run'] == run and r['Prefix'] == str(prefix) and r['Log'] == fileName ] db.update(records[0], TimeStamp=time.strftime("%b %d %Y %H:%M:%S", time.localtime()), Status='Completed') db.commit() except Exception, e: # Guard against race condition records = [ r for r in db if r['Run'] == run and r['Prefix'] == str(prefix) and r['Log'] == fileName ] db.update(records[0], TimeStamp=time.strftime("%b %d %Y %H:%M:%S", time.localtime()), Status='Failed: ' + str(e)) db.commit() raise
def likeconvert(likesRoot): histPath = likesRoot + '/history' convertcsv2db(likesRoot + '/totals.csv', likesRoot + '/likes.pdl') db = Base(likesRoot + '/likes.pdl') db.open() db.add_field('history', "") db.add_field('liked', "") dirContents = os.listdir(histPath) histFiles = [] for File in dirContents: if ".csv" in File: histFiles.append(File) for histFile in histFiles: try: csvfile = open(histPath + '/' + histFile, 'rb') reader = csv.DictReader(csvfile) for row in reader: if histFile.endswith('history.csv'): recName = histFile[:-11] print(recName) if db(userID=recName): rec = db(userID=recName).pop() if not rec['liked']: db.update(rec, liked=row['liked']) else: tmpLiked = rec['liked'] tmpLiked += " " + row['liked'] db.update(rec, liked=tmpLiked) if not rec['history']: db.update(rec, history=row['messageID']) else: tmpHist = rec['history'] tmpHist += " " + row['messageID'] db.update(rec, history=tmpHist) db.commit() except csv.Error: print("Could not open CSV file")
class vropsCollector(object): def __init__(self): requests.packages.urllib3.disable_warnings(InsecureRequestWarning) self.config = json.loads( open("/opt/prometheus/vrops_exporter/vrops.json").read()) journal.send("Connecting to vROPs host: ", FIELD2=self.config["server"]["hostname"]) self.vcops = nagini.Nagini(host=self.config["server"]["hostname"], user_pass=(self.config["server"]["user"], self.config["server"]["pwd"])) #print vcops.get_resources(resourceKind="VirtualMachine", pageSize=1) self.db = Base('/tmp/vrops.pd1') #logging.basicConfig(format='vrops_exporter - %(levelname)s:%(message)s', stream=sys.stdout, level=logging.DEBUG) def collect(self): self.db.open() journal.send("======Starting Collection=========") for r in self.config["metrics"]: #get_metrics(r["kind"],config["adapterKind"],r["keys"], iclient, db) stat_key = r["keys"].keys() #metric = Metric('compute_cluster_health', 'VROPS Compute Cluster Health', 'gauge') metric = GaugeMetricFamily( 'compute_cluster_health', 'VROPS Compute Cluster Health', labels=['vrops_host', 'site', 'cluster']) for i in self.db(type=r["kind"]): for j in self.vcops.get_latest_stats( id=i['id'], statKey=stat_key)['values']: for st in j['stat-list']['stat']: metric.add_metric([ self.config["server"]["hostname"], i["site"], i["object"] ], st['data'][0]) #print i["site"],i["object"],st['data'][0], st['data'][0] yield metric journal.send("======Completed Collection=========")
def get_cursor(db_name): if db_name == 'weather_data': db = Base('storage/weather_data.pdl') if not db.exists(): db.create('low', 'tmw', 'high', 'temp', 'date', 'text', 'code', 'history', 'uniq_id', 'location', 'astronomy', 'atmosphere', 'country_name', 'created_date', 'location_name') elif db_name == 'locations': db = Base('storage/locations.pdl') if not db.exists(): db.create('uniq_id', 'location', 'created_date') else: raise Exception('Please Enter Valid Name!') cursor = db.open() return cursor
def make_graph(): """ Make graph from data. """ year = [] lst_jungwat = [] lst_death = [] db = Base('Thai-db.pdl') db.open() make_list_year(year, db) make_list_jungwat(lst_jungwat, db) i = 0 """-----------------------------------------------""" change_death(i, db, lst_jungwat, lst_death) trace1 = Scatter( x=year, y=lst_death, connectgaps=True, line=Line( color='rgb(0, 0, 0)', width=1 ), name=lst_jungwat[i], uid='dd3a3c' ) """-----------------------------------------------""" i += 1 lst_death = [] change_death(i, db, lst_jungwat, lst_death) trace2 = Scatter( x=year, y=lst_death, connectgaps=True, line=Line( color='rgb(119, 136, 153)', width=1 ), name=lst_jungwat[i], uid='dd3a3c' ) """-----------------------------------------------""" i += 1 lst_death = [] change_death(i, db, lst_jungwat, lst_death) trace3 = Scatter( x=year, y=lst_death, connectgaps=True, line=Line( color='rgb(198, 226, 255)', width=1 ), name=lst_jungwat[i], uid='dd3a3c' ) """-----------------------------------------------""" i += 1 lst_death = [] change_death(i, db, lst_jungwat, lst_death) trace4 = Scatter( x=year, y=lst_death, connectgaps=True, line=Line( color='rgb(151, 255, 255)', width=1 ), name=lst_jungwat[i], uid='dd3a3c' ) """-----------------------------------------------""" i += 1 lst_death = [] change_death(i, db, lst_jungwat, lst_death) trace5 = Scatter( x=year, y=lst_death, connectgaps=True, line=Line( color='rgb(238, 232, 170)', width=1 ), name=lst_jungwat[i], uid='dd3a3c' ) """-----------------------------------------------""" i += 1 lst_death = [] change_death(i, db, lst_jungwat, lst_death) trace6 = Scatter( x=year, y=lst_death, connectgaps=True, line=Line( color='rgb(139, 69, 19)', width=1 ), name=lst_jungwat[i], uid='dd3a3c' ) """-----------------------------------------------""" i += 1 lst_death = [] change_death(i, db, lst_jungwat, lst_death) trace7 = Scatter( x=year, y=lst_death, connectgaps=True, line=Line( color='rgb(205, 133, 63)', width=1 ), name=lst_jungwat[i], uid='dd3a3c' ) """-----------------------------------------------""" i += 1 lst_death = [] change_death(i, db, lst_jungwat, lst_death) trace8 = Scatter( x=year, y=lst_death, connectgaps=True, line=Line( color='rgb(244, 164, 96)', width=1 ), name=lst_jungwat[i], uid='dd3a3c' ) """-----------------------------------------------""" i += 1 lst_death = [] change_death(i, db, lst_jungwat, lst_death) trace9 = Scatter( x=year, y=lst_death, connectgaps=True, line=Line( color='rgb(255, 218, 185)', width=1 ), name=lst_jungwat[i], uid='dd3a3c' ) """-----------------------------------------------""" i += 1 lst_death = [] change_death(i, db, lst_jungwat, lst_death) trace10 = Scatter( x=year, y=lst_death, connectgaps=True, line=Line( color='rgb(238, 207, 161)', width=1 ), name=lst_jungwat[i], uid='dd3a3c' ) """-----------------------------------------------""" i += 1 lst_death = [] change_death(i, db, lst_jungwat, lst_death) trace11 = Scatter( x=year, y=lst_death, connectgaps=True, line=Line( color='rgb(205, 201, 165)', width=1 ), name=lst_jungwat[i], uid='dd3a3c' ) """-----------------------------------------------""" i += 1 lst_death = [] change_death(i, db, lst_jungwat, lst_death) trace12 = Scatter( x=year, y=lst_death, connectgaps=True, line=Line( color='rgb(139, 136, 120)', width=1 ), name=lst_jungwat[i], uid='dd3a3c' ) """-----------------------------------------------""" i += 1 lst_death = [] change_death(i, db, lst_jungwat, lst_death) trace13 = Scatter( x=year, y=lst_death, connectgaps=True, line=Line( color='rgb(132, 112, 255)', width=1 ), name=lst_jungwat[i], uid='dd3a3c' ) """-----------------------------------------------""" i += 1 lst_death = [] change_death(i, db, lst_jungwat, lst_death) trace14 = Scatter( x=year, y=lst_death, connectgaps=True, line=Line( color='rgb(71, 60, 139)', width=1 ), name=lst_jungwat[i], uid='dd3a3c' ) """-----------------------------------------------""" i += 1 lst_death = [] change_death(i, db, lst_jungwat, lst_death) trace15 = Scatter( x=year, y=lst_death, connectgaps=True, line=Line( color='rgb(72, 118, 255)', width=1 ), name=lst_jungwat[i], uid='dd3a3c' ) """-----------------------------------------------""" i += 1 lst_death = [] change_death(i, db, lst_jungwat, lst_death) trace16 = Scatter( x=year, y=lst_death, connectgaps=True, line=Line( color='rgb(39, 64, 139)', width=1 ), name=lst_jungwat[i], uid='dd3a3c' ) """-----------------------------------------------""" i += 1 lst_death = [] change_death(i, db, lst_jungwat, lst_death) trace17 = Scatter( x=year, y=lst_death, connectgaps=True, line=Line( color='rgb(0, 0, 255)', width=1 ), name=lst_jungwat[i], uid='dd3a3c' ) """-----------------------------------------------""" i += 1 lst_death = [] change_death(i, db, lst_jungwat, lst_death) trace18 = Scatter( x=year, y=lst_death, connectgaps=True, line=Line( color='rgb(25, 25, 112)', width=1 ), name=lst_jungwat[i], uid='dd3a3c' ) """-----------------------------------------------""" i += 1 lst_death = [] change_death(i, db, lst_jungwat, lst_death) trace19 = Scatter( x=year, y=lst_death, connectgaps=True, line=Line( color='rgb(176, 224, 230)', width=1 ), name=lst_jungwat[i], uid='dd3a3c' ) """-----------------------------------------------""" i += 1 lst_death = [] change_death(i, db, lst_jungwat, lst_death) trace20 = Scatter( x=year, y=lst_death, connectgaps=True, line=Line( color='rgb(24, 116, 205)', width=1 ), name=lst_jungwat[i], uid='dd3a3c' ) """-----------------------------------------------""" i += 1 lst_death = [] change_death(i, db, lst_jungwat, lst_death) trace21 = Scatter( x=year, y=lst_death, connectgaps=True, line=Line( color='rgb(0, 154, 205)', width=1 ), name=lst_jungwat[i], uid='dd3a3c' ) """-----------------------------------------------""" i += 1 lst_death = [] change_death(i, db, lst_jungwat, lst_death) trace22 = Scatter( x=year, y=lst_death, connectgaps=True, line=Line( color='rgb(74, 112, 139)', width=1 ), name=lst_jungwat[i], uid='dd3a3c' ) """-----------------------------------------------""" i += 1 lst_death = [] change_death(i, db, lst_jungwat, lst_death) trace23 = Scatter( x=year, y=lst_death, connectgaps=True, line=Line( color='rgb(95, 158, 160)', width=1 ), name=lst_jungwat[i], uid='dd3a3c' ) """-----------------------------------------------""" i += 1 lst_death = [] change_death(i, db, lst_jungwat, lst_death) trace24 = Scatter( x=year, y=lst_death, connectgaps=True, line=Line( color='rgb(150, 205, 205)', width=1 ), name=lst_jungwat[i], uid='dd3a3c' ) """-----------------------------------------------""" i += 1 lst_death = [] change_death(i, db, lst_jungwat, lst_death) trace25 = Scatter( x=year, y=lst_death, connectgaps=True, line=Line( color='rgb(0, 206, 209)', width=1 ), name=lst_jungwat[i], uid='dd3a3c' ) """-----------------------------------------------""" i += 1 lst_death = [] change_death(i, db, lst_jungwat, lst_death) trace26 = Scatter( x=year, y=lst_death, connectgaps=True, line=Line( color='rgb(0, 245, 255)', width=1 ), name=lst_jungwat[i], uid='dd3a3c' ) """-----------------------------------------------""" i += 1 lst_death = [] change_death(i, db, lst_jungwat, lst_death) trace27 = Scatter( x=year, y=lst_death, connectgaps=True, line=Line( color='rgb(102, 205, 170)', width=1 ), name=lst_jungwat[i], uid='dd3a3c' ) """-----------------------------------------------""" i += 1 lst_death = [] change_death(i, db, lst_jungwat, lst_death) trace28 = Scatter( x=year, y=lst_death, connectgaps=True, line=Line( color='rgb(46, 139, 87)', width=1 ), name=lst_jungwat[i], uid='dd3a3c' ) """-----------------------------------------------""" i += 1 lst_death = [] change_death(i, db, lst_jungwat, lst_death) trace29 = Scatter( x=year, y=lst_death, connectgaps=True, line=Line( color='rgb(0, 139, 69)', width=1 ), name=lst_jungwat[i], uid='dd3a3c' ) """-----------------------------------------------""" i += 1 lst_death = [] change_death(i, db, lst_jungwat, lst_death) trace30 = Scatter( x=year, y=lst_death, connectgaps=True, line=Line( color='rgb(0, 255, 0)', width=1 ), name=lst_jungwat[i], uid='dd3a3c' ) """-----------------------------------------------""" i += 1 lst_death = [] change_death(i, db, lst_jungwat, lst_death) trace31 = Scatter( x=year, y=lst_death, connectgaps=True, line=Line( color='rgb(0, 100, 0)', width=1 ), name=lst_jungwat[i], uid='dd3a3c' ) """-----------------------------------------------""" i += 1 lst_death = [] change_death(i, db, lst_jungwat, lst_death) trace32 = Scatter( x=year, y=lst_death, connectgaps=True, line=Line( color='rgb(32, 178, 170)', width=1 ), name=lst_jungwat[i], uid='dd3a3c' ) """-----------------------------------------------""" i += 1 lst_death = [] change_death(i, db, lst_jungwat, lst_death) trace33 = Scatter( x=year, y=lst_death, connectgaps=True, line=Line( color='rgb(0, 250, 154)', width=1 ), name=lst_jungwat[i], uid='dd3a3c' ) """-----------------------------------------------""" i += 1 lst_death = [] change_death(i, db, lst_jungwat, lst_death) trace34 = Scatter( x=year, y=lst_death, connectgaps=True, line=Line( color='rgb(107, 142, 35)', width=1 ), name=lst_jungwat[i], uid='dd3a3c' ) """-----------------------------------------------""" i += 1 lst_death = [] change_death(i, db, lst_jungwat, lst_death) trace35 = Scatter( x=year, y=lst_death, connectgaps=True, line=Line( color='rgb(202, 255, 112)', width=1 ), name=lst_jungwat[i], uid='dd3a3c' ) """-----------------------------------------------""" i += 1 lst_death = [] change_death(i, db, lst_jungwat, lst_death) trace36 = Scatter( x=year, y=lst_death, connectgaps=True, line=Line( color='rgb(255, 246, 143)', width=1 ), name=lst_jungwat[i], uid='dd3a3c' ) """-----------------------------------------------""" i += 1 lst_death = [] change_death(i, db, lst_jungwat, lst_death) trace37 = Scatter( x=year, y=lst_death, connectgaps=True, line=Line( color='rgb(139, 134, 78)', width=1 ), name=lst_jungwat[i], uid='dd3a3c' ) """-----------------------------------------------""" i += 1 lst_death = [] change_death(i, db, lst_jungwat, lst_death) trace38 = Scatter( x=year, y=lst_death, connectgaps=True, line=Line( color='rgb(255, 255, 0)', width=1 ), name=lst_jungwat[i], uid='dd3a3c' ) """-----------------------------------------------""" i += 1 lst_death = [] change_death(i, db, lst_jungwat, lst_death) trace39 = Scatter( x=year, y=lst_death, connectgaps=True, line=Line( color='rgb(139, 139, 0)', width=1 ), name=lst_jungwat[i], uid='dd3a3c' ) """-----------------------------------------------""" i += 1 lst_death = [] change_death(i, db, lst_jungwat, lst_death) trace40 = Scatter( x=[2554, 2555, 2556, 2557], y=lst_death, connectgaps=True, line=Line( color='rgb(205, 173, 0)', width=1 ), name=lst_jungwat[i], uid='dd3a3c' ) """-----------------------------------------------""" i += 1 lst_death = [] change_death(i, db, lst_jungwat, lst_death) trace41 = Scatter( x=year, y=lst_death, connectgaps=True, line=Line( color='rgb(139, 101, 8)', width=1 ), name=lst_jungwat[i], uid='dd3a3c' ) """-----------------------------------------------""" i += 1 lst_death = [] change_death(i, db, lst_jungwat, lst_death) trace42 = Scatter( x=year, y=lst_death, connectgaps=True, line=Line( color='rgb(188, 143, 143)', width=1 ), name=lst_jungwat[i], uid='dd3a3c' ) """-----------------------------------------------""" i += 1 lst_death = [] change_death(i, db, lst_jungwat, lst_death) trace43 = Scatter( x=year, y=lst_death, connectgaps=True, line=Line( color='rgb(255, 193, 193)', width=1 ), name=lst_jungwat[i], uid='dd3a3c' ) """-----------------------------------------------""" i += 1 lst_birth = [] change_death(i, db, lst_jungwat, lst_death) trace44 = Scatter( x=year, y=lst_death, connectgaps=True, line=Line( color='rgb(205, 92, 92)', width=1 ), name=lst_jungwat[i], uid='dd3a3c' ) """-----------------------------------------------""" i += 1 lst_death = [] change_death(i, db, lst_jungwat, lst_death) trace45 = Scatter( x=year, y=lst_death, connectgaps=True, line=Line( color='rgb(255, 130, 71)', width=1 ), name=lst_jungwat[i], uid='dd3a3c' ) """-----------------------------------------------""" i += 1 lst_death = [] change_death(i, db, lst_jungwat, lst_death) trace46 = Scatter( x=year, y=lst_death, connectgaps=True, line=Line( color='rgb(139, 71, 38)', width=1 ), name=lst_jungwat[i], uid='dd3a3c' ) """-----------------------------------------------""" i += 1 lst_death = [] change_death(i, db, lst_jungwat, lst_death) trace47 = Scatter( x=year, y=lst_death, connectgaps=True, line=Line( color='rgb(139, 115, 85)', width=1 ), name=lst_jungwat[i], uid='dd3a3c' ) """-----------------------------------------------""" i += 1 lst_death = [] change_death(i, db, lst_jungwat, lst_death) trace48 = Scatter( x=year, y=lst_death, connectgaps=True, line=Line( color='rgb(205, 133, 63)', width=1 ), name=lst_jungwat[i], uid='dd3a3c' ) """-----------------------------------------------""" i += 1 lst_death = [] change_death(i, db, lst_jungwat, lst_death) trace49 = Scatter( x=year, y=lst_death, connectgaps=True, line=Line( color='rgb(255, 127, 36)', width=1 ), name=lst_jungwat[i], uid='dd3a3c' ) """-----------------------------------------------""" i += 1 lst_death = [] change_death(i, db, lst_jungwat, lst_death) trace50 = Scatter( x=year, y=lst_death, connectgaps=True, line=Line( color='rgb(205, 38, 38)', width=1 ), name=lst_jungwat[i], uid='dd3a3c' ) """-----------------------------------------------""" i += 1 lst_death = [] change_death(i, db, lst_jungwat, lst_death) trace51 = Scatter( x=year, y=lst_death, connectgaps=True, line=Line( color='rgb(255, 20, 147)', width=1 ), name=lst_jungwat[i], uid='dd3a3c' ) """-----------------------------------------------""" i += 1 lst_death = [] change_death(i, db, lst_jungwat, lst_death) trace52 = Scatter( x=year, y=lst_death, connectgaps=True, line=Line( color='rgb(139, 10, 80)', width=1 ), name=lst_jungwat[i], uid='dd3a3c' ) """-----------------------------------------------""" i += 1 lst_death = [] change_death(i, db, lst_jungwat, lst_death) trace53 = Scatter( x=year, y=lst_death, connectgaps=True, line=Line( color='rgb(205, 96, 144)', width=1 ), name=lst_jungwat[i], uid='dd3a3c' ) """-----------------------------------------------""" i += 1 lst_death = [] change_death(i, db, lst_jungwat, lst_death) trace54 = Scatter( x=year, y=lst_death, connectgaps=True, line=Line( color='rgb(139, 99, 108)', width=1 ), name=lst_jungwat[i], uid='dd3a3c' ) """-----------------------------------------------""" i += 1 lst_death = [] change_death(i, db, lst_jungwat, lst_death) trace55 = Scatter( x=year, y=lst_death, connectgaps=True, line=Line( color='rgb(176, 48, 96)', width=1 ), name=lst_jungwat[i], uid='dd3a3c' ) """-----------------------------------------------""" i += 1 lst_death = [] change_death(i, db, lst_jungwat, lst_death) trace56 = Scatter( x=year, y=lst_death, connectgaps=True, line=Line( color='rgb(205, 0, 205)', width=1 ), name=lst_jungwat[i], uid='dd3a3c' ) """-----------------------------------------------""" i += 1 lst_death = [] change_death(i, db, lst_jungwat, lst_death) trace57 = Scatter( x=year, y=lst_death, connectgaps=True, line=Line( color='rgb(139, 0, 139)', width=1 ), name=lst_jungwat[i], uid='dd3a3c' ) """-----------------------------------------------""" i += 1 lst_death = [] change_death(i, db, lst_jungwat, lst_death) trace58 = Scatter( x=year, y=lst_death, connectgaps=True, line=Line( color='rgb(186, 85, 211)', width=1 ), name=lst_jungwat[i], uid='dd3a3c' ) """-----------------------------------------------""" i += 1 lst_death = [] change_death(i, db, lst_jungwat, lst_death) trace59 = Scatter( x=year, y=lst_death, connectgaps=True, line=Line( color='rgb(148, 0, 211)', width=1 ), name=lst_jungwat[i], uid='dd3a3c' ) """-----------------------------------------------""" i += 1 lst_death = [] change_death(i, db, lst_jungwat, lst_death) trace60 = Scatter( x=year, y=lst_death, connectgaps=True, line=Line( color='rgb(128, 0, 128)', width=1 ), name=lst_jungwat[i], uid='dd3a3c' ) """-----------------------------------------------""" i += 1 lst_death = [] change_death(i, db, lst_jungwat, lst_death) trace61 = Scatter( x=year, y=lst_death, connectgaps=True, line=Line( color='rgb(236, 171, 83)', width=1 ), name=lst_jungwat[i], uid='dd3a3c' ) """-----------------------------------------------""" i += 1 lst_death = [] change_death(i, db, lst_jungwat, lst_death) trace62 = Scatter( x=year, y=lst_death, connectgaps=True, line=Line( color='rgb(192, 192, 192)', width=1 ), name=lst_jungwat[i], uid='dd3a3c' ) """-----------------------------------------------""" i += 1 lst_death = [] change_death(i, db, lst_jungwat, lst_death) trace63 = Scatter( x=year, y=lst_death, connectgaps=True, line=Line( color='rgb(0, 128, 128)', width=1 ), name=lst_jungwat[i], uid='dd3a3c' ) """-----------------------------------------------""" i += 1 lst_death = [] change_death(i, db, lst_jungwat, lst_death) trace64 = Scatter( x=year, y=lst_death, connectgaps=True, line=Line( color='rgb(255, 204, 153)', width=1 ), name=lst_jungwat[i], uid='dd3a3c' ) """-----------------------------------------------""" i += 1 lst_death = [] change_death(i, db, lst_jungwat, lst_death) trace65 = Scatter( x=year, y=lst_death, connectgaps=True, line=Line( color='rgb(142, 124, 195)', width=1 ), name=lst_jungwat[i], uid='dd3a3c' ) """-----------------------------------------------""" i += 1 lst_death = [] change_death(i, db, lst_jungwat, lst_death) trace66 = Scatter( x=year, y=lst_death, connectgaps=True, line=Line( color='rgb(0, 154, 205)', width=1 ), name=lst_jungwat[i], uid='dd3a3c' ) """-----------------------------------------------""" i += 1 lst_death = [] change_death(i, db, lst_jungwat, lst_death) trace67 = Scatter( x=year, y=lst_death, connectgaps=True, line=Line( color='rgb(238, 59, 59)', width=1 ), name=lst_jungwat[i], uid='dd3a3c' ) """-----------------------------------------------""" i += 1 lst_death = [] change_death(i, db, lst_jungwat, lst_death) trace68 = Scatter( x=year, y=lst_death, connectgaps=True, line=Line( color='rgb(50, 205, 50)', width=1 ), name=lst_jungwat[i], uid='dd3a3c' ) """-----------------------------------------------""" i += 1 lst_death = [] change_death(i, db, lst_jungwat, lst_death) trace69 = Scatter( x=year, y=lst_death, connectgaps=True, line=Line( color='rgb(34, 139, 34)', width=1 ), name=lst_jungwat[i], uid='dd3a3c' ) """-----------------------------------------------""" i += 1 lst_death = [] change_death(i, db, lst_jungwat, lst_death) trace70 = Scatter( x=year, y=lst_death, connectgaps=True, line=Line( color='rgb(105, 139, 34)', width=1 ), name=lst_jungwat[i], uid='dd3a3c' ) """-----------------------------------------------""" i += 1 lst_death = [] change_death(i, db, lst_jungwat, lst_death) trace71 = Scatter( x=year, y=lst_death, connectgaps=True, line=Line( color='rgb(205, 173, 0)', width=1 ), name=lst_jungwat[i], uid='dd3a3c' ) """-----------------------------------------------""" i += 1 lst_death = [] change_death(i, db, lst_jungwat, lst_death) trace72 = Scatter( x=year, y=lst_death, connectgaps=True, line=Line( color='rgb(0, 154, 205)', width=1 ), name=lst_jungwat[i], uid='dd3a3c' ) """-----------------------------------------------""" i += 1 lst_death = [] change_death(i, db, lst_jungwat, lst_death) trace73 = Scatter( x=year, y=lst_death, connectgaps=True, line=Line( color='rgb(155, 205, 155)', width=1 ), name=lst_jungwat[i], uid='dd3a3c' ) """-----------------------------------------------""" i += 1 lst_death = [] change_death(i, db, lst_jungwat, lst_death) trace74 = Scatter( x=year, y=lst_death, connectgaps=True, line=Line( color='rgb(46, 139, 87)', width=1 ), name=lst_jungwat[i], uid='dd3a3c' ) """-----------------------------------------------""" i += 1 lst_death = [] change_death(i, db, lst_jungwat, lst_death) trace75 = Scatter( x=year, y=lst_death, connectgaps=True, line=Line( color='rgb(192, 255, 62)', width=1 ), name=lst_jungwat[i], uid='dd3a3c' ) """-----------------------------------------------""" i += 1 lst_death = [] change_death(i, db, lst_jungwat, lst_death) trace76 = Scatter( x=year, y=lst_death, connectgaps=True, line=Line( color='rgb(95, 158, 160)', width=1 ), name=lst_jungwat[i], uid='dd3a3c' ) """-----------------------------------------------""" data = Data([trace1, trace2, trace3, trace4, trace5, trace6, trace7, trace8, trace9, trace10, trace11, trace12, trace13, trace14, trace15, trace16, trace17, trace18, trace19, trace20, trace21\ , trace22, trace23, trace24, trace25, trace26, trace27, trace28, trace29, trace30, trace31, trace32, trace33, trace34, trace35, trace36, trace37, trace38, trace39, trace40\ ,trace41, trace42, trace43, trace44, trace45, trace46, trace47, trace48, trace49, trace50, trace51, trace52, trace53, trace54, trace55, trace56, trace57, trace58, trace59\ , trace60, trace61, trace62, trace63, trace64, trace65, trace66, trace67, trace68, trace69, trace70, trace71, trace72, trace73, trace74, trace75, trace76]) layout = Layout( autosize=True, bargap=0.2, bargroupgap=0, barmode='stack', boxgap=0.3, boxgroupgap=0.3, boxmode='overlay', dragmode='zoom', font=Font( color='rgb(33, 33, 33)', family='"Old Standard TT", serif', size=12 ), height=600, hidesources=False, hovermode='x', legend=Legend( x=0.01788617886178862, y=1.0166666666666666, bgcolor='rgba(255, 255, 255, 0)', bordercolor='rgba(0, 0, 0, 0)', borderwidth=1, font=Font( color='rgb(33, 33, 33)', family='', size=0 ), traceorder='normal', xanchor='auto', yanchor='auto' ), margin=Margin( r=80, t=100, autoexpand=True, b=80, l=80, pad=2 ), paper_bgcolor='#fff', plot_bgcolor='#fff', separators='.,', showlegend=False, smith=False, title='The graph shows the number of death since 2548 to 2557.', titlefont=dict( color='', family='', size=0 ), width=775, xaxis=XAxis( anchor='y', autorange=True, autotick=True, domain=[0, 1], dtick='M12.000000000000002', exponentformat='e', gridcolor='#ddd', gridwidth=1, linecolor='rgb(221, 221, 221)', linewidth=1, mirror=False, nticks=15, overlaying=False, position=0, range=[1046754000000, 1378008000000], rangemode='normal', showexponent='all', showgrid=False, showline=True, showticklabels=True, tick0=946702800000, tickangle='auto', tickcolor='#000', tickfont=dict( color='', family='', size=0 ), ticklen=5, ticks='', tickwidth=1, title='<i>Year</i>', titlefont=dict( color='', family='', size=0 ), type='year', zeroline=False, zerolinecolor='#000', zerolinewidth=1 ), yaxis=YAxis( anchor='x', autorange=False, autotick=True, domain=[0, 1], dtick=100, gridcolor='#ddd', gridwidth=1, linecolor='rgb(221, 221, 221)', linewidth=1, mirror=False, nticks=0, overlaying=False, position=0, range=[0, 50000], rangemode='normal', showgrid=True, showline=True, showticklabels=True, tick0=0, tickangle='auto', tickcolor='#000', tickfont=dict( color='', family='', size=0 ), ticklen=5, ticks='', tickwidth=1, title='Number of death', titlefont=dict( color='', family='', size=0 ), type='linear', zeroline=False, zerolinecolor='#000', zerolinewidth=1 ) ) fig = Figure(data=data, layout=layout) plot_url = py.plot(fig)
class SignalDB: def __init__(self, name, path='./', mode="open"): '''mode can be 'override' ''' name_sig = name + '_sig.pdl' name_sig = join(path, name_sig) self.db_sig = Base(name_sig) self.db_sig.create('signal_bundle', 'signals', 'timestamps', 'name', 'labels', 'md5', 'sublabel', mode=mode) self.db_sig.open() def commit(self): self.db_sig.commit() def tohash(self, data): md5 = hashlib.md5(pickle.dumps(data)).hexdigest() return md5 def findld(self, ld): md5 = self.tohash(ld.signal_bundle.signals[0]) recarr = [r for r in (self.db_sig('md5') == md5)] if len(recarr) > 1: print 'duplicate signal bundles' elif len(recarr) == 1: r = recarr[0] sb = r['signal_bundle'] labels = r['labels'] name = r['name'] ld_out = LabeledData(sb) ld_out.labels = labels return ld_out else: print "signal doesn't currently exist" return None def add_labeleddata(self, ld, overwrite=False): md5 = self.tohash(ld.signal_bundle.signals[0]) recarr = [r for r in (self.db_sig('md5') == md5)] if len(recarr) > 1: print 'duplicate signal bundles' if not recarr: self.db_sig.insert(signal_bundle = ld.signal_bundle,\ signals = ld.signal_bundle.signals,\ timestamps = ld.signal_bundle.timestamps,\ name = ld.signal_bundle.name, \ labels = ld.labels,\ md5 = md5) else: rec = recarr[0] print rec['__id__'] if overwrite == False: for idx, (reclabel, ldlabel) in enumerate(zip(rec['labels'], ld.labels)): if reclabel == '': rec['labels'][idx] = ldlabel else: for idx, (reclabel, ldlabel) in enumerate(zip(rec['labels'], ld.labels)): if ldlabel != '': rec['labels'][idx] = ldlabel # print rec['__id__'],rec['labels'] self.db_sig.update(rec, labels=rec['labels']) def get_labeleddata(self): ld_arr = [] # signal_bundle, timestamps = None, label = "") for r in self.db_sig: sb = r['signal_bundle'] labels = r['labels'] name = r['name'] ld = LabeledData(sb) ld.labels = labels ld_arr.append(ld) return ld_arr
def run_every_10_seconds(): print 'run_every_10_seconds' now = datetime.datetime.now() #record = db(user="") #now = now.replace(hour=20, minute=0, second=1, microsecond=0) print now; db = Base(schedule_table_name) if db.exists(): db.open() records = db.records ''' list_of_records = []; for record in records: list_of_records.append(records[record]); db.delete(list_of_records); db.commit(); ''' for record in records: schedule_time = records[record]['schedule_time'] user = records[record]['user'] chat_id = records[record]['chat_id'] enable = records[record]['enable'] print schedule_time,user,chat_id,enable if enable=='no': continue try: if schedule_time==AM8: today8am0min = now.replace(hour=8, minute=0, second=0, microsecond=0) today8am1min = now.replace(hour=8, minute=1, second=0, microsecond=0) if now >= today8am0min and now <= today8am1min: kik.send_messages([TextMessage(to=user,chat_id=chat_id,body="scheduled message 8AM")]) except: pass try: if schedule_time==PM8: print "In 8PM"; today8pm0min = now.replace(hour=20, minute=0, second=0, microsecond=0) today8pm1min = now.replace(hour=20, minute=1, second=0, microsecond=0) print today8pm0min; print today8pm0min; if now > today8pm0min and now < today8pm1min: print "Condition matched. Sending message to " + str(user); kik.send_messages([TextMessage(to=user,chat_id=chat_id,body="scheduled message 8PM")]) except Exception as e: print (e); pass try: if schedule_time==AM10: today10am0min = now.replace(hour=10, minute=0, second=0, microsecond=0) today10am1min = now.replace(hour=10, minute=1, second=0, microsecond=0) if now > today10am0min and now < today10am1min: kik.send_messages([TextMessage(to=user,chat_id=chat_id,body="scheduled message 10AM")]) except: pass try: if schedule_time==PM10: today10pm0min = now.replace(hour=22, minute=0, second=0, microsecond=0) today10pm1min = now.replace(hour=22, minute=1, second=0, microsecond=0) if now > today10pm0min and now < today10pm1min: kik.send_messages([TextMessage(to=user,chat_id=chat_id,body="scheduled message 10PM")]) except: pass try: if schedule_time=='Default': todaydefault0 = now.replace(hour=DEFAULT_TIME, minute=0, second=0, microsecond=0) todaydefault1 = now.replace(hour=DEFAULT_TIME, minute=1, second=0, microsecond=0) if now > todaydefault0 and now < todaydefault1: kik.send_messages([TextMessage(to=user,chat_id=chat_id,body="scheduled message default")]) except: pass
from pathlib import Path from pydblite import Base if not Path('db').exists(): Path('db').mkdir() """ Base for client's application on service via client_id """ client_base = Base('db/client_base.pdl') if client_base.exists(): client_base.open() else: client_base.create('secret', 'redirect_uri', 'name') """ Base for keeping authorization codes while oauth """ authorization_code = Base('db/authorization_code.pdl') if authorization_code.exists(): authorization_code.open() else: authorization_code.create('user_id', 'code', 'expire_time') """ Base for access_tokens for authorized users """ access_token = Base('db/access_token.pdl') if access_token.exists(): access_token.open() else: access_token.create('user_id', 'access', 'expire_time', 'refresh') """
def reading_Database(path): adb = Base(path) adb.open() return adb
# palavrachavePath = '/Mestrado-2016/tabelas_dump/publicacaokeyword.csv' # palavrachaveArquivo = open(palavrachavePath, 'r') # # publicacaoPath = '/Mestrado-2016/tabelas_dump/publicacao.csv' # publicacaoArquivo = open(publicacaoPath, 'r') # # autoresPath = '/Mestrado-2016/tabelas_dump/autorpublicacao.csv' # autoresArquivo = open(autoresPath, 'r') # infoPath = '/Mestrado-2016/tabelas_dump/infoImportantes2000_2005.csv' infoArquivo = open(infoPath, 'w') infoArquivo.write('idpublication;year;keywords;authors\n') kdb = Base('/Mestrado-2016/tabelas_dump/palavra.pdl') kdb.open() kdb.create_index('idpublicacao') pdb = Base('/Mestrado-2016/tabelas_dump/publicacao.pdl') pdb.open() pdb.create_index('idpublicacao') adb = Base('/Mestrado-2016/tabelas_dump/autor.pdl') adb.open() adb.create_index('idpublicacao') pub = [r for r in pdb if r['ano'] >= 2000 and r['ano'] <= 2005] i = 0 tamanho = len(pub) for row in pub:
class Inventory: def __init__(self, session): self.session = session self.client = session.resource("ec2") self.create_database() def create_database(self): self.db = Base("test.pdl") if not self.db.exists(): self.db.create("resource", "name", "env") self.db.open() def fetch_instance(self, id): try: instances = self.client.instances.filter(InstanceIds=[id]) for instance in instances: tags = {t["Key"]: t["Value"] for t in instance.tags} env = tags["Env"] if "Env" in tags else tags["Environment"] self.db.insert(resource=id, name=tags["Name"], env=env) except Exception as e: print(e) self.db.insert(resource=id, name=id, env="") def get_instance(self, id): instance = self.db(resource=id) if not instance: self.fetch_instance(id) instance = self.db(resource=id) return instance[0] if instance else None def fetch_network_interface(self, id): c = self.client.meta.client try: data = c.describe_network_interfaces(NetworkInterfaceIds=[id]) nif = data["NetworkInterfaces"][0] if "Attachment" in nif: instance = self.get_instance(nif["Attachment"]["InstanceId"]) if instance: self.db.insert(resource=id, name=instance["name"], env=instance["env"]) except Exception as e: print(e) self.db.insert(resource=id, name=id, env="") def add_group(self, id, name): self.db.insert(resource=id, name=name, env="") def get_network_interface(self, id): nif = self.db(resource=id) if not nif: self.fetch_network_interface(id) nif = self.db(resource=id) return nif[0] if nif else None def fetch_security_group(self, id): c = self.client.meta.client try: groups = c.describe_security_groups(GroupIds=[id]) for group in groups["SecurityGroups"]: self.db.insert(resource=id, name=group["GroupName"]) except Exception as e: print(e) def get_security_group(self, id): group = self.db(resource=id) if not group: self.fetch_security_group(id) group = self.db(resource=id) return group[0] if group else None def get_resource_name(self, id): resource = self.db(resource=id) return resource[0]["name"] if resource else None
# -*- coding: utf-8 -*- from pydblite import Base ''' 序列化采用cPickle ''' db = Base("test.db", save_to_file=False) if db.exists(): db.open() else: db.create("name", "age") db.insert("bob", 10) index = db.insert(name="alice", age=20) print db[index] # 按照主键访问record record = db[1] db.update(record, name="dellian") #db.delete(record) # db.records (所有记录) # query for r in db("age") > 10: print r
def dolist(channel): db = Base(os.path.join(SCRIPT_DIR, f'{channel}_members.db')) db.open() for l in sorted(db, key=lambda x: x['time']): print(f"{l['members']} {str(l['time']).split('.')[0]}")
def open_db(self, db_name): _db = Base(manager.app_dir.joinpath('db', f'{db_name}.pdl')) if _db.exists(): return _db.open() raise TVShowsDBError(f'Couldn\'t connect to DB: {db_name}')
def get_nfc_key_data_base(): db = Base('nfc_key.pdl') if not db.exists(): db.create('time', 'pwd') db.open() return db
from pathlib import Path from pydblite import Base if not Path('db').exists(): Path('db').mkdir() client = Base('db/client.pdl') if client.exists(): client.open() else: client.create('secret', 'redirect_uri', 'name') authorization_code = Base('db/authorization_code.pdl') if authorization_code.exists(): authorization_code.open() else: authorization_code.create('user_id', 'code', 'expire_time') token = Base('db/token.pdl') if token.exists(): token.open() else: token.create('user_id', 'access', 'expire_time', 'refresh') user = Base('db/user.pdl') if user.exists(): user.open() else: user.create('login', 'password_hash', 'name', 'email', 'phone') food = Base('db/food.pdl')
from pathlib import Path from pydblite import Base if not Path("db").exists(): Path("db").mkdir() """ Base for client's application on service via client_id """ client_base = Base("db/client_base.pdl") if client_base.exists(): client_base.open() else: client_base.create("secret", "redirect_uri", "name") """ Base for keeping authorization codes while oauth """ authorization_code = Base("db/authorization_code.pdl") if authorization_code.exists(): authorization_code.open() else: authorization_code.create("user_id", "code", "expire_time") """ Base for access_tokens for authorized users """ access_token = Base("db/access_token.pdl") if access_token.exists(): access_token.open() else: access_token.create("user_id", "access", "expire_time", "refresh") """
# palavrachavePath = '/Mestrado-2016/tabelas_dump/publicacaokeyword.csv' # palavrachaveArquivo = open(palavrachavePath, 'r') # # publicacaoPath = '/Mestrado-2016/tabelas_dump/publicacao.csv' # publicacaoArquivo = open(publicacaoPath, 'r') # # autoresPath = '/Mestrado-2016/tabelas_dump/autorpublicacao.csv' # autoresArquivo = open(autoresPath, 'r') # infoPath = '/Mestrado-2016/tabelas_dump/infoImportantes2000_2005.csv' infoArquivo = open(infoPath, 'w') infoArquivo.write('idpublication;year;keywords;authors\n') kdb = Base('/Mestrado-2016/tabelas_dump/palavra.pdl') kdb.open() kdb.create_index('idpublicacao') pdb = Base('/Mestrado-2016/tabelas_dump/publicacao.pdl') pdb.open() pdb.create_index('idpublicacao') adb = Base('/Mestrado-2016/tabelas_dump/autor.pdl') adb.open() adb.create_index('idpublicacao') pub = [r for r in pdb if r['ano'] >= 2000 and r['ano'] <= 2005 ] i = 0 tamanho = len(pub) for row in pub:
from tornado import gen from tornado_json.requesthandlers import APIHandler from tornado_json import schema from tornado_json.gen import coroutine from pydblite import Base db = Base('test.pdl') if db.exists(): db.open() else: db.create('body', 'guid') class post_data(APIHandler): @schema.validate( input_schema={ "type": "object", "properties": { "body": {"type": "string"}, "guid": {"type": "string"}, } }, input_example={ "body": "Very Important Post-It Note", "guid": "information", } ) def post(self): # `schema.validate` will JSON-decode `self.request.body` for us # and set self.body as the result, so we can use that here
from datetime import datetime from pathlib import Path from pydblite import Base if not Path('db').exists(): Path('db').mkdir() client = Base('db/client.pdl') if client.exists(): client.open() else: client.create('secret', 'redirect_uri', 'name') authorization_code = Base('db/authorization_code.pdl') if authorization_code.exists(): authorization_code.open() else: authorization_code.create('user_id', 'code', 'expire_time') token = Base('db/token.pdl') if token.exists(): token.open() else: token.create('user_id', 'access', 'expire_time', 'refresh') user = Base('db/user.pdl') if user.exists(): user.open() else: user.create('login', 'password_hash', 'name', 'email', 'phone')
from pydblite import Base import datetime import crawler import configure as conf dbFileNameSuffix = conf.db_filename idData = Base('id.' + dbFileNameSuffix) if idData.exists(): idData.open() else: idData.create('id', 'name', 'meterNo', 'campus', \ 'building', 'floor', 'room') usageData = Base('usage.' + dbFileNameSuffix) if usageData.exists(): usageData.open() else: usageData.create('id', 'date', 'usage', 'remain') def updateIdData(): #idData.execute('delete from IDDATA;') # Clear old data idData.delete(idData) data = crawler.getIdData() for i in data: idData.insert( i['id'], i['name'], i['meterNo'], i['campus'], \ i['building'], i['floor'], i['room']) idData.commit() return def updateUsageData(mids):
from pathlib import Path from pydblite import Base if not Path('database').exists(): Path('database').mkdir() client = Base('database/client.pdl') if client.exists(): client.open() else: client.create('secret', 'redirect_uri', 'name') authorization_code = Base('database/authorization_code.pdl') if authorization_code.exists(): authorization_code.open() else: authorization_code.create('user_id', 'code', 'expire_time') token = Base('database/token.pdl') if token.exists(): token.open() else: token.create('user_id', 'access', 'expire_time', 'refresh') if len(client) == 0: client.insert(secret='test_secret', redirect_uri='http://example.com', name='app1') client.commit()
from pathlib import Path from pydblite import Base if not Path('db').exists(): Path('db').mkdir() client = Base('db/client.pdl') if client.exists(): client.open() else: client.create('secret', 'redirect_uri', 'name') authorization_code = Base('db/authorization_code.pdl') if authorization_code.exists(): authorization_code.open() else: authorization_code.create('user_id', 'code', 'expire_time') token = Base('db/token.pdl') if token.exists(): token.open() else: token.create('user_id', 'access', 'expire_time', 'refresh') user = Base('db/user.pdl') if user.exists(): user.open() else: user.create('login', 'password_hash', 'name', 'email') event = Base('db/event.pdl')
from pathlib import Path from pydblite import Base if not Path('db').exists(): Path('db').mkdir() client = Base('db/client.pdl') if client.exists(): client.open() else: client.create('secret', 'redirect_uri', 'name') authorization_code = Base('db/authorization_code.pdl') if authorization_code.exists(): authorization_code.open() else: authorization_code.create('user_id', 'code', 'expire_time') token = Base('db/token.pdl') if token.exists(): token.open() else: token.create('user_id', 'access', 'expire_time', 'refresh') user = Base('db/user.pdl') if user.exists(): user.open() else: user.create('login', 'password_hash', 'name', 'email', 'phone') clothes = Base('db/clothes.pdl')
def __init__(self): db = Base('block_chain.pdl') db.open() self.db = db
from pydblite import Base from pathlib import Path if not Path('database').exists(): Path('database').mkdir() client = Base('database/client.pdl') if client.exists(): client.open() else: client.create('client_id', 'client_secret', 'redirect_uri') auth_code = Base('database/auth_code.pdl') if auth_code.exists(): auth_code.open() else: auth_code.create('user_id', 'code', 'expired') token = Base('database/token.pdl') if token.exists(): token.open() else: token.create('user_id', 'access', 'expired', 'refresh') user = Base('database/user.pdl') if user.exists(): user.open() else: user.create('login', 'password', 'name', 'email', 'phone') item = Base('database/item1.pdl')