Ejemplo n.º 1
0
 def cat_name_cb(m, user_choice):
     if user_choice == texts['back']:
         add_category(m)
     else:
         api.Api(m.chat.id).add_category(chosen_type[0], user_choice)
         bot.send_message(m.chat.id, texts['success'])
         menu(m)
Ejemplo n.º 2
0
    def transact(self, to, from_, fun_name, sig, data, gas, gas_price, value,
                 wait):
        instance = api.Api(self.config)
        from_count = instance.transaction_count(defaultBlock='pending')
        if wait:
            from_block = instance.last_block()

        result = instance.transact(to,
                                   fun_name=fun_name,
                                   sig=sig,
                                   data=data,
                                   gas=gas,
                                   gas_price=gas_price,
                                   value=value)
        logger.info("      Result: %s" % (result if result else "OK"))

        instance.wait_for_transaction(
            from_count=from_count,
            verbose=(True
                     if self.config.get('misc', 'verbosity') > 1 else False))

        if wait:
            instance.wait_for_next_block(
                from_block=from_block,
                verbose=(True if self.config.get('misc', 'verbosity') > 1 else
                         False))
    def search(self):

        if (self.searchPhraseIn.text != ""):
            self.searchPhrase = self.searchPhraseIn.text
            #print(self.searchPhrase)
            self.searchPhraseIn.text = ""

            # Get an instance of the api
            apiSearch = api.Api()
            query = apiSearch.search({'item': self.searchPhrase})
            #apiSearch.display_results(query)

            #print("Parsed results")
            parsed_results = apiSearch.parse_results(query)
            # Check that there are results for the query
            resultBool = self.checkForResults(parsed_results)
            # print(parsed_results)

            if resultBool:
                # Show the query results in the SearchView
                wm.get_screen("searchView").send_query_results(
                    query, parsed_results)
                wm.get_screen("prodInfo").send_query_results(
                    query, parsed_results)
                wm.current = "searchView"
            else:
                wm.current = "homepage"
Ejemplo n.º 4
0
def add_operation(type_, m):
    """
	:param type_: True for income, False for expense
	:param m:
	:return:
	"""
    categories = api.Api(m.chat.id).get_category_list(type_)

    chosen_category = []

    def total_cb(m, total):
        if total != texts['back']:
            api.Api(m.chat.id).add_operation(type_, chosen_category[0], total)
            bot.send_message(m.chat.id, '✓')
            menu(m)

    def name_cb(m, user_choice):
        if user_choice == texts['back']:
            menu(m)
        else:
            chosen_category.append(user_choice)
            get_num(m, total_cb, 'Сумма')

    if len(categories) == 0:
        bot.send_message(m.chat.id, 'Сначала нужно добавить категорию')
        show_categories(m)
    else:
        get_text(m,
                 callback=name_cb,
                 title='Категория:',
                 options=categories + [texts['back']],
                 keyboard_row_width=2)
def find_unknown_faces_cmd():
    (cnx, cursor) = db_setup.connect(**config['db_config'])
    images = faces.find_unknown_in_db(cursor=cursor, api=api.Api(config['host']))
    render_html(
        output='output/unknown.html', template_name='./templates/unknown_faces.html.jinja', images=images, crop_size=100)
    webbrowser.open('file://{}'.format(os.path.realpath('./unknown.html')))
    cleanup(cnx=cnx, cursor=cursor)
Ejemplo n.º 6
0
def handleConnection(in_message, webhook):
    """
    Method to connect to the cluster using credentials provided and save the token until
    user decided to end session
    :param in_message:
    :param webhook:
    :return:
    """
    cmd, ipAddr, username, password = in_message.split(",")
    global apiObj
    apiObj = api.Api(ip=ipAddr, username=username, password=password)
    if apiObj is not None:
        msg = "**Connected Successfully!**\t\t"+ u"\u2713"
        sendSparkPOST("https://api.ciscospark.com/v1/messages", {"roomId": webhook['data']['roomId'], "markdown": msg})
        msg =       "Please try the commands to chat with me"+ line_separator
        msg = msg + "1. connect,<IP>,<UI-Username>,<UI-Password>       Connect to a cluster\n"
        msg = msg + "2. client <MAC ADDRESS>                                              Current information about a client\n"
        msg = msg + "3. device <DEVICE NAME>                                              Current information about a network device\n"
        msg = msg + "4. site-health-summary                                                   Healthy Unhealthy devices in a network\n"
        msg = msg + "5. site-health-detail                                                          Detailed health information per Site\n"
        msg = msg + "6. list-devices                                                                     Lists Devices on the network\n"
        msg = msg + "7. help                                                                                 Detailed health information per Site\n"
        msg = msg + "8. logout                                                                              Disconnect current connection to cluster\n"
    else:
        msg = "Cluster credentials incorrect/ Unable to authenticate.Please try again"
    sendSparkPOST("https://api.ciscospark.com/v1/messages", {"roomId": webhook['data']['roomId'], "text": msg})
Ejemplo n.º 7
0
    def __init__(self):
        # test a connection with the database
        try:
            print("Trying to connect to the database : '{}".format(
                config.DATABASE))
            self.database = mysql.connector.connect(user=config.USER,
                                                    password=config.PASSWORD,
                                                    host=config.HOST)
            print("\tConnection established")
        # if there is an error :
        except mysql.connector.Error as error:
            if error.errno == errorcode.ER_ACCESS_DENIED_ERROR:
                print("user'sname or password is wrong")
            elif error.errno == errorcode.ER_BAD_DB_ERROR:
                print("Database does not exist")
            else:
                print(
                    "Connection with database failed: \n Detected error : \n%s"
                    % error)

        else:
            print("creating cursor ...")
            self.cursor = self.database.cursor()
            print("cursors created !")

        # this variable access to api
        self.api_access = api.Api(self.cursor)

        # This variable access to database.py
        self.db_access = database.Database(self.cursor)

        # This variable access to view.py
        self.request_access = view.View(self.cursor, self.database)
Ejemplo n.º 8
0
 def __init__(self, key, time):
     self.time = time
     self.key = key
     self.api = api.Api()
     self.docker_client = docker.from_env()
     self.can_init = True
     self.cache_log = []
Ejemplo n.º 9
0
 def read_endpoints_from_xml(self, node):
     if node.tag == "endpoints":
         for child in node:
             if child.tag == "api":
                 tmp = api.Api()
                 tmp.parse_xml(child)
                 self.data.endpoints.append(tmp)
Ejemplo n.º 10
0
def updateip(apikey, domain_name, subdomain, port, domain_type):
    if port == None:
        port = 22
    if domain_type == None:
        domain_type = "A"

    FLAG = True
    linode = api.Api(apikey)
    domains = linode.domain_list()

    for domain in domains:
        if domain["DOMAIN"] == domain_name:
            did = domain["DOMAINID"]

    for each in linode.domain_resource_list(DomainID=did):
        if each["NAME"] == subdomain:
            FLAG = False
            resource_id = each["RESOURCEID"]

    ## grab IP address
    ip = getip()
    if FLAG == True:
        a = linode.domain_resource_create(Port=port,
                                          DomainID=did,
                                          Type=domain_type,
                                          Name=subdomain,
                                          Target=ip)
    else:
        a = linode.domain_resource_update(Port=port,
                                          DomainID=did,
                                          ResourceID=resource_id,
                                          Target=ip)
Ejemplo n.º 11
0
    def call(self, to, from_, fun_name, sig, data):
        instance = api.Api(self.config)

        result = instance.call(to, fun_name=fun_name, sig=sig, data=data)
        logger.info("      Result: %s" % result)

        return result
Ejemplo n.º 12
0
    def __init__(self, robot_name="", wait_services=False):

        self.robot_name = robot_name
        self.tf_listener = tf_server.TFClient()

        # Body parts
        self.parts = dict()
        self.parts['base'] = base.Base(self.robot_name, self.tf_listener)
        self.parts['torso'] = torso.Torso(self.robot_name, self.tf_listener)
        self.parts['leftArm'] = arms.Arm(self.robot_name,
                                         self.tf_listener,
                                         side="left")
        self.parts['rightArm'] = arms.Arm(self.robot_name,
                                          self.tf_listener,
                                          side="right")
        self.parts['head'] = head.Head(self.robot_name, self.tf_listener)

        # Human Robot Interaction
        self.parts['lights'] = lights.Lights(self.robot_name, self.tf_listener)
        self.parts['speech'] = speech.Speech(
            self.robot_name, self.tf_listener,
            lambda: self.lights.set_color(1, 0, 0),
            lambda: self.lights.set_color(0, 0, 1))
        self.parts['hmi'] = api.Api(self.robot_name, self.tf_listener)
        self.parts['ears'] = ears.Ears(self.robot_name,
                                       lambda: self.lights.set_color(0, 1, 0),
                                       lambda: self.lights.set_color(0, 0, 1))

        self.parts['ebutton'] = ebutton.EButton(self.robot_name,
                                                self.tf_listener)

        # Reasoning/world modeling
        self.parts['ed'] = world_model_ed.ED(self.robot_name, self.tf_listener)

        # Miscellaneous
        self.pub_target = rospy.Publisher("/target_location",
                                          geometry_msgs.msg.Pose2D,
                                          queue_size=10)
        self.base_link_frame = "/" + self.robot_name + "/base_link"

        # Grasp offsets
        #TODO: Don't hardcode, load from parameter server to make robot independent.
        self.grasp_offset = geometry_msgs.msg.Point(0.5, 0.2, 0.0)

        # Create attributes from dict
        for k, v in self.parts.iteritems():
            setattr(self, k, v)
        self.spindle = self.torso  # (ToDo: kind of ugly, why do we still have spindle???)
        self.arms = OrderedDict(
            left=self.leftArm, right=self.rightArm
        )  # (ToDo: kind of ugly, why do we need this???)
        self.ears._hmi = self.hmi  # ToDo: when ears is gone, remove this line

        # Wait for connections
        s = rospy.Time.now()
        for k, v in self.parts.iteritems():
            v.wait_for_connections(1.0)
        e = rospy.Time.now()
        rospy.logdebug("Connecting took {} seconds".format((e - s).to_sec()))
Ejemplo n.º 13
0
def compare_auctions():
    api = mfl_api.Api(2014)
    api.login(51974, '0015', sys.argv[1])
    url = 'http://football18.myfantasyleague.com/2014/options?L=51974&O=102&DISPLAY=CONFERENCE0{}'
    ind_rows = get_rows(url.format('0'), api)
    lib_rows = get_rows(url.format('1'), api)

    rows_to_csv(ind_rows, 'usfl_auction_ind.csv')
    rows_to_csv(lib_rows, 'usfl_auction_lib.csv')
Ejemplo n.º 14
0
 def cat_name_cb(m, user_choice):
     if user_choice == texts['back']:
         del_category(m)
     elif user_choice in category_list:
         api.Api(m.chat.id).del_category(chosen_type[0], user_choice)
         success_text(m)
         menu(m)
     else:
         bot.send_message(m.chat.id, 'Нет такой категории')
         ask_for_category_name(m)
Ejemplo n.º 15
0
def main():
    batch_size = int(sys.argv[1]) if len(sys.argv) > 1 else 5
    conf = config
    (cnx, cursor) = db_setup.connect(**conf['db_config'])
    db_setup.create_tables(cursor=cursor)
    queue = PhotoQueue(cnx)
    queue.consume(
        process=photos.process(api.Api(conf['host']), cursor=cursor),
        batch_size=batch_size)
    cleanup(cnx=cnx, cursor=cursor)
Ejemplo n.º 16
0
    def ask_for_category_name(m):
        categories_from_db = api.Api(m.chat.id).get_category_list(
            chosen_type[0])
        for cat in categories_from_db:
            category_list.append(cat)

        get_text(m,
                 cat_name_cb,
                 title='Как называется категория?',
                 options=category_list + [texts['back']])
Ejemplo n.º 17
0
 def try_transact(self, to, from_, sig, data, gas, gas_price, value):
     instance = api.Api(self.config)
     result = instance.transact(to,
                                from_=from_,
                                sig=sig,
                                data=data,
                                gas=gas,
                                gas_price=gas_price,
                                value=value)
     logger.info("      Result: " + colors.BOLD + "%s" %
                 (result if result else "OK") + colors.ENDC)
     return result
Ejemplo n.º 18
0
    def call(self, to, from_, sig, data, gas, gas_price, value):
        instance = api.Api(self.config)

        result = instance.call(to,
                               sig=sig,
                               data=data,
                               gas=gas,
                               gas_price=gas_price,
                               value=value)
        logger.info("      Result: " + colors.BOLD + "%s" % result +
                    colors.ENDC)

        return result
Ejemplo n.º 19
0
def show_categories(m):
    bot.send_message(m.chat.id,
                     text='<b>Доходов:</b>\n\n' +
                     '\n'.join(api.Api(m.chat.id).get_category_list(True)),
                     parse_mode='html')
    bot.send_message(m.chat.id,
                     text='<b>Расходов:</b>\n\n' +
                     '\n'.join(api.Api(m.chat.id).get_category_list(False)),
                     parse_mode='html')
    commands = {
        'Добавить категорию': add_category,
        'Удалить категорию': del_category,
        texts['menu']: menu
    }
    kb = make_kb(list(commands.keys()))

    def handler(m):
        # call method from commands, else: call menu
        commands.get(m.text, menu)(m)

    bot.send_message(m.chat.id, texts['default arrow'], reply_markup=kb)
    bot.register_next_step_handler(m, handler)
Ejemplo n.º 20
0
 def try_create(self,
                contract,
                from_,
                gas,
                gas_price,
                value,
                contract_name=None):
     instance = api.Api(self.config)
     tx_hash = instance.create(contract,
                               from_=from_,
                               gas=gas,
                               gas_price=gas_price,
                               endowment=value)
     return tx_hash
Ejemplo n.º 21
0
def main():
    parser = argparse.ArgumentParser()
    parser.set_defaults(api=api.Api(ETH_JSONRPC_URI))

    subparsers = parser.add_subparsers(help='sub-command help')
    parser_create = subparsers.add_parser('create', help='create the contract')
    parser_create.set_defaults(func=cmd_create)
    parser_create.add_argument('--wait',
                               action='store_true',
                               help='wait for block to be mined')

    parser_getreceivedbyaddress = subparsers.add_parser(
        'getreceivedbyaddress', help='getreceivedbyaddress')
    parser_getreceivedbyaddress.set_defaults(func=cmd_getreceivedbyaddress)
    parser_getreceivedbyaddress.add_argument('contract_address',
                                             help='contract address')
    parser_getreceivedbyaddress.add_argument('address',
                                             help='cryptocurrency address')

    parser_poll = subparsers.add_parser('poll', help='poll the contract state')
    parser_poll.set_defaults(func=cmd_poll)
    parser_poll.add_argument('contract_address', help='contract address')

    parser_status = subparsers.add_parser('status',
                                          help='display the eth node status')
    parser_status.set_defaults(func=cmd_status)

    parser_transact = subparsers.add_parser(
        'transact', help='transact ether to destination (default: 1 ETH)')
    parser_transact.set_defaults(func=cmd_transact)
    parser_transact.add_argument('dest', help='destination')
    parser_transact.add_argument('--value',
                                 type=int,
                                 default=1,
                                 help='value to transfer in ether')
    parser_transact.add_argument('--wait',
                                 action='store_true',
                                 help='wait for block to be mined')

    parser_watch = subparsers.add_parser('watch', help='watch the address')
    parser_watch.set_defaults(func=cmd_watch)
    parser_watch.add_argument('contract_address', help='contract address')
    parser_watch.add_argument('address', help='cryptocurrency address')
    parser_watch.add_argument('--wait',
                              action='store_true',
                              help='wait for block to be mined')

    args = parser.parse_args()
    args.func(args)
    def test(self):
        # Get an instance of the api
        apiSearch = api.Api()
        # Do the search
        testSearch = apiSearch.search({'item': 'x'})
        # Print search results for testing
        apiSearch.display_results(testSearch)
        # Parse results to only have a list of items
        # The full detail of each item is still in testSearch at this point
        results = apiSearch.parse_results(testSearch)
        # Print list of items for testing
        # print(results)

        # A list comprehension that builds a list of strings of item names
        self.my_label = [{'text': str(item)} for item in results]
Ejemplo n.º 23
0
def main():
    api = localapi.Api('config.sample')
    api2 = localapi.RemoteApi('http://115.182.62.171:9000/api',
                              'sg849KLWNETy6215zc9U1CapFlkt4JmC')

    query = '有什么不辣的川菜吗'
    friendly_display(api.nlu(query))
    friendly_display(api2.nlu(query))

    kw = {'name': '鱼香肉丝', 'taste': '甜'}
    friendly_display(api.nlg('answerNo', kw))
    friendly_display(api2.nlg('answerNo', kw))

    sparql = 'PREFIX r:<http://csaixyz.org/dish#> select ?o where { ?s r:has_taste "不辣"; r:dishtype "川菜"; r:name ?o. }'
    friendly_display(api.kb(sparql))
    friendly_display(api2.kb(sparql))
Ejemplo n.º 24
0
def apply_delta(api_key, config_file, dry_run):
    """
    Loads the Linode configuration (aka existing)
    Loads the YAML configuration (aka desired)
    Computes the zones to be added, deleted and modified.
    Deletes the zones as needed
    Adds the zones as needed
    Computes the changes for each zone that needs to be modified
    Computes the record changes for each zone that needs to be modified
    :param api_key:
    :param config_file:
    :param dry_run:
    :return:
    """
    linode_api = api.Api(api_key, dry_run)
    existing = get_linode_dns(linode_api)
    desired = config.Config(config_file).get_desired_dns()
    changes = zones_delta(existing, desired)
    to_be_deleted = changes[0]
    to_be_updated = changes[1]
    to_be_added = changes[2]
    for zone in to_be_deleted:
        linode_api.delete_zone(existing[zone])
    for zone in to_be_updated:
        field_changes = zone_delta(existing[zone], desired[zone])
        linode_api.modify_zone(existing[zone], desired[zone], field_changes)
        record_changes = records_delta(existing[zone].records,
                                       desired[zone].records)
        records_to_be_deleted = record_changes[0]
        records_to_be_updated = record_changes[1]
        records_to_be_added = record_changes[2]
        for record in records_to_be_deleted:
            linode_api.delete_record(existing[zone].records[record])
        for record in records_to_be_updated:
            field_changes = record_delta(existing[zone].records[record],
                                         desired[zone].records[record])
            linode_api.modify_record(existing[zone].records[record],
                                     desired[zone].records[record],
                                     field_changes)
        for record in records_to_be_added:
            linode_api.add_record(existing[zone],
                                  desired[zone].records[record])
    for zone in to_be_added:
        linode_api.add_zone(desired[zone])
        for record_name in desired[zone].records.keys():
            linode_api.add_record(desired[zone],
                                  desired[zone].records[record_name])
Ejemplo n.º 25
0
def get_all_bids():
    api = mfl_api.Api(2014)
    api.login(51974, '0015', sys.argv[1])

    current_bids_page = api.opener.open(
        'http://football.myfantasyleague.com/2014/options?L=51974&O=43')
    soup = BeautifulSoup(current_bids_page.read())
    auction_table = soup.find_all('table')[1]
    current_bids = auction_table.find_all('tr')[1:]

    finished_bids_page = api.opener.open(
        'http://football.myfantasyleague.com/2014/options?L=51974&O=102')
    soup2 = BeautifulSoup(finished_bids_page.read())
    auction_table = soup2.find_all('table')[2]
    finished_bids = auction_table.find_all('tr')[1:]

    return (current_bids, finished_bids)
Ejemplo n.º 26
0
def main():
    # This file should contain your couchsurfing email and password, separated by a newline.
    with open(r'C:\temp\courchsurfing_credentials.txt', 'r') as f:
        email, password = f.readline().strip(), f.readline().strip()

    # Set the latitude and longitude to your desired location.
    api = cs_api.Api(email, password, 32.0853, 34.7818)

    unseen_hangouts = hangouts.get_unseen_connections(api,
                                                      'latest_hangouts.txt')
    # Notify about new connections
    if unseen_hangouts:
        winsound.Beep(1000, 500)
        for hangout in unseen_hangouts:
            print('found new connection with: {}'.format(
                hangout['topParticipants'][0]['displayName']))

    hangouts.make_new_connections(api)
Ejemplo n.º 27
0
def menu(m):
    commands = {
        # user_text: function
        '+ Доход': add_income,
        '+ Расход': add_expense,
        texts['operations']: show_operations,
        texts['categories']: show_categories,
        texts['settings']: settings
    }
    kb = make_kb(options=list(commands.keys()), row_width=2)
    balance = api.Api(m.chat.id).get_balance()
    text = f'💰 {balance}₽'
    bot.send_message(m.chat.id, text, reply_markup=kb)

    def handler(m):
        # call method from commands, else: call menu
        commands.get(m.text, menu)(m)

    bot.register_next_step_handler(m, handler)
def lookup_faces_cmd():
    if (len(sys.argv) < 2):
        print('Please provide a face id')
        exit(1)
    face_id = int(sys.argv[1])
    limit = int(sys.argv[2]) if len(sys.argv) > 2 else 50
    (cnx, cursor) = db_setup.connect(**config['db_config'])
    results = faces.find_closest_match_by_id(face_id=face_id, cursor=cursor, limit=limit)
    _api = api.Api(config['host'])
    print("Found {} faces".format(len(results)))
    images = [
        (_api.get_img_url(hash=hash), json.loads(locations), distance, id)
        for (id, locations, hash, distance) in results
    ]
    render_html(
        output='output/results.html', template_name='./templates/faces.jinja.html',
        images=images)
    webbrowser.open('file://{}'.format(os.path.realpath('./results.html')))
    cleanup(cnx=cnx, cursor=cursor)
Ejemplo n.º 29
0
def startServer():
    ap = argparse.ArgumentParser(description='Server options')
    ap.add_argument('--clean', action='store_true', default=False)
    ap.add_argument('--port', type=int, default=1337)
    ap.add_argument('--domain', default='192.168.220.130')

    args = ap.parse_args()

    root = staticFiles.FileNoList('root')
    root.indexNames = ['index.rpy']
    root.ignoreExt('.rpy')
    root.processors = {'.rpy': script.ResourceScript}
    root.putChild('api', api.Api())

    if args.clean:
        try:
            shutil.rmtree('root/uploads')
        except:
            pass
        try:
            shutil.rmtree('root/config')
        except:
            pass
        os.mkdir('root/uploads/')
        os.mkdir('root/config/')

        shutil.copyfile('memeOfTheDay.png', 'root/uploads/memeOfTheDay.png')
        shutil.copyfile('admin.config', 'root/config/admin.config')
        os.system('chown -R nobody:nogroup root/uploads')
        os.system('chown -R nobody:nogroup root/config')

    globalVals.init(args, root)

    site = server.Site(root, logPath=b"access.log")
    reactor.listenTCP(args.port, site)
    drop_privileges('nobody', 'nogroup')
    reactor.run()
Ejemplo n.º 30
0
 def __init__(self, *args, **kwargs):
     self.api = api.Api()