示例#1
0
def music(path=''):

    absolute_path = u'{0}/{1}'.format(tool.music_folder, path)
    if isdir(absolute_path):

        info = {
            'folders': [],
            'files': []
        }

        for path in listdir(absolute_path):
            try:
                full_path = u'{0}/{1}'.format(absolute_path, path)
                if isdir(full_path) and not path.startswith('.'):
                    info['folders'].append(path)
                elif isfile(full_path) and full_path.lower().endswith('.mp3'):
                    info['files'].append(path)
            except Exception as e:
                pass
                tool.debug(u'Invalid folder {0}'.format(e))

        info['folders'].sort()
        info['files'].sort()

        return Tool.ok('Folder found !', data=info)

    else:
        return Tool.ko('Not a music folder')
示例#2
0
def music(path=''):

    absolute_path = u'{0}/{1}'.format(tool.music_folder, path)
    if isdir(absolute_path):

        info = {'folders': [], 'files': []}

        for path in listdir(absolute_path):
            try:
                full_path = u'{0}/{1}'.format(absolute_path, path)
                if isdir(full_path) and not path.startswith('.'):
                    info['folders'].append(path)
                elif isfile(full_path) and full_path.lower().endswith('.mp3'):
                    info['files'].append(path)
            except Exception as e:
                pass
                tool.debug(u'Invalid folder {0}'.format(e))

        info['folders'].sort()
        info['files'].sort()

        return Tool.ok('Folder found !', data=info)

    else:
        return Tool.ko('Not a music folder')
示例#3
0
async def transfer(net, request, *, source, dests, amounts, assetId, **kw):
    #params validation
    if not valid_net(net, request):
        return {'result': False, 'error': 'wrong net'}
    if not Tool.validate_address(source):
        return {'result': False, 'error': 'wrong source'}
    if assetId.startswith('0x'): assetId = assetId[2:]
    if not valid_asset(assetId):
        return {'result': False, 'error': 'wrong assetId'}
    asset = await get_an_asset(assetId, request)
    if not asset: return {'result': False, 'error': 'wrong assetId'}
    nep5_asset = global_asset = False
    if 40 == len(assetId): nep5_asset = True
    if 64 == len(assetId): global_asset = True
    ad = get_asset_decimal(asset)
    dests, amounts = dests.split(','), amounts.split(',')
    ld, la = len(dests), len(amounts)
    if ld != la:
        return {
            'result': False,
            'error': 'length of dests != length of amounts'
        }
    if nep5_asset and 1 != ld:
        return {
            'result': False,
            'error': "NEP5 token transfer only support One to One"
        }
    if False in map(Tool.validate_address, dests):
        return {'error': 'wrong dests'}
    try:
        amounts = [D(a) for a in amounts]
    except:
        return {'result': False, 'error': 'wrong amounts'}
    if [a for a in amounts if a <= D(0)]: return {'error': 'wrong amounts'}
    if False in [check_decimal(a, ad) for a in amounts]:
        return {'result': False, 'error': 'wrong amounts'}
    #check balance && transaction
    tran_num = sum(amounts)
    if nep5_asset:
        balance = D(await get_nep5_asset_balance(request, source, assetId, ad))
        if balance < tran_num:
            return {'result': False, 'error': 'insufficient balance'}
        transaction = Tool.transfer_nep5(assetId, source, dests[0], amounts[0],
                                         ad)
        result, msg = True, ''
    if global_asset:
        utxo = await get_utxo(request, source, assetId)
        balance = sum([D(i['value']) for i in utxo])
        if balance < tran_num:
            return {'result': False, 'error': 'insufficient balance'}
        items = [(dests[i], amounts[i]) for i in range(len(dests))]
        transaction, result, msg = Tool.transfer_global(
            source, utxo, items, assetId)
    if result:
        return {'result': True, 'transaction': transaction}
    return {'result': False, 'error': msg}
示例#4
0
 def __init__(self, scene, camera):
     VisBackend.__init__(self)
     #self.name_counter = 0
     #self.matrix_counter = 0
     self.names = {}
     self.clip_constants = [
         GL_CLIP_PLANE0, GL_CLIP_PLANE1, GL_CLIP_PLANE2, GL_CLIP_PLANE3,
         GL_CLIP_PLANE4, GL_CLIP_PLANE5
     ]
     self.tool = Tool()
示例#5
0
async def get_nep5_asset_balance(request, address, asset):
    result = await get_rpc(request, 'invokefunction', [
        asset, "balanceOf",
        [{
            "type": "Hash160",
            "value": big_or_little(Tool.address_to_scripthash(address))
        }]
    ])
    if result and "HALT, BREAK" == result["state"]:
        hex_str = result['stack'][0]['value']
        if hex_str: return Tool.hex_to_num_str(hex_str)
        return '0'
    return '0'
示例#6
0
async def broadcast(net, request, *, publicKey, signature, transaction):
    #params validation
    if not valid_net(net): return {'result': False, 'error': 'wrong net'}
    if not Tool.validate_cpubkey(publicKey):
        return {'result': False, 'error': 'wrong publicKey'}
    result, msg = Tool.verify(publicKey, signature, transaction)
    if not result: return {'result': False, 'error': msg}
    tx = Tool.get_transaction(publicKey, signature, transaction)
    txid = Tool.compute_txid(transaction)
    result, msg = await send_raw_transaction(tx, request)
    if result:
        return {'result': True, 'txid': txid}
    return {'result': False, 'error': msg}
示例#7
0
def file(path):

    absolute_path = u'{0}/{1}'.format(tool.music_folder, path)

    if isfile(absolute_path):
        return send_from_directory(tool.music_folder, path)
    return Tool.ko('Not a valid song path')
示例#8
0
def about():

    dir_path = os.path.dirname(os.path.realpath(__file__))
    parser = ET2.XMLParser(remove_blank_text=True)
    tree = ET2.parse(dir_path + "\\tools.xml", parser)

    name = request.form.get("title", "")

    result = tree.xpath('/tools/tool[title = "' + name + '"]')
    tool = ET2.tostring(result[0], pretty_print=True)

    root = ET.fromstring(tool)

    title = root[0].text
    position = root[1].text
    href = root[2].text
    change = root[3].text
    category = root[4].text
    datet = root[7].text
    subject = root[8].text
    if root[5].text == "True":
        learning = True
    else:
        learning = False
    if root[6].text == "True":
        teaching = True
    else:
        teaching = False

    newTool = Tool(title, position, href, change, category, learning, teaching,
                   datet, subject)

    return render_template('about.html', tool=newTool)
示例#9
0
 def parse_single_page(self, url):
     """
     解析单个文章的内容,只取文章主体部分,作为主题生成的原材料
     """
     content = self.download(url)
     if content == "": return
     pattern = re.compile('<div id="cnblogs_post_body".*?>(.*?)</div>',
                          re.S)
     match = pattern.search(content)
     if match:
         body = match.group(1)
         t = Tool()
         body = t.replace(body)
         self.dump_page_content(url, body)
     else:
         print("Parse page error")
示例#10
0
 def __init__(self, scene, camera):
     VisBackend.__init__(self)
     #self.name_counter = 0
     #self.matrix_counter = 0
     self.names = {}
     self.clip_constants = [GL_CLIP_PLANE0, GL_CLIP_PLANE1, GL_CLIP_PLANE2, GL_CLIP_PLANE3, GL_CLIP_PLANE4, GL_CLIP_PLANE5]
     self.tool = Tool()
示例#11
0
async def claim_ont(net, address, request):
    if not valid_net(net, request): return {'error': 'wrong net'}
    if not Tool.validate_address(address): return {'error': 'wrong address'}
    return {
        'available': await get_unclaim_ong(request, address),
        "unavailable": await compute_ong(request, address)
    }
示例#12
0
def engineering():
    dir_path = os.path.dirname(os.path.realpath(__file__))
    tree = ET2.parse(dir_path + "\\tools.xml")
    sub = "engineering"
    result = tree.xpath('/tools/tool[subject = "' + sub + '"]')
    tools = []
    for t in result:
        title = t[0].text
        position = t[1].text
        href = t[2].text
        change = t[3].text
        category = t[4].text
        datet = t[7].text
        subject = t[8].text
        if t[5].text == "True":
            learning = True
        else:
            learning = False
        if t[6].text == "True":
            teaching = True
        else:
            teaching = False

        newTool = Tool(title, position, href, change, category, learning,
                       teaching, datet, subject)
        tools.append(newTool)

    return render_template('listby.html', tools=tools)
示例#13
0
async def history(net, address, request, *, asset=0, index=1, length=20):
    if not valid_net(net, request): return {'error': 'wrong net'}
    if not Tool.validate_address(address): return {'error': 'wrong address'}
    result, info = valid_page_arg(index, length)
    if not result: return info
    index, length = info['index'], info['length']
    skip_num = (index - 1) * length
    raw_utxo = []
    query = {'address': address}
    if 0 != asset:
        if asset.startswith('0x'): asset = asset[2:]
        if not valid_asset(asset): return {'error': 'asset not exist'}
        if 64 == len(asset):
            query['asset'] = '0x' + asset
        else:
            query['asset'] = asset
    if 'asset' in query.keys() and 40 == len(query['asset']):
        cursor = request.app['db'].nep5history.find(query).sort(
            'time', DESCENDING)
    else:
        cursor = request.app['db'].history.find(query).sort('time', DESCENDING)
    for document in await cursor.skip(skip_num).to_list(length=length):
        del document['_id']
        del document['address']
        raw_utxo.append(document)
    return {'result': raw_utxo}
示例#14
0
def file(path):

    absolute_path = u'{0}/{1}'.format(tool.music_folder, path)

    if isfile(absolute_path):
        return send_from_directory(tool.music_folder, path)
    return Tool.ko('Not a valid song path')
示例#15
0
def engineeringrdf():
    tools = []
    url = dir_path + "/mainr.rdf"
    uri = pathlib.Path(url).as_uri()

    g = Graph()
    g.parse(url, format="xml")

    for i in range(201):
        if (i == 0):
            s = URIRef(uri + '#tools/tool/')
        if (i != 0 and i != 1):
            s = URIRef(uri + '#tools/tool_' + str(i) + '/')

        subject = findInGraph(g=g, sub=s + "subject")
        if (str(subject) == "engineering"):
            title = findInGraph(g=g, sub=s + "title")
            position = findInGraph(g=g, sub=s + "position")
            href = findInGraph(g=g, sub=s + "href")
            change = findInGraph(g=g, sub=s + "change")
            category = findInGraph(g=g, sub=s + "category")
            datet = findInGraph(g=g, sub=s + "datet")
            subject = findInGraph(g=g, sub=s + "subject")
            learning = findInGraph(g=g, sub=s + "learning")
            teaching = findInGraph(g=g, sub=s + "teaching")

            newTool = Tool(title, position, href, change, category, learning,
                           teaching, datet, subject)
            tools.append(newTool)

    return render_template('listby.html', tools=tools)
示例#16
0
async def address_ont(net, address, request):
    if not valid_net(net, request): return {'error': 'wrong net'}
    if not Tool.validate_address(address): return {'error': 'wrong address'}
    result = {
        'address': address,
        'balances': await get_ont_balance(request, address)
    }
    return result
示例#17
0
async def transfer_ont(net, request, *, source, dests, amounts, assetId, **kw):
    #params validation
    if not valid_net(net, request):
        return {'result': False, 'error': 'wrong net'}
    if not Tool.validate_address(source):
        return {'result': False, 'error': 'wrong source'}
    if assetId.startswith('0x'): assetId = assetId[2:]
    aname = get_asset_name(assetId)
    if not aname: return {'result': False, 'error': 'wrong assetId'}
    ad = get_asset_decimal(aname)
    dests, amounts = dests.split(','), amounts.split(',')
    ld, la = len(dests), len(amounts)
    if ld != la:
        return {
            'result': False,
            'error': 'length of dests != length of amounts'
        }
    if 1 != ld:
        return {
            'result': False,
            'error': "NEP5 token transfer only support One to One"
        }
    if False in map(Tool.validate_address, dests):
        return {'error': 'wrong dests'}
    try:
        amounts = [D(a) for a in amounts]
    except:
        return {'result': False, 'error': 'wrong amounts'}
    if [a for a in amounts if a <= D(0)]: return {'error': 'wrong amounts'}
    if False in [check_decimal(a, ad) for a in amounts]:
        return {'result': False, 'error': 'wrong amounts'}
    #check balance && transaction
    tran_num = sum(amounts)
    balance = D(await get_ont_balance(request, source, aname))
    if balance < tran_num:
        return {'result': False, 'error': 'insufficient balance'}
    transaction = Tool.transfer_ontology(assetId, source, dests[0], amounts[0],
                                         ad)
    result, msg = True, ''
    if result:
        return {
            'result': True,
            'sigdata': big_or_little(Tool.compute_txid(transaction)),
            'transaction': transaction
        }
    return {'result': False, 'error': msg}
示例#18
0
async def ong(net, request, *, publicKey, **kw):
    #params validation
    if not valid_net(net, request):
        return {'result': False, 'error': 'wrong net'}
    if not Tool.validate_cpubkey(publicKey):
        return {'result': False, 'error': 'wrong publicKey'}
    #get gas
    address = Tool.cpubkey_to_address(publicKey)
    amount = await get_unclaim_ong(request, address)
    tx, result, msg = Tool.ong_claim_transaction(address, amount)
    if result:
        return {
            'result': True,
            'transaction': tx,
            'sigdata': big_or_little(Tool.compute_txid(tx))
        }
    return {'result': False, 'error': msg}
示例#19
0
async def get_unbound_offset(request, address):
    #756e626f756e6454696d654f6666736574 = unboundTimeOffset
    result, err = await get_rpc_ont(request, 'getstorage', [
        '0100000000000000000000000000000000000000',
        '756e626f756e6454696d654f6666736574' +
        Tool.address_to_scripthash(address)
    ])
    if err or not result: return 0
    return int(big_or_little(result), 16)
示例#20
0
def search(token):

    if match_search:
        # Simple search
        results = []
        for x, entry in enumerate(fuzzy_choices_lower):
            tokens = token.split(' ')
            if all([field in entry for field in tokens]):
                results.append([fuzzy_choices[x], 100])
                if len(results) == search_limit:
                    break
        return Tool.ok('Simple search complete', data=results)
    else:
        # Fuzzy search
        return Tool.ok('Fuzzy search complete',
                       data=process.extract(token,
                                            fuzzy_choices,
                                            limit=search_limit))
示例#21
0
class DecisionTreeTest:
    def __init__(self):
        self.tool = Tool()
        self.id3 = Id3Util()

    def testbench(self):
        dataset = self.tool.load_dataset(train_data_file)
        dataset_tags = map(lambda vec: vec[-1] == "no-lenses", dataset)
        tree_root = self.id3.create_tree(dataset)
        self.tool.save_tree(tree_root)
        tree2_root = self.tool.load_tree()
        test_dataset = self.tool.load_dataset(test_data_file)
        sort_vec = partial(self.id3.sort_vector, dec_tree = tree2_root)
        #self.id3.show_tree("root",0,tree2_root)
        zip_set=zip(map(sort_vec, test_dataset), map(lambda x: x[-1], test_dataset))
        right=reduce(lambda x,y:x+y, map(lambda x: 1 if x[0] == x[1] else 0, zip_set))
        right_rate = float(right)/len(test_dataset)*100
        print(str(right_rate)+"%")
示例#22
0
def top10rdf():
    tools = []
    url = dir_path + "/mainr.rdf"
    uri = pathlib.Path(url).as_uri()

    g = Graph()
    g.parse(url, format="xml")
    """
    s = URIRef('file:///C://Users/Stefan/Desktop/aas.rdf#tools/tool_2/title')
    title = ""
    for person in g.objects(subject=s):
        print(person)
        print("----------------")
        title=person
    print(title)
    """
    for i in range(201):
        if (i == 0):
            s = URIRef(uri + '#tools/tool/')
        if (i != 0 and i != 1):
            s = URIRef(uri + '#tools/tool_' + str(i) + '/')

        position = findInGraph(g=g, sub=s + "position")
        if (int(position) <= 10):
            title = findInGraph(g=g, sub=s + "title")
            position = findInGraph(g=g, sub=s + "position")
            href = findInGraph(g=g, sub=s + "href")
            change = findInGraph(g=g, sub=s + "change")
            category = findInGraph(g=g, sub=s + "category")
            datet = findInGraph(g=g, sub=s + "datet")
            subject = findInGraph(g=g, sub=s + "subject")
            learning = findInGraph(g=g, sub=s + "learning")
            teaching = findInGraph(g=g, sub=s + "teaching")

            newTool = Tool(title, position, href, change, category, learning,
                           teaching, datet, subject)
            tools.append(newTool)
    """
    for i in range(2,11):
        s = URIRef('file:///C://Users/Stefan/Desktop/aas.rdf#tools/tool_'+str(i)+'/')
        title = findInGraph(g=g,sub=s + "title")
        position = findInGraph(g=g,sub=s + "position")
        href = findInGraph(g=g,sub=s + "href")
        change = findInGraph(g=g,sub=s + "change")
        category = findInGraph(g=g,sub=s + "category")
        datet = findInGraph(g=g,sub=s + "datet")
        subject = findInGraph(g=g,sub=s + "subject")
        learning = findInGraph(g=g,sub=s + "learning")
        teaching = findInGraph(g=g,sub=s + "teaching")
    
        newTool = Tool(title, position, href, change, category, learning, teaching, datet, subject)
        tools.append(newTool)
    """

    return render_template('listby.html', tools=tools)
示例#23
0
def search(token):

    if match_search:
        # Simple search
        results = []
        for x, entry in enumerate(fuzzy_choices_lower):
            tokens = token.split(' ')
            if all([field in entry for field in tokens]):
                results.append([fuzzy_choices[x], 100])
                if len(results) == search_limit:
                    break
        return Tool.ok('Simple search complete', data=results)
    else:
        # Fuzzy search
        return Tool.ok(
            'Fuzzy search complete',
            data=process.extract(
                token, fuzzy_choices, limit=search_limit
            )
        )
示例#24
0
async def broadcast_ont(net, request, *, publicKey, signature, transaction):
    #params validation
    if not valid_net(net, request):
        return {'result': False, 'error': 'wrong net'}
    if not Tool.validate_cpubkey(publicKey):
        return {'result': False, 'error': 'wrong publicKey'}
    sigdata = big_or_little(Tool.compute_txid(transaction))
    result, msg = Tool.verify(publicKey, signature, sigdata)
    if not result: return {'result': False, 'error': msg}
    tx = Tool.get_transaction_ontology(publicKey, signature, transaction)
    logging.info('tx:\n%s\n' % tx)
    txid = Tool.compute_txid(transaction)
    result, msg = await ont_send_raw_transaction(tx, request)
    if result:
        if txid != result:
            return {
                'result': True,
                'error': 'result:%s != txid:%s' % (result, txid)
            }
        return {'result': True, 'txid': result}
    return {'result': False, 'error': msg}
示例#25
0
async def gas(net, request, *, publicKey, **kw):
    #params validation
    if not valid_net(net): return {'result': False, 'error': 'wrong net'}
    if not Tool.validate_cpubkey(publicKey):
        return {'result': False, 'error': 'wrong publicKey'}
    #get gas
    address = Tool.cpubkey_to_address(publicKey)
    raw_utxo = []
    cursor = request.app['db'].utxos.find({
        'address': address,
        'asset': NEO,
        'claim_height': None
    })
    for document in await cursor.to_list(None):
        raw_utxo.append(document)
    r = await request.app['db'].state.find_one({'_id': 'height'})
    height = r['value'] + 1
    details = await Tool.compute_gas(height, raw_utxo, request.app['db'])
    tx, result, msg = Tool.claim_transaction(address, details)
    if result:
        return {'result': True, 'transaction': tx}
    return {'result': False, 'error': msg}
示例#26
0
async def address(net, address, request):
    if not valid_net(net): return {'error': 'wrong net'}
    if not Tool.validate_address(address): return {'error': 'wrong address'}
    result = {'_id': address, 'balances': {}}
    nep5_keys = list(NEP5.keys())
    aresult = await asyncio.gather(
        get_all_utxo(request, address),
        get_multi_nep5_balance(request, address, nep5_keys))
    result['utxo'], result['balances'] = aresult[0], aresult[1]
    for k, v in result['utxo'].items():
        result['balances'][k] = sci_to_str(str(sum([D(i['value'])
                                                    for i in v])))
    return result
示例#27
0
async def claim(net, address, request):
    if not valid_net(net): return {'error': 'wrong net'}
    if not Tool.validate_address(address): return {'error': 'wrong address'}
    raw_utxo = []
    cursor = request.app['db'].utxos.find({
        'address': address,
        'asset': NEO,
        'claim_height': None
    })
    for document in await cursor.to_list(None):
        raw_utxo.append(document)
    r = await request.app['db'].state.find_one({'_id': 'height'})
    height = r['value'] + 1
    return await Tool.compute_gas(height, raw_utxo, request.app['db'])
示例#28
0
async def history(net, address, request, *, asset=0):
    if not valid_net(net): return {'error': 'wrong net'}
    if not Tool.validate_address(address): return {'error': 'wrong address'}
    raw_utxo = []
    query = {'address': address}
    if 0 != asset:
        if asset.startswith('0x'): asset = asset[2:]
        if not valid_asset(asset): return {'error': 'asset not exist'}
        query['asset'] = '0x' + asset
    cursor = request.app['db'].history.find(query).sort('time', DESCENDING)
    for document in await cursor.to_list(length=100):
        del document['_id']
        del document['address']
        raw_utxo.append(document)
    return {'result': raw_utxo}
示例#29
0
def getcategory():
    if request.method == 'POST':
        categ = request.form.get("category", "")
        print(categ)

        dir_path = os.path.dirname(os.path.realpath(__file__))
        tree = ET2.parse(dir_path + "\\tools.xml")
        result = tree.xpath('/tools/tool[category = "' + categ + '"]')
        tools = []
        for t in result:
            title = t[0].text
            position = t[1].text
            href = t[2].text
            change = t[3].text
            category = t[4].text
            datet = t[7].text
            subject = t[8].text
            if t[5].text == "True":
                learning = True
            else:
                learning = False
            if t[6].text == "True":
                teaching = True
            else:
                teaching = False

            newTool = Tool(title, position, href, change, category, learning,
                           teaching, datet, subject)
            tools.append(newTool)

        return render_template('listby.html', tools=tools)

    dir_path = os.path.dirname(os.path.realpath(__file__))
    tree = ET.parse(dir_path + "\\tools.xml")
    root = tree.getroot()

    categories = []
    for tool in root.findall('./tool'):
        category = tool[4].text
        if category not in categories:
            categories.append(category)
    sorted_categories = sorted(categories, key=str.casefold)

    return render_template("catform.html", categories=sorted_categories)
示例#30
0
def days():
    if request.method == 'POST':
        days = request.form.get("days", "")
        todays = date.today().strftime("%d/%m/%Y")
        todaysdate = datetime.datetime.strptime(todays, "%d/%m/%Y")
        daysformated = datetime.timedelta(int(days))
        difference = todaysdate - daysformated

        differencestr = difference.strftime("%Y/%m/%d")
        differencestr = differencestr.replace("/", "")
        print(differencestr)
        #/tools/tool[number(translate(date,'/','')) > 03122020]

        dir_path = os.path.dirname(os.path.realpath(__file__))
        tree = ET2.parse(dir_path + "\\tools.xml")
        result = tree.xpath("/tools/tool[number(translate(date,'/','')) >= " +
                            differencestr + "]")
        tools = []
        for t in result:
            title = t[0].text
            position = t[1].text
            href = t[2].text
            change = t[3].text
            category = t[4].text
            datet = t[7].text
            subject = t[8].text
            if t[5].text == "True":
                learning = True
            else:
                learning = False
            if t[6].text == "True":
                teaching = True
            else:
                teaching = False

            newTool = Tool(title, position, href, change, category, learning,
                           teaching, datet, subject)
            tools.append(newTool)

        return render_template('listby.html', tools=tools)

    return render_template('days.html')
示例#31
0
def index():
    dir_path = os.path.dirname(os.path.realpath(__file__))
    #dom = ET2.parse(dir_path + "\\tools.xml")
    #xslt = ET2.parse(dir_path + "\\template.xsl")
    #transform = ET2.XSLT(xslt)
    #newdom = transform(dom)
    #xml_file = open(dir_path + "\\templates\\file.html", "w")
    #xml_file.write(str(ET2.tostring(newdom)))
    #xml_file.close()
    #return render_template('file.html')

    tree = ET.parse(dir_path + "\\tools.xml")
    root = tree.getroot()
    tools = []
    categories = []
    for tool in root.findall('./tool'):
        title = tool[0].text
        position = tool[1].text
        href = tool[2].text
        change = tool[3].text
        category = tool[4].text
        datet = tool[7].text
        subject = tool[8].text
        if tool[5].text == "True":
            learning = True
        else:
            learning = False
        if tool[6].text == "True":
            teaching = True
        else:
            teaching = False
        newTool = Tool(title, position, href, change, category, learning,
                       teaching, datet, subject)
        tools.append(newTool)
        if category not in categories:
            categories.append(category)
    sorted_categories = sorted(categories, key=str.casefold)
    return render_template('index.html',
                           tools=tools,
                           categories=sorted_categories)
示例#32
0
async def address(net, address, request):
    if not valid_net(net, request): return {'error': 'wrong net'}
    if not Tool.validate_address(address): return {'error': 'wrong address'}
    result = {'_id': address, 'balances': {}}
    nep5 = await get_all_nep5(request)
    aresult = await asyncio.gather(
        get_all_utxo(request, address),
        get_multi_nep5_balance(request, address, nep5),
        get_ont_balance(request, address))
    result['utxo'] = aresult[0]
    for k, v in result['utxo'].items():
        result['balances'][k] = sci_to_str(str(sum([D(i['value'])
                                                    for i in v])))
    else:
        if NEO[2:] not in result['balances'].keys():
            result['balances'][NEO[2:]] = "0"
        if GAS[2:] not in result['balances'].keys():
            result['balances'][GAS[2:]] = "0"
    result['balances'].update(aresult[1])
    result['balances'][ONT_ASSETS['ont']['scripthash']] = aresult[2]['ont']
    result['balances'][ONT_ASSETS['ong']['scripthash']] = aresult[2]['ong']
    return result
示例#33
0
class VisBackendOpenGL(VisBackend):
    select_buffer_size = 1024*64

    def __init__(self, scene, camera):
        VisBackend.__init__(self)
        #self.name_counter = 0
        #self.matrix_counter = 0
        self.names = {}
        self.clip_constants = [GL_CLIP_PLANE0, GL_CLIP_PLANE1, GL_CLIP_PLANE2, GL_CLIP_PLANE3, GL_CLIP_PLANE4, GL_CLIP_PLANE5]
        self.tool = Tool()

    #
    # Generic stuff
    #

    def initialize_draw(self):
        self.quadric = gluNewQuadric()
        gluQuadricNormals(self.quadric, GLU_SMOOTH)
        self.set_specular(True)
        self.set_bright(False)
        glLight(GL_LIGHT0, GL_SPECULAR, [0.7, 0.7, 0.7, 1.0])
        glLight(GL_LIGHT0, GL_AMBIENT, [0.1, 0.1, 0.1, 1.0])
        glLight(GL_LIGHT0, GL_POSITION, [1.0, 1.0, 3.0, 0.0])
        glEnable(GL_LIGHT0)
        glEnable(GL_LIGHTING)
        glDepthFunc(GL_LESS)
        glEnable(GL_DEPTH_TEST)
        glCullFace(GL_BACK)
        VisBackend.initialize_draw(self)
        self.tool.initialize_gl()

    def draw(self, width, height, selection_box=None):
        scene = context.application.scene
        camera = context.application.camera

        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
        if selection_box is not None:
            # set up a select buffer
            glSelectBuffer(self.select_buffer_size)
            glRenderMode(GL_SELECT)
            glInitNames()

        glMatrixMode(GL_PROJECTION)
        glLoadIdentity()
        # Apply the pick matrix if selecting
        if selection_box is not None:
            gluPickMatrix(0.5 * (selection_box[0] + selection_box[2]),
                          height - 0.5 * (selection_box[1] + selection_box[3]),
                          selection_box[2] - selection_box[0] + 1,
                          selection_box[3] - selection_box[1] + 1,
                          (0, 0, width, height))

        # Apply the frustum matrix
        znear = camera.znear
        zfar = camera.znear + camera.window_depth
        if width > height:
            w = 0.5*float(width) / float(height)
            h = 0.5
        else:
            w = 0.5
            h = 0.5*float(height) / float(width)
        if znear > 0.0:
            glFrustum(-w*camera.window_size, w*camera.window_size, -h*camera.window_size, h*camera.window_size, znear, zfar)
        else:
            glOrtho(-w*camera.window_size, w*camera.window_size, -h*camera.window_size, h*camera.window_size, znear, zfar)

        glMatrixMode(GL_MODELVIEW)
        glLoadIdentity()
        # Move to eye position (reverse)
        gl_apply_inverse(camera.eye)
        glTranslatef(0.0, 0.0, -znear)
        # Draw the rotation center, only when realy drawing objects:
        if selection_box is None:
            glMaterial(GL_FRONT, GL_AMBIENT_AND_DIFFUSE, [1.0, 1.0, 1.0, 1.0])
            glShadeModel(GL_SMOOTH)
            self.call_list(scene.rotation_center_list)
        # Now rotate to the model frame and move back to the model center (reverse)
        gl_apply_inverse(camera.rotation)
        # Then bring the rotation center at the right place (reverse)
        gl_apply_inverse(camera.rotation_center)
        gl_apply_inverse(scene.model_center)

        scene.draw()

        if selection_box is not None:
            # now let the caller analyze the hits by returning the selection
            # buffer. Note: The selection buffer can be used as an iterator
            # over 3-tupples (near, far, names) where names is tuple that
            # contains the gl_names associated with the encountered vertices.
            return glRenderMode(GL_RENDER)
        else:
            # draw the interactive tool (e.g. selection rectangle):
            glCallList(self.tool.total_list)

    #
    # List related functuions
    #

    def create_list(self, owner=None):
        l = glGenLists(1)
        if owner is not None:
            self.names[l] = owner
        return l

    def delete_list(self, l):
        glDeleteLists(l, 1)
        if l in self.names:
            del self.names[l]

    def begin_list(self, l):
        glNewList(l, GL_COMPILE)

    def end_list(self):
        glEndList()

    def call_list(self, l):
        glCallList(l)

    #
    # Names
    #

    def push_name(self, name):
        glPushName(name)
        #self.name_counter += 1
        #print "NAME UP  ", self.name_counter

    def pop_name(self):
        glPopName()
        #self.name_counter -= 1
        #print "NAME DOWN", self.name_counter
        #assert self.name_counter >= 0

    #
    # Transform functions
    #

    def push_matrix(self):
        glPushMatrix()
        #self.matrix_counter += 1
        #print "MATRIX UP  ", self.matrix_counter

    def translate(self, x, y, z):
        glTranslate(x, y, z)

    def rotate(self, angle, x, y, z):
        glRotate(angle, x, y, z)

    def transform(self, transformation):
        gl_apply(transformation)

    def pop_matrix(self):
        glPopMatrix()
        #self.matrix_counter -= 1
        #print "MATRIX DOWN", self.matrix_counter
        #assert self.matrix_counter >= 0


    #
    # Layout related functions
    #

    def set_color(self, r, g, b, a=1.0):
        glMaterial(GL_FRONT, GL_AMBIENT_AND_DIFFUSE, [r, g, b, a])

    def set_bright(self, bright):
        if bright:
            glMaterial(GL_FRONT, GL_SHININESS, 0.0)
        else:
            glMaterial(GL_FRONT, GL_SHININESS, 70.0)

    def set_specular(self, specular):
        if specular:
            glMaterial(GL_FRONT, GL_SPECULAR, [0.7, 0.7, 0.7, 1.0])
        else:
            glMaterial(GL_FRONT, GL_SPECULAR, [0.0, 0.0, 0.0, 0.0])

    def set_line_width(self, width):
        glLineWidth(width)

    #
    # Draw functions
    #

    def draw_line(self, *points):
        glBegin(GL_LINES)
        for point in points:
            glVertex(point)
        glEnd()

    def draw_polygon(self, *data):
        glBegin(GL_POLYGON)
        for normal, vectors in data:
            glNormal3fv(normal)
            for vector in vectors:
                glVertex(vector)
        glEnd()

    def draw_triangles(self, *data):
        glBegin(GL_TRIANGLES)
        for normal, vectors in data:
            glNormal3fv(normal)
            for vector in vectors:
                glVertex(vector)
        glEnd()

    def draw_triangle_strip(self, *data):
        glBegin(GL_TRIANGLE_STRIP)
        for normal, vectors in data:
            glNormal3fv(normal)
            for vector in vectors:
                glVertex(vector)
        glEnd()

    def draw_quads(self, *data):
        glBegin(GL_QUADS)
        for normal, vectors in data:
            glNormal3fv(normal)
            for vector in vectors:
                glVertex(vector)
        glEnd()

    def draw_quad_strip(self, *data):
        glBegin(GL_QUAD_STRIP)
        for normal, vectors in data:
            glNormal3fv(normal)
            for vector in vectors:
                glVertex(vector)
        glEnd()

    def draw_sphere(self, radius, quality):
        gluSphere(self.quadric, radius, quality, quality/2)

    def draw_cylinder(self, radius, length, quality):
        gluCylinder(self.quadric, radius, radius, length, quality, 1)

    def draw_cone(self, radius1, radius2, length, quality):
        gluCylinder(self.quadric, radius1, radius2, length, quality, 1)

    def draw_disk(self, radius, quality):
        gluDisk(self.quadric, 0, radius, quality, 1)

    def set_quadric_outside(self):
        gluQuadricOrientation(self.quadric, GLU_OUTSIDE)

    def set_quadric_inside(self):
        gluQuadricOrientation(self.quadric, GLU_INSIDE)

    #
    # Clip functions
    #

    def set_clip_plane(self, index, coefficients):
        glEnable(self.clip_constants[index])
        glClipPlane(self.clip_constants[index], coefficients)

    def unset_clip_plane(self, index):
        glDisable(self.clip_constants[index])

    #
    # Fog and background functions
    #

    def unset_fog(self):
        glDisable(GL_FOG)

    def set_fog(self, color, start, end):
        glFogfv(GL_FOG_COLOR, color)
        glEnable(GL_FOG)
        glFogfv(GL_FOG_MODE, GL_LINEAR)
        glFogfv(GL_FOG_START, start)
        glFogfv(GL_FOG_END, end)

    def set_background_color(self, color):
        glClearColor(*color)
示例#34
0
import time
import serial
from tools import Tool

TEMPERATURE_THRESHOLD = 28.0

t = Tool('feverfinder','Shivaal')
ser = serial.Serial('/dev/cu.usbmodem1421', 9600)

alarm_sent = False
count = 0
while True:
	line = ser.readline().strip()
	count += 1
	print line
	if count > 5:
		t.addTemperature(float(line),int(time.time() * 1000))
		if not alarm_sent and float(line) > TEMPERATURE_THRESHOLD:
			print "ALERT! High temperature in bed 14."
			t.send_sms()
			alarm_sent = True
示例#35
0
def getData():
  t = Tool("feverfinder","Shivaal")
  return t.getTemperature()
示例#36
0
def fuzzygen():

    popen('cd "{0}";find . -name "*.mp3" > {1}'.format(
        Tool.get('music_folder'),
        Tool.get('music_database'),
    ))
示例#37
0
def fuzzygen():

	popen('cd "{0}";find . -name "*.mp3" > {1}'.format(
		Tool.get('music_folder'),
		Tool.get('music_database'),
	))
示例#38
0
文件: rshack.py 项目: ydgaygui/RSHack
def choose(arg):

    attack = str(accueil(arg))

    if attack == "1":

        print("\n\t\t\t ***** Wiener Attack *****")

        args = input(
            "\n\t\t[*] Arguments ([-h] -n modulus -e exponent):\n\n\t\t\t"
        ).split()

        parser = argparse.ArgumentParser(
            description='This program allows to carry out a Wiener Attack')
        parser.add_argument('-n',
                            dest='n',
                            type=int,
                            help='RSA public key modulus',
                            required=True)
        parser.add_argument('-e',
                            dest='e',
                            type=int,
                            help='RSA public key exponent',
                            required=True)

        params = parser.parse_args(args)

        attack_object = Attack(params)
        attack_object.wiener()

    elif attack == "2":

        print("\n\t\t\t ***** Hastad Attack *****")

        try:

            args = input(
                "\n\t\t[*] Arguments ([-h] -n0 modulus_key0 -n1 modulus_key1 -n2 modulus_key2 -e public_exponent -c0 cipher1 -c1 cipher2 -c2 cipher3):\n\n\t\t\t"
            ).split()

        except:

            print("\n\t\t\t[-] Argument Error: Please verify your inputs\n")
            exit()

        parser = argparse.ArgumentParser(
            description='This program allows to carry out an Hastad Attack')
        parser.add_argument(
            '-n0',
            dest='n0',
            type=int,
            help='Modulus of the first RSA pulic key (decimal)',
            required=True)
        parser.add_argument(
            '-n1',
            dest='n1',
            type=int,
            help='Modulus of the second RSA pulic key (decimal)',
            required=True)
        parser.add_argument(
            '-n2',
            dest='n2',
            type=int,
            help='Modulus of the third RSA pulic key (decimal)',
            required=True)
        parser.add_argument('-e',
                            dest='e',
                            type=int,
                            help='Common public exponent (decimal)',
                            required=True)
        parser.add_argument('-c0',
                            dest='c0',
                            type=int,
                            help='first ciphertext (decimal)',
                            required=True)
        parser.add_argument('-c1',
                            dest='c1',
                            type=int,
                            help='second ciphertext (decimal)',
                            required=True)
        parser.add_argument('-c2',
                            dest='c2',
                            type=int,
                            help='third ciphertext (decimal)',
                            required=True)
        params = parser.parse_args(args)

        attack_object = Attack(params)
        attack_object.hastad()

    elif attack == "3":

        print("\n\t\t\t ***** Fermat Attack *****")

        try:

            args = input(
                "\n\t\t[*] Arguments ([-h] -n modulus -e exponent):\n\n\t\t\t"
            ).split()

        except:

            print("\n\t\t\t[-] Argument Error: Please verify your inputs\n")
            exit()

        parser = argparse.ArgumentParser(
            description=
            'This program allows to carry out a Fermat Factorization')
        parser.add_argument('-n',
                            dest='n',
                            type=int,
                            help='RSA public key modulus',
                            required=True)
        parser.add_argument('-e',
                            dest='e',
                            type=int,
                            help='RSA public key exponent',
                            required=True)

        params = parser.parse_args(args)

        attack_object = Attack(params)
        attack_object.fermat()

    elif attack == "4":

        print("\n\t\t\t ***** Bleichenbacher Attack *****")

        try:

            args = input(
                "\n\t\t[*] Arguments ([-h] -n modulus -e exponent -c ciphertext --host hostname -p port --error error padding message):\n\n\t\t\t"
            ).split()

        except:

            print("\n\t\t\t[-] Argument Error: Please verify your inputs\n")
            exit()

        parser = argparse.ArgumentParser(
            description=
            'This program allows to carry out a Bleichenbacher Attack')
        parser.add_argument('-n',
                            dest='n',
                            type=int,
                            help='RSA public key modulus (int)',
                            required=True)
        parser.add_argument('-e',
                            dest='e',
                            type=int,
                            help='RSA public key exponent (int)',
                            required=True)
        parser.add_argument('-c',
                            dest='c',
                            type=int,
                            help='ciphertext (int)',
                            required=True)
        parser.add_argument('--host',
                            dest='host',
                            type=str,
                            help='hostname',
                            required=True)
        parser.add_argument('-p',
                            dest='port',
                            type=int,
                            help='port',
                            required=True)
        parser.add_argument('--error',
                            dest='error',
                            type=str,
                            help='Oracle Padding Error',
                            required=True)
        params = parser.parse_args(args)

        attack_object = Attack(params)
        attack_object.bleichenbacher()

    elif attack == "5":

        print("\n\t\t\t ***** Common Modulus Attack *****")

        try:

            args = input(
                "\n\t\t[*] Arguments [-h] -n common modulus -e1 first exponent -e2 second exponent -c1 first cipher -c2 second cipher:\n\n\t\t\t"
            ).split()

        except:

            print("\n\t\t\t[-] Argument Error: Please verify your inputs\n")
            exit()

        parser = argparse.ArgumentParser(
            description=
            'This program allows to carry out a Common Modulus Attack')
        parser.add_argument('-n',
                            dest='n',
                            type=int,
                            help='RSA public key modulus',
                            required=True)
        parser.add_argument('-e1',
                            dest='e1',
                            type=int,
                            help='First RSA public key exponent',
                            required=True)
        parser.add_argument('-e2',
                            dest='e2',
                            type=int,
                            help='Second RSA public key exponent',
                            required=True)
        parser.add_argument('-c1',
                            dest='c1',
                            type=int,
                            help='First ciphered text',
                            required=True)
        parser.add_argument('-c2',
                            dest='c2',
                            type=int,
                            help='Second ciphered text',
                            required=True)

        params = parser.parse_args(args)

        attack_object = Attack(params)
        attack_object.comod()

    elif attack == "6":

        print("\n\t\t\t ***** Chosen Plaintext Attack *****")

        try:

            args = input(
                "\n\t\t[*] Arguments ([-h] -n modulus -e public_exponent -c ciphertext):\n\n\t\t\t"
            ).split()

        except:

            print("\n\t\t\t[-] Argument Error: Please verify your inputs\n")
            exit()

        parser = argparse.ArgumentParser(
            description=
            'This program allows to carry out a Chosen Plaintext Attack')
        parser.add_argument('-n',
                            dest='n',
                            type=int,
                            help='RSA public key modulus',
                            required=True)
        parser.add_argument('-e',
                            dest='e',
                            type=int,
                            help='first RSA public key exponent',
                            required=True)
        parser.add_argument('-c',
                            dest='c',
                            type=int,
                            help='ciphertext',
                            required=True)
        params = parser.parse_args(args)
        params = parser.parse_args(args)

        attack_object = Attack(params)
        attack_object.chopla()

    elif attack == "a":

        print("\n\t\t\t ***** RSA Public Key parameters extraction *****")

        try:

            args = input("\n\t\t[*] Argument ([-h] -k K):\n\n\t\t\t").split()

        except:

            print("\n\t\t\t[-] Argument Error: Please verify your inputs\n")
            exit()

        if args[0] == '-k' and args[1] != '/':

            args[1] = getcwd() + "/" + args[1]

        parser = argparse.ArgumentParser(
            description=
            'This program allows to extract the modulus and the exponent of an RSA public key (PEM)'
        )

        parser.add_argument('-k',
                            dest='k',
                            type=str,
                            help='path of the RSA public key',
                            required=True)
        params = parser.parse_args(args)

        tool_object = Tool(params)
        tool_object.pubex()

    elif attack == "b":

        print("\n\t\t\t ***** RSA Private Key paramters extraction *****")

        try:

            args = input("\n\t\t[*] Argument ([-h] -k K):\n\n\t\t\t").split()

        except:

            print("\n\t\t\t[-] Argument Error: Please verify your inputs\n")
            exit()

        if args[0] == '-k' and args[1] != '/':

            args[1] = getcwd() + "/" + args[1]

        parser = argparse.ArgumentParser(
            description=
            'This program allows to extract the parameters of an RSA private key (PEM)'
        )

        parser.add_argument('-k',
                            dest='k',
                            type=str,
                            help='path of the RSA private key',
                            required=True)
        params = parser.parse_args(args)

        tool_object = Tool(params)
        tool_object.privex()

    elif attack == "c":

        print("\n\t\t\t ***** RSA Private Key constructor *****")

        try:

            args = input(
                "\n\t\t[*] Argument ([-h] -p first_factorization_element -q second_factorization_element -e public_exponent [-o output_file]):\n\n\t\t\t"
            ).split()

        except:

            print("\n\t\t\t[-] Argument Error: Please verify your inputs\n")
            exit()

        parser = argparse.ArgumentParser(
            description=
            'This program allows to construct an RSA Private Key with its parameters'
        )

        parser.add_argument('-p',
                            dest='p',
                            type=int,
                            help='first element of the modulus factorization',
                            required=True)
        parser.add_argument('-q',
                            dest='q',
                            type=int,
                            help='second element of the modulus factorization',
                            required=True)
        parser.add_argument('-e',
                            dest='e',
                            type=int,
                            help='public exponent',
                            required=True)
        parser.add_argument('-o', dest='o', type=str, help='output file')
        params = parser.parse_args(args)

        tool_object = Tool(params)
        tool_object.privkeyconstruct()

    elif attack == "d":

        print("\n\t\t\t ***** RSA Public Key constructor *****")

        try:

            args = input(
                "\n\t\t[*] Argument ([-h] -n modulus -e public_exponent [-o output_file]):\n\n\t\t\t"
            ).split()

        except:

            print("\n\t\t\t[-] Argument Error: Please verify your inputs\n")
            exit()

        parser = argparse.ArgumentParser(
            description=
            'This program allows to construct an RSA Public Key with its parameters'
        )

        parser.add_argument('-n',
                            dest='n',
                            type=int,
                            help='modulus',
                            required=True)
        parser.add_argument('-e',
                            dest='e',
                            type=int,
                            help='public exponent',
                            required=True)
        parser.add_argument('-o', dest='o', type=str, help='output file')
        params = parser.parse_args(args)

        tool_object = Tool(params)
        tool_object.pubkeyconstruct()

    elif attack == "e":

        print("\n\t\t\t ***** RSA Decipher *****")

        try:

            args = input(
                "\n\t\t[*] Argument ([-h] -n modulus -d private_exponent -c ciphertext):\n\n\t\t\t"
            ).split()

        except:

            print("\n\t\t\t[-] Argument Error: Please verify your inputs\n")
            exit()

        parser = argparse.ArgumentParser(
            description=
            'This simple program allows to decipher a message using RSA')
        parser.add_argument('-n',
                            dest='n',
                            type=int,
                            help='RSA public key modulus',
                            required=True)
        parser.add_argument('-d',
                            dest='d',
                            type=int,
                            help='RSA private key exponent',
                            required=True)
        parser.add_argument('-c',
                            dest='c',
                            type=int,
                            help='ciphertext',
                            required=True)
        params = parser.parse_args(args)

        tool_object = Tool(params)
        tool_object.decipher()

    elif attack == "f":

        print("\n\t\t\t ***** RSA Encipher *****")

        try:

            args = input(
                "\n\t\t[*] Argument ([-h] -n modulus -e public_exponent -p plaintext):\n\n\t\t\t"
            ).split()

        except:

            print("\n\t\t\t[-] Argument Error: Please verify your inputs\n")
            exit()

        parser = argparse.ArgumentParser(
            description=
            'This simple program allows to encipher a message using RSA')
        parser.add_argument('-n',
                            dest='n',
                            type=int,
                            help='RSA public key modulus',
                            required=True)
        parser.add_argument('-e',
                            dest='e',
                            type=int,
                            help='RSA public key exponent',
                            required=True)
        parser.add_argument('-p',
                            dest='p',
                            type=int,
                            help='plaintext',
                            required=True)
        params = parser.parse_args(args)

        tool_object = Tool(params)
        tool_object.encipher()

    else:

        choose("again")
示例#39
0
# coding: utf-8
from flask import Flask, render_template, send_from_directory
from os.path import isdir, isfile
from os import listdir
from tools import Tool
from fuzzywuzzy import process

app = Flask(__name__)
tool = Tool()

# Initilize search engine
fuzzy_choices = []
fuzzy_choices_lower = []
ko = 0
match_search = tool.get('use_match')
music_db = tool.get('music_database')
if isfile(music_db):
    with open(tool.get('music_database')) as f:
        for line in f:
            try:
                entry = line.strip().decode('utf-8')
                fuzzy_choices.append(entry)
                #  put computed lower string in cache
                if match_search:
                    fuzzy_choices_lower.append(entry.lower())
            except Exception as decodeError:
                ko += 0
if ko:
    tool.debug(ko, 'files could not be add to the seach engine')

search_limit = tool.get('search_limit')