Invoke a function in the lxc module with no args

    path
        path to the container parent
        default: /var/lib/lxc (system default)

        .. versionadded:: 2015.8.0
972494
def _do(name, fun, path=None):
    '''
    
    '''
    host = find_guest(name, quiet=True, path=path)
    if not host:
        return False

    client = salt.client.get_local_client(__opts__['conf_file'])
    cmd_ret = client.cmd_iter(
            host,
            'lxc.{0}'.format(fun),
            [name],
            kwarg={'path': path},
            timeout=60)
    data = next(cmd_ret)
    data = data.get(host, {}).get('ret', None)
    if data:
        data = {host: data}
    return data
1246047
def call(self, fn, args, name='', cconv=None, tail=False, fastmath=()):
        
        inst = instructions.CallInstr(self.block, fn, args, name=name,
                                      cconv=cconv, tail=tail, fastmath=fastmath)
        self._insert(inst)
        return inst
965055
def ensure_container(self, name=None):
        """"""
        if get_lxc_version() < pkg_resources.parse_version('2.0.0'):
            # Nothing to do for old versions of LXC
            return

        if name is None:
            name = self.container_name

        args = [
            'lxc-create',
            '--name', name,
            '--template', 'none',
            '>', '/dev/null', '2>&1',
        ]
        os.system(' '.join(args))
1169130
async def invoke(self, ctx):
        
        if ctx.command is not None:
            self.dispatch('command', ctx)
            try:
                if await self.can_run(ctx, call_once=True):
                    await ctx.command.invoke(ctx)
            except errors.CommandError as exc:
                await ctx.command.dispatch_error(ctx, exc)
            else:
                self.dispatch('command_completion', ctx)
        elif ctx.invoked_with:
            exc = errors.CommandNotFound('Command "{}" is not found'.format(ctx.invoked_with))
            self.dispatch('command_error', ctx, exc)
123915
def lib(ctx,
        filepath=None,
        extra=False,
        bootstrap=False,
        cache=False,
        reveal=False,
        show=False,
        save=False,
        directory=False):
    
    verbose = ctx.obj['VERBOSE']
    sTime = ctx.obj['STIME']
    print_opts = {
        'labels': verbose,
    }
    DONE_ACTION = False

    if bootstrap:
        DONE_ACTION = True
        action_bootstrap(verbose)
        printDebug("Tip: you can now load an ontology by typing `ontospy lib -s`",
                   "important")
        # raise SystemExit(1)

    elif cache:
        DONE_ACTION = True
        action_cache_reset()

    elif directory:
        if not filepath:
            printDebug("Please specify a new directory for the local library.",
                       'important')
            sys.exit(0)
        else:
            _location = filepath[0]
            if _location.endswith("/"):
                # dont need the final slash
                _location = _location[:-1]
            output = action_update_library_location(_location)
            if output:
                printDebug(
                    "Note: no files have been moved or deleted (this has to be done manually)",
                    "comment")
                printDebug("----------\n" + "New location: '%s'" % _location,
                           "important")

            else:
                printDebug(
                    "----------\n" + "Please specify an existing folder path.",
                    "important")
            raise SystemExit(1)

    elif reveal:
        action_reveal_library()
        raise SystemExit(1)

    elif save:
        if filepath:
            DONE_ACTION = True
            action_import(filepath[0], verbose)
        else:
            click.secho(
                "You provided no arguments - please specify what to save..",
                fg='white')
        raise SystemExit(1)

    elif show:
        click.secho("Local library => '%s'" % get_home_location(), fg='white')
        filename = action_listlocal(all_details=False)

        if filename:
            DONE_ACTION = True
            g = get_pickled_ontology(filename)
            if not g:
                g = do_pickle_ontology(filename)
            shellPrintOverview(g, print_opts)

    else:
        click.echo(ctx.get_help())
        return

    if DONE_ACTION:
        eTime = time.time()
        tTime = eTime - sTime
        printDebug("\n-----------\n" + "Time:	   %0.2fs" % tTime, "comment")
    else:
        printDebug("Goodbye", "comment")
1224158
def compile(self, source, path=None):
        

        container = self._generate_code(source)

        def make_module_name(name, suffix=None):
            output = 'pybars._templates.%s' % name
            if suffix:
                output += '_%s' % suffix
            return output

        if not path:
            path = '_template'
            generate_name = True
        else:
            path = path.replace('\\', '/')
            path = path.replace('/', '_')
            mod_name = make_module_name(path)
            generate_name = mod_name in sys.modules

        if generate_name:
            mod_name = make_module_name(path, self.template_counter)
            while mod_name in sys.modules:
                self.template_counter += 1
                mod_name = make_module_name(path, self.template_counter)

        mod = ModuleType(mod_name)
        filename = '%s.py' % mod_name.replace('pybars.', '').replace('.', '/')
        exec(compile(container.full_code, filename, 'exec', dont_inherit=True), mod.__dict__)
        sys.modules[mod_name] = mod
        linecache.getlines(filename, mod.__dict__)

        return mod.__dict__[container.name]
495532
def add_module(  # noqa: C901
        self,
        module,
        module_or_package_name,
        local_names,
        import_alias_mapping,
        is_init=False,
        from_from=False,
        from_fdid=False
    ):
        
        module_path = module[1]

        parent_definitions = self.module_definitions_stack[-1]
        # Here, in `visit_Import` and in `visit_ImportFrom` are the only places the `import_alias_mapping` is updated
        parent_definitions.import_alias_mapping.update(import_alias_mapping)
        parent_definitions.import_names = local_names

        new_module_definitions = ModuleDefinitions(local_names, module_or_package_name)
        new_module_definitions.is_init = is_init
        self.module_definitions_stack.append(new_module_definitions)

        # Analyse the file
        self.filenames.append(module_path)
        self.local_modules = get_directory_modules(module_path) if self._allow_local_modules else []
        tree = generate_ast(module_path)

        # module[0] is None during e.g. "from . import foo", so we must str()
        self.nodes.append(EntryOrExitNode('Module Entry ' + str(module[0])))
        self.visit(tree)
        exit_node = self.append_node(EntryOrExitNode('Module Exit ' + str(module[0])))

        # Done analysing, pop the module off
        self.module_definitions_stack.pop()
        self.filenames.pop()

        if new_module_definitions.is_init:
            for def_ in new_module_definitions.definitions:
                module_def_alias = handle_aliases_in_init_files(
                    def_.name,
                    new_module_definitions.import_alias_mapping
                )
                parent_def_alias = handle_aliases_in_init_files(
                    def_.name,
                    parent_definitions.import_alias_mapping
                )
                # They should never both be set
                assert not (module_def_alias and parent_def_alias)

                def_name = def_.name
                if parent_def_alias:
                    def_name = parent_def_alias
                if module_def_alias:
                    def_name = module_def_alias

                local_definitions = self.module_definitions_stack[-1]
                if local_definitions != parent_definitions:
                    raise
                if not isinstance(module_or_package_name, str):
                    module_or_package_name = module_or_package_name.name

                if module_or_package_name:
                    if from_from:
                        qualified_name = def_name

                        if from_fdid:
                            alias = handle_fdid_aliases(module_or_package_name, import_alias_mapping)
                            if alias:
                                module_or_package_name = alias
                            parent_definition = ModuleDefinition(
                                parent_definitions,
                                qualified_name,
                                module_or_package_name,
                                self.filenames[-1]
                            )
                        else:
                            parent_definition = ModuleDefinition(
                                parent_definitions,
                                qualified_name,
                                None,
                                self.filenames[-1]
                            )
                    else:
                        qualified_name = module_or_package_name + '.' + def_name
                        parent_definition = ModuleDefinition(
                            parent_definitions,
                            qualified_name,
                            parent_definitions.module_name,
                            self.filenames[-1]
                        )
                    parent_definition.node = def_.node
                    parent_definitions.definitions.append(parent_definition)
                else:
                    parent_definition = ModuleDefinition(
                        parent_definitions,
                        def_name,
                        parent_definitions.module_name,
                        self.filenames[-1]
                    )
                    parent_definition.node = def_.node
                    parent_definitions.definitions.append(parent_definition)

        return exit_node
716655
def module_add(self, ev, path=None):
        
        log = self._params.get('log', self._discard)
        key = ev.get_key()
        if key is None:
            raise TaskError(name, "Attempt to register python module event with no key available")
        log.debug("Adding path %r for task %r, action %s", path, ev.get_name(), ev._handler_name)
        self._watch_modules.add(key, command_path=path)
        self._module_event_map[key] = ev
1142131
def execute_command(self, default_arg_list=None, **kwargs):
    
    _custom_func_arguments = set()

    if default_arg_list is None or len(default_arg_list) == 0:
      raise NoCommandException("No command passed, unable to continue")

    command_name = default_arg_list.pop(0)
    if command_name not in self._modules.keys():
      raise NoCommandException("No such command '{}' found, unable to continue".format(command_name))

    command = self._modules[command_name]
    entry_point = command["entry_point"]
    class_path = command["classpath"]
    metainfo = command["metainfo"]
    """:type metainfo ModuleMetaInfo"""

    try:
      args = metainfo.parse_default_arguments(default_arg_list)
      args.update(metainfo.parse_arguments(kwargs))

      f_args = entry_point.__code__.co_varnames[:entry_point.__code__.co_argcount]

      if len(f_args) - len(set(f_args) & _custom_func_arguments) != len(set(args.keys()) & set(f_args)):
        raise ArgumentException("Function \"{}\" from module {} doesn't implement all arguments in the signature".format(
          entry_point.__name__, class_path
        ))

      entry_point(**args)
    except ArgumentException as e:
      raise NoCommandException("Application arguments exception: {}\n".format(str(e)))
556489
def main(argv=None):
    
    if argv is None:
        argv = sys.argv

    # parse options
    parser = argparse.ArgumentParser(
        fromfile_prefix_chars='@',
        description=
        """Execute a command inside a simple container, i.e., partially isolated from the host.
           Command-line parameters can additionally be read from a file if file name prefixed with '@' is given as argument.
           Part of BenchExec: https://github.com/sosy-lab/benchexec/""")
    parser.add_argument("--dir", metavar="DIR",
                        help="working directory for executing the command (default is current directory)")
    parser.add_argument("--root", action="store_true",
                        help="use UID 0 and GID 0 (i.e., fake root account) within container")
    parser.add_argument("--uid", metavar="UID", type=int, default=None,
                        help="use given UID within container (default: current UID)")
    parser.add_argument("--gid", metavar="GID", type=int, default=None,
                        help="use given GID within container (default: current UID)")
    add_basic_container_args(parser)
    add_container_output_args(parser)
    baseexecutor.add_basic_executor_options(parser)

    options = parser.parse_args(argv[1:])
    baseexecutor.handle_basic_executor_options(options, parser)
    container_options = handle_basic_container_args(options, parser)
    container_output_options = handle_container_output_args(options, parser)

    if options.root:
        if options.uid is not None or options.gid is not None:
            parser.error("Cannot combine option --root with --uid/--gid")
        options.uid = 0
        options.gid = 0

    formatted_args = " ".join(map(util.escape_string_shell, options.args))
    logging.info('Starting command %s', formatted_args)

    executor = ContainerExecutor(uid=options.uid, gid=options.gid, **container_options)

    # ensure that process gets killed on interrupt/kill signal
    def signal_handler_kill(signum, frame):
        executor.stop()
    signal.signal(signal.SIGTERM, signal_handler_kill)
    signal.signal(signal.SIGINT,  signal_handler_kill)

    # actual run execution
    try:
        result = executor.execute_run(options.args, workingDir=options.dir,
                                      **container_output_options)
    except (BenchExecException, OSError) as e:
        if options.debug:
            logging.exception(e)
        sys.exit("Cannot execute {0}: {1}.".format(util.escape_string_shell(options.args[0]), e))
    return result.signal or result.value
1253459
def invoke(ctx, name, profile, stage):
    # type: (click.Context, str, str, str) -> None
    """"""
    factory = ctx.obj['factory']  # type: CLIFactory
    factory.profile = profile

    try:
        invoke_handler = factory.create_lambda_invoke_handler(name, stage)
        payload = factory.create_stdin_reader().read()
        invoke_handler.invoke(payload)
    except NoSuchFunctionError as e:
        err = click.ClickException(
            "could not find a lambda function named %s." % e.name)
        err.exit_code = 2
        raise err
    except botocore.exceptions.ClientError as e:
        error = e.response['Error']
        err = click.ClickException(
            "got '%s' exception back from Lambda\n%s"
            % (error['Code'], error['Message']))
        err.exit_code = 1
        raise err
    except UnhandledLambdaError:
        err = click.ClickException(
            "Unhandled exception in Lambda function, details above.")
        err.exit_code = 1
        raise err
    except ReadTimeout as e:
        err = click.ClickException(e.message)
        err.exit_code = 1
        raise err
1089515
def run_command(args):
    """"""
    library_rc = 'pylintrc'
    test_rc = 'pylintrc.test'

    if os.path.exists(library_rc):
        os.remove(library_rc)

    if os.path.exists(test_rc):
        os.remove(test_rc)

    default_config = read_config(get_default_config())
    user_config = load_local_config(args.config)
    configuration = determine_final_config(user_config)

    make_rc(default_config, library_rc,
            additions=configuration.library_additions,
            replacements=configuration.library_replacements)
    make_rc(default_config, test_rc,
            additions=configuration.test_additions,
            replacements=configuration.test_replacements)

    lint_fileset(*args.library_filesets, rc_filename=library_rc,
                 description='Library')
    lint_fileset(*args.test_filesets, rc_filename=test_rc,
                 description='Test')
563766
def command(self, *args, **kwargs):
        
        def decorator(func):
            kwargs.setdefault('parent', self)
            result = command(*args, **kwargs)(func)
            self.add_command(result)
            return result

        return decorator
1051667
function (version, cmd, args) {
        return __awaiter(this, void 0, void 0, function* () {
            let binpath = yield getBinPath(version);
            let parentEnv = process.env;
            let childPath = binpath + path.delimiter + parentEnv.PATH;
            let env = Object.assign({}, parentEnv, { PATH: childPath });
            let spawnOpts = { cwd: process.cwd(), env: env };
            return Promise.resolve(child_process_1.spawn(cmd, args, spawnOpts));
        });
    }
263726
def main():
    
    try:
        # Get the `src` directory's absolute path
        src_path = os.path.dirname(
            # `aoiklivereload` directory's absolute path
            os.path.dirname(
                # `demo` directory's absolute path
                os.path.dirname(
                    # This file's absolute path
                    os.path.abspath(__file__)
                )
            )
        )

        # If the `src` directory path is not in `sys.path`
        if src_path not in sys.path:
            # Add to `sys.path`.
            #
            # This aims to save user setting PYTHONPATH when running this demo.
            #
            sys.path.append(src_path)

        # Import reloader class
        from aoiklivereload import LiveReloader

        # Create reloader
        reloader = LiveReloader()

        # Start watcher thread
        reloader.start_watcher_thread()

        # Server host
        server_host = '0.0.0.0'

        # Server port
        server_port = 8000

        # Get message
        msg = '# ----- Run server -----\nHost: {}\nPort: {}'.format(
            server_host, server_port
        )

        # Print message
        print(msg)

        # Create Flask app
        flask_app = flask.Flask(__name__)

        # Create request handler
        @flask_app.route('/')
        def hello_handler():  # pylint: disable=unused-variable
            """
            Request handler.

            :return:
                Response body.
            """
            # Return response body
            return 'hello'

        # Run server
        flask_app.run(
            host=server_host,
            port=server_port,
            # Disable Flask's reloader
            debug=False,
        )

    # If have `KeyboardInterrupt`
    except KeyboardInterrupt:
        # Not treat as error
        pass
362670
function invokeCommand(command, argv, isInternalCommand) {

  const globs = getGlobs();

  if (globs.length === 0) {
    return invokeCommandError(command, isInternalCommand);
  }

  const modulesAnswered = getModulesAnswered(command, argv, globs);
  const modulesAnsweredLength = modulesAnswered.length;

  if (modulesAnsweredLength === 0) {
    return invokeCommandError(command, isInternalCommand);
  }

  const modulesAnsweredPlural = modulesAnsweredLength === 1 ? 'module' : 'modules';

  logger.verbose(
    `Successfully passed ${command} to ${modulesAnsweredLength} ${modulesAnsweredPlural}:`
  );
  logger.verbose(modulesAnswered.join(', '));
}
230202
def load_path_with_default(self, path, default_constructor):
        '''
        
        '''
        try:
            imported_obj = self.load_path(path)
        except (ImportError, ConfigurationError):
            imported_obj = default_constructor(path)
        else:
            # Ugly but seemingly expedient way to check a module was an
            # namespace type module
            if (isinstance(imported_obj, ModuleType) and
                    imported_obj.__spec__.origin == 'namespace'):
                imported_obj = default_constructor(path)
        return imported_obj