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 list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
zmathew/django-backbone | backbone/views.py | BackboneAPIView.has_add_permission | def has_add_permission(self, request):
"""
Returns True if the requesting user is allowed to add an object, False otherwise.
"""
perm_string = '%s.add_%s' % (self.model._meta.app_label,
self.model._meta.object_name.lower()
)
return request.user.has_perm(perm_s... | python | def has_add_permission(self, request):
"""
Returns True if the requesting user is allowed to add an object, False otherwise.
"""
perm_string = '%s.add_%s' % (self.model._meta.app_label,
self.model._meta.object_name.lower()
)
return request.user.has_perm(perm_s... | [
"def",
"has_add_permission",
"(",
"self",
",",
"request",
")",
":",
"perm_string",
"=",
"'%s.add_%s'",
"%",
"(",
"self",
".",
"model",
".",
"_meta",
".",
"app_label",
",",
"self",
".",
"model",
".",
"_meta",
".",
"object_name",
".",
"lower",
"(",
")",
... | Returns True if the requesting user is allowed to add an object, False otherwise. | [
"Returns",
"True",
"if",
"the",
"requesting",
"user",
"is",
"allowed",
"to",
"add",
"an",
"object",
"False",
"otherwise",
"."
] | 53505a247fb058e64a103c4f11da66993037bd6b | https://github.com/zmathew/django-backbone/blob/53505a247fb058e64a103c4f11da66993037bd6b/backbone/views.py#L212-L219 | train |
zmathew/django-backbone | backbone/views.py | BackboneAPIView.has_update_permission | def has_update_permission(self, request, obj):
"""
Returns True if the requesting user is allowed to update the given object, False otherwise.
"""
perm_string = '%s.change_%s' % (self.model._meta.app_label,
self.model._meta.object_name.lower()
)
return request... | python | def has_update_permission(self, request, obj):
"""
Returns True if the requesting user is allowed to update the given object, False otherwise.
"""
perm_string = '%s.change_%s' % (self.model._meta.app_label,
self.model._meta.object_name.lower()
)
return request... | [
"def",
"has_update_permission",
"(",
"self",
",",
"request",
",",
"obj",
")",
":",
"perm_string",
"=",
"'%s.change_%s'",
"%",
"(",
"self",
".",
"model",
".",
"_meta",
".",
"app_label",
",",
"self",
".",
"model",
".",
"_meta",
".",
"object_name",
".",
"lo... | Returns True if the requesting user is allowed to update the given object, False otherwise. | [
"Returns",
"True",
"if",
"the",
"requesting",
"user",
"is",
"allowed",
"to",
"update",
"the",
"given",
"object",
"False",
"otherwise",
"."
] | 53505a247fb058e64a103c4f11da66993037bd6b | https://github.com/zmathew/django-backbone/blob/53505a247fb058e64a103c4f11da66993037bd6b/backbone/views.py#L231-L238 | train |
zmathew/django-backbone | backbone/views.py | BackboneAPIView.serialize | def serialize(self, obj, fields):
"""
Serializes a single model instance to a Python dict, based on the specified list of fields.
"""
data = {}
remaining_fields = []
for field in fields:
if callable(field): # Callable
data[field.__name__] = f... | python | def serialize(self, obj, fields):
"""
Serializes a single model instance to a Python dict, based on the specified list of fields.
"""
data = {}
remaining_fields = []
for field in fields:
if callable(field): # Callable
data[field.__name__] = f... | [
"def",
"serialize",
"(",
"self",
",",
"obj",
",",
"fields",
")",
":",
"data",
"=",
"{",
"}",
"remaining_fields",
"=",
"[",
"]",
"for",
"field",
"in",
"fields",
":",
"if",
"callable",
"(",
"field",
")",
":",
"data",
"[",
"field",
".",
"__name__",
"]... | Serializes a single model instance to a Python dict, based on the specified list of fields. | [
"Serializes",
"a",
"single",
"model",
"instance",
"to",
"a",
"Python",
"dict",
"based",
"on",
"the",
"specified",
"list",
"of",
"fields",
"."
] | 53505a247fb058e64a103c4f11da66993037bd6b | https://github.com/zmathew/django-backbone/blob/53505a247fb058e64a103c4f11da66993037bd6b/backbone/views.py#L259-L295 | train |
zmathew/django-backbone | backbone/views.py | BackboneAPIView.json_dumps | def json_dumps(self, data, **options):
"""
Wrapper around `json.dumps` that uses a special JSON encoder.
"""
params = {'sort_keys': True, 'indent': 2}
params.update(options)
# This code is based off django's built in JSON serializer
if json.__version__.split('.') ... | python | def json_dumps(self, data, **options):
"""
Wrapper around `json.dumps` that uses a special JSON encoder.
"""
params = {'sort_keys': True, 'indent': 2}
params.update(options)
# This code is based off django's built in JSON serializer
if json.__version__.split('.') ... | [
"def",
"json_dumps",
"(",
"self",
",",
"data",
",",
"**",
"options",
")",
":",
"params",
"=",
"{",
"'sort_keys'",
":",
"True",
",",
"'indent'",
":",
"2",
"}",
"params",
".",
"update",
"(",
"options",
")",
"if",
"json",
".",
"__version__",
".",
"split... | Wrapper around `json.dumps` that uses a special JSON encoder. | [
"Wrapper",
"around",
"json",
".",
"dumps",
"that",
"uses",
"a",
"special",
"JSON",
"encoder",
"."
] | 53505a247fb058e64a103c4f11da66993037bd6b | https://github.com/zmathew/django-backbone/blob/53505a247fb058e64a103c4f11da66993037bd6b/backbone/views.py#L297-L307 | train |
artefactual-labs/mets-reader-writer | metsrw/fsentry.py | FSEntry.dir | def dir(cls, label, children):
"""Return ``FSEntry`` directory object."""
return FSEntry(label=label, children=children, type=u"Directory", use=None) | python | def dir(cls, label, children):
"""Return ``FSEntry`` directory object."""
return FSEntry(label=label, children=children, type=u"Directory", use=None) | [
"def",
"dir",
"(",
"cls",
",",
"label",
",",
"children",
")",
":",
"return",
"FSEntry",
"(",
"label",
"=",
"label",
",",
"children",
"=",
"children",
",",
"type",
"=",
"u\"Directory\"",
",",
"use",
"=",
"None",
")"
] | Return ``FSEntry`` directory object. | [
"Return",
"FSEntry",
"directory",
"object",
"."
] | d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/fsentry.py#L170-L172 | train |
artefactual-labs/mets-reader-writer | metsrw/fsentry.py | FSEntry.from_fptr | def from_fptr(cls, label, type_, fptr):
"""Return ``FSEntry`` object."""
return FSEntry(
label=label,
type=type_,
path=fptr.path,
use=fptr.use,
file_uuid=fptr.file_uuid,
derived_from=fptr.derived_from,
checksum=fptr.chec... | python | def from_fptr(cls, label, type_, fptr):
"""Return ``FSEntry`` object."""
return FSEntry(
label=label,
type=type_,
path=fptr.path,
use=fptr.use,
file_uuid=fptr.file_uuid,
derived_from=fptr.derived_from,
checksum=fptr.chec... | [
"def",
"from_fptr",
"(",
"cls",
",",
"label",
",",
"type_",
",",
"fptr",
")",
":",
"return",
"FSEntry",
"(",
"label",
"=",
"label",
",",
"type",
"=",
"type_",
",",
"path",
"=",
"fptr",
".",
"path",
",",
"use",
"=",
"fptr",
".",
"use",
",",
"file_... | Return ``FSEntry`` object. | [
"Return",
"FSEntry",
"object",
"."
] | d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/fsentry.py#L175-L186 | train |
artefactual-labs/mets-reader-writer | metsrw/fsentry.py | FSEntry.file_id | def file_id(self):
""" Returns the fptr @FILEID if this is not a Directory. """
if self.type.lower() == "directory":
return None
if self.file_uuid is None:
raise exceptions.MetsError(
"No FILEID: File %s does not have file_uuid set" % self.path
... | python | def file_id(self):
""" Returns the fptr @FILEID if this is not a Directory. """
if self.type.lower() == "directory":
return None
if self.file_uuid is None:
raise exceptions.MetsError(
"No FILEID: File %s does not have file_uuid set" % self.path
... | [
"def",
"file_id",
"(",
"self",
")",
":",
"if",
"self",
".",
"type",
".",
"lower",
"(",
")",
"==",
"\"directory\"",
":",
"return",
"None",
"if",
"self",
".",
"file_uuid",
"is",
"None",
":",
"raise",
"exceptions",
".",
"MetsError",
"(",
"\"No FILEID: File ... | Returns the fptr @FILEID if this is not a Directory. | [
"Returns",
"the",
"fptr"
] | d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/fsentry.py#L198-L208 | train |
artefactual-labs/mets-reader-writer | metsrw/fsentry.py | FSEntry.add_child | def add_child(self, child):
"""Add a child FSEntry to this FSEntry.
Only FSEntrys with a type of 'directory' can have children.
This does not detect cyclic parent/child relationships, but that will
cause problems.
:param metsrw.fsentry.FSEntry child: FSEntry to add as a child
... | python | def add_child(self, child):
"""Add a child FSEntry to this FSEntry.
Only FSEntrys with a type of 'directory' can have children.
This does not detect cyclic parent/child relationships, but that will
cause problems.
:param metsrw.fsentry.FSEntry child: FSEntry to add as a child
... | [
"def",
"add_child",
"(",
"self",
",",
"child",
")",
":",
"if",
"self",
".",
"type",
".",
"lower",
"(",
")",
"!=",
"\"directory\"",
":",
"raise",
"ValueError",
"(",
"\"Only directory objects can have children\"",
")",
"if",
"child",
"is",
"self",
":",
"raise"... | Add a child FSEntry to this FSEntry.
Only FSEntrys with a type of 'directory' can have children.
This does not detect cyclic parent/child relationships, but that will
cause problems.
:param metsrw.fsentry.FSEntry child: FSEntry to add as a child
:return: The newly added child
... | [
"Add",
"a",
"child",
"FSEntry",
"to",
"this",
"FSEntry",
"."
] | d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/fsentry.py#L337-L357 | train |
artefactual-labs/mets-reader-writer | metsrw/fsentry.py | FSEntry.remove_child | def remove_child(self, child):
"""
Remove a child from this FSEntry
If `child` is not actually a child of this entry, nothing happens.
:param child: Child to remove
"""
try:
self._children.remove(child)
except ValueError: # Child may not be in list
... | python | def remove_child(self, child):
"""
Remove a child from this FSEntry
If `child` is not actually a child of this entry, nothing happens.
:param child: Child to remove
"""
try:
self._children.remove(child)
except ValueError: # Child may not be in list
... | [
"def",
"remove_child",
"(",
"self",
",",
"child",
")",
":",
"try",
":",
"self",
".",
"_children",
".",
"remove",
"(",
"child",
")",
"except",
"ValueError",
":",
"pass",
"else",
":",
"child",
".",
"parent",
"=",
"None"
] | Remove a child from this FSEntry
If `child` is not actually a child of this entry, nothing happens.
:param child: Child to remove | [
"Remove",
"a",
"child",
"from",
"this",
"FSEntry"
] | d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/fsentry.py#L359-L372 | train |
artefactual-labs/mets-reader-writer | metsrw/fsentry.py | FSEntry.serialize_filesec | def serialize_filesec(self):
"""
Return the file Element for this file, appropriate for use in a fileSec.
If this is not an Item or has no use, return None.
:return: fileSec element for this FSEntry
"""
if (
self.type.lower() not in ("item", "archival inform... | python | def serialize_filesec(self):
"""
Return the file Element for this file, appropriate for use in a fileSec.
If this is not an Item or has no use, return None.
:return: fileSec element for this FSEntry
"""
if (
self.type.lower() not in ("item", "archival inform... | [
"def",
"serialize_filesec",
"(",
"self",
")",
":",
"if",
"(",
"self",
".",
"type",
".",
"lower",
"(",
")",
"not",
"in",
"(",
"\"item\"",
",",
"\"archival information package\"",
")",
"or",
"self",
".",
"use",
"is",
"None",
")",
":",
"return",
"None",
"... | Return the file Element for this file, appropriate for use in a fileSec.
If this is not an Item or has no use, return None.
:return: fileSec element for this FSEntry | [
"Return",
"the",
"file",
"Element",
"for",
"this",
"file",
"appropriate",
"for",
"use",
"in",
"a",
"fileSec",
"."
] | d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/fsentry.py#L376-L416 | train |
artefactual-labs/mets-reader-writer | metsrw/fsentry.py | FSEntry.is_empty_dir | def is_empty_dir(self):
"""Returns ``True`` if this fs item is a directory with no children or
a directory with only other empty directories as children.
"""
if self.mets_div_type == "Directory":
children = self._children
if children:
if all(child.... | python | def is_empty_dir(self):
"""Returns ``True`` if this fs item is a directory with no children or
a directory with only other empty directories as children.
"""
if self.mets_div_type == "Directory":
children = self._children
if children:
if all(child.... | [
"def",
"is_empty_dir",
"(",
"self",
")",
":",
"if",
"self",
".",
"mets_div_type",
"==",
"\"Directory\"",
":",
"children",
"=",
"self",
".",
"_children",
"if",
"children",
":",
"if",
"all",
"(",
"child",
".",
"is_empty_dir",
"for",
"child",
"in",
"children"... | Returns ``True`` if this fs item is a directory with no children or
a directory with only other empty directories as children. | [
"Returns",
"True",
"if",
"this",
"fs",
"item",
"is",
"a",
"directory",
"with",
"no",
"children",
"or",
"a",
"directory",
"with",
"only",
"other",
"empty",
"directories",
"as",
"children",
"."
] | d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/fsentry.py#L419-L433 | train |
artefactual-labs/mets-reader-writer | metsrw/fsentry.py | FSEntry.serialize_structmap | def serialize_structmap(self, recurse=True, normative=False):
"""Return the div Element for this file, appropriate for use in a
structMap.
If this FSEntry represents a directory, its children will be
recursively appended to itself. If this FSEntry represents a file, it
will cont... | python | def serialize_structmap(self, recurse=True, normative=False):
"""Return the div Element for this file, appropriate for use in a
structMap.
If this FSEntry represents a directory, its children will be
recursively appended to itself. If this FSEntry represents a file, it
will cont... | [
"def",
"serialize_structmap",
"(",
"self",
",",
"recurse",
"=",
"True",
",",
"normative",
"=",
"False",
")",
":",
"if",
"not",
"self",
".",
"label",
":",
"return",
"None",
"if",
"self",
".",
"is_empty_dir",
"and",
"not",
"normative",
":",
"return",
"None... | Return the div Element for this file, appropriate for use in a
structMap.
If this FSEntry represents a directory, its children will be
recursively appended to itself. If this FSEntry represents a file, it
will contain a <fptr> element.
:param bool recurse: If true, serialize an... | [
"Return",
"the",
"div",
"Element",
"for",
"this",
"file",
"appropriate",
"for",
"use",
"in",
"a",
"structMap",
"."
] | d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/fsentry.py#L435-L469 | train |
icgood/pysasl | pysasl/__init__.py | AuthenticationCredentials.check_secret | def check_secret(self, secret):
"""Checks if the secret string used in the authentication attempt
matches the "known" secret string. Some mechanisms will override this
method to control how this comparison is made.
Args:
secret: The secret string to compare against what was ... | python | def check_secret(self, secret):
"""Checks if the secret string used in the authentication attempt
matches the "known" secret string. Some mechanisms will override this
method to control how this comparison is made.
Args:
secret: The secret string to compare against what was ... | [
"def",
"check_secret",
"(",
"self",
",",
"secret",
")",
":",
"try",
":",
"return",
"hmac",
".",
"compare_digest",
"(",
"secret",
",",
"self",
".",
"secret",
")",
"except",
"AttributeError",
":",
"return",
"secret",
"==",
"self",
".",
"secret"
] | Checks if the secret string used in the authentication attempt
matches the "known" secret string. Some mechanisms will override this
method to control how this comparison is made.
Args:
secret: The secret string to compare against what was used in the
authentication ... | [
"Checks",
"if",
"the",
"secret",
"string",
"used",
"in",
"the",
"authentication",
"attempt",
"matches",
"the",
"known",
"secret",
"string",
".",
"Some",
"mechanisms",
"will",
"override",
"this",
"method",
"to",
"control",
"how",
"this",
"comparison",
"is",
"ma... | 241bdd349577cc99f05c4239755c307e6a46018c | https://github.com/icgood/pysasl/blob/241bdd349577cc99f05c4239755c307e6a46018c/pysasl/__init__.py#L107-L123 | train |
icgood/pysasl | pysasl/__init__.py | SASLAuth.secure | def secure(cls):
"""Uses only authentication mechanisms that are secure for use in
non-encrypted sessions.
Returns:
A new :class:`SASLAuth` object.
"""
builtin_mechs = cls._get_builtin_mechanisms()
secure_mechs = [mech for _, mech in builtin_mechs.items()
... | python | def secure(cls):
"""Uses only authentication mechanisms that are secure for use in
non-encrypted sessions.
Returns:
A new :class:`SASLAuth` object.
"""
builtin_mechs = cls._get_builtin_mechanisms()
secure_mechs = [mech for _, mech in builtin_mechs.items()
... | [
"def",
"secure",
"(",
"cls",
")",
":",
"builtin_mechs",
"=",
"cls",
".",
"_get_builtin_mechanisms",
"(",
")",
"secure_mechs",
"=",
"[",
"mech",
"for",
"_",
",",
"mech",
"in",
"builtin_mechs",
".",
"items",
"(",
")",
"if",
"not",
"mech",
".",
"insecure",
... | Uses only authentication mechanisms that are secure for use in
non-encrypted sessions.
Returns:
A new :class:`SASLAuth` object. | [
"Uses",
"only",
"authentication",
"mechanisms",
"that",
"are",
"secure",
"for",
"use",
"in",
"non",
"-",
"encrypted",
"sessions",
"."
] | 241bdd349577cc99f05c4239755c307e6a46018c | https://github.com/icgood/pysasl/blob/241bdd349577cc99f05c4239755c307e6a46018c/pysasl/__init__.py#L312-L323 | train |
artefactual-labs/mets-reader-writer | metsrw/mets.py | METSDocument.read | def read(cls, source):
"""Read ``source`` into a ``METSDocument`` instance. This is an
instance constructor. The ``source`` may be a path to a METS file, a
file-like object, or a string of XML.
"""
if hasattr(source, "read"):
return cls.fromfile(source)
if os.... | python | def read(cls, source):
"""Read ``source`` into a ``METSDocument`` instance. This is an
instance constructor. The ``source`` may be a path to a METS file, a
file-like object, or a string of XML.
"""
if hasattr(source, "read"):
return cls.fromfile(source)
if os.... | [
"def",
"read",
"(",
"cls",
",",
"source",
")",
":",
"if",
"hasattr",
"(",
"source",
",",
"\"read\"",
")",
":",
"return",
"cls",
".",
"fromfile",
"(",
"source",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"source",
")",
":",
"return",
"cls",
... | Read ``source`` into a ``METSDocument`` instance. This is an
instance constructor. The ``source`` may be a path to a METS file, a
file-like object, or a string of XML. | [
"Read",
"source",
"into",
"a",
"METSDocument",
"instance",
".",
"This",
"is",
"an",
"instance",
"constructor",
".",
"The",
"source",
"may",
"be",
"a",
"path",
"to",
"a",
"METS",
"file",
"a",
"file",
"-",
"like",
"object",
"or",
"a",
"string",
"of",
"XM... | d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/mets.py#L46-L57 | train |
artefactual-labs/mets-reader-writer | metsrw/mets.py | METSDocument._collect_all_files | def _collect_all_files(self, files=None):
"""
Collect all FSEntrys into a set, including all descendants.
:param list files: List of :class:`FSEntry` to traverse.
:returns: Set of FSEntry
"""
if files is None:
files = self._root_elements
collected = s... | python | def _collect_all_files(self, files=None):
"""
Collect all FSEntrys into a set, including all descendants.
:param list files: List of :class:`FSEntry` to traverse.
:returns: Set of FSEntry
"""
if files is None:
files = self._root_elements
collected = s... | [
"def",
"_collect_all_files",
"(",
"self",
",",
"files",
"=",
"None",
")",
":",
"if",
"files",
"is",
"None",
":",
"files",
"=",
"self",
".",
"_root_elements",
"collected",
"=",
"set",
"(",
")",
"for",
"entry",
"in",
"files",
":",
"collected",
".",
"add"... | Collect all FSEntrys into a set, including all descendants.
:param list files: List of :class:`FSEntry` to traverse.
:returns: Set of FSEntry | [
"Collect",
"all",
"FSEntrys",
"into",
"a",
"set",
"including",
"all",
"descendants",
"."
] | d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/mets.py#L61-L74 | train |
artefactual-labs/mets-reader-writer | metsrw/mets.py | METSDocument.get_file | def get_file(self, **kwargs):
"""
Return the FSEntry that matches parameters.
:param str file_uuid: UUID of the target FSEntry.
:param str label: structMap LABEL of the target FSEntry.
:param str type: structMap TYPE of the target FSEntry.
:returns: :class:`FSEntry` that... | python | def get_file(self, **kwargs):
"""
Return the FSEntry that matches parameters.
:param str file_uuid: UUID of the target FSEntry.
:param str label: structMap LABEL of the target FSEntry.
:param str type: structMap TYPE of the target FSEntry.
:returns: :class:`FSEntry` that... | [
"def",
"get_file",
"(",
"self",
",",
"**",
"kwargs",
")",
":",
"for",
"entry",
"in",
"self",
".",
"all_files",
"(",
")",
":",
"if",
"all",
"(",
"value",
"==",
"getattr",
"(",
"entry",
",",
"key",
")",
"for",
"key",
",",
"value",
"in",
"kwargs",
"... | Return the FSEntry that matches parameters.
:param str file_uuid: UUID of the target FSEntry.
:param str label: structMap LABEL of the target FSEntry.
:param str type: structMap TYPE of the target FSEntry.
:returns: :class:`FSEntry` that matches parameters, or None. | [
"Return",
"the",
"FSEntry",
"that",
"matches",
"parameters",
"."
] | d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/mets.py#L87-L102 | train |
artefactual-labs/mets-reader-writer | metsrw/mets.py | METSDocument.append_file | def append_file(self, fs_entry):
"""
Adds an FSEntry object to this METS document's tree. Any of the
represented object's children will also be added to the document.
A given FSEntry object can only be included in a document once,
and any attempt to add an object the second time... | python | def append_file(self, fs_entry):
"""
Adds an FSEntry object to this METS document's tree. Any of the
represented object's children will also be added to the document.
A given FSEntry object can only be included in a document once,
and any attempt to add an object the second time... | [
"def",
"append_file",
"(",
"self",
",",
"fs_entry",
")",
":",
"if",
"fs_entry",
"in",
"self",
".",
"_root_elements",
":",
"return",
"self",
".",
"_root_elements",
".",
"append",
"(",
"fs_entry",
")",
"self",
".",
"_all_files",
"=",
"None"
] | Adds an FSEntry object to this METS document's tree. Any of the
represented object's children will also be added to the document.
A given FSEntry object can only be included in a document once,
and any attempt to add an object the second time will be ignored.
:param metsrw.mets.FSEntry... | [
"Adds",
"an",
"FSEntry",
"object",
"to",
"this",
"METS",
"document",
"s",
"tree",
".",
"Any",
"of",
"the",
"represented",
"object",
"s",
"children",
"will",
"also",
"be",
"added",
"to",
"the",
"document",
"."
] | d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/mets.py#L104-L119 | train |
artefactual-labs/mets-reader-writer | metsrw/mets.py | METSDocument.remove_entry | def remove_entry(self, fs_entry):
"""Removes an FSEntry object from this METS document.
Any children of this FSEntry will also be removed. This will be removed
as a child of it's parent, if any.
:param metsrw.mets.FSEntry fs_entry: FSEntry to remove from the METS
"""
tr... | python | def remove_entry(self, fs_entry):
"""Removes an FSEntry object from this METS document.
Any children of this FSEntry will also be removed. This will be removed
as a child of it's parent, if any.
:param metsrw.mets.FSEntry fs_entry: FSEntry to remove from the METS
"""
tr... | [
"def",
"remove_entry",
"(",
"self",
",",
"fs_entry",
")",
":",
"try",
":",
"self",
".",
"_root_elements",
".",
"remove",
"(",
"fs_entry",
")",
"except",
"ValueError",
":",
"pass",
"if",
"fs_entry",
".",
"parent",
":",
"fs_entry",
".",
"parent",
".",
"rem... | Removes an FSEntry object from this METS document.
Any children of this FSEntry will also be removed. This will be removed
as a child of it's parent, if any.
:param metsrw.mets.FSEntry fs_entry: FSEntry to remove from the METS | [
"Removes",
"an",
"FSEntry",
"object",
"from",
"this",
"METS",
"document",
"."
] | d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/mets.py#L123-L138 | train |
artefactual-labs/mets-reader-writer | metsrw/mets.py | METSDocument._document_root | def _document_root(self, fully_qualified=True):
"""
Return the mets Element for the document root.
"""
nsmap = {"xsi": utils.NAMESPACES["xsi"], "xlink": utils.NAMESPACES["xlink"]}
if fully_qualified:
nsmap["mets"] = utils.NAMESPACES["mets"]
else:
n... | python | def _document_root(self, fully_qualified=True):
"""
Return the mets Element for the document root.
"""
nsmap = {"xsi": utils.NAMESPACES["xsi"], "xlink": utils.NAMESPACES["xlink"]}
if fully_qualified:
nsmap["mets"] = utils.NAMESPACES["mets"]
else:
n... | [
"def",
"_document_root",
"(",
"self",
",",
"fully_qualified",
"=",
"True",
")",
":",
"nsmap",
"=",
"{",
"\"xsi\"",
":",
"utils",
".",
"NAMESPACES",
"[",
"\"xsi\"",
"]",
",",
"\"xlink\"",
":",
"utils",
".",
"NAMESPACES",
"[",
"\"xlink\"",
"]",
"}",
"if",
... | Return the mets Element for the document root. | [
"Return",
"the",
"mets",
"Element",
"for",
"the",
"document",
"root",
"."
] | d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/mets.py#L166-L180 | train |
artefactual-labs/mets-reader-writer | metsrw/mets.py | METSDocument._mets_header | def _mets_header(self, now):
"""
Return the metsHdr Element.
"""
header_tag = etree.QName(utils.NAMESPACES[u"mets"], u"metsHdr")
header_attrs = {}
if self.createdate is None:
header_attrs[u"CREATEDATE"] = now
else:
header_attrs[u"CREATEDAT... | python | def _mets_header(self, now):
"""
Return the metsHdr Element.
"""
header_tag = etree.QName(utils.NAMESPACES[u"mets"], u"metsHdr")
header_attrs = {}
if self.createdate is None:
header_attrs[u"CREATEDATE"] = now
else:
header_attrs[u"CREATEDAT... | [
"def",
"_mets_header",
"(",
"self",
",",
"now",
")",
":",
"header_tag",
"=",
"etree",
".",
"QName",
"(",
"utils",
".",
"NAMESPACES",
"[",
"u\"mets\"",
"]",
",",
"u\"metsHdr\"",
")",
"header_attrs",
"=",
"{",
"}",
"if",
"self",
".",
"createdate",
"is",
... | Return the metsHdr Element. | [
"Return",
"the",
"metsHdr",
"Element",
"."
] | d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/mets.py#L182-L201 | train |
artefactual-labs/mets-reader-writer | metsrw/mets.py | METSDocument._collect_mdsec_elements | def _collect_mdsec_elements(files):
"""
Return all dmdSec and amdSec classes associated with the files.
Returns all dmdSecs, then all amdSecs, so they only need to be
serialized before being appended to the METS document.
:param List files: List of :class:`FSEntry` to collect M... | python | def _collect_mdsec_elements(files):
"""
Return all dmdSec and amdSec classes associated with the files.
Returns all dmdSecs, then all amdSecs, so they only need to be
serialized before being appended to the METS document.
:param List files: List of :class:`FSEntry` to collect M... | [
"def",
"_collect_mdsec_elements",
"(",
"files",
")",
":",
"dmdsecs",
"=",
"[",
"]",
"amdsecs",
"=",
"[",
"]",
"for",
"f",
"in",
"files",
":",
"for",
"d",
"in",
"f",
".",
"dmdsecs",
":",
"dmdsecs",
".",
"append",
"(",
"d",
")",
"for",
"a",
"in",
"... | Return all dmdSec and amdSec classes associated with the files.
Returns all dmdSecs, then all amdSecs, so they only need to be
serialized before being appended to the METS document.
:param List files: List of :class:`FSEntry` to collect MDSecs for.
:returns: List of AMDSecs and SubSect... | [
"Return",
"all",
"dmdSec",
"and",
"amdSec",
"classes",
"associated",
"with",
"the",
"files",
"."
] | d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/mets.py#L204-L224 | train |
artefactual-labs/mets-reader-writer | metsrw/mets.py | METSDocument._structmap | def _structmap(self):
"""
Returns structMap element for all files.
"""
structmap = etree.Element(
utils.lxmlns("mets") + "structMap",
TYPE="physical",
# TODO Add ability for multiple structMaps
ID="structMap_1",
# TODO don't har... | python | def _structmap(self):
"""
Returns structMap element for all files.
"""
structmap = etree.Element(
utils.lxmlns("mets") + "structMap",
TYPE="physical",
# TODO Add ability for multiple structMaps
ID="structMap_1",
# TODO don't har... | [
"def",
"_structmap",
"(",
"self",
")",
":",
"structmap",
"=",
"etree",
".",
"Element",
"(",
"utils",
".",
"lxmlns",
"(",
"\"mets\"",
")",
"+",
"\"structMap\"",
",",
"TYPE",
"=",
"\"physical\"",
",",
"ID",
"=",
"\"structMap_1\"",
",",
"LABEL",
"=",
"\"Arc... | Returns structMap element for all files. | [
"Returns",
"structMap",
"element",
"for",
"all",
"files",
"."
] | d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/mets.py#L226-L243 | train |
artefactual-labs/mets-reader-writer | metsrw/mets.py | METSDocument._filesec | def _filesec(self, files=None):
"""
Returns fileSec Element containing all files grouped by use.
"""
if files is None:
files = self.all_files()
filesec = etree.Element(utils.lxmlns("mets") + "fileSec")
filegrps = {}
for file_ in files:
if ... | python | def _filesec(self, files=None):
"""
Returns fileSec Element containing all files grouped by use.
"""
if files is None:
files = self.all_files()
filesec = etree.Element(utils.lxmlns("mets") + "fileSec")
filegrps = {}
for file_ in files:
if ... | [
"def",
"_filesec",
"(",
"self",
",",
"files",
"=",
"None",
")",
":",
"if",
"files",
"is",
"None",
":",
"files",
"=",
"self",
".",
"all_files",
"(",
")",
"filesec",
"=",
"etree",
".",
"Element",
"(",
"utils",
".",
"lxmlns",
"(",
"\"mets\"",
")",
"+"... | Returns fileSec Element containing all files grouped by use. | [
"Returns",
"fileSec",
"Element",
"containing",
"all",
"files",
"grouped",
"by",
"use",
"."
] | d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/mets.py#L262-L286 | train |
artefactual-labs/mets-reader-writer | metsrw/mets.py | METSDocument.serialize | def serialize(self, fully_qualified=True):
"""
Returns this document serialized to an xml Element.
:return: Element for this document
"""
now = datetime.utcnow().replace(microsecond=0).isoformat("T")
files = self.all_files()
mdsecs = self._collect_mdsec_elements(... | python | def serialize(self, fully_qualified=True):
"""
Returns this document serialized to an xml Element.
:return: Element for this document
"""
now = datetime.utcnow().replace(microsecond=0).isoformat("T")
files = self.all_files()
mdsecs = self._collect_mdsec_elements(... | [
"def",
"serialize",
"(",
"self",
",",
"fully_qualified",
"=",
"True",
")",
":",
"now",
"=",
"datetime",
".",
"utcnow",
"(",
")",
".",
"replace",
"(",
"microsecond",
"=",
"0",
")",
".",
"isoformat",
"(",
"\"T\"",
")",
"files",
"=",
"self",
".",
"all_f... | Returns this document serialized to an xml Element.
:return: Element for this document | [
"Returns",
"this",
"document",
"serialized",
"to",
"an",
"xml",
"Element",
"."
] | d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/mets.py#L288-L304 | train |
artefactual-labs/mets-reader-writer | metsrw/mets.py | METSDocument.tostring | def tostring(self, fully_qualified=True, pretty_print=True, encoding="UTF-8"):
"""
Serialize and return a string of this METS document.
To write to file, see :meth:`write`.
The default encoding is ``UTF-8``. This method will return a unicode
string when ``encoding`` is set to `... | python | def tostring(self, fully_qualified=True, pretty_print=True, encoding="UTF-8"):
"""
Serialize and return a string of this METS document.
To write to file, see :meth:`write`.
The default encoding is ``UTF-8``. This method will return a unicode
string when ``encoding`` is set to `... | [
"def",
"tostring",
"(",
"self",
",",
"fully_qualified",
"=",
"True",
",",
"pretty_print",
"=",
"True",
",",
"encoding",
"=",
"\"UTF-8\"",
")",
":",
"root",
"=",
"self",
".",
"serialize",
"(",
"fully_qualified",
"=",
"fully_qualified",
")",
"kwargs",
"=",
"... | Serialize and return a string of this METS document.
To write to file, see :meth:`write`.
The default encoding is ``UTF-8``. This method will return a unicode
string when ``encoding`` is set to ``unicode``.
:return: String of this document | [
"Serialize",
"and",
"return",
"a",
"string",
"of",
"this",
"METS",
"document",
"."
] | d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/mets.py#L306-L321 | train |
artefactual-labs/mets-reader-writer | metsrw/mets.py | METSDocument.write | def write(
self, filepath, fully_qualified=True, pretty_print=False, encoding="UTF-8"
):
"""Serialize and write this METS document to `filepath`.
The default encoding is ``UTF-8``. This method will return a unicode
string when ``encoding`` is set to ``unicode``.
:param str ... | python | def write(
self, filepath, fully_qualified=True, pretty_print=False, encoding="UTF-8"
):
"""Serialize and write this METS document to `filepath`.
The default encoding is ``UTF-8``. This method will return a unicode
string when ``encoding`` is set to ``unicode``.
:param str ... | [
"def",
"write",
"(",
"self",
",",
"filepath",
",",
"fully_qualified",
"=",
"True",
",",
"pretty_print",
"=",
"False",
",",
"encoding",
"=",
"\"UTF-8\"",
")",
":",
"root",
"=",
"self",
".",
"serialize",
"(",
"fully_qualified",
"=",
"fully_qualified",
")",
"... | Serialize and write this METS document to `filepath`.
The default encoding is ``UTF-8``. This method will return a unicode
string when ``encoding`` is set to ``unicode``.
:param str filepath: Path to write the METS document to | [
"Serialize",
"and",
"write",
"this",
"METS",
"document",
"to",
"filepath",
"."
] | d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/mets.py#L323-L338 | train |
artefactual-labs/mets-reader-writer | metsrw/mets.py | METSDocument._get_el_to_normative | def _get_el_to_normative(parent_elem, normative_parent_elem):
"""Return ordered dict ``el_to_normative``, which maps children of
``parent_elem`` to their normative counterparts in the children of
``normative_parent_elem`` or to ``None`` if there is no normative
parent. If there is a norm... | python | def _get_el_to_normative(parent_elem, normative_parent_elem):
"""Return ordered dict ``el_to_normative``, which maps children of
``parent_elem`` to their normative counterparts in the children of
``normative_parent_elem`` or to ``None`` if there is no normative
parent. If there is a norm... | [
"def",
"_get_el_to_normative",
"(",
"parent_elem",
",",
"normative_parent_elem",
")",
":",
"el_to_normative",
"=",
"OrderedDict",
"(",
")",
"if",
"normative_parent_elem",
"is",
"None",
":",
"for",
"el",
"in",
"parent_elem",
":",
"el_to_normative",
"[",
"el",
"]",
... | Return ordered dict ``el_to_normative``, which maps children of
``parent_elem`` to their normative counterparts in the children of
``normative_parent_elem`` or to ``None`` if there is no normative
parent. If there is a normative div element with no non-normative
counterpart, that element... | [
"Return",
"ordered",
"dict",
"el_to_normative",
"which",
"maps",
"children",
"of",
"parent_elem",
"to",
"their",
"normative",
"counterparts",
"in",
"the",
"children",
"of",
"normative_parent_elem",
"or",
"to",
"None",
"if",
"there",
"is",
"no",
"normative",
"paren... | d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/mets.py#L388-L413 | train |
artefactual-labs/mets-reader-writer | metsrw/mets.py | METSDocument.fromfile | def fromfile(cls, path):
"""
Creates a METS by parsing a file.
:param str path: Path to a METS document.
"""
parser = etree.XMLParser(remove_blank_text=True)
return cls.fromtree(etree.parse(path, parser=parser)) | python | def fromfile(cls, path):
"""
Creates a METS by parsing a file.
:param str path: Path to a METS document.
"""
parser = etree.XMLParser(remove_blank_text=True)
return cls.fromtree(etree.parse(path, parser=parser)) | [
"def",
"fromfile",
"(",
"cls",
",",
"path",
")",
":",
"parser",
"=",
"etree",
".",
"XMLParser",
"(",
"remove_blank_text",
"=",
"True",
")",
"return",
"cls",
".",
"fromtree",
"(",
"etree",
".",
"parse",
"(",
"path",
",",
"parser",
"=",
"parser",
")",
... | Creates a METS by parsing a file.
:param str path: Path to a METS document. | [
"Creates",
"a",
"METS",
"by",
"parsing",
"a",
"file",
"."
] | d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/mets.py#L555-L563 | train |
artefactual-labs/mets-reader-writer | metsrw/mets.py | METSDocument.fromstring | def fromstring(cls, string):
"""
Create a METS by parsing a string.
:param str string: String containing a METS document.
"""
parser = etree.XMLParser(remove_blank_text=True)
root = etree.fromstring(string, parser)
tree = root.getroottree()
return cls.fr... | python | def fromstring(cls, string):
"""
Create a METS by parsing a string.
:param str string: String containing a METS document.
"""
parser = etree.XMLParser(remove_blank_text=True)
root = etree.fromstring(string, parser)
tree = root.getroottree()
return cls.fr... | [
"def",
"fromstring",
"(",
"cls",
",",
"string",
")",
":",
"parser",
"=",
"etree",
".",
"XMLParser",
"(",
"remove_blank_text",
"=",
"True",
")",
"root",
"=",
"etree",
".",
"fromstring",
"(",
"string",
",",
"parser",
")",
"tree",
"=",
"root",
".",
"getro... | Create a METS by parsing a string.
:param str string: String containing a METS document. | [
"Create",
"a",
"METS",
"by",
"parsing",
"a",
"string",
"."
] | d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/mets.py#L566-L576 | train |
artefactual-labs/mets-reader-writer | metsrw/mets.py | METSDocument.fromtree | def fromtree(cls, tree):
"""
Create a METS from an ElementTree or Element.
:param ElementTree tree: ElementTree to build a METS document from.
"""
mets = cls()
mets.tree = tree
mets._parse_tree(tree)
return mets | python | def fromtree(cls, tree):
"""
Create a METS from an ElementTree or Element.
:param ElementTree tree: ElementTree to build a METS document from.
"""
mets = cls()
mets.tree = tree
mets._parse_tree(tree)
return mets | [
"def",
"fromtree",
"(",
"cls",
",",
"tree",
")",
":",
"mets",
"=",
"cls",
"(",
")",
"mets",
".",
"tree",
"=",
"tree",
"mets",
".",
"_parse_tree",
"(",
"tree",
")",
"return",
"mets"
] | Create a METS from an ElementTree or Element.
:param ElementTree tree: ElementTree to build a METS document from. | [
"Create",
"a",
"METS",
"from",
"an",
"ElementTree",
"or",
"Element",
"."
] | d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/mets.py#L579-L589 | train |
artefactual-labs/mets-reader-writer | metsrw/validate.py | schematron_validate | def schematron_validate(mets_doc, schematron=AM_SCT_PATH):
"""Validate a METS file using a schematron schema. Return a boolean
indicating validity and a report as an ``lxml.ElementTree`` instance.
"""
if isinstance(schematron, six.string_types):
schematron = get_schematron(schematron)
is_val... | python | def schematron_validate(mets_doc, schematron=AM_SCT_PATH):
"""Validate a METS file using a schematron schema. Return a boolean
indicating validity and a report as an ``lxml.ElementTree`` instance.
"""
if isinstance(schematron, six.string_types):
schematron = get_schematron(schematron)
is_val... | [
"def",
"schematron_validate",
"(",
"mets_doc",
",",
"schematron",
"=",
"AM_SCT_PATH",
")",
":",
"if",
"isinstance",
"(",
"schematron",
",",
"six",
".",
"string_types",
")",
":",
"schematron",
"=",
"get_schematron",
"(",
"schematron",
")",
"is_valid",
"=",
"sch... | Validate a METS file using a schematron schema. Return a boolean
indicating validity and a report as an ``lxml.ElementTree`` instance. | [
"Validate",
"a",
"METS",
"file",
"using",
"a",
"schematron",
"schema",
".",
"Return",
"a",
"boolean",
"indicating",
"validity",
"and",
"a",
"report",
"as",
"an",
"lxml",
".",
"ElementTree",
"instance",
"."
] | d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/validate.py#L98-L106 | train |
artefactual-labs/mets-reader-writer | metsrw/validate.py | sct_report_string | def sct_report_string(report):
"""Return a human-readable string representation of the error report
returned by lxml's schematron validator.
"""
ret = []
namespaces = {"svrl": "http://purl.oclc.org/dsdl/svrl"}
for index, failed_assert_el in enumerate(
report.findall("svrl:failed-assert",... | python | def sct_report_string(report):
"""Return a human-readable string representation of the error report
returned by lxml's schematron validator.
"""
ret = []
namespaces = {"svrl": "http://purl.oclc.org/dsdl/svrl"}
for index, failed_assert_el in enumerate(
report.findall("svrl:failed-assert",... | [
"def",
"sct_report_string",
"(",
"report",
")",
":",
"ret",
"=",
"[",
"]",
"namespaces",
"=",
"{",
"\"svrl\"",
":",
"\"http://purl.oclc.org/dsdl/svrl\"",
"}",
"for",
"index",
",",
"failed_assert_el",
"in",
"enumerate",
"(",
"report",
".",
"findall",
"(",
"\"sv... | Return a human-readable string representation of the error report
returned by lxml's schematron validator. | [
"Return",
"a",
"human",
"-",
"readable",
"string",
"representation",
"of",
"the",
"error",
"report",
"returned",
"by",
"lxml",
"s",
"schematron",
"validator",
"."
] | d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/validate.py#L109-L127 | train |
artefactual-labs/mets-reader-writer | metsrw/validate.py | xsd_error_log_string | def xsd_error_log_string(xsd_error_log):
"""Return a human-readable string representation of the error log
returned by lxml's XMLSchema validator.
"""
ret = []
for error in xsd_error_log:
ret.append(
"ERROR ON LINE {}: {}".format(error.line, error.message.encode("utf-8"))
... | python | def xsd_error_log_string(xsd_error_log):
"""Return a human-readable string representation of the error log
returned by lxml's XMLSchema validator.
"""
ret = []
for error in xsd_error_log:
ret.append(
"ERROR ON LINE {}: {}".format(error.line, error.message.encode("utf-8"))
... | [
"def",
"xsd_error_log_string",
"(",
"xsd_error_log",
")",
":",
"ret",
"=",
"[",
"]",
"for",
"error",
"in",
"xsd_error_log",
":",
"ret",
".",
"append",
"(",
"\"ERROR ON LINE {}: {}\"",
".",
"format",
"(",
"error",
".",
"line",
",",
"error",
".",
"message",
... | Return a human-readable string representation of the error log
returned by lxml's XMLSchema validator. | [
"Return",
"a",
"human",
"-",
"readable",
"string",
"representation",
"of",
"the",
"error",
"log",
"returned",
"by",
"lxml",
"s",
"XMLSchema",
"validator",
"."
] | d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/validate.py#L130-L139 | train |
djk2/django-popup-view-field | django_popup_view_field/widgets.py | PopupViewWidget.get_view_url | def get_view_url(self):
"""Return url for ajax to view for render dialog content"""
url = reverse("django_popup_view_field:get_popup_view", args=(self.view_class_name,))
return "{url}?{cd}".format(
url=url,
cd=self.callback_data
) | python | def get_view_url(self):
"""Return url for ajax to view for render dialog content"""
url = reverse("django_popup_view_field:get_popup_view", args=(self.view_class_name,))
return "{url}?{cd}".format(
url=url,
cd=self.callback_data
) | [
"def",
"get_view_url",
"(",
"self",
")",
":",
"url",
"=",
"reverse",
"(",
"\"django_popup_view_field:get_popup_view\"",
",",
"args",
"=",
"(",
"self",
".",
"view_class_name",
",",
")",
")",
"return",
"\"{url}?{cd}\"",
".",
"format",
"(",
"url",
"=",
"url",
"... | Return url for ajax to view for render dialog content | [
"Return",
"url",
"for",
"ajax",
"to",
"view",
"for",
"render",
"dialog",
"content"
] | f144e7acd221fab2a7f4867dd1430a8b1c941f90 | https://github.com/djk2/django-popup-view-field/blob/f144e7acd221fab2a7f4867dd1430a8b1c941f90/django_popup_view_field/widgets.py#L34-L40 | train |
sivy/pystatsd | pystatsd/statsd.py | Client.send | def send(self, data, sample_rate=1):
"""
Squirt the metrics over UDP
"""
if self.prefix:
data = dict((".".join((self.prefix, stat)), value) for stat, value in data.items())
if sample_rate < 1:
if random.random() > sample_rate:
return
... | python | def send(self, data, sample_rate=1):
"""
Squirt the metrics over UDP
"""
if self.prefix:
data = dict((".".join((self.prefix, stat)), value) for stat, value in data.items())
if sample_rate < 1:
if random.random() > sample_rate:
return
... | [
"def",
"send",
"(",
"self",
",",
"data",
",",
"sample_rate",
"=",
"1",
")",
":",
"if",
"self",
".",
"prefix",
":",
"data",
"=",
"dict",
"(",
"(",
"\".\"",
".",
"join",
"(",
"(",
"self",
".",
"prefix",
",",
"stat",
")",
")",
",",
"value",
")",
... | Squirt the metrics over UDP | [
"Squirt",
"the",
"metrics",
"over",
"UDP"
] | 69e362654c37df28582b12b964901334326620a7 | https://github.com/sivy/pystatsd/blob/69e362654c37df28582b12b964901334326620a7/pystatsd/statsd.py#L89-L110 | train |
sivy/pystatsd | pystatsd/daemon.py | Daemon.restart | def restart(self, *args, **kw):
"""Restart the daemon."""
self.stop()
self.start(*args, **kw) | python | def restart(self, *args, **kw):
"""Restart the daemon."""
self.stop()
self.start(*args, **kw) | [
"def",
"restart",
"(",
"self",
",",
"*",
"args",
",",
"**",
"kw",
")",
":",
"self",
".",
"stop",
"(",
")",
"self",
".",
"start",
"(",
"*",
"args",
",",
"**",
"kw",
")"
] | Restart the daemon. | [
"Restart",
"the",
"daemon",
"."
] | 69e362654c37df28582b12b964901334326620a7 | https://github.com/sivy/pystatsd/blob/69e362654c37df28582b12b964901334326620a7/pystatsd/daemon.py#L108-L111 | train |
F5Networks/f5-icontrol-rest-python | icontrol/authtoken.py | iControlRESTTokenAuth.get_auth_providers | def get_auth_providers(self, netloc):
"""BIG-IQ specific query for auth providers
BIG-IP doesn't really need this because BIG-IP's multiple auth providers
seem to handle fallthrough just fine. BIG-IQ on the other hand, needs to
have its auth provider specified if you're using one of the... | python | def get_auth_providers(self, netloc):
"""BIG-IQ specific query for auth providers
BIG-IP doesn't really need this because BIG-IP's multiple auth providers
seem to handle fallthrough just fine. BIG-IQ on the other hand, needs to
have its auth provider specified if you're using one of the... | [
"def",
"get_auth_providers",
"(",
"self",
",",
"netloc",
")",
":",
"url",
"=",
"\"https://%s/info/system?null\"",
"%",
"(",
"netloc",
")",
"response",
"=",
"requests",
".",
"get",
"(",
"url",
",",
"verify",
"=",
"self",
".",
"verify",
")",
"if",
"not",
"... | BIG-IQ specific query for auth providers
BIG-IP doesn't really need this because BIG-IP's multiple auth providers
seem to handle fallthrough just fine. BIG-IQ on the other hand, needs to
have its auth provider specified if you're using one of the non-default
ones.
:param netloc... | [
"BIG",
"-",
"IQ",
"specific",
"query",
"for",
"auth",
"providers"
] | 34bb916299f4a00829352e7eb9818589408fa35a | https://github.com/F5Networks/f5-icontrol-rest-python/blob/34bb916299f4a00829352e7eb9818589408fa35a/icontrol/authtoken.py#L85-L108 | train |
F5Networks/f5-icontrol-rest-python | icontrol/authtoken.py | iControlRESTTokenAuth.get_new_token | def get_new_token(self, netloc):
"""Get a new token from BIG-IP and store it internally.
Throws relevant exception if it fails to get a new token.
This method will be called automatically if a request is attempted
but there is no authentication token, or the authentication token
... | python | def get_new_token(self, netloc):
"""Get a new token from BIG-IP and store it internally.
Throws relevant exception if it fails to get a new token.
This method will be called automatically if a request is attempted
but there is no authentication token, or the authentication token
... | [
"def",
"get_new_token",
"(",
"self",
",",
"netloc",
")",
":",
"login_body",
"=",
"{",
"'username'",
":",
"self",
".",
"username",
",",
"'password'",
":",
"self",
".",
"password",
",",
"}",
"if",
"self",
".",
"auth_provider",
":",
"if",
"self",
".",
"au... | Get a new token from BIG-IP and store it internally.
Throws relevant exception if it fails to get a new token.
This method will be called automatically if a request is attempted
but there is no authentication token, or the authentication token
is expired. It is usually not necessary f... | [
"Get",
"a",
"new",
"token",
"from",
"BIG",
"-",
"IP",
"and",
"store",
"it",
"internally",
"."
] | 34bb916299f4a00829352e7eb9818589408fa35a | https://github.com/F5Networks/f5-icontrol-rest-python/blob/34bb916299f4a00829352e7eb9818589408fa35a/icontrol/authtoken.py#L110-L192 | train |
F5Networks/f5-icontrol-rest-python | icontrol/session.py | decorate_HTTP_verb_method | def decorate_HTTP_verb_method(method):
"""Prepare and Post-Process HTTP VERB method for BigIP-RESTServer request.
This function decorates all of the HTTP VERB methods in the
iControlRESTSession class. It provides the core logic for this module.
If necessary it validates and assembles a uri from parts ... | python | def decorate_HTTP_verb_method(method):
"""Prepare and Post-Process HTTP VERB method for BigIP-RESTServer request.
This function decorates all of the HTTP VERB methods in the
iControlRESTSession class. It provides the core logic for this module.
If necessary it validates and assembles a uri from parts ... | [
"def",
"decorate_HTTP_verb_method",
"(",
"method",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"method",
")",
"def",
"wrapper",
"(",
"self",
",",
"RIC_base_uri",
",",
"**",
"kwargs",
")",
":",
"partition",
"=",
"kwargs",
".",
"pop",
"(",
"'partition'",
... | Prepare and Post-Process HTTP VERB method for BigIP-RESTServer request.
This function decorates all of the HTTP VERB methods in the
iControlRESTSession class. It provides the core logic for this module.
If necessary it validates and assembles a uri from parts with a call to
`generate_bigip_uri`.
... | [
"Prepare",
"and",
"Post",
"-",
"Process",
"HTTP",
"VERB",
"method",
"for",
"BigIP",
"-",
"RESTServer",
"request",
"."
] | 34bb916299f4a00829352e7eb9818589408fa35a | https://github.com/F5Networks/f5-icontrol-rest-python/blob/34bb916299f4a00829352e7eb9818589408fa35a/icontrol/session.py#L243-L297 | train |
F5Networks/f5-icontrol-rest-python | icontrol/session.py | _unique_resource_identifier_from_kwargs | def _unique_resource_identifier_from_kwargs(**kwargs):
"""Chooses an identifier given different choices
The unique identifier in BIG-IP's REST API at the time of this writing
is called 'name'. This is in contrast to the unique identifier that is
used by iWorkflow and BIG-IQ which at some times is 'name... | python | def _unique_resource_identifier_from_kwargs(**kwargs):
"""Chooses an identifier given different choices
The unique identifier in BIG-IP's REST API at the time of this writing
is called 'name'. This is in contrast to the unique identifier that is
used by iWorkflow and BIG-IQ which at some times is 'name... | [
"def",
"_unique_resource_identifier_from_kwargs",
"(",
"**",
"kwargs",
")",
":",
"name",
"=",
"kwargs",
".",
"pop",
"(",
"'name'",
",",
"''",
")",
"uuid",
"=",
"kwargs",
".",
"pop",
"(",
"'uuid'",
",",
"''",
")",
"id",
"=",
"kwargs",
".",
"pop",
"(",
... | Chooses an identifier given different choices
The unique identifier in BIG-IP's REST API at the time of this writing
is called 'name'. This is in contrast to the unique identifier that is
used by iWorkflow and BIG-IQ which at some times is 'name' and other
times is 'uuid'.
For example, in iWorkflo... | [
"Chooses",
"an",
"identifier",
"given",
"different",
"choices"
] | 34bb916299f4a00829352e7eb9818589408fa35a | https://github.com/F5Networks/f5-icontrol-rest-python/blob/34bb916299f4a00829352e7eb9818589408fa35a/icontrol/session.py#L300-L341 | train |
F5Networks/f5-icontrol-rest-python | icontrol/session.py | iControlRESTSession.delete | def delete(self, uri, **kwargs):
"""Sends a HTTP DELETE command to the BIGIP REST Server.
Use this method to send a DELETE command to the BIGIP. When calling
this method with the optional arguments ``name`` and ``partition``
as part of ``**kwargs`` they will be added to the ``uri`` pas... | python | def delete(self, uri, **kwargs):
"""Sends a HTTP DELETE command to the BIGIP REST Server.
Use this method to send a DELETE command to the BIGIP. When calling
this method with the optional arguments ``name`` and ``partition``
as part of ``**kwargs`` they will be added to the ``uri`` pas... | [
"def",
"delete",
"(",
"self",
",",
"uri",
",",
"**",
"kwargs",
")",
":",
"args1",
"=",
"get_request_args",
"(",
"kwargs",
")",
"args2",
"=",
"get_send_args",
"(",
"kwargs",
")",
"req",
"=",
"requests",
".",
"Request",
"(",
"'DELETE'",
",",
"uri",
",",
... | Sends a HTTP DELETE command to the BIGIP REST Server.
Use this method to send a DELETE command to the BIGIP. When calling
this method with the optional arguments ``name`` and ``partition``
as part of ``**kwargs`` they will be added to the ``uri`` passed
in separated by ~ to create a pr... | [
"Sends",
"a",
"HTTP",
"DELETE",
"command",
"to",
"the",
"BIGIP",
"REST",
"Server",
"."
] | 34bb916299f4a00829352e7eb9818589408fa35a | https://github.com/F5Networks/f5-icontrol-rest-python/blob/34bb916299f4a00829352e7eb9818589408fa35a/icontrol/session.py#L474-L499 | train |
F5Networks/f5-icontrol-rest-python | icontrol/session.py | iControlRESTSession.append_user_agent | def append_user_agent(self, user_agent):
"""Append text to the User-Agent header for the request.
Use this method to update the User-Agent header by appending the
given string to the session's User-Agent header separated by a space.
:param user_agent: A string to append to the User-Age... | python | def append_user_agent(self, user_agent):
"""Append text to the User-Agent header for the request.
Use this method to update the User-Agent header by appending the
given string to the session's User-Agent header separated by a space.
:param user_agent: A string to append to the User-Age... | [
"def",
"append_user_agent",
"(",
"self",
",",
"user_agent",
")",
":",
"old_ua",
"=",
"self",
".",
"session",
".",
"headers",
".",
"get",
"(",
"'User-Agent'",
",",
"''",
")",
"ua",
"=",
"old_ua",
"+",
"' '",
"+",
"user_agent",
"self",
".",
"session",
".... | Append text to the User-Agent header for the request.
Use this method to update the User-Agent header by appending the
given string to the session's User-Agent header separated by a space.
:param user_agent: A string to append to the User-Agent header
:type user_agent: str | [
"Append",
"text",
"to",
"the",
"User",
"-",
"Agent",
"header",
"for",
"the",
"request",
"."
] | 34bb916299f4a00829352e7eb9818589408fa35a | https://github.com/F5Networks/f5-icontrol-rest-python/blob/34bb916299f4a00829352e7eb9818589408fa35a/icontrol/session.py#L623-L634 | train |
crgwbr/asymmetric-jwt-auth | src/asymmetric_jwt_auth/models.py | validate_public_key | def validate_public_key(value):
"""
Check that the given value is a valid RSA Public key in either PEM or OpenSSH format. If it is invalid,
raises ``django.core.exceptions.ValidationError``.
"""
is_valid = False
exc = None
for load in (load_pem_public_key, load_ssh_public_key):
if n... | python | def validate_public_key(value):
"""
Check that the given value is a valid RSA Public key in either PEM or OpenSSH format. If it is invalid,
raises ``django.core.exceptions.ValidationError``.
"""
is_valid = False
exc = None
for load in (load_pem_public_key, load_ssh_public_key):
if n... | [
"def",
"validate_public_key",
"(",
"value",
")",
":",
"is_valid",
"=",
"False",
"exc",
"=",
"None",
"for",
"load",
"in",
"(",
"load_pem_public_key",
",",
"load_ssh_public_key",
")",
":",
"if",
"not",
"is_valid",
":",
"try",
":",
"load",
"(",
"value",
".",
... | Check that the given value is a valid RSA Public key in either PEM or OpenSSH format. If it is invalid,
raises ``django.core.exceptions.ValidationError``. | [
"Check",
"that",
"the",
"given",
"value",
"is",
"a",
"valid",
"RSA",
"Public",
"key",
"in",
"either",
"PEM",
"or",
"OpenSSH",
"format",
".",
"If",
"it",
"is",
"invalid",
"raises",
"django",
".",
"core",
".",
"exceptions",
".",
"ValidationError",
"."
] | eae1a6474b6141edce4d6be2dc1746e18bbf5318 | https://github.com/crgwbr/asymmetric-jwt-auth/blob/eae1a6474b6141edce4d6be2dc1746e18bbf5318/src/asymmetric_jwt_auth/models.py#L8-L25 | train |
kenneth-reitz/pyandoc | pandoc/core.py | Document._register_formats | def _register_formats(cls):
"""Adds format properties."""
for fmt in cls.OUTPUT_FORMATS:
clean_fmt = fmt.replace('+', '_')
setattr(cls, clean_fmt, property(
(lambda x, fmt=fmt: cls._output(x, fmt)), # fget
(lambda x, y, fmt=fmt: cls._input(x, y, fm... | python | def _register_formats(cls):
"""Adds format properties."""
for fmt in cls.OUTPUT_FORMATS:
clean_fmt = fmt.replace('+', '_')
setattr(cls, clean_fmt, property(
(lambda x, fmt=fmt: cls._output(x, fmt)), # fget
(lambda x, y, fmt=fmt: cls._input(x, y, fm... | [
"def",
"_register_formats",
"(",
"cls",
")",
":",
"for",
"fmt",
"in",
"cls",
".",
"OUTPUT_FORMATS",
":",
"clean_fmt",
"=",
"fmt",
".",
"replace",
"(",
"'+'",
",",
"'_'",
")",
"setattr",
"(",
"cls",
",",
"clean_fmt",
",",
"property",
"(",
"(",
"lambda",... | Adds format properties. | [
"Adds",
"format",
"properties",
"."
] | 4417ee34e85c88c874f0a5ae93bc54b0f5d93af0 | https://github.com/kenneth-reitz/pyandoc/blob/4417ee34e85c88c874f0a5ae93bc54b0f5d93af0/pandoc/core.py#L73-L79 | train |
crgwbr/asymmetric-jwt-auth | src/asymmetric_jwt_auth/token.py | sign | def sign(username, private_key, generate_nonce=None, iat=None, algorithm=DEFAULT_ALGORITHM):
"""
Create a signed JWT using the given username and RSA private key.
:param username: Username (string) to authenticate as on the remote system.
:param private_key: Private key to use to sign the JWT claim.
... | python | def sign(username, private_key, generate_nonce=None, iat=None, algorithm=DEFAULT_ALGORITHM):
"""
Create a signed JWT using the given username and RSA private key.
:param username: Username (string) to authenticate as on the remote system.
:param private_key: Private key to use to sign the JWT claim.
... | [
"def",
"sign",
"(",
"username",
",",
"private_key",
",",
"generate_nonce",
"=",
"None",
",",
"iat",
"=",
"None",
",",
"algorithm",
"=",
"DEFAULT_ALGORITHM",
")",
":",
"iat",
"=",
"iat",
"if",
"iat",
"else",
"time",
".",
"time",
"(",
")",
"if",
"not",
... | Create a signed JWT using the given username and RSA private key.
:param username: Username (string) to authenticate as on the remote system.
:param private_key: Private key to use to sign the JWT claim.
:param generate_nonce: Optional. Callable to use to generate a new nonce. Defaults to
`random.r... | [
"Create",
"a",
"signed",
"JWT",
"using",
"the",
"given",
"username",
"and",
"RSA",
"private",
"key",
"."
] | eae1a6474b6141edce4d6be2dc1746e18bbf5318 | https://github.com/crgwbr/asymmetric-jwt-auth/blob/eae1a6474b6141edce4d6be2dc1746e18bbf5318/src/asymmetric_jwt_auth/token.py#L16-L41 | train |
crgwbr/asymmetric-jwt-auth | src/asymmetric_jwt_auth/token.py | get_claimed_username | def get_claimed_username(token):
"""
Given a JWT, get the username that it is claiming to be `without verifying that the signature is valid`.
:param token: JWT claim
:return: Username
"""
unverified_data = jwt.decode(token, options={
'verify_signature': False
})
if 'username' n... | python | def get_claimed_username(token):
"""
Given a JWT, get the username that it is claiming to be `without verifying that the signature is valid`.
:param token: JWT claim
:return: Username
"""
unverified_data = jwt.decode(token, options={
'verify_signature': False
})
if 'username' n... | [
"def",
"get_claimed_username",
"(",
"token",
")",
":",
"unverified_data",
"=",
"jwt",
".",
"decode",
"(",
"token",
",",
"options",
"=",
"{",
"'verify_signature'",
":",
"False",
"}",
")",
"if",
"'username'",
"not",
"in",
"unverified_data",
":",
"return",
"Non... | Given a JWT, get the username that it is claiming to be `without verifying that the signature is valid`.
:param token: JWT claim
:return: Username | [
"Given",
"a",
"JWT",
"get",
"the",
"username",
"that",
"it",
"is",
"claiming",
"to",
"be",
"without",
"verifying",
"that",
"the",
"signature",
"is",
"valid",
"."
] | eae1a6474b6141edce4d6be2dc1746e18bbf5318 | https://github.com/crgwbr/asymmetric-jwt-auth/blob/eae1a6474b6141edce4d6be2dc1746e18bbf5318/src/asymmetric_jwt_auth/token.py#L44-L57 | train |
crgwbr/asymmetric-jwt-auth | src/asymmetric_jwt_auth/token.py | verify | def verify(token, public_key, validate_nonce=None, algorithms=[DEFAULT_ALGORITHM]):
"""
Verify the validity of the given JWT using the given public key.
:param token: JWM claim
:param public_key: Public key to use when verifying the claim's signature.
:param validate_nonce: Callable to use to valid... | python | def verify(token, public_key, validate_nonce=None, algorithms=[DEFAULT_ALGORITHM]):
"""
Verify the validity of the given JWT using the given public key.
:param token: JWM claim
:param public_key: Public key to use when verifying the claim's signature.
:param validate_nonce: Callable to use to valid... | [
"def",
"verify",
"(",
"token",
",",
"public_key",
",",
"validate_nonce",
"=",
"None",
",",
"algorithms",
"=",
"[",
"DEFAULT_ALGORITHM",
"]",
")",
":",
"try",
":",
"token_data",
"=",
"jwt",
".",
"decode",
"(",
"token",
",",
"public_key",
",",
"algorithms",
... | Verify the validity of the given JWT using the given public key.
:param token: JWM claim
:param public_key: Public key to use when verifying the claim's signature.
:param validate_nonce: Callable to use to validate the claim's nonce.
:param algorithms: Allowable signing algorithms. Defaults to ['RS512'... | [
"Verify",
"the",
"validity",
"of",
"the",
"given",
"JWT",
"using",
"the",
"given",
"public",
"key",
"."
] | eae1a6474b6141edce4d6be2dc1746e18bbf5318 | https://github.com/crgwbr/asymmetric-jwt-auth/blob/eae1a6474b6141edce4d6be2dc1746e18bbf5318/src/asymmetric_jwt_auth/token.py#L60-L96 | train |
crgwbr/asymmetric-jwt-auth | src/asymmetric_jwt_auth/middleware.py | JWTAuthMiddleware.log_used_nonce | def log_used_nonce(self, username, iat, nonce):
"""
Log a nonce as being used, and therefore henceforth invalid.
:param username: Username as a string.
:param iat: Unix timestamp float or integer of when the nonce was used.
:param nonce: Nonce value.
"""
# TODO: ... | python | def log_used_nonce(self, username, iat, nonce):
"""
Log a nonce as being used, and therefore henceforth invalid.
:param username: Username as a string.
:param iat: Unix timestamp float or integer of when the nonce was used.
:param nonce: Nonce value.
"""
# TODO: ... | [
"def",
"log_used_nonce",
"(",
"self",
",",
"username",
",",
"iat",
",",
"nonce",
")",
":",
"key",
"=",
"self",
".",
"create_nonce_key",
"(",
"username",
",",
"iat",
")",
"used",
"=",
"cache",
".",
"get",
"(",
"key",
",",
"[",
"]",
")",
"used",
".",... | Log a nonce as being used, and therefore henceforth invalid.
:param username: Username as a string.
:param iat: Unix timestamp float or integer of when the nonce was used.
:param nonce: Nonce value. | [
"Log",
"a",
"nonce",
"as",
"being",
"used",
"and",
"therefore",
"henceforth",
"invalid",
"."
] | eae1a6474b6141edce4d6be2dc1746e18bbf5318 | https://github.com/crgwbr/asymmetric-jwt-auth/blob/eae1a6474b6141edce4d6be2dc1746e18bbf5318/src/asymmetric_jwt_auth/middleware.py#L29-L43 | train |
crgwbr/asymmetric-jwt-auth | src/asymmetric_jwt_auth/middleware.py | JWTAuthMiddleware.validate_nonce | def validate_nonce(self, username, iat, nonce):
"""
Confirm that the given nonce hasn't already been used.
:param username: Username as a string.
:param iat: Unix timestamp float or integer of when the nonce was used.
:param nonce: Nonce value.
:return: True if nonce is ... | python | def validate_nonce(self, username, iat, nonce):
"""
Confirm that the given nonce hasn't already been used.
:param username: Username as a string.
:param iat: Unix timestamp float or integer of when the nonce was used.
:param nonce: Nonce value.
:return: True if nonce is ... | [
"def",
"validate_nonce",
"(",
"self",
",",
"username",
",",
"iat",
",",
"nonce",
")",
":",
"key",
"=",
"self",
".",
"create_nonce_key",
"(",
"username",
",",
"iat",
")",
"used",
"=",
"cache",
".",
"get",
"(",
"key",
",",
"[",
"]",
")",
"return",
"n... | Confirm that the given nonce hasn't already been used.
:param username: Username as a string.
:param iat: Unix timestamp float or integer of when the nonce was used.
:param nonce: Nonce value.
:return: True if nonce is valid, False if it is invalid. | [
"Confirm",
"that",
"the",
"given",
"nonce",
"hasn",
"t",
"already",
"been",
"used",
"."
] | eae1a6474b6141edce4d6be2dc1746e18bbf5318 | https://github.com/crgwbr/asymmetric-jwt-auth/blob/eae1a6474b6141edce4d6be2dc1746e18bbf5318/src/asymmetric_jwt_auth/middleware.py#L46-L57 | train |
crgwbr/asymmetric-jwt-auth | src/asymmetric_jwt_auth/middleware.py | JWTAuthMiddleware.process_request | def process_request(self, request):
"""
Process a Django request and authenticate users.
If a JWT authentication header is detected and it is determined to be valid, the user is set as
``request.user`` and CSRF protection is disabled (``request._dont_enforce_csrf_checks = True``) on
... | python | def process_request(self, request):
"""
Process a Django request and authenticate users.
If a JWT authentication header is detected and it is determined to be valid, the user is set as
``request.user`` and CSRF protection is disabled (``request._dont_enforce_csrf_checks = True``) on
... | [
"def",
"process_request",
"(",
"self",
",",
"request",
")",
":",
"if",
"'HTTP_AUTHORIZATION'",
"not",
"in",
"request",
".",
"META",
":",
"return",
"try",
":",
"method",
",",
"claim",
"=",
"request",
".",
"META",
"[",
"'HTTP_AUTHORIZATION'",
"]",
".",
"spli... | Process a Django request and authenticate users.
If a JWT authentication header is detected and it is determined to be valid, the user is set as
``request.user`` and CSRF protection is disabled (``request._dont_enforce_csrf_checks = True``) on
the request.
:param request: Django Reques... | [
"Process",
"a",
"Django",
"request",
"and",
"authenticate",
"users",
"."
] | eae1a6474b6141edce4d6be2dc1746e18bbf5318 | https://github.com/crgwbr/asymmetric-jwt-auth/blob/eae1a6474b6141edce4d6be2dc1746e18bbf5318/src/asymmetric_jwt_auth/middleware.py#L60-L101 | train |
crgwbr/asymmetric-jwt-auth | src/asymmetric_jwt_auth/__init__.py | load_private_key | def load_private_key(key_file, key_password=None):
"""
Load a private key from disk.
:param key_file: File path to key file.
:param key_password: Optional. If the key file is encrypted, provide the password to decrypt it. Defaults to None.
:return: PrivateKey<string>
"""
key_file = os.path.... | python | def load_private_key(key_file, key_password=None):
"""
Load a private key from disk.
:param key_file: File path to key file.
:param key_password: Optional. If the key file is encrypted, provide the password to decrypt it. Defaults to None.
:return: PrivateKey<string>
"""
key_file = os.path.... | [
"def",
"load_private_key",
"(",
"key_file",
",",
"key_password",
"=",
"None",
")",
":",
"key_file",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"key_file",
")",
"key_file",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"key_file",
")",
"if",
"not",
... | Load a private key from disk.
:param key_file: File path to key file.
:param key_password: Optional. If the key file is encrypted, provide the password to decrypt it. Defaults to None.
:return: PrivateKey<string> | [
"Load",
"a",
"private",
"key",
"from",
"disk",
"."
] | eae1a6474b6141edce4d6be2dc1746e18bbf5318 | https://github.com/crgwbr/asymmetric-jwt-auth/blob/eae1a6474b6141edce4d6be2dc1746e18bbf5318/src/asymmetric_jwt_auth/__init__.py#L52-L69 | train |
crgwbr/asymmetric-jwt-auth | src/asymmetric_jwt_auth/__init__.py | decrypt_key | def decrypt_key(key, password):
"""
Decrypt an encrypted private key.
:param key: Encrypted private key as a string.
:param password: Key pass-phrase.
:return: Decrypted private key as a string.
"""
private = serialization.load_pem_private_key(key, password=password, backend=default_backend... | python | def decrypt_key(key, password):
"""
Decrypt an encrypted private key.
:param key: Encrypted private key as a string.
:param password: Key pass-phrase.
:return: Decrypted private key as a string.
"""
private = serialization.load_pem_private_key(key, password=password, backend=default_backend... | [
"def",
"decrypt_key",
"(",
"key",
",",
"password",
")",
":",
"private",
"=",
"serialization",
".",
"load_pem_private_key",
"(",
"key",
",",
"password",
"=",
"password",
",",
"backend",
"=",
"default_backend",
"(",
")",
")",
"return",
"private",
".",
"private... | Decrypt an encrypted private key.
:param key: Encrypted private key as a string.
:param password: Key pass-phrase.
:return: Decrypted private key as a string. | [
"Decrypt",
"an",
"encrypted",
"private",
"key",
"."
] | eae1a6474b6141edce4d6be2dc1746e18bbf5318 | https://github.com/crgwbr/asymmetric-jwt-auth/blob/eae1a6474b6141edce4d6be2dc1746e18bbf5318/src/asymmetric_jwt_auth/__init__.py#L72-L81 | train |
crgwbr/asymmetric-jwt-auth | src/asymmetric_jwt_auth/__init__.py | create_auth_header | def create_auth_header(username, key=None, key_file="~/.ssh/id_rsa", key_password=None):
"""
Create an HTTP Authorization header using a private key file.
Either a key or a key_file must be provided.
:param username: The username to authenticate as on the remote system.
:param key: Optional. A pri... | python | def create_auth_header(username, key=None, key_file="~/.ssh/id_rsa", key_password=None):
"""
Create an HTTP Authorization header using a private key file.
Either a key or a key_file must be provided.
:param username: The username to authenticate as on the remote system.
:param key: Optional. A pri... | [
"def",
"create_auth_header",
"(",
"username",
",",
"key",
"=",
"None",
",",
"key_file",
"=",
"\"~/.ssh/id_rsa\"",
",",
"key_password",
"=",
"None",
")",
":",
"if",
"not",
"key",
":",
"key",
"=",
"load_private_key",
"(",
"key_file",
",",
"key_password",
")",
... | Create an HTTP Authorization header using a private key file.
Either a key or a key_file must be provided.
:param username: The username to authenticate as on the remote system.
:param key: Optional. A private key as either a string or an instance of cryptography.hazmat.primitives.asymmetric.rsa.RSAPrivat... | [
"Create",
"an",
"HTTP",
"Authorization",
"header",
"using",
"a",
"private",
"key",
"file",
"."
] | eae1a6474b6141edce4d6be2dc1746e18bbf5318 | https://github.com/crgwbr/asymmetric-jwt-auth/blob/eae1a6474b6141edce4d6be2dc1746e18bbf5318/src/asymmetric_jwt_auth/__init__.py#L84-L99 | train |
peeringdb/peeringdb-py | peeringdb/__init__.py | _config_logs | def _config_logs(lvl=None, name=None):
"""
Set up or change logging configuration.
_config_logs() => idempotent setup;
_config_logs(L) => change log level
"""
# print('_config_log', 'from %s' %name if name else '')
FORMAT = '%(message)s'
# maybe better for log files
# FORMAT='[%(lev... | python | def _config_logs(lvl=None, name=None):
"""
Set up or change logging configuration.
_config_logs() => idempotent setup;
_config_logs(L) => change log level
"""
# print('_config_log', 'from %s' %name if name else '')
FORMAT = '%(message)s'
# maybe better for log files
# FORMAT='[%(lev... | [
"def",
"_config_logs",
"(",
"lvl",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"FORMAT",
"=",
"'%(message)s'",
"for",
"h",
"in",
"list",
"(",
"logging",
".",
"root",
".",
"handlers",
")",
":",
"logging",
".",
"root",
".",
"removeHandler",
"(",
"... | Set up or change logging configuration.
_config_logs() => idempotent setup;
_config_logs(L) => change log level | [
"Set",
"up",
"or",
"change",
"logging",
"configuration",
"."
] | cf2060a1d5ef879a01cf849e54b7756909ab2661 | https://github.com/peeringdb/peeringdb-py/blob/cf2060a1d5ef879a01cf849e54b7756909ab2661/peeringdb/__init__.py#L12-L37 | train |
peeringdb/peeringdb-py | peeringdb/whois.py | WhoisFormat.mk_set_headers | def mk_set_headers(self, data, columns):
""" figure out sizes and create header fmt """
columns = tuple(columns)
lens = []
for key in columns:
value_len = max(len(str(each.get(key, ''))) for each in data)
# account for header lengths
lens.append(max(v... | python | def mk_set_headers(self, data, columns):
""" figure out sizes and create header fmt """
columns = tuple(columns)
lens = []
for key in columns:
value_len = max(len(str(each.get(key, ''))) for each in data)
# account for header lengths
lens.append(max(v... | [
"def",
"mk_set_headers",
"(",
"self",
",",
"data",
",",
"columns",
")",
":",
"columns",
"=",
"tuple",
"(",
"columns",
")",
"lens",
"=",
"[",
"]",
"for",
"key",
"in",
"columns",
":",
"value_len",
"=",
"max",
"(",
"len",
"(",
"str",
"(",
"each",
".",... | figure out sizes and create header fmt | [
"figure",
"out",
"sizes",
"and",
"create",
"header",
"fmt"
] | cf2060a1d5ef879a01cf849e54b7756909ab2661 | https://github.com/peeringdb/peeringdb-py/blob/cf2060a1d5ef879a01cf849e54b7756909ab2661/peeringdb/whois.py#L19-L30 | train |
peeringdb/peeringdb-py | peeringdb/whois.py | WhoisFormat._get_name | def _get_name(self, key):
""" get display name for a key, or mangle for display """
if key in self.display_names:
return self.display_names[key]
return key.capitalize() | python | def _get_name(self, key):
""" get display name for a key, or mangle for display """
if key in self.display_names:
return self.display_names[key]
return key.capitalize() | [
"def",
"_get_name",
"(",
"self",
",",
"key",
")",
":",
"if",
"key",
"in",
"self",
".",
"display_names",
":",
"return",
"self",
".",
"display_names",
"[",
"key",
"]",
"return",
"key",
".",
"capitalize",
"(",
")"
] | get display name for a key, or mangle for display | [
"get",
"display",
"name",
"for",
"a",
"key",
"or",
"mangle",
"for",
"display"
] | cf2060a1d5ef879a01cf849e54b7756909ab2661 | https://github.com/peeringdb/peeringdb-py/blob/cf2060a1d5ef879a01cf849e54b7756909ab2661/peeringdb/whois.py#L32-L37 | train |
peeringdb/peeringdb-py | peeringdb/whois.py | WhoisFormat.display_set | def display_set(self, typ, data, columns):
""" display a list of dicts """
self.display_section("%s (%d)" % (self._get_name(typ), len(data)))
headers = tuple(map(self._get_name, columns))
fmt = self.mk_set_headers(data, columns)
self.display_headers(fmt, headers)
for eac... | python | def display_set(self, typ, data, columns):
""" display a list of dicts """
self.display_section("%s (%d)" % (self._get_name(typ), len(data)))
headers = tuple(map(self._get_name, columns))
fmt = self.mk_set_headers(data, columns)
self.display_headers(fmt, headers)
for eac... | [
"def",
"display_set",
"(",
"self",
",",
"typ",
",",
"data",
",",
"columns",
")",
":",
"self",
".",
"display_section",
"(",
"\"%s (%d)\"",
"%",
"(",
"self",
".",
"_get_name",
"(",
"typ",
")",
",",
"len",
"(",
"data",
")",
")",
")",
"headers",
"=",
"... | display a list of dicts | [
"display",
"a",
"list",
"of",
"dicts"
] | cf2060a1d5ef879a01cf849e54b7756909ab2661 | https://github.com/peeringdb/peeringdb-py/blob/cf2060a1d5ef879a01cf849e54b7756909ab2661/peeringdb/whois.py#L56-L67 | train |
peeringdb/peeringdb-py | peeringdb/whois.py | WhoisFormat._print | def _print(self, *args):
""" internal print to self.fobj """
string = u" ".join(args) + '\n'
self.fobj.write(string) | python | def _print(self, *args):
""" internal print to self.fobj """
string = u" ".join(args) + '\n'
self.fobj.write(string) | [
"def",
"_print",
"(",
"self",
",",
"*",
"args",
")",
":",
"string",
"=",
"u\" \"",
".",
"join",
"(",
"args",
")",
"+",
"'\\n'",
"self",
".",
"fobj",
".",
"write",
"(",
"string",
")"
] | internal print to self.fobj | [
"internal",
"print",
"to",
"self",
".",
"fobj"
] | cf2060a1d5ef879a01cf849e54b7756909ab2661 | https://github.com/peeringdb/peeringdb-py/blob/cf2060a1d5ef879a01cf849e54b7756909ab2661/peeringdb/whois.py#L152-L155 | train |
peeringdb/peeringdb-py | peeringdb/whois.py | WhoisFormat.display | def display(self, typ, data):
""" display section of typ with data """
if hasattr(self, 'print_' + typ):
getattr(self, 'print_' + typ)(data)
elif not data:
self._print("%s: %s" % (typ, data))
elif isinstance(data, collections.Mapping):
self._print("\... | python | def display(self, typ, data):
""" display section of typ with data """
if hasattr(self, 'print_' + typ):
getattr(self, 'print_' + typ)(data)
elif not data:
self._print("%s: %s" % (typ, data))
elif isinstance(data, collections.Mapping):
self._print("\... | [
"def",
"display",
"(",
"self",
",",
"typ",
",",
"data",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"'print_'",
"+",
"typ",
")",
":",
"getattr",
"(",
"self",
",",
"'print_'",
"+",
"typ",
")",
"(",
"data",
")",
"elif",
"not",
"data",
":",
"self",... | display section of typ with data | [
"display",
"section",
"of",
"typ",
"with",
"data"
] | cf2060a1d5ef879a01cf849e54b7756909ab2661 | https://github.com/peeringdb/peeringdb-py/blob/cf2060a1d5ef879a01cf849e54b7756909ab2661/peeringdb/whois.py#L161-L184 | train |
peeringdb/peeringdb-py | peeringdb/commands.py | _handler | def _handler(func):
"Decorate a command handler"
def _wrapped(*a, **k):
r = func(*a, **k)
if r is None: r = 0
return r
return staticmethod(_wrapped) | python | def _handler(func):
"Decorate a command handler"
def _wrapped(*a, **k):
r = func(*a, **k)
if r is None: r = 0
return r
return staticmethod(_wrapped) | [
"def",
"_handler",
"(",
"func",
")",
":",
"\"Decorate a command handler\"",
"def",
"_wrapped",
"(",
"*",
"a",
",",
"**",
"k",
")",
":",
"r",
"=",
"func",
"(",
"*",
"a",
",",
"**",
"k",
")",
"if",
"r",
"is",
"None",
":",
"r",
"=",
"0",
"return",
... | Decorate a command handler | [
"Decorate",
"a",
"command",
"handler"
] | cf2060a1d5ef879a01cf849e54b7756909ab2661 | https://github.com/peeringdb/peeringdb-py/blob/cf2060a1d5ef879a01cf849e54b7756909ab2661/peeringdb/commands.py#L16-L24 | train |
peeringdb/peeringdb-py | peeringdb/commands.py | add_subcommands | def add_subcommands(parser, commands):
"Add commands to a parser"
subps = parser.add_subparsers()
for cmd, cls in commands:
subp = subps.add_parser(cmd, help=cls.__doc__)
add_args = getattr(cls, 'add_arguments', None)
if add_args:
add_args(subp)
handler = getattr(... | python | def add_subcommands(parser, commands):
"Add commands to a parser"
subps = parser.add_subparsers()
for cmd, cls in commands:
subp = subps.add_parser(cmd, help=cls.__doc__)
add_args = getattr(cls, 'add_arguments', None)
if add_args:
add_args(subp)
handler = getattr(... | [
"def",
"add_subcommands",
"(",
"parser",
",",
"commands",
")",
":",
"\"Add commands to a parser\"",
"subps",
"=",
"parser",
".",
"add_subparsers",
"(",
")",
"for",
"cmd",
",",
"cls",
"in",
"commands",
":",
"subp",
"=",
"subps",
".",
"add_parser",
"(",
"cmd",... | Add commands to a parser | [
"Add",
"commands",
"to",
"a",
"parser"
] | cf2060a1d5ef879a01cf849e54b7756909ab2661 | https://github.com/peeringdb/peeringdb-py/blob/cf2060a1d5ef879a01cf849e54b7756909ab2661/peeringdb/commands.py#L27-L37 | train |
peeringdb/peeringdb-py | peeringdb/_update.py | Updater.update | def update(self, res, pk, depth=1, since=None):
"""
Try to sync an object to the local database, in case of failure
where a referenced object is not found, attempt to fetch said
object from the REST api
"""
fetch = lambda: self._fetcher.fetch_latest(res, pk, 1, since=sinc... | python | def update(self, res, pk, depth=1, since=None):
"""
Try to sync an object to the local database, in case of failure
where a referenced object is not found, attempt to fetch said
object from the REST api
"""
fetch = lambda: self._fetcher.fetch_latest(res, pk, 1, since=sinc... | [
"def",
"update",
"(",
"self",
",",
"res",
",",
"pk",
",",
"depth",
"=",
"1",
",",
"since",
"=",
"None",
")",
":",
"fetch",
"=",
"lambda",
":",
"self",
".",
"_fetcher",
".",
"fetch_latest",
"(",
"res",
",",
"pk",
",",
"1",
",",
"since",
"=",
"si... | Try to sync an object to the local database, in case of failure
where a referenced object is not found, attempt to fetch said
object from the REST api | [
"Try",
"to",
"sync",
"an",
"object",
"to",
"the",
"local",
"database",
"in",
"case",
"of",
"failure",
"where",
"a",
"referenced",
"object",
"is",
"not",
"found",
"attempt",
"to",
"fetch",
"said",
"object",
"from",
"the",
"REST",
"api"
] | cf2060a1d5ef879a01cf849e54b7756909ab2661 | https://github.com/peeringdb/peeringdb-py/blob/cf2060a1d5ef879a01cf849e54b7756909ab2661/peeringdb/_update.py#L44-L51 | train |
peeringdb/peeringdb-py | peeringdb/_update.py | UpdateContext.get_task | def get_task(self, key):
"""Get a scheduled task, or none"""
res, pk = key
jobs, lock = self._jobs
with lock:
return jobs[res].get(pk) | python | def get_task(self, key):
"""Get a scheduled task, or none"""
res, pk = key
jobs, lock = self._jobs
with lock:
return jobs[res].get(pk) | [
"def",
"get_task",
"(",
"self",
",",
"key",
")",
":",
"res",
",",
"pk",
"=",
"key",
"jobs",
",",
"lock",
"=",
"self",
".",
"_jobs",
"with",
"lock",
":",
"return",
"jobs",
"[",
"res",
"]",
".",
"get",
"(",
"pk",
")"
] | Get a scheduled task, or none | [
"Get",
"a",
"scheduled",
"task",
"or",
"none"
] | cf2060a1d5ef879a01cf849e54b7756909ab2661 | https://github.com/peeringdb/peeringdb-py/blob/cf2060a1d5ef879a01cf849e54b7756909ab2661/peeringdb/_update.py#L121-L126 | train |
peeringdb/peeringdb-py | peeringdb/_update.py | UpdateContext.set_job | def set_job(self, key, func, args):
"""
Get a scheduled task or set if none exists.
Returns:
- task coroutine/continuation
"""
res, pk = key
jobs, lock = self._jobs
task = _tasks.UpdateTask(func(*args), key)
with lock:
job = jobs[r... | python | def set_job(self, key, func, args):
"""
Get a scheduled task or set if none exists.
Returns:
- task coroutine/continuation
"""
res, pk = key
jobs, lock = self._jobs
task = _tasks.UpdateTask(func(*args), key)
with lock:
job = jobs[r... | [
"def",
"set_job",
"(",
"self",
",",
"key",
",",
"func",
",",
"args",
")",
":",
"res",
",",
"pk",
"=",
"key",
"jobs",
",",
"lock",
"=",
"self",
".",
"_jobs",
"task",
"=",
"_tasks",
".",
"UpdateTask",
"(",
"func",
"(",
"*",
"args",
")",
",",
"key... | Get a scheduled task or set if none exists.
Returns:
- task coroutine/continuation | [
"Get",
"a",
"scheduled",
"task",
"or",
"set",
"if",
"none",
"exists",
"."
] | cf2060a1d5ef879a01cf849e54b7756909ab2661 | https://github.com/peeringdb/peeringdb-py/blob/cf2060a1d5ef879a01cf849e54b7756909ab2661/peeringdb/_update.py#L128-L148 | train |
peeringdb/peeringdb-py | peeringdb/_update.py | UpdateContext.pending_tasks | def pending_tasks(self, res):
"Synchronized access to tasks"
jobs, lock = self._jobs
with lock:
return jobs[res].copy() | python | def pending_tasks(self, res):
"Synchronized access to tasks"
jobs, lock = self._jobs
with lock:
return jobs[res].copy() | [
"def",
"pending_tasks",
"(",
"self",
",",
"res",
")",
":",
"\"Synchronized access to tasks\"",
"jobs",
",",
"lock",
"=",
"self",
".",
"_jobs",
"with",
"lock",
":",
"return",
"jobs",
"[",
"res",
"]",
".",
"copy",
"(",
")"
] | Synchronized access to tasks | [
"Synchronized",
"access",
"to",
"tasks"
] | cf2060a1d5ef879a01cf849e54b7756909ab2661 | https://github.com/peeringdb/peeringdb-py/blob/cf2060a1d5ef879a01cf849e54b7756909ab2661/peeringdb/_update.py#L150-L154 | train |
peeringdb/peeringdb-py | peeringdb/_update.py | UpdateContext.fetch_and_index | def fetch_and_index(self, fetch_func):
"Fetch data with func, return dict indexed by ID"
data, e = fetch_func()
if e: raise e
yield {row['id']: row for row in data} | python | def fetch_and_index(self, fetch_func):
"Fetch data with func, return dict indexed by ID"
data, e = fetch_func()
if e: raise e
yield {row['id']: row for row in data} | [
"def",
"fetch_and_index",
"(",
"self",
",",
"fetch_func",
")",
":",
"\"Fetch data with func, return dict indexed by ID\"",
"data",
",",
"e",
"=",
"fetch_func",
"(",
")",
"if",
"e",
":",
"raise",
"e",
"yield",
"{",
"row",
"[",
"'id'",
"]",
":",
"row",
"for",
... | Fetch data with func, return dict indexed by ID | [
"Fetch",
"data",
"with",
"func",
"return",
"dict",
"indexed",
"by",
"ID"
] | cf2060a1d5ef879a01cf849e54b7756909ab2661 | https://github.com/peeringdb/peeringdb-py/blob/cf2060a1d5ef879a01cf849e54b7756909ab2661/peeringdb/_update.py#L157-L161 | train |
peeringdb/peeringdb-py | peeringdb/_sync.py | initialize_object | def initialize_object(B, res, row):
"""
Do a shallow initialization of an object
Arguments:
- row<dict>: dict of data like depth=1, i.e. many_refs are only ids
"""
B = get_backend()
field_groups = FieldGroups(B.get_concrete(res))
try:
obj = B.get_object(B.get_concrete(res),... | python | def initialize_object(B, res, row):
"""
Do a shallow initialization of an object
Arguments:
- row<dict>: dict of data like depth=1, i.e. many_refs are only ids
"""
B = get_backend()
field_groups = FieldGroups(B.get_concrete(res))
try:
obj = B.get_object(B.get_concrete(res),... | [
"def",
"initialize_object",
"(",
"B",
",",
"res",
",",
"row",
")",
":",
"B",
"=",
"get_backend",
"(",
")",
"field_groups",
"=",
"FieldGroups",
"(",
"B",
".",
"get_concrete",
"(",
"res",
")",
")",
"try",
":",
"obj",
"=",
"B",
".",
"get_object",
"(",
... | Do a shallow initialization of an object
Arguments:
- row<dict>: dict of data like depth=1, i.e. many_refs are only ids | [
"Do",
"a",
"shallow",
"initialization",
"of",
"an",
"object"
] | cf2060a1d5ef879a01cf849e54b7756909ab2661 | https://github.com/peeringdb/peeringdb-py/blob/cf2060a1d5ef879a01cf849e54b7756909ab2661/peeringdb/_sync.py#L36-L88 | train |
peeringdb/peeringdb-py | peeringdb/config.py | read_config | def read_config(conf_dir=DEFAULT_CONFIG_DIR):
"Find and read config file for a directory, return None if not found."
conf_path = os.path.expanduser(conf_dir)
if not os.path.exists(conf_path):
# only throw if not default
if conf_dir != DEFAULT_CONFIG_DIR:
raise IOError("Config di... | python | def read_config(conf_dir=DEFAULT_CONFIG_DIR):
"Find and read config file for a directory, return None if not found."
conf_path = os.path.expanduser(conf_dir)
if not os.path.exists(conf_path):
# only throw if not default
if conf_dir != DEFAULT_CONFIG_DIR:
raise IOError("Config di... | [
"def",
"read_config",
"(",
"conf_dir",
"=",
"DEFAULT_CONFIG_DIR",
")",
":",
"\"Find and read config file for a directory, return None if not found.\"",
"conf_path",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"conf_dir",
")",
"if",
"not",
"os",
".",
"path",
".",
... | Find and read config file for a directory, return None if not found. | [
"Find",
"and",
"read",
"config",
"file",
"for",
"a",
"directory",
"return",
"None",
"if",
"not",
"found",
"."
] | cf2060a1d5ef879a01cf849e54b7756909ab2661 | https://github.com/peeringdb/peeringdb-py/blob/cf2060a1d5ef879a01cf849e54b7756909ab2661/peeringdb/config.py#L59-L68 | train |
peeringdb/peeringdb-py | peeringdb/config.py | detect_old | def detect_old(data):
"Check for a config file with old schema"
if not data:
return False
ok, errors, warnings = _schema.validate(_OLD_SCHEMA, data)
return ok and not (errors or warnings) | python | def detect_old(data):
"Check for a config file with old schema"
if not data:
return False
ok, errors, warnings = _schema.validate(_OLD_SCHEMA, data)
return ok and not (errors or warnings) | [
"def",
"detect_old",
"(",
"data",
")",
":",
"\"Check for a config file with old schema\"",
"if",
"not",
"data",
":",
"return",
"False",
"ok",
",",
"errors",
",",
"warnings",
"=",
"_schema",
".",
"validate",
"(",
"_OLD_SCHEMA",
",",
"data",
")",
"return",
"ok",... | Check for a config file with old schema | [
"Check",
"for",
"a",
"config",
"file",
"with",
"old",
"schema"
] | cf2060a1d5ef879a01cf849e54b7756909ab2661 | https://github.com/peeringdb/peeringdb-py/blob/cf2060a1d5ef879a01cf849e54b7756909ab2661/peeringdb/config.py#L107-L112 | train |
peeringdb/peeringdb-py | peeringdb/config.py | convert_old | def convert_old(data):
"Convert config data with old schema to new schema"
ret = default_config()
ret['sync'].update(data.get('peeringdb', {}))
ret['orm']['database'].update(data.get('database', {}))
return ret | python | def convert_old(data):
"Convert config data with old schema to new schema"
ret = default_config()
ret['sync'].update(data.get('peeringdb', {}))
ret['orm']['database'].update(data.get('database', {}))
return ret | [
"def",
"convert_old",
"(",
"data",
")",
":",
"\"Convert config data with old schema to new schema\"",
"ret",
"=",
"default_config",
"(",
")",
"ret",
"[",
"'sync'",
"]",
".",
"update",
"(",
"data",
".",
"get",
"(",
"'peeringdb'",
",",
"{",
"}",
")",
")",
"ret... | Convert config data with old schema to new schema | [
"Convert",
"config",
"data",
"with",
"old",
"schema",
"to",
"new",
"schema"
] | cf2060a1d5ef879a01cf849e54b7756909ab2661 | https://github.com/peeringdb/peeringdb-py/blob/cf2060a1d5ef879a01cf849e54b7756909ab2661/peeringdb/config.py#L115-L120 | train |
peeringdb/peeringdb-py | peeringdb/config.py | write_config | def write_config(data, conf_dir=DEFAULT_CONFIG_DIR, codec="yaml",
backup_existing=False):
"""
Write config values to a file.
Arguments:
- conf_dir<str>: path to output directory
- codec<str>: output field format
- backup_existing<bool>: if a config file exists,
... | python | def write_config(data, conf_dir=DEFAULT_CONFIG_DIR, codec="yaml",
backup_existing=False):
"""
Write config values to a file.
Arguments:
- conf_dir<str>: path to output directory
- codec<str>: output field format
- backup_existing<bool>: if a config file exists,
... | [
"def",
"write_config",
"(",
"data",
",",
"conf_dir",
"=",
"DEFAULT_CONFIG_DIR",
",",
"codec",
"=",
"\"yaml\"",
",",
"backup_existing",
"=",
"False",
")",
":",
"if",
"not",
"codec",
":",
"codec",
"=",
"'yaml'",
"codec",
"=",
"munge",
".",
"get_codec",
"(",
... | Write config values to a file.
Arguments:
- conf_dir<str>: path to output directory
- codec<str>: output field format
- backup_existing<bool>: if a config file exists,
make a copy before overwriting | [
"Write",
"config",
"values",
"to",
"a",
"file",
"."
] | cf2060a1d5ef879a01cf849e54b7756909ab2661 | https://github.com/peeringdb/peeringdb-py/blob/cf2060a1d5ef879a01cf849e54b7756909ab2661/peeringdb/config.py#L123-L145 | train |
peeringdb/peeringdb-py | peeringdb/config.py | prompt_config | def prompt_config(sch, defaults=None, path=None):
"""
Utility function to recursively prompt for config values
Arguments:
- defaults<dict>: default values used for empty inputs
- path<str>: path to prepend to config keys (eg. "path.keyname")
"""
out = {}
for name, attr in sch.at... | python | def prompt_config(sch, defaults=None, path=None):
"""
Utility function to recursively prompt for config values
Arguments:
- defaults<dict>: default values used for empty inputs
- path<str>: path to prepend to config keys (eg. "path.keyname")
"""
out = {}
for name, attr in sch.at... | [
"def",
"prompt_config",
"(",
"sch",
",",
"defaults",
"=",
"None",
",",
"path",
"=",
"None",
")",
":",
"out",
"=",
"{",
"}",
"for",
"name",
",",
"attr",
"in",
"sch",
".",
"attributes",
"(",
")",
":",
"fullpath",
"=",
"name",
"if",
"path",
":",
"fu... | Utility function to recursively prompt for config values
Arguments:
- defaults<dict>: default values used for empty inputs
- path<str>: path to prepend to config keys (eg. "path.keyname") | [
"Utility",
"function",
"to",
"recursively",
"prompt",
"for",
"config",
"values"
] | cf2060a1d5ef879a01cf849e54b7756909ab2661 | https://github.com/peeringdb/peeringdb-py/blob/cf2060a1d5ef879a01cf849e54b7756909ab2661/peeringdb/config.py#L148-L175 | train |
peeringdb/peeringdb-py | peeringdb/client.py | Client.fetch | def fetch(self, R, pk, depth=1):
"Request object from API"
d, e = self._fetcher.fetch(R, pk, depth)
if e: raise e
return d | python | def fetch(self, R, pk, depth=1):
"Request object from API"
d, e = self._fetcher.fetch(R, pk, depth)
if e: raise e
return d | [
"def",
"fetch",
"(",
"self",
",",
"R",
",",
"pk",
",",
"depth",
"=",
"1",
")",
":",
"\"Request object from API\"",
"d",
",",
"e",
"=",
"self",
".",
"_fetcher",
".",
"fetch",
"(",
"R",
",",
"pk",
",",
"depth",
")",
"if",
"e",
":",
"raise",
"e",
... | Request object from API | [
"Request",
"object",
"from",
"API"
] | cf2060a1d5ef879a01cf849e54b7756909ab2661 | https://github.com/peeringdb/peeringdb-py/blob/cf2060a1d5ef879a01cf849e54b7756909ab2661/peeringdb/client.py#L64-L68 | train |
peeringdb/peeringdb-py | peeringdb/client.py | Client.fetch_all | def fetch_all(self, R, depth=1, **kwargs):
"Request multiple objects from API"
d, e = self._fetcher.fetch_all(R, depth, kwargs)
if e: raise e
return d | python | def fetch_all(self, R, depth=1, **kwargs):
"Request multiple objects from API"
d, e = self._fetcher.fetch_all(R, depth, kwargs)
if e: raise e
return d | [
"def",
"fetch_all",
"(",
"self",
",",
"R",
",",
"depth",
"=",
"1",
",",
"**",
"kwargs",
")",
":",
"\"Request multiple objects from API\"",
"d",
",",
"e",
"=",
"self",
".",
"_fetcher",
".",
"fetch_all",
"(",
"R",
",",
"depth",
",",
"kwargs",
")",
"if",
... | Request multiple objects from API | [
"Request",
"multiple",
"objects",
"from",
"API"
] | cf2060a1d5ef879a01cf849e54b7756909ab2661 | https://github.com/peeringdb/peeringdb-py/blob/cf2060a1d5ef879a01cf849e54b7756909ab2661/peeringdb/client.py#L70-L74 | train |
peeringdb/peeringdb-py | peeringdb/client.py | Client.all | def all(self, res):
"Get resources using a filter condition"
B = get_backend()
return B.get_objects(B.get_concrete(res)) | python | def all(self, res):
"Get resources using a filter condition"
B = get_backend()
return B.get_objects(B.get_concrete(res)) | [
"def",
"all",
"(",
"self",
",",
"res",
")",
":",
"\"Get resources using a filter condition\"",
"B",
"=",
"get_backend",
"(",
")",
"return",
"B",
".",
"get_objects",
"(",
"B",
".",
"get_concrete",
"(",
"res",
")",
")"
] | Get resources using a filter condition | [
"Get",
"resources",
"using",
"a",
"filter",
"condition"
] | cf2060a1d5ef879a01cf849e54b7756909ab2661 | https://github.com/peeringdb/peeringdb-py/blob/cf2060a1d5ef879a01cf849e54b7756909ab2661/peeringdb/client.py#L81-L84 | train |
peeringdb/peeringdb-py | peeringdb/_tasks_sequential.py | run_task | def run_task(func):
"""
Decorator to collect and return generator results, returning a list
if there are multiple results
"""
def _wrapped(*a, **k):
gen = func(*a, **k)
return _consume_task(gen)
return _wrapped | python | def run_task(func):
"""
Decorator to collect and return generator results, returning a list
if there are multiple results
"""
def _wrapped(*a, **k):
gen = func(*a, **k)
return _consume_task(gen)
return _wrapped | [
"def",
"run_task",
"(",
"func",
")",
":",
"def",
"_wrapped",
"(",
"*",
"a",
",",
"**",
"k",
")",
":",
"gen",
"=",
"func",
"(",
"*",
"a",
",",
"**",
"k",
")",
"return",
"_consume_task",
"(",
"gen",
")",
"return",
"_wrapped"
] | Decorator to collect and return generator results, returning a list
if there are multiple results | [
"Decorator",
"to",
"collect",
"and",
"return",
"generator",
"results",
"returning",
"a",
"list",
"if",
"there",
"are",
"multiple",
"results"
] | cf2060a1d5ef879a01cf849e54b7756909ab2661 | https://github.com/peeringdb/peeringdb-py/blob/cf2060a1d5ef879a01cf849e54b7756909ab2661/peeringdb/_tasks_sequential.py#L69-L79 | train |
peeringdb/peeringdb-py | peeringdb/_fetch.py | Fetcher.get | def get(self, typ, id, **kwargs):
"""
Load type by id
"""
return self._load(self._request(typ, id=id, params=kwargs)) | python | def get(self, typ, id, **kwargs):
"""
Load type by id
"""
return self._load(self._request(typ, id=id, params=kwargs)) | [
"def",
"get",
"(",
"self",
",",
"typ",
",",
"id",
",",
"**",
"kwargs",
")",
":",
"return",
"self",
".",
"_load",
"(",
"self",
".",
"_request",
"(",
"typ",
",",
"id",
"=",
"id",
",",
"params",
"=",
"kwargs",
")",
")"
] | Load type by id | [
"Load",
"type",
"by",
"id"
] | cf2060a1d5ef879a01cf849e54b7756909ab2661 | https://github.com/peeringdb/peeringdb-py/blob/cf2060a1d5ef879a01cf849e54b7756909ab2661/peeringdb/_fetch.py#L83-L87 | train |
peeringdb/peeringdb-py | peeringdb/_tasks_async.py | wrap_generator | def wrap_generator(func):
"""
Decorator to convert a generator function to an async function which collects
and returns generator results, returning a list if there are multiple results
"""
async def _wrapped(*a, **k):
r, ret = None, []
gen = func(*a, **k)
while True:
... | python | def wrap_generator(func):
"""
Decorator to convert a generator function to an async function which collects
and returns generator results, returning a list if there are multiple results
"""
async def _wrapped(*a, **k):
r, ret = None, []
gen = func(*a, **k)
while True:
... | [
"def",
"wrap_generator",
"(",
"func",
")",
":",
"async",
"def",
"_wrapped",
"(",
"*",
"a",
",",
"**",
"k",
")",
":",
"r",
",",
"ret",
"=",
"None",
",",
"[",
"]",
"gen",
"=",
"func",
"(",
"*",
"a",
",",
"**",
"k",
")",
"while",
"True",
":",
... | Decorator to convert a generator function to an async function which collects
and returns generator results, returning a list if there are multiple results | [
"Decorator",
"to",
"convert",
"a",
"generator",
"function",
"to",
"an",
"async",
"function",
"which",
"collects",
"and",
"returns",
"generator",
"results",
"returning",
"a",
"list",
"if",
"there",
"are",
"multiple",
"results"
] | cf2060a1d5ef879a01cf849e54b7756909ab2661 | https://github.com/peeringdb/peeringdb-py/blob/cf2060a1d5ef879a01cf849e54b7756909ab2661/peeringdb/_tasks_async.py#L30-L54 | train |
peeringdb/peeringdb-py | peeringdb/_tasks_async.py | run_task | def run_task(func):
"""
Decorator to wrap an async function in an event loop.
Use for main sync interface methods.
"""
def _wrapped(*a, **k):
loop = asyncio.get_event_loop()
return loop.run_until_complete(func(*a, **k))
return _wrapped | python | def run_task(func):
"""
Decorator to wrap an async function in an event loop.
Use for main sync interface methods.
"""
def _wrapped(*a, **k):
loop = asyncio.get_event_loop()
return loop.run_until_complete(func(*a, **k))
return _wrapped | [
"def",
"run_task",
"(",
"func",
")",
":",
"def",
"_wrapped",
"(",
"*",
"a",
",",
"**",
"k",
")",
":",
"loop",
"=",
"asyncio",
".",
"get_event_loop",
"(",
")",
"return",
"loop",
".",
"run_until_complete",
"(",
"func",
"(",
"*",
"a",
",",
"**",
"k",
... | Decorator to wrap an async function in an event loop.
Use for main sync interface methods. | [
"Decorator",
"to",
"wrap",
"an",
"async",
"function",
"in",
"an",
"event",
"loop",
".",
"Use",
"for",
"main",
"sync",
"interface",
"methods",
"."
] | cf2060a1d5ef879a01cf849e54b7756909ab2661 | https://github.com/peeringdb/peeringdb-py/blob/cf2060a1d5ef879a01cf849e54b7756909ab2661/peeringdb/_tasks_async.py#L57-L67 | train |
peeringdb/peeringdb-py | peeringdb/util.py | prompt | def prompt(msg, default=None):
"Prompt for input"
if default is not None:
msg = '{} ({})'.format(msg, repr(default))
msg = '{}: '.format(msg)
try:
s = input(msg)
except KeyboardInterrupt:
exit(1)
except EOFError:
s = ''
if not s:
s = default
return... | python | def prompt(msg, default=None):
"Prompt for input"
if default is not None:
msg = '{} ({})'.format(msg, repr(default))
msg = '{}: '.format(msg)
try:
s = input(msg)
except KeyboardInterrupt:
exit(1)
except EOFError:
s = ''
if not s:
s = default
return... | [
"def",
"prompt",
"(",
"msg",
",",
"default",
"=",
"None",
")",
":",
"\"Prompt for input\"",
"if",
"default",
"is",
"not",
"None",
":",
"msg",
"=",
"'{} ({})'",
".",
"format",
"(",
"msg",
",",
"repr",
"(",
"default",
")",
")",
"msg",
"=",
"'{}: '",
".... | Prompt for input | [
"Prompt",
"for",
"input"
] | cf2060a1d5ef879a01cf849e54b7756909ab2661 | https://github.com/peeringdb/peeringdb-py/blob/cf2060a1d5ef879a01cf849e54b7756909ab2661/peeringdb/util.py#L37-L50 | train |
peeringdb/peeringdb-py | peeringdb/util.py | limit_mem | def limit_mem(limit=(4 * 1024**3)):
"Set soft memory limit"
rsrc = resource.RLIMIT_DATA
soft, hard = resource.getrlimit(rsrc)
resource.setrlimit(rsrc, (limit, hard)) # 4GB
softnew, _ = resource.getrlimit(rsrc)
assert softnew == limit
_log = logging.getLogger(__name__)
_log.debug('Set s... | python | def limit_mem(limit=(4 * 1024**3)):
"Set soft memory limit"
rsrc = resource.RLIMIT_DATA
soft, hard = resource.getrlimit(rsrc)
resource.setrlimit(rsrc, (limit, hard)) # 4GB
softnew, _ = resource.getrlimit(rsrc)
assert softnew == limit
_log = logging.getLogger(__name__)
_log.debug('Set s... | [
"def",
"limit_mem",
"(",
"limit",
"=",
"(",
"4",
"*",
"1024",
"**",
"3",
")",
")",
":",
"\"Set soft memory limit\"",
"rsrc",
"=",
"resource",
".",
"RLIMIT_DATA",
"soft",
",",
"hard",
"=",
"resource",
".",
"getrlimit",
"(",
"rsrc",
")",
"resource",
".",
... | Set soft memory limit | [
"Set",
"soft",
"memory",
"limit"
] | cf2060a1d5ef879a01cf849e54b7756909ab2661 | https://github.com/peeringdb/peeringdb-py/blob/cf2060a1d5ef879a01cf849e54b7756909ab2661/peeringdb/util.py#L86-L95 | train |
nerox8664/gluon2pytorch | gluon2pytorch/gluon2pytorch.py | render_module | def render_module(inits, calls, inputs, outputs, dst_dir, pytorch_dict, pytorch_module_name):
"""
Render model.
"""
inits = [i for i in inits if len(i) > 0]
output = pytorch_model_template.format(**{
'module_name': pytorch_module_name,
'module_name_lower': pytorch_module_name.lower... | python | def render_module(inits, calls, inputs, outputs, dst_dir, pytorch_dict, pytorch_module_name):
"""
Render model.
"""
inits = [i for i in inits if len(i) > 0]
output = pytorch_model_template.format(**{
'module_name': pytorch_module_name,
'module_name_lower': pytorch_module_name.lower... | [
"def",
"render_module",
"(",
"inits",
",",
"calls",
",",
"inputs",
",",
"outputs",
",",
"dst_dir",
",",
"pytorch_dict",
",",
"pytorch_module_name",
")",
":",
"inits",
"=",
"[",
"i",
"for",
"i",
"in",
"inits",
"if",
"len",
"(",
"i",
")",
">",
"0",
"]"... | Render model. | [
"Render",
"model",
"."
] | 4fad7fc3a0a478d68bd509e239d4b7f1e0748ffa | https://github.com/nerox8664/gluon2pytorch/blob/4fad7fc3a0a478d68bd509e239d4b7f1e0748ffa/gluon2pytorch/gluon2pytorch.py#L31-L63 | train |
kowalpy/Robot-Framework-FTP-Library | FtpLibrary.py | FtpLibrary.getAllFtpConnections | def getAllFtpConnections(self):
"""
Returns a dictionary containing active ftp connections.
"""
outputMsg = "Current ftp connections:\n"
counter = 1
for k in self.ftpList:
outputMsg += str(counter) + ". " + k + " "
outputMsg += str(self.ftpList[k])... | python | def getAllFtpConnections(self):
"""
Returns a dictionary containing active ftp connections.
"""
outputMsg = "Current ftp connections:\n"
counter = 1
for k in self.ftpList:
outputMsg += str(counter) + ". " + k + " "
outputMsg += str(self.ftpList[k])... | [
"def",
"getAllFtpConnections",
"(",
"self",
")",
":",
"outputMsg",
"=",
"\"Current ftp connections:\\n\"",
"counter",
"=",
"1",
"for",
"k",
"in",
"self",
".",
"ftpList",
":",
"outputMsg",
"+=",
"str",
"(",
"counter",
")",
"+",
"\". \"",
"+",
"k",
"+",
"\" ... | Returns a dictionary containing active ftp connections. | [
"Returns",
"a",
"dictionary",
"containing",
"active",
"ftp",
"connections",
"."
] | 90794be0a12af489ac98e8ae3b4ff450c83e2f3d | https://github.com/kowalpy/Robot-Framework-FTP-Library/blob/90794be0a12af489ac98e8ae3b4ff450c83e2f3d/FtpLibrary.py#L105-L117 | train |
Robpol86/sphinxcontrib-versioning | sphinxcontrib/versioning/setup_logging.py | setup_logging | def setup_logging(verbose=0, colors=False, name=None):
"""Configure console logging. Info and below go to stdout, others go to stderr.
:param int verbose: Verbosity level. > 0 print debug statements. > 1 passed to sphinx-build.
:param bool colors: Print color text in non-verbose mode.
:param str name: ... | python | def setup_logging(verbose=0, colors=False, name=None):
"""Configure console logging. Info and below go to stdout, others go to stderr.
:param int verbose: Verbosity level. > 0 print debug statements. > 1 passed to sphinx-build.
:param bool colors: Print color text in non-verbose mode.
:param str name: ... | [
"def",
"setup_logging",
"(",
"verbose",
"=",
"0",
",",
"colors",
"=",
"False",
",",
"name",
"=",
"None",
")",
":",
"root_logger",
"=",
"logging",
".",
"getLogger",
"(",
"name",
")",
"root_logger",
".",
"setLevel",
"(",
"logging",
".",
"DEBUG",
"if",
"v... | Configure console logging. Info and below go to stdout, others go to stderr.
:param int verbose: Verbosity level. > 0 print debug statements. > 1 passed to sphinx-build.
:param bool colors: Print color text in non-verbose mode.
:param str name: Which logger name to set handlers to. Used for testing. | [
"Configure",
"console",
"logging",
".",
"Info",
"and",
"below",
"go",
"to",
"stdout",
"others",
"go",
"to",
"stderr",
"."
] | 920edec0ac764081b583a2ecf4e6952762b9dbf2 | https://github.com/Robpol86/sphinxcontrib-versioning/blob/920edec0ac764081b583a2ecf4e6952762b9dbf2/sphinxcontrib/versioning/setup_logging.py#L55-L77 | train |
Robpol86/sphinxcontrib-versioning | sphinxcontrib/versioning/setup_logging.py | ColorFormatter.format | def format(self, record):
"""Apply little arrow and colors to the record.
Arrow and colors are only applied to sphinxcontrib.versioning log statements.
:param logging.LogRecord record: The log record object to log.
"""
formatted = super(ColorFormatter, self).format(record)
... | python | def format(self, record):
"""Apply little arrow and colors to the record.
Arrow and colors are only applied to sphinxcontrib.versioning log statements.
:param logging.LogRecord record: The log record object to log.
"""
formatted = super(ColorFormatter, self).format(record)
... | [
"def",
"format",
"(",
"self",
",",
"record",
")",
":",
"formatted",
"=",
"super",
"(",
"ColorFormatter",
",",
"self",
")",
".",
"format",
"(",
"record",
")",
"if",
"self",
".",
"verbose",
"or",
"not",
"record",
".",
"name",
".",
"startswith",
"(",
"s... | Apply little arrow and colors to the record.
Arrow and colors are only applied to sphinxcontrib.versioning log statements.
:param logging.LogRecord record: The log record object to log. | [
"Apply",
"little",
"arrow",
"and",
"colors",
"to",
"the",
"record",
"."
] | 920edec0ac764081b583a2ecf4e6952762b9dbf2 | https://github.com/Robpol86/sphinxcontrib-versioning/blob/920edec0ac764081b583a2ecf4e6952762b9dbf2/sphinxcontrib/versioning/setup_logging.py#L29-L52 | train |
Robpol86/sphinxcontrib-versioning | sphinxcontrib/versioning/git.py | get_root | def get_root(directory):
"""Get root directory of the local git repo from any subdirectory within it.
:raise GitError: If git command fails (dir not a git repo?).
:param str directory: Subdirectory in the local repo.
:return: Root directory of repository.
:rtype: str
"""
command = ['git',... | python | def get_root(directory):
"""Get root directory of the local git repo from any subdirectory within it.
:raise GitError: If git command fails (dir not a git repo?).
:param str directory: Subdirectory in the local repo.
:return: Root directory of repository.
:rtype: str
"""
command = ['git',... | [
"def",
"get_root",
"(",
"directory",
")",
":",
"command",
"=",
"[",
"'git'",
",",
"'rev-parse'",
",",
"'--show-toplevel'",
"]",
"try",
":",
"output",
"=",
"run_command",
"(",
"directory",
",",
"command",
",",
"env_var",
"=",
"False",
")",
"except",
"Called... | Get root directory of the local git repo from any subdirectory within it.
:raise GitError: If git command fails (dir not a git repo?).
:param str directory: Subdirectory in the local repo.
:return: Root directory of repository.
:rtype: str | [
"Get",
"root",
"directory",
"of",
"the",
"local",
"git",
"repo",
"from",
"any",
"subdirectory",
"within",
"it",
"."
] | 920edec0ac764081b583a2ecf4e6952762b9dbf2 | https://github.com/Robpol86/sphinxcontrib-versioning/blob/920edec0ac764081b583a2ecf4e6952762b9dbf2/sphinxcontrib/versioning/git.py#L161-L178 | train |
Robpol86/sphinxcontrib-versioning | sphinxcontrib/versioning/git.py | filter_and_date | def filter_and_date(local_root, conf_rel_paths, commits):
"""Get commit Unix timestamps and first matching conf.py path. Exclude commits with no conf.py file.
:raise CalledProcessError: Unhandled git command failure.
:raise GitError: A commit SHA has not been fetched.
:param str local_root: Local path... | python | def filter_and_date(local_root, conf_rel_paths, commits):
"""Get commit Unix timestamps and first matching conf.py path. Exclude commits with no conf.py file.
:raise CalledProcessError: Unhandled git command failure.
:raise GitError: A commit SHA has not been fetched.
:param str local_root: Local path... | [
"def",
"filter_and_date",
"(",
"local_root",
",",
"conf_rel_paths",
",",
"commits",
")",
":",
"dates_paths",
"=",
"dict",
"(",
")",
"for",
"commit",
"in",
"commits",
":",
"if",
"commit",
"in",
"dates_paths",
":",
"continue",
"command",
"=",
"[",
"'git'",
"... | Get commit Unix timestamps and first matching conf.py path. Exclude commits with no conf.py file.
:raise CalledProcessError: Unhandled git command failure.
:raise GitError: A commit SHA has not been fetched.
:param str local_root: Local path to git root directory.
:param iter conf_rel_paths: List of p... | [
"Get",
"commit",
"Unix",
"timestamps",
"and",
"first",
"matching",
"conf",
".",
"py",
"path",
".",
"Exclude",
"commits",
"with",
"no",
"conf",
".",
"py",
"file",
"."
] | 920edec0ac764081b583a2ecf4e6952762b9dbf2 | https://github.com/Robpol86/sphinxcontrib-versioning/blob/920edec0ac764081b583a2ecf4e6952762b9dbf2/sphinxcontrib/versioning/git.py#L212-L249 | train |
Robpol86/sphinxcontrib-versioning | sphinxcontrib/versioning/git.py | fetch_commits | def fetch_commits(local_root, remotes):
"""Fetch from origin.
:raise CalledProcessError: Unhandled git command failure.
:param str local_root: Local path to git root directory.
:param iter remotes: Output of list_remote().
"""
# Fetch all known branches.
command = ['git', 'fetch', 'origin'... | python | def fetch_commits(local_root, remotes):
"""Fetch from origin.
:raise CalledProcessError: Unhandled git command failure.
:param str local_root: Local path to git root directory.
:param iter remotes: Output of list_remote().
"""
# Fetch all known branches.
command = ['git', 'fetch', 'origin'... | [
"def",
"fetch_commits",
"(",
"local_root",
",",
"remotes",
")",
":",
"command",
"=",
"[",
"'git'",
",",
"'fetch'",
",",
"'origin'",
"]",
"run_command",
"(",
"local_root",
",",
"command",
")",
"for",
"sha",
",",
"name",
",",
"kind",
"in",
"remotes",
":",
... | Fetch from origin.
:raise CalledProcessError: Unhandled git command failure.
:param str local_root: Local path to git root directory.
:param iter remotes: Output of list_remote(). | [
"Fetch",
"from",
"origin",
"."
] | 920edec0ac764081b583a2ecf4e6952762b9dbf2 | https://github.com/Robpol86/sphinxcontrib-versioning/blob/920edec0ac764081b583a2ecf4e6952762b9dbf2/sphinxcontrib/versioning/git.py#L252-L270 | train |
Robpol86/sphinxcontrib-versioning | sphinxcontrib/versioning/git.py | export | def export(local_root, commit, target):
"""Export git commit to directory. "Extracts" all files at the commit to the target directory.
Set mtime of RST files to last commit date.
:raise CalledProcessError: Unhandled git command failure.
:param str local_root: Local path to git root directory.
:pa... | python | def export(local_root, commit, target):
"""Export git commit to directory. "Extracts" all files at the commit to the target directory.
Set mtime of RST files to last commit date.
:raise CalledProcessError: Unhandled git command failure.
:param str local_root: Local path to git root directory.
:pa... | [
"def",
"export",
"(",
"local_root",
",",
"commit",
",",
"target",
")",
":",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
"target",
"=",
"os",
".",
"path",
".",
"realpath",
"(",
"target",
")",
"mtimes",
"=",
"list",
"(",
")",
"def",
... | Export git commit to directory. "Extracts" all files at the commit to the target directory.
Set mtime of RST files to last commit date.
:raise CalledProcessError: Unhandled git command failure.
:param str local_root: Local path to git root directory.
:param str commit: Git commit SHA to export.
:... | [
"Export",
"git",
"commit",
"to",
"directory",
".",
"Extracts",
"all",
"files",
"at",
"the",
"commit",
"to",
"the",
"target",
"directory",
"."
] | 920edec0ac764081b583a2ecf4e6952762b9dbf2 | https://github.com/Robpol86/sphinxcontrib-versioning/blob/920edec0ac764081b583a2ecf4e6952762b9dbf2/sphinxcontrib/versioning/git.py#L273-L322 | train |
Robpol86/sphinxcontrib-versioning | sphinxcontrib/versioning/git.py | clone | def clone(local_root, new_root, remote, branch, rel_dest, exclude):
"""Clone "local_root" origin into a new directory and check out a specific branch. Optionally run "git rm".
:raise CalledProcessError: Unhandled git command failure.
:raise GitError: Handled git failures.
:param str local_root: Local ... | python | def clone(local_root, new_root, remote, branch, rel_dest, exclude):
"""Clone "local_root" origin into a new directory and check out a specific branch. Optionally run "git rm".
:raise CalledProcessError: Unhandled git command failure.
:raise GitError: Handled git failures.
:param str local_root: Local ... | [
"def",
"clone",
"(",
"local_root",
",",
"new_root",
",",
"remote",
",",
"branch",
",",
"rel_dest",
",",
"exclude",
")",
":",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
"output",
"=",
"run_command",
"(",
"local_root",
",",
"[",
"'git'"... | Clone "local_root" origin into a new directory and check out a specific branch. Optionally run "git rm".
:raise CalledProcessError: Unhandled git command failure.
:raise GitError: Handled git failures.
:param str local_root: Local path to git root directory.
:param str new_root: Local path empty direc... | [
"Clone",
"local_root",
"origin",
"into",
"a",
"new",
"directory",
"and",
"check",
"out",
"a",
"specific",
"branch",
".",
"Optionally",
"run",
"git",
"rm",
"."
] | 920edec0ac764081b583a2ecf4e6952762b9dbf2 | https://github.com/Robpol86/sphinxcontrib-versioning/blob/920edec0ac764081b583a2ecf4e6952762b9dbf2/sphinxcontrib/versioning/git.py#L325-L390 | train |
Robpol86/sphinxcontrib-versioning | sphinxcontrib/versioning/git.py | commit_and_push | def commit_and_push(local_root, remote, versions):
"""Commit changed, new, and deleted files in the repo and attempt to push the branch to the remote repository.
:raise CalledProcessError: Unhandled git command failure.
:raise GitError: Conflicting changes made in remote by other client and bad git config ... | python | def commit_and_push(local_root, remote, versions):
"""Commit changed, new, and deleted files in the repo and attempt to push the branch to the remote repository.
:raise CalledProcessError: Unhandled git command failure.
:raise GitError: Conflicting changes made in remote by other client and bad git config ... | [
"def",
"commit_and_push",
"(",
"local_root",
",",
"remote",
",",
"versions",
")",
":",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
"current_branch",
"=",
"run_command",
"(",
"local_root",
",",
"[",
"'git'",
",",
"'rev-parse'",
",",
"'--abb... | Commit changed, new, and deleted files in the repo and attempt to push the branch to the remote repository.
:raise CalledProcessError: Unhandled git command failure.
:raise GitError: Conflicting changes made in remote by other client and bad git config for commits.
:param str local_root: Local path to git... | [
"Commit",
"changed",
"new",
"and",
"deleted",
"files",
"in",
"the",
"repo",
"and",
"attempt",
"to",
"push",
"the",
"branch",
"to",
"the",
"remote",
"repository",
"."
] | 920edec0ac764081b583a2ecf4e6952762b9dbf2 | https://github.com/Robpol86/sphinxcontrib-versioning/blob/920edec0ac764081b583a2ecf4e6952762b9dbf2/sphinxcontrib/versioning/git.py#L393-L457 | train |
Robpol86/sphinxcontrib-versioning | sphinxcontrib/versioning/versions.py | multi_sort | def multi_sort(remotes, sort):
"""Sort `remotes` in place. Allows sorting by multiple conditions.
This is needed because Python 3 no longer supports sorting lists of multiple types. Sort keys must all be of the
same type.
Problem: the user expects versions to be sorted latest first and timelogical to ... | python | def multi_sort(remotes, sort):
"""Sort `remotes` in place. Allows sorting by multiple conditions.
This is needed because Python 3 no longer supports sorting lists of multiple types. Sort keys must all be of the
same type.
Problem: the user expects versions to be sorted latest first and timelogical to ... | [
"def",
"multi_sort",
"(",
"remotes",
",",
"sort",
")",
":",
"exploded_alpha",
"=",
"list",
"(",
")",
"exploded_semver",
"=",
"list",
"(",
")",
"if",
"'alpha'",
"in",
"sort",
":",
"alpha_max_len",
"=",
"max",
"(",
"len",
"(",
"r",
"[",
"'name'",
"]",
... | Sort `remotes` in place. Allows sorting by multiple conditions.
This is needed because Python 3 no longer supports sorting lists of multiple types. Sort keys must all be of the
same type.
Problem: the user expects versions to be sorted latest first and timelogical to be most recent first (when viewing
... | [
"Sort",
"remotes",
"in",
"place",
".",
"Allows",
"sorting",
"by",
"multiple",
"conditions",
"."
] | 920edec0ac764081b583a2ecf4e6952762b9dbf2 | https://github.com/Robpol86/sphinxcontrib-versioning/blob/920edec0ac764081b583a2ecf4e6952762b9dbf2/sphinxcontrib/versioning/versions.py#L47-L87 | train |
Robpol86/sphinxcontrib-versioning | sphinxcontrib/versioning/routines.py | read_local_conf | def read_local_conf(local_conf):
"""Search for conf.py in any rel_source directory in CWD and if found read it and return.
:param str local_conf: Path to conf.py to read.
:return: Loaded conf.py.
:rtype: dict
"""
log = logging.getLogger(__name__)
# Attempt to read.
log.info('Reading c... | python | def read_local_conf(local_conf):
"""Search for conf.py in any rel_source directory in CWD and if found read it and return.
:param str local_conf: Path to conf.py to read.
:return: Loaded conf.py.
:rtype: dict
"""
log = logging.getLogger(__name__)
# Attempt to read.
log.info('Reading c... | [
"def",
"read_local_conf",
"(",
"local_conf",
")",
":",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
"log",
".",
"info",
"(",
"'Reading config from %s...'",
",",
"local_conf",
")",
"try",
":",
"config",
"=",
"read_config",
"(",
"os",
".",
... | Search for conf.py in any rel_source directory in CWD and if found read it and return.
:param str local_conf: Path to conf.py to read.
:return: Loaded conf.py.
:rtype: dict | [
"Search",
"for",
"conf",
".",
"py",
"in",
"any",
"rel_source",
"directory",
"in",
"CWD",
"and",
"if",
"found",
"read",
"it",
"and",
"return",
"."
] | 920edec0ac764081b583a2ecf4e6952762b9dbf2 | https://github.com/Robpol86/sphinxcontrib-versioning/blob/920edec0ac764081b583a2ecf4e6952762b9dbf2/sphinxcontrib/versioning/routines.py#L16-L35 | train |
Robpol86/sphinxcontrib-versioning | sphinxcontrib/versioning/routines.py | gather_git_info | def gather_git_info(root, conf_rel_paths, whitelist_branches, whitelist_tags):
"""Gather info about the remote git repository. Get list of refs.
:raise HandledError: If function fails with a handled error. Will be logged before raising.
:param str root: Root directory of repository.
:param iter conf_r... | python | def gather_git_info(root, conf_rel_paths, whitelist_branches, whitelist_tags):
"""Gather info about the remote git repository. Get list of refs.
:raise HandledError: If function fails with a handled error. Will be logged before raising.
:param str root: Root directory of repository.
:param iter conf_r... | [
"def",
"gather_git_info",
"(",
"root",
",",
"conf_rel_paths",
",",
"whitelist_branches",
",",
"whitelist_tags",
")",
":",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
"log",
".",
"info",
"(",
"'Getting list of all remote branches/tags...'",
")",
... | Gather info about the remote git repository. Get list of refs.
:raise HandledError: If function fails with a handled error. Will be logged before raising.
:param str root: Root directory of repository.
:param iter conf_rel_paths: List of possible relative paths (to git root) of Sphinx conf.py (e.g. docs/c... | [
"Gather",
"info",
"about",
"the",
"remote",
"git",
"repository",
".",
"Get",
"list",
"of",
"refs",
"."
] | 920edec0ac764081b583a2ecf4e6952762b9dbf2 | https://github.com/Robpol86/sphinxcontrib-versioning/blob/920edec0ac764081b583a2ecf4e6952762b9dbf2/sphinxcontrib/versioning/routines.py#L38-L97 | train |
Robpol86/sphinxcontrib-versioning | sphinxcontrib/versioning/routines.py | pre_build | def pre_build(local_root, versions):
"""Build docs for all versions to determine root directory and master_doc names.
Need to build docs to (a) avoid filename collision with files from root_ref and branch/tag names and (b) determine
master_doc config values for all versions (in case master_doc changes from... | python | def pre_build(local_root, versions):
"""Build docs for all versions to determine root directory and master_doc names.
Need to build docs to (a) avoid filename collision with files from root_ref and branch/tag names and (b) determine
master_doc config values for all versions (in case master_doc changes from... | [
"def",
"pre_build",
"(",
"local_root",
",",
"versions",
")",
":",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
"exported_root",
"=",
"TempDir",
"(",
"True",
")",
".",
"name",
"for",
"sha",
"in",
"{",
"r",
"[",
"'sha'",
"]",
"for",
"... | Build docs for all versions to determine root directory and master_doc names.
Need to build docs to (a) avoid filename collision with files from root_ref and branch/tag names and (b) determine
master_doc config values for all versions (in case master_doc changes from e.g. contents.rst to index.rst between
... | [
"Build",
"docs",
"for",
"all",
"versions",
"to",
"determine",
"root",
"directory",
"and",
"master_doc",
"names",
"."
] | 920edec0ac764081b583a2ecf4e6952762b9dbf2 | https://github.com/Robpol86/sphinxcontrib-versioning/blob/920edec0ac764081b583a2ecf4e6952762b9dbf2/sphinxcontrib/versioning/routines.py#L100-L154 | train |
Robpol86/sphinxcontrib-versioning | sphinxcontrib/versioning/routines.py | build_all | def build_all(exported_root, destination, versions):
"""Build all versions.
:param str exported_root: Tempdir path with exported commits as subdirectories.
:param str destination: Destination directory to copy/overwrite built docs to. Does not delete old files.
:param sphinxcontrib.versioning.versions.... | python | def build_all(exported_root, destination, versions):
"""Build all versions.
:param str exported_root: Tempdir path with exported commits as subdirectories.
:param str destination: Destination directory to copy/overwrite built docs to. Does not delete old files.
:param sphinxcontrib.versioning.versions.... | [
"def",
"build_all",
"(",
"exported_root",
",",
"destination",
",",
"versions",
")",
":",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
"while",
"True",
":",
"remote",
"=",
"versions",
"[",
"Config",
".",
"from_context",
"(",
")",
".",
"r... | Build all versions.
:param str exported_root: Tempdir path with exported commits as subdirectories.
:param str destination: Destination directory to copy/overwrite built docs to. Does not delete old files.
:param sphinxcontrib.versioning.versions.Versions versions: Versions class instance. | [
"Build",
"all",
"versions",
"."
] | 920edec0ac764081b583a2ecf4e6952762b9dbf2 | https://github.com/Robpol86/sphinxcontrib-versioning/blob/920edec0ac764081b583a2ecf4e6952762b9dbf2/sphinxcontrib/versioning/routines.py#L157-L185 | train |
Robpol86/sphinxcontrib-versioning | sphinxcontrib/versioning/sphinx_.py | _build | def _build(argv, config, versions, current_name, is_root):
"""Build Sphinx docs via multiprocessing for isolation.
:param tuple argv: Arguments to pass to Sphinx.
:param sphinxcontrib.versioning.lib.Config config: Runtime configuration.
:param sphinxcontrib.versioning.versions.Versions versions: Versio... | python | def _build(argv, config, versions, current_name, is_root):
"""Build Sphinx docs via multiprocessing for isolation.
:param tuple argv: Arguments to pass to Sphinx.
:param sphinxcontrib.versioning.lib.Config config: Runtime configuration.
:param sphinxcontrib.versioning.versions.Versions versions: Versio... | [
"def",
"_build",
"(",
"argv",
",",
"config",
",",
"versions",
",",
"current_name",
",",
"is_root",
")",
":",
"application",
".",
"Config",
"=",
"ConfigInject",
"if",
"config",
".",
"show_banner",
":",
"EventHandlers",
".",
"BANNER_GREATEST_TAG",
"=",
"config",... | Build Sphinx docs via multiprocessing for isolation.
:param tuple argv: Arguments to pass to Sphinx.
:param sphinxcontrib.versioning.lib.Config config: Runtime configuration.
:param sphinxcontrib.versioning.versions.Versions versions: Versions class instance.
:param str current_name: The ref name of th... | [
"Build",
"Sphinx",
"docs",
"via",
"multiprocessing",
"for",
"isolation",
"."
] | 920edec0ac764081b583a2ecf4e6952762b9dbf2 | https://github.com/Robpol86/sphinxcontrib-versioning/blob/920edec0ac764081b583a2ecf4e6952762b9dbf2/sphinxcontrib/versioning/sphinx_.py#L172-L204 | train |
Robpol86/sphinxcontrib-versioning | sphinxcontrib/versioning/sphinx_.py | _read_config | def _read_config(argv, config, current_name, queue):
"""Read the Sphinx config via multiprocessing for isolation.
:param tuple argv: Arguments to pass to Sphinx.
:param sphinxcontrib.versioning.lib.Config config: Runtime configuration.
:param str current_name: The ref name of the current version being ... | python | def _read_config(argv, config, current_name, queue):
"""Read the Sphinx config via multiprocessing for isolation.
:param tuple argv: Arguments to pass to Sphinx.
:param sphinxcontrib.versioning.lib.Config config: Runtime configuration.
:param str current_name: The ref name of the current version being ... | [
"def",
"_read_config",
"(",
"argv",
",",
"config",
",",
"current_name",
",",
"queue",
")",
":",
"EventHandlers",
".",
"ABORT_AFTER_READ",
"=",
"queue",
"_build",
"(",
"argv",
",",
"config",
",",
"Versions",
"(",
"list",
"(",
")",
")",
",",
"current_name",
... | Read the Sphinx config via multiprocessing for isolation.
:param tuple argv: Arguments to pass to Sphinx.
:param sphinxcontrib.versioning.lib.Config config: Runtime configuration.
:param str current_name: The ref name of the current version being built.
:param multiprocessing.queues.Queue queue: Commun... | [
"Read",
"the",
"Sphinx",
"config",
"via",
"multiprocessing",
"for",
"isolation",
"."
] | 920edec0ac764081b583a2ecf4e6952762b9dbf2 | https://github.com/Robpol86/sphinxcontrib-versioning/blob/920edec0ac764081b583a2ecf4e6952762b9dbf2/sphinxcontrib/versioning/sphinx_.py#L207-L219 | train |
Robpol86/sphinxcontrib-versioning | sphinxcontrib/versioning/sphinx_.py | read_config | def read_config(source, current_name):
"""Read the Sphinx config for one version.
:raise HandledError: If sphinx-build fails. Will be logged before raising.
:param str source: Source directory to pass to sphinx-build.
:param str current_name: The ref name of the current version being built.
:retu... | python | def read_config(source, current_name):
"""Read the Sphinx config for one version.
:raise HandledError: If sphinx-build fails. Will be logged before raising.
:param str source: Source directory to pass to sphinx-build.
:param str current_name: The ref name of the current version being built.
:retu... | [
"def",
"read_config",
"(",
"source",
",",
"current_name",
")",
":",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
"queue",
"=",
"multiprocessing",
".",
"Queue",
"(",
")",
"config",
"=",
"Config",
".",
"from_context",
"(",
")",
"with",
"T... | Read the Sphinx config for one version.
:raise HandledError: If sphinx-build fails. Will be logged before raising.
:param str source: Source directory to pass to sphinx-build.
:param str current_name: The ref name of the current version being built.
:return: Specific Sphinx config values.
:rtype:... | [
"Read",
"the",
"Sphinx",
"config",
"for",
"one",
"version",
"."
] | 920edec0ac764081b583a2ecf4e6952762b9dbf2 | https://github.com/Robpol86/sphinxcontrib-versioning/blob/920edec0ac764081b583a2ecf4e6952762b9dbf2/sphinxcontrib/versioning/sphinx_.py#L246-L272 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.