Ejemplo n.º 1
0
    def load(self):
        if self._is_loaded:
            logging.info(f'HVI2 schedule already loaded')
            return

        self.hardware.release_schedule()
        self.configure_modules()

        if self.hvi_exec is None:
            self.compile()

        logging.info(
            f"Load HVI2 schedule with script '{self.script.name}' (id:{self.hvi_id})"
        )
        self.hardware.set_schedule(self)
        self._might_be_loaded = True
        self.hvi_exec.load()
        if self.hvi_exec.is_running():
            logging.warning(
                f'HVI running after load; attempting to stop HVI and modules')
            self.hvi_exec.stop()
            self.reconfigure_modules()
            if self.hvi_exec.is_running():
                logging.eror(f'Still Running after stop')
        self._is_loaded = True
Ejemplo n.º 2
0
  def generic_handler(self, s, event):


    logging.info('%s,%s, %s', s, event,'type' in event)
    if str(event['from']).find('vijayp') == -1:
      return
    return
    try:
      if not event or not 'type' in event:
        return
    user = event['from']
    channel = str(event['to']).split('@')[0]
    
    
    if s == 'presence_subscribe':
      self._send_subscribed(channel, user)
      self._send_subscribe(channel, user)
    elif s == 'presence_subscribed':
      self._got_subscribed(channel, user)
    elif s == 'presence_unsubscribed':
      pass
    elif s == 'presence_unsubscribe':
      pass

    if event['type'] == 'probe':
      self._send_presence(channel, user)

    except Exception as e:
      logging.eror(e)
      return
Ejemplo n.º 3
0
 def post(self):
   if self.request.get('newRecipe') == '':
     logging.info('Recipe name must not be empty')
     self.redirect('/')
     return
   user = users.get_current_user()
   if user:
     userprefs_k = db.Key.from_path('UserPrefs', user.user_id())
     userprefs = db.get(userprefs_k)
     if userprefs == None:
       logging.eror('Unable to find current user')
       self.redirect('/')
    	return 
     newrecipe = Recipe(parent=userprefs_k, name=self.request.get('newRecipe'), key_name=self.request.get('newRecipe')) 
     
     #TODO reimplement testing if key exists
     recipe_query = Recipe.all().ancestor(userprefs_k)
     recipes = recipe_query.run(batch_size=1000)
     for currRec in recipes:
       if currRec.name == newrecipe.name:
         logging.info('Recipe with name ' + newrecipe.name + ' already exists')
         self.redirect('/')
         return
     logging.info('Writing new recipe with name: ' + newrecipe.name)
     newrecipe.put()
   self.redirect('/')
Ejemplo n.º 4
0
 def post(self):
   if self.request.get('newList') == '':
     logging.info('List name must not be empty')
     self.redirect('/')
     return
   user = users.get_current_user()
   if user:
     userprefs_k = db.Key.from_path('UserPrefs', user.user_id())
     userprefs = db.get(userprefs_k)
     if userprefs == None:
       logging.eror('Unable to find current user')
       self.redirect('/')
    	return 
     newtodolist = ToDoList(parent=userprefs_k, name=self.request.get('newList'), key_name=self.request.get('newList')) 
     
     #TODO reimplement testing if key exists
     todolist_query = ToDoList.all().ancestor(userprefs_k)
     todolists = todolist_query.run(batch_size=1000)
     for currlist in todolists:
       if currlist.name == newtodolist.name:
         logging.info('List with name ' + newtodolist.name + ' already exists')
         self.redirect('/')
         return
     logging.info('Writing new list with name: ' + newtodolist.name)
     newtodolist.put()
   self.redirect('/')
Ejemplo n.º 5
0
def run(cmd, exit=True, cwd=None):
    debg(cmd)
    if subprocess.Popen(cmd.split(), cwd=cwd).wait() != 0:
        if exit:
            crit('Failed!')
            sys.exit(1)
        else:
            eror('Ignoring failure.')
Ejemplo n.º 6
0
def run(cmd, exit=True, cwd=None):
    debg(cmd)
    if subprocess.Popen(cmd.split(), cwd=cwd).wait() != 0:
        if exit:
            crit('Failed!')
            sys.exit(1)
        else:
            eror('Ignoring failure.')
Ejemplo n.º 7
0
 def apply_cmd(cls, cmd):
     # type: (List[Text]) -> bool
     if common.opts.fDryrun:
         return False
     info("command invoked: " + Text(cmd))
     ret = subprocess.call(cmd)
     if ret != 0:
         eror("ng: with: " + Text(cmd))
     else:
         warn("ok: with: " + Text(cmd))
     return False
Ejemplo n.º 8
0
 def stop(self):
     try:
         self._channel.basic_cancel(self.on_cancelok, self._consumer_tag)
         logging.info('Sending a Basic.Cancel RPC command to RabbitMQ')
     except Exception as e:
         logging.warn("Sending a Basic.Cancel fail: %s" % str(e))
     logging.info("consumer stoppped")
     try:
         self._connection.ioloop.stop()
     except Exception as e:
         logging.eror("ioloop stop error: %s" % str(e))
     try:
         self._connection.close()
     except Exception as e:
         logging.error("rabbitmq connection closed: %s" % str(e))
Ejemplo n.º 9
0
 def stop(self):
     try:
         self._channel.basic_cancel(self.on_cancelok, self._consumer_tag)
         logging.info('Sending a Basic.Cancel RPC command to RabbitMQ')
     except Exception as e:
         logging.warn("Sending a Basic.Cancel fail: %s" % str(e))
     logging.info("consumer stoppped")
     try:
         self._connection.ioloop.stop()
     except Exception as e:
         logging.eror("ioloop stop error: %s" % str(e))
     try:
         self._connection.close()
     except Exception as e:
         logging.error("rabbitmq connection closed: %s" % str(e))
Ejemplo n.º 10
0
    def notify_server(self, totalCount, currCount, completed):
        url = NOTIFY_COMPLETE_URL.substitute(SERVER = self.server, CONTAINER=self.containerid)
        headers = {"content-type": "application/json"}
        payload = dict()
        curtime = time.strftime("%Y-%m-%d %H:%M:%S")
        payload['timestamp'] = curtime
        payload['volume'] = self.sourcepath
        payload['total'] = totalCount
        payload['current'] = currCount
        payload['completed'] = completed

        try:
            logging.debug("Notify cargo server URL: %s"%(url))
            resp = requests.post(url, data=json.dumps(payload), headers=headers)
        except requests.exceptions.ConnectionError as e:
            logging.eror("Error connecting to cargo server: %s"%(e))
Ejemplo n.º 11
0
def options_and_ini_model(
        cfg: configparser.ConfigParser,  # {{{1
        section: str,
        arg: str) -> int:
    ini_option = "Model"
    if arg == "" and not cfg.has_option(section, ini_option):
        model = 0x2737
        info("model name is default: 0x%x, see '--model ?' option." % model)
        return model

    def str_to_model_number(src: str) -> int:
        src = src.strip()
        if src in ["?", "help", "list"]:
            show_models_and_exit("")
        elif src.startswith("0x"):
            try:
                return int(src[2:], 16)  # model number
            except ValueError:
                return -1
        elif src.isdigit():
            try:
                return int(src)  # model number
            except ValueError:
                return -1
        elif len(src) > 0:
            for num, (cls, name, maker) in broadlink.SUPPORTED_TYPES.items():
                if src == name:
                    return num
        return -1

    if cfg.has_option(section, ini_option):
        model_str = cfg.get(section, ini_option)
        model = str_to_model_number(model_str)
        if model == -1:
            eror("invalid model name was specified in .ini: " + model_str)
    if len(arg) > 0:
        model_from_arg = str_to_model_number(arg)
        if model_from_arg == -1:
            show_models_and_exit("invalid model name:'%s', " % arg)
        if model != -1:
            info("model(0x%04x) was override by command line: %s(0x%04x)" %
                 (model, arg, model_from_arg))
            model = model_from_arg
    if model == -1:
        show_models_and_exit("")
    return model
Ejemplo n.º 12
0
    def apply(self, fn, f_changed):  # {{{1
        # type: (Callable[[List[Text]], bool], bool) -> bool
        info("-------- start apply() function -------------------------------")
        self._callback = fn

        for pgui in self.propgui_enum():
            prop = pgui.prop
            if not f_changed:
                pass
            elif prop.prop_id < 1:
                eror("did not found: {}-{}".format(prop.prop_id, prop.key))
                continue
            elif not pgui.is_changed():
                continue
            info("syncing {}...".format(prop.prop_id))
            pgui.sync()

        return False
Ejemplo n.º 13
0
 def compose_xconf(self):  # {{{1
     # type: () -> Iterable[Tuple[Text, Text]]
     n = 0
     for key, fmt in self.fmts:
         params = ""
         m = self.fmts.count_1fmt((key, fmt))
         vals = self.vals[n:n + m]
         n += m
         for val in vals:
             if len(val) < 1:
                 # TODO(shimoda): take default for missing parts.
                 eror("missing parameter: {}".format(key))
                 params += ' "nnn"'
             else:
                 params += ' "' + val + '"'
         line = ((" " * 8) + 'Option "' + key + '"' + params +
                 '  # by touchpadtuner\n')
         yield (key, line)
Ejemplo n.º 14
0
    def notify_server(self, totalCount, currCount, completed):
        url = NOTIFY_COMPLETE_URL.substitute(SERVER=self.server,
                                             CONTAINER=self.containerid)
        headers = {"content-type": "application/json"}
        payload = dict()
        curtime = time.strftime("%Y-%m-%d %H:%M:%S")
        payload['timestamp'] = curtime
        payload['volume'] = self.sourcepath
        payload['total'] = totalCount
        payload['current'] = currCount
        payload['completed'] = completed

        try:
            logging.debug("Notify cargo server URL: %s" % (url))
            resp = requests.post(url,
                                 data=json.dumps(payload),
                                 headers=headers)
        except requests.exceptions.ConnectionError as e:
            logging.eror("Error connecting to cargo server: %s" % (e))
Ejemplo n.º 15
0
def main_hg(drepo):  # {{{1
    fname = os.path.join(drepo, ".hg", "hgrc")
    fname = os.path.abspath(fname)
    if not os.path.isfile(fname):
        info(".hgrc not found and skip...")
        return ""

    info("parse '%s'" % fname)
    cfg = SafeConfigParser()
    cfg.read(fname)
    if not cfg.has_section("paths"):
        eror("?? .hgrc has no section [paths], ignored.")
        return ""

    for opt in cfg.options("paths"):
        v = cfg.get("paths", opt)
        if (v.startswith("git://") or v.startswith("git+ssh://")):
            return v  # use 1st URL to git.
    return ""
Ejemplo n.º 16
0
 def post(self):
   if self.request.get('newListItem') == '':
     logging.info('List item name must not be empty')
     self.redirect('/')
     return
   user = users.get_current_user()
   if user:
     userprefs_k = db.Key.from_path('UserPrefs', user.user_id())
     userprefs = db.get(userprefs_k)
     if userprefs == None:
       logging.eror('Unable to find current user')
       self.redirect('/')
    	return
     toview_name = self.request.get('list_name')
     todolist_k = db.Key.from_path('UserPrefs', user.user_id(), 'ToDoList', toview_name)
     item = SimpleItem(todolist_k, name=self.request.get('newListItem'))
     item.put()
   
   self.redirect('/viewList?list_name=' + self.request.get('list_name'))
Ejemplo n.º 17
0
def main_hg(drepo):                                         # {{{1
    fname = os.path.join(drepo, ".hg", "hgrc")
    fname = os.path.abspath(fname)
    if not os.path.isfile(fname):
        info(".hgrc not found and skip...")
        return ""

    info("parse '%s'" % fname)
    cfg = SafeConfigParser()
    cfg.read(fname)
    if not cfg.has_section("paths"):
        eror("?? .hgrc has no section [paths], ignored.")
        return ""

    for opt in cfg.options("paths"):
        v = cfg.get("paths", opt)
        if (v.startswith("git://") or
                v.startswith("git+ssh://")):
            return v     # use 1st URL to git.
    return ""
Ejemplo n.º 18
0
def main():  # {{{1
    # type: () -> int
    logging.basicConfig(format="%(levelname)-8s:%(asctime)s:%(message)s")

    n_props = NPropDb.auto_id()
    global gui
    debg("fetch settings, options and arguments...")
    opts = options()
    if opts is None:
        eror("can't found Synaptics in xinput.")
        return 1
    debg("create properties DB...")
    if n_props < 3:
        eror("can't found Synaptics properties in xinput.")
        return 2
    debg("build GUI...")
    gui = buildgui(opts)
    gui.root.after_idle(gui.callback_idle)  # type: ignore # for Tk
    debg("start gui...")
    gui.root.mainloop()  # type: ignore # for Tk
    return 0
Ejemplo n.º 19
0
    def __init__(self, data=None, manager_handle='\x00'*20,
                                  service_name='',
                                  binary_pathname='',
                                  display_name='',
                                  start_type=SVCCTL_SERVICE_DEMAND_START,
                                  is_unicode=True):
        Struct.__init__(self, data)

        if data is not None:
            pos = 0
            self['ManagerHandle'] = data[pos:pos+20]
            pos += 20
            self['ServiceName'] = DCERPCString(data=data[pos:])
            pos += len(self['ServiceName'].pack())
            self['DisplayNamePtr'] = data[pos:pos+4]
            self['DisplayName'] = DCERPCString(data=data[pos:])
            pos += len(self['DisplayName'].pack())
            self['AccessMask'] = data[pos:pos+4]
            pos += 4
            self['ServiceType'] = data[pos:pos+4]
            pos += 4
            self['ServiceStartType'] = data[pos:pos+4]
            pos += 4
            self['ServiceErrorControl'] = data[pos:pos+4]
            pos += 4
            self['BinaryPathName'] = DCERPCString(data=data[pos:])
            pos += len(self['BinaryPathName'].pack())
            self['LoadOrderGroupPtr'] = data[pos:pos+4]
            pos += 4
            self['TagId'] = data[pos:pos+4]
            pos += 4
            self['DependenciesPtr'] = data[pos:pos+4]
            if self['DependenciesPtr']:
                logging.eror('SVCCTL_ERROR: DependenciesPtr != 0')
                return
            pos += 4
            self['DependSize'] = data[pos:pos+4]
            pos += 4
            self['ServiceStartNamePtr'] = data[pos:pos+4]
            if self['ServiceStartNamePtr']:
                logging.eror('SVCCTL_ERROR: DependenciesPtr != 0')
                return
            pos += 4
            self['PasswordPtr'] = data[pos:pos+4]
            if self['PasswordPtr']:
                logging.eror('SVCCTL_ERROR: DependenciesPtr != 0')
                return
            pos += 4
            self['PasswordSize'] = data[pos:pos+4]
        else:
            self['ManagerHandle'] = manager_handle
            self['ServiceName'] = DCERPCString(string=service_name.encode('UTF-16LE'))
            self['BinaryPathName'] = DCERPCString(string=binary_pathname.encode('UTF-16LE'))
            if len(display_name):
                self['DisplayName'] = DCERPCString(string=display_name.encode('UTF-16LE'))
                self['DisplayNamePtr'] = 0x20004
            else:
                self['DisplayNamePtr'] = 0
            self['ServiceStartType'] = start_type