Ejemplo n.º 1
0
    def __init__(self,
                 serial_no=uuid.uuid4(),
                 display_name=None,
                 channel_interface_serial_no=None,
                 data_transformer=None,
                 config=None,
                 *args,
                 **kwargs):
        ABC.__init__(self)
        self.display_name = self.set_display_name(display_name)
        self.serial_no = serial_no
        self.channel_serial_no = channel_interface_serial_no
        self.channel = id_channels_map[str(self.channel_serial_no)]
        Accessory.__init__(self,
                           driver=driver,
                           display_name=self.display_name,
                           *args,
                           **kwargs)

        self.service = self.add_functional_service()
        self.char = self.add_functional_service_characteristic()
        if config is not None and 'datatransformer' in config.keys():
            self.data_transformer = config['datatransformer']
        if config is not None and 'data_transformer' in config.keys():
            self.data_transformer = config['data_transformer']
Ejemplo n.º 2
0
    def __init__(
        self,
        name: str,
        screen: Screen,
        parent: "TUI",
        previous_form: Optional[str] = None,
        next_form: Optional[str] = None,
    ) -> None:
        """Base class for TUI forms.

        Args:
            name: The name of the form.
            screen: The screen where the form will be displayed.
            parent: The parent TUI.
            previous: The name of the previous form (optional).
            next: The name of the next form (optional).
        """
        ABC.__init__(self)
        Frame.__init__(
            self,
            screen,
            int(screen.height),
            int(screen.width),
            name=name,
            on_load=self.refresh,
        )
        self.set_theme("bright")
        self.parent = parent
        self.previous_form = previous_form
        self.next_form = next_form
        self.draw()
Ejemplo n.º 3
0
    def __init__(self, weather=None):
        gym.Env.__init__(self)
        ABC.__init__(self)

        self.first_step = True
        self.config = None
        self.state = None
        self.current_plant_id = None
        self.current_time = None
        self.plant_type = 'Tomato'
        self.maturity = 0
        self.empty_sessions = OrganicSessions()
        self.action_dict = ['wait', 'water', 'harvest', 'fertilize']
        assert (len(self.action_dict) == env_args['num_products'])

        if weather is None:
            self.weather = np.zeros((env_args['harvest_period']))
        else:
            assert (len(weather) == env_args['harvest_period'])
            self.weather = weather

        self.day = 0
        self.water_level = 3
        self.fertilizer = 0
        self.water_opti = 10
        self.ferti_opti = 10

        #Getting the history of each day
        self.env_history = None
    def __init__(self,
                 name,
                 PATH_TO_CKPT,
                 PATH_TO_LABELS,
                 IMG_SCALE,
                 WITH_TRACKER=True,
                 ENABLE_BY_DEFAULT=False):

        threading.Thread.__init__(self)
        ABC.__init__(self)
        self.threadName = name
        self.done = False
        self.pause = not ENABLE_BY_DEFAULT

        self.IMG_SCALE = IMG_SCALE

        # TRACKER
        self.WITH_TRACKER = WITH_TRACKER
        try:
            self.category_index, self.NUM_CLASSES = self.get_label_map(
                PATH_TO_LABELS)
        except:
            self.done = True
            self.category_index = None
            self.NUM_CLASSES = None
            print("Error. Unable to load label map. Check your paths!")
Ejemplo n.º 5
0
 def __init__(self, mapping: Mapping, label_encoder: LabelEncoder):
     Object.__init__(self)
     ABC.__init__(self)
     data.Dataset.__init__(self)
     self.mapping = mapping
     self.label_encoder = label_encoder
     self.transforms = None
Ejemplo n.º 6
0
    def __init__(self):
        Object.__init__(self)
        ABC.__init__(self)
        self.model_output_folder = f"outputs/weights/{self.config.run_id}"
        self.result_output_folder = f"outputs/results/{self.config.run_id}"

        if self.config.save_best_model and not os.path.exists(
                self.model_output_folder):
            os.mkdir(self.model_output_folder)
        if self.config.save_results and not os.path.exists(
                self.result_output_folder):
            os.mkdir(self.result_output_folder)

        self.model: Optional[Union[Type[Model], nn.DataParallel]] = None
        self.optimizer: Optional[Type[Optimizer]] = None

        self.logger.info(f"Loading data mapping...")
        manifest_file = f"{self.config.data_lookup}"
        self.mapping: Mapping = Mapping(mapping_path=manifest_file)

        self.logger.info(f"Building label encoder...")
        labels = list(map(lambda x: x.label, self.mapping))
        self.label_encoder = LabelEncoder()
        self.label_encoder.fit(labels)
        self.logger.info(
            f"Created encoder with classes: {self.label_encoder.classes_}.")
Ejemplo n.º 7
0
    def __init__(self,
                 env,
                 horizon,
                 exploration_kwargs=None,
                 memory_kwargs=None,
                 n_episodes=1000,
                 batch_size=100,
                 target_update=1,
                 double=True,
                 **kwargs):
        ABC.__init__(self)
        IncrementalAgent.__init__(self, env, **kwargs)
        self.horizon = horizon
        self.exploration_kwargs = exploration_kwargs or {}
        self.memory_kwargs = memory_kwargs or {}
        self.n_episodes = n_episodes
        self.batch_size = batch_size
        self.target_update = target_update
        self.double = double

        assert isinstance(env.action_space, spaces.Discrete), \
            "Only compatible with Discrete action spaces."

        self.memory = ReplayMemory(**self.memory_kwargs)
        self.exploration_policy = \
            exploration_factory(self.env.action_space,
                                **self.exploration_kwargs)
        self.training = True
        self.steps = 0
        self.writer = None
Ejemplo n.º 8
0
    def __init__(self, A, i):
        self.state = State.stateDestination
        self.inputQ = deque([i])
        self.network_address = i

        def in_func():
            if self.inputQ:
                return self.inputQ.popleft()
            else:
                return self.inputQ_empty()

        def out_func(x):
            if self.state == State.stateDestination:
                self.outputQindex = x
            elif self.state == State.stateX:
                self.outputX = x
            elif self.state == State.stateY:
                if self.outputQindex < len(nics):
                    nics[self.outputQindex].inputQ += [self.outputX, x]
                    self.note()
                elif self.outputQindex == 255:
                    self.output_to_255(x)
                else:
                    raise ValueError("Unknown destination address!")
            self.state = next_state(self.state)

        program.__init__(self, A, in_func, out_func)
        ABC.__init__(self)
Ejemplo n.º 9
0
 def __init__(self, rel_url: str):
     # print(f'init {self.__class__.__name__}')
     QObject.__init__(self, parent=None)
     ABC.__init__(self)
     self.url = QUrl(f'http://{settings.daemon_address}{rel_url}')
     self.req = QNetworkRequest(self.url)
     self.nam = QNetworkAccessManager()
     self.nam.finished.connect(self.process_response)
Ejemplo n.º 10
0
 def __init__(self, method, aggregate, nstates, method_low=None):
     ABC.__init__(self)
     self.aggregate = aggregate
     self.computers = []
     self.computers.append(Computer.create(method, aggregate.qm, nstates))
     for i in range(1, aggregate.nfrags - 1):
         self.computers.append(
             Computer.create(method_low, aggregate.bath[i]))
Ejemplo n.º 11
0
 def __init__(self, n_cols, coord, features, is_plus_strand, max_len):
     Numerifier.__init__(self,
                         n_cols=n_cols,
                         coord=coord,
                         is_plus_strand=is_plus_strand,
                         max_len=max_len,
                         dtype=np.int8)
     ABC.__init__(self)
     self.features = features
Ejemplo n.º 12
0
 def __init__(self, name: str = "DEFAULT", empty: bool = False):
     ABC.__init__(self)
     SubWindow.__init__(self, empty)
     self._name = name
     self.setWindowTitle(self._name)
     self._win_geo_ident = self._name + "_geo"
     self._win_state_ident = self._name + "_state"
     self._settings_group_ident = "subwindow_settings"
     self._minimized = False
 def __init__(self, name, IMAGE_WIDTH=640, IMAGE_HEIGHT=480):
     threading.Thread.__init__(self)
     ABC.__init__(self)
     self.name = name
     self.image_data = ImageData()
     self.done = False
     self.IMAGE_WIDTH = IMAGE_WIDTH
     self.IMAGE_HEIGHT = IMAGE_HEIGHT
     self.cap = []
Ejemplo n.º 14
0
 def __init__(self, available_states : dict, initial_state : State, physical_data : dict):
     Simulated.__init__(self)
     ABC.__init__(self)
     self.available_states = available_states
     self.initial_state = initial_state
     self.dev_state = initial_state
     self.physical_data = physical_data
     self.next_states = []
     self.getAvailableNextStates()
Ejemplo n.º 15
0
 def __init__(self, address):
     ABC.__init__(self)
     self.address = address
     self.callbacks = []
     self.callbacks_empty = asyncio.Event(loop=_get_loop())
     self.output_msg = []
     self.output_msg_has_element = asyncio.Event(loop=_get_loop())
     self.task = None
     self.alive = False
Ejemplo n.º 16
0
    def __init__(self):
        gym.Env.__init__(self)
        ABC.__init__(self)

        self.first_step = True
        self.config = None
        self.state = None
        self.current_user_id = None
        self.current_time = None
        self.empty_sessions = OrganicSessions()
Ejemplo n.º 17
0
 def __init__(self, detectRoot, config_path='config.yml'):
     Thread.__init__(self)
     ABC.__init__(self)
     with open(config_path, 'r') as file_config:
         self.config = yaml.full_load(file_config)
     self.client = airsim.MultirotorClient()
     self.detectRoot = detectRoot
     self.detectData = DetectionData(algoritmo=self.__class__.__name__)
     self.interval = 0.5
     self._stop_detect = False
Ejemplo n.º 18
0
    def __init__(self, volatile_memory, ip_route):
        threading.Thread.__init__(self)
        ABC.__init__(self)
        print(__class__.__name__, 'inherited')

        self._publisher = network.publisher(ip_route)
        self._subscriber = network.subscriber(ip_route)

        self._reader = local.reader(volatile_memory)
        self._writer = local.writer(volatile_memory)
Ejemplo n.º 19
0
    def __init__(self, piece, verbosity=0):
        """Player class constructor."""
        self.piece = piece
        self.__verbosity = verbosity
        if piece == "x":
            self.other_piece = "o"
        else:
            self.other_piece = "x"

        ABC.__init__(self)
Ejemplo n.º 20
0
 def __init__(self, molecule):
     ABC.__init__(self)
     self.restart_wfn = None
     #
     self.molecule = molecule
     self.nuclear_repulsion_energy = molecule.nuclear_repulsion_energy()
     #
     self.ciwfn = None
     self.nstates = None
     self.forces = None
Ejemplo n.º 21
0
    def __init__(self):
        Object.__init__(self)
        ABC.__init__(self)

        self.dataset: Optional[Dataset] = Dataset(self.config.dataset_path)
        self.model: Optional[Union[Model, DataParallel]] = self.build_model()
        self.optimizer: Optional[Optimizer] = Engine.build_optimizer(
            **self.build_optimizer_params())
        self.lr_scheduler: Optional[
            lr_scheduler._LRScheduler] = self.build_lr_scheduler()
Ejemplo n.º 22
0
    def __init__(self, enable_app=False, name='not_implemented', exchange_names = ['BITSTAMP', 'LUNO']):
        ABC.__init__(self)
        
        self._connection_established = {name: asyncio.Event() for name in exchange_names}
        self._exchange_connections = {}
        self._securities = {}

        for idx, exchange_name in enumerate(exchange_names):
            conn = ExchangeConnection(enable_app=False, name=exchange_name, uri=self.get_ws_uri(exchange_name.lower()), setup_event = self._connection_established[idx])
            self._exchange_connections[exchange_name] = conn       
Ejemplo n.º 23
0
 def __init__(self, nao, nbo, nmo, rule):
     ABC.__init__(self)
     self.is_reference = False
     self.is_single = False
     self.is_double = False
     self.is_triple = False
     self.rule = rule
     self.nao = nao
     self.nbo = nbo
     self.nav = nmo - nao
     self.nbv = nmo - nbo
     self.nmo = nmo
Ejemplo n.º 24
0
    def __init__(self, **kwargs):
        ABC.__init__(self)
        self.__history_size = 0
        self.__history = []
        self.__rhs_func = None

        if 'rhs_func' in kwargs.keys():
            self.__rhs_func = kwargs['rhs_func']

        if 'step_size' in kwargs.keys():
            self.__step_size = kwargs['step_size']
        else:
            self.__step_size = 0.1
Ejemplo n.º 25
0
 def __init__(self):
     ABC.__init__(self)
     self._runtime_context = BenchmarkRuntimeContext(executor=self)
     # Performance metrics
     self._last_time = 0.0
     self._execution_counter: int = 0
     self._timing_recorder: List[float] = []
     # self._output_stream = io.StringIO()
     self._profile_stats: Optional[pstats.Stats] = None
     self._current_profiler: Optional[cProfile.Profile] = None
     # Will be set later
     self._window: Optional[AbstractBenchmarkWindow] = None
     self._result: Optional[UseCaseResult] = None
Ejemplo n.º 26
0
Archivo: ui.py Proyecto: lykius/hesiod
    def __init__(
        self,
        template_cfg: CFG_T,
        base_cfg_dir: Path,
    ) -> None:
        """Create a new user interface (UI).

        Args:
            template_file: The path to the config template file.
            base_cfg_dir: The path to the base configs directory.
        """
        ABC.__init__(self)
        self.template_cfg = template_cfg
        self.base_cfg_dir = base_cfg_dir
Ejemplo n.º 27
0
 def __init__(self, host: str, port: int):
     self.sel: selectors.DefaultSelector = selectors.DefaultSelector()
     # Start up the socket
     self.lsock = socket(AF_INET, SOCK_STREAM)
     self.lsock.bind((host, port))
     self.lsock.listen()
     # Ready to listen
     print('listening on', (host, port))
     # Set the socket to not block so that we can accept multiple connections
     self.lsock.setblocking(False)
     # Register the socket
     self.sel.register(self.lsock, selectors.EVENT_READ, data=None)
     ABC.__init__(self)
     Thread.__init__(self)
Ejemplo n.º 28
0
    def __init__(self, arg: list, window: Window):
        # pylint: disable=invalid-name
        """Initializes self.
		*arg* argument(s) to be inserted in url string.
		*window* window object.
		"""
        window.acquire()
        ABC.__init__(self)
        Process.__init__(self)
        self.arg = arg
        self.window = window
        self.url = self.url.format(*self.arg)
        self.soup = None
        self.data = dict()
Ejemplo n.º 29
0
    def __init__(self,
                 serial_port=None,
                 serial_baudrate=None,
                 serial_timeout=0.1):
        self.serial_port = serial_port
        self.serial_baudrate = serial_baudrate
        self.serial_timeout = serial_timeout

        # Create serial port
        self.serial = Serial.Serial(name=self.serial_port,
                                    baudrate=self.serial_baudrate,
                                    timeout=self.serial_timeout)

        # Call parent init
        ABC.__init__(self)
        threading.Thread.__init__(self)
Ejemplo n.º 30
0
    def __init__(self, pipeline_name: str, *, description: str, app_name: str,
                 env_config: Mapping[str, Any], schedule: Union[str, None],
                 start_date: datetime):
        ABC.__init__(self)

        self._pipeline_name = pipeline_name
        self._app_name = app_name
        self._env_config = env_config
        env_id = env_config['env_id']

        # get AWS environment configuration from the Airflow instance
        self._aws_env = requests.get(
            'http://169.254.169.254/latest/dynamic/instance-identity/document'
        ).json()
        self._region_designator = ''.join(
            part[0] for part in self._aws_env['region'].split('-'))

        # DAG assets location
        self._assets_location = (
            f"s3://iasrf-vcs-mixed-{self._region_designator}-de-{env_id}"
            f"/{PMIDAG.PRODUCT_NAME}/airflow/{app_name}/v{env_config['deployment_version']}"
        )

        # default operator arguments
        default_args = {
            'owner': PMIDAG.TEAM,
            'queue': f"{env_config['airflow_cluster_id']}.{env_id}",
            'start_date': start_date,
            'depends_on_past': False,
            'retries': 0,
            'email_on_failure': False,
            'email_on_retry': False,
            'on_failure_callback': _failure_callback
        }

        # initialize the DAG
        deployment_version_major = env_config['deployment_version'].split(
            '.')[0]
        DAG.__init__(
            self,
            f'{PMIDAG.PRODUCT_DOMAIN}-{PMIDAG.PRODUCT_NAME}-{pipeline_name}-v{deployment_version_major}-{env_id}',
            description=description,
            default_args=default_args,
            schedule_interval=schedule,
            user_defined_filters={
                'data_date_tz_offset': _data_date_tz_offset_filter
            })