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 |
---|---|---|---|---|---|---|---|---|---|---|---|
mathiasertl/django-ca
|
ca/django_ca/utils.py
|
parse_encoding
|
def parse_encoding(value=None):
"""Parse a value to a valid encoding.
This function accepts either a member of
:py:class:`~cg:cryptography.hazmat.primitives.serialization.Encoding` or a string describing a member. If
no value is passed, it will assume ``PEM`` as a default value. Note that ``"ASN1"`` is treated as an alias
for ``"DER"``.
>>> parse_encoding()
<Encoding.PEM: 'PEM'>
>>> parse_encoding('DER')
<Encoding.DER: 'DER'>
>>> parse_encoding(Encoding.PEM)
<Encoding.PEM: 'PEM'>
"""
if value is None:
return ca_settings.CA_DEFAULT_ENCODING
elif isinstance(value, Encoding):
return value
elif isinstance(value, six.string_types):
if value == 'ASN1':
value = 'DER'
try:
return getattr(Encoding, value)
except AttributeError:
raise ValueError('Unknown encoding: %s' % value)
else:
raise ValueError('Unknown type passed: %s' % type(value).__name__)
|
python
|
def parse_encoding(value=None):
"""Parse a value to a valid encoding.
This function accepts either a member of
:py:class:`~cg:cryptography.hazmat.primitives.serialization.Encoding` or a string describing a member. If
no value is passed, it will assume ``PEM`` as a default value. Note that ``"ASN1"`` is treated as an alias
for ``"DER"``.
>>> parse_encoding()
<Encoding.PEM: 'PEM'>
>>> parse_encoding('DER')
<Encoding.DER: 'DER'>
>>> parse_encoding(Encoding.PEM)
<Encoding.PEM: 'PEM'>
"""
if value is None:
return ca_settings.CA_DEFAULT_ENCODING
elif isinstance(value, Encoding):
return value
elif isinstance(value, six.string_types):
if value == 'ASN1':
value = 'DER'
try:
return getattr(Encoding, value)
except AttributeError:
raise ValueError('Unknown encoding: %s' % value)
else:
raise ValueError('Unknown type passed: %s' % type(value).__name__)
|
[
"def",
"parse_encoding",
"(",
"value",
"=",
"None",
")",
":",
"if",
"value",
"is",
"None",
":",
"return",
"ca_settings",
".",
"CA_DEFAULT_ENCODING",
"elif",
"isinstance",
"(",
"value",
",",
"Encoding",
")",
":",
"return",
"value",
"elif",
"isinstance",
"(",
"value",
",",
"six",
".",
"string_types",
")",
":",
"if",
"value",
"==",
"'ASN1'",
":",
"value",
"=",
"'DER'",
"try",
":",
"return",
"getattr",
"(",
"Encoding",
",",
"value",
")",
"except",
"AttributeError",
":",
"raise",
"ValueError",
"(",
"'Unknown encoding: %s'",
"%",
"value",
")",
"else",
":",
"raise",
"ValueError",
"(",
"'Unknown type passed: %s'",
"%",
"type",
"(",
"value",
")",
".",
"__name__",
")"
] |
Parse a value to a valid encoding.
This function accepts either a member of
:py:class:`~cg:cryptography.hazmat.primitives.serialization.Encoding` or a string describing a member. If
no value is passed, it will assume ``PEM`` as a default value. Note that ``"ASN1"`` is treated as an alias
for ``"DER"``.
>>> parse_encoding()
<Encoding.PEM: 'PEM'>
>>> parse_encoding('DER')
<Encoding.DER: 'DER'>
>>> parse_encoding(Encoding.PEM)
<Encoding.PEM: 'PEM'>
|
[
"Parse",
"a",
"value",
"to",
"a",
"valid",
"encoding",
"."
] |
976d7ea05276320f20daed2a6d59c8f5660fe976
|
https://github.com/mathiasertl/django-ca/blob/976d7ea05276320f20daed2a6d59c8f5660fe976/ca/django_ca/utils.py#L558-L586
|
train
|
mathiasertl/django-ca
|
ca/django_ca/utils.py
|
parse_key_curve
|
def parse_key_curve(value=None):
"""Parse an elliptic curve value.
This function uses a value identifying an elliptic curve to return an
:py:class:`~cg:cryptography.hazmat.primitives.asymmetric.ec.EllipticCurve` instance. The name must match a
class name of one of the classes named under "Elliptic Curves" in
:any:`cg:hazmat/primitives/asymmetric/ec`.
For convenience, passing ``None`` will return the value of :ref:`CA_DEFAULT_ECC_CURVE
<settings-ca-default-ecc-curve>`, and passing an
:py:class:`~cg:cryptography.hazmat.primitives.asymmetric.ec.EllipticCurve` will return that instance
unchanged.
Example usage::
>>> parse_key_curve('SECP256R1') # doctest: +ELLIPSIS
<cryptography.hazmat.primitives.asymmetric.ec.SECP256R1 object at ...>
>>> parse_key_curve('SECP384R1') # doctest: +ELLIPSIS
<cryptography.hazmat.primitives.asymmetric.ec.SECP384R1 object at ...>
>>> parse_key_curve(ec.SECP256R1()) # doctest: +ELLIPSIS
<cryptography.hazmat.primitives.asymmetric.ec.SECP256R1 object at ...>
>>> parse_key_curve() # doctest: +ELLIPSIS
<cryptography.hazmat.primitives.asymmetric.ec.SECP256R1 object at ...>
Parameters
----------
value : str, otional
The name of the curve or ``None`` to return the default curve.
Returns
-------
curve
An :py:class:`~cg:cryptography.hazmat.primitives.asymmetric.ec.EllipticCurve` instance.
Raises
------
ValueError
If the named curve is not supported.
"""
if isinstance(value, ec.EllipticCurve):
return value # name was already parsed
if value is None:
return ca_settings.CA_DEFAULT_ECC_CURVE
curve = getattr(ec, value.strip(), type)
if not issubclass(curve, ec.EllipticCurve):
raise ValueError('%s: Not a known Eliptic Curve' % value)
return curve()
|
python
|
def parse_key_curve(value=None):
"""Parse an elliptic curve value.
This function uses a value identifying an elliptic curve to return an
:py:class:`~cg:cryptography.hazmat.primitives.asymmetric.ec.EllipticCurve` instance. The name must match a
class name of one of the classes named under "Elliptic Curves" in
:any:`cg:hazmat/primitives/asymmetric/ec`.
For convenience, passing ``None`` will return the value of :ref:`CA_DEFAULT_ECC_CURVE
<settings-ca-default-ecc-curve>`, and passing an
:py:class:`~cg:cryptography.hazmat.primitives.asymmetric.ec.EllipticCurve` will return that instance
unchanged.
Example usage::
>>> parse_key_curve('SECP256R1') # doctest: +ELLIPSIS
<cryptography.hazmat.primitives.asymmetric.ec.SECP256R1 object at ...>
>>> parse_key_curve('SECP384R1') # doctest: +ELLIPSIS
<cryptography.hazmat.primitives.asymmetric.ec.SECP384R1 object at ...>
>>> parse_key_curve(ec.SECP256R1()) # doctest: +ELLIPSIS
<cryptography.hazmat.primitives.asymmetric.ec.SECP256R1 object at ...>
>>> parse_key_curve() # doctest: +ELLIPSIS
<cryptography.hazmat.primitives.asymmetric.ec.SECP256R1 object at ...>
Parameters
----------
value : str, otional
The name of the curve or ``None`` to return the default curve.
Returns
-------
curve
An :py:class:`~cg:cryptography.hazmat.primitives.asymmetric.ec.EllipticCurve` instance.
Raises
------
ValueError
If the named curve is not supported.
"""
if isinstance(value, ec.EllipticCurve):
return value # name was already parsed
if value is None:
return ca_settings.CA_DEFAULT_ECC_CURVE
curve = getattr(ec, value.strip(), type)
if not issubclass(curve, ec.EllipticCurve):
raise ValueError('%s: Not a known Eliptic Curve' % value)
return curve()
|
[
"def",
"parse_key_curve",
"(",
"value",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"ec",
".",
"EllipticCurve",
")",
":",
"return",
"value",
"# name was already parsed",
"if",
"value",
"is",
"None",
":",
"return",
"ca_settings",
".",
"CA_DEFAULT_ECC_CURVE",
"curve",
"=",
"getattr",
"(",
"ec",
",",
"value",
".",
"strip",
"(",
")",
",",
"type",
")",
"if",
"not",
"issubclass",
"(",
"curve",
",",
"ec",
".",
"EllipticCurve",
")",
":",
"raise",
"ValueError",
"(",
"'%s: Not a known Eliptic Curve'",
"%",
"value",
")",
"return",
"curve",
"(",
")"
] |
Parse an elliptic curve value.
This function uses a value identifying an elliptic curve to return an
:py:class:`~cg:cryptography.hazmat.primitives.asymmetric.ec.EllipticCurve` instance. The name must match a
class name of one of the classes named under "Elliptic Curves" in
:any:`cg:hazmat/primitives/asymmetric/ec`.
For convenience, passing ``None`` will return the value of :ref:`CA_DEFAULT_ECC_CURVE
<settings-ca-default-ecc-curve>`, and passing an
:py:class:`~cg:cryptography.hazmat.primitives.asymmetric.ec.EllipticCurve` will return that instance
unchanged.
Example usage::
>>> parse_key_curve('SECP256R1') # doctest: +ELLIPSIS
<cryptography.hazmat.primitives.asymmetric.ec.SECP256R1 object at ...>
>>> parse_key_curve('SECP384R1') # doctest: +ELLIPSIS
<cryptography.hazmat.primitives.asymmetric.ec.SECP384R1 object at ...>
>>> parse_key_curve(ec.SECP256R1()) # doctest: +ELLIPSIS
<cryptography.hazmat.primitives.asymmetric.ec.SECP256R1 object at ...>
>>> parse_key_curve() # doctest: +ELLIPSIS
<cryptography.hazmat.primitives.asymmetric.ec.SECP256R1 object at ...>
Parameters
----------
value : str, otional
The name of the curve or ``None`` to return the default curve.
Returns
-------
curve
An :py:class:`~cg:cryptography.hazmat.primitives.asymmetric.ec.EllipticCurve` instance.
Raises
------
ValueError
If the named curve is not supported.
|
[
"Parse",
"an",
"elliptic",
"curve",
"value",
"."
] |
976d7ea05276320f20daed2a6d59c8f5660fe976
|
https://github.com/mathiasertl/django-ca/blob/976d7ea05276320f20daed2a6d59c8f5660fe976/ca/django_ca/utils.py#L589-L639
|
train
|
mathiasertl/django-ca
|
ca/django_ca/utils.py
|
get_cert_builder
|
def get_cert_builder(expires):
"""Get a basic X509 cert builder object.
Parameters
----------
expires : datetime
When this certificate will expire.
"""
now = datetime.utcnow().replace(second=0, microsecond=0)
if expires is None:
expires = get_expires(expires, now=now)
expires = expires.replace(second=0, microsecond=0)
builder = x509.CertificateBuilder()
builder = builder.not_valid_before(now)
builder = builder.not_valid_after(expires)
builder = builder.serial_number(x509.random_serial_number())
return builder
|
python
|
def get_cert_builder(expires):
"""Get a basic X509 cert builder object.
Parameters
----------
expires : datetime
When this certificate will expire.
"""
now = datetime.utcnow().replace(second=0, microsecond=0)
if expires is None:
expires = get_expires(expires, now=now)
expires = expires.replace(second=0, microsecond=0)
builder = x509.CertificateBuilder()
builder = builder.not_valid_before(now)
builder = builder.not_valid_after(expires)
builder = builder.serial_number(x509.random_serial_number())
return builder
|
[
"def",
"get_cert_builder",
"(",
"expires",
")",
":",
"now",
"=",
"datetime",
".",
"utcnow",
"(",
")",
".",
"replace",
"(",
"second",
"=",
"0",
",",
"microsecond",
"=",
"0",
")",
"if",
"expires",
"is",
"None",
":",
"expires",
"=",
"get_expires",
"(",
"expires",
",",
"now",
"=",
"now",
")",
"expires",
"=",
"expires",
".",
"replace",
"(",
"second",
"=",
"0",
",",
"microsecond",
"=",
"0",
")",
"builder",
"=",
"x509",
".",
"CertificateBuilder",
"(",
")",
"builder",
"=",
"builder",
".",
"not_valid_before",
"(",
"now",
")",
"builder",
"=",
"builder",
".",
"not_valid_after",
"(",
"expires",
")",
"builder",
"=",
"builder",
".",
"serial_number",
"(",
"x509",
".",
"random_serial_number",
"(",
")",
")",
"return",
"builder"
] |
Get a basic X509 cert builder object.
Parameters
----------
expires : datetime
When this certificate will expire.
|
[
"Get",
"a",
"basic",
"X509",
"cert",
"builder",
"object",
"."
] |
976d7ea05276320f20daed2a6d59c8f5660fe976
|
https://github.com/mathiasertl/django-ca/blob/976d7ea05276320f20daed2a6d59c8f5660fe976/ca/django_ca/utils.py#L656-L676
|
train
|
mathiasertl/django-ca
|
ca/django_ca/utils.py
|
wrap_file_exceptions
|
def wrap_file_exceptions():
"""Contextmanager to wrap file exceptions into identicaly exceptions in py2 and py3.
This should be removed once py2 support is dropped.
"""
try:
yield
except (PermissionError, FileNotFoundError): # pragma: only py3
# In py3, we want to raise Exception unchanged, so there would be no need for this block.
# BUT (IOError, OSError) - see below - also matches, so we capture it here
raise
except (IOError, OSError) as e: # pragma: only py2
if e.errno == errno.EACCES:
raise PermissionError(str(e))
elif e.errno == errno.ENOENT:
raise FileNotFoundError(str(e))
raise
|
python
|
def wrap_file_exceptions():
"""Contextmanager to wrap file exceptions into identicaly exceptions in py2 and py3.
This should be removed once py2 support is dropped.
"""
try:
yield
except (PermissionError, FileNotFoundError): # pragma: only py3
# In py3, we want to raise Exception unchanged, so there would be no need for this block.
# BUT (IOError, OSError) - see below - also matches, so we capture it here
raise
except (IOError, OSError) as e: # pragma: only py2
if e.errno == errno.EACCES:
raise PermissionError(str(e))
elif e.errno == errno.ENOENT:
raise FileNotFoundError(str(e))
raise
|
[
"def",
"wrap_file_exceptions",
"(",
")",
":",
"try",
":",
"yield",
"except",
"(",
"PermissionError",
",",
"FileNotFoundError",
")",
":",
"# pragma: only py3",
"# In py3, we want to raise Exception unchanged, so there would be no need for this block.",
"# BUT (IOError, OSError) - see below - also matches, so we capture it here",
"raise",
"except",
"(",
"IOError",
",",
"OSError",
")",
"as",
"e",
":",
"# pragma: only py2",
"if",
"e",
".",
"errno",
"==",
"errno",
".",
"EACCES",
":",
"raise",
"PermissionError",
"(",
"str",
"(",
"e",
")",
")",
"elif",
"e",
".",
"errno",
"==",
"errno",
".",
"ENOENT",
":",
"raise",
"FileNotFoundError",
"(",
"str",
"(",
"e",
")",
")",
"raise"
] |
Contextmanager to wrap file exceptions into identicaly exceptions in py2 and py3.
This should be removed once py2 support is dropped.
|
[
"Contextmanager",
"to",
"wrap",
"file",
"exceptions",
"into",
"identicaly",
"exceptions",
"in",
"py2",
"and",
"py3",
"."
] |
976d7ea05276320f20daed2a6d59c8f5660fe976
|
https://github.com/mathiasertl/django-ca/blob/976d7ea05276320f20daed2a6d59c8f5660fe976/ca/django_ca/utils.py#L695-L711
|
train
|
mathiasertl/django-ca
|
ca/django_ca/utils.py
|
read_file
|
def read_file(path):
"""Read the file from the given path.
If ``path`` is an absolute path, reads a file from the local filesystem. For relative paths, read the file
using the storage backend configured using :ref:`CA_FILE_STORAGE <settings-ca-file-storage>`.
"""
if os.path.isabs(path):
with wrap_file_exceptions():
with open(path, 'rb') as stream:
return stream.read()
with wrap_file_exceptions():
stream = ca_storage.open(path)
try:
return stream.read()
finally:
stream.close()
|
python
|
def read_file(path):
"""Read the file from the given path.
If ``path`` is an absolute path, reads a file from the local filesystem. For relative paths, read the file
using the storage backend configured using :ref:`CA_FILE_STORAGE <settings-ca-file-storage>`.
"""
if os.path.isabs(path):
with wrap_file_exceptions():
with open(path, 'rb') as stream:
return stream.read()
with wrap_file_exceptions():
stream = ca_storage.open(path)
try:
return stream.read()
finally:
stream.close()
|
[
"def",
"read_file",
"(",
"path",
")",
":",
"if",
"os",
".",
"path",
".",
"isabs",
"(",
"path",
")",
":",
"with",
"wrap_file_exceptions",
"(",
")",
":",
"with",
"open",
"(",
"path",
",",
"'rb'",
")",
"as",
"stream",
":",
"return",
"stream",
".",
"read",
"(",
")",
"with",
"wrap_file_exceptions",
"(",
")",
":",
"stream",
"=",
"ca_storage",
".",
"open",
"(",
"path",
")",
"try",
":",
"return",
"stream",
".",
"read",
"(",
")",
"finally",
":",
"stream",
".",
"close",
"(",
")"
] |
Read the file from the given path.
If ``path`` is an absolute path, reads a file from the local filesystem. For relative paths, read the file
using the storage backend configured using :ref:`CA_FILE_STORAGE <settings-ca-file-storage>`.
|
[
"Read",
"the",
"file",
"from",
"the",
"given",
"path",
"."
] |
976d7ea05276320f20daed2a6d59c8f5660fe976
|
https://github.com/mathiasertl/django-ca/blob/976d7ea05276320f20daed2a6d59c8f5660fe976/ca/django_ca/utils.py#L714-L731
|
train
|
mathiasertl/django-ca
|
ca/django_ca/utils.py
|
get_extension_name
|
def get_extension_name(ext):
"""Function to get the name of an extension."""
# In cryptography 2.2, SCTs return "Unknown OID"
if ext.oid == ExtensionOID.PRECERT_SIGNED_CERTIFICATE_TIMESTAMPS:
return 'SignedCertificateTimestampList'
# Until at least cryptography 2.6.1, PrecertPoison has no name
# https://github.com/pyca/cryptography/issues/4817
elif ca_settings.CRYPTOGRAPHY_HAS_PRECERT_POISON: # pragma: no branch, pragma: only cryptography>=2.4
if ext.oid == ExtensionOID.PRECERT_POISON:
return 'PrecertPoison'
# uppercase the FIRST letter only ("keyUsage" -> "KeyUsage")
return re.sub('^([a-z])', lambda x: x.groups()[0].upper(), ext.oid._name)
|
python
|
def get_extension_name(ext):
"""Function to get the name of an extension."""
# In cryptography 2.2, SCTs return "Unknown OID"
if ext.oid == ExtensionOID.PRECERT_SIGNED_CERTIFICATE_TIMESTAMPS:
return 'SignedCertificateTimestampList'
# Until at least cryptography 2.6.1, PrecertPoison has no name
# https://github.com/pyca/cryptography/issues/4817
elif ca_settings.CRYPTOGRAPHY_HAS_PRECERT_POISON: # pragma: no branch, pragma: only cryptography>=2.4
if ext.oid == ExtensionOID.PRECERT_POISON:
return 'PrecertPoison'
# uppercase the FIRST letter only ("keyUsage" -> "KeyUsage")
return re.sub('^([a-z])', lambda x: x.groups()[0].upper(), ext.oid._name)
|
[
"def",
"get_extension_name",
"(",
"ext",
")",
":",
"# In cryptography 2.2, SCTs return \"Unknown OID\"",
"if",
"ext",
".",
"oid",
"==",
"ExtensionOID",
".",
"PRECERT_SIGNED_CERTIFICATE_TIMESTAMPS",
":",
"return",
"'SignedCertificateTimestampList'",
"# Until at least cryptography 2.6.1, PrecertPoison has no name",
"# https://github.com/pyca/cryptography/issues/4817",
"elif",
"ca_settings",
".",
"CRYPTOGRAPHY_HAS_PRECERT_POISON",
":",
"# pragma: no branch, pragma: only cryptography>=2.4",
"if",
"ext",
".",
"oid",
"==",
"ExtensionOID",
".",
"PRECERT_POISON",
":",
"return",
"'PrecertPoison'",
"# uppercase the FIRST letter only (\"keyUsage\" -> \"KeyUsage\")",
"return",
"re",
".",
"sub",
"(",
"'^([a-z])'",
",",
"lambda",
"x",
":",
"x",
".",
"groups",
"(",
")",
"[",
"0",
"]",
".",
"upper",
"(",
")",
",",
"ext",
".",
"oid",
".",
"_name",
")"
] |
Function to get the name of an extension.
|
[
"Function",
"to",
"get",
"the",
"name",
"of",
"an",
"extension",
"."
] |
976d7ea05276320f20daed2a6d59c8f5660fe976
|
https://github.com/mathiasertl/django-ca/blob/976d7ea05276320f20daed2a6d59c8f5660fe976/ca/django_ca/utils.py#L734-L748
|
train
|
mathiasertl/django-ca
|
ca/django_ca/utils.py
|
shlex_split
|
def shlex_split(s, sep):
"""Split a character on the given set of characters.
Example::
>>> shlex_split('foo,bar', ', ')
['foo', 'bar']
>>> shlex_split('foo\\\\,bar1', ',') # escape a separator
['foo,bar1']
>>> shlex_split('"foo,bar", bla', ', ')
['foo,bar', 'bla']
>>> shlex_split('foo,"bar,bla"', ',')
['foo', 'bar,bla']
"""
lex = shlex.shlex(s, posix=True)
lex.whitespace = sep
lex.whitespace_split = True
return [l for l in lex]
|
python
|
def shlex_split(s, sep):
"""Split a character on the given set of characters.
Example::
>>> shlex_split('foo,bar', ', ')
['foo', 'bar']
>>> shlex_split('foo\\\\,bar1', ',') # escape a separator
['foo,bar1']
>>> shlex_split('"foo,bar", bla', ', ')
['foo,bar', 'bla']
>>> shlex_split('foo,"bar,bla"', ',')
['foo', 'bar,bla']
"""
lex = shlex.shlex(s, posix=True)
lex.whitespace = sep
lex.whitespace_split = True
return [l for l in lex]
|
[
"def",
"shlex_split",
"(",
"s",
",",
"sep",
")",
":",
"lex",
"=",
"shlex",
".",
"shlex",
"(",
"s",
",",
"posix",
"=",
"True",
")",
"lex",
".",
"whitespace",
"=",
"sep",
"lex",
".",
"whitespace_split",
"=",
"True",
"return",
"[",
"l",
"for",
"l",
"in",
"lex",
"]"
] |
Split a character on the given set of characters.
Example::
>>> shlex_split('foo,bar', ', ')
['foo', 'bar']
>>> shlex_split('foo\\\\,bar1', ',') # escape a separator
['foo,bar1']
>>> shlex_split('"foo,bar", bla', ', ')
['foo,bar', 'bla']
>>> shlex_split('foo,"bar,bla"', ',')
['foo', 'bar,bla']
|
[
"Split",
"a",
"character",
"on",
"the",
"given",
"set",
"of",
"characters",
"."
] |
976d7ea05276320f20daed2a6d59c8f5660fe976
|
https://github.com/mathiasertl/django-ca/blob/976d7ea05276320f20daed2a6d59c8f5660fe976/ca/django_ca/utils.py#L766-L783
|
train
|
mathiasertl/django-ca
|
ca/django_ca/models.py
|
X509CertMixin.get_revocation_reason
|
def get_revocation_reason(self):
"""Get the revocation reason of this certificate."""
if self.revoked is False:
return
if self.revoked_reason == '' or self.revoked_reason is None:
return x509.ReasonFlags.unspecified
else:
return getattr(x509.ReasonFlags, self.revoked_reason)
|
python
|
def get_revocation_reason(self):
"""Get the revocation reason of this certificate."""
if self.revoked is False:
return
if self.revoked_reason == '' or self.revoked_reason is None:
return x509.ReasonFlags.unspecified
else:
return getattr(x509.ReasonFlags, self.revoked_reason)
|
[
"def",
"get_revocation_reason",
"(",
"self",
")",
":",
"if",
"self",
".",
"revoked",
"is",
"False",
":",
"return",
"if",
"self",
".",
"revoked_reason",
"==",
"''",
"or",
"self",
".",
"revoked_reason",
"is",
"None",
":",
"return",
"x509",
".",
"ReasonFlags",
".",
"unspecified",
"else",
":",
"return",
"getattr",
"(",
"x509",
".",
"ReasonFlags",
",",
"self",
".",
"revoked_reason",
")"
] |
Get the revocation reason of this certificate.
|
[
"Get",
"the",
"revocation",
"reason",
"of",
"this",
"certificate",
"."
] |
976d7ea05276320f20daed2a6d59c8f5660fe976
|
https://github.com/mathiasertl/django-ca/blob/976d7ea05276320f20daed2a6d59c8f5660fe976/ca/django_ca/models.py#L159-L167
|
train
|
mathiasertl/django-ca
|
ca/django_ca/models.py
|
X509CertMixin.get_revocation_time
|
def get_revocation_time(self):
"""Get the revocation time as naive datetime.
Note that this method is only used by cryptography>=2.4.
"""
if self.revoked is False:
return
if timezone.is_aware(self.revoked_date):
# convert datetime object to UTC and make it naive
return timezone.make_naive(self.revoked_date, pytz.utc)
return self.revoked_date
|
python
|
def get_revocation_time(self):
"""Get the revocation time as naive datetime.
Note that this method is only used by cryptography>=2.4.
"""
if self.revoked is False:
return
if timezone.is_aware(self.revoked_date):
# convert datetime object to UTC and make it naive
return timezone.make_naive(self.revoked_date, pytz.utc)
return self.revoked_date
|
[
"def",
"get_revocation_time",
"(",
"self",
")",
":",
"if",
"self",
".",
"revoked",
"is",
"False",
":",
"return",
"if",
"timezone",
".",
"is_aware",
"(",
"self",
".",
"revoked_date",
")",
":",
"# convert datetime object to UTC and make it naive",
"return",
"timezone",
".",
"make_naive",
"(",
"self",
".",
"revoked_date",
",",
"pytz",
".",
"utc",
")",
"return",
"self",
".",
"revoked_date"
] |
Get the revocation time as naive datetime.
Note that this method is only used by cryptography>=2.4.
|
[
"Get",
"the",
"revocation",
"time",
"as",
"naive",
"datetime",
"."
] |
976d7ea05276320f20daed2a6d59c8f5660fe976
|
https://github.com/mathiasertl/django-ca/blob/976d7ea05276320f20daed2a6d59c8f5660fe976/ca/django_ca/models.py#L179-L191
|
train
|
mathiasertl/django-ca
|
ca/django_ca/models.py
|
CertificateAuthority.get_authority_key_identifier
|
def get_authority_key_identifier(self):
"""Return the AuthorityKeyIdentifier extension used in certificates signed by this CA."""
try:
ski = self.x509.extensions.get_extension_for_class(x509.SubjectKeyIdentifier)
except x509.ExtensionNotFound:
return x509.AuthorityKeyIdentifier.from_issuer_public_key(self.x509.public_key())
else:
return x509.AuthorityKeyIdentifier.from_issuer_subject_key_identifier(ski)
|
python
|
def get_authority_key_identifier(self):
"""Return the AuthorityKeyIdentifier extension used in certificates signed by this CA."""
try:
ski = self.x509.extensions.get_extension_for_class(x509.SubjectKeyIdentifier)
except x509.ExtensionNotFound:
return x509.AuthorityKeyIdentifier.from_issuer_public_key(self.x509.public_key())
else:
return x509.AuthorityKeyIdentifier.from_issuer_subject_key_identifier(ski)
|
[
"def",
"get_authority_key_identifier",
"(",
"self",
")",
":",
"try",
":",
"ski",
"=",
"self",
".",
"x509",
".",
"extensions",
".",
"get_extension_for_class",
"(",
"x509",
".",
"SubjectKeyIdentifier",
")",
"except",
"x509",
".",
"ExtensionNotFound",
":",
"return",
"x509",
".",
"AuthorityKeyIdentifier",
".",
"from_issuer_public_key",
"(",
"self",
".",
"x509",
".",
"public_key",
"(",
")",
")",
"else",
":",
"return",
"x509",
".",
"AuthorityKeyIdentifier",
".",
"from_issuer_subject_key_identifier",
"(",
"ski",
")"
] |
Return the AuthorityKeyIdentifier extension used in certificates signed by this CA.
|
[
"Return",
"the",
"AuthorityKeyIdentifier",
"extension",
"used",
"in",
"certificates",
"signed",
"by",
"this",
"CA",
"."
] |
976d7ea05276320f20daed2a6d59c8f5660fe976
|
https://github.com/mathiasertl/django-ca/blob/976d7ea05276320f20daed2a6d59c8f5660fe976/ca/django_ca/models.py#L598-L606
|
train
|
mathiasertl/django-ca
|
ca/django_ca/models.py
|
CertificateAuthority.max_pathlen
|
def max_pathlen(self):
"""The maximum pathlen for any intermediate CAs signed by this CA.
This value is either ``None``, if this and all parent CAs don't have a ``pathlen`` attribute, or an
``int`` if any parent CA has the attribute.
"""
pathlen = self.pathlen
if self.parent is None:
return pathlen
max_parent = self.parent.max_pathlen
if max_parent is None:
return pathlen
elif pathlen is None:
return max_parent - 1
else:
return min(self.pathlen, max_parent - 1)
|
python
|
def max_pathlen(self):
"""The maximum pathlen for any intermediate CAs signed by this CA.
This value is either ``None``, if this and all parent CAs don't have a ``pathlen`` attribute, or an
``int`` if any parent CA has the attribute.
"""
pathlen = self.pathlen
if self.parent is None:
return pathlen
max_parent = self.parent.max_pathlen
if max_parent is None:
return pathlen
elif pathlen is None:
return max_parent - 1
else:
return min(self.pathlen, max_parent - 1)
|
[
"def",
"max_pathlen",
"(",
"self",
")",
":",
"pathlen",
"=",
"self",
".",
"pathlen",
"if",
"self",
".",
"parent",
"is",
"None",
":",
"return",
"pathlen",
"max_parent",
"=",
"self",
".",
"parent",
".",
"max_pathlen",
"if",
"max_parent",
"is",
"None",
":",
"return",
"pathlen",
"elif",
"pathlen",
"is",
"None",
":",
"return",
"max_parent",
"-",
"1",
"else",
":",
"return",
"min",
"(",
"self",
".",
"pathlen",
",",
"max_parent",
"-",
"1",
")"
] |
The maximum pathlen for any intermediate CAs signed by this CA.
This value is either ``None``, if this and all parent CAs don't have a ``pathlen`` attribute, or an
``int`` if any parent CA has the attribute.
|
[
"The",
"maximum",
"pathlen",
"for",
"any",
"intermediate",
"CAs",
"signed",
"by",
"this",
"CA",
"."
] |
976d7ea05276320f20daed2a6d59c8f5660fe976
|
https://github.com/mathiasertl/django-ca/blob/976d7ea05276320f20daed2a6d59c8f5660fe976/ca/django_ca/models.py#L721-L739
|
train
|
mathiasertl/django-ca
|
ca/django_ca/models.py
|
CertificateAuthority.bundle
|
def bundle(self):
"""A list of any parent CAs, including this CA.
The list is ordered so the Root CA will be the first.
"""
ca = self
bundle = [ca]
while ca.parent is not None:
bundle.append(ca.parent)
ca = ca.parent
return bundle
|
python
|
def bundle(self):
"""A list of any parent CAs, including this CA.
The list is ordered so the Root CA will be the first.
"""
ca = self
bundle = [ca]
while ca.parent is not None:
bundle.append(ca.parent)
ca = ca.parent
return bundle
|
[
"def",
"bundle",
"(",
"self",
")",
":",
"ca",
"=",
"self",
"bundle",
"=",
"[",
"ca",
"]",
"while",
"ca",
".",
"parent",
"is",
"not",
"None",
":",
"bundle",
".",
"append",
"(",
"ca",
".",
"parent",
")",
"ca",
"=",
"ca",
".",
"parent",
"return",
"bundle"
] |
A list of any parent CAs, including this CA.
The list is ordered so the Root CA will be the first.
|
[
"A",
"list",
"of",
"any",
"parent",
"CAs",
"including",
"this",
"CA",
"."
] |
976d7ea05276320f20daed2a6d59c8f5660fe976
|
https://github.com/mathiasertl/django-ca/blob/976d7ea05276320f20daed2a6d59c8f5660fe976/ca/django_ca/models.py#L749-L760
|
train
|
mathiasertl/django-ca
|
ca/django_ca/querysets.py
|
CertificateQuerySet.valid
|
def valid(self):
"""Return valid certificates."""
now = timezone.now()
return self.filter(revoked=False, expires__gt=now, valid_from__lt=now)
|
python
|
def valid(self):
"""Return valid certificates."""
now = timezone.now()
return self.filter(revoked=False, expires__gt=now, valid_from__lt=now)
|
[
"def",
"valid",
"(",
"self",
")",
":",
"now",
"=",
"timezone",
".",
"now",
"(",
")",
"return",
"self",
".",
"filter",
"(",
"revoked",
"=",
"False",
",",
"expires__gt",
"=",
"now",
",",
"valid_from__lt",
"=",
"now",
")"
] |
Return valid certificates.
|
[
"Return",
"valid",
"certificates",
"."
] |
976d7ea05276320f20daed2a6d59c8f5660fe976
|
https://github.com/mathiasertl/django-ca/blob/976d7ea05276320f20daed2a6d59c8f5660fe976/ca/django_ca/querysets.py#L45-L49
|
train
|
saltstack/salt-pylint
|
setup.py
|
_release_version
|
def _release_version():
'''
Returns release version
'''
with io.open(os.path.join(SETUP_DIRNAME, 'saltpylint', 'version.py'), encoding='utf-8') as fh_:
exec_locals = {}
exec_globals = {}
contents = fh_.read()
if not isinstance(contents, str):
contents = contents.encode('utf-8')
exec(contents, exec_globals, exec_locals) # pylint: disable=exec-used
return exec_locals['__version__']
|
python
|
def _release_version():
'''
Returns release version
'''
with io.open(os.path.join(SETUP_DIRNAME, 'saltpylint', 'version.py'), encoding='utf-8') as fh_:
exec_locals = {}
exec_globals = {}
contents = fh_.read()
if not isinstance(contents, str):
contents = contents.encode('utf-8')
exec(contents, exec_globals, exec_locals) # pylint: disable=exec-used
return exec_locals['__version__']
|
[
"def",
"_release_version",
"(",
")",
":",
"with",
"io",
".",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"SETUP_DIRNAME",
",",
"'saltpylint'",
",",
"'version.py'",
")",
",",
"encoding",
"=",
"'utf-8'",
")",
"as",
"fh_",
":",
"exec_locals",
"=",
"{",
"}",
"exec_globals",
"=",
"{",
"}",
"contents",
"=",
"fh_",
".",
"read",
"(",
")",
"if",
"not",
"isinstance",
"(",
"contents",
",",
"str",
")",
":",
"contents",
"=",
"contents",
".",
"encode",
"(",
"'utf-8'",
")",
"exec",
"(",
"contents",
",",
"exec_globals",
",",
"exec_locals",
")",
"# pylint: disable=exec-used",
"return",
"exec_locals",
"[",
"'__version__'",
"]"
] |
Returns release version
|
[
"Returns",
"release",
"version"
] |
524a419d3bfc7dbd91c9c85040bc64935a275b24
|
https://github.com/saltstack/salt-pylint/blob/524a419d3bfc7dbd91c9c85040bc64935a275b24/setup.py#L45-L56
|
train
|
saltstack/salt-pylint
|
saltpylint/ext/pyqver2.py
|
get_versions
|
def get_versions(source):
"""Return information about the Python versions required for specific features.
The return value is a dictionary with keys as a version number as a tuple
(for example Python 2.6 is (2,6)) and the value are a list of features that
require the indicated Python version.
"""
tree = compiler.parse(source)
checker = compiler.walk(tree, NodeChecker())
return checker.vers
|
python
|
def get_versions(source):
"""Return information about the Python versions required for specific features.
The return value is a dictionary with keys as a version number as a tuple
(for example Python 2.6 is (2,6)) and the value are a list of features that
require the indicated Python version.
"""
tree = compiler.parse(source)
checker = compiler.walk(tree, NodeChecker())
return checker.vers
|
[
"def",
"get_versions",
"(",
"source",
")",
":",
"tree",
"=",
"compiler",
".",
"parse",
"(",
"source",
")",
"checker",
"=",
"compiler",
".",
"walk",
"(",
"tree",
",",
"NodeChecker",
"(",
")",
")",
"return",
"checker",
".",
"vers"
] |
Return information about the Python versions required for specific features.
The return value is a dictionary with keys as a version number as a tuple
(for example Python 2.6 is (2,6)) and the value are a list of features that
require the indicated Python version.
|
[
"Return",
"information",
"about",
"the",
"Python",
"versions",
"required",
"for",
"specific",
"features",
"."
] |
524a419d3bfc7dbd91c9c85040bc64935a275b24
|
https://github.com/saltstack/salt-pylint/blob/524a419d3bfc7dbd91c9c85040bc64935a275b24/saltpylint/ext/pyqver2.py#L252-L261
|
train
|
saltstack/salt-pylint
|
saltpylint/strings.py
|
StringLiteralChecker.process_non_raw_string_token
|
def process_non_raw_string_token(self, prefix, string_body, start_row):
'''
check for bad escapes in a non-raw string.
prefix: lowercase string of eg 'ur' string prefix markers.
string_body: the un-parsed body of the string, not including the quote
marks.
start_row: integer line number in the source.
'''
if 'u' in prefix:
if string_body.find('\\0') != -1:
self.add_message('null-byte-unicode-literal', line=start_row)
|
python
|
def process_non_raw_string_token(self, prefix, string_body, start_row):
'''
check for bad escapes in a non-raw string.
prefix: lowercase string of eg 'ur' string prefix markers.
string_body: the un-parsed body of the string, not including the quote
marks.
start_row: integer line number in the source.
'''
if 'u' in prefix:
if string_body.find('\\0') != -1:
self.add_message('null-byte-unicode-literal', line=start_row)
|
[
"def",
"process_non_raw_string_token",
"(",
"self",
",",
"prefix",
",",
"string_body",
",",
"start_row",
")",
":",
"if",
"'u'",
"in",
"prefix",
":",
"if",
"string_body",
".",
"find",
"(",
"'\\\\0'",
")",
"!=",
"-",
"1",
":",
"self",
".",
"add_message",
"(",
"'null-byte-unicode-literal'",
",",
"line",
"=",
"start_row",
")"
] |
check for bad escapes in a non-raw string.
prefix: lowercase string of eg 'ur' string prefix markers.
string_body: the un-parsed body of the string, not including the quote
marks.
start_row: integer line number in the source.
|
[
"check",
"for",
"bad",
"escapes",
"in",
"a",
"non",
"-",
"raw",
"string",
"."
] |
524a419d3bfc7dbd91c9c85040bc64935a275b24
|
https://github.com/saltstack/salt-pylint/blob/524a419d3bfc7dbd91c9c85040bc64935a275b24/saltpylint/strings.py#L247-L258
|
train
|
saltstack/salt-pylint
|
saltpylint/blacklist.py
|
register
|
def register(linter):
'''
Required method to auto register this checker
'''
linter.register_checker(ResourceLeakageChecker(linter))
linter.register_checker(BlacklistedImportsChecker(linter))
linter.register_checker(MovedTestCaseClassChecker(linter))
linter.register_checker(BlacklistedLoaderModulesUsageChecker(linter))
linter.register_checker(BlacklistedFunctionsChecker(linter))
|
python
|
def register(linter):
'''
Required method to auto register this checker
'''
linter.register_checker(ResourceLeakageChecker(linter))
linter.register_checker(BlacklistedImportsChecker(linter))
linter.register_checker(MovedTestCaseClassChecker(linter))
linter.register_checker(BlacklistedLoaderModulesUsageChecker(linter))
linter.register_checker(BlacklistedFunctionsChecker(linter))
|
[
"def",
"register",
"(",
"linter",
")",
":",
"linter",
".",
"register_checker",
"(",
"ResourceLeakageChecker",
"(",
"linter",
")",
")",
"linter",
".",
"register_checker",
"(",
"BlacklistedImportsChecker",
"(",
"linter",
")",
")",
"linter",
".",
"register_checker",
"(",
"MovedTestCaseClassChecker",
"(",
"linter",
")",
")",
"linter",
".",
"register_checker",
"(",
"BlacklistedLoaderModulesUsageChecker",
"(",
"linter",
")",
")",
"linter",
".",
"register_checker",
"(",
"BlacklistedFunctionsChecker",
"(",
"linter",
")",
")"
] |
Required method to auto register this checker
|
[
"Required",
"method",
"to",
"auto",
"register",
"this",
"checker"
] |
524a419d3bfc7dbd91c9c85040bc64935a275b24
|
https://github.com/saltstack/salt-pylint/blob/524a419d3bfc7dbd91c9c85040bc64935a275b24/saltpylint/blacklist.py#L560-L568
|
train
|
saltstack/salt-pylint
|
saltpylint/smartup.py
|
register
|
def register(linter):
'''
Register the transformation functions.
'''
try:
MANAGER.register_transform(nodes.Class, rootlogger_transform)
except AttributeError:
MANAGER.register_transform(nodes.ClassDef, rootlogger_transform)
|
python
|
def register(linter):
'''
Register the transformation functions.
'''
try:
MANAGER.register_transform(nodes.Class, rootlogger_transform)
except AttributeError:
MANAGER.register_transform(nodes.ClassDef, rootlogger_transform)
|
[
"def",
"register",
"(",
"linter",
")",
":",
"try",
":",
"MANAGER",
".",
"register_transform",
"(",
"nodes",
".",
"Class",
",",
"rootlogger_transform",
")",
"except",
"AttributeError",
":",
"MANAGER",
".",
"register_transform",
"(",
"nodes",
".",
"ClassDef",
",",
"rootlogger_transform",
")"
] |
Register the transformation functions.
|
[
"Register",
"the",
"transformation",
"functions",
"."
] |
524a419d3bfc7dbd91c9c85040bc64935a275b24
|
https://github.com/saltstack/salt-pylint/blob/524a419d3bfc7dbd91c9c85040bc64935a275b24/saltpylint/smartup.py#L39-L46
|
train
|
edx/xblock-utils
|
xblockutils/settings.py
|
XBlockWithSettingsMixin.get_xblock_settings
|
def get_xblock_settings(self, default=None):
"""
Gets XBlock-specific settigns for current XBlock
Returns default if settings service is not available.
Parameters:
default - default value to be used in two cases:
* No settings service is available
* As a `default` parameter to `SettingsService.get_settings_bucket`
"""
settings_service = self.runtime.service(self, "settings")
if settings_service:
return settings_service.get_settings_bucket(self, default=default)
return default
|
python
|
def get_xblock_settings(self, default=None):
"""
Gets XBlock-specific settigns for current XBlock
Returns default if settings service is not available.
Parameters:
default - default value to be used in two cases:
* No settings service is available
* As a `default` parameter to `SettingsService.get_settings_bucket`
"""
settings_service = self.runtime.service(self, "settings")
if settings_service:
return settings_service.get_settings_bucket(self, default=default)
return default
|
[
"def",
"get_xblock_settings",
"(",
"self",
",",
"default",
"=",
"None",
")",
":",
"settings_service",
"=",
"self",
".",
"runtime",
".",
"service",
"(",
"self",
",",
"\"settings\"",
")",
"if",
"settings_service",
":",
"return",
"settings_service",
".",
"get_settings_bucket",
"(",
"self",
",",
"default",
"=",
"default",
")",
"return",
"default"
] |
Gets XBlock-specific settigns for current XBlock
Returns default if settings service is not available.
Parameters:
default - default value to be used in two cases:
* No settings service is available
* As a `default` parameter to `SettingsService.get_settings_bucket`
|
[
"Gets",
"XBlock",
"-",
"specific",
"settigns",
"for",
"current",
"XBlock"
] |
2960666907d3eea1ed312fa87d811e78cd043702
|
https://github.com/edx/xblock-utils/blob/2960666907d3eea1ed312fa87d811e78cd043702/xblockutils/settings.py#L25-L39
|
train
|
edx/xblock-utils
|
xblockutils/settings.py
|
ThemableXBlockMixin.include_theme_files
|
def include_theme_files(self, fragment):
"""
Gets theme configuration and renders theme css into fragment
"""
theme = self.get_theme()
if not theme or 'package' not in theme:
return
theme_package, theme_files = theme.get('package', None), theme.get('locations', [])
resource_loader = ResourceLoader(theme_package)
for theme_file in theme_files:
fragment.add_css(resource_loader.load_unicode(theme_file))
|
python
|
def include_theme_files(self, fragment):
"""
Gets theme configuration and renders theme css into fragment
"""
theme = self.get_theme()
if not theme or 'package' not in theme:
return
theme_package, theme_files = theme.get('package', None), theme.get('locations', [])
resource_loader = ResourceLoader(theme_package)
for theme_file in theme_files:
fragment.add_css(resource_loader.load_unicode(theme_file))
|
[
"def",
"include_theme_files",
"(",
"self",
",",
"fragment",
")",
":",
"theme",
"=",
"self",
".",
"get_theme",
"(",
")",
"if",
"not",
"theme",
"or",
"'package'",
"not",
"in",
"theme",
":",
"return",
"theme_package",
",",
"theme_files",
"=",
"theme",
".",
"get",
"(",
"'package'",
",",
"None",
")",
",",
"theme",
".",
"get",
"(",
"'locations'",
",",
"[",
"]",
")",
"resource_loader",
"=",
"ResourceLoader",
"(",
"theme_package",
")",
"for",
"theme_file",
"in",
"theme_files",
":",
"fragment",
".",
"add_css",
"(",
"resource_loader",
".",
"load_unicode",
"(",
"theme_file",
")",
")"
] |
Gets theme configuration and renders theme css into fragment
|
[
"Gets",
"theme",
"configuration",
"and",
"renders",
"theme",
"css",
"into",
"fragment"
] |
2960666907d3eea1ed312fa87d811e78cd043702
|
https://github.com/edx/xblock-utils/blob/2960666907d3eea1ed312fa87d811e78cd043702/xblockutils/settings.py#L81-L92
|
train
|
edx/xblock-utils
|
xblockutils/resources.py
|
ResourceLoader.load_unicode
|
def load_unicode(self, resource_path):
"""
Gets the content of a resource
"""
resource_content = pkg_resources.resource_string(self.module_name, resource_path)
return resource_content.decode('utf-8')
|
python
|
def load_unicode(self, resource_path):
"""
Gets the content of a resource
"""
resource_content = pkg_resources.resource_string(self.module_name, resource_path)
return resource_content.decode('utf-8')
|
[
"def",
"load_unicode",
"(",
"self",
",",
"resource_path",
")",
":",
"resource_content",
"=",
"pkg_resources",
".",
"resource_string",
"(",
"self",
".",
"module_name",
",",
"resource_path",
")",
"return",
"resource_content",
".",
"decode",
"(",
"'utf-8'",
")"
] |
Gets the content of a resource
|
[
"Gets",
"the",
"content",
"of",
"a",
"resource"
] |
2960666907d3eea1ed312fa87d811e78cd043702
|
https://github.com/edx/xblock-utils/blob/2960666907d3eea1ed312fa87d811e78cd043702/xblockutils/resources.py#L46-L51
|
train
|
edx/xblock-utils
|
xblockutils/resources.py
|
ResourceLoader.render_django_template
|
def render_django_template(self, template_path, context=None, i18n_service=None):
"""
Evaluate a django template by resource path, applying the provided context.
"""
context = context or {}
context['_i18n_service'] = i18n_service
libraries = {
'i18n': 'xblockutils.templatetags.i18n',
}
# For django 1.8, we have to load the libraries manually, and restore them once the template is rendered.
_libraries = None
if django.VERSION[0] == 1 and django.VERSION[1] == 8:
_libraries = TemplateBase.libraries.copy()
for library_name in libraries:
library = TemplateBase.import_library(libraries[library_name])
if library:
TemplateBase.libraries[library_name] = library
engine = Engine()
else:
# Django>1.8 Engine can load the extra templatetag libraries itself
# but we have to override the default installed libraries.
from django.template.backends.django import get_installed_libraries
installed_libraries = get_installed_libraries()
installed_libraries.update(libraries)
engine = Engine(libraries=installed_libraries)
template_str = self.load_unicode(template_path)
template = Template(template_str, engine=engine)
rendered = template.render(Context(context))
# Restore the original TemplateBase.libraries
if _libraries is not None:
TemplateBase.libraries = _libraries
return rendered
|
python
|
def render_django_template(self, template_path, context=None, i18n_service=None):
"""
Evaluate a django template by resource path, applying the provided context.
"""
context = context or {}
context['_i18n_service'] = i18n_service
libraries = {
'i18n': 'xblockutils.templatetags.i18n',
}
# For django 1.8, we have to load the libraries manually, and restore them once the template is rendered.
_libraries = None
if django.VERSION[0] == 1 and django.VERSION[1] == 8:
_libraries = TemplateBase.libraries.copy()
for library_name in libraries:
library = TemplateBase.import_library(libraries[library_name])
if library:
TemplateBase.libraries[library_name] = library
engine = Engine()
else:
# Django>1.8 Engine can load the extra templatetag libraries itself
# but we have to override the default installed libraries.
from django.template.backends.django import get_installed_libraries
installed_libraries = get_installed_libraries()
installed_libraries.update(libraries)
engine = Engine(libraries=installed_libraries)
template_str = self.load_unicode(template_path)
template = Template(template_str, engine=engine)
rendered = template.render(Context(context))
# Restore the original TemplateBase.libraries
if _libraries is not None:
TemplateBase.libraries = _libraries
return rendered
|
[
"def",
"render_django_template",
"(",
"self",
",",
"template_path",
",",
"context",
"=",
"None",
",",
"i18n_service",
"=",
"None",
")",
":",
"context",
"=",
"context",
"or",
"{",
"}",
"context",
"[",
"'_i18n_service'",
"]",
"=",
"i18n_service",
"libraries",
"=",
"{",
"'i18n'",
":",
"'xblockutils.templatetags.i18n'",
",",
"}",
"# For django 1.8, we have to load the libraries manually, and restore them once the template is rendered.",
"_libraries",
"=",
"None",
"if",
"django",
".",
"VERSION",
"[",
"0",
"]",
"==",
"1",
"and",
"django",
".",
"VERSION",
"[",
"1",
"]",
"==",
"8",
":",
"_libraries",
"=",
"TemplateBase",
".",
"libraries",
".",
"copy",
"(",
")",
"for",
"library_name",
"in",
"libraries",
":",
"library",
"=",
"TemplateBase",
".",
"import_library",
"(",
"libraries",
"[",
"library_name",
"]",
")",
"if",
"library",
":",
"TemplateBase",
".",
"libraries",
"[",
"library_name",
"]",
"=",
"library",
"engine",
"=",
"Engine",
"(",
")",
"else",
":",
"# Django>1.8 Engine can load the extra templatetag libraries itself",
"# but we have to override the default installed libraries.",
"from",
"django",
".",
"template",
".",
"backends",
".",
"django",
"import",
"get_installed_libraries",
"installed_libraries",
"=",
"get_installed_libraries",
"(",
")",
"installed_libraries",
".",
"update",
"(",
"libraries",
")",
"engine",
"=",
"Engine",
"(",
"libraries",
"=",
"installed_libraries",
")",
"template_str",
"=",
"self",
".",
"load_unicode",
"(",
"template_path",
")",
"template",
"=",
"Template",
"(",
"template_str",
",",
"engine",
"=",
"engine",
")",
"rendered",
"=",
"template",
".",
"render",
"(",
"Context",
"(",
"context",
")",
")",
"# Restore the original TemplateBase.libraries",
"if",
"_libraries",
"is",
"not",
"None",
":",
"TemplateBase",
".",
"libraries",
"=",
"_libraries",
"return",
"rendered"
] |
Evaluate a django template by resource path, applying the provided context.
|
[
"Evaluate",
"a",
"django",
"template",
"by",
"resource",
"path",
"applying",
"the",
"provided",
"context",
"."
] |
2960666907d3eea1ed312fa87d811e78cd043702
|
https://github.com/edx/xblock-utils/blob/2960666907d3eea1ed312fa87d811e78cd043702/xblockutils/resources.py#L53-L88
|
train
|
edx/xblock-utils
|
xblockutils/resources.py
|
ResourceLoader.render_mako_template
|
def render_mako_template(self, template_path, context=None):
"""
Evaluate a mako template by resource path, applying the provided context
"""
context = context or {}
template_str = self.load_unicode(template_path)
lookup = MakoTemplateLookup(directories=[pkg_resources.resource_filename(self.module_name, '')])
template = MakoTemplate(template_str, lookup=lookup)
return template.render(**context)
|
python
|
def render_mako_template(self, template_path, context=None):
"""
Evaluate a mako template by resource path, applying the provided context
"""
context = context or {}
template_str = self.load_unicode(template_path)
lookup = MakoTemplateLookup(directories=[pkg_resources.resource_filename(self.module_name, '')])
template = MakoTemplate(template_str, lookup=lookup)
return template.render(**context)
|
[
"def",
"render_mako_template",
"(",
"self",
",",
"template_path",
",",
"context",
"=",
"None",
")",
":",
"context",
"=",
"context",
"or",
"{",
"}",
"template_str",
"=",
"self",
".",
"load_unicode",
"(",
"template_path",
")",
"lookup",
"=",
"MakoTemplateLookup",
"(",
"directories",
"=",
"[",
"pkg_resources",
".",
"resource_filename",
"(",
"self",
".",
"module_name",
",",
"''",
")",
"]",
")",
"template",
"=",
"MakoTemplate",
"(",
"template_str",
",",
"lookup",
"=",
"lookup",
")",
"return",
"template",
".",
"render",
"(",
"*",
"*",
"context",
")"
] |
Evaluate a mako template by resource path, applying the provided context
|
[
"Evaluate",
"a",
"mako",
"template",
"by",
"resource",
"path",
"applying",
"the",
"provided",
"context"
] |
2960666907d3eea1ed312fa87d811e78cd043702
|
https://github.com/edx/xblock-utils/blob/2960666907d3eea1ed312fa87d811e78cd043702/xblockutils/resources.py#L90-L98
|
train
|
edx/xblock-utils
|
xblockutils/resources.py
|
ResourceLoader.render_template
|
def render_template(self, template_path, context=None):
"""
This function has been deprecated. It calls render_django_template to support backwards compatibility.
"""
warnings.warn(
"ResourceLoader.render_template has been deprecated in favor of ResourceLoader.render_django_template"
)
return self.render_django_template(template_path, context)
|
python
|
def render_template(self, template_path, context=None):
"""
This function has been deprecated. It calls render_django_template to support backwards compatibility.
"""
warnings.warn(
"ResourceLoader.render_template has been deprecated in favor of ResourceLoader.render_django_template"
)
return self.render_django_template(template_path, context)
|
[
"def",
"render_template",
"(",
"self",
",",
"template_path",
",",
"context",
"=",
"None",
")",
":",
"warnings",
".",
"warn",
"(",
"\"ResourceLoader.render_template has been deprecated in favor of ResourceLoader.render_django_template\"",
")",
"return",
"self",
".",
"render_django_template",
"(",
"template_path",
",",
"context",
")"
] |
This function has been deprecated. It calls render_django_template to support backwards compatibility.
|
[
"This",
"function",
"has",
"been",
"deprecated",
".",
"It",
"calls",
"render_django_template",
"to",
"support",
"backwards",
"compatibility",
"."
] |
2960666907d3eea1ed312fa87d811e78cd043702
|
https://github.com/edx/xblock-utils/blob/2960666907d3eea1ed312fa87d811e78cd043702/xblockutils/resources.py#L100-L107
|
train
|
edx/xblock-utils
|
xblockutils/resources.py
|
ResourceLoader.render_js_template
|
def render_js_template(self, template_path, element_id, context=None):
"""
Render a js template.
"""
context = context or {}
return u"<script type='text/template' id='{}'>\n{}\n</script>".format(
element_id,
self.render_template(template_path, context)
)
|
python
|
def render_js_template(self, template_path, element_id, context=None):
"""
Render a js template.
"""
context = context or {}
return u"<script type='text/template' id='{}'>\n{}\n</script>".format(
element_id,
self.render_template(template_path, context)
)
|
[
"def",
"render_js_template",
"(",
"self",
",",
"template_path",
",",
"element_id",
",",
"context",
"=",
"None",
")",
":",
"context",
"=",
"context",
"or",
"{",
"}",
"return",
"u\"<script type='text/template' id='{}'>\\n{}\\n</script>\"",
".",
"format",
"(",
"element_id",
",",
"self",
".",
"render_template",
"(",
"template_path",
",",
"context",
")",
")"
] |
Render a js template.
|
[
"Render",
"a",
"js",
"template",
"."
] |
2960666907d3eea1ed312fa87d811e78cd043702
|
https://github.com/edx/xblock-utils/blob/2960666907d3eea1ed312fa87d811e78cd043702/xblockutils/resources.py#L109-L117
|
train
|
edx/xblock-utils
|
xblockutils/templatetags/i18n.py
|
ProxyTransNode.merge_translation
|
def merge_translation(self, context):
"""
Context wrapper which modifies the given language's translation catalog using the i18n service, if found.
"""
language = get_language()
i18n_service = context.get('_i18n_service', None)
if i18n_service:
# Cache the original translation object to reduce overhead
if language not in self._translations:
self._translations[language] = trans_real.DjangoTranslation(language)
translation = trans_real.translation(language)
translation.merge(i18n_service)
yield
# Revert to original translation object
if language in self._translations:
trans_real._translations[language] = self._translations[language]
# Re-activate the current language to reset translation caches
trans_real.activate(language)
|
python
|
def merge_translation(self, context):
"""
Context wrapper which modifies the given language's translation catalog using the i18n service, if found.
"""
language = get_language()
i18n_service = context.get('_i18n_service', None)
if i18n_service:
# Cache the original translation object to reduce overhead
if language not in self._translations:
self._translations[language] = trans_real.DjangoTranslation(language)
translation = trans_real.translation(language)
translation.merge(i18n_service)
yield
# Revert to original translation object
if language in self._translations:
trans_real._translations[language] = self._translations[language]
# Re-activate the current language to reset translation caches
trans_real.activate(language)
|
[
"def",
"merge_translation",
"(",
"self",
",",
"context",
")",
":",
"language",
"=",
"get_language",
"(",
")",
"i18n_service",
"=",
"context",
".",
"get",
"(",
"'_i18n_service'",
",",
"None",
")",
"if",
"i18n_service",
":",
"# Cache the original translation object to reduce overhead",
"if",
"language",
"not",
"in",
"self",
".",
"_translations",
":",
"self",
".",
"_translations",
"[",
"language",
"]",
"=",
"trans_real",
".",
"DjangoTranslation",
"(",
"language",
")",
"translation",
"=",
"trans_real",
".",
"translation",
"(",
"language",
")",
"translation",
".",
"merge",
"(",
"i18n_service",
")",
"yield",
"# Revert to original translation object",
"if",
"language",
"in",
"self",
".",
"_translations",
":",
"trans_real",
".",
"_translations",
"[",
"language",
"]",
"=",
"self",
".",
"_translations",
"[",
"language",
"]",
"# Re-activate the current language to reset translation caches",
"trans_real",
".",
"activate",
"(",
"language",
")"
] |
Context wrapper which modifies the given language's translation catalog using the i18n service, if found.
|
[
"Context",
"wrapper",
"which",
"modifies",
"the",
"given",
"language",
"s",
"translation",
"catalog",
"using",
"the",
"i18n",
"service",
"if",
"found",
"."
] |
2960666907d3eea1ed312fa87d811e78cd043702
|
https://github.com/edx/xblock-utils/blob/2960666907d3eea1ed312fa87d811e78cd043702/xblockutils/templatetags/i18n.py#L29-L49
|
train
|
edx/xblock-utils
|
xblockutils/templatetags/i18n.py
|
ProxyTransNode.render
|
def render(self, context):
"""
Renders the translated text using the XBlock i18n service, if available.
"""
with self.merge_translation(context):
django_translated = self.do_translate.render(context)
return django_translated
|
python
|
def render(self, context):
"""
Renders the translated text using the XBlock i18n service, if available.
"""
with self.merge_translation(context):
django_translated = self.do_translate.render(context)
return django_translated
|
[
"def",
"render",
"(",
"self",
",",
"context",
")",
":",
"with",
"self",
".",
"merge_translation",
"(",
"context",
")",
":",
"django_translated",
"=",
"self",
".",
"do_translate",
".",
"render",
"(",
"context",
")",
"return",
"django_translated"
] |
Renders the translated text using the XBlock i18n service, if available.
|
[
"Renders",
"the",
"translated",
"text",
"using",
"the",
"XBlock",
"i18n",
"service",
"if",
"available",
"."
] |
2960666907d3eea1ed312fa87d811e78cd043702
|
https://github.com/edx/xblock-utils/blob/2960666907d3eea1ed312fa87d811e78cd043702/xblockutils/templatetags/i18n.py#L51-L58
|
train
|
edx/xblock-utils
|
xblockutils/studio_editable.py
|
StudioEditableXBlockMixin.studio_view
|
def studio_view(self, context):
"""
Render a form for editing this XBlock
"""
fragment = Fragment()
context = {'fields': []}
# Build a list of all the fields that can be edited:
for field_name in self.editable_fields:
field = self.fields[field_name]
assert field.scope in (Scope.content, Scope.settings), (
"Only Scope.content or Scope.settings fields can be used with "
"StudioEditableXBlockMixin. Other scopes are for user-specific data and are "
"not generally created/configured by content authors in Studio."
)
field_info = self._make_field_info(field_name, field)
if field_info is not None:
context["fields"].append(field_info)
fragment.content = loader.render_template('templates/studio_edit.html', context)
fragment.add_javascript(loader.load_unicode('public/studio_edit.js'))
fragment.initialize_js('StudioEditableXBlockMixin')
return fragment
|
python
|
def studio_view(self, context):
"""
Render a form for editing this XBlock
"""
fragment = Fragment()
context = {'fields': []}
# Build a list of all the fields that can be edited:
for field_name in self.editable_fields:
field = self.fields[field_name]
assert field.scope in (Scope.content, Scope.settings), (
"Only Scope.content or Scope.settings fields can be used with "
"StudioEditableXBlockMixin. Other scopes are for user-specific data and are "
"not generally created/configured by content authors in Studio."
)
field_info = self._make_field_info(field_name, field)
if field_info is not None:
context["fields"].append(field_info)
fragment.content = loader.render_template('templates/studio_edit.html', context)
fragment.add_javascript(loader.load_unicode('public/studio_edit.js'))
fragment.initialize_js('StudioEditableXBlockMixin')
return fragment
|
[
"def",
"studio_view",
"(",
"self",
",",
"context",
")",
":",
"fragment",
"=",
"Fragment",
"(",
")",
"context",
"=",
"{",
"'fields'",
":",
"[",
"]",
"}",
"# Build a list of all the fields that can be edited:",
"for",
"field_name",
"in",
"self",
".",
"editable_fields",
":",
"field",
"=",
"self",
".",
"fields",
"[",
"field_name",
"]",
"assert",
"field",
".",
"scope",
"in",
"(",
"Scope",
".",
"content",
",",
"Scope",
".",
"settings",
")",
",",
"(",
"\"Only Scope.content or Scope.settings fields can be used with \"",
"\"StudioEditableXBlockMixin. Other scopes are for user-specific data and are \"",
"\"not generally created/configured by content authors in Studio.\"",
")",
"field_info",
"=",
"self",
".",
"_make_field_info",
"(",
"field_name",
",",
"field",
")",
"if",
"field_info",
"is",
"not",
"None",
":",
"context",
"[",
"\"fields\"",
"]",
".",
"append",
"(",
"field_info",
")",
"fragment",
".",
"content",
"=",
"loader",
".",
"render_template",
"(",
"'templates/studio_edit.html'",
",",
"context",
")",
"fragment",
".",
"add_javascript",
"(",
"loader",
".",
"load_unicode",
"(",
"'public/studio_edit.js'",
")",
")",
"fragment",
".",
"initialize_js",
"(",
"'StudioEditableXBlockMixin'",
")",
"return",
"fragment"
] |
Render a form for editing this XBlock
|
[
"Render",
"a",
"form",
"for",
"editing",
"this",
"XBlock"
] |
2960666907d3eea1ed312fa87d811e78cd043702
|
https://github.com/edx/xblock-utils/blob/2960666907d3eea1ed312fa87d811e78cd043702/xblockutils/studio_editable.py#L78-L98
|
train
|
edx/xblock-utils
|
xblockutils/studio_editable.py
|
StudioEditableXBlockMixin.validate
|
def validate(self):
"""
Validates the state of this XBlock.
Subclasses should override validate_field_data() to validate fields and override this
only for validation not related to this block's field values.
"""
validation = super(StudioEditableXBlockMixin, self).validate()
self.validate_field_data(validation, self)
return validation
|
python
|
def validate(self):
"""
Validates the state of this XBlock.
Subclasses should override validate_field_data() to validate fields and override this
only for validation not related to this block's field values.
"""
validation = super(StudioEditableXBlockMixin, self).validate()
self.validate_field_data(validation, self)
return validation
|
[
"def",
"validate",
"(",
"self",
")",
":",
"validation",
"=",
"super",
"(",
"StudioEditableXBlockMixin",
",",
"self",
")",
".",
"validate",
"(",
")",
"self",
".",
"validate_field_data",
"(",
"validation",
",",
"self",
")",
"return",
"validation"
] |
Validates the state of this XBlock.
Subclasses should override validate_field_data() to validate fields and override this
only for validation not related to this block's field values.
|
[
"Validates",
"the",
"state",
"of",
"this",
"XBlock",
"."
] |
2960666907d3eea1ed312fa87d811e78cd043702
|
https://github.com/edx/xblock-utils/blob/2960666907d3eea1ed312fa87d811e78cd043702/xblockutils/studio_editable.py#L264-L273
|
train
|
edx/xblock-utils
|
xblockutils/studio_editable.py
|
StudioContainerXBlockMixin.render_children
|
def render_children(self, context, fragment, can_reorder=True, can_add=False):
"""
Renders the children of the module with HTML appropriate for Studio. If can_reorder is
True, then the children will be rendered to support drag and drop.
"""
contents = []
child_context = {'reorderable_items': set()}
if context:
child_context.update(context)
for child_id in self.children:
child = self.runtime.get_block(child_id)
if can_reorder:
child_context['reorderable_items'].add(child.scope_ids.usage_id)
view_to_render = 'author_view' if hasattr(child, 'author_view') else 'student_view'
rendered_child = child.render(view_to_render, child_context)
fragment.add_frag_resources(rendered_child)
contents.append({
'id': text_type(child.scope_ids.usage_id),
'content': rendered_child.content
})
fragment.add_content(self.runtime.render_template("studio_render_children_view.html", {
'items': contents,
'xblock_context': context,
'can_add': can_add,
'can_reorder': can_reorder,
}))
|
python
|
def render_children(self, context, fragment, can_reorder=True, can_add=False):
"""
Renders the children of the module with HTML appropriate for Studio. If can_reorder is
True, then the children will be rendered to support drag and drop.
"""
contents = []
child_context = {'reorderable_items': set()}
if context:
child_context.update(context)
for child_id in self.children:
child = self.runtime.get_block(child_id)
if can_reorder:
child_context['reorderable_items'].add(child.scope_ids.usage_id)
view_to_render = 'author_view' if hasattr(child, 'author_view') else 'student_view'
rendered_child = child.render(view_to_render, child_context)
fragment.add_frag_resources(rendered_child)
contents.append({
'id': text_type(child.scope_ids.usage_id),
'content': rendered_child.content
})
fragment.add_content(self.runtime.render_template("studio_render_children_view.html", {
'items': contents,
'xblock_context': context,
'can_add': can_add,
'can_reorder': can_reorder,
}))
|
[
"def",
"render_children",
"(",
"self",
",",
"context",
",",
"fragment",
",",
"can_reorder",
"=",
"True",
",",
"can_add",
"=",
"False",
")",
":",
"contents",
"=",
"[",
"]",
"child_context",
"=",
"{",
"'reorderable_items'",
":",
"set",
"(",
")",
"}",
"if",
"context",
":",
"child_context",
".",
"update",
"(",
"context",
")",
"for",
"child_id",
"in",
"self",
".",
"children",
":",
"child",
"=",
"self",
".",
"runtime",
".",
"get_block",
"(",
"child_id",
")",
"if",
"can_reorder",
":",
"child_context",
"[",
"'reorderable_items'",
"]",
".",
"add",
"(",
"child",
".",
"scope_ids",
".",
"usage_id",
")",
"view_to_render",
"=",
"'author_view'",
"if",
"hasattr",
"(",
"child",
",",
"'author_view'",
")",
"else",
"'student_view'",
"rendered_child",
"=",
"child",
".",
"render",
"(",
"view_to_render",
",",
"child_context",
")",
"fragment",
".",
"add_frag_resources",
"(",
"rendered_child",
")",
"contents",
".",
"append",
"(",
"{",
"'id'",
":",
"text_type",
"(",
"child",
".",
"scope_ids",
".",
"usage_id",
")",
",",
"'content'",
":",
"rendered_child",
".",
"content",
"}",
")",
"fragment",
".",
"add_content",
"(",
"self",
".",
"runtime",
".",
"render_template",
"(",
"\"studio_render_children_view.html\"",
",",
"{",
"'items'",
":",
"contents",
",",
"'xblock_context'",
":",
"context",
",",
"'can_add'",
":",
"can_add",
",",
"'can_reorder'",
":",
"can_reorder",
",",
"}",
")",
")"
] |
Renders the children of the module with HTML appropriate for Studio. If can_reorder is
True, then the children will be rendered to support drag and drop.
|
[
"Renders",
"the",
"children",
"of",
"the",
"module",
"with",
"HTML",
"appropriate",
"for",
"Studio",
".",
"If",
"can_reorder",
"is",
"True",
"then",
"the",
"children",
"will",
"be",
"rendered",
"to",
"support",
"drag",
"and",
"drop",
"."
] |
2960666907d3eea1ed312fa87d811e78cd043702
|
https://github.com/edx/xblock-utils/blob/2960666907d3eea1ed312fa87d811e78cd043702/xblockutils/studio_editable.py#L283-L312
|
train
|
edx/xblock-utils
|
xblockutils/studio_editable.py
|
StudioContainerXBlockMixin.author_view
|
def author_view(self, context):
"""
Display a the studio editor when the user has clicked "View" to see the container view,
otherwise just show the normal 'author_preview_view' or 'student_view' preview.
"""
root_xblock = context.get('root_xblock')
if root_xblock and root_xblock.location == self.location:
# User has clicked the "View" link. Show an editable preview of this block's children
return self.author_edit_view(context)
return self.author_preview_view(context)
|
python
|
def author_view(self, context):
"""
Display a the studio editor when the user has clicked "View" to see the container view,
otherwise just show the normal 'author_preview_view' or 'student_view' preview.
"""
root_xblock = context.get('root_xblock')
if root_xblock and root_xblock.location == self.location:
# User has clicked the "View" link. Show an editable preview of this block's children
return self.author_edit_view(context)
return self.author_preview_view(context)
|
[
"def",
"author_view",
"(",
"self",
",",
"context",
")",
":",
"root_xblock",
"=",
"context",
".",
"get",
"(",
"'root_xblock'",
")",
"if",
"root_xblock",
"and",
"root_xblock",
".",
"location",
"==",
"self",
".",
"location",
":",
"# User has clicked the \"View\" link. Show an editable preview of this block's children",
"return",
"self",
".",
"author_edit_view",
"(",
"context",
")",
"return",
"self",
".",
"author_preview_view",
"(",
"context",
")"
] |
Display a the studio editor when the user has clicked "View" to see the container view,
otherwise just show the normal 'author_preview_view' or 'student_view' preview.
|
[
"Display",
"a",
"the",
"studio",
"editor",
"when",
"the",
"user",
"has",
"clicked",
"View",
"to",
"see",
"the",
"container",
"view",
"otherwise",
"just",
"show",
"the",
"normal",
"author_preview_view",
"or",
"student_view",
"preview",
"."
] |
2960666907d3eea1ed312fa87d811e78cd043702
|
https://github.com/edx/xblock-utils/blob/2960666907d3eea1ed312fa87d811e78cd043702/xblockutils/studio_editable.py#L314-L324
|
train
|
edx/xblock-utils
|
xblockutils/studio_editable.py
|
StudioContainerXBlockMixin.author_edit_view
|
def author_edit_view(self, context):
"""
Child blocks can override this to control the view shown to authors in Studio when
editing this block's children.
"""
fragment = Fragment()
self.render_children(context, fragment, can_reorder=True, can_add=False)
return fragment
|
python
|
def author_edit_view(self, context):
"""
Child blocks can override this to control the view shown to authors in Studio when
editing this block's children.
"""
fragment = Fragment()
self.render_children(context, fragment, can_reorder=True, can_add=False)
return fragment
|
[
"def",
"author_edit_view",
"(",
"self",
",",
"context",
")",
":",
"fragment",
"=",
"Fragment",
"(",
")",
"self",
".",
"render_children",
"(",
"context",
",",
"fragment",
",",
"can_reorder",
"=",
"True",
",",
"can_add",
"=",
"False",
")",
"return",
"fragment"
] |
Child blocks can override this to control the view shown to authors in Studio when
editing this block's children.
|
[
"Child",
"blocks",
"can",
"override",
"this",
"to",
"control",
"the",
"view",
"shown",
"to",
"authors",
"in",
"Studio",
"when",
"editing",
"this",
"block",
"s",
"children",
"."
] |
2960666907d3eea1ed312fa87d811e78cd043702
|
https://github.com/edx/xblock-utils/blob/2960666907d3eea1ed312fa87d811e78cd043702/xblockutils/studio_editable.py#L326-L333
|
train
|
edx/xblock-utils
|
xblockutils/studio_editable.py
|
XBlockWithPreviewMixin.preview_view
|
def preview_view(self, context):
"""
Preview view - used by StudioContainerWithNestedXBlocksMixin to render nested xblocks in preview context.
Default implementation uses author_view if available, otherwise falls back to student_view
Child classes can override this method to control their presentation in preview context
"""
view_to_render = 'author_view' if hasattr(self, 'author_view') else 'student_view'
renderer = getattr(self, view_to_render)
return renderer(context)
|
python
|
def preview_view(self, context):
"""
Preview view - used by StudioContainerWithNestedXBlocksMixin to render nested xblocks in preview context.
Default implementation uses author_view if available, otherwise falls back to student_view
Child classes can override this method to control their presentation in preview context
"""
view_to_render = 'author_view' if hasattr(self, 'author_view') else 'student_view'
renderer = getattr(self, view_to_render)
return renderer(context)
|
[
"def",
"preview_view",
"(",
"self",
",",
"context",
")",
":",
"view_to_render",
"=",
"'author_view'",
"if",
"hasattr",
"(",
"self",
",",
"'author_view'",
")",
"else",
"'student_view'",
"renderer",
"=",
"getattr",
"(",
"self",
",",
"view_to_render",
")",
"return",
"renderer",
"(",
"context",
")"
] |
Preview view - used by StudioContainerWithNestedXBlocksMixin to render nested xblocks in preview context.
Default implementation uses author_view if available, otherwise falls back to student_view
Child classes can override this method to control their presentation in preview context
|
[
"Preview",
"view",
"-",
"used",
"by",
"StudioContainerWithNestedXBlocksMixin",
"to",
"render",
"nested",
"xblocks",
"in",
"preview",
"context",
".",
"Default",
"implementation",
"uses",
"author_view",
"if",
"available",
"otherwise",
"falls",
"back",
"to",
"student_view",
"Child",
"classes",
"can",
"override",
"this",
"method",
"to",
"control",
"their",
"presentation",
"in",
"preview",
"context"
] |
2960666907d3eea1ed312fa87d811e78cd043702
|
https://github.com/edx/xblock-utils/blob/2960666907d3eea1ed312fa87d811e78cd043702/xblockutils/studio_editable.py#L405-L413
|
train
|
edx/xblock-utils
|
xblockutils/studio_editable.py
|
StudioContainerWithNestedXBlocksMixin.get_nested_blocks_spec
|
def get_nested_blocks_spec(self):
"""
Converts allowed_nested_blocks items to NestedXBlockSpec to provide common interface
"""
return [
block_spec if isinstance(block_spec, NestedXBlockSpec) else NestedXBlockSpec(block_spec)
for block_spec in self.allowed_nested_blocks
]
|
python
|
def get_nested_blocks_spec(self):
"""
Converts allowed_nested_blocks items to NestedXBlockSpec to provide common interface
"""
return [
block_spec if isinstance(block_spec, NestedXBlockSpec) else NestedXBlockSpec(block_spec)
for block_spec in self.allowed_nested_blocks
]
|
[
"def",
"get_nested_blocks_spec",
"(",
"self",
")",
":",
"return",
"[",
"block_spec",
"if",
"isinstance",
"(",
"block_spec",
",",
"NestedXBlockSpec",
")",
"else",
"NestedXBlockSpec",
"(",
"block_spec",
")",
"for",
"block_spec",
"in",
"self",
".",
"allowed_nested_blocks",
"]"
] |
Converts allowed_nested_blocks items to NestedXBlockSpec to provide common interface
|
[
"Converts",
"allowed_nested_blocks",
"items",
"to",
"NestedXBlockSpec",
"to",
"provide",
"common",
"interface"
] |
2960666907d3eea1ed312fa87d811e78cd043702
|
https://github.com/edx/xblock-utils/blob/2960666907d3eea1ed312fa87d811e78cd043702/xblockutils/studio_editable.py#L443-L450
|
train
|
edx/xblock-utils
|
xblockutils/studio_editable.py
|
StudioContainerWithNestedXBlocksMixin.author_preview_view
|
def author_preview_view(self, context):
"""
View for previewing contents in studio.
"""
children_contents = []
fragment = Fragment()
for child_id in self.children:
child = self.runtime.get_block(child_id)
child_fragment = self._render_child_fragment(child, context, 'preview_view')
fragment.add_frag_resources(child_fragment)
children_contents.append(child_fragment.content)
render_context = {
'block': self,
'children_contents': children_contents
}
render_context.update(context)
fragment.add_content(self.loader.render_template(self.CHILD_PREVIEW_TEMPLATE, render_context))
return fragment
|
python
|
def author_preview_view(self, context):
"""
View for previewing contents in studio.
"""
children_contents = []
fragment = Fragment()
for child_id in self.children:
child = self.runtime.get_block(child_id)
child_fragment = self._render_child_fragment(child, context, 'preview_view')
fragment.add_frag_resources(child_fragment)
children_contents.append(child_fragment.content)
render_context = {
'block': self,
'children_contents': children_contents
}
render_context.update(context)
fragment.add_content(self.loader.render_template(self.CHILD_PREVIEW_TEMPLATE, render_context))
return fragment
|
[
"def",
"author_preview_view",
"(",
"self",
",",
"context",
")",
":",
"children_contents",
"=",
"[",
"]",
"fragment",
"=",
"Fragment",
"(",
")",
"for",
"child_id",
"in",
"self",
".",
"children",
":",
"child",
"=",
"self",
".",
"runtime",
".",
"get_block",
"(",
"child_id",
")",
"child_fragment",
"=",
"self",
".",
"_render_child_fragment",
"(",
"child",
",",
"context",
",",
"'preview_view'",
")",
"fragment",
".",
"add_frag_resources",
"(",
"child_fragment",
")",
"children_contents",
".",
"append",
"(",
"child_fragment",
".",
"content",
")",
"render_context",
"=",
"{",
"'block'",
":",
"self",
",",
"'children_contents'",
":",
"children_contents",
"}",
"render_context",
".",
"update",
"(",
"context",
")",
"fragment",
".",
"add_content",
"(",
"self",
".",
"loader",
".",
"render_template",
"(",
"self",
".",
"CHILD_PREVIEW_TEMPLATE",
",",
"render_context",
")",
")",
"return",
"fragment"
] |
View for previewing contents in studio.
|
[
"View",
"for",
"previewing",
"contents",
"in",
"studio",
"."
] |
2960666907d3eea1ed312fa87d811e78cd043702
|
https://github.com/edx/xblock-utils/blob/2960666907d3eea1ed312fa87d811e78cd043702/xblockutils/studio_editable.py#L472-L491
|
train
|
edx/xblock-utils
|
xblockutils/studio_editable.py
|
StudioContainerWithNestedXBlocksMixin._render_child_fragment
|
def _render_child_fragment(self, child, context, view='student_view'):
"""
Helper method to overcome html block rendering quirks
"""
try:
child_fragment = child.render(view, context)
except NoSuchViewError:
if child.scope_ids.block_type == 'html' and getattr(self.runtime, 'is_author_mode', False):
# html block doesn't support preview_view, and if we use student_view Studio will wrap
# it in HTML that we don't want in the preview. So just render its HTML directly:
child_fragment = Fragment(child.data)
else:
child_fragment = child.render('student_view', context)
return child_fragment
|
python
|
def _render_child_fragment(self, child, context, view='student_view'):
"""
Helper method to overcome html block rendering quirks
"""
try:
child_fragment = child.render(view, context)
except NoSuchViewError:
if child.scope_ids.block_type == 'html' and getattr(self.runtime, 'is_author_mode', False):
# html block doesn't support preview_view, and if we use student_view Studio will wrap
# it in HTML that we don't want in the preview. So just render its HTML directly:
child_fragment = Fragment(child.data)
else:
child_fragment = child.render('student_view', context)
return child_fragment
|
[
"def",
"_render_child_fragment",
"(",
"self",
",",
"child",
",",
"context",
",",
"view",
"=",
"'student_view'",
")",
":",
"try",
":",
"child_fragment",
"=",
"child",
".",
"render",
"(",
"view",
",",
"context",
")",
"except",
"NoSuchViewError",
":",
"if",
"child",
".",
"scope_ids",
".",
"block_type",
"==",
"'html'",
"and",
"getattr",
"(",
"self",
".",
"runtime",
",",
"'is_author_mode'",
",",
"False",
")",
":",
"# html block doesn't support preview_view, and if we use student_view Studio will wrap",
"# it in HTML that we don't want in the preview. So just render its HTML directly:",
"child_fragment",
"=",
"Fragment",
"(",
"child",
".",
"data",
")",
"else",
":",
"child_fragment",
"=",
"child",
".",
"render",
"(",
"'student_view'",
",",
"context",
")",
"return",
"child_fragment"
] |
Helper method to overcome html block rendering quirks
|
[
"Helper",
"method",
"to",
"overcome",
"html",
"block",
"rendering",
"quirks"
] |
2960666907d3eea1ed312fa87d811e78cd043702
|
https://github.com/edx/xblock-utils/blob/2960666907d3eea1ed312fa87d811e78cd043702/xblockutils/studio_editable.py#L493-L507
|
train
|
edx/xblock-utils
|
setup.py
|
package_data
|
def package_data(pkg, root_list):
"""Generic function to find package_data for `pkg` under `root`."""
data = []
for root in root_list:
for dirname, _, files in os.walk(os.path.join(pkg, root)):
for fname in files:
data.append(os.path.relpath(os.path.join(dirname, fname), pkg))
return {pkg: data}
|
python
|
def package_data(pkg, root_list):
"""Generic function to find package_data for `pkg` under `root`."""
data = []
for root in root_list:
for dirname, _, files in os.walk(os.path.join(pkg, root)):
for fname in files:
data.append(os.path.relpath(os.path.join(dirname, fname), pkg))
return {pkg: data}
|
[
"def",
"package_data",
"(",
"pkg",
",",
"root_list",
")",
":",
"data",
"=",
"[",
"]",
"for",
"root",
"in",
"root_list",
":",
"for",
"dirname",
",",
"_",
",",
"files",
"in",
"os",
".",
"walk",
"(",
"os",
".",
"path",
".",
"join",
"(",
"pkg",
",",
"root",
")",
")",
":",
"for",
"fname",
"in",
"files",
":",
"data",
".",
"append",
"(",
"os",
".",
"path",
".",
"relpath",
"(",
"os",
".",
"path",
".",
"join",
"(",
"dirname",
",",
"fname",
")",
",",
"pkg",
")",
")",
"return",
"{",
"pkg",
":",
"data",
"}"
] |
Generic function to find package_data for `pkg` under `root`.
|
[
"Generic",
"function",
"to",
"find",
"package_data",
"for",
"pkg",
"under",
"root",
"."
] |
2960666907d3eea1ed312fa87d811e78cd043702
|
https://github.com/edx/xblock-utils/blob/2960666907d3eea1ed312fa87d811e78cd043702/setup.py#L29-L37
|
train
|
edx/xblock-utils
|
setup.py
|
load_requirements
|
def load_requirements(*requirements_paths):
"""
Load all requirements from the specified requirements files.
Returns a list of requirement strings.
"""
requirements = set()
for path in requirements_paths:
requirements.update(
line.split('#')[0].strip() for line in open(path).readlines()
if is_requirement(line.strip())
)
return list(requirements)
|
python
|
def load_requirements(*requirements_paths):
"""
Load all requirements from the specified requirements files.
Returns a list of requirement strings.
"""
requirements = set()
for path in requirements_paths:
requirements.update(
line.split('#')[0].strip() for line in open(path).readlines()
if is_requirement(line.strip())
)
return list(requirements)
|
[
"def",
"load_requirements",
"(",
"*",
"requirements_paths",
")",
":",
"requirements",
"=",
"set",
"(",
")",
"for",
"path",
"in",
"requirements_paths",
":",
"requirements",
".",
"update",
"(",
"line",
".",
"split",
"(",
"'#'",
")",
"[",
"0",
"]",
".",
"strip",
"(",
")",
"for",
"line",
"in",
"open",
"(",
"path",
")",
".",
"readlines",
"(",
")",
"if",
"is_requirement",
"(",
"line",
".",
"strip",
"(",
")",
")",
")",
"return",
"list",
"(",
"requirements",
")"
] |
Load all requirements from the specified requirements files.
Returns a list of requirement strings.
|
[
"Load",
"all",
"requirements",
"from",
"the",
"specified",
"requirements",
"files",
".",
"Returns",
"a",
"list",
"of",
"requirement",
"strings",
"."
] |
2960666907d3eea1ed312fa87d811e78cd043702
|
https://github.com/edx/xblock-utils/blob/2960666907d3eea1ed312fa87d811e78cd043702/setup.py#L40-L51
|
train
|
edx/xblock-utils
|
setup.py
|
is_requirement
|
def is_requirement(line):
"""
Return True if the requirement line is a package requirement;
that is, it is not blank, a comment, a URL, or an included file.
"""
return not (
line == '' or
line.startswith('-r') or
line.startswith('#') or
line.startswith('-e') or
line.startswith('git+')
)
|
python
|
def is_requirement(line):
"""
Return True if the requirement line is a package requirement;
that is, it is not blank, a comment, a URL, or an included file.
"""
return not (
line == '' or
line.startswith('-r') or
line.startswith('#') or
line.startswith('-e') or
line.startswith('git+')
)
|
[
"def",
"is_requirement",
"(",
"line",
")",
":",
"return",
"not",
"(",
"line",
"==",
"''",
"or",
"line",
".",
"startswith",
"(",
"'-r'",
")",
"or",
"line",
".",
"startswith",
"(",
"'#'",
")",
"or",
"line",
".",
"startswith",
"(",
"'-e'",
")",
"or",
"line",
".",
"startswith",
"(",
"'git+'",
")",
")"
] |
Return True if the requirement line is a package requirement;
that is, it is not blank, a comment, a URL, or an included file.
|
[
"Return",
"True",
"if",
"the",
"requirement",
"line",
"is",
"a",
"package",
"requirement",
";",
"that",
"is",
"it",
"is",
"not",
"blank",
"a",
"comment",
"a",
"URL",
"or",
"an",
"included",
"file",
"."
] |
2960666907d3eea1ed312fa87d811e78cd043702
|
https://github.com/edx/xblock-utils/blob/2960666907d3eea1ed312fa87d811e78cd043702/setup.py#L54-L65
|
train
|
edx/xblock-utils
|
xblockutils/publish_event.py
|
PublishEventMixin.publish_event
|
def publish_event(self, data, suffix=''):
"""
AJAX handler to allow client-side code to publish a server-side event
"""
try:
event_type = data.pop('event_type')
except KeyError:
return {'result': 'error', 'message': 'Missing event_type in JSON data'}
return self.publish_event_from_dict(event_type, data)
|
python
|
def publish_event(self, data, suffix=''):
"""
AJAX handler to allow client-side code to publish a server-side event
"""
try:
event_type = data.pop('event_type')
except KeyError:
return {'result': 'error', 'message': 'Missing event_type in JSON data'}
return self.publish_event_from_dict(event_type, data)
|
[
"def",
"publish_event",
"(",
"self",
",",
"data",
",",
"suffix",
"=",
"''",
")",
":",
"try",
":",
"event_type",
"=",
"data",
".",
"pop",
"(",
"'event_type'",
")",
"except",
"KeyError",
":",
"return",
"{",
"'result'",
":",
"'error'",
",",
"'message'",
":",
"'Missing event_type in JSON data'",
"}",
"return",
"self",
".",
"publish_event_from_dict",
"(",
"event_type",
",",
"data",
")"
] |
AJAX handler to allow client-side code to publish a server-side event
|
[
"AJAX",
"handler",
"to",
"allow",
"client",
"-",
"side",
"code",
"to",
"publish",
"a",
"server",
"-",
"side",
"event"
] |
2960666907d3eea1ed312fa87d811e78cd043702
|
https://github.com/edx/xblock-utils/blob/2960666907d3eea1ed312fa87d811e78cd043702/xblockutils/publish_event.py#L37-L46
|
train
|
edx/xblock-utils
|
xblockutils/publish_event.py
|
PublishEventMixin.publish_event_from_dict
|
def publish_event_from_dict(self, event_type, data):
"""
Combine 'data' with self.additional_publish_event_data and publish an event
"""
for key, value in self.additional_publish_event_data.items():
if key in data:
return {'result': 'error', 'message': 'Key should not be in publish_event data: {}'.format(key)}
data[key] = value
self.runtime.publish(self, event_type, data)
return {'result': 'success'}
|
python
|
def publish_event_from_dict(self, event_type, data):
"""
Combine 'data' with self.additional_publish_event_data and publish an event
"""
for key, value in self.additional_publish_event_data.items():
if key in data:
return {'result': 'error', 'message': 'Key should not be in publish_event data: {}'.format(key)}
data[key] = value
self.runtime.publish(self, event_type, data)
return {'result': 'success'}
|
[
"def",
"publish_event_from_dict",
"(",
"self",
",",
"event_type",
",",
"data",
")",
":",
"for",
"key",
",",
"value",
"in",
"self",
".",
"additional_publish_event_data",
".",
"items",
"(",
")",
":",
"if",
"key",
"in",
"data",
":",
"return",
"{",
"'result'",
":",
"'error'",
",",
"'message'",
":",
"'Key should not be in publish_event data: {}'",
".",
"format",
"(",
"key",
")",
"}",
"data",
"[",
"key",
"]",
"=",
"value",
"self",
".",
"runtime",
".",
"publish",
"(",
"self",
",",
"event_type",
",",
"data",
")",
"return",
"{",
"'result'",
":",
"'success'",
"}"
] |
Combine 'data' with self.additional_publish_event_data and publish an event
|
[
"Combine",
"data",
"with",
"self",
".",
"additional_publish_event_data",
"and",
"publish",
"an",
"event"
] |
2960666907d3eea1ed312fa87d811e78cd043702
|
https://github.com/edx/xblock-utils/blob/2960666907d3eea1ed312fa87d811e78cd043702/xblockutils/publish_event.py#L48-L58
|
train
|
edx/xblock-utils
|
xblockutils/helpers.py
|
child_isinstance
|
def child_isinstance(block, child_id, block_class_or_mixin):
"""
Efficiently check if a child of an XBlock is an instance of the given class.
Arguments:
block -- the parent (or ancestor) of the child block in question
child_id -- the usage key of the child block we are wondering about
block_class_or_mixin -- We return true if block's child indentified by child_id is an
instance of this.
This method is equivalent to
isinstance(block.runtime.get_block(child_id), block_class_or_mixin)
but is far more efficient, as it avoids the need to instantiate the child.
"""
def_id = block.runtime.id_reader.get_definition_id(child_id)
type_name = block.runtime.id_reader.get_block_type(def_id)
child_class = block.runtime.load_block_type(type_name)
return issubclass(child_class, block_class_or_mixin)
|
python
|
def child_isinstance(block, child_id, block_class_or_mixin):
"""
Efficiently check if a child of an XBlock is an instance of the given class.
Arguments:
block -- the parent (or ancestor) of the child block in question
child_id -- the usage key of the child block we are wondering about
block_class_or_mixin -- We return true if block's child indentified by child_id is an
instance of this.
This method is equivalent to
isinstance(block.runtime.get_block(child_id), block_class_or_mixin)
but is far more efficient, as it avoids the need to instantiate the child.
"""
def_id = block.runtime.id_reader.get_definition_id(child_id)
type_name = block.runtime.id_reader.get_block_type(def_id)
child_class = block.runtime.load_block_type(type_name)
return issubclass(child_class, block_class_or_mixin)
|
[
"def",
"child_isinstance",
"(",
"block",
",",
"child_id",
",",
"block_class_or_mixin",
")",
":",
"def_id",
"=",
"block",
".",
"runtime",
".",
"id_reader",
".",
"get_definition_id",
"(",
"child_id",
")",
"type_name",
"=",
"block",
".",
"runtime",
".",
"id_reader",
".",
"get_block_type",
"(",
"def_id",
")",
"child_class",
"=",
"block",
".",
"runtime",
".",
"load_block_type",
"(",
"type_name",
")",
"return",
"issubclass",
"(",
"child_class",
",",
"block_class_or_mixin",
")"
] |
Efficiently check if a child of an XBlock is an instance of the given class.
Arguments:
block -- the parent (or ancestor) of the child block in question
child_id -- the usage key of the child block we are wondering about
block_class_or_mixin -- We return true if block's child indentified by child_id is an
instance of this.
This method is equivalent to
isinstance(block.runtime.get_block(child_id), block_class_or_mixin)
but is far more efficient, as it avoids the need to instantiate the child.
|
[
"Efficiently",
"check",
"if",
"a",
"child",
"of",
"an",
"XBlock",
"is",
"an",
"instance",
"of",
"the",
"given",
"class",
"."
] |
2960666907d3eea1ed312fa87d811e78cd043702
|
https://github.com/edx/xblock-utils/blob/2960666907d3eea1ed312fa87d811e78cd043702/xblockutils/helpers.py#L6-L25
|
train
|
Hrabal/TemPy
|
tempy/elements.py
|
Tag.attr
|
def attr(self, *args, **kwargs):
"""Add an attribute to the element"""
kwargs.update({k: bool for k in args})
for key, value in kwargs.items():
if key == "klass":
self.attrs["klass"].update(value.split())
elif key == "style":
if isinstance(value, str):
splitted = iter(re.split(";|:", value))
value = dict(zip(splitted, splitted))
self.attrs["style"].update(value)
else:
self.attrs[key] = value
self._stable = False
return self
|
python
|
def attr(self, *args, **kwargs):
"""Add an attribute to the element"""
kwargs.update({k: bool for k in args})
for key, value in kwargs.items():
if key == "klass":
self.attrs["klass"].update(value.split())
elif key == "style":
if isinstance(value, str):
splitted = iter(re.split(";|:", value))
value = dict(zip(splitted, splitted))
self.attrs["style"].update(value)
else:
self.attrs[key] = value
self._stable = False
return self
|
[
"def",
"attr",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
".",
"update",
"(",
"{",
"k",
":",
"bool",
"for",
"k",
"in",
"args",
"}",
")",
"for",
"key",
",",
"value",
"in",
"kwargs",
".",
"items",
"(",
")",
":",
"if",
"key",
"==",
"\"klass\"",
":",
"self",
".",
"attrs",
"[",
"\"klass\"",
"]",
".",
"update",
"(",
"value",
".",
"split",
"(",
")",
")",
"elif",
"key",
"==",
"\"style\"",
":",
"if",
"isinstance",
"(",
"value",
",",
"str",
")",
":",
"splitted",
"=",
"iter",
"(",
"re",
".",
"split",
"(",
"\";|:\"",
",",
"value",
")",
")",
"value",
"=",
"dict",
"(",
"zip",
"(",
"splitted",
",",
"splitted",
")",
")",
"self",
".",
"attrs",
"[",
"\"style\"",
"]",
".",
"update",
"(",
"value",
")",
"else",
":",
"self",
".",
"attrs",
"[",
"key",
"]",
"=",
"value",
"self",
".",
"_stable",
"=",
"False",
"return",
"self"
] |
Add an attribute to the element
|
[
"Add",
"an",
"attribute",
"to",
"the",
"element"
] |
7d229b73e2ce3ccbb8254deae05c1f758f626ed6
|
https://github.com/Hrabal/TemPy/blob/7d229b73e2ce3ccbb8254deae05c1f758f626ed6/tempy/elements.py#L72-L86
|
train
|
Hrabal/TemPy
|
tempy/elements.py
|
Tag.remove_attr
|
def remove_attr(self, attr):
"""Removes an attribute."""
self._stable = False
self.attrs.pop(attr, None)
return self
|
python
|
def remove_attr(self, attr):
"""Removes an attribute."""
self._stable = False
self.attrs.pop(attr, None)
return self
|
[
"def",
"remove_attr",
"(",
"self",
",",
"attr",
")",
":",
"self",
".",
"_stable",
"=",
"False",
"self",
".",
"attrs",
".",
"pop",
"(",
"attr",
",",
"None",
")",
"return",
"self"
] |
Removes an attribute.
|
[
"Removes",
"an",
"attribute",
"."
] |
7d229b73e2ce3ccbb8254deae05c1f758f626ed6
|
https://github.com/Hrabal/TemPy/blob/7d229b73e2ce3ccbb8254deae05c1f758f626ed6/tempy/elements.py#L88-L92
|
train
|
Hrabal/TemPy
|
tempy/elements.py
|
Tag.render_attrs
|
def render_attrs(self):
"""Renders the tag's attributes using the formats and performing special attributes name substitution."""
ret = []
for k, v in self.attrs.items():
if v:
if v is bool:
ret.append(" %s" % self._SPECIAL_ATTRS.get(k, k))
else:
fnc = self._FORMAT_ATTRS.get(k, None)
val = fnc(v) if fnc else v
ret.append(' %s="%s"' % (self._SPECIAL_ATTRS.get(k, k), val))
return "".join(ret)
|
python
|
def render_attrs(self):
"""Renders the tag's attributes using the formats and performing special attributes name substitution."""
ret = []
for k, v in self.attrs.items():
if v:
if v is bool:
ret.append(" %s" % self._SPECIAL_ATTRS.get(k, k))
else:
fnc = self._FORMAT_ATTRS.get(k, None)
val = fnc(v) if fnc else v
ret.append(' %s="%s"' % (self._SPECIAL_ATTRS.get(k, k), val))
return "".join(ret)
|
[
"def",
"render_attrs",
"(",
"self",
")",
":",
"ret",
"=",
"[",
"]",
"for",
"k",
",",
"v",
"in",
"self",
".",
"attrs",
".",
"items",
"(",
")",
":",
"if",
"v",
":",
"if",
"v",
"is",
"bool",
":",
"ret",
".",
"append",
"(",
"\" %s\"",
"%",
"self",
".",
"_SPECIAL_ATTRS",
".",
"get",
"(",
"k",
",",
"k",
")",
")",
"else",
":",
"fnc",
"=",
"self",
".",
"_FORMAT_ATTRS",
".",
"get",
"(",
"k",
",",
"None",
")",
"val",
"=",
"fnc",
"(",
"v",
")",
"if",
"fnc",
"else",
"v",
"ret",
".",
"append",
"(",
"' %s=\"%s\"'",
"%",
"(",
"self",
".",
"_SPECIAL_ATTRS",
".",
"get",
"(",
"k",
",",
"k",
")",
",",
"val",
")",
")",
"return",
"\"\"",
".",
"join",
"(",
"ret",
")"
] |
Renders the tag's attributes using the formats and performing special attributes name substitution.
|
[
"Renders",
"the",
"tag",
"s",
"attributes",
"using",
"the",
"formats",
"and",
"performing",
"special",
"attributes",
"name",
"substitution",
"."
] |
7d229b73e2ce3ccbb8254deae05c1f758f626ed6
|
https://github.com/Hrabal/TemPy/blob/7d229b73e2ce3ccbb8254deae05c1f758f626ed6/tempy/elements.py#L94-L105
|
train
|
Hrabal/TemPy
|
tempy/elements.py
|
Tag.toggle_class
|
def toggle_class(self, csscl):
"""Same as jQuery's toggleClass function. It toggles the css class on this element."""
self._stable = False
action = ("add", "remove")[self.has_class(csscl)]
return getattr(self.attrs["klass"], action)(csscl)
|
python
|
def toggle_class(self, csscl):
"""Same as jQuery's toggleClass function. It toggles the css class on this element."""
self._stable = False
action = ("add", "remove")[self.has_class(csscl)]
return getattr(self.attrs["klass"], action)(csscl)
|
[
"def",
"toggle_class",
"(",
"self",
",",
"csscl",
")",
":",
"self",
".",
"_stable",
"=",
"False",
"action",
"=",
"(",
"\"add\"",
",",
"\"remove\"",
")",
"[",
"self",
".",
"has_class",
"(",
"csscl",
")",
"]",
"return",
"getattr",
"(",
"self",
".",
"attrs",
"[",
"\"klass\"",
"]",
",",
"action",
")",
"(",
"csscl",
")"
] |
Same as jQuery's toggleClass function. It toggles the css class on this element.
|
[
"Same",
"as",
"jQuery",
"s",
"toggleClass",
"function",
".",
"It",
"toggles",
"the",
"css",
"class",
"on",
"this",
"element",
"."
] |
7d229b73e2ce3ccbb8254deae05c1f758f626ed6
|
https://github.com/Hrabal/TemPy/blob/7d229b73e2ce3ccbb8254deae05c1f758f626ed6/tempy/elements.py#L137-L141
|
train
|
Hrabal/TemPy
|
tempy/elements.py
|
Tag.add_class
|
def add_class(self, cssclass):
"""Adds a css class to this element."""
if self.has_class(cssclass):
return self
return self.toggle_class(cssclass)
|
python
|
def add_class(self, cssclass):
"""Adds a css class to this element."""
if self.has_class(cssclass):
return self
return self.toggle_class(cssclass)
|
[
"def",
"add_class",
"(",
"self",
",",
"cssclass",
")",
":",
"if",
"self",
".",
"has_class",
"(",
"cssclass",
")",
":",
"return",
"self",
"return",
"self",
".",
"toggle_class",
"(",
"cssclass",
")"
] |
Adds a css class to this element.
|
[
"Adds",
"a",
"css",
"class",
"to",
"this",
"element",
"."
] |
7d229b73e2ce3ccbb8254deae05c1f758f626ed6
|
https://github.com/Hrabal/TemPy/blob/7d229b73e2ce3ccbb8254deae05c1f758f626ed6/tempy/elements.py#L143-L147
|
train
|
Hrabal/TemPy
|
tempy/elements.py
|
Tag.remove_class
|
def remove_class(self, cssclass):
"""Removes the given class from this element."""
if not self.has_class(cssclass):
return self
return self.toggle_class(cssclass)
|
python
|
def remove_class(self, cssclass):
"""Removes the given class from this element."""
if not self.has_class(cssclass):
return self
return self.toggle_class(cssclass)
|
[
"def",
"remove_class",
"(",
"self",
",",
"cssclass",
")",
":",
"if",
"not",
"self",
".",
"has_class",
"(",
"cssclass",
")",
":",
"return",
"self",
"return",
"self",
".",
"toggle_class",
"(",
"cssclass",
")"
] |
Removes the given class from this element.
|
[
"Removes",
"the",
"given",
"class",
"from",
"this",
"element",
"."
] |
7d229b73e2ce3ccbb8254deae05c1f758f626ed6
|
https://github.com/Hrabal/TemPy/blob/7d229b73e2ce3ccbb8254deae05c1f758f626ed6/tempy/elements.py#L149-L153
|
train
|
Hrabal/TemPy
|
tempy/elements.py
|
Tag.css
|
def css(self, *props, **kwprops):
"""Adds css properties to this element."""
self._stable = False
styles = {}
if props:
if len(props) == 1 and isinstance(props[0], Mapping):
styles = props[0]
else:
raise WrongContentError(self, props, "Arguments not valid")
elif kwprops:
styles = kwprops
else:
raise WrongContentError(self, None, "args OR wkargs are needed")
return self.attr(style=styles)
|
python
|
def css(self, *props, **kwprops):
"""Adds css properties to this element."""
self._stable = False
styles = {}
if props:
if len(props) == 1 and isinstance(props[0], Mapping):
styles = props[0]
else:
raise WrongContentError(self, props, "Arguments not valid")
elif kwprops:
styles = kwprops
else:
raise WrongContentError(self, None, "args OR wkargs are needed")
return self.attr(style=styles)
|
[
"def",
"css",
"(",
"self",
",",
"*",
"props",
",",
"*",
"*",
"kwprops",
")",
":",
"self",
".",
"_stable",
"=",
"False",
"styles",
"=",
"{",
"}",
"if",
"props",
":",
"if",
"len",
"(",
"props",
")",
"==",
"1",
"and",
"isinstance",
"(",
"props",
"[",
"0",
"]",
",",
"Mapping",
")",
":",
"styles",
"=",
"props",
"[",
"0",
"]",
"else",
":",
"raise",
"WrongContentError",
"(",
"self",
",",
"props",
",",
"\"Arguments not valid\"",
")",
"elif",
"kwprops",
":",
"styles",
"=",
"kwprops",
"else",
":",
"raise",
"WrongContentError",
"(",
"self",
",",
"None",
",",
"\"args OR wkargs are needed\"",
")",
"return",
"self",
".",
"attr",
"(",
"style",
"=",
"styles",
")"
] |
Adds css properties to this element.
|
[
"Adds",
"css",
"properties",
"to",
"this",
"element",
"."
] |
7d229b73e2ce3ccbb8254deae05c1f758f626ed6
|
https://github.com/Hrabal/TemPy/blob/7d229b73e2ce3ccbb8254deae05c1f758f626ed6/tempy/elements.py#L155-L168
|
train
|
Hrabal/TemPy
|
tempy/elements.py
|
Tag.show
|
def show(self, display=None):
"""Removes the display style attribute.
If a display type is provided """
self._stable = False
if not display:
self.attrs["style"].pop("display")
else:
self.attrs["style"]["display"] = display
return self
|
python
|
def show(self, display=None):
"""Removes the display style attribute.
If a display type is provided """
self._stable = False
if not display:
self.attrs["style"].pop("display")
else:
self.attrs["style"]["display"] = display
return self
|
[
"def",
"show",
"(",
"self",
",",
"display",
"=",
"None",
")",
":",
"self",
".",
"_stable",
"=",
"False",
"if",
"not",
"display",
":",
"self",
".",
"attrs",
"[",
"\"style\"",
"]",
".",
"pop",
"(",
"\"display\"",
")",
"else",
":",
"self",
".",
"attrs",
"[",
"\"style\"",
"]",
"[",
"\"display\"",
"]",
"=",
"display",
"return",
"self"
] |
Removes the display style attribute.
If a display type is provided
|
[
"Removes",
"the",
"display",
"style",
"attribute",
".",
"If",
"a",
"display",
"type",
"is",
"provided"
] |
7d229b73e2ce3ccbb8254deae05c1f758f626ed6
|
https://github.com/Hrabal/TemPy/blob/7d229b73e2ce3ccbb8254deae05c1f758f626ed6/tempy/elements.py#L176-L184
|
train
|
Hrabal/TemPy
|
tempy/elements.py
|
Tag.toggle
|
def toggle(self):
"""Same as jQuery's toggle, toggles the display attribute of this element."""
self._stable = False
return self.show() if self.attrs["style"]["display"] == "none" else self.hide()
|
python
|
def toggle(self):
"""Same as jQuery's toggle, toggles the display attribute of this element."""
self._stable = False
return self.show() if self.attrs["style"]["display"] == "none" else self.hide()
|
[
"def",
"toggle",
"(",
"self",
")",
":",
"self",
".",
"_stable",
"=",
"False",
"return",
"self",
".",
"show",
"(",
")",
"if",
"self",
".",
"attrs",
"[",
"\"style\"",
"]",
"[",
"\"display\"",
"]",
"==",
"\"none\"",
"else",
"self",
".",
"hide",
"(",
")"
] |
Same as jQuery's toggle, toggles the display attribute of this element.
|
[
"Same",
"as",
"jQuery",
"s",
"toggle",
"toggles",
"the",
"display",
"attribute",
"of",
"this",
"element",
"."
] |
7d229b73e2ce3ccbb8254deae05c1f758f626ed6
|
https://github.com/Hrabal/TemPy/blob/7d229b73e2ce3ccbb8254deae05c1f758f626ed6/tempy/elements.py#L186-L189
|
train
|
Hrabal/TemPy
|
tempy/elements.py
|
Tag.text
|
def text(self):
"""Renders the contents inside this element, without html tags."""
texts = []
for child in self.childs:
if isinstance(child, Tag):
texts.append(child.text())
elif isinstance(child, Content):
texts.append(child.render())
else:
texts.append(child)
return " ".join(texts)
|
python
|
def text(self):
"""Renders the contents inside this element, without html tags."""
texts = []
for child in self.childs:
if isinstance(child, Tag):
texts.append(child.text())
elif isinstance(child, Content):
texts.append(child.render())
else:
texts.append(child)
return " ".join(texts)
|
[
"def",
"text",
"(",
"self",
")",
":",
"texts",
"=",
"[",
"]",
"for",
"child",
"in",
"self",
".",
"childs",
":",
"if",
"isinstance",
"(",
"child",
",",
"Tag",
")",
":",
"texts",
".",
"append",
"(",
"child",
".",
"text",
"(",
")",
")",
"elif",
"isinstance",
"(",
"child",
",",
"Content",
")",
":",
"texts",
".",
"append",
"(",
"child",
".",
"render",
"(",
")",
")",
"else",
":",
"texts",
".",
"append",
"(",
"child",
")",
"return",
"\" \"",
".",
"join",
"(",
"texts",
")"
] |
Renders the contents inside this element, without html tags.
|
[
"Renders",
"the",
"contents",
"inside",
"this",
"element",
"without",
"html",
"tags",
"."
] |
7d229b73e2ce3ccbb8254deae05c1f758f626ed6
|
https://github.com/Hrabal/TemPy/blob/7d229b73e2ce3ccbb8254deae05c1f758f626ed6/tempy/elements.py#L195-L205
|
train
|
Hrabal/TemPy
|
tempy/elements.py
|
Tag.render
|
def render(self, *args, **kwargs):
"""Renders the element and all his childrens."""
# args kwargs API provided for last minute content injection
# self._reverse_mro_func('pre_render')
pretty = kwargs.pop("pretty", False)
if pretty and self._stable != "pretty":
self._stable = False
for arg in args:
self._stable = False
if isinstance(arg, dict):
self.inject(arg)
if kwargs:
self._stable = False
self.inject(kwargs)
# If the tag or his contents are not changed and we already have rendered it
# with the same attrs we skip all the work
if self._stable and self._render:
return self._render
pretty_pre = pretty_inner = ""
if pretty:
pretty_pre = "\n" + ("\t" * self._depth) if pretty else ""
pretty_inner = "\n" + ("\t" * self._depth) if len(self.childs) > 1 else ""
inner = self.render_childs(pretty) if not self._void else ""
# We declare the tag is stable and have an official render:
tag_data = (
pretty_pre,
self._get__tag(),
self.render_attrs(),
inner,
pretty_inner,
self._get__tag()
)[: 6 - [0, 3][self._void]]
self._render = self._template % tag_data
self._stable = "pretty" if pretty else True
return self._render
|
python
|
def render(self, *args, **kwargs):
"""Renders the element and all his childrens."""
# args kwargs API provided for last minute content injection
# self._reverse_mro_func('pre_render')
pretty = kwargs.pop("pretty", False)
if pretty and self._stable != "pretty":
self._stable = False
for arg in args:
self._stable = False
if isinstance(arg, dict):
self.inject(arg)
if kwargs:
self._stable = False
self.inject(kwargs)
# If the tag or his contents are not changed and we already have rendered it
# with the same attrs we skip all the work
if self._stable and self._render:
return self._render
pretty_pre = pretty_inner = ""
if pretty:
pretty_pre = "\n" + ("\t" * self._depth) if pretty else ""
pretty_inner = "\n" + ("\t" * self._depth) if len(self.childs) > 1 else ""
inner = self.render_childs(pretty) if not self._void else ""
# We declare the tag is stable and have an official render:
tag_data = (
pretty_pre,
self._get__tag(),
self.render_attrs(),
inner,
pretty_inner,
self._get__tag()
)[: 6 - [0, 3][self._void]]
self._render = self._template % tag_data
self._stable = "pretty" if pretty else True
return self._render
|
[
"def",
"render",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# args kwargs API provided for last minute content injection",
"# self._reverse_mro_func('pre_render')",
"pretty",
"=",
"kwargs",
".",
"pop",
"(",
"\"pretty\"",
",",
"False",
")",
"if",
"pretty",
"and",
"self",
".",
"_stable",
"!=",
"\"pretty\"",
":",
"self",
".",
"_stable",
"=",
"False",
"for",
"arg",
"in",
"args",
":",
"self",
".",
"_stable",
"=",
"False",
"if",
"isinstance",
"(",
"arg",
",",
"dict",
")",
":",
"self",
".",
"inject",
"(",
"arg",
")",
"if",
"kwargs",
":",
"self",
".",
"_stable",
"=",
"False",
"self",
".",
"inject",
"(",
"kwargs",
")",
"# If the tag or his contents are not changed and we already have rendered it",
"# with the same attrs we skip all the work",
"if",
"self",
".",
"_stable",
"and",
"self",
".",
"_render",
":",
"return",
"self",
".",
"_render",
"pretty_pre",
"=",
"pretty_inner",
"=",
"\"\"",
"if",
"pretty",
":",
"pretty_pre",
"=",
"\"\\n\"",
"+",
"(",
"\"\\t\"",
"*",
"self",
".",
"_depth",
")",
"if",
"pretty",
"else",
"\"\"",
"pretty_inner",
"=",
"\"\\n\"",
"+",
"(",
"\"\\t\"",
"*",
"self",
".",
"_depth",
")",
"if",
"len",
"(",
"self",
".",
"childs",
")",
">",
"1",
"else",
"\"\"",
"inner",
"=",
"self",
".",
"render_childs",
"(",
"pretty",
")",
"if",
"not",
"self",
".",
"_void",
"else",
"\"\"",
"# We declare the tag is stable and have an official render:",
"tag_data",
"=",
"(",
"pretty_pre",
",",
"self",
".",
"_get__tag",
"(",
")",
",",
"self",
".",
"render_attrs",
"(",
")",
",",
"inner",
",",
"pretty_inner",
",",
"self",
".",
"_get__tag",
"(",
")",
")",
"[",
":",
"6",
"-",
"[",
"0",
",",
"3",
"]",
"[",
"self",
".",
"_void",
"]",
"]",
"self",
".",
"_render",
"=",
"self",
".",
"_template",
"%",
"tag_data",
"self",
".",
"_stable",
"=",
"\"pretty\"",
"if",
"pretty",
"else",
"True",
"return",
"self",
".",
"_render"
] |
Renders the element and all his childrens.
|
[
"Renders",
"the",
"element",
"and",
"all",
"his",
"childrens",
"."
] |
7d229b73e2ce3ccbb8254deae05c1f758f626ed6
|
https://github.com/Hrabal/TemPy/blob/7d229b73e2ce3ccbb8254deae05c1f758f626ed6/tempy/elements.py#L207-L245
|
train
|
Hrabal/TemPy
|
tempy/t.py
|
TempyParser._make_tempy_tag
|
def _make_tempy_tag(self, tag, attrs, void):
"""Searches in tempy.tags for the correct tag to use, if does not exists uses the TempyFactory to
create a custom tag."""
tempy_tag_cls = getattr(self.tempy_tags, tag.title(), None)
if not tempy_tag_cls:
unknow_maker = [self.unknown_tag_maker, self.unknown_tag_maker.Void][void]
tempy_tag_cls = unknow_maker[tag]
attrs = {Tag._TO_SPECIALS.get(k, k): v or True for k, v in attrs}
tempy_tag = tempy_tag_cls(**attrs)
if not self.current_tag:
self.result.append(tempy_tag)
if not void:
self.current_tag = tempy_tag
else:
if not tempy_tag._void:
self.current_tag(tempy_tag)
self.current_tag = self.current_tag.childs[-1]
|
python
|
def _make_tempy_tag(self, tag, attrs, void):
"""Searches in tempy.tags for the correct tag to use, if does not exists uses the TempyFactory to
create a custom tag."""
tempy_tag_cls = getattr(self.tempy_tags, tag.title(), None)
if not tempy_tag_cls:
unknow_maker = [self.unknown_tag_maker, self.unknown_tag_maker.Void][void]
tempy_tag_cls = unknow_maker[tag]
attrs = {Tag._TO_SPECIALS.get(k, k): v or True for k, v in attrs}
tempy_tag = tempy_tag_cls(**attrs)
if not self.current_tag:
self.result.append(tempy_tag)
if not void:
self.current_tag = tempy_tag
else:
if not tempy_tag._void:
self.current_tag(tempy_tag)
self.current_tag = self.current_tag.childs[-1]
|
[
"def",
"_make_tempy_tag",
"(",
"self",
",",
"tag",
",",
"attrs",
",",
"void",
")",
":",
"tempy_tag_cls",
"=",
"getattr",
"(",
"self",
".",
"tempy_tags",
",",
"tag",
".",
"title",
"(",
")",
",",
"None",
")",
"if",
"not",
"tempy_tag_cls",
":",
"unknow_maker",
"=",
"[",
"self",
".",
"unknown_tag_maker",
",",
"self",
".",
"unknown_tag_maker",
".",
"Void",
"]",
"[",
"void",
"]",
"tempy_tag_cls",
"=",
"unknow_maker",
"[",
"tag",
"]",
"attrs",
"=",
"{",
"Tag",
".",
"_TO_SPECIALS",
".",
"get",
"(",
"k",
",",
"k",
")",
":",
"v",
"or",
"True",
"for",
"k",
",",
"v",
"in",
"attrs",
"}",
"tempy_tag",
"=",
"tempy_tag_cls",
"(",
"*",
"*",
"attrs",
")",
"if",
"not",
"self",
".",
"current_tag",
":",
"self",
".",
"result",
".",
"append",
"(",
"tempy_tag",
")",
"if",
"not",
"void",
":",
"self",
".",
"current_tag",
"=",
"tempy_tag",
"else",
":",
"if",
"not",
"tempy_tag",
".",
"_void",
":",
"self",
".",
"current_tag",
"(",
"tempy_tag",
")",
"self",
".",
"current_tag",
"=",
"self",
".",
"current_tag",
".",
"childs",
"[",
"-",
"1",
"]"
] |
Searches in tempy.tags for the correct tag to use, if does not exists uses the TempyFactory to
create a custom tag.
|
[
"Searches",
"in",
"tempy",
".",
"tags",
"for",
"the",
"correct",
"tag",
"to",
"use",
"if",
"does",
"not",
"exists",
"uses",
"the",
"TempyFactory",
"to",
"create",
"a",
"custom",
"tag",
"."
] |
7d229b73e2ce3ccbb8254deae05c1f758f626ed6
|
https://github.com/Hrabal/TemPy/blob/7d229b73e2ce3ccbb8254deae05c1f758f626ed6/tempy/t.py#L33-L49
|
train
|
Hrabal/TemPy
|
tempy/t.py
|
TempyGod.from_string
|
def from_string(self, html_string):
"""Parses an html string and returns a list of Tempy trees."""
self._html_parser._reset().feed(html_string)
return self._html_parser.result
|
python
|
def from_string(self, html_string):
"""Parses an html string and returns a list of Tempy trees."""
self._html_parser._reset().feed(html_string)
return self._html_parser.result
|
[
"def",
"from_string",
"(",
"self",
",",
"html_string",
")",
":",
"self",
".",
"_html_parser",
".",
"_reset",
"(",
")",
".",
"feed",
"(",
"html_string",
")",
"return",
"self",
".",
"_html_parser",
".",
"result"
] |
Parses an html string and returns a list of Tempy trees.
|
[
"Parses",
"an",
"html",
"string",
"and",
"returns",
"a",
"list",
"of",
"Tempy",
"trees",
"."
] |
7d229b73e2ce3ccbb8254deae05c1f758f626ed6
|
https://github.com/Hrabal/TemPy/blob/7d229b73e2ce3ccbb8254deae05c1f758f626ed6/tempy/t.py#L104-L107
|
train
|
Hrabal/TemPy
|
tempy/t.py
|
TempyGod.dump
|
def dump(self, tempy_tree_list, filename, pretty=False):
"""Dumps a Tempy object to a python file"""
if not filename:
raise ValueError('"filename" argument should not be none.')
if len(filename.split(".")) > 1 and not filename.endswith(".py"):
raise ValueError(
'"filename" argument should have a .py extension, if given.'
)
if not filename.endswith(".py"):
filename += ".py"
with open(filename, "w") as f:
f.write(
"# -*- coding: utf-8 -*-\nfrom tempy import T\nfrom tempy.tags import *\n"
)
for tempy_tree in tempy_tree_list:
f.write(tempy_tree.to_code(pretty=pretty))
return filename
|
python
|
def dump(self, tempy_tree_list, filename, pretty=False):
"""Dumps a Tempy object to a python file"""
if not filename:
raise ValueError('"filename" argument should not be none.')
if len(filename.split(".")) > 1 and not filename.endswith(".py"):
raise ValueError(
'"filename" argument should have a .py extension, if given.'
)
if not filename.endswith(".py"):
filename += ".py"
with open(filename, "w") as f:
f.write(
"# -*- coding: utf-8 -*-\nfrom tempy import T\nfrom tempy.tags import *\n"
)
for tempy_tree in tempy_tree_list:
f.write(tempy_tree.to_code(pretty=pretty))
return filename
|
[
"def",
"dump",
"(",
"self",
",",
"tempy_tree_list",
",",
"filename",
",",
"pretty",
"=",
"False",
")",
":",
"if",
"not",
"filename",
":",
"raise",
"ValueError",
"(",
"'\"filename\" argument should not be none.'",
")",
"if",
"len",
"(",
"filename",
".",
"split",
"(",
"\".\"",
")",
")",
">",
"1",
"and",
"not",
"filename",
".",
"endswith",
"(",
"\".py\"",
")",
":",
"raise",
"ValueError",
"(",
"'\"filename\" argument should have a .py extension, if given.'",
")",
"if",
"not",
"filename",
".",
"endswith",
"(",
"\".py\"",
")",
":",
"filename",
"+=",
"\".py\"",
"with",
"open",
"(",
"filename",
",",
"\"w\"",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"\"# -*- coding: utf-8 -*-\\nfrom tempy import T\\nfrom tempy.tags import *\\n\"",
")",
"for",
"tempy_tree",
"in",
"tempy_tree_list",
":",
"f",
".",
"write",
"(",
"tempy_tree",
".",
"to_code",
"(",
"pretty",
"=",
"pretty",
")",
")",
"return",
"filename"
] |
Dumps a Tempy object to a python file
|
[
"Dumps",
"a",
"Tempy",
"object",
"to",
"a",
"python",
"file"
] |
7d229b73e2ce3ccbb8254deae05c1f758f626ed6
|
https://github.com/Hrabal/TemPy/blob/7d229b73e2ce3ccbb8254deae05c1f758f626ed6/tempy/t.py#L113-L129
|
train
|
Hrabal/TemPy
|
tempy/tempyrepr.py
|
_filter_classes
|
def _filter_classes(cls_list, cls_type):
"""Filters a list of classes and yields TempyREPR subclasses"""
for cls in cls_list:
if isinstance(cls, type) and issubclass(cls, cls_type):
if cls_type == TempyPlace and cls._base_place:
pass
else:
yield cls
|
python
|
def _filter_classes(cls_list, cls_type):
"""Filters a list of classes and yields TempyREPR subclasses"""
for cls in cls_list:
if isinstance(cls, type) and issubclass(cls, cls_type):
if cls_type == TempyPlace and cls._base_place:
pass
else:
yield cls
|
[
"def",
"_filter_classes",
"(",
"cls_list",
",",
"cls_type",
")",
":",
"for",
"cls",
"in",
"cls_list",
":",
"if",
"isinstance",
"(",
"cls",
",",
"type",
")",
"and",
"issubclass",
"(",
"cls",
",",
"cls_type",
")",
":",
"if",
"cls_type",
"==",
"TempyPlace",
"and",
"cls",
".",
"_base_place",
":",
"pass",
"else",
":",
"yield",
"cls"
] |
Filters a list of classes and yields TempyREPR subclasses
|
[
"Filters",
"a",
"list",
"of",
"classes",
"and",
"yields",
"TempyREPR",
"subclasses"
] |
7d229b73e2ce3ccbb8254deae05c1f758f626ed6
|
https://github.com/Hrabal/TemPy/blob/7d229b73e2ce3ccbb8254deae05c1f758f626ed6/tempy/tempyrepr.py#L10-L17
|
train
|
Hrabal/TemPy
|
tempy/tempyrepr.py
|
REPRFinder._evaluate_tempyREPR
|
def _evaluate_tempyREPR(self, child, repr_cls):
"""Assign a score ito a TempyRepr class.
The scores depends on the current scope and position of the object in which the TempyREPR is found."""
score = 0
if repr_cls.__name__ == self.__class__.__name__:
# One point if the REPR have the same name of the container
score += 1
elif repr_cls.__name__ == self.root.__class__.__name__:
# One point if the REPR have the same name of the Tempy tree root
score += 1
# Add points defined in scorers methods of used TempyPlaces
for parent_cls in _filter_classes(repr_cls.__mro__[1:], TempyPlace):
for scorer in (
method for method in dir(parent_cls) if method.startswith("_reprscore")
):
score += getattr(parent_cls, scorer, lambda *args: 0)(
parent_cls, self, child
)
return score
|
python
|
def _evaluate_tempyREPR(self, child, repr_cls):
"""Assign a score ito a TempyRepr class.
The scores depends on the current scope and position of the object in which the TempyREPR is found."""
score = 0
if repr_cls.__name__ == self.__class__.__name__:
# One point if the REPR have the same name of the container
score += 1
elif repr_cls.__name__ == self.root.__class__.__name__:
# One point if the REPR have the same name of the Tempy tree root
score += 1
# Add points defined in scorers methods of used TempyPlaces
for parent_cls in _filter_classes(repr_cls.__mro__[1:], TempyPlace):
for scorer in (
method for method in dir(parent_cls) if method.startswith("_reprscore")
):
score += getattr(parent_cls, scorer, lambda *args: 0)(
parent_cls, self, child
)
return score
|
[
"def",
"_evaluate_tempyREPR",
"(",
"self",
",",
"child",
",",
"repr_cls",
")",
":",
"score",
"=",
"0",
"if",
"repr_cls",
".",
"__name__",
"==",
"self",
".",
"__class__",
".",
"__name__",
":",
"# One point if the REPR have the same name of the container",
"score",
"+=",
"1",
"elif",
"repr_cls",
".",
"__name__",
"==",
"self",
".",
"root",
".",
"__class__",
".",
"__name__",
":",
"# One point if the REPR have the same name of the Tempy tree root",
"score",
"+=",
"1",
"# Add points defined in scorers methods of used TempyPlaces",
"for",
"parent_cls",
"in",
"_filter_classes",
"(",
"repr_cls",
".",
"__mro__",
"[",
"1",
":",
"]",
",",
"TempyPlace",
")",
":",
"for",
"scorer",
"in",
"(",
"method",
"for",
"method",
"in",
"dir",
"(",
"parent_cls",
")",
"if",
"method",
".",
"startswith",
"(",
"\"_reprscore\"",
")",
")",
":",
"score",
"+=",
"getattr",
"(",
"parent_cls",
",",
"scorer",
",",
"lambda",
"*",
"args",
":",
"0",
")",
"(",
"parent_cls",
",",
"self",
",",
"child",
")",
"return",
"score"
] |
Assign a score ito a TempyRepr class.
The scores depends on the current scope and position of the object in which the TempyREPR is found.
|
[
"Assign",
"a",
"score",
"ito",
"a",
"TempyRepr",
"class",
".",
"The",
"scores",
"depends",
"on",
"the",
"current",
"scope",
"and",
"position",
"of",
"the",
"object",
"in",
"which",
"the",
"TempyREPR",
"is",
"found",
"."
] |
7d229b73e2ce3ccbb8254deae05c1f758f626ed6
|
https://github.com/Hrabal/TemPy/blob/7d229b73e2ce3ccbb8254deae05c1f758f626ed6/tempy/tempyrepr.py#L23-L42
|
train
|
Hrabal/TemPy
|
tempy/tempyrepr.py
|
REPRFinder._search_for_view
|
def _search_for_view(self, obj):
"""Searches for TempyREPR class declarations in the child's class.
If at least one TempyREPR is found, it uses the best one to make a Tempy object.
Otherwise the original object is returned.
"""
evaluator = partial(self._evaluate_tempyREPR, obj)
sorted_reprs = sorted(
_filter_classes(obj.__class__.__dict__.values(), TempyREPR),
key=evaluator,
reverse=True,
)
if sorted_reprs:
# If we find some TempyREPR, we return the one with the best score.
return sorted_reprs[0]
return None
|
python
|
def _search_for_view(self, obj):
"""Searches for TempyREPR class declarations in the child's class.
If at least one TempyREPR is found, it uses the best one to make a Tempy object.
Otherwise the original object is returned.
"""
evaluator = partial(self._evaluate_tempyREPR, obj)
sorted_reprs = sorted(
_filter_classes(obj.__class__.__dict__.values(), TempyREPR),
key=evaluator,
reverse=True,
)
if sorted_reprs:
# If we find some TempyREPR, we return the one with the best score.
return sorted_reprs[0]
return None
|
[
"def",
"_search_for_view",
"(",
"self",
",",
"obj",
")",
":",
"evaluator",
"=",
"partial",
"(",
"self",
".",
"_evaluate_tempyREPR",
",",
"obj",
")",
"sorted_reprs",
"=",
"sorted",
"(",
"_filter_classes",
"(",
"obj",
".",
"__class__",
".",
"__dict__",
".",
"values",
"(",
")",
",",
"TempyREPR",
")",
",",
"key",
"=",
"evaluator",
",",
"reverse",
"=",
"True",
",",
")",
"if",
"sorted_reprs",
":",
"# If we find some TempyREPR, we return the one with the best score.",
"return",
"sorted_reprs",
"[",
"0",
"]",
"return",
"None"
] |
Searches for TempyREPR class declarations in the child's class.
If at least one TempyREPR is found, it uses the best one to make a Tempy object.
Otherwise the original object is returned.
|
[
"Searches",
"for",
"TempyREPR",
"class",
"declarations",
"in",
"the",
"child",
"s",
"class",
".",
"If",
"at",
"least",
"one",
"TempyREPR",
"is",
"found",
"it",
"uses",
"the",
"best",
"one",
"to",
"make",
"a",
"Tempy",
"object",
".",
"Otherwise",
"the",
"original",
"object",
"is",
"returned",
"."
] |
7d229b73e2ce3ccbb8254deae05c1f758f626ed6
|
https://github.com/Hrabal/TemPy/blob/7d229b73e2ce3ccbb8254deae05c1f758f626ed6/tempy/tempyrepr.py#L44-L58
|
train
|
Hrabal/TemPy
|
tempy/widgets.py
|
TempyTable.add_row
|
def add_row(self, row_data, resize_x=True):
"""Adds a row at the end of the table"""
if not resize_x:
self._check_row_size(row_data)
self.body(Tr()(Td()(cell) for cell in row_data))
return self
|
python
|
def add_row(self, row_data, resize_x=True):
"""Adds a row at the end of the table"""
if not resize_x:
self._check_row_size(row_data)
self.body(Tr()(Td()(cell) for cell in row_data))
return self
|
[
"def",
"add_row",
"(",
"self",
",",
"row_data",
",",
"resize_x",
"=",
"True",
")",
":",
"if",
"not",
"resize_x",
":",
"self",
".",
"_check_row_size",
"(",
"row_data",
")",
"self",
".",
"body",
"(",
"Tr",
"(",
")",
"(",
"Td",
"(",
")",
"(",
"cell",
")",
"for",
"cell",
"in",
"row_data",
")",
")",
"return",
"self"
] |
Adds a row at the end of the table
|
[
"Adds",
"a",
"row",
"at",
"the",
"end",
"of",
"the",
"table"
] |
7d229b73e2ce3ccbb8254deae05c1f758f626ed6
|
https://github.com/Hrabal/TemPy/blob/7d229b73e2ce3ccbb8254deae05c1f758f626ed6/tempy/widgets.py#L174-L179
|
train
|
Hrabal/TemPy
|
tempy/widgets.py
|
TempyTable.pop_row
|
def pop_row(self, idr=None, tags=False):
"""Pops a row, default the last"""
idr = idr if idr is not None else len(self.body) - 1
row = self.body.pop(idr)
return row if tags else [cell.childs[0] for cell in row]
|
python
|
def pop_row(self, idr=None, tags=False):
"""Pops a row, default the last"""
idr = idr if idr is not None else len(self.body) - 1
row = self.body.pop(idr)
return row if tags else [cell.childs[0] for cell in row]
|
[
"def",
"pop_row",
"(",
"self",
",",
"idr",
"=",
"None",
",",
"tags",
"=",
"False",
")",
":",
"idr",
"=",
"idr",
"if",
"idr",
"is",
"not",
"None",
"else",
"len",
"(",
"self",
".",
"body",
")",
"-",
"1",
"row",
"=",
"self",
".",
"body",
".",
"pop",
"(",
"idr",
")",
"return",
"row",
"if",
"tags",
"else",
"[",
"cell",
".",
"childs",
"[",
"0",
"]",
"for",
"cell",
"in",
"row",
"]"
] |
Pops a row, default the last
|
[
"Pops",
"a",
"row",
"default",
"the",
"last"
] |
7d229b73e2ce3ccbb8254deae05c1f758f626ed6
|
https://github.com/Hrabal/TemPy/blob/7d229b73e2ce3ccbb8254deae05c1f758f626ed6/tempy/widgets.py#L181-L185
|
train
|
Hrabal/TemPy
|
tempy/widgets.py
|
TempyTable.pop_cell
|
def pop_cell(self, idy=None, idx=None, tags=False):
"""Pops a cell, default the last of the last row"""
idy = idy if idy is not None else len(self.body) - 1
idx = idx if idx is not None else len(self.body[idy]) - 1
cell = self.body[idy].pop(idx)
return cell if tags else cell.childs[0]
|
python
|
def pop_cell(self, idy=None, idx=None, tags=False):
"""Pops a cell, default the last of the last row"""
idy = idy if idy is not None else len(self.body) - 1
idx = idx if idx is not None else len(self.body[idy]) - 1
cell = self.body[idy].pop(idx)
return cell if tags else cell.childs[0]
|
[
"def",
"pop_cell",
"(",
"self",
",",
"idy",
"=",
"None",
",",
"idx",
"=",
"None",
",",
"tags",
"=",
"False",
")",
":",
"idy",
"=",
"idy",
"if",
"idy",
"is",
"not",
"None",
"else",
"len",
"(",
"self",
".",
"body",
")",
"-",
"1",
"idx",
"=",
"idx",
"if",
"idx",
"is",
"not",
"None",
"else",
"len",
"(",
"self",
".",
"body",
"[",
"idy",
"]",
")",
"-",
"1",
"cell",
"=",
"self",
".",
"body",
"[",
"idy",
"]",
".",
"pop",
"(",
"idx",
")",
"return",
"cell",
"if",
"tags",
"else",
"cell",
".",
"childs",
"[",
"0",
"]"
] |
Pops a cell, default the last of the last row
|
[
"Pops",
"a",
"cell",
"default",
"the",
"last",
"of",
"the",
"last",
"row"
] |
7d229b73e2ce3ccbb8254deae05c1f758f626ed6
|
https://github.com/Hrabal/TemPy/blob/7d229b73e2ce3ccbb8254deae05c1f758f626ed6/tempy/widgets.py#L187-L192
|
train
|
Hrabal/TemPy
|
tempy/tags.py
|
Html.render
|
def render(self, *args, **kwargs):
"""Override so each html page served have a doctype"""
return self.doctype.render() + super().render(*args, **kwargs)
|
python
|
def render(self, *args, **kwargs):
"""Override so each html page served have a doctype"""
return self.doctype.render() + super().render(*args, **kwargs)
|
[
"def",
"render",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"doctype",
".",
"render",
"(",
")",
"+",
"super",
"(",
")",
".",
"render",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] |
Override so each html page served have a doctype
|
[
"Override",
"so",
"each",
"html",
"page",
"served",
"have",
"a",
"doctype"
] |
7d229b73e2ce3ccbb8254deae05c1f758f626ed6
|
https://github.com/Hrabal/TemPy/blob/7d229b73e2ce3ccbb8254deae05c1f758f626ed6/tempy/tags.py#L71-L73
|
train
|
Hrabal/TemPy
|
tempy/tempy.py
|
DOMNavigator._find_content
|
def _find_content(self, cont_name):
"""Search for a content_name in the content data, if not found the parent is searched."""
try:
a = self.content_data[cont_name]
return a
except KeyError:
if self.parent:
return self.parent._find_content(cont_name)
else:
# Fallback for no content (Raise NoContent?)
return ""
|
python
|
def _find_content(self, cont_name):
"""Search for a content_name in the content data, if not found the parent is searched."""
try:
a = self.content_data[cont_name]
return a
except KeyError:
if self.parent:
return self.parent._find_content(cont_name)
else:
# Fallback for no content (Raise NoContent?)
return ""
|
[
"def",
"_find_content",
"(",
"self",
",",
"cont_name",
")",
":",
"try",
":",
"a",
"=",
"self",
".",
"content_data",
"[",
"cont_name",
"]",
"return",
"a",
"except",
"KeyError",
":",
"if",
"self",
".",
"parent",
":",
"return",
"self",
".",
"parent",
".",
"_find_content",
"(",
"cont_name",
")",
"else",
":",
"# Fallback for no content (Raise NoContent?)",
"return",
"\"\""
] |
Search for a content_name in the content data, if not found the parent is searched.
|
[
"Search",
"for",
"a",
"content_name",
"in",
"the",
"content",
"data",
"if",
"not",
"found",
"the",
"parent",
"is",
"searched",
"."
] |
7d229b73e2ce3ccbb8254deae05c1f758f626ed6
|
https://github.com/Hrabal/TemPy/blob/7d229b73e2ce3ccbb8254deae05c1f758f626ed6/tempy/tempy.py#L26-L36
|
train
|
Hrabal/TemPy
|
tempy/tempy.py
|
DOMNavigator._get_non_tempy_contents
|
def _get_non_tempy_contents(self):
"""Returns rendered Contents and non-DOMElement stuff inside this Tag."""
for thing in filter(
lambda x: not issubclass(x.__class__, DOMElement), self.childs
):
yield thing
|
python
|
def _get_non_tempy_contents(self):
"""Returns rendered Contents and non-DOMElement stuff inside this Tag."""
for thing in filter(
lambda x: not issubclass(x.__class__, DOMElement), self.childs
):
yield thing
|
[
"def",
"_get_non_tempy_contents",
"(",
"self",
")",
":",
"for",
"thing",
"in",
"filter",
"(",
"lambda",
"x",
":",
"not",
"issubclass",
"(",
"x",
".",
"__class__",
",",
"DOMElement",
")",
",",
"self",
".",
"childs",
")",
":",
"yield",
"thing"
] |
Returns rendered Contents and non-DOMElement stuff inside this Tag.
|
[
"Returns",
"rendered",
"Contents",
"and",
"non",
"-",
"DOMElement",
"stuff",
"inside",
"this",
"Tag",
"."
] |
7d229b73e2ce3ccbb8254deae05c1f758f626ed6
|
https://github.com/Hrabal/TemPy/blob/7d229b73e2ce3ccbb8254deae05c1f758f626ed6/tempy/tempy.py#L38-L43
|
train
|
Hrabal/TemPy
|
tempy/tempy.py
|
DOMNavigator.siblings
|
def siblings(self):
"""Returns all the siblings of this element as a list."""
return list(filter(lambda x: id(x) != id(self), self.parent.childs))
|
python
|
def siblings(self):
"""Returns all the siblings of this element as a list."""
return list(filter(lambda x: id(x) != id(self), self.parent.childs))
|
[
"def",
"siblings",
"(",
"self",
")",
":",
"return",
"list",
"(",
"filter",
"(",
"lambda",
"x",
":",
"id",
"(",
"x",
")",
"!=",
"id",
"(",
"self",
")",
",",
"self",
".",
"parent",
".",
"childs",
")",
")"
] |
Returns all the siblings of this element as a list.
|
[
"Returns",
"all",
"the",
"siblings",
"of",
"this",
"element",
"as",
"a",
"list",
"."
] |
7d229b73e2ce3ccbb8254deae05c1f758f626ed6
|
https://github.com/Hrabal/TemPy/blob/7d229b73e2ce3ccbb8254deae05c1f758f626ed6/tempy/tempy.py#L129-L131
|
train
|
Hrabal/TemPy
|
tempy/tempy.py
|
DOMNavigator.bft
|
def bft(self):
""" Generator that returns each element of the tree in Breadth-first order"""
queue = deque([self])
while queue:
node = queue.pop()
yield node
if hasattr(node, "childs"):
queue.extendleft(node.childs)
|
python
|
def bft(self):
""" Generator that returns each element of the tree in Breadth-first order"""
queue = deque([self])
while queue:
node = queue.pop()
yield node
if hasattr(node, "childs"):
queue.extendleft(node.childs)
|
[
"def",
"bft",
"(",
"self",
")",
":",
"queue",
"=",
"deque",
"(",
"[",
"self",
"]",
")",
"while",
"queue",
":",
"node",
"=",
"queue",
".",
"pop",
"(",
")",
"yield",
"node",
"if",
"hasattr",
"(",
"node",
",",
"\"childs\"",
")",
":",
"queue",
".",
"extendleft",
"(",
"node",
".",
"childs",
")"
] |
Generator that returns each element of the tree in Breadth-first order
|
[
"Generator",
"that",
"returns",
"each",
"element",
"of",
"the",
"tree",
"in",
"Breadth",
"-",
"first",
"order"
] |
7d229b73e2ce3ccbb8254deae05c1f758f626ed6
|
https://github.com/Hrabal/TemPy/blob/7d229b73e2ce3ccbb8254deae05c1f758f626ed6/tempy/tempy.py#L141-L148
|
train
|
Hrabal/TemPy
|
tempy/tempy.py
|
DOMModifier._insert
|
def _insert(self, dom_group, idx=None, prepend=False, name=None):
"""Inserts a DOMGroup inside this element.
If provided at the given index, if prepend at the start of the childs list, by default at the end.
If the child is a DOMElement, correctly links the child.
If the DOMGroup have a name, an attribute containing the child is created in this instance.
"""
if idx and idx < 0:
idx = 0
if prepend:
idx = 0
else:
idx = idx if idx is not None else len(self.childs)
if dom_group is not None:
if not isinstance(dom_group, Iterable) or isinstance(
dom_group, (DOMElement, str)
):
dom_group = [dom_group]
for i_group, elem in enumerate(dom_group):
if elem is not None:
# Element insertion in this DOMElement childs
self.childs.insert(idx + i_group, elem)
# Managing child attributes if needed
if issubclass(elem.__class__, DOMElement):
elem.parent = self
if name:
setattr(self, name, elem)
|
python
|
def _insert(self, dom_group, idx=None, prepend=False, name=None):
"""Inserts a DOMGroup inside this element.
If provided at the given index, if prepend at the start of the childs list, by default at the end.
If the child is a DOMElement, correctly links the child.
If the DOMGroup have a name, an attribute containing the child is created in this instance.
"""
if idx and idx < 0:
idx = 0
if prepend:
idx = 0
else:
idx = idx if idx is not None else len(self.childs)
if dom_group is not None:
if not isinstance(dom_group, Iterable) or isinstance(
dom_group, (DOMElement, str)
):
dom_group = [dom_group]
for i_group, elem in enumerate(dom_group):
if elem is not None:
# Element insertion in this DOMElement childs
self.childs.insert(idx + i_group, elem)
# Managing child attributes if needed
if issubclass(elem.__class__, DOMElement):
elem.parent = self
if name:
setattr(self, name, elem)
|
[
"def",
"_insert",
"(",
"self",
",",
"dom_group",
",",
"idx",
"=",
"None",
",",
"prepend",
"=",
"False",
",",
"name",
"=",
"None",
")",
":",
"if",
"idx",
"and",
"idx",
"<",
"0",
":",
"idx",
"=",
"0",
"if",
"prepend",
":",
"idx",
"=",
"0",
"else",
":",
"idx",
"=",
"idx",
"if",
"idx",
"is",
"not",
"None",
"else",
"len",
"(",
"self",
".",
"childs",
")",
"if",
"dom_group",
"is",
"not",
"None",
":",
"if",
"not",
"isinstance",
"(",
"dom_group",
",",
"Iterable",
")",
"or",
"isinstance",
"(",
"dom_group",
",",
"(",
"DOMElement",
",",
"str",
")",
")",
":",
"dom_group",
"=",
"[",
"dom_group",
"]",
"for",
"i_group",
",",
"elem",
"in",
"enumerate",
"(",
"dom_group",
")",
":",
"if",
"elem",
"is",
"not",
"None",
":",
"# Element insertion in this DOMElement childs",
"self",
".",
"childs",
".",
"insert",
"(",
"idx",
"+",
"i_group",
",",
"elem",
")",
"# Managing child attributes if needed",
"if",
"issubclass",
"(",
"elem",
".",
"__class__",
",",
"DOMElement",
")",
":",
"elem",
".",
"parent",
"=",
"self",
"if",
"name",
":",
"setattr",
"(",
"self",
",",
"name",
",",
"elem",
")"
] |
Inserts a DOMGroup inside this element.
If provided at the given index, if prepend at the start of the childs list, by default at the end.
If the child is a DOMElement, correctly links the child.
If the DOMGroup have a name, an attribute containing the child is created in this instance.
|
[
"Inserts",
"a",
"DOMGroup",
"inside",
"this",
"element",
".",
"If",
"provided",
"at",
"the",
"given",
"index",
"if",
"prepend",
"at",
"the",
"start",
"of",
"the",
"childs",
"list",
"by",
"default",
"at",
"the",
"end",
".",
"If",
"the",
"child",
"is",
"a",
"DOMElement",
"correctly",
"links",
"the",
"child",
".",
"If",
"the",
"DOMGroup",
"have",
"a",
"name",
"an",
"attribute",
"containing",
"the",
"child",
"is",
"created",
"in",
"this",
"instance",
"."
] |
7d229b73e2ce3ccbb8254deae05c1f758f626ed6
|
https://github.com/Hrabal/TemPy/blob/7d229b73e2ce3ccbb8254deae05c1f758f626ed6/tempy/tempy.py#L245-L270
|
train
|
Hrabal/TemPy
|
tempy/tempy.py
|
DOMModifier.after
|
def after(self, i, sibling, name=None):
"""Adds siblings after the current tag."""
self.parent._insert(sibling, idx=self._own_index + 1 + i, name=name)
return self
|
python
|
def after(self, i, sibling, name=None):
"""Adds siblings after the current tag."""
self.parent._insert(sibling, idx=self._own_index + 1 + i, name=name)
return self
|
[
"def",
"after",
"(",
"self",
",",
"i",
",",
"sibling",
",",
"name",
"=",
"None",
")",
":",
"self",
".",
"parent",
".",
"_insert",
"(",
"sibling",
",",
"idx",
"=",
"self",
".",
"_own_index",
"+",
"1",
"+",
"i",
",",
"name",
"=",
"name",
")",
"return",
"self"
] |
Adds siblings after the current tag.
|
[
"Adds",
"siblings",
"after",
"the",
"current",
"tag",
"."
] |
7d229b73e2ce3ccbb8254deae05c1f758f626ed6
|
https://github.com/Hrabal/TemPy/blob/7d229b73e2ce3ccbb8254deae05c1f758f626ed6/tempy/tempy.py#L317-L320
|
train
|
Hrabal/TemPy
|
tempy/tempy.py
|
DOMModifier.prepend
|
def prepend(self, _, child, name=None):
"""Adds childs to this tag, starting from the first position."""
self._insert(child, prepend=True, name=name)
return self
|
python
|
def prepend(self, _, child, name=None):
"""Adds childs to this tag, starting from the first position."""
self._insert(child, prepend=True, name=name)
return self
|
[
"def",
"prepend",
"(",
"self",
",",
"_",
",",
"child",
",",
"name",
"=",
"None",
")",
":",
"self",
".",
"_insert",
"(",
"child",
",",
"prepend",
"=",
"True",
",",
"name",
"=",
"name",
")",
"return",
"self"
] |
Adds childs to this tag, starting from the first position.
|
[
"Adds",
"childs",
"to",
"this",
"tag",
"starting",
"from",
"the",
"first",
"position",
"."
] |
7d229b73e2ce3ccbb8254deae05c1f758f626ed6
|
https://github.com/Hrabal/TemPy/blob/7d229b73e2ce3ccbb8254deae05c1f758f626ed6/tempy/tempy.py#L329-L332
|
train
|
Hrabal/TemPy
|
tempy/tempy.py
|
DOMModifier.append
|
def append(self, _, child, name=None):
"""Adds childs to this tag, after the current existing childs."""
self._insert(child, name=name)
return self
|
python
|
def append(self, _, child, name=None):
"""Adds childs to this tag, after the current existing childs."""
self._insert(child, name=name)
return self
|
[
"def",
"append",
"(",
"self",
",",
"_",
",",
"child",
",",
"name",
"=",
"None",
")",
":",
"self",
".",
"_insert",
"(",
"child",
",",
"name",
"=",
"name",
")",
"return",
"self"
] |
Adds childs to this tag, after the current existing childs.
|
[
"Adds",
"childs",
"to",
"this",
"tag",
"after",
"the",
"current",
"existing",
"childs",
"."
] |
7d229b73e2ce3ccbb8254deae05c1f758f626ed6
|
https://github.com/Hrabal/TemPy/blob/7d229b73e2ce3ccbb8254deae05c1f758f626ed6/tempy/tempy.py#L340-L343
|
train
|
Hrabal/TemPy
|
tempy/tempy.py
|
DOMModifier.wrap
|
def wrap(self, other):
"""Wraps this element inside another empty tag."""
if other.childs:
raise TagError(self, "Wrapping in a non empty Tag is forbidden.")
if self.parent:
self.before(other)
self.parent.pop(self._own_index)
other.append(self)
return self
|
python
|
def wrap(self, other):
"""Wraps this element inside another empty tag."""
if other.childs:
raise TagError(self, "Wrapping in a non empty Tag is forbidden.")
if self.parent:
self.before(other)
self.parent.pop(self._own_index)
other.append(self)
return self
|
[
"def",
"wrap",
"(",
"self",
",",
"other",
")",
":",
"if",
"other",
".",
"childs",
":",
"raise",
"TagError",
"(",
"self",
",",
"\"Wrapping in a non empty Tag is forbidden.\"",
")",
"if",
"self",
".",
"parent",
":",
"self",
".",
"before",
"(",
"other",
")",
"self",
".",
"parent",
".",
"pop",
"(",
"self",
".",
"_own_index",
")",
"other",
".",
"append",
"(",
"self",
")",
"return",
"self"
] |
Wraps this element inside another empty tag.
|
[
"Wraps",
"this",
"element",
"inside",
"another",
"empty",
"tag",
"."
] |
7d229b73e2ce3ccbb8254deae05c1f758f626ed6
|
https://github.com/Hrabal/TemPy/blob/7d229b73e2ce3ccbb8254deae05c1f758f626ed6/tempy/tempy.py#L350-L358
|
train
|
Hrabal/TemPy
|
tempy/tempy.py
|
DOMModifier.replace_with
|
def replace_with(self, other):
"""Replace this element with the given DOMElement."""
self.after(other)
self.parent.pop(self._own_index)
return other
|
python
|
def replace_with(self, other):
"""Replace this element with the given DOMElement."""
self.after(other)
self.parent.pop(self._own_index)
return other
|
[
"def",
"replace_with",
"(",
"self",
",",
"other",
")",
":",
"self",
".",
"after",
"(",
"other",
")",
"self",
".",
"parent",
".",
"pop",
"(",
"self",
".",
"_own_index",
")",
"return",
"other"
] |
Replace this element with the given DOMElement.
|
[
"Replace",
"this",
"element",
"with",
"the",
"given",
"DOMElement",
"."
] |
7d229b73e2ce3ccbb8254deae05c1f758f626ed6
|
https://github.com/Hrabal/TemPy/blob/7d229b73e2ce3ccbb8254deae05c1f758f626ed6/tempy/tempy.py#L427-L431
|
train
|
Hrabal/TemPy
|
tempy/tempy.py
|
DOMModifier.remove
|
def remove(self):
"""Detach this element from his father."""
if self._own_index is not None and self.parent:
self.parent.pop(self._own_index)
return self
|
python
|
def remove(self):
"""Detach this element from his father."""
if self._own_index is not None and self.parent:
self.parent.pop(self._own_index)
return self
|
[
"def",
"remove",
"(",
"self",
")",
":",
"if",
"self",
".",
"_own_index",
"is",
"not",
"None",
"and",
"self",
".",
"parent",
":",
"self",
".",
"parent",
".",
"pop",
"(",
"self",
".",
"_own_index",
")",
"return",
"self"
] |
Detach this element from his father.
|
[
"Detach",
"this",
"element",
"from",
"his",
"father",
"."
] |
7d229b73e2ce3ccbb8254deae05c1f758f626ed6
|
https://github.com/Hrabal/TemPy/blob/7d229b73e2ce3ccbb8254deae05c1f758f626ed6/tempy/tempy.py#L433-L437
|
train
|
Hrabal/TemPy
|
tempy/tempy.py
|
DOMModifier._detach_childs
|
def _detach_childs(self, idx_from=None, idx_to=None):
"""Moves all the childs to a new father"""
idx_from = idx_from or 0
idx_to = idx_to or len(self.childs)
removed = self.childs[idx_from:idx_to]
for child in removed:
if issubclass(child.__class__, DOMElement):
child.parent = None
self.childs[idx_from:idx_to] = []
return removed
|
python
|
def _detach_childs(self, idx_from=None, idx_to=None):
"""Moves all the childs to a new father"""
idx_from = idx_from or 0
idx_to = idx_to or len(self.childs)
removed = self.childs[idx_from:idx_to]
for child in removed:
if issubclass(child.__class__, DOMElement):
child.parent = None
self.childs[idx_from:idx_to] = []
return removed
|
[
"def",
"_detach_childs",
"(",
"self",
",",
"idx_from",
"=",
"None",
",",
"idx_to",
"=",
"None",
")",
":",
"idx_from",
"=",
"idx_from",
"or",
"0",
"idx_to",
"=",
"idx_to",
"or",
"len",
"(",
"self",
".",
"childs",
")",
"removed",
"=",
"self",
".",
"childs",
"[",
"idx_from",
":",
"idx_to",
"]",
"for",
"child",
"in",
"removed",
":",
"if",
"issubclass",
"(",
"child",
".",
"__class__",
",",
"DOMElement",
")",
":",
"child",
".",
"parent",
"=",
"None",
"self",
".",
"childs",
"[",
"idx_from",
":",
"idx_to",
"]",
"=",
"[",
"]",
"return",
"removed"
] |
Moves all the childs to a new father
|
[
"Moves",
"all",
"the",
"childs",
"to",
"a",
"new",
"father"
] |
7d229b73e2ce3ccbb8254deae05c1f758f626ed6
|
https://github.com/Hrabal/TemPy/blob/7d229b73e2ce3ccbb8254deae05c1f758f626ed6/tempy/tempy.py#L439-L448
|
train
|
Hrabal/TemPy
|
tempy/tempy.py
|
DOMModifier.move
|
def move(self, new_father, idx=None, prepend=None, name=None):
"""Moves this element from his father to the given one."""
self.parent.pop(self._own_index)
new_father._insert(self, idx=idx, prepend=prepend, name=name)
new_father._stable = False
return self
|
python
|
def move(self, new_father, idx=None, prepend=None, name=None):
"""Moves this element from his father to the given one."""
self.parent.pop(self._own_index)
new_father._insert(self, idx=idx, prepend=prepend, name=name)
new_father._stable = False
return self
|
[
"def",
"move",
"(",
"self",
",",
"new_father",
",",
"idx",
"=",
"None",
",",
"prepend",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"self",
".",
"parent",
".",
"pop",
"(",
"self",
".",
"_own_index",
")",
"new_father",
".",
"_insert",
"(",
"self",
",",
"idx",
"=",
"idx",
",",
"prepend",
"=",
"prepend",
",",
"name",
"=",
"name",
")",
"new_father",
".",
"_stable",
"=",
"False",
"return",
"self"
] |
Moves this element from his father to the given one.
|
[
"Moves",
"this",
"element",
"from",
"his",
"father",
"to",
"the",
"given",
"one",
"."
] |
7d229b73e2ce3ccbb8254deae05c1f758f626ed6
|
https://github.com/Hrabal/TemPy/blob/7d229b73e2ce3ccbb8254deae05c1f758f626ed6/tempy/tempy.py#L455-L460
|
train
|
user-cont/colin
|
colin/core/colin.py
|
run
|
def run(
target,
target_type,
tags=None,
ruleset_name=None,
ruleset_file=None,
ruleset=None,
logging_level=logging.WARNING,
checks_paths=None,
pull=None,
insecure=False,
skips=None,
timeout=None,
):
"""
Runs the sanity checks for the target.
:param timeout: timeout per-check (in seconds)
:param skips: name of checks to skip
:param target: str (image name, ostree or dockertar)
or ImageTarget
or path/file-like object for dockerfile
:param target_type: string, either image, dockerfile, dockertar
:param tags: list of str (if not None, the checks will be filtered by tags.)
:param ruleset_name: str (e.g. fedora; if None, default would be used)
:param ruleset_file: fileobj instance holding ruleset configuration
:param ruleset: dict, content of a ruleset file
:param logging_level: logging level (default logging.WARNING)
:param checks_paths: list of str, directories where the checks are present
:param pull: bool, pull the image from registry
:param insecure: bool, pull from an insecure registry (HTTP/invalid TLS)
:return: Results instance
"""
_set_logging(level=logging_level)
logger.debug("Checking started.")
target = Target.get_instance(
target=target,
logging_level=logging_level,
pull=pull,
target_type=target_type,
insecure=insecure,
)
checks_to_run = _get_checks(
target_type=target.__class__,
tags=tags,
ruleset_name=ruleset_name,
ruleset_file=ruleset_file,
ruleset=ruleset,
checks_paths=checks_paths,
skips=skips,
)
result = go_through_checks(target=target, checks=checks_to_run, timeout=timeout)
return result
|
python
|
def run(
target,
target_type,
tags=None,
ruleset_name=None,
ruleset_file=None,
ruleset=None,
logging_level=logging.WARNING,
checks_paths=None,
pull=None,
insecure=False,
skips=None,
timeout=None,
):
"""
Runs the sanity checks for the target.
:param timeout: timeout per-check (in seconds)
:param skips: name of checks to skip
:param target: str (image name, ostree or dockertar)
or ImageTarget
or path/file-like object for dockerfile
:param target_type: string, either image, dockerfile, dockertar
:param tags: list of str (if not None, the checks will be filtered by tags.)
:param ruleset_name: str (e.g. fedora; if None, default would be used)
:param ruleset_file: fileobj instance holding ruleset configuration
:param ruleset: dict, content of a ruleset file
:param logging_level: logging level (default logging.WARNING)
:param checks_paths: list of str, directories where the checks are present
:param pull: bool, pull the image from registry
:param insecure: bool, pull from an insecure registry (HTTP/invalid TLS)
:return: Results instance
"""
_set_logging(level=logging_level)
logger.debug("Checking started.")
target = Target.get_instance(
target=target,
logging_level=logging_level,
pull=pull,
target_type=target_type,
insecure=insecure,
)
checks_to_run = _get_checks(
target_type=target.__class__,
tags=tags,
ruleset_name=ruleset_name,
ruleset_file=ruleset_file,
ruleset=ruleset,
checks_paths=checks_paths,
skips=skips,
)
result = go_through_checks(target=target, checks=checks_to_run, timeout=timeout)
return result
|
[
"def",
"run",
"(",
"target",
",",
"target_type",
",",
"tags",
"=",
"None",
",",
"ruleset_name",
"=",
"None",
",",
"ruleset_file",
"=",
"None",
",",
"ruleset",
"=",
"None",
",",
"logging_level",
"=",
"logging",
".",
"WARNING",
",",
"checks_paths",
"=",
"None",
",",
"pull",
"=",
"None",
",",
"insecure",
"=",
"False",
",",
"skips",
"=",
"None",
",",
"timeout",
"=",
"None",
",",
")",
":",
"_set_logging",
"(",
"level",
"=",
"logging_level",
")",
"logger",
".",
"debug",
"(",
"\"Checking started.\"",
")",
"target",
"=",
"Target",
".",
"get_instance",
"(",
"target",
"=",
"target",
",",
"logging_level",
"=",
"logging_level",
",",
"pull",
"=",
"pull",
",",
"target_type",
"=",
"target_type",
",",
"insecure",
"=",
"insecure",
",",
")",
"checks_to_run",
"=",
"_get_checks",
"(",
"target_type",
"=",
"target",
".",
"__class__",
",",
"tags",
"=",
"tags",
",",
"ruleset_name",
"=",
"ruleset_name",
",",
"ruleset_file",
"=",
"ruleset_file",
",",
"ruleset",
"=",
"ruleset",
",",
"checks_paths",
"=",
"checks_paths",
",",
"skips",
"=",
"skips",
",",
")",
"result",
"=",
"go_through_checks",
"(",
"target",
"=",
"target",
",",
"checks",
"=",
"checks_to_run",
",",
"timeout",
"=",
"timeout",
")",
"return",
"result"
] |
Runs the sanity checks for the target.
:param timeout: timeout per-check (in seconds)
:param skips: name of checks to skip
:param target: str (image name, ostree or dockertar)
or ImageTarget
or path/file-like object for dockerfile
:param target_type: string, either image, dockerfile, dockertar
:param tags: list of str (if not None, the checks will be filtered by tags.)
:param ruleset_name: str (e.g. fedora; if None, default would be used)
:param ruleset_file: fileobj instance holding ruleset configuration
:param ruleset: dict, content of a ruleset file
:param logging_level: logging level (default logging.WARNING)
:param checks_paths: list of str, directories where the checks are present
:param pull: bool, pull the image from registry
:param insecure: bool, pull from an insecure registry (HTTP/invalid TLS)
:return: Results instance
|
[
"Runs",
"the",
"sanity",
"checks",
"for",
"the",
"target",
"."
] |
00bb80e6e91522e15361935f813e8cf13d7e76dc
|
https://github.com/user-cont/colin/blob/00bb80e6e91522e15361935f813e8cf13d7e76dc/colin/core/colin.py#L26-L78
|
train
|
user-cont/colin
|
colin/core/colin.py
|
get_checks
|
def get_checks(
target_type=None,
tags=None,
ruleset_name=None,
ruleset_file=None,
ruleset=None,
logging_level=logging.WARNING,
checks_paths=None,
skips=None,
):
"""
Get the sanity checks for the target.
:param skips: name of checks to skip
:param target_type: TargetType enum
:param tags: list of str (if not None, the checks will be filtered by tags.)
:param ruleset_name: str (e.g. fedora; if None, default would be used)
:param ruleset_file: fileobj instance holding ruleset configuration
:param ruleset: dict, content of a ruleset file
:param logging_level: logging level (default logging.WARNING)
:param checks_paths: list of str, directories where the checks are present
:return: list of check instances
"""
_set_logging(level=logging_level)
logger.debug("Finding checks started.")
return _get_checks(
target_type=target_type,
tags=tags,
ruleset_name=ruleset_name,
ruleset_file=ruleset_file,
ruleset=ruleset,
checks_paths=checks_paths,
skips=skips,
)
|
python
|
def get_checks(
target_type=None,
tags=None,
ruleset_name=None,
ruleset_file=None,
ruleset=None,
logging_level=logging.WARNING,
checks_paths=None,
skips=None,
):
"""
Get the sanity checks for the target.
:param skips: name of checks to skip
:param target_type: TargetType enum
:param tags: list of str (if not None, the checks will be filtered by tags.)
:param ruleset_name: str (e.g. fedora; if None, default would be used)
:param ruleset_file: fileobj instance holding ruleset configuration
:param ruleset: dict, content of a ruleset file
:param logging_level: logging level (default logging.WARNING)
:param checks_paths: list of str, directories where the checks are present
:return: list of check instances
"""
_set_logging(level=logging_level)
logger.debug("Finding checks started.")
return _get_checks(
target_type=target_type,
tags=tags,
ruleset_name=ruleset_name,
ruleset_file=ruleset_file,
ruleset=ruleset,
checks_paths=checks_paths,
skips=skips,
)
|
[
"def",
"get_checks",
"(",
"target_type",
"=",
"None",
",",
"tags",
"=",
"None",
",",
"ruleset_name",
"=",
"None",
",",
"ruleset_file",
"=",
"None",
",",
"ruleset",
"=",
"None",
",",
"logging_level",
"=",
"logging",
".",
"WARNING",
",",
"checks_paths",
"=",
"None",
",",
"skips",
"=",
"None",
",",
")",
":",
"_set_logging",
"(",
"level",
"=",
"logging_level",
")",
"logger",
".",
"debug",
"(",
"\"Finding checks started.\"",
")",
"return",
"_get_checks",
"(",
"target_type",
"=",
"target_type",
",",
"tags",
"=",
"tags",
",",
"ruleset_name",
"=",
"ruleset_name",
",",
"ruleset_file",
"=",
"ruleset_file",
",",
"ruleset",
"=",
"ruleset",
",",
"checks_paths",
"=",
"checks_paths",
",",
"skips",
"=",
"skips",
",",
")"
] |
Get the sanity checks for the target.
:param skips: name of checks to skip
:param target_type: TargetType enum
:param tags: list of str (if not None, the checks will be filtered by tags.)
:param ruleset_name: str (e.g. fedora; if None, default would be used)
:param ruleset_file: fileobj instance holding ruleset configuration
:param ruleset: dict, content of a ruleset file
:param logging_level: logging level (default logging.WARNING)
:param checks_paths: list of str, directories where the checks are present
:return: list of check instances
|
[
"Get",
"the",
"sanity",
"checks",
"for",
"the",
"target",
"."
] |
00bb80e6e91522e15361935f813e8cf13d7e76dc
|
https://github.com/user-cont/colin/blob/00bb80e6e91522e15361935f813e8cf13d7e76dc/colin/core/colin.py#L81-L114
|
train
|
user-cont/colin
|
colin/core/colin.py
|
_set_logging
|
def _set_logging(
logger_name="colin",
level=logging.INFO,
handler_class=logging.StreamHandler,
handler_kwargs=None,
format='%(asctime)s.%(msecs).03d %(filename)-17s %(levelname)-6s %(message)s',
date_format='%H:%M:%S'):
"""
Set personal logger for this library.
:param logger_name: str, name of the logger
:param level: int, see logging.{DEBUG,INFO,ERROR,...}: level of logger and handler
:param handler_class: logging.Handler instance, default is StreamHandler (/dev/stderr)
:param handler_kwargs: dict, keyword arguments to handler's constructor
:param format: str, formatting style
:param date_format: str, date style in the logs
"""
if level != logging.NOTSET:
logger = logging.getLogger(logger_name)
logger.setLevel(level)
# do not readd handlers if they are already present
if not [x for x in logger.handlers if isinstance(x, handler_class)]:
handler_kwargs = handler_kwargs or {}
handler = handler_class(**handler_kwargs)
handler.setLevel(level)
formatter = logging.Formatter(format, date_format)
handler.setFormatter(formatter)
logger.addHandler(handler)
|
python
|
def _set_logging(
logger_name="colin",
level=logging.INFO,
handler_class=logging.StreamHandler,
handler_kwargs=None,
format='%(asctime)s.%(msecs).03d %(filename)-17s %(levelname)-6s %(message)s',
date_format='%H:%M:%S'):
"""
Set personal logger for this library.
:param logger_name: str, name of the logger
:param level: int, see logging.{DEBUG,INFO,ERROR,...}: level of logger and handler
:param handler_class: logging.Handler instance, default is StreamHandler (/dev/stderr)
:param handler_kwargs: dict, keyword arguments to handler's constructor
:param format: str, formatting style
:param date_format: str, date style in the logs
"""
if level != logging.NOTSET:
logger = logging.getLogger(logger_name)
logger.setLevel(level)
# do not readd handlers if they are already present
if not [x for x in logger.handlers if isinstance(x, handler_class)]:
handler_kwargs = handler_kwargs or {}
handler = handler_class(**handler_kwargs)
handler.setLevel(level)
formatter = logging.Formatter(format, date_format)
handler.setFormatter(formatter)
logger.addHandler(handler)
|
[
"def",
"_set_logging",
"(",
"logger_name",
"=",
"\"colin\"",
",",
"level",
"=",
"logging",
".",
"INFO",
",",
"handler_class",
"=",
"logging",
".",
"StreamHandler",
",",
"handler_kwargs",
"=",
"None",
",",
"format",
"=",
"'%(asctime)s.%(msecs).03d %(filename)-17s %(levelname)-6s %(message)s'",
",",
"date_format",
"=",
"'%H:%M:%S'",
")",
":",
"if",
"level",
"!=",
"logging",
".",
"NOTSET",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"logger_name",
")",
"logger",
".",
"setLevel",
"(",
"level",
")",
"# do not readd handlers if they are already present",
"if",
"not",
"[",
"x",
"for",
"x",
"in",
"logger",
".",
"handlers",
"if",
"isinstance",
"(",
"x",
",",
"handler_class",
")",
"]",
":",
"handler_kwargs",
"=",
"handler_kwargs",
"or",
"{",
"}",
"handler",
"=",
"handler_class",
"(",
"*",
"*",
"handler_kwargs",
")",
"handler",
".",
"setLevel",
"(",
"level",
")",
"formatter",
"=",
"logging",
".",
"Formatter",
"(",
"format",
",",
"date_format",
")",
"handler",
".",
"setFormatter",
"(",
"formatter",
")",
"logger",
".",
"addHandler",
"(",
"handler",
")"
] |
Set personal logger for this library.
:param logger_name: str, name of the logger
:param level: int, see logging.{DEBUG,INFO,ERROR,...}: level of logger and handler
:param handler_class: logging.Handler instance, default is StreamHandler (/dev/stderr)
:param handler_kwargs: dict, keyword arguments to handler's constructor
:param format: str, formatting style
:param date_format: str, date style in the logs
|
[
"Set",
"personal",
"logger",
"for",
"this",
"library",
"."
] |
00bb80e6e91522e15361935f813e8cf13d7e76dc
|
https://github.com/user-cont/colin/blob/00bb80e6e91522e15361935f813e8cf13d7e76dc/colin/core/colin.py#L135-L164
|
train
|
user-cont/colin
|
colin/core/checks/check_utils.py
|
check_label
|
def check_label(labels, required, value_regex, target_labels):
"""
Check if the label is required and match the regex
:param labels: [str]
:param required: bool (if the presence means pass or not)
:param value_regex: str (using search method)
:param target_labels: [str]
:return: bool (required==True: True if the label is present and match the regex if specified)
(required==False: True if the label is not present)
"""
present = target_labels is not None and not set(labels).isdisjoint(set(target_labels))
if present:
if required and not value_regex:
return True
elif value_regex:
pattern = re.compile(value_regex)
present_labels = set(labels) & set(target_labels)
for l in present_labels:
if not bool(pattern.search(target_labels[l])):
return False
return True
else:
return False
else:
return not required
|
python
|
def check_label(labels, required, value_regex, target_labels):
"""
Check if the label is required and match the regex
:param labels: [str]
:param required: bool (if the presence means pass or not)
:param value_regex: str (using search method)
:param target_labels: [str]
:return: bool (required==True: True if the label is present and match the regex if specified)
(required==False: True if the label is not present)
"""
present = target_labels is not None and not set(labels).isdisjoint(set(target_labels))
if present:
if required and not value_regex:
return True
elif value_regex:
pattern = re.compile(value_regex)
present_labels = set(labels) & set(target_labels)
for l in present_labels:
if not bool(pattern.search(target_labels[l])):
return False
return True
else:
return False
else:
return not required
|
[
"def",
"check_label",
"(",
"labels",
",",
"required",
",",
"value_regex",
",",
"target_labels",
")",
":",
"present",
"=",
"target_labels",
"is",
"not",
"None",
"and",
"not",
"set",
"(",
"labels",
")",
".",
"isdisjoint",
"(",
"set",
"(",
"target_labels",
")",
")",
"if",
"present",
":",
"if",
"required",
"and",
"not",
"value_regex",
":",
"return",
"True",
"elif",
"value_regex",
":",
"pattern",
"=",
"re",
".",
"compile",
"(",
"value_regex",
")",
"present_labels",
"=",
"set",
"(",
"labels",
")",
"&",
"set",
"(",
"target_labels",
")",
"for",
"l",
"in",
"present_labels",
":",
"if",
"not",
"bool",
"(",
"pattern",
".",
"search",
"(",
"target_labels",
"[",
"l",
"]",
")",
")",
":",
"return",
"False",
"return",
"True",
"else",
":",
"return",
"False",
"else",
":",
"return",
"not",
"required"
] |
Check if the label is required and match the regex
:param labels: [str]
:param required: bool (if the presence means pass or not)
:param value_regex: str (using search method)
:param target_labels: [str]
:return: bool (required==True: True if the label is present and match the regex if specified)
(required==False: True if the label is not present)
|
[
"Check",
"if",
"the",
"label",
"is",
"required",
"and",
"match",
"the",
"regex"
] |
00bb80e6e91522e15361935f813e8cf13d7e76dc
|
https://github.com/user-cont/colin/blob/00bb80e6e91522e15361935f813e8cf13d7e76dc/colin/core/checks/check_utils.py#L7-L34
|
train
|
user-cont/colin
|
colin/core/checks/abstract_check.py
|
AbstractCheck.json
|
def json(self):
"""
Get json representation of the check
:return: dict (str -> obj)
"""
return {
'name': self.name,
'message': self.message,
'description': self.description,
'reference_url': self.reference_url,
'tags': self.tags,
}
|
python
|
def json(self):
"""
Get json representation of the check
:return: dict (str -> obj)
"""
return {
'name': self.name,
'message': self.message,
'description': self.description,
'reference_url': self.reference_url,
'tags': self.tags,
}
|
[
"def",
"json",
"(",
"self",
")",
":",
"return",
"{",
"'name'",
":",
"self",
".",
"name",
",",
"'message'",
":",
"self",
".",
"message",
",",
"'description'",
":",
"self",
".",
"description",
",",
"'reference_url'",
":",
"self",
".",
"reference_url",
",",
"'tags'",
":",
"self",
".",
"tags",
",",
"}"
] |
Get json representation of the check
:return: dict (str -> obj)
|
[
"Get",
"json",
"representation",
"of",
"the",
"check"
] |
00bb80e6e91522e15361935f813e8cf13d7e76dc
|
https://github.com/user-cont/colin/blob/00bb80e6e91522e15361935f813e8cf13d7e76dc/colin/core/checks/abstract_check.py#L47-L59
|
train
|
user-cont/colin
|
colin/core/ruleset/ruleset.py
|
get_checks_paths
|
def get_checks_paths(checks_paths=None):
"""
Get path to checks.
:param checks_paths: list of str, directories where the checks are present
:return: list of str (absolute path of directory with checks)
"""
p = os.path.join(__file__, os.pardir, os.pardir, os.pardir, "checks")
p = os.path.abspath(p)
# let's utilize the default upstream checks always
if checks_paths:
p += [os.path.abspath(x) for x in checks_paths]
return [p]
|
python
|
def get_checks_paths(checks_paths=None):
"""
Get path to checks.
:param checks_paths: list of str, directories where the checks are present
:return: list of str (absolute path of directory with checks)
"""
p = os.path.join(__file__, os.pardir, os.pardir, os.pardir, "checks")
p = os.path.abspath(p)
# let's utilize the default upstream checks always
if checks_paths:
p += [os.path.abspath(x) for x in checks_paths]
return [p]
|
[
"def",
"get_checks_paths",
"(",
"checks_paths",
"=",
"None",
")",
":",
"p",
"=",
"os",
".",
"path",
".",
"join",
"(",
"__file__",
",",
"os",
".",
"pardir",
",",
"os",
".",
"pardir",
",",
"os",
".",
"pardir",
",",
"\"checks\"",
")",
"p",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"p",
")",
"# let's utilize the default upstream checks always",
"if",
"checks_paths",
":",
"p",
"+=",
"[",
"os",
".",
"path",
".",
"abspath",
"(",
"x",
")",
"for",
"x",
"in",
"checks_paths",
"]",
"return",
"[",
"p",
"]"
] |
Get path to checks.
:param checks_paths: list of str, directories where the checks are present
:return: list of str (absolute path of directory with checks)
|
[
"Get",
"path",
"to",
"checks",
"."
] |
00bb80e6e91522e15361935f813e8cf13d7e76dc
|
https://github.com/user-cont/colin/blob/00bb80e6e91522e15361935f813e8cf13d7e76dc/colin/core/ruleset/ruleset.py#L124-L136
|
train
|
user-cont/colin
|
colin/core/ruleset/ruleset.py
|
get_ruleset_file
|
def get_ruleset_file(ruleset=None):
"""
Get the ruleset file from name
:param ruleset: str
:return: str
"""
ruleset = ruleset or "default"
ruleset_dirs = get_ruleset_dirs()
for ruleset_directory in ruleset_dirs:
possible_ruleset_files = [os.path.join(ruleset_directory, ruleset + ext) for ext in EXTS]
for ruleset_file in possible_ruleset_files:
if os.path.isfile(ruleset_file):
logger.debug("Ruleset file '{}' found.".format(ruleset_file))
return ruleset_file
logger.warning("Ruleset with the name '{}' cannot be found at '{}'."
.format(ruleset, ruleset_dirs))
raise ColinRulesetException("Ruleset with the name '{}' cannot be found.".format(ruleset))
|
python
|
def get_ruleset_file(ruleset=None):
"""
Get the ruleset file from name
:param ruleset: str
:return: str
"""
ruleset = ruleset or "default"
ruleset_dirs = get_ruleset_dirs()
for ruleset_directory in ruleset_dirs:
possible_ruleset_files = [os.path.join(ruleset_directory, ruleset + ext) for ext in EXTS]
for ruleset_file in possible_ruleset_files:
if os.path.isfile(ruleset_file):
logger.debug("Ruleset file '{}' found.".format(ruleset_file))
return ruleset_file
logger.warning("Ruleset with the name '{}' cannot be found at '{}'."
.format(ruleset, ruleset_dirs))
raise ColinRulesetException("Ruleset with the name '{}' cannot be found.".format(ruleset))
|
[
"def",
"get_ruleset_file",
"(",
"ruleset",
"=",
"None",
")",
":",
"ruleset",
"=",
"ruleset",
"or",
"\"default\"",
"ruleset_dirs",
"=",
"get_ruleset_dirs",
"(",
")",
"for",
"ruleset_directory",
"in",
"ruleset_dirs",
":",
"possible_ruleset_files",
"=",
"[",
"os",
".",
"path",
".",
"join",
"(",
"ruleset_directory",
",",
"ruleset",
"+",
"ext",
")",
"for",
"ext",
"in",
"EXTS",
"]",
"for",
"ruleset_file",
"in",
"possible_ruleset_files",
":",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"ruleset_file",
")",
":",
"logger",
".",
"debug",
"(",
"\"Ruleset file '{}' found.\"",
".",
"format",
"(",
"ruleset_file",
")",
")",
"return",
"ruleset_file",
"logger",
".",
"warning",
"(",
"\"Ruleset with the name '{}' cannot be found at '{}'.\"",
".",
"format",
"(",
"ruleset",
",",
"ruleset_dirs",
")",
")",
"raise",
"ColinRulesetException",
"(",
"\"Ruleset with the name '{}' cannot be found.\"",
".",
"format",
"(",
"ruleset",
")",
")"
] |
Get the ruleset file from name
:param ruleset: str
:return: str
|
[
"Get",
"the",
"ruleset",
"file",
"from",
"name"
] |
00bb80e6e91522e15361935f813e8cf13d7e76dc
|
https://github.com/user-cont/colin/blob/00bb80e6e91522e15361935f813e8cf13d7e76dc/colin/core/ruleset/ruleset.py#L139-L159
|
train
|
user-cont/colin
|
colin/core/ruleset/ruleset.py
|
get_rulesets
|
def get_rulesets():
""""
Get available rulesets.
"""
rulesets_dirs = get_ruleset_dirs()
ruleset_files = []
for rulesets_dir in rulesets_dirs:
for f in os.listdir(rulesets_dir):
for ext in EXTS:
file_path = os.path.join(rulesets_dir, f)
if os.path.isfile(file_path) and f.lower().endswith(ext):
ruleset_files.append((f[:-len(ext)], file_path))
return ruleset_files
|
python
|
def get_rulesets():
""""
Get available rulesets.
"""
rulesets_dirs = get_ruleset_dirs()
ruleset_files = []
for rulesets_dir in rulesets_dirs:
for f in os.listdir(rulesets_dir):
for ext in EXTS:
file_path = os.path.join(rulesets_dir, f)
if os.path.isfile(file_path) and f.lower().endswith(ext):
ruleset_files.append((f[:-len(ext)], file_path))
return ruleset_files
|
[
"def",
"get_rulesets",
"(",
")",
":",
"rulesets_dirs",
"=",
"get_ruleset_dirs",
"(",
")",
"ruleset_files",
"=",
"[",
"]",
"for",
"rulesets_dir",
"in",
"rulesets_dirs",
":",
"for",
"f",
"in",
"os",
".",
"listdir",
"(",
"rulesets_dir",
")",
":",
"for",
"ext",
"in",
"EXTS",
":",
"file_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"rulesets_dir",
",",
"f",
")",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"file_path",
")",
"and",
"f",
".",
"lower",
"(",
")",
".",
"endswith",
"(",
"ext",
")",
":",
"ruleset_files",
".",
"append",
"(",
"(",
"f",
"[",
":",
"-",
"len",
"(",
"ext",
")",
"]",
",",
"file_path",
")",
")",
"return",
"ruleset_files"
] |
Get available rulesets.
|
[
"Get",
"available",
"rulesets",
"."
] |
00bb80e6e91522e15361935f813e8cf13d7e76dc
|
https://github.com/user-cont/colin/blob/00bb80e6e91522e15361935f813e8cf13d7e76dc/colin/core/ruleset/ruleset.py#L205-L217
|
train
|
user-cont/colin
|
colin/utils/cmd_tools.py
|
get_rpm_version
|
def get_rpm_version(package_name):
"""Get a version of the package with 'rpm -q' command."""
version_result = subprocess.run(["rpm", "-q", package_name],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
if version_result.returncode == 0:
return version_result.stdout.decode().rstrip()
else:
return None
|
python
|
def get_rpm_version(package_name):
"""Get a version of the package with 'rpm -q' command."""
version_result = subprocess.run(["rpm", "-q", package_name],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
if version_result.returncode == 0:
return version_result.stdout.decode().rstrip()
else:
return None
|
[
"def",
"get_rpm_version",
"(",
"package_name",
")",
":",
"version_result",
"=",
"subprocess",
".",
"run",
"(",
"[",
"\"rpm\"",
",",
"\"-q\"",
",",
"package_name",
"]",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
",",
"stderr",
"=",
"subprocess",
".",
"PIPE",
")",
"if",
"version_result",
".",
"returncode",
"==",
"0",
":",
"return",
"version_result",
".",
"stdout",
".",
"decode",
"(",
")",
".",
"rstrip",
"(",
")",
"else",
":",
"return",
"None"
] |
Get a version of the package with 'rpm -q' command.
|
[
"Get",
"a",
"version",
"of",
"the",
"package",
"with",
"rpm",
"-",
"q",
"command",
"."
] |
00bb80e6e91522e15361935f813e8cf13d7e76dc
|
https://github.com/user-cont/colin/blob/00bb80e6e91522e15361935f813e8cf13d7e76dc/colin/utils/cmd_tools.py#L77-L85
|
train
|
user-cont/colin
|
colin/utils/cmd_tools.py
|
is_rpm_installed
|
def is_rpm_installed():
"""Tests if the rpm command is present."""
try:
version_result = subprocess.run(["rpm", "--usage"],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
rpm_installed = not version_result.returncode
except FileNotFoundError:
rpm_installed = False
return rpm_installed
|
python
|
def is_rpm_installed():
"""Tests if the rpm command is present."""
try:
version_result = subprocess.run(["rpm", "--usage"],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
rpm_installed = not version_result.returncode
except FileNotFoundError:
rpm_installed = False
return rpm_installed
|
[
"def",
"is_rpm_installed",
"(",
")",
":",
"try",
":",
"version_result",
"=",
"subprocess",
".",
"run",
"(",
"[",
"\"rpm\"",
",",
"\"--usage\"",
"]",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
",",
"stderr",
"=",
"subprocess",
".",
"PIPE",
")",
"rpm_installed",
"=",
"not",
"version_result",
".",
"returncode",
"except",
"FileNotFoundError",
":",
"rpm_installed",
"=",
"False",
"return",
"rpm_installed"
] |
Tests if the rpm command is present.
|
[
"Tests",
"if",
"the",
"rpm",
"command",
"is",
"present",
"."
] |
00bb80e6e91522e15361935f813e8cf13d7e76dc
|
https://github.com/user-cont/colin/blob/00bb80e6e91522e15361935f813e8cf13d7e76dc/colin/utils/cmd_tools.py#L88-L97
|
train
|
user-cont/colin
|
colin/utils/cmd_tools.py
|
exit_after
|
def exit_after(s):
"""
Use as decorator to exit process if
function takes longer than s seconds.
Direct call is available via exit_after(TIMEOUT_IN_S)(fce)(args).
Inspired by https://stackoverflow.com/a/31667005
"""
def outer(fn):
def inner(*args, **kwargs):
timer = threading.Timer(s, thread.interrupt_main)
timer.start()
try:
result = fn(*args, **kwargs)
except KeyboardInterrupt:
raise TimeoutError("Function '{}' hit the timeout ({}s).".format(fn.__name__, s))
finally:
timer.cancel()
return result
return inner
return outer
|
python
|
def exit_after(s):
"""
Use as decorator to exit process if
function takes longer than s seconds.
Direct call is available via exit_after(TIMEOUT_IN_S)(fce)(args).
Inspired by https://stackoverflow.com/a/31667005
"""
def outer(fn):
def inner(*args, **kwargs):
timer = threading.Timer(s, thread.interrupt_main)
timer.start()
try:
result = fn(*args, **kwargs)
except KeyboardInterrupt:
raise TimeoutError("Function '{}' hit the timeout ({}s).".format(fn.__name__, s))
finally:
timer.cancel()
return result
return inner
return outer
|
[
"def",
"exit_after",
"(",
"s",
")",
":",
"def",
"outer",
"(",
"fn",
")",
":",
"def",
"inner",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"timer",
"=",
"threading",
".",
"Timer",
"(",
"s",
",",
"thread",
".",
"interrupt_main",
")",
"timer",
".",
"start",
"(",
")",
"try",
":",
"result",
"=",
"fn",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"except",
"KeyboardInterrupt",
":",
"raise",
"TimeoutError",
"(",
"\"Function '{}' hit the timeout ({}s).\"",
".",
"format",
"(",
"fn",
".",
"__name__",
",",
"s",
")",
")",
"finally",
":",
"timer",
".",
"cancel",
"(",
")",
"return",
"result",
"return",
"inner",
"return",
"outer"
] |
Use as decorator to exit process if
function takes longer than s seconds.
Direct call is available via exit_after(TIMEOUT_IN_S)(fce)(args).
Inspired by https://stackoverflow.com/a/31667005
|
[
"Use",
"as",
"decorator",
"to",
"exit",
"process",
"if",
"function",
"takes",
"longer",
"than",
"s",
"seconds",
"."
] |
00bb80e6e91522e15361935f813e8cf13d7e76dc
|
https://github.com/user-cont/colin/blob/00bb80e6e91522e15361935f813e8cf13d7e76dc/colin/utils/cmd_tools.py#L100-L124
|
train
|
user-cont/colin
|
colin/utils/cmd_tools.py
|
retry
|
def retry(retry_count=5, delay=2):
"""
Use as decorator to retry functions few times with delays
Exception will be raised if last call fails
:param retry_count: int could of retries in case of failures. It must be
a positive number
:param delay: int delay between retries
"""
if retry_count <= 0:
raise ValueError("retry_count have to be positive")
def decorator(f):
@functools.wraps(f)
def wrapper(*args, **kwargs):
for i in range(retry_count, 0, -1):
try:
return f(*args, **kwargs)
except Exception:
if i <= 1:
raise
time.sleep(delay)
return wrapper
return decorator
|
python
|
def retry(retry_count=5, delay=2):
"""
Use as decorator to retry functions few times with delays
Exception will be raised if last call fails
:param retry_count: int could of retries in case of failures. It must be
a positive number
:param delay: int delay between retries
"""
if retry_count <= 0:
raise ValueError("retry_count have to be positive")
def decorator(f):
@functools.wraps(f)
def wrapper(*args, **kwargs):
for i in range(retry_count, 0, -1):
try:
return f(*args, **kwargs)
except Exception:
if i <= 1:
raise
time.sleep(delay)
return wrapper
return decorator
|
[
"def",
"retry",
"(",
"retry_count",
"=",
"5",
",",
"delay",
"=",
"2",
")",
":",
"if",
"retry_count",
"<=",
"0",
":",
"raise",
"ValueError",
"(",
"\"retry_count have to be positive\"",
")",
"def",
"decorator",
"(",
"f",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"f",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"i",
"in",
"range",
"(",
"retry_count",
",",
"0",
",",
"-",
"1",
")",
":",
"try",
":",
"return",
"f",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"except",
"Exception",
":",
"if",
"i",
"<=",
"1",
":",
"raise",
"time",
".",
"sleep",
"(",
"delay",
")",
"return",
"wrapper",
"return",
"decorator"
] |
Use as decorator to retry functions few times with delays
Exception will be raised if last call fails
:param retry_count: int could of retries in case of failures. It must be
a positive number
:param delay: int delay between retries
|
[
"Use",
"as",
"decorator",
"to",
"retry",
"functions",
"few",
"times",
"with",
"delays"
] |
00bb80e6e91522e15361935f813e8cf13d7e76dc
|
https://github.com/user-cont/colin/blob/00bb80e6e91522e15361935f813e8cf13d7e76dc/colin/utils/cmd_tools.py#L127-L151
|
train
|
user-cont/colin
|
colin/utils/cont.py
|
ImageName.parse
|
def parse(cls, image_name):
"""
Get the instance of ImageName from the string representation.
:param image_name: str (any possible form of image name)
:return: ImageName instance
"""
result = cls()
# registry.org/namespace/repo:tag
s = image_name.split('/', 2)
if len(s) == 2:
if '.' in s[0] or ':' in s[0]:
result.registry = s[0]
else:
result.namespace = s[0]
elif len(s) == 3:
result.registry = s[0]
result.namespace = s[1]
result.repository = s[-1]
try:
result.repository, result.digest = result.repository.rsplit("@", 1)
except ValueError:
try:
result.repository, result.tag = result.repository.rsplit(":", 1)
except ValueError:
result.tag = "latest"
return result
|
python
|
def parse(cls, image_name):
"""
Get the instance of ImageName from the string representation.
:param image_name: str (any possible form of image name)
:return: ImageName instance
"""
result = cls()
# registry.org/namespace/repo:tag
s = image_name.split('/', 2)
if len(s) == 2:
if '.' in s[0] or ':' in s[0]:
result.registry = s[0]
else:
result.namespace = s[0]
elif len(s) == 3:
result.registry = s[0]
result.namespace = s[1]
result.repository = s[-1]
try:
result.repository, result.digest = result.repository.rsplit("@", 1)
except ValueError:
try:
result.repository, result.tag = result.repository.rsplit(":", 1)
except ValueError:
result.tag = "latest"
return result
|
[
"def",
"parse",
"(",
"cls",
",",
"image_name",
")",
":",
"result",
"=",
"cls",
"(",
")",
"# registry.org/namespace/repo:tag",
"s",
"=",
"image_name",
".",
"split",
"(",
"'/'",
",",
"2",
")",
"if",
"len",
"(",
"s",
")",
"==",
"2",
":",
"if",
"'.'",
"in",
"s",
"[",
"0",
"]",
"or",
"':'",
"in",
"s",
"[",
"0",
"]",
":",
"result",
".",
"registry",
"=",
"s",
"[",
"0",
"]",
"else",
":",
"result",
".",
"namespace",
"=",
"s",
"[",
"0",
"]",
"elif",
"len",
"(",
"s",
")",
"==",
"3",
":",
"result",
".",
"registry",
"=",
"s",
"[",
"0",
"]",
"result",
".",
"namespace",
"=",
"s",
"[",
"1",
"]",
"result",
".",
"repository",
"=",
"s",
"[",
"-",
"1",
"]",
"try",
":",
"result",
".",
"repository",
",",
"result",
".",
"digest",
"=",
"result",
".",
"repository",
".",
"rsplit",
"(",
"\"@\"",
",",
"1",
")",
"except",
"ValueError",
":",
"try",
":",
"result",
".",
"repository",
",",
"result",
".",
"tag",
"=",
"result",
".",
"repository",
".",
"rsplit",
"(",
"\":\"",
",",
"1",
")",
"except",
"ValueError",
":",
"result",
".",
"tag",
"=",
"\"latest\"",
"return",
"result"
] |
Get the instance of ImageName from the string representation.
:param image_name: str (any possible form of image name)
:return: ImageName instance
|
[
"Get",
"the",
"instance",
"of",
"ImageName",
"from",
"the",
"string",
"representation",
"."
] |
00bb80e6e91522e15361935f813e8cf13d7e76dc
|
https://github.com/user-cont/colin/blob/00bb80e6e91522e15361935f813e8cf13d7e76dc/colin/utils/cont.py#L22-L52
|
train
|
user-cont/colin
|
colin/core/ruleset/loader.py
|
CheckStruct.other_attributes
|
def other_attributes(self):
""" return dict with all other data except for the described above"""
return {k: v for k, v in self.c.items() if
k not in ["name", "names", "tags", "additional_tags", "usable_targets"]}
|
python
|
def other_attributes(self):
""" return dict with all other data except for the described above"""
return {k: v for k, v in self.c.items() if
k not in ["name", "names", "tags", "additional_tags", "usable_targets"]}
|
[
"def",
"other_attributes",
"(",
"self",
")",
":",
"return",
"{",
"k",
":",
"v",
"for",
"k",
",",
"v",
"in",
"self",
".",
"c",
".",
"items",
"(",
")",
"if",
"k",
"not",
"in",
"[",
"\"name\"",
",",
"\"names\"",
",",
"\"tags\"",
",",
"\"additional_tags\"",
",",
"\"usable_targets\"",
"]",
"}"
] |
return dict with all other data except for the described above
|
[
"return",
"dict",
"with",
"all",
"other",
"data",
"except",
"for",
"the",
"described",
"above"
] |
00bb80e6e91522e15361935f813e8cf13d7e76dc
|
https://github.com/user-cont/colin/blob/00bb80e6e91522e15361935f813e8cf13d7e76dc/colin/core/ruleset/loader.py#L118-L121
|
train
|
user-cont/colin
|
colin/core/loader.py
|
should_we_load
|
def should_we_load(kls):
""" should we load this class as a check? """
# we don't load abstract classes
if kls.__name__.endswith("AbstractCheck"):
return False
# and we only load checks
if not kls.__name__.endswith("Check"):
return False
mro = kls.__mro__
# and the class needs to be a child of AbstractCheck
for m in mro:
if m.__name__ == "AbstractCheck":
return True
return False
|
python
|
def should_we_load(kls):
""" should we load this class as a check? """
# we don't load abstract classes
if kls.__name__.endswith("AbstractCheck"):
return False
# and we only load checks
if not kls.__name__.endswith("Check"):
return False
mro = kls.__mro__
# and the class needs to be a child of AbstractCheck
for m in mro:
if m.__name__ == "AbstractCheck":
return True
return False
|
[
"def",
"should_we_load",
"(",
"kls",
")",
":",
"# we don't load abstract classes",
"if",
"kls",
".",
"__name__",
".",
"endswith",
"(",
"\"AbstractCheck\"",
")",
":",
"return",
"False",
"# and we only load checks",
"if",
"not",
"kls",
".",
"__name__",
".",
"endswith",
"(",
"\"Check\"",
")",
":",
"return",
"False",
"mro",
"=",
"kls",
".",
"__mro__",
"# and the class needs to be a child of AbstractCheck",
"for",
"m",
"in",
"mro",
":",
"if",
"m",
".",
"__name__",
"==",
"\"AbstractCheck\"",
":",
"return",
"True",
"return",
"False"
] |
should we load this class as a check?
|
[
"should",
"we",
"load",
"this",
"class",
"as",
"a",
"check?"
] |
00bb80e6e91522e15361935f813e8cf13d7e76dc
|
https://github.com/user-cont/colin/blob/00bb80e6e91522e15361935f813e8cf13d7e76dc/colin/core/loader.py#L54-L67
|
train
|
user-cont/colin
|
colin/core/loader.py
|
CheckLoader.obtain_check_classes
|
def obtain_check_classes(self):
""" find children of AbstractCheck class and return them as a list """
check_classes = set()
for path in self.paths:
for root, _, files in os.walk(path):
for fi in files:
if not fi.endswith(".py"):
continue
path = os.path.join(root, fi)
check_classes = check_classes.union(set(
load_check_classes_from_file(path)))
return list(check_classes)
|
python
|
def obtain_check_classes(self):
""" find children of AbstractCheck class and return them as a list """
check_classes = set()
for path in self.paths:
for root, _, files in os.walk(path):
for fi in files:
if not fi.endswith(".py"):
continue
path = os.path.join(root, fi)
check_classes = check_classes.union(set(
load_check_classes_from_file(path)))
return list(check_classes)
|
[
"def",
"obtain_check_classes",
"(",
"self",
")",
":",
"check_classes",
"=",
"set",
"(",
")",
"for",
"path",
"in",
"self",
".",
"paths",
":",
"for",
"root",
",",
"_",
",",
"files",
"in",
"os",
".",
"walk",
"(",
"path",
")",
":",
"for",
"fi",
"in",
"files",
":",
"if",
"not",
"fi",
".",
"endswith",
"(",
"\".py\"",
")",
":",
"continue",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"root",
",",
"fi",
")",
"check_classes",
"=",
"check_classes",
".",
"union",
"(",
"set",
"(",
"load_check_classes_from_file",
"(",
"path",
")",
")",
")",
"return",
"list",
"(",
"check_classes",
")"
] |
find children of AbstractCheck class and return them as a list
|
[
"find",
"children",
"of",
"AbstractCheck",
"class",
"and",
"return",
"them",
"as",
"a",
"list"
] |
00bb80e6e91522e15361935f813e8cf13d7e76dc
|
https://github.com/user-cont/colin/blob/00bb80e6e91522e15361935f813e8cf13d7e76dc/colin/core/loader.py#L103-L114
|
train
|
user-cont/colin
|
colin/core/loader.py
|
CheckLoader.import_class
|
def import_class(self, import_name):
"""
import selected class
:param import_name, str, e.g. some.module.MyClass
:return the class
"""
module_name, class_name = import_name.rsplit(".", 1)
mod = import_module(module_name)
check_class = getattr(mod, class_name)
self.mapping[check_class.name] = check_class
logger.info("successfully loaded class %s", check_class)
return check_class
|
python
|
def import_class(self, import_name):
"""
import selected class
:param import_name, str, e.g. some.module.MyClass
:return the class
"""
module_name, class_name = import_name.rsplit(".", 1)
mod = import_module(module_name)
check_class = getattr(mod, class_name)
self.mapping[check_class.name] = check_class
logger.info("successfully loaded class %s", check_class)
return check_class
|
[
"def",
"import_class",
"(",
"self",
",",
"import_name",
")",
":",
"module_name",
",",
"class_name",
"=",
"import_name",
".",
"rsplit",
"(",
"\".\"",
",",
"1",
")",
"mod",
"=",
"import_module",
"(",
"module_name",
")",
"check_class",
"=",
"getattr",
"(",
"mod",
",",
"class_name",
")",
"self",
".",
"mapping",
"[",
"check_class",
".",
"name",
"]",
"=",
"check_class",
"logger",
".",
"info",
"(",
"\"successfully loaded class %s\"",
",",
"check_class",
")",
"return",
"check_class"
] |
import selected class
:param import_name, str, e.g. some.module.MyClass
:return the class
|
[
"import",
"selected",
"class"
] |
00bb80e6e91522e15361935f813e8cf13d7e76dc
|
https://github.com/user-cont/colin/blob/00bb80e6e91522e15361935f813e8cf13d7e76dc/colin/core/loader.py#L116-L128
|
train
|
user-cont/colin
|
colin/core/result.py
|
CheckResults._dict_of_results
|
def _dict_of_results(self):
"""
Get the dictionary representation of results
:return: dict (str -> dict (str -> str))
"""
result_json = {}
result_list = []
for r in self.results:
result_list.append({
'name': r.check_name,
'ok': r.ok,
'status': r.status,
'description': r.description,
'message': r.message,
'reference_url': r.reference_url,
'logs': r.logs,
})
result_json["checks"] = result_list
return result_json
|
python
|
def _dict_of_results(self):
"""
Get the dictionary representation of results
:return: dict (str -> dict (str -> str))
"""
result_json = {}
result_list = []
for r in self.results:
result_list.append({
'name': r.check_name,
'ok': r.ok,
'status': r.status,
'description': r.description,
'message': r.message,
'reference_url': r.reference_url,
'logs': r.logs,
})
result_json["checks"] = result_list
return result_json
|
[
"def",
"_dict_of_results",
"(",
"self",
")",
":",
"result_json",
"=",
"{",
"}",
"result_list",
"=",
"[",
"]",
"for",
"r",
"in",
"self",
".",
"results",
":",
"result_list",
".",
"append",
"(",
"{",
"'name'",
":",
"r",
".",
"check_name",
",",
"'ok'",
":",
"r",
".",
"ok",
",",
"'status'",
":",
"r",
".",
"status",
",",
"'description'",
":",
"r",
".",
"description",
",",
"'message'",
":",
"r",
".",
"message",
",",
"'reference_url'",
":",
"r",
".",
"reference_url",
",",
"'logs'",
":",
"r",
".",
"logs",
",",
"}",
")",
"result_json",
"[",
"\"checks\"",
"]",
"=",
"result_list",
"return",
"result_json"
] |
Get the dictionary representation of results
:return: dict (str -> dict (str -> str))
|
[
"Get",
"the",
"dictionary",
"representation",
"of",
"results"
] |
00bb80e6e91522e15361935f813e8cf13d7e76dc
|
https://github.com/user-cont/colin/blob/00bb80e6e91522e15361935f813e8cf13d7e76dc/colin/core/result.py#L64-L84
|
train
|
user-cont/colin
|
colin/core/result.py
|
CheckResults.statistics
|
def statistics(self):
"""
Get the dictionary with the count of the check-statuses
:return: dict(str -> int)
"""
result = {}
for r in self.results:
result.setdefault(r.status, 0)
result[r.status] += 1
return result
|
python
|
def statistics(self):
"""
Get the dictionary with the count of the check-statuses
:return: dict(str -> int)
"""
result = {}
for r in self.results:
result.setdefault(r.status, 0)
result[r.status] += 1
return result
|
[
"def",
"statistics",
"(",
"self",
")",
":",
"result",
"=",
"{",
"}",
"for",
"r",
"in",
"self",
".",
"results",
":",
"result",
".",
"setdefault",
"(",
"r",
".",
"status",
",",
"0",
")",
"result",
"[",
"r",
".",
"status",
"]",
"+=",
"1",
"return",
"result"
] |
Get the dictionary with the count of the check-statuses
:return: dict(str -> int)
|
[
"Get",
"the",
"dictionary",
"with",
"the",
"count",
"of",
"the",
"check",
"-",
"statuses"
] |
00bb80e6e91522e15361935f813e8cf13d7e76dc
|
https://github.com/user-cont/colin/blob/00bb80e6e91522e15361935f813e8cf13d7e76dc/colin/core/result.py#L101-L111
|
train
|
user-cont/colin
|
colin/core/result.py
|
CheckResults.generate_pretty_output
|
def generate_pretty_output(self, stat, verbose, output_function, logs=True):
"""
Send the formated to the provided function
:param stat: if True print stat instead of full output
:param verbose: bool
:param output_function: function to send output to
"""
has_check = False
for r in self.results:
has_check = True
if stat:
output_function(OUTPUT_CHARS[r.status],
fg=COLOURS[r.status],
nl=False)
else:
output_function(str(r), fg=COLOURS[r.status])
if verbose:
output_function(" -> {}\n"
" -> {}".format(r.description,
r.reference_url),
fg=COLOURS[r.status])
if logs and r.logs:
output_function(" -> logs:",
fg=COLOURS[r.status])
for l in r.logs:
output_function(" -> {}".format(l),
fg=COLOURS[r.status])
if not has_check:
output_function("No check found.")
elif stat and not verbose:
output_function("")
else:
output_function("")
for status, count in six.iteritems(self.statistics):
output_function("{}:{} ".format(status, count), nl=False)
output_function("")
|
python
|
def generate_pretty_output(self, stat, verbose, output_function, logs=True):
"""
Send the formated to the provided function
:param stat: if True print stat instead of full output
:param verbose: bool
:param output_function: function to send output to
"""
has_check = False
for r in self.results:
has_check = True
if stat:
output_function(OUTPUT_CHARS[r.status],
fg=COLOURS[r.status],
nl=False)
else:
output_function(str(r), fg=COLOURS[r.status])
if verbose:
output_function(" -> {}\n"
" -> {}".format(r.description,
r.reference_url),
fg=COLOURS[r.status])
if logs and r.logs:
output_function(" -> logs:",
fg=COLOURS[r.status])
for l in r.logs:
output_function(" -> {}".format(l),
fg=COLOURS[r.status])
if not has_check:
output_function("No check found.")
elif stat and not verbose:
output_function("")
else:
output_function("")
for status, count in six.iteritems(self.statistics):
output_function("{}:{} ".format(status, count), nl=False)
output_function("")
|
[
"def",
"generate_pretty_output",
"(",
"self",
",",
"stat",
",",
"verbose",
",",
"output_function",
",",
"logs",
"=",
"True",
")",
":",
"has_check",
"=",
"False",
"for",
"r",
"in",
"self",
".",
"results",
":",
"has_check",
"=",
"True",
"if",
"stat",
":",
"output_function",
"(",
"OUTPUT_CHARS",
"[",
"r",
".",
"status",
"]",
",",
"fg",
"=",
"COLOURS",
"[",
"r",
".",
"status",
"]",
",",
"nl",
"=",
"False",
")",
"else",
":",
"output_function",
"(",
"str",
"(",
"r",
")",
",",
"fg",
"=",
"COLOURS",
"[",
"r",
".",
"status",
"]",
")",
"if",
"verbose",
":",
"output_function",
"(",
"\" -> {}\\n\"",
"\" -> {}\"",
".",
"format",
"(",
"r",
".",
"description",
",",
"r",
".",
"reference_url",
")",
",",
"fg",
"=",
"COLOURS",
"[",
"r",
".",
"status",
"]",
")",
"if",
"logs",
"and",
"r",
".",
"logs",
":",
"output_function",
"(",
"\" -> logs:\"",
",",
"fg",
"=",
"COLOURS",
"[",
"r",
".",
"status",
"]",
")",
"for",
"l",
"in",
"r",
".",
"logs",
":",
"output_function",
"(",
"\" -> {}\"",
".",
"format",
"(",
"l",
")",
",",
"fg",
"=",
"COLOURS",
"[",
"r",
".",
"status",
"]",
")",
"if",
"not",
"has_check",
":",
"output_function",
"(",
"\"No check found.\"",
")",
"elif",
"stat",
"and",
"not",
"verbose",
":",
"output_function",
"(",
"\"\"",
")",
"else",
":",
"output_function",
"(",
"\"\"",
")",
"for",
"status",
",",
"count",
"in",
"six",
".",
"iteritems",
"(",
"self",
".",
"statistics",
")",
":",
"output_function",
"(",
"\"{}:{} \"",
".",
"format",
"(",
"status",
",",
"count",
")",
",",
"nl",
"=",
"False",
")",
"output_function",
"(",
"\"\"",
")"
] |
Send the formated to the provided function
:param stat: if True print stat instead of full output
:param verbose: bool
:param output_function: function to send output to
|
[
"Send",
"the",
"formated",
"to",
"the",
"provided",
"function"
] |
00bb80e6e91522e15361935f813e8cf13d7e76dc
|
https://github.com/user-cont/colin/blob/00bb80e6e91522e15361935f813e8cf13d7e76dc/colin/core/result.py#L133-L171
|
train
|
user-cont/colin
|
colin/core/result.py
|
CheckResults.get_pretty_string
|
def get_pretty_string(self, stat, verbose):
"""
Pretty string representation of the results
:param stat: bool
:param verbose: bool
:return: str
"""
pretty_output = _PrettyOutputToStr()
self.generate_pretty_output(stat=stat,
verbose=verbose,
output_function=pretty_output.save_output)
return pretty_output.result
|
python
|
def get_pretty_string(self, stat, verbose):
"""
Pretty string representation of the results
:param stat: bool
:param verbose: bool
:return: str
"""
pretty_output = _PrettyOutputToStr()
self.generate_pretty_output(stat=stat,
verbose=verbose,
output_function=pretty_output.save_output)
return pretty_output.result
|
[
"def",
"get_pretty_string",
"(",
"self",
",",
"stat",
",",
"verbose",
")",
":",
"pretty_output",
"=",
"_PrettyOutputToStr",
"(",
")",
"self",
".",
"generate_pretty_output",
"(",
"stat",
"=",
"stat",
",",
"verbose",
"=",
"verbose",
",",
"output_function",
"=",
"pretty_output",
".",
"save_output",
")",
"return",
"pretty_output",
".",
"result"
] |
Pretty string representation of the results
:param stat: bool
:param verbose: bool
:return: str
|
[
"Pretty",
"string",
"representation",
"of",
"the",
"results"
] |
00bb80e6e91522e15361935f813e8cf13d7e76dc
|
https://github.com/user-cont/colin/blob/00bb80e6e91522e15361935f813e8cf13d7e76dc/colin/core/result.py#L173-L185
|
train
|
user-cont/colin
|
colin/core/checks/fmf_check.py
|
receive_fmf_metadata
|
def receive_fmf_metadata(name, path, object_list=False):
"""
search node identified by name fmfpath
:param path: path to filesystem
:param name: str - name as pattern to search - "/name" (prepended hierarchy item)
:param object_list: bool, if true, return whole list of found items
:return: Tree Object or list
"""
output = {}
fmf_tree = ExtendedTree(path)
logger.debug("get FMF metadata for test (path:%s name=%s)", path, name)
# ignore items with @ in names, to avoid using unreferenced items
items = [x for x in fmf_tree.climb() if x.name.endswith("/" + name) and "@" not in x.name]
if object_list:
return items
if len(items) == 1:
output = items[0]
elif len(items) > 1:
raise Exception("There is more FMF test metadata for item by name:{}({}) {}".format(
name, len(items), [x.name for x in items]))
elif not items:
raise Exception("Unable to get FMF metadata for: {}".format(name))
return output
|
python
|
def receive_fmf_metadata(name, path, object_list=False):
"""
search node identified by name fmfpath
:param path: path to filesystem
:param name: str - name as pattern to search - "/name" (prepended hierarchy item)
:param object_list: bool, if true, return whole list of found items
:return: Tree Object or list
"""
output = {}
fmf_tree = ExtendedTree(path)
logger.debug("get FMF metadata for test (path:%s name=%s)", path, name)
# ignore items with @ in names, to avoid using unreferenced items
items = [x for x in fmf_tree.climb() if x.name.endswith("/" + name) and "@" not in x.name]
if object_list:
return items
if len(items) == 1:
output = items[0]
elif len(items) > 1:
raise Exception("There is more FMF test metadata for item by name:{}({}) {}".format(
name, len(items), [x.name for x in items]))
elif not items:
raise Exception("Unable to get FMF metadata for: {}".format(name))
return output
|
[
"def",
"receive_fmf_metadata",
"(",
"name",
",",
"path",
",",
"object_list",
"=",
"False",
")",
":",
"output",
"=",
"{",
"}",
"fmf_tree",
"=",
"ExtendedTree",
"(",
"path",
")",
"logger",
".",
"debug",
"(",
"\"get FMF metadata for test (path:%s name=%s)\"",
",",
"path",
",",
"name",
")",
"# ignore items with @ in names, to avoid using unreferenced items",
"items",
"=",
"[",
"x",
"for",
"x",
"in",
"fmf_tree",
".",
"climb",
"(",
")",
"if",
"x",
".",
"name",
".",
"endswith",
"(",
"\"/\"",
"+",
"name",
")",
"and",
"\"@\"",
"not",
"in",
"x",
".",
"name",
"]",
"if",
"object_list",
":",
"return",
"items",
"if",
"len",
"(",
"items",
")",
"==",
"1",
":",
"output",
"=",
"items",
"[",
"0",
"]",
"elif",
"len",
"(",
"items",
")",
">",
"1",
":",
"raise",
"Exception",
"(",
"\"There is more FMF test metadata for item by name:{}({}) {}\"",
".",
"format",
"(",
"name",
",",
"len",
"(",
"items",
")",
",",
"[",
"x",
".",
"name",
"for",
"x",
"in",
"items",
"]",
")",
")",
"elif",
"not",
"items",
":",
"raise",
"Exception",
"(",
"\"Unable to get FMF metadata for: {}\"",
".",
"format",
"(",
"name",
")",
")",
"return",
"output"
] |
search node identified by name fmfpath
:param path: path to filesystem
:param name: str - name as pattern to search - "/name" (prepended hierarchy item)
:param object_list: bool, if true, return whole list of found items
:return: Tree Object or list
|
[
"search",
"node",
"identified",
"by",
"name",
"fmfpath"
] |
00bb80e6e91522e15361935f813e8cf13d7e76dc
|
https://github.com/user-cont/colin/blob/00bb80e6e91522e15361935f813e8cf13d7e76dc/colin/core/checks/fmf_check.py#L15-L38
|
train
|
user-cont/colin
|
colin/cli/colin.py
|
list_checks
|
def list_checks(ruleset, ruleset_file, debug, json, skip, tag, verbose, checks_paths):
"""
Print the checks.
"""
if ruleset and ruleset_file:
raise click.BadOptionUsage(
"Options '--ruleset' and '--file-ruleset' cannot be used together.")
try:
if not debug:
logging.basicConfig(stream=six.StringIO())
log_level = _get_log_level(debug=debug,
verbose=verbose)
checks = get_checks(ruleset_name=ruleset,
ruleset_file=ruleset_file,
logging_level=log_level,
tags=tag,
checks_paths=checks_paths,
skips=skip)
_print_checks(checks=checks)
if json:
AbstractCheck.save_checks_to_json(file=json, checks=checks)
except ColinException as ex:
logger.error("An error occurred: %r", ex)
if debug:
raise
else:
raise click.ClickException(str(ex))
except Exception as ex:
logger.error("An error occurred: %r", ex)
if debug:
raise
else:
raise click.ClickException(str(ex))
|
python
|
def list_checks(ruleset, ruleset_file, debug, json, skip, tag, verbose, checks_paths):
"""
Print the checks.
"""
if ruleset and ruleset_file:
raise click.BadOptionUsage(
"Options '--ruleset' and '--file-ruleset' cannot be used together.")
try:
if not debug:
logging.basicConfig(stream=six.StringIO())
log_level = _get_log_level(debug=debug,
verbose=verbose)
checks = get_checks(ruleset_name=ruleset,
ruleset_file=ruleset_file,
logging_level=log_level,
tags=tag,
checks_paths=checks_paths,
skips=skip)
_print_checks(checks=checks)
if json:
AbstractCheck.save_checks_to_json(file=json, checks=checks)
except ColinException as ex:
logger.error("An error occurred: %r", ex)
if debug:
raise
else:
raise click.ClickException(str(ex))
except Exception as ex:
logger.error("An error occurred: %r", ex)
if debug:
raise
else:
raise click.ClickException(str(ex))
|
[
"def",
"list_checks",
"(",
"ruleset",
",",
"ruleset_file",
",",
"debug",
",",
"json",
",",
"skip",
",",
"tag",
",",
"verbose",
",",
"checks_paths",
")",
":",
"if",
"ruleset",
"and",
"ruleset_file",
":",
"raise",
"click",
".",
"BadOptionUsage",
"(",
"\"Options '--ruleset' and '--file-ruleset' cannot be used together.\"",
")",
"try",
":",
"if",
"not",
"debug",
":",
"logging",
".",
"basicConfig",
"(",
"stream",
"=",
"six",
".",
"StringIO",
"(",
")",
")",
"log_level",
"=",
"_get_log_level",
"(",
"debug",
"=",
"debug",
",",
"verbose",
"=",
"verbose",
")",
"checks",
"=",
"get_checks",
"(",
"ruleset_name",
"=",
"ruleset",
",",
"ruleset_file",
"=",
"ruleset_file",
",",
"logging_level",
"=",
"log_level",
",",
"tags",
"=",
"tag",
",",
"checks_paths",
"=",
"checks_paths",
",",
"skips",
"=",
"skip",
")",
"_print_checks",
"(",
"checks",
"=",
"checks",
")",
"if",
"json",
":",
"AbstractCheck",
".",
"save_checks_to_json",
"(",
"file",
"=",
"json",
",",
"checks",
"=",
"checks",
")",
"except",
"ColinException",
"as",
"ex",
":",
"logger",
".",
"error",
"(",
"\"An error occurred: %r\"",
",",
"ex",
")",
"if",
"debug",
":",
"raise",
"else",
":",
"raise",
"click",
".",
"ClickException",
"(",
"str",
"(",
"ex",
")",
")",
"except",
"Exception",
"as",
"ex",
":",
"logger",
".",
"error",
"(",
"\"An error occurred: %r\"",
",",
"ex",
")",
"if",
"debug",
":",
"raise",
"else",
":",
"raise",
"click",
".",
"ClickException",
"(",
"str",
"(",
"ex",
")",
")"
] |
Print the checks.
|
[
"Print",
"the",
"checks",
"."
] |
00bb80e6e91522e15361935f813e8cf13d7e76dc
|
https://github.com/user-cont/colin/blob/00bb80e6e91522e15361935f813e8cf13d7e76dc/colin/cli/colin.py#L158-L193
|
train
|
user-cont/colin
|
colin/cli/colin.py
|
list_rulesets
|
def list_rulesets(debug):
"""
List available rulesets.
"""
try:
rulesets = get_rulesets()
max_len = max([len(r[0]) for r in rulesets])
for r in rulesets:
click.echo('{0: <{1}} ({2})'.format(r[0], max_len, r[1]))
except Exception as ex:
logger.error("An error occurred: %r", ex)
if debug:
raise
else:
raise click.ClickException(str(ex))
|
python
|
def list_rulesets(debug):
"""
List available rulesets.
"""
try:
rulesets = get_rulesets()
max_len = max([len(r[0]) for r in rulesets])
for r in rulesets:
click.echo('{0: <{1}} ({2})'.format(r[0], max_len, r[1]))
except Exception as ex:
logger.error("An error occurred: %r", ex)
if debug:
raise
else:
raise click.ClickException(str(ex))
|
[
"def",
"list_rulesets",
"(",
"debug",
")",
":",
"try",
":",
"rulesets",
"=",
"get_rulesets",
"(",
")",
"max_len",
"=",
"max",
"(",
"[",
"len",
"(",
"r",
"[",
"0",
"]",
")",
"for",
"r",
"in",
"rulesets",
"]",
")",
"for",
"r",
"in",
"rulesets",
":",
"click",
".",
"echo",
"(",
"'{0: <{1}} ({2})'",
".",
"format",
"(",
"r",
"[",
"0",
"]",
",",
"max_len",
",",
"r",
"[",
"1",
"]",
")",
")",
"except",
"Exception",
"as",
"ex",
":",
"logger",
".",
"error",
"(",
"\"An error occurred: %r\"",
",",
"ex",
")",
"if",
"debug",
":",
"raise",
"else",
":",
"raise",
"click",
".",
"ClickException",
"(",
"str",
"(",
"ex",
")",
")"
] |
List available rulesets.
|
[
"List",
"available",
"rulesets",
"."
] |
00bb80e6e91522e15361935f813e8cf13d7e76dc
|
https://github.com/user-cont/colin/blob/00bb80e6e91522e15361935f813e8cf13d7e76dc/colin/cli/colin.py#L200-L214
|
train
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.