def render_DELETE(self, request): connection_id = self.pop_connection_id() connection = Connection(self, request, connection_id) try: (channel_id, format) = connection.get_channel_id_and_format() except ValueError, e: return connection.error(-1, str(e))
def establish(self, timeout=None): """ Tries to establish a client connection. Args: timeout: the timeout in seconds Returns: True if the connection was established, and False if it wasn't. """ Connection.establish(self, timeout) # Create and configure the endpoint if (not self._useSSL) : endpoint = TCP4ClientEndpoint(reactor, self.__host, self._port, timeout, None) else : keyPath = self._certificatesDirectory + "/" + "server.key" certificatePath = self._certificatesDirectory + "/" + "server.crt" try : endpoint = SSL4ClientEndpoint(reactor, self.__host, self._port, ssl.DefaultOpenSSLContextFactory(keyPath, certificatePath), timeout) except Exception: raise ConnectionException("The key, the certificate or both were not found") # Establish the connection self._deferred = endpoint.connect(self._factory) self.__working = True def _handleError(error): self.__working = False self._setError(Connection._prettyPrintTwistedError(error)) def _handleConnection(error): self.__working = False self._deferred.addCallback(_handleConnection) self._deferred.addErrback(_handleError) # Wait until it's ready while(self.__working) : sleep(0.1) return self._error == None
def render_POST(self, request): connection_id = self.pop_connection_id() connection = Connection(self, request, connection_id) try: format = connection.get_format(self.config.clients_uri_path) except ValueError, e: return connection.error(-1, str(e))
class InfiniteQuestWindow(QMainWindow): # ---------------------------------------------------------------------- def __init__(self): """""" super(InfiniteQuestWindow, self).__init__() self.setWindowTitle("Infinite Quest") self.mapview = MapView() # self.mapview = QGraphicsView() # self.sc = MapScene() # self.mapview.setScene(self.sc) self.mapview.installEventFilter(self) self.setCentralWidget(self.mapview) self.minimap = MiniMapView(self.mapview) minimap_dw = QDockWidget() minimap_dw.setWidget(self.minimap) self.addDockWidget(Qt.LeftDockWidgetArea, minimap_dw) self.statushero = StatusHeroWidget() statushero_dw = QDockWidget() statushero_dw.setWidget(self.statushero) self.addDockWidget(Qt.LeftDockWidgetArea, statushero_dw) # self.mapview.setSizePolicy(QSizePolicy(QSizePolicy.MinimumExpanding,QSizePolicy.MinimumExpanding)) self.world = World() self.hero = Hero(self.world.map(), *self.world.map().find_passable_landscape_coords()) self.connection = Connection(self.hero, self.world) self.game_state_update() # ---------------------------------------------------------------------- def game_state_update(self): """""" st = self.connection.get_world_state() self.mapview.scene.mapstate_update(st["map_state"]) # ---------------------------------------------------------------------- def eventFilter(self, obj, ev): """""" if ev.type() == QEvent.KeyPress: try: self.connection.action( { Qt.Key_Up: "move_up", Qt.Key_Down: "move_down", Qt.Key_Right: "move_right", Qt.Key_Left: "move_left", }[ev.key()] ) self.game_state_update() return True except KeyError: pass else: pass return super(InfiniteQuestWindow, self).eventFilter(obj, ev)
def sync_description(self): """ Salva a descrição da coluna no banco de dados """ try: if self.description is not None: Connection.execute( u"""COMMENT ON COLUMN "{0}"."{1}"."{2}" IS %s""" .format(self.schema, self.table, self.name,), (self.description,) ) else: Connection.execute( u"""COMMENT ON COLUMN "{0}"."{1}"."{2}" IS NULL""" .format(self.schema, self.table, self.name,) ) except Exception, e: warnings.warn( "Erro ao sincronizar a coluna {0}.{1}.{2}: {3}" .format(self.schema, self.table, self.name, e), RuntimeWarning )
def get_new_con(self, server=None, port=None, auth=None, register_events=False, **kwargs): ''' Return a new esl connection to the specified FS server and optionally subscribe to any events actively handled by this listener Parameters ---------- server : string fs server ip port : string port to connect on auth : string authorization username register_events : bool indicates whether or not the connection should be subscribed to receive all default events declared by the listener's 'default_handlers' map kwargs : same as for .connection.Connection Returns ------- con : Connection ''' con = Connection(server or self.server, port or self.port, auth or self.auth, **kwargs) if register_events: con.subscribe(self._handlers) return con
def main(): server_port = 30000 client_port = 30001 protocol_id= 0x99887766 delta_time = 0.25 send_rate = 0.25 time_out = 10 connection = Connection(protocol_id, time_out) if not connection.start(server_port): print("Could not start connection on port {}".format(server_port)) return 1 connection.listen() while 1: if connection.is_connected(): print('server sending packet') packet = [c for c in "server to client"] connection.send_packet(packet) while 1: bytes_read, pack = connection.receive_packet(256) if bytes_read == 0: break print("Received packet from client") connection.update(delta_time) time.sleep(delta_time)
def main(): c = Connection("amihailov.pro", "/rtsup/api") succeed, employees = c.get_employee_list() if succeed: w = ExcelSaver() w.makeEmployeeList(employees) w.save("test.xls")
def establish(self, timeout): """ Establishes a server connection. Args: timeout: this parameter will be ignored. Returns: Nothing """ Connection.establish(self, timeout) # Create and configure the endpoint if (not self._useSSL) : endpoint = TCP4ServerEndpoint(reactor, self._port) else : keyPath = self._certificatesDirectory + "/" + "server.key" certificatePath = self._certificatesDirectory + "/" + "server.crt" try : endpoint = SSL4ServerEndpoint(reactor, self._port, ssl.DefaultOpenSSLContextFactory(keyPath, certificatePath)) except Exception: raise ConnectionException("The key, the certificate or both were not found") # Establish the connection def _registerListeningPort(port): self.__listenningPort = port def _onError(error): self._setError(Connection._prettyPrintTwistedError(error)) self._deferred = endpoint.listen(self._factory) # Configure the deferred object self._deferred.addCallback(_registerListeningPort) self._deferred.addErrback(_onError)
def on_message(self, message): if not message: return # print(message) if message == "request_code": letters = [b for b in [random.choice(string.ascii_uppercase) for a in range(5)]] code = "" for letter in letters: code += letter self.ws.send("code %s" % code) elif message[:6] == "hello ": command, session, role = message.split() session = session.upper() con = Connection.get_connection(session) if role == "controller": if con.connected("display"): con.connect(role, self.ws) con.display.send("controller_connected") con.controller.send("connect_succesful") else: self.ws.send("connect_failed") elif role == "display": con.connect(role, self.ws) else: print("Error: unknown role: %s" % role) else: con = Connection.get_connection_ws(self.ws) destination_ws = con.another_ws(self.ws) if destination_ws is not None: destination_ws.send(message)
def dialog_handler(ns): """Show the dialog window.""" verb = verbose_print(ns.verbose) conn = Connection(verb, ssh=False) verb('Show dialog window') io.show_dialog_header(conn) conn.init_dialog_window()
def __init__(self, url=None, project=None, user=None, groups=None, certificate=None, privateKey=None, caChain=None): '''Initialize LGI client connection. Configuration can be supplied as parameters, or else defaults will be read from the first existing file/directory out of this list: @type url str @param url LGI project server url to work with @type project str @param project LGI project to work with @type user str @param user LGI username @type groups str @param groups LGI groups @type certificate str @param certificate location of user certificate file @type privateKey str @param privateKey location of user private key file @type caChain str @param caChain location of CA chain to validate LGI project server with ''' Connection.__init__(self, url, project, certificate, privateKey, caChain) self.readConfig() if url is not None: self._url = url if project is not None: self._project = project if certificate is not None: self._certificate = certificate if privateKey is not None: self._privateKey = privateKey if caChain is not None: self._chChain = caChain if user is not None: self._user = user if groups is not None: self._groups = groups
class Client: def __init__(self, socket, address, port): print 'Init Client' ee = EventEmitter() self._packet_sender = PacketSender(socket, address, port) self._connection = Connection(self._packet_sender) @self._connection.ee.on('data') def on_data(data): ee.emit('data', data) def on_message(message, rinfo): if rinfo.address is not address or rinfo.port is not port: return packet = Packet(message) if packet.getIsFinish(): socket.close() return self._connection.receive(packet) #socket.on('message', on_message) def send(self, data): self._connection.send(data) def close(self): self._packet_sender.send(Packet.createFinishPacket())
def sync_description(self): """ Salva a descrição do schema e de suas tabelas e views no banco de dados """ try: if self.description is not None: Connection.execute( u"""COMMENT ON SCHEMA {0} IS %s""".format(self.name,), (self.description,)) else: Connection.execute( u"""COMMENT ON SCHEMA {0} IS NULL""".format(self.name,)) for table in self.tables(): table.sync_description() for view in self.views(): view.sync_description() except Exception, e: warnings.warn( "Erro ao sincronizar o schema {0}: {1}" .format(self.name, e), RuntimeWarning)
def run(self): log.info("btserver running") while self.running: self.server_sock = None try: self.server_sock = bt.BluetoothSocket(bt.RFCOMM) self.server_sock.setblocking(0) self.server_sock.bind(("", self.channel)) self.server_sock.listen(1) bt.advertise_service(self.server_sock, config.PNAME, service_classes = [bt.SERIAL_PORT_CLASS], profiles = [bt.SERIAL_PORT_PROFILE]) log.info("Waiting for connections on RFCOMM channel [{}]".format(self.server_sock.getsockname()[1])) while self.running: readable, _, _ = select.select([self.server_sock], [], [], 0.1) for s in readable: if s is self.server_sock: client_sock, client_info = self.server_sock.accept() log.info("Accepted connection from: " + str(client_info)) client_sock.setblocking(1) client_sock.settimeout(self.timeout) if self.running: conn = Connection(client_sock, self) conn.start() except: if self.running: log.exception("Error while listening for connections") time.sleep(1.0) finally: self.close()
def send_near(output_lock, neighbors, msg): for peer in neighbors: # Non invio all'indirizzo da cui è arrivato il pacchetto # if sender is None or (peer['ipv4'] != sender and peer['ipv6'] != sender): try: output(output_lock, "\nConnecting to: " + peer['ipv4'] + "\t" + peer['ipv6'] + "\t" + peer['port']) c = Connection(output_lock, peer['ipv4'], peer['ipv6'], peer['port']) # Creazione connessione con un peer noto c.connect() peerSock = c.socket peerSock.send(msg) output(output_lock, "\nMessage sent : ") output(output_lock, msg[0:4] + "\t" + msg[4:20] + "\t" + msg[20:35] + "\t" + msg[36:75] + "\t" + msg[76:80] + "\t" + msg[ 80:112]) peerSock.close() except IOError as e: output(output_lock, 'send_near-Socket Error: ' + e.message) except socket.error, msg: output(output_lock, 'send_near-Socket Error: ' + str(msg)) continue except Exception as e: output(output_lock, 'send_near-Error: ' + e.message) continue
def evaluate(self, dt=0.01): """ Update weights relative to connection equation """ if not self._equation: return Connection.evaluate(self,dt) if self._mask is not 1: self._weights *= self._mask
def readBroadcastDatagram(self): while self.broadcastSocket.hasPendingDatagrams(): senderIp = QHostAddress() senderPort = 0; datagram = QByteArray() #datagram.resize(self.broadcastSocket.pendingDatagramSize()) #if self.broadcastSocket.readDatagram(datagram.data(), datagram.size(), senderIp, senderPort) == -1: # continue datagram, host, port = self.broadcastSocket.readDatagram(self.broadcastSocket.pendingDatagramSize()) try: # Python v3. datagram = str(datagram, encoding='ascii') except TypeError: # Python v2. pass senderIp = host.toString() senderPort = port templist = list() templist = datagram.split('@') if len(templist) != 2: continue senderServerPort = int(templist[1]) if self.isLocalHostAddress(senderIp) and senderServerPort == self.serverPort: continue senderPort = -1 if not self.client.hasConnection(senderIp, senderPort): connection = Connection(self) self.newconnection_signal.emit(connection) connection.connectToHost(senderIp, senderServerPort)
def main(): with open("swift_xauth.conf", "w+") as swift_open: get_connection = Connection(sys.argv[1], sys.argv[2]) auth_token = get_connection.get_xauthtoken() xstorageurl = get_connection.get_storage_url() swift_open.write(auth_token + "\n") swift_open.write(xstorageurl)
def run(self): logging.debug('Connecting to {}'.format(self.destination)) self._connect() if not shared.shutting_down and self.success: c = Connection(self.destination, 'i2p', self.s, 'i2p', False, self.destination) c.start() shared.connections.add(c)
def accept_new(self): """Acepta una nueva conexión""" socket, addr = self.master_socket.accept() # Acepta c = Connection(socket, addr) # Instancia Connection # La primera tarea de toda conexion es una instancia a RHT c.task = RequestHandlerTask(self) self.append(c) # Agrega a la lista de conexiones
def run(self): for topic, msg_type, trusted in self.broadcasting: if topic[0] != "/": topic = "/" + topic self.create_subscriber(topic, msg_type, trusted) if topic == "/receiving": rospy.logerr("{}: topic name 'receiving' is reserved".format( self.name)) continue self.conn[topic] = Connection(host, port, "{}{}".format( self.name, topic), private_key) self.conn[topic].start() self.receiver = Connection(host, port, "{}{}".format( self.name, "/receiving"), private_key) self.descriptionConn = Connection(host, port, "{}/description".format( self.name), private_key) self.receiver.start() self.descriptionConn.start() self.timer.start() while not rospy.is_shutdown(): #for key, conn in self.conn.iteritems(): # updates = conn.updates() updates = self.receiver.updates() for v in updates.values(): self.pub_man.publish(v) for key, conn in self.conn.iteritems(): conn.stop() self.receiver.stop() self.timer.cancel() self.descriptionConn.stop()
def __init__(self, urlOrCfg, project=None, certificate=None, privateKey=None, caChain=None): '''Initialize resource. This is done either by specifying all components or by only giving the first parameter pointing to a resource daemon configuration file. Instead of a resource daemon configuration file, it can also point to a tarball containing LGI.cfg as resource daemon configuration file and certificates. @type urlOrCfg str @param urlOrCfg location of configuration file, or LGI project server url @type project str @param project LGI project to work with @type certificate str @param certificate location of user certificate file @type privateKey str @param privateKey location of user private key file @type caChain str @param caChain location of CA chain to validate LGI project server with ''' self._apps = None self._sessionId = None self._tmpdir = None if project: Connection.__init__(self, urlOrCfg, project, certificate, privateKey, caChain) else: Connection.__init__(self, None, None, None, None, None) if tarfile.is_tarfile(urlOrCfg): self.parseTarball(urlOrCfg) else: self.parseConfig(urlOrCfg)
def send_sms(to, signature, text, userid, key): """Fast function for sending sms. Create connection with given (userid, key) pair and send sms. :note: Your @signature must be verified on bytehand. :param to: receiver phone number. :param signature: value of "from"-field of sms message. :param text: message content. :param userid: your bytehand api id. :param key: your bytehand api key. :see: https://www.bytehand.com/secure/settings to get your key and id. """ to = str(to) userid = str(userid) if not to.isdigit(): raise TypeError('Incorrect "to"-field format. ' 'It must be string of digits, ' 'but it is: "{}"'.format(to)) if not text: raise TypeError('Can\'t send empty message.') if not signature: raise TypeError('Signature should be set.') if not userid.isdigit(): raise TypeError('User id must be digit, ' 'but it is: {}'.format(userid)) conn = Connection(userid=userid, key=key) return conn.send(to=to, signature=signature, text=text)
def __init__(self, sock, addr): # First order of business is to check for an existing Connection # class object with our socket's fileno. If no such database entry # exists, make a new one and populate it. # from connection import Connection session = db.Session() #connections = session.query(Connection).filter(Connection.fileno == sock.fileno()) conn = session.query(Connection).get(sock.fileno()) if conn is None: conn = Connection( fileno = sock.fileno() remote_address = addr[0] remote_port = addr[1] ) session.add(conn) session.commit() else: # We may want to check for reconnection after getting a username # For now, just fill in the address and port and save it so it's up to date. conn.remote_address = addr[0] conn.remote_port = addr[1] session.commit() self._connection = conn # underlying Connection object, for database persistence self._read_buffer = '' # buffer for data read from the socket self._write_buffer = '' # buffer for data to be written to the socket self._bytes_sent = 0 # total bytes sent self._bytes_received = 0 # total bytes received self.connected = True # the socket is connected self.pending = False # output to the socket is ready to be sent
def __init__(self, dcfilename=default_dcfilename): Connection.__init__(self) self.mod = module.Module() # Add Astron-specific keywords for word in astron_keywords: self.mod.add_keyword(word) dcfile.parse_dcfile(self.mod, dcfilename) # Create class definition dicts self.create_dclass_dicts() self.distributed_objects = {} self.owner_views = {} self.handlers = {} # FIXME: Maybe move this into ClientRepository, if Internals won't get Interests in the future. # FIXME: Actually, fold this into the general callback mechanism. self.interest_counters = {} self.interest_callback_map = {} # The callback system for handling *_RESP messages self.msg_to_msgresp_map = { servermsg.STATESERVER_OBJECT_GET_FIELD : servermsg.STATESERVER_OBJECT_GET_FIELD_RESP, servermsg.STATESERVER_OBJECT_GET_FIELDS : servermsg.STATESERVER_OBJECT_GET_FIELDS_RESP, servermsg.STATESERVER_OBJECT_GET_ALL : servermsg.STATESERVER_OBJECT_GET_ALL_RESP, servermsg.STATESERVER_OBJECT_GET_LOCATION : servermsg.STATESERVER_OBJECT_GET_LOCATION_RESP, servermsg.STATESERVER_OBJECT_GET_AI : servermsg.STATESERVER_OBJECT_GET_AI_RESP, servermsg.STATESERVER_OBJECT_GET_OWNER : servermsg.STATESERVER_OBJECT_GET_OWNER_RESP, servermsg.STATESERVER_OBJECT_GET_ZONE_COUNT : servermsg.STATESERVER_OBJECT_GET_ZONE_COUNT_RESP, servermsg.STATESERVER_OBJECT_GET_ZONES_COUNT : servermsg.STATESERVER_OBJECT_GET_ZONES_COUNT_RESP, servermsg.STATESERVER_OBJECT_GET_CHILD_COUNT : servermsg.STATESERVER_OBJECT_GET_CHILD_COUNT_RESP, servermsg.DBSS_OBJECT_GET_ACTIVATED : servermsg.DBSS_OBJECT_GET_ACTIVATED_RESP, servermsg.DBSERVER_CREATE_OBJECT : servermsg.DBSERVER_CREATE_OBJECT_RESP, servermsg.DBSERVER_OBJECT_GET_FIELD : servermsg.DBSERVER_OBJECT_GET_FIELD_RESP, servermsg.DBSERVER_OBJECT_GET_FIELDS : servermsg.DBSERVER_OBJECT_GET_FIELDS_RESP, servermsg.DBSERVER_OBJECT_GET_ALL : servermsg.DBSERVER_OBJECT_GET_ALL_RESP, servermsg.DBSERVER_OBJECT_SET_FIELD_IF_EQUALS : servermsg.DBSERVER_OBJECT_SET_FIELD_IF_EQUALS_RESP, servermsg.DBSERVER_OBJECT_SET_FIELDS_IF_EQUALS: servermsg.DBSERVER_OBJECT_SET_FIELDS_IF_EQUALS_RESP, servermsg.DBSERVER_OBJECT_SET_FIELD_IF_EMPTY : servermsg.DBSERVER_OBJECT_SET_FIELD_IF_EMPTY_RESP, } self.context_counters = { servermsg.STATESERVER_OBJECT_GET_FIELD_RESP : 0, servermsg.STATESERVER_OBJECT_GET_FIELDS_RESP : 0, servermsg.STATESERVER_OBJECT_GET_ALL_RESP : 0, servermsg.STATESERVER_OBJECT_GET_LOCATION_RESP : 0, servermsg.STATESERVER_OBJECT_GET_AI_RESP : 0, servermsg.STATESERVER_OBJECT_GET_OWNER_RESP : 0, servermsg.STATESERVER_OBJECT_GET_ZONE_COUNT_RESP : 0, servermsg.STATESERVER_OBJECT_GET_ZONES_COUNT_RESP : 0, servermsg.STATESERVER_OBJECT_GET_CHILD_COUNT_RESP : 0, servermsg.DBSS_OBJECT_GET_ACTIVATED_RESP : 0, servermsg.DBSERVER_CREATE_OBJECT_RESP : 0, servermsg.DBSERVER_OBJECT_GET_FIELD_RESP : 0, servermsg.DBSERVER_OBJECT_GET_FIELDS_RESP : 0, servermsg.DBSERVER_OBJECT_GET_ALL_RESP : 0, servermsg.DBSERVER_OBJECT_SET_FIELD_IF_EQUALS_RESP : 0, servermsg.DBSERVER_OBJECT_SET_FIELDS_IF_EQUALS_RESP: 0, servermsg.DBSERVER_OBJECT_SET_FIELD_IF_EMPTY_RESP : 0, } self.callbacks = {}
def __init__(self, inmod, outmod, name=None, inSliceFrom=0, inSliceTo=None, outSliceFrom=0, outSliceTo=None): if outSliceTo is None: outSliceTo = outmod.indim size = outSliceTo - outSliceFrom Connection.__init__(self, inmod, outmod, name, inSliceFrom, inSliceTo, outSliceFrom, outSliceTo) ParameterContainer.__init__(self, size)
def connection_thread(data_queue, msg_queue): global con con = Connection() con.broad_to_connect() fp.start() con.start_data_process(data_queue, msg_queue) print 'Connection thread terminated.' return 0
def main(): protocol_path = os.path.normpath(os.path.expanduser(Config.MC_DATA_FOLDER)) threaded_dispatcher = ThreadedDispatcher() connection = Connection(Config.SERVER, Config.PORT) factory = PacketFactory(protocol_path, Config.PROTOCOL_VERSION) agent_reactor = ModelReactor(factory, connection) inventory = InventoryReactor(factory, connection) packet_reactor = PacketReactor(factory, connection) # TODO should the inventory reactor be on the model? robot = Robot(factory, model=agent_reactor, inventory=inventory) # # establish our threaded dispatcher # TODO need a better way to do this # # # TODO need a way to signal threaded reactors to shutdown gracefully # connection.raw_packet_emitter.dispatcher = threaded_dispatcher packet_reactor.play_state_emitter.dispatcher = threaded_dispatcher packet_reactor.state_change_emitter.dispatcher = threaded_dispatcher packet_reactor.login_state_emitter.dispatcher = threaded_dispatcher packet_reactor.handshake_state_emitter.dispatcher = threaded_dispatcher agent_reactor.stop_emitter.dispatcher = threaded_dispatcher agent_reactor.tick_emitter.dispatcher = threaded_dispatcher # connection connection.raw_packet_emitter.bind(packet_reactor) # packet_reactor packet_reactor.play_state_emitter.bind(agent_reactor) packet_reactor.play_state_emitter.bind(inventory) packet_reactor.play_state_emitter.bind(robot) # agent_reactor agent_reactor.stop_emitter.bind(robot) agent_reactor.tick_emitter.bind(robot) try: connection.connect() packet_reactor.login('bobo') while True: connection.process() finally: agent_reactor.stop() threaded_dispatcher.stop() raise
def download(self, filename): last_modified_time = self.get_modification_time(filename) url = 'http://java.shadowlands.ru/zombievk/items' data = Connection(url).get_changed_document( data={'lang': 'ru'}, last_client_time=last_modified_time ) with open(filename, 'w') as f: f.write(data.encode(u'utf-8'))
def vol_handler(ns): verb = verbose_print(ns.verbose) conn = Connection(verb, ssh=False) verb('Volume level: {}'.format(ns.level)) target = conn.set_volume(ns.level) print('Setting volume to {}'.format(col.magenta(target)))
def reboot_handler(ns): verb = verbose_print(ns.verbose) conn = Connection(verb, ssh=False) print('Rebooting ...') conn.robot_reboot()
import json import os from flask import Flask, jsonify, request, abort from connection import Connection app = Flask(__name__) wsgi_app = app.wsgi_app connection = Connection(os.environ['DB_SERVER'], os.environ['DB_NAME'], os.environ['DB_USERNAME'], os.environ['DB_PASSWORD'], os.environ['DB_PORT'], os.environ['DB_DRIVER']) connection.connect() @app.route("/", methods=['GET']) def index(): return "Hello, welcome to mural" @app.route("/api/mural", methods=['GET']) def mural_index(): posts = connection.get_mural_records() posts_list = list(posts) posts_list = [{"id": a, "nome": b, "mensagem": c} for a, b, c in posts_list] return json.dumps(posts_list) @app.route("/api/mural", methods=['POST']) def mural_create_post(): if not request.form.get('nome') or not request.form.get('mensagem'): return abort(400)
class Document(BaseDocument): ''' The ORM core, supports `all the query operations of motor <http://motor.readthedocs.org/en/stable/api/motor_collection.html>`_.''' __metaclass__ = MonguoMeta meta = {} create_index = MonguoOperation() drop_indexes = MonguoOperation() drop_index = MonguoOperation() drop = MonguoOperation() ensure_index = MonguoOperation() reindex = MonguoOperation() rename = MonguoOperation() find_and_modify = MonguoOperation() map_reduce = MonguoOperation() update = MonguoOperation() insert = MonguoOperation() remove = MonguoOperation() save = MonguoOperation() index_information = MonguoOperation() count = MonguoOperation() options = MonguoOperation() group = MonguoOperation() distinct = MonguoOperation() inline_map_reduce = MonguoOperation() find_one = MonguoOperation() find = MonguoOperation() aggregate = MonguoOperation() uuid_subtype = MonguoOperation() full_name = MonguoOperation() @classmethod def get_database_name(cls): '''Get the database name related to `cls`.''' db_name = (cls.meta['db'] if 'db' in cls.meta else Connection.get_default_database_name()) return db_name @classmethod def get_collection_name(cls): '''Get the collection name related to `cls`.''' collection_name = (cls.meta['collection'] if 'collection' in cls.meta else util.camel_to_underline(cls.__name__)) return collection_name @classmethod def get_database(cls, pymongo=False): ''' Get the database related to `cls`, it's an instance of :class:`~motor.MotorDatabase`. :Parameters: - `pymongo`: Return pymongo.database if True. ''' connection_name = cls.meta[ 'connection'] if 'connection' in cls.meta else None db_name = cls.get_database_name() db = Connection.get_database(connection_name, db_name, pymongo) return db @classmethod def get_collection(cls, pymongo=False): ''' Get the collection related to `cls`, it's an instance of :class:`~motor.MotorCollection`. :Parameters: - `pymongo`: Return pymongo.collection if True. ''' db = cls.get_database(pymongo) collection_name = cls.get_collection_name() collection = db[collection_name] return collection @classmethod @gen.coroutine def translate_dbref(cls, dbref): '''Get the document related with `dbref`. :Parameters: - `dbref`: The dbref to be translated. ''' if not isinstance(dbref, DBRef): raise TypeError("'%s' isn't DBRef type.") if dbref.database is not None: connection_name = cls.meta[ 'connection'] if 'connection' in cls.meta else None db = Connection.get_database(connection_name, dbref.database) else: db = cls.get_database() collection = db[dbref.collection] result = yield collection.find_one({'_id': ObjectId(dbref.id)}) raise gen.Return(result) @classmethod @gen.coroutine def translate_dbref_in_document(cls, document, depth=1): '''Translate dbrefs in the specified `document`. :Parameters: - `document`: The specified document. - `depth`: The translate depth. ''' if not isinstance(document, dict): raise TypeError("Argument 'document' should be dict type.") for name, value in document.items(): if isinstance(value, DBRef): document[name] = yield cls.translate_dbref(value) if depth > 1: document[name] = yield cls.translate_dbref_in_document( document[name], depth - 1) raise gen.Return(document) @classmethod @gen.coroutine def translate_dbref_in_document_list(cls, document_list, depth=1): '''Translate dbrefs in the document list. :Parameters: - `document_list`: The specified document list. - `depth`: The translate depth. ''' if not isinstance(document_list, (list, tuple)): raise TypeError( "Argument document_list should be list or tuple tpye.") for document in document_list: document = yield cls.translate_dbref_in_document(document, depth) raise gen.Return(document_list) @classmethod @gen.coroutine def to_list(cls, cursor, length=None): '''Warp cursor.to_list() since `length` is required in `cursor.to_list`''' resut = [] if length is not None: assert isinstance(length, int) reuslt = yield cursor.to_list(length=length) else: while (yield cursor.fetch_next): resut.append(cursor.next_object()) raise gen.Return(resut) @classmethod def get_gridfs(cls, async=True): if async: db = Connection.get_database() fs = motor.MotorGridFS(db) else: db = Connection.get_database(pymongo=True) fs = gridfs.GridFS(db) return fs
def __init__(self, user: str, password: str, host: str, database: str): self.connection = Connection(user, password, host, database) self.available_tables = [] self.table_name = '' self.choose_table()
from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column, String, INTEGER, DateTime, engine from sqlalchemy.sql.sqltypes import Integer from connection import Connection Base = declarative_base() class Student(Base): __tablename__ = "student" studenId = Column(INTEGER(), primary_key=True, autoincrement=True) name = Column(String(50)) family = Column(String(50)) grade = Column(Integer) created_at = Column(DateTime()) def __init__(self, name=None, family=None, grade=None): self.name = name self.family = family self.grade = grade engine = Connection().get_connection() if not engine.dialect.has_table(engine, "student"): Base.metadata.create_all(engine, checkfirst=True) print("Database Created") else: print("Database {} exists!".format("student"))
class Source(object): def __init__(self, **kwargs): self._socket = None self._conf = kwargs self._conn = None self._tables = {} def _query(self, sql): """ Query mysql with reconnecting once on failure. """ try: res = [] with open_cursor(self._conn) as cursor: cursor.execute(sql) columns_desc = cursor.description columns = tuple([d[0] for d in columns_desc]) for row in cursor: res.append(dict(zip(columns, row))) return res, columns_desc except: self.disconnect() self.connect() res = [] with open_cursor(self._conn) as cursor: cursor.execute(sql) columns_desc = cursor.description columns = tuple([d[0] for d in columns_desc]) print cursor.description for row in cursor: res.append(dict(zip(columns, row))) return res, columns_desc def connect(self): """ build connection to mysql server. """ self._conn = Connection(**(self._conf)) self._conn.connect() self._socket = self._conn.socket def disconnect(self): """ disconnect mysql server. """ self._conn.close() self._socket = None def show_master_status(self): res, _ = self._query("show master status;") print res return res[0] def get_server_id(self): return 123456 def binlog_dump(self, log_file, offset): """ COM_BINLOG_DUMP +=============================================+ | packet header | packet length 0 : 3 | | +-------------------------+ | | sequence number 3 : 1 | +============================================+ | command packet | command code 4 : 1 | COM_BINLOG_DUMP | +------------------------―+ | | offset 5 : 4 | | +-------------------------+ | | flags 9 : 2 | | +-------------------------+ | | server id 11 : 4| | +-------------------------+ | | log name 15 : x| +============================================+ """ payload = '' payload += utils.int1store(ServerCmd.BINLOG_DUMP) payload += utils.int4store(offset) payload += utils.int2store(0) payload += utils.int4store(self.get_server_id()) payload += log_file payload += '\x00' log.debug("len(payload) = %d" % len(payload)) # send BIGLOGDUMP command and parse ok packet response. self._socket.send(payload, 0) ok_packet = self._socket.recv() parser = MySQLProtocol() ok_packet = parser.parse_ok(ok_packet) print ok_packet def __iter__(self): return self def next(self): packet = self._socket.recv() event = BinlogEvent(packet) log.debug(str(event)) if event.is_eof() or event.is_error(): raise StopIteration event_type = EventMap().get_event_type(event.header.event_type) if event_type: event = event_type(packet) log.debug(str(event)) return event def add_table(self, db, table, col): if db not in self._tables: self._tables[db] = {} if table not in self._tables[db]: self._tables[db][table] = { "columns_info": {}, "do_columns": {}, "pos_map": {} } for i in col: if not isinstance(i, str): log.warning("non-string col name.") continue if i not in self._tables[db][table]["do_columns"]: self._tables[db][table]["do_columns"][i] = None log.debug(json.dumps(self._tables)) def get_full_columns(self): for db, tables in self._tables.items(): for table, desc in tables.items(): try: sql = "show full columns from %s.%s" % (db, table) res, _ = self._query(sql) for idx, field in enumerate(res): if field["Field"] in desc["do_columns"]: desc["columns_info"][idx] = \ {"name":field["Field"], \ "type":field["Type"], \ "Default":field["Default"]} except: log.warning(get_trace_info()) continue log.debug(json.dumps(self._tables)) def get_columns_info(self): for db, tables in self._tables.items(): for table, desc in tables.items(): try: sql = "select * from %s.%s limit 0,0" % (db, table) res, columns_desc = self._query(sql) for idx, field in enumerate(columns_desc): if field[0] in desc["do_columns"]: desc["columns_info"][field[0]] = field desc["pos_map"][idx] = field[0] except: log.warning(get_trace_info()) continue log.debug(json.dumps(self._tables))
class Minecraft: """The main class to interact with a running instance of Minecraft Pi.""" def __init__(self, connection=None, autoId=True): if connection: self.conn = connection else: self.conn = Connection() self.camera = CmdCamera(self.conn) self.entity = CmdEntity(self.conn) if autoId: try: playerId = int(environ['MINECRAFT_PLAYER_ID']) self.player = CmdPlayer(self.conn, playerId=playerId) except: self.player = CmdPlayer(self.conn) else: self.player = CmdPlayer(self.conn) self.events = CmdEvents(self.conn) self.enabledNBT = False def spawnEntity(self, *args): """Spawn entity (type,x,y,z,tags) and get its id => id:int""" return int(self.conn.sendReceive("world.spawnEntity", args)) def removeEntity(self, *args): """Remove entity (id)""" self.conn.send("world.removeEntity", args) def getBlock(self, *args): """Get block (x,y,z) => id:int""" return int( self.conn.sendReceive_flat("world.getBlock", floorFlatten(args))) def getBlockWithData(self, *args): """Get block with data (x,y,z) => Block""" ans = self.conn.sendReceive_flat("world.getBlockWithData", floorFlatten(args)) return Block(*map(int, ans.split(",")[:2])) def getBlockWithNBT(self, *args): """ Get block with data and nbt (x,y,z) => Block (if no NBT) or (Block,nbt) For this to work, you first need to do setting("include_nbt_with_data",1) """ if not self.enabledNBT: self.setting("include_nbt_with_data", 1) self.enabledNBT = True try: ans = self.conn.sendReceive_flat("world.getBlockWithData", floorFlatten(args)) except RequestError: # retry in case we had a Fail from the setting ans = self.conn.receive() else: ans = self.conn.sendReceive_flat("world.getBlockWithData", floorFlatten(args)) return stringToBlockWithNBT(ans) """ @TODO """ def fallbackGetCuboid(self, getBlock, *args): (x0, y0, z0, x1, y1, z1) = map(lambda x: int(math.floor(float(x))), flatten(args)) out = [] for y in range(min(y0, y1), max(y0, y1) + 1): for x in range(min(x0, x1), max(x0, x1) + 1): for z in range(min(z0, z1), max(z0, z1) + 1): out.append(getBlock(x, y, z)) return out def fallbackGetBlocksWithData(self, *args): return self.fallbackGetCuboid(self.getBlockWithData, args) def fallbackGetBlocks(self, *args): return self.fallbackGetCuboid(self.getBlock, args) def fallbackGetBlocksWithNBT(self, *args): return self.fallbackGetCuboid(self.getBlockWithNBT, args) def getBlocks(self, *args): """ Get a cuboid of blocks (x0,y0,z0,x1,y1,z1) => [id:int] Packed with a y-loop, x-loop, z-loop, in this order. """ try: ans = self.conn.sendReceive_flat("world.getBlocks", floorFlatten(args)) return map(int, ans.split(",")) except: self.getBlocks = self.fallbackGetBlocks return self.fallbackGetBlocks(*args) def getBlocksWithData(self, *args): """Get a cuboid of blocks (x0,y0,z0,x1,y1,z1) => [Block(id:int, meta:int)]""" try: ans = self.conn.sendReceive_flat("world.getBlocksWithData", floorFlatten(args)) return [Block(*map(int, x.split(",")[:2])) for x in ans.split("|")] except: self.getBlocksWithData = self.fallbackGetBlocksWithData return self.fallbackGetBlocksWithData(*args) def getBlocksWithNBT(self, *args): """Get a cuboid of blocks (x0,y0,z0,x1,y1,z1) => [Block(id, meta, nbt)]""" try: if not self.enabledNBT: self.setting("include_nbt_with_data", 1) self.enabledNBT = True try: ans = self.conn.sendReceive_flat("world.getBlocksWithData", floorFlatten(args)) except RequestError: # retry in case we had a Fail from the setting ans = self.conn.receive() else: ans = self.conn.sendReceive_flat("world.getBlocksWithData", floorFlatten(args)) ans = self.conn.sendReceive_flat("world.getBlocksWithData", floorFlatten(args)) return [ stringToBlockWithNBT(x, pipeFix=True) for x in ans.split("|") ] except: self.getBlocksWithNBT = self.fallbackGetBlocksWithNBT return self.fallbackGetBlocksWithNBT(*args) # must have no NBT tags in Block instance def setBlock(self, *args): """Set block (x,y,z,id,[data])""" self.conn.send_flat("world.setBlock", floorFlatten(args)) def setBlockWithNBT(self, *args): """Set block (x,y,z,id,data,nbt)""" data = list(flatten(args)) self.conn.send_flat("world.setBlock", list(floorFlatten(data[:5])) + data[5:]) # must have no NBT tags in Block instance def setBlocks(self, *args): """Set a cuboid of blocks (x0,y0,z0,x1,y1,z1,id,[data])""" self.conn.send_flat("world.setBlocks", floorFlatten(args)) def setBlocksWithNBT(self, *args): """Set a cuboid of blocks (x0,y0,z0,x1,y1,z1,id,data,nbt)""" data = list(flatten(args)) self.conn.send_flat("world.setBlocks", list(floorFlatten(data[:8])) + data[8:]) def getHeight(self, *args): """Get the height of the world (x,z) => int""" return int( self.conn.sendReceive_flat("world.getHeight", floorFlatten(args))) def getPlayerId(self, *args): """Get the id of the current player""" return int( self.conn.sendReceive_flat("world.getPlayerId", floorFlatten(args))) def getPlayerEntityIds(self): """Get the entity ids of the connected players => [id:int]""" ids = self.conn.sendReceive("world.getPlayerIds") return map(int, ids.split("|")) def saveCheckpoint(self): """Save a checkpoint that can be used for restoring the world""" self.conn.send("world.checkpoint.save") def restoreCheckpoint(self): """Restore the world state to the checkpoint""" self.conn.send("world.checkpoint.restore") def postToChat(self, msg): """Post a message to the game chat""" self.conn.send("chat.post", msg) def setting(self, setting, status): """Set a world setting (setting, status). keys: world_immutable, nametags_visible""" self.conn.send("world.setting", setting, 1 if bool(status) else 0) @staticmethod def create(address=None, port=None): return Minecraft(Connection(address, port))
class Client(Thread,WhiteBoard): Objects = {'line': 'L', 'oval': 'O', 'circle': 'C', 'rectangle': 'R', 'square': 'S', 'drag': 'DR'} def __init__(self): self.conn = Connection() Thread.__init__(self) WhiteBoard.__init__(self) self._init_mouse_event() self.setDaemon(True) self.isMouseDown = False self.x_pos = None self.y_pos = None self.last_time = None self.line_x1,self.line_y1,self.line_x2,self.line_y2 = None, None, None, None def _init_mouse_event(self): self.drawing_area.bind("<Motion>", self.motion) self.drawing_area.bind("<ButtonPress-1>", self.left_but_down) self.drawing_area.bind("<ButtonRelease-1>", self.left_but_up) def send_del_msg(self,event): canvas_item_tuple = self.drawing_area.find_overlapping(event.x + 2, event.y + 2, event.x - 2, event.y - 2) print(canvas_item_tuple) if len(canvas_item_tuple) > 0: to_delete_id = max(canvas_item_tuple) tags = self.drawing_area.gettags(to_delete_id) msgid = tags[0] msg = ('Z', msgid) self.conn.send_message(msg) #(tpye,startx,starty,endx,endy,color) #('D',startx,starty,endx,endy,'red') def left_but_down(self,event=None): self.isMouseDown = True self.x_pos = event.x self.y_pos = event.y self.last_time = time.time() self.line_x1, self.line_y1 = event.x,event.y if self.isMouseDown == True and self.drawing_tool == 'eraser': self.send_del_msg(event) def left_but_up(self,event=None): self.isMouseDown = False print(event.x,event.y) self.last_time = None self.line_x2, self.line_y2 = event.x, event.y if self.drawing_tool == 'text': self.draw_text() else: self.draw_one_obj() def draw_text(self): text_to_draw = UserDialog._Text msg = ('T', self.line_x1, self.line_y1, 'red',text_to_draw) self.conn.send_message(msg) def draw_one_obj(self): tool = self.drawing_tool if tool not in Client.Objects.keys(): return else: cmd_type = Client.Objects[tool] msg = (cmd_type, self.line_x1, self.line_y1, self.line_x2, self.line_y2, 'red') self.conn.send_message(msg) # (tpye,startx,starty,endx,endy,color) # ('D',startx,starty,endx,endy,'red') def motion(self,event=None): if self.isMouseDown == True and self.drawing_tool == 'pencil': now = time.time() if now - self.last_time < 0.02: print('too fast') return self.last_time = now msg = ('D',self.x_pos,self.y_pos,event.x,event.y,'red') self.conn.send_message(msg) self.x_pos = event.x self.y_pos = event.y elif self.isMouseDown == True and self.drawing_tool == 'eraser': self.send_del_msg(event) def run(self): # print('run')aa while True: msg = self.conn.receive_msg() self.draw_from_msg(msg) print(msg) if msg == 'xxx': pass
class Ludo(object): """This is the main Ludo class. It initialises my_player, genie_owner, all_pieces, board, connection, the score board and the timer. It also holds the main run function which runs the game. """ def __init__(self): """ Initialises the main attributes but does not take in any arguments. """ self.my_player = None self.genie_owner = None self.starting_point = {"red": 0, "green": 13, "yellow": 26, "blue": 39} self.cs = ["red", "green", "yellow", "blue"] self.colour_to_img = {"red": c.RED_PIECE, "green": c.GREEN_PIECE, "yellow": c.YELLOW_PIECE, "blue": c.BLUE_PIECE} self.all_pieces = [Piece(self.cs[c], num, self.colour_to_img[self.cs[c]], self.starting_point[self.cs[c]]) for c in range(4) for num in range(1, 5)] self.board = Board(self.genie_owner, self.my_player, self.all_pieces, self.colour_to_img) self.connection = Connection(self.board, self.my_player, None, self.all_pieces) self.current_player = self.connection.current_player self.clock = pygame.time.Clock() self.IN = 1 self.colour_check = 0 self.time_limited = 15 self.p = Queue() self.font = pygame.font.SysFont("Arial", 72) self.text = self.font.render("time", True, (0, 128, 0)) def setup(self): """Creates the coo-rdinate dictionary for the board, initialises pygame. It also blocks out some pygame events so the queue doesn't overflow from unneeded events such as MOUSEMOTION. It also setups attributes in board, connects to the server and shows the start screen. """ create_dicts() pygame.init() pygame.event.set_blocked([pygame.MOUSEMOTION, pygame.KEYUP, pygame.MOUSEBUTTONUP]) self.board.add_connection(self.connection) #Draw form returns a tuple of name and ip of server name_and_ip = self.connection.form.draw_form() self.connection.connect_to_server(name_and_ip[0], name_and_ip[1]) self.show_start_screen() self.bgm() def draw_Time_Out(self): # time out function on the client side """Draws the timer which counts down until it reaches 0. When this happens it goes back to its original number and counts down again. """ while True: j = self.time_limited + 1 while j != 0: if j>6: j -= 1 print(str(j)) elif j<=6: pygame.mixer.Sound.play(c.noMove_sound) j -= 1 print(str(j)) self.p.put(str(j)) if not self.connection.q.empty(): data = self.connection.q.get() # receive a data and reset the timer if data == "already push a button": j = self.time_limited + 1 continue time.sleep(1) self.connection.time_out() def terminate(self): """Quit game if user closes window.""" pygame.quit() sys.exit() def click_piece(self, num, piece): """ After a dice is roller, if the player clicks a movable piece, call click_piece. It calls the move_piece function, it also sends what piece was moved to the server. """ self.board.move_piece(num, self.connection.my_player.roll) self.connection.send_movement(num, self.connection.my_player.roll) self.connection.end_roll() print("Outside", piece.get_steps_from_start()) def show_start_screen(self): """Shows the start screen whent game first starts. It shows the word LUDO in flashing colours. Once the player connects to the server, the screen goes away.""" FPSCLOCK = pygame.time.Clock() title_font = pygame.font.SysFont("Arial", 100) colours = [c.RED, c.GREEN, c.YELLOW, c.BLUE] index = 0 while True: SCREEN.fill(c.WHITE) title_surf = title_font.render('Ludo!', True, colours[index]) title_surf_rect = title_surf.get_rect() title_surf_rect.center = (c.BOARD_WIDTH / 2, c.BOARD_HEIGHT / 2) SCREEN.blit(title_surf, title_surf_rect) if self.connection.my_player is not None: pygame.event.get() return if pygame.event.get(pygame.QUIT): self.terminate() index = (index + 1) % 4 pygame.display.update() FPSCLOCK.tick(5) def get_score(self, list_of_pieces): #Returns a list of the scores in order: [red, green, yellow, blue] red_score = 0 blue_score = 0 green_score = 0 yellow_score = 0 for piece in list_of_pieces: if piece.colour == "red": red_score += piece.get_steps_from_start() elif piece.colour == "blue": blue_score += piece.get_steps_from_start() elif piece.colour == "green": green_score += piece.get_steps_from_start() elif piece.colour == "yellow": yellow_score += piece.get_steps_from_start() return [red_score, green_score, yellow_score, blue_score] def draw_scoreboard(self, list_of_pieces, x, y, w, h): name = Box("Name", x, y, w, h, c.BLACK, 1) x += w score = Box("Score", x, y, w, h, c.BLACK, 1) x += w name.draw() score.draw() #Returns a list of the scores in order: red, green, yellow, blue scores = self.get_score(list_of_pieces) list_of_scores = [(scores[0], "red"), (scores[1], "green"), (scores[2], "yellow"), (scores[3], "blue")] #If all scores are zero, scoreboard is ordered as default if scores != [0, 0, 0, 0]: list_of_scores = sorted(list_of_scores)[::-1] color_to_color = { "red" : c.RED, "green" : c.GREEN, "yellow" : c.YELLOW, "blue" : c.BLUE} # Used to get the name of the player variable names contains all the names of the # players [red, green, yellow, blue] colors = ["red", "green", "yellow", "blue"] for i in list_of_scores: #Access each player, sort them by score and draw the 4 players on the scoreboard. color = color_to_color[i[1]] y += h x = 900 if self.connection.my_player.names != []: nameField = Box( self.connection.my_player.names[colors.index(i[1])], x, y, w, h, color) else: nameField = Box("", x, y, w, h, color) nameField.draw() outlineBox = Box("", x, y, w, h, c.BLACK, 1) outlineBox.draw() x += w scoreField = Box(str(i[0]), x, y, w, h, color) scoreField.draw() outlineBox = Box("", x, y, w, h, c.BLACK, 1) outlineBox.draw() x += w # Draws a marker after your entry to show who you are if self.connection.my_player.name == self.connection.my_player.names[colors.index(i[1])]: marker = Box("--", x, y, w, h, c.WHITE) marker.draw() else: blank = Box("", x, y, w, h, c.WHITE) # Returns a list of the scores in order: [red, green, yellow, blue] def run(self): """This is the main game method. It draws the board, pieces and the buttons. It also shows the dice rolling animation. """ while True: try: SCREEN.fill(c.WHITE) SCREEN.blit(c.BG, (c.INDENT_BOARD, c.INDENT_BOARD)) self.board.draw_board(self.colour_check) self.colour_check = (self.colour_check + 1) % c.FLASH_RATE self.draw_scoreboard(self.all_pieces, 900, 500, 100, 30) self.board.PLAYER_FIELD.draw() OUTPUT = self.board.ROLL_BUTTON.click() if OUTPUT is not None: self.board.dice_object.dice.roll_dice_gif(OUTPUT, self.IN, 900, 230) self.board.dice_object.display_dice(900, 230, self.connection.current_dice) # draw remain time if not self.p.empty(): message = self.p.get() # receive a data and reset the timer if message != "time": self.text = self.font.render(message, True, (0, 128, 0)) SCREEN.blit(self.text, (900, 20)) pygame.display.update() for event in pygame.event.get(): if event.type == pygame.QUIT: self.terminate() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_a: self.board.move_piece(1, 1) if event.key == pygame.K_s: self.board.move_piece(4, 6) if event.key == pygame.K_d: self.board.move_piece(8, 1) if event.key == pygame.K_f: self.board.move_piece(12, 1) if event.key == pygame.K_g: self.board.move_piece(2, 1) if event.key == pygame.K_h: self.board.move_piece(3, 1) elif event.type == pygame.MOUSEBUTTONDOWN: if self.connection.my_player.turn_token is True and self.connection.my_player.diceroll_token is False: x, y = event.pos print(x, y) for num in range(self.connection.my_player.low_range, self.connection.my_player.low_range + 4): #e.g for "red" - range(0, 4), for "green" - range(4, 8) piece = self.connection.my_player.my_pieces[num - self.connection.my_player.low_range] #gets index 0-3 to use my_pieces. pos = piece.get_position() if piece.movable: if piece.image.get_width() == 64: if pos is not None and piece.image.get_rect(topleft=(coOrds[pos][0]-7, coOrds[pos][1]-25)).collidepoint(x, y): #If you clicked a piece, move them (if you rolled) self.click_piece(num, piece) break elif piece.image.get_rect(topleft=(self.board.home_coords[num])).collidepoint(x, y) and self.connection.my_player.roll == 6: #If you clicked a piece in home and you rolled 6, move them out. self.board.move_piece(num, self.connection.my_player.roll) self.connection.send_out(num, self.connection.my_player.start) self.connection.end_roll() print("Home", piece.get_steps_from_start()) break else: if piece.image.get_rect(topleft=(coOrds[pos][0], coOrds[pos][1])).collidepoint(x, y): #If you clicked a piece, move them (if you rolled) self.click_piece(num, piece) break self.clock.tick(c.FPS) except pygame.error as e: print(e) continue def bgm(self): pygame.mixer.pre_init(44100,16,2,4096) pygame.mixer.music.load("sound/BGM.mp3") pygame.mixer.music.play(-1)
def get_conn(section='ldap', prefix='ldap.', filename=os.path.expanduser('~/.ldap.cfg')): return Connection(section=section, prefix=prefix, filename=filename)
def __init__(self): Connection.__init__(self) self.loginfo = Connection() self.masterhandle = '' self.home = ''
class Environment(Connection): logger = logging.getLogger(__name__) def __init__(self): Connection.__init__(self) self.loginfo = Connection() self.masterhandle = '' self.home = '' def DownLoadCode(self, handle, codeurl): """ Download Code use 'git clone' parameters: handle: current working handle codeurl: clone code url """ self.logger.info("Now loading test codes! Please wait in patient...") originalfolder = sys.path[0] self.logger.info(originalfolder) gitclone = handle gitclone.sendline("git clone " + codeurl) index = 0 # increment = 0 while index != 1 or index != 4: index = gitclone.expect(['already exists', 'esolving deltas: 100%', 'eceiving objects', 'Already up-to-date', 'npacking objects: 100%', pexpect.EOF]) filefolder = self.home + '/' + codeurl.split('/')[-1].split('.')[0] if index == 0: os.chdir(filefolder) os.system('git pull') os.chdir(originalfolder) self.loginfo.log('Download code success!') break elif index == 1 or index == 4: self.loginfo.log('Download code success!') gitclone.sendline("mkdir onos") gitclone.prompt() gitclone.sendline("cp -rf " + filefolder + "/tools onos/") gitclone.prompt() break elif index == 2: os.write(1, gitclone.before) sys.stdout.flush() else: self.loginfo.log('Download code failed!') self.loginfo.log('Information before' + gitclone.before) break gitclone.prompt() def InstallDefaultSoftware(self, handle): """ Install default software parameters: handle(input): current working handle """ self.logger.info("Now Cleaning test environment") handle.sendline("sudo apt-get install -y mininet") handle.prompt() handle.sendline("sudo pip install configobj") handle.prompt() handle.sendline("sudo apt-get install -y sshpass") handle.prompt() handle.sendline("OnosSystemTest/TestON/bin/cleanup.sh") handle.prompt() time.sleep(5) self.loginfo.log('Clean environment success!') def OnosPushKeys(self, handle, cmd, password): """ Using onos-push-keys to make ssh device without password parameters: handle(input): working handle cmd(input): onos-push-keys xxx(xxx is device) password(input): login in password """ self.logger.info("Now Pushing Onos Keys:" + cmd) Pushkeys = handle Pushkeys.sendline(cmd) Result = 0 while Result != 2: Result = Pushkeys.expect(["(yes/no)", "assword:", "PEXPECT]#", pexpect.EOF, pexpect.TIMEOUT]) if(Result == 0): Pushkeys.sendline("yes") if(Result == 1): Pushkeys.sendline(password) if(Result == 2): self.loginfo.log("ONOS Push keys Success!") break if(Result == 3): self.loginfo.log("ONOS Push keys Error!") break time.sleep(2) Pushkeys.prompt() self.logger.info("Done!") def SetOnosEnvVar(self, handle, masterpass, agentpass): """ Setup onos pushkeys to all devices(3+2) parameters: handle(input): current working handle masterpass: scripts running server's password agentpass: onos cluster&compute node password """ self.logger.info("Now Setting test environment") for host in self.hosts: self.logger.info("try to connect " + str(host)) result = self.CheckSshNoPasswd(host) if not result: self.logger.info( "ssh login failed,try to copy master publickey" + "to agent " + str(host)) self.CopyPublicKey(host) self.OnosPushKeys(handle, "onos-push-keys " + self.OCT, masterpass) self.OnosPushKeys(handle, "onos-push-keys " + self.OC1, agentpass) self.OnosPushKeys(handle, "onos-push-keys " + self.OC2, agentpass) self.OnosPushKeys(handle, "onos-push-keys " + self.OC3, agentpass) self.OnosPushKeys(handle, "onos-push-keys " + self.OCN, agentpass) self.OnosPushKeys(handle, "onos-push-keys " + self.OCN2, agentpass) def CheckSshNoPasswd(self, host): """ Check master can connect agent with no password """ login = pexpect.spawn("ssh " + str(host)) index = 4 while index == 4: index = login.expect(['(yes/no)', '>|#|\$', pexpect.EOF, pexpect.TIMEOUT]) if index == 0: login.sendline("yes") index = 4 if index == 1: self.loginfo.log("ssh connect to " + str(host) + " success,no need to copy ssh public key") return True login.interact() return False def ChangeOnosName(self, user, password): """ Change onos name in envDefault file Because some command depend on this parameters: user: onos&compute node user password: onos&compute node password """ self.logger.info("Now Changing ONOS name&password") filepath = self.home + '/onos/tools/build/envDefaults' line = open(filepath, 'r').readlines() lenall = len(line) - 1 for i in range(lenall): if "ONOS_USER="******"sdn", user) if "ONOS_GROUP" in line[i]: line[i] = line[i].replace("sdn", user) if "ONOS_PWD" in line[i]: line[i] = line[i].replace("rocks", password) NewFile = open(filepath, 'w') NewFile.writelines(line) NewFile.close self.logger.info("Done!") def ChangeTestCasePara(self, testcase, user, password): """ When running test script, there's something need to change in every test folder's *.param & *.topo files user: onos&compute node user password: onos&compute node password """ self.logger.info("Now Changing " + testcase + " name&password") if self.masterusername == 'root': filepath = '/root/' else: filepath = '/home/' + self.masterusername + '/' filepath = (filepath + "OnosSystemTest/TestON/tests/" + testcase + "/" + testcase + ".topo") line = open(filepath, 'r').readlines() lenall = len(line) - 1 for i in range(lenall - 2): if("localhost" in line[i]) or ("OCT" in line[i]): line[i + 1] = re.sub(">\w+", ">" + user, line[i + 1]) line[i + 2] = re.sub(">\w+", ">" + password, line[i + 2]) if ("OC1" in line[i] or "OC2" in line[i] or "OC3" in line[i] or "OCN" in line[i] or "OCN2" in line[i]): line[i + 1] = re.sub(">\w+", ">root", line[i + 1]) line[i + 2] = re.sub(">\w+", ">root", line[i + 2]) NewFile = open(filepath, 'w') NewFile.writelines(line) NewFile.close def SSHlogin(self, ipaddr, username, password): """ SSH login provide a connection to destination. parameters: ipaddr: ip address username: login user name password: login password return: handle """ login = pxssh.pxssh() login.login(ipaddr, username, password, original_prompt='[$#>]') # send command ls -l login.sendline('ls -l') # match prompt login.prompt() self.logger.info("SSH login " + ipaddr + " success!") return login def SSHRelease(self, handle): # Release ssh handle.logout() def CopyOnostoTestbin(self): sourcefile = self.cipath + '/dependencies/onos' destifile = self.home + '/onos/tools/test/bin/' os.system('pwd') runcommand = 'cp ' + sourcefile + ' ' + destifile os.system(runcommand) def CopyPublicKey(self, host): output = os.popen('cat /root/.ssh/id_rsa.pub') publickey = output.read().strip('\n') tmphandle = self.SSHlogin(self.installer_master, self.installer_master_username, self.installer_master_password) tmphandle.sendline("ssh " + host + " -T \'echo " + str(publickey) + ">>/root/.ssh/authorized_keys\'") tmphandle.prompt() self.SSHRelease(tmphandle) self.logger.info("Add OCT PublicKey to " + host + " success") def OnosEnvSetup(self, handle): """ Onos Environment Setup function """ self.Gensshkey(handle) self.home = self.GetEnvValue(handle, 'HOME') self.AddKnownHost(handle, self.OC1, "karaf", "karaf") self.AddKnownHost(handle, self.OC2, "karaf", "karaf") self.AddKnownHost(handle, self.OC3, "karaf", "karaf") self.DownLoadCode(handle, 'https://github.com/wuwenbin2/OnosSystemTest.git') # self.DownLoadCode(handle, 'https://gerrit.onosproject.org/onos') if self.masterusername == 'root': filepath = '/root/' else: filepath = '/home/' + self.masterusername + '/' self.OnosRootPathChange(filepath) self.CopyOnostoTestbin() self.ChangeOnosName(self.agentusername, self.agentpassword) self.InstallDefaultSoftware(handle) self.SetOnosEnvVar(handle, self.masterpassword, self.agentpassword)
def connection(self): if self._connection is None: self._connection = Connection() return self._connection
def show_account(): db = Connection() if 'user' in session: user_data = db.call_procedure("projekt.wyszukaj_info_użytkownika('%s')" % (session['user']))[0] if request.method == 'POST': if 'mainFindUserForm' in request.form: log = request.form['mainFindUserForm'] searched_users = db.call_procedure("projekt.wyszukaj_użytkowników('%s', '%s')" % (session['user'], '%' + log + '%')) observed = db.call_procedure("projekt.wyszukaj_obserwowanych('%s')" % (session['user'])) return render_template('account.html', user_data=user_data, observed=observed, searched_users=searched_users) elif 'add' in request.form: id_obs = request.form['add'] db.add_to_observed({'id': id_obs, 'user': session['user'], 'date': datetime.now().strftime('%Y-%m-%d %H:%M:%S')}) observed = db.call_procedure("projekt.wyszukaj_obserwowanych('%s')" % (session['user'])) return render_template('account.html', user_data=user_data, observed=observed) elif 'delete' in request.form: id_obs = request.form['delete'] db.delete_from_observed({'id': id_obs, 'id_user': db.call_procedure("projekt.id_użytkownika('%s')" % (session['user']))[0]['id_użytkownika'], 'user': session['user']}) observed = db.call_procedure("projekt.wyszukaj_obserwowanych('%s')" % (session['user'])) return render_template('account.html', user_data=user_data, observed=observed) else: observed = db.call_procedure("projekt.wyszukaj_obserwowanych('%s')" % (session['user'])) return render_template('account.html', user_data=user_data, observed=observed) else: return redirect('/')
def create(address=None, port=None): return Minecraft(Connection(address, port))
def connect_output(self, other_neuron): connect = Connection(self, other_neuron, self.learning_rate) self.outputs.append(connect) other_neuron.inputs.append(connect)
def __enter__(self): self.__conn = Connection.getConnection() self.__cursor = self.__conn.cursor() logger.debug(f'Start With method ') return self.__cursor
noticias = json.loads(req.text) for news in noticias['articles']: titulo = news['title'] link = news['url'] new = 'Alfio_bot: ' + titulo + ' ' + link + '\n' self.caixa_de_mensagem.send_keys(new) time.sleep(1) if __name__ == "__main__": try: con = Connection() #con = Connection('sigma.blisk.solutions',9906,'root','mt14GWE04L6Csjuk') logging.basicConfig(level=logging.DEBUG,format='%(asctime)s-%(levelname)s-%(message)s') logging.disable(logging.DEBUG) bot = wppbot('Alfio_bot') bot.treina('treino/') bot.inicia('Treino_bot') #configura o grupo do whatsapp escolhido bot.saudacao(['Alfio_bot: Oi sou o Alfio_bot e entrei no grupo!','Alfio_bot: Use :: no início para falar comigo!','Alfio_bot: Tenho um vasto(?) conhecimento sobre provas. Digite ::prova seguido do nome da disciplina, grau (p1,p2 ou p3) e nome do professor (tudo em minúsculo e sem assentos) da prova desejada, e eu consultarei no meu banco de dados. Ex. ::prova estatistica p1 rossana','Alfio_bot: e de quebra, também posso dizer as noticias. Use ::noticias para ficar informado dos fatos mais recentes que eu conseguir ;)']) ultimo_texto = '' while True: texto = bot.escuta() if texto != ultimo_texto and texto == 'atrasado' or texto == 'atrasei' or texto == 'vou chegar tarde' or texto == 'onde é a sala' or texto == 'onde é a sala?' or texto == 'qual a sala?' or texto == 'qual a sala' or texto == 'que sala' or texto == 'onde é a aula?' or texto == 'onde e a aula?' or texto == 'vou me atrasar' or texto == 'to atrasado' or texto == 'e ae galera! Vou me atrasar!' or texto == 'e ae galera vo me atrasa' or texto == 'e ae galera vo me atrasa!' or texto == 'que sala?' or texto == 'que sala': bot.rapidinha('Eu não me atraso nunca. NUNCA!')
def test_find_by_alias(self): con = Connection("http://127.0.0.1:9888") key = Keys.find_by_alias(con, "sender-key") print(key.alias, key.xpub, key.file) self.assertIsNotNone(key)
def realizar_operacao (opcao): if opcao == 1: cpf=meu_cpf() cpf_valido = valid_cpf(cpf) if cpf_valido == 1: nome = meu_nome() nome_valido = valid_nome(nome) email = meu_email() email_valido = validate_email(email) if nome_valido == 1 and email_valido == 1: conn = Connection().getConnection() cur = conn.cursor() cur.execute ("insert into pessoa (nome, cpf, email, logado) values ('{0}','{1}','{2}','1')".format(nome, cpf, email)) conn.commit() conn.close() menu() else: menu() else: menu() #-------------------------------------------------------------------------- #Menu Select elif opcao == 2: acao_select = int(input("O que gostaria de fazer?\n1- Ver tudo\n2- Consultar por CPF\n3- Consultar por email\n4- Sair\n\nDIGITE: ")) if acao_select == 1: conn = Connection().getConnection() cur = conn.cursor() cur.execute("select * from pessoa where logado = '1'") rows = cur.fetchall() for row in rows: print(row[0], str(row[1]), row[2], row[3]) conn.close() menu() #-------------------------- elif acao_select == 2: cpf=meu_cpf() cpf_valido = valid_cpf(cpf) if cpf_valido == 1: conn = Connection().getConnection() cur = conn.cursor() cur.execute("select * from pessoa where logado = '1' and cpf = '{0}'".format(cpf)) rows = cur.fetchall() for row in rows: print(row[0], str(row[1]), row[2], row[3]) conn.close() menu() else: menu() #-------------------------- elif acao_select == 3: email = meu_email() email_valido = validate_email(email) if email_valido == 1: conn = Connection().getConnection() cur = conn.cursor() cur.execute("select * from pessoa where logado = '1' and email = '{0}'".format(email)) rows = cur.fetchall() for row in rows: print(row[0], str(row[1]), row[2], row[3]) conn.close() menu() else: print("Email não encontrado.") menu() #-------------------------- elif acao_select == 4: print("Adeus.") menu() #-------------------------- else: print ("Opção inválida. Tente novamente.") menu() #-------------------------------------------------------------------------- #Menu Atualizar elif opcao == 3: acao_select = int(input("O que gostaria de fazer?\n1- Atualizar nome\n2- Atualizar email\n3- Sair\n\nDIGITE: ")) if acao_select == 1: cpf = meu_cpf() cpf_valido = valid_cpf(cpf) nome = meu_nome() nome_valido = valid_nome(nome) if nome_valido == 1: conn = Connection().getConnection() cur = conn.cursor() cur.execute("update pessoa set nome = '{0}' where cpf = '{1}'".format(nome,cpf)) conn.commit() conn.close() else: print ("Nome inválido. Tente novamente.") #-------------------------- elif acao_select == 2: cpf = meu_cpf() cpf_valido=valid_cpf(cpf) email = meu_email() email_valido = validate_email(email) if email_valido == 1: conn = Connection().getConnection() cur = conn.cursor() cur.execute("Update pessoa set email = '{0}'".format(email)) conn.commit() conn.close() else: print ("Email inválido. Tente novamente.") menu() #-------------------------- elif acao_select == 3: menu() else: print ("Opção inválida. Tente novamente.") menu() #-------------------------------------------------------------------------- #Menu Deletar elif opcao == 4: cpf=meu_cpf() cpf_valido = valid_cpf(cpf) if cpf_valido == 1: conn = Connect().getConnection() cur = conn.cursor() cur.execute("update pessoa set logado = 0 where cpf = '{0}'".format(cpf)) conn.commit() conn.close() menu() else: print ("CPF inválido. Tente novamente.") #-------------------------------------------------------------------------- #Menu Sair elif opcao == 0: print("Adeus.") exit() #-------------------------------------------------------------------------- else: print ("Comando inválido. Tente novamente.") menu()
def test_create(self): con = Connection("http://127.0.0.1:9888") key = Keys.create(con, "sheng", "123456") print(key.alias, key.xpub, key.file) self.assertIsNotNone(key)
def get_database_name(cls): '''Get the database name related to `cls`.''' db_name = (cls.meta['db'] if 'db' in cls.meta else Connection.get_default_database_name()) return db_name
def test_delete(self): con = Connection("http://127.0.0.1:9888") xpub = Keys.find_by_alias(con, "sheng").xpub status = Keys.delete(con, xpub, "123456") self.assertIs("true", status) pass
def start_handler(ns): verb = verbose_print(ns.verbose) conn = Connection(verb, ssh=False) behaviors = conn.get_installed_behaviors() if ns.life: inp = io.prompt_for_behavior(behaviors) try: verb('Switch focus to: {}'.format(inp)) conn.life_switch_focus(inp) except RuntimeError: # this is a huge hack but its not my fault verb('Couldnt find behavior {} so appending "/.": {}'.format( inp, inp + '/.')) inp = inp + '/.' verb('switch focus to: {}'.format(inp)) conn.life_switch_focus(inp) else: services = conn.get_declared_services() inp = io.prompt_for_behavior(services + behaviors) if inp in services: verb('Start service: {}'.format(inp)) conn.start_service(inp) elif inp in behaviors: verb('Start behavior: {}'.format(inp)) conn.start_behavior(inp) else: print('{}: {} is not an eligible behavior or service'.format( col.red('ERROR'), inp))
def test_delete_by_alias(self): con = Connection("http://127.0.0.1:9888") status = Keys.delete_by_alias(con, "sheng", "123456") self.assertIs("true", status)
def shutdown_handler(ns): verb = verbose_print(ns.verbose) conn = Connection(verb, ssh=False) print('Shutting down ...') conn.robot_shutdown()
def test_reset_password(self): con = Connection("http://127.0.0.1:9888") xpub = Keys.find_by_alias(con, "sheng").xpub print(xpub) status = Keys.reset_password(con, xpub, "567890", "123456") self.assertIs("true", status)
def wake_handler(ns): verb = verbose_print(ns.verbose) conn = Connection(verb, ssh=False) print('Waking up {}'.format(conn.get_robot_name())) conn.wake_up()
def test_list(self): con = Connection("http://127.0.0.1:9888") key_list = Keys.list(con) for key in key_list: print(key.alias, key.xpub, key.file) self.assertIsNotNone(key_list)