Used to create configuration files, set permissions and so on.
1682
def main(overwrite):
    
    logger.debug("Checking existence of '%s'.", CONF_PATH)
    if not os.path.exists(CONF_PATH):
        logger.debug("Directory %s not found! Panicking..", CONF_PATH)
        raise UserWarning(
            "Can't find '%s' - it looks like ProFTPD is not installed!" % (
                CONF_PATH,
            )
        )

    # check existence of proftpd.conf
    logger.debug("Checking existence of configuration file '%s'.", CONF_FILE)
    if not os.path.exists(CONF_FILE):
        logger.debug("Configuration file not found, creating..")
        _write_conf_file()
    else:
        logger.debug("Found.")

        if not os.path.exists(CONF_FILE + "_"):
            logger.debug(
                "Backing up the configuration file '%s' -> '%s'.",
                CONF_FILE,
                CONF_FILE + "_"
            )
            shutil.copyfile(CONF_FILE, CONF_FILE + "_")
        else:
            logger.debug(
                "Backup already exists. '%s' will be overwritten.",
                CONF_FILE
            )
    if overwrite:
        logger.debug("--update switch not found, overwriting conf file")
        _write_conf_file()

    logger.debug("Checking existence of the '%s' file.", MODULES_FILE)
    if not os.path.exists(MODULES_FILE) and _is_deb_system():
        with open(MODULES_FILE, "w") as f:
            f.write(DEFAULT_MODULES_CONF)
            logger.debug("Modules file not found. Created '%s'.", MODULES_FILE)

    # create data directory, where the user informations will be stored
    logger.debug("Checking existence of user's directory '%s'.", DATA_PATH)
    if not os.path.exists(DATA_PATH):
        logger.debug("Directory '%s' not found, creating..", DATA_PATH)

        os.makedirs(DATA_PATH, 0777)

        logger.debug("Done. '%s' created.", DATA_PATH)

    # create user files if they doesn't exists
    logger.debug("Checking existence of passwd file '%s'.", LOGIN_FILE)
    if not os.path.exists(LOGIN_FILE):
        logger.debug("passwd file not found, creating..")

        open(LOGIN_FILE, "a").close()

        logger.debug("Done. '%s' created.")

    logger.debug("Setting permissions..")
    os.chown(LOGIN_FILE, get_ftp_uid(), -1)
    os.chmod(LOGIN_FILE, 0400)

    # load values from protpd conf file
    logger.debug("Switching and adding options..")
    data = ""
    with open(CONF_FILE) as f:
        data = f.read()

    # set path to passwd file
    logger.debug("\tAuthUserFile")
    data = add_or_update(
        data,
        "AuthUserFile",
        LOGIN_FILE
    )
    logger.debug("\tRequireValidShell")
    data = add_or_update(data, "RequireValidShell", "off")
    logger.debug("\tDefaultRoot")
    data = add_or_update(data, "DefaultRoot", "~")

    # http://www.proftpd.org/docs/modules/mod_log.html
    logger.debug("\tLogFormat")
    data = add_or_update(data, "LogFormat", 'paths "%f, %u, %m, %{%s}t"')
    logger.debug("\tExtendedLog")
    data = add_or_update(
        data,
        "ExtendedLog",
        LOG_FILE + " WRITE paths"
    )

    if not _is_deb_system():
        logger.debug("Detected non debian based linux. Aplying SUSE changes.")
        data = comment(data, "IdentLookups off")
        data = comment(data, "Include /etc/proftpd/modules.conf")
        data = add_or_update(data, "User", "ftp")

    # save changed file
    logger.debug("Saving into config file..")
    with open(CONF_FILE, "w") as f:
        f.write(data)
        logger.debug("Done.")

    logger.debug("Sending proftpd signal to reload configuration..")
    reload_configuration()
    logger.debug("Done.")
    logger.info("All set.")
976281
def __setup(self):
        
        if not os.path.exists(self.__local_download_dir_warc):
            os.makedirs(self.__local_download_dir_warc)

        # make loggers quite
        configure_logging({"LOG_LEVEL": "ERROR"})
        logging.getLogger('requests').setLevel(logging.CRITICAL)
        logging.getLogger('readability').setLevel(logging.CRITICAL)
        logging.getLogger('PIL').setLevel(logging.CRITICAL)
        logging.getLogger('newspaper').setLevel(logging.CRITICAL)
        logging.getLogger('newsplease').setLevel(logging.CRITICAL)
        logging.getLogger('urllib3').setLevel(logging.CRITICAL)

        # set own logger
        logging.basicConfig(level=self.__log_level)
        self.__logger = logging.getLogger(__name__)
        self.__logger.setLevel(self.__log_level)
656110
def create_conf_file (self):
        """"""
        cmd_obj = self.distribution.get_command_obj("install")
        cmd_obj.ensure_finalized()
        # we have to write a configuration file because we need the
        # <install_data> directory (and other stuff like author, url, ...)
        # all paths are made absolute by cnormpath()
        data = []
        for d in ['purelib', 'platlib', 'lib', 'headers', 'scripts', 'data']:
            attr = 'install_%s' % d
            if cmd_obj.root:
                # cut off root path prefix
                cutoff = len(cmd_obj.root)
                # don't strip the path separator
                if cmd_obj.root.endswith(os.sep):
                    cutoff -= 1
                val = getattr(cmd_obj, attr)[cutoff:]
            else:
                val = getattr(cmd_obj, attr)
            if attr == 'install_data':
                cdir = os.path.join(val, "share", "linkchecker")
                data.append('config_dir = %r' % cnormpath(cdir))
            elif attr == 'install_lib':
                if cmd_obj.root:
                    _drive, tail = os.path.splitdrive(val)
                    if tail.startswith(os.sep):
                        tail = tail[1:]
                    self.install_lib = os.path.join(cmd_obj.root, tail)
                else:
                    self.install_lib = val
            data.append("%s = %r" % (attr, cnormpath(val)))
        self.distribution.create_conf_file(data, directory=self.install_lib)
        return self.get_conf_output()
483896
private function doSetPermissions(): void
    {
        $permissionMethod = $this->getConfig(Option::permissionMethod);
        $writableDirs = implode(' ', $this->getConfig(Option::writableDirs));
        $this->log(sprintf('<h2>Setting permissions for writable dirs using the "%s" method</>', $permissionMethod));

        if ('chmod' === $permissionMethod) {
            $this->runRemote(sprintf('chmod -R %s %s', $this->getConfig(Option::permissionMode), $writableDirs));

            return;
        }

        if ('chown' === $permissionMethod) {
            $this->runRemote(sprintf('sudo chown -RL %s %s', $this->getConfig(Option::permissionUser), $writableDirs));

            return;
        }

        if ('chgrp' === $permissionMethod) {
            $this->runRemote(sprintf('sudo chgrp -RH %s %s', $this->getConfig(Option::permissionGroup), $writableDirs));

            return;
        }

        if ('acl' === $permissionMethod) {
            $this->runRemote(sprintf('sudo setfacl -RL -m u:"%s":rwX -m u:`whoami`:rwX %s', $this->getConfig(Option::permissionUser), $writableDirs));
            $this->runRemote(sprintf('sudo setfacl -dRL -m u:"%s":rwX -m u:`whoami`:rwX %s', $this->getConfig(Option::permissionUser), $writableDirs));

            return;
        }

        throw new InvalidConfigurationException(sprintf('The "%s" permission method is not valid. Select one of the supported methods.', $permissionMethod));
    }
79627
function createConfigurationDirectory()
    {
        $this->files->ensureDirExists(preg_replace('~/valet$~', '', VALET_HOME_PATH), user());

        $oldPath = posix_getpwuid(fileowner(__FILE__))['dir'].'/.valet';

        if ($this->files->isDir($oldPath)) {
            rename($oldPath, VALET_HOME_PATH);
            $this->prependPath(VALET_HOME_PATH.'/Sites');
        }

        $this->files->ensureDirExists(VALET_HOME_PATH, user());
    }
876142
def init(config_file):
    ''''''
    schema = generate_schema_file(open(config_file, 'r').read())
    sys.stdout.write(schema)
206048
public function create()
    {
        $filesystem = new Filesystem();
        if (! file_exists($this->configDir)) {
            $filesystem->mkdir($this->configDir, 0777);
            $filesystem->copy(__DIR__ . '/../Resources/role_template/ServiceConfiguration.cscfg', $this->configDir . '/ServiceConfiguration.cscfg');
            $filesystem->copy(__DIR__ . '/../Resources/role_template/ServiceDefinition.csdef', $this->configDir . '/ServiceDefinition.csdef');
            $filesystem->mirror(__DIR__ . '/../Resources/role_template/resources', $this->configDir . '/resources', null, array(
                'copy_on_windows' => true
            ));
            $filesystem->mirror(__DIR__ . '/../Resources/role_template/php', $this->configDir . '/php', null, array(
                'copy_on_windows' => true
            ));
        }
        
        if (! file_exists($this->binDir)) {
            $filesystem->mkdir($this->binDir, 0777);
        }
        $filesystem->mirror(__DIR__ . '/../Resources/role_template/bin', $this->binDir, null, array(
            'copy_on_windows' => true
        ));
    }
791208
def create_project_configuration(filename):
    """"""
    home = os.path.expanduser("~")
    project_root_folder = os.path.join(home, "hwr-experiments")
    config = {'root': project_root_folder,
              'nntoolkit': None,
              'dropbox_app_key': None,
              'dropbox_app_secret': None,
              'dbconfig': os.path.join(home, "hwrt-config/db.config.yml"),
              'data_analyzation_queue': [{'Creator': None}],
              'worker_api_key': '1234567890abc',
              'environment': 'development'}
    with open(filename, 'w') as f:
        yaml.dump(config, f, default_flow_style=False)
1331851
def createDefaultConfigFile() :
	""""""
	s = "[pyGeno_config]\nsettings_dir=%s\nremote_location=%s" % (pyGeno_SETTINGS_DIR, pyGeno_REMOTE_LOCATION)
	f = open('%s/config.ini' % pyGeno_SETTINGS_DIR, 'w')
	f.write(s)
	f.close()
656648
public static function initKernel()
    {
        $configFiles = self::getConfigFiles();

        $fs = new Filesystem();

        if(!$fs->exists($configFiles['bundles'])){
            $fs->copy($configFiles['bundles_dist'], $configFiles['bundles'], true);
        }
        if(!$fs->exists($configFiles['config'])){
            $fs->copy($configFiles['config_dist'], $configFiles['config'], true);
        }
        if(!$fs->exists($configFiles['routing'])){
            $fs->copy($configFiles['routing_dist'], $configFiles['routing'], true);
        }
        if(!$fs->exists($configFiles['security'])){
            $fs->copy($configFiles['security_dist'], $configFiles['security'], true);
        }
    }
517783
def create_user(name, groups=None, key_file=None):
    """"""

    groups = groups or []
    if not user_exists(name):
        for group in groups:
            if not group_exists(group):
                sudo(u"addgroup %s" % group)
        groups = groups and u'-G %s' % u','.join(groups) or ''
        sudo(u"useradd -m %s -s /bin/bash %s" % (groups, name))
        sudo(u"passwd -d %s" % name)
    if key_file:
        sudo(u"mkdir -p /home/%s/.ssh" % name)
        put(key_file, u"/home/%s/.ssh/authorized_keys" % name, use_sudo=True)
        sudo(u"chown -R %(name)s:%(name)s /home/%(name)s/.ssh" % {'name': name})
273698
def set_up(self):
        """"""
        self.path.state = self.path.gen.joinpath("state")
        if self.path.state.exists():
            self.path.state.rmtree(ignore_errors=True)
        self.path.state.mkdir()

        if self.path.gen.joinpath("q").exists():
            self.path.gen.joinpath("q").remove()

        for filename, text in self.given.get("files", {}).items():
            filepath = self.path.state.joinpath(filename)
            if not filepath.dirname().exists():
                filepath.dirname().makedirs()
            filepath.write_text(text)

        for filename, linkto in self.given.get("symlinks", {}).items():
            filepath = self.path.state.joinpath(filename)
            linktopath = self.path.state.joinpath(linkto)
            linktopath.symlink(filepath)

        for filename, permission in self.given.get("permissions", {}).items():
            filepath = self.path.state.joinpath(filename)
            filepath.chmod(int(permission, 8))


        pylibrary = hitchbuildpy.PyLibrary(
            name="py3.5.0",
            base_python=hitchbuildpy.PyenvBuild("3.5.0").with_build_path(self.path.share),
            module_name="pathquery",
            library_src=self.path.project,
        ).with_build_path(self.path.gen)
        
        pylibrary.ensure_built()
        
        self.python = pylibrary.bin.python


        self.example_py_code = ExamplePythonCode(self.python, self.path.state)\
            .with_code(self.given.get('code', ''))\
            .with_setup_code(self.given.get('setup', ''))\
            .with_terminal_size(160, 100)\
            .with_env(TMPDIR=self.path.gen)\
            .with_long_strings(
                yaml_snippet_1=self.given.get('yaml_snippet_1'),
                yaml_snippet=self.given.get('yaml_snippet'),
                yaml_snippet_2=self.given.get('yaml_snippet_2'),
                modified_yaml_snippet=self.given.get('modified_yaml_snippet'),
            )
458767
def create(self):
        """"""

        self.before_create()

        puts(green('Creating app context'))
        tdir = os.path.dirname(__file__)

        # Ensure the app context user exists
        user_ensure(self.user, home='/home/' + self.user)
        dir_ensure('/home/%s/.ssh' % self.user)

        t = '/home/%s/.ssh/authorized_keys'
        app_authorized_keys = t % env.user
        ctx_authorized_keys = t % self.user

        # Ensure the app user has the same authorized_keys as the admin user
        if file_exists(app_authorized_keys) and \
           not file_exists(ctx_authorized_keys):
            sudo('cp %s %s' % (app_authorized_keys, ctx_authorized_keys))
            file_attribs(ctx_authorized_keys, mode=755,
                         owner=self.user, group=self.user)

        # Actions to be performed with the app context user
        with settings(user=self.user):
            # Make sure the dot files exist
            # This is mostly necessary for virtualenvwrapper to work properly
            for f in ['bashrc', 'bash_profile', 'profile']:
                lfn = os.path.join(tdir, 'templates', '%s.tmpl' % f)
                contents = file_local_read(lfn) % self.__dict__
                rfn = '/home/%s/.%s' % (self.user, f)
                file_ensure(rfn, owner=self.user, group=self.user)
                file_update(rfn, lambda _: contents)

            # Make sure the sites folder exists
            dir_ensure('/home/%s/sites' % self.user)

            # Make sure the app's required folders exist
            for d in [self.root_dir, self.releases_dir, self.etc_dir,
                      self.log_dir, self.run_dir, self.shared_dir]:
                dir_ensure(d)

            # Create the virtualenv
            run('mkvirtualenv ' + self.name)

        self.after_create()
52279
public static function createParametersConfiguration()
    {
        $configurationFilePath = static::getApplicationRoot() . static::PARAMETERS_CONFIGURATION_FILE;
        if (file_exists($configurationFilePath)) {
            return;
        }

        $templateFilePath = __DIR__ . '/../..' . static::PARAMETERS_TEMPLATE_FILE;
        $template = file_get_contents($templateFilePath);

        $secret = bin2hex(random_bytes(20));
        $configuration = sprintf($template, $secret);

        static::createAndWriteFile($configurationFilePath, $configuration);
    }
510897
def create_config(allow_insecure_config_file=False):
    
    config = Config()
    config.add_properties(GLOBAL_CONFIG_FILENAME)
    user_config_filename = get_user_config_filename()
    if user_config_filename == LOCAL_CONFIG_FILENAME and not allow_insecure_config_file:
        verify_file_private(user_config_filename)
    config.add_properties(user_config_filename)
    return config
1313246
def add_permission(self, perm):
        
        self.Permissions(permission=perm)
        PermissionCache.flush()
        self.save()
116683
def _create_permissions(**kwargs):
    
    from django.contrib.contenttypes.models import ContentType

    object_tools.autodiscover()
    tools = object_tools.tools._registry

    # This will hold the permissions we're looking for as
    # (content_type, (codename, name))
    searched_perms = list()
    # The codenames and ctypes that should exist.
    ctypes = set()
    for model, tools in tools.items():
        ctype = ContentType.objects.get_for_model(model)
        ctypes.add(ctype)
        for perm in _get_all_permissions(model._meta, tools):
            searched_perms.append((ctype, perm))

    # Find all the Permissions that have a context_type for a model we're
    # looking for.  We don't need to check for codenames since we already have
    # a list of the ones we're going to create.
    all_perms = set(auth_app.Permission.objects.filter(
        content_type__in=ctypes,
    ).values_list(
        "content_type", "codename"
    ))

    for ctype, (codename, name) in searched_perms:
        # If the permissions exists, move on.
        if (ctype.pk, codename) in all_perms:
            continue
        p = auth_app.Permission.objects.create(
            codename=codename,
            name=name,
            content_type=ctype
        )
        if kwargs.get("verbosity", 2) >= 2:
            print("Adding permission '%s'" % p)