Esempio n. 1
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()
Esempio n. 2
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()
Esempio n. 3
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()
Esempio n. 4
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()
Esempio n. 5
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 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
Esempio n. 7
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()
Esempio n. 8
0
    def find_point(self, t=0.5, method='arc_connect'):

        layer = int(t // 1)
        t = t - layer
        if layer >= self.depth - 1:
            layer = self.depth - 2
            t = 1

        assert layer < self.depth, 'the network is shot for this t value'
        W10 = deepcopy(self.weights_adjusted[layer])
        W20 = deepcopy(self.weights_model2[0::2][layer])

        B10 = deepcopy(self.weights_model1[1::2][layer])
        B20 = deepcopy(self.weights_model2[1::2][layer])

        W11 = deepcopy(self.weights_model1[0::2][layer + 1])
        # W11b2 = deepcopy(self.weights_adjusted[layer + 1])

        W1_butterflyed = self.butterfly_weights(W10, B10)
        W2_butterflyed = self.butterfly_weights(W20, B20)
        GO = self.solve_optimal_transport_problem(W1_butterflyed,
                                                  W2_butterflyed)
        indices = np.argmax(GO, axis=-1)
        W2_butterflyed_permuted = W2_butterflyed[indices]

        W20, B20 = self.unbutterfly_weights(W2_butterflyed_permuted, W20.shape)

        Wn0 = getattr(Connector(W10, W20), method)(t=t)[1]
        Bn0 = getattr(Connector(B10, B20), method)(t=t)[1]

        # beg new
        weights_model_till_n1 = self.weights_model2[:2 * layer] + [
            Wn0, Bn0
        ] + self.weights_model1[2 * layer + 2:]
        m_till_n1 = get_model_from_weights(weights_model_till_n1,
                                           self.architecture)
        features_new = self.get_funcs(m_till_n1,
                                      self.loader,
                                      layer + 1,
                                      padding=self.padding,
                                      kernel_size=self.kernel_size,
                                      stride=self.stride)
        Wn1 = self.adjust_weights(
            self.funcs1[layer],
            features_new,
            W11,
        )
        # end new

        weights_model_t = self.weights_model2[:2 * layer] + [
            Wn0, Bn0, Wn1
        ] + self.weights_model1[2 * layer + 3:]
        m = get_model_from_weights(weights_model_t, self.architecture)
        return m
Esempio n. 9
0
 def get_connect_str(self, connobj):
     if isinstance(connobj, dict):
         self._connobj = Connector(**connobj)
         self._connobj._engine = self
         return self._connobj.connect_str
     elif isinstance(connobj, Connector):
         self._connobj._engine = self
         return connobj.connect_str
     elif isinstance(connobj, basestring):
         self._connobj = Connector(connect_str=connobj)
         self._connobj._engine = self
         return connobj
     raise Exception('Error %s\'connector type: %s(%s)' %
                     (self.__class__.__name__, connobj, type(connobj)))
Esempio n. 10
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
Esempio n. 11
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
 def connect_butterflies(W10,
                         W20,
                         B10,
                         B20,
                         W11,
                         W11b2,
                         t=0.5,
                         method='arc_connect'):
     Wn0 = getattr(Connector(W10, W20), method)(t=t)[1]
     Bn0 = getattr(Connector(B10, B20), method)(t=t)[1]
     Wn1 = getattr(
         Connector(PointFinderStepWiseButterflyConvWBias.transpose(W11),
                   PointFinderStepWiseButterflyConvWBias.transpose(W11b2)),
         method)(t=t)[1]
     Wn1 = PointFinderStepWiseButterflyConvWBias.transpose(Wn1)
     return Wn0, Bn0, Wn1
Esempio n. 13
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
Esempio n. 14
0
    def load_from_connector(self, name, method_name):
        '''
        Load given connector (name) and apply the given method on it.
        Supported method: get_accounts and get_history.

        Expected fields:

        * login
        * password
        * website (optional)
        '''
        params_connector = {
            'login': self.login,
            'password': self.password,
        }

        if self.website is not None:
            params_connector['website'] = self.website

        try:
            connector = Connector(name, params_connector)
            results = {}
            callback = getattr(connector, method_name)
            results[name] = callback()
        except ModuleLoadError:
            raise Exception("Could not load module: %s" % name)
        except BrowserIncorrectPassword:
            raise Exception("Wrong credentials")
        except Exception as e:
            EnsurePrint(unicode(e))
            raise Exception("Something went wrong (weboob modules should "
                            "probably be updated)")

        return results
Esempio n. 15
0
 def test_connector_instance_creation_without_connection_to_database_wrong(
         self):
     with self.assertRaises(connector.DatabaseConnectionError) as raised_exception:
         inst = Connector("sad", 'sad', 'someesindex', 'sda')
     self.assertEqual(
         raised_exception.exception.args[0],
         'Connection to databes has failed')
Esempio n. 16
0
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']
Esempio n. 17
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")
Esempio n. 18
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()
Esempio n. 19
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")
Esempio n. 20
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)
Esempio n. 21
0
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']
Esempio n. 22
0
    def __new__(self, shape):
        if shape == "Chart":
            return Chart()
        if shape == "Image":
            return Image()
        if shape == "Table":
            return Table()
        if shape == "BarCode":
            return BarCode()
        if shape == "Text":
            return Text()
        if shape == "Rounded":
            return Rounded()
        if shape == "Box":
            return Box()
        if shape == "Connector":
            return Connector()
        if shape == "Curve":
            return Curve()
        if shape == "Line":
            return Line()
        if shape == "Arc":
            return Arc()

        return None
Esempio n. 23
0
    def find_point(self, t=0.5, method='lin_connect'):

        layer = int(t // 1)
        t = t - layer
        if layer >= self.depth - 1:
            layer = self.depth - 2
            t = 1

        assert layer < self.depth, 'the network is shot for this t value'
        W11 = self.weights_model1[layer + 1]
        W20 = self.weights_model2[layer]
        W10 = self.weights_adjusted[layer]
        W11b2 = self.weights_adjusted[layer + 1]
        weights1 = self.butterfly_weights(W10, W11)
        weights2 = self.butterfly_weights(W20, W11b2)
        GO = self.solve_optimal_transport_problem(weights1, weights2)
        # TODO: make an assertion that there are only zero and ones in GO
        indices = np.argmax(GO, axis=-1)

        weights2_permuted = weights2[indices]
        weights_model_new = getattr(Connector(weights1, weights2_permuted), method)(t=t)[1]
        Wn0, Wn1 = self.unbutterfly_weights(weights_model_new, len(W10.T))
        weights_model_t = self.weights_model2[:layer] + [Wn0, Wn1] + self.weights_model1[layer + 2:]

        m = get_model_from_weights(weights_model_t, self.architecture)
        m.cuda();
        return m
Esempio n. 24
0
    def __init__(self, client, peer_id, addr, socket=None, info_hash=None):
        self._client = client
        self._socket = socket
        self._info_hash = info_hash
        self._peer_id = peer_id
        self._addr = addr

        self._choked = True
        self._interested = False
        self._peer_choked = True
        self._peer_interested = False

        if len(peer_id) != 20:
            raise ValueError("Peer id must be 20 bytes long")

        if socket is None:
            if info_hash is None or len(info_hash) != 20:
                raise ValueError("Info hash must be a 20 byte value")

            self._translator = None
            self._socketreaderwriter = None
            Connector().connect(addr, self)

            self._state = self._States.Awaiting_Connection
        else:
            self._setup_handshake_translator()
            self._state = self._States.Awaiting_Handshake
Esempio n. 25
0
    def generate_connections(self):
        try:
            self.atom_labels, self.bonds
        except AttributeError:
            raise Exception("Simulation has not been assigned atom types and bonds yet")

        connect = Connector()
        self.bond_types = connect.find_bond_types(self.atom_labels, self.bonds)
        self.bond_labels = connect.bond_labels(
            self.atom_labels, self.bonds, self.bond_types
        )

        self.bond_graph = self.generate_bond_graph(self.bonds)

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

        self.dihedrals = connect.dihedrals(self.bonds, self.bond_graph)
        self.dihedral_types = connect.find_dihedral_types(
            self.atom_labels, self.dihedrals
        )
        self.dihedral_labels = connect.dihedral_labels(
            self.atom_labels, self.dihedrals, self.dihedral_types
        )

        self.impropers = connect.impropers(self.bonds, self.bond_graph)
        self.improper_types = connect.find_improper_types(
            self.atom_labels, self.impropers
        )
        self.improper_labels = connect.improper_labels(
            self.atom_labels, self.impropers, self.improper_types
        )
Esempio n. 26
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()
Esempio n. 27
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)
Esempio n. 28
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)
Esempio n. 29
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)
Esempio n. 30
0
	def mode(self, mode = 'hour', color = [0, 0, 0]):
		"""
		Update Dotti to the given mode
		
		Args:
			mode (str): either 'hour' or 'color'
			color (arr[int, int, int]): R,G,B color to use
		"""

		conn = Connector(self.mac)
		conn.connect()

		if not conn.isconnected:
			conn.connect()
			if not conn.isconnected:
				return
		
		try:
			if mode == 'color':
				conn.writeCharacteristic('0x2a', '0601'+self.__twoDigitHex(int(color[0]))+self.__twoDigitHex(int(color[1]))+self.__twoDigitHex(int(color[2]))+'00')
			elif mode == 'hour':
				conn.writeCharacteristic('0x2a', '040502')

		except Exception as error:
			logger.error(str(error))

		conn.disconnect()
		return