Beispiel #1
0
def request_authorization(target_identity, requesting_identity, requesting_token, request_message, request_query=None):
    """
    Called by other people who wish to connect with me.
    """
    library = Library.objects.get(identity=target_identity)
    Connection.create_pending_connection(library, requesting_identity, requesting_token, request_message, request_query)
    return "OK"
Beispiel #2
0
 def __connect(self, server):
     connection = Connection(server)
     connected = connection.connect()
     if connected:
         self.connection_manager.register(connection)
     
     return connected
Beispiel #3
0
 def testOpenRaisesNetworkExceptionOnAlreadyOpenConnection(self):
     context = ssl.SSLContext(ssl.PROTOCOL_TLS)
     mysocket = context.wrap_socket(
         socket(AF_INET, SOCK_STREAM),
         server_hostname=self.config["server"]["hostname"])
     con = Connection(self.config["server"]["ip"],
                      self.config["server"]["port"], mysocket)
     with self.assertRaises(NetworkException):
         con.open()
 def __init__(self):
     """Create ServerAPI object."""
     with open(os.path.join("..", "config", "config.json")) as config_file:
         config = json.load(config_file)
     self.con = Connection(config["server"]["ip"], config["server"]["port"])
     self.con2 = Connection(config["server"]["ip"],
                            config["server"]["port"])
     logger = Logger("client.log", "Client", config["logging"]["log_level"])
     self._log = logger.get_logger()
     self.id = None
     self._game_state = None
Beispiel #5
0
    def __init__(self):
        """
        Init the (boto) SNS connection and prepare the cloudwatch topic
        """

        self.conn = Connection().sns_connection()

        # Create the cloudwatch topic if not exists, and store its ARN
        self.cloudwatch_arn = self._create_topic_if_not_exists(self.CLOUDWATCH_TOPIC)

        # If there are no subscriptions, subscribe the default email
        if not len(self.get_cloudwatch_email_subscriptions()):
            self.subscribe_email_to_cloudwatch(Connection().DEFAULT_ALERT_EMAIL)
class Game(object):
    def __init__(self):
        self.c = Connection()
        self.game = self.c.get_game()

    def start(self):
        print "-=" * 20
        print "GAME START"
        response = None
        while not response or not response.get("alive"):
            response = self.c.submit_move(
                move_distance=0, shot_angle=random.randrange(-90, 90), shot_power=random.randrange(1, 100)
            )
            print "-=" * 20
            print response
Beispiel #7
0
def Connect(*args, **kwargs):
    """
    Connect to the database; see connections.Connection.__init__() for
    more information.
    """
    from connections import Connection
    return Connection(*args, **kwargs)
Beispiel #8
0
 def testConnectionMatchesPassedInConnection(self):
     context = ssl.SSLContext(ssl.PROTOCOL_TLS)
     mysocket = context.wrap_socket(
         socket(AF_INET, SOCK_STREAM),
         server_hostname=self.config["server"]["hostname"])
     con = Connection(self.config["server"]["ip"],
                      self.config["server"]["port"], mysocket)
     self.assertEqual(con._socket, mysocket)
Beispiel #9
0
 def load_connections(self):
     # Read excel file and create a list with connection objects
     with open('ConnectiesHolland.csv') as csv_file:
         csv_reader = csv.reader(csv_file, delimiter=',')
     
         connections = []
         for row in csv_reader:
             connections.append(Connection(row[0], row[1], row[2], False)) 
         return connections
Beispiel #10
0
def process_event(e):
    apply_graph_change(e)

    # add one connection to open_connections or close the connection
    if e.is_opening():
        c = Connection(e)
        open_connections.append(c)
        created_connections.append(c)
    else:
        # it is a connection closing event
        close_connection(e)
Beispiel #11
0
def getGeoGraph():
    G = nx.soft_random_geometric_graph(5000, 0.07)

    neurons = {}
    for i in range(len(G.nodes)):
        x, y = G.node[i]['pos']
        neurons[i] = Node([])
        neurons[i].runActiv = 0
    neurons[250].runActiv = 10
    nx.set_node_attributes(G, neurons, 'node')
    densities = {}
    for edge in G.edges:
        density = random.gauss(0.5, 0.3)
        while density < 0 or density > 1:
            density = random.gauss(0.5, 0.3)
        densities[edge] = density
        neurons[edge[0]].addConnection(Connection(neurons[edge[1]], density))
        neurons[edge[1]].addConnection(Connection(neurons[edge[0]], density))

    nx.set_edge_attributes(G, densities, 'density')
    print(G.nodes(data=True))

    return G
Beispiel #12
0
    def try_to_make_connection(self):
        if self.connection_starter and self.connection_ender and \
                self.connection_starter.conn_type == self.connection_ender.conn_type and \
                self.connection_starter.parent is not self.connection_ender.parent:

            for conn in self.connections:
                if conn.input == self.connection_starter and conn.output == self.connection_ender:
                    break
            else:
                self.connections.append(
                    Connection(self.connection_starter, self.connection_ender,
                               self.connection_ender.conn_type))

            self.connection_starter = None
            self.connection_ender = None
Beispiel #13
0
 def handler(self):
     """Handle incoming tcp connections passing to new thread."""
     while not self._stop_flag:
         try:
             self._socket.settimeout(0.2)
             conn, addr = self._socket.accept()
             conn = self._context.wrap_socket(conn, server_side=True)
         except ssl.SSLEOFError as e:
             self._log.error("Run-time error: %s" % e)
             pass
         except timeout:
             pass
         except Exception as e:
             self._log.error("Run-time error: %s" % e)
             pass
         else:
             client_conn = Connection(addr[0], addr[1], connection=conn)
             thread = threading.Thread(name="worker",
                                       target=self._function,
                                       daemon=True,
                                       args=(client_conn,))
             thread.start()
             self._threads.append(thread)
Beispiel #14
0
def build_db(build_name,
             credentials_file_location='config.ini',
             build_settings_file_location='settings.json'):
    with open(build_settings_file_location) as f:
        build_settings_list = json.load(f)
    build_settings = [
        d for d in build_settings_list if d['build_name'] == build_name
    ][0]
    connection_name = build_settings['connection_name']

    if not build_settings:
        logging.error(
            f'Provided build_name not found in {build_settings_file_location}')
        raise Exception(
            f'Provided build_name not found in {build_settings_file_location}')

    connection = Connection(connection_name, credentials_file_location)

    execute_raw_sql_from_settings_dict(connection, build_settings)
    execute_sql_file_list_from_settings_dict(connection, build_settings)
    execute_stored_procedure_list_from_settings_dict(connection,
                                                     build_settings)

    return f'Database built for connection {connection_name}.'
Beispiel #15
0
 def testPortMatchesPassedInPort(self):
     con = Connection(self.config["server"]["ip"],
                      self.config["server"]["port"])
     self.assertEqual(con._port, self.config["server"]["port"])
Beispiel #16
0
def Connect(*args, **kwargs):
    """Factory function for connections.Connection."""
    from connections import Connection
    return Connection(*args, **kwargs)
Beispiel #17
0
 def __init__(self):
     self.c = Connection()
     self.game = self.c.get_game()
Beispiel #18
0
 def testSendingOverClosedConnectionRaisesNetworkException(self):
     con = Connection(self.config["server"]["ip"],
                      self.config["server"]["port"])
     with self.assertRaises(NetworkException):
         con.send("Hello world")
Beispiel #19
0
                if len(line) > 0 and line[0] == 'x':
                    coordinates = line.split(" ")
                    x = int(coordinates[0][2:])
                    y = int(coordinates[1][2:])
                    z = int(coordinates[2][2:])
                    tags_coords[tag] = (x, y, z)
    return (tags_coords[0][0], tags_coords[0][1], tags_coords[0][2])


def back_platform(port):
    a = input()
    port.send(-1000, -1000, -1000, -1000)


if __name__ == "__main__":
    with Connection(UNO) as uno:
        time.sleep(2)
        T = 0.01
        F = np.array([[1, -T], [0, 1]], dtype=float)  # матрица перехода
        H = np.array([[0], [T]], dtype=float)
        C = np.array([1, 0], dtype=float)  # матрица-строка связи
        K = np.empty((1, 2), dtype=float)
        M_waited = np.empty((2, 2), dtype=float)
        R = 0.2**2
        Q = 0.01**2  # ???
        ONE_STEP = 0.1
        V_step = 1000
        V = V_step * 0.058  # сами задаём скорость в мм / c (перевести из щагов в мм)

        sum = 0
        k = 0
Beispiel #20
0
 def testRecvOverClosedConnectionRaisesNetworkException(self):
     con = Connection(self.config["server"]["ip"],
                      self.config["server"]["port"])
     with self.assertRaises(NetworkException):
         con.recv()
Beispiel #21
0
def main():
    """\internal
    \brief Parse command line options and start the server.
    """
    global server, domain_server, node_id, neighbours, local_ts, options

    options = getOptions()

    if not options.daemon:
        import subprocess
        subprocess.Popen("linda_monitor", shell=True)
        #pid = os.fork()
        #if pid != 0:
        #    from monitor import monitor
        #    return monitor.Thread(options.port).run()

    _linda_server.init()

    if options.peer:
        options.peer.append("127.0.0.1")  # always allow local connections.

    def lookupname(addr):
        try:
            addr, r = addr.split("/")
        except ValueError:
            r = "32"

        addr = socket.gethostbyname(addr)
        if addr.count(".") != 3:
            print "%s is not in n.n.n.n[/r] format" % (addr + "/" + r)
            sys.exit(0)
        return addr + "/" + r

    node_id = "N" + guid.generate()
    _linda_server.setnodeid(node_id)

    if options.mdns and not options.disable_mdns:
        import mdns
        s = mdns.connect()
        if s:
            options.connect = s[0]
            options.connectport = s[1]

    if options.connect is not None and len(options.connect) > 0:
        if options.connectport:
            con = zip(options.connect, options.connectport) + [
                (x, 2102) for x in options.connect[len(options.connectport):]
            ]
        else:
            con = zip(options.connect, [2102 for _ in options.connect])
        assert len(con) == len(options.connect)
        i = 0
        while True:
            svr, port = con[i]
            s = _linda_server.connect("%s:%s" % (svr, port))
            if s is None:
                if i < len(con) - 1:
                    i += 1
                    continue
                else:
                    print "Unable to connect to server %s:%i." % (svr, port)
                    sys.exit(-1)

            s = Connection(s)
            s.type = None

            s.send(None, (get_node_id, ))
            node = s.recv()[2]
            assert utils.isNodeId(node), repr(node)

            s.send(None, (my_name_is, node_id))
            s.recv()
            s.type = "SERVER"

            s.name = node
            neighbours[node] = s
            connections.sockets.append(s)
            break

    local_ts.newTupleSpace("UTS")

    while True:
        try:
            socket_watcher()
        except KeyboardInterrupt:
            cleanShutdown()
            raise
        break
Beispiel #22
0
 def testCloseRaisesNetworkExceptionOnAlreadyClosedConnection(self):
     con = Connection(self.config["server"]["ip"],
                      self.config["server"]["port"])
     with self.assertRaises(NetworkException):
         con.close()
            home.allCommandList()
            allActions()
        else:
            opera.delete()

    def deleteAll(self):
        confirm = input('Confirm delete all data!')
        if (confirm == 'y' or confirm == 'Y'):
            deleted = mycon.deleteData()
            if deleted:
                print('Deleted successfully', deleted)
            print('Wait for Home')
            sleep(2)
            system('cls')
            home.allCommandList()
            allActions()
        else:
            system('cls')
            home.allCommandList()
            allActions()


#-------------Connection Methods ----------------
mycon = Connection()
opera = Operations()
mycon.myDB()
home = Home()
home.allCommandList()
allActions()
#-------------Operations Methods ----------------
Beispiel #24
0
def main():
    """\internal
    \brief Parse command line options and start the server.
    """
    global server, domain_server, node_id, neighbours, local_ts, options

    options = getOptions()

    if not options.daemon:
        import subprocess
        subprocess.Popen("linda_monitor", shell=True)
        #pid = os.fork()
        #if pid != 0:
        #    from monitor import monitor
        #    return monitor.Thread(options.port).run()

    _linda_server.init()

    if options.peer:
        options.peer.append("127.0.0.1") # always allow local connections.

    def lookupname(addr):
        try:
            addr,r = addr.split("/")
        except ValueError:
            r = "32"

        addr = socket.gethostbyname(addr)
        if addr.count(".") != 3:
            print "%s is not in n.n.n.n[/r] format" % (addr+"/"+r)
            sys.exit(0)
        return addr+"/"+r

    node_id = "N"+guid.generate()
    _linda_server.setnodeid(node_id)

    if options.mdns and not options.disable_mdns:
        import mdns
        s = mdns.connect()
        if s:
            options.connect = s[0]
            options.connectport = s[1]

    if options.connect is not None and len(options.connect) > 0:
        if options.connectport:
            con = zip(options.connect, options.connectport) + [(x, 2102) for x in options.connect[len(options.connectport):]]
        else:
            con = zip(options.connect, [2102 for _ in options.connect])
        assert len(con) == len(options.connect)
        i = 0
        while True:
            svr, port = con[i]
            s = _linda_server.connect("%s:%s" % (svr, port));
            if s is None:
                if i < len(con)-1:
                    i += 1
                    continue
                else:
                    print "Unable to connect to server %s:%i." % (svr, port)
                    sys.exit(-1)

            s = Connection(s)
            s.type = None

            s.send(None, (get_node_id, ))
            node = s.recv()[2]
            assert utils.isNodeId(node), repr(node)

            s.send(None, (my_name_is, node_id))
            s.recv()
            s.type = "SERVER"

            s.name = node
            neighbours[node] = s
            connections.sockets.append(s)
            break

    local_ts.newTupleSpace("UTS")

    while True:
        try:
            socket_watcher()
        except KeyboardInterrupt:
            cleanShutdown()
            raise
        break
Beispiel #25
0
 def __init__(self):
     """
     Create an storage instance with an OpenStack (Swift) storage connection
     """
     Storage.__init__(self, Connection().openstack_swift_connection())
Beispiel #26
0
class Sns:
    """
    Amazon Simple Notification Service

    This service provided by Amazon can be used as a message queue and notification service
    For our purposes, it will be used to send emails regarding CloudWatch alerts
    """

    # Topic name for cloudwatch alerts
    CLOUDWATCH_TOPIC = 'cloudwatch_alert'

    def __init__(self):
        """
        Init the (boto) SNS connection and prepare the cloudwatch topic
        """

        self.conn = Connection().sns_connection()

        # Create the cloudwatch topic if not exists, and store its ARN
        self.cloudwatch_arn = self._create_topic_if_not_exists(self.CLOUDWATCH_TOPIC)

        # If there are no subscriptions, subscribe the default email
        if not len(self.get_cloudwatch_email_subscriptions()):
            self.subscribe_email_to_cloudwatch(Connection().DEFAULT_ALERT_EMAIL)

    def _create_topic_if_not_exists(self, topic_name):
        """
        Create a topic if it does not exist

        :param topic_name: Topic name to create
        :return: Topic ARN
        """
        creation_result = self.conn.create_topic(topic_name)
        return creation_result['CreateTopicResponse']['CreateTopicResult']['TopicArn']

    def _get_subscriptions(self, topic_arn):
        """
        Get all the subscriptions given a topic arn
        :param topic_arn: ARN of the topic
        :return: Subscriptions of the topic
        """
        return self.conn.get_all_subscriptions_by_topic(topic_arn)['ListSubscriptionsByTopicResponse']['ListSubscriptionsByTopicResult']['Subscriptions']

    def _get_cloudwatch_subscriptions(self):
        """
        Get subscriptions of the cloudwatch topic

        :return: Subscriptions of the cloudwatch topic
        """
        return self._get_subscriptions(self.cloudwatch_arn)

    def get_cloudwatch_email_subscriptions(self):
        """
        Map the cloudwatch subscriptions to its emails

        :return: Emails subscribed to the cloudwatch topic
        """
        return map(lambda subscription: subscription['Endpoint'], self._get_cloudwatch_subscriptions())

    def subscribe_email_to_cloudwatch(self, email):
        """
        Subscribe an email to CloudWatch

        :param email: Email to subscribe
        """
        return self.conn.subscribe(self.cloudwatch_arn, 'email', email)

    def unsubscribe_all_emails_from_cloudwatch(self):
        """
        Ubsubscribe all the emails from CloudWatch
        """
        for subscription in self._get_cloudwatch_subscriptions():
            subscription_arn = subscription['SubscriptionArn']
            if not subscription_arn == 'PendingConfirmation':
                self.conn.unsubscribe(subscription_arn)

    def set_only_subscriber_to_cloudwatch(self, email):
        """
        Set an only subscribe to cloudwatch, this is, unsubscribing all the emails and registering the new one

        :param email: Email to subscribe
        :return: True if subscribed, false otherwise
        """
        # noinspection PyBroadException
        try:
            self.unsubscribe_all_emails_from_cloudwatch()
            self.subscribe_email_to_cloudwatch(email)
            return True
        except Exception:
            return False
Beispiel #27
0
 def __init__(self):
     """
     Create an storage instance passing an Amazon S3 connection
     """
     Storage.__init__(self, Connection().s3_connection())
Beispiel #28
0
 def testA(self):
     """Note that all test method names must begin with 'test.'"""
     con = Connection("127.0.0.1", 10000)
     con.open()
     con.send("Can you hear me?")
     con.close()
     con.open()
     con.send("Can you hear me now?")
     con.close()
     assert 5 == 5, "bar() not calculating values correctly"
Beispiel #29
0
    # calib = Calib((7, 5), camera, board, squareSize=33)
    # # calib.makeSamples()
    # calib.calibrate(loadPlane='laserPlane.npy')
    #
    # scanner = Scanner(camera, board, calib)
    # objectScan = None

    tower = Tower(car_x=start_car_pos[0],
                  car_y=start_car_pos[1],
                  car_z=start_car_pos[2],
                  car_e=start_car_pos[3],
                  step_length=2,
                  std_v=standart_v)
    # with Connection(MEGA) as mega, \
    #         Connection(UNO) as uno:
    with Connection(MEGA) as mega:
        """
            блок инициализации объектов
        """
        # navi = Navigation(uno, TAG_PORT)
        touch_probe = TouchProbe(mega, tower)
        heater = Heater(mega)
        table = TableCalibrate(mega, tower, touch_probe)
        edge_search = EdgeSearch(mega, tower, table)
        time.sleep(2)
        print('start')
        if (is_interactive):

            run_tests(mega, num_tests=1000)

        else:
def Connect(*args, **kwargs):
    from connections import Connection
    return Connection(*args, **kwargs)