Exemple #1
0
def main():
    global connector
    global detector

    # Get port argument
    if len(sys.argv) < 2:
        raise Exception("Missing port argument")
    port = None
    try:
        port = int(sys.argv[1])
        if type(port) is not int or port < 1 or port > 65535:
            raise Exception()
    except:
        raise TypeError(
            "Port argument must be an integer between 1 and 65535 (inclusive)")

    # Connect to server
    connector = Connector(port, message_received)

    # Start Detector
    detector = Detector(new_detections)
    detector.start_detections()

    # Notify server that the client has started
    connector.send_message(Message(100, "{}"))

    # Keep the program alive
    detector._thread.join()
Exemple #2
0
 def addConnectors(self):
     for i in range(self.mapBorder, self.width - self.mapBorder):
         for j in range(self.mapBorder, self.height - self.mapBorder):
             for k in range(-1, 2, 2):
                 if self.tiles[i - 1][j] != self.tiles[
                         i + 1][j] and self.tiles[i][j] == 0 and self.tiles[
                             i - 1][j] != 0 and self.tiles[
                                 i + 1][j] != 0 and self.tiles[
                                     i - 1][j] != 1000 and self.tiles[
                                         i + 1][j] != 1000:
                     self.tiles[i][j] = 1000
                     self.connectors.append(
                         Connector(
                             len(self.connectors) + 1, i, j,
                             self.tiles[i - 1][j], self.tiles[i + 1][j], 0))
                 if self.tiles[i][j - 1] != self.tiles[i][
                         j + 1] and self.tiles[i][j] == 0 and self.tiles[i][
                             j - 1] != 0 and self.tiles[i][
                                 j + 1] != 0 and self.tiles[i][
                                     j - 1] != 1000 and self.tiles[i][
                                         j + 1] != 1000:
                     self.tiles[i][j] = 1000
                     self.connectors.append(
                         Connector(
                             len(self.connectors) + 1, i, j,
                             self.tiles[i][j + 1], self.tiles[i][j - 1], 0))
    def __init__(self, type, id_zamowienia):
        super().__init__()
        self.setWindowTitle("Podgląd zamówienia")
        self.layout = QVBoxLayout()
        if type == "ekwipunek":
            info = create_info_box(
                '"Zamowienie-ekwipunek"', id_zamowienia, "id_zamowienia", int,
                ["id_zamowienia", "koszt", "data_zam", "deadline"])
            numer_seryjny = Connector.get_filtered(
                "ekwipunek", ["numer_seryjny"],
                " WHERE id_zamowienia = " + str(id_zamowienia))[0][0]
            ekwipunek = create_info_box(
                "ekwipunek", numer_seryjny, "numer_seryjny", int,
                ["typ", "producent", "model", "numer_seryjny"])
            ekwipunek.setTitle("Ekwipunek")
            self.layout.addWidget(info)
            self.layout.addWidget(ekwipunek)
        else:
            info = create_info_box(
                '"Zamowienie-pojazd"', id_zamowienia, "id_zamowienia", int,
                ["id_zamowienia", "koszt", "data_zam", "deadline"])
            id_pojazdu = Connector.get_filtered(
                "pojazdy", ["id_pojazdu"],
                " WHERE id_zamowienia = " + str(id_zamowienia))[0][0]
            pojazd = create_info_box(
                "pojazdy", id_pojazdu, "id_pojazdu", int,
                ["rodzaj", "producent", "model", "id_pojazdu"])
            pojazd.setTitle("Pojazd")
            self.layout.addWidget(info)
            self.layout.addWidget(pojazd)

        self.setMinimumSize(300, 230)
        self.setLayout(self.layout)
Exemple #4
0
    def __init__(self, server, options):
        Connector.__init__(self, "ig.com", server, options)

        self._host = "ig.com"
        self._base_url = "/api/v2/"
        self._timeout = 7
        self._connected = False
        self._server = server

        # config
        self._host = options['connector'].get('host', "ig.com")
        self._account_id = options['connector'].get('accountId', "")
        self.__username = options['connector'].get('username', "")
        self.__password = options['connector'].get('password', "")
        self.__api_key = options['connector'].get('apiKey', "")

        self._session = None
        self._ig_service = None
        self._client_id = None
        self._lightstreamer = None

        self._account_type = "LIVE" if self._host == "api.ig.com" else "DEMO"

        self._cached_tick = {}  # last cached tick when none value
        self._ig_tick_subscriptions = {}  # tick subscriptions id per market id

        # trader capacity, instanciate it
        self._trader = IGTrader(self)
 def __init__(self, id_jednostki):
     super().__init__()
     self.unit_id = id_jednostki
     self.setWindowTitle("Przydziały")
     self.setMinimumSize(400, 350)
     #self.listTab1 = None
     #self.refresh_eq_assignments()
     #self.listTab2 = None
     #self.refresh_vh_assignments()
     self.listTab1 = self.create_list_tab(
         ["Od", "Do", "PESEL oficera", "Numer seryjny"],
         Connector.get_filtered(
             '"Przydzial-ekwipunek"',
             ["data_od", "data_do", "pesel_oficera", "numer_seryjny"],
             " WHERE (SELECT id_jednostki FROM oficerowie WHERE pesel LIKE pesel_oficera) = "
             + self.unit_id +
             " AND (data_do >= current_date OR data_do is NULL) " +
             " ORDER BY data_od DESC"), "ekwipunek")
     self.insertTab(0, self.listTab1, "Ekwipunek")
     self.listTab2 = self.create_list_tab(
         ["Od", "Do", "PESEL oficera", "ID pojazdu"],
         Connector.get_filtered(
             '"Przydzial-pojazd"',
             ["data_od", "data_do", "pesel_oficera", "id_pojazdu"],
             " WHERE (SELECT id_jednostki FROM oficerowie WHERE pesel LIKE pesel_oficera) = "
             + self.unit_id +
             " AND (data_do >= current_date OR data_do is NULL) " +
             " ORDER BY data_od DESC"), "pojazdy")
     self.insertTab(1, self.listTab2, "Pojazdy")
     self.addWindow = None
     self.deleteWindow = None
     self.previewWindow = None
     self.setCurrentIndex(0)
Exemple #6
0
def runConnectorRefused():
    confi['configs'][0]['parameters'][0]['state'] = 'BEGIN'
    confi['configs'][0]['parameters'][0]['action'] = 'BEGIN'
    confi['configs'][0]['parameters'][0]['flags'] = 'RPA'
    con = Connector(confi, debug=3)
    con.runbg()
    return con
Exemple #7
0
    def setUp(self):
        c = omero.client(
            pmap=['--Ice.Config=' + (os.environ.get("ICE_CONFIG"))])
        try:
            self.root_password = c.ic.getProperties().getProperty(
                'omero.rootpass')
            omero_host = c.ic.getProperties().getProperty('omero.host')
        finally:
            c.__del__()

        blitz = Server.find(host=omero_host)
        if blitz is None:
            Server.reset()
            for s in settings.SERVER_LIST:
                server = (len(s) > 2) and unicode(s[2]) or None
                Server(host=unicode(s[0]), port=int(s[1]), server=server)
            Server.freeze()
            blitz = Server.find(server=omero_host)

        if len(blitz):
            self.server_id = blitz[0].id
            connector = Connector(self.server_id, True)
            self.rootconn = connector.create_connection(
                'TEST.webadmin', 'root', self.root_password)

            if self.rootconn is None or not self.rootconn.isConnected(
            ) or not self.rootconn.keepAlive():
                raise exceptions.Exception("Cannot connect")
        else:
            raise exceptions.Exception("'%s' is not on omero.web.server_list" %
                                       omero_host)
Exemple #8
0
 def confirm(self):
     rodzaj = self.rodzaj.currentText()
     producent = self.producent.text()
     model = self.model.text()
     masa = self.masa.text()
     zaloga = self.zaloga.text()
     zasieg = self.zasieg.text()
     rok = self.rok.text()
     rejestracja = self.rejestracja.text()
     if rejestracja == "":
         rejestracja = None
     id_zamowienia = None
     if self.id_pojazdu is not None:
         if (Connector.update_row("pojazdy", [
                 "rodzaj", "producent", "model", "rok_produkcji", "masa",
                 "liczba_zalogi", "zasieg", "rejestracja", "status"
         ], [
                 rodzaj, producent, model, rok, masa, zaloga, zasieg,
                 rejestracja, self.status
         ], self.id_pojazdu, "id_pojazdu", int)):
             self.commited.emit()
             self.close()
     else:
         if (Connector.create_vehicle([
                 rodzaj, producent, model, masa, zaloga, zasieg,
                 self.status, rok, rejestracja, self.id_jednostki,
                 id_zamowienia
         ])):
             self.commited.emit()
             self.close()
Exemple #9
0
def create_info_box(tablename, id, idname, idtype, columns=None):
    box = QGroupBox("Informacje")
    layout = QFormLayout()
    if columns is not None:
        data = Connector.get_dict(tablename, columns, id, idname, idtype)
    else:
        data = Connector.get_dict(tablename, column_names[tablename], id,
                                  idname, idtype)
        if tablename == "pojazdy" and data["status"] == "Zamówiony":
            ex_columns = [
                "rodzaj", "producent", "model", "rok_produkcji", "masa",
                "liczba_zalogi", "zasieg", "rejestracja", "id_jednostki",
                "status", "id_zamowienia"
            ]
            data = Connector.get_dict(tablename, ex_columns, id, idname,
                                      idtype)
        if tablename == "ekwipunek" and data["status"] == "Zamówiony":
            ex_columns = [
                "typ", "producent", "model", "numer_seryjny", "data_produkcji",
                "data_waznosci", "status", "id_zamowienia"
            ]
            data = Connector.get_dict(tablename, ex_columns, id, idname,
                                      idtype)
    font = QFont()
    font.setBold(True)
    for k, v in data.items():
        if v is None:
            label = QLabel(str("-"))
        else:
            label = QLabel(str(v))
        label.setFont(font)
        layout.addRow(formatter[k] + ": ", label)
    box.setLayout(layout)
    return box
Exemple #10
0
    def test_loginFromForm(self):
        params = {
            'username': '******',
            'password': self.root_password,
            'server':self.server_id,
            'ssl':'on'
        }        
        request = fakeRequest(method="post", params=params)
        
        server_id = request.REQUEST.get('server')
        form = LoginForm(data=request.REQUEST.copy())
        if form.is_valid():
            username = form.cleaned_data['username']
            password = form.cleaned_data['password']
            server_id = form.cleaned_data['server']
            is_secure = toBoolean(form.cleaned_data['ssl'])

            connector = Connector(server_id, is_secure)
            conn = connector.create_connection('OMERO.web', username, password)
            if conn is None:
                self.fail('Cannot connect')
            
            conn.seppuku()
            if conn.isConnected() and conn.keepAlive():
                self.fail('Connection was not closed')
            
        else:
            errors = form.errors.as_text()
            self.fail(errors)
Exemple #11
0
    def __init__(self, slave = False, protocol = None, address = None, port = None, target_name = None):
        self.config = Configurator()
        self.is_connected = False
        self.is_slave = slave
        self.parameters = None
        self.datastream_queue = None
        self.datastream_poller = None
        self.datastream_collector = None
        self.signal_structure = None

        # Sets basic configurations
        if protocol:
            self.config.setAttr('protocol', protocol)

        if address:
            self.config.setAttr('address', address)

        if port:
            self.config.setAttr('port', port)

        if target_name:
            self.config.setAttr('target_name', target_name)

        # Initializes connection
        self.connection = Connector(self.config)
 def confirm(self):
     data_od = self.data_od.text()
     data_do = self.data_do.text()
     oficer = self.oficerowie[self.oficer.currentIndex()][2]
     if self.type == "ekwipunek":
         ekwipunek = self.eq[self.ekwipunek.currentIndex()][3]
         if (Connector.insert_row(
                 '"Przydzial-ekwipunek"',
             ["data_od", "data_do", "pesel_oficera", "numer_seryjny"],
             [data_od, data_do, oficer, ekwipunek])):
             if Connector.update_row("ekwipunek", ["status"],
                                     ["Przydzielony"], ekwipunek,
                                     "numer_seryjny", int):
                 self.commited.emit()
                 self.close()
     else:
         pojazd = self.vh[self.pojazdy.currentIndex()][2]
         if (Connector.insert_row(
                 '"Przydzial-pojazd"',
             ["data_od", "data_do", "pesel_oficera", "id_pojazdu"],
             [data_od, data_do, oficer, pojazd])):
             if Connector.update_row("pojazdy", ["status"],
                                     ["Przydzielony"], pojazd, "id_pojazdu",
                                     int):
                 self.commited.emit()
                 self.close()
Exemple #13
0
def upload_livery():

    user = validate_request(request.headers)
    if not user:
        abort(401)

    if not os.path.exists(download_dir):
        os.mkdir(download_dir)

    filename = str(uuid.uuid4()) + '.zip'

    if not 'file' in request.files\
        or not 'Name' in request.form\
        or not 'Checksum' in request.form:

        abort(400)

    liv = Livery()
    liv.name = request.form['Name'][:50]  # limited to 50 chars
    liv.checksum = request.form['Checksum'][:40]  # limited to 40
    liv.filename = filename
    liv.owner_id = user.id

    if Connector.get_livery_by_name(liv.name):
        abort(409)  # livery duplicate

    liv = Connector.add_livery(liv)

    data = request.files['file']
    data.save(download_dir + filename)

    return jsonify(liv.to_json())
    def setUp (self):
        c = omero.client(pmap=['--Ice.Config='+(os.environ.get("ICE_CONFIG"))])
        try:
            self.root_password = c.ic.getProperties().getProperty('omero.rootpass')
            omero_host = c.ic.getProperties().getProperty('omero.host')
        finally:
            c.__del__()

        blitz = Server.find(host=omero_host)
        if blitz is None:
            Server.reset()
            for s in settings.SERVER_LIST:
                server = (len(s) > 2) and unicode(s[2]) or None
                Server(host=unicode(s[0]), port=int(s[1]), server=server)
            Server.freeze()
            blitz = Server.find(server=omero_host)
        
        if len(blitz):
            self.server_id = blitz[0].id
            connector = Connector(self.server_id, True)
            self.rootconn = connector.create_connection('TEST.webadmin', 'root', self.root_password)

            if self.rootconn is None or not self.rootconn.isConnected() or not self.rootconn.keepAlive():
                raise exceptions.Exception("Cannot connect")
        else:
            raise exceptions.Exception("'%s' is not on omero.web.server_list" % omero_host)
Exemple #15
0
    def post(self):
        # Region Set Up

        #create resultService object
        _resultsService = ResultsService()
        #load queries
        q = Queries()
        # create connection to postgres database
        _connector = Connector()
        conn = _connector.connect(1)

        # create cursor
        cur = conn.cursor()

        #define query parameters
        _failID = self.get_argument("_failureId")

        # endregion
        # Region main block

        cur.execute(q._email_failure, (_failID, ))
        _result = cur.fetchall()
        _result_to_json = _resultsService.parse(_result)

        self.render("emailMonitor.html", results=_result)

        cur.close()
        conn.close
Exemple #16
0
 async def check(self, proxy: ProxyModel):
     logger.debug('Start Verify Proxy: %s' % proxy)
     proxy.usable = False
     judge = self.https_judge if proxy.protocol == 'https' else self.http_judge
     content = None
     conn = Connector(proxy.ip, proxy.port)
     negotiator = NGTRS[proxy.protocol.upper()](conn)
     try:
         await conn.connect()
         await negotiator.negotiate(judge)
         headers, content, hdrs = await _send_test_request(
             self._method, conn, negotiator, judge)
         content = _decompress_content(headers, content)
         judge.parse_response(proxy, content, hdrs)
     except ProxyError:
         pass
     except JSONDecodeError:
         # Config.logger.error('Json decode error when using %s' % proxy)
         logger.debug(content)
     except Exception as e:
         logger.error('Error: %s, type: %s' % (proxy, type(e)),
                      exc_info=True)
     finally:
         conn.close()
     proxy.verified_at = datetime.datetime.now()
     self.finished += 1
     logger.debug('Finished Proxy: %s' % (proxy))
     return proxy
Exemple #17
0
    def post(self):
        # Region Set Up

        #create resultService object
        _resultsService = ResultsService()
        #load queries
        q = Queries()
        # create connection to postgres database
        _connector = Connector()
        conn = _connector.connect(2)

        # create cursor
        cur = conn.cursor()

        #define query parameters
        _firstname = self.get_argument("_firstname_field")
        _lastname = self.get_argument("_lastname_field")
        _timenow = datetime.datetime.now()
        # endregion
        # Region main block

        _query = q._get_all_users
        cur.execute(_query)
        _result = cur.fetchall()
        _result_to_json = _resultsService.parse(_result)

        _query = q._create_new_user
        cur.execute(_query, (_firstname, _lastname, _timenow))
        conn.commit()

        cur.close()
        conn.close
        self.redirect("/users")
Exemple #18
0
    def post(self):
        # Region Set Up
        _resultsService = ResultsService()
        _q = Queries()
        _connector = Connector()
        conn = _connector.connect(2)
        cur = conn.cursor()

        # endregion
        # Region Main Block
        cur.execute(_q._get_all_users)
        _result = cur.fetchall()
        _result_to_json = _resultsService.parse(_result)

        for item in _result:
            _rID = str(item[3])
            _id = self.get_arguments("_checkbox")
            if _rID in _id:
                print("Deleting " + str(item[0]))
                cur.execute(_q._delete_user, (item[3], ))
                conn.commit()

        cur.close()
        conn.close()
        self.redirect("/users")
Exemple #19
0
def poolLoadTSV((tsv, ks_minor, units, db, ksm_filter, ksm_id, rename, host,
                 port, is_json)):
    """
  This function is used by multiprocess.Pool to populate framespace with a new dataframe.
  """
    try:
        # register vectors and get the dataframe object for insert
        conn = Connector(db, host=host, port=port)
        if is_json:
            df_id = conn.registerDataFrame(tsv,
                                           ks_minor,
                                           units,
                                           is_json=is_json)
        else:
            df_id = conn.registerDataFrame(
                getDataFrame(tsv,
                             ksminor_id=ksm_id,
                             ksminor_filter=ksm_filter,
                             rename=rename), ks_minor, units)

    except Exception, e:
        traceback.print_exc(file=sys.stdout)

        print "Error processing"
        print str(e)
        return (-1, tsv)
def add_insta(received):
    username = received['username']
    password = received['password']
    user = received['user']
    conn = Connector()
    result = conn.add_insta(username, password, user)
    return result['message']
def schedule_posting(received):
    user = received['user']
    img = received['img']
    binary_image = received['binary_image']
    subtitle = received['subtitle']
    location = received['location']
    instagram = received['instagram']
    date = received['date']

    date_image = f'{datetime.now().year}-' + f'{datetime.now().month}-' + f'{datetime.now().day}'

    BASE_DIR = os.path.dirname(os.path.abspath(__file__))
    img_path = os.path.join(BASE_DIR, f"uploads/{date_image}-{user}-{img}")

    if date < datetime.now():
        return 'Horario invalido'

    conn = Connector()
    result = conn.add_schedule(img_path, subtitle, location, instagram, date,
                               user)
    if result['status'] != None:
        # Salvando a imagem na pasta upload com o nome padrão : yyyy-mm-dd-email-name.jpeg
        with open((img_path), 'wb') as f:
            f.write(binary_image)
            f.close()
        scheduler()
        time.sleep(1)
        return 'success'
        # return send_api(received, img_path)

    return result['message']
Exemple #22
0
    def setupGraphics(self):
        n1 = Nand2(self, "N1", self.scale1((80, 30)))  # Nand Gate
        i1 = Inv(self,   "I1")  # Inverter for n1.A
        i2 = Inv(self,   "I2")  # Inverter for n1.B
        # external connectorself. Same depth as xor circuit
        i1.align(i1.B, n1.A, -40, -20)  # inverter precedes Nand
        i2.align(i2.B, n1.B, -40,  20)  # inverter precedes Nand
        self.A = Connector(self, "A", ((i1.A.x(-20), i1.A.y())))
        self.B = Connector(self, "B", ((i2.A.x(-20), i2.B.y())))
        self.C = Connector(self, "C", ((n1.C.x( 20), n1.C.y())))
        self.output = self.C       # who is output

        self.gates = (i1, i2, n1)
        self.i1, self.i2, self.n1 = (i1, i2, n1)

        i1.B.addWire(n1.A)
        i2.B.addWire(n1.B)
        self.A.addWire(i1.A)
        self.B.addWire(i2.A)
        n1.C.addWire(self.C)

        if self.encapsulated():  # if encapsulated re-work externals
            self.A.pos, self.B.pos, self.C.pos = self.scaleM(( 0,  5),
                                                             ( 0, 35),
                                                             (20, 20))
Exemple #23
0
 def __init__(self):
     rospy.init_node('Gateway', log_level=rospy.DEBUG)
     server_config_file = rospy.get_param("~server_config_file")
     self.config = Config(server_config_file)
     self.pf = ProtocolFactory(self.config)
     self.run_id = rospy.get_param("run_id")
     print("runid = ", self.run_id)
     self.node_list = rosnode.get_node_names()
     self.timer = Timer()
     self.monitor = Monitor(self.node_list, self.timer)
     self._server_request = {}  # stores server_request
     self._event_bus = Queue()
     self._heartbeat_timeout_job = None
     self._tele_report_job = None
     self._report_car_job = None
     self._report_task_job = None
     self._service = DrivingTaskService(self._event_bus)
     self.__client = Connector(self._event_bus, self.config.host,
                               self.config.port)
     self._handler_map = {}
     self._event_handler_map = {}
     self._add_command_handler()
     self._add_event_handler()
     self._web_server = WebServer(self.monitor, self._service, self.config)
     self._tele_control_service = TeleControlService()
Exemple #24
0
 def create_tabs(self):
     self.listTab1 = self.create_list_tab(["Oznaczenie", "Rola"],
                                          Connector.get_filtered("budynki", ["oznaczenie", "rola_budynku"],
                                                                 " WHERE id_jednostki = " + self.unit_id +
                                                                 " AND (UPPER(oznaczenie) LIKE UPPER('%" +
                                                                 self.filter_budynki.text() + "%')" +
                                                                 " OR UPPER(rola_budynku) LIKE UPPER('%" +
                                                                 self.filter_budynki.text() + "%'))" +
                                                                 " ORDER BY oznaczenie ASC"),
                                          "budynki")
     self.insertTab(1, self.listTab1, "Budynki")
     self.listTab2 = self.create_list_tab(["ID", "Producent", "Model"],
                                          Connector.get_filtered("pojazdy", ["id_pojazdu", "producent", "model"],
                                                                 " WHERE id_jednostki = " + self.unit_id +
                                                                 " AND (UPPER(model) LIKE UPPER('%" +
                                                                 self.filter_pojazdy.text() + "%')" +
                                                                 " OR UPPER(producent) LIKE UPPER('%" +
                                                                 self.filter_pojazdy.text() + "%'))" +
                                                                 " ORDER BY id_pojazdu ASC"),
                                          "pojazdy")
     self.insertTab(2, self.listTab2, "Pojazdy")
     self.listTab3 = self.create_list_tab(["Imię", "Nazwisko", "PESEL"],
                                          Connector.get_filtered("oficerowie", ["imie", "nazwisko", "pesel"],
                                                                 " WHERE id_jednostki = " + self.unit_id +
                                                                 " AND (UPPER(imie) LIKE UPPER('%" +
                                                                 self.filter_oficerowie.text() + "%')" +
                                                                 " OR UPPER(nazwisko) LIKE UPPER('%" +
                                                                 self.filter_oficerowie.text() + "%')" +
                                                                 " OR UPPER(pesel) LIKE UPPER('%" +
                                                                 self.filter_oficerowie.text() + "%'))" +
                                                                 " ORDER BY nazwisko, imie ASC"),
                                          "oficerowie")
     self.insertTab(3, self.listTab3, "Oficerowie")
Exemple #25
0
def fill_gen_assign_workshop_attendee():

    connector = Connector()
    conn = connector.connect(secretpassword)
    cursor = conn.cursor()

    workshop_attendees = []

    cursor.execute("select distinct Attendees.AttendeeID, WorkshopReservations.WReservationID "
                   "from Attendees "
                   "inner join Participation on Participation.AttendeeID = Attendees.AttendeeID "
                   "inner join Reservations on Reservations.ReservationID = Participation.ReservationID "
                   "inner join WorkshopReservations on WorkshopReservations.ReservationID = Reservations.ReservationID")

    row = cursor.fetchone()

    while row:
        workshop_attendees.append((row[0], row[1]))
        row = cursor.fetchone()

    filler = Connector()

    workshop_attendees_size = len(workshop_attendees)
    filler.apply_proc_multi('AssignParticipantToWorkshop', workshop_attendees, workshop_attendees_size)



    conn.close()
def _generate_token_list():
    return [
        Connector.build(TerminalSymbol.OPEN),
        Variable.build('x'),
        Connector.build(TerminalSymbol.PLUS),
        Variable.build('y'),
        Connector.build(TerminalSymbol.CLOSE)
    ]
Exemple #27
0
 def setUp(self):
     with patch('connector.create_engine') as mocked_engine:
         with patch('connector.MetaData') as mocked_metadata:
             with patch('connector.Table') as mocked_table:
                 mocked_table.return_value.columns = [
                     "Table", 'name', 'somethingelse']
                 self.inst = Connector(
                     'somedb', 'sometable', 'someesindex', 'somedb_type')
Exemple #28
0
 def get(self):
     self.render("index.html")
     conn = Connector()
     session = conn.r_connect()
     test = session.query(object_type=Timesheet).where_in(
         "NumericID", [1800, 1799])
     for ts in test:
         print(ts.tsStatus)
Exemple #29
0
def makeRequestFavico():
    con = Connector(config, debug=3)
    con.runbg()

    my_IPaddress = "http://%s" % (get_my_IPaddress('eth0'))

    r = requests.get(my_IPaddress + '/favicon.ico', timeout=5)
    return r.text
Exemple #30
0
def makeRequest500():
    con = Connector(config, debug=3)
    con.runbg()

    my_IPaddress = "http://%s" % (get_my_IPaddress(config['interface']))

    r = requests.get(my_IPaddress + '/500', timeout=5)
    return r
 def find_point(self, t, method='arc_connect'):
     assert 0 <= t <= 1, 't must be between 0 and 1'
     weights_model_new = getattr(Connector(self.weights_model1, self.weights_model2_permuted), method)(t=t)[1]
     B = self.get_b(self.model1, self.model2)
     B = getattr(Connector(B[:1], B[1:]), method)(t=t)[1]
     m = self.get_model_from_weights(weights_model_new, B[0], self.architecture)
     m.cuda();
     return m
Exemple #32
0
def main():
    config = SafeConfigParser()
    config.read(PROPERTIES_FILE)
    ctor = Connector(config)
    report = ctor.get_result()

    prsr = Parser()
    prsr.parse(report)
    prsr.format()
	def fetch_news_by_feed_list(self, news_data):
		conn = Connector()
		for n in news_data['news_items']:
			print("INF: Fetching news page for '{}'".format(n['link']))
			news_item_page = conn.send_req('GET', url=n['link'])
			if news_item_page is None:
				continue

			self.__get_article_from_html__(n, news_item_page.data)
Exemple #34
0
def runConnectorEHOSTUNREACH():
    confi['configs'][0]['parameters'][0]['sub-category'] = 'icmz'
    confi['configs'][0]['parameters'][0]['state'] = 'ESTABLISHED'
    confi['configs'][0]['parameters'][0]['action'] = 'sendAck'
    confi['configs'][0]['parameters'][0]['type'] = 3
    confi['configs'][0]['parameters'][0]['code'] = 1
    con = Connector(confi, debug=3)
    con.runbg()
    return con
Exemple #35
0
    def fetch_news_by_feed_list(self, news_data):
        conn = Connector()
        for n in news_data['news_items']:
            print("INF: Fetching news page for '{}'".format(n['link']))
            news_item_page = conn.send_req('GET', url=n['link'])
            if news_item_page is None:
                continue

            self.__get_article_from_html__(n, news_item_page.data)
 def loginAsUser(self, username, password):
     blitz = Server.get(pk=self.server_id) 
     if blitz is not None:
         connector = Connector(self.server_id, True)
         conn = connector.create_connection('TEST.webadmin', username, password)
         if conn is None or not conn.isConnected() or not conn.keepAlive():
             raise Exception("Cannot connect")
         return conn
     else:
         raise Exception("'%s' is not on omero.web.server_list"  % self.omero_host)
Exemple #37
0
class MainController:
    def __init__(self, app):
        self.deviceData = DeviceData()
        self.view = MainView(None)
        self.view.scanForDevices.Bind(wx.EVT_BUTTON, self.ScanForDevices)
        self.view.syncActivities.Bind(wx.EVT_BUTTON, self.SyncActivities)
        self.view.Bind(wx.EVT_MENU, self.OnAbout, self.view.aboutMenuItem)
        self.view.Bind(wx.EVT_MENU, self.OnExit, self.view.exitMenuItem)
        self.view.Show()
        self.scanner = Scanner()
        ## TODO Preferences for Selected Scanners
        self.scanner.addScanner(AntScanner())
        self.connector = Connector()
        ## TODO Preferences for Selected Connectors
        self.connector.addConnector(GarminConnector())
        pub.subscribe(self.ScanningStarted, "SCANNING STARTED")
        pub.subscribe(self.DeviceDetected, "DEVICE DETECTED")
        pub.subscribe(self.ActivityRetrieved, "ACTIVITY RETRIEVED")
        pub.subscribe(self.ScanningEnded, "SCANNING ENDED")
        pub.subscribe(self.SyncStarted, "SYNC STARTED")
        pub.subscribe(self.SyncEnded, "SYNC ENDED")
        pub.subscribe(self.LoginSuccesful, "LOGIN SUCCESFUL")
        pub.subscribe(self.LoginFailed, "LOGIN FAILED")
        pub.subscribe(self.ActivitiesUploaded, "ACTIVITIES UPLOADED")
    def ScanForDevices(self, evt):
        self.scanner.scan()
    def ScanningStarted(self, evt):
        self.view.setStatus("Scanning started")
    def ScanningEnded(self, evt):
        self.view.setStatus("Scanning ended")
    def DeviceDetected(self, evt):
        self.view.setStatus("Device detected")
    def ActivityRetrieved(self, evt):
        self.view.setStatus("Retrieved activity")
    def SyncActivities(self, evt):
        self.connector.sync()
    def SyncStarted(self, evt):
        self.view.setStatus("Sync started")
    def SyncEnded(self, evt):
        self.view.setStatus("Sync ended")
    def LoginSuccesful(self, evt):
        self.view.setStatus("Login Succesful")
    def LoginFailed(self, evt):
        self.view.setStatus("Login Failed")
    def ActivitiesUploaded(self, evt):
        self.view.setStatus("Activities Uploaded")
    def OnExit(self,e):
        self.Close(True)
    def OnAbout(self, event):
        dlg = wx.MessageDialog( self.view, "A community-developed Linux version of the ANT Agent. Supports Garmin-based fitness devices that communicate either over USB serial or via the ANT USB connector. Developed by Philip Whitehouse, based on work by Braiden Kindt, Gustav Tiger and Collin (cpfair). Copyright 2014", "About ANT Agent for Linux", wx.OK);
        dlg.ShowModal()
        dlg.Destroy()
Exemple #38
0
  def inject_metric(self,quiet):
    if self.value == None:
      self.load_value()

    if quiet == False:
      self.print_metric()

    cw = Connector()
    retval = cw.inject(self.metricname,self.namespace,self.value,self.units,self.dimensions)
    
    if retval == -1:
      sys.stderr.write("\033[91mERROR: Monitor [" + self.monid + "] failed to be injected into CloudWatch.\n")
      sys.stderr.write("  -- Check JSON entry and that command is returning proper value and format.\033[0m\n")
 def __init__(self, p12_path, p12_password, p12_buffer=None, production=True, request_timeout=2.0, proxy=None):
     self.connector = Connector(p12_path=p12_path,
                                p12_password=p12_password,
                                p12_buffer=p12_buffer,
                                production=production,
                                request_timeout=request_timeout,
                                proxy=proxy)
    def setUp (self):
        c = omero.client(pmap=['--Ice.Config='+(os.environ.get("ICE_CONFIG"))])
        try:
            self.root_password = c.ic.getProperties().getProperty('omero.rootpass')
            self.omero_host = c.ic.getProperties().getProperty('omero.host')
            self.omero_port = c.ic.getProperties().getProperty('omero.port')
            Server.reset()
            Server(host=self.omero_host, port=self.omero_port)
        finally:
            c.__del__()

        self.server_id = 1
        connector = Connector(self.server_id, True)
        self.rootconn = connector.create_connection('TEST.webadmin', 'root', self.root_password)
        if self.rootconn is None or not self.rootconn.isConnected() or not self.rootconn.keepAlive():
            raise Exception("Cannot connect")
Exemple #41
0
 def __init__(self, ip, port, automatic = True, control_buf_size = 32, data_buf_size = 128, \
     m_to = 0.01, socket_to = 0.005):
     """
     Constructor, initialize the modem and the connector. Connect the
     modem to the submerged node
     @param self pointer to the class object
     @param ip string cointaining the IP address of the TCP server
     @param port string with the port of the TCP server socket
     @param control_buf_size: int with the control buffer size, in bytes
     @param data_buf_size: int with the data buffer size, in bytes
     @param m_to: float value time out of the cycle, in [s]
     @param socket_to: time out of the socket checking operation, [s]
     """
     self.conn = Connector(ip, port, control_buf_size, data_buf_size, socket_to)
     self.conn.connect()
     self.m_to = m_to
     self.status = Modem.Status.IDLE
     self.node_status = 0
     self.automatic = automatic
     self.interpreter = Interpreter()
     self.mainPID = os.getpid()
     self.error_status = Modem.ErrorDict.NONE
     self.commands_queue = "".split(Interpreter.END_COMMAND)
     if automatic:
         thread.start_new_thread(self.run,())
Exemple #42
0
    def __init__(self, slave=False, protocol=None, address=None, port=None, target_name=None):
        self.config = Configurator()
        self.is_connected = False
        self.is_slave = slave
        self.parameters = None
        self.datastream_queue = None
        self.datastream_poller = None
        self.datastream_collector = None
        self.signal_structure = None

        # Sets basic configurations
        if protocol:
            self.config.setAttr("protocol", protocol)

        if address:
            self.config.setAttr("address", address)

        if port:
            self.config.setAttr("port", port)

        if target_name:
            self.config.setAttr("target_name", target_name)

        # Initializes connection
        self.connection = Connector(self.config)
Exemple #43
0
	def __init__(self):
		# initialize file table
		self.maxFiles = 1024
#		self.files = [dict(path=None, dirty=False, data=None)] * self.maxFiles
		self.files = [None] * self.maxFiles
		for i in range(0, self.maxFiles):
			self.files[i] = dict(path=None, dirty=False, data=None)
		self.conn = Connector()
 def __init__(self, url, profile, store, assessor, notifications, update_interval = 180, name = "Unnamed Observer"):
     super(Observer, self).__init__()
     self._interval = update_interval
     self._connector = Connector(url, profile)
     self._store = store
     self._assessor = assessor
     self._notifications = notifications
     self._name = name
     self._quit = False
     self._time_mark = datetime.datetime.now() - datetime.timedelta(days = 1)
     self._state = Observer.RUNNING
     self.name = name
Exemple #45
0
def clone_repo(src, dest):
    """
    Clone a repository.
    
    Arguments:
    src  -- URL of to the repository to clone from.
    dest -- URL of the target directory of the clone.
    
    Returns:
    A clone of the supplied repository.
    """
    src_connector = Connector.from_string(src)
    with src_connector.connected():
        origin = repo.Repo.load_from_disk(src_connector)
        dest = os.path.join(dest, origin.name)  # make clone at "<dest>/<name>"
        dest_connector = Connector.from_string(dest)
        with dest_connector.connected():
            clone = repo.Repo.clone(origin, dest_connector)
    init_repo_logging(clone)
    log.info("Cloned repository from %s to %s" % (src, dest))
    return clone
Exemple #46
0
def fill_gen_add_attendees():
    connector = Connector()
    conn = connector.connect(secretpassword)
    cursor = conn.cursor()

    cursor.execute("select company.clientid, spotsreserved from company "
                   "inner join clients on clients.clientid = company.clientid "
                   "inner join reservations on reservations.clientid = clients.clientid")
    row = cursor.fetchone()

    c = Connector()
    cn = c.connect(secretpassword)

    while row:
        clientid = row[0]
        spots_reserved = row[1]

        for reservation in range(spots_reserved):

            name, surname = getNameSurname()
            result = (clientid, name, surname)
            print("Add Attendee " + str(result))
            c.apply_proc('AddAttendee', result)

        row = cursor.fetchone()

    conn.close()
    cn.close()
Exemple #47
0
def fill_gen_add_payment():
    connector = Connector()
    conn = connector.connect(secretpassword)
    cursor = conn.cursor()

    cursor.execute("select ReservationID, ToPay, ReservationDate from Reservations")
    row = cursor.fetchone()

    ratio = [i / 10 for i in range(1, 11)]

    c = Connector()
    cn = c.connect(secretpassword)

    while row:
        reservationid = row[0]
        topay = row[1]
        date = row[2]
        money_deposited = math.floor(int(topay) * random.choice(ratio))

        (y, m, d) = date.split("-")
        begin = dt.date(int(y), int(m), int(d)).toordinal()
        book_ord = dt.datetime.fromordinal(begin + random.randint(1, 7))
        date_of_payment = "/".join((str(book_ord.year), str(book_ord.month), str(book_ord.day)))

        result = (reservationid, money_deposited, date_of_payment)
        print("Add Payment " + str(result))
        c.apply_proc('GeneratorAddPayment', result)

        row = cursor.fetchone()

    conn.close()
    cn.close()
Exemple #48
0
def fill_gen_book_places_for_workshop():
    connector = Connector()
    conn = connector.connect(secretpassword)
    cursor = conn.cursor()

    cursor.execute("select Reservations.ReservationID, WorkshopID, MaxSpots "
                   "from DaysOfConf "
                   "inner join Workshops on Workshops.DayID = DaysOfConf.DayID "
                   "inner join Reservations on Reservations.DayID = DaysOfConf.DayID")
    row = cursor.fetchone()

    c = Connector()
    cn = c.connect(secretpassword)

    while row:
        reservationid = row[0]
        workshopid = row[1]
        maxspots = math.floor(row[2] / 3)

        result = (reservationid, workshopid, maxspots)
        print("Add Workshop Reservation " + str(result))
        c.apply_proc('BookPlacesForWorkshop', result)

        row = cursor.fetchone()

    conn.close()
    cn.close()
    def generate_connections(self):
        connect = Connector()
        bond_types, angle_types, torsion_types, improper_types = self.molecule.connection_types()
        self.bonds = self.molecule.assign_bonds(self.lattice_dimensions)
        self.bond_labels = connect.bond_labels(self.atom_labels, self.bonds, bond_types)

        self.angles = connect.angles(self.bonds)
        self.angle_labels = connect.angle_labels(self.atom_labels, self.angles, angle_types)

        self.torsions = connect.torsions(self.bonds)
        self.torsion_labels = connect.torsion_labels(self.atom_labels, self.torsions, torsion_types)

        self.impropers = connect.impropers(self.bonds)
        self.improper_labels = connect.improper_labels(self.atom_labels, self.impropers, improper_types)
Exemple #50
0
    def test_loginFromRequest(self):
        params = {
            'username': '******',
            'password': self.root_password,
            'server':self.server_id,
            'ssl':'on'
        }        
        request = fakeRequest(method="post", path="/webadmin/login", params=params)
        
        server_id = request.REQUEST.get('server')
        username = request.REQUEST.get('username')
        password = request.REQUEST.get('password')
        is_secure = toBoolean(request.REQUEST.get('ssl'))

        connector = Connector(server_id, is_secure)
        conn = connector.create_connection('TEST.webadmin', username, password)
        if conn is None:
            self.fail('Cannot connect')
        
        conn.seppuku()
        if conn.isConnected() and conn.keepAlive():
            self.fail('Connection was not closed')
Exemple #51
0
def fill_gen_assign_attendee():

    connector = Connector()
    conn = connector.connect(secretpassword)
    cursor = conn.cursor()

    individual_participation = []

    cursor.execute("select distinct Attendees.AttendeeID, Reservations.ReservationID "
                   "from Attendees "
                   "inner join Clients on Attendees.ClientID = Clients.ClientID "
                   "inner join Reservations on Reservations.ClientID = Clients.ClientID "
                   "inner join Individual on Individual.ClientID = Clients.ClientID")

    row = cursor.fetchone()

    while row:
        individual_participation.append((row[0], row[1]))
        row = cursor.fetchone()

    company_participation = []

    cursor.execute("select distinct Attendees.AttendeeID, Reservations.ReservationID "
                   "from Attendees "
                   "inner join Clients on Attendees.ClientID = Clients.ClientID "
                   "inner join Reservations on Reservations.ClientID = Clients.ClientID "
                   "inner join Company on Company.ClientID = Clients.ClientID")

    row = cursor.fetchone()

    while row:
        company_participation.append((row[0], row[1]))
        row = cursor.fetchone()

    # Two list of (AttendeeID, ReservationID) to apply

    # The following lines may cause declination of IDE control xD
    # print(individual_participation)
    # print(len(individual_participation))
    # print(company_participation)
    # print(len(company_participation))

    # Those insertions causes error -> try block
    filler = Connector()

    individual_size = len(individual_participation)
    filler.apply_proc_multi('AssignAttendee', individual_participation, individual_size)

    company_size = len(company_participation)
    filler.apply_proc_multi('AssignAttendee', company_participation, company_size)

    conn.close()
Exemple #52
0
    def run(s):

        s.log.info('Started host node {0} on {1}'.format(s.nodename, s.address))

        # Make some count of creator
        for i in range(0, s.creators):

            # Create instance
            creator = Creator(s.nodename)

            # Run thread
            creator.start()

            # Logging
            s.log.info('Started creator thread: {0}'.format(creator.name))

        # Make connector
        connector = Connector(s.nodename)

        # Run connector thread
        connector.start()

        # Logging
        s.log.info('Started connector thread: {0}'.format(connector.name))
Exemple #53
0
    def test_loginFailure(self):
        params = {
            'username': '******',
            'password': '******',
            'server':self.server_id
        }        
        request = fakeRequest(method="post", params=params)
        
        server_id = request.REQUEST.get('server')
        form = LoginForm(data=request.REQUEST.copy())
        if form.is_valid():
            username = form.cleaned_data['username']
            password = form.cleaned_data['password']
            server_id = form.cleaned_data['server']
            is_secure = toBoolean(form.cleaned_data['ssl'])

            connector = Connector(server_id, is_secure)
            conn = connector.create_connection('OMERO.web', username, password)
            if conn is not None:
                self.fail('This user does not exist. Login failure error!')
        
        else:
            errors = form.errors.as_text()
            self.fail(errors)            
Exemple #54
0
 def createConnector(self):
     self.view.statusBar().showMessage('connecting...')
     self.c = Connector(self.view.serverLineEdit.text(), self.view.userLineEdit.text(),
                         self.view.passwdLineEdit.text(), '')
     
     print (self.c.getWikiVersion())
     self.allPages = self.c.getAllPages()
     if (self.allPages != None):
         self.view.statusBar().showMessage('connected.')
         parentItem = self.pageModel.invisibleRootItem()
         for i in self.allPages:
             parentItem.appendRow(QStandardItem(i['id']))
         self.connected = True
     else:
         self.view.statusBar().showMessage("Couldn't get pages.")
         print ("Couldn't get pages.")
Exemple #55
0
def load_repo(url):
    """
    Load an existing repository from disk and return it.
    
    Arguments:
    url -- URL of the repository on disk.
    
    Returns:
    The loaded repository.
    """
    connector = Connector.from_string(url)
    with connector.connected():
        rep = repo.Repo.load_from_disk(connector)
    init_repo_logging(rep)
    log.info("Loaded PictureClerk repository from disk")
    return rep
Exemple #56
0
def init_repo(url):
    """
    Initialize a new repository and return it.
    
    Arguments:
    url -- URL of the repository to be initialized (e.g. '/home/user/repo').
    
    Returns:
    The initialized repository.
    """
    config = repo.new_repo_config()
    connector = Connector.from_string(url)
    with connector.connected():
        rep = repo.Repo.create_on_disk(connector, config)
    init_repo_logging(rep)
    log.info("Initialized empty PictureClerk repository")
    return rep
Exemple #57
0
    def __init__(self):        
        QMainWindow.__init__(self)
        self.setupUi(self)  # set up User Interface (widgets, layout...)
 
        self.registerAllParameters()  # we register all command line arguments
        self.job = Connector(self)  # connector object for submitting the command
        self.dirs = AdvancedChecks(self)  # Object for performing all operations on dirs
        self.lastdir = self.dirs.homedir  # set the starting open directory to HOME
        
        ## TODO: just for GUI testin
        self.afsaccount.setChecked(1)
        
        QObject.connect(self.setinputdirectory,
            SIGNAL("clicked()"),self.getInputDirectory)  # data input directory
        QObject.connect(self.inputdirectory,
            SIGNAL("returnPressed()"),self.dirs.initInputDirectory)  # data input through keyboard
        QObject.connect(self.sinogramdirectory,
            SIGNAL("returnPressed()"),self.dirs.initSinDirectory)  # sinogram dir input through keyboard
        QObject.connect(self.setsinogramdirectory,
            SIGNAL("clicked()"),self.getSinogramDirectory)  # sinogram output
        QObject.connect(self.setcprdirectory,
            SIGNAL("clicked()"),self.getCprDirectory)  # cpr output
        QObject.connect(self.setfltpdirectory,
            SIGNAL("clicked()"),self.getFltpDirectory)  # fltp output
        QObject.connect(self.setrecodirectory,
            SIGNAL("clicked()"),self.getRecoDirectory)  # reconstructions output
        QObject.connect(self.sinon,
            SIGNAL("clicked()"),self.setUnsetSinoCheckBox)  # sinogram checkbox ("toggled" not working)
        QObject.connect(self.paganinon,
            SIGNAL("clicked()"),self.setUnsetPaganinCheckBox)  # Paganin checkbox ("toggled" not working)
        QObject.connect(self.openinfiji,
            SIGNAL("clicked()"),self.setUnsetFijiOn)  # Fiji previw image checkbox ("toggled" not working)
        QObject.connect(self.submit,
            SIGNAL("released()"),self.submitToCluster)  # BUTTON submit button
        QObject.connect(self.clearfields,
            SIGNAL("released()"),self.clearAllFields)  # BUTTON clear all fields method
        QObject.connect(self.testbutton,
            SIGNAL("released()"),self.test_button)  # BUTTON test button
        QObject.connect(self.singleslice,
            SIGNAL("released()"),self.calcSingleSlice)  # BUTTON Single Slice calculation
        QObject.connect(self.menuloadsettings,
            SIGNAL("triggered()"),self.loadConfigFile)  # MENU load settings
        QObject.connect(self.menusavesettings,
            SIGNAL("triggered()"),self.saveConfigFile)  # MENU save settings
def transfer_gtfs_ckan(full_gtfs=False):
    # Pass full_gtfs as True if you want to import
    # all the GTFS data to CKAN.
    try:
        print 'Retrieving GTFS data from OST...',
        connector = Connector()
        if full_gtfs:
            connector.fetch_full_gtfs()
            print 'Done.'
            print 'Pushing GTFS files to CKAN\'s DataStore...',
            connector.push_to_ckan(gtfs_csv=True)
        else:
            connector.fetch_gtfs_stops()
            print 'Done.'
            print 'Importing Transit Stops to CKAN\'s DataStore...',
            connector.push_to_ckan()
            print 'Done.'
    except CKANError as error:
        message = Fore.RED + str(error) + Fore.RESET + ': ' + \
            error.message
        print('\n> ' + message)
    except (APIKeyError, CrawlerError, OSTError) as error:
        message = get_error_message(error)
        print(Fore.RED + str(error) + Fore.RESET + ':' + message)
Exemple #59
0
def backup_repo(rep, *urls):
    """
    Backup a repository to multiple locations.
    
    Arguments:
    rep  -- Repository to be backed up
    urls -- Backup repository to these locations (1 or more URL args).
    
    Returns:
    Backup repositories (clones of the supplied respositories).
    """
    backups = list()
    for url in urls:
        url = os.path.join(url, rep.name)
        connector = Connector.from_string(url)
        with rep.connector.connected(), connector.connected():
            backup = repo.Repo.clone(rep, connector)
        init_repo_logging(backup)
        backups.append(backup)
        log.info("Backed up repository to %s" % url)
    return backups