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
sequence | docstring
stringlengths 3
17.3k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 87
242
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
Felspar/django-fost-authn | fost_authn/signature.py | sha1_hmac | def sha1_hmac(secret, document):
"""
Calculate the Base 64 encoding of the HMAC for the given document.
"""
signature = hmac.new(secret, document, hashlib.sha1).digest().encode("base64")[:-1]
return signature | python | def sha1_hmac(secret, document):
"""
Calculate the Base 64 encoding of the HMAC for the given document.
"""
signature = hmac.new(secret, document, hashlib.sha1).digest().encode("base64")[:-1]
return signature | [
"def",
"sha1_hmac",
"(",
"secret",
",",
"document",
")",
":",
"signature",
"=",
"hmac",
".",
"new",
"(",
"secret",
",",
"document",
",",
"hashlib",
".",
"sha1",
")",
".",
"digest",
"(",
")",
".",
"encode",
"(",
"\"base64\"",
")",
"[",
":",
"-",
"1",
"]",
"return",
"signature"
] | Calculate the Base 64 encoding of the HMAC for the given document. | [
"Calculate",
"the",
"Base",
"64",
"encoding",
"of",
"the",
"HMAC",
"for",
"the",
"given",
"document",
"."
] | 31623fa9f77570fe9b99962595da12f67f24c409 | https://github.com/Felspar/django-fost-authn/blob/31623fa9f77570fe9b99962595da12f67f24c409/fost_authn/signature.py#L6-L11 | train |
Felspar/django-fost-authn | fost_authn/signature.py | filter_query_string | def filter_query_string(query):
"""
Return a version of the query string with the _e, _k and _s values
removed.
"""
return '&'.join([q for q in query.split('&')
if not (q.startswith('_k=') or q.startswith('_e=') or q.startswith('_s'))]) | python | def filter_query_string(query):
"""
Return a version of the query string with the _e, _k and _s values
removed.
"""
return '&'.join([q for q in query.split('&')
if not (q.startswith('_k=') or q.startswith('_e=') or q.startswith('_s'))]) | [
"def",
"filter_query_string",
"(",
"query",
")",
":",
"return",
"'&'",
".",
"join",
"(",
"[",
"q",
"for",
"q",
"in",
"query",
".",
"split",
"(",
"'&'",
")",
"if",
"not",
"(",
"q",
".",
"startswith",
"(",
"'_k='",
")",
"or",
"q",
".",
"startswith",
"(",
"'_e='",
")",
"or",
"q",
".",
"startswith",
"(",
"'_s'",
")",
")",
"]",
")"
] | Return a version of the query string with the _e, _k and _s values
removed. | [
"Return",
"a",
"version",
"of",
"the",
"query",
"string",
"with",
"the",
"_e",
"_k",
"and",
"_s",
"values",
"removed",
"."
] | 31623fa9f77570fe9b99962595da12f67f24c409 | https://github.com/Felspar/django-fost-authn/blob/31623fa9f77570fe9b99962595da12f67f24c409/fost_authn/signature.py#L14-L20 | train |
Felspar/django-fost-authn | fost_authn/signature.py | fost_hmac_url_signature | def fost_hmac_url_signature(
key, secret, host, path, query_string, expires):
"""
Return a signature that corresponds to the signed URL.
"""
if query_string:
document = '%s%s?%s\n%s' % (host, path, query_string, expires)
else:
document = '%s%s\n%s' % (host, path, expires)
signature = sha1_hmac(secret, document)
return signature | python | def fost_hmac_url_signature(
key, secret, host, path, query_string, expires):
"""
Return a signature that corresponds to the signed URL.
"""
if query_string:
document = '%s%s?%s\n%s' % (host, path, query_string, expires)
else:
document = '%s%s\n%s' % (host, path, expires)
signature = sha1_hmac(secret, document)
return signature | [
"def",
"fost_hmac_url_signature",
"(",
"key",
",",
"secret",
",",
"host",
",",
"path",
",",
"query_string",
",",
"expires",
")",
":",
"if",
"query_string",
":",
"document",
"=",
"'%s%s?%s\\n%s'",
"%",
"(",
"host",
",",
"path",
",",
"query_string",
",",
"expires",
")",
"else",
":",
"document",
"=",
"'%s%s\\n%s'",
"%",
"(",
"host",
",",
"path",
",",
"expires",
")",
"signature",
"=",
"sha1_hmac",
"(",
"secret",
",",
"document",
")",
"return",
"signature"
] | Return a signature that corresponds to the signed URL. | [
"Return",
"a",
"signature",
"that",
"corresponds",
"to",
"the",
"signed",
"URL",
"."
] | 31623fa9f77570fe9b99962595da12f67f24c409 | https://github.com/Felspar/django-fost-authn/blob/31623fa9f77570fe9b99962595da12f67f24c409/fost_authn/signature.py#L23-L33 | train |
Felspar/django-fost-authn | fost_authn/signature.py | fost_hmac_request_signature | def fost_hmac_request_signature(
secret, method, path, timestamp, headers = {}, body = ''):
"""
Calculate the signature for the given secret and arguments.
"""
signed_headers, header_values = 'X-FOST-Headers', []
for header, value in headers.items():
signed_headers += ' ' + header
header_values.append(value)
return fost_hmac_request_signature_with_headers(
secret, method, path, timestamp,
[signed_headers] + header_values, body) | python | def fost_hmac_request_signature(
secret, method, path, timestamp, headers = {}, body = ''):
"""
Calculate the signature for the given secret and arguments.
"""
signed_headers, header_values = 'X-FOST-Headers', []
for header, value in headers.items():
signed_headers += ' ' + header
header_values.append(value)
return fost_hmac_request_signature_with_headers(
secret, method, path, timestamp,
[signed_headers] + header_values, body) | [
"def",
"fost_hmac_request_signature",
"(",
"secret",
",",
"method",
",",
"path",
",",
"timestamp",
",",
"headers",
"=",
"{",
"}",
",",
"body",
"=",
"''",
")",
":",
"signed_headers",
",",
"header_values",
"=",
"'X-FOST-Headers'",
",",
"[",
"]",
"for",
"header",
",",
"value",
"in",
"headers",
".",
"items",
"(",
")",
":",
"signed_headers",
"+=",
"' '",
"+",
"header",
"header_values",
".",
"append",
"(",
"value",
")",
"return",
"fost_hmac_request_signature_with_headers",
"(",
"secret",
",",
"method",
",",
"path",
",",
"timestamp",
",",
"[",
"signed_headers",
"]",
"+",
"header_values",
",",
"body",
")"
] | Calculate the signature for the given secret and arguments. | [
"Calculate",
"the",
"signature",
"for",
"the",
"given",
"secret",
"and",
"arguments",
"."
] | 31623fa9f77570fe9b99962595da12f67f24c409 | https://github.com/Felspar/django-fost-authn/blob/31623fa9f77570fe9b99962595da12f67f24c409/fost_authn/signature.py#L36-L47 | train |
Felspar/django-fost-authn | fost_authn/signature.py | fost_hmac_request_signature_with_headers | def fost_hmac_request_signature_with_headers(
secret, method, path, timestamp, headers, body):
"""
Calculate the signature for the given secret and other arguments.
The headers must be the correct header value list in the proper order.
"""
document = "%s %s\n%s\n%s\n%s" % (
method, path,
timestamp,
'\n'.join(headers),
body)
signature = sha1_hmac(secret, document)
logging.info("Calculated signature %s for document\n%s", signature, document)
return document, signature | python | def fost_hmac_request_signature_with_headers(
secret, method, path, timestamp, headers, body):
"""
Calculate the signature for the given secret and other arguments.
The headers must be the correct header value list in the proper order.
"""
document = "%s %s\n%s\n%s\n%s" % (
method, path,
timestamp,
'\n'.join(headers),
body)
signature = sha1_hmac(secret, document)
logging.info("Calculated signature %s for document\n%s", signature, document)
return document, signature | [
"def",
"fost_hmac_request_signature_with_headers",
"(",
"secret",
",",
"method",
",",
"path",
",",
"timestamp",
",",
"headers",
",",
"body",
")",
":",
"document",
"=",
"\"%s %s\\n%s\\n%s\\n%s\"",
"%",
"(",
"method",
",",
"path",
",",
"timestamp",
",",
"'\\n'",
".",
"join",
"(",
"headers",
")",
",",
"body",
")",
"signature",
"=",
"sha1_hmac",
"(",
"secret",
",",
"document",
")",
"logging",
".",
"info",
"(",
"\"Calculated signature %s for document\\n%s\"",
",",
"signature",
",",
"document",
")",
"return",
"document",
",",
"signature"
] | Calculate the signature for the given secret and other arguments.
The headers must be the correct header value list in the proper order. | [
"Calculate",
"the",
"signature",
"for",
"the",
"given",
"secret",
"and",
"other",
"arguments",
"."
] | 31623fa9f77570fe9b99962595da12f67f24c409 | https://github.com/Felspar/django-fost-authn/blob/31623fa9f77570fe9b99962595da12f67f24c409/fost_authn/signature.py#L50-L64 | train |
AASHE/python-membersuite-api-client | membersuite_api_client/orders/services.py | get_order | def get_order(membersuite_id, client=None):
"""Get an Order by ID.
"""
if not membersuite_id:
return None
client = client or get_new_client(request_session=True)
if not client.session_id:
client.request_session()
object_query = "SELECT Object() FROM ORDER WHERE ID = '{}'".format(
membersuite_id)
result = client.execute_object_query(object_query)
msql_result = result["body"]["ExecuteMSQLResult"]
if msql_result["Success"]:
membersuite_object_data = (msql_result["ResultValue"]
["SingleObject"])
else:
raise ExecuteMSQLError(result=result)
return Order(membersuite_object_data=membersuite_object_data) | python | def get_order(membersuite_id, client=None):
"""Get an Order by ID.
"""
if not membersuite_id:
return None
client = client or get_new_client(request_session=True)
if not client.session_id:
client.request_session()
object_query = "SELECT Object() FROM ORDER WHERE ID = '{}'".format(
membersuite_id)
result = client.execute_object_query(object_query)
msql_result = result["body"]["ExecuteMSQLResult"]
if msql_result["Success"]:
membersuite_object_data = (msql_result["ResultValue"]
["SingleObject"])
else:
raise ExecuteMSQLError(result=result)
return Order(membersuite_object_data=membersuite_object_data) | [
"def",
"get_order",
"(",
"membersuite_id",
",",
"client",
"=",
"None",
")",
":",
"if",
"not",
"membersuite_id",
":",
"return",
"None",
"client",
"=",
"client",
"or",
"get_new_client",
"(",
"request_session",
"=",
"True",
")",
"if",
"not",
"client",
".",
"session_id",
":",
"client",
".",
"request_session",
"(",
")",
"object_query",
"=",
"\"SELECT Object() FROM ORDER WHERE ID = '{}'\"",
".",
"format",
"(",
"membersuite_id",
")",
"result",
"=",
"client",
".",
"execute_object_query",
"(",
"object_query",
")",
"msql_result",
"=",
"result",
"[",
"\"body\"",
"]",
"[",
"\"ExecuteMSQLResult\"",
"]",
"if",
"msql_result",
"[",
"\"Success\"",
"]",
":",
"membersuite_object_data",
"=",
"(",
"msql_result",
"[",
"\"ResultValue\"",
"]",
"[",
"\"SingleObject\"",
"]",
")",
"else",
":",
"raise",
"ExecuteMSQLError",
"(",
"result",
"=",
"result",
")",
"return",
"Order",
"(",
"membersuite_object_data",
"=",
"membersuite_object_data",
")"
] | Get an Order by ID. | [
"Get",
"an",
"Order",
"by",
"ID",
"."
] | 221f5ed8bc7d4424237a4669c5af9edc11819ee9 | https://github.com/AASHE/python-membersuite-api-client/blob/221f5ed8bc7d4424237a4669c5af9edc11819ee9/membersuite_api_client/orders/services.py#L6-L29 | train |
a1ezzz/wasp-general | wasp_general/crypto/rsa.py | WRSA.export_private_key | def export_private_key(self, password=None):
""" Export a private key in PEM-format
:param password: If it is not None, then result will be encrypt with given password
:return: bytes
"""
if self.__private_key is None:
raise ValueError('Unable to call this method. Private key must be set')
if password is not None:
if isinstance(password, str) is True:
password = password.encode()
return self.__private_key.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.PKCS8,
encryption_algorithm=serialization.BestAvailableEncryption(password)
)
return self.__private_key.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.TraditionalOpenSSL,
encryption_algorithm=serialization.NoEncryption()
) | python | def export_private_key(self, password=None):
""" Export a private key in PEM-format
:param password: If it is not None, then result will be encrypt with given password
:return: bytes
"""
if self.__private_key is None:
raise ValueError('Unable to call this method. Private key must be set')
if password is not None:
if isinstance(password, str) is True:
password = password.encode()
return self.__private_key.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.PKCS8,
encryption_algorithm=serialization.BestAvailableEncryption(password)
)
return self.__private_key.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.TraditionalOpenSSL,
encryption_algorithm=serialization.NoEncryption()
) | [
"def",
"export_private_key",
"(",
"self",
",",
"password",
"=",
"None",
")",
":",
"if",
"self",
".",
"__private_key",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"'Unable to call this method. Private key must be set'",
")",
"if",
"password",
"is",
"not",
"None",
":",
"if",
"isinstance",
"(",
"password",
",",
"str",
")",
"is",
"True",
":",
"password",
"=",
"password",
".",
"encode",
"(",
")",
"return",
"self",
".",
"__private_key",
".",
"private_bytes",
"(",
"encoding",
"=",
"serialization",
".",
"Encoding",
".",
"PEM",
",",
"format",
"=",
"serialization",
".",
"PrivateFormat",
".",
"PKCS8",
",",
"encryption_algorithm",
"=",
"serialization",
".",
"BestAvailableEncryption",
"(",
"password",
")",
")",
"return",
"self",
".",
"__private_key",
".",
"private_bytes",
"(",
"encoding",
"=",
"serialization",
".",
"Encoding",
".",
"PEM",
",",
"format",
"=",
"serialization",
".",
"PrivateFormat",
".",
"TraditionalOpenSSL",
",",
"encryption_algorithm",
"=",
"serialization",
".",
"NoEncryption",
"(",
")",
")"
] | Export a private key in PEM-format
:param password: If it is not None, then result will be encrypt with given password
:return: bytes | [
"Export",
"a",
"private",
"key",
"in",
"PEM",
"-",
"format"
] | 1029839d33eb663f8dec76c1c46754d53c1de4a9 | https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/crypto/rsa.py#L106-L128 | train |
a1ezzz/wasp-general | wasp_general/crypto/rsa.py | WRSA.export_public_key | def export_public_key(self):
""" Export a public key in PEM-format
:return: bytes
"""
if self.__public_key is None:
raise ValueError('Unable to call this method. Public key must be set')
return self.__public_key.public_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PublicFormat.SubjectPublicKeyInfo
) | python | def export_public_key(self):
""" Export a public key in PEM-format
:return: bytes
"""
if self.__public_key is None:
raise ValueError('Unable to call this method. Public key must be set')
return self.__public_key.public_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PublicFormat.SubjectPublicKeyInfo
) | [
"def",
"export_public_key",
"(",
"self",
")",
":",
"if",
"self",
".",
"__public_key",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"'Unable to call this method. Public key must be set'",
")",
"return",
"self",
".",
"__public_key",
".",
"public_bytes",
"(",
"encoding",
"=",
"serialization",
".",
"Encoding",
".",
"PEM",
",",
"format",
"=",
"serialization",
".",
"PublicFormat",
".",
"SubjectPublicKeyInfo",
")"
] | Export a public key in PEM-format
:return: bytes | [
"Export",
"a",
"public",
"key",
"in",
"PEM",
"-",
"format"
] | 1029839d33eb663f8dec76c1c46754d53c1de4a9 | https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/crypto/rsa.py#L130-L141 | train |
a1ezzz/wasp-general | wasp_general/crypto/rsa.py | WRSA.import_private_key | def import_private_key(self, pem_text, password=None):
""" Import a private key from data in PEM-format
:param pem_text: text with private key
:param password: If it is not None, then result will be decrypt with the given password
:return: None
"""
if isinstance(pem_text, str) is True:
pem_text = pem_text.encode()
if password is not None and isinstance(password, str) is True:
password = password.encode()
self.__set_private_key(
serialization.load_pem_private_key(pem_text, password=password, backend=default_backend())
) | python | def import_private_key(self, pem_text, password=None):
""" Import a private key from data in PEM-format
:param pem_text: text with private key
:param password: If it is not None, then result will be decrypt with the given password
:return: None
"""
if isinstance(pem_text, str) is True:
pem_text = pem_text.encode()
if password is not None and isinstance(password, str) is True:
password = password.encode()
self.__set_private_key(
serialization.load_pem_private_key(pem_text, password=password, backend=default_backend())
) | [
"def",
"import_private_key",
"(",
"self",
",",
"pem_text",
",",
"password",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"pem_text",
",",
"str",
")",
"is",
"True",
":",
"pem_text",
"=",
"pem_text",
".",
"encode",
"(",
")",
"if",
"password",
"is",
"not",
"None",
"and",
"isinstance",
"(",
"password",
",",
"str",
")",
"is",
"True",
":",
"password",
"=",
"password",
".",
"encode",
"(",
")",
"self",
".",
"__set_private_key",
"(",
"serialization",
".",
"load_pem_private_key",
"(",
"pem_text",
",",
"password",
"=",
"password",
",",
"backend",
"=",
"default_backend",
"(",
")",
")",
")"
] | Import a private key from data in PEM-format
:param pem_text: text with private key
:param password: If it is not None, then result will be decrypt with the given password
:return: None | [
"Import",
"a",
"private",
"key",
"from",
"data",
"in",
"PEM",
"-",
"format"
] | 1029839d33eb663f8dec76c1c46754d53c1de4a9 | https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/crypto/rsa.py#L144-L158 | train |
a1ezzz/wasp-general | wasp_general/crypto/rsa.py | WRSA.decrypt | def decrypt(self, data, oaep_hash_fn_name=None, mgf1_hash_fn_name=None):
""" Decrypt a data that used PKCS1 OAEP protocol
:param data: data to decrypt
:param oaep_hash_fn_name: hash function name to use with OAEP
:param mgf1_hash_fn_name: hash function name to use with MGF1 padding
:return: bytes
"""
if self.__private_key is None:
raise ValueError('Unable to call this method. Private key must be set')
if oaep_hash_fn_name is None:
oaep_hash_fn_name = self.__class__.__default_oaep_hash_function_name__
if mgf1_hash_fn_name is None:
mgf1_hash_fn_name = self.__class__.__default_mgf1_hash_function_name__
oaep_hash_cls = getattr(hashes, oaep_hash_fn_name)
mgf1_hash_cls = getattr(hashes, mgf1_hash_fn_name)
return self.__private_key.decrypt(
data,
padding.OAEP(
mgf=padding.MGF1(algorithm=mgf1_hash_cls()),
algorithm=oaep_hash_cls(),
label=None
)
) | python | def decrypt(self, data, oaep_hash_fn_name=None, mgf1_hash_fn_name=None):
""" Decrypt a data that used PKCS1 OAEP protocol
:param data: data to decrypt
:param oaep_hash_fn_name: hash function name to use with OAEP
:param mgf1_hash_fn_name: hash function name to use with MGF1 padding
:return: bytes
"""
if self.__private_key is None:
raise ValueError('Unable to call this method. Private key must be set')
if oaep_hash_fn_name is None:
oaep_hash_fn_name = self.__class__.__default_oaep_hash_function_name__
if mgf1_hash_fn_name is None:
mgf1_hash_fn_name = self.__class__.__default_mgf1_hash_function_name__
oaep_hash_cls = getattr(hashes, oaep_hash_fn_name)
mgf1_hash_cls = getattr(hashes, mgf1_hash_fn_name)
return self.__private_key.decrypt(
data,
padding.OAEP(
mgf=padding.MGF1(algorithm=mgf1_hash_cls()),
algorithm=oaep_hash_cls(),
label=None
)
) | [
"def",
"decrypt",
"(",
"self",
",",
"data",
",",
"oaep_hash_fn_name",
"=",
"None",
",",
"mgf1_hash_fn_name",
"=",
"None",
")",
":",
"if",
"self",
".",
"__private_key",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"'Unable to call this method. Private key must be set'",
")",
"if",
"oaep_hash_fn_name",
"is",
"None",
":",
"oaep_hash_fn_name",
"=",
"self",
".",
"__class__",
".",
"__default_oaep_hash_function_name__",
"if",
"mgf1_hash_fn_name",
"is",
"None",
":",
"mgf1_hash_fn_name",
"=",
"self",
".",
"__class__",
".",
"__default_mgf1_hash_function_name__",
"oaep_hash_cls",
"=",
"getattr",
"(",
"hashes",
",",
"oaep_hash_fn_name",
")",
"mgf1_hash_cls",
"=",
"getattr",
"(",
"hashes",
",",
"mgf1_hash_fn_name",
")",
"return",
"self",
".",
"__private_key",
".",
"decrypt",
"(",
"data",
",",
"padding",
".",
"OAEP",
"(",
"mgf",
"=",
"padding",
".",
"MGF1",
"(",
"algorithm",
"=",
"mgf1_hash_cls",
"(",
")",
")",
",",
"algorithm",
"=",
"oaep_hash_cls",
"(",
")",
",",
"label",
"=",
"None",
")",
")"
] | Decrypt a data that used PKCS1 OAEP protocol
:param data: data to decrypt
:param oaep_hash_fn_name: hash function name to use with OAEP
:param mgf1_hash_fn_name: hash function name to use with MGF1 padding
:return: bytes | [
"Decrypt",
"a",
"data",
"that",
"used",
"PKCS1",
"OAEP",
"protocol"
] | 1029839d33eb663f8dec76c1c46754d53c1de4a9 | https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/crypto/rsa.py#L208-L236 | train |
projectshift/shift-schema | shiftschema/validators/length.py | Length.validate | def validate(self, value, model=None, context=None):
"""
Validate
Perform value validation against validation settings and return
simple result object
:param value: str, value to check
:param model: parent model being validated
:param context: object or None, validation context
:return: shiftschema.results.SimpleResult
"""
length = len(str(value))
params = dict(min=self.min, max=self.max)
# too short?
if self.min and self.max is None:
if length < self.min:
return Error(self.too_short, params)
# too long?
if self.max and self.min is None:
if length > self.max:
return Error(self.too_long, params)
# within range?
if self.min and self.max:
if length < self.min or length > self.max:
return Error(self.not_in_range, params)
# success otherwise
return Error() | python | def validate(self, value, model=None, context=None):
"""
Validate
Perform value validation against validation settings and return
simple result object
:param value: str, value to check
:param model: parent model being validated
:param context: object or None, validation context
:return: shiftschema.results.SimpleResult
"""
length = len(str(value))
params = dict(min=self.min, max=self.max)
# too short?
if self.min and self.max is None:
if length < self.min:
return Error(self.too_short, params)
# too long?
if self.max and self.min is None:
if length > self.max:
return Error(self.too_long, params)
# within range?
if self.min and self.max:
if length < self.min or length > self.max:
return Error(self.not_in_range, params)
# success otherwise
return Error() | [
"def",
"validate",
"(",
"self",
",",
"value",
",",
"model",
"=",
"None",
",",
"context",
"=",
"None",
")",
":",
"length",
"=",
"len",
"(",
"str",
"(",
"value",
")",
")",
"params",
"=",
"dict",
"(",
"min",
"=",
"self",
".",
"min",
",",
"max",
"=",
"self",
".",
"max",
")",
"# too short?",
"if",
"self",
".",
"min",
"and",
"self",
".",
"max",
"is",
"None",
":",
"if",
"length",
"<",
"self",
".",
"min",
":",
"return",
"Error",
"(",
"self",
".",
"too_short",
",",
"params",
")",
"# too long?",
"if",
"self",
".",
"max",
"and",
"self",
".",
"min",
"is",
"None",
":",
"if",
"length",
">",
"self",
".",
"max",
":",
"return",
"Error",
"(",
"self",
".",
"too_long",
",",
"params",
")",
"# within range?",
"if",
"self",
".",
"min",
"and",
"self",
".",
"max",
":",
"if",
"length",
"<",
"self",
".",
"min",
"or",
"length",
">",
"self",
".",
"max",
":",
"return",
"Error",
"(",
"self",
".",
"not_in_range",
",",
"params",
")",
"# success otherwise",
"return",
"Error",
"(",
")"
] | Validate
Perform value validation against validation settings and return
simple result object
:param value: str, value to check
:param model: parent model being validated
:param context: object or None, validation context
:return: shiftschema.results.SimpleResult | [
"Validate",
"Perform",
"value",
"validation",
"against",
"validation",
"settings",
"and",
"return",
"simple",
"result",
"object"
] | 07787b540d3369bb37217ffbfbe629118edaf0eb | https://github.com/projectshift/shift-schema/blob/07787b540d3369bb37217ffbfbe629118edaf0eb/shiftschema/validators/length.py#L34-L65 | train |
olitheolix/qtmacs | qtmacs/base_macro.py | QtmacsMacro.qteSaveMacroData | def qteSaveMacroData(self, data, widgetObj: QtGui.QWidget=None):
"""
Associate arbitrary ``data`` with ``widgetObj``.
This is a convenience method to easily store applet/widget
specific information in between calls.
If ``widgetObj`` is **None** then the calling widget
``self.qteWidget`` will be used.
Note that this function overwrites any previously saved data.
|Args|
* ``data`` (**object**): arbitrary python object to save.
* ``widgetObj`` (**QWidget**): the widget/applet with which
the data should be associated.
|Returns|
* **None**
|Raises|
* **QtmacsArgumentError** if at least one argument has an invalid type.
* **QtmacsOtherError** if ``widgetObj`` was not added with
``qteAddWidget`` method.
"""
# Check type of input arguments.
if not hasattr(widgetObj, '_qteAdmin') and (widgetObj is not None):
msg = '<widgetObj> was probably not added with <qteAddWidget>'
msg += ' method because it lacks the <_qteAdmin> attribute.'
raise QtmacsOtherError(msg)
# If no widget was specified then use the calling widget.
if not widgetObj:
widgetObj = self.qteWidget
# Store the supplied data in the applet specific macro storage.
widgetObj._qteAdmin.macroData[self.qteMacroName()] = data | python | def qteSaveMacroData(self, data, widgetObj: QtGui.QWidget=None):
"""
Associate arbitrary ``data`` with ``widgetObj``.
This is a convenience method to easily store applet/widget
specific information in between calls.
If ``widgetObj`` is **None** then the calling widget
``self.qteWidget`` will be used.
Note that this function overwrites any previously saved data.
|Args|
* ``data`` (**object**): arbitrary python object to save.
* ``widgetObj`` (**QWidget**): the widget/applet with which
the data should be associated.
|Returns|
* **None**
|Raises|
* **QtmacsArgumentError** if at least one argument has an invalid type.
* **QtmacsOtherError** if ``widgetObj`` was not added with
``qteAddWidget`` method.
"""
# Check type of input arguments.
if not hasattr(widgetObj, '_qteAdmin') and (widgetObj is not None):
msg = '<widgetObj> was probably not added with <qteAddWidget>'
msg += ' method because it lacks the <_qteAdmin> attribute.'
raise QtmacsOtherError(msg)
# If no widget was specified then use the calling widget.
if not widgetObj:
widgetObj = self.qteWidget
# Store the supplied data in the applet specific macro storage.
widgetObj._qteAdmin.macroData[self.qteMacroName()] = data | [
"def",
"qteSaveMacroData",
"(",
"self",
",",
"data",
",",
"widgetObj",
":",
"QtGui",
".",
"QWidget",
"=",
"None",
")",
":",
"# Check type of input arguments.",
"if",
"not",
"hasattr",
"(",
"widgetObj",
",",
"'_qteAdmin'",
")",
"and",
"(",
"widgetObj",
"is",
"not",
"None",
")",
":",
"msg",
"=",
"'<widgetObj> was probably not added with <qteAddWidget>'",
"msg",
"+=",
"' method because it lacks the <_qteAdmin> attribute.'",
"raise",
"QtmacsOtherError",
"(",
"msg",
")",
"# If no widget was specified then use the calling widget.",
"if",
"not",
"widgetObj",
":",
"widgetObj",
"=",
"self",
".",
"qteWidget",
"# Store the supplied data in the applet specific macro storage.",
"widgetObj",
".",
"_qteAdmin",
".",
"macroData",
"[",
"self",
".",
"qteMacroName",
"(",
")",
"]",
"=",
"data"
] | Associate arbitrary ``data`` with ``widgetObj``.
This is a convenience method to easily store applet/widget
specific information in between calls.
If ``widgetObj`` is **None** then the calling widget
``self.qteWidget`` will be used.
Note that this function overwrites any previously saved data.
|Args|
* ``data`` (**object**): arbitrary python object to save.
* ``widgetObj`` (**QWidget**): the widget/applet with which
the data should be associated.
|Returns|
* **None**
|Raises|
* **QtmacsArgumentError** if at least one argument has an invalid type.
* **QtmacsOtherError** if ``widgetObj`` was not added with
``qteAddWidget`` method. | [
"Associate",
"arbitrary",
"data",
"with",
"widgetObj",
"."
] | 36253b082b82590f183fe154b053eb3a1e741be2 | https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/base_macro.py#L216-L256 | train |
olitheolix/qtmacs | qtmacs/base_macro.py | QtmacsMacro.qteMacroData | def qteMacroData(self, widgetObj: QtGui.QWidget=None):
"""
Retrieve ``widgetObj`` specific data previously saved with
``qteSaveMacroData``.
If no data has been stored previously then **None** is
returned.
If ``widgetObj`` is **None** then the calling widget
``self.qteWidget`` will be used.
|Args|
* ``widgetObj`` (**QWidget**): the widget/applet with which
the data should be associated.
|Returns|
* **object**: the previously stored data.
|Raises|
* **QtmacsArgumentError** if at least one argument has an invalid type.
* **QtmacsOtherError** if ``widgetObj`` was not added with
``qteAddWidget`` method.
"""
# Check type of input arguments.
if not hasattr(widgetObj, '_qteAdmin') and (widgetObj is not None):
msg = '<widgetObj> was probably not added with <qteAddWidget>'
msg += ' method because it lacks the <_qteAdmin> attribute.'
raise QtmacsOtherError(msg)
# If no widget was specified then use the calling widget.
if not widgetObj:
widgetObj = self.qteWidget
# Retrieve the data structure.
try:
_ = widgetObj._qteAdmin.macroData[self.qteMacroName()]
except KeyError:
# If the entry does not exist then this is a bug; create
# an empty entry for next time.
widgetObj._qteAdmin.macroData[self.qteMacroName()] = None
# Return the data.
return widgetObj._qteAdmin.macroData[self.qteMacroName()] | python | def qteMacroData(self, widgetObj: QtGui.QWidget=None):
"""
Retrieve ``widgetObj`` specific data previously saved with
``qteSaveMacroData``.
If no data has been stored previously then **None** is
returned.
If ``widgetObj`` is **None** then the calling widget
``self.qteWidget`` will be used.
|Args|
* ``widgetObj`` (**QWidget**): the widget/applet with which
the data should be associated.
|Returns|
* **object**: the previously stored data.
|Raises|
* **QtmacsArgumentError** if at least one argument has an invalid type.
* **QtmacsOtherError** if ``widgetObj`` was not added with
``qteAddWidget`` method.
"""
# Check type of input arguments.
if not hasattr(widgetObj, '_qteAdmin') and (widgetObj is not None):
msg = '<widgetObj> was probably not added with <qteAddWidget>'
msg += ' method because it lacks the <_qteAdmin> attribute.'
raise QtmacsOtherError(msg)
# If no widget was specified then use the calling widget.
if not widgetObj:
widgetObj = self.qteWidget
# Retrieve the data structure.
try:
_ = widgetObj._qteAdmin.macroData[self.qteMacroName()]
except KeyError:
# If the entry does not exist then this is a bug; create
# an empty entry for next time.
widgetObj._qteAdmin.macroData[self.qteMacroName()] = None
# Return the data.
return widgetObj._qteAdmin.macroData[self.qteMacroName()] | [
"def",
"qteMacroData",
"(",
"self",
",",
"widgetObj",
":",
"QtGui",
".",
"QWidget",
"=",
"None",
")",
":",
"# Check type of input arguments.",
"if",
"not",
"hasattr",
"(",
"widgetObj",
",",
"'_qteAdmin'",
")",
"and",
"(",
"widgetObj",
"is",
"not",
"None",
")",
":",
"msg",
"=",
"'<widgetObj> was probably not added with <qteAddWidget>'",
"msg",
"+=",
"' method because it lacks the <_qteAdmin> attribute.'",
"raise",
"QtmacsOtherError",
"(",
"msg",
")",
"# If no widget was specified then use the calling widget.",
"if",
"not",
"widgetObj",
":",
"widgetObj",
"=",
"self",
".",
"qteWidget",
"# Retrieve the data structure.",
"try",
":",
"_",
"=",
"widgetObj",
".",
"_qteAdmin",
".",
"macroData",
"[",
"self",
".",
"qteMacroName",
"(",
")",
"]",
"except",
"KeyError",
":",
"# If the entry does not exist then this is a bug; create",
"# an empty entry for next time.",
"widgetObj",
".",
"_qteAdmin",
".",
"macroData",
"[",
"self",
".",
"qteMacroName",
"(",
")",
"]",
"=",
"None",
"# Return the data.",
"return",
"widgetObj",
".",
"_qteAdmin",
".",
"macroData",
"[",
"self",
".",
"qteMacroName",
"(",
")",
"]"
] | Retrieve ``widgetObj`` specific data previously saved with
``qteSaveMacroData``.
If no data has been stored previously then **None** is
returned.
If ``widgetObj`` is **None** then the calling widget
``self.qteWidget`` will be used.
|Args|
* ``widgetObj`` (**QWidget**): the widget/applet with which
the data should be associated.
|Returns|
* **object**: the previously stored data.
|Raises|
* **QtmacsArgumentError** if at least one argument has an invalid type.
* **QtmacsOtherError** if ``widgetObj`` was not added with
``qteAddWidget`` method. | [
"Retrieve",
"widgetObj",
"specific",
"data",
"previously",
"saved",
"with",
"qteSaveMacroData",
"."
] | 36253b082b82590f183fe154b053eb3a1e741be2 | https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/base_macro.py#L259-L306 | train |
olitheolix/qtmacs | qtmacs/base_macro.py | QtmacsMacro.qteSetAppletSignature | def qteSetAppletSignature(self, appletSignatures: (str, tuple, list)):
"""
Specify the applet signatures with which this macro is compatible.
Qtmacs uses this information at run time to determine if this
macro is compatible with a particular applet, as specified by
the applet's signature. Note that this function overwrites
all previously set values.
|Args|
* ``*appletSignatures`` (**str, tuple, list**): applet signatures
as a string, or tuple/list of strings.
|Returns|
* **None**
|Raises|
* **QtmacsArgumentError** if at least one argument has an invalid type.
"""
# Convert the argument to a tuple if it is not already a tuple
# or list.
if not isinstance(appletSignatures, (tuple, list)):
appletSignatures = appletSignatures,
# Ensure that all arguments in the tuple/list are strings.
for idx, val in enumerate(appletSignatures):
if not isinstance(val, str):
args = ('appletSignatures', 'str', inspect.stack()[0][3])
raise QtmacsArgumentError(*args)
# Store the compatible applet signatures as a tuple (of strings).
self._qteAppletSignatures = tuple(appletSignatures) | python | def qteSetAppletSignature(self, appletSignatures: (str, tuple, list)):
"""
Specify the applet signatures with which this macro is compatible.
Qtmacs uses this information at run time to determine if this
macro is compatible with a particular applet, as specified by
the applet's signature. Note that this function overwrites
all previously set values.
|Args|
* ``*appletSignatures`` (**str, tuple, list**): applet signatures
as a string, or tuple/list of strings.
|Returns|
* **None**
|Raises|
* **QtmacsArgumentError** if at least one argument has an invalid type.
"""
# Convert the argument to a tuple if it is not already a tuple
# or list.
if not isinstance(appletSignatures, (tuple, list)):
appletSignatures = appletSignatures,
# Ensure that all arguments in the tuple/list are strings.
for idx, val in enumerate(appletSignatures):
if not isinstance(val, str):
args = ('appletSignatures', 'str', inspect.stack()[0][3])
raise QtmacsArgumentError(*args)
# Store the compatible applet signatures as a tuple (of strings).
self._qteAppletSignatures = tuple(appletSignatures) | [
"def",
"qteSetAppletSignature",
"(",
"self",
",",
"appletSignatures",
":",
"(",
"str",
",",
"tuple",
",",
"list",
")",
")",
":",
"# Convert the argument to a tuple if it is not already a tuple",
"# or list.",
"if",
"not",
"isinstance",
"(",
"appletSignatures",
",",
"(",
"tuple",
",",
"list",
")",
")",
":",
"appletSignatures",
"=",
"appletSignatures",
",",
"# Ensure that all arguments in the tuple/list are strings.",
"for",
"idx",
",",
"val",
"in",
"enumerate",
"(",
"appletSignatures",
")",
":",
"if",
"not",
"isinstance",
"(",
"val",
",",
"str",
")",
":",
"args",
"=",
"(",
"'appletSignatures'",
",",
"'str'",
",",
"inspect",
".",
"stack",
"(",
")",
"[",
"0",
"]",
"[",
"3",
"]",
")",
"raise",
"QtmacsArgumentError",
"(",
"*",
"args",
")",
"# Store the compatible applet signatures as a tuple (of strings).",
"self",
".",
"_qteAppletSignatures",
"=",
"tuple",
"(",
"appletSignatures",
")"
] | Specify the applet signatures with which this macro is compatible.
Qtmacs uses this information at run time to determine if this
macro is compatible with a particular applet, as specified by
the applet's signature. Note that this function overwrites
all previously set values.
|Args|
* ``*appletSignatures`` (**str, tuple, list**): applet signatures
as a string, or tuple/list of strings.
|Returns|
* **None**
|Raises|
* **QtmacsArgumentError** if at least one argument has an invalid type. | [
"Specify",
"the",
"applet",
"signatures",
"with",
"which",
"this",
"macro",
"is",
"compatible",
"."
] | 36253b082b82590f183fe154b053eb3a1e741be2 | https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/base_macro.py#L343-L377 | train |
olitheolix/qtmacs | qtmacs/base_macro.py | QtmacsMacro.qteSetWidgetSignature | def qteSetWidgetSignature(self, widgetSignatures: (str, tuple, list)):
"""
Specify the widget signatures with which this macro is
compatible.
Qtmacs uses this information at run time to determine if this
macro is compatible with a particular widget, as specified by
the widget's signature. Note that this function overwrites all
previously set values.
|Args|
* ``*widgetSignatures`` (**str, tuple, list**): widget signatures
as a string, or tuple/list of strings.
|Returns|
* **None**
|Raises|
* **QtmacsArgumentError** if at least one argument has an invalid type.
"""
# Convert the argument to a tuple if it is not already a tuple
# or list.
if not isinstance(widgetSignatures, (tuple, list)):
widgetSignatures = widgetSignatures,
# Ensure that all arguments in the tuple/list are strings.
for idx, val in enumerate(widgetSignatures):
if not isinstance(val, str):
args = ('widgetSignatures', 'str', inspect.stack()[0][3])
raise QtmacsArgumentError(*args)
# Store the compatible widget signatures as a tuple (of strings).
self._qteWidgetSignatures = tuple(widgetSignatures) | python | def qteSetWidgetSignature(self, widgetSignatures: (str, tuple, list)):
"""
Specify the widget signatures with which this macro is
compatible.
Qtmacs uses this information at run time to determine if this
macro is compatible with a particular widget, as specified by
the widget's signature. Note that this function overwrites all
previously set values.
|Args|
* ``*widgetSignatures`` (**str, tuple, list**): widget signatures
as a string, or tuple/list of strings.
|Returns|
* **None**
|Raises|
* **QtmacsArgumentError** if at least one argument has an invalid type.
"""
# Convert the argument to a tuple if it is not already a tuple
# or list.
if not isinstance(widgetSignatures, (tuple, list)):
widgetSignatures = widgetSignatures,
# Ensure that all arguments in the tuple/list are strings.
for idx, val in enumerate(widgetSignatures):
if not isinstance(val, str):
args = ('widgetSignatures', 'str', inspect.stack()[0][3])
raise QtmacsArgumentError(*args)
# Store the compatible widget signatures as a tuple (of strings).
self._qteWidgetSignatures = tuple(widgetSignatures) | [
"def",
"qteSetWidgetSignature",
"(",
"self",
",",
"widgetSignatures",
":",
"(",
"str",
",",
"tuple",
",",
"list",
")",
")",
":",
"# Convert the argument to a tuple if it is not already a tuple",
"# or list.",
"if",
"not",
"isinstance",
"(",
"widgetSignatures",
",",
"(",
"tuple",
",",
"list",
")",
")",
":",
"widgetSignatures",
"=",
"widgetSignatures",
",",
"# Ensure that all arguments in the tuple/list are strings.",
"for",
"idx",
",",
"val",
"in",
"enumerate",
"(",
"widgetSignatures",
")",
":",
"if",
"not",
"isinstance",
"(",
"val",
",",
"str",
")",
":",
"args",
"=",
"(",
"'widgetSignatures'",
",",
"'str'",
",",
"inspect",
".",
"stack",
"(",
")",
"[",
"0",
"]",
"[",
"3",
"]",
")",
"raise",
"QtmacsArgumentError",
"(",
"*",
"args",
")",
"# Store the compatible widget signatures as a tuple (of strings).",
"self",
".",
"_qteWidgetSignatures",
"=",
"tuple",
"(",
"widgetSignatures",
")"
] | Specify the widget signatures with which this macro is
compatible.
Qtmacs uses this information at run time to determine if this
macro is compatible with a particular widget, as specified by
the widget's signature. Note that this function overwrites all
previously set values.
|Args|
* ``*widgetSignatures`` (**str, tuple, list**): widget signatures
as a string, or tuple/list of strings.
|Returns|
* **None**
|Raises|
* **QtmacsArgumentError** if at least one argument has an invalid type. | [
"Specify",
"the",
"widget",
"signatures",
"with",
"which",
"this",
"macro",
"is",
"compatible",
"."
] | 36253b082b82590f183fe154b053eb3a1e741be2 | https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/base_macro.py#L380-L416 | train |
olitheolix/qtmacs | qtmacs/base_macro.py | QtmacsMacro.qtePrepareToRun | def qtePrepareToRun(self):
"""
This method is called by Qtmacs to prepare the macro for
execution.
It is probably a bad idea to overload this method as it only
administrates the macro execution and calls the ``qteRun``
method (which *should* be overloaded by the macro programmer
in order for the macro to do something).
|Args|
* **None**
|Returns|
* **None**
|Raises|
* **None**
"""
# Report the execution attempt.
msgObj = QtmacsMessage((self.qteMacroName(), self.qteWidget), None)
msgObj.setSignalName('qtesigMacroStart')
self.qteMain.qtesigMacroStart.emit(msgObj)
# Try to run the macro and radio the success via the
# ``qtesigMacroFinished`` signal.
try:
self.qteRun()
self.qteMain.qtesigMacroFinished.emit(msgObj)
except Exception as err:
if self.qteApplet is None:
appID = appSig = None
else:
appID = self.qteApplet.qteAppletID()
appSig = self.qteApplet.qteAppletSignature()
msg = ('Macro <b>{}</b> (called from the <b>{}</b> applet'
' with ID <b>{}</b>) did not execute properly.')
msg = msg.format(self.qteMacroName(), appSig, appID)
if isinstance(err, QtmacsArgumentError):
msg += '<br/>' + str(err)
# Irrespective of the error, log it, enable macro
# processing (in case it got disabled), and trigger the
# error signal.
self.qteMain.qteEnableMacroProcessing()
self.qteMain.qtesigMacroError.emit(msgObj)
self.qteLogger.exception(msg, exc_info=True, stack_info=True) | python | def qtePrepareToRun(self):
"""
This method is called by Qtmacs to prepare the macro for
execution.
It is probably a bad idea to overload this method as it only
administrates the macro execution and calls the ``qteRun``
method (which *should* be overloaded by the macro programmer
in order for the macro to do something).
|Args|
* **None**
|Returns|
* **None**
|Raises|
* **None**
"""
# Report the execution attempt.
msgObj = QtmacsMessage((self.qteMacroName(), self.qteWidget), None)
msgObj.setSignalName('qtesigMacroStart')
self.qteMain.qtesigMacroStart.emit(msgObj)
# Try to run the macro and radio the success via the
# ``qtesigMacroFinished`` signal.
try:
self.qteRun()
self.qteMain.qtesigMacroFinished.emit(msgObj)
except Exception as err:
if self.qteApplet is None:
appID = appSig = None
else:
appID = self.qteApplet.qteAppletID()
appSig = self.qteApplet.qteAppletSignature()
msg = ('Macro <b>{}</b> (called from the <b>{}</b> applet'
' with ID <b>{}</b>) did not execute properly.')
msg = msg.format(self.qteMacroName(), appSig, appID)
if isinstance(err, QtmacsArgumentError):
msg += '<br/>' + str(err)
# Irrespective of the error, log it, enable macro
# processing (in case it got disabled), and trigger the
# error signal.
self.qteMain.qteEnableMacroProcessing()
self.qteMain.qtesigMacroError.emit(msgObj)
self.qteLogger.exception(msg, exc_info=True, stack_info=True) | [
"def",
"qtePrepareToRun",
"(",
"self",
")",
":",
"# Report the execution attempt.",
"msgObj",
"=",
"QtmacsMessage",
"(",
"(",
"self",
".",
"qteMacroName",
"(",
")",
",",
"self",
".",
"qteWidget",
")",
",",
"None",
")",
"msgObj",
".",
"setSignalName",
"(",
"'qtesigMacroStart'",
")",
"self",
".",
"qteMain",
".",
"qtesigMacroStart",
".",
"emit",
"(",
"msgObj",
")",
"# Try to run the macro and radio the success via the",
"# ``qtesigMacroFinished`` signal.",
"try",
":",
"self",
".",
"qteRun",
"(",
")",
"self",
".",
"qteMain",
".",
"qtesigMacroFinished",
".",
"emit",
"(",
"msgObj",
")",
"except",
"Exception",
"as",
"err",
":",
"if",
"self",
".",
"qteApplet",
"is",
"None",
":",
"appID",
"=",
"appSig",
"=",
"None",
"else",
":",
"appID",
"=",
"self",
".",
"qteApplet",
".",
"qteAppletID",
"(",
")",
"appSig",
"=",
"self",
".",
"qteApplet",
".",
"qteAppletSignature",
"(",
")",
"msg",
"=",
"(",
"'Macro <b>{}</b> (called from the <b>{}</b> applet'",
"' with ID <b>{}</b>) did not execute properly.'",
")",
"msg",
"=",
"msg",
".",
"format",
"(",
"self",
".",
"qteMacroName",
"(",
")",
",",
"appSig",
",",
"appID",
")",
"if",
"isinstance",
"(",
"err",
",",
"QtmacsArgumentError",
")",
":",
"msg",
"+=",
"'<br/>'",
"+",
"str",
"(",
"err",
")",
"# Irrespective of the error, log it, enable macro",
"# processing (in case it got disabled), and trigger the",
"# error signal.",
"self",
".",
"qteMain",
".",
"qteEnableMacroProcessing",
"(",
")",
"self",
".",
"qteMain",
".",
"qtesigMacroError",
".",
"emit",
"(",
"msgObj",
")",
"self",
".",
"qteLogger",
".",
"exception",
"(",
"msg",
",",
"exc_info",
"=",
"True",
",",
"stack_info",
"=",
"True",
")"
] | This method is called by Qtmacs to prepare the macro for
execution.
It is probably a bad idea to overload this method as it only
administrates the macro execution and calls the ``qteRun``
method (which *should* be overloaded by the macro programmer
in order for the macro to do something).
|Args|
* **None**
|Returns|
* **None**
|Raises|
* **None** | [
"This",
"method",
"is",
"called",
"by",
"Qtmacs",
"to",
"prepare",
"the",
"macro",
"for",
"execution",
"."
] | 36253b082b82590f183fe154b053eb3a1e741be2 | https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/base_macro.py#L418-L469 | train |
weijia/djangoautoconf | djangoautoconf/class_based_views/detail_with_inline_view.py | all_valid | def all_valid(formsets):
"""Returns true if every formset in formsets is valid."""
valid = True
for formset in formsets:
if not formset.is_valid():
valid = False
return valid | python | def all_valid(formsets):
"""Returns true if every formset in formsets is valid."""
valid = True
for formset in formsets:
if not formset.is_valid():
valid = False
return valid | [
"def",
"all_valid",
"(",
"formsets",
")",
":",
"valid",
"=",
"True",
"for",
"formset",
"in",
"formsets",
":",
"if",
"not",
"formset",
".",
"is_valid",
"(",
")",
":",
"valid",
"=",
"False",
"return",
"valid"
] | Returns true if every formset in formsets is valid. | [
"Returns",
"true",
"if",
"every",
"formset",
"in",
"formsets",
"is",
"valid",
"."
] | b7dbda2287ed8cb9de6d02cb3abaaa1c36b1ced0 | https://github.com/weijia/djangoautoconf/blob/b7dbda2287ed8cb9de6d02cb3abaaa1c36b1ced0/djangoautoconf/class_based_views/detail_with_inline_view.py#L7-L13 | train |
weijia/djangoautoconf | djangoautoconf/class_based_views/detail_with_inline_view.py | DetailWithInlineView.forms_valid | def forms_valid(self, inlines):
"""
If the form and formsets are valid, save the associated models.
"""
for formset in inlines:
formset.save()
return HttpResponseRedirect(self.get_success_url()) | python | def forms_valid(self, inlines):
"""
If the form and formsets are valid, save the associated models.
"""
for formset in inlines:
formset.save()
return HttpResponseRedirect(self.get_success_url()) | [
"def",
"forms_valid",
"(",
"self",
",",
"inlines",
")",
":",
"for",
"formset",
"in",
"inlines",
":",
"formset",
".",
"save",
"(",
")",
"return",
"HttpResponseRedirect",
"(",
"self",
".",
"get_success_url",
"(",
")",
")"
] | If the form and formsets are valid, save the associated models. | [
"If",
"the",
"form",
"and",
"formsets",
"are",
"valid",
"save",
"the",
"associated",
"models",
"."
] | b7dbda2287ed8cb9de6d02cb3abaaa1c36b1ced0 | https://github.com/weijia/djangoautoconf/blob/b7dbda2287ed8cb9de6d02cb3abaaa1c36b1ced0/djangoautoconf/class_based_views/detail_with_inline_view.py#L34-L40 | train |
weijia/djangoautoconf | djangoautoconf/class_based_views/detail_with_inline_view.py | DetailWithInlineView.post | def post(self, request, *args, **kwargs):
"""
Handles POST requests, instantiating a form and formset instances with the passed
POST variables and then checked for validity.
"""
self.object = self.get_object()
self.get_context_data()
inlines = self.construct_inlines()
if all_valid(inlines):
return self.forms_valid(inlines)
return self.forms_invalid(inlines) | python | def post(self, request, *args, **kwargs):
"""
Handles POST requests, instantiating a form and formset instances with the passed
POST variables and then checked for validity.
"""
self.object = self.get_object()
self.get_context_data()
inlines = self.construct_inlines()
if all_valid(inlines):
return self.forms_valid(inlines)
return self.forms_invalid(inlines) | [
"def",
"post",
"(",
"self",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"object",
"=",
"self",
".",
"get_object",
"(",
")",
"self",
".",
"get_context_data",
"(",
")",
"inlines",
"=",
"self",
".",
"construct_inlines",
"(",
")",
"if",
"all_valid",
"(",
"inlines",
")",
":",
"return",
"self",
".",
"forms_valid",
"(",
"inlines",
")",
"return",
"self",
".",
"forms_invalid",
"(",
"inlines",
")"
] | Handles POST requests, instantiating a form and formset instances with the passed
POST variables and then checked for validity. | [
"Handles",
"POST",
"requests",
"instantiating",
"a",
"form",
"and",
"formset",
"instances",
"with",
"the",
"passed",
"POST",
"variables",
"and",
"then",
"checked",
"for",
"validity",
"."
] | b7dbda2287ed8cb9de6d02cb3abaaa1c36b1ced0 | https://github.com/weijia/djangoautoconf/blob/b7dbda2287ed8cb9de6d02cb3abaaa1c36b1ced0/djangoautoconf/class_based_views/detail_with_inline_view.py#L60-L71 | train |
weijia/djangoautoconf | djangoautoconf/class_based_views/detail_with_inline_view.py | DetailWithInlineView.get_success_url | def get_success_url(self):
"""
Returns the supplied success URL.
"""
if self.success_url:
# Forcing possible reverse_lazy evaluation
url = force_text(self.success_url)
else:
raise ImproperlyConfigured(
"No URL to redirect to. Provide a success_url.")
return url | python | def get_success_url(self):
"""
Returns the supplied success URL.
"""
if self.success_url:
# Forcing possible reverse_lazy evaluation
url = force_text(self.success_url)
else:
raise ImproperlyConfigured(
"No URL to redirect to. Provide a success_url.")
return url | [
"def",
"get_success_url",
"(",
"self",
")",
":",
"if",
"self",
".",
"success_url",
":",
"# Forcing possible reverse_lazy evaluation",
"url",
"=",
"force_text",
"(",
"self",
".",
"success_url",
")",
"else",
":",
"raise",
"ImproperlyConfigured",
"(",
"\"No URL to redirect to. Provide a success_url.\"",
")",
"return",
"url"
] | Returns the supplied success URL. | [
"Returns",
"the",
"supplied",
"success",
"URL",
"."
] | b7dbda2287ed8cb9de6d02cb3abaaa1c36b1ced0 | https://github.com/weijia/djangoautoconf/blob/b7dbda2287ed8cb9de6d02cb3abaaa1c36b1ced0/djangoautoconf/class_based_views/detail_with_inline_view.py#L78-L88 | train |
olitheolix/qtmacs | qtmacs/applets/statusbar.py | StatusBar.displayStatusMessage | def displayStatusMessage(self, msgObj):
"""
Display the last status message and partially completed key sequences.
|Args|
* ``msgObj`` (**QtmacsMessage**): the data supplied by the hook.
|Returns|
* **None**
|Raises|
* **None**
"""
# Ensure the message ends with a newline character.
msg = msgObj.data
if not msg.endswith('\n'):
msg = msg + '\n'
# Display the message in the status field.
self.qteLabel.setText(msg) | python | def displayStatusMessage(self, msgObj):
"""
Display the last status message and partially completed key sequences.
|Args|
* ``msgObj`` (**QtmacsMessage**): the data supplied by the hook.
|Returns|
* **None**
|Raises|
* **None**
"""
# Ensure the message ends with a newline character.
msg = msgObj.data
if not msg.endswith('\n'):
msg = msg + '\n'
# Display the message in the status field.
self.qteLabel.setText(msg) | [
"def",
"displayStatusMessage",
"(",
"self",
",",
"msgObj",
")",
":",
"# Ensure the message ends with a newline character.",
"msg",
"=",
"msgObj",
".",
"data",
"if",
"not",
"msg",
".",
"endswith",
"(",
"'\\n'",
")",
":",
"msg",
"=",
"msg",
"+",
"'\\n'",
"# Display the message in the status field.",
"self",
".",
"qteLabel",
".",
"setText",
"(",
"msg",
")"
] | Display the last status message and partially completed key sequences.
|Args|
* ``msgObj`` (**QtmacsMessage**): the data supplied by the hook.
|Returns|
* **None**
|Raises|
* **None** | [
"Display",
"the",
"last",
"status",
"message",
"and",
"partially",
"completed",
"key",
"sequences",
"."
] | 36253b082b82590f183fe154b053eb3a1e741be2 | https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/applets/statusbar.py#L78-L101 | train |
olitheolix/qtmacs | qtmacs/applets/logviewer.py | LogViewer.qteUpdateLogSlot | def qteUpdateLogSlot(self):
"""
Fetch and display the next batch of log messages.
"""
# Fetch all log records that have arrived since the last
# fetch() call and update the record counter.
log = self.logHandler.fetch(start=self.qteLogCnt)
self.qteLogCnt += len(log)
# Return immediately if no log message is available (this case
# should be impossible).
if not len(log):
return
# Remove all duplicate entries and count their repetitions.
log_pruned = []
last_entry = log[0]
num_rep = -1
for cur_entry in log:
# If the previous log message is identical to the current
# one increase its repetition counter. If the two log
# messages differ, add the last message to the output log
# and reset the repetition counter.
if last_entry.msg == cur_entry.msg:
num_rep += 1
else:
log_pruned.append([last_entry, num_rep])
num_rep = 0
last_entry = cur_entry
# The very last entry must be added by hand.
log_pruned.append([cur_entry, num_rep])
# Format the log entries (eg. color coding etc.)
log_formatted = ""
for cur_entry in log_pruned:
log_formatted += self.qteFormatMessage(cur_entry[0], cur_entry[1])
log_formatted + '\n'
# Insert the formatted text all at once as calls to insertHtml
# are expensive.
self.qteText.insertHtml(log_formatted)
self.qteMoveToEndOfBuffer()
# If the log contained an error (or something else of interest
# to the user) then switch to the messages buffer (ie. switch
# to this very applet).
if self.qteAutoActivate:
self.qteAutoActivate = False
self.qteMain.qteMakeAppletActive(self) | python | def qteUpdateLogSlot(self):
"""
Fetch and display the next batch of log messages.
"""
# Fetch all log records that have arrived since the last
# fetch() call and update the record counter.
log = self.logHandler.fetch(start=self.qteLogCnt)
self.qteLogCnt += len(log)
# Return immediately if no log message is available (this case
# should be impossible).
if not len(log):
return
# Remove all duplicate entries and count their repetitions.
log_pruned = []
last_entry = log[0]
num_rep = -1
for cur_entry in log:
# If the previous log message is identical to the current
# one increase its repetition counter. If the two log
# messages differ, add the last message to the output log
# and reset the repetition counter.
if last_entry.msg == cur_entry.msg:
num_rep += 1
else:
log_pruned.append([last_entry, num_rep])
num_rep = 0
last_entry = cur_entry
# The very last entry must be added by hand.
log_pruned.append([cur_entry, num_rep])
# Format the log entries (eg. color coding etc.)
log_formatted = ""
for cur_entry in log_pruned:
log_formatted += self.qteFormatMessage(cur_entry[0], cur_entry[1])
log_formatted + '\n'
# Insert the formatted text all at once as calls to insertHtml
# are expensive.
self.qteText.insertHtml(log_formatted)
self.qteMoveToEndOfBuffer()
# If the log contained an error (or something else of interest
# to the user) then switch to the messages buffer (ie. switch
# to this very applet).
if self.qteAutoActivate:
self.qteAutoActivate = False
self.qteMain.qteMakeAppletActive(self) | [
"def",
"qteUpdateLogSlot",
"(",
"self",
")",
":",
"# Fetch all log records that have arrived since the last",
"# fetch() call and update the record counter.",
"log",
"=",
"self",
".",
"logHandler",
".",
"fetch",
"(",
"start",
"=",
"self",
".",
"qteLogCnt",
")",
"self",
".",
"qteLogCnt",
"+=",
"len",
"(",
"log",
")",
"# Return immediately if no log message is available (this case",
"# should be impossible).",
"if",
"not",
"len",
"(",
"log",
")",
":",
"return",
"# Remove all duplicate entries and count their repetitions.",
"log_pruned",
"=",
"[",
"]",
"last_entry",
"=",
"log",
"[",
"0",
"]",
"num_rep",
"=",
"-",
"1",
"for",
"cur_entry",
"in",
"log",
":",
"# If the previous log message is identical to the current",
"# one increase its repetition counter. If the two log",
"# messages differ, add the last message to the output log",
"# and reset the repetition counter.",
"if",
"last_entry",
".",
"msg",
"==",
"cur_entry",
".",
"msg",
":",
"num_rep",
"+=",
"1",
"else",
":",
"log_pruned",
".",
"append",
"(",
"[",
"last_entry",
",",
"num_rep",
"]",
")",
"num_rep",
"=",
"0",
"last_entry",
"=",
"cur_entry",
"# The very last entry must be added by hand.",
"log_pruned",
".",
"append",
"(",
"[",
"cur_entry",
",",
"num_rep",
"]",
")",
"# Format the log entries (eg. color coding etc.)",
"log_formatted",
"=",
"\"\"",
"for",
"cur_entry",
"in",
"log_pruned",
":",
"log_formatted",
"+=",
"self",
".",
"qteFormatMessage",
"(",
"cur_entry",
"[",
"0",
"]",
",",
"cur_entry",
"[",
"1",
"]",
")",
"log_formatted",
"+",
"'\\n'",
"# Insert the formatted text all at once as calls to insertHtml",
"# are expensive.",
"self",
".",
"qteText",
".",
"insertHtml",
"(",
"log_formatted",
")",
"self",
".",
"qteMoveToEndOfBuffer",
"(",
")",
"# If the log contained an error (or something else of interest",
"# to the user) then switch to the messages buffer (ie. switch",
"# to this very applet).",
"if",
"self",
".",
"qteAutoActivate",
":",
"self",
".",
"qteAutoActivate",
"=",
"False",
"self",
".",
"qteMain",
".",
"qteMakeAppletActive",
"(",
"self",
")"
] | Fetch and display the next batch of log messages. | [
"Fetch",
"and",
"display",
"the",
"next",
"batch",
"of",
"log",
"messages",
"."
] | 36253b082b82590f183fe154b053eb3a1e741be2 | https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/applets/logviewer.py#L196-L246 | train |
olitheolix/qtmacs | qtmacs/applets/logviewer.py | LogViewer.qteMoveToEndOfBuffer | def qteMoveToEndOfBuffer(self):
"""
Move cursor to the end of the buffer to facilitate auto
scrolling.
Technically, this is exactly the 'endOfBuffer' macro but to
avoid swamping Qtmacs with 'qteRunMacroStarted' messages to no
avail it was implemented here natively.
"""
tc = self.qteText.textCursor()
tc.movePosition(QtGui.QTextCursor.End)
self.qteText.setTextCursor(tc) | python | def qteMoveToEndOfBuffer(self):
"""
Move cursor to the end of the buffer to facilitate auto
scrolling.
Technically, this is exactly the 'endOfBuffer' macro but to
avoid swamping Qtmacs with 'qteRunMacroStarted' messages to no
avail it was implemented here natively.
"""
tc = self.qteText.textCursor()
tc.movePosition(QtGui.QTextCursor.End)
self.qteText.setTextCursor(tc) | [
"def",
"qteMoveToEndOfBuffer",
"(",
"self",
")",
":",
"tc",
"=",
"self",
".",
"qteText",
".",
"textCursor",
"(",
")",
"tc",
".",
"movePosition",
"(",
"QtGui",
".",
"QTextCursor",
".",
"End",
")",
"self",
".",
"qteText",
".",
"setTextCursor",
"(",
"tc",
")"
] | Move cursor to the end of the buffer to facilitate auto
scrolling.
Technically, this is exactly the 'endOfBuffer' macro but to
avoid swamping Qtmacs with 'qteRunMacroStarted' messages to no
avail it was implemented here natively. | [
"Move",
"cursor",
"to",
"the",
"end",
"of",
"the",
"buffer",
"to",
"facilitate",
"auto",
"scrolling",
"."
] | 36253b082b82590f183fe154b053eb3a1e741be2 | https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/applets/logviewer.py#L248-L259 | train |
blockstack-packages/blockstack-profiles-py | blockstack_profiles/token_signing.py | sign_token_records | def sign_token_records(profile_components, parent_private_key,
signing_algorithm="ES256K"):
""" Function for iterating through a list of profile components and
signing separate individual profile tokens.
"""
if signing_algorithm != "ES256K":
raise ValueError("Signing algorithm not supported")
token_records = []
for profile_component in profile_components:
private_key = ECPrivateKey(parent_private_key)
public_key = private_key.public_key()
subject = {
"publicKey": public_key.to_hex()
}
token = sign_token(profile_component, private_key.to_hex(), subject,
signing_algorithm=signing_algorithm)
token_record = wrap_token(token)
token_record["parentPublicKey"] = public_key.to_hex()
token_records.append(token_record)
return token_records | python | def sign_token_records(profile_components, parent_private_key,
signing_algorithm="ES256K"):
""" Function for iterating through a list of profile components and
signing separate individual profile tokens.
"""
if signing_algorithm != "ES256K":
raise ValueError("Signing algorithm not supported")
token_records = []
for profile_component in profile_components:
private_key = ECPrivateKey(parent_private_key)
public_key = private_key.public_key()
subject = {
"publicKey": public_key.to_hex()
}
token = sign_token(profile_component, private_key.to_hex(), subject,
signing_algorithm=signing_algorithm)
token_record = wrap_token(token)
token_record["parentPublicKey"] = public_key.to_hex()
token_records.append(token_record)
return token_records | [
"def",
"sign_token_records",
"(",
"profile_components",
",",
"parent_private_key",
",",
"signing_algorithm",
"=",
"\"ES256K\"",
")",
":",
"if",
"signing_algorithm",
"!=",
"\"ES256K\"",
":",
"raise",
"ValueError",
"(",
"\"Signing algorithm not supported\"",
")",
"token_records",
"=",
"[",
"]",
"for",
"profile_component",
"in",
"profile_components",
":",
"private_key",
"=",
"ECPrivateKey",
"(",
"parent_private_key",
")",
"public_key",
"=",
"private_key",
".",
"public_key",
"(",
")",
"subject",
"=",
"{",
"\"publicKey\"",
":",
"public_key",
".",
"to_hex",
"(",
")",
"}",
"token",
"=",
"sign_token",
"(",
"profile_component",
",",
"private_key",
".",
"to_hex",
"(",
")",
",",
"subject",
",",
"signing_algorithm",
"=",
"signing_algorithm",
")",
"token_record",
"=",
"wrap_token",
"(",
"token",
")",
"token_record",
"[",
"\"parentPublicKey\"",
"]",
"=",
"public_key",
".",
"to_hex",
"(",
")",
"token_records",
".",
"append",
"(",
"token_record",
")",
"return",
"token_records"
] | Function for iterating through a list of profile components and
signing separate individual profile tokens. | [
"Function",
"for",
"iterating",
"through",
"a",
"list",
"of",
"profile",
"components",
"and",
"signing",
"separate",
"individual",
"profile",
"tokens",
"."
] | 103783798df78cf0f007801e79ec6298f00b2817 | https://github.com/blockstack-packages/blockstack-profiles-py/blob/103783798df78cf0f007801e79ec6298f00b2817/blockstack_profiles/token_signing.py#L46-L69 | train |
projectshift/shift-schema | shiftschema/translator.py | Translator.normalize_locale | def normalize_locale(locale):
"""
Normalize locale
Extracts language code from passed in locale string to be used later
for dictionaries loading.
:param locale: string, locale (en, en_US)
:return: string, language code
"""
import re
match = re.match(r'^[a-z]+', locale.lower())
if match:
return match.group() | python | def normalize_locale(locale):
"""
Normalize locale
Extracts language code from passed in locale string to be used later
for dictionaries loading.
:param locale: string, locale (en, en_US)
:return: string, language code
"""
import re
match = re.match(r'^[a-z]+', locale.lower())
if match:
return match.group() | [
"def",
"normalize_locale",
"(",
"locale",
")",
":",
"import",
"re",
"match",
"=",
"re",
".",
"match",
"(",
"r'^[a-z]+'",
",",
"locale",
".",
"lower",
"(",
")",
")",
"if",
"match",
":",
"return",
"match",
".",
"group",
"(",
")"
] | Normalize locale
Extracts language code from passed in locale string to be used later
for dictionaries loading.
:param locale: string, locale (en, en_US)
:return: string, language code | [
"Normalize",
"locale",
"Extracts",
"language",
"code",
"from",
"passed",
"in",
"locale",
"string",
"to",
"be",
"used",
"later",
"for",
"dictionaries",
"loading",
"."
] | 07787b540d3369bb37217ffbfbe629118edaf0eb | https://github.com/projectshift/shift-schema/blob/07787b540d3369bb37217ffbfbe629118edaf0eb/shiftschema/translator.py#L22-L34 | train |
projectshift/shift-schema | shiftschema/translator.py | Translator.get_translations | def get_translations(self, locale):
"""
Get translation dictionary
Returns a dictionary for locale or raises an exception if such can't
be located. If a dictionary for locale was previously loaded returns
that, otherwise goes through registered locations and merges any
found custom dictionaries with defaults.
:param locale: str, locale to load translations
:return: dict, translations dictionary
"""
locale = self.normalize_locale(locale)
if locale in self.translations:
return self.translations[locale]
translations = {}
for path in self.dirs:
file = os.path.join(path, '{}.py'.format(locale))
if not os.path.isfile(file):
continue
loader = SourceFileLoader(locale, file)
locale_dict = loader.load_module()
if not hasattr(locale_dict, 'translations'):
continue
language = getattr(locale_dict, 'translations')
if translations:
translations = language
else:
merged = dict(translations.items() | language.items())
translations = merged
if translations:
self.translations[locale] = translations
return translations
err = 'No translations found for locale [{}]'
raise NoTranslations(err.format(locale)) | python | def get_translations(self, locale):
"""
Get translation dictionary
Returns a dictionary for locale or raises an exception if such can't
be located. If a dictionary for locale was previously loaded returns
that, otherwise goes through registered locations and merges any
found custom dictionaries with defaults.
:param locale: str, locale to load translations
:return: dict, translations dictionary
"""
locale = self.normalize_locale(locale)
if locale in self.translations:
return self.translations[locale]
translations = {}
for path in self.dirs:
file = os.path.join(path, '{}.py'.format(locale))
if not os.path.isfile(file):
continue
loader = SourceFileLoader(locale, file)
locale_dict = loader.load_module()
if not hasattr(locale_dict, 'translations'):
continue
language = getattr(locale_dict, 'translations')
if translations:
translations = language
else:
merged = dict(translations.items() | language.items())
translations = merged
if translations:
self.translations[locale] = translations
return translations
err = 'No translations found for locale [{}]'
raise NoTranslations(err.format(locale)) | [
"def",
"get_translations",
"(",
"self",
",",
"locale",
")",
":",
"locale",
"=",
"self",
".",
"normalize_locale",
"(",
"locale",
")",
"if",
"locale",
"in",
"self",
".",
"translations",
":",
"return",
"self",
".",
"translations",
"[",
"locale",
"]",
"translations",
"=",
"{",
"}",
"for",
"path",
"in",
"self",
".",
"dirs",
":",
"file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"'{}.py'",
".",
"format",
"(",
"locale",
")",
")",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"file",
")",
":",
"continue",
"loader",
"=",
"SourceFileLoader",
"(",
"locale",
",",
"file",
")",
"locale_dict",
"=",
"loader",
".",
"load_module",
"(",
")",
"if",
"not",
"hasattr",
"(",
"locale_dict",
",",
"'translations'",
")",
":",
"continue",
"language",
"=",
"getattr",
"(",
"locale_dict",
",",
"'translations'",
")",
"if",
"translations",
":",
"translations",
"=",
"language",
"else",
":",
"merged",
"=",
"dict",
"(",
"translations",
".",
"items",
"(",
")",
"|",
"language",
".",
"items",
"(",
")",
")",
"translations",
"=",
"merged",
"if",
"translations",
":",
"self",
".",
"translations",
"[",
"locale",
"]",
"=",
"translations",
"return",
"translations",
"err",
"=",
"'No translations found for locale [{}]'",
"raise",
"NoTranslations",
"(",
"err",
".",
"format",
"(",
"locale",
")",
")"
] | Get translation dictionary
Returns a dictionary for locale or raises an exception if such can't
be located. If a dictionary for locale was previously loaded returns
that, otherwise goes through registered locations and merges any
found custom dictionaries with defaults.
:param locale: str, locale to load translations
:return: dict, translations dictionary | [
"Get",
"translation",
"dictionary",
"Returns",
"a",
"dictionary",
"for",
"locale",
"or",
"raises",
"an",
"exception",
"if",
"such",
"can",
"t",
"be",
"located",
".",
"If",
"a",
"dictionary",
"for",
"locale",
"was",
"previously",
"loaded",
"returns",
"that",
"otherwise",
"goes",
"through",
"registered",
"locations",
"and",
"merges",
"any",
"found",
"custom",
"dictionaries",
"with",
"defaults",
"."
] | 07787b540d3369bb37217ffbfbe629118edaf0eb | https://github.com/projectshift/shift-schema/blob/07787b540d3369bb37217ffbfbe629118edaf0eb/shiftschema/translator.py#L51-L89 | train |
projectshift/shift-schema | shiftschema/translator.py | Translator.translate | def translate(self, message, locale):
"""
Translate
Translates a message to the given locale language. Will return original
message if no translation exists for the message.
:param message: str, a message to translate
:param locale: str, locale or language code
:return: str, translated (if possible)
"""
translations = self.get_translations(locale)
if message in translations:
return translations[message]
# return untranslated
return message | python | def translate(self, message, locale):
"""
Translate
Translates a message to the given locale language. Will return original
message if no translation exists for the message.
:param message: str, a message to translate
:param locale: str, locale or language code
:return: str, translated (if possible)
"""
translations = self.get_translations(locale)
if message in translations:
return translations[message]
# return untranslated
return message | [
"def",
"translate",
"(",
"self",
",",
"message",
",",
"locale",
")",
":",
"translations",
"=",
"self",
".",
"get_translations",
"(",
"locale",
")",
"if",
"message",
"in",
"translations",
":",
"return",
"translations",
"[",
"message",
"]",
"# return untranslated",
"return",
"message"
] | Translate
Translates a message to the given locale language. Will return original
message if no translation exists for the message.
:param message: str, a message to translate
:param locale: str, locale or language code
:return: str, translated (if possible) | [
"Translate",
"Translates",
"a",
"message",
"to",
"the",
"given",
"locale",
"language",
".",
"Will",
"return",
"original",
"message",
"if",
"no",
"translation",
"exists",
"for",
"the",
"message",
"."
] | 07787b540d3369bb37217ffbfbe629118edaf0eb | https://github.com/projectshift/shift-schema/blob/07787b540d3369bb37217ffbfbe629118edaf0eb/shiftschema/translator.py#L93-L108 | train |
casouri/launchdman | launchdman/__init__.py | flatten | def flatten(l):
'''Flatten a multi-deminision list and return a iterable
Note that dict and str will not be expanded, instead, they will be kept as a single element.
Args:
l (list): The list needs to be flattened
Returns:
A iterable of flattened list. To have a list instead use ``list(flatten(l))``
'''
for el in l:
# I don;t want dict to be flattened
if isinstance(el, Iterable) and not isinstance(
el, (str, bytes)) and not isinstance(el, dict):
yield from flatten(el)
else:
yield el | python | def flatten(l):
'''Flatten a multi-deminision list and return a iterable
Note that dict and str will not be expanded, instead, they will be kept as a single element.
Args:
l (list): The list needs to be flattened
Returns:
A iterable of flattened list. To have a list instead use ``list(flatten(l))``
'''
for el in l:
# I don;t want dict to be flattened
if isinstance(el, Iterable) and not isinstance(
el, (str, bytes)) and not isinstance(el, dict):
yield from flatten(el)
else:
yield el | [
"def",
"flatten",
"(",
"l",
")",
":",
"for",
"el",
"in",
"l",
":",
"# I don;t want dict to be flattened",
"if",
"isinstance",
"(",
"el",
",",
"Iterable",
")",
"and",
"not",
"isinstance",
"(",
"el",
",",
"(",
"str",
",",
"bytes",
")",
")",
"and",
"not",
"isinstance",
"(",
"el",
",",
"dict",
")",
":",
"yield",
"from",
"flatten",
"(",
"el",
")",
"else",
":",
"yield",
"el"
] | Flatten a multi-deminision list and return a iterable
Note that dict and str will not be expanded, instead, they will be kept as a single element.
Args:
l (list): The list needs to be flattened
Returns:
A iterable of flattened list. To have a list instead use ``list(flatten(l))`` | [
"Flatten",
"a",
"multi",
"-",
"deminision",
"list",
"and",
"return",
"a",
"iterable"
] | c83840e640cb075fab2534049f1e25fac6933c64 | https://github.com/casouri/launchdman/blob/c83840e640cb075fab2534049f1e25fac6933c64/launchdman/__init__.py#L33-L50 | train |
casouri/launchdman | launchdman/__init__.py | crossCombine | def crossCombine(l):
''' Taken a list of lists, returns a big list of lists contain all the possibilities of elements of sublist combining together.
It is basically a Combinatorics of list. For example:
>>> crossCombine([[a,a1,a2,...], [b,b1,b2,...]])
>>> [[a,b], [a,b1], [a,b2], [a1,b], [a1,b1], [a1, b2], [a2,b], [a2,b1], [a2,b2], ...]
For using in StartCalendarInterval, the syntax of ``l`` is like below:
``l: [[dic of month], [dict of day]]``
such as:
``l: [[{'month': 1}, {'month': 2}], [{'day': 2}, {'day': 3}, {'day': 4}]]``
Args:
l (list[list]): the list of lists you want to crossCombine with.
Returns:
list: crossCombined list
'''
resultList = []
firstList = l[0]
rest = l[1:]
if len(rest) == 0:
return firstList
for e in firstList:
for e1 in crossCombine(rest):
resultList.append(combinteDict(e, e1))
return resultList | python | def crossCombine(l):
''' Taken a list of lists, returns a big list of lists contain all the possibilities of elements of sublist combining together.
It is basically a Combinatorics of list. For example:
>>> crossCombine([[a,a1,a2,...], [b,b1,b2,...]])
>>> [[a,b], [a,b1], [a,b2], [a1,b], [a1,b1], [a1, b2], [a2,b], [a2,b1], [a2,b2], ...]
For using in StartCalendarInterval, the syntax of ``l`` is like below:
``l: [[dic of month], [dict of day]]``
such as:
``l: [[{'month': 1}, {'month': 2}], [{'day': 2}, {'day': 3}, {'day': 4}]]``
Args:
l (list[list]): the list of lists you want to crossCombine with.
Returns:
list: crossCombined list
'''
resultList = []
firstList = l[0]
rest = l[1:]
if len(rest) == 0:
return firstList
for e in firstList:
for e1 in crossCombine(rest):
resultList.append(combinteDict(e, e1))
return resultList | [
"def",
"crossCombine",
"(",
"l",
")",
":",
"resultList",
"=",
"[",
"]",
"firstList",
"=",
"l",
"[",
"0",
"]",
"rest",
"=",
"l",
"[",
"1",
":",
"]",
"if",
"len",
"(",
"rest",
")",
"==",
"0",
":",
"return",
"firstList",
"for",
"e",
"in",
"firstList",
":",
"for",
"e1",
"in",
"crossCombine",
"(",
"rest",
")",
":",
"resultList",
".",
"append",
"(",
"combinteDict",
"(",
"e",
",",
"e1",
")",
")",
"return",
"resultList"
] | Taken a list of lists, returns a big list of lists contain all the possibilities of elements of sublist combining together.
It is basically a Combinatorics of list. For example:
>>> crossCombine([[a,a1,a2,...], [b,b1,b2,...]])
>>> [[a,b], [a,b1], [a,b2], [a1,b], [a1,b1], [a1, b2], [a2,b], [a2,b1], [a2,b2], ...]
For using in StartCalendarInterval, the syntax of ``l`` is like below:
``l: [[dic of month], [dict of day]]``
such as:
``l: [[{'month': 1}, {'month': 2}], [{'day': 2}, {'day': 3}, {'day': 4}]]``
Args:
l (list[list]): the list of lists you want to crossCombine with.
Returns:
list: crossCombined list | [
"Taken",
"a",
"list",
"of",
"lists",
"returns",
"a",
"big",
"list",
"of",
"lists",
"contain",
"all",
"the",
"possibilities",
"of",
"elements",
"of",
"sublist",
"combining",
"together",
"."
] | c83840e640cb075fab2534049f1e25fac6933c64 | https://github.com/casouri/launchdman/blob/c83840e640cb075fab2534049f1e25fac6933c64/launchdman/__init__.py#L53-L82 | train |
casouri/launchdman | launchdman/__init__.py | combine | def combine(a1, a2):
''' Combine to argument into a single flat list
It is used when you are not sure whether arguments are lists but want to combine them into one flat list
Args:
a1: list or other thing
a2: list or other thing
Returns:
list: a flat list contain a1 and a2
'''
if not isinstance(a1, list):
a1 = [a1]
if not isinstance(a2, list):
a2 = [a2]
return a1 + a2 | python | def combine(a1, a2):
''' Combine to argument into a single flat list
It is used when you are not sure whether arguments are lists but want to combine them into one flat list
Args:
a1: list or other thing
a2: list or other thing
Returns:
list: a flat list contain a1 and a2
'''
if not isinstance(a1, list):
a1 = [a1]
if not isinstance(a2, list):
a2 = [a2]
return a1 + a2 | [
"def",
"combine",
"(",
"a1",
",",
"a2",
")",
":",
"if",
"not",
"isinstance",
"(",
"a1",
",",
"list",
")",
":",
"a1",
"=",
"[",
"a1",
"]",
"if",
"not",
"isinstance",
"(",
"a2",
",",
"list",
")",
":",
"a2",
"=",
"[",
"a2",
"]",
"return",
"a1",
"+",
"a2"
] | Combine to argument into a single flat list
It is used when you are not sure whether arguments are lists but want to combine them into one flat list
Args:
a1: list or other thing
a2: list or other thing
Returns:
list: a flat list contain a1 and a2 | [
"Combine",
"to",
"argument",
"into",
"a",
"single",
"flat",
"list"
] | c83840e640cb075fab2534049f1e25fac6933c64 | https://github.com/casouri/launchdman/blob/c83840e640cb075fab2534049f1e25fac6933c64/launchdman/__init__.py#L85-L101 | train |
casouri/launchdman | launchdman/__init__.py | singleOrPair | def singleOrPair(obj):
'''Chech an object is single or pair or neither.
Of course,, all pairs are single, so what the function is really detecting is whether an object is only single or at the same time a pair.
Args:
obj (object): Literally anything.
Returns:
str: 'Single', or 'Pair', or 'Neither'
'''
if len(list(obj.__class__.__mro__)) <= 2:
return 'Neither'
else:
# Pair check comes first for Pair is a subclass of Single
if ancestorJr(obj) is Pair:
return 'Pair'
elif ancestor(obj) is Single:
return 'Single'
else:
return 'Neither' | python | def singleOrPair(obj):
'''Chech an object is single or pair or neither.
Of course,, all pairs are single, so what the function is really detecting is whether an object is only single or at the same time a pair.
Args:
obj (object): Literally anything.
Returns:
str: 'Single', or 'Pair', or 'Neither'
'''
if len(list(obj.__class__.__mro__)) <= 2:
return 'Neither'
else:
# Pair check comes first for Pair is a subclass of Single
if ancestorJr(obj) is Pair:
return 'Pair'
elif ancestor(obj) is Single:
return 'Single'
else:
return 'Neither' | [
"def",
"singleOrPair",
"(",
"obj",
")",
":",
"if",
"len",
"(",
"list",
"(",
"obj",
".",
"__class__",
".",
"__mro__",
")",
")",
"<=",
"2",
":",
"return",
"'Neither'",
"else",
":",
"# Pair check comes first for Pair is a subclass of Single",
"if",
"ancestorJr",
"(",
"obj",
")",
"is",
"Pair",
":",
"return",
"'Pair'",
"elif",
"ancestor",
"(",
"obj",
")",
"is",
"Single",
":",
"return",
"'Single'",
"else",
":",
"return",
"'Neither'"
] | Chech an object is single or pair or neither.
Of course,, all pairs are single, so what the function is really detecting is whether an object is only single or at the same time a pair.
Args:
obj (object): Literally anything.
Returns:
str: 'Single', or 'Pair', or 'Neither' | [
"Chech",
"an",
"object",
"is",
"single",
"or",
"pair",
"or",
"neither",
"."
] | c83840e640cb075fab2534049f1e25fac6933c64 | https://github.com/casouri/launchdman/blob/c83840e640cb075fab2534049f1e25fac6933c64/launchdman/__init__.py#L146-L166 | train |
casouri/launchdman | launchdman/__init__.py | removeEverything | def removeEverything(toBeRemoved, l):
'''Remove every instance that matches the input from a list
Match with ==, operation, which can be defined in __eq__.
Args:
tobeRemoved (object): the same object you want to remove from the list.
l (list): the llist you want to remove stuff from.
'''
successful = True
while successful:
try:
# list.remove will remove item if equal,
# which is evaluated by __eq__
l.remove(toBeRemoved)
except:
successful = False | python | def removeEverything(toBeRemoved, l):
'''Remove every instance that matches the input from a list
Match with ==, operation, which can be defined in __eq__.
Args:
tobeRemoved (object): the same object you want to remove from the list.
l (list): the llist you want to remove stuff from.
'''
successful = True
while successful:
try:
# list.remove will remove item if equal,
# which is evaluated by __eq__
l.remove(toBeRemoved)
except:
successful = False | [
"def",
"removeEverything",
"(",
"toBeRemoved",
",",
"l",
")",
":",
"successful",
"=",
"True",
"while",
"successful",
":",
"try",
":",
"# list.remove will remove item if equal,",
"# which is evaluated by __eq__",
"l",
".",
"remove",
"(",
"toBeRemoved",
")",
"except",
":",
"successful",
"=",
"False"
] | Remove every instance that matches the input from a list
Match with ==, operation, which can be defined in __eq__.
Args:
tobeRemoved (object): the same object you want to remove from the list.
l (list): the llist you want to remove stuff from. | [
"Remove",
"every",
"instance",
"that",
"matches",
"the",
"input",
"from",
"a",
"list"
] | c83840e640cb075fab2534049f1e25fac6933c64 | https://github.com/casouri/launchdman/blob/c83840e640cb075fab2534049f1e25fac6933c64/launchdman/__init__.py#L169-L185 | train |
casouri/launchdman | launchdman/__init__.py | Single.add | def add(self, *value):
'''convert value and add to self.value
Subclass must overwrite this method.
Subclass are responsible of creating whatever single instance it need from its ``add(*value)`` and call ``_add()`` to add them to ``self.value``
Args:
*value: the value to be added
'''
flattenedValueList = list(flatten(value))
return self._add(flattenedValueList, self.value) | python | def add(self, *value):
'''convert value and add to self.value
Subclass must overwrite this method.
Subclass are responsible of creating whatever single instance it need from its ``add(*value)`` and call ``_add()`` to add them to ``self.value``
Args:
*value: the value to be added
'''
flattenedValueList = list(flatten(value))
return self._add(flattenedValueList, self.value) | [
"def",
"add",
"(",
"self",
",",
"*",
"value",
")",
":",
"flattenedValueList",
"=",
"list",
"(",
"flatten",
"(",
"value",
")",
")",
"return",
"self",
".",
"_add",
"(",
"flattenedValueList",
",",
"self",
".",
"value",
")"
] | convert value and add to self.value
Subclass must overwrite this method.
Subclass are responsible of creating whatever single instance it need from its ``add(*value)`` and call ``_add()`` to add them to ``self.value``
Args:
*value: the value to be added | [
"convert",
"value",
"and",
"add",
"to",
"self",
".",
"value"
] | c83840e640cb075fab2534049f1e25fac6933c64 | https://github.com/casouri/launchdman/blob/c83840e640cb075fab2534049f1e25fac6933c64/launchdman/__init__.py#L309-L319 | train |
casouri/launchdman | launchdman/__init__.py | Single._remove | def _remove(self, removeList, selfValue):
'''Remove elements from a list by matching the elements in the other list.
This method only looks inside current instance's value, not recursive.
There is no need for a recursive one anyway.
Match by == operation.
Args:
removeList (list): The list of matching elements.
selfValue (list): The list you remove value from. Usually ``self.value``
'''
for removeValue in removeList:
print(removeValue, removeList)
# if removeValue equal to selfValue, remove
removeEverything(removeValue, selfValue) | python | def _remove(self, removeList, selfValue):
'''Remove elements from a list by matching the elements in the other list.
This method only looks inside current instance's value, not recursive.
There is no need for a recursive one anyway.
Match by == operation.
Args:
removeList (list): The list of matching elements.
selfValue (list): The list you remove value from. Usually ``self.value``
'''
for removeValue in removeList:
print(removeValue, removeList)
# if removeValue equal to selfValue, remove
removeEverything(removeValue, selfValue) | [
"def",
"_remove",
"(",
"self",
",",
"removeList",
",",
"selfValue",
")",
":",
"for",
"removeValue",
"in",
"removeList",
":",
"print",
"(",
"removeValue",
",",
"removeList",
")",
"# if removeValue equal to selfValue, remove",
"removeEverything",
"(",
"removeValue",
",",
"selfValue",
")"
] | Remove elements from a list by matching the elements in the other list.
This method only looks inside current instance's value, not recursive.
There is no need for a recursive one anyway.
Match by == operation.
Args:
removeList (list): The list of matching elements.
selfValue (list): The list you remove value from. Usually ``self.value`` | [
"Remove",
"elements",
"from",
"a",
"list",
"by",
"matching",
"the",
"elements",
"in",
"the",
"other",
"list",
"."
] | c83840e640cb075fab2534049f1e25fac6933c64 | https://github.com/casouri/launchdman/blob/c83840e640cb075fab2534049f1e25fac6933c64/launchdman/__init__.py#L321-L335 | train |
casouri/launchdman | launchdman/__init__.py | Single.remove | def remove(self, *l):
''' remove elements from self.value by matching.
Create the exactly same single you want to delete and pass it(them) in.
Normally this method needs to be overwrited by subclass. It only looks inside current instance's value, not recursive. There is no need for a recursive one anyway.
Args:
*l: a single element, a bunch of element seperated by comma, or a list of elements, or any combination. Element is what you match with.
'''
removeList = list(flatten(l))
self._remove(removeList, self.value) | python | def remove(self, *l):
''' remove elements from self.value by matching.
Create the exactly same single you want to delete and pass it(them) in.
Normally this method needs to be overwrited by subclass. It only looks inside current instance's value, not recursive. There is no need for a recursive one anyway.
Args:
*l: a single element, a bunch of element seperated by comma, or a list of elements, or any combination. Element is what you match with.
'''
removeList = list(flatten(l))
self._remove(removeList, self.value) | [
"def",
"remove",
"(",
"self",
",",
"*",
"l",
")",
":",
"removeList",
"=",
"list",
"(",
"flatten",
"(",
"l",
")",
")",
"self",
".",
"_remove",
"(",
"removeList",
",",
"self",
".",
"value",
")"
] | remove elements from self.value by matching.
Create the exactly same single you want to delete and pass it(them) in.
Normally this method needs to be overwrited by subclass. It only looks inside current instance's value, not recursive. There is no need for a recursive one anyway.
Args:
*l: a single element, a bunch of element seperated by comma, or a list of elements, or any combination. Element is what you match with. | [
"remove",
"elements",
"from",
"self",
".",
"value",
"by",
"matching",
"."
] | c83840e640cb075fab2534049f1e25fac6933c64 | https://github.com/casouri/launchdman/blob/c83840e640cb075fab2534049f1e25fac6933c64/launchdman/__init__.py#L337-L347 | train |
casouri/launchdman | launchdman/__init__.py | Job.write | def write(self):
'''Write the job to the corresponding plist.'''
with open(self.me, 'w') as f:
f.write(self.printMe(self.tag, self.value)) | python | def write(self):
'''Write the job to the corresponding plist.'''
with open(self.me, 'w') as f:
f.write(self.printMe(self.tag, self.value)) | [
"def",
"write",
"(",
"self",
")",
":",
"with",
"open",
"(",
"self",
".",
"me",
",",
"'w'",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"self",
".",
"printMe",
"(",
"self",
".",
"tag",
",",
"self",
".",
"value",
")",
")"
] | Write the job to the corresponding plist. | [
"Write",
"the",
"job",
"to",
"the",
"corresponding",
"plist",
"."
] | c83840e640cb075fab2534049f1e25fac6933c64 | https://github.com/casouri/launchdman/blob/c83840e640cb075fab2534049f1e25fac6933c64/launchdman/__init__.py#L367-L370 | train |
casouri/launchdman | launchdman/__init__.py | OuterOFInnerPair.add | def add(self, *l):
'''add inner to outer
Args:
*l: element that is passed into Inner init
'''
for a in flatten(l):
self._add([self.Inner(a)], self.l) | python | def add(self, *l):
'''add inner to outer
Args:
*l: element that is passed into Inner init
'''
for a in flatten(l):
self._add([self.Inner(a)], self.l) | [
"def",
"add",
"(",
"self",
",",
"*",
"l",
")",
":",
"for",
"a",
"in",
"flatten",
"(",
"l",
")",
":",
"self",
".",
"_add",
"(",
"[",
"self",
".",
"Inner",
"(",
"a",
")",
"]",
",",
"self",
".",
"l",
")"
] | add inner to outer
Args:
*l: element that is passed into Inner init | [
"add",
"inner",
"to",
"outer"
] | c83840e640cb075fab2534049f1e25fac6933c64 | https://github.com/casouri/launchdman/blob/c83840e640cb075fab2534049f1e25fac6933c64/launchdman/__init__.py#L593-L600 | train |
casouri/launchdman | launchdman/__init__.py | OuterOFInnerPair.remove | def remove(self, *l):
'''remove inner from outer
Args:
*l element that is passes into Inner init
'''
for a in flatten(l):
self._remove([self.Inner(a)], self.l) | python | def remove(self, *l):
'''remove inner from outer
Args:
*l element that is passes into Inner init
'''
for a in flatten(l):
self._remove([self.Inner(a)], self.l) | [
"def",
"remove",
"(",
"self",
",",
"*",
"l",
")",
":",
"for",
"a",
"in",
"flatten",
"(",
"l",
")",
":",
"self",
".",
"_remove",
"(",
"[",
"self",
".",
"Inner",
"(",
"a",
")",
"]",
",",
"self",
".",
"l",
")"
] | remove inner from outer
Args:
*l element that is passes into Inner init | [
"remove",
"inner",
"from",
"outer"
] | c83840e640cb075fab2534049f1e25fac6933c64 | https://github.com/casouri/launchdman/blob/c83840e640cb075fab2534049f1e25fac6933c64/launchdman/__init__.py#L602-L609 | train |
casouri/launchdman | launchdman/__init__.py | SingleDictPair.add | def add(self, dic):
'''adds a dict as pair
Args:
dic (dict): key and value
'''
for kw in dic:
checkKey(kw, self.keyWord)
self._add([Pair(kw, StringSingle(dic[kw]))], self.d) | python | def add(self, dic):
'''adds a dict as pair
Args:
dic (dict): key and value
'''
for kw in dic:
checkKey(kw, self.keyWord)
self._add([Pair(kw, StringSingle(dic[kw]))], self.d) | [
"def",
"add",
"(",
"self",
",",
"dic",
")",
":",
"for",
"kw",
"in",
"dic",
":",
"checkKey",
"(",
"kw",
",",
"self",
".",
"keyWord",
")",
"self",
".",
"_add",
"(",
"[",
"Pair",
"(",
"kw",
",",
"StringSingle",
"(",
"dic",
"[",
"kw",
"]",
")",
")",
"]",
",",
"self",
".",
"d",
")"
] | adds a dict as pair
Args:
dic (dict): key and value | [
"adds",
"a",
"dict",
"as",
"pair"
] | c83840e640cb075fab2534049f1e25fac6933c64 | https://github.com/casouri/launchdman/blob/c83840e640cb075fab2534049f1e25fac6933c64/launchdman/__init__.py#L661-L669 | train |
casouri/launchdman | launchdman/__init__.py | SingleDictPair.remove | def remove(self, dic):
'''remove the pair by passing a identical dict
Args:
dic (dict): key and value
'''
for kw in dic:
removePair = Pair(kw, dic[kw])
self._remove([removePair]) | python | def remove(self, dic):
'''remove the pair by passing a identical dict
Args:
dic (dict): key and value
'''
for kw in dic:
removePair = Pair(kw, dic[kw])
self._remove([removePair]) | [
"def",
"remove",
"(",
"self",
",",
"dic",
")",
":",
"for",
"kw",
"in",
"dic",
":",
"removePair",
"=",
"Pair",
"(",
"kw",
",",
"dic",
"[",
"kw",
"]",
")",
"self",
".",
"_remove",
"(",
"[",
"removePair",
"]",
")"
] | remove the pair by passing a identical dict
Args:
dic (dict): key and value | [
"remove",
"the",
"pair",
"by",
"passing",
"a",
"identical",
"dict"
] | c83840e640cb075fab2534049f1e25fac6933c64 | https://github.com/casouri/launchdman/blob/c83840e640cb075fab2534049f1e25fac6933c64/launchdman/__init__.py#L671-L679 | train |
casouri/launchdman | launchdman/__init__.py | StartInterval._update | def _update(self, baseNumber, magnification):
'''update self.value with basenumber and time interval
Args:
baseNumber (str): self.baseNumber
magnification (str): self.magnification
'''
interval = int(baseNumber * magnification)
self.value = [IntegerSingle(interval)] | python | def _update(self, baseNumber, magnification):
'''update self.value with basenumber and time interval
Args:
baseNumber (str): self.baseNumber
magnification (str): self.magnification
'''
interval = int(baseNumber * magnification)
self.value = [IntegerSingle(interval)] | [
"def",
"_update",
"(",
"self",
",",
"baseNumber",
",",
"magnification",
")",
":",
"interval",
"=",
"int",
"(",
"baseNumber",
"*",
"magnification",
")",
"self",
".",
"value",
"=",
"[",
"IntegerSingle",
"(",
"interval",
")",
"]"
] | update self.value with basenumber and time interval
Args:
baseNumber (str): self.baseNumber
magnification (str): self.magnification | [
"update",
"self",
".",
"value",
"with",
"basenumber",
"and",
"time",
"interval"
] | c83840e640cb075fab2534049f1e25fac6933c64 | https://github.com/casouri/launchdman/blob/c83840e640cb075fab2534049f1e25fac6933c64/launchdman/__init__.py#L876-L884 | train |
casouri/launchdman | launchdman/__init__.py | StartInterval.second | def second(self):
'''set unit to second'''
self.magnification = 1
self._update(self.baseNumber, self.magnification)
return self | python | def second(self):
'''set unit to second'''
self.magnification = 1
self._update(self.baseNumber, self.magnification)
return self | [
"def",
"second",
"(",
"self",
")",
":",
"self",
".",
"magnification",
"=",
"1",
"self",
".",
"_update",
"(",
"self",
".",
"baseNumber",
",",
"self",
".",
"magnification",
")",
"return",
"self"
] | set unit to second | [
"set",
"unit",
"to",
"second"
] | c83840e640cb075fab2534049f1e25fac6933c64 | https://github.com/casouri/launchdman/blob/c83840e640cb075fab2534049f1e25fac6933c64/launchdman/__init__.py#L887-L891 | train |
casouri/launchdman | launchdman/__init__.py | StartInterval.minute | def minute(self):
'''set unit to minute'''
self.magnification = 60
self._update(self.baseNumber, self.magnification)
return self | python | def minute(self):
'''set unit to minute'''
self.magnification = 60
self._update(self.baseNumber, self.magnification)
return self | [
"def",
"minute",
"(",
"self",
")",
":",
"self",
".",
"magnification",
"=",
"60",
"self",
".",
"_update",
"(",
"self",
".",
"baseNumber",
",",
"self",
".",
"magnification",
")",
"return",
"self"
] | set unit to minute | [
"set",
"unit",
"to",
"minute"
] | c83840e640cb075fab2534049f1e25fac6933c64 | https://github.com/casouri/launchdman/blob/c83840e640cb075fab2534049f1e25fac6933c64/launchdman/__init__.py#L894-L898 | train |
casouri/launchdman | launchdman/__init__.py | StartInterval.hour | def hour(self):
'''set unit to hour'''
self.magnification = 3600
self._update(self.baseNumber, self.magnification)
return self | python | def hour(self):
'''set unit to hour'''
self.magnification = 3600
self._update(self.baseNumber, self.magnification)
return self | [
"def",
"hour",
"(",
"self",
")",
":",
"self",
".",
"magnification",
"=",
"3600",
"self",
".",
"_update",
"(",
"self",
".",
"baseNumber",
",",
"self",
".",
"magnification",
")",
"return",
"self"
] | set unit to hour | [
"set",
"unit",
"to",
"hour"
] | c83840e640cb075fab2534049f1e25fac6933c64 | https://github.com/casouri/launchdman/blob/c83840e640cb075fab2534049f1e25fac6933c64/launchdman/__init__.py#L901-L905 | train |
casouri/launchdman | launchdman/__init__.py | StartInterval.day | def day(self):
'''set unit to day'''
self.magnification = 86400
self._update(self.baseNumber, self.magnification)
return self | python | def day(self):
'''set unit to day'''
self.magnification = 86400
self._update(self.baseNumber, self.magnification)
return self | [
"def",
"day",
"(",
"self",
")",
":",
"self",
".",
"magnification",
"=",
"86400",
"self",
".",
"_update",
"(",
"self",
".",
"baseNumber",
",",
"self",
".",
"magnification",
")",
"return",
"self"
] | set unit to day | [
"set",
"unit",
"to",
"day"
] | c83840e640cb075fab2534049f1e25fac6933c64 | https://github.com/casouri/launchdman/blob/c83840e640cb075fab2534049f1e25fac6933c64/launchdman/__init__.py#L908-L912 | train |
casouri/launchdman | launchdman/__init__.py | StartInterval.week | def week(self):
'''set unit to week'''
self.magnification = 345600
self._update(self.baseNumber, self.magnification)
return self | python | def week(self):
'''set unit to week'''
self.magnification = 345600
self._update(self.baseNumber, self.magnification)
return self | [
"def",
"week",
"(",
"self",
")",
":",
"self",
".",
"magnification",
"=",
"345600",
"self",
".",
"_update",
"(",
"self",
".",
"baseNumber",
",",
"self",
".",
"magnification",
")",
"return",
"self"
] | set unit to week | [
"set",
"unit",
"to",
"week"
] | c83840e640cb075fab2534049f1e25fac6933c64 | https://github.com/casouri/launchdman/blob/c83840e640cb075fab2534049f1e25fac6933c64/launchdman/__init__.py#L915-L919 | train |
casouri/launchdman | launchdman/__init__.py | StartCalendarInterval.add | def add(self, *dic):
'''add a config to StartCalendarInterval.
Args:
*dic (dict): dictionary with format {'Day': 12, 'Hour': 34} Avaliable keys are Month, Day, Weekday, Hour, Minute. *Note the uppercase.* You can use gen(), genMix() to generate complex config dictionary.
'''
dicList = list(flatten(dic))
# for every dict in the list passed in
for d in dicList:
# make a dict single (list of pairs)
di = []
for k in d:
# checkKey(k, self.keyWord)
di.append(Pair(k, IntegerSingle(d[k])))
dictSingle = DictSingle(di)
# append dict single to array single's value
self._add([dictSingle], self.l) | python | def add(self, *dic):
'''add a config to StartCalendarInterval.
Args:
*dic (dict): dictionary with format {'Day': 12, 'Hour': 34} Avaliable keys are Month, Day, Weekday, Hour, Minute. *Note the uppercase.* You can use gen(), genMix() to generate complex config dictionary.
'''
dicList = list(flatten(dic))
# for every dict in the list passed in
for d in dicList:
# make a dict single (list of pairs)
di = []
for k in d:
# checkKey(k, self.keyWord)
di.append(Pair(k, IntegerSingle(d[k])))
dictSingle = DictSingle(di)
# append dict single to array single's value
self._add([dictSingle], self.l) | [
"def",
"add",
"(",
"self",
",",
"*",
"dic",
")",
":",
"dicList",
"=",
"list",
"(",
"flatten",
"(",
"dic",
")",
")",
"# for every dict in the list passed in",
"for",
"d",
"in",
"dicList",
":",
"# make a dict single (list of pairs)",
"di",
"=",
"[",
"]",
"for",
"k",
"in",
"d",
":",
"# checkKey(k, self.keyWord)",
"di",
".",
"append",
"(",
"Pair",
"(",
"k",
",",
"IntegerSingle",
"(",
"d",
"[",
"k",
"]",
")",
")",
")",
"dictSingle",
"=",
"DictSingle",
"(",
"di",
")",
"# append dict single to array single's value",
"self",
".",
"_add",
"(",
"[",
"dictSingle",
"]",
",",
"self",
".",
"l",
")"
] | add a config to StartCalendarInterval.
Args:
*dic (dict): dictionary with format {'Day': 12, 'Hour': 34} Avaliable keys are Month, Day, Weekday, Hour, Minute. *Note the uppercase.* You can use gen(), genMix() to generate complex config dictionary. | [
"add",
"a",
"config",
"to",
"StartCalendarInterval",
"."
] | c83840e640cb075fab2534049f1e25fac6933c64 | https://github.com/casouri/launchdman/blob/c83840e640cb075fab2534049f1e25fac6933c64/launchdman/__init__.py#L963-L979 | train |
casouri/launchdman | launchdman/__init__.py | StartCalendarInterval.remove | def remove(self, *dic):
'''remove a calendar config.
Args:
*dic (dict): dictionary with format {'Day': 12, 'Hour': 34} Avaliable keys are Month, Day, Weekday, Hour, Minute. *Note the uppercase.* You can use gen(), genMix() to generate complex config dictionary.
'''
dicList = list(flatten(dic))
for d in dicList:
di = []
for k in d:
# checkkey(k, self.keyword)
di.append(Pair(k, IntegerSingle(d[k])))
dictSingle = DictSingle(di)
# append dict single to array single
self._remove([dictSingle], self.l) | python | def remove(self, *dic):
'''remove a calendar config.
Args:
*dic (dict): dictionary with format {'Day': 12, 'Hour': 34} Avaliable keys are Month, Day, Weekday, Hour, Minute. *Note the uppercase.* You can use gen(), genMix() to generate complex config dictionary.
'''
dicList = list(flatten(dic))
for d in dicList:
di = []
for k in d:
# checkkey(k, self.keyword)
di.append(Pair(k, IntegerSingle(d[k])))
dictSingle = DictSingle(di)
# append dict single to array single
self._remove([dictSingle], self.l) | [
"def",
"remove",
"(",
"self",
",",
"*",
"dic",
")",
":",
"dicList",
"=",
"list",
"(",
"flatten",
"(",
"dic",
")",
")",
"for",
"d",
"in",
"dicList",
":",
"di",
"=",
"[",
"]",
"for",
"k",
"in",
"d",
":",
"# checkkey(k, self.keyword)",
"di",
".",
"append",
"(",
"Pair",
"(",
"k",
",",
"IntegerSingle",
"(",
"d",
"[",
"k",
"]",
")",
")",
")",
"dictSingle",
"=",
"DictSingle",
"(",
"di",
")",
"# append dict single to array single",
"self",
".",
"_remove",
"(",
"[",
"dictSingle",
"]",
",",
"self",
".",
"l",
")"
] | remove a calendar config.
Args:
*dic (dict): dictionary with format {'Day': 12, 'Hour': 34} Avaliable keys are Month, Day, Weekday, Hour, Minute. *Note the uppercase.* You can use gen(), genMix() to generate complex config dictionary. | [
"remove",
"a",
"calendar",
"config",
"."
] | c83840e640cb075fab2534049f1e25fac6933c64 | https://github.com/casouri/launchdman/blob/c83840e640cb075fab2534049f1e25fac6933c64/launchdman/__init__.py#L981-L995 | train |
dmonroy/chilero | chilero/web/resource.py | Resource.get_index_url | def get_index_url(self, resource=None, **kwargs):
"""
Builds the url of the resource's index.
:param resource: name of the resource or None
:param kwargs: additional keyword arguments to build the url
:return: url of the resource's index
"""
default_kwargs = self.default_kwargs_for_urls() \
if resource == self.get_resource_name() else {}
default_kwargs.update(kwargs)
return self.get_full_url(
self.app.reverse(
'{}_index'.format(resource or self.get_resource_name()),
**default_kwargs
)
) | python | def get_index_url(self, resource=None, **kwargs):
"""
Builds the url of the resource's index.
:param resource: name of the resource or None
:param kwargs: additional keyword arguments to build the url
:return: url of the resource's index
"""
default_kwargs = self.default_kwargs_for_urls() \
if resource == self.get_resource_name() else {}
default_kwargs.update(kwargs)
return self.get_full_url(
self.app.reverse(
'{}_index'.format(resource or self.get_resource_name()),
**default_kwargs
)
) | [
"def",
"get_index_url",
"(",
"self",
",",
"resource",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"default_kwargs",
"=",
"self",
".",
"default_kwargs_for_urls",
"(",
")",
"if",
"resource",
"==",
"self",
".",
"get_resource_name",
"(",
")",
"else",
"{",
"}",
"default_kwargs",
".",
"update",
"(",
"kwargs",
")",
"return",
"self",
".",
"get_full_url",
"(",
"self",
".",
"app",
".",
"reverse",
"(",
"'{}_index'",
".",
"format",
"(",
"resource",
"or",
"self",
".",
"get_resource_name",
"(",
")",
")",
",",
"*",
"*",
"default_kwargs",
")",
")"
] | Builds the url of the resource's index.
:param resource: name of the resource or None
:param kwargs: additional keyword arguments to build the url
:return: url of the resource's index | [
"Builds",
"the",
"url",
"of",
"the",
"resource",
"s",
"index",
"."
] | 8f1118a60cb7eab3f9ad31cb8a14b30bc102893d | https://github.com/dmonroy/chilero/blob/8f1118a60cb7eab3f9ad31cb8a14b30bc102893d/chilero/web/resource.py#L40-L58 | train |
dmonroy/chilero | chilero/web/resource.py | Resource.get_parent | def get_parent(self):
"""Returns the url to the parent endpoint."""
if self.is_entity():
return self.get_index_url(**self.default_kwargs_for_urls())
elif self._parent is not None:
resource = self._parent.rsplit('_', 1)[0]
parts = self.default_kwargs_for_urls()
if '{}_id'.format(resource) in parts:
id = parts.pop('{}_id'.format(resource))
parts['id'] = id
return self.get_full_url(
self.app.reverse(
self._parent, **parts
)
) | python | def get_parent(self):
"""Returns the url to the parent endpoint."""
if self.is_entity():
return self.get_index_url(**self.default_kwargs_for_urls())
elif self._parent is not None:
resource = self._parent.rsplit('_', 1)[0]
parts = self.default_kwargs_for_urls()
if '{}_id'.format(resource) in parts:
id = parts.pop('{}_id'.format(resource))
parts['id'] = id
return self.get_full_url(
self.app.reverse(
self._parent, **parts
)
) | [
"def",
"get_parent",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_entity",
"(",
")",
":",
"return",
"self",
".",
"get_index_url",
"(",
"*",
"*",
"self",
".",
"default_kwargs_for_urls",
"(",
")",
")",
"elif",
"self",
".",
"_parent",
"is",
"not",
"None",
":",
"resource",
"=",
"self",
".",
"_parent",
".",
"rsplit",
"(",
"'_'",
",",
"1",
")",
"[",
"0",
"]",
"parts",
"=",
"self",
".",
"default_kwargs_for_urls",
"(",
")",
"if",
"'{}_id'",
".",
"format",
"(",
"resource",
")",
"in",
"parts",
":",
"id",
"=",
"parts",
".",
"pop",
"(",
"'{}_id'",
".",
"format",
"(",
"resource",
")",
")",
"parts",
"[",
"'id'",
"]",
"=",
"id",
"return",
"self",
".",
"get_full_url",
"(",
"self",
".",
"app",
".",
"reverse",
"(",
"self",
".",
"_parent",
",",
"*",
"*",
"parts",
")",
")"
] | Returns the url to the parent endpoint. | [
"Returns",
"the",
"url",
"to",
"the",
"parent",
"endpoint",
"."
] | 8f1118a60cb7eab3f9ad31cb8a14b30bc102893d | https://github.com/dmonroy/chilero/blob/8f1118a60cb7eab3f9ad31cb8a14b30bc102893d/chilero/web/resource.py#L143-L158 | train |
a1ezzz/wasp-general | wasp_general/command/context.py | WContext.export_context | def export_context(cls, context):
""" Export the specified context to be capable context transferring
:param context: context to export
:return: tuple
"""
if context is None:
return
result = [(x.context_name(), x.context_value()) for x in context]
result.reverse()
return tuple(result) | python | def export_context(cls, context):
""" Export the specified context to be capable context transferring
:param context: context to export
:return: tuple
"""
if context is None:
return
result = [(x.context_name(), x.context_value()) for x in context]
result.reverse()
return tuple(result) | [
"def",
"export_context",
"(",
"cls",
",",
"context",
")",
":",
"if",
"context",
"is",
"None",
":",
"return",
"result",
"=",
"[",
"(",
"x",
".",
"context_name",
"(",
")",
",",
"x",
".",
"context_value",
"(",
")",
")",
"for",
"x",
"in",
"context",
"]",
"result",
".",
"reverse",
"(",
")",
"return",
"tuple",
"(",
"result",
")"
] | Export the specified context to be capable context transferring
:param context: context to export
:return: tuple | [
"Export",
"the",
"specified",
"context",
"to",
"be",
"capable",
"context",
"transferring"
] | 1029839d33eb663f8dec76c1c46754d53c1de4a9 | https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/command/context.py#L141-L151 | train |
a1ezzz/wasp-general | wasp_general/command/context.py | WCommandContextAdapter.match | def match(self, command_context=None, **command_env):
""" Check if context request is compatible with adapters specification. True - if compatible,
False - otherwise
:param command_context: context to check
:param command_env: command environment
:return: bool
"""
spec = self.specification()
if command_context is None and spec is None:
return True
elif command_context is not None and spec is not None:
return command_context == spec
return False | python | def match(self, command_context=None, **command_env):
""" Check if context request is compatible with adapters specification. True - if compatible,
False - otherwise
:param command_context: context to check
:param command_env: command environment
:return: bool
"""
spec = self.specification()
if command_context is None and spec is None:
return True
elif command_context is not None and spec is not None:
return command_context == spec
return False | [
"def",
"match",
"(",
"self",
",",
"command_context",
"=",
"None",
",",
"*",
"*",
"command_env",
")",
":",
"spec",
"=",
"self",
".",
"specification",
"(",
")",
"if",
"command_context",
"is",
"None",
"and",
"spec",
"is",
"None",
":",
"return",
"True",
"elif",
"command_context",
"is",
"not",
"None",
"and",
"spec",
"is",
"not",
"None",
":",
"return",
"command_context",
"==",
"spec",
"return",
"False"
] | Check if context request is compatible with adapters specification. True - if compatible,
False - otherwise
:param command_context: context to check
:param command_env: command environment
:return: bool | [
"Check",
"if",
"context",
"request",
"is",
"compatible",
"with",
"adapters",
"specification",
".",
"True",
"-",
"if",
"compatible",
"False",
"-",
"otherwise"
] | 1029839d33eb663f8dec76c1c46754d53c1de4a9 | https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/command/context.py#L214-L227 | train |
OpenGov/og-python-utils | ogutils/collections/checks.py | any_shared | def any_shared(enum_one, enum_two):
'''
Truthy if any element in enum_one is present in enum_two
'''
if not is_collection(enum_one) or not is_collection(enum_two):
return False
enum_one = enum_one if isinstance(enum_one, (set, dict)) else set(enum_one)
enum_two = enum_two if isinstance(enum_two, (set, dict)) else set(enum_two)
return any(e in enum_two for e in enum_one) | python | def any_shared(enum_one, enum_two):
'''
Truthy if any element in enum_one is present in enum_two
'''
if not is_collection(enum_one) or not is_collection(enum_two):
return False
enum_one = enum_one if isinstance(enum_one, (set, dict)) else set(enum_one)
enum_two = enum_two if isinstance(enum_two, (set, dict)) else set(enum_two)
return any(e in enum_two for e in enum_one) | [
"def",
"any_shared",
"(",
"enum_one",
",",
"enum_two",
")",
":",
"if",
"not",
"is_collection",
"(",
"enum_one",
")",
"or",
"not",
"is_collection",
"(",
"enum_two",
")",
":",
"return",
"False",
"enum_one",
"=",
"enum_one",
"if",
"isinstance",
"(",
"enum_one",
",",
"(",
"set",
",",
"dict",
")",
")",
"else",
"set",
"(",
"enum_one",
")",
"enum_two",
"=",
"enum_two",
"if",
"isinstance",
"(",
"enum_two",
",",
"(",
"set",
",",
"dict",
")",
")",
"else",
"set",
"(",
"enum_two",
")",
"return",
"any",
"(",
"e",
"in",
"enum_two",
"for",
"e",
"in",
"enum_one",
")"
] | Truthy if any element in enum_one is present in enum_two | [
"Truthy",
"if",
"any",
"element",
"in",
"enum_one",
"is",
"present",
"in",
"enum_two"
] | 00f44927383dd1bd6348f47302c4453d56963479 | https://github.com/OpenGov/og-python-utils/blob/00f44927383dd1bd6348f47302c4453d56963479/ogutils/collections/checks.py#L13-L21 | train |
a1ezzz/wasp-general | wasp_general/network/web/service.py | WWebRoute.match | def match(self, request, service):
""" Check this route for matching the given request. If this route is matched, then target route is
returned.
:param request: request to match
:param service: source service
:return: WWebTargetRoute or None
"""
uri = self.normalize_uri(request.path())
if request.session().protocol() not in self.protocols:
return
if request.method() not in self.methods:
return
if self.virtual_hosts and request.virtual_host() not in self.virtual_hosts:
return
if self.ports and int(request.session().server_address().port()) not in self.ports:
return
match_obj = self.re_pattern.match(uri)
if not match_obj:
return
presenter_action = self.action
presenter_args = self.presenter_args.copy()
for i in range(len(self.route_args)):
if self.route_args[i] == 'action':
presenter_action = match_obj.group(i + 1)
else:
presenter_args[self.route_args[i]] = match_obj.group(i + 1)
return WWebTargetRoute(self.presenter, presenter_action, self, service.route_map(), **presenter_args) | python | def match(self, request, service):
""" Check this route for matching the given request. If this route is matched, then target route is
returned.
:param request: request to match
:param service: source service
:return: WWebTargetRoute or None
"""
uri = self.normalize_uri(request.path())
if request.session().protocol() not in self.protocols:
return
if request.method() not in self.methods:
return
if self.virtual_hosts and request.virtual_host() not in self.virtual_hosts:
return
if self.ports and int(request.session().server_address().port()) not in self.ports:
return
match_obj = self.re_pattern.match(uri)
if not match_obj:
return
presenter_action = self.action
presenter_args = self.presenter_args.copy()
for i in range(len(self.route_args)):
if self.route_args[i] == 'action':
presenter_action = match_obj.group(i + 1)
else:
presenter_args[self.route_args[i]] = match_obj.group(i + 1)
return WWebTargetRoute(self.presenter, presenter_action, self, service.route_map(), **presenter_args) | [
"def",
"match",
"(",
"self",
",",
"request",
",",
"service",
")",
":",
"uri",
"=",
"self",
".",
"normalize_uri",
"(",
"request",
".",
"path",
"(",
")",
")",
"if",
"request",
".",
"session",
"(",
")",
".",
"protocol",
"(",
")",
"not",
"in",
"self",
".",
"protocols",
":",
"return",
"if",
"request",
".",
"method",
"(",
")",
"not",
"in",
"self",
".",
"methods",
":",
"return",
"if",
"self",
".",
"virtual_hosts",
"and",
"request",
".",
"virtual_host",
"(",
")",
"not",
"in",
"self",
".",
"virtual_hosts",
":",
"return",
"if",
"self",
".",
"ports",
"and",
"int",
"(",
"request",
".",
"session",
"(",
")",
".",
"server_address",
"(",
")",
".",
"port",
"(",
")",
")",
"not",
"in",
"self",
".",
"ports",
":",
"return",
"match_obj",
"=",
"self",
".",
"re_pattern",
".",
"match",
"(",
"uri",
")",
"if",
"not",
"match_obj",
":",
"return",
"presenter_action",
"=",
"self",
".",
"action",
"presenter_args",
"=",
"self",
".",
"presenter_args",
".",
"copy",
"(",
")",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"route_args",
")",
")",
":",
"if",
"self",
".",
"route_args",
"[",
"i",
"]",
"==",
"'action'",
":",
"presenter_action",
"=",
"match_obj",
".",
"group",
"(",
"i",
"+",
"1",
")",
"else",
":",
"presenter_args",
"[",
"self",
".",
"route_args",
"[",
"i",
"]",
"]",
"=",
"match_obj",
".",
"group",
"(",
"i",
"+",
"1",
")",
"return",
"WWebTargetRoute",
"(",
"self",
".",
"presenter",
",",
"presenter_action",
",",
"self",
",",
"service",
".",
"route_map",
"(",
")",
",",
"*",
"*",
"presenter_args",
")"
] | Check this route for matching the given request. If this route is matched, then target route is
returned.
:param request: request to match
:param service: source service
:return: WWebTargetRoute or None | [
"Check",
"this",
"route",
"for",
"matching",
"the",
"given",
"request",
".",
"If",
"this",
"route",
"is",
"matched",
"then",
"target",
"route",
"is",
"returned",
"."
] | 1029839d33eb663f8dec76c1c46754d53c1de4a9 | https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/network/web/service.py#L338-L374 | train |
a1ezzz/wasp-general | wasp_general/network/web/service.py | WWebRouteMap.connect | def connect(self, pattern, presenter, **kwargs):
""" Connect the given pattern with the given presenter
:param pattern: URI pattern
:param presenter: target presenter name
:param kwargs: route arguments (see :class:`.WWebRoute`)
:return: None
"""
self.__routes.append(WWebRoute(pattern, presenter, **kwargs)) | python | def connect(self, pattern, presenter, **kwargs):
""" Connect the given pattern with the given presenter
:param pattern: URI pattern
:param presenter: target presenter name
:param kwargs: route arguments (see :class:`.WWebRoute`)
:return: None
"""
self.__routes.append(WWebRoute(pattern, presenter, **kwargs)) | [
"def",
"connect",
"(",
"self",
",",
"pattern",
",",
"presenter",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"__routes",
".",
"append",
"(",
"WWebRoute",
"(",
"pattern",
",",
"presenter",
",",
"*",
"*",
"kwargs",
")",
")"
] | Connect the given pattern with the given presenter
:param pattern: URI pattern
:param presenter: target presenter name
:param kwargs: route arguments (see :class:`.WWebRoute`)
:return: None | [
"Connect",
"the",
"given",
"pattern",
"with",
"the",
"given",
"presenter"
] | 1029839d33eb663f8dec76c1c46754d53c1de4a9 | https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/network/web/service.py#L540-L548 | train |
a1ezzz/wasp-general | wasp_general/network/web/service.py | WWebRouteMap.import_route | def import_route(self, route_as_txt):
""" Import route written as a string
:param route_as_txt: single string (single route) to import
:return: None
"""
route_match = WWebRouteMap.import_route_re.match(route_as_txt)
if route_match is None:
raise ValueError('Invalid route code')
pattern = route_match.group(1)
presenter_name = route_match.group(2)
route_args = route_match.group(4) # may be None
if route_args is not None:
result_args = {}
for arg_declaration in route_args.split(","):
arg_match = WWebRouteMap.import_route_arg_re.match(arg_declaration)
if arg_match is None:
raise RuntimeError('Invalid argument declaration in route')
result_args[arg_match.group(1)] = arg_match.group(3)
self.connect(pattern, presenter_name, **result_args)
else:
self.connect(pattern, presenter_name) | python | def import_route(self, route_as_txt):
""" Import route written as a string
:param route_as_txt: single string (single route) to import
:return: None
"""
route_match = WWebRouteMap.import_route_re.match(route_as_txt)
if route_match is None:
raise ValueError('Invalid route code')
pattern = route_match.group(1)
presenter_name = route_match.group(2)
route_args = route_match.group(4) # may be None
if route_args is not None:
result_args = {}
for arg_declaration in route_args.split(","):
arg_match = WWebRouteMap.import_route_arg_re.match(arg_declaration)
if arg_match is None:
raise RuntimeError('Invalid argument declaration in route')
result_args[arg_match.group(1)] = arg_match.group(3)
self.connect(pattern, presenter_name, **result_args)
else:
self.connect(pattern, presenter_name) | [
"def",
"import_route",
"(",
"self",
",",
"route_as_txt",
")",
":",
"route_match",
"=",
"WWebRouteMap",
".",
"import_route_re",
".",
"match",
"(",
"route_as_txt",
")",
"if",
"route_match",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"'Invalid route code'",
")",
"pattern",
"=",
"route_match",
".",
"group",
"(",
"1",
")",
"presenter_name",
"=",
"route_match",
".",
"group",
"(",
"2",
")",
"route_args",
"=",
"route_match",
".",
"group",
"(",
"4",
")",
"# may be None",
"if",
"route_args",
"is",
"not",
"None",
":",
"result_args",
"=",
"{",
"}",
"for",
"arg_declaration",
"in",
"route_args",
".",
"split",
"(",
"\",\"",
")",
":",
"arg_match",
"=",
"WWebRouteMap",
".",
"import_route_arg_re",
".",
"match",
"(",
"arg_declaration",
")",
"if",
"arg_match",
"is",
"None",
":",
"raise",
"RuntimeError",
"(",
"'Invalid argument declaration in route'",
")",
"result_args",
"[",
"arg_match",
".",
"group",
"(",
"1",
")",
"]",
"=",
"arg_match",
".",
"group",
"(",
"3",
")",
"self",
".",
"connect",
"(",
"pattern",
",",
"presenter_name",
",",
"*",
"*",
"result_args",
")",
"else",
":",
"self",
".",
"connect",
"(",
"pattern",
",",
"presenter_name",
")"
] | Import route written as a string
:param route_as_txt: single string (single route) to import
:return: None | [
"Import",
"route",
"written",
"as",
"a",
"string"
] | 1029839d33eb663f8dec76c1c46754d53c1de4a9 | https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/network/web/service.py#L561-L585 | train |
a1ezzz/wasp-general | wasp_general/network/web/service.py | WWebService.process_request | def process_request(self, session):
""" Process single request from the given session
:param session: session for reading requests and writing responses
:return: None
"""
debugger = self.debugger()
debugger_session_id = debugger.session_id() if debugger is not None else None
try:
request = session.read_request()
if debugger_session_id is not None:
debugger.request(
debugger_session_id, request, session.protocol_version(), session.protocol()
)
try:
target_route = self.route_map().route(request, self)
if debugger_session_id is not None:
debugger.target_route(debugger_session_id, target_route)
if target_route is not None:
response = self.execute(request, target_route)
else:
presenter_cls = self.route_map().error_presenter()
presenter = presenter_cls(request)
response = presenter.error_code(code=404)
if debugger_session_id is not None:
debugger.response(debugger_session_id, response)
except Exception as e:
if debugger_session_id is not None:
debugger.exception(debugger_session_id, e)
presenter_cls = self.route_map().error_presenter()
presenter = presenter_cls(request)
response = presenter.exception_error(e)
session.write_response(request, response, *response.__pushed_responses__())
except Exception as e:
if debugger_session_id is not None:
debugger.exception(debugger_session_id, e)
session.session_close()
if debugger_session_id is not None:
debugger.finalize(debugger_session_id) | python | def process_request(self, session):
""" Process single request from the given session
:param session: session for reading requests and writing responses
:return: None
"""
debugger = self.debugger()
debugger_session_id = debugger.session_id() if debugger is not None else None
try:
request = session.read_request()
if debugger_session_id is not None:
debugger.request(
debugger_session_id, request, session.protocol_version(), session.protocol()
)
try:
target_route = self.route_map().route(request, self)
if debugger_session_id is not None:
debugger.target_route(debugger_session_id, target_route)
if target_route is not None:
response = self.execute(request, target_route)
else:
presenter_cls = self.route_map().error_presenter()
presenter = presenter_cls(request)
response = presenter.error_code(code=404)
if debugger_session_id is not None:
debugger.response(debugger_session_id, response)
except Exception as e:
if debugger_session_id is not None:
debugger.exception(debugger_session_id, e)
presenter_cls = self.route_map().error_presenter()
presenter = presenter_cls(request)
response = presenter.exception_error(e)
session.write_response(request, response, *response.__pushed_responses__())
except Exception as e:
if debugger_session_id is not None:
debugger.exception(debugger_session_id, e)
session.session_close()
if debugger_session_id is not None:
debugger.finalize(debugger_session_id) | [
"def",
"process_request",
"(",
"self",
",",
"session",
")",
":",
"debugger",
"=",
"self",
".",
"debugger",
"(",
")",
"debugger_session_id",
"=",
"debugger",
".",
"session_id",
"(",
")",
"if",
"debugger",
"is",
"not",
"None",
"else",
"None",
"try",
":",
"request",
"=",
"session",
".",
"read_request",
"(",
")",
"if",
"debugger_session_id",
"is",
"not",
"None",
":",
"debugger",
".",
"request",
"(",
"debugger_session_id",
",",
"request",
",",
"session",
".",
"protocol_version",
"(",
")",
",",
"session",
".",
"protocol",
"(",
")",
")",
"try",
":",
"target_route",
"=",
"self",
".",
"route_map",
"(",
")",
".",
"route",
"(",
"request",
",",
"self",
")",
"if",
"debugger_session_id",
"is",
"not",
"None",
":",
"debugger",
".",
"target_route",
"(",
"debugger_session_id",
",",
"target_route",
")",
"if",
"target_route",
"is",
"not",
"None",
":",
"response",
"=",
"self",
".",
"execute",
"(",
"request",
",",
"target_route",
")",
"else",
":",
"presenter_cls",
"=",
"self",
".",
"route_map",
"(",
")",
".",
"error_presenter",
"(",
")",
"presenter",
"=",
"presenter_cls",
"(",
"request",
")",
"response",
"=",
"presenter",
".",
"error_code",
"(",
"code",
"=",
"404",
")",
"if",
"debugger_session_id",
"is",
"not",
"None",
":",
"debugger",
".",
"response",
"(",
"debugger_session_id",
",",
"response",
")",
"except",
"Exception",
"as",
"e",
":",
"if",
"debugger_session_id",
"is",
"not",
"None",
":",
"debugger",
".",
"exception",
"(",
"debugger_session_id",
",",
"e",
")",
"presenter_cls",
"=",
"self",
".",
"route_map",
"(",
")",
".",
"error_presenter",
"(",
")",
"presenter",
"=",
"presenter_cls",
"(",
"request",
")",
"response",
"=",
"presenter",
".",
"exception_error",
"(",
"e",
")",
"session",
".",
"write_response",
"(",
"request",
",",
"response",
",",
"*",
"response",
".",
"__pushed_responses__",
"(",
")",
")",
"except",
"Exception",
"as",
"e",
":",
"if",
"debugger_session_id",
"is",
"not",
"None",
":",
"debugger",
".",
"exception",
"(",
"debugger_session_id",
",",
"e",
")",
"session",
".",
"session_close",
"(",
")",
"if",
"debugger_session_id",
"is",
"not",
"None",
":",
"debugger",
".",
"finalize",
"(",
"debugger_session_id",
")"
] | Process single request from the given session
:param session: session for reading requests and writing responses
:return: None | [
"Process",
"single",
"request",
"from",
"the",
"given",
"session"
] | 1029839d33eb663f8dec76c1c46754d53c1de4a9 | https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/network/web/service.py#L670-L718 | train |
a1ezzz/wasp-general | wasp_general/network/web/service.py | WWebService.create_presenter | def create_presenter(self, request, target_route):
""" Create presenter from the given requests and target routes
:param request: client request
:param target_route: route to use
:return: WWebPresenter
"""
presenter_name = target_route.presenter_name()
if self.presenter_collection().has(presenter_name) is False:
raise RuntimeError('No such presenter: %s' % presenter_name)
presenter_class = self.presenter_collection().presenter(presenter_name)
return self.presenter_factory().instantiate(presenter_class, request, target_route, self) | python | def create_presenter(self, request, target_route):
""" Create presenter from the given requests and target routes
:param request: client request
:param target_route: route to use
:return: WWebPresenter
"""
presenter_name = target_route.presenter_name()
if self.presenter_collection().has(presenter_name) is False:
raise RuntimeError('No such presenter: %s' % presenter_name)
presenter_class = self.presenter_collection().presenter(presenter_name)
return self.presenter_factory().instantiate(presenter_class, request, target_route, self) | [
"def",
"create_presenter",
"(",
"self",
",",
"request",
",",
"target_route",
")",
":",
"presenter_name",
"=",
"target_route",
".",
"presenter_name",
"(",
")",
"if",
"self",
".",
"presenter_collection",
"(",
")",
".",
"has",
"(",
"presenter_name",
")",
"is",
"False",
":",
"raise",
"RuntimeError",
"(",
"'No such presenter: %s'",
"%",
"presenter_name",
")",
"presenter_class",
"=",
"self",
".",
"presenter_collection",
"(",
")",
".",
"presenter",
"(",
"presenter_name",
")",
"return",
"self",
".",
"presenter_factory",
"(",
")",
".",
"instantiate",
"(",
"presenter_class",
",",
"request",
",",
"target_route",
",",
"self",
")"
] | Create presenter from the given requests and target routes
:param request: client request
:param target_route: route to use
:return: WWebPresenter | [
"Create",
"presenter",
"from",
"the",
"given",
"requests",
"and",
"target",
"routes"
] | 1029839d33eb663f8dec76c1c46754d53c1de4a9 | https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/network/web/service.py#L721-L732 | train |
a1ezzz/wasp-general | wasp_general/network/web/service.py | WWebService.proxy | def proxy(self, request, original_target_route, presenter_name, **kwargs):
""" Execute the given presenter as a target for the given client request
:param request: original client request
:param original_target_route: previous target route
:param presenter_name: target presenter name
:param kwargs: presenter arguments
:return: WWebResponseProto
"""
action_kwargs = kwargs.copy()
action_name = 'index'
if 'action' in action_kwargs:
action_name = action_kwargs['action']
action_kwargs.pop('action')
original_route = original_target_route.route()
original_route_map = original_target_route.route_map()
target_route = WWebTargetRoute(
presenter_name, action_name, original_route, original_route_map, **action_kwargs
)
return self.execute(request, target_route) | python | def proxy(self, request, original_target_route, presenter_name, **kwargs):
""" Execute the given presenter as a target for the given client request
:param request: original client request
:param original_target_route: previous target route
:param presenter_name: target presenter name
:param kwargs: presenter arguments
:return: WWebResponseProto
"""
action_kwargs = kwargs.copy()
action_name = 'index'
if 'action' in action_kwargs:
action_name = action_kwargs['action']
action_kwargs.pop('action')
original_route = original_target_route.route()
original_route_map = original_target_route.route_map()
target_route = WWebTargetRoute(
presenter_name, action_name, original_route, original_route_map, **action_kwargs
)
return self.execute(request, target_route) | [
"def",
"proxy",
"(",
"self",
",",
"request",
",",
"original_target_route",
",",
"presenter_name",
",",
"*",
"*",
"kwargs",
")",
":",
"action_kwargs",
"=",
"kwargs",
".",
"copy",
"(",
")",
"action_name",
"=",
"'index'",
"if",
"'action'",
"in",
"action_kwargs",
":",
"action_name",
"=",
"action_kwargs",
"[",
"'action'",
"]",
"action_kwargs",
".",
"pop",
"(",
"'action'",
")",
"original_route",
"=",
"original_target_route",
".",
"route",
"(",
")",
"original_route_map",
"=",
"original_target_route",
".",
"route_map",
"(",
")",
"target_route",
"=",
"WWebTargetRoute",
"(",
"presenter_name",
",",
"action_name",
",",
"original_route",
",",
"original_route_map",
",",
"*",
"*",
"action_kwargs",
")",
"return",
"self",
".",
"execute",
"(",
"request",
",",
"target_route",
")"
] | Execute the given presenter as a target for the given client request
:param request: original client request
:param original_target_route: previous target route
:param presenter_name: target presenter name
:param kwargs: presenter arguments
:return: WWebResponseProto | [
"Execute",
"the",
"given",
"presenter",
"as",
"a",
"target",
"for",
"the",
"given",
"client",
"request"
] | 1029839d33eb663f8dec76c1c46754d53c1de4a9 | https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/network/web/service.py#L804-L825 | train |
shaypal5/strct | strct/sortedlists/sortedlist.py | find_point_in_section_list | def find_point_in_section_list(point, section_list):
"""Returns the start of the section the given point belongs to.
The given list is assumed to contain start points of consecutive
sections, except for the final point, assumed to be the end point of the
last section. For example, the list [5, 8, 30, 31] is interpreted as the
following list of sections: [5-8), [8-30), [30-31], so the points -32, 4.5,
32 and 100 all match no section, while 5 and 7.5 match [5-8) and so for
them the function returns 5, and 30, 30.7 and 31 all match [30-31].
Parameters
---------
point : float
The point for which to match a section.
section_list : sortedcontainers.SortedList
A list of start points of consecutive sections.
Returns
-------
float
The start of the section the given point belongs to. None if no match
was found.
Example
-------
>>> from sortedcontainers import SortedList
>>> seclist = SortedList([5, 8, 30, 31])
>>> find_point_in_section_list(4, seclist)
>>> find_point_in_section_list(5, seclist)
5
>>> find_point_in_section_list(27, seclist)
8
>>> find_point_in_section_list(31, seclist)
30
"""
if point < section_list[0] or point > section_list[-1]:
return None
if point in section_list:
if point == section_list[-1]:
return section_list[-2]
ind = section_list.bisect(point)-1
if ind == 0:
return section_list[0]
return section_list[ind]
try:
ind = section_list.bisect(point)
return section_list[ind-1]
except IndexError:
return None | python | def find_point_in_section_list(point, section_list):
"""Returns the start of the section the given point belongs to.
The given list is assumed to contain start points of consecutive
sections, except for the final point, assumed to be the end point of the
last section. For example, the list [5, 8, 30, 31] is interpreted as the
following list of sections: [5-8), [8-30), [30-31], so the points -32, 4.5,
32 and 100 all match no section, while 5 and 7.5 match [5-8) and so for
them the function returns 5, and 30, 30.7 and 31 all match [30-31].
Parameters
---------
point : float
The point for which to match a section.
section_list : sortedcontainers.SortedList
A list of start points of consecutive sections.
Returns
-------
float
The start of the section the given point belongs to. None if no match
was found.
Example
-------
>>> from sortedcontainers import SortedList
>>> seclist = SortedList([5, 8, 30, 31])
>>> find_point_in_section_list(4, seclist)
>>> find_point_in_section_list(5, seclist)
5
>>> find_point_in_section_list(27, seclist)
8
>>> find_point_in_section_list(31, seclist)
30
"""
if point < section_list[0] or point > section_list[-1]:
return None
if point in section_list:
if point == section_list[-1]:
return section_list[-2]
ind = section_list.bisect(point)-1
if ind == 0:
return section_list[0]
return section_list[ind]
try:
ind = section_list.bisect(point)
return section_list[ind-1]
except IndexError:
return None | [
"def",
"find_point_in_section_list",
"(",
"point",
",",
"section_list",
")",
":",
"if",
"point",
"<",
"section_list",
"[",
"0",
"]",
"or",
"point",
">",
"section_list",
"[",
"-",
"1",
"]",
":",
"return",
"None",
"if",
"point",
"in",
"section_list",
":",
"if",
"point",
"==",
"section_list",
"[",
"-",
"1",
"]",
":",
"return",
"section_list",
"[",
"-",
"2",
"]",
"ind",
"=",
"section_list",
".",
"bisect",
"(",
"point",
")",
"-",
"1",
"if",
"ind",
"==",
"0",
":",
"return",
"section_list",
"[",
"0",
"]",
"return",
"section_list",
"[",
"ind",
"]",
"try",
":",
"ind",
"=",
"section_list",
".",
"bisect",
"(",
"point",
")",
"return",
"section_list",
"[",
"ind",
"-",
"1",
"]",
"except",
"IndexError",
":",
"return",
"None"
] | Returns the start of the section the given point belongs to.
The given list is assumed to contain start points of consecutive
sections, except for the final point, assumed to be the end point of the
last section. For example, the list [5, 8, 30, 31] is interpreted as the
following list of sections: [5-8), [8-30), [30-31], so the points -32, 4.5,
32 and 100 all match no section, while 5 and 7.5 match [5-8) and so for
them the function returns 5, and 30, 30.7 and 31 all match [30-31].
Parameters
---------
point : float
The point for which to match a section.
section_list : sortedcontainers.SortedList
A list of start points of consecutive sections.
Returns
-------
float
The start of the section the given point belongs to. None if no match
was found.
Example
-------
>>> from sortedcontainers import SortedList
>>> seclist = SortedList([5, 8, 30, 31])
>>> find_point_in_section_list(4, seclist)
>>> find_point_in_section_list(5, seclist)
5
>>> find_point_in_section_list(27, seclist)
8
>>> find_point_in_section_list(31, seclist)
30 | [
"Returns",
"the",
"start",
"of",
"the",
"section",
"the",
"given",
"point",
"belongs",
"to",
"."
] | f3a301692d052ddb79331230b3c00625db1d83fc | https://github.com/shaypal5/strct/blob/f3a301692d052ddb79331230b3c00625db1d83fc/strct/sortedlists/sortedlist.py#L4-L53 | train |
shaypal5/strct | strct/sortedlists/sortedlist.py | find_range_ix_in_section_list | def find_range_ix_in_section_list(start, end, section_list):
"""Returns the index range all sections belonging to the given range.
The given list is assumed to contain start points of consecutive
sections, except for the final point, assumed to be the end point of the
last section. For example, the list [5, 8, 30, 31] is interpreted as the
following list of sections: [5-8), [8-30), [30-31]. As such, this function
will return [5,8] for the range (7,9) and [5,8,30] while for (7, 30).
Parameters
---------
start : float
The start of the desired range.
end : float
The end of the desired range.
section_list : sortedcontainers.SortedList
A list of start points of consecutive sections.
Returns
-------
iterable
The index range of all sections belonging to the given range.
Example
-------
>>> from sortedcontainers import SortedList
>>> seclist = SortedList([5, 8, 30, 31])
>>> find_range_ix_in_section_list(3, 4, seclist)
[0, 0]
>>> find_range_ix_in_section_list(6, 7, seclist)
[0, 1]
>>> find_range_ix_in_section_list(7, 9, seclist)
[0, 2]
>>> find_range_ix_in_section_list(7, 30, seclist)
[0, 3]
>>> find_range_ix_in_section_list(7, 321, seclist)
[0, 3]
>>> find_range_ix_in_section_list(4, 321, seclist)
[0, 3]
"""
if start > section_list[-1] or end < section_list[0]:
return [0, 0]
if start < section_list[0]:
start_section = section_list[0]
else:
start_section = find_point_in_section_list(start, section_list)
if end > section_list[-1]:
end_section = section_list[-2]
else:
end_section = find_point_in_section_list(end, section_list)
return [
section_list.index(start_section), section_list.index(end_section)+1] | python | def find_range_ix_in_section_list(start, end, section_list):
"""Returns the index range all sections belonging to the given range.
The given list is assumed to contain start points of consecutive
sections, except for the final point, assumed to be the end point of the
last section. For example, the list [5, 8, 30, 31] is interpreted as the
following list of sections: [5-8), [8-30), [30-31]. As such, this function
will return [5,8] for the range (7,9) and [5,8,30] while for (7, 30).
Parameters
---------
start : float
The start of the desired range.
end : float
The end of the desired range.
section_list : sortedcontainers.SortedList
A list of start points of consecutive sections.
Returns
-------
iterable
The index range of all sections belonging to the given range.
Example
-------
>>> from sortedcontainers import SortedList
>>> seclist = SortedList([5, 8, 30, 31])
>>> find_range_ix_in_section_list(3, 4, seclist)
[0, 0]
>>> find_range_ix_in_section_list(6, 7, seclist)
[0, 1]
>>> find_range_ix_in_section_list(7, 9, seclist)
[0, 2]
>>> find_range_ix_in_section_list(7, 30, seclist)
[0, 3]
>>> find_range_ix_in_section_list(7, 321, seclist)
[0, 3]
>>> find_range_ix_in_section_list(4, 321, seclist)
[0, 3]
"""
if start > section_list[-1] or end < section_list[0]:
return [0, 0]
if start < section_list[0]:
start_section = section_list[0]
else:
start_section = find_point_in_section_list(start, section_list)
if end > section_list[-1]:
end_section = section_list[-2]
else:
end_section = find_point_in_section_list(end, section_list)
return [
section_list.index(start_section), section_list.index(end_section)+1] | [
"def",
"find_range_ix_in_section_list",
"(",
"start",
",",
"end",
",",
"section_list",
")",
":",
"if",
"start",
">",
"section_list",
"[",
"-",
"1",
"]",
"or",
"end",
"<",
"section_list",
"[",
"0",
"]",
":",
"return",
"[",
"0",
",",
"0",
"]",
"if",
"start",
"<",
"section_list",
"[",
"0",
"]",
":",
"start_section",
"=",
"section_list",
"[",
"0",
"]",
"else",
":",
"start_section",
"=",
"find_point_in_section_list",
"(",
"start",
",",
"section_list",
")",
"if",
"end",
">",
"section_list",
"[",
"-",
"1",
"]",
":",
"end_section",
"=",
"section_list",
"[",
"-",
"2",
"]",
"else",
":",
"end_section",
"=",
"find_point_in_section_list",
"(",
"end",
",",
"section_list",
")",
"return",
"[",
"section_list",
".",
"index",
"(",
"start_section",
")",
",",
"section_list",
".",
"index",
"(",
"end_section",
")",
"+",
"1",
"]"
] | Returns the index range all sections belonging to the given range.
The given list is assumed to contain start points of consecutive
sections, except for the final point, assumed to be the end point of the
last section. For example, the list [5, 8, 30, 31] is interpreted as the
following list of sections: [5-8), [8-30), [30-31]. As such, this function
will return [5,8] for the range (7,9) and [5,8,30] while for (7, 30).
Parameters
---------
start : float
The start of the desired range.
end : float
The end of the desired range.
section_list : sortedcontainers.SortedList
A list of start points of consecutive sections.
Returns
-------
iterable
The index range of all sections belonging to the given range.
Example
-------
>>> from sortedcontainers import SortedList
>>> seclist = SortedList([5, 8, 30, 31])
>>> find_range_ix_in_section_list(3, 4, seclist)
[0, 0]
>>> find_range_ix_in_section_list(6, 7, seclist)
[0, 1]
>>> find_range_ix_in_section_list(7, 9, seclist)
[0, 2]
>>> find_range_ix_in_section_list(7, 30, seclist)
[0, 3]
>>> find_range_ix_in_section_list(7, 321, seclist)
[0, 3]
>>> find_range_ix_in_section_list(4, 321, seclist)
[0, 3] | [
"Returns",
"the",
"index",
"range",
"all",
"sections",
"belonging",
"to",
"the",
"given",
"range",
"."
] | f3a301692d052ddb79331230b3c00625db1d83fc | https://github.com/shaypal5/strct/blob/f3a301692d052ddb79331230b3c00625db1d83fc/strct/sortedlists/sortedlist.py#L56-L107 | train |
shaypal5/strct | strct/sortedlists/sortedlist.py | find_range_in_section_list | def find_range_in_section_list(start, end, section_list):
"""Returns all sections belonging to the given range.
The given list is assumed to contain start points of consecutive
sections, except for the final point, assumed to be the end point of the
last section. For example, the list [5, 8, 30, 31] is interpreted as the
following list of sections: [5-8), [8-30), [30-31]. As such, this function
will return [5,8] for the range (7,9) and [5,8,30] while for (7, 30).
Parameters
---------
start : float
The start of the desired range.
end : float
The end of the desired range.
section_list : sortedcontainers.SortedList
A list of start points of consecutive sections.
Returns
-------
iterable
The starting points of all sections belonging to the given range.
Example
-------
>>> from sortedcontainers import SortedList
>>> seclist = SortedList([5, 8, 30, 31])
>>> find_range_in_section_list(3, 4, seclist)
[]
>>> find_range_in_section_list(6, 7, seclist)
[5]
>>> find_range_in_section_list(7, 9, seclist)
[5, 8]
>>> find_range_in_section_list(7, 30, seclist)
[5, 8, 30]
>>> find_range_in_section_list(7, 321, seclist)
[5, 8, 30]
>>> find_range_in_section_list(4, 321, seclist)
[5, 8, 30]
"""
ind = find_range_ix_in_section_list(start, end, section_list)
return section_list[ind[0]: ind[1]] | python | def find_range_in_section_list(start, end, section_list):
"""Returns all sections belonging to the given range.
The given list is assumed to contain start points of consecutive
sections, except for the final point, assumed to be the end point of the
last section. For example, the list [5, 8, 30, 31] is interpreted as the
following list of sections: [5-8), [8-30), [30-31]. As such, this function
will return [5,8] for the range (7,9) and [5,8,30] while for (7, 30).
Parameters
---------
start : float
The start of the desired range.
end : float
The end of the desired range.
section_list : sortedcontainers.SortedList
A list of start points of consecutive sections.
Returns
-------
iterable
The starting points of all sections belonging to the given range.
Example
-------
>>> from sortedcontainers import SortedList
>>> seclist = SortedList([5, 8, 30, 31])
>>> find_range_in_section_list(3, 4, seclist)
[]
>>> find_range_in_section_list(6, 7, seclist)
[5]
>>> find_range_in_section_list(7, 9, seclist)
[5, 8]
>>> find_range_in_section_list(7, 30, seclist)
[5, 8, 30]
>>> find_range_in_section_list(7, 321, seclist)
[5, 8, 30]
>>> find_range_in_section_list(4, 321, seclist)
[5, 8, 30]
"""
ind = find_range_ix_in_section_list(start, end, section_list)
return section_list[ind[0]: ind[1]] | [
"def",
"find_range_in_section_list",
"(",
"start",
",",
"end",
",",
"section_list",
")",
":",
"ind",
"=",
"find_range_ix_in_section_list",
"(",
"start",
",",
"end",
",",
"section_list",
")",
"return",
"section_list",
"[",
"ind",
"[",
"0",
"]",
":",
"ind",
"[",
"1",
"]",
"]"
] | Returns all sections belonging to the given range.
The given list is assumed to contain start points of consecutive
sections, except for the final point, assumed to be the end point of the
last section. For example, the list [5, 8, 30, 31] is interpreted as the
following list of sections: [5-8), [8-30), [30-31]. As such, this function
will return [5,8] for the range (7,9) and [5,8,30] while for (7, 30).
Parameters
---------
start : float
The start of the desired range.
end : float
The end of the desired range.
section_list : sortedcontainers.SortedList
A list of start points of consecutive sections.
Returns
-------
iterable
The starting points of all sections belonging to the given range.
Example
-------
>>> from sortedcontainers import SortedList
>>> seclist = SortedList([5, 8, 30, 31])
>>> find_range_in_section_list(3, 4, seclist)
[]
>>> find_range_in_section_list(6, 7, seclist)
[5]
>>> find_range_in_section_list(7, 9, seclist)
[5, 8]
>>> find_range_in_section_list(7, 30, seclist)
[5, 8, 30]
>>> find_range_in_section_list(7, 321, seclist)
[5, 8, 30]
>>> find_range_in_section_list(4, 321, seclist)
[5, 8, 30] | [
"Returns",
"all",
"sections",
"belonging",
"to",
"the",
"given",
"range",
"."
] | f3a301692d052ddb79331230b3c00625db1d83fc | https://github.com/shaypal5/strct/blob/f3a301692d052ddb79331230b3c00625db1d83fc/strct/sortedlists/sortedlist.py#L110-L151 | train |
shaypal5/strct | strct/sortedlists/sortedlist.py | find_range_ix_in_point_list | def find_range_ix_in_point_list(start, end, point_list):
"""Returns the index range all points inside the given range.
Parameters
---------
start : float
The start of the desired range.
end : float
The end of the desired range.
point_list : sortedcontainers.SortedList
A list of points.
Returns
-------
iterable
The index range of all points inside the given range.
Example
-------
>>> from sortedcontainers import SortedList
>>> point_list = SortedList([5, 8, 15])
>>> find_range_ix_in_point_list(3, 4, point_list)
[0, 0]
>>> find_range_ix_in_point_list(3, 7, point_list)
[0, 1]
>>> find_range_ix_in_point_list(3, 8, point_list)
[0, 2]
>>> find_range_ix_in_point_list(4, 15, point_list)
[0, 3]
>>> find_range_ix_in_point_list(4, 321, point_list)
[0, 3]
>>> find_range_ix_in_point_list(6, 321, point_list)
[1, 3]
"""
return [point_list.bisect_left(start), point_list.bisect_right(end)] | python | def find_range_ix_in_point_list(start, end, point_list):
"""Returns the index range all points inside the given range.
Parameters
---------
start : float
The start of the desired range.
end : float
The end of the desired range.
point_list : sortedcontainers.SortedList
A list of points.
Returns
-------
iterable
The index range of all points inside the given range.
Example
-------
>>> from sortedcontainers import SortedList
>>> point_list = SortedList([5, 8, 15])
>>> find_range_ix_in_point_list(3, 4, point_list)
[0, 0]
>>> find_range_ix_in_point_list(3, 7, point_list)
[0, 1]
>>> find_range_ix_in_point_list(3, 8, point_list)
[0, 2]
>>> find_range_ix_in_point_list(4, 15, point_list)
[0, 3]
>>> find_range_ix_in_point_list(4, 321, point_list)
[0, 3]
>>> find_range_ix_in_point_list(6, 321, point_list)
[1, 3]
"""
return [point_list.bisect_left(start), point_list.bisect_right(end)] | [
"def",
"find_range_ix_in_point_list",
"(",
"start",
",",
"end",
",",
"point_list",
")",
":",
"return",
"[",
"point_list",
".",
"bisect_left",
"(",
"start",
")",
",",
"point_list",
".",
"bisect_right",
"(",
"end",
")",
"]"
] | Returns the index range all points inside the given range.
Parameters
---------
start : float
The start of the desired range.
end : float
The end of the desired range.
point_list : sortedcontainers.SortedList
A list of points.
Returns
-------
iterable
The index range of all points inside the given range.
Example
-------
>>> from sortedcontainers import SortedList
>>> point_list = SortedList([5, 8, 15])
>>> find_range_ix_in_point_list(3, 4, point_list)
[0, 0]
>>> find_range_ix_in_point_list(3, 7, point_list)
[0, 1]
>>> find_range_ix_in_point_list(3, 8, point_list)
[0, 2]
>>> find_range_ix_in_point_list(4, 15, point_list)
[0, 3]
>>> find_range_ix_in_point_list(4, 321, point_list)
[0, 3]
>>> find_range_ix_in_point_list(6, 321, point_list)
[1, 3] | [
"Returns",
"the",
"index",
"range",
"all",
"points",
"inside",
"the",
"given",
"range",
"."
] | f3a301692d052ddb79331230b3c00625db1d83fc | https://github.com/shaypal5/strct/blob/f3a301692d052ddb79331230b3c00625db1d83fc/strct/sortedlists/sortedlist.py#L154-L188 | train |
a1ezzz/wasp-general | wasp_general/config.py | WConfig.split_option | def split_option(self, section, option):
""" Return list of strings that are made by splitting coma-separated option value. Method returns
empty list if option value is empty string
:param section: option section name
:param option: option name
:return: list of strings
"""
value = self[section][option].strip()
if value == "":
return []
return [x.strip() for x in (value.split(","))] | python | def split_option(self, section, option):
""" Return list of strings that are made by splitting coma-separated option value. Method returns
empty list if option value is empty string
:param section: option section name
:param option: option name
:return: list of strings
"""
value = self[section][option].strip()
if value == "":
return []
return [x.strip() for x in (value.split(","))] | [
"def",
"split_option",
"(",
"self",
",",
"section",
",",
"option",
")",
":",
"value",
"=",
"self",
"[",
"section",
"]",
"[",
"option",
"]",
".",
"strip",
"(",
")",
"if",
"value",
"==",
"\"\"",
":",
"return",
"[",
"]",
"return",
"[",
"x",
".",
"strip",
"(",
")",
"for",
"x",
"in",
"(",
"value",
".",
"split",
"(",
"\",\"",
")",
")",
"]"
] | Return list of strings that are made by splitting coma-separated option value. Method returns
empty list if option value is empty string
:param section: option section name
:param option: option name
:return: list of strings | [
"Return",
"list",
"of",
"strings",
"that",
"are",
"made",
"by",
"splitting",
"coma",
"-",
"separated",
"option",
"value",
".",
"Method",
"returns",
"empty",
"list",
"if",
"option",
"value",
"is",
"empty",
"string"
] | 1029839d33eb663f8dec76c1c46754d53c1de4a9 | https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/config.py#L39-L50 | train |
a1ezzz/wasp-general | wasp_general/config.py | WConfig.merge | def merge(self, config):
""" Load configuration from given configuration.
:param config: config to load. If config is a string type, then it's treated as .ini filename
:return: None
"""
if isinstance(config, ConfigParser) is True:
self.update(config)
elif isinstance(config, str):
self.read(config) | python | def merge(self, config):
""" Load configuration from given configuration.
:param config: config to load. If config is a string type, then it's treated as .ini filename
:return: None
"""
if isinstance(config, ConfigParser) is True:
self.update(config)
elif isinstance(config, str):
self.read(config) | [
"def",
"merge",
"(",
"self",
",",
"config",
")",
":",
"if",
"isinstance",
"(",
"config",
",",
"ConfigParser",
")",
"is",
"True",
":",
"self",
".",
"update",
"(",
"config",
")",
"elif",
"isinstance",
"(",
"config",
",",
"str",
")",
":",
"self",
".",
"read",
"(",
"config",
")"
] | Load configuration from given configuration.
:param config: config to load. If config is a string type, then it's treated as .ini filename
:return: None | [
"Load",
"configuration",
"from",
"given",
"configuration",
"."
] | 1029839d33eb663f8dec76c1c46754d53c1de4a9 | https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/config.py#L54-L63 | train |
a1ezzz/wasp-general | wasp_general/config.py | WConfig.merge_section | def merge_section(self, config, section_to, section_from=None):
""" Load configuration section from other configuration. If specified section doesn't exist in current
configuration, then it will be added automatically.
:param config: source configuration
:param section_to: destination section name
:param section_from: source section name (if it is None, then section_to is used as source section name)
:return: None
"""
section_from = section_from if section_from is not None else section_to
if section_from not in config.sections():
raise ValueError('There is no such section "%s" in config' % section_from)
if section_to not in self.sections():
self.add_section(section_to)
for option in config[section_from].keys():
self.set(section_to, option, config[section_from][option]) | python | def merge_section(self, config, section_to, section_from=None):
""" Load configuration section from other configuration. If specified section doesn't exist in current
configuration, then it will be added automatically.
:param config: source configuration
:param section_to: destination section name
:param section_from: source section name (if it is None, then section_to is used as source section name)
:return: None
"""
section_from = section_from if section_from is not None else section_to
if section_from not in config.sections():
raise ValueError('There is no such section "%s" in config' % section_from)
if section_to not in self.sections():
self.add_section(section_to)
for option in config[section_from].keys():
self.set(section_to, option, config[section_from][option]) | [
"def",
"merge_section",
"(",
"self",
",",
"config",
",",
"section_to",
",",
"section_from",
"=",
"None",
")",
":",
"section_from",
"=",
"section_from",
"if",
"section_from",
"is",
"not",
"None",
"else",
"section_to",
"if",
"section_from",
"not",
"in",
"config",
".",
"sections",
"(",
")",
":",
"raise",
"ValueError",
"(",
"'There is no such section \"%s\" in config'",
"%",
"section_from",
")",
"if",
"section_to",
"not",
"in",
"self",
".",
"sections",
"(",
")",
":",
"self",
".",
"add_section",
"(",
"section_to",
")",
"for",
"option",
"in",
"config",
"[",
"section_from",
"]",
".",
"keys",
"(",
")",
":",
"self",
".",
"set",
"(",
"section_to",
",",
"option",
",",
"config",
"[",
"section_from",
"]",
"[",
"option",
"]",
")"
] | Load configuration section from other configuration. If specified section doesn't exist in current
configuration, then it will be added automatically.
:param config: source configuration
:param section_to: destination section name
:param section_from: source section name (if it is None, then section_to is used as source section name)
:return: None | [
"Load",
"configuration",
"section",
"from",
"other",
"configuration",
".",
"If",
"specified",
"section",
"doesn",
"t",
"exist",
"in",
"current",
"configuration",
"then",
"it",
"will",
"be",
"added",
"automatically",
"."
] | 1029839d33eb663f8dec76c1c46754d53c1de4a9 | https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/config.py#L66-L83 | train |
a1ezzz/wasp-general | wasp_general/config.py | WConfigSelection.__option | def __option(self):
""" Check and return option from section from configuration. Option name is equal to option prefix
:return: tuple of section name and option prefix
"""
section = self.section()
option = self.option_prefix()
if self.config().has_option(section, option) is False:
raise NoOptionError(option, section)
return section, option | python | def __option(self):
""" Check and return option from section from configuration. Option name is equal to option prefix
:return: tuple of section name and option prefix
"""
section = self.section()
option = self.option_prefix()
if self.config().has_option(section, option) is False:
raise NoOptionError(option, section)
return section, option | [
"def",
"__option",
"(",
"self",
")",
":",
"section",
"=",
"self",
".",
"section",
"(",
")",
"option",
"=",
"self",
".",
"option_prefix",
"(",
")",
"if",
"self",
".",
"config",
"(",
")",
".",
"has_option",
"(",
"section",
",",
"option",
")",
"is",
"False",
":",
"raise",
"NoOptionError",
"(",
"option",
",",
"section",
")",
"return",
"section",
",",
"option"
] | Check and return option from section from configuration. Option name is equal to option prefix
:return: tuple of section name and option prefix | [
"Check",
"and",
"return",
"option",
"from",
"section",
"from",
"configuration",
".",
"Option",
"name",
"is",
"equal",
"to",
"option",
"prefix"
] | 1029839d33eb663f8dec76c1c46754d53c1de4a9 | https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/config.py#L139-L148 | train |
a1ezzz/wasp-general | wasp_general/config.py | WConfigSelection.select_options | def select_options(self, options_prefix):
""" Select options from this selection, that are started with the specified prefix
:param options_prefix: name prefix of options that should be selected
:return: WConfigSelection
"""
return WConfigSelection(
self.config(), self.section(), self.option_prefix() + options_prefix
) | python | def select_options(self, options_prefix):
""" Select options from this selection, that are started with the specified prefix
:param options_prefix: name prefix of options that should be selected
:return: WConfigSelection
"""
return WConfigSelection(
self.config(), self.section(), self.option_prefix() + options_prefix
) | [
"def",
"select_options",
"(",
"self",
",",
"options_prefix",
")",
":",
"return",
"WConfigSelection",
"(",
"self",
".",
"config",
"(",
")",
",",
"self",
".",
"section",
"(",
")",
",",
"self",
".",
"option_prefix",
"(",
")",
"+",
"options_prefix",
")"
] | Select options from this selection, that are started with the specified prefix
:param options_prefix: name prefix of options that should be selected
:return: WConfigSelection | [
"Select",
"options",
"from",
"this",
"selection",
"that",
"are",
"started",
"with",
"the",
"specified",
"prefix"
] | 1029839d33eb663f8dec76c1c46754d53c1de4a9 | https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/config.py#L184-L192 | train |
a1ezzz/wasp-general | wasp_general/config.py | WConfigSelection.has_option | def has_option(self, option_name=None):
""" Check whether configuration selection has the specified option.
:param option_name: option name to check. If no option is specified, then check is made for this option
:return: bool
"""
if option_name is None:
option_name = ''
return self.config().has_option(self.section(), self.option_prefix() + option_name) | python | def has_option(self, option_name=None):
""" Check whether configuration selection has the specified option.
:param option_name: option name to check. If no option is specified, then check is made for this option
:return: bool
"""
if option_name is None:
option_name = ''
return self.config().has_option(self.section(), self.option_prefix() + option_name) | [
"def",
"has_option",
"(",
"self",
",",
"option_name",
"=",
"None",
")",
":",
"if",
"option_name",
"is",
"None",
":",
"option_name",
"=",
"''",
"return",
"self",
".",
"config",
"(",
")",
".",
"has_option",
"(",
"self",
".",
"section",
"(",
")",
",",
"self",
".",
"option_prefix",
"(",
")",
"+",
"option_name",
")"
] | Check whether configuration selection has the specified option.
:param option_name: option name to check. If no option is specified, then check is made for this option
:return: bool | [
"Check",
"whether",
"configuration",
"selection",
"has",
"the",
"specified",
"option",
"."
] | 1029839d33eb663f8dec76c1c46754d53c1de4a9 | https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/config.py#L205-L214 | train |
a1ezzz/wasp-general | wasp_general/verify.py | Verifier._args_checks_gen | def _args_checks_gen(self, decorated_function, function_spec, arg_specs):
""" Generate checks for positional argument testing
:param decorated_function: function decorator
:param function_spec: function inspect information
:param arg_specs: argument specification (same as arg_specs in :meth:`.Verifier.decorate`)
:return: internal structure, that is used by :meth:`.Verifier._args_checks_test`
"""
inspected_args = function_spec.args
args_check = {}
for i in range(len(inspected_args)):
arg_name = inspected_args[i]
if arg_name in arg_specs.keys():
args_check[arg_name] = self.check(arg_specs[arg_name], arg_name, decorated_function)
return args_check | python | def _args_checks_gen(self, decorated_function, function_spec, arg_specs):
""" Generate checks for positional argument testing
:param decorated_function: function decorator
:param function_spec: function inspect information
:param arg_specs: argument specification (same as arg_specs in :meth:`.Verifier.decorate`)
:return: internal structure, that is used by :meth:`.Verifier._args_checks_test`
"""
inspected_args = function_spec.args
args_check = {}
for i in range(len(inspected_args)):
arg_name = inspected_args[i]
if arg_name in arg_specs.keys():
args_check[arg_name] = self.check(arg_specs[arg_name], arg_name, decorated_function)
return args_check | [
"def",
"_args_checks_gen",
"(",
"self",
",",
"decorated_function",
",",
"function_spec",
",",
"arg_specs",
")",
":",
"inspected_args",
"=",
"function_spec",
".",
"args",
"args_check",
"=",
"{",
"}",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"inspected_args",
")",
")",
":",
"arg_name",
"=",
"inspected_args",
"[",
"i",
"]",
"if",
"arg_name",
"in",
"arg_specs",
".",
"keys",
"(",
")",
":",
"args_check",
"[",
"arg_name",
"]",
"=",
"self",
".",
"check",
"(",
"arg_specs",
"[",
"arg_name",
"]",
",",
"arg_name",
",",
"decorated_function",
")",
"return",
"args_check"
] | Generate checks for positional argument testing
:param decorated_function: function decorator
:param function_spec: function inspect information
:param arg_specs: argument specification (same as arg_specs in :meth:`.Verifier.decorate`)
:return: internal structure, that is used by :meth:`.Verifier._args_checks_test` | [
"Generate",
"checks",
"for",
"positional",
"argument",
"testing"
] | 1029839d33eb663f8dec76c1c46754d53c1de4a9 | https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/verify.py#L120-L137 | train |
a1ezzz/wasp-general | wasp_general/verify.py | Verifier._kwargs_checks_gen | def _kwargs_checks_gen(self, decorated_function, function_spec, arg_specs):
""" Generate checks for keyword argument testing
:param decorated_function: function decorator
:param function_spec: function inspect information
:param arg_specs: argument specification (same as arg_specs in :meth:`.Verifier.decorate`)
:return: internal structure, that is used by :meth:`.Verifier._kwargs_checks_test`
"""
args_names = []
args_names.extend(function_spec.args)
if function_spec.varargs is not None:
args_names.append(function_spec.args)
args_check = {}
for arg_name in arg_specs.keys():
if arg_name not in args_names:
args_check[arg_name] = self.check(
arg_specs[arg_name], arg_name, decorated_function
)
return args_check | python | def _kwargs_checks_gen(self, decorated_function, function_spec, arg_specs):
""" Generate checks for keyword argument testing
:param decorated_function: function decorator
:param function_spec: function inspect information
:param arg_specs: argument specification (same as arg_specs in :meth:`.Verifier.decorate`)
:return: internal structure, that is used by :meth:`.Verifier._kwargs_checks_test`
"""
args_names = []
args_names.extend(function_spec.args)
if function_spec.varargs is not None:
args_names.append(function_spec.args)
args_check = {}
for arg_name in arg_specs.keys():
if arg_name not in args_names:
args_check[arg_name] = self.check(
arg_specs[arg_name], arg_name, decorated_function
)
return args_check | [
"def",
"_kwargs_checks_gen",
"(",
"self",
",",
"decorated_function",
",",
"function_spec",
",",
"arg_specs",
")",
":",
"args_names",
"=",
"[",
"]",
"args_names",
".",
"extend",
"(",
"function_spec",
".",
"args",
")",
"if",
"function_spec",
".",
"varargs",
"is",
"not",
"None",
":",
"args_names",
".",
"append",
"(",
"function_spec",
".",
"args",
")",
"args_check",
"=",
"{",
"}",
"for",
"arg_name",
"in",
"arg_specs",
".",
"keys",
"(",
")",
":",
"if",
"arg_name",
"not",
"in",
"args_names",
":",
"args_check",
"[",
"arg_name",
"]",
"=",
"self",
".",
"check",
"(",
"arg_specs",
"[",
"arg_name",
"]",
",",
"arg_name",
",",
"decorated_function",
")",
"return",
"args_check"
] | Generate checks for keyword argument testing
:param decorated_function: function decorator
:param function_spec: function inspect information
:param arg_specs: argument specification (same as arg_specs in :meth:`.Verifier.decorate`)
:return: internal structure, that is used by :meth:`.Verifier._kwargs_checks_test` | [
"Generate",
"checks",
"for",
"keyword",
"argument",
"testing"
] | 1029839d33eb663f8dec76c1c46754d53c1de4a9 | https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/verify.py#L199-L220 | train |
a1ezzz/wasp-general | wasp_general/verify.py | Verifier.decorator | def decorator(self, **arg_specs):
""" Return decorator that can decorate target function
:param arg_specs: dictionary where keys are parameters name and values are theirs specification.\
Specific specification is passed as is to :meth:`Verifier.check` method with corresponding \
parameter name.
:return: function
"""
if self.decorate_disabled() is True:
def empty_decorator(decorated_function):
return decorated_function
return empty_decorator
def first_level_decorator(decorated_function):
function_spec = getfullargspec(decorated_function)
args_checks = self._args_checks_gen(decorated_function, function_spec, arg_specs)
varargs_check = self._varargs_checks_gen(decorated_function, function_spec, arg_specs)
kwargs_checks = self._kwargs_checks_gen(decorated_function, function_spec, arg_specs)
def second_level_decorator(original_function, *args, **kwargs):
self._args_checks_test(original_function, function_spec, args_checks, args, arg_specs)
self._varargs_checks_test(original_function, function_spec, varargs_check, args, arg_specs)
self._kwargs_checks_test(original_function, kwargs_checks, kwargs, arg_specs)
return original_function(*args, **kwargs)
return decorator(second_level_decorator)(decorated_function)
return first_level_decorator | python | def decorator(self, **arg_specs):
""" Return decorator that can decorate target function
:param arg_specs: dictionary where keys are parameters name and values are theirs specification.\
Specific specification is passed as is to :meth:`Verifier.check` method with corresponding \
parameter name.
:return: function
"""
if self.decorate_disabled() is True:
def empty_decorator(decorated_function):
return decorated_function
return empty_decorator
def first_level_decorator(decorated_function):
function_spec = getfullargspec(decorated_function)
args_checks = self._args_checks_gen(decorated_function, function_spec, arg_specs)
varargs_check = self._varargs_checks_gen(decorated_function, function_spec, arg_specs)
kwargs_checks = self._kwargs_checks_gen(decorated_function, function_spec, arg_specs)
def second_level_decorator(original_function, *args, **kwargs):
self._args_checks_test(original_function, function_spec, args_checks, args, arg_specs)
self._varargs_checks_test(original_function, function_spec, varargs_check, args, arg_specs)
self._kwargs_checks_test(original_function, kwargs_checks, kwargs, arg_specs)
return original_function(*args, **kwargs)
return decorator(second_level_decorator)(decorated_function)
return first_level_decorator | [
"def",
"decorator",
"(",
"self",
",",
"*",
"*",
"arg_specs",
")",
":",
"if",
"self",
".",
"decorate_disabled",
"(",
")",
"is",
"True",
":",
"def",
"empty_decorator",
"(",
"decorated_function",
")",
":",
"return",
"decorated_function",
"return",
"empty_decorator",
"def",
"first_level_decorator",
"(",
"decorated_function",
")",
":",
"function_spec",
"=",
"getfullargspec",
"(",
"decorated_function",
")",
"args_checks",
"=",
"self",
".",
"_args_checks_gen",
"(",
"decorated_function",
",",
"function_spec",
",",
"arg_specs",
")",
"varargs_check",
"=",
"self",
".",
"_varargs_checks_gen",
"(",
"decorated_function",
",",
"function_spec",
",",
"arg_specs",
")",
"kwargs_checks",
"=",
"self",
".",
"_kwargs_checks_gen",
"(",
"decorated_function",
",",
"function_spec",
",",
"arg_specs",
")",
"def",
"second_level_decorator",
"(",
"original_function",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"_args_checks_test",
"(",
"original_function",
",",
"function_spec",
",",
"args_checks",
",",
"args",
",",
"arg_specs",
")",
"self",
".",
"_varargs_checks_test",
"(",
"original_function",
",",
"function_spec",
",",
"varargs_check",
",",
"args",
",",
"arg_specs",
")",
"self",
".",
"_kwargs_checks_test",
"(",
"original_function",
",",
"kwargs_checks",
",",
"kwargs",
",",
"arg_specs",
")",
"return",
"original_function",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"decorator",
"(",
"second_level_decorator",
")",
"(",
"decorated_function",
")",
"return",
"first_level_decorator"
] | Return decorator that can decorate target function
:param arg_specs: dictionary where keys are parameters name and values are theirs specification.\
Specific specification is passed as is to :meth:`Verifier.check` method with corresponding \
parameter name.
:return: function | [
"Return",
"decorator",
"that",
"can",
"decorate",
"target",
"function"
] | 1029839d33eb663f8dec76c1c46754d53c1de4a9 | https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/verify.py#L241-L270 | train |
a1ezzz/wasp-general | wasp_general/verify.py | Verifier.function_name | def function_name(fn):
""" Return function name in pretty style
:param fn: source function
:return: str
"""
fn_name = fn.__name__
if hasattr(fn, '__qualname__'):
return fn.__qualname__
elif hasattr(fn, '__self__'):
owner = fn.__self__
if isclass(owner) is False:
owner = owner.__class__
return '%s.%s' % (owner.__name__, fn_name)
return fn_name | python | def function_name(fn):
""" Return function name in pretty style
:param fn: source function
:return: str
"""
fn_name = fn.__name__
if hasattr(fn, '__qualname__'):
return fn.__qualname__
elif hasattr(fn, '__self__'):
owner = fn.__self__
if isclass(owner) is False:
owner = owner.__class__
return '%s.%s' % (owner.__name__, fn_name)
return fn_name | [
"def",
"function_name",
"(",
"fn",
")",
":",
"fn_name",
"=",
"fn",
".",
"__name__",
"if",
"hasattr",
"(",
"fn",
",",
"'__qualname__'",
")",
":",
"return",
"fn",
".",
"__qualname__",
"elif",
"hasattr",
"(",
"fn",
",",
"'__self__'",
")",
":",
"owner",
"=",
"fn",
".",
"__self__",
"if",
"isclass",
"(",
"owner",
")",
"is",
"False",
":",
"owner",
"=",
"owner",
".",
"__class__",
"return",
"'%s.%s'",
"%",
"(",
"owner",
".",
"__name__",
",",
"fn_name",
")",
"return",
"fn_name"
] | Return function name in pretty style
:param fn: source function
:return: str | [
"Return",
"function",
"name",
"in",
"pretty",
"style"
] | 1029839d33eb663f8dec76c1c46754d53c1de4a9 | https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/verify.py#L298-L312 | train |
a1ezzz/wasp-general | wasp_general/verify.py | TypeVerifier.check | def check(self, type_spec, arg_name, decorated_function):
""" Return callable that checks function parameter for type validity. Checks parameter if it is
instance of specified class or classes
:param type_spec: type or list/tuple/set of types
:param arg_name: function parameter name
:param decorated_function: target function
:return: function
"""
def raise_exception(x_spec):
exc_text = 'Argument "%s" for function "%s" has invalid type' % (
arg_name, Verifier.function_name(decorated_function)
)
exc_text += ' (%s should be %s)' % (x_spec, type_spec)
raise TypeError(exc_text)
if isinstance(type_spec, (tuple, list, set)):
for single_type in type_spec:
if (single_type is not None) and isclass(single_type) is False:
raise RuntimeError(
'Invalid specification. Must be type or tuple/list/set of types'
)
if None in type_spec:
type_spec = tuple(filter(lambda x: x is not None, type_spec))
return lambda x: None if x is None or isinstance(x, tuple(type_spec)) is True else \
raise_exception(str((type(x))))
else:
return lambda x: None if isinstance(x, tuple(type_spec)) is True else \
raise_exception(str((type(x))))
elif isclass(type_spec):
return lambda x: None if isinstance(x, type_spec) is True else \
raise_exception(str((type(x))))
else:
raise RuntimeError('Invalid specification. Must be type or tuple/list/set of types') | python | def check(self, type_spec, arg_name, decorated_function):
""" Return callable that checks function parameter for type validity. Checks parameter if it is
instance of specified class or classes
:param type_spec: type or list/tuple/set of types
:param arg_name: function parameter name
:param decorated_function: target function
:return: function
"""
def raise_exception(x_spec):
exc_text = 'Argument "%s" for function "%s" has invalid type' % (
arg_name, Verifier.function_name(decorated_function)
)
exc_text += ' (%s should be %s)' % (x_spec, type_spec)
raise TypeError(exc_text)
if isinstance(type_spec, (tuple, list, set)):
for single_type in type_spec:
if (single_type is not None) and isclass(single_type) is False:
raise RuntimeError(
'Invalid specification. Must be type or tuple/list/set of types'
)
if None in type_spec:
type_spec = tuple(filter(lambda x: x is not None, type_spec))
return lambda x: None if x is None or isinstance(x, tuple(type_spec)) is True else \
raise_exception(str((type(x))))
else:
return lambda x: None if isinstance(x, tuple(type_spec)) is True else \
raise_exception(str((type(x))))
elif isclass(type_spec):
return lambda x: None if isinstance(x, type_spec) is True else \
raise_exception(str((type(x))))
else:
raise RuntimeError('Invalid specification. Must be type or tuple/list/set of types') | [
"def",
"check",
"(",
"self",
",",
"type_spec",
",",
"arg_name",
",",
"decorated_function",
")",
":",
"def",
"raise_exception",
"(",
"x_spec",
")",
":",
"exc_text",
"=",
"'Argument \"%s\" for function \"%s\" has invalid type'",
"%",
"(",
"arg_name",
",",
"Verifier",
".",
"function_name",
"(",
"decorated_function",
")",
")",
"exc_text",
"+=",
"' (%s should be %s)'",
"%",
"(",
"x_spec",
",",
"type_spec",
")",
"raise",
"TypeError",
"(",
"exc_text",
")",
"if",
"isinstance",
"(",
"type_spec",
",",
"(",
"tuple",
",",
"list",
",",
"set",
")",
")",
":",
"for",
"single_type",
"in",
"type_spec",
":",
"if",
"(",
"single_type",
"is",
"not",
"None",
")",
"and",
"isclass",
"(",
"single_type",
")",
"is",
"False",
":",
"raise",
"RuntimeError",
"(",
"'Invalid specification. Must be type or tuple/list/set of types'",
")",
"if",
"None",
"in",
"type_spec",
":",
"type_spec",
"=",
"tuple",
"(",
"filter",
"(",
"lambda",
"x",
":",
"x",
"is",
"not",
"None",
",",
"type_spec",
")",
")",
"return",
"lambda",
"x",
":",
"None",
"if",
"x",
"is",
"None",
"or",
"isinstance",
"(",
"x",
",",
"tuple",
"(",
"type_spec",
")",
")",
"is",
"True",
"else",
"raise_exception",
"(",
"str",
"(",
"(",
"type",
"(",
"x",
")",
")",
")",
")",
"else",
":",
"return",
"lambda",
"x",
":",
"None",
"if",
"isinstance",
"(",
"x",
",",
"tuple",
"(",
"type_spec",
")",
")",
"is",
"True",
"else",
"raise_exception",
"(",
"str",
"(",
"(",
"type",
"(",
"x",
")",
")",
")",
")",
"elif",
"isclass",
"(",
"type_spec",
")",
":",
"return",
"lambda",
"x",
":",
"None",
"if",
"isinstance",
"(",
"x",
",",
"type_spec",
")",
"is",
"True",
"else",
"raise_exception",
"(",
"str",
"(",
"(",
"type",
"(",
"x",
")",
")",
")",
")",
"else",
":",
"raise",
"RuntimeError",
"(",
"'Invalid specification. Must be type or tuple/list/set of types'",
")"
] | Return callable that checks function parameter for type validity. Checks parameter if it is
instance of specified class or classes
:param type_spec: type or list/tuple/set of types
:param arg_name: function parameter name
:param decorated_function: target function
:return: function | [
"Return",
"callable",
"that",
"checks",
"function",
"parameter",
"for",
"type",
"validity",
".",
"Checks",
"parameter",
"if",
"it",
"is",
"instance",
"of",
"specified",
"class",
"or",
"classes"
] | 1029839d33eb663f8dec76c1c46754d53c1de4a9 | https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/verify.py#L326-L360 | train |
a1ezzz/wasp-general | wasp_general/verify.py | SubclassVerifier.check | def check(self, type_spec, arg_name, decorated_function):
""" Return callable that checks function parameter for class validity. Checks parameter if it is
class or subclass of specified class or classes
:param type_spec: type or list/tuple/set of types
:param arg_name: function parameter name
:param decorated_function: target function
:return: function
"""
def raise_exception(text_spec):
exc_text = 'Argument "%s" for function "%s" has invalid type' % (
arg_name, Verifier.function_name(decorated_function)
)
exc_text += ' (%s)' % text_spec
raise TypeError(exc_text)
if isinstance(type_spec, (tuple, list, set)):
for single_type in type_spec:
if (single_type is not None) and isclass(single_type) is False:
raise RuntimeError(
'Invalid specification. Must be type or tuple/list/set of types'
)
if None in type_spec:
type_spec = tuple(filter(lambda x: x is not None, type_spec))
return lambda x: None if \
x is None or (isclass(x) is True and issubclass(x, type_spec) is True) else \
raise_exception(str(x))
else:
return lambda x: None if (isclass(x) is True and issubclass(x, type_spec) is True) else \
raise_exception(str(x))
elif isclass(type_spec):
return lambda x: None if (isclass(x) is True and issubclass(x, type_spec) is True) else \
raise_exception(str(x))
else:
raise RuntimeError('Invalid specification. Must be type or tuple/list/set of types') | python | def check(self, type_spec, arg_name, decorated_function):
""" Return callable that checks function parameter for class validity. Checks parameter if it is
class or subclass of specified class or classes
:param type_spec: type or list/tuple/set of types
:param arg_name: function parameter name
:param decorated_function: target function
:return: function
"""
def raise_exception(text_spec):
exc_text = 'Argument "%s" for function "%s" has invalid type' % (
arg_name, Verifier.function_name(decorated_function)
)
exc_text += ' (%s)' % text_spec
raise TypeError(exc_text)
if isinstance(type_spec, (tuple, list, set)):
for single_type in type_spec:
if (single_type is not None) and isclass(single_type) is False:
raise RuntimeError(
'Invalid specification. Must be type or tuple/list/set of types'
)
if None in type_spec:
type_spec = tuple(filter(lambda x: x is not None, type_spec))
return lambda x: None if \
x is None or (isclass(x) is True and issubclass(x, type_spec) is True) else \
raise_exception(str(x))
else:
return lambda x: None if (isclass(x) is True and issubclass(x, type_spec) is True) else \
raise_exception(str(x))
elif isclass(type_spec):
return lambda x: None if (isclass(x) is True and issubclass(x, type_spec) is True) else \
raise_exception(str(x))
else:
raise RuntimeError('Invalid specification. Must be type or tuple/list/set of types') | [
"def",
"check",
"(",
"self",
",",
"type_spec",
",",
"arg_name",
",",
"decorated_function",
")",
":",
"def",
"raise_exception",
"(",
"text_spec",
")",
":",
"exc_text",
"=",
"'Argument \"%s\" for function \"%s\" has invalid type'",
"%",
"(",
"arg_name",
",",
"Verifier",
".",
"function_name",
"(",
"decorated_function",
")",
")",
"exc_text",
"+=",
"' (%s)'",
"%",
"text_spec",
"raise",
"TypeError",
"(",
"exc_text",
")",
"if",
"isinstance",
"(",
"type_spec",
",",
"(",
"tuple",
",",
"list",
",",
"set",
")",
")",
":",
"for",
"single_type",
"in",
"type_spec",
":",
"if",
"(",
"single_type",
"is",
"not",
"None",
")",
"and",
"isclass",
"(",
"single_type",
")",
"is",
"False",
":",
"raise",
"RuntimeError",
"(",
"'Invalid specification. Must be type or tuple/list/set of types'",
")",
"if",
"None",
"in",
"type_spec",
":",
"type_spec",
"=",
"tuple",
"(",
"filter",
"(",
"lambda",
"x",
":",
"x",
"is",
"not",
"None",
",",
"type_spec",
")",
")",
"return",
"lambda",
"x",
":",
"None",
"if",
"x",
"is",
"None",
"or",
"(",
"isclass",
"(",
"x",
")",
"is",
"True",
"and",
"issubclass",
"(",
"x",
",",
"type_spec",
")",
"is",
"True",
")",
"else",
"raise_exception",
"(",
"str",
"(",
"x",
")",
")",
"else",
":",
"return",
"lambda",
"x",
":",
"None",
"if",
"(",
"isclass",
"(",
"x",
")",
"is",
"True",
"and",
"issubclass",
"(",
"x",
",",
"type_spec",
")",
"is",
"True",
")",
"else",
"raise_exception",
"(",
"str",
"(",
"x",
")",
")",
"elif",
"isclass",
"(",
"type_spec",
")",
":",
"return",
"lambda",
"x",
":",
"None",
"if",
"(",
"isclass",
"(",
"x",
")",
"is",
"True",
"and",
"issubclass",
"(",
"x",
",",
"type_spec",
")",
"is",
"True",
")",
"else",
"raise_exception",
"(",
"str",
"(",
"x",
")",
")",
"else",
":",
"raise",
"RuntimeError",
"(",
"'Invalid specification. Must be type or tuple/list/set of types'",
")"
] | Return callable that checks function parameter for class validity. Checks parameter if it is
class or subclass of specified class or classes
:param type_spec: type or list/tuple/set of types
:param arg_name: function parameter name
:param decorated_function: target function
:return: function | [
"Return",
"callable",
"that",
"checks",
"function",
"parameter",
"for",
"class",
"validity",
".",
"Checks",
"parameter",
"if",
"it",
"is",
"class",
"or",
"subclass",
"of",
"specified",
"class",
"or",
"classes"
] | 1029839d33eb663f8dec76c1c46754d53c1de4a9 | https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/verify.py#L374-L409 | train |
a1ezzz/wasp-general | wasp_general/verify.py | ValueVerifier.check | def check(self, value_spec, arg_name, decorated_function):
""" Return callable that checks function parameter for value validity. Checks parameter if its value
passes specified restrictions.
:param value_spec: function or list/tuple/set of functions. Each function must accept one parameter and \
must return True or False if it passed restrictions or not.
:param arg_name: function parameter name
:param decorated_function: target function
:return: function
"""
def raise_exception(text_spec):
exc_text = 'Argument "%s" for function "%s" has invalid value' % (
arg_name, Verifier.function_name(decorated_function)
)
exc_text += ' (%s)' % text_spec
raise ValueError(exc_text)
if isinstance(value_spec, (tuple, list, set)):
for single_value in value_spec:
if isfunction(single_value) is False:
raise RuntimeError(
'Invalid specification. Must be function or tuple/list/set of functions'
)
def check(x):
for f in value_spec:
if f(x) is not True:
raise_exception(str(x))
return check
elif isfunction(value_spec):
return lambda x: None if value_spec(x) is True else raise_exception(str(x))
else:
raise RuntimeError('Invalid specification. Must be function or tuple/list/set of functions') | python | def check(self, value_spec, arg_name, decorated_function):
""" Return callable that checks function parameter for value validity. Checks parameter if its value
passes specified restrictions.
:param value_spec: function or list/tuple/set of functions. Each function must accept one parameter and \
must return True or False if it passed restrictions or not.
:param arg_name: function parameter name
:param decorated_function: target function
:return: function
"""
def raise_exception(text_spec):
exc_text = 'Argument "%s" for function "%s" has invalid value' % (
arg_name, Verifier.function_name(decorated_function)
)
exc_text += ' (%s)' % text_spec
raise ValueError(exc_text)
if isinstance(value_spec, (tuple, list, set)):
for single_value in value_spec:
if isfunction(single_value) is False:
raise RuntimeError(
'Invalid specification. Must be function or tuple/list/set of functions'
)
def check(x):
for f in value_spec:
if f(x) is not True:
raise_exception(str(x))
return check
elif isfunction(value_spec):
return lambda x: None if value_spec(x) is True else raise_exception(str(x))
else:
raise RuntimeError('Invalid specification. Must be function or tuple/list/set of functions') | [
"def",
"check",
"(",
"self",
",",
"value_spec",
",",
"arg_name",
",",
"decorated_function",
")",
":",
"def",
"raise_exception",
"(",
"text_spec",
")",
":",
"exc_text",
"=",
"'Argument \"%s\" for function \"%s\" has invalid value'",
"%",
"(",
"arg_name",
",",
"Verifier",
".",
"function_name",
"(",
"decorated_function",
")",
")",
"exc_text",
"+=",
"' (%s)'",
"%",
"text_spec",
"raise",
"ValueError",
"(",
"exc_text",
")",
"if",
"isinstance",
"(",
"value_spec",
",",
"(",
"tuple",
",",
"list",
",",
"set",
")",
")",
":",
"for",
"single_value",
"in",
"value_spec",
":",
"if",
"isfunction",
"(",
"single_value",
")",
"is",
"False",
":",
"raise",
"RuntimeError",
"(",
"'Invalid specification. Must be function or tuple/list/set of functions'",
")",
"def",
"check",
"(",
"x",
")",
":",
"for",
"f",
"in",
"value_spec",
":",
"if",
"f",
"(",
"x",
")",
"is",
"not",
"True",
":",
"raise_exception",
"(",
"str",
"(",
"x",
")",
")",
"return",
"check",
"elif",
"isfunction",
"(",
"value_spec",
")",
":",
"return",
"lambda",
"x",
":",
"None",
"if",
"value_spec",
"(",
"x",
")",
"is",
"True",
"else",
"raise_exception",
"(",
"str",
"(",
"x",
")",
")",
"else",
":",
"raise",
"RuntimeError",
"(",
"'Invalid specification. Must be function or tuple/list/set of functions'",
")"
] | Return callable that checks function parameter for value validity. Checks parameter if its value
passes specified restrictions.
:param value_spec: function or list/tuple/set of functions. Each function must accept one parameter and \
must return True or False if it passed restrictions or not.
:param arg_name: function parameter name
:param decorated_function: target function
:return: function | [
"Return",
"callable",
"that",
"checks",
"function",
"parameter",
"for",
"value",
"validity",
".",
"Checks",
"parameter",
"if",
"its",
"value",
"passes",
"specified",
"restrictions",
"."
] | 1029839d33eb663f8dec76c1c46754d53c1de4a9 | https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/verify.py#L425-L461 | train |
a1ezzz/wasp-general | wasp_general/cache.py | cache_control | def cache_control(validator=None, storage=None):
""" Decorator that is used for caching result.
:param validator: function, that has following signature (decorated_function, \*args, \*\*kwargs), where \
decorated_function - original function, args - function arguments, kwargs - function keyword arguments. \
This function must return True if cache is valid (old result must be use if it there is one), or False - to \
generate and to store new result. So function that always return True can be used as singleton. And function \
that always return False won't cache anything at all. By default (if no validator is specified), it presumes \
that cache is always valid.
:param storage: storage that is used for caching results. see :class:`.WCacheStorage` class.
:return: decorated function
"""
def default_validator(*args, **kwargs):
return True
if validator is None:
validator = default_validator
if storage is None:
storage = WGlobalSingletonCacheStorage()
def first_level_decorator(decorated_function):
def second_level_decorator(original_function, *args, **kwargs):
validator_check = validator(original_function, *args, **kwargs)
cache_entry = storage.get_cache(original_function, *args, **kwargs)
if validator_check is not True or cache_entry.has_value is False:
result = original_function(*args, **kwargs)
storage.put(result, original_function, *args, **kwargs)
return result
else:
return cache_entry.cached_value
return decorator(second_level_decorator)(decorated_function)
return first_level_decorator | python | def cache_control(validator=None, storage=None):
""" Decorator that is used for caching result.
:param validator: function, that has following signature (decorated_function, \*args, \*\*kwargs), where \
decorated_function - original function, args - function arguments, kwargs - function keyword arguments. \
This function must return True if cache is valid (old result must be use if it there is one), or False - to \
generate and to store new result. So function that always return True can be used as singleton. And function \
that always return False won't cache anything at all. By default (if no validator is specified), it presumes \
that cache is always valid.
:param storage: storage that is used for caching results. see :class:`.WCacheStorage` class.
:return: decorated function
"""
def default_validator(*args, **kwargs):
return True
if validator is None:
validator = default_validator
if storage is None:
storage = WGlobalSingletonCacheStorage()
def first_level_decorator(decorated_function):
def second_level_decorator(original_function, *args, **kwargs):
validator_check = validator(original_function, *args, **kwargs)
cache_entry = storage.get_cache(original_function, *args, **kwargs)
if validator_check is not True or cache_entry.has_value is False:
result = original_function(*args, **kwargs)
storage.put(result, original_function, *args, **kwargs)
return result
else:
return cache_entry.cached_value
return decorator(second_level_decorator)(decorated_function)
return first_level_decorator | [
"def",
"cache_control",
"(",
"validator",
"=",
"None",
",",
"storage",
"=",
"None",
")",
":",
"def",
"default_validator",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"True",
"if",
"validator",
"is",
"None",
":",
"validator",
"=",
"default_validator",
"if",
"storage",
"is",
"None",
":",
"storage",
"=",
"WGlobalSingletonCacheStorage",
"(",
")",
"def",
"first_level_decorator",
"(",
"decorated_function",
")",
":",
"def",
"second_level_decorator",
"(",
"original_function",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"validator_check",
"=",
"validator",
"(",
"original_function",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"cache_entry",
"=",
"storage",
".",
"get_cache",
"(",
"original_function",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"if",
"validator_check",
"is",
"not",
"True",
"or",
"cache_entry",
".",
"has_value",
"is",
"False",
":",
"result",
"=",
"original_function",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"storage",
".",
"put",
"(",
"result",
",",
"original_function",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"result",
"else",
":",
"return",
"cache_entry",
".",
"cached_value",
"return",
"decorator",
"(",
"second_level_decorator",
")",
"(",
"decorated_function",
")",
"return",
"first_level_decorator"
] | Decorator that is used for caching result.
:param validator: function, that has following signature (decorated_function, \*args, \*\*kwargs), where \
decorated_function - original function, args - function arguments, kwargs - function keyword arguments. \
This function must return True if cache is valid (old result must be use if it there is one), or False - to \
generate and to store new result. So function that always return True can be used as singleton. And function \
that always return False won't cache anything at all. By default (if no validator is specified), it presumes \
that cache is always valid.
:param storage: storage that is used for caching results. see :class:`.WCacheStorage` class.
:return: decorated function | [
"Decorator",
"that",
"is",
"used",
"for",
"caching",
"result",
"."
] | 1029839d33eb663f8dec76c1c46754d53c1de4a9 | https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/cache.py#L384-L421 | train |
a1ezzz/wasp-general | wasp_general/cache.py | WCacheStorage.has | def has(self, decorated_function, *args, **kwargs):
""" Check if there is a result for given function
:param decorated_function: called function (original)
:param args: args with which function is called
:param kwargs: kwargs with which function is called
:return: None
"""
return self.get_cache(decorated_function, *args, **kwargs).has_value | python | def has(self, decorated_function, *args, **kwargs):
""" Check if there is a result for given function
:param decorated_function: called function (original)
:param args: args with which function is called
:param kwargs: kwargs with which function is called
:return: None
"""
return self.get_cache(decorated_function, *args, **kwargs).has_value | [
"def",
"has",
"(",
"self",
",",
"decorated_function",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"get_cache",
"(",
"decorated_function",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
".",
"has_value"
] | Check if there is a result for given function
:param decorated_function: called function (original)
:param args: args with which function is called
:param kwargs: kwargs with which function is called
:return: None | [
"Check",
"if",
"there",
"is",
"a",
"result",
"for",
"given",
"function"
] | 1029839d33eb663f8dec76c1c46754d53c1de4a9 | https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/cache.py#L99-L108 | train |
a1ezzz/wasp-general | wasp_general/cache.py | WInstanceSingletonCacheStorage.__check | def __check(self, decorated_function, *args, **kwargs):
""" Check whether function is a bounded method or not. If check fails then exception is raised
:param decorated_function: called function (original)
:param args: args with which function is called
:param kwargs: kwargs with which function is called
:return: None
"""
# TODO replace this function with decorator which can be turned off like verify_* does
if len(args) >= 1:
obj = args[0]
function_name = decorated_function.__name__
if hasattr(obj, function_name) is True:
fn = getattr(obj, function_name)
if callable(fn) and fn.__self__ == obj:
return
raise RuntimeError('Only bounded methods are allowed') | python | def __check(self, decorated_function, *args, **kwargs):
""" Check whether function is a bounded method or not. If check fails then exception is raised
:param decorated_function: called function (original)
:param args: args with which function is called
:param kwargs: kwargs with which function is called
:return: None
"""
# TODO replace this function with decorator which can be turned off like verify_* does
if len(args) >= 1:
obj = args[0]
function_name = decorated_function.__name__
if hasattr(obj, function_name) is True:
fn = getattr(obj, function_name)
if callable(fn) and fn.__self__ == obj:
return
raise RuntimeError('Only bounded methods are allowed') | [
"def",
"__check",
"(",
"self",
",",
"decorated_function",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# TODO replace this function with decorator which can be turned off like verify_* does",
"if",
"len",
"(",
"args",
")",
">=",
"1",
":",
"obj",
"=",
"args",
"[",
"0",
"]",
"function_name",
"=",
"decorated_function",
".",
"__name__",
"if",
"hasattr",
"(",
"obj",
",",
"function_name",
")",
"is",
"True",
":",
"fn",
"=",
"getattr",
"(",
"obj",
",",
"function_name",
")",
"if",
"callable",
"(",
"fn",
")",
"and",
"fn",
".",
"__self__",
"==",
"obj",
":",
"return",
"raise",
"RuntimeError",
"(",
"'Only bounded methods are allowed'",
")"
] | Check whether function is a bounded method or not. If check fails then exception is raised
:param decorated_function: called function (original)
:param args: args with which function is called
:param kwargs: kwargs with which function is called
:return: None | [
"Check",
"whether",
"function",
"is",
"a",
"bounded",
"method",
"or",
"not",
".",
"If",
"check",
"fails",
"then",
"exception",
"is",
"raised"
] | 1029839d33eb663f8dec76c1c46754d53c1de4a9 | https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/cache.py#L279-L296 | train |
alixnovosi/drewtilities | drewtilities/drewtilities.py | ensure_dir | def ensure_dir(directory: str) -> None:
"""Create a directory if it doesn't exist."""
if not os.path.isdir(directory):
LOG.debug(f"Directory {directory} does not exist, creating it.")
os.makedirs(directory) | python | def ensure_dir(directory: str) -> None:
"""Create a directory if it doesn't exist."""
if not os.path.isdir(directory):
LOG.debug(f"Directory {directory} does not exist, creating it.")
os.makedirs(directory) | [
"def",
"ensure_dir",
"(",
"directory",
":",
"str",
")",
"->",
"None",
":",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"directory",
")",
":",
"LOG",
".",
"debug",
"(",
"f\"Directory {directory} does not exist, creating it.\"",
")",
"os",
".",
"makedirs",
"(",
"directory",
")"
] | Create a directory if it doesn't exist. | [
"Create",
"a",
"directory",
"if",
"it",
"doesn",
"t",
"exist",
"."
] | 4e9b7f65f11195dc48347bf9c6ca4e56baca8b45 | https://github.com/alixnovosi/drewtilities/blob/4e9b7f65f11195dc48347bf9c6ca4e56baca8b45/drewtilities/drewtilities.py#L22-L26 | train |
alixnovosi/drewtilities | drewtilities/drewtilities.py | expand | def expand(directory: str) -> str:
"""Apply expanduser and expandvars to directory to expand '~' and env vars."""
temp1 = os.path.expanduser(directory)
return os.path.expandvars(temp1) | python | def expand(directory: str) -> str:
"""Apply expanduser and expandvars to directory to expand '~' and env vars."""
temp1 = os.path.expanduser(directory)
return os.path.expandvars(temp1) | [
"def",
"expand",
"(",
"directory",
":",
"str",
")",
"->",
"str",
":",
"temp1",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"directory",
")",
"return",
"os",
".",
"path",
".",
"expandvars",
"(",
"temp1",
")"
] | Apply expanduser and expandvars to directory to expand '~' and env vars. | [
"Apply",
"expanduser",
"and",
"expandvars",
"to",
"directory",
"to",
"expand",
"~",
"and",
"env",
"vars",
"."
] | 4e9b7f65f11195dc48347bf9c6ca4e56baca8b45 | https://github.com/alixnovosi/drewtilities/blob/4e9b7f65f11195dc48347bf9c6ca4e56baca8b45/drewtilities/drewtilities.py#L28-L31 | train |
alixnovosi/drewtilities | drewtilities/drewtilities.py | generate_downloader | def generate_downloader(headers: Dict[str, str], args: Any, max_per_hour: int=30
) -> Callable[..., None]:
"""Create function to download with rate limiting and text progress."""
def _downloader(url: str, dest: str) -> None:
@rate_limited(max_per_hour, args)
def _rate_limited_download() -> None:
# Create parent directory of file, and its parents, if they don't exist.
parent = os.path.dirname(dest)
if not os.path.exists(parent):
os.makedirs(parent)
response = requests.get(url, headers=headers, stream=True)
LOG.info(f"Downloading from '{url}'.")
LOG.info(f"Trying to save to '{dest}'.")
length = response.headers.get("content-length")
if length is None:
total_length = 0
else:
total_length = int(length)
expected_size = (total_length / CHUNK_SIZE) + 1
chunks = response.iter_content(chunk_size=CHUNK_SIZE)
open(dest, "a", encoding=FORCED_ENCODING).close()
# per http://stackoverflow.com/a/20943461
with open(dest, "wb") as stream:
for chunk in tui.progress.bar(chunks, expected_size=expected_size):
if not chunk:
return
stream.write(chunk)
stream.flush()
_rate_limited_download()
return _downloader | python | def generate_downloader(headers: Dict[str, str], args: Any, max_per_hour: int=30
) -> Callable[..., None]:
"""Create function to download with rate limiting and text progress."""
def _downloader(url: str, dest: str) -> None:
@rate_limited(max_per_hour, args)
def _rate_limited_download() -> None:
# Create parent directory of file, and its parents, if they don't exist.
parent = os.path.dirname(dest)
if not os.path.exists(parent):
os.makedirs(parent)
response = requests.get(url, headers=headers, stream=True)
LOG.info(f"Downloading from '{url}'.")
LOG.info(f"Trying to save to '{dest}'.")
length = response.headers.get("content-length")
if length is None:
total_length = 0
else:
total_length = int(length)
expected_size = (total_length / CHUNK_SIZE) + 1
chunks = response.iter_content(chunk_size=CHUNK_SIZE)
open(dest, "a", encoding=FORCED_ENCODING).close()
# per http://stackoverflow.com/a/20943461
with open(dest, "wb") as stream:
for chunk in tui.progress.bar(chunks, expected_size=expected_size):
if not chunk:
return
stream.write(chunk)
stream.flush()
_rate_limited_download()
return _downloader | [
"def",
"generate_downloader",
"(",
"headers",
":",
"Dict",
"[",
"str",
",",
"str",
"]",
",",
"args",
":",
"Any",
",",
"max_per_hour",
":",
"int",
"=",
"30",
")",
"->",
"Callable",
"[",
"...",
",",
"None",
"]",
":",
"def",
"_downloader",
"(",
"url",
":",
"str",
",",
"dest",
":",
"str",
")",
"->",
"None",
":",
"@",
"rate_limited",
"(",
"max_per_hour",
",",
"args",
")",
"def",
"_rate_limited_download",
"(",
")",
"->",
"None",
":",
"# Create parent directory of file, and its parents, if they don't exist.",
"parent",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"dest",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"parent",
")",
":",
"os",
".",
"makedirs",
"(",
"parent",
")",
"response",
"=",
"requests",
".",
"get",
"(",
"url",
",",
"headers",
"=",
"headers",
",",
"stream",
"=",
"True",
")",
"LOG",
".",
"info",
"(",
"f\"Downloading from '{url}'.\"",
")",
"LOG",
".",
"info",
"(",
"f\"Trying to save to '{dest}'.\"",
")",
"length",
"=",
"response",
".",
"headers",
".",
"get",
"(",
"\"content-length\"",
")",
"if",
"length",
"is",
"None",
":",
"total_length",
"=",
"0",
"else",
":",
"total_length",
"=",
"int",
"(",
"length",
")",
"expected_size",
"=",
"(",
"total_length",
"/",
"CHUNK_SIZE",
")",
"+",
"1",
"chunks",
"=",
"response",
".",
"iter_content",
"(",
"chunk_size",
"=",
"CHUNK_SIZE",
")",
"open",
"(",
"dest",
",",
"\"a\"",
",",
"encoding",
"=",
"FORCED_ENCODING",
")",
".",
"close",
"(",
")",
"# per http://stackoverflow.com/a/20943461",
"with",
"open",
"(",
"dest",
",",
"\"wb\"",
")",
"as",
"stream",
":",
"for",
"chunk",
"in",
"tui",
".",
"progress",
".",
"bar",
"(",
"chunks",
",",
"expected_size",
"=",
"expected_size",
")",
":",
"if",
"not",
"chunk",
":",
"return",
"stream",
".",
"write",
"(",
"chunk",
")",
"stream",
".",
"flush",
"(",
")",
"_rate_limited_download",
"(",
")",
"return",
"_downloader"
] | Create function to download with rate limiting and text progress. | [
"Create",
"function",
"to",
"download",
"with",
"rate",
"limiting",
"and",
"text",
"progress",
"."
] | 4e9b7f65f11195dc48347bf9c6ca4e56baca8b45 | https://github.com/alixnovosi/drewtilities/blob/4e9b7f65f11195dc48347bf9c6ca4e56baca8b45/drewtilities/drewtilities.py#L33-L71 | train |
alixnovosi/drewtilities | drewtilities/drewtilities.py | parse_int_string | def parse_int_string(int_string: str) -> List[int]:
"""
Given a string like "1 23 4-8 32 1", return a unique list of those integers in the string and
the integers in the ranges in the string.
Non-numbers ignored. Not necessarily sorted
"""
cleaned = " ".join(int_string.strip().split())
cleaned = cleaned.replace(" - ", "-")
cleaned = cleaned.replace(",", " ")
tokens = cleaned.split(" ")
indices: Set[int] = set()
for token in tokens:
if "-" in token:
endpoints = token.split("-")
if len(endpoints) != 2:
LOG.info(f"Dropping '{token}' as invalid - weird range.")
continue
start = int(endpoints[0])
end = int(endpoints[1]) + 1
indices = indices.union(indices, set(range(start, end)))
else:
try:
indices.add(int(token))
except ValueError:
LOG.info(f"Dropping '{token}' as invalid - not an int.")
return list(indices) | python | def parse_int_string(int_string: str) -> List[int]:
"""
Given a string like "1 23 4-8 32 1", return a unique list of those integers in the string and
the integers in the ranges in the string.
Non-numbers ignored. Not necessarily sorted
"""
cleaned = " ".join(int_string.strip().split())
cleaned = cleaned.replace(" - ", "-")
cleaned = cleaned.replace(",", " ")
tokens = cleaned.split(" ")
indices: Set[int] = set()
for token in tokens:
if "-" in token:
endpoints = token.split("-")
if len(endpoints) != 2:
LOG.info(f"Dropping '{token}' as invalid - weird range.")
continue
start = int(endpoints[0])
end = int(endpoints[1]) + 1
indices = indices.union(indices, set(range(start, end)))
else:
try:
indices.add(int(token))
except ValueError:
LOG.info(f"Dropping '{token}' as invalid - not an int.")
return list(indices) | [
"def",
"parse_int_string",
"(",
"int_string",
":",
"str",
")",
"->",
"List",
"[",
"int",
"]",
":",
"cleaned",
"=",
"\" \"",
".",
"join",
"(",
"int_string",
".",
"strip",
"(",
")",
".",
"split",
"(",
")",
")",
"cleaned",
"=",
"cleaned",
".",
"replace",
"(",
"\" - \"",
",",
"\"-\"",
")",
"cleaned",
"=",
"cleaned",
".",
"replace",
"(",
"\",\"",
",",
"\" \"",
")",
"tokens",
"=",
"cleaned",
".",
"split",
"(",
"\" \"",
")",
"indices",
":",
"Set",
"[",
"int",
"]",
"=",
"set",
"(",
")",
"for",
"token",
"in",
"tokens",
":",
"if",
"\"-\"",
"in",
"token",
":",
"endpoints",
"=",
"token",
".",
"split",
"(",
"\"-\"",
")",
"if",
"len",
"(",
"endpoints",
")",
"!=",
"2",
":",
"LOG",
".",
"info",
"(",
"f\"Dropping '{token}' as invalid - weird range.\"",
")",
"continue",
"start",
"=",
"int",
"(",
"endpoints",
"[",
"0",
"]",
")",
"end",
"=",
"int",
"(",
"endpoints",
"[",
"1",
"]",
")",
"+",
"1",
"indices",
"=",
"indices",
".",
"union",
"(",
"indices",
",",
"set",
"(",
"range",
"(",
"start",
",",
"end",
")",
")",
")",
"else",
":",
"try",
":",
"indices",
".",
"add",
"(",
"int",
"(",
"token",
")",
")",
"except",
"ValueError",
":",
"LOG",
".",
"info",
"(",
"f\"Dropping '{token}' as invalid - not an int.\"",
")",
"return",
"list",
"(",
"indices",
")"
] | Given a string like "1 23 4-8 32 1", return a unique list of those integers in the string and
the integers in the ranges in the string.
Non-numbers ignored. Not necessarily sorted | [
"Given",
"a",
"string",
"like",
"1",
"23",
"4",
"-",
"8",
"32",
"1",
"return",
"a",
"unique",
"list",
"of",
"those",
"integers",
"in",
"the",
"string",
"and",
"the",
"integers",
"in",
"the",
"ranges",
"in",
"the",
"string",
".",
"Non",
"-",
"numbers",
"ignored",
".",
"Not",
"necessarily",
"sorted"
] | 4e9b7f65f11195dc48347bf9c6ca4e56baca8b45 | https://github.com/alixnovosi/drewtilities/blob/4e9b7f65f11195dc48347bf9c6ca4e56baca8b45/drewtilities/drewtilities.py#L77-L107 | train |
alixnovosi/drewtilities | drewtilities/drewtilities.py | set_up_logging | def set_up_logging(log_filename: str = "log", verbosity: int = 0) ->logging.Logger:
"""Set up proper logging."""
LOG.setLevel(logging.DEBUG)
# Log everything verbosely to a file.
file_handler = RotatingFileHandler(filename=log_filename, maxBytes=1024000000, backupCount=10)
verbose_form = logging.Formatter(fmt="%(asctime)s - %(levelname)s - %(module)s - %(message)s")
file_handler.setFormatter(verbose_form)
file_handler.setLevel(logging.DEBUG)
LOG.addHandler(file_handler)
# Provide a stdout handler logging at INFO.
stream_handler = logging.StreamHandler(sys.stdout)
simple_form = logging.Formatter(fmt="%(message)s")
stream_handler.setFormatter(simple_form)
if verbosity > 0:
stream_handler.setLevel(logging.DEBUG)
else:
stream_handler.setLevel(logging.INFO)
LOG.addHandler(stream_handler)
return LOG | python | def set_up_logging(log_filename: str = "log", verbosity: int = 0) ->logging.Logger:
"""Set up proper logging."""
LOG.setLevel(logging.DEBUG)
# Log everything verbosely to a file.
file_handler = RotatingFileHandler(filename=log_filename, maxBytes=1024000000, backupCount=10)
verbose_form = logging.Formatter(fmt="%(asctime)s - %(levelname)s - %(module)s - %(message)s")
file_handler.setFormatter(verbose_form)
file_handler.setLevel(logging.DEBUG)
LOG.addHandler(file_handler)
# Provide a stdout handler logging at INFO.
stream_handler = logging.StreamHandler(sys.stdout)
simple_form = logging.Formatter(fmt="%(message)s")
stream_handler.setFormatter(simple_form)
if verbosity > 0:
stream_handler.setLevel(logging.DEBUG)
else:
stream_handler.setLevel(logging.INFO)
LOG.addHandler(stream_handler)
return LOG | [
"def",
"set_up_logging",
"(",
"log_filename",
":",
"str",
"=",
"\"log\"",
",",
"verbosity",
":",
"int",
"=",
"0",
")",
"->",
"logging",
".",
"Logger",
":",
"LOG",
".",
"setLevel",
"(",
"logging",
".",
"DEBUG",
")",
"# Log everything verbosely to a file.",
"file_handler",
"=",
"RotatingFileHandler",
"(",
"filename",
"=",
"log_filename",
",",
"maxBytes",
"=",
"1024000000",
",",
"backupCount",
"=",
"10",
")",
"verbose_form",
"=",
"logging",
".",
"Formatter",
"(",
"fmt",
"=",
"\"%(asctime)s - %(levelname)s - %(module)s - %(message)s\"",
")",
"file_handler",
".",
"setFormatter",
"(",
"verbose_form",
")",
"file_handler",
".",
"setLevel",
"(",
"logging",
".",
"DEBUG",
")",
"LOG",
".",
"addHandler",
"(",
"file_handler",
")",
"# Provide a stdout handler logging at INFO.",
"stream_handler",
"=",
"logging",
".",
"StreamHandler",
"(",
"sys",
".",
"stdout",
")",
"simple_form",
"=",
"logging",
".",
"Formatter",
"(",
"fmt",
"=",
"\"%(message)s\"",
")",
"stream_handler",
".",
"setFormatter",
"(",
"simple_form",
")",
"if",
"verbosity",
">",
"0",
":",
"stream_handler",
".",
"setLevel",
"(",
"logging",
".",
"DEBUG",
")",
"else",
":",
"stream_handler",
".",
"setLevel",
"(",
"logging",
".",
"INFO",
")",
"LOG",
".",
"addHandler",
"(",
"stream_handler",
")",
"return",
"LOG"
] | Set up proper logging. | [
"Set",
"up",
"proper",
"logging",
"."
] | 4e9b7f65f11195dc48347bf9c6ca4e56baca8b45 | https://github.com/alixnovosi/drewtilities/blob/4e9b7f65f11195dc48347bf9c6ca4e56baca8b45/drewtilities/drewtilities.py#L180-L203 | train |
alixnovosi/drewtilities | drewtilities/drewtilities.py | random_line | def random_line(file_path: str, encoding: str = FORCED_ENCODING) -> str:
"""Get random line from a file."""
# Fancy alg from http://stackoverflow.com/a/35579149 to avoid loading full file.
line_num = 0
selected_line = ""
with open(file_path, encoding=encoding) as stream:
while True:
line = stream.readline()
if not line:
break
line_num += 1
if random.uniform(0, line_num) < 1:
selected_line = line
return selected_line.strip() | python | def random_line(file_path: str, encoding: str = FORCED_ENCODING) -> str:
"""Get random line from a file."""
# Fancy alg from http://stackoverflow.com/a/35579149 to avoid loading full file.
line_num = 0
selected_line = ""
with open(file_path, encoding=encoding) as stream:
while True:
line = stream.readline()
if not line:
break
line_num += 1
if random.uniform(0, line_num) < 1:
selected_line = line
return selected_line.strip() | [
"def",
"random_line",
"(",
"file_path",
":",
"str",
",",
"encoding",
":",
"str",
"=",
"FORCED_ENCODING",
")",
"->",
"str",
":",
"# Fancy alg from http://stackoverflow.com/a/35579149 to avoid loading full file.",
"line_num",
"=",
"0",
"selected_line",
"=",
"\"\"",
"with",
"open",
"(",
"file_path",
",",
"encoding",
"=",
"encoding",
")",
"as",
"stream",
":",
"while",
"True",
":",
"line",
"=",
"stream",
".",
"readline",
"(",
")",
"if",
"not",
"line",
":",
"break",
"line_num",
"+=",
"1",
"if",
"random",
".",
"uniform",
"(",
"0",
",",
"line_num",
")",
"<",
"1",
":",
"selected_line",
"=",
"line",
"return",
"selected_line",
".",
"strip",
"(",
")"
] | Get random line from a file. | [
"Get",
"random",
"line",
"from",
"a",
"file",
"."
] | 4e9b7f65f11195dc48347bf9c6ca4e56baca8b45 | https://github.com/alixnovosi/drewtilities/blob/4e9b7f65f11195dc48347bf9c6ca4e56baca8b45/drewtilities/drewtilities.py#L205-L219 | train |
vecnet/vecnet.openmalaria | vecnet/openmalaria/healthsystem.py | get_percentage_from_prob | def get_percentage_from_prob(prob):
"""
Converted probability of being treated to total percentage of clinical cases treated
"""
assert isinstance(prob, (float, int))
prob = float(prob)
assert prob >= 0
assert prob <= 1
percentages = list(probability_list.keys())
percentages.sort()
for percentage in percentages:
if prob < probability_list[percentage]:
return percentage - 1
return 100 | python | def get_percentage_from_prob(prob):
"""
Converted probability of being treated to total percentage of clinical cases treated
"""
assert isinstance(prob, (float, int))
prob = float(prob)
assert prob >= 0
assert prob <= 1
percentages = list(probability_list.keys())
percentages.sort()
for percentage in percentages:
if prob < probability_list[percentage]:
return percentage - 1
return 100 | [
"def",
"get_percentage_from_prob",
"(",
"prob",
")",
":",
"assert",
"isinstance",
"(",
"prob",
",",
"(",
"float",
",",
"int",
")",
")",
"prob",
"=",
"float",
"(",
"prob",
")",
"assert",
"prob",
">=",
"0",
"assert",
"prob",
"<=",
"1",
"percentages",
"=",
"list",
"(",
"probability_list",
".",
"keys",
"(",
")",
")",
"percentages",
".",
"sort",
"(",
")",
"for",
"percentage",
"in",
"percentages",
":",
"if",
"prob",
"<",
"probability_list",
"[",
"percentage",
"]",
":",
"return",
"percentage",
"-",
"1",
"return",
"100"
] | Converted probability of being treated to total percentage of clinical cases treated | [
"Converted",
"probability",
"of",
"being",
"treated",
"to",
"total",
"percentage",
"of",
"clinical",
"cases",
"treated"
] | 795bc9d1b81a6c664f14879edda7a7c41188e95a | https://github.com/vecnet/vecnet.openmalaria/blob/795bc9d1b81a6c664f14879edda7a7c41188e95a/vecnet/openmalaria/healthsystem.py#L135-L149 | train |
OpenGov/og-python-utils | ogutils/functions/decorators.py | listify | def listify(generator_func):
'''
Converts generator functions into list returning functions.
@listify
def test():
yield 1
test()
# => [1]
'''
def list_func(*args, **kwargs):
return degenerate(generator_func(*args, **kwargs))
return list_func | python | def listify(generator_func):
'''
Converts generator functions into list returning functions.
@listify
def test():
yield 1
test()
# => [1]
'''
def list_func(*args, **kwargs):
return degenerate(generator_func(*args, **kwargs))
return list_func | [
"def",
"listify",
"(",
"generator_func",
")",
":",
"def",
"list_func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"degenerate",
"(",
"generator_func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
")",
"return",
"list_func"
] | Converts generator functions into list returning functions.
@listify
def test():
yield 1
test()
# => [1] | [
"Converts",
"generator",
"functions",
"into",
"list",
"returning",
"functions",
"."
] | 00f44927383dd1bd6348f47302c4453d56963479 | https://github.com/OpenGov/og-python-utils/blob/00f44927383dd1bd6348f47302c4453d56963479/ogutils/functions/decorators.py#L3-L15 | train |
mangalam-research/selenic | selenic/util.py | locations_within | def locations_within(a, b, tolerance):
"""
Verifies whether two positions are the same. A tolerance value
determines how close the two positions must be to be considered
"same".
The two locations must be dictionaries that have the same keys. If
a key is pesent in one but not in the other, this is an error. The
values must be integers or anything that can be converted to an
integer through ``int``. (If somehow you need floating point
precision, this is not the function for you.)
Do not rely on this function to determine whether two object have
the same keys. If the function finds the locations to be within
tolerances, then the two objects have the same keys. Otherwise,
you cannot infer anything regarding the keys because the function
will return as soon as it knows that the two locations are **not**
within tolerance.
:param a: First position.
:type a: :class:`dict`
:param b: Second position.
:type b: :class:`dict`
:param tolerance: The tolerance within which the two positions
must be.
:return: An empty string if the comparison is successful. Otherwise,
the string contains a description of the differences.
:rtype: :class:`str`
:raises ValueError: When a key is present in one object but not
the other.
"""
ret = ''
# Clone b so that we can destroy it.
b = dict(b)
for (key, value) in a.items():
if key not in b:
raise ValueError("b does not have the key: " + key)
if abs(int(value) - int(b[key])) > tolerance:
ret += 'key {0} differs: {1} {2}'.format(key, int(value),
int(b[key]))
del b[key]
if b:
raise ValueError("keys in b not seen in a: " + ", ".join(b.keys()))
return ret | python | def locations_within(a, b, tolerance):
"""
Verifies whether two positions are the same. A tolerance value
determines how close the two positions must be to be considered
"same".
The two locations must be dictionaries that have the same keys. If
a key is pesent in one but not in the other, this is an error. The
values must be integers or anything that can be converted to an
integer through ``int``. (If somehow you need floating point
precision, this is not the function for you.)
Do not rely on this function to determine whether two object have
the same keys. If the function finds the locations to be within
tolerances, then the two objects have the same keys. Otherwise,
you cannot infer anything regarding the keys because the function
will return as soon as it knows that the two locations are **not**
within tolerance.
:param a: First position.
:type a: :class:`dict`
:param b: Second position.
:type b: :class:`dict`
:param tolerance: The tolerance within which the two positions
must be.
:return: An empty string if the comparison is successful. Otherwise,
the string contains a description of the differences.
:rtype: :class:`str`
:raises ValueError: When a key is present in one object but not
the other.
"""
ret = ''
# Clone b so that we can destroy it.
b = dict(b)
for (key, value) in a.items():
if key not in b:
raise ValueError("b does not have the key: " + key)
if abs(int(value) - int(b[key])) > tolerance:
ret += 'key {0} differs: {1} {2}'.format(key, int(value),
int(b[key]))
del b[key]
if b:
raise ValueError("keys in b not seen in a: " + ", ".join(b.keys()))
return ret | [
"def",
"locations_within",
"(",
"a",
",",
"b",
",",
"tolerance",
")",
":",
"ret",
"=",
"''",
"# Clone b so that we can destroy it.",
"b",
"=",
"dict",
"(",
"b",
")",
"for",
"(",
"key",
",",
"value",
")",
"in",
"a",
".",
"items",
"(",
")",
":",
"if",
"key",
"not",
"in",
"b",
":",
"raise",
"ValueError",
"(",
"\"b does not have the key: \"",
"+",
"key",
")",
"if",
"abs",
"(",
"int",
"(",
"value",
")",
"-",
"int",
"(",
"b",
"[",
"key",
"]",
")",
")",
">",
"tolerance",
":",
"ret",
"+=",
"'key {0} differs: {1} {2}'",
".",
"format",
"(",
"key",
",",
"int",
"(",
"value",
")",
",",
"int",
"(",
"b",
"[",
"key",
"]",
")",
")",
"del",
"b",
"[",
"key",
"]",
"if",
"b",
":",
"raise",
"ValueError",
"(",
"\"keys in b not seen in a: \"",
"+",
"\", \"",
".",
"join",
"(",
"b",
".",
"keys",
"(",
")",
")",
")",
"return",
"ret"
] | Verifies whether two positions are the same. A tolerance value
determines how close the two positions must be to be considered
"same".
The two locations must be dictionaries that have the same keys. If
a key is pesent in one but not in the other, this is an error. The
values must be integers or anything that can be converted to an
integer through ``int``. (If somehow you need floating point
precision, this is not the function for you.)
Do not rely on this function to determine whether two object have
the same keys. If the function finds the locations to be within
tolerances, then the two objects have the same keys. Otherwise,
you cannot infer anything regarding the keys because the function
will return as soon as it knows that the two locations are **not**
within tolerance.
:param a: First position.
:type a: :class:`dict`
:param b: Second position.
:type b: :class:`dict`
:param tolerance: The tolerance within which the two positions
must be.
:return: An empty string if the comparison is successful. Otherwise,
the string contains a description of the differences.
:rtype: :class:`str`
:raises ValueError: When a key is present in one object but not
the other. | [
"Verifies",
"whether",
"two",
"positions",
"are",
"the",
"same",
".",
"A",
"tolerance",
"value",
"determines",
"how",
"close",
"the",
"two",
"positions",
"must",
"be",
"to",
"be",
"considered",
"same",
"."
] | 2284c68e15fa3d34b88aa2eec1a2e8ecd37f44ad | https://github.com/mangalam-research/selenic/blob/2284c68e15fa3d34b88aa2eec1a2e8ecd37f44ad/selenic/util.py#L479-L525 | train |
mangalam-research/selenic | selenic/util.py | Util.ctrl_x | def ctrl_x(self, x, to=None):
"""
Sends a character to the currently active element with Ctrl
pressed. This method takes care of pressing and releasing
Ctrl.
"""
seq = [Keys.CONTROL, x, Keys.CONTROL]
# This works around a bug in Selenium that happens in FF on
# Windows, and in Chrome on Linux.
#
# The bug was reported here:
#
# https://code.google.com/p/selenium/issues/detail?id=7303
#
if (self.firefox and self.windows) or (self.linux and self.chrome):
seq.append(Keys.PAUSE)
if to is None:
ActionChains(self.driver) \
.send_keys(seq) \
.perform()
else:
self.send_keys(to, seq) | python | def ctrl_x(self, x, to=None):
"""
Sends a character to the currently active element with Ctrl
pressed. This method takes care of pressing and releasing
Ctrl.
"""
seq = [Keys.CONTROL, x, Keys.CONTROL]
# This works around a bug in Selenium that happens in FF on
# Windows, and in Chrome on Linux.
#
# The bug was reported here:
#
# https://code.google.com/p/selenium/issues/detail?id=7303
#
if (self.firefox and self.windows) or (self.linux and self.chrome):
seq.append(Keys.PAUSE)
if to is None:
ActionChains(self.driver) \
.send_keys(seq) \
.perform()
else:
self.send_keys(to, seq) | [
"def",
"ctrl_x",
"(",
"self",
",",
"x",
",",
"to",
"=",
"None",
")",
":",
"seq",
"=",
"[",
"Keys",
".",
"CONTROL",
",",
"x",
",",
"Keys",
".",
"CONTROL",
"]",
"# This works around a bug in Selenium that happens in FF on",
"# Windows, and in Chrome on Linux.",
"#",
"# The bug was reported here:",
"#",
"# https://code.google.com/p/selenium/issues/detail?id=7303",
"#",
"if",
"(",
"self",
".",
"firefox",
"and",
"self",
".",
"windows",
")",
"or",
"(",
"self",
".",
"linux",
"and",
"self",
".",
"chrome",
")",
":",
"seq",
".",
"append",
"(",
"Keys",
".",
"PAUSE",
")",
"if",
"to",
"is",
"None",
":",
"ActionChains",
"(",
"self",
".",
"driver",
")",
".",
"send_keys",
"(",
"seq",
")",
".",
"perform",
"(",
")",
"else",
":",
"self",
".",
"send_keys",
"(",
"to",
",",
"seq",
")"
] | Sends a character to the currently active element with Ctrl
pressed. This method takes care of pressing and releasing
Ctrl. | [
"Sends",
"a",
"character",
"to",
"the",
"currently",
"active",
"element",
"with",
"Ctrl",
"pressed",
".",
"This",
"method",
"takes",
"care",
"of",
"pressing",
"and",
"releasing",
"Ctrl",
"."
] | 2284c68e15fa3d34b88aa2eec1a2e8ecd37f44ad | https://github.com/mangalam-research/selenic/blob/2284c68e15fa3d34b88aa2eec1a2e8ecd37f44ad/selenic/util.py#L132-L155 | train |
mangalam-research/selenic | selenic/util.py | Util.command_x | def command_x(self, x, to=None):
"""
Sends a character to the currently active element with Command
pressed. This method takes care of pressing and releasing
Command.
"""
if to is None:
ActionChains(self.driver) \
.send_keys([Keys.COMMAND, x, Keys.COMMAND]) \
.perform()
else:
self.send_keys(to, [Keys.COMMAND, x, Keys.COMMAND]) | python | def command_x(self, x, to=None):
"""
Sends a character to the currently active element with Command
pressed. This method takes care of pressing and releasing
Command.
"""
if to is None:
ActionChains(self.driver) \
.send_keys([Keys.COMMAND, x, Keys.COMMAND]) \
.perform()
else:
self.send_keys(to, [Keys.COMMAND, x, Keys.COMMAND]) | [
"def",
"command_x",
"(",
"self",
",",
"x",
",",
"to",
"=",
"None",
")",
":",
"if",
"to",
"is",
"None",
":",
"ActionChains",
"(",
"self",
".",
"driver",
")",
".",
"send_keys",
"(",
"[",
"Keys",
".",
"COMMAND",
",",
"x",
",",
"Keys",
".",
"COMMAND",
"]",
")",
".",
"perform",
"(",
")",
"else",
":",
"self",
".",
"send_keys",
"(",
"to",
",",
"[",
"Keys",
".",
"COMMAND",
",",
"x",
",",
"Keys",
".",
"COMMAND",
"]",
")"
] | Sends a character to the currently active element with Command
pressed. This method takes care of pressing and releasing
Command. | [
"Sends",
"a",
"character",
"to",
"the",
"currently",
"active",
"element",
"with",
"Command",
"pressed",
".",
"This",
"method",
"takes",
"care",
"of",
"pressing",
"and",
"releasing",
"Command",
"."
] | 2284c68e15fa3d34b88aa2eec1a2e8ecd37f44ad | https://github.com/mangalam-research/selenic/blob/2284c68e15fa3d34b88aa2eec1a2e8ecd37f44ad/selenic/util.py#L167-L178 | train |
mangalam-research/selenic | selenic/util.py | Util.wait | def wait(self, condition):
"""
Waits for a condition to be true.
:param condition: Should be a callable that operates in the
same way ``WebDriverWait.until`` expects.
:returns: Whatever ``WebDriverWait.until`` returns.
"""
return WebDriverWait(self.driver, self.timeout).until(condition) | python | def wait(self, condition):
"""
Waits for a condition to be true.
:param condition: Should be a callable that operates in the
same way ``WebDriverWait.until`` expects.
:returns: Whatever ``WebDriverWait.until`` returns.
"""
return WebDriverWait(self.driver, self.timeout).until(condition) | [
"def",
"wait",
"(",
"self",
",",
"condition",
")",
":",
"return",
"WebDriverWait",
"(",
"self",
".",
"driver",
",",
"self",
".",
"timeout",
")",
".",
"until",
"(",
"condition",
")"
] | Waits for a condition to be true.
:param condition: Should be a callable that operates in the
same way ``WebDriverWait.until`` expects.
:returns: Whatever ``WebDriverWait.until`` returns. | [
"Waits",
"for",
"a",
"condition",
"to",
"be",
"true",
"."
] | 2284c68e15fa3d34b88aa2eec1a2e8ecd37f44ad | https://github.com/mangalam-research/selenic/blob/2284c68e15fa3d34b88aa2eec1a2e8ecd37f44ad/selenic/util.py#L391-L399 | train |
mangalam-research/selenic | selenic/util.py | Util.wait_until_not | def wait_until_not(self, condition):
"""
Waits for a condition to be false.
:param condition: Should be a callable that operates in the
same way ``WebDriverWait.until_not`` expects.
:returns: Whatever ``WebDriverWait.until_not`` returns.
"""
return WebDriverWait(self.driver, self.timeout).until_not(condition) | python | def wait_until_not(self, condition):
"""
Waits for a condition to be false.
:param condition: Should be a callable that operates in the
same way ``WebDriverWait.until_not`` expects.
:returns: Whatever ``WebDriverWait.until_not`` returns.
"""
return WebDriverWait(self.driver, self.timeout).until_not(condition) | [
"def",
"wait_until_not",
"(",
"self",
",",
"condition",
")",
":",
"return",
"WebDriverWait",
"(",
"self",
".",
"driver",
",",
"self",
".",
"timeout",
")",
".",
"until_not",
"(",
"condition",
")"
] | Waits for a condition to be false.
:param condition: Should be a callable that operates in the
same way ``WebDriverWait.until_not`` expects.
:returns: Whatever ``WebDriverWait.until_not`` returns. | [
"Waits",
"for",
"a",
"condition",
"to",
"be",
"false",
"."
] | 2284c68e15fa3d34b88aa2eec1a2e8ecd37f44ad | https://github.com/mangalam-research/selenic/blob/2284c68e15fa3d34b88aa2eec1a2e8ecd37f44ad/selenic/util.py#L401-L409 | train |
mediawiki-utilities/python-mwpersistence | mwpersistence/utilities/persistence2stats.py | persistence2stats | def persistence2stats(rev_docs, min_persisted=5, min_visible=1209600,
include=None, exclude=None, verbose=False):
"""
Processes a sorted and page-partitioned sequence of revision documents into
and adds statistics to the 'persistence' field each token "added" in the
revision persisted through future revisions.
:Parameters:
rev_docs : `iterable` ( `dict` )
JSON documents of revision data containing a 'diff' field as
generated by ``dump2diffs``. It's assumed that rev_docs are
partitioned by page and otherwise in chronological order.
window_size : `int`
The size of the window of revisions from which persistence data
will be generated.
min_persisted : `int`
The minimum future revisions that a token must persist in order
to be considered "persistent".
min_visible : `int`
The minimum number of seconds that a token must be visible in order
to be considered "persistent".
include : `func`
A function that returns `True` when a token should be included in
statistical processing
exclude : `str` | `re.SRE_Pattern`
A function that returns `True` when a token should *not* be
included in statistical processing (Takes precedence over
'include')
verbose : `bool`
Prints out dots and stuff to stderr
:Returns:
A generator of rev_docs with a 'persistence' field containing
statistics about individual tokens.
"""
rev_docs = mwxml.utilities.normalize(rev_docs)
min_persisted = int(min_persisted)
min_visible = int(min_visible)
include = include if include is not None else lambda t: True
exclude = exclude if exclude is not None else lambda t: False
for rev_doc in rev_docs:
persistence_doc = rev_doc['persistence']
stats_doc = {
'tokens_added': 0,
'persistent_tokens': 0,
'non_self_persistent_tokens': 0,
'sum_log_persisted': 0,
'sum_log_non_self_persisted': 0,
'sum_log_seconds_visible': 0,
'censored': False,
'non_self_censored': False
}
filtered_docs = (t for t in persistence_doc['tokens']
if include(t['text']) and not exclude(t['text']))
for token_doc in filtered_docs:
if verbose:
sys.stderr.write(".")
sys.stderr.flush()
stats_doc['tokens_added'] += 1
stats_doc['sum_log_persisted'] += log(token_doc['persisted'] + 1)
stats_doc['sum_log_non_self_persisted'] += \
log(token_doc['non_self_persisted'] + 1)
stats_doc['sum_log_seconds_visible'] += \
log(token_doc['seconds_visible'] + 1)
# Look for time threshold
if token_doc['seconds_visible'] >= min_visible:
stats_doc['persistent_tokens'] += 1
stats_doc['non_self_persistent_tokens'] += 1
else:
# Look for review threshold
stats_doc['persistent_tokens'] += \
token_doc['persisted'] >= min_persisted
stats_doc['non_self_persistent_tokens'] += \
token_doc['non_self_persisted'] >= min_persisted
# Check for censoring
if persistence_doc['seconds_possible'] < min_visible:
stats_doc['censored'] = True
stats_doc['non_self_censored'] = True
else:
if persistence_doc['revisions_processed'] < min_persisted:
stats_doc['censored'] = True
if persistence_doc['non_self_processed'] < min_persisted:
stats_doc['non_self_censored'] = True
if verbose:
sys.stderr.write("\n")
sys.stderr.flush()
rev_doc['persistence'].update(stats_doc)
yield rev_doc | python | def persistence2stats(rev_docs, min_persisted=5, min_visible=1209600,
include=None, exclude=None, verbose=False):
"""
Processes a sorted and page-partitioned sequence of revision documents into
and adds statistics to the 'persistence' field each token "added" in the
revision persisted through future revisions.
:Parameters:
rev_docs : `iterable` ( `dict` )
JSON documents of revision data containing a 'diff' field as
generated by ``dump2diffs``. It's assumed that rev_docs are
partitioned by page and otherwise in chronological order.
window_size : `int`
The size of the window of revisions from which persistence data
will be generated.
min_persisted : `int`
The minimum future revisions that a token must persist in order
to be considered "persistent".
min_visible : `int`
The minimum number of seconds that a token must be visible in order
to be considered "persistent".
include : `func`
A function that returns `True` when a token should be included in
statistical processing
exclude : `str` | `re.SRE_Pattern`
A function that returns `True` when a token should *not* be
included in statistical processing (Takes precedence over
'include')
verbose : `bool`
Prints out dots and stuff to stderr
:Returns:
A generator of rev_docs with a 'persistence' field containing
statistics about individual tokens.
"""
rev_docs = mwxml.utilities.normalize(rev_docs)
min_persisted = int(min_persisted)
min_visible = int(min_visible)
include = include if include is not None else lambda t: True
exclude = exclude if exclude is not None else lambda t: False
for rev_doc in rev_docs:
persistence_doc = rev_doc['persistence']
stats_doc = {
'tokens_added': 0,
'persistent_tokens': 0,
'non_self_persistent_tokens': 0,
'sum_log_persisted': 0,
'sum_log_non_self_persisted': 0,
'sum_log_seconds_visible': 0,
'censored': False,
'non_self_censored': False
}
filtered_docs = (t for t in persistence_doc['tokens']
if include(t['text']) and not exclude(t['text']))
for token_doc in filtered_docs:
if verbose:
sys.stderr.write(".")
sys.stderr.flush()
stats_doc['tokens_added'] += 1
stats_doc['sum_log_persisted'] += log(token_doc['persisted'] + 1)
stats_doc['sum_log_non_self_persisted'] += \
log(token_doc['non_self_persisted'] + 1)
stats_doc['sum_log_seconds_visible'] += \
log(token_doc['seconds_visible'] + 1)
# Look for time threshold
if token_doc['seconds_visible'] >= min_visible:
stats_doc['persistent_tokens'] += 1
stats_doc['non_self_persistent_tokens'] += 1
else:
# Look for review threshold
stats_doc['persistent_tokens'] += \
token_doc['persisted'] >= min_persisted
stats_doc['non_self_persistent_tokens'] += \
token_doc['non_self_persisted'] >= min_persisted
# Check for censoring
if persistence_doc['seconds_possible'] < min_visible:
stats_doc['censored'] = True
stats_doc['non_self_censored'] = True
else:
if persistence_doc['revisions_processed'] < min_persisted:
stats_doc['censored'] = True
if persistence_doc['non_self_processed'] < min_persisted:
stats_doc['non_self_censored'] = True
if verbose:
sys.stderr.write("\n")
sys.stderr.flush()
rev_doc['persistence'].update(stats_doc)
yield rev_doc | [
"def",
"persistence2stats",
"(",
"rev_docs",
",",
"min_persisted",
"=",
"5",
",",
"min_visible",
"=",
"1209600",
",",
"include",
"=",
"None",
",",
"exclude",
"=",
"None",
",",
"verbose",
"=",
"False",
")",
":",
"rev_docs",
"=",
"mwxml",
".",
"utilities",
".",
"normalize",
"(",
"rev_docs",
")",
"min_persisted",
"=",
"int",
"(",
"min_persisted",
")",
"min_visible",
"=",
"int",
"(",
"min_visible",
")",
"include",
"=",
"include",
"if",
"include",
"is",
"not",
"None",
"else",
"lambda",
"t",
":",
"True",
"exclude",
"=",
"exclude",
"if",
"exclude",
"is",
"not",
"None",
"else",
"lambda",
"t",
":",
"False",
"for",
"rev_doc",
"in",
"rev_docs",
":",
"persistence_doc",
"=",
"rev_doc",
"[",
"'persistence'",
"]",
"stats_doc",
"=",
"{",
"'tokens_added'",
":",
"0",
",",
"'persistent_tokens'",
":",
"0",
",",
"'non_self_persistent_tokens'",
":",
"0",
",",
"'sum_log_persisted'",
":",
"0",
",",
"'sum_log_non_self_persisted'",
":",
"0",
",",
"'sum_log_seconds_visible'",
":",
"0",
",",
"'censored'",
":",
"False",
",",
"'non_self_censored'",
":",
"False",
"}",
"filtered_docs",
"=",
"(",
"t",
"for",
"t",
"in",
"persistence_doc",
"[",
"'tokens'",
"]",
"if",
"include",
"(",
"t",
"[",
"'text'",
"]",
")",
"and",
"not",
"exclude",
"(",
"t",
"[",
"'text'",
"]",
")",
")",
"for",
"token_doc",
"in",
"filtered_docs",
":",
"if",
"verbose",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"\".\"",
")",
"sys",
".",
"stderr",
".",
"flush",
"(",
")",
"stats_doc",
"[",
"'tokens_added'",
"]",
"+=",
"1",
"stats_doc",
"[",
"'sum_log_persisted'",
"]",
"+=",
"log",
"(",
"token_doc",
"[",
"'persisted'",
"]",
"+",
"1",
")",
"stats_doc",
"[",
"'sum_log_non_self_persisted'",
"]",
"+=",
"log",
"(",
"token_doc",
"[",
"'non_self_persisted'",
"]",
"+",
"1",
")",
"stats_doc",
"[",
"'sum_log_seconds_visible'",
"]",
"+=",
"log",
"(",
"token_doc",
"[",
"'seconds_visible'",
"]",
"+",
"1",
")",
"# Look for time threshold",
"if",
"token_doc",
"[",
"'seconds_visible'",
"]",
">=",
"min_visible",
":",
"stats_doc",
"[",
"'persistent_tokens'",
"]",
"+=",
"1",
"stats_doc",
"[",
"'non_self_persistent_tokens'",
"]",
"+=",
"1",
"else",
":",
"# Look for review threshold",
"stats_doc",
"[",
"'persistent_tokens'",
"]",
"+=",
"token_doc",
"[",
"'persisted'",
"]",
">=",
"min_persisted",
"stats_doc",
"[",
"'non_self_persistent_tokens'",
"]",
"+=",
"token_doc",
"[",
"'non_self_persisted'",
"]",
">=",
"min_persisted",
"# Check for censoring",
"if",
"persistence_doc",
"[",
"'seconds_possible'",
"]",
"<",
"min_visible",
":",
"stats_doc",
"[",
"'censored'",
"]",
"=",
"True",
"stats_doc",
"[",
"'non_self_censored'",
"]",
"=",
"True",
"else",
":",
"if",
"persistence_doc",
"[",
"'revisions_processed'",
"]",
"<",
"min_persisted",
":",
"stats_doc",
"[",
"'censored'",
"]",
"=",
"True",
"if",
"persistence_doc",
"[",
"'non_self_processed'",
"]",
"<",
"min_persisted",
":",
"stats_doc",
"[",
"'non_self_censored'",
"]",
"=",
"True",
"if",
"verbose",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"\"\\n\"",
")",
"sys",
".",
"stderr",
".",
"flush",
"(",
")",
"rev_doc",
"[",
"'persistence'",
"]",
".",
"update",
"(",
"stats_doc",
")",
"yield",
"rev_doc"
] | Processes a sorted and page-partitioned sequence of revision documents into
and adds statistics to the 'persistence' field each token "added" in the
revision persisted through future revisions.
:Parameters:
rev_docs : `iterable` ( `dict` )
JSON documents of revision data containing a 'diff' field as
generated by ``dump2diffs``. It's assumed that rev_docs are
partitioned by page and otherwise in chronological order.
window_size : `int`
The size of the window of revisions from which persistence data
will be generated.
min_persisted : `int`
The minimum future revisions that a token must persist in order
to be considered "persistent".
min_visible : `int`
The minimum number of seconds that a token must be visible in order
to be considered "persistent".
include : `func`
A function that returns `True` when a token should be included in
statistical processing
exclude : `str` | `re.SRE_Pattern`
A function that returns `True` when a token should *not* be
included in statistical processing (Takes precedence over
'include')
verbose : `bool`
Prints out dots and stuff to stderr
:Returns:
A generator of rev_docs with a 'persistence' field containing
statistics about individual tokens. | [
"Processes",
"a",
"sorted",
"and",
"page",
"-",
"partitioned",
"sequence",
"of",
"revision",
"documents",
"into",
"and",
"adds",
"statistics",
"to",
"the",
"persistence",
"field",
"each",
"token",
"added",
"in",
"the",
"revision",
"persisted",
"through",
"future",
"revisions",
"."
] | 2b98847fb8acaca38b3cbf94bde3fd7e27d2b67d | https://github.com/mediawiki-utilities/python-mwpersistence/blob/2b98847fb8acaca38b3cbf94bde3fd7e27d2b67d/mwpersistence/utilities/persistence2stats.py#L88-L187 | train |
a1ezzz/wasp-general | wasp_general/task/health.py | WTaskHealth.healthy | def healthy(self):
""" Return task health. If None - task is healthy, otherwise - maximum severity of sensors
:return: None or WTaskHealthSensor.WTaskSensorSeverity
"""
state = None
for sensor in self._sensors.values():
if sensor.healthy() is False:
if state is None or sensor.severity().value > state.value:
state = sensor.severity()
if state == WTaskHealthSensor.WTaskSensorSeverity.critical:
break
return state | python | def healthy(self):
""" Return task health. If None - task is healthy, otherwise - maximum severity of sensors
:return: None or WTaskHealthSensor.WTaskSensorSeverity
"""
state = None
for sensor in self._sensors.values():
if sensor.healthy() is False:
if state is None or sensor.severity().value > state.value:
state = sensor.severity()
if state == WTaskHealthSensor.WTaskSensorSeverity.critical:
break
return state | [
"def",
"healthy",
"(",
"self",
")",
":",
"state",
"=",
"None",
"for",
"sensor",
"in",
"self",
".",
"_sensors",
".",
"values",
"(",
")",
":",
"if",
"sensor",
".",
"healthy",
"(",
")",
"is",
"False",
":",
"if",
"state",
"is",
"None",
"or",
"sensor",
".",
"severity",
"(",
")",
".",
"value",
">",
"state",
".",
"value",
":",
"state",
"=",
"sensor",
".",
"severity",
"(",
")",
"if",
"state",
"==",
"WTaskHealthSensor",
".",
"WTaskSensorSeverity",
".",
"critical",
":",
"break",
"return",
"state"
] | Return task health. If None - task is healthy, otherwise - maximum severity of sensors
:return: None or WTaskHealthSensor.WTaskSensorSeverity | [
"Return",
"task",
"health",
".",
"If",
"None",
"-",
"task",
"is",
"healthy",
"otherwise",
"-",
"maximum",
"severity",
"of",
"sensors"
] | 1029839d33eb663f8dec76c1c46754d53c1de4a9 | https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/task/health.py#L169-L182 | train |
Chilipp/model-organization | docs/square_preproc.py | SquareModelOrganizer.preproc | def preproc(self, which='sin', **kwargs):
"""
Create preprocessing data
Parameters
----------
which: str
The name of the numpy function to apply
``**kwargs``
Any other parameter for the
:meth:`model_organization.ModelOrganizer.app_main` method
"""
self.app_main(**kwargs)
config = self.exp_config
config['infile'] = infile = osp.join(config['expdir'], 'input.dat')
func = getattr(np, which) # np.sin, np.cos or np.tan
data = func(np.linspace(-np.pi, np.pi))
self.logger.info('Saving input data to %s', infile)
np.savetxt(infile, data) | python | def preproc(self, which='sin', **kwargs):
"""
Create preprocessing data
Parameters
----------
which: str
The name of the numpy function to apply
``**kwargs``
Any other parameter for the
:meth:`model_organization.ModelOrganizer.app_main` method
"""
self.app_main(**kwargs)
config = self.exp_config
config['infile'] = infile = osp.join(config['expdir'], 'input.dat')
func = getattr(np, which) # np.sin, np.cos or np.tan
data = func(np.linspace(-np.pi, np.pi))
self.logger.info('Saving input data to %s', infile)
np.savetxt(infile, data) | [
"def",
"preproc",
"(",
"self",
",",
"which",
"=",
"'sin'",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"app_main",
"(",
"*",
"*",
"kwargs",
")",
"config",
"=",
"self",
".",
"exp_config",
"config",
"[",
"'infile'",
"]",
"=",
"infile",
"=",
"osp",
".",
"join",
"(",
"config",
"[",
"'expdir'",
"]",
",",
"'input.dat'",
")",
"func",
"=",
"getattr",
"(",
"np",
",",
"which",
")",
"# np.sin, np.cos or np.tan",
"data",
"=",
"func",
"(",
"np",
".",
"linspace",
"(",
"-",
"np",
".",
"pi",
",",
"np",
".",
"pi",
")",
")",
"self",
".",
"logger",
".",
"info",
"(",
"'Saving input data to %s'",
",",
"infile",
")",
"np",
".",
"savetxt",
"(",
"infile",
",",
"data",
")"
] | Create preprocessing data
Parameters
----------
which: str
The name of the numpy function to apply
``**kwargs``
Any other parameter for the
:meth:`model_organization.ModelOrganizer.app_main` method | [
"Create",
"preprocessing",
"data"
] | 694d1219c7ed7e1b2b17153afa11bdc21169bca2 | https://github.com/Chilipp/model-organization/blob/694d1219c7ed7e1b2b17153afa11bdc21169bca2/docs/square_preproc.py#L17-L36 | train |
a1ezzz/wasp-general | wasp_general/os/linux/mounts.py | WMountPoint.mounts | def mounts(cls):
""" Return tuple of current mount points
:return: tuple of WMountPoint
"""
result = []
with open(cls.__mounts_file__) as f:
for mount_record in f:
result.append(WMountPoint(mount_record))
return tuple(result) | python | def mounts(cls):
""" Return tuple of current mount points
:return: tuple of WMountPoint
"""
result = []
with open(cls.__mounts_file__) as f:
for mount_record in f:
result.append(WMountPoint(mount_record))
return tuple(result) | [
"def",
"mounts",
"(",
"cls",
")",
":",
"result",
"=",
"[",
"]",
"with",
"open",
"(",
"cls",
".",
"__mounts_file__",
")",
"as",
"f",
":",
"for",
"mount_record",
"in",
"f",
":",
"result",
".",
"append",
"(",
"WMountPoint",
"(",
"mount_record",
")",
")",
"return",
"tuple",
"(",
"result",
")"
] | Return tuple of current mount points
:return: tuple of WMountPoint | [
"Return",
"tuple",
"of",
"current",
"mount",
"points"
] | 1029839d33eb663f8dec76c1c46754d53c1de4a9 | https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/os/linux/mounts.py#L123-L132 | train |
a1ezzz/wasp-general | wasp_general/os/linux/mounts.py | WMountPoint.mount_point | def mount_point(cls, file_path):
""" Return mount point that, where the given path is reside on
:param file_path: target path to search
:return: WMountPoint or None (if file path is outside current mount points)
"""
mount = None
for mp in cls.mounts():
mp_path = mp.path()
if file_path.startswith(mp_path) is True:
if mount is None or len(mount.path()) <= len(mp_path):
mount = mp
return mount | python | def mount_point(cls, file_path):
""" Return mount point that, where the given path is reside on
:param file_path: target path to search
:return: WMountPoint or None (if file path is outside current mount points)
"""
mount = None
for mp in cls.mounts():
mp_path = mp.path()
if file_path.startswith(mp_path) is True:
if mount is None or len(mount.path()) <= len(mp_path):
mount = mp
return mount | [
"def",
"mount_point",
"(",
"cls",
",",
"file_path",
")",
":",
"mount",
"=",
"None",
"for",
"mp",
"in",
"cls",
".",
"mounts",
"(",
")",
":",
"mp_path",
"=",
"mp",
".",
"path",
"(",
")",
"if",
"file_path",
".",
"startswith",
"(",
"mp_path",
")",
"is",
"True",
":",
"if",
"mount",
"is",
"None",
"or",
"len",
"(",
"mount",
".",
"path",
"(",
")",
")",
"<=",
"len",
"(",
"mp_path",
")",
":",
"mount",
"=",
"mp",
"return",
"mount"
] | Return mount point that, where the given path is reside on
:param file_path: target path to search
:return: WMountPoint or None (if file path is outside current mount points) | [
"Return",
"mount",
"point",
"that",
"where",
"the",
"given",
"path",
"is",
"reside",
"on"
] | 1029839d33eb663f8dec76c1c46754d53c1de4a9 | https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/os/linux/mounts.py#L137-L151 | train |
a1ezzz/wasp-general | wasp_general/os/linux/mounts.py | WMountPoint.mount | def mount(cls, device, mount_directory, fs=None, options=None, cmd_timeout=None, sudo=False):
""" Mount a device to mount directory
:param device: device to mount
:param mount_directory: target directory where the given device will be mounted to
:param fs: optional, filesystem on the specified device. If specifies - overrides OS filesystem \
detection with this value.
:param options: specifies mount options (OS/filesystem dependent)
:param cmd_timeout: if specified - timeout with which this mount command should be evaluated (if \
command isn't complete within the given timeout - an exception will be raised)
:param sudo: whether to use sudo to run mount command
:return: None
"""
cmd = [] if sudo is False else ['sudo']
cmd.extend(['mount', device, os.path.abspath(mount_directory)])
if fs is not None:
cmd.extend(['-t', fs])
if options is not None and len(options) > 0:
cmd.append('-o')
cmd.extend(options)
subprocess.check_output(cmd, timeout=cmd_timeout) | python | def mount(cls, device, mount_directory, fs=None, options=None, cmd_timeout=None, sudo=False):
""" Mount a device to mount directory
:param device: device to mount
:param mount_directory: target directory where the given device will be mounted to
:param fs: optional, filesystem on the specified device. If specifies - overrides OS filesystem \
detection with this value.
:param options: specifies mount options (OS/filesystem dependent)
:param cmd_timeout: if specified - timeout with which this mount command should be evaluated (if \
command isn't complete within the given timeout - an exception will be raised)
:param sudo: whether to use sudo to run mount command
:return: None
"""
cmd = [] if sudo is False else ['sudo']
cmd.extend(['mount', device, os.path.abspath(mount_directory)])
if fs is not None:
cmd.extend(['-t', fs])
if options is not None and len(options) > 0:
cmd.append('-o')
cmd.extend(options)
subprocess.check_output(cmd, timeout=cmd_timeout) | [
"def",
"mount",
"(",
"cls",
",",
"device",
",",
"mount_directory",
",",
"fs",
"=",
"None",
",",
"options",
"=",
"None",
",",
"cmd_timeout",
"=",
"None",
",",
"sudo",
"=",
"False",
")",
":",
"cmd",
"=",
"[",
"]",
"if",
"sudo",
"is",
"False",
"else",
"[",
"'sudo'",
"]",
"cmd",
".",
"extend",
"(",
"[",
"'mount'",
",",
"device",
",",
"os",
".",
"path",
".",
"abspath",
"(",
"mount_directory",
")",
"]",
")",
"if",
"fs",
"is",
"not",
"None",
":",
"cmd",
".",
"extend",
"(",
"[",
"'-t'",
",",
"fs",
"]",
")",
"if",
"options",
"is",
"not",
"None",
"and",
"len",
"(",
"options",
")",
">",
"0",
":",
"cmd",
".",
"append",
"(",
"'-o'",
")",
"cmd",
".",
"extend",
"(",
"options",
")",
"subprocess",
".",
"check_output",
"(",
"cmd",
",",
"timeout",
"=",
"cmd_timeout",
")"
] | Mount a device to mount directory
:param device: device to mount
:param mount_directory: target directory where the given device will be mounted to
:param fs: optional, filesystem on the specified device. If specifies - overrides OS filesystem \
detection with this value.
:param options: specifies mount options (OS/filesystem dependent)
:param cmd_timeout: if specified - timeout with which this mount command should be evaluated (if \
command isn't complete within the given timeout - an exception will be raised)
:param sudo: whether to use sudo to run mount command
:return: None | [
"Mount",
"a",
"device",
"to",
"mount",
"directory"
] | 1029839d33eb663f8dec76c1c46754d53c1de4a9 | https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/os/linux/mounts.py#L158-L180 | train |
AASHE/python-membersuite-api-client | membersuite_api_client/organizations/services.py | OrganizationService.get_org_types | def get_org_types(self):
"""
Retrieves all current OrganizationType objects
"""
if not self.client.session_id:
self.client.request_session()
object_query = "SELECT Objects() FROM OrganizationType"
result = self.client.execute_object_query(object_query=object_query)
msql_result = result['body']["ExecuteMSQLResult"]
return self.package_org_types(msql_result["ResultValue"]
["ObjectSearchResult"]
["Objects"]["MemberSuiteObject"]
) | python | def get_org_types(self):
"""
Retrieves all current OrganizationType objects
"""
if not self.client.session_id:
self.client.request_session()
object_query = "SELECT Objects() FROM OrganizationType"
result = self.client.execute_object_query(object_query=object_query)
msql_result = result['body']["ExecuteMSQLResult"]
return self.package_org_types(msql_result["ResultValue"]
["ObjectSearchResult"]
["Objects"]["MemberSuiteObject"]
) | [
"def",
"get_org_types",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"client",
".",
"session_id",
":",
"self",
".",
"client",
".",
"request_session",
"(",
")",
"object_query",
"=",
"\"SELECT Objects() FROM OrganizationType\"",
"result",
"=",
"self",
".",
"client",
".",
"execute_object_query",
"(",
"object_query",
"=",
"object_query",
")",
"msql_result",
"=",
"result",
"[",
"'body'",
"]",
"[",
"\"ExecuteMSQLResult\"",
"]",
"return",
"self",
".",
"package_org_types",
"(",
"msql_result",
"[",
"\"ResultValue\"",
"]",
"[",
"\"ObjectSearchResult\"",
"]",
"[",
"\"Objects\"",
"]",
"[",
"\"MemberSuiteObject\"",
"]",
")"
] | Retrieves all current OrganizationType objects | [
"Retrieves",
"all",
"current",
"OrganizationType",
"objects"
] | 221f5ed8bc7d4424237a4669c5af9edc11819ee9 | https://github.com/AASHE/python-membersuite-api-client/blob/221f5ed8bc7d4424237a4669c5af9edc11819ee9/membersuite_api_client/organizations/services.py#L80-L93 | train |
AASHE/python-membersuite-api-client | membersuite_api_client/organizations/services.py | OrganizationService.package_org_types | def package_org_types(self, obj_list):
"""
Loops through MS objects returned from queries to turn them into
OrganizationType objects and pack them into a list for later use.
"""
org_type_list = []
for obj in obj_list:
sane_obj = convert_ms_object(
obj['Fields']['KeyValueOfstringanyType']
)
org = OrganizationType(sane_obj)
org_type_list.append(org)
return org_type_list | python | def package_org_types(self, obj_list):
"""
Loops through MS objects returned from queries to turn them into
OrganizationType objects and pack them into a list for later use.
"""
org_type_list = []
for obj in obj_list:
sane_obj = convert_ms_object(
obj['Fields']['KeyValueOfstringanyType']
)
org = OrganizationType(sane_obj)
org_type_list.append(org)
return org_type_list | [
"def",
"package_org_types",
"(",
"self",
",",
"obj_list",
")",
":",
"org_type_list",
"=",
"[",
"]",
"for",
"obj",
"in",
"obj_list",
":",
"sane_obj",
"=",
"convert_ms_object",
"(",
"obj",
"[",
"'Fields'",
"]",
"[",
"'KeyValueOfstringanyType'",
"]",
")",
"org",
"=",
"OrganizationType",
"(",
"sane_obj",
")",
"org_type_list",
".",
"append",
"(",
"org",
")",
"return",
"org_type_list"
] | Loops through MS objects returned from queries to turn them into
OrganizationType objects and pack them into a list for later use. | [
"Loops",
"through",
"MS",
"objects",
"returned",
"from",
"queries",
"to",
"turn",
"them",
"into",
"OrganizationType",
"objects",
"and",
"pack",
"them",
"into",
"a",
"list",
"for",
"later",
"use",
"."
] | 221f5ed8bc7d4424237a4669c5af9edc11819ee9 | https://github.com/AASHE/python-membersuite-api-client/blob/221f5ed8bc7d4424237a4669c5af9edc11819ee9/membersuite_api_client/organizations/services.py#L95-L107 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.