Example #1
0
 def pilot_monitor(self):
    log_info('starting pilot state monitor')
    rc_timeout = 1.0
    return_when_signal_lost = False
    last_valid = time()
    while True:
       self.pilot.mon_read()
Example #2
0
 def __init__(self, sockets):
     logfile = user_data_dir + sep + 'ICARUS.log'
     log_config(filename=logfile,
                level=DEBUG,
                format='%(asctime)s - %(levelname)s: %(message)s')
     log_info('icarus starting up')
     self.setpoints = [0.0, 0.0, 2.0]  # x, y, z
     self.flight_time = 0
     self.icarus_takeover = False
     self.emergency_land = False
     self.factory = ICARUS_MissionFactory
     self.fsm = FlightSM(self.error, self.broadcast, self.takeoff,
                         self.land, self.move, self.stop)
     self.landing_spots = LandingSpots(3.0)
     self.pilot = PilotInterface(sockets['pilot'], sockets['mon'])
     #self.gps_shifter = GPS_Shifter()
     self.state_emitter = StateEmitter(sockets['state'])
     self.powerman = PowerMan(sockets['power_ctrl'], sockets['power_mon'])
     start_daemon_thread(self.power_state_monitor)
     start_daemon_thread(self.state_time_monitor)
     start_daemon_thread(self.pilot_monitor)
     self.activity = DummyActivity()
     self.activity.start()
     self.icarus_srv = ICARUS_Server(sockets['ctrl'], self)
     self.icarus_srv.start()
     log_info('icarus up and running')
Example #3
0
 def state_time_monitor(self):
    # count the time for "in-the-air-states":
    log_info('starting state time monitor')
    while True:
       if self.fsm.state != 'standing':
          self.flight_time += 1
       sleep(1)
Example #4
0
    def highlight(self, element):
        try:
            for elements in element:
                self.elementlist.append(elements)
            if len(self.elementlist) > 1:
                ecountpopup = Psg.PopupOKCancel("Multiple Elements "
                                                "Found!: {}".format(
                                                    len(self.elementlist)))
                if ecountpopup == "OK":
                    pass
                elif ecountpopup == "Cancel":
                    return
                else:
                    return

        except TypeError:
            self.elementlist.append(element)

        if len(self.elementstore) == 1:
            log_info("Single Element Store Needs to be Emptied")
            try:
                log_info("Removing Previous Element from Single Store")
                self.highlight_remove(element)
                log_info("Single Removed:".format(element))
            except (NoSuchElementException, TypeError,
                    StaleElementReferenceException) as elem_remove_error:
                log_error(elem_remove_error)
            self.elementstore.clear()
            log_info("Emptied Single Element from Store")

        if len(self.elementstore) > 1:
            log_info("Multiple Element Store Needs to be Emptied")
            thread.start_new_thread(self.highlight_remove_multi, ())

        thread.start_new_thread(self.highlight_add, ())
    def __pow__(self, other):
        """
        Returns the proxied function raised at an integer power.
        :param other: Object to raise the proxied with
        :return: Value of raised proxied function
        """
        if isinstance(other, int) and other >= 0:
            
            def anon_pow_times(*args):
                """
                Multiplies the proxied function as many times as
                the integer used to raise it.
                :param args: The args used for the original function
                :return: Proxied function multiplied as many times as other
                """
                # Return the proxied function at least once (in case other==0)
                result = self
                
                for _ in range(other-1):
                    result *= self

                return result(*args)
            
            log_info("{0} raised {1} times".format(self.func.__name__, other))
            return Composable(anon_pow_times)
        
        elif isinstance(other, int) and other < 0:
            log_error("Raised {0} w/ negative int".format(self.func.__name__))
            raise ValueError("Composable can only be raised w/ positive int")
        
        log_error("Attempt to raise {0} with type {1}".format(
                    self.func.__name__, type(other)))
        raise TypeError("Composable instance can only be raised w/ integers")
    def __pow__(self, other):
        """
        Returns the proxied function raised at an integer power.
        :param other: Object to raise the proxied with
        :return: Value of raised proxied function
        """
        if isinstance(other, int) and other >= 0:

            def anon_pow_times(*args):
                """
                Multiplies the proxied function as many times as
                the integer used to raise it.
                :param args: The args used for the original function
                :return: Proxied function multiplied as many times as other
                """
                # Return the proxied function at least once (in case other==0)
                result = self

                for _ in range(other - 1):
                    result *= self

                return result(*args)

            log_info("{0} raised {1} times".format(self.func.__name__, other))
            return Composable(anon_pow_times)

        elif isinstance(other, int) and other < 0:
            log_error("Raised {0} w/ negative int".format(self.func.__name__))
            raise ValueError("Composable can only be raised w/ positive int")

        log_error("Attempt to raise {0} with type {1}".format(
            self.func.__name__, type(other)))
        raise TypeError("Composable instance can only be raised w/ integers")
Example #7
0
 def pilot_monitor(self):
     log_info('starting pilot state monitor')
     rc_timeout = 1.0
     return_when_signal_lost = False
     last_valid = time()
     while True:
         self.pilot.mon_read()
Example #8
0
 def state_time_monitor(self):
     # count the time for "in-the-air-states":
     log_info('starting state time monitor')
     while True:
         if self.fsm.state != 'standing':
             self.flight_time += 1
         sleep(1)
Example #9
0
    def sign_in(self):
        self.user_login = self.line_login.text()
        self.user_passwd = self.line_passwd.text()
        self.user_hidden = self.btn_hide.isChecked()
        self._logging()

        log_info("Sended sing_in package")
Example #10
0
 def _send_message_to_client(self, client, message):
     send_message(client.sock, message)
     log_info("sended {len} bytes to {client}: {data}".format(
         len=len(message),
         client=client,
         data=message
     ))
Example #11
0
    def __delitem__(self, key):
        x, y, z = self._validate_key(key)

        log_info("Deleting value {0} in Dict_array ins key {1}".format(self._data[x, y, z], key))

        del self._data[x, y, z]
        self.array_len -= 1
Example #12
0
 def __setitem__(self, key, value):
     """
     Sets the appropriate element for a three-element subscript tuple.
     """
     x, y, z = self._validate_key(key)
     self._data[x][y][z] = value
     log_info("Set value: {0} for List_of_lists_array element {1}".format(value, [x, y, z]))
Example #13
0
    def communication(self):
        # data = self.server_socket.readAll()
        data = qt_recv_until_end_messages(self.server_socket)
        if data:
            log_info("recieved {len} bytes from server: {data}".format(
                len=len(data),
                data=data
            ))
            response = ChatResponse()
            response.ParseFromString(data)

            if self._communication_logging(response):
                return
            elif response.command_type == ChatResponse.CHATS_AND_MESSAGES:
                self._gui_add_chats(response.chats)
                self._gui_add_messages(response.messages)
            elif response.command_type == ChatResponse.CHATS:
                self._gui_add_chats(response.chats)
                self._gui_add_messages(response.messages)
            elif response.command_type == ChatResponse.MESSAGES:
                self._gui_add_messages(response.messages)
            else:
                log_info("shit")
                exit(0)
        else:
            print("Disconnected from server")
            sys.exit()
    def __mul__(self, other):
        """
        Return the composition of proxied and another function.
        :param other: Object to multiply the proxied with
        :return: Composition of the proxied function and the passed object
        """
        if type(other) is Composable:

            def anon(x):
                return self.func(other.func(x))

            log_info("{0} multiplied by Composable obj {1}".format(
                self.func.__name__, other))
            return Composable(anon)

        elif type(other) is types.FunctionType:

            def anon(x):
                return self.func(other(x))

            log_info("{0} multiplied by function {1}".format(
                self.func.__name__, other))
            return Composable(anon)

        log_error("Attempt to multiply {0} by {1}".format(
            self.func.__name__, other))
        raise TypeError("Illegal operands for multiplication")
 def __mul__(self, other):
     """
     Return the composition of proxied and another function.
     :param other: Object to multiply the proxied with
     :return: Composition of the proxied function and the passed object
     """
     if type(other) is Composable:
         def anon(x):
             return self.func(other.func(x))
         
         log_info("{0} multiplied by Composable obj {1}".format(
                     self.func.__name__, other))
         return Composable(anon)
     
     elif type(other) is types.FunctionType:
         def anon(x):
             return self.func(other(x))
         
         log_info("{0} multiplied by function {1}".format(
                 self.func.__name__, other))
         return Composable(anon)
     
     log_error("Attempt to multiply {0} by {1}".format(
                 self.func.__name__, other))
     raise TypeError("Illegal operands for multiplication")
Example #16
0
def handle_exception(msg, e):
    maybe_print_stack()
    log_error("Caught exception at %s" %
              time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()))
    html = twill.get_browser().get_html()
    if options.dump_file == '-':
        print html
    else:
        dump_file_name = os.path.expanduser(options.dump_file)

        try:
            if html is not None:
                if options.show_error_in_browser:
                    # If we are showing it in the browser, lets get the
                    # paths right (even if if means changing the HTML a
                    # little)
                    base_href = '\n<!-- added by flunc: --><base href="%s">' % twill.get_browser(
                    ).get_url()
                    match = re.search('<head.*?>', html, re.I | re.S)
                    if match:
                        html = html[:match.end()] + base_href + html[match.end(
                        ):]
                    else:
                        html = base_href + html
                f = open(dump_file_name, 'wb')
                f.write(html)
                f.close()
                log_info("saved error html to: %s" % dump_file_name)
        except IOError, e:
            log_warn("Unable to save error HTML to: %s" % dump_file_name)
Example #17
0
 def takeoff(self):
     log_info('taking off')
     self.landing_spots.add((self.pilot.mon[0], self.pilot.mon[1]))
     self.activity.cancel_and_join()
     self.yaw_setpoint = self.pilot.mon[4]
     self.activity = TakeoffActivity(self.fsm, self)
     self.activity.start()
Example #18
0
def run_suite(name):
    try:
        if not options.cleanup_mode:
            log_info("running suite: %s" % name)
            output_stream.indent()
        try:

            suite_data = file(current_namespace[-1].suites[name]).read()
            calls = parse_suite(suite_data)

            load_configuration(name)
            load_overrides()

            error_list = []
            # skip running suites if cleanup-only mode is set
            if not options.cleanup_mode:
                for script, args, line in calls:
                    errors = run_test(script, args)
                    if len(errors):
                        error_list += [
                            name + "(%d)::%s" % (line, x) for x in errors if x
                        ]
            return error_list
        except IOError, e:
            handle_exception("Unable to read suite %s" % name, e)
            return [name]
    finally:
        do_cleanup_for(name)
        output_stream.outdent()
Example #19
0
def run_suite(name):
    try: 
        if not options.cleanup_mode:
            log_info("running suite: %s" % name)
            output_stream.indent()
        try:
        
            suite_data = file(current_namespace[-1].suites[name]).read()
            calls = parse_suite(suite_data)
        
            load_configuration(name)
            load_overrides() 

            error_list = [] 
            # skip running suites if cleanup-only mode is set 
            if not options.cleanup_mode:
                for script,args,line in calls: 
                    errors = run_test(script,args)
                    if len(errors):                     
                        error_list += [name + "(%d)::%s" % (line,x) for x in errors if x]
            return error_list
        except IOError,e: 
            handle_exception("Unable to read suite %s" % name,e)
            return [name]
    finally: 
        do_cleanup_for(name)
        output_stream.outdent()
Example #20
0
def _generate_stats(directory, base_names, stat_types, cache_file_path):
    """
    Generate the document statistics from scratch
    """
    log_info('generating statistics for "%s"' % directory)
    docstats = []
    for docname in base_names:
        with Annotations(path_join(directory, docname),
                         read_only=True) as ann_obj:
            tb_count = len([a for a in ann_obj.get_entities()])
            rel_count = (len([a for a in ann_obj.get_relations()]) +
                         len([a for a in ann_obj.get_equivs()]))
            event_count = len([a for a in ann_obj.get_events()])

            if options_get_validation(directory) == 'none':
                docstats.append([tb_count, rel_count, event_count])
            else:
                # verify and include verification issue count
                projectconf = ProjectConfiguration(directory)
                issues = verify_annotation(ann_obj, projectconf)
                issue_count = len(issues)
                docstats.append(
                    [tb_count, rel_count, event_count, issue_count])

    _store_cache_stat(docstats, cache_file_path, directory)

    return stat_types, docstats
Example #21
0
def do_cleanup_for(name):
    if has_cleanup_handler(name) and not options.no_cleanup_mode: 
        log_info("running cleanup handler for %s" % name)
        try:
            suite_data = file(current_namespace[-1].cleanup[name]).read()
            calls = parse_suite(suite_data)
            for script,args,line in calls:
                try:
                    if current_namespace[-1].suites.get(script):
                        log_warn("Cannot call sub-suite %s during cleanup at %s(%d)" % (script,name,line))
                    else:
                        log_info("running cleanup: %s" % name)
                        script_data = read_test(script)
                        try:
                            parameters = make_dict_from_call(args,get_twill_glocals()[0])
                        except (ValueError, TypeError, SyntaxError), e:
                            e.args = ("\"%s%s\": Only positional argument passing is supported in suites." % \
                                          (name, args), ) + e.args[1:]
                            raise e
                        script_data = make_twill_local_defs(parameters) + script_data 
                        twill.execute_string(script_data, no_reset=1)
                except Exception, e:
                    maybe_print_stack() 
                    log_warn("Cleanup call to %s failed at %s(%d)" 
                         % (script + args, name + CLEANUP, line))
        except IOError,e:
            maybe_print_stack()
            log_warn("Unable to read cleanup handler for %s" % name)
        except Exception,e:
            maybe_print_stack()
            log_warn("Exception during cleanup handler for %s" % name)
def def_inspect(module):
    """
    Scans a module's functions with inspect, returns their signatures, if any.
    :param module: Module, or name of module to be imported
    :return: String detailing the signature of each function in the module
    """
    # Take the __name__ attr of the module if the argument is not a string
    mod_name = module if isinstance(module, str) else module.__name__
    log_info("Attempting to inspect functions in module {}".format(mod_name))

    try:
        imported = import_module(str(mod_name))

    except ImportError as e:
        log_error(e)
        raise ImportError(e)

    result = []
    functions = inspect.getmembers(imported, inspect.isfunction)

    # For each function name, description tuple retrieved...
    for func, desc in functions:

        # ...Use getattr to take each function's signature
        func_txt = inspect.formatargspec(
            *inspect.getfullargspec(getattr(imported, func)))

        result.append("'def {0}{1}'".format(func, func_txt))

    return "\n".join(result)
def def_inspect(module):
    """
    Scans a module's functions with inspect, returns their signatures, if any.
    :param module: Module, or name of module to be imported
    :return: String detailing the signature of each function in the module
    """
    # Take the __name__ attr of the module if the argument is not a string
    mod_name = module if isinstance(module, str) else module.__name__
    log_info("Attempting to inspect functions in module {}".format(mod_name))
    
    try:
        imported = import_module(str(mod_name))
        
    except ImportError as e:
        log_error(e)
        raise ImportError(e)
    
    result = []
    functions = inspect.getmembers(imported, inspect.isfunction)
    
    # For each function name, description tuple retrieved...
    for func, desc in functions:
        
        # ...Use getattr to take each function's signature
        func_txt = inspect.formatargspec(
                   *inspect.getfullargspec(getattr(imported, func)))
        
        result.append("'def {0}{1}'".format(func, func_txt))
    
    return "\n".join(result)
Example #24
0
def handle_exception(msg, e):
    maybe_print_stack()
    log_error("Caught exception at %s" %
              time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()))
    html = twill.get_browser().get_html()
    if options.dump_file == '-':
        print html
    else:
        dump_file_name = os.path.expanduser(options.dump_file)
            
        try:
            if html is not None:
                if options.show_error_in_browser:
                    # If we are showing it in the browser, lets get the
                    # paths right (even if if means changing the HTML a
                    # little)
                    base_href = '\n<!-- added by flunc: --><base href="%s">' % twill.get_browser().get_url()
                    match = re.search('<head.*?>', html, re.I|re.S)
                    if match:
                        html = html[:match.end()] + base_href + html[match.end():]
                    else:
                        html = base_href + html
                f = open(dump_file_name, 'wb')
                f.write(html)
                f.close()
                log_info("saved error html to: %s" % dump_file_name)
        except IOError, e:
            log_warn("Unable to save error HTML to: %s" % dump_file_name)
Example #25
0
 def takeoff(self):
    log_info('taking off')
    self.landing_spots.add((self.pilot.mon[0], self.pilot.mon[1]))
    self.activity.cancel_and_join()
    self.yaw_setpoint = self.pilot.mon[4]
    self.activity = TakeoffActivity(self.fsm, self)
    self.activity.start()
Example #26
0
 def highlight_remove(self, element):
     try:
         parent = element._parent
         self.stylize_remove(parent, element, " ;")
         log_info("Element Removed")
     except (NoSuchElementException, TypeError, WebDriverException):
         log_error("Could not Remove Element Highlight")
Example #27
0
   def __init__(self, name):
      # set-up logger:
      logfile = user_data_dir() + sep + 'PowerMan.log'
      log_config(filename = logfile, level = DEBUG,
                 format = '%(asctime)s - %(levelname)s: %(message)s')
      # initialized and load config:
      log_info('powerman starting up')
      map = generate_map(name)
      self.ctrl_socket = map['ctrl']
      self.monitor_socket = map['mon']
      self.opcd = OPCD_Interface(map['opcd_ctrl'], 'powerman')
      bus = SMBus(self.opcd.get('gpio_i2c_bus'))
      self.gpio_mosfet = GPIO_Bank(bus, self.opcd.get('gpio_i2c_address'))
      self.power_pin = self.opcd.get('gpio_power_pin')
      self.cells = self.opcd.get('battery_cells')
      self.low_cell_voltage = self.opcd.get('battery_low_cell_voltage')
      self.capacity = self.opcd.get('battery_capacity')
      self.low_battery_voltage = self.cells * self.low_cell_voltage
      self.critical = False
      self.gpio_mosfet.write()
      self.warning_started = False

      # start threads:
      self.standing = True
      self.adc_thread = start_daemon_thread(self.adc_reader)
      self.emitter_thread = start_daemon_thread(self.power_state_emitter)
      self.request_thread = start_daemon_thread(self.request_handler)
      log_info('powerman running')
Example #28
0
    def __init__(self, host, port):
        self.host = host
        self.port = port
        self.connected_clients = []
        self.server_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

        # TODO
        set_default_curve()
        self.alices_private_key = keys.UmbralPrivateKey.from_bytes(
            b'\x86(\xb4Av\xa7\xf8\x1a\x16\x08\xc0K3\xa8\x1a;"i\xa8\x13Q\xc4s\xe5\x19\xef\x86@\x011\xf7\xfd'
        )
        self.alices_public_key = keys.UmbralPublicKey.from_bytes(
            b'\x03\xb6\x81\xba\x8e\xcb\x08e\x7f(\x04\xe3\xff\xbe\xc6UA\xa0\xfe5\x1c\xb2\xe0\xf0\xf7;\xd1D}NHo\xf7'
        )

        self.alices_signing_key = keys.UmbralPrivateKey.from_bytes(
            b'Q:5|\x01^=\xd6D\xbd\xed\xbb\x8f\xef\xc9\x04\xed2g}\xf3Yn\xf4\xb2\xfdZ\x03\x16\xceM\x94'
        )
        self.alices_verifying_key = keys.UmbralPublicKey.from_bytes(
            b'\x03Yn\x9dx\xa7\x1c\xd1\xad\xe5\x80\xc9[\xe8^\xae\x81\x95\xaaQ\xadi\x9d\x83\x91\x18}\xc2\x85\xe3\x1em\xd0'
        )
        self.alices_signer = signing.Signer(
            private_key=self.alices_signing_key)

        try:
            self._db_connect()
        except BaseException:
            log_info("Unable to connect database")
 def __init__(self, f):
     """
     Stores a reference to a proxied function.
     :param f: Function namespace to be proxied
     """
     self.func = f
     start_logging()
     log_info("New Composable proxied function: {0}".format(f.__name__))
Example #30
0
 def run(self):
     for _ in range(self.sleeptime):
         sleep(1)
         log_info("{0} currently located at directory {1}".format(
             self.name, os.getcwd()))
         
     log_info("{0} has finished execution at directory {1}".format(
             self.name, os.getcwd()))
Example #31
0
def thread_list(path_list):
    """
    Takes list of filepaths to create DirectoryTravelThread as many instances.
    :param path_list: List of directories to be accessed
    :return: List of DirectoryTravelThread instances
    """
    log_info("Creating a new list of DirectoryTravelThread instances")
    return [DirectoryTravelThread(path_list[i]) for i in range(len(path_list))]
Example #32
0
 def LoadResource(self, resourceName):
     global soundPlayer
     if not soundPlayer:
         try:
             soundPlayer = pyglet.media.Player()
         except Exception, ex:
             log_info('Could not construct sound Player:%s' % ex)
             return
Example #33
0
 def _takeoff_activity(self):
     log_info("taking off")
     self.landing_spots.add((self.mon_data.x, self.mon_data.y))
     self.activity.cancel_and_join()
     self.powerman.flight_power()
     self.yaw_setpoint = self.mon_data.yaw
     self.activity = TakeoffActivity(self.fsm, self)
     self.activity.start()
 def __init__(self, f):
     """
     Stores a reference to a proxied function.
     :param f: Function namespace to be proxied
     """
     self.func = f
     start_logging()
     log_info("New Composable proxied function: {0}".format(f.__name__))
Example #35
0
    def search_page_for_job_soups(self, data, page, url, job_soup_list):
        """function that scrapes the glassdoor page for a list of job soups"""
        log_info(f'getting glassdoor page {page} : {url}')

        job = BeautifulSoup(
            self.s.post(url, headers=self.headers, data=data).text,
            self.bs4_parser).find_all('li', attrs={'class', 'jl'})
        job_soup_list.extend(job)
Example #36
0
    def __delitem__(self, key):
        x, y, z = self._validate_key(key)

        log_info("Deleting value {0} in Dict_array ins key {1}".format(
            self._data[x, y, z], key))

        del self._data[x, y, z]
        self.array_len -= 1
Example #37
0
 def __setitem__(self, key, value):
     """
     Sets the appropriate element for a three-element subscript tuple.
     """
     x, y, z = self._validate_key(key)
     self._data[x][y][z] = value
     log_info("Set value: {0} for List_of_lists_array element {1}".format(
         value, [x, y, z]))
Example #38
0
 def start(self):
     self.server_sock.bind((self.host, self.port))
     log_info("Server started")
     self.server_sock.listen(10)
     try:
         self._input_loop()
     finally:
         self.server_sock.close()
Example #39
0
 def takeoff(self):
     log_info('taking off')
     self.landing_spots.add((self.mon_data.x, self.mon_data.y))
     self.activity.cancel_and_join()
     self.powerman.flight_power()
     self.yaw_setpoint = self.mon_data.yaw
     self.activity = TakeoffActivity(self.fsm, self)
     self.activity.start()
Example #40
0
 def LoadResource(self, resourceName):
         global soundPlayer
         if not soundPlayer:
                 try:
                     soundPlayer = pyglet.media.Player()
                 except Exception, ex:
                     log_info('Could not construct sound Player:%s' % ex)
                     return
Example #41
0
    def run(self):
        for _ in range(self.sleeptime):
            sleep(1)
            log_info("{0} currently located at directory {1}".format(
                self.name, os.getcwd()))

        log_info("{0} has finished execution at directory {1}".format(
            self.name, os.getcwd()))
 def check_unsubscriptions(self):
     " Checks for any subscriptor that has requested being removed. "
     for subscriber in self.subscriber_list:
         if subscriber.unsubscribe_condition():
             self.publisher.unsubscribe(subscriber.process)
             self.subscriber_list.remove(subscriber)
             
             log_info("{0} unsubscribed from {1}".format(
                     subscriber.name, publisher.__class__.__name__))
Example #43
0
    def search_page_for_job_soups(self, page, url, job_soup_list):
        """function that scrapes the glassdoor page for a list of job soups"""
        log_info(f'getting glassdoor page {page} : {url}')

        self.driver.get(url)
        job = BeautifulSoup(self.driver.page_source,
                            self.bs4_parser).find_all('li',
                                                      attrs={'class', 'jl'})
        job_soup_list.extend(job)
Example #44
0
    def get_blurb_with_delay(self, job, delay):
        """gets blurb from glassdoor job link and sets delays for requests"""
        sleep(delay)

        search = job['link']
        log_info(f'delay of {delay:.2f}s, getting glassdoor search: {search}')

        res = self.s.post(search, headers=self.location_headers).text
        return job, res
Example #45
0
    def get_blurb_with_delay(self, job, delay):
        """gets blurb from monster job link and sets delays for requests"""
        sleep(delay)

        search = job['link']
        log_info(f'delay of {delay:.2f}s, getting monster search: {search}')

        res = get(search, headers=self.headers).text
        return job, res
        def check_unsubscriptions(self):
            " Checks for any subscriptor that has requested being removed. "
            for subscriber in self.subscriber_list:
                if subscriber.unsubscribe_condition():
                    self.publisher.unsubscribe(subscriber.process)
                    self.subscriber_list.remove(subscriber)

                    log_info("{0} unsubscribed from {1}".format(
                        subscriber.name, publisher.__class__.__name__))
Example #47
0
    def __delitem__(self, key):
        """
        Deletes the appropriate element from _data whtough subscripting.
        """
        x, y, z = self._validate_key(key)

        log_info("Deleting: {0} from List_of_lists_array ins in {1}".format(self._data[x][y][z], [x, y, z]))
        del self._data[x][y][z]
        self.array_len -= 1
Example #48
0
    def get_blurb_with_delay(self, job, delay):
        """gets blurb from indeed job link and sets delays for requests"""
        sleep(delay)

        search = job['link']
        log_info(f'delay of {delay:.2f}s, getting indeed search: {search}')

        res = self.s.get(search).text
        return job, res
 def new_subscription(self, subscriber):
     """
     A new Subscriber has requested subscribe its process
     to the publisher. Add it to the manager's list.ty
     """
     self.publisher.subscribe(subscriber.process)
     self.subscriber_list.append(subscriber)
     
     log_info("{0} subscribed to {1}".format(
             subscriber.name, publisher.__class__.__name__))
Example #50
0
 def __init__(self, sleeptime, *args, **kwargs):
     """
     Initializes a new DirectoryTravelThead instance.
     :param path: Filepath to travel to
     """
     threading.Thread.__init__(self, *args, **kwargs)
     self.sleeptime = sleeptime
     
     log_info("New DirectoryTravelThead instance at directory {}".format(
                 os.getcwd()))
Example #51
0
 def power_state_monitor(self):
     log_info("starting power state monitor")
     while True:
         self.power_state = self.powerman.read()
         if self.power_state.critical:
             log_warn("critical power state: emergency landing")
             # disable system interface and take over control:
             self.icarus_takeover = True
             if not self.emergency_land:
                 self.emergency_landing()
Example #52
0
 def __getattr__(self, attname):
         try:
                 return self.__dict__[attname]
         except KeyError:
                 log_info( 'loader got key err' )
                 try:
                         return self._d[attname]
                 except KeyError:
                         self.LoadResource( attname )
                         return self._d[attname]
Example #53
0
 def __init__(self, key, data=None):
     """
     Create a new Tree object with empty L & R subtrees.
     :param key: Object to be used as the identifier/key of this node
     :param data: Data to be associated with this node
     """
     self.key = key
     self._data = data
     self.left = self.right = None
     
     log_info("New Tree node with key {0} and associated data: {1}".format(
             key, data))
Example #54
0
 def LoadResource(self, resourceName):
     resourceName = str(resourceName)
     png = pngs['levelmask'+resourceName+'.png']
     pickleFname = 'levelmask'+resourceName+'.pkl'
     pickleFname = os.path.join( data_dir, pickleFname )
     mask = None
     if os.path.exists(pickleFname):
         fp = file(pickleFname, 'rb')
         try:
             mask = pickle.load(fp)
         except Exception, ex:
             log_info('Failed loading pickle')
         finally:
Example #55
0
 def state_time_monitor(self):
     log_info("starting state time monitor")
     while True:
         if self.fsm._state != flight_Standing:
             # count the time for "in-the-air-states":
             self.flight_time += 1
         else:
             # use system uptime here:
             up_file = open("/proc/uptime", "r")
             up_list = up_file.read().split()
             self.uptime = int(up_list[0])
             up_file.close()
         sleep(1)
Example #56
0
def load_configuration(name):
    filename = current_namespace[-1].conf.get(name)
    if filename:
        try: 
            configuration = read_configuration(name)
            twill.execute_string(configuration, no_reset=1)
            log_info("loaded configuration: %s" % (name + CONFIGURATION))
        except IOError,e: 
            handle_exception("Unable to read configuration for suite %s" \
                             % (name + SUITE), e)
        except Exception,e:
            handle_exception("Invalid configuration: '%s'" \
                             % (name + CONFIGURATION), e)
Example #57
0
    def __init__(self, x, y, z):
        " Create lists of lists of lists in the same way than array_func. "
        Array.__init__(self, x, y, z)
        self._data = []

        for _ in range(x):
            d3_rows = []
            for _ in range(y):
                d3_rows.append([0] * z)
                self.array_len += 1

            self._data.append(d3_rows)

        log_info("New List_of_lists_array instance. Dimensions: {0}".format([x, y, z]))
Example #58
0
   def run(self):
      arg = self.icarus.arg
      core = self.icarus.core
      mon_data = self.icarus.mon_data
      params = self.icarus.core.params

      if arg.HasField('move_data'):
         z_setpoint = arg.move_data.z
         if arg.HasField('rel'):
            log_warn('rel field ignored for take-off')
         if arg.HasField('glob'):
            if not arg.glob:
               if z_setpoint < core.params.start_alt + mon_data.z + 3.0:
                  msg = 'absolute z setpoint %f is below current altitude' % z_setpoint
                  log_err(msg)
                  raise ValueError(msg)
               log_info('taking off to absolute altitude %f' % z_setpoint)
            else:
               z_setpoint = mon_data.z + z_setpoint
               log_info('taking off to relative altitude %f' % z_setpoint)
      else:
         z_setpoint = self.STD_HOVERING_ALT

      try:
         core.spin_up()
      except:
         core.spin_down()
         self.fsm.failed()
         log_error('could not spin up motors');
         return

      if self.canceled:
         core.spin_down()
         log_error('take-off canceled');
         return

      # "point of no return":
      # reset controllers:
      core.set_ctrl_param(POS_YAW, mon_data.yaw)
      core.set_ctrl_param(POS_X, mon_data.x)
      core.set_ctrl_param(POS_Y, mon_data.y)
      core.reset_ctrl()

      # set new altitude setpoint and stabilize:
      core.set_ctrl_param(POS_Z, z_setpoint)
      self.stabilize()
      self.fsm.done()
Example #59
0
 def scan_for_tests(self): 
     """
     scans for relevant files in the directory given.
     """
     log_info("scanning for tests in '%s'" % self.directory)
     for filename in os.listdir(self.directory):
         base, ext = os.path.splitext(filename)
         fullname = os.path.join(self.directory, filename)
         if ext == SUITE:
             if base.endswith(CLEANUP):
                 base = base.rsplit(CLEANUP, 1)[0]
                 self.cleanup[base] = fullname
             else:
                 self.suites[base] = fullname
         if ext == CONFIGURATION:
             self.conf[base] = fullname
         if ext == TEST:
             self.tests[base] = fullname
Example #60
0
 def core_monitor(self):
     log_info("starting core state monitor")
     rc_timeout = 1.0
     return_when_signal_lost = False
     self.mon_data = MonData()
     last_valid = time()
     while True:
         self.core.mon_read(self.mon_data)
         self.kalman_lat, self.kalman_lon = gps_add_meters(
             (self.core.params.start_lat, self.core.params.start_lon), self.setpoints[0:2]
         )
         if self.mon_data.signal_valid:
             last_valid = time()
         else:
             if time() - rc_timeout < last_valid and return_when_signal_lost:
                 if not self.icarus_takeover:
                     self.icarus_takeover = True
                     log_err("invalid RC signal, disabling mission interface")