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)])
Пример #2
0
def generateWeights(graph, weightFile, param):
    pdb = Base(weightFile)
    pdb.create('pair', 'node1', 'node2', 'FI')
    pdb.create_index('pair')

    sortedNodes = sorted(graph.nodes())
    for node in sortedNodes:
        others = sorted(set(n for n in sortedNodes if n > node))
        for other in others:
            if graph.has_edge(node, other):
                informations = list(
                    edge
                    for n1, n2, edge in graph.edges([node, other], data=True)
                    if ((n1 == node and n2 == other) or (
                        n1 == other and n2 == node)))

                total_publications = len(informations)
                bagNode1 = list(
                    eval(edge['keywords'])
                    for n1, n2, edge in graph.edges([node], data=True)
                    if (n1 != other and n2 != other))
                bagNode2 = list(
                    eval(edge['keywords'])
                    for n1, n2, edge in graph.edges([other], data=True)
                    if (n1 != node and n2 != node))
                jc = get_jacard_domain(bagNode1, bagNode2)

                pdb.insert(
                    str(node) + ';' + str(other), node, other,
                    (total_publications * (jc + 1)))

    pdb.commit()
    return pdb
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 generateWeights(graph, weightFile, param):
    pdb = Base(weightFile)
    pdb.create('pair', 'node1', 'node2', 'TS02', 'TS05', 'TS08')
    pdb.create_index('pair')

    sortedNodes = sorted(graph.nodes())
    for node in sortedNodes:
        others = sorted(set(n for n in sortedNodes if n > node))
        for other in others:
            if graph.has_edge(node, other):
                informations = list(
                    edge
                    for n1, n2, edge in graph.edges([node, other], data=True)
                    if ((n1 == node and n2 == other) or (
                        n1 == other and n2 == node)))
                timesofLinks = []
                for info in informations:
                    timesofLinks.append(int(info['time']))

                total_publications = len(informations)
                k = int(param.t0_) - max(timesofLinks)
                decayfunction02 = (1 - 0.2)**k
                decayfunction05 = (1 - 0.5)**k
                decayfunction08 = (1 - 0.8)**k

                pdb.insert(
                    str(node) + ';' + str(other), node, other,
                    (total_publications * decayfunction02),
                    (total_publications * decayfunction05),
                    (total_publications * decayfunction08))

    pdb.commit()
    return pdb
Пример #5
0
 def __init__(self):
     self._pdb = Base('centric.partition')
     self._sdb = Base('centric.scanner')
     self._pdb.create('pid',
                      'maxSeq',
                      'minSeq',
                      'tableName',
                      'assigned',
                      'splitNum',
                      'phase',
                      'creator',
                      'createTime',
                      'lastUpdateTime',
                      mode="override")
     self._sdb.create('startSeq',
                      'endSeq',
                      'intervalSecs',
                      'scannerId',
                      'pid',
                      'creator',
                      'createTime',
                      'lastUpdateTime',
                      'url',
                      'port',
                      mode="override")
Пример #6
0
def calculatingWeights(graph, nodesnotLinked, database, calculatingFile):
    pdb = Base(calculatingFile)
    pdb.create('node1', 'node2', 'WCNFI','WAAFI')
    pdb.create_index('node1', 'node2')
                
    element = 0
    qtyofNodesToProcess = len(nodesnotLinked)
    for pair in nodesnotLinked:
        element = element+1
        FormatingDataSets.printProgressofEvents(element, qtyofNodesToProcess, "Calculating features for nodes not liked: ")
        neighbors_node1 = all_neighbors(graph, pair[0])
        neighbors_node2 = all_neighbors(graph, pair[1])
        len_neihbors_node1 = len(neighbors_node1)
        len_neihbors_node2 = len(neighbors_node2)
        CommonNeigbors = neighbors_node1.intersection(neighbors_node2)
        WCNFI = 0;
        WAAFI = 0;
        
        for cn in CommonNeigbors:
            item = get_partOfWeightCalculating(graph, database, pair, cn)
            WCNFI = WCNFI + item['WCN'];
            WAAFI = WAAFI + item['WAA'];
        pdb.insert(str(pair[0]), str(pair[1]), WCNFI, WAAFI )   
    pdb.commit()
    return pdb;
Пример #7
0
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'))
Пример #8
0
 def __init__(self, mode):
     self.db = Base("./mlfv_hosts.pdl")
     self.db.create('ip',
                    'port',
                    'libs',
                    'cpu',
                    'mem',
                    'net',
                    'runs',
                    mode=mode)
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 generateWeights(graph, weightFile, param):
    pdb = Base(weightFile)
    pdb.create('pair', 'node1', 'node2','TS02','TS05','TS08', 'JC')
    pdb.create_index('pair')
    
    sortedNodes = sorted(graph.nodes())
    for node in sortedNodes:
        others = sorted(set(n for n in sortedNodes if n > node))
        for other in others:
            if graph.has_edge(node, other):
                informations = list(edge for n1, n2, edge in graph.edges([node, other], data=True) if ((n1 == node and n2 == other) or (n1 == other and n2 == node)) )
                timesofLinks = []
                for info in informations:
                    timesofLinks.append(int(info['time']))
        
                
                bagNode1 = list(eval(edge['keywords']) for n1, n2, edge in graph.edges([node], data=True) if (n1 != other and n2 != other)  )
                bagNode2 = list(eval(edge['keywords']) for n1, n2, edge in graph.edges([other], data=True) if (n1 != node and n2 != node)  )
                
                
                total_publications = len(informations)   
                k =  int(param.t0_)  - max(timesofLinks)
                decayfunction02 = (1 - 0.2) ** k
                decayfunction05 = (1 - 0.5) ** k
                decayfunction08 = (1 - 0.8) ** k
                
                pdb.insert(str(node) + ';' + str(other),node,other,(total_publications * decayfunction02) , (total_publications * decayfunction05) , (total_publications * decayfunction08), get_jacard_domain(bagNode1, bagNode2) ) 
                 
    pdb.commit()            
    return pdb
Пример #11
0
def generateWeights(graph, weightFile, param):
    pdb = Base(weightFile)
    pdb.create('pair', 'node1', 'node2','FTI01','FTI02','FTI03','FTI04','FTI05','FTI06','FTI07','FTI08','FTI09')
    pdb.create_index('pair')
    
    sortedNodes = sorted(graph.nodes())
    for node in sortedNodes:
        others = sorted(set(n for n in sortedNodes if n > node))
        for other in others:
            if graph.has_edge(node, other):
                informations = list(edge for n1, n2, edge in graph.edges([node, other], data=True) if ((n1 == node and n2 == other) or (n1 == other and n2 == node)) )
                timesofLinks = []
                for info in informations:
                    timesofLinks.append(int(info['time']))
                
                total_publications = len(informations)   
                k =  int(param.t0_)  - max(timesofLinks)
                FTI01 = total_publications * (0.1**k)
                FTI02 = total_publications * (0.2**k)
                FTI03 = total_publications * (0.3**k)
                FTI04 = total_publications * (0.4**k)
                FTI05 = total_publications * (0.5**k)
                FTI06 = total_publications * (0.6**k)
                FTI07 = total_publications * (0.7**k)
                FTI08 = total_publications * (0.8**k)
                FTI09 = total_publications * (0.9**k)
                 
                
 
                pdb.insert(str(node) + ';' + str(other),node,other, FTI01, FTI02, FTI03, FTI04, FTI05, FTI06, FTI07, FTI08, FTI09 ) 
                 
    pdb.commit()            
    return pdb
 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')
Пример #13
0
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"
Пример #14
0
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 generateDataForCalculate(self):
     if self.trainnigGraph == None:
         self.generating_Training_Graph()
     
     _nodes = sorted(self.trainnigGraph.nodes())
     adb = Base(self.filePathTrainingGraph + ".calc.pdl")
     adb.create('pairNodes', 'common', 'time', 'domain' )
     
     for node in sorted(_nodes):
         othernodes = set(n for n in _nodes if n > node)
         for other in othernodes:
             common =  set(networkx.common_neighbors(self.trainnigGraph, node, other))
             arestas = self.trainnigGraph.edges([node, other], True)
Пример #16
0
def generateWeights(graph, weightFile, param):
    pdb = Base(weightFile)
    pdb.create('pair', 'node1', 'node2', 'FTI01', 'FTI02', 'FTI03', 'FTI04',
               'FTI05', 'FTI06', 'FTI07', 'FTI08', 'FTI09')
    pdb.create_index('pair')

    sortedNodes = sorted(graph.nodes())
    for node in sortedNodes:
        others = sorted(set(n for n in sortedNodes if n > node))
        for other in others:
            if graph.has_edge(node, other):
                informations = list(
                    edge
                    for n1, n2, edge in graph.edges([node, other], data=True)
                    if ((n1 == node and n2 == other) or (
                        n1 == other and n2 == node)))
                timesofLinks = []
                for info in informations:
                    timesofLinks.append(int(info['time']))

                total_publications = len(informations)
                k = int(param.t0_) - max(timesofLinks)

                decayfunction = (0.8)**k
                bagNode1 = list(
                    eval(edge['keywords'])
                    for n1, n2, edge in graph.edges([node], data=True)
                    if (n1 != other and n2 != other))
                bagNode2 = list(
                    eval(edge['keywords'])
                    for n1, n2, edge in graph.edges([other], data=True)
                    if (n1 != node and n2 != node))

                jc = get_jacard_domain(bagNode1, bagNode2)

                FTI01 = total_publications * (decayfunction * (1 / (0.1**jc)))
                FTI02 = total_publications * (decayfunction * (1 / (0.2**jc)))
                FTI03 = total_publications * (decayfunction * (1 / (0.3**jc)))
                FTI04 = total_publications * (decayfunction * (1 / (0.4**jc)))
                FTI05 = total_publications * (decayfunction * (1 / (0.5**jc)))
                FTI06 = total_publications * (decayfunction * (1 / (0.6**jc)))
                FTI07 = total_publications * (decayfunction * (1 / (0.7**jc)))
                FTI08 = total_publications * (decayfunction * (1 / (0.8**jc)))
                FTI09 = total_publications * (decayfunction * (1 / (0.9**jc)))

                pdb.insert(
                    str(node) + ';' + str(other), node, other, FTI01, FTI02,
                    FTI03, FTI04, FTI05, FTI06, FTI07, FTI08, FTI09)

    pdb.commit()
    return pdb
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 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!")
Пример #19
0
def generateWeights(graph, weightFile, param):
    pdb = Base(weightFile)
    pdb.create('pair', 'node1', 'node2', 'CTS02', 'CTS05', 'CTS08')
    pdb.create_index('pair')

    sortedNodes = sorted(graph.nodes())
    for node in sortedNodes:
        others = sorted(set(n for n in sortedNodes if n > node))
        for other in others:
            if graph.has_edge(node, other):
                informations = list(
                    edge
                    for n1, n2, edge in graph.edges([node, other], data=True)
                    if ((n1 == node and n2 == other) or (
                        n1 == other and n2 == node)))
                timesofLinks = []
                for info in informations:
                    timesofLinks.append(int(info['time']))

                bagNode1 = list(
                    eval(edge['keywords'])
                    for n1, n2, edge in graph.edges([node], data=True)
                    if (n1 != other and n2 != other))
                bagNode2 = list(
                    eval(edge['keywords'])
                    for n1, n2, edge in graph.edges([other], data=True)
                    if (n1 != node and n2 != node))

                total_publications = len(informations)
                k = int(param.t0_) - max(timesofLinks)

                jc = get_jacard_domain(bagNode1, bagNode2)
                decayfunction = (0.6)**k
                decayfunction02 = (1 - 0.7)**jc
                decayfunction05 = (1 - 0.8)**jc
                decayfunction08 = (1 - 0.9)**jc

                CTS02 = total_publications * (decayfunction *
                                              (1 / decayfunction02))
                CTS05 = total_publications * (decayfunction *
                                              (1 / decayfunction05))
                CTS08 = total_publications * (decayfunction *
                                              (1 / decayfunction08))

                pdb.insert(
                    str(node) + ';' + str(other), node, other, CTS02, CTS05,
                    CTS08)

    pdb.commit()
    return pdb
    def generateDataForCalculate(self):
        if self.trainnigGraph == None:
            self.generating_Training_Graph()

        _nodes = sorted(self.trainnigGraph.nodes())
        adb = Base(self.filePathTrainingGraph + ".calc.pdl")
        adb.create('pairNodes', 'common', 'time', 'domain')

        for node in sorted(_nodes):
            othernodes = set(n for n in _nodes if n > node)
            for other in othernodes:
                common = set(
                    networkx.common_neighbors(self.trainnigGraph, node, other))
                arestas = self.trainnigGraph.edges([node, other], True)
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")
Пример #22
0
def save_in_db(comic_url):
    db = Base(os.path.join(SCRIPT_DIR, 'comics.db'))
    db.create('comic', 'time', mode="open")

    db.insert(comic=comic_url, time=datetime.datetime.now())
    db.commit()

    return len(db(comic=comic_url)) == 1
    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()
Пример #24
0
def _create_db():
    try:
        app.db = Base('pets.pdl')
        app.db.create('name', 'type', 'age', 'sex', 'description', 'owner_email', 'image_url')
    except IOError:
        app.db.open()
        print('Base db already exists')
Пример #25
0
 def open_spider(self, spider):
     # Creation of DB
     self.db = Base(spider.database)
     self.db.create('uid', 'type', 'author', 'title', 'text', 'date_time',
                    'tags', 'views', 'answers', 'resolve', 'upvotes', 'url',
                    mode="override")
     dispatcher.connect(self.spider_closed, signals.spider_closed)
Пример #26
0
 def __init__(self, database_name=None):
     print ("Opening " + database_name)
     db_r = Base(database_name)
     # Choose the DB of the Question Thread URL
     db_r.create('url', 'date', mode="open")
     # Check if the DB is empty or new
     if len(db_r)==0:
         print ("ERROR: Database not found or empty")
         sys.exit()
     else:
         print ("Database elements: " + str(len(db_r)))
         for r in db_r:
             self.url_to_scrape.append(UrlDate(r["url"], r["date"]))
         # Making a SET of the Database in order to delete duplicate URLS
         self.url_to_scrape = {x.url: x for x in self.url_to_scrape}.values()
         print ("Database elements after set operation: " + str(len(db_r)))
Пример #27
0
class Owner(Model):
    name = 'owner'
    base = Base('database/' + name + '.pdl')

    def create_db(cls):
        cls.base.create('login', 'password', 'name', 'email', 'phone',
                        'address')

    def insert_db(cls, request):
        return cls.db().insert(
            login=request.form['login'],
            name=request.form['name'],
            email=request.form['email'],
            phone=request.form['phone'],
            address=request.form['address'],
            password=sha256(
                request.json['password'].encode('UTF-8')).hexdigest())

    def update_db(cls, item, request):
        return cls.db().update(item,
                               name=request.form['name'],
                               email=request.form['email'],
                               phone=request.form['phone'],
                               address=request.form['address'])

    def __init__(self, id):
        super().__init__(id)
        self.data.pop('password')
Пример #28
0
def save_in_db(channel, count):
    db = Base(os.path.join(SCRIPT_DIR, f'{channel}_members.db'))
    db.create('members', 'time', mode="open")
    len_db = len(db)
    count_previous = db[len_db - 1]['members'] if len_db else 0
    if count != count_previous:
        db.insert(members=count, time=datetime.datetime.now())
        db.commit()
        return True
Пример #29
0
def generateWeights(graph, weightFile, param):
    pdb = Base(weightFile)
    pdb.create('pair', 'node1', 'node2','FI')
    pdb.create_index('pair')
    
    sortedNodes = sorted(graph.nodes())
    for node in sortedNodes:
        others = sorted(set(n for n in sortedNodes if n > node))
        for other in others:
            if graph.has_edge(node, other):
                informations = list(edge for n1, n2, edge in graph.edges([node, other], data=True) if ((n1 == node and n2 == other) or (n1 == other and n2 == node)) )
                        
                total_publications = len(informations)   
                pdb.insert(str(node) + ';' + str(other),node,other, total_publications ) 
                 
    pdb.commit()            
    return pdb
Пример #30
0
 def open_spider(self, spider):
     # Creation of DB
     self.db = Base(spider.database)
     self.db.create('uid',
                    'type',
                    'author',
                    'title',
                    'text',
                    'date_time',
                    'tags',
                    'views',
                    'answers',
                    'resolve',
                    'upvotes',
                    'url',
                    mode="override")
     dispatcher.connect(self.spider_closed, signals.spider_closed)
Пример #31
0
def save_in_db(channel, count, date):
    db = Base(os.path.join(SCRIPT_DIR, f'{channel}_members.db'))
    db.create('members', 'time', mode="open")
    variant = db[0]['members'].split()[1]
    value = f"{count} {variant}"
    already_present = [r for r in db if r['members'] == value]
    if not already_present:
        db.insert(members=value, time=date)
        db.commit()
        return True
Пример #32
0
    def do_Delete (self, result, request, args):
        def transfomType(x):
            if isinstance(x, unicode): return str(x)
            else: return x
    
        #######    Replace this section by your logic   #######
        db = Base('database_service6.pdl')
        db.create('testId', 'testMessage', mode="open")
        result = db(testId = int(args['testId']))
        
        if len(result) == 0:
            responseCode = 404 #ResponseCode.Ok
            responseBody = json.dumps(result, sort_keys=True, indent=4, separators=(',', ': '))
        else:
            responseCode = 200 #ResponseCode.Ok
            responseBody = json.dumps(result[0], sort_keys=True, indent=4, separators=(',', ': '))
            db.delete(result[0])
            db.commit()
        #######    Replace this section by your logic   #######


        request.setResponseCode(responseCode)
        resp = utils.serviceResponse(responseCode, responseBody)
        
        return resp
Пример #33
0
    def do_Post (self, result, request, args):
        def transfomType(x):
            if isinstance(x, unicode): return str(x)
            else: return x
    
        requestBody = args['requestContent']
        
        #######    Replace this section by your logic   #######
        vTestId = transfomType(json.loads(requestBody)['testId'])
        vTestMessage = transfomType(json.loads(requestBody)['testMessage'])
    
        responseCode = 200 #ResponseCode.Ok
 
       
        db = Base('database_service6.pdl')
        db.create('testId', 'testMessage', mode="open")
        db.insert(testId = vTestId, testMessage = vTestMessage)
        db.commit()

        result = []

        responseBody = json.dumps(result, sort_keys=True, indent=4, separators=(',', ': '))
        #######    Replace this section by your logic   #######


        request.setResponseCode(responseCode)
        resp = utils.serviceResponse(responseCode, responseBody)
        
        return resp
Пример #34
0
    def __init__(self):

        #Creating log file
        filename = "session_log.txt"
        self.log_target = codecs.open(filename, 'a+', encoding='utf-8')
        self.log_target.truncate()
        self.log_target.write("***New session started at: "+ str(datetime.datetime.strftime(datetime.datetime.now(), ' %Y-%m-%d %H:%M:%S ')) + " ***" +"\n")

        #Creating database for items
        self.db = Base('QuestionThreadExtracted.pdl')
        self.db.create('uid', 'type', 'author', 'title', 'text', 'date_time',
                       'tags', 'views', 'answers', 'resolve', 'upvotes', 'url', mode="open")

        #Some data for the log file
        self.number_of_questions = 0
        self.number_of_answers = 0
        self.last_id=0
        dispatcher.connect(self.spider_closed, signals.spider_closed)
Пример #35
0
def open_db():
  db = Base(DB_FILE)
  db.create('abbr', 'name', 'available', 'volume', 'buy', 'sell', 'date',
            mode="open")
  if not db.exists():
    raise Exception('Database error')
  db.create_index('abbr')
  return db
Пример #36
0
    def open_spider(self, spider):

        filename = "urls_log.txt"
        self.log_target = codecs.open(filename, 'a+', encoding='utf-8')
        self.log_target.truncate()

        self.db = Base('URL_database.pdl')
        self.db.create('url', 'date', mode="open")
        self.log_target.write("***New url scraping session started at: " + str(
            datetime.datetime.strftime(datetime.datetime.now(),
                                       ' %Y-%m-%d %H:%M:%S ')) + " ***" + "\n")
        print("***New url scraping session started at: " + str(
            datetime.datetime.strftime(datetime.datetime.now(),
                                       ' %Y-%m-%d %H:%M:%S ')) + " ***" + "\n")
        self.log_target.write(
            "*** Total url in the Database BEFORE new search: " +
            str(len(self.db)) + " ***" + "\n")

        dispatcher.connect(self.spider_closed, signals.spider_closed)
def calculatingWeights(graph, nodesnotLinked, database, calculatingFile):
    pdb = Base(calculatingFile)
    pdb.create('node1', 'node2', 'cnWTS02', 'cnWTS05', 'cnWTS08', 'aaWTS02',
               'aaWTS05', 'aaWTS08')
    pdb.create_index('node1', 'node2')

    element = 0
    qtyofNodesToProcess = len(nodesnotLinked)
    for pair in nodesnotLinked:
        element = element + 1
        FormatingDataSets.printProgressofEvents(
            element, qtyofNodesToProcess,
            "Calculating features for nodes not liked: ")
        neighbors_node1 = all_neighbors(graph, pair[0])
        neighbors_node2 = all_neighbors(graph, pair[1])
        len_neihbors_node1 = len(neighbors_node1)
        len_neihbors_node2 = len(neighbors_node2)
        CommonNeigbors = neighbors_node1.intersection(neighbors_node2)
        CNWts02Feature = 0
        CNWts05Feature = 0
        CNWts08Feature = 0
        AAWts02Feature = 0
        AAWts05Feature = 0
        AAWts08Feature = 0
        CNWJCFeature = 0
        AAWJCFeature = 0

        for cn in CommonNeigbors:
            item = get_partOfWeightCalculating(graph, database, pair, cn)
            CNWts02Feature = CNWts02Feature + item['cnWts02']
            CNWts05Feature = CNWts05Feature + item['cnWts05']
            CNWts08Feature = CNWts08Feature + item['cnWts08']
            AAWts02Feature = AAWts02Feature + item['aaWts02']
            AAWts05Feature = AAWts05Feature + item['aaWts05']
            AAWts08Feature = AAWts08Feature + item['aaWts08']
            #CNWJCFeature = CNWJCFeature + item['cnWJC'];
            #AAWJCFeature = AAWJCFeature + item['aaWJC'];

        pdb.insert(str(pair[0]), str(pair[1]), CNWts02Feature, CNWts05Feature,
                   CNWts08Feature, AAWts02Feature, AAWts05Feature,
                   AAWts08Feature)
    pdb.commit()
    return pdb
Пример #38
0
class Data:
    """Stores global data

    Gives access to a series of global variables for use throughout the file
    """
    books = {}
    authors = {}
    bookDB = Base(EBOOK_FOLDER + 'books.pdl')
    authorDB = Base(EBOOK_FOLDER + 'authors.pdl')

    @staticmethod
    def debug_log(msg_str):
        """Log helper

        Prefixes a debug message with the plugin title to allow for easy search in the log

        Arguments:
            msg_str {string} -- Message to log
        """
        Log.Debug(TITLE + ": " + msg_str)
Пример #39
0
    def do_Get (self, result, request, args):
 
        #######    Replace this section by your logic   #######
        db = Base('database_service6.pdl')
        db.create('testId', 'testMessage', mode="open")
        result = db(testId = int(args['testId']))
        
        if len(result) == 0:
            responseCode = 404 #ResponseCode.Ok
            responseBody = json.dumps(result, sort_keys=True, indent=4, separators=(',', ': '))
        else:
            responseCode = 200 #ResponseCode.Ok
            responseBody = json.dumps(result[0], sort_keys=True, indent=4, separators=(',', ': '))
        #######    Replace this section by your logic   #######


        request.setResponseCode(responseCode)
        resp = utils.serviceResponse(responseCode, responseBody)
        
        return resp
Пример #40
0
 def checkCondition(cls, result):
     if result == "error":
         return "erro"
     else:
         
         db = Base('database_service1.pdl')
         db.create('cod', 'message', mode="open")
         db.insert(cod='1', message='valid')
         db.insert(cod='2', message='not valid')
         db.commit()
         #for rec in (db("age") > 30):
         for rec in db:
             print rec["cod"] +' '+ rec["message"]
         
         
         
         return "ok"
Пример #41
0
def get_gbq_query_results(gbq_service, query, prj_id='ace-amplifier-455', index_col=None,
                          col_order=None, cache=True, cache_path='', db=None):
    
    # set_trace()
    if cache:
        if db is None:
            db = Base(cache_path).create('query', 'result_df', mode='open')
            # db.create_index('query')
        final_df = extract(db, query)
        if len(final_df) > 0:
            # print 'extracted from cache ' + db.path
            return final_df

    df = gbq.read_gbq(query, prj_id)

    if cache:
        db.insert(query, df)
        db.commit()
        print 'saved to cache ' + db.path

    return df
Пример #42
0
class Posts:
    def __init__(self, filename, erase_db):
        self.db = Base(filename)
        self.db.create('author', 'content', 'date', mode="override" if erase_db else "open")

    def addPost(self, post):
        """ Persist a Post object in db and returns auto-generated id. """
        post.id = self.db.insert(author = post.author, content = post.content, date = post.date)
        self.db.commit()
        return post.id

    def getPost(self, id):
        """ Get a post by its id. Returns a Post object or None if id is not found. """
        db_entry = self.db[id] if id in self.db else None
        return self.__createPost(db_entry) if db_entry is not None else None

    def getPosts(self, from_date = None, to_date = None, author = None):
        """ Get all posts matching optionally provided conditions. Returns a list (can be empty). """
        iterator = self.db.filter()
        if from_date is not None:
            iterator = iterator & (self.db("date") > from_date)
        if to_date is not None:
            iterator = iterator & (self.db("date") < to_date)
        if author is not None:
            iterator = iterator & (self.db("author") == author)

        return [self.__createPost(db_entry) for db_entry in iterator]

    def getPostsCount(self):
        """ Get total number of posts in db. """
        return len(self.db)

    def __createPost(self, db_entry):
        return Post(db_entry['author'], db_entry['content'], db_entry['date'], db_entry['__id__'])
Пример #43
0
def likes(currentMessage):
    try:
        db = Base('chatStorage/likes/likes.pdl') #The path to the database
        db.create('userID', 'likes', 'dislikes', 'history', 'liked', mode="open") #Create a new DB if one doesn't exist. If it does, open it
        sentMyKarma = False
        try:
            likes = 0
            dislikes = 0
            if int(currentMessage.reply_to_message.from_user.id) == int(117924410): #is replying to bot message with /likes
                for user in db:
                    if int(user['userID']) == 117924410:
                        likes = int(user['likes'])
                        dislikes = int(user[dislikes])
                karma = int(likes) - int(dislikes)
                response = "Since you asked, I have " + str(likes) + " likes and " + str(dislikes) + " dislikes, for a total of " + str(karma) + " karma. "
                if karma > 0:
                    response += "\xF0\x9F\x98\x83".decode("utf-8") #smiley
                else:
                    response += "\xF0\x9F\x98\xAD".decode("utf-8") #crying
                return response
                sentMyKarma = True
        except Exception:
            print traceback.format_exc()

        if not sentMyKarma:
            userWasFound = False
            for user in db:
                if(int(user['userID']) == int(currentMessage.from_user.id)):
                    userWasFound = True
                    likes = int(user['likes'])
                    dislikes = int(user['dislikes'])

            if userWasFound:
                return currentMessage.from_user.first_name + ", you have " + str(likes) + " likes and " + str(dislikes) + " dislikes, for a total of " + str(int(likes) - int(dislikes)) + " karma."
            else:
                return "No like data found!"
    except Exception:
        print traceback.format_exc()
        return ""
Пример #44
0
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
Пример #45
0
    def open_spider(self, spider):

        filename = "urls_log.txt"
        self.log_target = codecs.open(filename, 'a+', encoding='utf-8')
        self.log_target.truncate()

        self.db = Base('URL_database.pdl')
        self.db.create('url', 'date', mode="open")
        self.log_target.write("***New url scraping session started at: "+ str(datetime.datetime.strftime(datetime.datetime.now(), ' %Y-%m-%d %H:%M:%S ')) + " ***" +"\n")
        print("***New url scraping session started at: "+ str(datetime.datetime.strftime(datetime.datetime.now(), ' %Y-%m-%d %H:%M:%S ')) + " ***" +"\n")
        self.log_target.write("*** Total url in the Database BEFORE new search: "+ str(len(self.db)) + " ***" + "\n")


        dispatcher.connect(self.spider_closed, signals.spider_closed)
Пример #46
0
class DBPipeline(object):
    def __init__(self):

        #Creating log file
        filename = "session_log.txt"
        self.log_target = codecs.open(filename, 'a+', encoding='utf-8')
        self.log_target.truncate()
        self.log_target.write("***New session started at: "+ str(datetime.datetime.strftime(datetime.datetime.now(), ' %Y-%m-%d %H:%M:%S ')) + " ***" +"\n")

        #Creating database for items
        self.db = Base('QuestionThreadExtracted.pdl')
        self.db.create('uid', 'type', 'author', 'title', 'text', 'date_time',
                       'tags', 'views', 'answers', 'resolve', 'upvotes', 'url', mode="open")

        #Some data for the log file
        self.number_of_questions = 0
        self.number_of_answers = 0
        self.last_id=0
        dispatcher.connect(self.spider_closed, signals.spider_closed)

 
    def process_item(self, item, spider):

        self.db.insert(uid=item['uid'],
                       type=item['type'],
                       author=item['author'],
                       title=item['title'],
                       text=item['text'],
                       date_time=item['date_time'],
                       tags=item['tags'],
                       views=item['views'],
                       answers=item['answers'],
                       resolve=item['resolve'],
                       upvotes=item['upvotes'],
                       url=item['url']
                       )
        #Count questions and answers
        if "question" in item['type']:
            self.number_of_questions+=1
            if self.last_id<item['uid']:
                self.last_id=item['uid']
        else:
            self.number_of_answers+=1


        self.db.commit()
        return item

    def spider_closed(self, spider):
        self.log_target.write("Questions founded: "+ str(self.number_of_questions) + "\n")
        self.log_target.write("Answers founded: "+ str(self.number_of_answers) + "\n")
        self.log_target.write("Last UID: "+str(self.last_id) + "\n" + "\n")


        self.log_target.write("***Session End at: "+ str(datetime.datetime.strftime(datetime.datetime.now(), ' %Y-%m-%d %H:%M:%S ')) + " ***" +"\n")

        self.log_target.close()
Пример #47
0
class Rates:
    """ Persistence layer for exchange rates. """

    def __init__(self, filename, erase_db):
        self.__db = Base(filename)
        self.__db.create('currency', 'rate', mode="override" if erase_db else "open")
        self.__db.create_index('currency')

    def setRate(self, currency, rate):
        """ Persist a currency's exchange rate. """
        assert rate > 0.0

        records = self.__db._currency[currency]

        if len(records) > 0:
            assert len(records) == 1 # We never expect several exchange rates for the same currency
            self.__db.update(records[0], rate = rate)
        else:
            self.__db.insert(currency = currency, rate = rate)

        self.__db.commit()

    def getRate(self, currency):
        """ Get the exchange rate with EUR for the provided currency or None if it is not found.
            An exchange rate for currency CUR is Value(EUR) / Value(CUR): 1 EUR = rate(CUR) CUR <=> 1/rate(CUR) EUR = 1 CUR.
        """
        records = self.__db._currency[currency]
        return records[0]['rate'] if len(records) > 0 else None

    def getAllRates(self):
        """ Get all known exchange rates as a dict. """
        return [(r['currency'], r['rate']) for r in self.__db]

    def getRatesCount(self):
        """ Get total number of exchange rates in db. """
        return len(self.__db)
def calculatingWeights(graph, nodesnotLinked, database, calculatingFile):
    pdb = Base(calculatingFile)
    pdb.create('node1', 'node2', 'cnWTS02','cnWTS05','cnWTS08', 'aaWTS02', 'aaWTS05', 'aaWTS08')
    pdb.create_index('node1', 'node2')
                
    element = 0
    qtyofNodesToProcess = len(nodesnotLinked)
    for pair in nodesnotLinked:
        element = element+1
        FormatingDataSets.printProgressofEvents(element, qtyofNodesToProcess, "Calculating features for nodes not liked: ")
        neighbors_node1 = all_neighbors(graph, pair[0])
        neighbors_node2 = all_neighbors(graph, pair[1])
        len_neihbors_node1 = len(neighbors_node1)
        len_neihbors_node2 = len(neighbors_node2)
        CommonNeigbors = neighbors_node1.intersection(neighbors_node2)
        CNWts02Feature = 0;
        CNWts05Feature = 0;
        CNWts08Feature = 0;
        AAWts02Feature = 0;
        AAWts05Feature = 0;
        AAWts08Feature = 0;
        CNWJCFeature = 0;
        AAWJCFeature = 0;
        
        for cn in CommonNeigbors:
            item = get_partOfWeightCalculating(graph, database, pair, cn)
            CNWts02Feature = CNWts02Feature + item['cnWts02'];
            CNWts05Feature = CNWts05Feature + item['cnWts05'];
            CNWts08Feature = CNWts08Feature + item['cnWts08'];
            AAWts02Feature = AAWts02Feature + item['aaWts02'];
            AAWts05Feature = AAWts05Feature + item['aaWts05'];
            AAWts08Feature = AAWts08Feature + item['aaWts08'];
            #CNWJCFeature = CNWJCFeature + item['cnWJC'];
            #AAWJCFeature = AAWJCFeature + item['aaWJC'];
        
            
        pdb.insert(str(pair[0]), str(pair[1]), CNWts02Feature, CNWts05Feature, CNWts08Feature, AAWts02Feature, AAWts05Feature, AAWts08Feature  )   
    pdb.commit()
    return pdb;
Пример #49
0
def convertcsv2db(csvpath, dbpath): #Converts a CSV file to a PyDBLite database
    db = Base(dbpath)
    try:
        csvfile = open(csvpath, 'rb')
    except csv.Error:
        print "Could not open CSV file at " + csvpath + "\n"
    reader = csv.reader(csvfile)
    header = reader.next()
    try:
        db.create(*header)
    except IOError:
        print "Existing DB at " + dbpath + "\n"
    for row in reader:
        db.insert(*row)
    db.commit()
Пример #50
0
class DBPipeline(object):
    # Pipeline to write an Item in the database
    def open_spider(self, spider):
        # Creation of DB
        self.db = Base(spider.database)
        self.db.create('uid', 'type', 'author', 'title', 'text', 'date_time',
                       'tags', 'views', 'answers', 'resolve', 'upvotes', 'url',
                       mode="override")
        dispatcher.connect(self.spider_closed, signals.spider_closed)

    def process_item(self, item, spider):
        # Writing of the item
        self.db.insert(uid=item['uid'],
                       type=item['type'],
                       author=item['author'],
                       title=item['title'],
                       text=item['text'],
                       date_time=item['date_time'],
                       tags=item['tags'],
                       views=item['views'],
                       answers=item['answers'],
                       resolve=item['resolve'],
                       upvotes=item['upvotes'],
                       url=item['url']
                       )

        self.db.commit()
        return item

    def spider_closed(self, spider):
        # Number of items saved, shown at the end
        i = 0
        j = 0
        for r in self.db:

            if r["type"] == "question":
                i += 1
            else:
                j += 1

        print ('Number of questions and answers found:')
        print (str(i) + ' questions \n')
        print (str(j) + ' answers \n')
Пример #51
0
def setup(args):
    if os.path.isfile(path):
        backup_path = path + '.bak'
        shutil.copy(path, backup_path)

    db = Base(path)

    if args.overwrite:
        while 1:
            confirm = input('Do you really want to overwrite the database ? (y/n) ')
            if confirm in ['y', 'n']:
                break
        if confirm == 'y':
            db.create('name', 'cost', 'date', 'tags', mode='override')
            print('Data base in {} has been overwritten!'.format(path))
    else:
        if db.exists():
            print('{} already exists and is a database. If you want to recreate'
                  ' it, use the -o flag.'.format(path))
        else:
            db.create('name', 'cost', 'date', 'tags', mode='open')
            print('Created database at {}!'.format(path))
Пример #52
0
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")
"""
Пример #53
0
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 calculatingWeights(graph, nodesnotLinked, database, calculatingFile):
    pdb = Base(calculatingFile)
    pdb.create('node1', 'node2', 'WCNFTI01','WCNFTI02', 'WCNFTI03','WCNFTI04','WCNFTI05','WCNFTI06','WCNFTI07','WCNFTI08','WCNFTI09','WAAFTI01','WAAFTI02', 'WAAFTI03','WAAFTI04','WAAFTI05','WAAFTI06','WAAFTI07','WAAFTI08','WAAFTI09')
    pdb.create_index('node1', 'node2')
                
    element = 0
    qtyofNodesToProcess = len(nodesnotLinked)
    for pair in nodesnotLinked:
        element = element+1
        FormatingDataSets.printProgressofEvents(element, qtyofNodesToProcess, "Calculating features for nodes not liked: ")
        neighbors_node1 = all_neighbors(graph, pair[0])
        neighbors_node2 = all_neighbors(graph, pair[1])
        len_neihbors_node1 = len(neighbors_node1)
        len_neihbors_node2 = len(neighbors_node2)
        CommonNeigbors = neighbors_node1.intersection(neighbors_node2)
        WCNFTI01 = 0;
        WCNFTI02 = 0;
        WCNFTI03 = 0;
        WCNFTI04 = 0;
        WCNFTI05 = 0;
        WCNFTI06 = 0;
        WCNFTI07 = 0;
        WCNFTI08 = 0;
        WCNFTI09 = 0;
        
        WAAFTI01 = 0;
        WAAFTI02 = 0;
        WAAFTI03 = 0;
        WAAFTI04 = 0;
        WAAFTI05 = 0;
        WAAFTI06 = 0;
        WAAFTI07 = 0;
        WAAFTI08 = 0;
        WAAFTI09 = 0;
        
        
        for cn in CommonNeigbors:
            item = get_partOfWeightCalculating(graph, database, pair, cn)
            WCNFTI01 = WCNFTI01 + item['WCN'][0];
            WCNFTI02 = WCNFTI02 + item['WCN'][1];
            WCNFTI03 = WCNFTI03 + item['WCN'][2];
            WCNFTI04 = WCNFTI04 + item['WCN'][3];
            WCNFTI05 = WCNFTI05 + item['WCN'][4];
            WCNFTI06 = WCNFTI06 + item['WCN'][5];
            WCNFTI07 = WCNFTI07 + item['WCN'][6];
            WCNFTI08 = WCNFTI08 + item['WCN'][7];
            WCNFTI09 = WCNFTI09 + item['WCN'][8];
            
            WAAFTI01 = WAAFTI01 + item['WAA'][0];
            WAAFTI02 = WAAFTI02 + item['WAA'][1];
            WAAFTI03 = WAAFTI03 + item['WAA'][2];
            WAAFTI04 = WAAFTI04 + item['WAA'][3];
            WAAFTI05 = WAAFTI05 + item['WAA'][4];
            WAAFTI06 = WAAFTI06 + item['WAA'][5];
            WAAFTI07 = WAAFTI07 + item['WAA'][6];
            WAAFTI08 = WAAFTI08 + item['WAA'][7];
            WAAFTI09 = WAAFTI09 + item['WAA'][8];
            
        pdb.insert(str(pair[0]), str(pair[1]), WCNFTI01, WCNFTI02,  WCNFTI02,
                   WCNFTI03,WCNFTI04,WCNFTI05,WCNFTI06,WCNFTI07,WCNFTI08,WCNFTI09,
                   WAAFTI01, WAAFTI02,  WAAFTI02,
                   WAAFTI03,WAAFTI04,WAAFTI05,WAAFTI06,WAAFTI07,WAAFTI08,WAAFTI09,
                    
                    )   
    pdb.commit()
    return pdb;
def generate_finalResult(order,topRank, TestGraph, FileNameResult ):
    pdb = Base(FileNameResult)
    pdb.create('node1', 'node2', 'value', 'sucesso','topRank')
    pdb.create_index('node1', 'node2')
 
    indice = 0 
    for nodeToCheck in order:
        indice = indice+1
        isTopRank = (indice <= topRank)
        if (TestGraph.has_edge(nodeToCheck['node1'],nodeToCheck['node2'])):
            pdb.insert(str(nodeToCheck['node1']), nodeToCheck['node2'],nodeToCheck['value'] , True, isTopRank  ) 
        else:   
            pdb.insert(str(nodeToCheck['node1']), nodeToCheck['node2'],nodeToCheck['value'] , False, isTopRank  ) 
    
    pdb.commit()
    return pdb
Пример #56
0
def process(bot, chat_id, parsedCommand, messageText, currentMessage, update, instanceAge):
    def sendText(givenText, replyingMessageID=0, keyboardLayout=[]):
        if not chatInstanceArray[chat_id]['adminDisable']:
            atbSendFunctions.sendText(bot, chat_id, givenText, replyingMessageID, keyboardLayout)

    def sendPhoto(imageName):
        atbSendFunctions.sendPhoto(bot, chat_id, "images/"+ imageName)

    def sendSticker(stickerName):
        atbSendFunctions.sendSticker(bot, chat_id, "stickers/"+ stickerName)

    def passSpamCheck():
        return atbMiscFunctions.spamCheck(chat_id, currentMessage.date)


    try:
        chatInstanceArray[chat_id]['checking'] = True
    except Exception:
        chatInstanceArray[chat_id] = {'checking': True, 'adminDisable': False, 'spamTimestamp': 0, 'shottyTimestamp': 0, 'shottyWinner': "", 'checkingVehicles': False, 'whoArray': []}


    try:
        #commands go here, in this if-elif block. Python doesn't have switch statements.
        if parsedCommand == "/mom": #sends "MOM GET THE CAMERA"
            sendText("MOM GET THE CAMERA")

        elif atbMiscFunctions.isMoom(parsedCommand): #sends M {random number of Os} M
            if passSpamCheck(): #use this to prevent spamming of a command
                response = "M"
                for i in range(0, random.randint(3, 75)):
                    response += "O"
                sendText(response + "M")

        elif parsedCommand == "/swag":
            sendText("swiggity swag, what\'s in the bag?")

        elif parsedCommand == "/worms":
            if passSpamCheck():
                response = "hey man can I borrow your "
                if len(messageText) > len("/worms "):
                    response += messageText[len("/worms "):]
                else:
                    response += "worms"
                sendText(response)

        elif parsedCommand == "/shh" or parsedCommand == "/shhh":
            if passSpamCheck():
                sendPhoto("shhh.jpg")

        elif parsedCommand == "/father":
            if (random.randint(0, 1)):
                sendText("You ARE the father!")
            else:
                sendText("You are NOT the father!")

        elif parsedCommand == "/rip":   #sends "I can't believe that [name (defaults to sender's name)] is f*****g dead."
            if passSpamCheck():
                response = "I can't believe that "
                if len(messageText) > len("/rip "):
                    if (messageText[len("/rip "):] == "me"):
                        response += currentMessage.from_user.first_name
                    else:
                        response += messageText[len("/rip "):]
                else:
                    response += currentMessage.from_user.first_name
                response += " is f*****g dead."
                sendText(response)

        elif parsedCommand == "/scrub":
            checkingStats = False
            try:
                if currentMessage.text.lower().split()[1] == "stats":
                    db = Base('chatStorage/scrub.pdl') #The path to the DB
                    db.create('username', 'name', 'counter', mode="open")
                    K = list()
                    for user in db:
                        K.append(user)
                    sortedK = sorted(K, key=lambda x: int(x['counter']), reverse=True)
                    outputString = "SCRUBBIEST LEADERBOARD:\n"
                    for user in sortedK:
                        pluralString = " SCRUB POINT"
                        if not(int(user['counter']) == 1):
                            pluralString += "S"
                        pluralString += "\n"
                        outputString += user['name'].upper() + ": " + str(user['counter']) + pluralString
                    sendText(outputString)
                    checkingStats = True
            except IndexError:
                pass

            if not checkingStats and (currentMessage.from_user.id == 169883788 or currentMessage.from_user.id == 44961843):
                db = Base('chatStorage/scrub.pdl')
                db.create('username', 'name', 'counter', mode="open")

                userWasFound = False
                valueSuccessfullyChanged = False

                for user in db:
                    if int(user['username']) == currentMessage.reply_to_message.from_user.id:
                        db.update(user, counter=int(user['counter']) + 1)
                        valueSuccessfullyChanged = True
                        userWasFound = True
                db.commit()

                if not userWasFound:
                    db.insert(currentMessage.reply_to_message.from_user.id, currentMessage.reply_to_message.from_user.first_name, 1)
                    db.commit()

                if valueSuccessfullyChanged or not userWasFound:
                    sendText("Matt Gomez awarded a scrub point to " + currentMessage.reply_to_message.from_user.first_name + ".")

            elif not checkingStats:
                sendText("AdamTestBot, powered by ScrubSoft (C)")

        elif parsedCommand == "/hiss":
            checkingStats = False
            try:
                if currentMessage.text.lower().split()[1] == "stats":
                    db = Base('chatStorage/hiss.pdl')
                    db.create('username', 'name', 'counter', mode="open")
                    K = list()
                    for user in db:
                        K.append(user)
                    sortedK = sorted(K, key=lambda x: int(x['counter']), reverse=True)
                    outputString = "Hiss Leaderboard:\n"
                    for user in sortedK:
                        pluralString = " hiss"
                        if not(int(user['counter']) == 1):
                            pluralString += "es"
                        pluralString += "\n"
                        outputString += user['name'] + ": " + str(user['counter']) + pluralString
                    sendText(outputString)
                checkingStats = True
            except IndexError:
                pass

            if not checkingStats and (currentMessage.from_user.id == 122526873 or currentMessage.from_user.id == 44961843):
                db = Base('chatStorage/hiss.pdl')
                db.create('username', 'name', 'counter', mode="open")

                userWasFound = False
                valueSuccessfullyChanged = False

                for user in db:
                    if int(user['username']) == currentMessage.reply_to_message.from_user.id:
                        db.update(user, counter=int(user['counter']) + 1)
                        valueSuccessfullyChanged = True
                        userWasFound = True
                db.commit()
                
                if not userWasFound:
                    db.insert(currentMessage.reply_to_message.from_user.id, currentMessage.reply_to_message.from_user.first_name, 1)
                    db.commit()

                if valueSuccessfullyChanged or not userWasFound:
                    sendText("Robyn hissed at " + currentMessage.reply_to_message.from_user.first_name + ".")

        elif parsedCommand == "/water":
            if (random.randint(0, 1) == 0):
                sendSticker("water.webp")
            else:
                sendSticker("hoboken_water.webp")

        #this command should go last:
        elif parsedCommand == "/community": #add your command to this list
            response = "/mom - get the camera\n"
            response += "/mooom (any number of \'o\'s) - call for help\n"
            response += "/swag - more memes\n"
            response += "/worms - can I borrow them?\n"
            response += "/shh(h) - here, be relaxed\n"
            response += "/father - are you the father?\n"
            response += "/rip (something) - I can't believe they're dead!\n"
            response += "/hiss stats - see how many time Robyn has hissed at people\n"
            response += "/scrub or /scrub stats - see who sponsors me or how many times Matt Gomez has called you a scrub\n"
            response += "/water - does this water look brown to you?"
            sendText(response)

        else:
            return False

        return True
    except Exception:
        print traceback.format_exc()
        return False
def reading_Database(path):
    adb = Base(path)
    adb.open()
    return adb
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)