Esempio n. 1
0
class MySdkTests(unittest.TestCase):
    def setUp(self):
        self.sdk = ServerProxy(RPC_SERVER_URI).sdk

    def tearDown(self):
        pass

    def test_add(self, a=123, b=456):
        result = self.sdk.add(a, b)
        print("\nsdk.add(%d, %d) = %d" % (a, b, result))
        self.assertEqual(result, 579)

    def test_subtract(self, a=2015, b=1999):
        result = self.sdk.subtract(a, b)
        print("\nsdk.subtract(%d, %d) = %d" % (a, b, result))
        self.assertEqual(result, 16)

    def test_httpGet(self, ip="203.208.48.146"):
        result = self.sdk.httpGet(ip)
        print("\nsdk.httpGet(%s) is %s" % (ip, result))
        self.assertIsNotNone(result)

    def test_getDeviceInfo(self):
        result = self.sdk.getDeviceInfo()
        print("\nsdk.getDeviceInfo() is:\n%s" % (result))
        self.assertIsNotNone(result)
Esempio n. 2
0
def NZBConnection(url):
    """Method to connect to NZBget client.

    :param url: nzb url to connect
    :return: True if connected, else False
    """
    nzbGetRPC = ServerProxy(url)
    try:
        if nzbGetRPC.writelog('INFO', 'Medusa connected to test connection.'):
            log.debug('Successfully connected to NZBget')
        else:
            log.warning('Successfully connected to NZBget but unable to'
                        ' send a message')
        return True

    except ProtocolError as error:
        if error.errmsg == 'Unauthorized':
            log.warning('NZBget username or password is incorrect.')
        else:
            log.error('Protocol Error: {msg}', {'msg': error.errmsg})
        return False

    except Error as error:
        log.warning('Please check your NZBget host and port (if it is running).'
                    ' NZBget is not responding to this combination.'
                    ' Error: {msg}', {'msg': error.errmsg})
        return False

    except socket.error as error:
        log.warning('Please check your NZBget host and port (if it is running).'
                    ' NZBget is not responding to this combination.'
                    ' Socket Error: {msg}', {'msg': error})
        return False
Esempio n. 3
0
    def _do_update(self, hwids):
        """Query remote server for driver updates for a set of HardwareIDs."""

        logging.debug("Querying XML-RPC driver database %s...", self.url)
        client = ServerProxy(self.url)
        # TODO: error handling; pass kernel_version, architecture
        (res_proto_ver, res_proto_subver, drivers) = client.query(
            "20080407",
            "0",
            {
                "os_name": OSLib.inst.os_vendor,
                "os_version": OSLib.inst.os_version,
                "system_vendor": self.sys_vendor,
                "system_product": self.sys_product,
                "components": ["%s:%s" % (h.type, h.id) for h in hwids],
            },
        )
        logging.debug("  -> protocol: %s/%s, drivers: %s", res_proto_ver, res_proto_subver, str(drivers))

        self.cache = {}
        if res_proto_ver != "20080407":
            logging.warning("   unknown protocol version, not updating")
            return

        for hwid in hwids:
            for drv in drivers.get("%s:%s" % (hwid.type, hwid.id), []):
                if "driver_type" not in drv:
                    continue
                self.cache.setdefault(hwid, []).append(DriverID(**drv))
Esempio n. 4
0
    def __sort_inputs_by_humanoid(self, possible_events):
        if sys.version.startswith("3"):
            from xmlrpc.client import ServerProxy
        else:
            from xmlrpclib import ServerProxy
        proxy = ServerProxy("http://%s/" % self.device.humanoid)
        request_json = {
            "history_view_trees": self.humanoid_view_trees,
            "history_events": [x.__dict__ for x in self.humanoid_events],
            "possible_events": [x.__dict__ for x in possible_events],
            "screen_res": [self.device.display_info["width"],
                           self.device.display_info["height"]]
        }
        result = json.loads(proxy.predict(json.dumps(request_json)))
        new_idx = result["indices"]
        text = result["text"]
        new_events = []

        # get rid of infinite recursive by randomizing first event
        if not self.utg.is_state_reached(self.current_state):
            new_first = random.randint(0, len(new_idx) - 1)
            new_idx[0], new_idx[new_first] = new_idx[new_first], new_idx[0]

        for idx in new_idx:
            if isinstance(possible_events[idx], SetTextEvent):
                possible_events[idx].text = text
            new_events.append(possible_events[idx])
        return new_events
Esempio n. 5
0
    def _register_with_server(self):
        """
        Register child node with server
        """        
        name = self.name
        self.logger.info("attempting to register with roslaunch parent [%s]"%self.server_uri)
        try:
            server = ServerProxy(self.server_uri)
            code, msg, _ = server.register(name, self.uri)
            if code != 1:
                raise RLException("unable to register with roslaunch server: %s"%msg)
        except Exception as e:
            self.logger.error("Exception while registering with roslaunch parent [%s]: %s"%(self.server_uri, traceback.format_exc()))
            # fail
            raise RLException("Exception while registering with roslaunch parent [%s]: %s"%(self.server_uri, traceback.format_exc()))
        
        self.logger.debug("child registered with server")
        
        # register printlog handler so messages are funneled to remote
        def serverlog(msg):
            server.log(name, Log.INFO, msg)
        def servererrlog(msg):
            server.log(name, Log.ERROR, msg)
        add_printlog_handler(serverlog)
        add_printerrlog_handler(servererrlog)            

        # register process listener to forward process death events to main server
        self.pm.add_process_listener(_ProcessListenerForwarder(server))
Esempio n. 6
0
 def test_get_last_N_minutes(self):
     proxy = ServerProxy('http://127.0.0.1:8000/')
     r = proxy.get_last_N_minutes('node-021', 'PH_EXT', 10)
     logging.debug(r)
     self.assertTrue('ReceptionTime' in r)
     self.assertTrue('PH_EXT' in r)
     self.assertTrue(len(r['ReceptionTime']) == len(r['PH_EXT']))
Esempio n. 7
0
class Client(Cmd):
    intro = 'Welcome to the p2p file share shell.\n\
Type help or ? to list commands.'
    prompt = '>'

    def __init__(self, url, dirname, urlfile):
        Cmd.__init__(self)
        self.secret = random_string(SECRET_LENGTH)
        n = Node(url, dirname, self.secret)
        t = Thread(target=n.serve_forever)
        t.setDaemon(1)
        t.start()
        time.sleep(HEAD_START)
        self.server = ServerProxy(url)
        for line in open(urlfile):
            line = line.strip()
            self.server.hello(line)

    def do_fetch(self, arg):
        try:
            self.server.fetch(arg, self.secret)
        except Fault as f:
            if f.faultCode != UNHANDLED:
                raise
            print("Couldn't find the file ", arg)

    def do_exit(self, arg):
        sys.exit()

    do_EOF = do_exit
Esempio n. 8
0
    def check_pypi(self):
        """
        If the requirement is frozen to pypi, check for a new version.
        """
        for dist in get_installed_distributions():
            name = dist.project_name
            if name in self.reqs.keys():
                self.reqs[name]["dist"] = dist

        pypi = ServerProxy("https://pypi.python.org/pypi")
        for name, req in list(self.reqs.items()):
            if req["url"]:
                continue  # skipping github packages.
            elif "dist" in req:
                dist = req["dist"]
                dist_version = LooseVersion(dist.version)
                available = pypi.package_releases(req["pip_req"].name, True) or pypi.package_releases(req["pip_req"].name.replace('-', '_'), True)
                available_version = self._available_version(dist_version, available)

                if not available_version:
                    msg = self.style.WARN("release is not on pypi (check capitalization and/or --extra-index-url)")
                elif self.options['show_newer'] and dist_version > available_version:
                    msg = self.style.INFO("{0} available (newer installed)".format(available_version))
                elif available_version > dist_version:
                    msg = self.style.INFO("{0} available".format(available_version))
                else:
                    msg = "up to date"
                    del self.reqs[name]
                    continue
                pkg_info = self.style.BOLD("{dist.project_name} {dist.version}".format(dist=dist))
            else:
                msg = "not installed"
                pkg_info = name
            print("{pkg_info:40} {msg}".format(pkg_info=pkg_info, msg=msg))
            del self.reqs[name]
Esempio n. 9
0
    def register(self):
        """Tries to register with the Meta-Server"""

        foamLogger().info("Trying to register as IP:%s PID:%d Port:%d"
                          % (self._answerer.ip(),
                             self._answerer.pid(),self._port))
        try:
            try:
                meta=ServerProxy(
                    "http://%s:%d" % (config().get(
                        "Metaserver","ip"),config().getint("Metaserver","port")))
                response=meta.registerServer(self._answerer.ip(),
                                             self._answerer.pid(),self._port)
                self.isRegistered=True
                foamLogger().info("Registered with server. Response "
                                  + str(response))
            except socket.error:
                reason = sys.exc_info()[1] # compatible with 2.x and 3.x
                foamLogger().warning("Can't connect to meta-server - SocketError: "+str(reason))
            except:
                foamLogger().error("Can't connect to meta-server - Unknown Error: "+str(sys.exc_info()[0]))
                foamLogger().error(str(sys.exc_info()[1]))
                foamLogger().error("Traceback: "+str(extract_tb(sys.exc_info()[2])))
        except:
            # print "Error during registering (no socket module?)"
            pass
Esempio n. 10
0
def setup_platform(hass, config, add_devices, discovery_info=None):
    """Setup the Homematic thermostat."""
    devices = []
    try:
        address = config[CONF_ADDRESS]
        homegear = ServerProxy(address)

        for name, device_cfg in config[CONF_DEVICES].items():
            # get device description to detect the type
            device_type = homegear.getDeviceDescription(
                device_cfg[CONF_ID] + ':-1')['TYPE']

            if device_type in HM_TYPE_MAPPING.keys():
                devices.append(HomematicThermostat(
                    HM_TYPE_MAPPING[device_type],
                    address,
                    device_cfg[CONF_ID],
                    name))
            else:
                raise ValueError(
                    "Device Type '{}' currently not supported".format(
                        device_type))
    except socket.error:
        _LOGGER.exception("Connection error to homematic web service")
        return False

    add_devices(devices)

    return True
Esempio n. 11
0
    def test_ROSLaunchNode(self):
        #exercise the basic ROSLaunchNode API
        from roslaunch.server import ROSLaunchNode

        # - create a node with a handler
        handler = TestHandler(self.pmon)
        node = ROSLaunchNode(handler)

        # - start the node
        node.start()
        self.assert_(node.uri)

        # - call the ping API that we added
        s = ServerProxy(node.uri)
        test_val = 'test-%s'%time.time()
        s.ping(test_val)
        self.assertEquals(handler.pinged, test_val)

        # - call the pid API
        code, msg, pid = s.get_pid()
        self.assertEquals(1, code)
        self.assert_(type(msg) == str)
        self.assertEquals(os.getpid(), pid)
        
        # - shut it down
        node.shutdown('test done')
Esempio n. 12
0
def show_pypi_status(ctx, severe=True):
    """Show project status on PyPI before doing a release.
    """
    info = atelier.current_project.SETUP_INFO
    version = info['version']
    name = info['name']

    assert name and version

    from xmlrpc.client import ServerProxy
    client = ServerProxy('https://pypi.python.org/pypi')
    released_versions = client.package_releases(name)
    if len(released_versions) == 0:
        print("No PyPI release of %(name)s has been done so far." % info)
    else:
        urls = client.release_urls(name, released_versions[-1])
        if len(urls) == 0:
            msg = "Last PyPI release was {0} (no files available)."
            msg = msg.format(released_versions[-1])
            print(msg)
        else:
            lastrel = urls[-1]
            # dt = lastrel['upload_time']
            # lastrel['upload_time'] = dt.ISO()
            print(LASTREL_INFO % lastrel)
        if severe and version in released_versions:
            raise Exit(
                "ABORT: %(name)s %(version)s has already been "
                "released." % info)
Esempio n. 13
0
def setup_platform(hass, config, add_devices, discovery_info=None):
    """ Sets up the Homematic thermostat. """

    devices = []
    try:
        homegear = ServerProxy(config[CONF_ADDRESS])
        for name, device_cfg in config[CONF_DEVICES].items():
            # get device description to detect the type
            device_type = homegear.getDeviceDescription(
                device_cfg[CONF_ID] + ':-1')['TYPE']

            if device_type in ['HM-CC-RT-DN', 'HM-CC-RT-DN-BoM']:
                devices.append(HomematicThermostat(homegear,
                                                   device_cfg[CONF_ID],
                                                   name, 4))
            elif device_type == 'HM-TC-IT-WM-W-EU':
                devices.append(HomematicThermostat(homegear,
                                                   device_cfg[CONF_ID],
                                                   name, 2))
            else:
                raise ValueError(
                    "Device Type '{}' currently not supported".format(
                        device_type))
    except socket.error:
        _LOGGER.exception("Connection error to homematic web service")
        return False

    add_devices(devices)

    return True
Esempio n. 14
0
    def test_unpublish(self):
        node_proxy = ServerProxy(rospy.get_node_uri())
        
        _, _, pubs = node_proxy.getPublications('/foo')
        pubs = [p for p in pubs if p[0] != '/rosout']
        self.assert_(not pubs, pubs)
        
        print("Publishing ", PUBTOPIC)
        pub = rospy.Publisher(PUBTOPIC, String)
        topic = rospy.resolve_name(PUBTOPIC)
        _, _, pubs = node_proxy.getPublications('/foo')
        pubs = [p for p in pubs if p[0] != '/rosout']
        self.assertEquals([[topic, String._type]], pubs, "Pubs were %s"%pubs)

        # publish about 10 messages for fun
        for i in range(0, 10):
            pub.publish(String("hi [%s]"%i))
            time.sleep(0.1)
        
        # begin actual test by unsubscribing
        pub.unregister()
        
        # make sure no new messages are received in the next 2 seconds
        timeout_t = time.time() + 2.0
        while timeout_t < time.time():
            time.sleep(1.0)
        self.assert_(_last_callback is None)

        # verify that close cleaned up master and node state
        _, _, pubs = node_proxy.getPublications('/foo')
        pubs = [p for p in pubs if p[0] != '/rosout']
        self.assert_(not pubs, "Node still has pubs: %s"%pubs)
        n = rospy.get_caller_id()
        self.assert_(not rostest.is_publisher(topic, n), "publication is still active on master")
Esempio n. 15
0
    def on_task_output(self, task, config):
        from xmlrpc.client import ServerProxy

        params = dict(config)

        server = ServerProxy(params["url"])

        for entry in task.accepted:
            if task.options.test:
                log.info('Would add into nzbget: %s', entry['title'])
                continue

            # allow overriding the category
            if 'category' in entry:
                params['category'] = entry['category']

            try:
                server.appendurl(
                    entry['title'] + '.nzb',
                    params['category'],
                    params['priority'],
                    params['top'],
                    entry['url'],
                )
                log.info('Added `%s` to nzbget', entry['title'])
            except Exception as e:
                log.critical('rpc call to nzbget failed: %s', e)
                entry.fail('could not call appendurl via RPC')
Esempio n. 16
0
    def replicate(self, item):
        if item is None:
            return

        path = item[0]
        cs_list = item[1]

        alive = [x for x in cs_list if self.ns._is_alive_cs(x)]

        if len(alive) == 0:
            print('There no live cs for chunk', path)
            return

        if len(alive) >= 2:
            print('File', path, 'is already replicated to more than 2 nodes')
            return

        new_cs = self.ns._select_available_cs(alive)
        if new_cs is None:
            print("Can't find available cs for replication", path)
        else:
            try:
                cl = ServerProxy(alive[0])
                cl.replicate_chunk(path, new_cs)
                print("File", path, "replicated to", new_cs)

                file = self.ns.root.find_file_by_chunk(path)
                if file is not None and path in file.chunks:
                    file.chunks[path].append(new_cs)
                else:
                    print("Cant find file for chunk", path, "after replication")
            except Exception as e:
                print('Error during replicatiion', path, 'to', new_cs, ':', e)
Esempio n. 17
0
    def _do_update(self, hwids):
        '''Query remote server for driver updates for a set of HardwareIDs.'''

        logging.debug('Querying XML-RPC driver database %s...', self.url)
        client = ServerProxy(self.url)
        # TODO: error handling; pass kernel_version, architecture
        (res_proto_ver, res_proto_subver, drivers) = client.query(
            '20080407', '0', { 
            'os_name': OSLib.inst.os_vendor,
            'os_version': OSLib.inst.os_version, 
            'system_vendor': self.sys_vendor,
            'system_product': self.sys_product,
            'components': ['%s:%s' % (h.type, h.id) for h in hwids]
            })
        logging.debug('  -> protocol: %s/%s, drivers: %s', res_proto_ver,
            res_proto_subver, str(drivers))

        self.cache = {}
        if res_proto_ver != '20080407':
            logging.warning('   unknown protocol version, not updating')
            return

        for hwid in hwids:
            for drv in drivers.get('%s:%s' % (hwid.type, hwid.id), []):
                if 'driver_type' not in drv:
                    continue
                self.cache.setdefault(hwid, []).append(DriverID(**drv))
Esempio n. 18
0
def list_processes(roslaunch_uris=None):
    """
    @param roslaunch_uris: (optional) list of XML-RPCS. If none
        are provided, will look up URIs dynamically
    @type  roslaunch_uris: [str]
    @return: list of roslaunch processes
    @rtype: [L{NetProcess}]
    """
    if not roslaunch_uris:
        roslaunch_uris = get_roslaunch_uris()
        if not roslaunch_uris:
            return []

    procs = []
    for uri in roslaunch_uris:
        try:
            r = ServerProxy(uri)
            code, msg, val = r.list_processes()
            if code == 1:
                active, dead = val
                procs.extend([NetProcess(a[0], a[1], True, uri) for a in active])
                procs.extend([NetProcess(d[0], d[1], False, uri) for d in dead])
        except:
            #import traceback
            #traceback.print_exc()
            # don't have a mechanism for reporting these errors upwards yet
            pass 
    return procs
Esempio n. 19
0
def test_server(host='localhost', port=4966):
    """Test for a Larch server on host and port

    Arguments
      host (str): host name ['localhost']
      port (int): port number [4966]

    Returns
      integer status number:
          0    Not in use.
          1    Connected, valid Larch server
          2    In use, but not a valid Larch server
    """
    server = ServerProxy('http://%s:%d' % (host, port))
    try:
        methods = server.system.listMethods()
    except socket.error:
        return NOT_IN_USE

    # verify that this is a valid larch server
    if len(methods) < 5 or 'larch' not in methods:
        return NOT_LARCHSERVER
    ret = ''
    try:
        ret = server.get_rawdata('_sys.config.user_larchdir')
    except:
        return NOT_LARCHSERVER
    if len(ret) < 1:
        return NOT_LARCHSERVER

    return CONNECTED
Esempio n. 20
0
File: RPC.py Progetto: gspd/FlexA
    def get_next_server(self):
        """
        Get the next server online

        return rpc server object
        """

        #if index is out of list range, scan network again
        if self.index_list_online >= len(self.list_online):
            self.scan_online_servers()

        if len(self.list_online) == 0 :
            sys.exit("Couldn't find any server. Verify your connection.")


        #get the next server of the list of servers online
        self.ip_server = self.list_online[self.index_list_online]
        self.index_list_online += 1
        #make the structure to connect rpc_server
        server_addr = 'http://{}:{}'.format(self.ip_server, self.config.sync_port)

        try:
            #set configurations of connection
            connection = ServerProxy(server_addr)
            socket.setdefaulttimeout(10)
            #verify if server is online and fine
            connection.still_alive()
            socket.setdefaulttimeout(None)
            #return the object server_rpc
            return connection
        except:
            #try next connection
            return self.get_next_server()
Esempio n. 21
0
def kill_nodes(node_names):
    """
    Call shutdown on the specified nodes

    @return: list of nodes that shutdown was called on successfully and list of failures
    @rtype: ([str], [str])
    """
    master = rosgraph.Master(ID)
    
    success = []
    fail = []
    tocall = []
    try:
        # lookup all nodes keeping track of lookup failures for return value
        for n in node_names:
            try:
                uri = master.lookupNode(n)
                tocall.append([n, uri])
            except:
                fail.append(n)
    except socket.error:
        raise ROSNodeIOException("Unable to communicate with master!")

    for n, uri in tocall:
        # the shutdown call can sometimes fail to succeed if the node
        # tears down during the request handling, so we assume success
        try:
            p = ServerProxy(uri)
            _succeed(p.shutdown(ID, 'user request'))
        except:
            pass
        success.append(n)            

    return success, fail
class PageStorageClient(object):
    def __init__(self, server_address=("127.0.0.1", 9966)):
        self.server_address = server_address
        self.server_proxy = XMLRPCServerProxy(
            "http://%s:%s/" % self.server_address,
            allow_none=True)


    def get_page(self, target_url):
        return decode_from_binary(self.server_proxy.get_page(target_url))


    def get_page_by_id(self, page_id):
        return decode_from_binary(self.server_proxy.get_page_by_id(page_id))


    def set_page(self, page_info):
        return self.server_proxy.set_page(encode_to_binary(page_info))


    def remove_page(self, target):
        return self.server_proxy.remove_page(encode_to_binary(target))


    def __contains__(self, key):
        return self.server_proxy.has_key(key)


    def has_key(self, key):
        return self.__contains__(key)
Esempio n. 23
0
class Client(Cmd):
    prompt = '> '

    def __init__(self, url, dirname, urlfile):
        Cmd.__init__(self)
        self.secret = randomString(SECRET_LENGTH)
        n = Node(url, dirname, self.secret)
        t = Thread(target=n._start)
        t.setDaemon(1)
        t.start()

        sleep(HEAD_START)
        self.server = ServerProxy(url)
        urlfile = path.join(dirname, urlfile)
        for line in open(urlfile):
            line = line.strip()
            self.server.hello(line)

    def do_fetch(self, arg):
        try:
            self.server.fetch(arg, self.secret)
        except Fault as f:
            if f.faultCode != UNHANDLED: raise
            print("Couldn't find the file", arg)

    def do_exit(self, arg):
        print()
        sys.exit()

    do_EOF = do_exit
Esempio n. 24
0
 def test_condense(self):
     proxy = ServerProxy('http://127.0.0.1:8000/')
     from random import randint
     for i in range(100):
         N = randint(1, 1000)
         lim = randint(1, N)
         a = list(range(N))
         assert len(proxy.condense(a, lim)) <= lim
Esempio n. 25
0
 def pypi_release(self):
     """Get the latest pypi release
     """
     meta = self.distribution.metadata
     pypi = ServerProxy(self.pypi_index_url)
     releases = pypi.package_releases(meta.name)
     if releases:
         return next(iter(sorted(releases, reverse=True)))
Esempio n. 26
0
 def __init__(
     self, address, username=None, password=None, language="en", verbose=False
 ):
     self.__address = address
     ServerProxy.__init__(
         self, address, transport=InwxTransport(), encoding="UTF-8", verbose=verbose
     )
     self.account.login({"lang": language, "user": username, "pass": password})
Esempio n. 27
0
def _fetch_version(name):
    arch_name = fix_name(name)

    # First try to get the package by name
    r = requests.get("https://www.archlinux.org/packages/search/json",
                     params={"name": arch_name})
    if r.status_code == 200:
        results = r.json()["results"]
    else:
        results = []

    def build_url(r):
        return "https://www.archlinux.org/packages/%s/%s/%s" % (
            r["repo"], r["arch"], r["pkgname"])

    versions = {}
    for result in results:
        url = build_url(result)
        versions[arch_name] = (result["pkgver"], url)
        for vs in result["provides"]:
            if "=" in vs:
                prov_name, ver = vs.split("=", 1)
                ver = ver.rsplit("-", 1)[0]
                versions[prov_name] = (ver, url)
            else:
                versions[vs] = (result["pkgver"], url)
        return versions

    # If all fails, search the AUR
    r = requests.get("https://aur.archlinux.org/rpc.php", params={
        "v": "5", "type": "search", "by": "name", "arg": arch_name})
    if r.status_code == 200:
        results = r.json()["results"]
    else:
        results = []

    for result in results:
        if result["Name"] == arch_name:
            url = "https://aur.archlinux.org/packages/%s" % result["Name"]
            return {arch_name: (result["Version"].rsplit("-", 1)[0], url)}

    if arch_name.startswith(("python-", "python2-")):
        pypi_name = arch_name.split("-", 1)[-1]
    else:
        pypi_name = arch_name

    client = ServerProxy('https://pypi.python.org/pypi')
    releases = client.package_releases(pypi_name)
    if releases:
        return {arch_name: (
            releases[0], "https://pypi.python.org/pypi/%s" % pypi_name)}

    r = requests.get(
        "http://ftp.gnome.org/pub/GNOME/sources/%s/cache.json" % arch_name)
    if r.status_code == 200:
        return {arch_name: (list(r.json()[2].values())[0][-1], "")}

    return {}
Esempio n. 28
0
    def test_ROSLaunchParentNode(self):
        from roslaunch.server import ROSLaunchParentNode
        from roslaunch.server import ChildROSLaunchProcess
        from roslaunch.config import ROSLaunchConfig
        from roslaunch.pmon import ProcessListener
        rosconfig = ROSLaunchConfig()
        try:
            ROSLaunchParentNode(rosconfig, None)
            self.fail("should not allow pm as None")
        except: pass
        pmon = self.pmon
        n = ROSLaunchParentNode(rosconfig, pmon)
        self.assertEquals(rosconfig, n.rosconfig)
        self.assertEquals([], n.listeners)
        self.assertEquals({}, n.child_processes)
        self.assertEquals(n.handler.listeners, n.listeners)
        self.assertEquals(n.handler.child_processes, n.child_processes)

        # test add listener
        self.assertEquals(n.handler.listeners, n.listeners)
        l = ProcessListener() 
        n.add_process_listener(l)
        self.assertEquals([l], n.listeners)
        self.assertEquals(n.handler.listeners, n.listeners)

        # now, lets make some xmlrpc calls against it
        import roslaunch.config
        server = roslaunch.server.ROSLaunchParentNode(roslaunch.config.ROSLaunchConfig(), self.pmon)

        # it's really dangerous for logging when both a parent and a
        # child are in the same process, so out of paranoia, clear the
        # logging handlers
        roslaunch.core.clear_printlog_handlers()
        roslaunch.core.clear_printerrlog_handlers()
        
        # - register a fake child with the server so that it accepts registration from ROSLaunchChild
        child_name = 'child-%s'%time.time()
        child_proc = ChildROSLaunchProcess('foo', [], {})
        server.add_child(child_name, child_proc)
        
        try:
            server.start()
            self.assert_(server.uri, "server URI did not initialize")
            s = ServerProxy(server.uri)
            child_uri = 'http://fake-unroutable:1324'
            # - list children should be empty
            val = self._succeed(s.list_children())
            self.assertEquals([], val)
            # - register
            val = self._succeed(s.register(child_name, child_uri))
            self.assertEquals(1, val)
            # - list children
            val = self._succeed(s.list_children())
            self.assertEquals([child_uri], val)
        finally:
            server.shutdown('test done')
Esempio n. 29
0
    def test_ROSLaunchChildNode(self):
        from roslaunch.server import ROSLaunchChildNode
        from roslaunch.server import ChildROSLaunchProcess
        pmon = self.pmon
        try:
            # if there is a core up, we have to use its run id
            run_id = get_param('/run_id')
        except:
            run_id = 'foo-%s'%time.time()
        name = 'foo-bob'
        server_uri = 'http://localhost:12345'
        try:
            ROSLaunchChildNode(run_id, name, server_uri, None)
            self.fail("should not allow pm as None")
        except: pass
        try:
            ROSLaunchChildNode(run_id, name, 'http://bad_uri:0', pmon)
            self.fail("should not allow bad uri")
        except: pass

        n = ROSLaunchChildNode(run_id, name, server_uri, pmon)
        self.assertEquals(run_id, n.run_id)
        self.assertEquals(name, n.name)        
        self.assertEquals(server_uri, n.server_uri)

        # tests for actual registration with server
        import roslaunch.config
        server = roslaunch.server.ROSLaunchParentNode(roslaunch.config.ROSLaunchConfig(), self.pmon)
        # - register a fake child with the server so that it accepts registration from ROSLaunchChild
        child_proc = ChildROSLaunchProcess('foo', [], {})
        server.add_child(name, child_proc)
        
        try:
            server.start()
            self.assert_(server.uri, "server URI did not initialize")
            s = ServerProxy(server.uri)

            print("SERVER STARTED")
            
            # start the child
            n = ROSLaunchChildNode(run_id, name, server.uri, pmon)            
            n.start()
            print("CHILD STARTED")            
            self.assert_(n.uri, "child URI did not initialize")            

            # verify registration
            print("VERIFYING REGISTRATION")                        
            self.assertEquals(child_proc.uri, n.uri)
            child_uri = 'http://fake-unroutable:1324'
            # - list children
            val = self._succeed(s.list_children())
            self.assertEquals([n.uri], val)
        finally:
            print("SHUTTING DOWN")                                    
            n.shutdown('test done')
            server.shutdown('test done')
Esempio n. 30
0
def send_file(filename, is_public=False):
    results = False
    proxy = ServerProxy('http://{host}:{port}'.format(host=host, port=port), allow_none=True)
    with open(filename, 'rb') as f:
        path, fn = os.path.split(filename)
        print('Sending {fn}'.format(fn=fn))
        data = f.read()
        results = proxy.upload(fn, Binary(data), is_public)

    return results
Esempio n. 31
0
def get_xmlrpc_client(pypi_url):
    return ServerProxy(pypi_url, transport=RequestsTransport())
Esempio n. 32
0
 def getProxy(self, server_url):
     return ServerProxy(server_url)
Esempio n. 33
0
def _fetch_version(name):
    arch_name = fix_name(name)

    # First try to get the package by name
    r = requests.get("https://www.archlinux.org/packages/search/json",
                     params={"name": arch_name})
    if r.status_code == 200:
        results = r.json()["results"]
    else:
        results = []

    def build_url(r):
        return "https://www.archlinux.org/packages/%s/%s/%s" % (
            r["repo"], r["arch"], r["pkgname"])

    versions = {}
    for result in results:
        url = build_url(result)
        versions[arch_name] = (result["pkgver"], url)
        for vs in result["provides"]:
            if "=" in vs:
                prov_name, ver = vs.split("=", 1)
                ver = ver.rsplit("-", 1)[0]
                versions[prov_name] = (ver, url)
            else:
                versions[vs] = (result["pkgver"], url)
        return versions

    # If all fails, search the AUR
    r = requests.get("https://aur.archlinux.org/rpc.php",
                     params={
                         "v": "5",
                         "type": "search",
                         "by": "name",
                         "arg": arch_name
                     })
    if r.status_code == 200:
        results = r.json()["results"]
    else:
        results = []

    for result in results:
        if result["Name"] == arch_name:
            url = "https://aur.archlinux.org/packages/%s" % result["Name"]
            return {arch_name: (result["Version"].rsplit("-", 1)[0], url)}

    if arch_name.startswith(("python-", "python2-")):
        pypi_name = arch_name.split("-", 1)[-1]
    else:
        pypi_name = arch_name

    client = ServerProxy('https://pypi.python.org/pypi')
    releases = client.package_releases(pypi_name)
    if releases:
        return {
            arch_name:
            (releases[0], "https://pypi.python.org/pypi/%s" % pypi_name)
        }

    r = requests.get("http://ftp.gnome.org/pub/GNOME/sources/%s/cache.json" %
                     arch_name)
    if r.status_code == 200:
        return {arch_name: (list(r.json()[2].values())[0][-1], "")}

    return {}
Esempio n. 34
0
 def __request(self, methodname, params):
     return ServerProxy._ServerProxy__request(self, methodname, params)
Esempio n. 35
0
    with SimpleXMLRPCServer(('localhost', args.port), Handler) as server:
        server.register_function(path_check)
        server.register_function(check_file_hash)
        server.register_function(get_filenames)
        server.register_function(make_dirs)
        server.register_function(delete_file)
        server.register_function(upload_file)
        server.register_function(fetch_file)
        server.register_function(delete_empty_dir)
        server.register_function(cp_same_folder)
        server.register_function(mv_file) 

        server_url = 'http://{}:{}'.format(server.server_address[0], server.server_address[1])

        server_registered = False
        with ServerProxy(name_server_url, allow_none=True) as proxy:
            server_registered = proxy.register_file_server(args.server_id, server_url)

        if server_registered:
            root_dir = root_dir / str(args.server_id)
            if not root_dir.exists():
                root_dir.mkdir(parents=True) 

            print('Initializing server for files in "{}"...'.format(str(root_dir)))

            file_list = []
            for root, dirs, files in os.walk(str(root_dir)):
                for file_name in files:
                    file_path = os.path.join(root, file_name)
                    file_info = generate_file_info(args.server_id, file_path, file_name)
Esempio n. 36
0
#! python3

from xmlrpc.client import ServerProxy

proxy = ServerProxy("https://secure2.roisolutions.net/enterprise/xmlrpc")

id = 'dcsinsi'
pwd = '*******'
client = 'oa'

proxy.Init.logon(id, pwd, client)
Esempio n. 37
0
from electrum_rby import bitcoin, util
from electrum_rby import transaction
from electrum_rby.plugins import BasePlugin, hook
from electrum_rby.i18n import _
from electrum_rby.wallet import Multisig_Wallet
from electrum_rby.util import bh2u, bfh

from electrum_rby_gui.qt.transaction_dialog import show_transaction

import sys
import traceback


PORT = 12344
HOST = 'cosigner.electrum.org'
server = ServerProxy('http://%s:%d'%(HOST,PORT), allow_none=True)


class Listener(util.DaemonThread):

    def __init__(self, parent):
        util.DaemonThread.__init__(self)
        self.daemon = True
        self.parent = parent
        self.received = set()
        self.keyhashes = []

    def set_keyhashes(self, keyhashes):
        self.keyhashes = keyhashes

    def clear(self, keyhash):
import argparse
import mimetypes
import subprocess

if sys.version_info >= (3, 0):
    import shutil
    import urllib.request
    from xmlrpc.client import ServerProxy, Error
else:  # python2
    import urllib
    from xmlrpclib import ServerProxy, Error

# ==== OpenSubtitles.org server settings =======================================

# XML-RPC server domain for opensubtitles.org:
osd_server = ServerProxy('https://api.opensubtitles.org/xml-rpc')

# You can use your opensubtitles.org VIP account to avoid "in-subtitles" advertisement and bypass download limits.
# Be careful about your password security, it will be stored right here in plain text...
# You can also change opensubtitles.org language, it will be used for error codes and stuff.
# Can be overridden at run time with '-u' and '-p' arguments.
osd_username = ''
osd_password = ''
osd_language = 'en'

# ==== Language settings =======================================================

# 1/ Change the search language by using any supported 3-letter (ISO639-2) language code:
#    > Supported language codes: https://www.opensubtitles.org/addons/export_languages.php
#    > Full guide: https://github.com/emericg/OpenSubtitlesDownload/wiki/Adjust-settings
#    > Ex: opt_languages = ['eng']
Esempio n. 39
0
 def __init__(self, url, config, env):
     self.server = ServerProxy(url)
     self.config = config
     self.env = env
Esempio n. 40
0
                        print('Fetching failed.')
            elif command[0] == 'help' and len(command) == 1:
                helpcommand(self.username)

            elif command[0] == 'exit':
                break
            else:
                print('Invalid Command.')


if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('mode',
                        help='Client run mode. Either "signup" or "login".',
                        type=str)
    parser.add_argument('username', help='Username of the user.', type=str)
    parser.add_argument('password', help='Password of the user.', type=str)
    args = parser.parse_args()

    proxy = ServerProxy(name_server_url, allow_none=True)

    if args.mode == 'signup':
        sign_up(args.username, args.password)
    elif args.mode == 'login':
        app = login(args.username, args.password)

        if app is not None:
            app.main_loop()
    else:
        print('Invalid operation.')
Esempio n. 41
0
    def main_loop(self):
        while True:

            command = str(
                input(
                    '\033[1;32;40mPraveenSharma@CustomShell$\033[1;31;40m\033[0;37;40m '
                )).split(' ')

            if command[0] == 'cd' and len(command) == 2:
                target_dir = Path(self.cd) / command[1].strip()
                can_change, rel_path = can_change_dir(self.user_id,
                                                      str(target_dir))

                if can_change:
                    self.cd = rel_path
                else:
                    print('Invalid file path.')

            elif command[0] == 'ls' and len(command) == 1:
                list_file_names(self.user_id, str(self.cd))

            elif command[0] == 'pwd' and len(command) == 1:
                print('Current directory:', self.username + os.sep + self.cd)

            elif command[0] == 'mkdir' and len(command) == 2:
                target_dir_str = str(Path(self.cd) / command[1].strip())

                if make_dirs(self.user_id, target_dir_str):
                    print('Successfully created "{}".'.format(target_dir_str))
                else:
                    print('Could not create directory.')

            elif command[0] == 'deletedir' and len(command) == 2:
                target_dir_str = str(Path(self.cd) / command[1].strip())

                if del_dir(self.user_id, target_dir_str):
                    print('Successfully deleted "{}".'.format(target_dir_str))
                else:
                    print('Could not delete directory.')

            elif command[0] == 'cp' and len(command) == 3:
                src = str(Path(self.cd) / command[1].strip())
                dst = str(command[2].strip())
                addresses = proxy.get_server_addresses(self.user_id)

                flag = False
                file_bin = None

                rel_path_str = ""

                for address in addresses:
                    with ServerProxy(address, allow_none=True) as new_proxy:
                        path_valid, path_exists, rel_path_str = new_proxy.path_check(
                            self.user_id, src)

                        if path_valid and path_exists:
                            if not new_proxy.cp_same_folder(
                                    self.user_id, src, dst):
                                print('Can not copy')
                        #  print('path2 :',str(dir+"/"+dst)

            elif command[0] == 'mv' and len(command) == 3:
                src = str(Path(self.cd) / command[1].strip())
                dst = str(command[2].strip())
                addresses = proxy.get_server_addresses(self.user_id)

                flag = False
                file_bin = None

                rel_path_str = ""

                for address in addresses:
                    with ServerProxy(address, allow_none=True) as new_proxy:
                        path_valid, path_exists, rel_path_str = new_proxy.path_check(
                            self.user_id, src)

                        if path_valid and path_exists:
                            if not new_proxy.mv_file(self.user_id, src, dst):
                                print('Can not move file')

            elif command[0] == 'upload' and len(command) == 4:
                local_file_path_obj = Path(command[1].strip()).resolve()
                cloud_file_path = str(Path(self.cd) / command[2].strip())
                filename = command[3].strip()

                can_change, rel_path = can_change_dir(self.user_id,
                                                      cloud_file_path)

                if can_change:
                    if local_file_path_obj.is_file():
                        file_bin = encrypt_file(
                            self.username,
                            get_file_binary(str(local_file_path_obj)))

                        if upload_file(self.user_id, file_bin, cloud_file_path,
                                       filename):
                            print('Uploaded "{}" to "{}" successfully.'.format(
                                filename, self.username + os.sep + rel_path))
                        else:
                            print('Upload failed.')
                else:
                    print('Invalid cloud path.')

            elif command[0] == 'rm' and len(command) == 2:
                target_dir_str = str(Path(self.cd) / command[1].strip())

                if delete_file(self.user_id, target_dir_str):
                    print('File at "{}" deleted successfully.'.format(
                        target_dir_str))
                else:
                    print('Could not delete file.')

            elif command[0] == 'fetch' and len(command) == 3:
                cloud_file_path = str(Path(self.cd) / command[1].strip())
                local_path_to_save_obj = Path(command[2].strip()).resolve()

                if not local_path_to_save_obj.is_dir():
                    print('Invalid local directory.')
                else:
                    if fetch_file(self.user_id, self.username, cloud_file_path,
                                  local_path_to_save_obj):
                        print('File saved to {}.'.format(
                            str(local_path_to_save_obj)))
                    else:
                        print('Fetching failed.')
            elif command[0] == 'help' and len(command) == 1:
                helpcommand(self.username)

            elif command[0] == 'exit':
                break
            else:
                print('Invalid Command.')
Esempio n. 42
0
def rpc_client1():
    s = ServerProxy('http://localhost:20000', allow_none=True)

    s.set('foo', 'bar')
    s.set('spam', [1, 2, 3])

    keys = s.keys()
    print(keys)  # ['foo', 'spam']

    foo = s.get('foo')
    print(foo)  # bar

    s.delete('spam')

    exist = s.exists('spam')
    print(exist)  # False

    # rpc 处理自定义的对象时,只有字典部分数据被处理
    s.set('point', Point(1, 2))
    p = s.get('point')
    print(p)  # {'x': 1, 'y': 2}

    s.set('bin', b'hello world')
    bin = s.get('bin')
    print('{!r:}'.format(bin))  # <xmlrpc.client.Binary object at 0x10d578e48>
    print('{!s:}'.format(bin))  # hello world 自动转码
Esempio n. 43
0
#!/usr/bin/python

# client.py

# implements the arithmetic functions found at
# https://en.wikipedia.org/wiki/Rinda_(Ruby_programming_language)

from xmlrpc.client import ServerProxy, Error

with ServerProxy("http://localhost:8000", allow_none=True) as proxy:
    try:
        tuples = [("*", 2, 2), ("+", 2, 5), ("-", 9, 3)]
        for t in tuples:
            # ops, a, b = t
            tmp = proxy.arith._out(t)
            print(tmp)
            res = proxy.arith._in(["result", {"class": "Numeric"}])
            print(f'{res[1]} = {t[1]} {t[0]} {t[2]}')
    except Error as e:
        print(f'Error: {e}')
class Cliente(MainWindowUI, MainWindowBase):
    def __init__(self):
        super(Cliente, self).__init__()
        uic.loadUi('cliente.ui', self)
        self.setupUi(self)
        self.espera = 0
        self.timer = QtCore.QTimer(self)
        self.timer.timeout.connect(self.estado_juego)
        self.timer.start(self.espera)
        self.servidor = None
        self.snake = False
        self.redimensionar()
        self.poner_lienzo_celdas()
        self.clickers()
        self.tabla.setSelectionMode(QtGui.QTableWidget.NoSelection)

    def conexion(self):
        url = self.url.text()
        puerto = self.puerto.value()

        self.servidor = ServerProxy("http://" + url + ":" + str(puerto))
        #self.servidor = ServerProxy( "http://127.0.0.1:8000" )

    def conectar_con_ping(self):
        self.ping_pong.setText("Pinging...")

        try:
            self.conexion()
            pong = self.serv.ping()
            print(pong)
            self.ping_pong.setText("¡Pong!")
        except:
            self.ping_pong.setText("No pong :(")

    def conectar_con_yo_juego(self):
        if self.servidor is None:
            return

        datos = self.servidor.yo_juego()
        self.id.setValue(datos["id"])
        self.color.setValue(datos["color"])
        #desabilita la entrada de datos en esos input (lool)
        self.id.configure(state="disabled")
        self.color.configure(state="disabled")
        self.snake = True

    def conectar_con_cambia_direccion(self, teclita):
        id = self.id.text()

        if teclita == QtCore.Qt.Key_Up:
            direccion = 0
        if teclita == QtCore.Qt.Key_Down:
            direccion = 2
        if teclita == QtCore.Qt.Key_Left:
            direccion = 3
        if teclita == QtCore.Qt.Key_Right:
            direccion = 1

        self.servidor.cambia_direccion(id, direccion)

    def eventFilter(self, source, event):
        if event.type() == QtCore.QEvent.KeyPress and source is self.tabla:
            teclita = event.key()
            self.conectar_con_cambia_direccion(teclita)

    def estado_juego(self):
        if self.servidor is None or not self.snake:
            return

        self.tabla.installEventFilter(self)
        datos = self.servidor.estado_del_juego()
        self.cambio_espera(datos["espera"])
        columnas = datos["tamX"]
        filas = datos["tamY"]
        snakes = datos["viboras"]

        self.cambio_numero_celdas(filas, columnas)

        for snake in snakes:
            R = snake["color"]["r"]
            G = snake["color"]["g"]
            B = snake["color"]["b"]
            for cachito_snake in snake["camino"]:
                tabla.item(cachito_snake_bb[0],
                           cachito_snake[1]).setBackground(
                               QtGui.QColor(R, G, B))

    def cambio_espera(self, espera):
        if self.espera != espera:
            self.espera = espera
            self.timer.setInterval(espera)

    def redimensionar(self):
        self.tabla.verticalHeader().setResizeMode(QtGui.QHeaderView.Stretch)
        self.tabla.horizontalHeader().setResizeMode(QtGui.QHeaderView.Stretch)

    def poner_lienzo_celdas(self):
        self.tabla.setSelectionMode(QtGui.QTableWidget.NoSelection)
        for i in range(self.tabla.rowCount()):
            for j in range(self.tabla.columnCount()):
                self.tabla.setItem(i, j, QtGui.QTableWidgetItem())
                self.tabla.item(i, j).setBackground(QtGui.QColor(0, 0, 0))

    def cambio_numero_celdas(self, filas, columnas):
        self.tabla.setRowCount(filas)
        self.tabla.setColumnCount(columnas)
        self.poner_lienzo_celdas()
        self.redimensionar()

    def clickers(self):
        self.ping_pong.clicked.connect(self.conectar_con_ping)
        self.participar.clicked.connect(self.conectar_con_yo_juego)
Esempio n. 45
0
 def __init__(self, ecosystem):
     """Initialize instance."""
     super(PypiReleasesFetcher, self).__init__(ecosystem)
     self._rpc = ServerProxy(self.ecosystem.fetch_url)
Esempio n. 46
0
 def participate_register(self):
     with ServerProxy(args.coordinator_uri, allow_none=True) as proxy:
         uri = 'http://' + self._ip + ':' + str(self._port)
         a = proxy.participate_register(uri)
Esempio n. 47
0
 def connectionServeur(self):
     serveur = ServerProxy(self.adresseServeur)
     return serveur
Esempio n. 48
0
def pull_server_logs(args):
    """Copy Bluetooth Protocol Viewer logs from auto-pts servers.
    :param server_addr: list of servers addresses
    :param server_port: list of servers ports
    """
    logs_folder = 'tmp/' + args.workspace
    xml_folder = 'tmp/XMLs'
    shutil.rmtree(logs_folder, ignore_errors=True)
    shutil.rmtree(xml_folder, ignore_errors=True)
    Path(xml_folder).mkdir(parents=True, exist_ok=True)

    server_addr = args.ip_addr
    server_port = args.srv_port

    for i in range(len(server_addr)):
        if i != 0 and server_addr[i] in server_addr[0:i]:
            continue
        last_xml = ('', '')

        with ServerProxy(
                "http://{}:{}/".format(server_addr[i], server_port[i]),
                allow_none=True,
        ) as proxy:
            file_list = proxy.list_workspace_tree(args.workspace)
            if len(file_list) == 0:
                continue

            workspace_root = file_list.pop()
            while len(file_list) > 0:
                file_path = file_list.pop(0)
                xml_file_path = file_path
                try:
                    file_bin = proxy.copy_file(file_path)

                    if not os.path.splitext(file_path)[1] in ['.pts', '.pqw6']:
                        proxy.delete_file(file_path)

                    if file_bin is None:
                        continue

                    file_path = '/'.join([
                        logs_folder,
                        file_path[len(workspace_root) + 1:].replace('\\', '/')
                    ])
                    Path(os.path.dirname(file_path)).mkdir(parents=True,
                                                           exist_ok=True)

                    with open(file_path, 'wb') as handle:
                        handle.write(file_bin.data)

                    if file_path.endswith('.xml') and not 'tc_log' in file_path\
                            and b'Final Verdict:PASS' in file_bin.data:
                        (test_name, timestamp) = split_xml_filename(file_path)
                        if test_name in last_xml[0]:
                            if timestamp <= last_xml[1]:
                                continue
                            os.remove(last_xml[0])
                        xml_file_path = \
                            '/'.join([xml_folder,
                                      xml_file_path[
                                          xml_file_path.rfind('\\') + 1:]
                                      .replace('\\', '/')])
                        Path(os.path.dirname(xml_file_path)).mkdir(
                            parents=True, exist_ok=True)
                        with open(xml_file_path, 'wb') as handle:
                            handle.write(file_bin.data)
                        last_xml = (xml_file_path, timestamp)
                except BaseException as e:
                    logging.exception(e)

    return logs_folder, xml_folder
Esempio n. 49
0
from PyQt5.QtCore import *
from PyQt5.QtWidgets import QPushButton

from electrum_mac import bitcoin, util, keystore
from electrum_mac import transaction
from electrum_mac.plugins import BasePlugin, hook
from electrum_mac.i18n import _
from electrum_mac.wallet import Multisig_Wallet
from electrum_mac.util import bh2u, bfh

from electrum_mac_gui.qt.transaction_dialog import show_transaction

import sys
import traceback

server = ServerProxy('https://cosigner.electrum.org/', allow_none=True)


class Listener(util.DaemonThread):
    def __init__(self, parent):
        util.DaemonThread.__init__(self)
        self.daemon = True
        self.parent = parent
        self.received = set()
        self.keyhashes = []

    def set_keyhashes(self, keyhashes):
        self.keyhashes = keyhashes

    def clear(self, keyhash):
        server.delete(keyhash)
Esempio n. 50
0
	def __init__(self,clientName):
		Cmd.__init__(self)
		self.clientName=clientName
		self.proxy = ServerProxy(URL)  #连接自己启动的服务器
		self.host = clientName #已连接的对象默认为自己
		MyCmd.prompt = 'Alex_p2p@' + self.host + '>' 
Esempio n. 51
0
        #get the biggest contour
        c = max(cnts, key=cv2.contourArea)

        #and find the center of it
        M = cv2.moments(c)
        cX = int(M["m10"] / M["m00"])
        cY = int(M["m01"] / M["m00"])
        return cX, cY
    #no neopixel found, so return -1, -1 to show this
    return -1, -1


cam = Camera()

#connect to the RasPi connected to the tree
proxy = ServerProxy("http://stairlights.local:8000", allow_none=True)

#turn all the lights off
proxy.clear()

#make the images consistent
time.sleep(2)
settings = cam.get_exposure()
cam.set_exposure(*settings)
time.sleep(1)

#get our image with no lights on
base = cam.get_image()
for i in range(100):
    proxy.light_one(i)
    image = cam.get_image()
Esempio n. 52
0
class MyCmd(Cmd):
	prompt = 'Alex_p2p>'

	def __init__(self,clientName):
		Cmd.__init__(self)
		self.clientName=clientName
		self.proxy = ServerProxy(URL)  #连接自己启动的服务器
		self.host = clientName #已连接的对象默认为自己
		MyCmd.prompt = 'Alex_p2p@' + self.host + '>' 


	def do_fetch(self,arg):
		args = arg.split(" ")
		fromW,filename = args[0],args[1] 
		try:
			if  not isfile(join(self.clientName,filename)):
				self.proxy.getFileFromOther(fromW,self.clientName,filename)
				print("From ",fromW,":",filename," start getting file.....")
				self.proxy.setSessionState(self.clientName,"fileFetch","0") 
				i=0
				while not isfile(join(self.clientName,filename)):
					
					state = self.proxy.getSessionState(self.clientName,"fileFetch")
					if state == "fail":
						sleep(4)
						return
					sleep(1)
					i+=1
					if i>20:
						print("time out")
						return
				print("From ",fromW,":",filename," checked successfully")
			else:
				print(filename," is existed!")

		except Fault as f:
			if f.faultCode != UNHANDLED: raise
			#print(f.faultCode)
			print("Couldn't find file:",arg)
		#finally:
		#	print("fail")

	def do_get(self,arg):
		filename = arg
		if self.host == self.clientName:
			print("use conn to set host firstly..")
		else:
			self.do_fetch(self.host + " " + filename)



	def do_test(self,arg,arg1='arg1'):
		print("arg:",arg,"arg1:",arg1)
			
	def do_cd(self,arg):
		#args = arg.split(" ")
		#clientName,dirName = args[0],args[1] 
		dirName = arg
		clientName = self.host
		#print(self.clientName,clientName,dirName)
		self.proxy.changeDir(self.clientName,clientName,dirName)
		print("Start to change ",clientName," dir to ",dirName,"...")
		sleep(4)
		self.do_getClient(clientName)

	def do_conn(self,host):
		if host.strip()=='':
			self.do_getCl("")
			return
		cl = self.proxy.getClientList()
		if host in cl.keys():
			self.host = host
			print("已连接远程终端: " ,self.host)
			MyCmd.prompt = 'Alex_p2p@' + self.host + '>'
		else:
			print("远程客户端:{} 未注册到服务器".format(host))



	def do_getClient(self,clientName):
		c = self.proxy.getClient(clientName)
		print(clientName,":",c["absDir"],"@",c["dirName"],":")
		for f in c["fileList"]:
			print(f)

	def do_getCl(self,args):
		cl = self.proxy.getClientList()
		for c in cl.keys():
			print(c)


	def do_getHost(self,args):
		self.do_getClient(self.host)
		c = self.proxy.getClient(self.host)

	do_dir = do_getHost

	def do_exit(self,arg):
		print()
		sys.exit()

	do_EOF = do_exit
Esempio n. 53
0
 def __init__(self):
     self.backend_server = ServerProxy(BACKEND_SUPERVISOR_URI)
     if MON_SUPERVISOR_URI:
         self.mon_server = ServerProxy(MON_SUPERVISOR_URI)
     else:
         self.mon_server = None
from datetime import datetime
from xmlrpc.client import ServerProxy

proxy = ServerProxy('http://localhost:8000/')

# 登録されているメソッド名を取得
print(proxy.system.listMethods())
# それぞれを取得
print(proxy.is_alive())
print(proxy.hello('World'))
nowtime = datetime.strptime(proxy.nowtime().value, '%Y%m%dT%H:%M:%S')
print(nowtime.strftime('%Y/%m/%d %H:%M:%S'))
Esempio n. 55
0
def report():
    subject = u"【测试报告】easyhttpbenchmark性能测试报告"
    # if(len(sys.argv) != 4):
    #     print("""======================================================================================
    #     |                              Usage Instructions                                    |
    #     ======================================================================================""")
    #     print("""|  usage              : ./easystatclient from_mail_addr to_mail_addr mail_server""")
    #     print("""|  example            : ./easystatclient [email protected] [email protected] mail2-in.baidu.com""")
    #     print("""======================================================================================""")
    #     sys.exit()
    from_mail_addr = ""
    to_mail_addr = ""
    mail_server = ""

    import json
    # cfg_json=json.load(open("./conf/easyhttpbenchmark.conf", "r"),encoding='utf-8')
    stat_rpc_server = options.stat_rpc_server
    stat_rpc_port = options.stat_rpc_port
    svr = ServerProxy("http://" + stat_rpc_server + ":" + stat_rpc_port)
    print(
        """======================================================================================
    |                                 TEST REPORT                                        |
    ======================================================================================"""
    )
    print("""|  client_num              : """ + str(svr.ret_clientnum()))
    print("""|  maxconnectoin           : """ + str(svr.ret_maxclientnum()))
    print(
        """|-------------------------------------------------------------------------------------"""
    )

    print("""|  test_time(min)          : """ + str(svr.get_test_time()))
    print("""|  total_req_cnt           : """ + str(svr.ret_total_req_cnt()))
    print("""|  total_res_cnt           : """ + str(svr.ret_total_res_cnt()))
    print("""|  total_err_cnt           : """ + str(svr.ret_total_err_cnt()))
    print("""|  total_nul_cnt           : """ + str(svr.ret_total_nul_cnt()))
    print("""|  QPS(query per second)   : """ + str("%0.2f" % svr.ret_qps()))
    print(
        """|-------------------------------------------------------------------------------------"""
    )

    print("""|  avg_res_time(ms)        : """ +
          str("%0.2f" % svr.ret_avg_res_time()))
    print("""|  below_10(ms)            : """ + str(svr.ret_total_below_10()))
    print("""|  between_10_20(ms)       : """ +
          str(svr.ret_total_between_10_20()))
    print("""|  between_20_30(ms)       : """ +
          str(svr.ret_total_between_20_30()))
    print("""|  over_30(ms)             : """ + str(svr.ret_total_over_30()))
    print(
        """======================================================================================"""
    )

    try:
        content = u"<div style='color:black;text-align:center;display:block;font-size:20px;font-family:微软雅黑'>easyhttpbenchmark性能测试报告</div>"

        content += u"<div style='font-family:微软雅黑;font-size:12px;font-style:italic;text-align:center;'>"
        content += u"<a href='https://github.com/JunneYang/easyhttpbenchmark'>@easyBenchmarkTesttool</a> 2014"
        content += u"</div>"

        report = ""
        report += "======================================================================================<br/>"
        report += "|                                 TEST REPORT                                        |<br/>"
        report += "======================================================================================<br/>"
        report += "|  client_num              : " + str(
            svr.ret_clientnum()) + "<br/>"
        report += "|  maxconnectoin           : " + str(
            svr.ret_maxclientnum()) + "<br/>"
        report += "|-------------------------------------------------------------------------------------<br/>"
        report += "|  test_time(min)          : " + str(
            svr.get_test_time()) + "<br/>"
        report += "|  total_req_cnt           : " + str(
            svr.ret_total_req_cnt()) + "<br/>"
        report += "|  total_res_cnt           : " + str(
            svr.ret_total_res_cnt()) + "<br/>"
        report += "|  total_err_cnt           : " + str(
            svr.ret_total_err_cnt()) + "<br/>"
        report += "|  total_nul_cnt           : " + str(
            svr.ret_total_nul_cnt()) + "<br/>"
        report += "|  QPS(query per second)   : " + str(
            "%0.2f" % svr.ret_qps()) + "<br/>"
        report += "|-------------------------------------------------------------------------------------<br/>"
        report += "|  avg_res_time(ms)        : " + str(
            "%0.2f" % svr.ret_avg_res_time()) + "<br/>"
        report += "|  below_10(ms)            : " + str(
            svr.ret_total_below_10()) + "<br/>"
        report += "|  between_10_20(ms)       : " + str(
            svr.ret_total_between_10_20()) + "<br/>"
        report += "|  between_20_30(ms)       : " + str(
            svr.ret_total_between_20_30()) + "<br/>"
        report += "|  over_30(ms)             : " + str(
            svr.ret_total_over_30()) + "<br/>"
        report += "======================================================================================<br/>"
        #report = report.replace(" ","&nbsp;")
        content += report
        print(content)
        #img_file = u"./img/imgtest.png"
        img_file = None
        #content += u"<p><img src='cid:"+img_file+"' alt='"+img_file+"' /></p>"
        '''from_mail_addr = u"*****@*****.**"
            to_mail_addr = u"*****@*****.**"
            mail_server = u"mail2-in.baidu.com"'''

        # email.mail_send(subject,content,img_file,from_mail_addr,to_mail_addr,mail_server)
    except Exception as e:
        pass

    try:
        svr.shutdown()
        svr.shutdown()
    except:
        pass
class VentanaCliente(QtGui.QMainWindow):
    def __init__(self):
        '''
        Constructor de la ventana principal del cliente, misma
        que se encarga de estar haciendo peticiones al servidor
        xmlrpc para conocer el estado actual del juego de snake.
        '''
        super(VentanaCliente, self).__init__()
        uic.loadUi('cliente.ui',
                   self)  #Cargamos la interfaz creada con QtDesigner.
        self.expandir_cuadros_tabla(
        )  #Hacemos que las columnas y filas siempre llenen todo el widget y sean proporcionales en cuanto a tamaño.
        self.pushButton.clicked.connect(
            self.manejo_servidor)  #Asociando los botones con las funciones.
        self.pushButton_2.clicked.connect(self.participar_juego)
        self.pushButton_2.clicked.connect(self.reiniciar)
        self.id_usuario = 0  #Tenemos una variable para el id del usuario que luego se verá modificada.
        self.direccion = 2  #Y una dirección por defecto en la que se moverá su serpiente.
        self.label_5.setStyleSheet("QLabel { color : #F4D442; }")
        self.tableWidget.setSelectionMode(
            QtGui.QTableWidget.NoSelection
        )  #Para que no se resalten las celdas al darles click.
        self.creado_usuario = False  #Bandera que indica si el usuario ya está jugando.
        self.doomed = False  #Y si su serpiente ya murió.
        self.intervalo_server = 0  #El intervalo (ms) en el que se está actualizando el servidor-
        self.timer = QtCore.QTimer(self)
        self.timer.timeout.connect(
            self.poner_tabla_bien
        )  #Conectando el QTimer con las funciones que se tienen que esar constantemente ejecutando.
        self.timer.timeout.connect(self.comenzar_juego)
        self.timer.timeout.connect(self.actualizar_timer_interval)
        self.timer.timeout.connect(self.actualizar_highscore)
        self.timer.start(self.intervalo_server)
        self.show()  #Mostrando la ventana y todo su contenido.
        self.server = None

    def poner_tabla_bien(self):
        '''
        Se encarga de que el número de filas y columnas que hay en la tabla 
        del servidor sean exactamente las mismas que las que se despliegan en 
        la tabla del UI del cliente.
        '''
        if self.creado_usuario:
            #La información se obtiene del diccionario que devuelve la función del servidor.
            game = self.server.estado_del_juego()
            self.tableWidget.setRowCount(game["tamY"])
            self.tableWidget.setColumnCount(game["tamX"])
            self.llenar_tabla(
            )  #Se crean los items para poder colorearlos en la tabla.

    def actualizar_highscore(self):
        '''
        Constantemente está viendo cuál es el highscore del juego --
        la serpiente que más ha comido-- para poder mostrarlo en el lcdNumber
        del UI. Para poder conocer el highscore del juego, tuve que registrar otra
        función al servidor dado que esta información ya era conocida por éste.
        '''
        if self.creado_usuario:
            high = self.server.highscore_game()
            self.lcdNumber.display(high)  #Mostrando el highscore.

    def llenar_tabla(self):
        '''
        Se encaga de colorear adecuadamente la tabla, poniendo la comida 
        en las celdas que debe ir y pintando las demás del color del fondo.
        '''
        guisantes = self.server.posiciones_de_guisantes(
        )  #Tuve que registrar otra función al servidor para poder regresar este diccionario de posiciones que ya tenía en servidor.py.
        for i in range(self.tableWidget.rowCount()):
            for j in range(self.tableWidget.columnCount()):
                self.tableWidget.setItem(i, j, QtGui.QTableWidgetItem(
                ))  #Si le corresponde la celda a un guisante,
                if [i, j] in guisantes:
                    self.tableWidget.item(i, j).setBackground(
                        QtGui.QColor(64, 244, 167))  #Se pone del color verde.
                else:
                    self.tableWidget.item(i, j).setBackground(
                        QtGui.QColor(82, 135, 135)
                    )  #Si no, es parte del fondo y se pinta del otro color.

    def comenzar_juego(self):
        '''
        Se encarga de estar actualizando la partida.
        '''
        if self.creado_usuario:
            if self.ha_muerto():
                #Muestra un mensaje si la serpiente del cliente ya no existe (chocó consigo misma o con otra víbora).
                self.lineEdit.setText("¡MORISTE!")
            self.llenar_tabla(
            )  #Se tiene que estar llenando la tabla como debe ir.
            self.tableWidget.installEventFilter(
                self
            )  #Asociando la tabla con el eventfilter para poder detectar las flechas del teclado.
            diccionario = self.server.estado_del_juego()
            lista_viboras = diccionario["viboras"]
            for vibora in lista_viboras:
                lista_camino = vibora["camino"]
                colores = vibora["color"]
                self.dibuja_vibora(
                    lista_camino, colores
                )  #Se dibujan todas las víboras a partir del "camino" de las mismas.

    def actualizar_timer_interval(self):
        '''
        En caso de que el juego haya comenzado y se modifique la espera en el servidor,
        entonces tenemos que modificar el intervalo del timer del cliente
        para no estar preguntando más de lo debido por el estado del juego ya que 
        es innecesario.
        '''
        if self.creado_usuario:
            diccionario = self.server.estado_del_juego()
            intervalo = diccionario[
                "espera"]  #Se ve de cuánto es la espera del servidor.
            if self.intervalo_server != intervalo:
                self.intervalo_server = intervalo
                self.timer.setInterval(
                    self.intervalo_server
                )  #Y con base en ello se puede modificar, en caso de ser necesario, el intervalo del QTimer del cliente.

    '''
    def dibujar_guisantes(self):
        lista_guisantes = self.server.posiciones_de_guisantes()
        for x in lista_guisantes:
            print(x[0], x[1])
            self.tableWidget.item(x[0],x[1]).setBackground(QtGui.QColor(244,212,66)) #Finalmente, esta celda se pinta de un color distinto.
            '''

    def dibuja_vibora(self, lista_camino, colores):
        '''
        Se encarga de dibujar una víbora en la tabla del cliente a través de 
        su color (RGB) y la lista de tuplas que representa las celdas que ocupa en 
        cada momento.
        '''
        for tupla in lista_camino:
            self.tableWidget.item(tupla[0], tupla[1]).setBackground(
                QtGui.QColor(colores['r'], colores['g'], colores['b']))

    def manejo_servidor(self):
        '''
        Función que debuggea la conexión con el servidor a través del botón de 
        Ping.
        '''
        self.pushButton.setText(
            "Pinging...")  #Temporalmente se cambia el texto del botón.
        try:
            self.crea_servidor()  #Intenta crear el servidor.
            pong = self.server.ping(
            )  #Mandamos llamar a la función registrada en el servidor.
            self.pushButton.setText(
                "¡Pong!"
            )  #Y si todo funciona óptimamente, el texto del botón cambia.
        except:  #Si no se puede crear el servidor, el texto del botón debe ser otro.
            self.pushButton.setText("No PONG :(")

    def crea_servidor(self):
        '''
        Función que crea un servidor a partir de los valores que están en el LineEdit
        y en el SpinBox del UI.
        '''
        self.url = self.lineEdit_3.text(
        )  #Se extraen estos valores de la interfaz.
        self.port = self.spinBox.value()
        self.direccion = "http://" + self.url + ":" + str(
            self.port)  #Se almacena la dirección del servidor.
        self.server = ServerProxy(
            self.direccion
        )  #Y finalmente se manda crear el servidor con esta dirección.

    def participar_juego(self):
        '''
        Función que hace inicializa el juego para el cliente cuando éste presiona el botón de 
        Participar.
        '''
        try:
            self.crea_servidor()  #Se crea el servidor.
            informacion = self.server.yo_juego()
            self.lineEdit.setText(informacion["id"])
            self.id_usuario = informacion["id"]
            self.color = informacion["color"]
            self.red = self.color["r"]
            self.green = self.color["g"]
            self.blue = self.color["b"]
            #Se coloca el id del jugador y el color de la serpiente en los campos adecuados de la UI.
            self.lineEdit_2.setText("R:" + str(self.red) + " G:" +
                                    str(self.green) + " B:" + str(self.blue))
            #Para hacer más fácil el reconocimiento del color del jugador, el fondo del LineEdit del color se cambia justo a ese color.
            self.lineEdit_2.setStyleSheet('QLineEdit {background-color: rgb(' +
                                          str(self.red) + ',' +
                                          str(self.green) + ',' +
                                          str(self.blue) + ');}')
            self.creado_usuario = True  #El usuario ya fue creado-
        except:  #Si ocurren anomalías, se le notifica al usuario.
            self.lineEdit.setText("Conexión fallida: servidor inalcanzable.")
            self.lineEdit_2.setText(
                "Verifica que el URL y puerto sean correctos.")

    def ha_muerto(self):
        '''
        Verifica si la serpiente del jugador ya murió, ya sea porque 
        chocó consigo misma o con alguna otra serpiente. 
        '''
        diccionario = self.server.estado_del_juego()
        lista_serpientes = diccionario["viboras"]
        #Lo que se hace es comparar el id del cliente con el de todas las serpientes del juego para ver si coincide con alguna.
        for vibora in lista_serpientes:
            if vibora["id"] == self.id_usuario:
                return False
        self.doomed = True
        return True  #Si no coincide con ninguna, es porque su serpiente ya no existe, i.e., murió.

    def reiniciar(self):
        '''
        Función que se encarga de reiniciar el juego para el cliente, esto es, 
        crear una nueva serpiente asociada a él cuando ya había muerto 
        para seguir jugando.
        '''
        if self.doomed:
            self.doomed = False  #Decimos que el jugador no ha muerto.
            self.lineEdit.setText("")  #Reiniciamos el texto de los LineEdits.
            self.lineEdit.setText("")
            self.participar_juego(
            )  #Creamos una nueva serpiente para el jugador.
            self.timer.start()  #Iniciamos el timer.
            self.comenzar_juego(
            )  #Y comenzamos el juego llenando la tabla con la nueva serpiente, etc.

    def expandir_cuadros_tabla(self):
        '''
        Función encargada de lograr que las celdas del TableWidget de expandan
        dinámicamente para ajustarse a las dimensiones del mismo sin importar 
        que cambien las dimensiones de la ventana princiapal del cliente.
        Se especifica --para las filas y columnas-- que pueden expandirse para llenar
        el espacio del tableWidget y ésto lo hacen de forma uniforme considerando el tamaño
        total y el número de celdas para ajustar su tamaño. El tamaño mínimo
        de los encabezados respectivos fue establecido para que tuviera como mínimo un pixel.
        '''
        self.tableWidget.horizontalHeader().setResizeMode(
            QtGui.QHeaderView.Stretch)
        self.tableWidget.verticalHeader().setResizeMode(
            QtGui.QHeaderView.Stretch)

    def eventFilter(self, source, event):
        '''
        Permite detectar si el cliente presiona las teclas de flechas para 
        intentar mover a su víbora. Este escucha depende de la flecha que se presione
        para poder validar el movimiento de la serpiente como se hizo en el caso 
        del servidor, esto es, por ejemplo una serpiente no puede moverse hacia arriba
        si actualmente se mueve hacia abajo.
        '''
        if (event.type() == QtCore.QEvent.KeyPress
                and source is self.tableWidget):
            key = event.key()
            if (key == QtCore.Qt.Key_Up and source is self.tableWidget):
                if self.direccion != 2:
                    self.direccion = 0
            elif (key == QtCore.Qt.Key_Down and source is self.tableWidget):
                if self.direccion != 0:
                    self.direccion = 2
            elif (key == QtCore.Qt.Key_Right and source is self.tableWidget):
                if self.direccion != 3:
                    self.direccion = 1
            elif (key == QtCore.Qt.Key_Left and source is self.tableWidget):
                if self.direccion != 1:
                    self.direccion = 3
            #Al final de todo, solamente tenemos que mover a la serpiente del usuario a través de su identificador empleando la función registrada en el servidor.
            self.server.cambia_direccion(self.id_usuario, self.direccion)
        return QtGui.QMainWindow.eventFilter(
            self, source, event)  #Requiere un regreso la función.
Esempio n. 57
0
#Client RPC
from xmlrpc.client import ServerProxy # RPC do Python usa HTTP como protocolo de transporte
cliente = ServerProxy('http://localhost:20064', allow_none=True) # criar uma instância cliente localhost e na porta do servidor
while True:
    nome = input("Digite o nome para receber o número \n")
    cliente.nome(nome) # chama a função que está implementada do lado do servidor
Esempio n. 58
0
 def search(self, url):
     '''
     
     '''
     client = ServerProxy(url)
     return client.handle(self.file_name)
Esempio n. 59
0
class Controleur():
    def __init__(self):
        #Debug: Ouvre automatiquement le Serveur Controleur
        pid1 = Popen(
            ["C:\\Python34\\Python.exe", "../Serveur/Serveur_controleur.py"],
            cwd='../Serveur',
            shell=1).pid
        pid2 = Popen([
            "C:\\Python34\\Python.exe",
            "../SQL Serveur/ServeurBD_controleur.py"
        ],
                     cwd='../SQL Serveur',
                     shell=1).pid

        self.clientIP = self.chercherIP()
        #IP Saas
        self.saasIP = self.clientIP
        self.serveur = None
        self.log = Log(self, self.clientIP)  #,self.serveur)
        #string utilisateur et organisation
        self.utilisateur = "None"
        self.organisation = None
        self.idOrga = None
        self.utilisateurId = None
        #id du projet selectionne
        self.idProjet = None
        self.vue = Vue(self, self.clientIP)

        self.vue.root.mainloop()

    def chargerProjet(self, nomprojet):
        idProjet = self.serveur.chargerProjet(nomprojet, self.idOrga)
        self.idProjet = idProjet
        self.log.writeLog("Projet ID: " + str(idProjet), "PE0")
        return idProjet

    #trouve l'IP du client
    def chercherIP(self):
        clientIP = socket.gethostbyname(socket.gethostname())
        return clientIP

    def fermerApplication(self):
        if self.serveur:
            self.log.writeLog("Fermeture du Client", "L03")
            self.serveur.fermeture(self.utilisateurId)
        self.vue.root.destroy()

    def logInClient(self, pIdentifiantNomUsager, pIdentifiantNomOrga,
                    pIdentifiantMotDePasse):
        #Vérification des informations avant l'envoi au serveur
        if (pIdentifiantNomOrga != "" and pIdentifiantNomUsager != ""
                and pIdentifiantMotDePasse != ""):
            #connection au Serveur
            ad = "http://" + self.saasIP + ":9999"
            self.serveur = ServerProxy(ad, allow_none=1)
            #Needs those Var for LOGS
            self.log.setLog(
                pIdentifiantNomOrga,
                pIdentifiantNomUsager,
            )
            reponseServeur = self.serveur.logInServeur(self.clientIP,
                                                       pIdentifiantNomUsager,
                                                       pIdentifiantNomOrga,
                                                       pIdentifiantMotDePasse)

            if (reponseServeur == 0):
                self.log.writeLog("Login Fail")
                self.vue.logInClientFail(0)
            elif reponseServeur == "Simulation deja en cours":
                self.log.writeLog("Tentative de connexions multiple")
                self.vue.logInClientFail(1)
            else:
                self.utilisateurId = reponseServeur[0][0]
                self.utilisateur = pIdentifiantNomUsager
                self.organisation = pIdentifiantNomOrga
                self.log.writeLog("Login Successful", "L00")
                self.idOrga = reponseServeur[1]
                self.vue.chargerCentral(reponseServeur[0][1],
                                        reponseServeur[0][2],
                                        reponseServeur[0][3],
                                        reponseServeur[0][4])
        else:
            self.vue.logInClientFail(2)

    def creerProjet(self, nom):

        self.serveur.insertionSQL("Projets",
                                  "'" + str(self.idOrga) + "','" + nom + "'")

    def requeteModule(self, mod):

        rep = self.serveur.requeteModule(mod)
        if rep:
            cwd = os.getcwd()
            lieuApp = "/" + rep[0]
            lieu = cwd + lieuApp
            if not os.path.exists(lieu):
                os.mkdir(lieu)  #plante s'il existe deja
            reso = rep[1]
            for i in rep[2]:
                if i[0] == "fichier":
                    nom = reso + i[1]
                    rep = self.serveur.requeteFichier(nom)
                    fiche = open(lieu + "/" + i[1], "wb")
                    fiche.write(rep.data)
                    fiche.close()
            chaineappli = "." + lieuApp + lieuApp + ".py"
            #Arguments####################################################################################
            # self.saasIP=      sys.argv[1]
            # self.utilisateur= sys.argv[2]
            # self.organisation=sys.argv[3]
            # self.idProjet=    sys.argv[4]
            # self.clientIP=    sys.argv[5]
            ############################################################
            #argumentsServeur=[self.saasIP," ",self.utilisateur,self.organisation,self.idProjet]

            #Ouvre le programme telecharge
            pid = Popen([
                "C:\\Python34\\Python.exe", chaineappli, self.saasIP,
                self.utilisateur, self.organisation, self.idProjet,
                self.clientIP
            ],
                        shell=1).pid
            #pid = Popen(["C:\\Python34\\Python.exe", chaineappli,argumentsServeur],shell=1).pid
            #pid = Popen(["C:\\Python34\\Python.exe", chaineappli],shell=1).pid
        else:
            messagebox.showinfo("Erreur", "Il n'y a pas de connexion")

    def requeteOutil(self, mod):
        rep = self.serveur.requeteOutil(mod)
        if rep:
            cwd = os.getcwd()
            lieuApp = "/" + rep[0]
            lieu = cwd + lieuApp
            if not os.path.exists(lieu):
                os.mkdir(lieu)  #plante s'il exist deja
            reso = rep[1]
            for i in rep[2]:
                if i[0] == "fichier":
                    nom = reso + i[1]
                    rep = self.serveur.requeteFichier(nom)
                    fiche = open(lieu + "/" + i[1], "wb")
                    fiche.write(rep.data)
                    fiche.close()
            chaineappli = "." + lieuApp + lieuApp + ".py"
            pid = Popen([
                "C:\\Python34\\Python.exe", chaineappli, self.saasIP,
                self.utilisateur, self.organisation, self.clientIP
            ],
                        shell=1).pid
        else:
            messagebox.showinfo("Erreur", "Il n'y a pas de connexion")
    def conexion(self):
        url = self.url.text()
        puerto = self.puerto.value()

        self.servidor = ServerProxy("http://" + url + ":" + str(puerto))