handle commands from user
588
def process_stdin(line):
    ''''''
    if line is None:
        sys.exit(0)

    line = line.strip()
    if not line:
        return

    args = shlex.split(line)
    cmd = args[0]
    if cmd == 'help':
        k = command_map.keys()
        k.sort()
        for cmd in k:
            (fn, help) = command_map[cmd]
            print("%-15s : %s" % (cmd, help))
        return
    if cmd == 'exit':
        mestate.exit = True
        return

    if not cmd in command_map:
        print("Unknown command '%s'" % line)
        return
    (fn, help) = command_map[cmd]
    try:
        fn(args[1:])
    except Exception as e:
        print("ERROR in command %s: %s" % (args[1:], str(e)))
1344541
def execute_command(self, cmnd, *args, **options):
        ""
        args, options = self.preprocess_command(cmnd, *args, **options)
        return self.client.execute_command(cmnd, *args, **options)
1266996
public function cmdUpdateUser()
    {
        $params = $this->getParam();

        if (empty($params[0]) || count($params) < 2) {
            $this->errorAndExit($this->text('Invalid command'));
        }

        if (!is_numeric($params[0])) {
            $this->errorAndExit($this->text('Invalid argument'));
        }

        $this->setSubmitted(null, $params);
        $this->setSubmitted('update', $params[0]);
        $this->setSubmittedJson('data');

        $this->validateComponent('user', array('admin' => true));

        $this->updateUser($params[0]);
        $this->output();
    }
308064
def do_command(self):
        """"""
        method = self.args[0]

        raw_args = self.args[1:]
        if '=' in method:
            if raw_args:
                self.parser.error("Please don't mix rTorrent and shell argument styles!")
            method, raw_args = method.split('=', 1)
            raw_args = raw_args.split(',')

        self.execute(self.open(), method, self.cooked(raw_args))
1306742
def handle(self, *args, **options):
        

        yacms_user = options.get("yacms_user")
        site = Site.objects.get_current()
        verbosity = int(options.get("verbosity", 1))
        prompt = options.get("interactive")

        # Validate the yacms user.
        if yacms_user is None:
            raise CommandError("No yacms user has been specified")
        try:
            yacms_user = User.objects.get(username=yacms_user)
        except User.DoesNotExist:
            raise CommandError("Invalid yacms user: %s" % yacms_user)

        # Run the subclassed ``handle_import`` and save posts, tags,
        # categories, and comments to the DB.
        self.handle_import(options)
        for post_data in self.posts:
            categories = post_data.pop("categories")
            tags = post_data.pop("tags")
            comments = post_data.pop("comments")
            old_url = post_data.pop("old_url")
            post_data = self.trunc(BlogPost, prompt, **post_data)
            initial = {
                "title": post_data.pop("title"),
                "user": yacms_user,
            }
            if post_data["publish_date"] is None:
                post_data["status"] = CONTENT_STATUS_DRAFT
            post, created = BlogPost.objects.get_or_create(**initial)
            for k, v in post_data.items():
                setattr(post, k, v)
            post.save()
            if created and verbosity >= 1:
                print("Imported post: %s" % post)
            for name in categories:
                cat = self.trunc(BlogCategory, prompt, title=name)
                if not cat["title"]:
                    continue
                cat, created = BlogCategory.objects.get_or_create(**cat)
                if created and verbosity >= 1:
                    print("Imported category: %s" % cat)
                post.categories.add(cat)
            for comment in comments:
                comment = self.trunc(ThreadedComment, prompt, **comment)
                comment["site"] = site
                post.comments.create(**comment)
                if verbosity >= 1:
                    print("Imported comment by: %s" % comment["user_name"])
            self.add_meta(post, tags, prompt, verbosity, old_url)

        # Create any pages imported (Wordpress can include pages)
        in_menus = []
        footer = [menu[0] for menu in settings.PAGE_MENU_TEMPLATES
                  if menu[-1] == "pages/menus/footer.html"]
        if options["in_navigation"]:
            in_menus = [menu[0] for menu in settings.PAGE_MENU_TEMPLATES]
            if footer and not options["in_footer"]:
                in_menus.remove(footer[0])
        elif footer and options["in_footer"]:
            in_menus = footer
        parents = []
        for page in self.pages:
            tags = page.pop("tags")
            old_url = page.pop("old_url")
            old_id = page.pop("old_id")
            old_parent_id = page.pop("old_parent_id")
            page = self.trunc(RichTextPage, prompt, **page)
            page["status"] = CONTENT_STATUS_PUBLISHED
            page["in_menus"] = in_menus
            page, created = RichTextPage.objects.get_or_create(**page)
            if created and verbosity >= 1:
                print("Imported page: %s" % page)
            self.add_meta(page, tags, prompt, verbosity, old_url)
            parents.append({
                'old_id': old_id,
                'old_parent_id': old_parent_id,
                'page': page,
            })

        for obj in parents:
            if obj['old_parent_id']:
                for parent in parents:
                    if parent['old_id'] == obj['old_parent_id']:
                        obj['page'].parent = parent['page']
                        obj['page'].save()
                        break
761837
def handle_exec(args):
    
    session_file = get_db_name(args.get('<session-file>'))
    cosmic_ray.commands.execute(session_file)

    return ExitCode.OK
1043013
def run(self, argv):
        """"""
        command = argv[0]
        handlers = { 
            'clean': self.clean,
            'create': self.create,
            'disable': self.disable,
            'enable': self.enable,
            'list': self.list,
            'update': self.update,
        }
        handler = handlers.get(command, None)
        if handler is None:
            error("Unrecognized command: %s" % command, 2)
        handler(argv[1:])
1240798
def handle(self, *args, **options):
        

        def get_user(username):
            try:
                return User.objects.get(username=username)
            except ObjectDoesNotExist as e:
                raise CommandError("This user doesn't exist in the database")

        def get_fields_permissions(user):
            try:
                return UserFieldPermissions.objects.get(user=user)
            except ObjectDoesNotExist as e:
                raise CommandError("This user doesn't have fields permissions")



        if len(args) !=1:
            raise CommandError("Specifies a user")
        else:
            try:
                self.stdout.ending = None
                user = get_user(args[0])
                fields_permissions  = get_fields_permissions(user)
                permissions = fields_permissions.permissions.all()

                jsoneatthat = {'username': user.username, 
                    'fields_permissions' : [ {'app_label': permission.content_type.app_label, 'model' : permission.content_type.model, 'name': permission.name } for permission in permissions]}

                self.stdout.write(json.dumps(jsoneatthat))

            except:
                raise
580876
def execute_command(self, cmd, timeout, wait_for_string, password):
        """"""
        try:
            self.last_command_result = None
            self.ctrl.send_command(cmd, password=password)
            if wait_for_string is None:
                wait_for_string = self.prompt_re

            # hide cmd in case it's password for further error messages or exceptions.
            if password:
                cmd = "*** Password ***"

            if not self.driver.wait_for_string(wait_for_string, timeout):
                self.chain.connection.log("Unexpected session disconnect during '{}' command execution".format(cmd))
                raise ConnectionError("Unexpected session disconnect", host=self.hostname)

            if self.last_command_result:
                output = self.last_command_result.replace('\r', '')
            else:
                output = self.ctrl.before.replace('\r', '')

            # not needed. Fixes the issue #11
            # second_line_index = output.find('\n') + 1
            # output = output[second_line_index:]
            return output

        except CommandSyntaxError as e:  # pylint: disable=invalid-name
            self.chain.connection.log("{}: '{}'".format(e.message, cmd))
            e.command = cmd
            # TODO: Verify why lint raises an issue
            raise e  # pylint: disable=raising-bad-type

        except (CommandTimeoutError, pexpect.TIMEOUT):
            self.chain.connection.log("Command timeout: '{}'".format(cmd))
            raise CommandTimeoutError(message="Command timeout", host=self.hostname, command=cmd)

        except ConnectionError as e:  # pylint: disable=invalid-name
            self.chain.connection.log("{}: '{}'".format(e.message, cmd))
            raise

        except pexpect.EOF:
            self.chain.connection.log("Unexpected session disconnect")
            raise ConnectionError("Unexpected session disconnect", host=self.hostname)

        except Exception as e:  # pylint: disable=invalid-name
            self.chain.connection.log("Exception {}".format(e))
            raise ConnectionError(message="Unexpected error", host=self.hostname)
756277
def handle_command(command):
  
  try:
    cmds = command.split(None, 1)
    cmd = cmds[0]
    if cmd == 'new':
      add_task(get_arg(cmds))
    elif cmd == 'done':
      mark_done(int(get_arg(cmds)))
    elif cmd == 'list':
      for task in format_tasks(list_tasks()):
        print task
    elif cmd == 'delete':
      delete_task(int(get_arg(cmds)))
    else:
      print_usage()
  except Exception, e:  # pylint: disable=broad-except
    print e
    print_usage()
532738
def cmd(send, _, args):
    
    if args['target'] == 'private':
        send("You're all alone!")
        return
    with args['handler'].data_lock:
        channel = args['handler'].channels[args['target']]
        voiced = len([x for x in args['handler'].voiced[args['target']].values() if x])
        total = len(channel.users())
    send("%d active users, %d total users, %g%% active" % (voiced, total, voiced / total * 100))
743397
function (cmd, blind, response) {
  var toecho = '';
  if (typeof cmd !== 'string') {
    toecho = cmd.echo;
    blind = cmd.blind;
    response = cmd.response;
    cmd = cmd.cmd;
  } else {
    toecho = cmd;
  }

  cmd = trim(cmd);

  // Add the command to the user's history – unless this was blind
  if (!blind) {
    history.push(cmd.trim());
    setHistory(history);
  }

  // Show the user what they typed
  echo(toecho.trim());

  // If we were handed a response, show the response straight away – otherwise
  // runs it
  if (response) return showResponse(response);
  run(cmd, showResponse);

  setCursorTo('');

}
455882
def _dispatch_commands(self, from_state, to_state, smtp_command):
        """"""
        #print from_state, ' -> ', to_state, ':', smtp_command
        name_handler_method = 'smtp_%s' % smtp_command.lower().replace(' ', '_')
        try:
            handler_method = getattr(self, name_handler_method)
        except AttributeError:
            # base_msg = 'No handler for %s though transition is defined (no method %s)'
            # print base_msg % (smtp_command, name_handler_method)
            self.reply(451, 'Temporary Local Problem: Please come back later')
        else:
            # Don't catch InvalidDataError here - else the state would be moved
            # forward. Instead the handle_input will catch it and send out the
            # appropriate reply.
            handler_method()
349662
def handle(self):
        
        self.output = PyStratumStyle(self.input, self.output)

        command = self.get_application().find('constants')
        ret = command.execute(self.input, self.output)
        if ret:
            return ret

        command = self.get_application().find('loader')
        ret = command.execute(self.input, self.output)
        if ret:
            return ret

        command = self.get_application().find('wrapper')
        ret = command.execute(self.input, self.output)

        self.output.writeln('')

        return ret
172880
def handle_internal_commands(command):
    
    if command.startswith(":"):
        target = _get_registered_target(command[1:], default=None)
        if target:
            return target()
158644
private void handleCommand(MetaCommand cmd) throws IOException {
    if (cmd == null) {
      return;
    }
    switch (cmd) {
      case MetaCommand_Nothing:
        break;
      // Leader master requests re-registration
      case MetaCommand_Register:
        setIdAndRegister();
        break;
      // Unknown request
      case MetaCommand_Unknown:
        LOG.error("Master heartbeat sends unknown command {}", cmd);
        break;
      default:
        throw new RuntimeException("Un-recognized command from leader master " + cmd);
    }
  }
251628
def do(self, command):
        
        echo = self.echo and command or ''
        if not self.logged_in:
            return echo + '\n' + self._get_prompt()

        response = self.commands.eval(command)
        if response is None:
            return echo + '\n' + self._get_prompt()
        return echo + response