repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
senaite/senaite.core.supermodel | src/senaite/core/supermodel/model.py | SuperModel.brain | def brain(self):
"""Catalog brain of the wrapped object
"""
if self._brain is None:
logger.debug("SuperModel::brain: *Fetch catalog brain*")
self._brain = self.get_brain_by_uid(self.uid)
return self._brain | python | def brain(self):
"""Catalog brain of the wrapped object
"""
if self._brain is None:
logger.debug("SuperModel::brain: *Fetch catalog brain*")
self._brain = self.get_brain_by_uid(self.uid)
return self._brain | [
"def",
"brain",
"(",
"self",
")",
":",
"if",
"self",
".",
"_brain",
"is",
"None",
":",
"logger",
".",
"debug",
"(",
"\"SuperModel::brain: *Fetch catalog brain*\"",
")",
"self",
".",
"_brain",
"=",
"self",
".",
"get_brain_by_uid",
"(",
"self",
".",
"uid",
"... | Catalog brain of the wrapped object | [
"Catalog",
"brain",
"of",
"the",
"wrapped",
"object"
] | 1819154332b8776f187aa98a2e299701983a0119 | https://github.com/senaite/senaite.core.supermodel/blob/1819154332b8776f187aa98a2e299701983a0119/src/senaite/core/supermodel/model.py#L243-L249 | train | 44,300 |
senaite/senaite.core.supermodel | src/senaite/core/supermodel/model.py | SuperModel.catalog | def catalog(self):
"""Primary registered catalog for the wrapped portal type
"""
if self._catalog is None:
logger.debug("SuperModel::catalog: *Fetch catalog*")
self._catalog = self.get_catalog_for(self.brain)
return self._catalog | python | def catalog(self):
"""Primary registered catalog for the wrapped portal type
"""
if self._catalog is None:
logger.debug("SuperModel::catalog: *Fetch catalog*")
self._catalog = self.get_catalog_for(self.brain)
return self._catalog | [
"def",
"catalog",
"(",
"self",
")",
":",
"if",
"self",
".",
"_catalog",
"is",
"None",
":",
"logger",
".",
"debug",
"(",
"\"SuperModel::catalog: *Fetch catalog*\"",
")",
"self",
".",
"_catalog",
"=",
"self",
".",
"get_catalog_for",
"(",
"self",
".",
"brain",
... | Primary registered catalog for the wrapped portal type | [
"Primary",
"registered",
"catalog",
"for",
"the",
"wrapped",
"portal",
"type"
] | 1819154332b8776f187aa98a2e299701983a0119 | https://github.com/senaite/senaite.core.supermodel/blob/1819154332b8776f187aa98a2e299701983a0119/src/senaite/core/supermodel/model.py#L252-L258 | train | 44,301 |
senaite/senaite.core.supermodel | src/senaite/core/supermodel/model.py | SuperModel.get_catalog_for | def get_catalog_for(self, brain_or_object):
"""Return the primary catalog for the given brain or object
"""
if not api.is_object(brain_or_object):
raise TypeError("Invalid object type %r" % brain_or_object)
catalogs = api.get_catalogs_for(brain_or_object, default="uid_catalog")
return catalogs[0] | python | def get_catalog_for(self, brain_or_object):
"""Return the primary catalog for the given brain or object
"""
if not api.is_object(brain_or_object):
raise TypeError("Invalid object type %r" % brain_or_object)
catalogs = api.get_catalogs_for(brain_or_object, default="uid_catalog")
return catalogs[0] | [
"def",
"get_catalog_for",
"(",
"self",
",",
"brain_or_object",
")",
":",
"if",
"not",
"api",
".",
"is_object",
"(",
"brain_or_object",
")",
":",
"raise",
"TypeError",
"(",
"\"Invalid object type %r\"",
"%",
"brain_or_object",
")",
"catalogs",
"=",
"api",
".",
... | Return the primary catalog for the given brain or object | [
"Return",
"the",
"primary",
"catalog",
"for",
"the",
"given",
"brain",
"or",
"object"
] | 1819154332b8776f187aa98a2e299701983a0119 | https://github.com/senaite/senaite.core.supermodel/blob/1819154332b8776f187aa98a2e299701983a0119/src/senaite/core/supermodel/model.py#L260-L266 | train | 44,302 |
senaite/senaite.core.supermodel | src/senaite/core/supermodel/model.py | SuperModel.get_brain_by_uid | def get_brain_by_uid(self, uid):
"""Lookup brain from the right catalog
"""
if uid == "0":
return api.get_portal()
# ensure we have the primary catalog
if self._catalog is None:
uid_catalog = api.get_tool("uid_catalog")
results = uid_catalog({"UID": uid})
if len(results) != 1:
raise ValueError("No object found for UID '{}'".format(uid))
brain = results[0]
self._catalog = self.get_catalog_for(brain)
# Fetch the brain with the primary catalog
results = self.catalog({"UID": uid})
if not results:
raise ValueError("No results found for UID '{}'".format(uid))
if len(results) != 1:
raise ValueError("Found more than one object for UID '{}'"
.format(uid))
return results[0] | python | def get_brain_by_uid(self, uid):
"""Lookup brain from the right catalog
"""
if uid == "0":
return api.get_portal()
# ensure we have the primary catalog
if self._catalog is None:
uid_catalog = api.get_tool("uid_catalog")
results = uid_catalog({"UID": uid})
if len(results) != 1:
raise ValueError("No object found for UID '{}'".format(uid))
brain = results[0]
self._catalog = self.get_catalog_for(brain)
# Fetch the brain with the primary catalog
results = self.catalog({"UID": uid})
if not results:
raise ValueError("No results found for UID '{}'".format(uid))
if len(results) != 1:
raise ValueError("Found more than one object for UID '{}'"
.format(uid))
return results[0] | [
"def",
"get_brain_by_uid",
"(",
"self",
",",
"uid",
")",
":",
"if",
"uid",
"==",
"\"0\"",
":",
"return",
"api",
".",
"get_portal",
"(",
")",
"# ensure we have the primary catalog",
"if",
"self",
".",
"_catalog",
"is",
"None",
":",
"uid_catalog",
"=",
"api",
... | Lookup brain from the right catalog | [
"Lookup",
"brain",
"from",
"the",
"right",
"catalog"
] | 1819154332b8776f187aa98a2e299701983a0119 | https://github.com/senaite/senaite.core.supermodel/blob/1819154332b8776f187aa98a2e299701983a0119/src/senaite/core/supermodel/model.py#L268-L290 | train | 44,303 |
senaite/senaite.core.supermodel | src/senaite/core/supermodel/model.py | SuperModel.to_super_model | def to_super_model(self, thing):
"""Wraps an object into a Super Model
"""
if api.is_uid(thing):
return SuperModel(thing)
if not api.is_object(thing):
raise TypeError("Expected a portal object, got '{}'"
.format(type(thing)))
return thing | python | def to_super_model(self, thing):
"""Wraps an object into a Super Model
"""
if api.is_uid(thing):
return SuperModel(thing)
if not api.is_object(thing):
raise TypeError("Expected a portal object, got '{}'"
.format(type(thing)))
return thing | [
"def",
"to_super_model",
"(",
"self",
",",
"thing",
")",
":",
"if",
"api",
".",
"is_uid",
"(",
"thing",
")",
":",
"return",
"SuperModel",
"(",
"thing",
")",
"if",
"not",
"api",
".",
"is_object",
"(",
"thing",
")",
":",
"raise",
"TypeError",
"(",
"\"E... | Wraps an object into a Super Model | [
"Wraps",
"an",
"object",
"into",
"a",
"Super",
"Model"
] | 1819154332b8776f187aa98a2e299701983a0119 | https://github.com/senaite/senaite.core.supermodel/blob/1819154332b8776f187aa98a2e299701983a0119/src/senaite/core/supermodel/model.py#L293-L301 | train | 44,304 |
senaite/senaite.core.supermodel | src/senaite/core/supermodel/model.py | SuperModel.stringify | def stringify(self, value):
"""Convert value to string
This method is used to generate a simple JSON representation of the
object (without dereferencing objects etc.)
"""
# SuperModel -> UID
if ISuperModel.providedBy(value):
return str(value)
# DateTime -> ISO8601 format
elif isinstance(value, (DateTime)):
return value.ISO8601()
# Image/Files -> filename
elif safe_hasattr(value, "filename"):
return value.filename
# Dict -> convert_value_to_string
elif isinstance(value, dict):
return {k: self.stringify(v) for k, v in value.iteritems()}
# List -> convert_value_to_string
if isinstance(value, (list, tuple, LazyMap)):
return map(self.stringify, value)
# Callables
elif safe_callable(value):
return self.stringify(value())
elif isinstance(value, unicode):
value = value.encode("utf8")
try:
return str(value)
except (AttributeError, TypeError, ValueError):
logger.warn("Could not convert {} to string".format(repr(value)))
return None | python | def stringify(self, value):
"""Convert value to string
This method is used to generate a simple JSON representation of the
object (without dereferencing objects etc.)
"""
# SuperModel -> UID
if ISuperModel.providedBy(value):
return str(value)
# DateTime -> ISO8601 format
elif isinstance(value, (DateTime)):
return value.ISO8601()
# Image/Files -> filename
elif safe_hasattr(value, "filename"):
return value.filename
# Dict -> convert_value_to_string
elif isinstance(value, dict):
return {k: self.stringify(v) for k, v in value.iteritems()}
# List -> convert_value_to_string
if isinstance(value, (list, tuple, LazyMap)):
return map(self.stringify, value)
# Callables
elif safe_callable(value):
return self.stringify(value())
elif isinstance(value, unicode):
value = value.encode("utf8")
try:
return str(value)
except (AttributeError, TypeError, ValueError):
logger.warn("Could not convert {} to string".format(repr(value)))
return None | [
"def",
"stringify",
"(",
"self",
",",
"value",
")",
":",
"# SuperModel -> UID",
"if",
"ISuperModel",
".",
"providedBy",
"(",
"value",
")",
":",
"return",
"str",
"(",
"value",
")",
"# DateTime -> ISO8601 format",
"elif",
"isinstance",
"(",
"value",
",",
"(",
... | Convert value to string
This method is used to generate a simple JSON representation of the
object (without dereferencing objects etc.) | [
"Convert",
"value",
"to",
"string"
] | 1819154332b8776f187aa98a2e299701983a0119 | https://github.com/senaite/senaite.core.supermodel/blob/1819154332b8776f187aa98a2e299701983a0119/src/senaite/core/supermodel/model.py#L312-L342 | train | 44,305 |
senaite/senaite.core.supermodel | src/senaite/core/supermodel/model.py | SuperModel.to_dict | def to_dict(self, converter=None):
"""Returns a copy dict of the current object
If a converter function is given, pass each value to it.
Per default the values are converted by `self.stringify`.
"""
if converter is None:
converter = self.stringify
out = dict()
for k, v in self.iteritems():
out[k] = converter(v)
return out | python | def to_dict(self, converter=None):
"""Returns a copy dict of the current object
If a converter function is given, pass each value to it.
Per default the values are converted by `self.stringify`.
"""
if converter is None:
converter = self.stringify
out = dict()
for k, v in self.iteritems():
out[k] = converter(v)
return out | [
"def",
"to_dict",
"(",
"self",
",",
"converter",
"=",
"None",
")",
":",
"if",
"converter",
"is",
"None",
":",
"converter",
"=",
"self",
".",
"stringify",
"out",
"=",
"dict",
"(",
")",
"for",
"k",
",",
"v",
"in",
"self",
".",
"iteritems",
"(",
")",
... | Returns a copy dict of the current object
If a converter function is given, pass each value to it.
Per default the values are converted by `self.stringify`. | [
"Returns",
"a",
"copy",
"dict",
"of",
"the",
"current",
"object"
] | 1819154332b8776f187aa98a2e299701983a0119 | https://github.com/senaite/senaite.core.supermodel/blob/1819154332b8776f187aa98a2e299701983a0119/src/senaite/core/supermodel/model.py#L344-L355 | train | 44,306 |
TurboGears/gearbox | gearbox/command.py | Command.get_parser | def get_parser(self, prog_name):
"""Override to add command options."""
parser = argparse.ArgumentParser(description=self.get_description(),
prog=prog_name, add_help=False)
return parser | python | def get_parser(self, prog_name):
"""Override to add command options."""
parser = argparse.ArgumentParser(description=self.get_description(),
prog=prog_name, add_help=False)
return parser | [
"def",
"get_parser",
"(",
"self",
",",
"prog_name",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"self",
".",
"get_description",
"(",
")",
",",
"prog",
"=",
"prog_name",
",",
"add_help",
"=",
"False",
")",
"return",
... | Override to add command options. | [
"Override",
"to",
"add",
"command",
"options",
"."
] | df496ab28050ce6a4cc4c502488f5c5812f2baff | https://github.com/TurboGears/gearbox/blob/df496ab28050ce6a4cc4c502488f5c5812f2baff/gearbox/command.py#L20-L24 | train | 44,307 |
jbeluch/xbmcswift2 | xbmcswift2/cli/create.py | validate_pluginid | def validate_pluginid(value):
'''Returns True if the provided value is a valid pluglin id'''
valid = string.ascii_letters + string.digits + '.'
return all(c in valid for c in value) | python | def validate_pluginid(value):
'''Returns True if the provided value is a valid pluglin id'''
valid = string.ascii_letters + string.digits + '.'
return all(c in valid for c in value) | [
"def",
"validate_pluginid",
"(",
"value",
")",
":",
"valid",
"=",
"string",
".",
"ascii_letters",
"+",
"string",
".",
"digits",
"+",
"'.'",
"return",
"all",
"(",
"c",
"in",
"valid",
"for",
"c",
"in",
"value",
")"
] | Returns True if the provided value is a valid pluglin id | [
"Returns",
"True",
"if",
"the",
"provided",
"value",
"is",
"a",
"valid",
"pluglin",
"id"
] | 0e7a3642499554edc8265fdf1ba6c5ee567daa78 | https://github.com/jbeluch/xbmcswift2/blob/0e7a3642499554edc8265fdf1ba6c5ee567daa78/xbmcswift2/cli/create.py#L60-L63 | train | 44,308 |
jbeluch/xbmcswift2 | xbmcswift2/cli/create.py | get_valid_value | def get_valid_value(prompt, validator, default=None):
'''Displays the provided prompt and gets input from the user. This behavior
loops indefinitely until the provided validator returns True for the user
input. If a default value is provided, it will be used only if the user
hits Enter and does not provide a value.
If the validator callable has an error_message attribute, it will be
displayed for an invalid value, otherwise a generic message is used.
'''
ans = get_value(prompt, default)
while not validator(ans):
try:
print validator.error_message
except AttributeError:
print 'Invalid value.'
ans = get_value(prompt, default)
return ans | python | def get_valid_value(prompt, validator, default=None):
'''Displays the provided prompt and gets input from the user. This behavior
loops indefinitely until the provided validator returns True for the user
input. If a default value is provided, it will be used only if the user
hits Enter and does not provide a value.
If the validator callable has an error_message attribute, it will be
displayed for an invalid value, otherwise a generic message is used.
'''
ans = get_value(prompt, default)
while not validator(ans):
try:
print validator.error_message
except AttributeError:
print 'Invalid value.'
ans = get_value(prompt, default)
return ans | [
"def",
"get_valid_value",
"(",
"prompt",
",",
"validator",
",",
"default",
"=",
"None",
")",
":",
"ans",
"=",
"get_value",
"(",
"prompt",
",",
"default",
")",
"while",
"not",
"validator",
"(",
"ans",
")",
":",
"try",
":",
"print",
"validator",
".",
"er... | Displays the provided prompt and gets input from the user. This behavior
loops indefinitely until the provided validator returns True for the user
input. If a default value is provided, it will be used only if the user
hits Enter and does not provide a value.
If the validator callable has an error_message attribute, it will be
displayed for an invalid value, otherwise a generic message is used. | [
"Displays",
"the",
"provided",
"prompt",
"and",
"gets",
"input",
"from",
"the",
"user",
".",
"This",
"behavior",
"loops",
"indefinitely",
"until",
"the",
"provided",
"validator",
"returns",
"True",
"for",
"the",
"user",
"input",
".",
"If",
"a",
"default",
"v... | 0e7a3642499554edc8265fdf1ba6c5ee567daa78 | https://github.com/jbeluch/xbmcswift2/blob/0e7a3642499554edc8265fdf1ba6c5ee567daa78/xbmcswift2/cli/create.py#L72-L89 | train | 44,309 |
jbeluch/xbmcswift2 | xbmcswift2/cli/create.py | get_value | def get_value(prompt, default=None, hidden=False):
'''Displays the provided prompt and returns the input from the user. If the
user hits Enter and there is a default value provided, the default is
returned.
'''
_prompt = '%s : ' % prompt
if default:
_prompt = '%s [%s]: ' % (prompt, default)
if hidden:
ans = getpass(_prompt)
else:
ans = raw_input(_prompt)
# If user hit Enter and there is a default value
if not ans and default:
ans = default
return ans | python | def get_value(prompt, default=None, hidden=False):
'''Displays the provided prompt and returns the input from the user. If the
user hits Enter and there is a default value provided, the default is
returned.
'''
_prompt = '%s : ' % prompt
if default:
_prompt = '%s [%s]: ' % (prompt, default)
if hidden:
ans = getpass(_prompt)
else:
ans = raw_input(_prompt)
# If user hit Enter and there is a default value
if not ans and default:
ans = default
return ans | [
"def",
"get_value",
"(",
"prompt",
",",
"default",
"=",
"None",
",",
"hidden",
"=",
"False",
")",
":",
"_prompt",
"=",
"'%s : '",
"%",
"prompt",
"if",
"default",
":",
"_prompt",
"=",
"'%s [%s]: '",
"%",
"(",
"prompt",
",",
"default",
")",
"if",
"hidden... | Displays the provided prompt and returns the input from the user. If the
user hits Enter and there is a default value provided, the default is
returned. | [
"Displays",
"the",
"provided",
"prompt",
"and",
"returns",
"the",
"input",
"from",
"the",
"user",
".",
"If",
"the",
"user",
"hits",
"Enter",
"and",
"there",
"is",
"a",
"default",
"value",
"provided",
"the",
"default",
"is",
"returned",
"."
] | 0e7a3642499554edc8265fdf1ba6c5ee567daa78 | https://github.com/jbeluch/xbmcswift2/blob/0e7a3642499554edc8265fdf1ba6c5ee567daa78/xbmcswift2/cli/create.py#L92-L109 | train | 44,310 |
jbeluch/xbmcswift2 | xbmcswift2/cli/create.py | create_new_project | def create_new_project():
'''Creates a new XBMC Addon directory based on user input'''
readline.parse_and_bind('tab: complete')
print \
'''
xbmcswift2 - A micro-framework for creating XBMC plugins.
xbmc@jonathanbeluch.com
--
'''
print 'I\'m going to ask you a few questions to get this project' \
' started.'
opts = {}
# Plugin Name
opts['plugin_name'] = get_valid_value(
'What is your plugin name?',
validate_nonblank
)
# Plugin ID
opts['plugin_id'] = get_valid_value(
'Enter your plugin id.',
validate_pluginid,
'plugin.video.%s' % (opts['plugin_name'].lower().replace(' ', ''))
)
# Parent Directory
opts['parent_dir'] = get_valid_value(
'Enter parent folder (where to create project)',
validate_isfolder,
getcwd()
)
opts['plugin_dir'] = os.path.join(opts['parent_dir'], opts['plugin_id'])
assert not os.path.isdir(opts['plugin_dir']), \
'A folder named %s already exists in %s.' % (opts['plugin_id'],
opts['parent_dir'])
# Provider
opts['provider_name'] = get_valid_value(
'Enter provider name',
validate_nonblank,
)
# Create the project folder by copying over skel
copytree(SKEL, opts['plugin_dir'], ignore=ignore_patterns('*.pyc'))
# Walk through all the new files and fill in with out options
for root, dirs, files in os.walk(opts['plugin_dir']):
for filename in files:
update_file(os.path.join(root, filename), opts)
print 'Projects successfully created in %s.' % opts['plugin_dir']
print 'Done.' | python | def create_new_project():
'''Creates a new XBMC Addon directory based on user input'''
readline.parse_and_bind('tab: complete')
print \
'''
xbmcswift2 - A micro-framework for creating XBMC plugins.
xbmc@jonathanbeluch.com
--
'''
print 'I\'m going to ask you a few questions to get this project' \
' started.'
opts = {}
# Plugin Name
opts['plugin_name'] = get_valid_value(
'What is your plugin name?',
validate_nonblank
)
# Plugin ID
opts['plugin_id'] = get_valid_value(
'Enter your plugin id.',
validate_pluginid,
'plugin.video.%s' % (opts['plugin_name'].lower().replace(' ', ''))
)
# Parent Directory
opts['parent_dir'] = get_valid_value(
'Enter parent folder (where to create project)',
validate_isfolder,
getcwd()
)
opts['plugin_dir'] = os.path.join(opts['parent_dir'], opts['plugin_id'])
assert not os.path.isdir(opts['plugin_dir']), \
'A folder named %s already exists in %s.' % (opts['plugin_id'],
opts['parent_dir'])
# Provider
opts['provider_name'] = get_valid_value(
'Enter provider name',
validate_nonblank,
)
# Create the project folder by copying over skel
copytree(SKEL, opts['plugin_dir'], ignore=ignore_patterns('*.pyc'))
# Walk through all the new files and fill in with out options
for root, dirs, files in os.walk(opts['plugin_dir']):
for filename in files:
update_file(os.path.join(root, filename), opts)
print 'Projects successfully created in %s.' % opts['plugin_dir']
print 'Done.' | [
"def",
"create_new_project",
"(",
")",
":",
"readline",
".",
"parse_and_bind",
"(",
"'tab: complete'",
")",
"print",
"'''\n xbmcswift2 - A micro-framework for creating XBMC plugins.\n xbmc@jonathanbeluch.com\n --\n'''",
"print",
"'I\\'m going to ask you a few questions to get th... | Creates a new XBMC Addon directory based on user input | [
"Creates",
"a",
"new",
"XBMC",
"Addon",
"directory",
"based",
"on",
"user",
"input"
] | 0e7a3642499554edc8265fdf1ba6c5ee567daa78 | https://github.com/jbeluch/xbmcswift2/blob/0e7a3642499554edc8265fdf1ba6c5ee567daa78/xbmcswift2/cli/create.py#L135-L189 | train | 44,311 |
mozilla/amo-validator | validator/chromemanifest.py | ChromeManifest.get_objects | def get_objects(self, subject=None, predicate=None):
"""Returns a generator of objects that correspond to the
specified subjects and predicates."""
for triple in self.triples:
# Filter out non-matches
if ((subject and triple['subject'] != subject) or
(predicate and triple['predicate'] != predicate)):
continue
yield triple['object'] | python | def get_objects(self, subject=None, predicate=None):
"""Returns a generator of objects that correspond to the
specified subjects and predicates."""
for triple in self.triples:
# Filter out non-matches
if ((subject and triple['subject'] != subject) or
(predicate and triple['predicate'] != predicate)):
continue
yield triple['object'] | [
"def",
"get_objects",
"(",
"self",
",",
"subject",
"=",
"None",
",",
"predicate",
"=",
"None",
")",
":",
"for",
"triple",
"in",
"self",
".",
"triples",
":",
"# Filter out non-matches",
"if",
"(",
"(",
"subject",
"and",
"triple",
"[",
"'subject'",
"]",
"!... | Returns a generator of objects that correspond to the
specified subjects and predicates. | [
"Returns",
"a",
"generator",
"of",
"objects",
"that",
"correspond",
"to",
"the",
"specified",
"subjects",
"and",
"predicates",
"."
] | 0251bfbd7d93106e01ecdb6de5fcd1dc1a180664 | https://github.com/mozilla/amo-validator/blob/0251bfbd7d93106e01ecdb6de5fcd1dc1a180664/validator/chromemanifest.py#L61-L72 | train | 44,312 |
mozilla/amo-validator | validator/chromemanifest.py | ChromeManifest.get_triples | def get_triples(self, subject=None, predicate=None, object_=None):
"""Returns triples that correspond to the specified subject,
predicates, and objects."""
for triple in self.triples:
# Filter out non-matches
if subject is not None and triple['subject'] != subject:
continue
if predicate is not None and triple['predicate'] != predicate:
continue
if object_ is not None and triple['object'] != object_:
continue
yield triple | python | def get_triples(self, subject=None, predicate=None, object_=None):
"""Returns triples that correspond to the specified subject,
predicates, and objects."""
for triple in self.triples:
# Filter out non-matches
if subject is not None and triple['subject'] != subject:
continue
if predicate is not None and triple['predicate'] != predicate:
continue
if object_ is not None and triple['object'] != object_:
continue
yield triple | [
"def",
"get_triples",
"(",
"self",
",",
"subject",
"=",
"None",
",",
"predicate",
"=",
"None",
",",
"object_",
"=",
"None",
")",
":",
"for",
"triple",
"in",
"self",
".",
"triples",
":",
"# Filter out non-matches",
"if",
"subject",
"is",
"not",
"None",
"a... | Returns triples that correspond to the specified subject,
predicates, and objects. | [
"Returns",
"triples",
"that",
"correspond",
"to",
"the",
"specified",
"subject",
"predicates",
"and",
"objects",
"."
] | 0251bfbd7d93106e01ecdb6de5fcd1dc1a180664 | https://github.com/mozilla/amo-validator/blob/0251bfbd7d93106e01ecdb6de5fcd1dc1a180664/validator/chromemanifest.py#L74-L88 | train | 44,313 |
mozilla/amo-validator | validator/chromemanifest.py | ChromeManifest.get_applicable_overlays | def get_applicable_overlays(self, error_bundle):
"""
Given an error bundle, a list of overlays that are present in the
current package or subpackage are returned.
"""
content_paths = self.get_triples(subject='content')
if not content_paths:
return set()
# Create some variables that will store where the applicable content
# instruction path references and where it links to.
chrome_path = ''
content_root_path = '/'
# Look through each of the listed packages and paths.
for path in content_paths:
chrome_name = path['predicate']
if not path['object']:
continue
path_location = path['object'].strip().split()[0]
# Handle jarred paths differently.
if path_location.startswith('jar:'):
if not error_bundle.is_nested_package:
continue
# Parse out the JAR and it's location within the chrome.
split_jar_url = path_location[4:].split('!', 2)
# Ignore invalid/unsupported JAR URLs.
if len(split_jar_url) != 2:
continue
# Unpack the JAR URL.
jar_path, package_path = split_jar_url
# Ignore the instruction if the JAR it points to doesn't match
# up with the current subpackage tree.
if jar_path != error_bundle.package_stack[0]:
continue
chrome_path = self._url_chunk_join(chrome_name, package_path)
# content_root_path stays at the default: /
break
else:
# If we're in a subpackage, a content instruction referring to
# the root of the package obviously doesn't apply.
if error_bundle.is_nested_package:
continue
chrome_path = self._url_chunk_join(chrome_name, 'content')
content_root_path = '/%s/' % path_location.strip('/')
break
if not chrome_path:
return set()
applicable_overlays = set()
chrome_path = 'chrome://%s' % self._url_chunk_join(chrome_path + '/')
for overlay in self.get_triples(subject='overlay'):
if not overlay['object']:
error_bundle.error(
err_id=('chromemanifest', 'get_applicable_overalys',
'object'),
error='Overlay instruction missing a property.',
description='When overlays are registered in a chrome '
'manifest file, they require a namespace and '
'a chrome URL at minimum.',
filename=overlay['filename'],
line=overlay['line'],
context=self.context) #TODO(basta): Update this!
continue
overlay_url = overlay['object'].split()[0]
if overlay_url.startswith(chrome_path):
overlay_relative_path = overlay_url[len(chrome_path):]
applicable_overlays.add('/%s' %
self._url_chunk_join(content_root_path,
overlay_relative_path))
return applicable_overlays | python | def get_applicable_overlays(self, error_bundle):
"""
Given an error bundle, a list of overlays that are present in the
current package or subpackage are returned.
"""
content_paths = self.get_triples(subject='content')
if not content_paths:
return set()
# Create some variables that will store where the applicable content
# instruction path references and where it links to.
chrome_path = ''
content_root_path = '/'
# Look through each of the listed packages and paths.
for path in content_paths:
chrome_name = path['predicate']
if not path['object']:
continue
path_location = path['object'].strip().split()[0]
# Handle jarred paths differently.
if path_location.startswith('jar:'):
if not error_bundle.is_nested_package:
continue
# Parse out the JAR and it's location within the chrome.
split_jar_url = path_location[4:].split('!', 2)
# Ignore invalid/unsupported JAR URLs.
if len(split_jar_url) != 2:
continue
# Unpack the JAR URL.
jar_path, package_path = split_jar_url
# Ignore the instruction if the JAR it points to doesn't match
# up with the current subpackage tree.
if jar_path != error_bundle.package_stack[0]:
continue
chrome_path = self._url_chunk_join(chrome_name, package_path)
# content_root_path stays at the default: /
break
else:
# If we're in a subpackage, a content instruction referring to
# the root of the package obviously doesn't apply.
if error_bundle.is_nested_package:
continue
chrome_path = self._url_chunk_join(chrome_name, 'content')
content_root_path = '/%s/' % path_location.strip('/')
break
if not chrome_path:
return set()
applicable_overlays = set()
chrome_path = 'chrome://%s' % self._url_chunk_join(chrome_path + '/')
for overlay in self.get_triples(subject='overlay'):
if not overlay['object']:
error_bundle.error(
err_id=('chromemanifest', 'get_applicable_overalys',
'object'),
error='Overlay instruction missing a property.',
description='When overlays are registered in a chrome '
'manifest file, they require a namespace and '
'a chrome URL at minimum.',
filename=overlay['filename'],
line=overlay['line'],
context=self.context) #TODO(basta): Update this!
continue
overlay_url = overlay['object'].split()[0]
if overlay_url.startswith(chrome_path):
overlay_relative_path = overlay_url[len(chrome_path):]
applicable_overlays.add('/%s' %
self._url_chunk_join(content_root_path,
overlay_relative_path))
return applicable_overlays | [
"def",
"get_applicable_overlays",
"(",
"self",
",",
"error_bundle",
")",
":",
"content_paths",
"=",
"self",
".",
"get_triples",
"(",
"subject",
"=",
"'content'",
")",
"if",
"not",
"content_paths",
":",
"return",
"set",
"(",
")",
"# Create some variables that will ... | Given an error bundle, a list of overlays that are present in the
current package or subpackage are returned. | [
"Given",
"an",
"error",
"bundle",
"a",
"list",
"of",
"overlays",
"that",
"are",
"present",
"in",
"the",
"current",
"package",
"or",
"subpackage",
"are",
"returned",
"."
] | 0251bfbd7d93106e01ecdb6de5fcd1dc1a180664 | https://github.com/mozilla/amo-validator/blob/0251bfbd7d93106e01ecdb6de5fcd1dc1a180664/validator/chromemanifest.py#L90-L170 | train | 44,314 |
mozilla/amo-validator | validator/chromemanifest.py | ChromeManifest.reverse_lookup | def reverse_lookup(self, state, path):
"""
Returns a chrome URL for a given path, given the current package depth
in an error bundle.
State may either be an error bundle or the actual package stack.
"""
# Make sure the path starts with a forward slash.
if not path.startswith('/'):
path = '/%s' % path
# If the state is an error bundle, extract the package stack.
if not isinstance(state, list):
state = state.package_stack
content_paths = self.get_triples(subject='content')
for content_path in content_paths:
chrome_name = content_path['predicate']
if not content_path['object']:
continue
path_location = content_path['object'].split()[0]
if path_location.startswith('jar:'):
if not state:
continue
# Parse out the JAR and it's location within the chrome.
split_jar_url = path_location[4:].split('!', 2)
# Ignore invalid/unsupported JAR URLs.
if len(split_jar_url) != 2:
continue
# Unpack the JAR URL.
jar_path, package_path = split_jar_url
if jar_path != state[0]:
continue
return 'chrome://%s' % self._url_chunk_join(chrome_name,
package_path,
path)
else:
if state:
continue
path_location = '/%s/' % path_location.strip('/')
rel_path = os.path.relpath(path, path_location)
if rel_path.startswith('../') or rel_path == '..':
continue
return 'chrome://%s' % self._url_chunk_join(chrome_name,
rel_path)
return None | python | def reverse_lookup(self, state, path):
"""
Returns a chrome URL for a given path, given the current package depth
in an error bundle.
State may either be an error bundle or the actual package stack.
"""
# Make sure the path starts with a forward slash.
if not path.startswith('/'):
path = '/%s' % path
# If the state is an error bundle, extract the package stack.
if not isinstance(state, list):
state = state.package_stack
content_paths = self.get_triples(subject='content')
for content_path in content_paths:
chrome_name = content_path['predicate']
if not content_path['object']:
continue
path_location = content_path['object'].split()[0]
if path_location.startswith('jar:'):
if not state:
continue
# Parse out the JAR and it's location within the chrome.
split_jar_url = path_location[4:].split('!', 2)
# Ignore invalid/unsupported JAR URLs.
if len(split_jar_url) != 2:
continue
# Unpack the JAR URL.
jar_path, package_path = split_jar_url
if jar_path != state[0]:
continue
return 'chrome://%s' % self._url_chunk_join(chrome_name,
package_path,
path)
else:
if state:
continue
path_location = '/%s/' % path_location.strip('/')
rel_path = os.path.relpath(path, path_location)
if rel_path.startswith('../') or rel_path == '..':
continue
return 'chrome://%s' % self._url_chunk_join(chrome_name,
rel_path)
return None | [
"def",
"reverse_lookup",
"(",
"self",
",",
"state",
",",
"path",
")",
":",
"# Make sure the path starts with a forward slash.",
"if",
"not",
"path",
".",
"startswith",
"(",
"'/'",
")",
":",
"path",
"=",
"'/%s'",
"%",
"path",
"# If the state is an error bundle, extra... | Returns a chrome URL for a given path, given the current package depth
in an error bundle.
State may either be an error bundle or the actual package stack. | [
"Returns",
"a",
"chrome",
"URL",
"for",
"a",
"given",
"path",
"given",
"the",
"current",
"package",
"depth",
"in",
"an",
"error",
"bundle",
"."
] | 0251bfbd7d93106e01ecdb6de5fcd1dc1a180664 | https://github.com/mozilla/amo-validator/blob/0251bfbd7d93106e01ecdb6de5fcd1dc1a180664/validator/chromemanifest.py#L172-L227 | train | 44,315 |
mozilla/amo-validator | validator/chromemanifest.py | ChromeManifest._url_chunk_join | def _url_chunk_join(self, *args):
"""Join the arguments together to form a predictable URL chunk."""
# Strip slashes from either side of each path piece.
pathlets = map(lambda s: s.strip('/'), args)
# Remove empty pieces.
pathlets = filter(None, pathlets)
url = '/'.join(pathlets)
# If this is a directory, add a trailing slash.
if args[-1].endswith('/'):
url = '%s/' % url
return url | python | def _url_chunk_join(self, *args):
"""Join the arguments together to form a predictable URL chunk."""
# Strip slashes from either side of each path piece.
pathlets = map(lambda s: s.strip('/'), args)
# Remove empty pieces.
pathlets = filter(None, pathlets)
url = '/'.join(pathlets)
# If this is a directory, add a trailing slash.
if args[-1].endswith('/'):
url = '%s/' % url
return url | [
"def",
"_url_chunk_join",
"(",
"self",
",",
"*",
"args",
")",
":",
"# Strip slashes from either side of each path piece.",
"pathlets",
"=",
"map",
"(",
"lambda",
"s",
":",
"s",
".",
"strip",
"(",
"'/'",
")",
",",
"args",
")",
"# Remove empty pieces.",
"pathlets"... | Join the arguments together to form a predictable URL chunk. | [
"Join",
"the",
"arguments",
"together",
"to",
"form",
"a",
"predictable",
"URL",
"chunk",
"."
] | 0251bfbd7d93106e01ecdb6de5fcd1dc1a180664 | https://github.com/mozilla/amo-validator/blob/0251bfbd7d93106e01ecdb6de5fcd1dc1a180664/validator/chromemanifest.py#L229-L239 | train | 44,316 |
mozilla/amo-validator | validator/rdf.py | RDFParser.uri | def uri(self, element, namespace=None):
'Returns a URIRef object for use with the RDF document.'
if namespace is None:
namespace = self.namespace
return URIRef('%s#%s' % (namespace, element)) | python | def uri(self, element, namespace=None):
'Returns a URIRef object for use with the RDF document.'
if namespace is None:
namespace = self.namespace
return URIRef('%s#%s' % (namespace, element)) | [
"def",
"uri",
"(",
"self",
",",
"element",
",",
"namespace",
"=",
"None",
")",
":",
"if",
"namespace",
"is",
"None",
":",
"namespace",
"=",
"self",
".",
"namespace",
"return",
"URIRef",
"(",
"'%s#%s'",
"%",
"(",
"namespace",
",",
"element",
")",
")"
] | Returns a URIRef object for use with the RDF document. | [
"Returns",
"a",
"URIRef",
"object",
"for",
"use",
"with",
"the",
"RDF",
"document",
"."
] | 0251bfbd7d93106e01ecdb6de5fcd1dc1a180664 | https://github.com/mozilla/amo-validator/blob/0251bfbd7d93106e01ecdb6de5fcd1dc1a180664/validator/rdf.py#L123-L129 | train | 44,317 |
mozilla/amo-validator | validator/rdf.py | RDFParser.get_root_subject | def get_root_subject(self):
'Returns the BNode which describes the topmost subject of the graph.'
manifest = URIRef(self.manifest)
if list(self.rdf.triples((manifest, None, None))):
return manifest
else:
return self.rdf.subjects(None, self.manifest).next() | python | def get_root_subject(self):
'Returns the BNode which describes the topmost subject of the graph.'
manifest = URIRef(self.manifest)
if list(self.rdf.triples((manifest, None, None))):
return manifest
else:
return self.rdf.subjects(None, self.manifest).next() | [
"def",
"get_root_subject",
"(",
"self",
")",
":",
"manifest",
"=",
"URIRef",
"(",
"self",
".",
"manifest",
")",
"if",
"list",
"(",
"self",
".",
"rdf",
".",
"triples",
"(",
"(",
"manifest",
",",
"None",
",",
"None",
")",
")",
")",
":",
"return",
"ma... | Returns the BNode which describes the topmost subject of the graph. | [
"Returns",
"the",
"BNode",
"which",
"describes",
"the",
"topmost",
"subject",
"of",
"the",
"graph",
"."
] | 0251bfbd7d93106e01ecdb6de5fcd1dc1a180664 | https://github.com/mozilla/amo-validator/blob/0251bfbd7d93106e01ecdb6de5fcd1dc1a180664/validator/rdf.py#L131-L139 | train | 44,318 |
mozilla/amo-validator | validator/rdf.py | RDFParser.get_objects | def get_objects(self, subject=None, predicate=None):
"""Same as get_object, except returns a list of objects which
satisfy the query rather than a single result."""
# Get the result of the search
results = self.rdf.objects(subject, predicate)
return list(results) | python | def get_objects(self, subject=None, predicate=None):
"""Same as get_object, except returns a list of objects which
satisfy the query rather than a single result."""
# Get the result of the search
results = self.rdf.objects(subject, predicate)
return list(results) | [
"def",
"get_objects",
"(",
"self",
",",
"subject",
"=",
"None",
",",
"predicate",
"=",
"None",
")",
":",
"# Get the result of the search",
"results",
"=",
"self",
".",
"rdf",
".",
"objects",
"(",
"subject",
",",
"predicate",
")",
"return",
"list",
"(",
"re... | Same as get_object, except returns a list of objects which
satisfy the query rather than a single result. | [
"Same",
"as",
"get_object",
"except",
"returns",
"a",
"list",
"of",
"objects",
"which",
"satisfy",
"the",
"query",
"rather",
"than",
"a",
"single",
"result",
"."
] | 0251bfbd7d93106e01ecdb6de5fcd1dc1a180664 | https://github.com/mozilla/amo-validator/blob/0251bfbd7d93106e01ecdb6de5fcd1dc1a180664/validator/rdf.py#L157-L163 | train | 44,319 |
jbeluch/xbmcswift2 | xbmcswift2/listitem.py | ListItem.add_context_menu_items | def add_context_menu_items(self, items, replace_items=False):
'''Adds context menu items. If replace_items is True all
previous context menu items will be removed.
'''
for label, action in items:
assert isinstance(label, basestring)
assert isinstance(action, basestring)
if replace_items:
self._context_menu_items = []
self._context_menu_items.extend(items)
self._listitem.addContextMenuItems(items, replace_items) | python | def add_context_menu_items(self, items, replace_items=False):
'''Adds context menu items. If replace_items is True all
previous context menu items will be removed.
'''
for label, action in items:
assert isinstance(label, basestring)
assert isinstance(action, basestring)
if replace_items:
self._context_menu_items = []
self._context_menu_items.extend(items)
self._listitem.addContextMenuItems(items, replace_items) | [
"def",
"add_context_menu_items",
"(",
"self",
",",
"items",
",",
"replace_items",
"=",
"False",
")",
":",
"for",
"label",
",",
"action",
"in",
"items",
":",
"assert",
"isinstance",
"(",
"label",
",",
"basestring",
")",
"assert",
"isinstance",
"(",
"action",
... | Adds context menu items. If replace_items is True all
previous context menu items will be removed. | [
"Adds",
"context",
"menu",
"items",
".",
"If",
"replace_items",
"is",
"True",
"all",
"previous",
"context",
"menu",
"items",
"will",
"be",
"removed",
"."
] | 0e7a3642499554edc8265fdf1ba6c5ee567daa78 | https://github.com/jbeluch/xbmcswift2/blob/0e7a3642499554edc8265fdf1ba6c5ee567daa78/xbmcswift2/listitem.py#L55-L65 | train | 44,320 |
jbeluch/xbmcswift2 | xbmcswift2/listitem.py | ListItem.set_icon | def set_icon(self, icon):
'''Sets the listitem's icon image'''
self._icon = icon
return self._listitem.setIconImage(icon) | python | def set_icon(self, icon):
'''Sets the listitem's icon image'''
self._icon = icon
return self._listitem.setIconImage(icon) | [
"def",
"set_icon",
"(",
"self",
",",
"icon",
")",
":",
"self",
".",
"_icon",
"=",
"icon",
"return",
"self",
".",
"_listitem",
".",
"setIconImage",
"(",
"icon",
")"
] | Sets the listitem's icon image | [
"Sets",
"the",
"listitem",
"s",
"icon",
"image"
] | 0e7a3642499554edc8265fdf1ba6c5ee567daa78 | https://github.com/jbeluch/xbmcswift2/blob/0e7a3642499554edc8265fdf1ba6c5ee567daa78/xbmcswift2/listitem.py#L119-L122 | train | 44,321 |
jbeluch/xbmcswift2 | xbmcswift2/listitem.py | ListItem.set_thumbnail | def set_thumbnail(self, thumbnail):
'''Sets the listitem's thumbnail image'''
self._thumbnail = thumbnail
return self._listitem.setThumbnailImage(thumbnail) | python | def set_thumbnail(self, thumbnail):
'''Sets the listitem's thumbnail image'''
self._thumbnail = thumbnail
return self._listitem.setThumbnailImage(thumbnail) | [
"def",
"set_thumbnail",
"(",
"self",
",",
"thumbnail",
")",
":",
"self",
".",
"_thumbnail",
"=",
"thumbnail",
"return",
"self",
".",
"_listitem",
".",
"setThumbnailImage",
"(",
"thumbnail",
")"
] | Sets the listitem's thumbnail image | [
"Sets",
"the",
"listitem",
"s",
"thumbnail",
"image"
] | 0e7a3642499554edc8265fdf1ba6c5ee567daa78 | https://github.com/jbeluch/xbmcswift2/blob/0e7a3642499554edc8265fdf1ba6c5ee567daa78/xbmcswift2/listitem.py#L130-L133 | train | 44,322 |
jbeluch/xbmcswift2 | xbmcswift2/listitem.py | ListItem.set_path | def set_path(self, path):
'''Sets the listitem's path'''
self._path = path
return self._listitem.setPath(path) | python | def set_path(self, path):
'''Sets the listitem's path'''
self._path = path
return self._listitem.setPath(path) | [
"def",
"set_path",
"(",
"self",
",",
"path",
")",
":",
"self",
".",
"_path",
"=",
"path",
"return",
"self",
".",
"_listitem",
".",
"setPath",
"(",
"path",
")"
] | Sets the listitem's path | [
"Sets",
"the",
"listitem",
"s",
"path"
] | 0e7a3642499554edc8265fdf1ba6c5ee567daa78 | https://github.com/jbeluch/xbmcswift2/blob/0e7a3642499554edc8265fdf1ba6c5ee567daa78/xbmcswift2/listitem.py#L141-L144 | train | 44,323 |
jbeluch/xbmcswift2 | xbmcswift2/listitem.py | ListItem.set_is_playable | def set_is_playable(self, is_playable):
'''Sets the listitem's playable flag'''
value = 'false'
if is_playable:
value = 'true'
self.set_property('isPlayable', value)
self.is_folder = not is_playable | python | def set_is_playable(self, is_playable):
'''Sets the listitem's playable flag'''
value = 'false'
if is_playable:
value = 'true'
self.set_property('isPlayable', value)
self.is_folder = not is_playable | [
"def",
"set_is_playable",
"(",
"self",
",",
"is_playable",
")",
":",
"value",
"=",
"'false'",
"if",
"is_playable",
":",
"value",
"=",
"'true'",
"self",
".",
"set_property",
"(",
"'isPlayable'",
",",
"value",
")",
"self",
".",
"is_folder",
"=",
"not",
"is_p... | Sets the listitem's playable flag | [
"Sets",
"the",
"listitem",
"s",
"playable",
"flag"
] | 0e7a3642499554edc8265fdf1ba6c5ee567daa78 | https://github.com/jbeluch/xbmcswift2/blob/0e7a3642499554edc8265fdf1ba6c5ee567daa78/xbmcswift2/listitem.py#L154-L160 | train | 44,324 |
jbeluch/xbmcswift2 | xbmcswift2/xbmcmixin.py | XBMCMixin.get_storage | def get_storage(self, name='main', file_format='pickle', TTL=None):
'''Returns a storage for the given name. The returned storage is a
fully functioning python dictionary and is designed to be used that
way. It is usually not necessary for the caller to load or save the
storage manually. If the storage does not already exist, it will be
created.
.. seealso:: :class:`xbmcswift2.TimedStorage` for more details.
:param name: The name of the storage to retrieve.
:param file_format: Choices are 'pickle', 'csv', and 'json'. Pickle is
recommended as it supports python objects.
.. note:: If a storage already exists for the given
name, the file_format parameter is
ignored. The format will be determined by
the existing storage file.
:param TTL: The time to live for storage items specified in minutes or None
for no expiration. Since storage items aren't expired until a
storage is loaded form disk, it is possible to call
get_storage() with a different TTL than when the storage was
created. The currently specified TTL is always honored.
'''
if not hasattr(self, '_unsynced_storages'):
self._unsynced_storages = {}
filename = os.path.join(self.storage_path, name)
try:
storage = self._unsynced_storages[filename]
log.debug('Loaded storage "%s" from memory', name)
except KeyError:
if TTL:
TTL = timedelta(minutes=TTL)
try:
storage = TimedStorage(filename, file_format, TTL)
except ValueError:
# Thrown when the storage file is corrupted and can't be read.
# Prompt user to delete storage.
choices = ['Clear storage', 'Cancel']
ret = xbmcgui.Dialog().select('A storage file is corrupted. It'
' is recommended to clear it.',
choices)
if ret == 0:
os.remove(filename)
storage = TimedStorage(filename, file_format, TTL)
else:
raise Exception('Corrupted storage file at %s' % filename)
self._unsynced_storages[filename] = storage
log.debug('Loaded storage "%s" from disk', name)
return storage | python | def get_storage(self, name='main', file_format='pickle', TTL=None):
'''Returns a storage for the given name. The returned storage is a
fully functioning python dictionary and is designed to be used that
way. It is usually not necessary for the caller to load or save the
storage manually. If the storage does not already exist, it will be
created.
.. seealso:: :class:`xbmcswift2.TimedStorage` for more details.
:param name: The name of the storage to retrieve.
:param file_format: Choices are 'pickle', 'csv', and 'json'. Pickle is
recommended as it supports python objects.
.. note:: If a storage already exists for the given
name, the file_format parameter is
ignored. The format will be determined by
the existing storage file.
:param TTL: The time to live for storage items specified in minutes or None
for no expiration. Since storage items aren't expired until a
storage is loaded form disk, it is possible to call
get_storage() with a different TTL than when the storage was
created. The currently specified TTL is always honored.
'''
if not hasattr(self, '_unsynced_storages'):
self._unsynced_storages = {}
filename = os.path.join(self.storage_path, name)
try:
storage = self._unsynced_storages[filename]
log.debug('Loaded storage "%s" from memory', name)
except KeyError:
if TTL:
TTL = timedelta(minutes=TTL)
try:
storage = TimedStorage(filename, file_format, TTL)
except ValueError:
# Thrown when the storage file is corrupted and can't be read.
# Prompt user to delete storage.
choices = ['Clear storage', 'Cancel']
ret = xbmcgui.Dialog().select('A storage file is corrupted. It'
' is recommended to clear it.',
choices)
if ret == 0:
os.remove(filename)
storage = TimedStorage(filename, file_format, TTL)
else:
raise Exception('Corrupted storage file at %s' % filename)
self._unsynced_storages[filename] = storage
log.debug('Loaded storage "%s" from disk', name)
return storage | [
"def",
"get_storage",
"(",
"self",
",",
"name",
"=",
"'main'",
",",
"file_format",
"=",
"'pickle'",
",",
"TTL",
"=",
"None",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'_unsynced_storages'",
")",
":",
"self",
".",
"_unsynced_storages",
"=",
"{"... | Returns a storage for the given name. The returned storage is a
fully functioning python dictionary and is designed to be used that
way. It is usually not necessary for the caller to load or save the
storage manually. If the storage does not already exist, it will be
created.
.. seealso:: :class:`xbmcswift2.TimedStorage` for more details.
:param name: The name of the storage to retrieve.
:param file_format: Choices are 'pickle', 'csv', and 'json'. Pickle is
recommended as it supports python objects.
.. note:: If a storage already exists for the given
name, the file_format parameter is
ignored. The format will be determined by
the existing storage file.
:param TTL: The time to live for storage items specified in minutes or None
for no expiration. Since storage items aren't expired until a
storage is loaded form disk, it is possible to call
get_storage() with a different TTL than when the storage was
created. The currently specified TTL is always honored. | [
"Returns",
"a",
"storage",
"for",
"the",
"given",
"name",
".",
"The",
"returned",
"storage",
"is",
"a",
"fully",
"functioning",
"python",
"dictionary",
"and",
"is",
"designed",
"to",
"be",
"used",
"that",
"way",
".",
"It",
"is",
"usually",
"not",
"necessar... | 0e7a3642499554edc8265fdf1ba6c5ee567daa78 | https://github.com/jbeluch/xbmcswift2/blob/0e7a3642499554edc8265fdf1ba6c5ee567daa78/xbmcswift2/xbmcmixin.py#L104-L155 | train | 44,325 |
jbeluch/xbmcswift2 | xbmcswift2/xbmcmixin.py | XBMCMixin.get_string | def get_string(self, stringid):
'''Returns the localized string from strings.xml for the given
stringid.
'''
stringid = int(stringid)
if not hasattr(self, '_strings'):
self._strings = {}
if not stringid in self._strings:
self._strings[stringid] = self.addon.getLocalizedString(stringid)
return self._strings[stringid] | python | def get_string(self, stringid):
'''Returns the localized string from strings.xml for the given
stringid.
'''
stringid = int(stringid)
if not hasattr(self, '_strings'):
self._strings = {}
if not stringid in self._strings:
self._strings[stringid] = self.addon.getLocalizedString(stringid)
return self._strings[stringid] | [
"def",
"get_string",
"(",
"self",
",",
"stringid",
")",
":",
"stringid",
"=",
"int",
"(",
"stringid",
")",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'_strings'",
")",
":",
"self",
".",
"_strings",
"=",
"{",
"}",
"if",
"not",
"stringid",
"in",
"self"... | Returns the localized string from strings.xml for the given
stringid. | [
"Returns",
"the",
"localized",
"string",
"from",
"strings",
".",
"xml",
"for",
"the",
"given",
"stringid",
"."
] | 0e7a3642499554edc8265fdf1ba6c5ee567daa78 | https://github.com/jbeluch/xbmcswift2/blob/0e7a3642499554edc8265fdf1ba6c5ee567daa78/xbmcswift2/xbmcmixin.py#L160-L169 | train | 44,326 |
jbeluch/xbmcswift2 | xbmcswift2/xbmcmixin.py | XBMCMixin.get_view_mode_id | def get_view_mode_id(self, view_mode):
'''Attempts to return a view_mode_id for a given view_mode
taking into account the current skin. If not view_mode_id can
be found, None is returned. 'thumbnail' is currently the only
suppported view_mode.
'''
view_mode_ids = VIEW_MODES.get(view_mode.lower())
if view_mode_ids:
return view_mode_ids.get(xbmc.getSkinDir())
return None | python | def get_view_mode_id(self, view_mode):
'''Attempts to return a view_mode_id for a given view_mode
taking into account the current skin. If not view_mode_id can
be found, None is returned. 'thumbnail' is currently the only
suppported view_mode.
'''
view_mode_ids = VIEW_MODES.get(view_mode.lower())
if view_mode_ids:
return view_mode_ids.get(xbmc.getSkinDir())
return None | [
"def",
"get_view_mode_id",
"(",
"self",
",",
"view_mode",
")",
":",
"view_mode_ids",
"=",
"VIEW_MODES",
".",
"get",
"(",
"view_mode",
".",
"lower",
"(",
")",
")",
"if",
"view_mode_ids",
":",
"return",
"view_mode_ids",
".",
"get",
"(",
"xbmc",
".",
"getSkin... | Attempts to return a view_mode_id for a given view_mode
taking into account the current skin. If not view_mode_id can
be found, None is returned. 'thumbnail' is currently the only
suppported view_mode. | [
"Attempts",
"to",
"return",
"a",
"view_mode_id",
"for",
"a",
"given",
"view_mode",
"taking",
"into",
"account",
"the",
"current",
"skin",
".",
"If",
"not",
"view_mode_id",
"can",
"be",
"found",
"None",
"is",
"returned",
".",
"thumbnail",
"is",
"currently",
"... | 0e7a3642499554edc8265fdf1ba6c5ee567daa78 | https://github.com/jbeluch/xbmcswift2/blob/0e7a3642499554edc8265fdf1ba6c5ee567daa78/xbmcswift2/xbmcmixin.py#L253-L262 | train | 44,327 |
jbeluch/xbmcswift2 | xbmcswift2/xbmcmixin.py | XBMCMixin.keyboard | def keyboard(self, default=None, heading=None, hidden=False):
'''Displays the keyboard input window to the user. If the user does not
cancel the modal, the value entered by the user will be returned.
:param default: The placeholder text used to prepopulate the input field.
:param heading: The heading for the window. Defaults to the current
addon's name. If you require a blank heading, pass an
empty string.
:param hidden: Whether or not the input field should be masked with
stars, e.g. a password field.
'''
if heading is None:
heading = self.addon.getAddonInfo('name')
if default is None:
default = ''
keyboard = xbmc.Keyboard(default, heading, hidden)
keyboard.doModal()
if keyboard.isConfirmed():
return keyboard.getText() | python | def keyboard(self, default=None, heading=None, hidden=False):
'''Displays the keyboard input window to the user. If the user does not
cancel the modal, the value entered by the user will be returned.
:param default: The placeholder text used to prepopulate the input field.
:param heading: The heading for the window. Defaults to the current
addon's name. If you require a blank heading, pass an
empty string.
:param hidden: Whether or not the input field should be masked with
stars, e.g. a password field.
'''
if heading is None:
heading = self.addon.getAddonInfo('name')
if default is None:
default = ''
keyboard = xbmc.Keyboard(default, heading, hidden)
keyboard.doModal()
if keyboard.isConfirmed():
return keyboard.getText() | [
"def",
"keyboard",
"(",
"self",
",",
"default",
"=",
"None",
",",
"heading",
"=",
"None",
",",
"hidden",
"=",
"False",
")",
":",
"if",
"heading",
"is",
"None",
":",
"heading",
"=",
"self",
".",
"addon",
".",
"getAddonInfo",
"(",
"'name'",
")",
"if",
... | Displays the keyboard input window to the user. If the user does not
cancel the modal, the value entered by the user will be returned.
:param default: The placeholder text used to prepopulate the input field.
:param heading: The heading for the window. Defaults to the current
addon's name. If you require a blank heading, pass an
empty string.
:param hidden: Whether or not the input field should be masked with
stars, e.g. a password field. | [
"Displays",
"the",
"keyboard",
"input",
"window",
"to",
"the",
"user",
".",
"If",
"the",
"user",
"does",
"not",
"cancel",
"the",
"modal",
"the",
"value",
"entered",
"by",
"the",
"user",
"will",
"be",
"returned",
"."
] | 0e7a3642499554edc8265fdf1ba6c5ee567daa78 | https://github.com/jbeluch/xbmcswift2/blob/0e7a3642499554edc8265fdf1ba6c5ee567daa78/xbmcswift2/xbmcmixin.py#L269-L287 | train | 44,328 |
jbeluch/xbmcswift2 | xbmcswift2/xbmcmixin.py | XBMCMixin.notify | def notify(self, msg='', title=None, delay=5000, image=''):
'''Displays a temporary notification message to the user. If
title is not provided, the plugin name will be used. To have a
blank title, pass '' for the title argument. The delay argument
is in milliseconds.
'''
if not msg:
log.warning('Empty message for notification dialog')
if title is None:
title = self.addon.getAddonInfo('name')
xbmc.executebuiltin('XBMC.Notification("%s", "%s", "%s", "%s")' %
(msg, title, delay, image)) | python | def notify(self, msg='', title=None, delay=5000, image=''):
'''Displays a temporary notification message to the user. If
title is not provided, the plugin name will be used. To have a
blank title, pass '' for the title argument. The delay argument
is in milliseconds.
'''
if not msg:
log.warning('Empty message for notification dialog')
if title is None:
title = self.addon.getAddonInfo('name')
xbmc.executebuiltin('XBMC.Notification("%s", "%s", "%s", "%s")' %
(msg, title, delay, image)) | [
"def",
"notify",
"(",
"self",
",",
"msg",
"=",
"''",
",",
"title",
"=",
"None",
",",
"delay",
"=",
"5000",
",",
"image",
"=",
"''",
")",
":",
"if",
"not",
"msg",
":",
"log",
".",
"warning",
"(",
"'Empty message for notification dialog'",
")",
"if",
"... | Displays a temporary notification message to the user. If
title is not provided, the plugin name will be used. To have a
blank title, pass '' for the title argument. The delay argument
is in milliseconds. | [
"Displays",
"a",
"temporary",
"notification",
"message",
"to",
"the",
"user",
".",
"If",
"title",
"is",
"not",
"provided",
"the",
"plugin",
"name",
"will",
"be",
"used",
".",
"To",
"have",
"a",
"blank",
"title",
"pass",
"for",
"the",
"title",
"argument",
... | 0e7a3642499554edc8265fdf1ba6c5ee567daa78 | https://github.com/jbeluch/xbmcswift2/blob/0e7a3642499554edc8265fdf1ba6c5ee567daa78/xbmcswift2/xbmcmixin.py#L289-L300 | train | 44,329 |
jbeluch/xbmcswift2 | xbmcswift2/xbmcmixin.py | XBMCMixin._listitemify | def _listitemify(self, item):
'''Creates an xbmcswift2.ListItem if the provided value for item is a
dict. If item is already a valid xbmcswift2.ListItem, the item is
returned unmodified.
'''
info_type = self.info_type if hasattr(self, 'info_type') else 'video'
# Create ListItems for anything that is not already an instance of
# ListItem
if not hasattr(item, 'as_tuple'):
if 'info_type' not in item.keys():
item['info_type'] = info_type
item = xbmcswift2.ListItem.from_dict(**item)
return item | python | def _listitemify(self, item):
'''Creates an xbmcswift2.ListItem if the provided value for item is a
dict. If item is already a valid xbmcswift2.ListItem, the item is
returned unmodified.
'''
info_type = self.info_type if hasattr(self, 'info_type') else 'video'
# Create ListItems for anything that is not already an instance of
# ListItem
if not hasattr(item, 'as_tuple'):
if 'info_type' not in item.keys():
item['info_type'] = info_type
item = xbmcswift2.ListItem.from_dict(**item)
return item | [
"def",
"_listitemify",
"(",
"self",
",",
"item",
")",
":",
"info_type",
"=",
"self",
".",
"info_type",
"if",
"hasattr",
"(",
"self",
",",
"'info_type'",
")",
"else",
"'video'",
"# Create ListItems for anything that is not already an instance of",
"# ListItem",
"if",
... | Creates an xbmcswift2.ListItem if the provided value for item is a
dict. If item is already a valid xbmcswift2.ListItem, the item is
returned unmodified. | [
"Creates",
"an",
"xbmcswift2",
".",
"ListItem",
"if",
"the",
"provided",
"value",
"for",
"item",
"is",
"a",
"dict",
".",
"If",
"item",
"is",
"already",
"a",
"valid",
"xbmcswift2",
".",
"ListItem",
"the",
"item",
"is",
"returned",
"unmodified",
"."
] | 0e7a3642499554edc8265fdf1ba6c5ee567daa78 | https://github.com/jbeluch/xbmcswift2/blob/0e7a3642499554edc8265fdf1ba6c5ee567daa78/xbmcswift2/xbmcmixin.py#L302-L315 | train | 44,330 |
jbeluch/xbmcswift2 | xbmcswift2/xbmcmixin.py | XBMCMixin._add_subtitles | def _add_subtitles(self, subtitles):
'''Adds subtitles to playing video.
:param subtitles: A URL to a remote subtitles file or a local filename
for a subtitles file.
.. warning:: You must start playing a video before calling this method
or it will loop for an indefinite length.
'''
# This method is named with an underscore to suggest that callers pass
# the subtitles argument to set_resolved_url instead of calling this
# method directly. This is to ensure a video is played before calling
# this method.
player = xbmc.Player()
for _ in xrange(30):
if player.isPlaying():
break
time.sleep(1)
else:
raise Exception('No video playing. Aborted after 30 seconds.')
player.setSubtitles(subtitles) | python | def _add_subtitles(self, subtitles):
'''Adds subtitles to playing video.
:param subtitles: A URL to a remote subtitles file or a local filename
for a subtitles file.
.. warning:: You must start playing a video before calling this method
or it will loop for an indefinite length.
'''
# This method is named with an underscore to suggest that callers pass
# the subtitles argument to set_resolved_url instead of calling this
# method directly. This is to ensure a video is played before calling
# this method.
player = xbmc.Player()
for _ in xrange(30):
if player.isPlaying():
break
time.sleep(1)
else:
raise Exception('No video playing. Aborted after 30 seconds.')
player.setSubtitles(subtitles) | [
"def",
"_add_subtitles",
"(",
"self",
",",
"subtitles",
")",
":",
"# This method is named with an underscore to suggest that callers pass",
"# the subtitles argument to set_resolved_url instead of calling this",
"# method directly. This is to ensure a video is played before calling",
"# this m... | Adds subtitles to playing video.
:param subtitles: A URL to a remote subtitles file or a local filename
for a subtitles file.
.. warning:: You must start playing a video before calling this method
or it will loop for an indefinite length. | [
"Adds",
"subtitles",
"to",
"playing",
"video",
"."
] | 0e7a3642499554edc8265fdf1ba6c5ee567daa78 | https://github.com/jbeluch/xbmcswift2/blob/0e7a3642499554edc8265fdf1ba6c5ee567daa78/xbmcswift2/xbmcmixin.py#L317-L338 | train | 44,331 |
jbeluch/xbmcswift2 | xbmcswift2/xbmcmixin.py | XBMCMixin.set_resolved_url | def set_resolved_url(self, item=None, subtitles=None):
'''Takes a url or a listitem to be played. Used in conjunction with a
playable list item with a path that calls back into your addon.
:param item: A playable list item or url. Pass None to alert XBMC of a
failure to resolve the item.
.. warning:: When using set_resolved_url you should ensure
the initial playable item (which calls back
into your addon) doesn't have a trailing
slash in the URL. Otherwise it won't work
reliably with XBMC's PlayMedia().
:param subtitles: A URL to a remote subtitles file or a local filename
for a subtitles file to be played along with the
item.
'''
if self._end_of_directory:
raise Exception('Current XBMC handle has been removed. Either '
'set_resolved_url(), end_of_directory(), or '
'finish() has already been called.')
self._end_of_directory = True
succeeded = True
if item is None:
# None item indicates the resolve url failed.
item = {}
succeeded = False
if isinstance(item, basestring):
# caller is passing a url instead of an item dict
item = {'path': item}
item = self._listitemify(item)
item.set_played(True)
xbmcplugin.setResolvedUrl(self.handle, succeeded,
item.as_xbmc_listitem())
# call to _add_subtitles must be after setResolvedUrl
if subtitles:
self._add_subtitles(subtitles)
return [item] | python | def set_resolved_url(self, item=None, subtitles=None):
'''Takes a url or a listitem to be played. Used in conjunction with a
playable list item with a path that calls back into your addon.
:param item: A playable list item or url. Pass None to alert XBMC of a
failure to resolve the item.
.. warning:: When using set_resolved_url you should ensure
the initial playable item (which calls back
into your addon) doesn't have a trailing
slash in the URL. Otherwise it won't work
reliably with XBMC's PlayMedia().
:param subtitles: A URL to a remote subtitles file or a local filename
for a subtitles file to be played along with the
item.
'''
if self._end_of_directory:
raise Exception('Current XBMC handle has been removed. Either '
'set_resolved_url(), end_of_directory(), or '
'finish() has already been called.')
self._end_of_directory = True
succeeded = True
if item is None:
# None item indicates the resolve url failed.
item = {}
succeeded = False
if isinstance(item, basestring):
# caller is passing a url instead of an item dict
item = {'path': item}
item = self._listitemify(item)
item.set_played(True)
xbmcplugin.setResolvedUrl(self.handle, succeeded,
item.as_xbmc_listitem())
# call to _add_subtitles must be after setResolvedUrl
if subtitles:
self._add_subtitles(subtitles)
return [item] | [
"def",
"set_resolved_url",
"(",
"self",
",",
"item",
"=",
"None",
",",
"subtitles",
"=",
"None",
")",
":",
"if",
"self",
".",
"_end_of_directory",
":",
"raise",
"Exception",
"(",
"'Current XBMC handle has been removed. Either '",
"'set_resolved_url(), end_of_directory()... | Takes a url or a listitem to be played. Used in conjunction with a
playable list item with a path that calls back into your addon.
:param item: A playable list item or url. Pass None to alert XBMC of a
failure to resolve the item.
.. warning:: When using set_resolved_url you should ensure
the initial playable item (which calls back
into your addon) doesn't have a trailing
slash in the URL. Otherwise it won't work
reliably with XBMC's PlayMedia().
:param subtitles: A URL to a remote subtitles file or a local filename
for a subtitles file to be played along with the
item. | [
"Takes",
"a",
"url",
"or",
"a",
"listitem",
"to",
"be",
"played",
".",
"Used",
"in",
"conjunction",
"with",
"a",
"playable",
"list",
"item",
"with",
"a",
"path",
"that",
"calls",
"back",
"into",
"your",
"addon",
"."
] | 0e7a3642499554edc8265fdf1ba6c5ee567daa78 | https://github.com/jbeluch/xbmcswift2/blob/0e7a3642499554edc8265fdf1ba6c5ee567daa78/xbmcswift2/xbmcmixin.py#L340-L380 | train | 44,332 |
jbeluch/xbmcswift2 | xbmcswift2/xbmcmixin.py | XBMCMixin.add_items | def add_items(self, items):
'''Adds ListItems to the XBMC interface. Each item in the
provided list should either be instances of xbmcswift2.ListItem,
or regular dictionaries that will be passed to
xbmcswift2.ListItem.from_dict. Returns the list of ListItems.
:param items: An iterable of items where each item is either a
dictionary with keys/values suitable for passing to
:meth:`xbmcswift2.ListItem.from_dict` or an instance of
:class:`xbmcswift2.ListItem`.
'''
_items = [self._listitemify(item) for item in items]
tuples = [item.as_tuple() for item in _items]
xbmcplugin.addDirectoryItems(self.handle, tuples, len(tuples))
# We need to keep track internally of added items so we can return them
# all at the end for testing purposes
self.added_items.extend(_items)
# Possibly need an if statement if only for debug mode
return _items | python | def add_items(self, items):
'''Adds ListItems to the XBMC interface. Each item in the
provided list should either be instances of xbmcswift2.ListItem,
or regular dictionaries that will be passed to
xbmcswift2.ListItem.from_dict. Returns the list of ListItems.
:param items: An iterable of items where each item is either a
dictionary with keys/values suitable for passing to
:meth:`xbmcswift2.ListItem.from_dict` or an instance of
:class:`xbmcswift2.ListItem`.
'''
_items = [self._listitemify(item) for item in items]
tuples = [item.as_tuple() for item in _items]
xbmcplugin.addDirectoryItems(self.handle, tuples, len(tuples))
# We need to keep track internally of added items so we can return them
# all at the end for testing purposes
self.added_items.extend(_items)
# Possibly need an if statement if only for debug mode
return _items | [
"def",
"add_items",
"(",
"self",
",",
"items",
")",
":",
"_items",
"=",
"[",
"self",
".",
"_listitemify",
"(",
"item",
")",
"for",
"item",
"in",
"items",
"]",
"tuples",
"=",
"[",
"item",
".",
"as_tuple",
"(",
")",
"for",
"item",
"in",
"_items",
"]"... | Adds ListItems to the XBMC interface. Each item in the
provided list should either be instances of xbmcswift2.ListItem,
or regular dictionaries that will be passed to
xbmcswift2.ListItem.from_dict. Returns the list of ListItems.
:param items: An iterable of items where each item is either a
dictionary with keys/values suitable for passing to
:meth:`xbmcswift2.ListItem.from_dict` or an instance of
:class:`xbmcswift2.ListItem`. | [
"Adds",
"ListItems",
"to",
"the",
"XBMC",
"interface",
".",
"Each",
"item",
"in",
"the",
"provided",
"list",
"should",
"either",
"be",
"instances",
"of",
"xbmcswift2",
".",
"ListItem",
"or",
"regular",
"dictionaries",
"that",
"will",
"be",
"passed",
"to",
"x... | 0e7a3642499554edc8265fdf1ba6c5ee567daa78 | https://github.com/jbeluch/xbmcswift2/blob/0e7a3642499554edc8265fdf1ba6c5ee567daa78/xbmcswift2/xbmcmixin.py#L398-L418 | train | 44,333 |
jbeluch/xbmcswift2 | xbmcswift2/xbmcmixin.py | XBMCMixin.end_of_directory | def end_of_directory(self, succeeded=True, update_listing=False,
cache_to_disc=True):
'''Wrapper for xbmcplugin.endOfDirectory. Records state in
self._end_of_directory.
Typically it is not necessary to call this method directly, as
calling :meth:`~xbmcswift2.Plugin.finish` will call this method.
'''
self._update_listing = update_listing
if not self._end_of_directory:
self._end_of_directory = True
# Finalize the directory items
return xbmcplugin.endOfDirectory(self.handle, succeeded,
update_listing, cache_to_disc)
assert False, 'Already called endOfDirectory.' | python | def end_of_directory(self, succeeded=True, update_listing=False,
cache_to_disc=True):
'''Wrapper for xbmcplugin.endOfDirectory. Records state in
self._end_of_directory.
Typically it is not necessary to call this method directly, as
calling :meth:`~xbmcswift2.Plugin.finish` will call this method.
'''
self._update_listing = update_listing
if not self._end_of_directory:
self._end_of_directory = True
# Finalize the directory items
return xbmcplugin.endOfDirectory(self.handle, succeeded,
update_listing, cache_to_disc)
assert False, 'Already called endOfDirectory.' | [
"def",
"end_of_directory",
"(",
"self",
",",
"succeeded",
"=",
"True",
",",
"update_listing",
"=",
"False",
",",
"cache_to_disc",
"=",
"True",
")",
":",
"self",
".",
"_update_listing",
"=",
"update_listing",
"if",
"not",
"self",
".",
"_end_of_directory",
":",
... | Wrapper for xbmcplugin.endOfDirectory. Records state in
self._end_of_directory.
Typically it is not necessary to call this method directly, as
calling :meth:`~xbmcswift2.Plugin.finish` will call this method. | [
"Wrapper",
"for",
"xbmcplugin",
".",
"endOfDirectory",
".",
"Records",
"state",
"in",
"self",
".",
"_end_of_directory",
"."
] | 0e7a3642499554edc8265fdf1ba6c5ee567daa78 | https://github.com/jbeluch/xbmcswift2/blob/0e7a3642499554edc8265fdf1ba6c5ee567daa78/xbmcswift2/xbmcmixin.py#L420-L434 | train | 44,334 |
jbeluch/xbmcswift2 | xbmcswift2/xbmcmixin.py | XBMCMixin.finish | def finish(self, items=None, sort_methods=None, succeeded=True,
update_listing=False, cache_to_disc=True, view_mode=None):
'''Adds the provided items to the XBMC interface.
:param items: an iterable of items where each item is either a
dictionary with keys/values suitable for passing to
:meth:`xbmcswift2.ListItem.from_dict` or an instance of
:class:`xbmcswift2.ListItem`.
:param sort_methods: a list of valid XBMC sort_methods. Each item in
the list can either be a sort method or a tuple of
``sort_method, label2_mask``. See
:meth:`add_sort_method` for
more detail concerning valid sort_methods.
Example call with sort_methods::
sort_methods = ['label', 'title', ('date', '%D')]
plugin.finish(items, sort_methods=sort_methods)
:param view_mode: can either be an integer (or parseable integer
string) corresponding to a view_mode or the name of a type of view.
Currrently the only view type supported is 'thumbnail'.
:returns: a list of all ListItems added to the XBMC interface.
'''
# If we have any items, add them. Items are optional here.
if items:
self.add_items(items)
if sort_methods:
for sort_method in sort_methods:
if not isinstance(sort_method, basestring) and hasattr(sort_method, '__len__'):
self.add_sort_method(*sort_method)
else:
self.add_sort_method(sort_method)
# Attempt to set a view_mode if given
if view_mode is not None:
# First check if we were given an integer or parseable integer
try:
view_mode_id = int(view_mode)
except ValueError:
# Attempt to lookup a view mode
view_mode_id = self.get_view_mode_id(view_mode)
if view_mode_id is not None:
self.set_view_mode(view_mode_id)
# Finalize the directory items
self.end_of_directory(succeeded, update_listing, cache_to_disc)
# Return the cached list of all the list items that were added
return self.added_items | python | def finish(self, items=None, sort_methods=None, succeeded=True,
update_listing=False, cache_to_disc=True, view_mode=None):
'''Adds the provided items to the XBMC interface.
:param items: an iterable of items where each item is either a
dictionary with keys/values suitable for passing to
:meth:`xbmcswift2.ListItem.from_dict` or an instance of
:class:`xbmcswift2.ListItem`.
:param sort_methods: a list of valid XBMC sort_methods. Each item in
the list can either be a sort method or a tuple of
``sort_method, label2_mask``. See
:meth:`add_sort_method` for
more detail concerning valid sort_methods.
Example call with sort_methods::
sort_methods = ['label', 'title', ('date', '%D')]
plugin.finish(items, sort_methods=sort_methods)
:param view_mode: can either be an integer (or parseable integer
string) corresponding to a view_mode or the name of a type of view.
Currrently the only view type supported is 'thumbnail'.
:returns: a list of all ListItems added to the XBMC interface.
'''
# If we have any items, add them. Items are optional here.
if items:
self.add_items(items)
if sort_methods:
for sort_method in sort_methods:
if not isinstance(sort_method, basestring) and hasattr(sort_method, '__len__'):
self.add_sort_method(*sort_method)
else:
self.add_sort_method(sort_method)
# Attempt to set a view_mode if given
if view_mode is not None:
# First check if we were given an integer or parseable integer
try:
view_mode_id = int(view_mode)
except ValueError:
# Attempt to lookup a view mode
view_mode_id = self.get_view_mode_id(view_mode)
if view_mode_id is not None:
self.set_view_mode(view_mode_id)
# Finalize the directory items
self.end_of_directory(succeeded, update_listing, cache_to_disc)
# Return the cached list of all the list items that were added
return self.added_items | [
"def",
"finish",
"(",
"self",
",",
"items",
"=",
"None",
",",
"sort_methods",
"=",
"None",
",",
"succeeded",
"=",
"True",
",",
"update_listing",
"=",
"False",
",",
"cache_to_disc",
"=",
"True",
",",
"view_mode",
"=",
"None",
")",
":",
"# If we have any ite... | Adds the provided items to the XBMC interface.
:param items: an iterable of items where each item is either a
dictionary with keys/values suitable for passing to
:meth:`xbmcswift2.ListItem.from_dict` or an instance of
:class:`xbmcswift2.ListItem`.
:param sort_methods: a list of valid XBMC sort_methods. Each item in
the list can either be a sort method or a tuple of
``sort_method, label2_mask``. See
:meth:`add_sort_method` for
more detail concerning valid sort_methods.
Example call with sort_methods::
sort_methods = ['label', 'title', ('date', '%D')]
plugin.finish(items, sort_methods=sort_methods)
:param view_mode: can either be an integer (or parseable integer
string) corresponding to a view_mode or the name of a type of view.
Currrently the only view type supported is 'thumbnail'.
:returns: a list of all ListItems added to the XBMC interface. | [
"Adds",
"the",
"provided",
"items",
"to",
"the",
"XBMC",
"interface",
"."
] | 0e7a3642499554edc8265fdf1ba6c5ee567daa78 | https://github.com/jbeluch/xbmcswift2/blob/0e7a3642499554edc8265fdf1ba6c5ee567daa78/xbmcswift2/xbmcmixin.py#L467-L517 | train | 44,335 |
jbeluch/xbmcswift2 | xbmcswift2/urls.py | UrlRule.match | def match(self, path):
'''Attempts to match a url to the given path. If successful, a tuple is
returned. The first item is the matchd function and the second item is
a dictionary containing items to be passed to the function parsed from
the provided path.
If the provided path does not match this url rule then a
NotFoundException is raised.
'''
m = self._regex.search(path)
if not m:
raise NotFoundException
# urlunencode the values
items = dict((key, unquote_plus(val))
for key, val in m.groupdict().items())
# unpickle any items if present
items = unpickle_dict(items)
# We need to update our dictionary with default values provided in
# options if the keys don't already exist.
[items.setdefault(key, val) for key, val in self._options.items()]
return self._view_func, items | python | def match(self, path):
'''Attempts to match a url to the given path. If successful, a tuple is
returned. The first item is the matchd function and the second item is
a dictionary containing items to be passed to the function parsed from
the provided path.
If the provided path does not match this url rule then a
NotFoundException is raised.
'''
m = self._regex.search(path)
if not m:
raise NotFoundException
# urlunencode the values
items = dict((key, unquote_plus(val))
for key, val in m.groupdict().items())
# unpickle any items if present
items = unpickle_dict(items)
# We need to update our dictionary with default values provided in
# options if the keys don't already exist.
[items.setdefault(key, val) for key, val in self._options.items()]
return self._view_func, items | [
"def",
"match",
"(",
"self",
",",
"path",
")",
":",
"m",
"=",
"self",
".",
"_regex",
".",
"search",
"(",
"path",
")",
"if",
"not",
"m",
":",
"raise",
"NotFoundException",
"# urlunencode the values",
"items",
"=",
"dict",
"(",
"(",
"key",
",",
"unquote_... | Attempts to match a url to the given path. If successful, a tuple is
returned. The first item is the matchd function and the second item is
a dictionary containing items to be passed to the function parsed from
the provided path.
If the provided path does not match this url rule then a
NotFoundException is raised. | [
"Attempts",
"to",
"match",
"a",
"url",
"to",
"the",
"given",
"path",
".",
"If",
"successful",
"a",
"tuple",
"is",
"returned",
".",
"The",
"first",
"item",
"is",
"the",
"matchd",
"function",
"and",
"the",
"second",
"item",
"is",
"a",
"dictionary",
"contai... | 0e7a3642499554edc8265fdf1ba6c5ee567daa78 | https://github.com/jbeluch/xbmcswift2/blob/0e7a3642499554edc8265fdf1ba6c5ee567daa78/xbmcswift2/urls.py#L75-L98 | train | 44,336 |
jbeluch/xbmcswift2 | xbmcswift2/urls.py | UrlRule._make_path | def _make_path(self, items):
'''Returns a relative path for the given dictionary of items.
Uses this url rule's url pattern and replaces instances of <var_name>
with the appropriate value from the items dict.
'''
for key, val in items.items():
if not isinstance(val, basestring):
raise TypeError, ('Value "%s" for key "%s" must be an instance'
' of basestring' % (val, key))
items[key] = quote_plus(val)
try:
path = self._url_format.format(**items)
except AttributeError:
# Old version of python
path = self._url_format
for key, val in items.items():
path = path.replace('{%s}' % key, val)
return path | python | def _make_path(self, items):
'''Returns a relative path for the given dictionary of items.
Uses this url rule's url pattern and replaces instances of <var_name>
with the appropriate value from the items dict.
'''
for key, val in items.items():
if not isinstance(val, basestring):
raise TypeError, ('Value "%s" for key "%s" must be an instance'
' of basestring' % (val, key))
items[key] = quote_plus(val)
try:
path = self._url_format.format(**items)
except AttributeError:
# Old version of python
path = self._url_format
for key, val in items.items():
path = path.replace('{%s}' % key, val)
return path | [
"def",
"_make_path",
"(",
"self",
",",
"items",
")",
":",
"for",
"key",
",",
"val",
"in",
"items",
".",
"items",
"(",
")",
":",
"if",
"not",
"isinstance",
"(",
"val",
",",
"basestring",
")",
":",
"raise",
"TypeError",
",",
"(",
"'Value \"%s\" for key \... | Returns a relative path for the given dictionary of items.
Uses this url rule's url pattern and replaces instances of <var_name>
with the appropriate value from the items dict. | [
"Returns",
"a",
"relative",
"path",
"for",
"the",
"given",
"dictionary",
"of",
"items",
"."
] | 0e7a3642499554edc8265fdf1ba6c5ee567daa78 | https://github.com/jbeluch/xbmcswift2/blob/0e7a3642499554edc8265fdf1ba6c5ee567daa78/xbmcswift2/urls.py#L100-L119 | train | 44,337 |
jbeluch/xbmcswift2 | xbmcswift2/urls.py | UrlRule.make_path_qs | def make_path_qs(self, items):
'''Returns a relative path complete with query string for the given
dictionary of items.
Any items with keys matching this rule's url pattern will be inserted
into the path. Any remaining items will be appended as query string
parameters.
All items will be urlencoded. Any items which are not instances of
basestring, or int/long will be pickled before being urlencoded.
.. warning:: The pickling of items only works for key/value pairs which
will be in the query string. This behavior should only be
used for the simplest of python objects. It causes the
URL to get very lengthy (and unreadable) and XBMC has a
hard limit on URL length. See the caching section if you
need to persist a large amount of data between requests.
'''
# Convert any ints and longs to strings
for key, val in items.items():
if isinstance(val, (int, long)):
items[key] = str(val)
# First use our defaults passed when registering the rule
url_items = dict((key, val) for key, val in self._options.items()
if key in self._keywords)
# Now update with any items explicitly passed to url_for
url_items.update((key, val) for key, val in items.items()
if key in self._keywords)
# Create the path
path = self._make_path(url_items)
# Extra arguments get tacked on to the query string
qs_items = dict((key, val) for key, val in items.items()
if key not in self._keywords)
qs = self._make_qs(qs_items)
if qs:
return '?'.join([path, qs])
return path | python | def make_path_qs(self, items):
'''Returns a relative path complete with query string for the given
dictionary of items.
Any items with keys matching this rule's url pattern will be inserted
into the path. Any remaining items will be appended as query string
parameters.
All items will be urlencoded. Any items which are not instances of
basestring, or int/long will be pickled before being urlencoded.
.. warning:: The pickling of items only works for key/value pairs which
will be in the query string. This behavior should only be
used for the simplest of python objects. It causes the
URL to get very lengthy (and unreadable) and XBMC has a
hard limit on URL length. See the caching section if you
need to persist a large amount of data between requests.
'''
# Convert any ints and longs to strings
for key, val in items.items():
if isinstance(val, (int, long)):
items[key] = str(val)
# First use our defaults passed when registering the rule
url_items = dict((key, val) for key, val in self._options.items()
if key in self._keywords)
# Now update with any items explicitly passed to url_for
url_items.update((key, val) for key, val in items.items()
if key in self._keywords)
# Create the path
path = self._make_path(url_items)
# Extra arguments get tacked on to the query string
qs_items = dict((key, val) for key, val in items.items()
if key not in self._keywords)
qs = self._make_qs(qs_items)
if qs:
return '?'.join([path, qs])
return path | [
"def",
"make_path_qs",
"(",
"self",
",",
"items",
")",
":",
"# Convert any ints and longs to strings",
"for",
"key",
",",
"val",
"in",
"items",
".",
"items",
"(",
")",
":",
"if",
"isinstance",
"(",
"val",
",",
"(",
"int",
",",
"long",
")",
")",
":",
"i... | Returns a relative path complete with query string for the given
dictionary of items.
Any items with keys matching this rule's url pattern will be inserted
into the path. Any remaining items will be appended as query string
parameters.
All items will be urlencoded. Any items which are not instances of
basestring, or int/long will be pickled before being urlencoded.
.. warning:: The pickling of items only works for key/value pairs which
will be in the query string. This behavior should only be
used for the simplest of python objects. It causes the
URL to get very lengthy (and unreadable) and XBMC has a
hard limit on URL length. See the caching section if you
need to persist a large amount of data between requests. | [
"Returns",
"a",
"relative",
"path",
"complete",
"with",
"query",
"string",
"for",
"the",
"given",
"dictionary",
"of",
"items",
"."
] | 0e7a3642499554edc8265fdf1ba6c5ee567daa78 | https://github.com/jbeluch/xbmcswift2/blob/0e7a3642499554edc8265fdf1ba6c5ee567daa78/xbmcswift2/urls.py#L128-L169 | train | 44,338 |
jbeluch/xbmcswift2 | xbmcswift2/storage.py | _PersistentDictMixin.sync | def sync(self):
'''Write the dict to disk'''
if self.flag == 'r':
return
filename = self.filename
tempname = filename + '.tmp'
fileobj = open(tempname, 'wb' if self.file_format == 'pickle' else 'w')
try:
self.dump(fileobj)
except Exception:
os.remove(tempname)
raise
finally:
fileobj.close()
shutil.move(tempname, self.filename) # atomic commit
if self.mode is not None:
os.chmod(self.filename, self.mode) | python | def sync(self):
'''Write the dict to disk'''
if self.flag == 'r':
return
filename = self.filename
tempname = filename + '.tmp'
fileobj = open(tempname, 'wb' if self.file_format == 'pickle' else 'w')
try:
self.dump(fileobj)
except Exception:
os.remove(tempname)
raise
finally:
fileobj.close()
shutil.move(tempname, self.filename) # atomic commit
if self.mode is not None:
os.chmod(self.filename, self.mode) | [
"def",
"sync",
"(",
"self",
")",
":",
"if",
"self",
".",
"flag",
"==",
"'r'",
":",
"return",
"filename",
"=",
"self",
".",
"filename",
"tempname",
"=",
"filename",
"+",
"'.tmp'",
"fileobj",
"=",
"open",
"(",
"tempname",
",",
"'wb'",
"if",
"self",
"."... | Write the dict to disk | [
"Write",
"the",
"dict",
"to",
"disk"
] | 0e7a3642499554edc8265fdf1ba6c5ee567daa78 | https://github.com/jbeluch/xbmcswift2/blob/0e7a3642499554edc8265fdf1ba6c5ee567daa78/xbmcswift2/storage.py#L49-L65 | train | 44,339 |
jbeluch/xbmcswift2 | xbmcswift2/storage.py | _PersistentDictMixin.dump | def dump(self, fileobj):
'''Handles the writing of the dict to the file object'''
if self.file_format == 'csv':
csv.writer(fileobj).writerows(self.raw_dict().items())
elif self.file_format == 'json':
json.dump(self.raw_dict(), fileobj, separators=(',', ':'))
elif self.file_format == 'pickle':
pickle.dump(dict(self.raw_dict()), fileobj, 2)
else:
raise NotImplementedError('Unknown format: ' +
repr(self.file_format)) | python | def dump(self, fileobj):
'''Handles the writing of the dict to the file object'''
if self.file_format == 'csv':
csv.writer(fileobj).writerows(self.raw_dict().items())
elif self.file_format == 'json':
json.dump(self.raw_dict(), fileobj, separators=(',', ':'))
elif self.file_format == 'pickle':
pickle.dump(dict(self.raw_dict()), fileobj, 2)
else:
raise NotImplementedError('Unknown format: ' +
repr(self.file_format)) | [
"def",
"dump",
"(",
"self",
",",
"fileobj",
")",
":",
"if",
"self",
".",
"file_format",
"==",
"'csv'",
":",
"csv",
".",
"writer",
"(",
"fileobj",
")",
".",
"writerows",
"(",
"self",
".",
"raw_dict",
"(",
")",
".",
"items",
"(",
")",
")",
"elif",
... | Handles the writing of the dict to the file object | [
"Handles",
"the",
"writing",
"of",
"the",
"dict",
"to",
"the",
"file",
"object"
] | 0e7a3642499554edc8265fdf1ba6c5ee567daa78 | https://github.com/jbeluch/xbmcswift2/blob/0e7a3642499554edc8265fdf1ba6c5ee567daa78/xbmcswift2/storage.py#L77-L87 | train | 44,340 |
jbeluch/xbmcswift2 | xbmcswift2/storage.py | _PersistentDictMixin.load | def load(self, fileobj):
'''Load the dict from the file object'''
# try formats from most restrictive to least restrictive
for loader in (pickle.load, json.load, csv.reader):
fileobj.seek(0)
try:
return self.initial_update(loader(fileobj))
except Exception as e:
pass
raise ValueError('File not in a supported format') | python | def load(self, fileobj):
'''Load the dict from the file object'''
# try formats from most restrictive to least restrictive
for loader in (pickle.load, json.load, csv.reader):
fileobj.seek(0)
try:
return self.initial_update(loader(fileobj))
except Exception as e:
pass
raise ValueError('File not in a supported format') | [
"def",
"load",
"(",
"self",
",",
"fileobj",
")",
":",
"# try formats from most restrictive to least restrictive",
"for",
"loader",
"in",
"(",
"pickle",
".",
"load",
",",
"json",
".",
"load",
",",
"csv",
".",
"reader",
")",
":",
"fileobj",
".",
"seek",
"(",
... | Load the dict from the file object | [
"Load",
"the",
"dict",
"from",
"the",
"file",
"object"
] | 0e7a3642499554edc8265fdf1ba6c5ee567daa78 | https://github.com/jbeluch/xbmcswift2/blob/0e7a3642499554edc8265fdf1ba6c5ee567daa78/xbmcswift2/storage.py#L89-L98 | train | 44,341 |
jbeluch/xbmcswift2 | xbmcswift2/storage.py | TimedStorage.initial_update | def initial_update(self, mapping):
'''Initially fills the underlying dictionary with keys, values and
timestamps.
'''
for key, val in mapping.items():
_, timestamp = val
if not self.TTL or (datetime.utcnow() -
datetime.utcfromtimestamp(timestamp) < self.TTL):
self.__setitem__(key, val, raw=True) | python | def initial_update(self, mapping):
'''Initially fills the underlying dictionary with keys, values and
timestamps.
'''
for key, val in mapping.items():
_, timestamp = val
if not self.TTL or (datetime.utcnow() -
datetime.utcfromtimestamp(timestamp) < self.TTL):
self.__setitem__(key, val, raw=True) | [
"def",
"initial_update",
"(",
"self",
",",
"mapping",
")",
":",
"for",
"key",
",",
"val",
"in",
"mapping",
".",
"items",
"(",
")",
":",
"_",
",",
"timestamp",
"=",
"val",
"if",
"not",
"self",
".",
"TTL",
"or",
"(",
"datetime",
".",
"utcnow",
"(",
... | Initially fills the underlying dictionary with keys, values and
timestamps. | [
"Initially",
"fills",
"the",
"underlying",
"dictionary",
"with",
"keys",
"values",
"and",
"timestamps",
"."
] | 0e7a3642499554edc8265fdf1ba6c5ee567daa78 | https://github.com/jbeluch/xbmcswift2/blob/0e7a3642499554edc8265fdf1ba6c5ee567daa78/xbmcswift2/storage.py#L176-L184 | train | 44,342 |
jbeluch/xbmcswift2 | xbmcswift2/logger.py | setup_log | def setup_log(name):
'''Returns a logging instance for the provided name. The returned
object is an instance of logging.Logger. Logged messages will be
printed to stderr when running in the CLI, or forwarded to XBMC's
log when running in XBMC mode.
'''
_log = logging.getLogger(name)
_log.setLevel(GLOBAL_LOG_LEVEL)
handler = logging.StreamHandler()
formatter = logging.Formatter(
'%(asctime)s - %(levelname)s - [%(name)s] %(message)s')
handler.setFormatter(formatter)
_log.addHandler(handler)
_log.addFilter(XBMCFilter('[%s] ' % name))
return _log | python | def setup_log(name):
'''Returns a logging instance for the provided name. The returned
object is an instance of logging.Logger. Logged messages will be
printed to stderr when running in the CLI, or forwarded to XBMC's
log when running in XBMC mode.
'''
_log = logging.getLogger(name)
_log.setLevel(GLOBAL_LOG_LEVEL)
handler = logging.StreamHandler()
formatter = logging.Formatter(
'%(asctime)s - %(levelname)s - [%(name)s] %(message)s')
handler.setFormatter(formatter)
_log.addHandler(handler)
_log.addFilter(XBMCFilter('[%s] ' % name))
return _log | [
"def",
"setup_log",
"(",
"name",
")",
":",
"_log",
"=",
"logging",
".",
"getLogger",
"(",
"name",
")",
"_log",
".",
"setLevel",
"(",
"GLOBAL_LOG_LEVEL",
")",
"handler",
"=",
"logging",
".",
"StreamHandler",
"(",
")",
"formatter",
"=",
"logging",
".",
"Fo... | Returns a logging instance for the provided name. The returned
object is an instance of logging.Logger. Logged messages will be
printed to stderr when running in the CLI, or forwarded to XBMC's
log when running in XBMC mode. | [
"Returns",
"a",
"logging",
"instance",
"for",
"the",
"provided",
"name",
".",
"The",
"returned",
"object",
"is",
"an",
"instance",
"of",
"logging",
".",
"Logger",
".",
"Logged",
"messages",
"will",
"be",
"printed",
"to",
"stderr",
"when",
"running",
"in",
... | 0e7a3642499554edc8265fdf1ba6c5ee567daa78 | https://github.com/jbeluch/xbmcswift2/blob/0e7a3642499554edc8265fdf1ba6c5ee567daa78/xbmcswift2/logger.py#L80-L94 | train | 44,343 |
jbeluch/xbmcswift2 | xbmcswift2/logger.py | XBMCFilter.filter | def filter(self, record):
'''Returns True for all records if running in the CLI, else returns
True.
When running inside XBMC it calls the xbmc.log() method and prevents
the message from being double printed to STDOUT.
'''
# When running in XBMC, any logged statements will be double printed
# since we are calling xbmc.log() explicitly. Therefore we return False
# so every log message is filtered out and not printed again.
if CLI_MODE:
return True
else:
# Must not be imported until here because of import order issues
# when running in CLI
from xbmcswift2 import xbmc
xbmc_level = XBMCFilter.xbmc_levels.get(
XBMCFilter.python_to_xbmc.get(record.levelname))
xbmc.log('%s%s' % (self.prefix, record.getMessage()), xbmc_level)
return False | python | def filter(self, record):
'''Returns True for all records if running in the CLI, else returns
True.
When running inside XBMC it calls the xbmc.log() method and prevents
the message from being double printed to STDOUT.
'''
# When running in XBMC, any logged statements will be double printed
# since we are calling xbmc.log() explicitly. Therefore we return False
# so every log message is filtered out and not printed again.
if CLI_MODE:
return True
else:
# Must not be imported until here because of import order issues
# when running in CLI
from xbmcswift2 import xbmc
xbmc_level = XBMCFilter.xbmc_levels.get(
XBMCFilter.python_to_xbmc.get(record.levelname))
xbmc.log('%s%s' % (self.prefix, record.getMessage()), xbmc_level)
return False | [
"def",
"filter",
"(",
"self",
",",
"record",
")",
":",
"# When running in XBMC, any logged statements will be double printed",
"# since we are calling xbmc.log() explicitly. Therefore we return False",
"# so every log message is filtered out and not printed again.",
"if",
"CLI_MODE",
":",
... | Returns True for all records if running in the CLI, else returns
True.
When running inside XBMC it calls the xbmc.log() method and prevents
the message from being double printed to STDOUT. | [
"Returns",
"True",
"for",
"all",
"records",
"if",
"running",
"in",
"the",
"CLI",
"else",
"returns",
"True",
"."
] | 0e7a3642499554edc8265fdf1ba6c5ee567daa78 | https://github.com/jbeluch/xbmcswift2/blob/0e7a3642499554edc8265fdf1ba6c5ee567daa78/xbmcswift2/logger.py#L51-L71 | train | 44,344 |
mozilla/amo-validator | validator/metadata_helpers.py | validate_name | def validate_name(err, value, source):
'Tests a manifest name value for trademarks.'
ff_pattern = re.compile('(mozilla|firefox)', re.I)
err.metadata['name'] = value
if ff_pattern.search(value):
err.warning(
('metadata_helpers', '_test_name', 'trademark'),
'Add-on has potentially illegal name.',
'Add-on names cannot contain the Mozilla or Firefox '
'trademarks. These names should not be contained in add-on '
'names if at all possible.',
source) | python | def validate_name(err, value, source):
'Tests a manifest name value for trademarks.'
ff_pattern = re.compile('(mozilla|firefox)', re.I)
err.metadata['name'] = value
if ff_pattern.search(value):
err.warning(
('metadata_helpers', '_test_name', 'trademark'),
'Add-on has potentially illegal name.',
'Add-on names cannot contain the Mozilla or Firefox '
'trademarks. These names should not be contained in add-on '
'names if at all possible.',
source) | [
"def",
"validate_name",
"(",
"err",
",",
"value",
",",
"source",
")",
":",
"ff_pattern",
"=",
"re",
".",
"compile",
"(",
"'(mozilla|firefox)'",
",",
"re",
".",
"I",
")",
"err",
".",
"metadata",
"[",
"'name'",
"]",
"=",
"value",
"if",
"ff_pattern",
".",... | Tests a manifest name value for trademarks. | [
"Tests",
"a",
"manifest",
"name",
"value",
"for",
"trademarks",
"."
] | 0251bfbd7d93106e01ecdb6de5fcd1dc1a180664 | https://github.com/mozilla/amo-validator/blob/0251bfbd7d93106e01ecdb6de5fcd1dc1a180664/validator/metadata_helpers.py#L6-L20 | train | 44,345 |
mozilla/amo-validator | validator/metadata_helpers.py | validate_id | def validate_id(err, value, source):
'Tests a manifest UUID value'
field_name = '<em:id>' if source == 'install.rdf' else 'id'
id_pattern = re.compile(
'('
# UUID format.
'\{[0-9a-f]{8}-([0-9a-f]{4}-){3}[0-9a-f]{12}\}'
'|'
# "email" format.
'[a-z0-9-\.\+_]*\@[a-z0-9-\._]+'
')',
re.I)
err.metadata['id'] = value
# Must be a valid UUID string.
if not id_pattern.match(value):
err.error(
('metadata_helpers', '_test_id', 'invalid'),
'The value of {name} is invalid'.format(name=field_name),
['The values supplied for {name} in the {source} file is not a '
'valid UUID string or email address.'.format(
name=field_name, source=source),
'For help, please consult: '
'https://developer.mozilla.org/en/install_manifests#id'],
source) | python | def validate_id(err, value, source):
'Tests a manifest UUID value'
field_name = '<em:id>' if source == 'install.rdf' else 'id'
id_pattern = re.compile(
'('
# UUID format.
'\{[0-9a-f]{8}-([0-9a-f]{4}-){3}[0-9a-f]{12}\}'
'|'
# "email" format.
'[a-z0-9-\.\+_]*\@[a-z0-9-\._]+'
')',
re.I)
err.metadata['id'] = value
# Must be a valid UUID string.
if not id_pattern.match(value):
err.error(
('metadata_helpers', '_test_id', 'invalid'),
'The value of {name} is invalid'.format(name=field_name),
['The values supplied for {name} in the {source} file is not a '
'valid UUID string or email address.'.format(
name=field_name, source=source),
'For help, please consult: '
'https://developer.mozilla.org/en/install_manifests#id'],
source) | [
"def",
"validate_id",
"(",
"err",
",",
"value",
",",
"source",
")",
":",
"field_name",
"=",
"'<em:id>'",
"if",
"source",
"==",
"'install.rdf'",
"else",
"'id'",
"id_pattern",
"=",
"re",
".",
"compile",
"(",
"'('",
"# UUID format.",
"'\\{[0-9a-f]{8}-([0-9a-f]{4}-)... | Tests a manifest UUID value | [
"Tests",
"a",
"manifest",
"UUID",
"value"
] | 0251bfbd7d93106e01ecdb6de5fcd1dc1a180664 | https://github.com/mozilla/amo-validator/blob/0251bfbd7d93106e01ecdb6de5fcd1dc1a180664/validator/metadata_helpers.py#L23-L50 | train | 44,346 |
mozilla/amo-validator | validator/metadata_helpers.py | validate_version | def validate_version(err, value, source):
'Tests a manifest version number'
field_name = '<em:version>' if source == 'install.rdf' else 'version'
err.metadata['version'] = value
# May not be longer than 32 characters
if len(value) > 32:
err.error(
('metadata_helpers', '_test_version', 'too_long'),
'The value of {name} is too long'.format(name=field_name),
'Values supplied for {name} in the {source} file must be 32 '
'characters or less.'.format(name=field_name, source=source),
source)
# Must be a valid version number.
if not VERSION_PATTERN.match(value):
err.error(
('metadata_helpers', '_test_version', 'invalid_format'),
'The value of {name} is invalid'.format(name=field_name),
'The values supplied for version in the {source} file is not a '
'valid version string. It can only contain letters, numbers, and '
'the symbols +*.-_.'.format(name=field_name, source=source),
source) | python | def validate_version(err, value, source):
'Tests a manifest version number'
field_name = '<em:version>' if source == 'install.rdf' else 'version'
err.metadata['version'] = value
# May not be longer than 32 characters
if len(value) > 32:
err.error(
('metadata_helpers', '_test_version', 'too_long'),
'The value of {name} is too long'.format(name=field_name),
'Values supplied for {name} in the {source} file must be 32 '
'characters or less.'.format(name=field_name, source=source),
source)
# Must be a valid version number.
if not VERSION_PATTERN.match(value):
err.error(
('metadata_helpers', '_test_version', 'invalid_format'),
'The value of {name} is invalid'.format(name=field_name),
'The values supplied for version in the {source} file is not a '
'valid version string. It can only contain letters, numbers, and '
'the symbols +*.-_.'.format(name=field_name, source=source),
source) | [
"def",
"validate_version",
"(",
"err",
",",
"value",
",",
"source",
")",
":",
"field_name",
"=",
"'<em:version>'",
"if",
"source",
"==",
"'install.rdf'",
"else",
"'version'",
"err",
".",
"metadata",
"[",
"'version'",
"]",
"=",
"value",
"# May not be longer than ... | Tests a manifest version number | [
"Tests",
"a",
"manifest",
"version",
"number"
] | 0251bfbd7d93106e01ecdb6de5fcd1dc1a180664 | https://github.com/mozilla/amo-validator/blob/0251bfbd7d93106e01ecdb6de5fcd1dc1a180664/validator/metadata_helpers.py#L53-L78 | train | 44,347 |
konnected-io/konnected-py | konnected/__init__.py | Client.get_status | def get_status(self):
""" Query the device status. Returns JSON of the device internal state """
url = self.base_url + '/status'
try:
r = requests.get(url, timeout=10)
return r.json()
except RequestException as err:
raise Client.ClientError(err) | python | def get_status(self):
""" Query the device status. Returns JSON of the device internal state """
url = self.base_url + '/status'
try:
r = requests.get(url, timeout=10)
return r.json()
except RequestException as err:
raise Client.ClientError(err) | [
"def",
"get_status",
"(",
"self",
")",
":",
"url",
"=",
"self",
".",
"base_url",
"+",
"'/status'",
"try",
":",
"r",
"=",
"requests",
".",
"get",
"(",
"url",
",",
"timeout",
"=",
"10",
")",
"return",
"r",
".",
"json",
"(",
")",
"except",
"RequestExc... | Query the device status. Returns JSON of the device internal state | [
"Query",
"the",
"device",
"status",
".",
"Returns",
"JSON",
"of",
"the",
"device",
"internal",
"state"
] | 0a3f2d0cfe23deb222ed92e43dee96f27b0f664c | https://github.com/konnected-io/konnected-py/blob/0a3f2d0cfe23deb222ed92e43dee96f27b0f664c/konnected/__init__.py#L29-L36 | train | 44,348 |
konnected-io/konnected-py | konnected/__init__.py | Client.put_device | def put_device(self, pin, state, momentary=None, times=None, pause=None):
""" Actuate a device pin """
url = self.base_url + '/device'
payload = {
"pin": pin,
"state": state
}
if momentary is not None:
payload["momentary"] = momentary
if times is not None:
payload["times"] = times
if pause is not None:
payload["pause"] = pause
try:
r = requests.put(url, json=payload, timeout=10)
return r.json()
except RequestException as err:
raise Client.ClientError(err) | python | def put_device(self, pin, state, momentary=None, times=None, pause=None):
""" Actuate a device pin """
url = self.base_url + '/device'
payload = {
"pin": pin,
"state": state
}
if momentary is not None:
payload["momentary"] = momentary
if times is not None:
payload["times"] = times
if pause is not None:
payload["pause"] = pause
try:
r = requests.put(url, json=payload, timeout=10)
return r.json()
except RequestException as err:
raise Client.ClientError(err) | [
"def",
"put_device",
"(",
"self",
",",
"pin",
",",
"state",
",",
"momentary",
"=",
"None",
",",
"times",
"=",
"None",
",",
"pause",
"=",
"None",
")",
":",
"url",
"=",
"self",
".",
"base_url",
"+",
"'/device'",
"payload",
"=",
"{",
"\"pin\"",
":",
"... | Actuate a device pin | [
"Actuate",
"a",
"device",
"pin"
] | 0a3f2d0cfe23deb222ed92e43dee96f27b0f664c | https://github.com/konnected-io/konnected-py/blob/0a3f2d0cfe23deb222ed92e43dee96f27b0f664c/konnected/__init__.py#L38-L60 | train | 44,349 |
konnected-io/konnected-py | konnected/__init__.py | Client.put_settings | def put_settings(self, sensors=[], actuators=[], auth_token=None,
endpoint=None, blink=None, discovery=None,
dht_sensors=[], ds18b20_sensors=[]):
""" Sync settings to the Konnected device """
url = self.base_url + '/settings'
payload = {
"sensors": sensors,
"actuators": actuators,
"dht_sensors": dht_sensors,
"ds18b20_sensors": ds18b20_sensors,
"token": auth_token,
"apiUrl": endpoint
}
if blink is not None:
payload['blink'] = blink
if discovery is not None:
payload['discovery'] = discovery
try:
r = requests.put(url, json=payload, timeout=10)
return r.ok
except RequestException as err:
raise Client.ClientError(err) | python | def put_settings(self, sensors=[], actuators=[], auth_token=None,
endpoint=None, blink=None, discovery=None,
dht_sensors=[], ds18b20_sensors=[]):
""" Sync settings to the Konnected device """
url = self.base_url + '/settings'
payload = {
"sensors": sensors,
"actuators": actuators,
"dht_sensors": dht_sensors,
"ds18b20_sensors": ds18b20_sensors,
"token": auth_token,
"apiUrl": endpoint
}
if blink is not None:
payload['blink'] = blink
if discovery is not None:
payload['discovery'] = discovery
try:
r = requests.put(url, json=payload, timeout=10)
return r.ok
except RequestException as err:
raise Client.ClientError(err) | [
"def",
"put_settings",
"(",
"self",
",",
"sensors",
"=",
"[",
"]",
",",
"actuators",
"=",
"[",
"]",
",",
"auth_token",
"=",
"None",
",",
"endpoint",
"=",
"None",
",",
"blink",
"=",
"None",
",",
"discovery",
"=",
"None",
",",
"dht_sensors",
"=",
"[",
... | Sync settings to the Konnected device | [
"Sync",
"settings",
"to",
"the",
"Konnected",
"device"
] | 0a3f2d0cfe23deb222ed92e43dee96f27b0f664c | https://github.com/konnected-io/konnected-py/blob/0a3f2d0cfe23deb222ed92e43dee96f27b0f664c/konnected/__init__.py#L62-L87 | train | 44,350 |
dbtsai/python-mimeparse | mimeparse.py | parse_mime_type | def parse_mime_type(mime_type):
"""Parses a mime-type into its component parts.
Carves up a mime-type and returns a tuple of the (type, subtype, params)
where 'params' is a dictionary of all the parameters for the media range.
For example, the media range 'application/xhtml;q=0.5' would get parsed
into:
('application', 'xhtml', {'q', '0.5'})
:rtype: (str,str,dict)
"""
full_type, params = cgi.parse_header(mime_type)
# Java URLConnection class sends an Accept header that includes a
# single '*'. Turn it into a legal wildcard.
if full_type == '*':
full_type = '*/*'
type_parts = full_type.split('/') if '/' in full_type else None
if not type_parts or len(type_parts) > 2:
raise MimeTypeParseException(
"Can't parse type \"{}\"".format(full_type))
(type, subtype) = type_parts
return (type.strip(), subtype.strip(), params) | python | def parse_mime_type(mime_type):
"""Parses a mime-type into its component parts.
Carves up a mime-type and returns a tuple of the (type, subtype, params)
where 'params' is a dictionary of all the parameters for the media range.
For example, the media range 'application/xhtml;q=0.5' would get parsed
into:
('application', 'xhtml', {'q', '0.5'})
:rtype: (str,str,dict)
"""
full_type, params = cgi.parse_header(mime_type)
# Java URLConnection class sends an Accept header that includes a
# single '*'. Turn it into a legal wildcard.
if full_type == '*':
full_type = '*/*'
type_parts = full_type.split('/') if '/' in full_type else None
if not type_parts or len(type_parts) > 2:
raise MimeTypeParseException(
"Can't parse type \"{}\"".format(full_type))
(type, subtype) = type_parts
return (type.strip(), subtype.strip(), params) | [
"def",
"parse_mime_type",
"(",
"mime_type",
")",
":",
"full_type",
",",
"params",
"=",
"cgi",
".",
"parse_header",
"(",
"mime_type",
")",
"# Java URLConnection class sends an Accept header that includes a",
"# single '*'. Turn it into a legal wildcard.",
"if",
"full_type",
"=... | Parses a mime-type into its component parts.
Carves up a mime-type and returns a tuple of the (type, subtype, params)
where 'params' is a dictionary of all the parameters for the media range.
For example, the media range 'application/xhtml;q=0.5' would get parsed
into:
('application', 'xhtml', {'q', '0.5'})
:rtype: (str,str,dict) | [
"Parses",
"a",
"mime",
"-",
"type",
"into",
"its",
"component",
"parts",
"."
] | cf605c0994149b1a1936b3a8a597203fe3fbb62e | https://github.com/dbtsai/python-mimeparse/blob/cf605c0994149b1a1936b3a8a597203fe3fbb62e/mimeparse.py#L14-L39 | train | 44,351 |
dbtsai/python-mimeparse | mimeparse.py | parse_media_range | def parse_media_range(range):
"""Parse a media-range into its component parts.
Carves up a media range and returns a tuple of the (type, subtype,
params) where 'params' is a dictionary of all the parameters for the media
range. For example, the media range 'application/*;q=0.5' would get parsed
into:
('application', '*', {'q', '0.5'})
In addition this function also guarantees that there is a value for 'q'
in the params dictionary, filling it in with a proper default if
necessary.
:rtype: (str,str,dict)
"""
(type, subtype, params) = parse_mime_type(range)
params.setdefault('q', params.pop('Q', None)) # q is case insensitive
try:
if not params['q'] or not 0 <= float(params['q']) <= 1:
params['q'] = '1'
except ValueError: # from float()
params['q'] = '1'
return (type, subtype, params) | python | def parse_media_range(range):
"""Parse a media-range into its component parts.
Carves up a media range and returns a tuple of the (type, subtype,
params) where 'params' is a dictionary of all the parameters for the media
range. For example, the media range 'application/*;q=0.5' would get parsed
into:
('application', '*', {'q', '0.5'})
In addition this function also guarantees that there is a value for 'q'
in the params dictionary, filling it in with a proper default if
necessary.
:rtype: (str,str,dict)
"""
(type, subtype, params) = parse_mime_type(range)
params.setdefault('q', params.pop('Q', None)) # q is case insensitive
try:
if not params['q'] or not 0 <= float(params['q']) <= 1:
params['q'] = '1'
except ValueError: # from float()
params['q'] = '1'
return (type, subtype, params) | [
"def",
"parse_media_range",
"(",
"range",
")",
":",
"(",
"type",
",",
"subtype",
",",
"params",
")",
"=",
"parse_mime_type",
"(",
"range",
")",
"params",
".",
"setdefault",
"(",
"'q'",
",",
"params",
".",
"pop",
"(",
"'Q'",
",",
"None",
")",
")",
"# ... | Parse a media-range into its component parts.
Carves up a media range and returns a tuple of the (type, subtype,
params) where 'params' is a dictionary of all the parameters for the media
range. For example, the media range 'application/*;q=0.5' would get parsed
into:
('application', '*', {'q', '0.5'})
In addition this function also guarantees that there is a value for 'q'
in the params dictionary, filling it in with a proper default if
necessary.
:rtype: (str,str,dict) | [
"Parse",
"a",
"media",
"-",
"range",
"into",
"its",
"component",
"parts",
"."
] | cf605c0994149b1a1936b3a8a597203fe3fbb62e | https://github.com/dbtsai/python-mimeparse/blob/cf605c0994149b1a1936b3a8a597203fe3fbb62e/mimeparse.py#L42-L66 | train | 44,352 |
dbtsai/python-mimeparse | mimeparse.py | quality_and_fitness_parsed | def quality_and_fitness_parsed(mime_type, parsed_ranges):
"""Find the best match for a mime-type amongst parsed media-ranges.
Find the best match for a given mime-type against a list of media_ranges
that have already been parsed by parse_media_range(). Returns a tuple of
the fitness value and the value of the 'q' quality parameter of the best
match, or (-1, 0) if no match was found. Just as for quality_parsed(),
'parsed_ranges' must be a list of parsed media ranges.
:rtype: (float,int)
"""
best_fitness = -1
best_fit_q = 0
(target_type, target_subtype, target_params) = \
parse_media_range(mime_type)
for (type, subtype, params) in parsed_ranges:
# check if the type and the subtype match
type_match = (
type in (target_type, '*') or
target_type == '*'
)
subtype_match = (
subtype in (target_subtype, '*') or
target_subtype == '*'
)
# if they do, assess the "fitness" of this mime_type
if type_match and subtype_match:
# 100 points if the type matches w/o a wildcard
fitness = type == target_type and 100 or 0
# 10 points if the subtype matches w/o a wildcard
fitness += subtype == target_subtype and 10 or 0
# 1 bonus point for each matching param besides "q"
param_matches = sum([
1 for (key, value) in target_params.items()
if key != 'q' and key in params and value == params[key]
])
fitness += param_matches
# finally, add the target's "q" param (between 0 and 1)
fitness += float(target_params.get('q', 1))
if fitness > best_fitness:
best_fitness = fitness
best_fit_q = params['q']
return float(best_fit_q), best_fitness | python | def quality_and_fitness_parsed(mime_type, parsed_ranges):
"""Find the best match for a mime-type amongst parsed media-ranges.
Find the best match for a given mime-type against a list of media_ranges
that have already been parsed by parse_media_range(). Returns a tuple of
the fitness value and the value of the 'q' quality parameter of the best
match, or (-1, 0) if no match was found. Just as for quality_parsed(),
'parsed_ranges' must be a list of parsed media ranges.
:rtype: (float,int)
"""
best_fitness = -1
best_fit_q = 0
(target_type, target_subtype, target_params) = \
parse_media_range(mime_type)
for (type, subtype, params) in parsed_ranges:
# check if the type and the subtype match
type_match = (
type in (target_type, '*') or
target_type == '*'
)
subtype_match = (
subtype in (target_subtype, '*') or
target_subtype == '*'
)
# if they do, assess the "fitness" of this mime_type
if type_match and subtype_match:
# 100 points if the type matches w/o a wildcard
fitness = type == target_type and 100 or 0
# 10 points if the subtype matches w/o a wildcard
fitness += subtype == target_subtype and 10 or 0
# 1 bonus point for each matching param besides "q"
param_matches = sum([
1 for (key, value) in target_params.items()
if key != 'q' and key in params and value == params[key]
])
fitness += param_matches
# finally, add the target's "q" param (between 0 and 1)
fitness += float(target_params.get('q', 1))
if fitness > best_fitness:
best_fitness = fitness
best_fit_q = params['q']
return float(best_fit_q), best_fitness | [
"def",
"quality_and_fitness_parsed",
"(",
"mime_type",
",",
"parsed_ranges",
")",
":",
"best_fitness",
"=",
"-",
"1",
"best_fit_q",
"=",
"0",
"(",
"target_type",
",",
"target_subtype",
",",
"target_params",
")",
"=",
"parse_media_range",
"(",
"mime_type",
")",
"... | Find the best match for a mime-type amongst parsed media-ranges.
Find the best match for a given mime-type against a list of media_ranges
that have already been parsed by parse_media_range(). Returns a tuple of
the fitness value and the value of the 'q' quality parameter of the best
match, or (-1, 0) if no match was found. Just as for quality_parsed(),
'parsed_ranges' must be a list of parsed media ranges.
:rtype: (float,int) | [
"Find",
"the",
"best",
"match",
"for",
"a",
"mime",
"-",
"type",
"amongst",
"parsed",
"media",
"-",
"ranges",
"."
] | cf605c0994149b1a1936b3a8a597203fe3fbb62e | https://github.com/dbtsai/python-mimeparse/blob/cf605c0994149b1a1936b3a8a597203fe3fbb62e/mimeparse.py#L69-L120 | train | 44,353 |
tadashi-aikawa/owlmixin | owlmixin/__init__.py | OwlMixin.from_dict | def from_dict(cls, d: dict, force_snake_case: bool=True, force_cast: bool=False, restrict: bool=True) -> T:
"""From dict to instance
:param d: Dict
:param force_snake_case: Keys are transformed to snake case in order to compliant PEP8 if True
:param force_cast: Cast forcibly if True
:param restrict: Prohibit extra parameters if True
:return: Instance
Usage:
>>> from owlmixin.samples import Human, Food, Japanese
>>> human: Human = Human.from_dict({
... "id": 1,
... "name": "Tom",
... "favorites": [
... {"name": "Apple", "names_by_lang": {"en": "Apple", "de": "Apfel"}},
... {"name": "Orange"}
... ]
... })
>>> human.id
1
>>> human.name
'Tom'
>>> human.favorites[0].name
'Apple'
>>> human.favorites[0].names_by_lang.get()["de"]
'Apfel'
You can use default value
>>> taro: Japanese = Japanese.from_dict({
... "name": 'taro'
... }) # doctest: +NORMALIZE_WHITESPACE
>>> taro.name
'taro'
>>> taro.language
'japanese'
If you don't set `force_snake=False` explicitly, keys are transformed to snake case as following.
>>> human: Human = Human.from_dict({
... "--id": 1,
... "<name>": "Tom",
... "favorites": [
... {"name": "Apple", "namesByLang": {"en": "Apple"}}
... ]
... })
>>> human.id
1
>>> human.name
'Tom'
>>> human.favorites[0].names_by_lang.get()["en"]
'Apple'
You can allow extra parameters (like ``hogehoge``) if you set `restrict=False`.
>>> apple: Food = Food.from_dict({
... "name": "Apple",
... "hogehoge": "ooooooooooooooooooooo",
... }, restrict=False)
>>> apple.to_dict()
{'name': 'Apple'}
You can prohibit extra parameters (like ``hogehoge``) if you set `restrict=True` (which is default).
>>> human = Human.from_dict({
... "id": 1,
... "name": "Tom",
... "hogehoge1": "ooooooooooooooooooooo",
... "hogehoge2": ["aaaaaaaaaaaaaaaaaa", "iiiiiiiiiiiiiiiii"],
... "favorites": [
... {"name": "Apple", "namesByLang": {"en": "Apple", "de": "Apfel"}},
... {"name": "Orange"}
... ]
... }) # doctest: +NORMALIZE_WHITESPACE
Traceback (most recent call last):
...
owlmixin.errors.UnknownPropertiesError:
. ∧,,_∧ ,___________________
⊂ ( ・ω・ )つ- < Unknown properties error
/// /::/ `-------------------
|::|/⊂ヽノ|::|」
/ ̄ ̄旦 ̄ ̄ ̄/|
______/ | |
|------ー----ー|/
<BLANKLINE>
`owlmixin.samples.Human` has unknown properties ['hogehoge1', 'hogehoge2']!!
<BLANKLINE>
* If you want to allow unknown properties, set `restrict=False`
* If you want to disallow unknown properties, add `hogehoge1` and `hogehoge2` to owlmixin.samples.Human
<BLANKLINE>
If you specify wrong type...
>>> human: Human = Human.from_dict({
... "id": 1,
... "name": "ichiro",
... "favorites": ["apple", "orange"]
... }) # doctest: +NORMALIZE_WHITESPACE
Traceback (most recent call last):
...
owlmixin.errors.InvalidTypeError:
. ∧,,_∧ ,___________________
⊂ ( ・ω・ )つ- < Invalid Type error
/// /::/ `-------------------
|::|/⊂ヽノ|::|」
/ ̄ ̄旦 ̄ ̄ ̄/|
______/ | |
|------ー----ー|/
<BLANKLINE>
`owlmixin.samples.Human#favorites.0 = apple` doesn't match expected types.
Expected type is one of ['Food', 'dict'], but actual type is `str`
<BLANKLINE>
* If you want to force cast, set `force_cast=True`
* If you don't want to force cast, specify value which has correct type
<BLANKLINE>
If you don't specify required params... (ex. name
>>> human: Human = Human.from_dict({
... "id": 1
... }) # doctest: +NORMALIZE_WHITESPACE
Traceback (most recent call last):
...
owlmixin.errors.RequiredError:
. ∧,,_∧ ,___________________
⊂ ( ・ω・ )つ- < Required error
/// /::/ `-------------------
|::|/⊂ヽノ|::|」
/ ̄ ̄旦 ̄ ̄ ̄/|
______/ | |
|------ー----ー|/
<BLANKLINE>
`owlmixin.samples.Human#name: str` is empty!!
<BLANKLINE>
* If `name` is certainly required, specify anything.
* If `name` is optional, change type from `str` to `TOption[str]`
<BLANKLINE>
"""
if isinstance(d, cls):
return d
instance: T = cls()
d = util.replace_keys(d, {"self": "_self"}, force_snake_case)
properties = cls.__annotations__.items()
if restrict:
assert_extra(properties, d, cls)
for n, t in properties:
f = cls._methods_dict.get(f'_{cls.__name__}___{n}')
arg_v = f(d.get(n)) if f else d.get(n)
def_v = getattr(instance, n, None)
setattr(instance, n,
traverse(
type_=t,
name=n,
value=def_v if arg_v is None else arg_v,
cls=cls,
force_snake_case=force_snake_case,
force_cast=force_cast,
restrict=restrict
))
return instance | python | def from_dict(cls, d: dict, force_snake_case: bool=True, force_cast: bool=False, restrict: bool=True) -> T:
"""From dict to instance
:param d: Dict
:param force_snake_case: Keys are transformed to snake case in order to compliant PEP8 if True
:param force_cast: Cast forcibly if True
:param restrict: Prohibit extra parameters if True
:return: Instance
Usage:
>>> from owlmixin.samples import Human, Food, Japanese
>>> human: Human = Human.from_dict({
... "id": 1,
... "name": "Tom",
... "favorites": [
... {"name": "Apple", "names_by_lang": {"en": "Apple", "de": "Apfel"}},
... {"name": "Orange"}
... ]
... })
>>> human.id
1
>>> human.name
'Tom'
>>> human.favorites[0].name
'Apple'
>>> human.favorites[0].names_by_lang.get()["de"]
'Apfel'
You can use default value
>>> taro: Japanese = Japanese.from_dict({
... "name": 'taro'
... }) # doctest: +NORMALIZE_WHITESPACE
>>> taro.name
'taro'
>>> taro.language
'japanese'
If you don't set `force_snake=False` explicitly, keys are transformed to snake case as following.
>>> human: Human = Human.from_dict({
... "--id": 1,
... "<name>": "Tom",
... "favorites": [
... {"name": "Apple", "namesByLang": {"en": "Apple"}}
... ]
... })
>>> human.id
1
>>> human.name
'Tom'
>>> human.favorites[0].names_by_lang.get()["en"]
'Apple'
You can allow extra parameters (like ``hogehoge``) if you set `restrict=False`.
>>> apple: Food = Food.from_dict({
... "name": "Apple",
... "hogehoge": "ooooooooooooooooooooo",
... }, restrict=False)
>>> apple.to_dict()
{'name': 'Apple'}
You can prohibit extra parameters (like ``hogehoge``) if you set `restrict=True` (which is default).
>>> human = Human.from_dict({
... "id": 1,
... "name": "Tom",
... "hogehoge1": "ooooooooooooooooooooo",
... "hogehoge2": ["aaaaaaaaaaaaaaaaaa", "iiiiiiiiiiiiiiiii"],
... "favorites": [
... {"name": "Apple", "namesByLang": {"en": "Apple", "de": "Apfel"}},
... {"name": "Orange"}
... ]
... }) # doctest: +NORMALIZE_WHITESPACE
Traceback (most recent call last):
...
owlmixin.errors.UnknownPropertiesError:
. ∧,,_∧ ,___________________
⊂ ( ・ω・ )つ- < Unknown properties error
/// /::/ `-------------------
|::|/⊂ヽノ|::|」
/ ̄ ̄旦 ̄ ̄ ̄/|
______/ | |
|------ー----ー|/
<BLANKLINE>
`owlmixin.samples.Human` has unknown properties ['hogehoge1', 'hogehoge2']!!
<BLANKLINE>
* If you want to allow unknown properties, set `restrict=False`
* If you want to disallow unknown properties, add `hogehoge1` and `hogehoge2` to owlmixin.samples.Human
<BLANKLINE>
If you specify wrong type...
>>> human: Human = Human.from_dict({
... "id": 1,
... "name": "ichiro",
... "favorites": ["apple", "orange"]
... }) # doctest: +NORMALIZE_WHITESPACE
Traceback (most recent call last):
...
owlmixin.errors.InvalidTypeError:
. ∧,,_∧ ,___________________
⊂ ( ・ω・ )つ- < Invalid Type error
/// /::/ `-------------------
|::|/⊂ヽノ|::|」
/ ̄ ̄旦 ̄ ̄ ̄/|
______/ | |
|------ー----ー|/
<BLANKLINE>
`owlmixin.samples.Human#favorites.0 = apple` doesn't match expected types.
Expected type is one of ['Food', 'dict'], but actual type is `str`
<BLANKLINE>
* If you want to force cast, set `force_cast=True`
* If you don't want to force cast, specify value which has correct type
<BLANKLINE>
If you don't specify required params... (ex. name
>>> human: Human = Human.from_dict({
... "id": 1
... }) # doctest: +NORMALIZE_WHITESPACE
Traceback (most recent call last):
...
owlmixin.errors.RequiredError:
. ∧,,_∧ ,___________________
⊂ ( ・ω・ )つ- < Required error
/// /::/ `-------------------
|::|/⊂ヽノ|::|」
/ ̄ ̄旦 ̄ ̄ ̄/|
______/ | |
|------ー----ー|/
<BLANKLINE>
`owlmixin.samples.Human#name: str` is empty!!
<BLANKLINE>
* If `name` is certainly required, specify anything.
* If `name` is optional, change type from `str` to `TOption[str]`
<BLANKLINE>
"""
if isinstance(d, cls):
return d
instance: T = cls()
d = util.replace_keys(d, {"self": "_self"}, force_snake_case)
properties = cls.__annotations__.items()
if restrict:
assert_extra(properties, d, cls)
for n, t in properties:
f = cls._methods_dict.get(f'_{cls.__name__}___{n}')
arg_v = f(d.get(n)) if f else d.get(n)
def_v = getattr(instance, n, None)
setattr(instance, n,
traverse(
type_=t,
name=n,
value=def_v if arg_v is None else arg_v,
cls=cls,
force_snake_case=force_snake_case,
force_cast=force_cast,
restrict=restrict
))
return instance | [
"def",
"from_dict",
"(",
"cls",
",",
"d",
":",
"dict",
",",
"force_snake_case",
":",
"bool",
"=",
"True",
",",
"force_cast",
":",
"bool",
"=",
"False",
",",
"restrict",
":",
"bool",
"=",
"True",
")",
"->",
"T",
":",
"if",
"isinstance",
"(",
"d",
",... | From dict to instance
:param d: Dict
:param force_snake_case: Keys are transformed to snake case in order to compliant PEP8 if True
:param force_cast: Cast forcibly if True
:param restrict: Prohibit extra parameters if True
:return: Instance
Usage:
>>> from owlmixin.samples import Human, Food, Japanese
>>> human: Human = Human.from_dict({
... "id": 1,
... "name": "Tom",
... "favorites": [
... {"name": "Apple", "names_by_lang": {"en": "Apple", "de": "Apfel"}},
... {"name": "Orange"}
... ]
... })
>>> human.id
1
>>> human.name
'Tom'
>>> human.favorites[0].name
'Apple'
>>> human.favorites[0].names_by_lang.get()["de"]
'Apfel'
You can use default value
>>> taro: Japanese = Japanese.from_dict({
... "name": 'taro'
... }) # doctest: +NORMALIZE_WHITESPACE
>>> taro.name
'taro'
>>> taro.language
'japanese'
If you don't set `force_snake=False` explicitly, keys are transformed to snake case as following.
>>> human: Human = Human.from_dict({
... "--id": 1,
... "<name>": "Tom",
... "favorites": [
... {"name": "Apple", "namesByLang": {"en": "Apple"}}
... ]
... })
>>> human.id
1
>>> human.name
'Tom'
>>> human.favorites[0].names_by_lang.get()["en"]
'Apple'
You can allow extra parameters (like ``hogehoge``) if you set `restrict=False`.
>>> apple: Food = Food.from_dict({
... "name": "Apple",
... "hogehoge": "ooooooooooooooooooooo",
... }, restrict=False)
>>> apple.to_dict()
{'name': 'Apple'}
You can prohibit extra parameters (like ``hogehoge``) if you set `restrict=True` (which is default).
>>> human = Human.from_dict({
... "id": 1,
... "name": "Tom",
... "hogehoge1": "ooooooooooooooooooooo",
... "hogehoge2": ["aaaaaaaaaaaaaaaaaa", "iiiiiiiiiiiiiiiii"],
... "favorites": [
... {"name": "Apple", "namesByLang": {"en": "Apple", "de": "Apfel"}},
... {"name": "Orange"}
... ]
... }) # doctest: +NORMALIZE_WHITESPACE
Traceback (most recent call last):
...
owlmixin.errors.UnknownPropertiesError:
. ∧,,_∧ ,___________________
⊂ ( ・ω・ )つ- < Unknown properties error
/// /::/ `-------------------
|::|/⊂ヽノ|::|」
/ ̄ ̄旦 ̄ ̄ ̄/|
______/ | |
|------ー----ー|/
<BLANKLINE>
`owlmixin.samples.Human` has unknown properties ['hogehoge1', 'hogehoge2']!!
<BLANKLINE>
* If you want to allow unknown properties, set `restrict=False`
* If you want to disallow unknown properties, add `hogehoge1` and `hogehoge2` to owlmixin.samples.Human
<BLANKLINE>
If you specify wrong type...
>>> human: Human = Human.from_dict({
... "id": 1,
... "name": "ichiro",
... "favorites": ["apple", "orange"]
... }) # doctest: +NORMALIZE_WHITESPACE
Traceback (most recent call last):
...
owlmixin.errors.InvalidTypeError:
. ∧,,_∧ ,___________________
⊂ ( ・ω・ )つ- < Invalid Type error
/// /::/ `-------------------
|::|/⊂ヽノ|::|」
/ ̄ ̄旦 ̄ ̄ ̄/|
______/ | |
|------ー----ー|/
<BLANKLINE>
`owlmixin.samples.Human#favorites.0 = apple` doesn't match expected types.
Expected type is one of ['Food', 'dict'], but actual type is `str`
<BLANKLINE>
* If you want to force cast, set `force_cast=True`
* If you don't want to force cast, specify value which has correct type
<BLANKLINE>
If you don't specify required params... (ex. name
>>> human: Human = Human.from_dict({
... "id": 1
... }) # doctest: +NORMALIZE_WHITESPACE
Traceback (most recent call last):
...
owlmixin.errors.RequiredError:
. ∧,,_∧ ,___________________
⊂ ( ・ω・ )つ- < Required error
/// /::/ `-------------------
|::|/⊂ヽノ|::|」
/ ̄ ̄旦 ̄ ̄ ̄/|
______/ | |
|------ー----ー|/
<BLANKLINE>
`owlmixin.samples.Human#name: str` is empty!!
<BLANKLINE>
* If `name` is certainly required, specify anything.
* If `name` is optional, change type from `str` to `TOption[str]`
<BLANKLINE> | [
"From",
"dict",
"to",
"instance"
] | 7c4a042c3008abddc56a8e8e55ae930d276071f5 | https://github.com/tadashi-aikawa/owlmixin/blob/7c4a042c3008abddc56a8e8e55ae930d276071f5/owlmixin/__init__.py#L93-L259 | train | 44,354 |
tadashi-aikawa/owlmixin | owlmixin/__init__.py | OwlMixin.from_optional_dict | def from_optional_dict(cls, d: Optional[dict],
force_snake_case: bool=True,force_cast: bool=False, restrict: bool=True) -> TOption[T]:
"""From dict to optional instance.
:param d: Dict
:param force_snake_case: Keys are transformed to snake case in order to compliant PEP8 if True
:param force_cast: Cast forcibly if True
:param restrict: Prohibit extra parameters if True
:return: Instance
Usage:
>>> from owlmixin.samples import Human
>>> Human.from_optional_dict(None).is_none()
True
>>> Human.from_optional_dict({}).get() # doctest: +NORMALIZE_WHITESPACE
Traceback (most recent call last):
...
owlmixin.errors.RequiredError:
. ∧,,_∧ ,___________________
⊂ ( ・ω・ )つ- < Required error
/// /::/ `-------------------
|::|/⊂ヽノ|::|」
/ ̄ ̄旦 ̄ ̄ ̄/|
______/ | |
|------ー----ー|/
<BLANKLINE>
`owlmixin.samples.Human#id: int` is empty!!
<BLANKLINE>
* If `id` is certainly required, specify anything.
* If `id` is optional, change type from `int` to `TOption[int]`
<BLANKLINE>
"""
return TOption(cls.from_dict(d,
force_snake_case=force_snake_case,
force_cast=force_cast,
restrict=restrict) if d is not None else None) | python | def from_optional_dict(cls, d: Optional[dict],
force_snake_case: bool=True,force_cast: bool=False, restrict: bool=True) -> TOption[T]:
"""From dict to optional instance.
:param d: Dict
:param force_snake_case: Keys are transformed to snake case in order to compliant PEP8 if True
:param force_cast: Cast forcibly if True
:param restrict: Prohibit extra parameters if True
:return: Instance
Usage:
>>> from owlmixin.samples import Human
>>> Human.from_optional_dict(None).is_none()
True
>>> Human.from_optional_dict({}).get() # doctest: +NORMALIZE_WHITESPACE
Traceback (most recent call last):
...
owlmixin.errors.RequiredError:
. ∧,,_∧ ,___________________
⊂ ( ・ω・ )つ- < Required error
/// /::/ `-------------------
|::|/⊂ヽノ|::|」
/ ̄ ̄旦 ̄ ̄ ̄/|
______/ | |
|------ー----ー|/
<BLANKLINE>
`owlmixin.samples.Human#id: int` is empty!!
<BLANKLINE>
* If `id` is certainly required, specify anything.
* If `id` is optional, change type from `int` to `TOption[int]`
<BLANKLINE>
"""
return TOption(cls.from_dict(d,
force_snake_case=force_snake_case,
force_cast=force_cast,
restrict=restrict) if d is not None else None) | [
"def",
"from_optional_dict",
"(",
"cls",
",",
"d",
":",
"Optional",
"[",
"dict",
"]",
",",
"force_snake_case",
":",
"bool",
"=",
"True",
",",
"force_cast",
":",
"bool",
"=",
"False",
",",
"restrict",
":",
"bool",
"=",
"True",
")",
"->",
"TOption",
"[",... | From dict to optional instance.
:param d: Dict
:param force_snake_case: Keys are transformed to snake case in order to compliant PEP8 if True
:param force_cast: Cast forcibly if True
:param restrict: Prohibit extra parameters if True
:return: Instance
Usage:
>>> from owlmixin.samples import Human
>>> Human.from_optional_dict(None).is_none()
True
>>> Human.from_optional_dict({}).get() # doctest: +NORMALIZE_WHITESPACE
Traceback (most recent call last):
...
owlmixin.errors.RequiredError:
. ∧,,_∧ ,___________________
⊂ ( ・ω・ )つ- < Required error
/// /::/ `-------------------
|::|/⊂ヽノ|::|」
/ ̄ ̄旦 ̄ ̄ ̄/|
______/ | |
|------ー----ー|/
<BLANKLINE>
`owlmixin.samples.Human#id: int` is empty!!
<BLANKLINE>
* If `id` is certainly required, specify anything.
* If `id` is optional, change type from `int` to `TOption[int]`
<BLANKLINE> | [
"From",
"dict",
"to",
"optional",
"instance",
"."
] | 7c4a042c3008abddc56a8e8e55ae930d276071f5 | https://github.com/tadashi-aikawa/owlmixin/blob/7c4a042c3008abddc56a8e8e55ae930d276071f5/owlmixin/__init__.py#L262-L298 | train | 44,355 |
tadashi-aikawa/owlmixin | owlmixin/__init__.py | OwlMixin.from_dicts | def from_dicts(cls, ds: List[dict],
force_snake_case: bool=True, force_cast: bool=False, restrict: bool=True) -> TList[T]:
"""From list of dict to list of instance
:param ds: List of dict
:param force_snake_case: Keys are transformed to snake case in order to compliant PEP8 if True
:param force_cast: Cast forcibly if True
:param restrict: Prohibit extra parameters if True
:return: List of instance
Usage:
>>> from owlmixin.samples import Human
>>> humans: TList[Human] = Human.from_dicts([
... {"id": 1, "name": "Tom", "favorites": [{"name": "Apple"}]},
... {"id": 2, "name": "John", "favorites": [{"name": "Orange"}]}
... ])
>>> humans[0].name
'Tom'
>>> humans[1].name
'John'
"""
return TList([cls.from_dict(d,
force_snake_case=force_snake_case,
force_cast=force_cast,
restrict=restrict) for d in ds]) | python | def from_dicts(cls, ds: List[dict],
force_snake_case: bool=True, force_cast: bool=False, restrict: bool=True) -> TList[T]:
"""From list of dict to list of instance
:param ds: List of dict
:param force_snake_case: Keys are transformed to snake case in order to compliant PEP8 if True
:param force_cast: Cast forcibly if True
:param restrict: Prohibit extra parameters if True
:return: List of instance
Usage:
>>> from owlmixin.samples import Human
>>> humans: TList[Human] = Human.from_dicts([
... {"id": 1, "name": "Tom", "favorites": [{"name": "Apple"}]},
... {"id": 2, "name": "John", "favorites": [{"name": "Orange"}]}
... ])
>>> humans[0].name
'Tom'
>>> humans[1].name
'John'
"""
return TList([cls.from_dict(d,
force_snake_case=force_snake_case,
force_cast=force_cast,
restrict=restrict) for d in ds]) | [
"def",
"from_dicts",
"(",
"cls",
",",
"ds",
":",
"List",
"[",
"dict",
"]",
",",
"force_snake_case",
":",
"bool",
"=",
"True",
",",
"force_cast",
":",
"bool",
"=",
"False",
",",
"restrict",
":",
"bool",
"=",
"True",
")",
"->",
"TList",
"[",
"T",
"]"... | From list of dict to list of instance
:param ds: List of dict
:param force_snake_case: Keys are transformed to snake case in order to compliant PEP8 if True
:param force_cast: Cast forcibly if True
:param restrict: Prohibit extra parameters if True
:return: List of instance
Usage:
>>> from owlmixin.samples import Human
>>> humans: TList[Human] = Human.from_dicts([
... {"id": 1, "name": "Tom", "favorites": [{"name": "Apple"}]},
... {"id": 2, "name": "John", "favorites": [{"name": "Orange"}]}
... ])
>>> humans[0].name
'Tom'
>>> humans[1].name
'John' | [
"From",
"list",
"of",
"dict",
"to",
"list",
"of",
"instance"
] | 7c4a042c3008abddc56a8e8e55ae930d276071f5 | https://github.com/tadashi-aikawa/owlmixin/blob/7c4a042c3008abddc56a8e8e55ae930d276071f5/owlmixin/__init__.py#L301-L326 | train | 44,356 |
tadashi-aikawa/owlmixin | owlmixin/__init__.py | OwlMixin.from_optional_dicts | def from_optional_dicts(cls, ds: Optional[List[dict]],
force_snake_case: bool=True, force_cast: bool=False, restrict: bool=True) -> TOption[TList[T]]:
"""From list of dict to optional list of instance.
:param ds: List of dict
:param force_snake_case: Keys are transformed to snake case in order to compliant PEP8 if True
:param force_cast: Cast forcibly if True
:param restrict: Prohibit extra parameters if True
:return: List of instance
Usage:
>>> from owlmixin.samples import Human
>>> Human.from_optional_dicts(None).is_none()
True
>>> Human.from_optional_dicts([]).get()
[]
"""
return TOption(cls.from_dicts(ds,
force_snake_case=force_snake_case,
force_cast=force_cast,
restrict=restrict) if ds is not None else None) | python | def from_optional_dicts(cls, ds: Optional[List[dict]],
force_snake_case: bool=True, force_cast: bool=False, restrict: bool=True) -> TOption[TList[T]]:
"""From list of dict to optional list of instance.
:param ds: List of dict
:param force_snake_case: Keys are transformed to snake case in order to compliant PEP8 if True
:param force_cast: Cast forcibly if True
:param restrict: Prohibit extra parameters if True
:return: List of instance
Usage:
>>> from owlmixin.samples import Human
>>> Human.from_optional_dicts(None).is_none()
True
>>> Human.from_optional_dicts([]).get()
[]
"""
return TOption(cls.from_dicts(ds,
force_snake_case=force_snake_case,
force_cast=force_cast,
restrict=restrict) if ds is not None else None) | [
"def",
"from_optional_dicts",
"(",
"cls",
",",
"ds",
":",
"Optional",
"[",
"List",
"[",
"dict",
"]",
"]",
",",
"force_snake_case",
":",
"bool",
"=",
"True",
",",
"force_cast",
":",
"bool",
"=",
"False",
",",
"restrict",
":",
"bool",
"=",
"True",
")",
... | From list of dict to optional list of instance.
:param ds: List of dict
:param force_snake_case: Keys are transformed to snake case in order to compliant PEP8 if True
:param force_cast: Cast forcibly if True
:param restrict: Prohibit extra parameters if True
:return: List of instance
Usage:
>>> from owlmixin.samples import Human
>>> Human.from_optional_dicts(None).is_none()
True
>>> Human.from_optional_dicts([]).get()
[] | [
"From",
"list",
"of",
"dict",
"to",
"optional",
"list",
"of",
"instance",
"."
] | 7c4a042c3008abddc56a8e8e55ae930d276071f5 | https://github.com/tadashi-aikawa/owlmixin/blob/7c4a042c3008abddc56a8e8e55ae930d276071f5/owlmixin/__init__.py#L329-L350 | train | 44,357 |
tadashi-aikawa/owlmixin | owlmixin/__init__.py | OwlMixin.from_dicts_by_key | def from_dicts_by_key(cls, ds: dict,
force_snake_case: bool=True, force_cast: bool=False, restrict: bool=True) -> TDict[T]:
"""From dict of dict to dict of instance
:param ds: Dict of dict
:param force_snake_case: Keys are transformed to snake case in order to compliant PEP8 if True
:param force_cast: Cast forcibly if True
:param restrict: Prohibit extra parameters if True
:return: Dict of instance
Usage:
>>> from owlmixin.samples import Human
>>> humans_by_name: TDict[Human] = Human.from_dicts_by_key({
... 'Tom': {"id": 1, "name": "Tom", "favorites": [{"name": "Apple"}]},
... 'John': {"id": 2, "name": "John", "favorites": [{"name": "Orange"}]}
... })
>>> humans_by_name['Tom'].name
'Tom'
>>> humans_by_name['John'].name
'John'
"""
return TDict({k: cls.from_dict(v,
force_snake_case=force_snake_case,
force_cast=force_cast,
restrict=restrict) for k, v in ds.items()}) | python | def from_dicts_by_key(cls, ds: dict,
force_snake_case: bool=True, force_cast: bool=False, restrict: bool=True) -> TDict[T]:
"""From dict of dict to dict of instance
:param ds: Dict of dict
:param force_snake_case: Keys are transformed to snake case in order to compliant PEP8 if True
:param force_cast: Cast forcibly if True
:param restrict: Prohibit extra parameters if True
:return: Dict of instance
Usage:
>>> from owlmixin.samples import Human
>>> humans_by_name: TDict[Human] = Human.from_dicts_by_key({
... 'Tom': {"id": 1, "name": "Tom", "favorites": [{"name": "Apple"}]},
... 'John': {"id": 2, "name": "John", "favorites": [{"name": "Orange"}]}
... })
>>> humans_by_name['Tom'].name
'Tom'
>>> humans_by_name['John'].name
'John'
"""
return TDict({k: cls.from_dict(v,
force_snake_case=force_snake_case,
force_cast=force_cast,
restrict=restrict) for k, v in ds.items()}) | [
"def",
"from_dicts_by_key",
"(",
"cls",
",",
"ds",
":",
"dict",
",",
"force_snake_case",
":",
"bool",
"=",
"True",
",",
"force_cast",
":",
"bool",
"=",
"False",
",",
"restrict",
":",
"bool",
"=",
"True",
")",
"->",
"TDict",
"[",
"T",
"]",
":",
"retur... | From dict of dict to dict of instance
:param ds: Dict of dict
:param force_snake_case: Keys are transformed to snake case in order to compliant PEP8 if True
:param force_cast: Cast forcibly if True
:param restrict: Prohibit extra parameters if True
:return: Dict of instance
Usage:
>>> from owlmixin.samples import Human
>>> humans_by_name: TDict[Human] = Human.from_dicts_by_key({
... 'Tom': {"id": 1, "name": "Tom", "favorites": [{"name": "Apple"}]},
... 'John': {"id": 2, "name": "John", "favorites": [{"name": "Orange"}]}
... })
>>> humans_by_name['Tom'].name
'Tom'
>>> humans_by_name['John'].name
'John' | [
"From",
"dict",
"of",
"dict",
"to",
"dict",
"of",
"instance"
] | 7c4a042c3008abddc56a8e8e55ae930d276071f5 | https://github.com/tadashi-aikawa/owlmixin/blob/7c4a042c3008abddc56a8e8e55ae930d276071f5/owlmixin/__init__.py#L353-L378 | train | 44,358 |
tadashi-aikawa/owlmixin | owlmixin/__init__.py | OwlMixin.from_optional_dicts_by_key | def from_optional_dicts_by_key(cls, ds: Optional[dict],
force_snake_case=True, force_cast: bool=False, restrict: bool=True) -> TOption[TDict[T]]:
"""From dict of dict to optional dict of instance.
:param ds: Dict of dict
:param force_snake_case: Keys are transformed to snake case in order to compliant PEP8 if True
:param force_cast: Cast forcibly if True
:param restrict: Prohibit extra parameters if True
:return: Dict of instance
Usage:
>>> from owlmixin.samples import Human
>>> Human.from_optional_dicts_by_key(None).is_none()
True
>>> Human.from_optional_dicts_by_key({}).get()
{}
"""
return TOption(cls.from_dicts_by_key(ds,
force_snake_case=force_snake_case,
force_cast=force_cast,
restrict=restrict) if ds is not None else None) | python | def from_optional_dicts_by_key(cls, ds: Optional[dict],
force_snake_case=True, force_cast: bool=False, restrict: bool=True) -> TOption[TDict[T]]:
"""From dict of dict to optional dict of instance.
:param ds: Dict of dict
:param force_snake_case: Keys are transformed to snake case in order to compliant PEP8 if True
:param force_cast: Cast forcibly if True
:param restrict: Prohibit extra parameters if True
:return: Dict of instance
Usage:
>>> from owlmixin.samples import Human
>>> Human.from_optional_dicts_by_key(None).is_none()
True
>>> Human.from_optional_dicts_by_key({}).get()
{}
"""
return TOption(cls.from_dicts_by_key(ds,
force_snake_case=force_snake_case,
force_cast=force_cast,
restrict=restrict) if ds is not None else None) | [
"def",
"from_optional_dicts_by_key",
"(",
"cls",
",",
"ds",
":",
"Optional",
"[",
"dict",
"]",
",",
"force_snake_case",
"=",
"True",
",",
"force_cast",
":",
"bool",
"=",
"False",
",",
"restrict",
":",
"bool",
"=",
"True",
")",
"->",
"TOption",
"[",
"TDic... | From dict of dict to optional dict of instance.
:param ds: Dict of dict
:param force_snake_case: Keys are transformed to snake case in order to compliant PEP8 if True
:param force_cast: Cast forcibly if True
:param restrict: Prohibit extra parameters if True
:return: Dict of instance
Usage:
>>> from owlmixin.samples import Human
>>> Human.from_optional_dicts_by_key(None).is_none()
True
>>> Human.from_optional_dicts_by_key({}).get()
{} | [
"From",
"dict",
"of",
"dict",
"to",
"optional",
"dict",
"of",
"instance",
"."
] | 7c4a042c3008abddc56a8e8e55ae930d276071f5 | https://github.com/tadashi-aikawa/owlmixin/blob/7c4a042c3008abddc56a8e8e55ae930d276071f5/owlmixin/__init__.py#L381-L402 | train | 44,359 |
tadashi-aikawa/owlmixin | owlmixin/__init__.py | OwlMixin.from_json | def from_json(cls, data: str, force_snake_case=True, force_cast: bool=False, restrict: bool=False) -> T:
"""From json string to instance
:param data: Json string
:param force_snake_case: Keys are transformed to snake case in order to compliant PEP8 if True
:param force_cast: Cast forcibly if True
:param restrict: Prohibit extra parameters if True
:return: Instance
Usage:
>>> from owlmixin.samples import Human
>>> human: Human = Human.from_json('''{
... "id": 1,
... "name": "Tom",
... "favorites": [
... {"name": "Apple", "names_by_lang": {"en": "Apple", "de": "Apfel"}},
... {"name": "Orange"}
... ]
... }''')
>>> human.id
1
>>> human.name
'Tom'
>>> human.favorites[0].names_by_lang.get()["de"]
'Apfel'
"""
return cls.from_dict(util.load_json(data),
force_snake_case=force_snake_case,
force_cast=force_cast,
restrict=restrict) | python | def from_json(cls, data: str, force_snake_case=True, force_cast: bool=False, restrict: bool=False) -> T:
"""From json string to instance
:param data: Json string
:param force_snake_case: Keys are transformed to snake case in order to compliant PEP8 if True
:param force_cast: Cast forcibly if True
:param restrict: Prohibit extra parameters if True
:return: Instance
Usage:
>>> from owlmixin.samples import Human
>>> human: Human = Human.from_json('''{
... "id": 1,
... "name": "Tom",
... "favorites": [
... {"name": "Apple", "names_by_lang": {"en": "Apple", "de": "Apfel"}},
... {"name": "Orange"}
... ]
... }''')
>>> human.id
1
>>> human.name
'Tom'
>>> human.favorites[0].names_by_lang.get()["de"]
'Apfel'
"""
return cls.from_dict(util.load_json(data),
force_snake_case=force_snake_case,
force_cast=force_cast,
restrict=restrict) | [
"def",
"from_json",
"(",
"cls",
",",
"data",
":",
"str",
",",
"force_snake_case",
"=",
"True",
",",
"force_cast",
":",
"bool",
"=",
"False",
",",
"restrict",
":",
"bool",
"=",
"False",
")",
"->",
"T",
":",
"return",
"cls",
".",
"from_dict",
"(",
"uti... | From json string to instance
:param data: Json string
:param force_snake_case: Keys are transformed to snake case in order to compliant PEP8 if True
:param force_cast: Cast forcibly if True
:param restrict: Prohibit extra parameters if True
:return: Instance
Usage:
>>> from owlmixin.samples import Human
>>> human: Human = Human.from_json('''{
... "id": 1,
... "name": "Tom",
... "favorites": [
... {"name": "Apple", "names_by_lang": {"en": "Apple", "de": "Apfel"}},
... {"name": "Orange"}
... ]
... }''')
>>> human.id
1
>>> human.name
'Tom'
>>> human.favorites[0].names_by_lang.get()["de"]
'Apfel' | [
"From",
"json",
"string",
"to",
"instance"
] | 7c4a042c3008abddc56a8e8e55ae930d276071f5 | https://github.com/tadashi-aikawa/owlmixin/blob/7c4a042c3008abddc56a8e8e55ae930d276071f5/owlmixin/__init__.py#L405-L435 | train | 44,360 |
tadashi-aikawa/owlmixin | owlmixin/__init__.py | OwlMixin.from_jsonf | def from_jsonf(cls, fpath: str, encoding: str='utf8',
force_snake_case=True, force_cast: bool=False, restrict: bool=False) -> T:
"""From json file path to instance
:param fpath: Json file path
:param encoding: Json file encoding
:param force_snake_case: Keys are transformed to snake case in order to compliant PEP8 if True
:param force_cast: Cast forcibly if True
:param restrict: Prohibit extra parameters if True
:return: Instance
"""
return cls.from_dict(util.load_jsonf(fpath, encoding),
force_snake_case=force_snake_case,
force_cast=force_cast,
restrict=restrict) | python | def from_jsonf(cls, fpath: str, encoding: str='utf8',
force_snake_case=True, force_cast: bool=False, restrict: bool=False) -> T:
"""From json file path to instance
:param fpath: Json file path
:param encoding: Json file encoding
:param force_snake_case: Keys are transformed to snake case in order to compliant PEP8 if True
:param force_cast: Cast forcibly if True
:param restrict: Prohibit extra parameters if True
:return: Instance
"""
return cls.from_dict(util.load_jsonf(fpath, encoding),
force_snake_case=force_snake_case,
force_cast=force_cast,
restrict=restrict) | [
"def",
"from_jsonf",
"(",
"cls",
",",
"fpath",
":",
"str",
",",
"encoding",
":",
"str",
"=",
"'utf8'",
",",
"force_snake_case",
"=",
"True",
",",
"force_cast",
":",
"bool",
"=",
"False",
",",
"restrict",
":",
"bool",
"=",
"False",
")",
"->",
"T",
":"... | From json file path to instance
:param fpath: Json file path
:param encoding: Json file encoding
:param force_snake_case: Keys are transformed to snake case in order to compliant PEP8 if True
:param force_cast: Cast forcibly if True
:param restrict: Prohibit extra parameters if True
:return: Instance | [
"From",
"json",
"file",
"path",
"to",
"instance"
] | 7c4a042c3008abddc56a8e8e55ae930d276071f5 | https://github.com/tadashi-aikawa/owlmixin/blob/7c4a042c3008abddc56a8e8e55ae930d276071f5/owlmixin/__init__.py#L438-L452 | train | 44,361 |
tadashi-aikawa/owlmixin | owlmixin/__init__.py | OwlMixin.from_json_to_list | def from_json_to_list(cls, data: str,
force_snake_case=True, force_cast: bool=False, restrict: bool=False) -> TList[T]:
"""From json string to list of instance
:param data: Json string
:param force_snake_case: Keys are transformed to snake case in order to compliant PEP8 if True
:param force_cast: Cast forcibly if True
:param restrict: Prohibit extra parameters if True
:return: List of instance
Usage:
>>> from owlmixin.samples import Human
>>> humans: TList[Human] = Human.from_json_to_list('''[
... {"id": 1, "name": "Tom", "favorites": [{"name": "Apple"}]},
... {"id": 2, "name": "John", "favorites": [{"name": "Orange"}]}
... ]''')
>>> humans[0].name
'Tom'
>>> humans[1].name
'John'
"""
return cls.from_dicts(util.load_json(data),
force_snake_case=force_snake_case,
force_cast=force_cast,
restrict=restrict) | python | def from_json_to_list(cls, data: str,
force_snake_case=True, force_cast: bool=False, restrict: bool=False) -> TList[T]:
"""From json string to list of instance
:param data: Json string
:param force_snake_case: Keys are transformed to snake case in order to compliant PEP8 if True
:param force_cast: Cast forcibly if True
:param restrict: Prohibit extra parameters if True
:return: List of instance
Usage:
>>> from owlmixin.samples import Human
>>> humans: TList[Human] = Human.from_json_to_list('''[
... {"id": 1, "name": "Tom", "favorites": [{"name": "Apple"}]},
... {"id": 2, "name": "John", "favorites": [{"name": "Orange"}]}
... ]''')
>>> humans[0].name
'Tom'
>>> humans[1].name
'John'
"""
return cls.from_dicts(util.load_json(data),
force_snake_case=force_snake_case,
force_cast=force_cast,
restrict=restrict) | [
"def",
"from_json_to_list",
"(",
"cls",
",",
"data",
":",
"str",
",",
"force_snake_case",
"=",
"True",
",",
"force_cast",
":",
"bool",
"=",
"False",
",",
"restrict",
":",
"bool",
"=",
"False",
")",
"->",
"TList",
"[",
"T",
"]",
":",
"return",
"cls",
... | From json string to list of instance
:param data: Json string
:param force_snake_case: Keys are transformed to snake case in order to compliant PEP8 if True
:param force_cast: Cast forcibly if True
:param restrict: Prohibit extra parameters if True
:return: List of instance
Usage:
>>> from owlmixin.samples import Human
>>> humans: TList[Human] = Human.from_json_to_list('''[
... {"id": 1, "name": "Tom", "favorites": [{"name": "Apple"}]},
... {"id": 2, "name": "John", "favorites": [{"name": "Orange"}]}
... ]''')
>>> humans[0].name
'Tom'
>>> humans[1].name
'John' | [
"From",
"json",
"string",
"to",
"list",
"of",
"instance"
] | 7c4a042c3008abddc56a8e8e55ae930d276071f5 | https://github.com/tadashi-aikawa/owlmixin/blob/7c4a042c3008abddc56a8e8e55ae930d276071f5/owlmixin/__init__.py#L455-L480 | train | 44,362 |
tadashi-aikawa/owlmixin | owlmixin/__init__.py | OwlMixin.from_jsonf_to_list | def from_jsonf_to_list(cls, fpath: str, encoding: str='utf8',
force_snake_case=True, force_cast: bool=False, restrict: bool=False) -> TList[T]:
"""From json file path to list of instance
:param fpath: Json file path
:param encoding: Json file encoding
:param force_snake_case: Keys are transformed to snake case in order to compliant PEP8 if True
:param force_cast: Cast forcibly if True
:param restrict: Prohibit extra parameters if True
:return: List of instance
"""
return cls.from_dicts(util.load_jsonf(fpath, encoding),
force_snake_case=force_snake_case,
force_cast=force_cast,
restrict=restrict) | python | def from_jsonf_to_list(cls, fpath: str, encoding: str='utf8',
force_snake_case=True, force_cast: bool=False, restrict: bool=False) -> TList[T]:
"""From json file path to list of instance
:param fpath: Json file path
:param encoding: Json file encoding
:param force_snake_case: Keys are transformed to snake case in order to compliant PEP8 if True
:param force_cast: Cast forcibly if True
:param restrict: Prohibit extra parameters if True
:return: List of instance
"""
return cls.from_dicts(util.load_jsonf(fpath, encoding),
force_snake_case=force_snake_case,
force_cast=force_cast,
restrict=restrict) | [
"def",
"from_jsonf_to_list",
"(",
"cls",
",",
"fpath",
":",
"str",
",",
"encoding",
":",
"str",
"=",
"'utf8'",
",",
"force_snake_case",
"=",
"True",
",",
"force_cast",
":",
"bool",
"=",
"False",
",",
"restrict",
":",
"bool",
"=",
"False",
")",
"->",
"T... | From json file path to list of instance
:param fpath: Json file path
:param encoding: Json file encoding
:param force_snake_case: Keys are transformed to snake case in order to compliant PEP8 if True
:param force_cast: Cast forcibly if True
:param restrict: Prohibit extra parameters if True
:return: List of instance | [
"From",
"json",
"file",
"path",
"to",
"list",
"of",
"instance"
] | 7c4a042c3008abddc56a8e8e55ae930d276071f5 | https://github.com/tadashi-aikawa/owlmixin/blob/7c4a042c3008abddc56a8e8e55ae930d276071f5/owlmixin/__init__.py#L483-L497 | train | 44,363 |
tadashi-aikawa/owlmixin | owlmixin/__init__.py | OwlMixin.from_yaml | def from_yaml(cls, data: str, force_snake_case=True, force_cast: bool=False, restrict: bool=True) -> T:
"""From yaml string to instance
:param data: Yaml string
:param force_snake_case: Keys are transformed to snake case in order to compliant PEP8 if True
:param force_cast: Cast forcibly if True
:param restrict: Prohibit extra parameters if True
:return: Instance
Usage:
>>> from owlmixin.samples import Human
>>> human: Human = Human.from_yaml('''
... id: 1
... name: Tom
... favorites:
... - name: Apple
... names_by_lang:
... en: Apple
... de: Apfel
... - name: Orange
... ''')
>>> human.id
1
>>> human.name
'Tom'
>>> human.favorites[0].names_by_lang.get()["de"]
'Apfel'
"""
return cls.from_dict(util.load_yaml(data),
force_snake_case=force_snake_case,
force_cast=force_cast,
restrict=restrict) | python | def from_yaml(cls, data: str, force_snake_case=True, force_cast: bool=False, restrict: bool=True) -> T:
"""From yaml string to instance
:param data: Yaml string
:param force_snake_case: Keys are transformed to snake case in order to compliant PEP8 if True
:param force_cast: Cast forcibly if True
:param restrict: Prohibit extra parameters if True
:return: Instance
Usage:
>>> from owlmixin.samples import Human
>>> human: Human = Human.from_yaml('''
... id: 1
... name: Tom
... favorites:
... - name: Apple
... names_by_lang:
... en: Apple
... de: Apfel
... - name: Orange
... ''')
>>> human.id
1
>>> human.name
'Tom'
>>> human.favorites[0].names_by_lang.get()["de"]
'Apfel'
"""
return cls.from_dict(util.load_yaml(data),
force_snake_case=force_snake_case,
force_cast=force_cast,
restrict=restrict) | [
"def",
"from_yaml",
"(",
"cls",
",",
"data",
":",
"str",
",",
"force_snake_case",
"=",
"True",
",",
"force_cast",
":",
"bool",
"=",
"False",
",",
"restrict",
":",
"bool",
"=",
"True",
")",
"->",
"T",
":",
"return",
"cls",
".",
"from_dict",
"(",
"util... | From yaml string to instance
:param data: Yaml string
:param force_snake_case: Keys are transformed to snake case in order to compliant PEP8 if True
:param force_cast: Cast forcibly if True
:param restrict: Prohibit extra parameters if True
:return: Instance
Usage:
>>> from owlmixin.samples import Human
>>> human: Human = Human.from_yaml('''
... id: 1
... name: Tom
... favorites:
... - name: Apple
... names_by_lang:
... en: Apple
... de: Apfel
... - name: Orange
... ''')
>>> human.id
1
>>> human.name
'Tom'
>>> human.favorites[0].names_by_lang.get()["de"]
'Apfel' | [
"From",
"yaml",
"string",
"to",
"instance"
] | 7c4a042c3008abddc56a8e8e55ae930d276071f5 | https://github.com/tadashi-aikawa/owlmixin/blob/7c4a042c3008abddc56a8e8e55ae930d276071f5/owlmixin/__init__.py#L500-L532 | train | 44,364 |
tadashi-aikawa/owlmixin | owlmixin/__init__.py | OwlMixin.from_yamlf | def from_yamlf(cls, fpath: str, encoding: str='utf8',
force_snake_case=True, force_cast: bool=False, restrict: bool=True) -> T:
"""From yaml file path to instance
:param fpath: Yaml file path
:param encoding: Yaml file encoding
:param force_snake_case: Keys are transformed to snake case in order to compliant PEP8 if True
:param force_cast: Cast forcibly if True
:param restrict: Prohibit extra parameters if True
:return: Instance
"""
return cls.from_dict(util.load_yamlf(fpath, encoding),
force_snake_case=force_snake_case,
force_cast=force_cast,
restrict=restrict) | python | def from_yamlf(cls, fpath: str, encoding: str='utf8',
force_snake_case=True, force_cast: bool=False, restrict: bool=True) -> T:
"""From yaml file path to instance
:param fpath: Yaml file path
:param encoding: Yaml file encoding
:param force_snake_case: Keys are transformed to snake case in order to compliant PEP8 if True
:param force_cast: Cast forcibly if True
:param restrict: Prohibit extra parameters if True
:return: Instance
"""
return cls.from_dict(util.load_yamlf(fpath, encoding),
force_snake_case=force_snake_case,
force_cast=force_cast,
restrict=restrict) | [
"def",
"from_yamlf",
"(",
"cls",
",",
"fpath",
":",
"str",
",",
"encoding",
":",
"str",
"=",
"'utf8'",
",",
"force_snake_case",
"=",
"True",
",",
"force_cast",
":",
"bool",
"=",
"False",
",",
"restrict",
":",
"bool",
"=",
"True",
")",
"->",
"T",
":",... | From yaml file path to instance
:param fpath: Yaml file path
:param encoding: Yaml file encoding
:param force_snake_case: Keys are transformed to snake case in order to compliant PEP8 if True
:param force_cast: Cast forcibly if True
:param restrict: Prohibit extra parameters if True
:return: Instance | [
"From",
"yaml",
"file",
"path",
"to",
"instance"
] | 7c4a042c3008abddc56a8e8e55ae930d276071f5 | https://github.com/tadashi-aikawa/owlmixin/blob/7c4a042c3008abddc56a8e8e55ae930d276071f5/owlmixin/__init__.py#L535-L549 | train | 44,365 |
tadashi-aikawa/owlmixin | owlmixin/__init__.py | OwlMixin.from_yaml_to_list | def from_yaml_to_list(cls, data: str,
force_snake_case=True, force_cast: bool=False, restrict: bool=True) -> TList[T]:
"""From yaml string to list of instance
:param data: Yaml string
:param force_snake_case: Keys are transformed to snake case in order to compliant PEP8 if True
:param force_cast: Cast forcibly if True
:param restrict: Prohibit extra parameters if True
:return: List of instance
Usage:
>>> from owlmixin.samples import Human
>>> humans: TList[Human] = Human.from_yaml_to_list('''
... - id: 1
... name: Tom
... favorites:
... - name: Apple
... - id: 2
... name: John
... favorites:
... - name: Orange
... ''')
>>> humans[0].name
'Tom'
>>> humans[1].name
'John'
>>> humans[0].favorites[0].name
'Apple'
"""
return cls.from_dicts(util.load_yaml(data),
force_snake_case=force_snake_case,
force_cast=force_cast,
restrict=restrict) | python | def from_yaml_to_list(cls, data: str,
force_snake_case=True, force_cast: bool=False, restrict: bool=True) -> TList[T]:
"""From yaml string to list of instance
:param data: Yaml string
:param force_snake_case: Keys are transformed to snake case in order to compliant PEP8 if True
:param force_cast: Cast forcibly if True
:param restrict: Prohibit extra parameters if True
:return: List of instance
Usage:
>>> from owlmixin.samples import Human
>>> humans: TList[Human] = Human.from_yaml_to_list('''
... - id: 1
... name: Tom
... favorites:
... - name: Apple
... - id: 2
... name: John
... favorites:
... - name: Orange
... ''')
>>> humans[0].name
'Tom'
>>> humans[1].name
'John'
>>> humans[0].favorites[0].name
'Apple'
"""
return cls.from_dicts(util.load_yaml(data),
force_snake_case=force_snake_case,
force_cast=force_cast,
restrict=restrict) | [
"def",
"from_yaml_to_list",
"(",
"cls",
",",
"data",
":",
"str",
",",
"force_snake_case",
"=",
"True",
",",
"force_cast",
":",
"bool",
"=",
"False",
",",
"restrict",
":",
"bool",
"=",
"True",
")",
"->",
"TList",
"[",
"T",
"]",
":",
"return",
"cls",
"... | From yaml string to list of instance
:param data: Yaml string
:param force_snake_case: Keys are transformed to snake case in order to compliant PEP8 if True
:param force_cast: Cast forcibly if True
:param restrict: Prohibit extra parameters if True
:return: List of instance
Usage:
>>> from owlmixin.samples import Human
>>> humans: TList[Human] = Human.from_yaml_to_list('''
... - id: 1
... name: Tom
... favorites:
... - name: Apple
... - id: 2
... name: John
... favorites:
... - name: Orange
... ''')
>>> humans[0].name
'Tom'
>>> humans[1].name
'John'
>>> humans[0].favorites[0].name
'Apple' | [
"From",
"yaml",
"string",
"to",
"list",
"of",
"instance"
] | 7c4a042c3008abddc56a8e8e55ae930d276071f5 | https://github.com/tadashi-aikawa/owlmixin/blob/7c4a042c3008abddc56a8e8e55ae930d276071f5/owlmixin/__init__.py#L552-L585 | train | 44,366 |
tadashi-aikawa/owlmixin | owlmixin/__init__.py | OwlMixin.from_yamlf_to_list | def from_yamlf_to_list(cls, fpath: str, encoding: str='utf8',
force_snake_case=True, force_cast: bool=False, restrict: bool=True) -> TList[T]:
"""From yaml file path to list of instance
:param fpath: Yaml file path
:param encoding: Yaml file encoding
:param force_snake_case: Keys are transformed to snake case in order to compliant PEP8 if True
:param force_cast: Cast forcibly if True
:param restrict: Prohibit extra parameters if True
:return: List of instance
"""
return cls.from_dicts(util.load_yamlf(fpath, encoding),
force_snake_case=force_snake_case,
force_cast=force_cast,
restrict=restrict) | python | def from_yamlf_to_list(cls, fpath: str, encoding: str='utf8',
force_snake_case=True, force_cast: bool=False, restrict: bool=True) -> TList[T]:
"""From yaml file path to list of instance
:param fpath: Yaml file path
:param encoding: Yaml file encoding
:param force_snake_case: Keys are transformed to snake case in order to compliant PEP8 if True
:param force_cast: Cast forcibly if True
:param restrict: Prohibit extra parameters if True
:return: List of instance
"""
return cls.from_dicts(util.load_yamlf(fpath, encoding),
force_snake_case=force_snake_case,
force_cast=force_cast,
restrict=restrict) | [
"def",
"from_yamlf_to_list",
"(",
"cls",
",",
"fpath",
":",
"str",
",",
"encoding",
":",
"str",
"=",
"'utf8'",
",",
"force_snake_case",
"=",
"True",
",",
"force_cast",
":",
"bool",
"=",
"False",
",",
"restrict",
":",
"bool",
"=",
"True",
")",
"->",
"TL... | From yaml file path to list of instance
:param fpath: Yaml file path
:param encoding: Yaml file encoding
:param force_snake_case: Keys are transformed to snake case in order to compliant PEP8 if True
:param force_cast: Cast forcibly if True
:param restrict: Prohibit extra parameters if True
:return: List of instance | [
"From",
"yaml",
"file",
"path",
"to",
"list",
"of",
"instance"
] | 7c4a042c3008abddc56a8e8e55ae930d276071f5 | https://github.com/tadashi-aikawa/owlmixin/blob/7c4a042c3008abddc56a8e8e55ae930d276071f5/owlmixin/__init__.py#L588-L602 | train | 44,367 |
tadashi-aikawa/owlmixin | owlmixin/__init__.py | OwlMixin.from_csvf | def from_csvf(cls, fpath: str, fieldnames: Optional[Sequence[str]]=None, encoding: str='utf8',
force_snake_case: bool=True, restrict: bool=True) -> TList[T]:
"""From csv file path to list of instance
:param fpath: Csv file path
:param fieldnames: Specify csv header names if not included in the file
:param encoding: Csv file encoding
:param force_snake_case: Keys are transformed to snake case in order to compliant PEP8 if True
:param restrict: Prohibit extra parameters if True
:return: List of Instance
"""
return cls.from_dicts(util.load_csvf(fpath, fieldnames, encoding),
force_snake_case=force_snake_case,
force_cast=True,
restrict=restrict) | python | def from_csvf(cls, fpath: str, fieldnames: Optional[Sequence[str]]=None, encoding: str='utf8',
force_snake_case: bool=True, restrict: bool=True) -> TList[T]:
"""From csv file path to list of instance
:param fpath: Csv file path
:param fieldnames: Specify csv header names if not included in the file
:param encoding: Csv file encoding
:param force_snake_case: Keys are transformed to snake case in order to compliant PEP8 if True
:param restrict: Prohibit extra parameters if True
:return: List of Instance
"""
return cls.from_dicts(util.load_csvf(fpath, fieldnames, encoding),
force_snake_case=force_snake_case,
force_cast=True,
restrict=restrict) | [
"def",
"from_csvf",
"(",
"cls",
",",
"fpath",
":",
"str",
",",
"fieldnames",
":",
"Optional",
"[",
"Sequence",
"[",
"str",
"]",
"]",
"=",
"None",
",",
"encoding",
":",
"str",
"=",
"'utf8'",
",",
"force_snake_case",
":",
"bool",
"=",
"True",
",",
"res... | From csv file path to list of instance
:param fpath: Csv file path
:param fieldnames: Specify csv header names if not included in the file
:param encoding: Csv file encoding
:param force_snake_case: Keys are transformed to snake case in order to compliant PEP8 if True
:param restrict: Prohibit extra parameters if True
:return: List of Instance | [
"From",
"csv",
"file",
"path",
"to",
"list",
"of",
"instance"
] | 7c4a042c3008abddc56a8e8e55ae930d276071f5 | https://github.com/tadashi-aikawa/owlmixin/blob/7c4a042c3008abddc56a8e8e55ae930d276071f5/owlmixin/__init__.py#L605-L619 | train | 44,368 |
tadashi-aikawa/owlmixin | owlmixin/__init__.py | OwlMixin.from_json_url | def from_json_url(cls, url: str, force_snake_case=True, force_cast: bool=False, restrict: bool=False) -> T:
"""From url which returns json to instance
:param url: Url which returns json
:param force_snake_case: Keys are transformed to snake case in order to compliant PEP8 if True
:param force_cast: Cast forcibly if True
:param restrict: Prohibit extra parameters if True
:return: Instance
"""
return cls.from_dict(util.load_json_url(url),
force_snake_case=force_snake_case,
force_cast=force_cast,
restrict=restrict) | python | def from_json_url(cls, url: str, force_snake_case=True, force_cast: bool=False, restrict: bool=False) -> T:
"""From url which returns json to instance
:param url: Url which returns json
:param force_snake_case: Keys are transformed to snake case in order to compliant PEP8 if True
:param force_cast: Cast forcibly if True
:param restrict: Prohibit extra parameters if True
:return: Instance
"""
return cls.from_dict(util.load_json_url(url),
force_snake_case=force_snake_case,
force_cast=force_cast,
restrict=restrict) | [
"def",
"from_json_url",
"(",
"cls",
",",
"url",
":",
"str",
",",
"force_snake_case",
"=",
"True",
",",
"force_cast",
":",
"bool",
"=",
"False",
",",
"restrict",
":",
"bool",
"=",
"False",
")",
"->",
"T",
":",
"return",
"cls",
".",
"from_dict",
"(",
"... | From url which returns json to instance
:param url: Url which returns json
:param force_snake_case: Keys are transformed to snake case in order to compliant PEP8 if True
:param force_cast: Cast forcibly if True
:param restrict: Prohibit extra parameters if True
:return: Instance | [
"From",
"url",
"which",
"returns",
"json",
"to",
"instance"
] | 7c4a042c3008abddc56a8e8e55ae930d276071f5 | https://github.com/tadashi-aikawa/owlmixin/blob/7c4a042c3008abddc56a8e8e55ae930d276071f5/owlmixin/__init__.py#L622-L634 | train | 44,369 |
openstax/rhaptos.cnxmlutils | rhaptos/cnxmlutils/addsectiontags.py | docHandler.endSections | def endSections(self, level=u'0'):
"""Closes all sections of level >= sectnum. Defaults to closing all open sections"""
iSectionsClosed = self.storeSectionState(level)
self.document.append("</section>\n" * iSectionsClosed) | python | def endSections(self, level=u'0'):
"""Closes all sections of level >= sectnum. Defaults to closing all open sections"""
iSectionsClosed = self.storeSectionState(level)
self.document.append("</section>\n" * iSectionsClosed) | [
"def",
"endSections",
"(",
"self",
",",
"level",
"=",
"u'0'",
")",
":",
"iSectionsClosed",
"=",
"self",
".",
"storeSectionState",
"(",
"level",
")",
"self",
".",
"document",
".",
"append",
"(",
"\"</section>\\n\"",
"*",
"iSectionsClosed",
")"
] | Closes all sections of level >= sectnum. Defaults to closing all open sections | [
"Closes",
"all",
"sections",
"of",
"level",
">",
"=",
"sectnum",
".",
"Defaults",
"to",
"closing",
"all",
"open",
"sections"
] | c32b1a7428dc652e8cd745f3fdf4019a20543649 | https://github.com/openstax/rhaptos.cnxmlutils/blob/c32b1a7428dc652e8cd745f3fdf4019a20543649/rhaptos/cnxmlutils/addsectiontags.py#L176-L180 | train | 44,370 |
tadashi-aikawa/owlmixin | owlmixin/transformers.py | JsonTransformer.to_json | def to_json(self, indent: int=None, ignore_none: bool=True, ignore_empty: bool=False) -> str:
"""From instance to json string
:param indent: Number of indentation
:param ignore_none: Properties which is None are excluded if True
:param ignore_empty: Properties which is empty are excluded if True
:return: Json string
Usage:
>>> from owlmixin.samples import Human
>>> human = Human.from_dict({
... "id": 1,
... "name": "Tom",
... "favorites": [
... {"name": "Apple", "names_by_lang": {"en": "Apple", "de": "Apfel"}},
... {"name": "Orange"}
... ]
... })
>>> human.to_json()
'{"favorites": [{"name": "Apple","names_by_lang": {"de": "Apfel","en": "Apple"}},{"name": "Orange"}],"id": 1,"name": "Tom"}'
"""
return util.dump_json(traverse(self, ignore_none, force_value=True, ignore_empty=ignore_empty), indent) | python | def to_json(self, indent: int=None, ignore_none: bool=True, ignore_empty: bool=False) -> str:
"""From instance to json string
:param indent: Number of indentation
:param ignore_none: Properties which is None are excluded if True
:param ignore_empty: Properties which is empty are excluded if True
:return: Json string
Usage:
>>> from owlmixin.samples import Human
>>> human = Human.from_dict({
... "id": 1,
... "name": "Tom",
... "favorites": [
... {"name": "Apple", "names_by_lang": {"en": "Apple", "de": "Apfel"}},
... {"name": "Orange"}
... ]
... })
>>> human.to_json()
'{"favorites": [{"name": "Apple","names_by_lang": {"de": "Apfel","en": "Apple"}},{"name": "Orange"}],"id": 1,"name": "Tom"}'
"""
return util.dump_json(traverse(self, ignore_none, force_value=True, ignore_empty=ignore_empty), indent) | [
"def",
"to_json",
"(",
"self",
",",
"indent",
":",
"int",
"=",
"None",
",",
"ignore_none",
":",
"bool",
"=",
"True",
",",
"ignore_empty",
":",
"bool",
"=",
"False",
")",
"->",
"str",
":",
"return",
"util",
".",
"dump_json",
"(",
"traverse",
"(",
"sel... | From instance to json string
:param indent: Number of indentation
:param ignore_none: Properties which is None are excluded if True
:param ignore_empty: Properties which is empty are excluded if True
:return: Json string
Usage:
>>> from owlmixin.samples import Human
>>> human = Human.from_dict({
... "id": 1,
... "name": "Tom",
... "favorites": [
... {"name": "Apple", "names_by_lang": {"en": "Apple", "de": "Apfel"}},
... {"name": "Orange"}
... ]
... })
>>> human.to_json()
'{"favorites": [{"name": "Apple","names_by_lang": {"de": "Apfel","en": "Apple"}},{"name": "Orange"}],"id": 1,"name": "Tom"}' | [
"From",
"instance",
"to",
"json",
"string"
] | 7c4a042c3008abddc56a8e8e55ae930d276071f5 | https://github.com/tadashi-aikawa/owlmixin/blob/7c4a042c3008abddc56a8e8e55ae930d276071f5/owlmixin/transformers.py#L194-L216 | train | 44,371 |
tadashi-aikawa/owlmixin | owlmixin/transformers.py | JsonTransformer.to_jsonf | def to_jsonf(self, fpath: str, encoding: str='utf8', indent: int=None, ignore_none: bool=True, ignore_empty: bool=False) -> str:
"""From instance to json file
:param fpath: Json file path
:param encoding: Json file encoding
:param indent: Number of indentation
:param ignore_none: Properties which is None are excluded if True
:param ignore_empty: Properties which is empty are excluded if True
:return: Json file path
"""
return util.save_jsonf(traverse(self, ignore_none, force_value=True, ignore_empty=ignore_empty), fpath, encoding, indent) | python | def to_jsonf(self, fpath: str, encoding: str='utf8', indent: int=None, ignore_none: bool=True, ignore_empty: bool=False) -> str:
"""From instance to json file
:param fpath: Json file path
:param encoding: Json file encoding
:param indent: Number of indentation
:param ignore_none: Properties which is None are excluded if True
:param ignore_empty: Properties which is empty are excluded if True
:return: Json file path
"""
return util.save_jsonf(traverse(self, ignore_none, force_value=True, ignore_empty=ignore_empty), fpath, encoding, indent) | [
"def",
"to_jsonf",
"(",
"self",
",",
"fpath",
":",
"str",
",",
"encoding",
":",
"str",
"=",
"'utf8'",
",",
"indent",
":",
"int",
"=",
"None",
",",
"ignore_none",
":",
"bool",
"=",
"True",
",",
"ignore_empty",
":",
"bool",
"=",
"False",
")",
"->",
"... | From instance to json file
:param fpath: Json file path
:param encoding: Json file encoding
:param indent: Number of indentation
:param ignore_none: Properties which is None are excluded if True
:param ignore_empty: Properties which is empty are excluded if True
:return: Json file path | [
"From",
"instance",
"to",
"json",
"file"
] | 7c4a042c3008abddc56a8e8e55ae930d276071f5 | https://github.com/tadashi-aikawa/owlmixin/blob/7c4a042c3008abddc56a8e8e55ae930d276071f5/owlmixin/transformers.py#L218-L228 | train | 44,372 |
tadashi-aikawa/owlmixin | owlmixin/transformers.py | JsonTransformer.to_pretty_json | def to_pretty_json(self, ignore_none: bool=True, ignore_empty: bool=False) -> str:
"""From instance to pretty json string
:param ignore_none: Properties which is None are excluded if True
:param ignore_empty: Properties which is empty are excluded if True
:return: Json string
Usage:
>>> from owlmixin.samples import Human
>>> human = Human.from_dict({
... "id": 1,
... "name": "Tom",
... "favorites": [
... {"name": "Apple", "names_by_lang": {"en": "Apple", "de": "Apfel"}},
... {"name": "Orange"}
... ]
... })
>>> print(human.to_pretty_json())
{
"favorites": [
{
"name": "Apple",
"names_by_lang": {
"de": "Apfel",
"en": "Apple"
}
},
{
"name": "Orange"
}
],
"id": 1,
"name": "Tom"
}
"""
return self.to_json(4, ignore_none, ignore_empty) | python | def to_pretty_json(self, ignore_none: bool=True, ignore_empty: bool=False) -> str:
"""From instance to pretty json string
:param ignore_none: Properties which is None are excluded if True
:param ignore_empty: Properties which is empty are excluded if True
:return: Json string
Usage:
>>> from owlmixin.samples import Human
>>> human = Human.from_dict({
... "id": 1,
... "name": "Tom",
... "favorites": [
... {"name": "Apple", "names_by_lang": {"en": "Apple", "de": "Apfel"}},
... {"name": "Orange"}
... ]
... })
>>> print(human.to_pretty_json())
{
"favorites": [
{
"name": "Apple",
"names_by_lang": {
"de": "Apfel",
"en": "Apple"
}
},
{
"name": "Orange"
}
],
"id": 1,
"name": "Tom"
}
"""
return self.to_json(4, ignore_none, ignore_empty) | [
"def",
"to_pretty_json",
"(",
"self",
",",
"ignore_none",
":",
"bool",
"=",
"True",
",",
"ignore_empty",
":",
"bool",
"=",
"False",
")",
"->",
"str",
":",
"return",
"self",
".",
"to_json",
"(",
"4",
",",
"ignore_none",
",",
"ignore_empty",
")"
] | From instance to pretty json string
:param ignore_none: Properties which is None are excluded if True
:param ignore_empty: Properties which is empty are excluded if True
:return: Json string
Usage:
>>> from owlmixin.samples import Human
>>> human = Human.from_dict({
... "id": 1,
... "name": "Tom",
... "favorites": [
... {"name": "Apple", "names_by_lang": {"en": "Apple", "de": "Apfel"}},
... {"name": "Orange"}
... ]
... })
>>> print(human.to_pretty_json())
{
"favorites": [
{
"name": "Apple",
"names_by_lang": {
"de": "Apfel",
"en": "Apple"
}
},
{
"name": "Orange"
}
],
"id": 1,
"name": "Tom"
} | [
"From",
"instance",
"to",
"pretty",
"json",
"string"
] | 7c4a042c3008abddc56a8e8e55ae930d276071f5 | https://github.com/tadashi-aikawa/owlmixin/blob/7c4a042c3008abddc56a8e8e55ae930d276071f5/owlmixin/transformers.py#L230-L266 | train | 44,373 |
tadashi-aikawa/owlmixin | owlmixin/transformers.py | YamlTransformer.to_yaml | def to_yaml(self, ignore_none: bool=True, ignore_empty: bool=False) -> str:
"""From instance to yaml string
:param ignore_none: Properties which is None are excluded if True
:param ignore_empty: Properties which is empty are excluded if True
:return: Yaml string
Usage:
>>> from owlmixin.samples import Human
>>> human = Human.from_dict({
... "id": 1,
... "name": "Tom",
... "favorites": [
... {"name": "Apple", "names_by_lang": {"en": "Apple", "de": "Apfel"}},
... {"name": "Orange"}
... ]
... })
>>> print(human.to_yaml())
favorites:
- name: Apple
names_by_lang:
de: Apfel
en: Apple
- name: Orange
id: 1
name: Tom
<BLANKLINE>
"""
return util.dump_yaml(traverse(self, ignore_none, force_value=True, ignore_empty=ignore_empty)) | python | def to_yaml(self, ignore_none: bool=True, ignore_empty: bool=False) -> str:
"""From instance to yaml string
:param ignore_none: Properties which is None are excluded if True
:param ignore_empty: Properties which is empty are excluded if True
:return: Yaml string
Usage:
>>> from owlmixin.samples import Human
>>> human = Human.from_dict({
... "id": 1,
... "name": "Tom",
... "favorites": [
... {"name": "Apple", "names_by_lang": {"en": "Apple", "de": "Apfel"}},
... {"name": "Orange"}
... ]
... })
>>> print(human.to_yaml())
favorites:
- name: Apple
names_by_lang:
de: Apfel
en: Apple
- name: Orange
id: 1
name: Tom
<BLANKLINE>
"""
return util.dump_yaml(traverse(self, ignore_none, force_value=True, ignore_empty=ignore_empty)) | [
"def",
"to_yaml",
"(",
"self",
",",
"ignore_none",
":",
"bool",
"=",
"True",
",",
"ignore_empty",
":",
"bool",
"=",
"False",
")",
"->",
"str",
":",
"return",
"util",
".",
"dump_yaml",
"(",
"traverse",
"(",
"self",
",",
"ignore_none",
",",
"force_value",
... | From instance to yaml string
:param ignore_none: Properties which is None are excluded if True
:param ignore_empty: Properties which is empty are excluded if True
:return: Yaml string
Usage:
>>> from owlmixin.samples import Human
>>> human = Human.from_dict({
... "id": 1,
... "name": "Tom",
... "favorites": [
... {"name": "Apple", "names_by_lang": {"en": "Apple", "de": "Apfel"}},
... {"name": "Orange"}
... ]
... })
>>> print(human.to_yaml())
favorites:
- name: Apple
names_by_lang:
de: Apfel
en: Apple
- name: Orange
id: 1
name: Tom
<BLANKLINE> | [
"From",
"instance",
"to",
"yaml",
"string"
] | 7c4a042c3008abddc56a8e8e55ae930d276071f5 | https://github.com/tadashi-aikawa/owlmixin/blob/7c4a042c3008abddc56a8e8e55ae930d276071f5/owlmixin/transformers.py#L273-L302 | train | 44,374 |
openstax/rhaptos.cnxmlutils | rhaptos/cnxmlutils/utils.py | _pre_tidy | def _pre_tidy(html):
""" This method transforms a few things before tidy runs. When we get rid
of tidy, this can go away. """
tree = etree.fromstring(html, etree.HTMLParser())
for el in tree.xpath('//u'):
el.tag = 'em'
c = el.attrib.get('class', '').split()
if 'underline' not in c:
c.append('underline')
el.attrib['class'] = ' '.join(c)
return tohtml(tree) | python | def _pre_tidy(html):
""" This method transforms a few things before tidy runs. When we get rid
of tidy, this can go away. """
tree = etree.fromstring(html, etree.HTMLParser())
for el in tree.xpath('//u'):
el.tag = 'em'
c = el.attrib.get('class', '').split()
if 'underline' not in c:
c.append('underline')
el.attrib['class'] = ' '.join(c)
return tohtml(tree) | [
"def",
"_pre_tidy",
"(",
"html",
")",
":",
"tree",
"=",
"etree",
".",
"fromstring",
"(",
"html",
",",
"etree",
".",
"HTMLParser",
"(",
")",
")",
"for",
"el",
"in",
"tree",
".",
"xpath",
"(",
"'//u'",
")",
":",
"el",
".",
"tag",
"=",
"'em'",
"c",
... | This method transforms a few things before tidy runs. When we get rid
of tidy, this can go away. | [
"This",
"method",
"transforms",
"a",
"few",
"things",
"before",
"tidy",
"runs",
".",
"When",
"we",
"get",
"rid",
"of",
"tidy",
"this",
"can",
"go",
"away",
"."
] | c32b1a7428dc652e8cd745f3fdf4019a20543649 | https://github.com/openstax/rhaptos.cnxmlutils/blob/c32b1a7428dc652e8cd745f3fdf4019a20543649/rhaptos/cnxmlutils/utils.py#L43-L54 | train | 44,375 |
openstax/rhaptos.cnxmlutils | rhaptos/cnxmlutils/utils.py | _post_tidy | def _post_tidy(html):
""" This method transforms post tidy. Will go away when tidy goes away. """
tree = etree.fromstring(html)
ems = tree.xpath(
"//xh:em[@class='underline']|//xh:em[contains(@class, ' underline ')]",
namespaces={'xh': 'http://www.w3.org/1999/xhtml'})
for el in ems:
c = el.attrib.get('class', '').split()
c.remove('underline')
el.tag = '{http://www.w3.org/1999/xhtml}u'
if c:
el.attrib['class'] = ' '.join(c)
elif 'class' in el.attrib:
del(el.attrib['class'])
return tree | python | def _post_tidy(html):
""" This method transforms post tidy. Will go away when tidy goes away. """
tree = etree.fromstring(html)
ems = tree.xpath(
"//xh:em[@class='underline']|//xh:em[contains(@class, ' underline ')]",
namespaces={'xh': 'http://www.w3.org/1999/xhtml'})
for el in ems:
c = el.attrib.get('class', '').split()
c.remove('underline')
el.tag = '{http://www.w3.org/1999/xhtml}u'
if c:
el.attrib['class'] = ' '.join(c)
elif 'class' in el.attrib:
del(el.attrib['class'])
return tree | [
"def",
"_post_tidy",
"(",
"html",
")",
":",
"tree",
"=",
"etree",
".",
"fromstring",
"(",
"html",
")",
"ems",
"=",
"tree",
".",
"xpath",
"(",
"\"//xh:em[@class='underline']|//xh:em[contains(@class, ' underline ')]\"",
",",
"namespaces",
"=",
"{",
"'xh'",
":",
"'... | This method transforms post tidy. Will go away when tidy goes away. | [
"This",
"method",
"transforms",
"post",
"tidy",
".",
"Will",
"go",
"away",
"when",
"tidy",
"goes",
"away",
"."
] | c32b1a7428dc652e8cd745f3fdf4019a20543649 | https://github.com/openstax/rhaptos.cnxmlutils/blob/c32b1a7428dc652e8cd745f3fdf4019a20543649/rhaptos/cnxmlutils/utils.py#L57-L72 | train | 44,376 |
openstax/rhaptos.cnxmlutils | rhaptos/cnxmlutils/utils.py | _transform | def _transform(xsl_filename, xml, **kwargs):
"""Transforms the xml using the specifiec xsl file."""
xslt = _make_xsl(xsl_filename)
xml = xslt(xml, **kwargs)
return xml | python | def _transform(xsl_filename, xml, **kwargs):
"""Transforms the xml using the specifiec xsl file."""
xslt = _make_xsl(xsl_filename)
xml = xslt(xml, **kwargs)
return xml | [
"def",
"_transform",
"(",
"xsl_filename",
",",
"xml",
",",
"*",
"*",
"kwargs",
")",
":",
"xslt",
"=",
"_make_xsl",
"(",
"xsl_filename",
")",
"xml",
"=",
"xslt",
"(",
"xml",
",",
"*",
"*",
"kwargs",
")",
"return",
"xml"
] | Transforms the xml using the specifiec xsl file. | [
"Transforms",
"the",
"xml",
"using",
"the",
"specifiec",
"xsl",
"file",
"."
] | c32b1a7428dc652e8cd745f3fdf4019a20543649 | https://github.com/openstax/rhaptos.cnxmlutils/blob/c32b1a7428dc652e8cd745f3fdf4019a20543649/rhaptos/cnxmlutils/utils.py#L187-L191 | train | 44,377 |
openstax/rhaptos.cnxmlutils | rhaptos/cnxmlutils/utils.py | _unescape_math | def _unescape_math(xml):
"""Unescapes Math from Mathjax to MathML."""
xpath_math_script = etree.XPath(
'//x:script[@type="math/mml"]',
namespaces={'x': 'http://www.w3.org/1999/xhtml'})
math_script_list = xpath_math_script(xml)
for mathscript in math_script_list:
math = mathscript.text
# some browsers double escape like e.g. Firefox
math = unescape(unescape(math))
mathscript.clear()
mathscript.set('type', 'math/mml')
new_math = etree.fromstring(math)
mathscript.append(new_math)
return xml | python | def _unescape_math(xml):
"""Unescapes Math from Mathjax to MathML."""
xpath_math_script = etree.XPath(
'//x:script[@type="math/mml"]',
namespaces={'x': 'http://www.w3.org/1999/xhtml'})
math_script_list = xpath_math_script(xml)
for mathscript in math_script_list:
math = mathscript.text
# some browsers double escape like e.g. Firefox
math = unescape(unescape(math))
mathscript.clear()
mathscript.set('type', 'math/mml')
new_math = etree.fromstring(math)
mathscript.append(new_math)
return xml | [
"def",
"_unescape_math",
"(",
"xml",
")",
":",
"xpath_math_script",
"=",
"etree",
".",
"XPath",
"(",
"'//x:script[@type=\"math/mml\"]'",
",",
"namespaces",
"=",
"{",
"'x'",
":",
"'http://www.w3.org/1999/xhtml'",
"}",
")",
"math_script_list",
"=",
"xpath_math_script",
... | Unescapes Math from Mathjax to MathML. | [
"Unescapes",
"Math",
"from",
"Mathjax",
"to",
"MathML",
"."
] | c32b1a7428dc652e8cd745f3fdf4019a20543649 | https://github.com/openstax/rhaptos.cnxmlutils/blob/c32b1a7428dc652e8cd745f3fdf4019a20543649/rhaptos/cnxmlutils/utils.py#L194-L208 | train | 44,378 |
openstax/rhaptos.cnxmlutils | rhaptos/cnxmlutils/utils.py | cnxml_to_html | def cnxml_to_html(cnxml_source):
"""Transform the CNXML source to HTML"""
source = _string2io(cnxml_source)
xml = etree.parse(source)
# Run the CNXML to HTML transform
xml = _transform('cnxml-to-html5.xsl', xml,
version='"{}"'.format(version))
xml = XHTML_MODULE_BODY_XPATH(xml)
return etree.tostring(xml[0]) | python | def cnxml_to_html(cnxml_source):
"""Transform the CNXML source to HTML"""
source = _string2io(cnxml_source)
xml = etree.parse(source)
# Run the CNXML to HTML transform
xml = _transform('cnxml-to-html5.xsl', xml,
version='"{}"'.format(version))
xml = XHTML_MODULE_BODY_XPATH(xml)
return etree.tostring(xml[0]) | [
"def",
"cnxml_to_html",
"(",
"cnxml_source",
")",
":",
"source",
"=",
"_string2io",
"(",
"cnxml_source",
")",
"xml",
"=",
"etree",
".",
"parse",
"(",
"source",
")",
"# Run the CNXML to HTML transform",
"xml",
"=",
"_transform",
"(",
"'cnxml-to-html5.xsl'",
",",
... | Transform the CNXML source to HTML | [
"Transform",
"the",
"CNXML",
"source",
"to",
"HTML"
] | c32b1a7428dc652e8cd745f3fdf4019a20543649 | https://github.com/openstax/rhaptos.cnxmlutils/blob/c32b1a7428dc652e8cd745f3fdf4019a20543649/rhaptos/cnxmlutils/utils.py#L211-L219 | train | 44,379 |
openstax/rhaptos.cnxmlutils | rhaptos/cnxmlutils/utils.py | aloha_to_etree | def aloha_to_etree(html_source):
""" Converts HTML5 from Aloha editor output to a lxml etree. """
xml = _tidy2xhtml5(html_source)
for i, transform in enumerate(ALOHA2HTML_TRANSFORM_PIPELINE):
xml = transform(xml)
return xml | python | def aloha_to_etree(html_source):
""" Converts HTML5 from Aloha editor output to a lxml etree. """
xml = _tidy2xhtml5(html_source)
for i, transform in enumerate(ALOHA2HTML_TRANSFORM_PIPELINE):
xml = transform(xml)
return xml | [
"def",
"aloha_to_etree",
"(",
"html_source",
")",
":",
"xml",
"=",
"_tidy2xhtml5",
"(",
"html_source",
")",
"for",
"i",
",",
"transform",
"in",
"enumerate",
"(",
"ALOHA2HTML_TRANSFORM_PIPELINE",
")",
":",
"xml",
"=",
"transform",
"(",
"xml",
")",
"return",
"... | Converts HTML5 from Aloha editor output to a lxml etree. | [
"Converts",
"HTML5",
"from",
"Aloha",
"editor",
"output",
"to",
"a",
"lxml",
"etree",
"."
] | c32b1a7428dc652e8cd745f3fdf4019a20543649 | https://github.com/openstax/rhaptos.cnxmlutils/blob/c32b1a7428dc652e8cd745f3fdf4019a20543649/rhaptos/cnxmlutils/utils.py#L233-L238 | train | 44,380 |
openstax/rhaptos.cnxmlutils | rhaptos/cnxmlutils/utils.py | aloha_to_html | def aloha_to_html(html_source):
"""Converts HTML5 from Aloha to a more structured HTML5"""
xml = aloha_to_etree(html_source)
return etree.tostring(xml, pretty_print=True) | python | def aloha_to_html(html_source):
"""Converts HTML5 from Aloha to a more structured HTML5"""
xml = aloha_to_etree(html_source)
return etree.tostring(xml, pretty_print=True) | [
"def",
"aloha_to_html",
"(",
"html_source",
")",
":",
"xml",
"=",
"aloha_to_etree",
"(",
"html_source",
")",
"return",
"etree",
".",
"tostring",
"(",
"xml",
",",
"pretty_print",
"=",
"True",
")"
] | Converts HTML5 from Aloha to a more structured HTML5 | [
"Converts",
"HTML5",
"from",
"Aloha",
"to",
"a",
"more",
"structured",
"HTML5"
] | c32b1a7428dc652e8cd745f3fdf4019a20543649 | https://github.com/openstax/rhaptos.cnxmlutils/blob/c32b1a7428dc652e8cd745f3fdf4019a20543649/rhaptos/cnxmlutils/utils.py#L241-L244 | train | 44,381 |
openstax/rhaptos.cnxmlutils | rhaptos/cnxmlutils/utils.py | html_to_cnxml | def html_to_cnxml(html_source, cnxml_source):
"""Transform the HTML to CNXML. We need the original CNXML content in
order to preserve the metadata in the CNXML document.
"""
source = _string2io(html_source)
xml = etree.parse(source)
cnxml = etree.parse(_string2io(cnxml_source))
# Run the HTML to CNXML transform on it
xml = _transform('html5-to-cnxml.xsl', xml)
# Replace the original content element with the transformed one.
namespaces = {'c': 'http://cnx.rice.edu/cnxml'}
xpath = etree.XPath('//c:content', namespaces=namespaces)
replaceable_node = xpath(cnxml)[0]
replaceable_node.getparent().replace(replaceable_node, xml.getroot())
# Set the content into the existing cnxml source
return etree.tostring(cnxml) | python | def html_to_cnxml(html_source, cnxml_source):
"""Transform the HTML to CNXML. We need the original CNXML content in
order to preserve the metadata in the CNXML document.
"""
source = _string2io(html_source)
xml = etree.parse(source)
cnxml = etree.parse(_string2io(cnxml_source))
# Run the HTML to CNXML transform on it
xml = _transform('html5-to-cnxml.xsl', xml)
# Replace the original content element with the transformed one.
namespaces = {'c': 'http://cnx.rice.edu/cnxml'}
xpath = etree.XPath('//c:content', namespaces=namespaces)
replaceable_node = xpath(cnxml)[0]
replaceable_node.getparent().replace(replaceable_node, xml.getroot())
# Set the content into the existing cnxml source
return etree.tostring(cnxml) | [
"def",
"html_to_cnxml",
"(",
"html_source",
",",
"cnxml_source",
")",
":",
"source",
"=",
"_string2io",
"(",
"html_source",
")",
"xml",
"=",
"etree",
".",
"parse",
"(",
"source",
")",
"cnxml",
"=",
"etree",
".",
"parse",
"(",
"_string2io",
"(",
"cnxml_sour... | Transform the HTML to CNXML. We need the original CNXML content in
order to preserve the metadata in the CNXML document. | [
"Transform",
"the",
"HTML",
"to",
"CNXML",
".",
"We",
"need",
"the",
"original",
"CNXML",
"content",
"in",
"order",
"to",
"preserve",
"the",
"metadata",
"in",
"the",
"CNXML",
"document",
"."
] | c32b1a7428dc652e8cd745f3fdf4019a20543649 | https://github.com/openstax/rhaptos.cnxmlutils/blob/c32b1a7428dc652e8cd745f3fdf4019a20543649/rhaptos/cnxmlutils/utils.py#L247-L262 | train | 44,382 |
openstax/rhaptos.cnxmlutils | rhaptos/cnxmlutils/symbols.py | replace | def replace(text):
"""Replace both the hex and decimal versions of symbols in an XML string"""
for hex, value in UNICODE_DICTIONARY.items():
num = int(hex[3:-1], 16)
#uni = unichr(num)
decimal = '&#' + str(num) + ';'
for key in [ hex, decimal ]: #uni
text = text.replace(key, value)
return text | python | def replace(text):
"""Replace both the hex and decimal versions of symbols in an XML string"""
for hex, value in UNICODE_DICTIONARY.items():
num = int(hex[3:-1], 16)
#uni = unichr(num)
decimal = '&#' + str(num) + ';'
for key in [ hex, decimal ]: #uni
text = text.replace(key, value)
return text | [
"def",
"replace",
"(",
"text",
")",
":",
"for",
"hex",
",",
"value",
"in",
"UNICODE_DICTIONARY",
".",
"items",
"(",
")",
":",
"num",
"=",
"int",
"(",
"hex",
"[",
"3",
":",
"-",
"1",
"]",
",",
"16",
")",
"#uni = unichr(num)",
"decimal",
"=",
"'&#'",... | Replace both the hex and decimal versions of symbols in an XML string | [
"Replace",
"both",
"the",
"hex",
"and",
"decimal",
"versions",
"of",
"symbols",
"in",
"an",
"XML",
"string"
] | c32b1a7428dc652e8cd745f3fdf4019a20543649 | https://github.com/openstax/rhaptos.cnxmlutils/blob/c32b1a7428dc652e8cd745f3fdf4019a20543649/rhaptos/cnxmlutils/symbols.py#L219-L227 | train | 44,383 |
openstax/rhaptos.cnxmlutils | rhaptos/cnxmlutils/odt2cnxml.py | writeXMLFile | def writeXMLFile(filename, content):
""" Used only for debugging to write out intermediate files"""
xmlfile = open(filename, 'w')
# pretty print
content = etree.tostring(content, pretty_print=True)
xmlfile.write(content)
xmlfile.close() | python | def writeXMLFile(filename, content):
""" Used only for debugging to write out intermediate files"""
xmlfile = open(filename, 'w')
# pretty print
content = etree.tostring(content, pretty_print=True)
xmlfile.write(content)
xmlfile.close() | [
"def",
"writeXMLFile",
"(",
"filename",
",",
"content",
")",
":",
"xmlfile",
"=",
"open",
"(",
"filename",
",",
"'w'",
")",
"# pretty print",
"content",
"=",
"etree",
".",
"tostring",
"(",
"content",
",",
"pretty_print",
"=",
"True",
")",
"xmlfile",
".",
... | Used only for debugging to write out intermediate files | [
"Used",
"only",
"for",
"debugging",
"to",
"write",
"out",
"intermediate",
"files"
] | c32b1a7428dc652e8cd745f3fdf4019a20543649 | https://github.com/openstax/rhaptos.cnxmlutils/blob/c32b1a7428dc652e8cd745f3fdf4019a20543649/rhaptos/cnxmlutils/odt2cnxml.py#L56-L62 | train | 44,384 |
Autodesk/aomi | aomi/seed_action.py | auto_thaw | def auto_thaw(vault_client, opt):
"""Will thaw into a temporary location"""
icefile = opt.thaw_from
if not os.path.exists(icefile):
raise aomi.exceptions.IceFile("%s missing" % icefile)
thaw(vault_client, icefile, opt)
return opt | python | def auto_thaw(vault_client, opt):
"""Will thaw into a temporary location"""
icefile = opt.thaw_from
if not os.path.exists(icefile):
raise aomi.exceptions.IceFile("%s missing" % icefile)
thaw(vault_client, icefile, opt)
return opt | [
"def",
"auto_thaw",
"(",
"vault_client",
",",
"opt",
")",
":",
"icefile",
"=",
"opt",
".",
"thaw_from",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"icefile",
")",
":",
"raise",
"aomi",
".",
"exceptions",
".",
"IceFile",
"(",
"\"%s missing\"",
... | Will thaw into a temporary location | [
"Will",
"thaw",
"into",
"a",
"temporary",
"location"
] | 84da2dfb0424837adf9c4ddc1aa352e942bb7a4a | https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/seed_action.py#L26-L33 | train | 44,385 |
Autodesk/aomi | aomi/seed_action.py | seed | def seed(vault_client, opt):
"""Will provision vault based on the definition within a Secretfile"""
if opt.thaw_from:
opt.secrets = tempfile.mkdtemp('aomi-thaw')
auto_thaw(vault_client, opt)
Context.load(get_secretfile(opt), opt) \
.fetch(vault_client) \
.sync(vault_client, opt)
if opt.thaw_from:
rmtree(opt.secrets) | python | def seed(vault_client, opt):
"""Will provision vault based on the definition within a Secretfile"""
if opt.thaw_from:
opt.secrets = tempfile.mkdtemp('aomi-thaw')
auto_thaw(vault_client, opt)
Context.load(get_secretfile(opt), opt) \
.fetch(vault_client) \
.sync(vault_client, opt)
if opt.thaw_from:
rmtree(opt.secrets) | [
"def",
"seed",
"(",
"vault_client",
",",
"opt",
")",
":",
"if",
"opt",
".",
"thaw_from",
":",
"opt",
".",
"secrets",
"=",
"tempfile",
".",
"mkdtemp",
"(",
"'aomi-thaw'",
")",
"auto_thaw",
"(",
"vault_client",
",",
"opt",
")",
"Context",
".",
"load",
"(... | Will provision vault based on the definition within a Secretfile | [
"Will",
"provision",
"vault",
"based",
"on",
"the",
"definition",
"within",
"a",
"Secretfile"
] | 84da2dfb0424837adf9c4ddc1aa352e942bb7a4a | https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/seed_action.py#L36-L47 | train | 44,386 |
Autodesk/aomi | aomi/seed_action.py | render | def render(directory, opt):
"""Render any provided template. This includes the Secretfile,
Vault policies, and inline AWS roles"""
if not os.path.exists(directory) and not os.path.isdir(directory):
os.mkdir(directory)
a_secretfile = render_secretfile(opt)
s_path = "%s/Secretfile" % directory
LOG.debug("writing Secretfile to %s", s_path)
open(s_path, 'w').write(a_secretfile)
ctx = Context.load(yaml.safe_load(a_secretfile), opt)
for resource in ctx.resources():
if not resource.present:
continue
if issubclass(type(resource), Policy):
if not os.path.isdir("%s/policy" % directory):
os.mkdir("%s/policy" % directory)
filename = "%s/policy/%s" % (directory, resource.path)
open(filename, 'w').write(resource.obj())
LOG.debug("writing %s to %s", resource, filename)
elif issubclass(type(resource), AWSRole):
if not os.path.isdir("%s/aws" % directory):
os.mkdir("%s/aws" % directory)
if 'policy' in resource.obj():
filename = "%s/aws/%s" % (directory,
os.path.basename(resource.path))
r_obj = resource.obj()
if 'policy' in r_obj:
LOG.debug("writing %s to %s", resource, filename)
open(filename, 'w').write(r_obj['policy']) | python | def render(directory, opt):
"""Render any provided template. This includes the Secretfile,
Vault policies, and inline AWS roles"""
if not os.path.exists(directory) and not os.path.isdir(directory):
os.mkdir(directory)
a_secretfile = render_secretfile(opt)
s_path = "%s/Secretfile" % directory
LOG.debug("writing Secretfile to %s", s_path)
open(s_path, 'w').write(a_secretfile)
ctx = Context.load(yaml.safe_load(a_secretfile), opt)
for resource in ctx.resources():
if not resource.present:
continue
if issubclass(type(resource), Policy):
if not os.path.isdir("%s/policy" % directory):
os.mkdir("%s/policy" % directory)
filename = "%s/policy/%s" % (directory, resource.path)
open(filename, 'w').write(resource.obj())
LOG.debug("writing %s to %s", resource, filename)
elif issubclass(type(resource), AWSRole):
if not os.path.isdir("%s/aws" % directory):
os.mkdir("%s/aws" % directory)
if 'policy' in resource.obj():
filename = "%s/aws/%s" % (directory,
os.path.basename(resource.path))
r_obj = resource.obj()
if 'policy' in r_obj:
LOG.debug("writing %s to %s", resource, filename)
open(filename, 'w').write(r_obj['policy']) | [
"def",
"render",
"(",
"directory",
",",
"opt",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"directory",
")",
"and",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"directory",
")",
":",
"os",
".",
"mkdir",
"(",
"directory",
")",
"... | Render any provided template. This includes the Secretfile,
Vault policies, and inline AWS roles | [
"Render",
"any",
"provided",
"template",
".",
"This",
"includes",
"the",
"Secretfile",
"Vault",
"policies",
"and",
"inline",
"AWS",
"roles"
] | 84da2dfb0424837adf9c4ddc1aa352e942bb7a4a | https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/seed_action.py#L50-L82 | train | 44,387 |
Autodesk/aomi | aomi/seed_action.py | export | def export(vault_client, opt):
"""Export contents of a Secretfile from the Vault server
into a specified directory."""
ctx = Context.load(get_secretfile(opt), opt) \
.fetch(vault_client)
for resource in ctx.resources():
resource.export(opt.directory) | python | def export(vault_client, opt):
"""Export contents of a Secretfile from the Vault server
into a specified directory."""
ctx = Context.load(get_secretfile(opt), opt) \
.fetch(vault_client)
for resource in ctx.resources():
resource.export(opt.directory) | [
"def",
"export",
"(",
"vault_client",
",",
"opt",
")",
":",
"ctx",
"=",
"Context",
".",
"load",
"(",
"get_secretfile",
"(",
"opt",
")",
",",
"opt",
")",
".",
"fetch",
"(",
"vault_client",
")",
"for",
"resource",
"in",
"ctx",
".",
"resources",
"(",
")... | Export contents of a Secretfile from the Vault server
into a specified directory. | [
"Export",
"contents",
"of",
"a",
"Secretfile",
"from",
"the",
"Vault",
"server",
"into",
"a",
"specified",
"directory",
"."
] | 84da2dfb0424837adf9c4ddc1aa352e942bb7a4a | https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/seed_action.py#L85-L91 | train | 44,388 |
Autodesk/aomi | aomi/seed_action.py | maybe_colored | def maybe_colored(msg, color, opt):
"""Maybe it will render in color maybe it will not!"""
if opt.monochrome:
return msg
return colored(msg, color) | python | def maybe_colored(msg, color, opt):
"""Maybe it will render in color maybe it will not!"""
if opt.monochrome:
return msg
return colored(msg, color) | [
"def",
"maybe_colored",
"(",
"msg",
",",
"color",
",",
"opt",
")",
":",
"if",
"opt",
".",
"monochrome",
":",
"return",
"msg",
"return",
"colored",
"(",
"msg",
",",
"color",
")"
] | Maybe it will render in color maybe it will not! | [
"Maybe",
"it",
"will",
"render",
"in",
"color",
"maybe",
"it",
"will",
"not!"
] | 84da2dfb0424837adf9c4ddc1aa352e942bb7a4a | https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/seed_action.py#L94-L99 | train | 44,389 |
Autodesk/aomi | aomi/seed_action.py | details_dict | def details_dict(obj, existing, ignore_missing, opt):
"""Output the changes, if any, for a dict"""
existing = dict_unicodeize(existing)
obj = dict_unicodeize(obj)
for ex_k, ex_v in iteritems(existing):
new_value = normalize_val(obj.get(ex_k))
og_value = normalize_val(ex_v)
if ex_k in obj and og_value != new_value:
print(maybe_colored("-- %s: %s" % (ex_k, og_value),
'red', opt))
print(maybe_colored("++ %s: %s" % (ex_k, new_value),
'green', opt))
if (not ignore_missing) and (ex_k not in obj):
print(maybe_colored("-- %s: %s" % (ex_k, og_value),
'red', opt))
for ob_k, ob_v in iteritems(obj):
val = normalize_val(ob_v)
if ob_k not in existing:
print(maybe_colored("++ %s: %s" % (ob_k, val),
'green', opt))
return | python | def details_dict(obj, existing, ignore_missing, opt):
"""Output the changes, if any, for a dict"""
existing = dict_unicodeize(existing)
obj = dict_unicodeize(obj)
for ex_k, ex_v in iteritems(existing):
new_value = normalize_val(obj.get(ex_k))
og_value = normalize_val(ex_v)
if ex_k in obj and og_value != new_value:
print(maybe_colored("-- %s: %s" % (ex_k, og_value),
'red', opt))
print(maybe_colored("++ %s: %s" % (ex_k, new_value),
'green', opt))
if (not ignore_missing) and (ex_k not in obj):
print(maybe_colored("-- %s: %s" % (ex_k, og_value),
'red', opt))
for ob_k, ob_v in iteritems(obj):
val = normalize_val(ob_v)
if ob_k not in existing:
print(maybe_colored("++ %s: %s" % (ob_k, val),
'green', opt))
return | [
"def",
"details_dict",
"(",
"obj",
",",
"existing",
",",
"ignore_missing",
",",
"opt",
")",
":",
"existing",
"=",
"dict_unicodeize",
"(",
"existing",
")",
"obj",
"=",
"dict_unicodeize",
"(",
"obj",
")",
"for",
"ex_k",
",",
"ex_v",
"in",
"iteritems",
"(",
... | Output the changes, if any, for a dict | [
"Output",
"the",
"changes",
"if",
"any",
"for",
"a",
"dict"
] | 84da2dfb0424837adf9c4ddc1aa352e942bb7a4a | https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/seed_action.py#L115-L138 | train | 44,390 |
Autodesk/aomi | aomi/seed_action.py | maybe_details | def maybe_details(resource, opt):
"""At the first level of verbosity this will print out detailed
change information on for the specified Vault resource"""
if opt.verbose == 0:
return
if not resource.present:
return
obj = None
existing = None
if isinstance(resource, Resource):
obj = resource.obj()
existing = resource.existing
elif isinstance(resource, VaultBackend):
obj = resource.config
existing = resource.existing
if not obj:
return
if is_unicode(existing) and is_unicode(obj):
a_diff = difflib.unified_diff(existing.splitlines(),
obj.splitlines(),
lineterm='')
for line in a_diff:
if line.startswith('+++') or line.startswith('---'):
continue
if line[0] == '+':
print(maybe_colored("++ %s" % line[1:], 'green', opt))
elif line[0] == '-':
print(maybe_colored("-- %s" % line[1:], 'red', opt))
else:
print(line)
elif isinstance(existing, dict):
ignore_missing = isinstance(resource, VaultBackend)
details_dict(obj, existing, ignore_missing, opt) | python | def maybe_details(resource, opt):
"""At the first level of verbosity this will print out detailed
change information on for the specified Vault resource"""
if opt.verbose == 0:
return
if not resource.present:
return
obj = None
existing = None
if isinstance(resource, Resource):
obj = resource.obj()
existing = resource.existing
elif isinstance(resource, VaultBackend):
obj = resource.config
existing = resource.existing
if not obj:
return
if is_unicode(existing) and is_unicode(obj):
a_diff = difflib.unified_diff(existing.splitlines(),
obj.splitlines(),
lineterm='')
for line in a_diff:
if line.startswith('+++') or line.startswith('---'):
continue
if line[0] == '+':
print(maybe_colored("++ %s" % line[1:], 'green', opt))
elif line[0] == '-':
print(maybe_colored("-- %s" % line[1:], 'red', opt))
else:
print(line)
elif isinstance(existing, dict):
ignore_missing = isinstance(resource, VaultBackend)
details_dict(obj, existing, ignore_missing, opt) | [
"def",
"maybe_details",
"(",
"resource",
",",
"opt",
")",
":",
"if",
"opt",
".",
"verbose",
"==",
"0",
":",
"return",
"if",
"not",
"resource",
".",
"present",
":",
"return",
"obj",
"=",
"None",
"existing",
"=",
"None",
"if",
"isinstance",
"(",
"resourc... | At the first level of verbosity this will print out detailed
change information on for the specified Vault resource | [
"At",
"the",
"first",
"level",
"of",
"verbosity",
"this",
"will",
"print",
"out",
"detailed",
"change",
"information",
"on",
"for",
"the",
"specified",
"Vault",
"resource"
] | 84da2dfb0424837adf9c4ddc1aa352e942bb7a4a | https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/seed_action.py#L141-L178 | train | 44,391 |
Autodesk/aomi | aomi/seed_action.py | diff_a_thing | def diff_a_thing(thing, opt):
"""Handle the diff action for a single thing. It may be a Vault backend
implementation or it may be a Vault data resource"""
changed = thing.diff()
if changed == ADD:
print("%s %s" % (maybe_colored("+", "green", opt), str(thing)))
elif changed == DEL:
print("%s %s" % (maybe_colored("-", "red", opt), str(thing)))
elif changed == CHANGED:
print("%s %s" % (maybe_colored("~", "yellow", opt), str(thing)))
elif changed == OVERWRITE:
print("%s %s" % (maybe_colored("+", "yellow", opt), str(thing)))
elif changed == CONFLICT:
print("%s %s" % (maybe_colored("!", "red", opt), str(thing)))
if changed != OVERWRITE and changed != NOOP:
maybe_details(thing, opt) | python | def diff_a_thing(thing, opt):
"""Handle the diff action for a single thing. It may be a Vault backend
implementation or it may be a Vault data resource"""
changed = thing.diff()
if changed == ADD:
print("%s %s" % (maybe_colored("+", "green", opt), str(thing)))
elif changed == DEL:
print("%s %s" % (maybe_colored("-", "red", opt), str(thing)))
elif changed == CHANGED:
print("%s %s" % (maybe_colored("~", "yellow", opt), str(thing)))
elif changed == OVERWRITE:
print("%s %s" % (maybe_colored("+", "yellow", opt), str(thing)))
elif changed == CONFLICT:
print("%s %s" % (maybe_colored("!", "red", opt), str(thing)))
if changed != OVERWRITE and changed != NOOP:
maybe_details(thing, opt) | [
"def",
"diff_a_thing",
"(",
"thing",
",",
"opt",
")",
":",
"changed",
"=",
"thing",
".",
"diff",
"(",
")",
"if",
"changed",
"==",
"ADD",
":",
"print",
"(",
"\"%s %s\"",
"%",
"(",
"maybe_colored",
"(",
"\"+\"",
",",
"\"green\"",
",",
"opt",
")",
",",
... | Handle the diff action for a single thing. It may be a Vault backend
implementation or it may be a Vault data resource | [
"Handle",
"the",
"diff",
"action",
"for",
"a",
"single",
"thing",
".",
"It",
"may",
"be",
"a",
"Vault",
"backend",
"implementation",
"or",
"it",
"may",
"be",
"a",
"Vault",
"data",
"resource"
] | 84da2dfb0424837adf9c4ddc1aa352e942bb7a4a | https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/seed_action.py#L181-L197 | train | 44,392 |
Autodesk/aomi | aomi/seed_action.py | diff | def diff(vault_client, opt):
"""Derive a comparison between what is represented in the Secretfile
and what is actually live on a Vault instance"""
if opt.thaw_from:
opt.secrets = tempfile.mkdtemp('aomi-thaw')
auto_thaw(vault_client, opt)
ctx = Context.load(get_secretfile(opt), opt) \
.fetch(vault_client)
for backend in ctx.mounts():
diff_a_thing(backend, opt)
for resource in ctx.resources():
diff_a_thing(resource, opt)
if opt.thaw_from:
rmtree(opt.secrets) | python | def diff(vault_client, opt):
"""Derive a comparison between what is represented in the Secretfile
and what is actually live on a Vault instance"""
if opt.thaw_from:
opt.secrets = tempfile.mkdtemp('aomi-thaw')
auto_thaw(vault_client, opt)
ctx = Context.load(get_secretfile(opt), opt) \
.fetch(vault_client)
for backend in ctx.mounts():
diff_a_thing(backend, opt)
for resource in ctx.resources():
diff_a_thing(resource, opt)
if opt.thaw_from:
rmtree(opt.secrets) | [
"def",
"diff",
"(",
"vault_client",
",",
"opt",
")",
":",
"if",
"opt",
".",
"thaw_from",
":",
"opt",
".",
"secrets",
"=",
"tempfile",
".",
"mkdtemp",
"(",
"'aomi-thaw'",
")",
"auto_thaw",
"(",
"vault_client",
",",
"opt",
")",
"ctx",
"=",
"Context",
"."... | Derive a comparison between what is represented in the Secretfile
and what is actually live on a Vault instance | [
"Derive",
"a",
"comparison",
"between",
"what",
"is",
"represented",
"in",
"the",
"Secretfile",
"and",
"what",
"is",
"actually",
"live",
"on",
"a",
"Vault",
"instance"
] | 84da2dfb0424837adf9c4ddc1aa352e942bb7a4a | https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/seed_action.py#L200-L217 | train | 44,393 |
Autodesk/aomi | aomi/cli.py | help_me | def help_me(parser, opt):
"""Handle display of help and whatever diagnostics"""
print("aomi v%s" % version)
print('Get started with aomi'
' https://autodesk.github.io/aomi/quickstart')
if opt.verbose == 2:
tf_str = 'Token File,' if token_file() else ''
app_str = 'AppID File,' if appid_file() else ''
approle_str = 'Approle File,' if approle_file() else ''
tfe_str = 'Token Env,' if 'VAULT_TOKEN' in os.environ else ''
appre_str = 'App Role Env,' if 'VAULT_ROLE_ID' in os.environ and \
'VAULT_SECRET_ID' in os.environ else ''
appe_str = 'AppID Env,' if 'VAULT_USER_ID' in os.environ and \
'VAULT_APP_ID' in os.environ else ''
LOG.info(("Auth Hints Present : %s%s%s%s%s%s" %
(tf_str, app_str, approle_str, tfe_str,
appre_str, appe_str))[:-1])
LOG.info("Vault Server %s" %
os.environ['VAULT_ADDR']
if 'VAULT_ADDR' in os.environ else '??')
parser.print_help()
sys.exit(0) | python | def help_me(parser, opt):
"""Handle display of help and whatever diagnostics"""
print("aomi v%s" % version)
print('Get started with aomi'
' https://autodesk.github.io/aomi/quickstart')
if opt.verbose == 2:
tf_str = 'Token File,' if token_file() else ''
app_str = 'AppID File,' if appid_file() else ''
approle_str = 'Approle File,' if approle_file() else ''
tfe_str = 'Token Env,' if 'VAULT_TOKEN' in os.environ else ''
appre_str = 'App Role Env,' if 'VAULT_ROLE_ID' in os.environ and \
'VAULT_SECRET_ID' in os.environ else ''
appe_str = 'AppID Env,' if 'VAULT_USER_ID' in os.environ and \
'VAULT_APP_ID' in os.environ else ''
LOG.info(("Auth Hints Present : %s%s%s%s%s%s" %
(tf_str, app_str, approle_str, tfe_str,
appre_str, appe_str))[:-1])
LOG.info("Vault Server %s" %
os.environ['VAULT_ADDR']
if 'VAULT_ADDR' in os.environ else '??')
parser.print_help()
sys.exit(0) | [
"def",
"help_me",
"(",
"parser",
",",
"opt",
")",
":",
"print",
"(",
"\"aomi v%s\"",
"%",
"version",
")",
"print",
"(",
"'Get started with aomi'",
"' https://autodesk.github.io/aomi/quickstart'",
")",
"if",
"opt",
".",
"verbose",
"==",
"2",
":",
"tf_str",
"=",
... | Handle display of help and whatever diagnostics | [
"Handle",
"display",
"of",
"help",
"and",
"whatever",
"diagnostics"
] | 84da2dfb0424837adf9c4ddc1aa352e942bb7a4a | https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/cli.py#L20-L43 | train | 44,394 |
Autodesk/aomi | aomi/cli.py | extract_file_args | def extract_file_args(subparsers):
"""Add the command line options for the extract_file operation"""
extract_parser = subparsers.add_parser('extract_file',
help='Extract a single secret from'
'Vault to a local file')
extract_parser.add_argument('vault_path',
help='Full path (including key) to secret')
extract_parser.add_argument('destination',
help='Location of destination file')
base_args(extract_parser) | python | def extract_file_args(subparsers):
"""Add the command line options for the extract_file operation"""
extract_parser = subparsers.add_parser('extract_file',
help='Extract a single secret from'
'Vault to a local file')
extract_parser.add_argument('vault_path',
help='Full path (including key) to secret')
extract_parser.add_argument('destination',
help='Location of destination file')
base_args(extract_parser) | [
"def",
"extract_file_args",
"(",
"subparsers",
")",
":",
"extract_parser",
"=",
"subparsers",
".",
"add_parser",
"(",
"'extract_file'",
",",
"help",
"=",
"'Extract a single secret from'",
"'Vault to a local file'",
")",
"extract_parser",
".",
"add_argument",
"(",
"'vaul... | Add the command line options for the extract_file operation | [
"Add",
"the",
"command",
"line",
"options",
"for",
"the",
"extract_file",
"operation"
] | 84da2dfb0424837adf9c4ddc1aa352e942bb7a4a | https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/cli.py#L46-L55 | train | 44,395 |
Autodesk/aomi | aomi/cli.py | mapping_args | def mapping_args(parser):
"""Add various variable mapping command line options to the parser"""
parser.add_argument('--add-prefix',
dest='add_prefix',
help='Specify a prefix to use when '
'generating secret key names')
parser.add_argument('--add-suffix',
dest='add_suffix',
help='Specify a suffix to use when '
'generating secret key names')
parser.add_argument('--merge-path',
dest='merge_path',
action='store_true',
default=True,
help='merge vault path and key name')
parser.add_argument('--no-merge-path',
dest='merge_path',
action='store_false',
default=True,
help='do not merge vault path and key name')
parser.add_argument('--key-map',
dest='key_map',
action='append',
type=str,
default=[]) | python | def mapping_args(parser):
"""Add various variable mapping command line options to the parser"""
parser.add_argument('--add-prefix',
dest='add_prefix',
help='Specify a prefix to use when '
'generating secret key names')
parser.add_argument('--add-suffix',
dest='add_suffix',
help='Specify a suffix to use when '
'generating secret key names')
parser.add_argument('--merge-path',
dest='merge_path',
action='store_true',
default=True,
help='merge vault path and key name')
parser.add_argument('--no-merge-path',
dest='merge_path',
action='store_false',
default=True,
help='do not merge vault path and key name')
parser.add_argument('--key-map',
dest='key_map',
action='append',
type=str,
default=[]) | [
"def",
"mapping_args",
"(",
"parser",
")",
":",
"parser",
".",
"add_argument",
"(",
"'--add-prefix'",
",",
"dest",
"=",
"'add_prefix'",
",",
"help",
"=",
"'Specify a prefix to use when '",
"'generating secret key names'",
")",
"parser",
".",
"add_argument",
"(",
"'-... | Add various variable mapping command line options to the parser | [
"Add",
"various",
"variable",
"mapping",
"command",
"line",
"options",
"to",
"the",
"parser"
] | 84da2dfb0424837adf9c4ddc1aa352e942bb7a4a | https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/cli.py#L58-L82 | train | 44,396 |
Autodesk/aomi | aomi/cli.py | aws_env_args | def aws_env_args(subparsers):
"""Add command line options for the aws_environment operation"""
env_parser = subparsers.add_parser('aws_environment')
env_parser.add_argument('vault_path',
help='Full path(s) to the AWS secret')
export_arg(env_parser)
base_args(env_parser) | python | def aws_env_args(subparsers):
"""Add command line options for the aws_environment operation"""
env_parser = subparsers.add_parser('aws_environment')
env_parser.add_argument('vault_path',
help='Full path(s) to the AWS secret')
export_arg(env_parser)
base_args(env_parser) | [
"def",
"aws_env_args",
"(",
"subparsers",
")",
":",
"env_parser",
"=",
"subparsers",
".",
"add_parser",
"(",
"'aws_environment'",
")",
"env_parser",
".",
"add_argument",
"(",
"'vault_path'",
",",
"help",
"=",
"'Full path(s) to the AWS secret'",
")",
"export_arg",
"(... | Add command line options for the aws_environment operation | [
"Add",
"command",
"line",
"options",
"for",
"the",
"aws_environment",
"operation"
] | 84da2dfb0424837adf9c4ddc1aa352e942bb7a4a | https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/cli.py#L93-L99 | train | 44,397 |
Autodesk/aomi | aomi/cli.py | environment_args | def environment_args(subparsers):
"""Add command line options for the environment operation"""
env_parser = subparsers.add_parser('environment')
env_parser.add_argument('vault_paths',
help='Full path(s) to secret',
nargs='+')
env_parser.add_argument('--prefix',
dest='prefix',
help='Old style prefix to use when'
'generating secret key names')
export_arg(env_parser)
mapping_args(env_parser)
base_args(env_parser) | python | def environment_args(subparsers):
"""Add command line options for the environment operation"""
env_parser = subparsers.add_parser('environment')
env_parser.add_argument('vault_paths',
help='Full path(s) to secret',
nargs='+')
env_parser.add_argument('--prefix',
dest='prefix',
help='Old style prefix to use when'
'generating secret key names')
export_arg(env_parser)
mapping_args(env_parser)
base_args(env_parser) | [
"def",
"environment_args",
"(",
"subparsers",
")",
":",
"env_parser",
"=",
"subparsers",
".",
"add_parser",
"(",
"'environment'",
")",
"env_parser",
".",
"add_argument",
"(",
"'vault_paths'",
",",
"help",
"=",
"'Full path(s) to secret'",
",",
"nargs",
"=",
"'+'",
... | Add command line options for the environment operation | [
"Add",
"command",
"line",
"options",
"for",
"the",
"environment",
"operation"
] | 84da2dfb0424837adf9c4ddc1aa352e942bb7a4a | https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/cli.py#L102-L114 | train | 44,398 |
Autodesk/aomi | aomi/cli.py | template_args | def template_args(subparsers):
"""Add command line options for the template operation"""
template_parser = subparsers.add_parser('template')
template_parser.add_argument('template',
help='Template source',
nargs='?')
template_parser.add_argument('destination',
help='Path to write rendered template',
nargs='?')
template_parser.add_argument('vault_paths',
help='Full path(s) to secret',
nargs='*')
template_parser.add_argument('--builtin-list',
dest='builtin_list',
help='Display a list of builtin templates',
action='store_true',
default=False)
template_parser.add_argument('--builtin-info',
dest='builtin_info',
help='Display information on a '
'particular builtin template')
vars_args(template_parser)
mapping_args(template_parser)
base_args(template_parser) | python | def template_args(subparsers):
"""Add command line options for the template operation"""
template_parser = subparsers.add_parser('template')
template_parser.add_argument('template',
help='Template source',
nargs='?')
template_parser.add_argument('destination',
help='Path to write rendered template',
nargs='?')
template_parser.add_argument('vault_paths',
help='Full path(s) to secret',
nargs='*')
template_parser.add_argument('--builtin-list',
dest='builtin_list',
help='Display a list of builtin templates',
action='store_true',
default=False)
template_parser.add_argument('--builtin-info',
dest='builtin_info',
help='Display information on a '
'particular builtin template')
vars_args(template_parser)
mapping_args(template_parser)
base_args(template_parser) | [
"def",
"template_args",
"(",
"subparsers",
")",
":",
"template_parser",
"=",
"subparsers",
".",
"add_parser",
"(",
"'template'",
")",
"template_parser",
".",
"add_argument",
"(",
"'template'",
",",
"help",
"=",
"'Template source'",
",",
"nargs",
"=",
"'?'",
")",... | Add command line options for the template operation | [
"Add",
"command",
"line",
"options",
"for",
"the",
"template",
"operation"
] | 84da2dfb0424837adf9c4ddc1aa352e942bb7a4a | https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/cli.py#L117-L140 | train | 44,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.