Python oyaml.dump() Examples

The following are 21 code examples of oyaml.dump(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module oyaml , or try the search function .
Example #1
Source File: zynthian_gui_keybinding.py    From zynthian-ui with GNU General Public License v3.0 6 votes vote down vote up
def save(self, config="keybinding"):
		"""
		Save key binding map to file
		
		Parameters
		----------
		config : str,optional
			Name of configuration to save - the file <config>.yaml will be saved to the Zynthian config directory
			Default: 'keybinding'
		
		Returns
		-------
		bool
			True on success
		"""
		
		logging.info("Saving key binding to %s.yaml", config)
		config_dir = environ.get('ZYNTHIAN_CONFIG_DIR',"/zynthian/config")
		config_fpath = config_dir + "/" + config + ".yaml"
		try:
			with open(config_fpath,"w") as fh:
				yaml.dump(self.config, fh)
				logging.info("Saving keyboard binding config file {}".format(config_fpath))
				return True

		except Exception as e:
			logging.error("Can't save keyboard binding config file '{}': {}".format(config_fpath,e))
			return False 
Example #2
Source File: serialization.py    From CycleGAN-Tensorflow-2 with MIT License 6 votes vote down vote up
def save_pickle(path, obj, **kwargs):

    path = _check_ext(path, 'pkl')

    # wrap pickle.dump
    with open(path, 'wb') as f:
        pickle.dump(obj, f, **kwargs) 
Example #3
Source File: __init__.py    From pentagon with Apache License 2.0 6 votes vote down vote up
def write(self, file=None):
            if file is not None:
                self.file = file
                with open(self.file, 'w') as yf:
                    yf.write(yaml.dump(self.data)) 
Example #4
Source File: serialization.py    From AttGAN-Tensorflow with MIT License 5 votes vote down vote up
def save_pickle(path, obj, **kwargs):

    path = _check_ext(path, 'pkl')

    # wrap pickle.dump
    with open(path, 'wb') as f:
        pickle.dump(obj, f, **kwargs) 
Example #5
Source File: serialization.py    From DCGAN-LSGAN-WGAN-GP-DRAGAN-Tensorflow-2 with MIT License 5 votes vote down vote up
def save_json(path, obj, **kwargs):
    # default
    if 'indent' not in kwargs:
        kwargs['indent'] = 4
    if 'separators' not in kwargs:
        kwargs['separators'] = (',', ': ')

    path = _check_ext(path, 'json')

    # wrap json.dump
    with open(path, 'w') as f:
        json.dump(obj, f, **kwargs) 
Example #6
Source File: serialization.py    From AttGAN-Tensorflow with MIT License 5 votes vote down vote up
def save_yaml(path, data, **kwargs):
    import oyaml as yaml

    path = _check_ext(path, 'yml')

    with open(path, 'w') as f:
        yaml.dump(data, f, **kwargs) 
Example #7
Source File: serialization.py    From AttGAN-Tensorflow with MIT License 5 votes vote down vote up
def save_json(path, obj, **kwargs):
    # default
    if 'indent' not in kwargs:
        kwargs['indent'] = 4
    if 'separators' not in kwargs:
        kwargs['separators'] = (',', ': ')

    path = _check_ext(path, 'json')

    # wrap json.dump
    with open(path, 'w') as f:
        json.dump(obj, f, **kwargs) 
Example #8
Source File: serialization.py    From DCGAN-LSGAN-WGAN-GP-DRAGAN-Pytorch with MIT License 5 votes vote down vote up
def save_pickle(path, obj, **kwargs):

    path = _check_ext(path, 'pkl')

    # wrap pickle.dump
    with open(path, 'wb') as f:
        pickle.dump(obj, f, **kwargs) 
Example #9
Source File: serialization.py    From DCGAN-LSGAN-WGAN-GP-DRAGAN-Pytorch with MIT License 5 votes vote down vote up
def save_yaml(path, data, **kwargs):
    import oyaml as yaml

    path = _check_ext(path, 'yml')

    with open(path, 'w') as f:
        yaml.dump(data, f, **kwargs) 
Example #10
Source File: serialization.py    From DCGAN-LSGAN-WGAN-GP-DRAGAN-Pytorch with MIT License 5 votes vote down vote up
def save_json(path, obj, **kwargs):
    # default
    if 'indent' not in kwargs:
        kwargs['indent'] = 4
    if 'separators' not in kwargs:
        kwargs['separators'] = (',', ': ')

    path = _check_ext(path, 'json')

    # wrap json.dump
    with open(path, 'w') as f:
        json.dump(obj, f, **kwargs) 
Example #11
Source File: config.py    From mapchete with MIT License 5 votes vote down vote up
def get_hash(x):
    """Return hash of x."""
    if isinstance(x, str):
        return hash(x)
    elif isinstance(x, dict):
        return hash(yaml.dump(x)) 
Example #12
Source File: serialization.py    From CycleGAN-Tensorflow-2 with MIT License 5 votes vote down vote up
def save_yaml(path, data, **kwargs):
    import oyaml as yaml

    path = _check_ext(path, 'yml')

    with open(path, 'w') as f:
        yaml.dump(data, f, **kwargs) 
Example #13
Source File: serialization.py    From CycleGAN-Tensorflow-2 with MIT License 5 votes vote down vote up
def save_json(path, obj, **kwargs):
    # default
    if 'indent' not in kwargs:
        kwargs['indent'] = 4
    if 'separators' not in kwargs:
        kwargs['separators'] = (',', ': ')

    path = _check_ext(path, 'json')

    # wrap json.dump
    with open(path, 'w') as f:
        json.dump(obj, f, **kwargs) 
Example #14
Source File: config.py    From kafka-shell with Apache License 2.0 5 votes vote down vote up
def save_yaml(config, f):
    yaml.dump(config, f, default_flow_style=False, sort_keys=False) 
Example #15
Source File: cron_rules.py    From cronyo with MIT License 5 votes vote down vote up
def delete(name):
    rules = _find([name, _namespaced(name)])
    for rule in rules:
        logger.info("deleting rule:\n{}".format(yaml.dump(_export_rule(rule))))
    _delete(rules) 
Example #16
Source File: cron_rules.py    From cronyo with MIT License 5 votes vote down vote up
def export(prefix, search):
    logger.info('exporting rules')
    kwargs = {"EventBusName": "default"}
    if prefix is not None:
        kwargs["NamePrefix"] = prefix
    if search is not None:
        query = "Rules[?contains(Name, '{0}')] | {{Rules: @}}".format(search)
        kwargs["query"] = query
    rules = events("list_rules", **kwargs)['Rules']
    print(yaml.dump([_export_rule(rule) for rule in rules])) 
Example #17
Source File: serialization.py    From DCGAN-LSGAN-WGAN-GP-DRAGAN-Tensorflow-2 with MIT License 5 votes vote down vote up
def save_pickle(path, obj, **kwargs):

    path = _check_ext(path, 'pkl')

    # wrap pickle.dump
    with open(path, 'wb') as f:
        pickle.dump(obj, f, **kwargs) 
Example #18
Source File: serialization.py    From DCGAN-LSGAN-WGAN-GP-DRAGAN-Tensorflow-2 with MIT License 5 votes vote down vote up
def save_yaml(path, data, **kwargs):
    import oyaml as yaml

    path = _check_ext(path, 'yml')

    with open(path, 'w') as f:
        yaml.dump(data, f, **kwargs) 
Example #19
Source File: commands.py    From sqlfluff with MIT License 4 votes vote down vote up
def lint(paths, format, nofail, **kwargs):
    """Lint SQL files via passing a list of files or using stdin.

    PATH is the path to a sql file or directory to lint. This can be either a
    file ('path/to/file.sql'), a path ('directory/of/sql/files'), a single ('-')
    character to indicate reading from *stdin* or a dot/blank ('.'/' ') which will
    be interpreted like passing the current working directory as a path argument.

    Linting SQL files:

        sqlfluff lint path/to/file.sql
        sqlfluff lint directory/of/sql/files

    Linting a file via stdin (note the lone '-' character):

        cat path/to/file.sql | sqlfluff lint -
        echo 'select col from tbl' | sqlfluff lint -

    """
    c = get_config(**kwargs)
    lnt = get_linter(c, silent=format in ('json', 'yaml'))
    verbose = c.get('verbose')

    config_string = format_config(lnt, verbose=verbose)
    if len(config_string) > 0:
        lnt.log(config_string)

    # add stdin if specified via lone '-'
    if ('-',) == paths:
        result = lnt.lint_string_wrapped(sys.stdin.read(), fname='stdin', verbosity=verbose)
    else:
        # Output the results as we go
        lnt.log(format_linting_result_header(verbose=verbose))
        try:
            result = lnt.lint_paths(paths, verbosity=verbose, ignore_non_existent_files=False)
        except IOError:
            click.echo(colorize('The path(s) {0!r} could not be accessed. Check it/they exist(s).'.format(paths), 'red'))
            sys.exit(1)
        # Output the final stats
        lnt.log(format_linting_result_footer(result, verbose=verbose))

    if format == 'json':
        click.echo(json.dumps(result.as_records()))
    elif format == 'yaml':
        click.echo(yaml.dump(result.as_records()))

    if not nofail:
        sys.exit(result.stats()['exit code'])
    else:
        sys.exit(0) 
Example #20
Source File: create.py    From mapchete with MIT License 4 votes vote down vote up
def create(
    mapchete_file,
    process_file,
    out_format,
    out_path=None,
    pyramid_type=None,
    force=False
):
    """Create an empty Mapchete and process file in a given directory."""
    if os.path.isfile(process_file) or os.path.isfile(mapchete_file):
        if not force:
            raise IOError("file(s) already exists")

    out_path = out_path if out_path else os.path.join(os.getcwd(), "output")

    # copy file template to target directory
    # Reads contents with UTF-8 encoding and returns str.
    process_template = str(files("mapchete.static").joinpath("process_template.py"))
    process_file = os.path.join(os.getcwd(), process_file)
    copyfile(process_template, process_file)

    # modify and copy mapchete file template to target directory
    mapchete_template = str(
        files("mapchete.static").joinpath("mapchete_template.mapchete")
    )

    output_options = dict(
        format=out_format, path=out_path, **FORMAT_MANDATORY[out_format]
    )

    pyramid_options = {'grid': pyramid_type}

    substitute_elements = {
        'process_file': process_file,
        'output': dump({'output': output_options}, default_flow_style=False),
        'pyramid': dump({'pyramid': pyramid_options}, default_flow_style=False)
    }
    with open(mapchete_template, 'r') as config_template:
        config = Template(config_template.read())
        customized_config = config.substitute(substitute_elements)
    with open(mapchete_file, 'w') as target_config:
        target_config.write(customized_config) 
Example #21
Source File: cron_rules.py    From cronyo with MIT License 4 votes vote down vote up
def put(name,
        cron_expression,
        function_name,
        target_input={},
        description=None):

    logger.info("finding lambda function {}".format(function_name))
    target_arn = \
        _get_target_arn(function_name) or \
        _get_target_arn(_namespaced(function_name))
    if not target_arn:
        logger.error("unable to find lambda function for {}".format(function_name))
        return

    logger.debug(
        "create / update cron rule {0}: {1} for target {2}".format(
            name,
            cron_expression,
            target_arn
        )
    )
    if description:
        rule = events("put_rule",
                      Name=name,
                      ScheduleExpression=cron_expression,
                      Description=description)
    else:
        rule = events("put_rule",
                      Name=name,
                      ScheduleExpression=cron_expression)
    events(
        "put_targets",
        Rule=name,
        Targets=[
            {
                "Id": "1",
                "Arn": target_arn,
                "Input": json.dumps(target_input)
            }
        ]
    )
    try:
        logger.debug("setting lambda permission")
        source_arn = rule["RuleArn"]
        if source_arn.find(NAMESPACE) > 0:
            rule_prefix = rule["RuleArn"].split("/{}".format(NAMESPACE))[0]
            source_arn = "{}/{}*".format(rule_prefix, NAMESPACE)
        logger.debug("lambda permission SourceArn:{}".format(source_arn))
        aws_lambda(
            "add_permission",
            FunctionName=target_arn,
            Action="lambda:InvokeFunction",
            Principal="events.amazonaws.com",
            SourceArn=source_arn,
            StatementId=hashlib.sha1(source_arn.encode("utf-8")).hexdigest()
        )
    except ClientError as error:
        logger.debug("permission already set. {}".format(error))

    for rule in _find([name]):
        logger.info("rule created/updated:\n{}".format(yaml.dump(_export_rule(rule))))