Save the configured defaults to be used when the factory is instantiated
763757
function setDefaults(definition) {
      providerConfig.optionsFactory = definition.options;
      providerConfig.methods = (definition.methods || []).concat(EXPOSED_METHODS);
      return provider;
    }
460975
def save_configure(self,
                       repo=None,
                       name=None,
                       groups=None,
                       config_val='',
                       from_registry=False,
                       main_cfg=False,
                       instances=1):
        
        def template_to_manifest(vent_template, manifest, tool, instances):
            """
            Helper function to transfer information from vent.template
            to plugin_manifest
            """
            sections = vent_template.sections()
            if sections[0]:
                for section in sections[1]:
                    section_dict = {}
                    if section == 'settings':
                        section_dict.update({'instances': str(instances)})
                    options = vent_template.options(section)
                    if options[0]:
                        for option in options[1]:
                            option_name = option
                            if option == 'name':
                                option_name = 'link_name'
                            opt_val = vent_template.option(section,
                                                           option)[1]
                            section_dict[option_name] = opt_val
                    if section_dict:
                        manifest.set_option(tool, section,
                                            json.dumps(section_dict))
                    elif manifest.option(tool, section)[0]:
                        manifest.del_option(tool, section)

        constraints = locals()
        del constraints['config_val']
        del constraints['from_registry']
        del constraints['main_cfg']
        del constraints['instances']
        del constraints['template_to_manifest']
        status = (True, None)
        fd = None
        # ensure instances is an int and remove instances from config_val to
        # ensure correct info
        instances = int(instances)
        config_val = re.sub(r'instances\ *=\ *\d+\n', '', config_val)
        api_system = System()
        manifest = api_system.manifest
        if not main_cfg:
            if not from_registry:
                # creating new instances
                if instances > 1:
                    fd, template_path = tempfile.mkstemp(suffix='.template')
                    # scrub name for clean section name
                    if re.search(r'\d+$', name):
                        name = re.sub(r'\d+$', '', name)
                    t_identifier = {'name': name,
                                    'branch': branch,
                                    'version': version}
                    result = Template(manifest).constrain_opts(
                        t_identifier, [])
                    tools = result[0]
                    tool = list(tools.keys())[0]
                else:
                    options = ['path', 'multi_tool', 'name']
                    tools, _ = Template(manifest).constrain_opts(
                        constraints, options)
                    # only one tool in tools because perform this function for
                    # every tool
                    if tools:
                        tool = list(tools.keys())[0]
                        if ('multi_tool' in tools[tool] and
                                tools[tool]['multi_tool'] == 'yes'):
                            name = tools[tool]['name']
                            if name == 'unspecified':
                                name = 'vent'
                            template_path = join(tools[tool]['path'],
                                                 name+'.template')
                        else:
                            template_path = join(tools[tool]['path'],
                                                 'vent.template')
                    else:
                        status = (False, "Couldn't save configuration")
            else:
                fd, template_path = tempfile.mkstemp(suffix='.template')
                options = ['namespace']
                constraints.update({'type': 'registry'})
                tools, _ = Template(manifest).constrain_opts(constraints,
                                                             options)
                if tools:
                    tool = list(tools.keys())[0]
                else:
                    status = (False, "Couldn't save configuration")
            if status[0]:
                try:
                    # save in vent.template
                    with open(template_path, 'w') as f:
                        f.write(config_val)
                    # save in plugin_manifest
                    vent_template = Template(template_path)
                    manifest = Template(manifest)
                    if instances > 1:
                        # add instances as needed
                        for i in range(1, instances + 1):
                            i_section = tool.rsplit(':', 2)
                            i_section[0] += str(i) if i != 1 else ''
                            i_section = ':'.join(i_section)
                            if not manifest.section(i_section)[0]:
                                manifest.add_section(i_section)
                                for val_pair in manifest.section(tool)[1]:
                                    name = val_pair[0]
                                    val = val_pair[1]
                                    if name == 'name':
                                        val += str(i)
                                    elif name == 'last_updated':
                                        val = Timestamp()
                                    elif name == 'running':
                                        val = 'no'
                                    manifest.set_option(i_section, name, val)
                                template_to_manifest(vent_template, manifest,
                                                     i_section, instances)
                            else:
                                settings = manifest.option(i_section,
                                                           'settings')
                                if settings[0]:
                                    settings_dict = json.loads(settings[1])
                                    settings_dict['instances'] = str(instances)
                                    manifest.set_option(i_section, 'settings',
                                                        json.dumps(
                                                            settings_dict))
                                else:
                                    inst = str(instances)
                                    settings_dict = {'instances': inst}
                                    manifest.set_option(i_section, 'settings',
                                                        json.dumps(
                                                            settings_dict))
                    else:
                        try:
                            settings_str = manifest.option(tool, 'settings')[1]
                            settings_dict = json.loads(settings_str)
                            old_instances = int(settings_dict['instances'])
                        except Exception:
                            old_instances = 1
                        template_to_manifest(vent_template, manifest,
                                             tool, old_instances)
                    manifest.write_config()
                    status = (True, manifest)
                except Exception as e:  # pragma: no cover
                    self.logger.error('save_configure error: ' + str(e))
                    status = (False, str(e))
            # close os file handle and remove temp file
            if from_registry or instances > 1:
                try:
                    close(fd)
                    remove(template_path)
                except Exception as e:  # pragma: no cover
                    self.logger.error('save_configure error: ' + str(e))
        else:
            with open(self.vent_config, 'w') as f:
                f.write(config_val)
        return status
1293195
function init(opt_config) {
  if (singleton) {
    return;
  }
  var config = objects.clone(defaultConfig);
  if (opt_config) {
    objects.merge(config, opt_config);
  }

  singleton = new YouTubeModal(config);
}
361081
def _auto_fill_defaults(cls):
        """"""
        if not cls.spec.appname:
            cls.spec.appname = get_basename(get_program_path())
        if not cls.spec.dev:
            cls.spec.dev = get_dev_folder()
1099662
def setup(self, options=None, extractor=None):
        
        # Get our programmatic options
        self._util.use_options(options, extractor)

        # Overwrite non defaults in self.values with values from config
        self._util.use_config_file()
846576
private synchronized void initialize() {
        Iterator types = EntityTypesLocator.getEntityTypes().getAllEntityTypes();
        String factoryName = null;

        while (types.hasNext()) {
            Class type = (Class) types.next();
            if (type != Object.class) {
                String factoryKey =
                        "org.apereo.portal.services.EntityNameFinderService.NameFinderFactory.implementation_"
                                + type.getName();
                try {
                    factoryName = PropertiesManager.getProperty(factoryKey);
                } catch (Exception runtime) {
                    String dMsg =
                            "EntityNameFinderService.initialize(): "
                                    + "could not find property for "
                                    + type.getName()
                                    + " factory.";
                    log.debug(dMsg);
                }
                if (factoryName != null) {
                    try {
                        IEntityNameFinderFactory factory =
                                (IEntityNameFinderFactory) Class.forName(factoryName).newInstance();
                        getNameFinders().put(type, factory.newFinder());
                    } catch (Exception e) {
                        String eMsg =
                                "EntityNameFinderService.initialize(): "
                                        + "Could not instantiate finder for "
                                        + type.getName()
                                        + ": ";
                        log.error(eMsg, e);
                    }
                }
            }
        }
        setInitialized(true);
    }
912817
function () {
      var defaultConfig = JSON.parse(fs.readFileSync(__dirname + '/../patsy.default.json', 'utf8'));

      var projectSpecificSettings = {
        "project": {
          "details" : {
            "name" : path.basename(process.cwd())
          },
          "environment": {
            "root" : path.basename(process.cwd()),
            "abs_path": process.cwd() + path.sep
          }
        }
      };

      var almostDefaultConfig = require('./utils').deepExtend(defaultConfig, projectSpecificSettings);

      almostDefaultConfig = JSON.stringify(almostDefaultConfig, null, 2);

      fs.writeFileSync("patsy.json", almostDefaultConfig);

    }
540444
def _saveGuiSettings(self):
        
        # Put the settings into a ConfigObj dict (don't use a config-spec)
        rcFile = self._rcDir+os.sep+APP_NAME.lower()+'.cfg'
        #
        if os.path.exists(rcFile): os.remove(rcFile)
        co = configobj.ConfigObj(rcFile) # can skip try-block, won't read file

        co['showHelpInBrowser']       = self._showHelpInBrowser
        co['saveAndCloseOnExec']      = self._saveAndCloseOnExec
        co['writeProtectOnSaveAsOpt'] = self._writeProtectOnSaveAs
        co['flagNonDefaultVals']      = self._flagNonDefaultVals
        co['frameColor']              = self._frmeColor
        co['taskBoxColor']            = self._taskColor
        co['buttonBoxColor']          = self._bboxColor
        co['entriesColor']            = self._entsColor
        co['flaggedColor']            = self._flagColor

        co.initial_comment = ['Automatically generated by '+\
            APP_NAME+'.  All edits will eventually be overwritten.']
        co.initial_comment.append('To use platform default colors, delete each color line below.')
        co.final_comment = [''] # ensure \n at EOF
        co.write()
1291734
def _set_defaults(self):
        
        for field_name in self._fields:
            if field_name in self._init_fields:
                continue
            field = self.get_field(field_name)
            if hasattr(field, "default"):
                field.proxy_set(field.default)
874879
private void apiAfterConfiguration(){
		ProducerFilterConfig filterConfig[] = WebUIConfig.getInstance().getFilters();
		if (filterConfig==null || filterConfig.length==0)
			return;
		List<ProducerFilter> newProducerFilters = new ArrayList<>(filterConfig.length);
		for (ProducerFilterConfig pfc : filterConfig){
			try {
				ProducerFilter filter = (ProducerFilter)Class.forName(pfc.getClazzName()).newInstance();
				filter.customize(pfc.getParameter());
				newProducerFilters.add(filter);
			} catch (InstantiationException e) {
				log.warn("Can't initialize filter of class "+pfc.getClazzName());
			} catch (IllegalAccessException e) {
				log.warn("Can't initialize filter of class " + pfc.getClazzName());
			} catch (ClassNotFoundException e) {
				log.warn("Can't initialize filter of class " + pfc.getClazzName());
			}
		}

		DecoratorConfig[] decoratorConfigs = WebUIConfig.getInstance().getDecorators();
		if (decoratorConfigs != null){
			log.debug("Configuring decorator configs "+ Arrays.toString(decoratorConfigs));
			for (DecoratorConfig config : decoratorConfigs){
				try{
					Class decoratorClass = Class.forName(config.getDecoratorClazzName());
					IDecorator decorator = (IDecorator) decoratorClass.newInstance();
					DecoratorRegistryFactory.getDecoratorRegistry().addDecorator(config.getStatClazzName(), decorator);

				}catch (ClassNotFoundException e){
					log.warn("can't configure decorator "+config+" due ", e);
				} catch (InstantiationException e) {
					log.warn("can't configure decorator " + config + " due ", e);
				} catch (IllegalAccessException e) {
					log.warn("can't configure decorator "+config+" due ", e);
				}
			}
		}

		producerFilters = newProducerFilters;

	}
860995
def reset_to_defaults(self, save=True, verbose=False, section=None):
        
        for sec, options in self.defaults:
            if section == None or section == sec:
                for option in options:
                    value = options[ option ]
                    self._set(sec, option, value, verbose)
        if save:
            self._save()
459495
def save(self):
        ''''''
        if self.app.cfg_mode == 'json':
            with open(self.app.cfg_file, 'w') as opened_file:
                json.dump(self.app.cfg, opened_file)
        else:
            with open(self.app.cfg_file, 'w')as opened_file:
                yaml.dump(self.app.cfg, opened_file)
1347396
def save_configs(self):
        

        try:
            config_path = os.path.join(self._working_directory, "configs")
            os.makedirs(config_path, exist_ok=True)
        except OSError as e:
            raise DynamipsError("Could could not create configuration directory {}: {}".format(config_path, e))

        startup_config_base64, private_config_base64 = yield from self.extract_config()
        if startup_config_base64:
            startup_config = self.startup_config_path
            try:
                config = base64.b64decode(startup_config_base64).decode("utf-8", errors="replace")
                config = "!\n" + config.replace("\r", "")
                config_path = os.path.join(self._working_directory, startup_config)
                with open(config_path, "wb") as f:
                    log.info("saving startup-config to {}".format(startup_config))
                    f.write(config.encode("utf-8"))
            except (binascii.Error, OSError) as e:
                raise DynamipsError("Could not save the startup configuration {}: {}".format(config_path, e))

        if private_config_base64 and base64.b64decode(private_config_base64) != b'\nkerberos password \nend\n':
            private_config = self.private_config_path
            try:
                config = base64.b64decode(private_config_base64).decode("utf-8", errors="replace")
                config_path = os.path.join(self._working_directory, private_config)
                with open(config_path, "wb") as f:
                    log.info("saving private-config to {}".format(private_config))
                    f.write(config.encode("utf-8"))
            except (binascii.Error, OSError) as e:
                raise DynamipsError("Could not save the private configuration {}: {}".format(config_path, e))
1143150
def saveProfile(self, settings=None):
        
        self._updateNonDefaultsForInspector(self.inspectorRegItem, self.inspector)

        if settings is None:
            settings = QtCore.QSettings()
        logger.debug("Writing settings to: {}".format(settings.group()))

        settings.beginGroup('cfg_inspectors')
        try:
            for key, nonDefaults in self._inspectorsNonDefaults.items():
                if nonDefaults:
                    settings.setValue(key, ctiDumps(nonDefaults))
                    logger.debug("Writing non defaults for {}: {}".format(key, nonDefaults))
        finally:
            settings.endGroup()

        self.configWidget.configTreeView.saveProfile("config_tree/header_state", settings)
        self.repoWidget.repoTreeView.saveProfile("repo_tree/header_state", settings)

        settings.setValue("geometry", self.saveGeometry())
        settings.setValue("state", self.saveState())

        identifier = self.inspectorRegItem.identifier if self.inspectorRegItem else ''
        settings.setValue("inspector", identifier)
701420
protected function initDefaults()
    {
        if ($this->properties['header'] === null) {
            $this->setHeader($this->name);
        }
        if ($this->properties['type'] === null) {
            $this->setType(ColumnType::createType(ColumnType::TYPE_STRING));
        }
    }
130720
def _load_defaults(self, default='settings.py'):
        '''
        
        '''
        if default[-3:] == '.py':
            default = default[:-3]

        self.my_settings = {}
        try:
            settings = importlib.import_module(default)
            self.my_settings = self._convert_to_dict(settings)
        except ImportError:
            log.warning("No default settings found")
49018
def _save_new_defaults(self, defaults, new_version, subfolder):
        """"""
        new_defaults = DefaultsConfig(name='defaults-'+new_version,
                                      subfolder=subfolder)
        if not osp.isfile(new_defaults.filename()):
            new_defaults.set_defaults(defaults)
            new_defaults._save()