Load custom environment setup from a Python source file and run the setup
    function.
960261
def setup_custom_environment(custom_module_path):
    
    module = import_file("maskrcnn_benchmark.utils.env.custom_module", custom_module_path)
    assert hasattr(module, "setup_environment") and callable(
        module.setup_environment
    ), (
        "Custom environment module defined in {} does not have the "
        "required callable attribute 'setup_environment'."
    ).format(
        custom_module_path
    )
    module.setup_environment()
269078
def main():
    
    parser = argparse.ArgumentParser(description='Github-based load test')

    parser.add_argument('--version', action='store_true', default=False,
                        help='Displays version and exits.')

    parser.add_argument('--virtualenv', type=str, default='virtualenv',
                        help='Virtualenv executable.')

    parser.add_argument('--python', type=str, default=sys.executable,
                        help='Python executable.')

    parser.add_argument('--config', type=str, default='molotov.json',
                        help='Path of the configuration file.')

    parser.add_argument('repo', help='Github repo', type=str, nargs="?")
    parser.add_argument('run', help='Test to run', nargs="?")

    args = parser.parse_args()

    if args.version:
        print(__version__)
        sys.exit(0)

    tempdir = tempfile.mkdtemp()
    curdir = os.getcwd()
    os.chdir(tempdir)
    print('Working directory is %s' % tempdir)
    try:
        clone_repo(args.repo)
        config_file = os.path.join(tempdir, args.config)

        with open(config_file) as f:
            config = json.loads(f.read())

        # creating the virtualenv
        create_virtualenv(args.virtualenv, args.python)

        # install deps
        if 'requirements' in config['molotov']:
            install_reqs(config['molotov']['requirements'])

        # load deps into sys.path
        pyver = '%d.%d' % (sys.version_info.major, sys.version_info.minor)
        site_pkg = os.path.join(tempdir, 'venv', 'lib', 'python' + pyver,
                                'site-packages')
        site.addsitedir(site_pkg)
        pkg_resources.working_set.add_entry(site_pkg)

        # environment
        if 'env' in config['molotov']:
            for key, value in config['molotov']['env'].items():
                os.environ[key] = value

        run_test(**config['molotov']['tests'][args.run])
    except Exception:
        os.chdir(curdir)
        shutil.rmtree(tempdir, ignore_errors=True)
        raise
215826
def _run_code(code, run_globals, init_globals=None,
              mod_name=None, mod_fname=None,
              mod_loader=None, pkg_name=None):
    """"""
    if init_globals is not None:
        run_globals.update(init_globals)
    run_globals.update(__name__ = mod_name,
                       __file__ = mod_fname,
                       __loader__ = mod_loader,
                       __package__ = pkg_name)
    exec code in run_globals
    return run_globals
161651
def run_file(path):
    """"""
    if PY26:
        dirpath, name, _ = splitname(path)
        found = imp.find_module(name, [dirpath])
        module = imp.load_module("__main__", *found)
        return vars(module)
    else:
        return runpy.run_path(path, run_name="__main__")
1199676
def setup(interactive, not_relative, dry_run, reset, root_dir, testuser):
    """"""

    click.echo("[cellpy] (setup)")

    # generate variables
    init_filename = create_custom_init_filename()
    userdir, dst_file = get_user_dir_and_dst(init_filename)

    if testuser:
        if not root_dir:
            root_dir = os.getcwd()

        click.echo(f"[cellpy] (setup) DEV-MODE testuser: {testuser}")
        init_filename = create_custom_init_filename(testuser)
        userdir = root_dir
        dst_file = get_dst_file(userdir, init_filename)
        click.echo(f"[cellpy] (setup) DEV-MODE userdir: {userdir}")
        click.echo(f"[cellpy] (setup) DEV-MODE dst_file: {dst_file}")

    if not pathlib.Path(dst_file).is_file():
        reset = True

    if interactive:
        click.echo(" interactive mode ".center(80, "-"))
        _update_paths(root_dir, not not_relative, dry_run=dry_run, reset=reset)
        _write_config_file(
            userdir, dst_file,
            init_filename, dry_run,
        )
        _check()

    else:
        _write_config_file(userdir, dst_file, init_filename, dry_run)
        _check()
630605
def run(self):
        """"""
        self._make_lib_file_symbolic_links()
        self._copy_each_include_files_to_include_dir()
        self._make_dep_lib_file_sym_links_and_copy_include_files()
        self.setup_py.add_patchs_to_build_without_pkg_config(
            self.rpm.lib_dir, self.rpm.include_dir
        )
        self.setup_py.apply_and_save()
        self._build_and_install()
297741
def load_config_from_setup(app):
    
    # for now, assume project root is one level up
    root = os.path.join(app.confdir, '..')
    setup_script = os.path.join(root, 'setup.py')
    fields = ['--name', '--version', '--url', '--author']
    dist_info_cmd = [sys.executable, setup_script] + fields
    output = subprocess.check_output(
        dist_info_cmd,
        cwd=root,
        universal_newlines=True,
    )
    outputs = output.strip().split('\n')
    project, version, url, author = outputs
    app.config.project = project
    app.config.version = app.config.release = version
    app.config.package_url = url
    app.config.author = app.config.copyright = author
1117828
def _setup_environment(self, environments):
        """"""
        # If keepEnv is set or sudo is used, start from a fresh environment,
        # otherwise with the current one.
        # keepEnv specifies variables to copy from the current environment,
        # newEnv specifies variables to set to a new value,
        # additionalEnv specifies variables where some value should be appended, and
        # clearEnv specifies variables to delete.
        if self._user is not None or environments.get("keepEnv", None) is not None:
            run_environment = {}
        else:
            run_environment = os.environ.copy()
        for key, value in environments.get("keepEnv", {}).items():
            if key in os.environ:
                run_environment[key] = os.environ[key]
        for key, value in environments.get("newEnv", {}).items():
            run_environment[key] = value
        for key, value in environments.get("additionalEnv", {}).items():
            run_environment[key] = os.environ.get(key, "") + value
        for key in environments.get("clearEnv", {}).items():
            run_environment.pop(key, None)

        logging.debug("Using additional environment %s.", environments)
        return run_environment
617631
def _setup(self, name=None):
        
        envvar = self.__dict__['env_var']
        if envvar:
            settings_file = os.environ.get(envvar)
        else:
            settings_file = self.__dict__['file_path']

        if not settings_file:
            msg = ("Requested settings, but none can be obtained for the envvar."
                   "Since no config filepath can be obtained, a default config "
                   "will be used.")
            logger.error(msg)
            raise OSError(msg)

        self._wrapped = Settings(settings_file)
1268384
def create_environment(home_dir, site_packages=False, clear=False,
                       unzip_setuptools=False,
                       prompt=None, search_dirs=None, download=False,
                       no_setuptools=False, no_pip=False, no_wheel=False,
                       symlink=True):
    
    home_dir, lib_dir, inc_dir, bin_dir = path_locations(home_dir)

    py_executable = os.path.abspath(install_python(
        home_dir, lib_dir, inc_dir, bin_dir,
        site_packages=site_packages, clear=clear, symlink=symlink))

    install_distutils(home_dir)

    to_install = []

    if not no_setuptools:
        to_install.append('setuptools')

    if not no_pip:
        to_install.append('pip')

    if not no_wheel:
        to_install.append('wheel')

    if to_install:
        install_wheel(
            to_install,
            py_executable,
            search_dirs,
            download=download,
        )

    install_activate(home_dir, bin_dir, prompt)

    install_python_config(home_dir, bin_dir, prompt)
400856
def load_env(file):
    

    env = yaml.load(open(file))

    for org in env.get('organizations', []):
        if not org.get('applications'):
            org['applications'] = []

        if org.get('starter-kit'):
            kit_meta = get_starter_kit_meta(org.get('starter-kit'))
            for meta_app in get_applications_from_metadata(kit_meta):
                org['applications'].append(meta_app)

        if org.get('meta'):
            for meta_app in get_applications_from_metadata(org.get('meta')):
                org['applications'].append(meta_app)

        for app in org.get('applications', []):
            if app.get('file'):
                app['file'] = os.path.realpath(os.path.join(os.path.dirname(file), app['file']))
    return env
279449
def start(configfile=None, daemonize=False, environment=None,
          fastcgi=False, scgi=False, pidfile=None,
          cgi=False, debug=False):
    """"""
    sys.path = [''] + sys.path

    # monkey patching cherrypy to disable config interpolation
    def new_as_dict(self, raw=True, vars=None):
        """Convert an INI file to a dictionary"""
        # Load INI file into a dict
        result = {}
        for section in self.sections():
            if section not in result:
                result[section] = {}
            for option in self.options(section):
                value = self.get(section, option, raw=raw, vars=vars)
                try:
                    value = cherrypy.lib.reprconf.unrepr(value)
                except Exception:
                    x = sys.exc_info()[1]
                    msg = ("Config error in section: %r, option: %r, "
                           "value: %r. Config values must be valid Python." %
                           (section, option, value))
                    raise ValueError(msg, x.__class__.__name__, x.args)
                result[section][option] = value
        return result
    cherrypy.lib.reprconf.Parser.as_dict = new_as_dict

    instance = LdapCherry()
    app = cherrypy.tree.mount(instance, '/', configfile)
    cherrypy.config.update(configfile)
    instance.reload(app.config, debug)

    engine = cherrypy.engine

    # Turn off autoreload
    cherrypy.config.update({'engine.autoreload.on': False})

    if environment is not None:
        cherrypy.config.update({'environment': environment})

    # Only daemonize if asked to.
    if daemonize:
        # Don't print anything to stdout/sterr.
        cherrypy.config.update({'log.screen': False})
        plugins.Daemonizer(engine).subscribe()

    if pidfile:
        plugins.PIDFile(engine, pidfile).subscribe()

    if hasattr(engine, "signal_handler"):
        engine.signal_handler.subscribe()
    if hasattr(engine, "console_control_handler"):
        engine.console_control_handler.subscribe()

    if (fastcgi and (scgi or cgi)) or (scgi and cgi):
        cherrypy.log.error("You may only specify one of the cgi, fastcgi, and "
                           "scgi options.", 'ENGINE')
        sys.exit(1)
    elif fastcgi or scgi or cgi:
        # Turn off the default HTTP server (which is subscribed by default).
        cherrypy.server.unsubscribe()

        addr = cherrypy.server.bind_addr
        if fastcgi:
            f = servers.FlupFCGIServer(application=cherrypy.tree,
                                       bindAddress=addr)
        elif scgi:
            f = servers.FlupSCGIServer(application=cherrypy.tree,
                                       bindAddress=addr)
        else:
            f = servers.FlupCGIServer(application=cherrypy.tree,
                                      bindAddress=addr)
        s = servers.ServerAdapter(engine, httpserver=f, bind_addr=addr)
        s.subscribe()

    # Always start the engine; this will start all other services
    try:
        engine.start()
    except Exception as e:
        # Assume the error has been logged already via bus.log.
        sys.exit(1)
    else:
        engine.block()
38505
def _load_settings_from_source(self, source):
        
        if not source:
            pass
        elif source == 'env_settings_uri':
            for env_settings_uri_key in self.env_settings_uri_keys:
                env_settings_uri = self._search_environ(env_settings_uri_key)
                if env_settings_uri:
                    logger.debug('Found {} in the environment.'.format(env_settings_uri_key))
                    yield env_settings_uri, self._load_settings_from_uri(env_settings_uri)
                #end if
            #end for

        elif source == 'env':
            logger.debug('Loaded {} settings from the environment.'.format(len(os.environ)))
            yield source, dict(os.environ.items())

        elif isinstance(source, ParseResult):
            settings = self._load_settings_from_uri(source)
            yield source, settings

        elif isinstance(source, str):
            try: spec = importlib.util.find_spec(source)
            except (AttributeError, ImportError): spec = None

            settings = self._load_settings_from_spec(spec, name=source)
            if settings is None:
                _, ext = os.path.splitext(source)
                with uri_open(source, 'rb') as f:
                    yield source, self._load_settings_from_file(f, ext=ext)
            else:
                yield source, settings
            #end if

        elif hasattr(source, 'read'):
            yield source.name, self._load_settings_from_file(source)

        elif hasattr(source, 'items'):
            source_type = type(source).__name__
            for dict_settings_uri_key in self.dict_settings_uri_keys:
                if dict_settings_uri_key and dict_settings_uri_key in source and source[dict_settings_uri_key]:
                    logger.debug('Found {} in the dict-like object <{}>.'.format(dict_settings_uri_key, source_type))
                    yield from self._load_settings_from_source(source[dict_settings_uri_key])
                #end if
            #end for

            logger.debug('Loaded {} settings from dict-like object <{}>.'.format(len(source), source_type))
            yield self._get_unique_name(source_type), source

        else:
            source_type = type(source).__name__
            for object_settings_uri_key in self.object_settings_uri_keys:
                if object_settings_uri_key and hasattr(source, object_settings_uri_key) and getattr(source, object_settings_uri_key):
                    logger.debug('Found {} in the object <{}>.'.format(object_settings_uri_key, source_type))
                    yield from self._load_settings_from_source(getattr(source, object_settings_uri_key))
                #end if
            #end for

            settings = dict((k, v) for k, v in source.__dict__.items() if not k.startswith('__'))
            logger.debug('Loaded {} settings from object <{}>.'.format(len(settings), source_type))
            yield self._get_unique_name(source_type), settings
143931
def prepare_environment(default_settings=_default_settings, **kwargs):
    # pylint: disable=unused-argument
    '''
    
    '''
    for key, value in default_settings.items():
        os.environ.setdefault(key, value)
    os.environ.update(kwargs)
    if six.PY2:  # nocv
        warnings.warn(
            'Python 2.7 is deprecated and will dropped in 2.0, use Python >3.5',
            DeprecationWarning
        )
604437
def init(ctx, force):
    """"""
    if os.path.exists(PROJECT_CONFIG) and not force:
        click.secho(
            'An existing configuration file was found at "{}".\n'
            .format(PROJECT_CONFIG),
            fg='red', bold=True
        )
        click.secho(
            'Please remove it before in order to run the setup wizard or use\n'
            'the --force flag to overwrite it.'
        )
        ctx.exit(1)

    project_key = click.prompt('Project key on the issue tracker')
    base_branch = click.prompt('Integration branch', default='master')

    virtualenvs = ('.venv', '.env', 'venv', 'env')
    for p in virtualenvs:
        if os.path.exists(os.path.join(p, 'bin', 'activate')):
            venv = p
            break
    else:
        venv = ''
    venv_path = click.prompt('Path to virtual environment', default=venv)

    project_id = click.prompt('Project ID on Harvest', type=int)
    task_id = click.prompt('Task id on Harvest', type=int)

    config = configparser.ConfigParser()

    config.add_section('lancet')
    config.set('lancet', 'virtualenv', venv_path)

    config.add_section('tracker')
    config.set('tracker', 'default_project', project_key)

    config.add_section('harvest')
    config.set('harvest', 'project_id', str(project_id))
    config.set('harvest', 'task_id', str(task_id))

    config.add_section('repository')
    config.set('repository', 'base_branch', base_branch)

    with open(PROJECT_CONFIG, 'w') as fh:
        config.write(fh)

    click.secho('\nConfiguration correctly written to "{}".'
                .format(PROJECT_CONFIG), fg='green')
551566
def clone_environment(self, clone, name=None, prefix=None, **kwargs):
        """"""
        cmd_list = ['create', '--json']

        if (name and prefix) or not (name or prefix):
            raise TypeError("conda clone_environment: exactly one of `name` "
                            "or `path` required")

        if name:
            cmd_list.extend(['--name', name])

        if prefix:
            cmd_list.extend(['--prefix', prefix])

        cmd_list.extend(['--clone', clone])

        cmd_list.extend(
            self._setup_install_commands_from_kwargs(
                kwargs,
                ('dry_run', 'unknown', 'use_index_cache', 'use_local',
                 'no_pin', 'force', 'all', 'channel', 'override_channels',
                 'no_default_packages')))

        return self._call_and_parse(cmd_list, abspath=kwargs.get('abspath',
                                                                 True))
1098268
def load(self, source, as_defaults=False):
        
        if isinstance(source, six.string_types):
            source = os.path.expanduser(source)
            with open(source, encoding='utf-8') as f:
                self._rw.load_config_from_file(self._config, f, as_defaults=as_defaults)

        elif isinstance(source, (list, tuple)):
            for s in source:
                with open(s, encoding='utf-8') as f:
                    self._rw.load_config_from_file(self._config, f, as_defaults=as_defaults)

        else:
            self._rw.load_config_from_file(self._config, source, as_defaults=as_defaults)