Пример #1
0
def main():
    # Establish gmail connection
    creds = None
    # The file token.pickle stores the user's access and refresh tokens, and is
    # created automatically when the authorization flow completes for the first
    # time.
    if os.path.exists('token.pickle'):
        with open('token.pickle', 'rb') as token:
            creds = pickle.load(token)
    # If there are no (valid) credentials available, let the user log in.
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials.json', SCOPES)
            creds = flow.run_local_server(port=0)
        # Save the credentials for the next run
        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token)

    service = build('gmail', 'v1', credentials=creds)

    print('{} Establishing params'.format(getTime()))
    params = set_params()
    params['service'] = service
    params['user_id'] = 'me'
    printGreen('{} Successfully established params'.format(getTime()))

    listener = HaroListener(params)
    listener.messageLoop()
Пример #2
0
    def processMessages(self, msg_ids):
        """Process all the messages corresponding to the items in msg_ids for
        links containing key words/phrases specified in self.link_keys. If any
        links are found, call self.notify() to notify the notification_emails.

        @param msg_ids List[String]: msg_ids obtained from getMessages()
        """
        for msg_id in msg_ids:
            print('{} Processing message with id {}'.format(getTime(), msg_id))
            try:
                response = self.service.users().messages().get(
                    userId=self.user_id, id=msg_id, format='raw').execute()
            except Exception as error:
                printFail("{} Error retrieving message with id {}: {}".format(
                    getTime(), id, error))
                return

            msg_body = messageutils.getMimeMessage(response['raw'])

            found_links = messageutils.findLinks(str(msg_body), self.link_keys)
            if len(found_links) > 0:
                print('{} Found {} links containing key words/phrases'.format(
                    getTime(), len(found_links)))
                self.notify(found_links)
            else:
                print('{} Found 0 links containing key words'.format(
                    getTime()))

            self.inbox_manager.markProcessed(msg_id, self.label_ids)
Пример #3
0
def getItemAnalysis():
    logPath = './analysisLog/'
    df = dfPreprocesing()
    #Items frecuency
    itemsBalance = Counter(df['ITEM'])
    df.groupby('ITEM').agg({'ITEM': ['count']})
    #Number frecuency
    #Number of words
    df['numeroPalabras'] = df['PARRAFO'].apply(wordCount)
    #Number of Punctuation characters
    df['numeroCaracteres'] = df['PARRAFO'].apply(charCount)
    #Word frecuency by item
    dfItem = df.groupby('ITEM').agg({
        'PARRAFO': 'sum',
        'numeroPalabras': 'mean',
        'numeroCaracteres': 'mean'
    })
    dfItem = dfItem.reset_index()
    dfItem['frecPalabras'] = dfItem['PARRAFO'].apply(wordFreq)

    dfItem.to_csv(os.path.join(logPath, 'analysisItem_' + getTime() + '.csv'),
                  sep=',')
    with open(os.path.join(logPath, 'itemsBalance_' + getTime() + '.json'),
              'w') as outPutFile:
        json.dump(dict(itemsBalance), outPutFile)
    #Mean Page, Max - Min
    return getItemAnalysis
Пример #4
0
def savePlayerPlusPPInfo(plusInfo):
    userId = plusInfo.get('osuid')
    plusInfo['time'] = utils.getTime(1)
    userRecord = PlayerPlusPPRecord.query.get(userId)
    if userRecord == None:
        actionType = 'add'
        db.session.add(
            PlayerPlusPPRecord(osuid=userId,
                               osuname=plusInfo.get('osuname'),
                               current_total=str(plusInfo.get('totalPP')),
                               current_raw=str(plusInfo.get('rawPP')),
                               history=str([]),
                               update_time=utils.getTime(1)))
    else:
        actionType = 'update'
        userRecord.osuname = plusInfo.get('osuname')
        userRecord.current_total = str(plusInfo.get('totalPP'))
        userRecord.current_raw = str(plusInfo.get('rawPP'))
        history = eval(userRecord.history)
        history.append(plusInfo)
        userRecord.history = str(history)
        userRecord.update_time = utils.getTime(1)

    db.session.commit()
    return True, f'{actionType} player {userId}'
Пример #5
0
def handleSetUserGroup(data,
                       info='修改用户所属权限组',
                       message='',
                       status=-1,
                       privilege={}):
    count = 0
    try:
        user, group, actor = data.get('targetUsers'), data.get(
            'targetGroup'), data.get('Osuid')
        if type(user) == list:
            for uid in user:
                if database.setUserGroup(uid, group, actor) == True:
                    count += 1
                loginTime = utils.getTime(needFormat=1)
                otsuToken = utils.tokenGenerator(uid, loginTime)
                database.setUserOtsuToken(uid, otsuToken, loginTime, expiresIn)
        else:
            if database.setUserGroup(user, group, actor) == True:
                count += 1
            loginTime = utils.getTime(needFormat=1)
            otsuToken = utils.tokenGenerator(user, loginTime)
            database.setUserOtsuToken(user, otsuToken, loginTime, expiresIn)
    except Exception as Err:
        print(str(Err))
    if count > 0: status = 1
    return None, f'修改了{count}位用户所属的权限组', info, status
Пример #6
0
def printUpcomming(img: Image, show, timeStart: datetime, pos, detail = False):
    draw = ImageDraw.Draw(img)

    if detail:
        pos *= 2

    width, height = draw.textsize(utils.getTime(timeStart), font = rbtv_config.fontSmall)
    
    title = str(show['title'])
    if not detail and (show['topic'] or show['game']):
        title = title +' - '+ str(show['topic'] if show['topic'] else show['game'])
    title = utils.string_normalizer(title)
    title = truncateString(draw, title)

    height = 220 if detail else 210
    if detail:
        height += pos * 5
    paddingLeft = 70
    draw.text((10 + paddingLeft, 33 * pos + height), utils.getTime(timeStart) +' '+ title, font = rbtv_config.fontSmall, fill = 0)
    
    if detail and (show['topic'] or show['game']):
        detailStr = str((show['topic'] if show['topic'] else show['game']))
        detailStr = utils.string_normalizer(detailStr)
        detailStr = truncateString(draw, detailStr)
        draw.text((10 + paddingLeft + width, 33 * pos + height + 32), ' ' +detailStr, font = rbtv_config.fontSmall, fill = 0)

    if show['type'] == 'premiere':
        img.paste(rbtv_config.neu, (10, 33 * pos + height))
    elif show['type'] == 'live':
        img.paste(rbtv_config.live, (10, 33 * pos + height))
    
    if detail and show.get('isSubscribed', False):
        img.paste(rbtv_config.abonniert, (10, 33 * pos + height + 32))
    if detail and show.get('streamExclusive', False):
        img.paste(rbtv_config.streamExclusive, (10, 33 * pos + height + 32))
def callInvoke(appName):
    cmd = "wsk -i action invoke %s --blocking --result" % appName
    startTime = utils.getTime()
    r = os.popen(cmd)
    r.read()
    endTime = utils.getTime()
    return endTime - startTime
Пример #8
0
    def initInbox(self):
        """Initialize the inbox and return the label and filter ids

        @return Dictionary with label ids and filter id
        """
        print('{} Initializing setup...'.format(getTime()))
        print('{} Initializing Labels...'.format(getTime()))
        labels = self.initLabels()
        print('{} Initializing Filter...'.format(getTime()))
        filter_id = self.initFilter(labels['unprocessed'])
        colors.printGreen('{} Setup complete!'.format(getTime()))
        return {'labels': labels, 'filter': filter_id}
Пример #9
0
 def messageLoop(self):
     """Infinite loop that checks the inbox every 30 minutes for new HARO
     emails to be processed.
     """
     while True:
         print('{} Checking for messages...'.format(getTime()))
         msg_ids = self.getMessages()
         if len(msg_ids) > 0:
             self.processMessages(msg_ids)
         sleep_time = 1800
         print('{} Sleeping for {} minutes'.format(getTime(),
                                                   int(sleep_time / 60)))
         sleep(1800)
Пример #10
0
def osuTokenSave(osuid, oauthData):
    osuTokenRecord = osuUserTokenV2.query.get(osuid)
    if osuTokenRecord == None:
        db.session.add(
            osuUserTokenV2(token_v2=str(oauthData),
                           osuid=osuid,
                           record_time=utils.getTime(needFormat=1)))
        db.session.commit()
    else:
        osuTokenRecord.token_v2 = str(oauthData)
        osuTokenRecord.record_time = utils.getTime(needFormat=1)
        db.session.commit()
    return True, osuid
Пример #11
0
async def list(ctx, option, *, message):  #Add or Remove a word to the list
    if ctx.author.id != shizzle.fuhrer_id:  #Checks if its me
        print(getTime(), ctx.author, 'Tried to use addword')
        await ctx.channel.send(
            'You dont have Authorization, please contact an Administator')
    elif option == 'add':  #Adds a word
        woordenlijst.lijst.append(message)
        print(getTime(), message, 'Added to the list')
    elif option == 'remove':  #Removes a word
        print(getTime(), 'Removed', message, 'From the list')
        woordenlijst.lijst.remove(message)
    else:  #If all failed tell me
        print(getTime(), 'Tried to use ;list but something went wrong')
        await ctx.channel.send('Something went wrong')
Пример #12
0
def printCurrent(image: Image, show, timeStart: datetime, timeEnd: datetime, today: datetime, font = rbtv_config.fontSmall):
    draw = ImageDraw.Draw(image)
    
    lowborder = 10
    ypos = 210

    width, height = draw.textsize(utils.getTime(timeStart), font = font)
    draw.text((10, ypos - lowborder - height), utils.getTime(timeStart), font = font, fill = 0)

    width, height = draw.textsize(utils.getTime(timeEnd), font = font)
    draw.text((600 - 10 - width, ypos - lowborder - height), utils.getTime(timeEnd), font = font, fill = 0)


    draw.rectangle((10 + 10 + width, ypos - lowborder - height + 2, 600 - 10 - width - 10, ypos - lowborder + 2))

    width2 = 600 - 10 - width - 10 - 2 - (10 + 10 + width + 2)
    sts = datetime.timestamp(timeStart)
    ets = datetime.timestamp(timeEnd)
    tts = datetime.timestamp(today)

    width2 = width2 * (tts-sts)/(ets-sts)

    draw.rectangle((10 + 10 + width + 2, ypos - lowborder - height + 4, 10 + 10 + width + 2 + width2, ypos - lowborder - 0), 0)


    title = str(show['title'])
    if show['topic'] or show['game']:
        title = title +' - '+ str(show['topic'] if show['topic'] else show['game'])
    title = utils.string_normalizer(title)
    title = truncateString(draw, title, 500)

    draw.text((10 + 10 + width, ypos - lowborder - 53), title, font = font, fill = 0)

    if show['type'] == 'premiere':
        image.paste(rbtv_config.neu, (10, ypos - lowborder - 53))
    elif show['type'] == 'live':
        image.paste(rbtv_config.live, (10, ypos - lowborder - 53))

    r = requests.get(show['episodeImage'])
    try:
        img = Image.open(BytesIO(r.content))

        maxsize = (250, 140)
        tn_image = img.thumbnail(maxsize)

        image.paste(img, (350, 0))
    except:
        print('could not load episodeImage')
        pass
    pass
Пример #13
0
    def cancelOrder(self,
                    symbol,
                    orderId='',
                    origClientOrderId='',
                    newClientOrderId='',
                    recvWindow=''):
        '''
        Name                Type    Mandatory    Description
        symbol                STRING    YES    
        orderId                LONG    NO    
        origClientOrderId    STRING    NO    
        newClientOrderId    STRING    NO    Used to uniquely identify this cancel. Automatically generated by default.
        recvWindow            LONG    NO    
        timestamp            LONG    YES    
        '''
        url = "/api/v3/order"
        params = {'symbol': symbol, 'timestamp': utils.getTime()}
        if (origClientOrderId != ''):
            params.update({'origClientOrderId': origClientOrderId})
        if (orderId != ''):
            params.update({'orderId': orderId})
        if (recvWindow != ''):
            params.update({'recvWindow': recvWindow})
        if (newClientOrderId != ''):
            params.update({'newClientOrderId': newClientOrderId})

        data = self.hitBinanceWebAPI(self.DELETE, url, params, signed=True)

        return data
Пример #14
0
def authorizer(osuid, otsuToken, path, needGroup=[], customInfo={}):
    def infoer(infoType):
        default = {
            'invalid': '请求被拒绝,授权认证',
            'group': '请求被拒绝,认证用户组权限不足',
            'success': '请求已确认,授权认证'
        }
        cust = customInfo.get(infoType)
        if cust != None and cust != '': info = cust
        else: info = default.get(infoType)
        return info

    authorize, actionTime = database.getRedisData(
        osuid, 'userToken', doEval=True), utils.getTime(1)
    if authorize == None or authorize.get('otsuToken') != otsuToken:
        return infoer('invalid'), -1, {}
    groupStatus, privilege = userGroupChecker(needGroup,
                                              eval(authorize.get('group')),
                                              path)
    if groupStatus != True:
        return infoer('group'), -1, {}
    if authorize.get('otsuToken') == otsuToken:
        # pass and refresh token
        database.setUserOtsuToken(osuid,
                                  otsuToken,
                                  actionTime,
                                  expiresIn,
                                  user=None)
        privilege['osuid'] = osuid
        userObject = database.getUserByosuid(osuid)
        if userObject != None: privilege['osuname'] = userObject.osuname
        else: privilege['osuname'] = '未知'
        return infoer('success'), 1, privilege
Пример #15
0
async def shutdown(ctx):  #shutsdown bot
    await ctx.message.delete()
    print(getTime(), ctx.author, "used ;shutdown")
    if ctx.author.id == shizzle.fuhrer_id:
        await bot.logout()
    else:
        ctx.send('You dont have Authorization, pls contact Marek')
Пример #16
0
def getRawPPFromDB(userKey):
    plusRecord, target = database.getPlayerPlusPPRecord(userKey), -1
    rawPP = {}
    osuid = None
    osuname = None
    if plusRecord != None:
        if type(plusRecord) == list:
            if len(plusRecord) > 1:
                status = -1
                repairDuplicateDataRecord(plusRecord)
            elif len(plusRecord) == 1:
                target, status = plusRecord[0], 1
            else:
                status = -1
        else:
            target, status = plusRecord, 1
    if target != -1:
        timer = utils.getTime() - utils.toTimeStamp(str(target.update_time))
        if timer < 1600:
            rawPP, status = eval(target.current_raw), 1
            osuid = target.osuid
            osuname = target.osuname
        else:
            status = -1
    else:
        status = -1
    return {
        'rawPP': rawPP,
        'status': status,
        'osuid': osuid,
        'osuname': osuname
    }
Пример #17
0
async def sourcecode(ctx): #sends the sourcecode
    await ctx.message.delete()
    print(getTime(), ctx.author, "used ;sourcecode")
    if ctx.author.id == shizzle.fuhrer_id:
        await ctx.send(file=discord.File(r"C:\PYTHON\Discord Makrek Bot\main.py"), delete_after=60)
    else:
        ctx.send('You dont have Authorization, pls contact Marek')
Пример #18
0
def handleUserLogin(osuid,
                    userInfo='',
                    loginInfo='',
                    status=-1,
                    loginType=0,
                    user=None):
    loginTime = utils.getTime(needFormat=1)
    database.newLoginRecord(osuid,
                            loginTime,
                            userInfo=str(userInfo),
                            loginInfo=str(loginInfo),
                            loginState=status,
                            loginType=loginType)
    if status == 1:
        otsuToken = utils.tokenGenerator(osuid, loginTime)
        database.setUserOtsuToken(osuid,
                                  otsuToken,
                                  loginTime,
                                  expiresIn,
                                  user=user)
        return {
            'token': otsuToken,
            'timestamp': utils.toTimeStamp(loginTime),
            'expires_in': expiresIn
        }
Пример #19
0
def analysis():
    with open('saleInfo.csv') as csvfile:
        reader = csv.DictReader(csvfile)
        dqu = deque(reader, 2)

        if len(dqu) == 2:
            lastRow = dqu.pop()
            secondRow = dqu.pop()

            sale1 = sumCount(secondRow) - sumCount(lastRow)
            sale2 = int(secondRow['5B']) - int(lastRow['5B'])
            left = int(lastRow['5B'])

            more_sale = int(lastRow['totalAmount']) - \
                int(secondRow['totalAmount'])

            str1 = '蓝光昨天售出:%d 5号楼售出:%d 5号楼剩余:%d' % (sale1, sale2, left)
            
            str2 = '昨天成都总出售:%s 总成交:%s 环比前天出售:%d' % (
                lastRow['totalAmount'], lastRow['totalPrice'], more_sale)

            msg = '\n'.join([utils.getTime(), getWearth(),getStock(),str1, str2])

            #utils.sendMail('我的资讯',msg )
            return msg
Пример #20
0
def trainBestModel():

    encoder = pickle.load(open('./models/encoder/encoderLicitabot','rb'))
    trainDF = dfPreprocesing()
    t0 = time()
    #encoder = preprocessing.LabelEncoder()
    #encoder.fit(trainDF['ITEM'])
    print('Categories:', encoder.classes_)

    text_clf = loadModel(model='tuning')#grid_search.best_estimator_
    # text_clf = Pipeline(steps = [('vect', CountVectorizer()),
    #('tfidf', TfidfTransformer( norm=best_parameters['tfidf'].get_params()['norm'],
    #                             )),
    # ('clf', MultinomialNB(best_parameters['clf'].get_params()['alpha']))])
    #
    # text_clf.set_params(**grid_search.best_params_)

    labels = encoder.transform(trainDF['ITEM'])
    print("Train Samples:", len(labels))
    text_clf.fit(trainDF['PARRAFO'], labels)

    outputPredictions = text_clf.predict(trainDF['PARRAFO'])

    #metrics
    cm, cm_normalized, accuracy, balancedAccuracy = modelMetrics(labels, outputPredictions, encoder)

    fileName = 'productionModelLicitaBot'
    modelName = fileName + '_' + getTime()
    modelPath = os.path.join('./models/productionModels/', modelName)

    pickle.dump(text_clf, open(modelPath, 'wb'))
    trainingTime = time() - t0
    generateLog(cm, cm_normalized, accuracy, balancedAccuracy, modelName, encoder, trainingTime)
Пример #21
0
def handleMassMessage(data, info='发送群发消息', message='', status=-1):
    queue = data.get('target')
    content = data.get('content')
    result = []
    count, failed, success = 0, 0, 0
    if type(queue) == list:
        status = 1
        for tt in queue:
            rss, rsinfo = otsocketio.apiSendRoom(tt, content.get("data"),
                                                 content.get("text"),
                                                 content.get('action'))
            if rss == 1:
                stat = '成功'
                success += 1
            else:
                stat = '失败'
                failed += 1
            count += 1
            result.append({
                'num': count,
                'staus': stat,
                'info': rsinfo,
                'time': utils.getTime(1)
            })

    return {
        'result': result,
        'count': count,
        'success': success,
        'fail': failed
    }, message, info, status
Пример #22
0
    def get_elo_data(self, osuid=None):
        if osuid == None: osuid = self.osuid
        tip = f'osuid({osuid})'
        for i in range(3):
            log(f'正在请求玩家elo数据({i}):{tip}')
            resp = requests.get(
                f'http://api.osuwiki.cn:5005/api/users/elo/{osuid}')
            if resp.status_code in range(200, 207):
                data = resp.json()
                elo_time = getTime(1)
                elo = data.get('elo')
                init_elo = data.get('init_elo')
                elo_rank = data.get('rank')
                never_match = (elo_rank == None)

                if elo or init_elo:
                    self.elo = elo
                    self.init_elo = init_elo
                    self.elo_time = elo_time
                    self.elo_rank = elo_rank
                    self.never_match = never_match
                    self.elo_level, self.elo_level_range = self.get_elo_level()
                    log(f'成功取得玩家elo数据({i}):{tip} elo({elo}) init_elo({init_elo}) elo_time({elo_time}) never_match({never_match}) {str(data)}'
                        )
                    return True

            if i < 2:
                log(f'玩家elo数据请求失败,准备进行重试({i}):{tip}')
            else:
                log(f'玩家elo数据请求失败,重试次数已达上限({i}),请重新提交初始化请求:{tip}')
Пример #23
0
    def generate_user_data(self):
        regInput = self.collect_input()
        question1 = str(self.ques1.currentText())
        question2 = str(self.ques2.currentText())
        title = str(self.titleField.text()) or "Guess"

        token = getToken()
        timelog = getTime()
        sysInfo = get_user_location()
        productID = sysInfo['Product ID']
        ip, cityIP, countryIP = get_local_pc_info()
        unix = getUnix()
        datelog = getDate()
        pcOS = sysInfo['os']
        pcUser = sysInfo['pcUser']
        pcPython = sysInfo['python']

        if not os.path.exists(self.rawAvatarPth):
            avatar = get_avatar_image('default')
        else:
            avatar = self.rawAvatarPth

        data = [
            regInput[0], regInput[1], regInput[3], regInput[4], title,
            regInput[5], regInput[6], regInput[7], regInput[8], regInput[9],
            regInput[10], regInput[11], token, timelog, productID, ip, cityIP,
            countryIP, unix, question1, regInput[12], question2, regInput[13],
            datelog, pcOS, pcUser, pcPython, avatar
        ]
        return data
    def run(self,
            bid_log_path,
            N,
            c0,
            max_bid,
            input_type="file reader",
            delimiter=" ",
            save_log=False):
        auction = 0
        imp = 0
        clk = 0
        cost = 0

        if save_log:
            log_in = open(bid_log_path, "w")
        B = int(self.cpm * c0 * N)

        episode = 1
        n = N
        b = B

        click = 0
        theta, price = self.env.reset()
        done = False

        while not done:

            action = self.bid(n, b, theta, max_bid)
            action = min(int(action), min(b, max_bid))

            done, new_theta, new_price, result_imp, result_click = self.env.step(
                action)

            log = getTime() + "\t{}\t{}_{}\t{}_{}_{}\t{}_{}\t".format(
                episode, b, n, action, price, result_click, clk, imp)
            if save_log:
                log_in.write(log + "\n")

            if result_imp == 1:
                imp += 1
                if result_click == 1:
                    clk += 1
                b -= price
                cost += price
            n -= 1
            auction += 1

            if n == 0:
                episode += 1
                n = N
                b = B

            theta = new_theta
            price = new_price

        if save_log:
            log_in.flush()
            log_in.close()

        return auction, imp, clk, cost
Пример #25
0
    def save_checkpoint(self):

        checkpoint_state = {
            'save_time': getTime(),
            'cur_epoch': self.cur_epoch,
            'cur_batch': self.cur_batch,
            'threshold': self.threshBest,
            'accuracy': self.accBest,
            'f1score': self.f1Best,
            'save_times': self.save_times,
            'loss': self.criterion.state_dict(),
            'net': self.net.state_dict(),
            'optimizer_state': self.optimizer.state_dict(),
            'lr_scheduler_state': self.lr_scheduler.state_dict(),
        }

        checkpoint_path = os.path.join(self.ckptdir, "{}_{:04d}.pkl".\
                            format(self.net._get_name(), self.save_times))
        torch.save(checkpoint_state, checkpoint_path)

        checkpoint_path = os.path.join(self.ckptdir, "{}_{:04d}.pkl".\
                            format(self.net._get_name(), self.save_times-self.num_to_keep))
        if os.path.exists(checkpoint_path): os.remove(checkpoint_path)

        self.save_times += 1
Пример #26
0
def setCostFormula(data,
                   valid,
                   nickName=None,
                   version=None,
                   remark=None,
                   public=0):
    version = data.get('version').strip()
    name = data.get('name').strip()
    fullName = name + ' ' + version
    if getFormulaByContent(data.get('content')) != None:
        return 2
    if getFormulaByFullName(fullName) != None:
        return 3
    if int(data.get('public')) in (0, 1): public = int(data.get('public'))
    db.session.add(
        CostFormulas(full_name=fullName,
                     name=name,
                     nick_name=data.get('nickName'),
                     version=version,
                     content=data.get('content'),
                     remark=data.get('remark'),
                     creator_id=data.get('Osuid'),
                     create_time=utils.getTime(1),
                     valid=valid,
                     public=public))
    db.session.commit()
    return 1
Пример #27
0
def writeDataToFile(soup, fileName, dir) :
    if os.path.exists(dir + "/" + fileName) :
        print "Skip " + dir + "/" + fileName
        return
    else :
        div = soup.findAll(attrs={"class":"history-tab"})
        if len(div) == 0 :
            print  fileName + ", no data!"
            return
        dataObject = open(dir + "/" + fileName, "w")
        for i in range(1,4) :
            column = div[0].findAll(attrs={"class":"tr-odd" + str(i)})[0].tbody.findAll("tr")
            for index in column :
                td = index.findAll("td")
                if not td[0].text == '' :
                    dataNumber = td[1].text.encode("utf8")
                    frontThree = 0
                    endThree   = 0
                    if not (dataNumber == "" or dataNumber == '- -'):
                        frontThree = checkThree(dataNumber[0:3])
                        endThree   = checkThree(dataNumber[2:])
                    else :
                        continue
                    lineNumber = " ".join([fileName+td[0].text.encode("utf8"), utils.getTime(120, td[0].text.encode("utf8"), dir),
                                           dataNumber, frontThree, endThree])
                    dataObject.write(lineNumber)
                    dataObject.write("\n")

                else :
                    break
        dataObject.close()
        print "Create File " + dir + "/" + fileName
Пример #28
0
    def accountInfo(self):
        url = "/api/v3/account"

        params = {'timestamp': utils.getTime()}

        data = self.hitBinanceWebAPI(self.GET, url, params, signed=True)

        return data
Пример #29
0
async def on_message(message): #check if message is from the bot itself
    if message.author.id == bot.user.id:
        return
#everytime someone says "tinko" the bot will say something
    elif "tinko" in message.content.lower():
        await message.channel.send(content=("Tinko is een " + random.choice(shizzle.nl_scheldwoord_list)))
        print(getTime(), "Someone said 'tinko' I responded :)")
#Overide on_message so it takes commands
    await bot.process_commands(message)
Пример #30
0
def initialUserGroupPermissions():
    if UserGroupPermissions.query.count() == 0:
        for g in userGroups:
            db.session.add(
                UserGroupPermissions(group_name=prefix + g,
                                     privilege_level=userGroups.get(g),
                                     add_time=utils.getTime(1)))
        db.session.commit()
        return True
Пример #31
0
def writeArrayToFile(array, date, dataFolder) :
    if not os.path.exists(dataFolder) :
        os.makedirs(dataFolder)

    if os.path.exists(dataFolder + "/" + date) :
        print "skip " + dataFolder + "/" + date
    else :
        outputObject = open(dataFolder + "/" + date, "w+")
        totalNumber = len(array)
        for line in array :
            info = line.split("\t")
            dateNumber = info[0].split("-")[1]
            dataNumber = info[1]
            frontThree = checkThree(dataNumber[0:3])
            endThree   = checkThree(dataNumber[2:])
            time = utils.getTime(totalNumber, dateNumber, dataFolder)
            newLine = " ".join([date + dateNumber, time,
                                dataNumber, frontThree, endThree])
            outputObject.write(newLine)
            outputObject.write("\n")
        outputObject.close()
        print "Create File " + dataFolder + "/" + date
 def checkAndUpdate(self, dType=utils.TYPE_REFERENCE_DEVICE):
     '''  This function will keep checking the device state, and if changed for it will call db thread to update
     accordingly'''
     
     #initialize state
     self.firstConnectionTime =   -1   # the time when the ID dev connected first
     self.lastSeenTime        =   -1   # the last time, dev seen without waiting for maxTimeToChangeStatus 
     
     self.lastDeviceState     =   utils.DISCONNECTED
     self.currentDeviceState  =   utils.DISCONNECTED
     
     self.timeSinceDisconnected    =   0
     
     self.lastConnectedDeviceId      =   utils.getConnectedDeviceId(dType);
     self.currentConnectedDeviceId   =   utils.getConnectedDeviceId(dType);
     
     
     #This flag is to set whe
     addedDbEntryFlag                =   False
     #always running loop after every utils.getMaxWaitBetweenDeviceConnectionCheck()
     while(True):
                     
         time.sleep(utils.getMaxWaitBetweenDeviceConnectionCheck())
         self.currentDeviceState              =   utils.getDeviceConnectioState(dType);
         
         #if no device connected since boot
         if((self.lastConnectedDeviceId    ==  None) and (currentDeviceState == utils.DISCONNECTED)):
             self.logger.debug("No Device connected since PC Boot or last device disconnected")
             continue
         
         self.currentConnectedDeviceId   =   utils.getConnectedDeviceId()
         
         if(self.currentDeviceState  ==  utils.CONNECTED ):
             #self.logger.debug("Some Device is found Connected " + str(self.currentConnectedDeviceId))
             
             if(self.lastConnectedDeviceId   ==   self.currentConnectedDeviceId):
                 self.logger.info("Same device is still connected" + str(self.currentConnectedDeviceId))
                 #do reinitialization
                 
                 self.lastConnectedDeviceId  =   self.currentConnectedDeviceId
                 self.timeSinceDisconnected  =   0
                 self.lastSeenTime           =   utils.getTime()
                 continue
             #lastdevId != currentConnectedDeviceId    
             else:
                 self.logger.debug("Last Connected Device is not the same as current one: in else" )
                 
                 self.firstConnectionTime    =   utils.getMeanTime(utils.getTime(), utils.getTime() - utils.getMaxWaitBetweenDeviceConnectionCheck())
                 self.lastSeenTime   =   self.lastSeenTime   +   self.firstConnectionTime
                 
                 self.logger.debug("Updating old device disconnection entry");
                 self.updateDeviceDisconnectedEntry()
                 self.logger.debug("Adding new connection device connection entry");
                 self.addDeviceConnectedEntry()
         #last device id is not in none
         else:
             self.logger.debug("No device connected block")
             
             if(self.timeSinceDisconnected >= utils.getMaxTimeToChangeStatus()):
                 self.logger.info("Device disconnected for long time than allowed, marking as disconnected");
                 
                 self.updateDeviceConnectedEntry();
                 
                 self.lastConnectedDeviceId      =   None
                 self.timeSinceDisconnected      =   0
                 self.currentConnectedDeviceId   =   None
                 self.lastSeenTime               =   -1
                 self.firstConnectionTime        =   -1
                 self.lastDeviceState            =   utils.DISCONNECTED
                 
             else:
                 
                 self.timeSinceDisconnected   +=  utils.getMaxWaitBetweenDeviceConnectionCheck()
                 self.logger.debug("Device disconnected since " + str(self.timeSinceDisconnected) )