示例#1
0
def save():
    '''Saves the current clipboard data to history.

    The data is retrieved using getData() and is then appended
    to the existing clipboard history.
    '''
    data = getData()
    old = getHistory()

    old = old[-1] if old else {}

    if data:
        startTime = time.time()

        # If the data that needs to be saved is exactly the same
        # as the latest data in the history, give it 1 second
        # to make sure changes have been reflected and if
        # there is still no change return

        # Otherwise carry on saving the data, as
        # it can be assumed that it is different
        # than the latest one in the history
        while data == old:
            if time.time() - startTime > 1:
                logging.error("Failed to save")
                return
            time.sleep(.01)
            data = getData()
        database.write(data)
示例#2
0
def get_data():
    feg_res = feg()
    if not feg_res["ok"]:
        return {"ok": False}

    gas_res = gas_price()
    if not gas_res["ok"]:
        return {"ok": False}

    print("get_data: feg_result:\t", feg_res)
    print("get_data: gas_result:\t", gas_res)

    locale.setlocale(locale.LC_ALL, 'de_DE')

    # data in formato UTC
    utc_data = datetime.datetime.utcnow()

    result = {
        "quantita":
        "" + locale.format_string('%.2f', feg_res["quantita"], True),
        "totale_eur": "{0:.2f}".format(usd_to_eur(feg_res["totale_usd"])),
        "totale_usd": "{0:.2f}".format(feg_res["totale_usd"]),
        "tempo": str(gas_res["time_to_complete"]),
        "gas_eur": "{0:.2f}".format(usd_to_eur(gas_res["transaction_cost"])),
        "gas_usd": "{0:.2f}".format(gas_res["transaction_cost"]),
        "data": utc_data
    }

    database.write(result)

    return {"ok": True}
示例#3
0
def create_ex(title, author, difficulty, desc, inputs, output, hidden, language, timeout, enable):
    os.mkdir(title)
    dec = database.read("exercices.json")
    data = {'difficulty': difficulty, 'date': database.get_time(), 'author': str(author), 'description': desc, 'inputs': inputs, 'output': output, 'hidden': hidden, 'language': language, 'timeout': timeout, 'enable': enable, 'test_amount': 0, 'executed_test': 0}
    dec[title] = data
    database.write("exercices.json", dec)
    return show_ex(title, data)
示例#4
0
 def add_transactions():
     while mining[0]:
         new_transactions = database.read('transaction', 'cache')
         transactions.extend(new_transactions)
         database.write([], 'transaction', 'cache')
         database.append(new_transactions, 'transaction', 'mined')
         time.sleep(1)
示例#5
0
def fetchRandom():
    #random 1 to 30 return that as json
    scrape_time = datetime.datetime.now().strftime("%Y_%m_%d_%H")
    rank = random.randint(1,30)
    if not database.tableExists(scrape_time):
        database.createTable(scrape_time)
        database.write(scrape_time,final)
    data = database.read(scrape_time,rank)
    return {"rank": data[0], "title": data[1], "time": data[2]}
示例#6
0
def test_write():
    """
    Тестирование записи в DB
    :return:null
    """

    call = CallManager(phone="89008007060", api_key="", secret_key="")

    database.write(call, call.db_host, call.db_user, call.db_pass)
示例#7
0
def undo_block(block_index):
    block, block_hash = read_block(block_index, True)
    block_size = sys.getsizeof(pickle.dumps(block, protocol=4))
    _ = add_mean_block_size(-block_size, 4, 3)
    old_mean = database.read('block_size', 'mean')
    reward = config.reward_function(block_index, block_size, old_mean)
    database.sub('wallet', block['wallet'], reward)
    database.sub('block_height', 'main', 1)
    database.write('block', block_hash, {})
示例#8
0
 def store():
     if validated[0] or (validated[0] is None and verify()):
         if cache:
             database.append(transaction_dict, 'transaction', 'cache')
         else:
             database.write(transaction_dict, 'transaction', transaction_hash[0])
             database.sub('wallet', wallet_in, amount)
             database.add('wallet', wallet_out, amount)
         return transaction_dict
示例#9
0
def button():
	# read POSTed data
	ttype = request.form.get('type')
	titem = request.form.get('item')
	print(ttype,titem)
	print ('Telemetry data recieved')
	# Send to DB
	db.write(db.connection, (ttype, titem))
	return ""
示例#10
0
def keypair():
    private = database.read('keypair', 'private')
    if private is None:
        _, _, keygen = crypto.eddsa()
        public, private = keygen()
        database.write(public, 'keypair', 'public')
        database.write(private, 'keypair', 'private')
    else:
        public = database.read('keypair', 'public')

    return public, private
示例#11
0
def main():
    search_query = local_settings.SEARCH_QUERY
    status_frame = local_settings.RESPONSE

    tweet_id, tweet_text, tweet_user, tweet_user_id = find_tweets(search_query)

    status = status_frame % (tweet_user, tweet_text)

    sent_tweet = post_tweet(status, tweet_id)

    database.write(tweet_user_id)
示例#12
0
def tell_hook(irc_con):
    try:
        host = irc_con.matches[0]
        nick = parse_nick(host)
        msgs = db['tell'][nick]
        chan = irc_con.matches[3].replace('\r', '')
        [irc_con.privmsg(nick, '%s told you: %s' % pair) for pair in msgs]

        del db['tell'][nick]
        database.write(db, db_path)
    except KeyError:
        pass
示例#13
0
def edit_ex(title, difficulty, desc, inputs, output, hidden, language, timeout, enable):
    dec = database.read("exercices.json")
    ex = dec[title]
    if difficulty != -1: ex['difficulty'] = difficulty
    if desc != "": ex['description'] = desc
    if inputs != "": ex['inputs'] = inputs
    if output != "": ex['output'] = output
    if hidden is not None: ex['hidden'] = hidden
    if language is not None: ex['language'] = language
    if timeout != -1: ex['timeout'] = timeout
    if enable is not None: ex['enable'] = enable
    database.write("exercices.json", dec)
    return show_ex(title, ex)
示例#14
0
def add_test(title, inp, out):
    dec = database.read("exercices.json")
    ex = dec[title]
    ex['test_amount'] += 1
    ind = ex['test_amount']

    with open(f"{title}/in_{ind}.txt", 'w') as mf:
        mf.write(inp)
    mf.close()
    with open(f"{title}/out_{ind}.txt", 'w') as mf:
        mf.write(out+"\n")
    mf.close()

    database.write("exercices.json", dec)
示例#15
0
def delete_ex(title):
    rmtree(title, ignore_errors=True)
    dec = database.read("exercices.json")
    del dec[title]
    database.write("exercices.json", dec)
    dec = database.read("users.json")
    for user in dec.values():
        try:
            user['score']['general'] -= user['submit'][title]['best_score']
            for sub, data in user['submit'][title].items():
                if sub not in ["best_score", "complete"]: user['score'][sub] -= data['score']
            del user['submit'][title]
        except KeyError: pass
    database.write("users.json", dec)
示例#16
0
 def store():
     if verify():
         database.write(header, 'block',
                        crypto.pickle_hash(header).decode(errors='ignore'))
         for tx in transactions:
             transaction(**tx)[2]()
         block_size = sys.getsizeof(pickle.dumps(header, protocol=4))
         old_mean = interface.add_mean_block_size(block_size)
         reward = config.reward_function(block_index, block_size, old_mean)
         database.add('wallet', wallet, reward)
         height = database.read('block_height', 'main')
         if block_index == height:  # < implies insertion | > does not exist
             database.add('block_height', 'main', 1)
         return
     return False
示例#17
0
def set_intro_hook(irc_con):
    if irc_con.msg_matches[0] == irc_con.cmd('intro'):
        target = irc_con.matches[2]
        host = irc_con.matches[0]
        nick = parse_nick(host)

        if target[0] != '#':
            target = nick

        cmd = None

        try:
            cmd = irc_con.msg_matches[1]
        except IndexError:
            try:
                irc_con.privmsg(target, db['intro'][nick])
            except KeyError:
                irc_con.privmsg(
                    target,
                    'usage: ' + irc_con.cmd('intro') + ' [add|del] [msg]')
            return

        if cmd == 'add':
            terms = irc_con.msg_matches[2:]

            if len(terms) == 0:
                irc_con.privmsg(
                    target,
                    'usage: ' + irc_con.cmd('intro') + ' [add|del] [msg]')
                return

            msg = ' '.join(terms)
            db['intro'][nick] = msg

            irc_con.privmsg(target, 'intro message has been saved')
        elif cmd == 'del':
            del db['intro'][nick]
            irc_con.privmsg(target, 'intro message has been deleted')
        else:
            irc_con.privmsg(
                target, 'usage: ' + irc_con.cmd('intro') + ' [add|del] [msg]')
            return

        database.write(db, db_path)
示例#18
0
def returnBook(bookID):
    """
    Marks a book with matching ID as available and logs the transaction

    Inputs:
        bookID (String) : Book ID number

    Returns:
        file   (String) : Formatted database to be written

    Raises:
        IndexError : "No such book with ID"
        Exception  : "Book is already available"
    """

    # Searches for a book that matches ID
    record = bs.bookID(bookID)

    # Database file to be modified, as 2D list.
    library = db.read(db.__DB__)

    # Checks if a book with given ID exists
    if record:
        # Since the 2D list only has one element,
        # the first element is extracted for ease of use
        record = record[0]

        # Checks if each book in library is borrowed
        # Available books always have memberID = "0"
        if record[4] != "0":
            for book in library:
                if book[0] == bookID:
                    book[4] = "0"

                    # Updates database and log transaction
                    file = db.formatStr(library)
                    db.write(db.__DB__, file)
                    db.log("0", bookID)

                    return file
        else:
            raise Exception("Book is already available")
    else:
        raise IndexError("No such book with ID")
示例#19
0
def checkout(memberID, bookID):
    """
    Marks a book with matching ID as borrowed by memberID

    Inputs:
        memberID (Int) : ID of a library member
        bookID   (Int) : ID of a book to borrow

    Returns:
        (String) : Database file to be written

    Raises:
        IndexError : "No such book with ID"
        Exception  : "Book is borrowed"
                     "IDs out of range"
    """

    library = db.read(db.__DB__)

    if not bs.bookID(bookID):
        raise IndexError("No such book with ID")
    else:
        # Checks if IDs are int and more than 4 digits
        if (int(memberID) < 10000 and int(bookID) < 10000 and int(memberID) > 0
                and int(bookID) > 0):
            # Searches through each record for matching bookID
            for book in library:
                if book[0] == bookID:
                    # Checks if this book is borrowed
                    if book[4] == "0":
                        book[4] = memberID

                    else:
                        raise Exception("Book is borrowed")

            msg = db.formatStr(library)
            db.write(db.__DB__, msg)
            db.log(memberID, bookID)

            return msg
        else:
            raise Exception("IDs out of range")
示例#20
0
def post(utf8_text, expiry_policy=EXPIRY_NEVER, preferred_uid=None,linked_uid_list=None):
    if not utf8_text:
        return None
    
    if expiry_policy not in expiry_policies:
        raise ValueError("Policy %s is not in policies" % expiry_policy)
    entry = {}
    entry['text'] = utf8_text
    entry['expiry_policy'] = expiry_policy
    entry['timestamp'] = str(time.time())
    entry['read_timestamp'] = None
    entry['linked'] = linked_uid_list
    uid = database.write(entry, preferred_uid)
    return uid
示例#21
0
def command_reportcsv(args):
    db.read()
    try:
        unreported = []

        with open(args.file, "r") as inFile:
            for line in inFile:
                print(">", line.strip())
                parts = map(lambda s: s.strip(), line.split())
                tag1, tag2, score = tuple(parts)
                if not report(tag1, tag2, score):
                    unreported.append(line)
                print()

        print(
            "\n>>> The following matches have not been reported (errors occured). Please report them manually."
        )
        for match in unreported:
            print(match.strip())
    except IOError as err:
        print("Error opening file!:", err)
        return
    db.write()
示例#22
0
def set_tell_hook(irc_con):
    if irc_con.msg_matches[0] == irc_con.cmd('tell'):
        target = irc_con.matches[2]
        host = irc_con.matches[0]
        nick = parse_nick(host)

        if target[0] != '#':
            target = nick

        who = None

        try:
            who = irc_con.msg_matches[1]
        except IndexError:
            irc_con.privmsg(target,
                            'usage: ' + irc_con.cmd('tell') + ' [who] [msg]')
            return

        terms = irc_con.msg_matches[2:]

        if len(terms) == 0:
            irc_con.privmsg(target,
                            'usage: ' + irc_con.cmd('tell') + ' [who] [msg]')
            return

        msg = ' '.join(terms)

        try:
            db['tell'][who].append((nick, msg))
        except KeyError:
            db['tell'][who] = [(nick, msg)]

        irc_con.privmsg(target,
                        '%s will be notified next time he/she is online' % who)

        database.write(db, db_path)
示例#23
0
    def detection(self):
        frame = np.fromstring(self.frame.getvalue(), dtype=np.uint8)
        frame = cv2.imdecode(frame, 1)
        frame_gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

        if self.status == 'detect_motion':
            if sensors.motion():
                database.write('Датчик движения')
                self.status = 'camera_scan'

            elif detect.motion(frame, frame_gray):
                database.write('Движение по камере')
                self.status = 'detect_animal'
                self.status_time = time.time()

        if self.status == 'camera_scan':
            if not motor.camera_scan():
                motor.camera_scan_stop(return_to_center=True)
                self.status = 'detect_motion'

        if self.status in ('detect_animal', 'camera_scan'):
            # Обнаружение животных
            animal, position = detect.animal(frame, frame_gray)
            if animal == 'wildcat':
                database.write('Обнаружено животное', 'лесной кот')
            elif animal == 'monkey':
                database.write('Обнаружено животное', 'обезьяна')

            # Переключение на режим обнаружения движения
            if self.status == 'detect_animal':
                if animal is not None or time.time() - self.status_time > 5:
                    self.status = 'detect_motion'
            elif self.status == 'camera_scan':
                if animal is not None:
                    motor.camera_scan_stop()
                    self.status = 'detect_motion'
示例#24
0
async def compute(pathFile,
                  filename,
                  extension,
                  exer_name,
                  msg,
                  author,
                  username,
                  isReal=True):

    exercice = database.read("exercices.json")[exer_name]

    if not bool(exercice['enable']) and isReal:
        await msg.edit(
            content=f":x: **Cet exercice n'est pas/plus disponible !**")
        return

    bashCommand = ''
    if extension == '.zip':
        rmtree(f"{pathFile}/{filename[:-4]}", ignore_errors=True)
        bashCommand = f"unzip -o {filename} -d {filename[:-4]}"  # -o Overwrite / -d Destination
        run(bashCommand, check=False, stdout=PIPE, cwd=pathFile, shell=True)
        print(f"Succesfully extracted {filename}")
        filename = filename[:-4]
        file = checkFile(f"{pathFile}/{filename}", filename)
        if file is None:
            await msg.edit(
                content=
                f"[`{filename}.zip`]\n:x: **Le fichier `{filename}` à exécuter n'a pas été trouvé !**"
            )
            print("Executing file not found")
            return
        pathFile += '/' + filename
        extension = '.' + file.split('.')[-1]
        filename += extension

    try:
        lang = language[extension]
    except KeyError:
        await msg.edit(
            content=f":x: **`{extension}` n'est pas une extension valide !**")
        return
    if exercice['language'] != "all" and lang.lower() != exercice['language']:
        await msg.edit(
            content=
            f":x: **Cet exercice est seulement disponible en `{exercice['language'].capitalize()}` !**"
        )
        return

    if extension == '.py': bashCommand = f"python3 -S {filename}"
    if extension == '.js': bashCommand = f"node {filename}"
    if extension == '.java':
        bashCommand = "javac *.java"
        p = run(bashCommand,
                stdout=PIPE,
                stderr=PIPE,
                check=False,
                encoding="utf-8",
                cwd=pathFile,
                shell=True)
        if p.stderr != "":
            await msg.edit(
                content=
                f"`{exer_name}` ({exercice['difficulty']}:star:) [{language[extension]}]\n:x: **Erreur de compilation !** ```{p.stderr}```"
            )
            print("Compilation Error")
            return
        # run(f"chmod +x {filename[:-5]}.class", check=False, cwd=pathFile, shell=True)
        bashCommand = f"java {filename[:-5]}"

    if extension == '.c':
        try:
            os.remove(f"{pathFile}/{filename[:-2]}_c")
        except FileNotFoundError:
            pass

        bashCommand = f"gcc {filename} -o {filename[:-2]}_c -I."
        p = run(bashCommand,
                stdout=PIPE,
                stderr=PIPE,
                check=False,
                encoding="utf-8",
                cwd=pathFile,
                shell=True)

        filename = filename[:-2]
        newFile = checkFile(pathFile, f"{filename}_c")
        if newFile is None:
            await msg.edit(
                content=
                f"`{exer_name}` ({exercice['difficulty']}:star:) [{language[extension]}]\n:x: **Erreur de compilation !** ```{p.stderr}```"
            )
            print("Compilation Error")
            return
        bashCommand = f"./{filename}_c"

    if extension == ".cpp":
        try:
            os.remove(f"{pathFile}/{filename[:-4]}_cpp")
        except FileNotFoundError:
            pass

        bashCommand = f"g++ {filename} -o {filename[:-4]}_cpp -std=c++17 -O2 -I."
        p = run(bashCommand,
                stdout=PIPE,
                stderr=PIPE,
                check=False,
                encoding="utf-8",
                cwd=pathFile,
                shell=True)

        filename = filename[:-4]
        newFile = checkFile(pathFile, f"{filename}_cpp")
        if newFile is None:
            await msg.edit(
                content=
                f"`{exer_name}` ({exercice['difficulty']}:star:) [{language[extension]}]\n:x: **Erreur de compilation !** ```{p.stderr}```"
            )
            print("Compilation Error")
            return
        bashCommand = f"./{filename}_cpp"

    if extension == ".cs":
        try:
            os.remove(f"{pathFile}/{filename[:-3]}.exe")
        except FileNotFoundError:
            pass

        bashCommand = f"mcs -optimize+ {filename}"
        p = run(bashCommand,
                stdout=PIPE,
                stderr=PIPE,
                check=False,
                encoding="utf-8",
                cwd=pathFile,
                shell=True)

        filename = filename[:-3]
        newFile = checkFile(pathFile, f"{filename}.exe")
        if newFile is None:
            await msg.edit(
                content=
                f"`{exer_name}` ({exercice['difficulty']}:star:) [{language[extension]}]\n:x: **Erreur de compilation !** ```{p.stderr}```"
            )
            print("Compilation Error")
            return
        bashCommand = f"mono {filename}.exe"

    if extension == ".rs":
        try:
            os.remove(f"{pathFile}/{filename[:-3]}_rs")
        except FileNotFoundError:
            pass

        bashCommand = f"rustc -o {filename[:-3]}_rs -W warnings -O {filename}"
        p = run(bashCommand,
                stdout=PIPE,
                stderr=PIPE,
                check=False,
                encoding="utf-8",
                cwd=pathFile,
                shell=True)

        filename = filename[:-3]
        newFile = checkFile(pathFile, f"{filename}_rs")
        if newFile is None:
            await msg.edit(
                content=
                f"`{exer_name}` ({exercice['difficulty']}:star:) [{language[extension]}]\n:x: **Erreur de compilation !** ```{p.stderr}```"
            )
            print("Compilation Error")
            return
        bashCommand = f"./{filename}_rs"

    if extension == ".fs":
        try:
            os.remove(f"{pathFile}/{filename[:-3]}_fs")
        except FileNotFoundError:
            pass

        bashCommand = f"fsharpc -o {filename[:-3]}_fs {filename}"
        p = run(bashCommand,
                stdout=PIPE,
                stderr=PIPE,
                check=False,
                encoding="utf-8",
                cwd=pathFile,
                shell=True)

        filename = filename[:-3]
        newFile = checkFile(pathFile, f"{filename}_fs")
        if newFile is None:
            await msg.edit(
                content=
                f"`{exer_name}` ({exercice['difficulty']}:star:) [{language[extension]}]\n:x: **Erreur de compilation !** ```{p.stderr}```"
            )
            print("Compilation Error")
            return
        bashCommand = f"./{filename}_fs"

    dec = database.read("exercices.json")
    ex_data = dec[exer_name]
    testAmount = ex_data['test_amount']
    difficulty = ex_data['difficulty']
    ishidden = bool(ex_data['hidden'])
    timeout = ex_data['timeout']
    ex_data['executed_test'] += 1
    database.write("exercices.json", dec)

    pwd = open("PWD", 'r').read()

    print(f"Running {filename}..", end='')
    await msg.edit(
        content=
        f"`{exer_name}` ({exercice['difficulty']}:star:) [{language[extension]}] {'***__UNRANKED__***' if not isReal else ''}\n:clock1: Exécution du programme en cours..."
    )
    run(f"echo {pwd} | sudo -S -u programcompiler cat empty",
        check=False,
        shell=True)  # connecting

    exercice_done = 0
    for i in range(1, testAmount + 1):

        inp = open(f"{exer_name}/in_{i}.txt", "r").read()
        try:
            process = run(
                f'echo "{inp}" | sudo -u programcompiler timeout -v {timeout} {bashCommand}',
                stdout=PIPE,
                stderr=PIPE,
                check=False,
                cwd=pathFile,
                shell=True,
                universal_newlines=True)
            output = process.stdout
            error = process.stderr
            if output == '': output = ' '
        except UnicodeDecodeError as e:
            error = str(e)
        neededOut = open(f"{exer_name}/out_{i}.txt", "r").read()

        if error != '':  # on error
            if error.startswith("timeout:"):
                await msg.edit(
                    content=
                    f"{msg.content}\n`{i}/{testAmount}` :x: **Test échoué : Votre programme a mis trop de temps à répondre !**"
                )
            else:
                if not ishidden:
                    await msg.edit(
                        content=
                        f"{msg.content}\n`{i}/{testAmount}` :x: **Test échoué : votre programme a rencontré une erreur.**\nSortie standard attendue :```{neededOut[:-1]}```\nSortie standard du programme :```{output}```\nSortie d'erreur du programme :```{error}```"
                    )
                else:
                    await msg.edit(
                        content=
                        f"{msg.content}\n`{i}/{testAmount}` :x: **Test échoué : votre programme a rencontré une erreur.**\n*Sortie attendue masquée pour ce défi*\nSortie standard du programme :```{output}```\nSortie d'erreur du programme :```{error}```"
                    )
            print('. Failed!')
            if isReal:
                await msg.edit(
                    content=
                    f"{msg.content}\n{database.add_submition(author, username, exer_name, language[extension].lower(), exercice_done, False, exercice_done*difficulty)}"
                )
            return

        if output != neededOut:  # not good output
            if not ishidden:
                await msg.edit(
                    content=
                    f"{msg.content}\n`{i}/{testAmount}` :x: **Test échoué : votre programme s'est exécuté correctement, mais :**\nSortie standard attendue :```{neededOut[:-1]}```\nSortie standard du programme :```{output}```"
                )
            else:
                await msg.edit(
                    content=
                    f"{msg.content}\n`{i}/{testAmount}` :x: **Test échoué : votre programme s'est exécuté correctement, mais :**\n*Sortie attendue masquée pour ce défi*\nSortie standard du programme :```{output}```"
                )
            print('. Failed!')
            if isReal:
                await msg.edit(
                    content=
                    f"{msg.content}\n{database.add_submition(author, username, exer_name, language[extension].lower(), exercice_done, False, exercice_done*difficulty)}"
                )
            return

        await msg.edit(
            content=
            f"{msg.content}\n`{i}/{testAmount}` :white_check_mark: **Test passé !**"
        )
        exercice_done += 1

    await msg.edit(
        content=f"{msg.content}\n\n:trophy: Bravo, tu as réussi cet exercice !"
    )
    print('. Done!')

    if isReal:
        await msg.edit(
            content=
            f"{msg.content}\n{database.add_submition(author, username, exer_name, language[extension].lower(), exercice_done, True, exercice_done*difficulty)}"
        )
示例#25
0
def lfm_np_hook(irc_con):
    target = irc_con.matches[2]

    if target[0] != '#':
        host = irc_con.matches[0]
        target = parse_nick(host)

    if irc_con.msg_matches[0] == irc_con.cmd('np'):
        host = irc_con.matches[0]
        nick = parse_nick(host)
        user = None
        save_user = True

        try:
            user = irc_con.msg_matches[1]
        except IndexError:
            try:
                host = irc_con.matches[0]
                user = db['lfm'][nick]
                save_user = False
            except KeyError:
                irc_con.privmsg(target,
                                'usage: ' + irc_con.cmd('np') + ' [lfm_user]')
                return

        rsp = None
        conn = None

        try:
            conn = httplib.HTTPConnection('ws.audioscrobbler.com')
            fmt = '/2.0/?method=user.getrecenttracks&user=%s&api_key=%s&format=json'
            req = fmt % (user, irc_con.extern['lfm_key'])
            conn.request('GET', req)
            rsp = conn.getresponse()
        except socket.gaierror:
            irc_con.privmsg(target, 'the last.fm API is down')
            return

        if rsp.status != 200:
            irc_con.privmsg(target, 'could not fetch response')
        else:
            lfm = json.loads(rsp.read())

            try:
                irc_con.privmsg(target, lfm['message'])
            except KeyError:
                if save_user:
                    usr = db['lfm'].get(nick) or None

                    if not (usr or usr == user):
                        try:
                            db['lfm'][nick] = user
                            database.write(db, db_path)
                        except IOError:
                            print 'error saving database'

                track = lfm['recenttracks']['track'][0]
                artist = track['artist']['#text']
                title = track['name']
                album = track['album']['#text']

                try:
                    date = track['date']
                    msg = rp(
                        '**%s** last played **%s - %s**, from the album **%s**, on **%s**'
                        % (user, artist, title, album, date['#text']))
                    irc_con.privmsg(target, msg)
                except KeyError:
                    msg = rp(
                        '**%s** is playing **%s - %s**, from the album **%s**'
                        % (user, artist, title, album))
                    irc_con.privmsg(target, msg)

            del lfm
示例#26
0
def main():
    parser = argparse.ArgumentParser(description='FIX Gateway')
    parser.add_argument('--debug',
                        action='store_true',
                        help='Run in debug mode')
    parser.add_argument('--config-file',
                        type=argparse.FileType('r'),
                        help='Alternate configuration file')
    parser.add_argument('--log-config',
                        type=argparse.FileType('w'),
                        help='Alternate logger configuration file')

    args, unknown_args = parser.parse_known_args()

    logging.config.fileConfig(logconfig_file)
    log = logging.getLogger()
    if args.debug:
        log.setLevel(logging.DEBUG)
    log.info("Starting FIX Gateway")

    config = configparser.RawConfigParser()
    # To kepp configparser from making everythign lowercase
    #config.optionxform = str
    config.read(config_file)
    try:
        database.init(config)
    except Exception as e:
        log.error("Database failure, Exiting")
        print(e)
        raise
        return  # we don't want to run with a screwed up database

    log.info("Setting Initial Values")
    fn = config.get("config", "ini_file")
    try:
        f = open(fn, 'r')
        for line in f.readlines():
            l = line.strip()
            if l and l[0] != '#':
                x = l.split("=")
                if len(x) >= 2:
                    database.write(x[0].strip(), x[1].strip())
    except Exception as e:
        log.error(
            "Problem setting initial values from configuration - {0}".format(
                e))
        raise

    # TODO: Add a hook here for post database creation code

    # TODO: Need to do some more thorough error checking here

    # run through the plugin_list dict and find all the plugins that are
    # configured to be loaded and load them.

    for each in config.sections():
        if each[:5] == "conn_":
            if config.getboolean(each, "load"):
                module = config.get(each, "module")
                try:
                    load_plugin(each[5:], module, config)
                except Exception as e:
                    logging.critical("Unable to load module - " + module +
                                     ": " + str(e))
                    if args.debug:
                        raise

    status.initialize(plugins)

    def sig_int_handler(signum, frame):
        plugin.jobQueue.put("QUIT")

    signal.signal(signal.SIGINT, sig_int_handler)

    # TODO add a hook here for pre module run code

    for each in plugins:
        log.debug("Attempting to start plugin {0}".format(each))
        try:
            plugins[each].start()
        except Exception as e:
            if args.debug:
                raise e  # If we have debuggin set we'll raise this exception

    iteration = 0
    while True:
        try:
            job = plugin.jobQueue.get(timeout=1.0)
            if job == "QUIT":
                break
        except KeyboardInterrupt:  # This should be broken by the signal handler
            log.info("Termination from keybaord received")
            break
        except queue.Empty:
            pass
        iteration += 1
        # Every four times through the loop we do some stuff
        if iteration % 4 == 0:
            # check how many plugins are running and exit if zero
            running_count = 0
            for each in plugins:
                if plugins[each].is_running():
                    running_count += 1
            if running_count == 0:
                log.info("No plugins running, quitting")
                break

    cleanstop = True
    for each in plugins:
        log.debug("Attempting to stop plugin {0}".format(each))
        try:
            plugins[each].shutdown()
        except plugin.PluginFail:
            log.warning("Plugin {0} did not shutdown properly".format(each))
            cleanstop = False

    if cleanstop == True:
        log.info("FIX Gateway Exiting Normally")
    else:
        log.info("FIX Gateway Exiting Forcefully")
        os._exit(-1)
示例#27
0
def main():
    parser = argparse.ArgumentParser(description='FIX Gateway')
    parser.add_argument('--debug', action='store_true',
                        help='Run in debug mode')
    parser.add_argument('--config-file', type=argparse.FileType('r'),
                        help='Alternate configuration file')
    parser.add_argument('--log-config', type=argparse.FileType('w'),
                        help='Alternate logger configuration file')

    args, unknown_args = parser.parse_known_args()

    logging.config.fileConfig(logconfig_file)
    log = logging.getLogger()
    if args.debug:
        log.setLevel(logging.DEBUG)
    log.info("Starting FIX Gateway")

    config = configparser.ConfigParser()
    # To kepp configparser from making everythign lowercase
    config.optionxform = str
    config.read(config_file)
    try:
        database.init(config)
    except Exception as e:
        log.error("Database failure, Exiting")
        print(e)
        raise
        return # we don't want to run with a screwed up database

    log.info("Setting Initial Values")
    try:
        for item in config.items("initial"):
            database.write(item[0], item[1])
    except Exception as e:
        log.error("Problem setting initial values from configuration - {0}".format(e))

    # TODO: Add a hook here for post database creation code

    # TODO: Need to do some more thorough error checking here

    # run through the plugin_list dict and find all the plugins that are
    # configured to be loaded and load them.

    for each in config:
        if each[:5] == "conn_":
            if config.getboolean(each, "load"):
                module = config.get(each, "module")
                try:
                    load_plugin(each[5:], module, config)
                except Exception as e:
                    logging.critical("Unable to load module - " + module + ": " + str(e))


    # TODO add a hook here for pre module run code

    for each in plugins:
        plugins[each].run()

    iteration = 0
    while True:
        try:
            job = plugin.jobQueue.get(timeout=1.0)
            if job == "QUIT":
                break
        except KeyboardInterrupt:
            log.info("Termination from keybaord received")
            break
        except queue.Empty:
            pass
        iteration += 1
        # Every four times through the loop we do some stuff
        if iteration % 4 == 0:
            # check how many plugins are running and exit if zero
            running_count = 0
            for each in plugins:
                if plugins[each].is_running():
                    running_count += 1
            if running_count == 0:
                log.info("No plugins running, quitting")
                break

    for each in plugins:
        plugins[each].stop()

    log.info("FIX Gateway Exiting Normally")
示例#28
0
def load_key(private):
    private = signing.SigningKey(private.encode(),
                                 encoder=encoding.URLSafeBase64Encoder)
    public = private.verify_key.encode(encoding.Base32Encoder).decode()
    database.write(public, 'keypair', 'public')
    database.write(private, 'keypair', 'private')
import database
database.write("lkaapodajgggih","a!B6")
示例#30
0
def add_mean_block_size(block_size, factor=3, divisor=4):
    old_mean = database.read('block_size', 'mean')
    new_mean = (factor * old_mean + block_size) / divisor
    database.write(new_mean, 'block_size', 'mean')
    return old_mean
示例#31
0
def main():
    parser = argparse.ArgumentParser(description='FIX Gateway')
    parser.add_argument('--debug',
                        action='store_true',
                        help='Run in debug mode')
    parser.add_argument('--config-file',
                        type=argparse.FileType('r'),
                        help='Alternate configuration file')
    parser.add_argument('--log-config',
                        type=argparse.FileType('w'),
                        help='Alternate logger configuration file')

    args, unknown_args = parser.parse_known_args()

    logging.config.fileConfig(logconfig_file)
    log = logging.getLogger()
    if args.debug:
        log.setLevel(logging.DEBUG)
    log.info("Starting FIX Gateway")

    config = configparser.ConfigParser()
    # To kepp configparser from making everythign lowercase
    config.optionxform = str
    config.read(config_file)
    try:
        database.init(config)
    except Exception as e:
        log.error("Database failure, Exiting")
        print(e)
        raise
        return  # we don't want to run with a screwed up database

    log.info("Setting Initial Values")
    try:
        for item in config.items("initial"):
            database.write(item[0], item[1])
    except Exception as e:
        log.error(
            "Problem setting initial values from configuration - {0}".format(
                e))

    # TODO: Add a hook here for post database creation code

    # TODO: Need to do some more thorough error checking here

    # run through the plugin_list dict and find all the plugins that are
    # configured to be loaded and load them.

    for each in config:
        if each[:5] == "conn_":
            if config.getboolean(each, "load"):
                module = config.get(each, "module")
                try:
                    load_plugin(each[5:], module, config)
                except Exception as e:
                    logging.critical("Unable to load module - " + module +
                                     ": " + str(e))

    # TODO add a hook here for pre module run code

    for each in plugins:
        plugins[each].run()

    iteration = 0
    while True:
        try:
            job = plugin.jobQueue.get(timeout=1.0)
            if job == "QUIT":
                break
        except KeyboardInterrupt:
            log.info("Termination from keybaord received")
            break
        except queue.Empty:
            pass
        iteration += 1
        # Every four times through the loop we do some stuff
        if iteration % 4 == 0:
            # check how many plugins are running and exit if zero
            running_count = 0
            for each in plugins:
                if plugins[each].is_running():
                    running_count += 1
            if running_count == 0:
                log.info("No plugins running, quitting")
                break

    for each in plugins:
        plugins[each].stop()

    log.info("FIX Gateway Exiting Normally")
示例#32
0
    def react(self, x, master=None):
        if x=='OK':
            if self.state == 'active': #if self.problem is None:
                self.compile = False
                self.specialform = Specialform()
                if self.winner.field.grid_info(): self.winner.field.grid_remove()
                if self.loser.field.grid_info(): self.loser.field.grid_remove()
                if self.unclear.field.grid_info(): self.unclear.field.grid_remove()
                try:
                    self.question = self.quiz.next()
                    #print(self.question.problem, self.question.answer)
                    self.problem.update(Symform(self.question.problem))
                except StopIteration:
                    if not(self.iteration_stopped):
                        write('register.txt', self.kwargs['type'],
                              tuple(datetime.now().timetuple())[1:5],
                              round(time.time() - self.inception_time), self.score)
                        self.iteration_stopped = True

                    if self.score >= 9:
                        self.finals_photo = ImageTk.PhotoImage(self.finals_image1)
                        self.level = Level(self, self.tasks)
                    elif self.score >= 7: self.finals_photo = ImageTk.PhotoImage(self.finals_image2)
                    else: self.finals_photo = ImageTk.PhotoImage(self.finals_image3)
                    self.finals_field = Label(master, image=self.finals_photo)
                    self.finals_field.grid(row=1, column=6, rowspan=2, sticky="nsew")
                    self.problem.update(Symform(''))
                    self.answer.update(Symform(''))
                else:
                    self.symform = Symform('')
                    self.state = 'not active'
                    self.timer.reset()
            else:
                if self.specialform.state == 2: #COPYPASTING
                    self.specialform.state = 0
                    self.superbutton.button.configure(bg='#007f7f', text='·/·', relief='raised')
                    with sp.evaluate(False):
                        self.compile = True
                        self.symform.add(
                            f'{self.specialform.symform1.get_plain()}/{self.specialform.symform2.get_plain()}')
                try:
                    self.symform.tosympy()
                except Exception as e:
                    print('Exception: can''t convert input form to sympy expression')
                    self.unclear.field.grid(row=1, column=6, rowspan=2, sticky="nsew")
                else:
                    print(f'input converted to: {self.symform.get_sympy()}, correct input: {self.question.answer}')
                    if self.is_equal(self.symform.get_sympy(), self.question.answer):
                        self.score += 1
                        self.answer.check(True)
                        self.winner.field.grid(row=1, column=6, rowspan=2, sticky="nsew")
                        self.starpacket.credit(True)
                    else:
                        self.answer.check(False, symform = Symform(self.question.answer))
                        self.loser.field.grid(row=1, column=6, rowspan=2, sticky="nsew")
                        self.starpacket.credit(False)
                    self.state = 'active'

        elif x=='back':
            self.symform.rewind()
        elif x=='²':
            self.symform.add('^2')
        elif x=='·/·':
            #self.symform.plain += r'\frac{\cdot}{\dots}' #???
            if self.specialform.state == 0:
                self.specialform.state = 1
                self.superbutton.button.configure(bg='orange', text='▯/·', relief='groove')
                #self.symform.add(x)
            elif self.specialform.state == 1:
                self.specialform.state = 2
                self.superbutton.button.configure(bg='green', text='·/▯', relief='groove')
            elif self.specialform.state == 2:
                self.specialform.state = 0
                self.superbutton.button.configure(bg='#007f7f', text='·/·', relief='raised')
                '''self.specialform.symform1.tosympy()
                self.specialform.symform2.tosympy()
                nom = self.specialform.symform1.get_sympy()
                denom = self.specialform.symform2.get_sympy()'''
                with sp.evaluate(False):
                    self.compile = True
                    self.symform.add(f'{self.specialform.symform1.get_plain()}/{self.specialform.symform2.get_plain()}')
        else:
            if self.specialform.state != 0:
                self.specialform.add(x)
            else:
                self.symform.add(x)
        if self.state == 'not active':
            try:
                if self.specialform.state == 0:
                    self.answer.update(self.symform, compile=self.compile)
                elif self.specialform.state == 1:
                    if self.specialform.symform1.get_plain()=='':
                        specplain = r'\frac{\ }{\ }'
                    else:
                        specplain = r'\frac{' + self.specialform.symform1.get_plain()+r'}{\ }'
                    self.answer.update(Symform(self.symform.plain + specplain), compile=False)
                elif self.specialform.state == 2:
                    if self.specialform.symform1.get_plain() == '':
                        self.specialform.state = 1
                        self.superbutton.button.configure(bg='orange', text='▯/·', relief='groove')
                        raise ValueError
                    if self.specialform.symform2.get_plain() == '':
                        specplain = r'\frac{' + self.specialform.symform1.get_plain() + r'}{\ }'
                    else:
                        specplain = r'\frac{' + self.specialform.symform1.get_plain() + r'}{'+\
                        self.specialform.symform2.get_plain()+r'}'
                    self.answer.update(Symform(self.symform.plain + specplain), compile=False)
            except ValueError:
                print('Exception: cant display your input:', self.symform.plain)
                self.unclear.field.grid(row=1, column=6, rowspan=2, sticky="nsew")
                self.symform.plain = ''
示例#33
0
def main():
    con = conn()
    while True:
        cpu = cpu_usage()
        write(con, generate("cpu", cpu, "cpu"))
        print(cpu)
示例#34
0
 def db_write(self, key, value):
     database.write(key, value)