repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
JensRantil/rewind | rewind/server/eventstores.py | RotatedEventStore.rotate | def rotate(self):
"""Rotate the files to disk.
This is done by calling `store.close()` on each store, bumping the
batchno and reopening the stores using their factories.
"""
self._logger.info('Rotating data files. New batch number will be: %s',
self.ba... | python | def rotate(self):
"""Rotate the files to disk.
This is done by calling `store.close()` on each store, bumping the
batchno and reopening the stores using their factories.
"""
self._logger.info('Rotating data files. New batch number will be: %s',
self.ba... | [
"def",
"rotate",
"(",
"self",
")",
":",
"self",
".",
"_logger",
".",
"info",
"(",
"'Rotating data files. New batch number will be: %s'",
",",
"self",
".",
"batchno",
"+",
"1",
")",
"self",
".",
"estore",
".",
"close",
"(",
")",
"self",
".",
"estore",
"=",
... | Rotate the files to disk.
This is done by calling `store.close()` on each store, bumping the
batchno and reopening the stores using their factories. | [
"Rotate",
"the",
"files",
"to",
"disk",
"."
] | 7f645d20186c1db55cfe53a0310c9fd6292f91ea | https://github.com/JensRantil/rewind/blob/7f645d20186c1db55cfe53a0310c9fd6292f91ea/rewind/server/eventstores.py#L785-L797 | train |
JensRantil/rewind | rewind/server/eventstores.py | RotatedEventStore._find_batch_containing_event | def _find_batch_containing_event(self, uuid):
"""Find the batch number that contains a certain event.
Parameters:
uuid -- the event uuid to search for.
returns -- a batch number, or None if not found.
"""
if self.estore.key_exists(uuid):
# Reusing alread... | python | def _find_batch_containing_event(self, uuid):
"""Find the batch number that contains a certain event.
Parameters:
uuid -- the event uuid to search for.
returns -- a batch number, or None if not found.
"""
if self.estore.key_exists(uuid):
# Reusing alread... | [
"def",
"_find_batch_containing_event",
"(",
"self",
",",
"uuid",
")",
":",
"if",
"self",
".",
"estore",
".",
"key_exists",
"(",
"uuid",
")",
":",
"# Reusing already opened DB if possible",
"return",
"self",
".",
"batchno",
"else",
":",
"for",
"batchno",
"in",
... | Find the batch number that contains a certain event.
Parameters:
uuid -- the event uuid to search for.
returns -- a batch number, or None if not found. | [
"Find",
"the",
"batch",
"number",
"that",
"contains",
"a",
"certain",
"event",
"."
] | 7f645d20186c1db55cfe53a0310c9fd6292f91ea | https://github.com/JensRantil/rewind/blob/7f645d20186c1db55cfe53a0310c9fd6292f91ea/rewind/server/eventstores.py#L803-L823 | train |
JensRantil/rewind | rewind/server/eventstores.py | SyncedRotationEventStores.from_config | def from_config(config, **options):
"""Instantiate an `SyncedRotationEventStores` from config.
Parameters:
config -- the configuration file options read from file(s).
**options -- various options given to the specific event store. Shall
not be used with this even... | python | def from_config(config, **options):
"""Instantiate an `SyncedRotationEventStores` from config.
Parameters:
config -- the configuration file options read from file(s).
**options -- various options given to the specific event store. Shall
not be used with this even... | [
"def",
"from_config",
"(",
"config",
",",
"*",
"*",
"options",
")",
":",
"required_args",
"=",
"(",
"'storage-backends'",
",",
")",
"optional_args",
"=",
"{",
"'events_per_batch'",
":",
"25000",
"}",
"rconfig",
".",
"check_config_options",
"(",
"\"SyncedRotation... | Instantiate an `SyncedRotationEventStores` from config.
Parameters:
config -- the configuration file options read from file(s).
**options -- various options given to the specific event store. Shall
not be used with this event store. Warning will be logged
... | [
"Instantiate",
"an",
"SyncedRotationEventStores",
"from",
"config",
"."
] | 7f645d20186c1db55cfe53a0310c9fd6292f91ea | https://github.com/JensRantil/rewind/blob/7f645d20186c1db55cfe53a0310c9fd6292f91ea/rewind/server/eventstores.py#L915-L951 | train |
tehmaze/natural | natural/data.py | hexdump | def hexdump(stream):
'''
Display stream contents in hexadecimal and ASCII format. The ``stream``
specified must either be a file-like object that supports the ``read``
method to receive bytes, or it can be a string.
To dump a file::
>>> hexdump(file(filename)) # doctest: +SKIP
Or ... | python | def hexdump(stream):
'''
Display stream contents in hexadecimal and ASCII format. The ``stream``
specified must either be a file-like object that supports the ``read``
method to receive bytes, or it can be a string.
To dump a file::
>>> hexdump(file(filename)) # doctest: +SKIP
Or ... | [
"def",
"hexdump",
"(",
"stream",
")",
":",
"if",
"isinstance",
"(",
"stream",
",",
"six",
".",
"string_types",
")",
":",
"stream",
"=",
"BytesIO",
"(",
"stream",
")",
"row",
"=",
"0",
"while",
"True",
":",
"data",
"=",
"stream",
".",
"read",
"(",
"... | Display stream contents in hexadecimal and ASCII format. The ``stream``
specified must either be a file-like object that supports the ``read``
method to receive bytes, or it can be a string.
To dump a file::
>>> hexdump(file(filename)) # doctest: +SKIP
Or to dump stdin::
>>> impo... | [
"Display",
"stream",
"contents",
"in",
"hexadecimal",
"and",
"ASCII",
"format",
".",
"The",
"stream",
"specified",
"must",
"either",
"be",
"a",
"file",
"-",
"like",
"object",
"that",
"supports",
"the",
"read",
"method",
"to",
"receive",
"bytes",
"or",
"it",
... | d7a1fc9de712f9bcf68884a80826a7977df356fb | https://github.com/tehmaze/natural/blob/d7a1fc9de712f9bcf68884a80826a7977df356fb/natural/data.py#L39-L75 | train |
tehmaze/natural | natural/data.py | printable | def printable(sequence):
'''
Return a printable string from the input ``sequence``
:param sequence: byte or string sequence
>>> print(printable('\\x1b[1;34mtest\\x1b[0m'))
.[1;34mtest.[0m
>>> printable('\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x06') == '........'
True
>>> print(printable(... | python | def printable(sequence):
'''
Return a printable string from the input ``sequence``
:param sequence: byte or string sequence
>>> print(printable('\\x1b[1;34mtest\\x1b[0m'))
.[1;34mtest.[0m
>>> printable('\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x06') == '........'
True
>>> print(printable(... | [
"def",
"printable",
"(",
"sequence",
")",
":",
"return",
"''",
".",
"join",
"(",
"list",
"(",
"map",
"(",
"lambda",
"c",
":",
"c",
"if",
"c",
"in",
"PRINTABLE",
"else",
"'.'",
",",
"sequence",
")",
")",
")"
] | Return a printable string from the input ``sequence``
:param sequence: byte or string sequence
>>> print(printable('\\x1b[1;34mtest\\x1b[0m'))
.[1;34mtest.[0m
>>> printable('\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x06') == '........'
True
>>> print(printable('12345678'))
12345678
>>> pri... | [
"Return",
"a",
"printable",
"string",
"from",
"the",
"input",
"sequence"
] | d7a1fc9de712f9bcf68884a80826a7977df356fb | https://github.com/tehmaze/natural/blob/d7a1fc9de712f9bcf68884a80826a7977df356fb/natural/data.py#L78-L97 | train |
tehmaze/natural | natural/data.py | sparkline | def sparkline(data):
'''
Return a spark line for the given data set.
:value data: sequence of numeric values
>>> print sparkline([1, 2, 3, 4, 5, 6, 5, 4, 3, 1, 5, 6]) # doctest: +SKIP
▁▂▃▄▅▆▅▄▃▁▅▆
'''
min_value = float(min(data))
max_value = float(max(data))
steps = (max_value -... | python | def sparkline(data):
'''
Return a spark line for the given data set.
:value data: sequence of numeric values
>>> print sparkline([1, 2, 3, 4, 5, 6, 5, 4, 3, 1, 5, 6]) # doctest: +SKIP
▁▂▃▄▅▆▅▄▃▁▅▆
'''
min_value = float(min(data))
max_value = float(max(data))
steps = (max_value -... | [
"def",
"sparkline",
"(",
"data",
")",
":",
"min_value",
"=",
"float",
"(",
"min",
"(",
"data",
")",
")",
"max_value",
"=",
"float",
"(",
"max",
"(",
"data",
")",
")",
"steps",
"=",
"(",
"max_value",
"-",
"min_value",
")",
"/",
"float",
"(",
"len",
... | Return a spark line for the given data set.
:value data: sequence of numeric values
>>> print sparkline([1, 2, 3, 4, 5, 6, 5, 4, 3, 1, 5, 6]) # doctest: +SKIP
▁▂▃▄▅▆▅▄▃▁▅▆ | [
"Return",
"a",
"spark",
"line",
"for",
"the",
"given",
"data",
"set",
"."
] | d7a1fc9de712f9bcf68884a80826a7977df356fb | https://github.com/tehmaze/natural/blob/d7a1fc9de712f9bcf68884a80826a7977df356fb/natural/data.py#L100-L117 | train |
yeraydiazdiaz/lunr.py | lunr/languages/stemmer.py | get_language_stemmer | def get_language_stemmer(language):
"""Retrieves the SnowballStemmer for a particular language.
Args:
language (str): ISO-639-1 code of the language.
"""
from lunr.languages import SUPPORTED_LANGUAGES
from nltk.stem.snowball import SnowballStemmer
return SnowballStemmer(SUPPORTED_LANGU... | python | def get_language_stemmer(language):
"""Retrieves the SnowballStemmer for a particular language.
Args:
language (str): ISO-639-1 code of the language.
"""
from lunr.languages import SUPPORTED_LANGUAGES
from nltk.stem.snowball import SnowballStemmer
return SnowballStemmer(SUPPORTED_LANGU... | [
"def",
"get_language_stemmer",
"(",
"language",
")",
":",
"from",
"lunr",
".",
"languages",
"import",
"SUPPORTED_LANGUAGES",
"from",
"nltk",
".",
"stem",
".",
"snowball",
"import",
"SnowballStemmer",
"return",
"SnowballStemmer",
"(",
"SUPPORTED_LANGUAGES",
"[",
"lan... | Retrieves the SnowballStemmer for a particular language.
Args:
language (str): ISO-639-1 code of the language. | [
"Retrieves",
"the",
"SnowballStemmer",
"for",
"a",
"particular",
"language",
"."
] | 28ec3f6d4888295eed730211ee9617aa488d6ba3 | https://github.com/yeraydiazdiaz/lunr.py/blob/28ec3f6d4888295eed730211ee9617aa488d6ba3/lunr/languages/stemmer.py#L1-L10 | train |
yeraydiazdiaz/lunr.py | lunr/languages/stemmer.py | nltk_stemmer | def nltk_stemmer(stemmer, token, i=None, tokens=None):
"""Wrapper around a NLTK SnowballStemmer, which includes stop words for
each language.
Args:
stemmer (SnowballStemmer): Stemmer instance that performs the stemming.
token (lunr.Token): The token to stem.
i (int): The index of th... | python | def nltk_stemmer(stemmer, token, i=None, tokens=None):
"""Wrapper around a NLTK SnowballStemmer, which includes stop words for
each language.
Args:
stemmer (SnowballStemmer): Stemmer instance that performs the stemming.
token (lunr.Token): The token to stem.
i (int): The index of th... | [
"def",
"nltk_stemmer",
"(",
"stemmer",
",",
"token",
",",
"i",
"=",
"None",
",",
"tokens",
"=",
"None",
")",
":",
"def",
"wrapped_stem",
"(",
"token",
",",
"metadata",
"=",
"None",
")",
":",
"return",
"stemmer",
".",
"stem",
"(",
"token",
")",
"retur... | Wrapper around a NLTK SnowballStemmer, which includes stop words for
each language.
Args:
stemmer (SnowballStemmer): Stemmer instance that performs the stemming.
token (lunr.Token): The token to stem.
i (int): The index of the token in a set.
tokens (list): A list of tokens repr... | [
"Wrapper",
"around",
"a",
"NLTK",
"SnowballStemmer",
"which",
"includes",
"stop",
"words",
"for",
"each",
"language",
"."
] | 28ec3f6d4888295eed730211ee9617aa488d6ba3 | https://github.com/yeraydiazdiaz/lunr.py/blob/28ec3f6d4888295eed730211ee9617aa488d6ba3/lunr/languages/stemmer.py#L13-L27 | train |
Othernet-Project/sqlize | sqlize/builder.py | is_seq | def is_seq(obj):
""" Returns True if object is not a string but is iterable """
if not hasattr(obj, '__iter__'):
return False
if isinstance(obj, basestring):
return False
return True | python | def is_seq(obj):
""" Returns True if object is not a string but is iterable """
if not hasattr(obj, '__iter__'):
return False
if isinstance(obj, basestring):
return False
return True | [
"def",
"is_seq",
"(",
"obj",
")",
":",
"if",
"not",
"hasattr",
"(",
"obj",
",",
"'__iter__'",
")",
":",
"return",
"False",
"if",
"isinstance",
"(",
"obj",
",",
"basestring",
")",
":",
"return",
"False",
"return",
"True"
] | Returns True if object is not a string but is iterable | [
"Returns",
"True",
"if",
"object",
"is",
"not",
"a",
"string",
"but",
"is",
"iterable"
] | f32cb38e4245800ece339b998ae6647c207a8ca5 | https://github.com/Othernet-Project/sqlize/blob/f32cb38e4245800ece339b998ae6647c207a8ca5/sqlize/builder.py#L26-L32 | train |
jaraco/jaraco.mongodb | jaraco/mongodb/migration.py | Manager.register | def register(cls, func):
"""
Decorate a migration function with this method
to make it available for migrating cases.
"""
cls._add_version_info(func)
cls._upgrade_funcs.add(func)
return func | python | def register(cls, func):
"""
Decorate a migration function with this method
to make it available for migrating cases.
"""
cls._add_version_info(func)
cls._upgrade_funcs.add(func)
return func | [
"def",
"register",
"(",
"cls",
",",
"func",
")",
":",
"cls",
".",
"_add_version_info",
"(",
"func",
")",
"cls",
".",
"_upgrade_funcs",
".",
"add",
"(",
"func",
")",
"return",
"func"
] | Decorate a migration function with this method
to make it available for migrating cases. | [
"Decorate",
"a",
"migration",
"function",
"with",
"this",
"method",
"to",
"make",
"it",
"available",
"for",
"migrating",
"cases",
"."
] | 280f17894941f4babf2e97db033dbb1fd2b9f705 | https://github.com/jaraco/jaraco.mongodb/blob/280f17894941f4babf2e97db033dbb1fd2b9f705/jaraco/mongodb/migration.py#L69-L76 | train |
jaraco/jaraco.mongodb | jaraco/mongodb/migration.py | Manager._add_version_info | def _add_version_info(func):
"""
Add .source and .target attributes to the registered function.
"""
pattern = r'v(?P<source>\d+)_to_(?P<target>\d+)$'
match = re.match(pattern, func.__name__)
if not match:
raise ValueError("migration function name must match " + pattern)
func.source, func.target = map(i... | python | def _add_version_info(func):
"""
Add .source and .target attributes to the registered function.
"""
pattern = r'v(?P<source>\d+)_to_(?P<target>\d+)$'
match = re.match(pattern, func.__name__)
if not match:
raise ValueError("migration function name must match " + pattern)
func.source, func.target = map(i... | [
"def",
"_add_version_info",
"(",
"func",
")",
":",
"pattern",
"=",
"r'v(?P<source>\\d+)_to_(?P<target>\\d+)$'",
"match",
"=",
"re",
".",
"match",
"(",
"pattern",
",",
"func",
".",
"__name__",
")",
"if",
"not",
"match",
":",
"raise",
"ValueError",
"(",
"\"migra... | Add .source and .target attributes to the registered function. | [
"Add",
".",
"source",
"and",
".",
"target",
"attributes",
"to",
"the",
"registered",
"function",
"."
] | 280f17894941f4babf2e97db033dbb1fd2b9f705 | https://github.com/jaraco/jaraco.mongodb/blob/280f17894941f4babf2e97db033dbb1fd2b9f705/jaraco/mongodb/migration.py#L79-L87 | train |
jaraco/jaraco.mongodb | jaraco/mongodb/migration.py | Manager.migrate_doc | def migrate_doc(self, doc):
"""
Migrate the doc from its current version to the target version
and return it.
"""
orig_ver = doc.get(self.version_attribute_name, 0)
funcs = self._get_migrate_funcs(orig_ver, self.target_version)
for func in funcs:
func(self, doc)
doc[self.version_attribute_name] = fu... | python | def migrate_doc(self, doc):
"""
Migrate the doc from its current version to the target version
and return it.
"""
orig_ver = doc.get(self.version_attribute_name, 0)
funcs = self._get_migrate_funcs(orig_ver, self.target_version)
for func in funcs:
func(self, doc)
doc[self.version_attribute_name] = fu... | [
"def",
"migrate_doc",
"(",
"self",
",",
"doc",
")",
":",
"orig_ver",
"=",
"doc",
".",
"get",
"(",
"self",
".",
"version_attribute_name",
",",
"0",
")",
"funcs",
"=",
"self",
".",
"_get_migrate_funcs",
"(",
"orig_ver",
",",
"self",
".",
"target_version",
... | Migrate the doc from its current version to the target version
and return it. | [
"Migrate",
"the",
"doc",
"from",
"its",
"current",
"version",
"to",
"the",
"target",
"version",
"and",
"return",
"it",
"."
] | 280f17894941f4babf2e97db033dbb1fd2b9f705 | https://github.com/jaraco/jaraco.mongodb/blob/280f17894941f4babf2e97db033dbb1fd2b9f705/jaraco/mongodb/migration.py#L89-L99 | train |
jaraco/jaraco.mongodb | jaraco/mongodb/migration.py | Manager._get_func | def _get_func(cls, source_ver, target_ver):
"""
Return exactly one function to convert from source to target
"""
matches = (
func for func in cls._upgrade_funcs
if func.source == source_ver and func.target == target_ver
)
try:
match, = matches
except ValueError:
raise ValueError(
f"No migr... | python | def _get_func(cls, source_ver, target_ver):
"""
Return exactly one function to convert from source to target
"""
matches = (
func for func in cls._upgrade_funcs
if func.source == source_ver and func.target == target_ver
)
try:
match, = matches
except ValueError:
raise ValueError(
f"No migr... | [
"def",
"_get_func",
"(",
"cls",
",",
"source_ver",
",",
"target_ver",
")",
":",
"matches",
"=",
"(",
"func",
"for",
"func",
"in",
"cls",
".",
"_upgrade_funcs",
"if",
"func",
".",
"source",
"==",
"source_ver",
"and",
"func",
".",
"target",
"==",
"target_v... | Return exactly one function to convert from source to target | [
"Return",
"exactly",
"one",
"function",
"to",
"convert",
"from",
"source",
"to",
"target"
] | 280f17894941f4babf2e97db033dbb1fd2b9f705 | https://github.com/jaraco/jaraco.mongodb/blob/280f17894941f4babf2e97db033dbb1fd2b9f705/jaraco/mongodb/migration.py#L132-L145 | train |
senaite/senaite.api | src/senaite/api/__init__.py | get_uid | def get_uid(brain_or_object):
"""Get the Plone UID for this object
:param brain_or_object: A single catalog brain or content object
:type brain_or_object: ATContentType/DexterityContentType/CatalogBrain
:returns: Plone UID
:rtype: string
"""
if is_portal(brain_or_object):
return '0'... | python | def get_uid(brain_or_object):
"""Get the Plone UID for this object
:param brain_or_object: A single catalog brain or content object
:type brain_or_object: ATContentType/DexterityContentType/CatalogBrain
:returns: Plone UID
:rtype: string
"""
if is_portal(brain_or_object):
return '0'... | [
"def",
"get_uid",
"(",
"brain_or_object",
")",
":",
"if",
"is_portal",
"(",
"brain_or_object",
")",
":",
"return",
"'0'",
"if",
"is_brain",
"(",
"brain_or_object",
")",
"and",
"base_hasattr",
"(",
"brain_or_object",
",",
"\"UID\"",
")",
":",
"return",
"brain_o... | Get the Plone UID for this object
:param brain_or_object: A single catalog brain or content object
:type brain_or_object: ATContentType/DexterityContentType/CatalogBrain
:returns: Plone UID
:rtype: string | [
"Get",
"the",
"Plone",
"UID",
"for",
"this",
"object"
] | c79c53abcbe6e3a5ab3ced86d2f455275efa20cf | https://github.com/senaite/senaite.api/blob/c79c53abcbe6e3a5ab3ced86d2f455275efa20cf/src/senaite/api/__init__.py#L366-L378 | train |
senaite/senaite.api | src/senaite/api/__init__.py | get_icon | def get_icon(brain_or_object, html_tag=True):
"""Get the icon of the content object
:param brain_or_object: A single catalog brain or content object
:type brain_or_object: ATContentType/DexterityContentType/CatalogBrain
:param html_tag: A value of 'True' returns the HTML tag, else the image url
:ty... | python | def get_icon(brain_or_object, html_tag=True):
"""Get the icon of the content object
:param brain_or_object: A single catalog brain or content object
:type brain_or_object: ATContentType/DexterityContentType/CatalogBrain
:param html_tag: A value of 'True' returns the HTML tag, else the image url
:ty... | [
"def",
"get_icon",
"(",
"brain_or_object",
",",
"html_tag",
"=",
"True",
")",
":",
"# Manual approach, because `plone.app.layout.getIcon` does not reliable",
"# work for Bika Contents coming from other catalogs than the",
"# `portal_catalog`",
"portal_types",
"=",
"get_tool",
"(",
... | Get the icon of the content object
:param brain_or_object: A single catalog brain or content object
:type brain_or_object: ATContentType/DexterityContentType/CatalogBrain
:param html_tag: A value of 'True' returns the HTML tag, else the image url
:type html_tag: bool
:returns: HTML '<img>' tag if '... | [
"Get",
"the",
"icon",
"of",
"the",
"content",
"object"
] | c79c53abcbe6e3a5ab3ced86d2f455275efa20cf | https://github.com/senaite/senaite.api/blob/c79c53abcbe6e3a5ab3ced86d2f455275efa20cf/src/senaite/api/__init__.py#L394-L417 | train |
senaite/senaite.api | src/senaite/api/__init__.py | get_review_history | def get_review_history(brain_or_object, rev=True):
"""Get the review history for the given brain or context.
:param brain_or_object: A single catalog brain or content object
:type brain_or_object: ATContentType/DexterityContentType/CatalogBrain
:returns: Workflow history
:rtype: [{}, ...]
"""
... | python | def get_review_history(brain_or_object, rev=True):
"""Get the review history for the given brain or context.
:param brain_or_object: A single catalog brain or content object
:type brain_or_object: ATContentType/DexterityContentType/CatalogBrain
:returns: Workflow history
:rtype: [{}, ...]
"""
... | [
"def",
"get_review_history",
"(",
"brain_or_object",
",",
"rev",
"=",
"True",
")",
":",
"obj",
"=",
"get_object",
"(",
"brain_or_object",
")",
"review_history",
"=",
"[",
"]",
"try",
":",
"workflow",
"=",
"get_tool",
"(",
"\"portal_workflow\"",
")",
"review_hi... | Get the review history for the given brain or context.
:param brain_or_object: A single catalog brain or content object
:type brain_or_object: ATContentType/DexterityContentType/CatalogBrain
:returns: Workflow history
:rtype: [{}, ...] | [
"Get",
"the",
"review",
"history",
"for",
"the",
"given",
"brain",
"or",
"context",
"."
] | c79c53abcbe6e3a5ab3ced86d2f455275efa20cf | https://github.com/senaite/senaite.api/blob/c79c53abcbe6e3a5ab3ced86d2f455275efa20cf/src/senaite/api/__init__.py#L658-L681 | train |
senaite/senaite.api | src/senaite/api/__init__.py | get_cancellation_status | def get_cancellation_status(brain_or_object, default="active"):
"""Get the `cancellation_state` of an object
:param brain_or_object: A single catalog brain or content object
:type brain_or_object: ATContentType/DexterityContentType/CatalogBrain
:returns: Value of the review_status variable
:rtype: ... | python | def get_cancellation_status(brain_or_object, default="active"):
"""Get the `cancellation_state` of an object
:param brain_or_object: A single catalog brain or content object
:type brain_or_object: ATContentType/DexterityContentType/CatalogBrain
:returns: Value of the review_status variable
:rtype: ... | [
"def",
"get_cancellation_status",
"(",
"brain_or_object",
",",
"default",
"=",
"\"active\"",
")",
":",
"if",
"is_brain",
"(",
"brain_or_object",
")",
":",
"return",
"getattr",
"(",
"brain_or_object",
",",
"\"cancellation_state\"",
",",
"default",
")",
"workflows",
... | Get the `cancellation_state` of an object
:param brain_or_object: A single catalog brain or content object
:type brain_or_object: ATContentType/DexterityContentType/CatalogBrain
:returns: Value of the review_status variable
:rtype: String | [
"Get",
"the",
"cancellation_state",
"of",
"an",
"object"
] | c79c53abcbe6e3a5ab3ced86d2f455275efa20cf | https://github.com/senaite/senaite.api/blob/c79c53abcbe6e3a5ab3ced86d2f455275efa20cf/src/senaite/api/__init__.py#L759-L772 | train |
senaite/senaite.api | src/senaite/api/__init__.py | get_inactive_status | def get_inactive_status(brain_or_object, default="active"):
"""Get the `cancellation_state` of an objct
:param brain_or_object: A single catalog brain or content object
:type brain_or_object: ATContentType/DexterityContentType/CatalogBrain
:returns: Value of the review_status variable
:rtype: Strin... | python | def get_inactive_status(brain_or_object, default="active"):
"""Get the `cancellation_state` of an objct
:param brain_or_object: A single catalog brain or content object
:type brain_or_object: ATContentType/DexterityContentType/CatalogBrain
:returns: Value of the review_status variable
:rtype: Strin... | [
"def",
"get_inactive_status",
"(",
"brain_or_object",
",",
"default",
"=",
"\"active\"",
")",
":",
"if",
"is_brain",
"(",
"brain_or_object",
")",
":",
"return",
"getattr",
"(",
"brain_or_object",
",",
"\"inactive_state\"",
",",
"default",
")",
"workflows",
"=",
... | Get the `cancellation_state` of an objct
:param brain_or_object: A single catalog brain or content object
:type brain_or_object: ATContentType/DexterityContentType/CatalogBrain
:returns: Value of the review_status variable
:rtype: String | [
"Get",
"the",
"cancellation_state",
"of",
"an",
"objct"
] | c79c53abcbe6e3a5ab3ced86d2f455275efa20cf | https://github.com/senaite/senaite.api/blob/c79c53abcbe6e3a5ab3ced86d2f455275efa20cf/src/senaite/api/__init__.py#L792-L805 | train |
wroberts/fsed | fsed/fsed.py | set_log_level | def set_log_level(verbose, quiet):
'''
Ses the logging level of the script based on command line options.
Arguments:
- `verbose`:
- `quiet`:
'''
if quiet:
verbose = -1
if verbose < 0:
verbose = logging.CRITICAL
elif verbose == 0:
verbose = logging.WARNING
... | python | def set_log_level(verbose, quiet):
'''
Ses the logging level of the script based on command line options.
Arguments:
- `verbose`:
- `quiet`:
'''
if quiet:
verbose = -1
if verbose < 0:
verbose = logging.CRITICAL
elif verbose == 0:
verbose = logging.WARNING
... | [
"def",
"set_log_level",
"(",
"verbose",
",",
"quiet",
")",
":",
"if",
"quiet",
":",
"verbose",
"=",
"-",
"1",
"if",
"verbose",
"<",
"0",
":",
"verbose",
"=",
"logging",
".",
"CRITICAL",
"elif",
"verbose",
"==",
"0",
":",
"verbose",
"=",
"logging",
".... | Ses the logging level of the script based on command line options.
Arguments:
- `verbose`:
- `quiet`: | [
"Ses",
"the",
"logging",
"level",
"of",
"the",
"script",
"based",
"on",
"command",
"line",
"options",
"."
] | c0c1c5e0ea3a413ef679fdf71635f7f2e5d79ca2 | https://github.com/wroberts/fsed/blob/c0c1c5e0ea3a413ef679fdf71635f7f2e5d79ca2/fsed/fsed.py#L23-L41 | train |
wroberts/fsed | fsed/fsed.py | detect_pattern_format | def detect_pattern_format(pattern_filename, encoding, on_word_boundaries):
'''
Automatically detects the pattern file format, and determines
whether the Aho-Corasick string matching should pay attention to
word boundaries or not.
Arguments:
- `pattern_filename`:
- `encoding`:
- `on_word... | python | def detect_pattern_format(pattern_filename, encoding, on_word_boundaries):
'''
Automatically detects the pattern file format, and determines
whether the Aho-Corasick string matching should pay attention to
word boundaries or not.
Arguments:
- `pattern_filename`:
- `encoding`:
- `on_word... | [
"def",
"detect_pattern_format",
"(",
"pattern_filename",
",",
"encoding",
",",
"on_word_boundaries",
")",
":",
"tsv",
"=",
"True",
"boundaries",
"=",
"on_word_boundaries",
"with",
"open_file",
"(",
"pattern_filename",
")",
"as",
"input_file",
":",
"for",
"line",
"... | Automatically detects the pattern file format, and determines
whether the Aho-Corasick string matching should pay attention to
word boundaries or not.
Arguments:
- `pattern_filename`:
- `encoding`:
- `on_word_boundaries`: | [
"Automatically",
"detects",
"the",
"pattern",
"file",
"format",
"and",
"determines",
"whether",
"the",
"Aho",
"-",
"Corasick",
"string",
"matching",
"should",
"pay",
"attention",
"to",
"word",
"boundaries",
"or",
"not",
"."
] | c0c1c5e0ea3a413ef679fdf71635f7f2e5d79ca2 | https://github.com/wroberts/fsed/blob/c0c1c5e0ea3a413ef679fdf71635f7f2e5d79ca2/fsed/fsed.py#L43-L65 | train |
wroberts/fsed | fsed/fsed.py | sub_escapes | def sub_escapes(sval):
'''
Process escaped characters in ``sval``.
Arguments:
- `sval`:
'''
sval = sval.replace('\\a', '\a')
sval = sval.replace('\\b', '\x00')
sval = sval.replace('\\f', '\f')
sval = sval.replace('\\n', '\n')
sval = sval.replace('\\r', '\r')
sval = sval.repl... | python | def sub_escapes(sval):
'''
Process escaped characters in ``sval``.
Arguments:
- `sval`:
'''
sval = sval.replace('\\a', '\a')
sval = sval.replace('\\b', '\x00')
sval = sval.replace('\\f', '\f')
sval = sval.replace('\\n', '\n')
sval = sval.replace('\\r', '\r')
sval = sval.repl... | [
"def",
"sub_escapes",
"(",
"sval",
")",
":",
"sval",
"=",
"sval",
".",
"replace",
"(",
"'\\\\a'",
",",
"'\\a'",
")",
"sval",
"=",
"sval",
".",
"replace",
"(",
"'\\\\b'",
",",
"'\\x00'",
")",
"sval",
"=",
"sval",
".",
"replace",
"(",
"'\\\\f'",
",",
... | Process escaped characters in ``sval``.
Arguments:
- `sval`: | [
"Process",
"escaped",
"characters",
"in",
"sval",
"."
] | c0c1c5e0ea3a413ef679fdf71635f7f2e5d79ca2 | https://github.com/wroberts/fsed/blob/c0c1c5e0ea3a413ef679fdf71635f7f2e5d79ca2/fsed/fsed.py#L67-L82 | train |
wroberts/fsed | fsed/fsed.py | build_trie | def build_trie(pattern_filename, pattern_format, encoding, on_word_boundaries):
'''
Constructs a finite state machine for performing string rewriting.
Arguments:
- `pattern_filename`:
- `pattern_format`:
- `encoding`:
- `on_word_boundaries`:
'''
boundaries = on_word_boundaries
i... | python | def build_trie(pattern_filename, pattern_format, encoding, on_word_boundaries):
'''
Constructs a finite state machine for performing string rewriting.
Arguments:
- `pattern_filename`:
- `pattern_format`:
- `encoding`:
- `on_word_boundaries`:
'''
boundaries = on_word_boundaries
i... | [
"def",
"build_trie",
"(",
"pattern_filename",
",",
"pattern_format",
",",
"encoding",
",",
"on_word_boundaries",
")",
":",
"boundaries",
"=",
"on_word_boundaries",
"if",
"pattern_format",
"==",
"'auto'",
"or",
"not",
"on_word_boundaries",
":",
"tsv",
",",
"boundarie... | Constructs a finite state machine for performing string rewriting.
Arguments:
- `pattern_filename`:
- `pattern_format`:
- `encoding`:
- `on_word_boundaries`: | [
"Constructs",
"a",
"finite",
"state",
"machine",
"for",
"performing",
"string",
"rewriting",
"."
] | c0c1c5e0ea3a413ef679fdf71635f7f2e5d79ca2 | https://github.com/wroberts/fsed/blob/c0c1c5e0ea3a413ef679fdf71635f7f2e5d79ca2/fsed/fsed.py#L84-L148 | train |
wroberts/fsed | fsed/fsed.py | warn_prefix_values | def warn_prefix_values(trie):
'''
Prints warning messages for every node that has both a value and a
longest_prefix.
'''
for current, _parent in trie.dfs():
if current.has_value and current.longest_prefix is not None:
LOGGER.warn(('pattern {} (value {}) is a superstring of patter... | python | def warn_prefix_values(trie):
'''
Prints warning messages for every node that has both a value and a
longest_prefix.
'''
for current, _parent in trie.dfs():
if current.has_value and current.longest_prefix is not None:
LOGGER.warn(('pattern {} (value {}) is a superstring of patter... | [
"def",
"warn_prefix_values",
"(",
"trie",
")",
":",
"for",
"current",
",",
"_parent",
"in",
"trie",
".",
"dfs",
"(",
")",
":",
"if",
"current",
".",
"has_value",
"and",
"current",
".",
"longest_prefix",
"is",
"not",
"None",
":",
"LOGGER",
".",
"warn",
... | Prints warning messages for every node that has both a value and a
longest_prefix. | [
"Prints",
"warning",
"messages",
"for",
"every",
"node",
"that",
"has",
"both",
"a",
"value",
"and",
"a",
"longest_prefix",
"."
] | c0c1c5e0ea3a413ef679fdf71635f7f2e5d79ca2 | https://github.com/wroberts/fsed/blob/c0c1c5e0ea3a413ef679fdf71635f7f2e5d79ca2/fsed/fsed.py#L150-L160 | train |
wroberts/fsed | fsed/fsed.py | rewrite_str_with_trie | def rewrite_str_with_trie(sval, trie, boundaries = False, slow = False):
'''
Rewrites a string using the given trie object.
Arguments:
- `sval`:
- `trie`:
- `boundaries`:
- `slow`:
'''
if boundaries:
sval = fsed.ahocorasick.boundary_transform(sval)
if slow:
sval ... | python | def rewrite_str_with_trie(sval, trie, boundaries = False, slow = False):
'''
Rewrites a string using the given trie object.
Arguments:
- `sval`:
- `trie`:
- `boundaries`:
- `slow`:
'''
if boundaries:
sval = fsed.ahocorasick.boundary_transform(sval)
if slow:
sval ... | [
"def",
"rewrite_str_with_trie",
"(",
"sval",
",",
"trie",
",",
"boundaries",
"=",
"False",
",",
"slow",
"=",
"False",
")",
":",
"if",
"boundaries",
":",
"sval",
"=",
"fsed",
".",
"ahocorasick",
".",
"boundary_transform",
"(",
"sval",
")",
"if",
"slow",
"... | Rewrites a string using the given trie object.
Arguments:
- `sval`:
- `trie`:
- `boundaries`:
- `slow`: | [
"Rewrites",
"a",
"string",
"using",
"the",
"given",
"trie",
"object",
"."
] | c0c1c5e0ea3a413ef679fdf71635f7f2e5d79ca2 | https://github.com/wroberts/fsed/blob/c0c1c5e0ea3a413ef679fdf71635f7f2e5d79ca2/fsed/fsed.py#L162-L180 | train |
yeraydiazdiaz/lunr.py | lunr/pipeline.py | Pipeline.register_function | def register_function(cls, fn, label):
"""Register a function with the pipeline."""
if label in cls.registered_functions:
log.warning("Overwriting existing registered function %s", label)
fn.label = label
cls.registered_functions[fn.label] = fn | python | def register_function(cls, fn, label):
"""Register a function with the pipeline."""
if label in cls.registered_functions:
log.warning("Overwriting existing registered function %s", label)
fn.label = label
cls.registered_functions[fn.label] = fn | [
"def",
"register_function",
"(",
"cls",
",",
"fn",
",",
"label",
")",
":",
"if",
"label",
"in",
"cls",
".",
"registered_functions",
":",
"log",
".",
"warning",
"(",
"\"Overwriting existing registered function %s\"",
",",
"label",
")",
"fn",
".",
"label",
"=",
... | Register a function with the pipeline. | [
"Register",
"a",
"function",
"with",
"the",
"pipeline",
"."
] | 28ec3f6d4888295eed730211ee9617aa488d6ba3 | https://github.com/yeraydiazdiaz/lunr.py/blob/28ec3f6d4888295eed730211ee9617aa488d6ba3/lunr/pipeline.py#L34-L40 | train |
yeraydiazdiaz/lunr.py | lunr/pipeline.py | Pipeline.load | def load(cls, serialised):
"""Loads a previously serialised pipeline."""
pipeline = cls()
for fn_name in serialised:
try:
fn = cls.registered_functions[fn_name]
except KeyError:
raise BaseLunrException(
"Cannot load unre... | python | def load(cls, serialised):
"""Loads a previously serialised pipeline."""
pipeline = cls()
for fn_name in serialised:
try:
fn = cls.registered_functions[fn_name]
except KeyError:
raise BaseLunrException(
"Cannot load unre... | [
"def",
"load",
"(",
"cls",
",",
"serialised",
")",
":",
"pipeline",
"=",
"cls",
"(",
")",
"for",
"fn_name",
"in",
"serialised",
":",
"try",
":",
"fn",
"=",
"cls",
".",
"registered_functions",
"[",
"fn_name",
"]",
"except",
"KeyError",
":",
"raise",
"Ba... | Loads a previously serialised pipeline. | [
"Loads",
"a",
"previously",
"serialised",
"pipeline",
"."
] | 28ec3f6d4888295eed730211ee9617aa488d6ba3 | https://github.com/yeraydiazdiaz/lunr.py/blob/28ec3f6d4888295eed730211ee9617aa488d6ba3/lunr/pipeline.py#L43-L56 | train |
yeraydiazdiaz/lunr.py | lunr/pipeline.py | Pipeline.add | def add(self, *args):
"""Adds new functions to the end of the pipeline.
Functions must accept three arguments:
- Token: A lunr.Token object which will be updated
- i: The index of the token in the set
- tokens: A list of tokens representing the set
"""
for fn in ... | python | def add(self, *args):
"""Adds new functions to the end of the pipeline.
Functions must accept three arguments:
- Token: A lunr.Token object which will be updated
- i: The index of the token in the set
- tokens: A list of tokens representing the set
"""
for fn in ... | [
"def",
"add",
"(",
"self",
",",
"*",
"args",
")",
":",
"for",
"fn",
"in",
"args",
":",
"self",
".",
"warn_if_function_not_registered",
"(",
"fn",
")",
"self",
".",
"_stack",
".",
"append",
"(",
"fn",
")"
] | Adds new functions to the end of the pipeline.
Functions must accept three arguments:
- Token: A lunr.Token object which will be updated
- i: The index of the token in the set
- tokens: A list of tokens representing the set | [
"Adds",
"new",
"functions",
"to",
"the",
"end",
"of",
"the",
"pipeline",
"."
] | 28ec3f6d4888295eed730211ee9617aa488d6ba3 | https://github.com/yeraydiazdiaz/lunr.py/blob/28ec3f6d4888295eed730211ee9617aa488d6ba3/lunr/pipeline.py#L58-L68 | train |
yeraydiazdiaz/lunr.py | lunr/pipeline.py | Pipeline.after | def after(self, existing_fn, new_fn):
"""Adds a single function after a function that already exists in the
pipeline."""
self.warn_if_function_not_registered(new_fn)
try:
index = self._stack.index(existing_fn)
self._stack.insert(index + 1, new_fn)
except V... | python | def after(self, existing_fn, new_fn):
"""Adds a single function after a function that already exists in the
pipeline."""
self.warn_if_function_not_registered(new_fn)
try:
index = self._stack.index(existing_fn)
self._stack.insert(index + 1, new_fn)
except V... | [
"def",
"after",
"(",
"self",
",",
"existing_fn",
",",
"new_fn",
")",
":",
"self",
".",
"warn_if_function_not_registered",
"(",
"new_fn",
")",
"try",
":",
"index",
"=",
"self",
".",
"_stack",
".",
"index",
"(",
"existing_fn",
")",
"self",
".",
"_stack",
"... | Adds a single function after a function that already exists in the
pipeline. | [
"Adds",
"a",
"single",
"function",
"after",
"a",
"function",
"that",
"already",
"exists",
"in",
"the",
"pipeline",
"."
] | 28ec3f6d4888295eed730211ee9617aa488d6ba3 | https://github.com/yeraydiazdiaz/lunr.py/blob/28ec3f6d4888295eed730211ee9617aa488d6ba3/lunr/pipeline.py#L81-L89 | train |
yeraydiazdiaz/lunr.py | lunr/pipeline.py | Pipeline.run | def run(self, tokens):
"""Runs the current list of functions that make up the pipeline against
the passed tokens."""
for fn in self._stack:
results = []
for i, token in enumerate(tokens):
# JS ignores additional arguments to the functions but we
... | python | def run(self, tokens):
"""Runs the current list of functions that make up the pipeline against
the passed tokens."""
for fn in self._stack:
results = []
for i, token in enumerate(tokens):
# JS ignores additional arguments to the functions but we
... | [
"def",
"run",
"(",
"self",
",",
"tokens",
")",
":",
"for",
"fn",
"in",
"self",
".",
"_stack",
":",
"results",
"=",
"[",
"]",
"for",
"i",
",",
"token",
"in",
"enumerate",
"(",
"tokens",
")",
":",
"# JS ignores additional arguments to the functions but we",
... | Runs the current list of functions that make up the pipeline against
the passed tokens. | [
"Runs",
"the",
"current",
"list",
"of",
"functions",
"that",
"make",
"up",
"the",
"pipeline",
"against",
"the",
"passed",
"tokens",
"."
] | 28ec3f6d4888295eed730211ee9617aa488d6ba3 | https://github.com/yeraydiazdiaz/lunr.py/blob/28ec3f6d4888295eed730211ee9617aa488d6ba3/lunr/pipeline.py#L110-L128 | train |
yeraydiazdiaz/lunr.py | lunr/pipeline.py | Pipeline.run_string | def run_string(self, string, metadata=None):
"""Convenience method for passing a string through a pipeline and
getting strings out. This method takes care of wrapping the passed
string in a token and mapping the resulting tokens back to strings."""
token = Token(string, metadata)
... | python | def run_string(self, string, metadata=None):
"""Convenience method for passing a string through a pipeline and
getting strings out. This method takes care of wrapping the passed
string in a token and mapping the resulting tokens back to strings."""
token = Token(string, metadata)
... | [
"def",
"run_string",
"(",
"self",
",",
"string",
",",
"metadata",
"=",
"None",
")",
":",
"token",
"=",
"Token",
"(",
"string",
",",
"metadata",
")",
"return",
"[",
"str",
"(",
"tkn",
")",
"for",
"tkn",
"in",
"self",
".",
"run",
"(",
"[",
"token",
... | Convenience method for passing a string through a pipeline and
getting strings out. This method takes care of wrapping the passed
string in a token and mapping the resulting tokens back to strings. | [
"Convenience",
"method",
"for",
"passing",
"a",
"string",
"through",
"a",
"pipeline",
"and",
"getting",
"strings",
"out",
".",
"This",
"method",
"takes",
"care",
"of",
"wrapping",
"the",
"passed",
"string",
"in",
"a",
"token",
"and",
"mapping",
"the",
"resul... | 28ec3f6d4888295eed730211ee9617aa488d6ba3 | https://github.com/yeraydiazdiaz/lunr.py/blob/28ec3f6d4888295eed730211ee9617aa488d6ba3/lunr/pipeline.py#L130-L135 | train |
jaraco/jaraco.mongodb | jaraco/mongodb/pmxbot.py | get_client | def get_client():
"""
Use the same MongoDB client as pmxbot if available.
"""
with contextlib.suppress(Exception):
store = Storage.from_URI()
assert isinstance(store, pmxbot.storage.MongoDBStorage)
return store.db.database.client | python | def get_client():
"""
Use the same MongoDB client as pmxbot if available.
"""
with contextlib.suppress(Exception):
store = Storage.from_URI()
assert isinstance(store, pmxbot.storage.MongoDBStorage)
return store.db.database.client | [
"def",
"get_client",
"(",
")",
":",
"with",
"contextlib",
".",
"suppress",
"(",
"Exception",
")",
":",
"store",
"=",
"Storage",
".",
"from_URI",
"(",
")",
"assert",
"isinstance",
"(",
"store",
",",
"pmxbot",
".",
"storage",
".",
"MongoDBStorage",
")",
"r... | Use the same MongoDB client as pmxbot if available. | [
"Use",
"the",
"same",
"MongoDB",
"client",
"as",
"pmxbot",
"if",
"available",
"."
] | 280f17894941f4babf2e97db033dbb1fd2b9f705 | https://github.com/jaraco/jaraco.mongodb/blob/280f17894941f4babf2e97db033dbb1fd2b9f705/jaraco/mongodb/pmxbot.py#L13-L20 | train |
jaraco/jaraco.mongodb | jaraco/mongodb/sharding.py | create_db_in_shard | def create_db_in_shard(db_name, shard, client=None):
"""
In a sharded cluster, create a database in a particular shard.
"""
client = client or pymongo.MongoClient()
# flush the router config to ensure it's not stale
res = client.admin.command('flushRouterConfig')
if not res.get('ok'):
... | python | def create_db_in_shard(db_name, shard, client=None):
"""
In a sharded cluster, create a database in a particular shard.
"""
client = client or pymongo.MongoClient()
# flush the router config to ensure it's not stale
res = client.admin.command('flushRouterConfig')
if not res.get('ok'):
... | [
"def",
"create_db_in_shard",
"(",
"db_name",
",",
"shard",
",",
"client",
"=",
"None",
")",
":",
"client",
"=",
"client",
"or",
"pymongo",
".",
"MongoClient",
"(",
")",
"# flush the router config to ensure it's not stale",
"res",
"=",
"client",
".",
"admin",
"."... | In a sharded cluster, create a database in a particular shard. | [
"In",
"a",
"sharded",
"cluster",
"create",
"a",
"database",
"in",
"a",
"particular",
"shard",
"."
] | 280f17894941f4babf2e97db033dbb1fd2b9f705 | https://github.com/jaraco/jaraco.mongodb/blob/280f17894941f4babf2e97db033dbb1fd2b9f705/jaraco/mongodb/sharding.py#L16-L43 | train |
tehmaze/natural | natural/util.py | luhn_checksum | def luhn_checksum(number, chars=DIGITS):
'''
Calculates the Luhn checksum for `number`
:param number: string or int
:param chars: string
>>> luhn_checksum(1234)
4
'''
length = len(chars)
number = [chars.index(n) for n in reversed(str(number))]
return (
sum(number[::2])... | python | def luhn_checksum(number, chars=DIGITS):
'''
Calculates the Luhn checksum for `number`
:param number: string or int
:param chars: string
>>> luhn_checksum(1234)
4
'''
length = len(chars)
number = [chars.index(n) for n in reversed(str(number))]
return (
sum(number[::2])... | [
"def",
"luhn_checksum",
"(",
"number",
",",
"chars",
"=",
"DIGITS",
")",
":",
"length",
"=",
"len",
"(",
"chars",
")",
"number",
"=",
"[",
"chars",
".",
"index",
"(",
"n",
")",
"for",
"n",
"in",
"reversed",
"(",
"str",
"(",
"number",
")",
")",
"]... | Calculates the Luhn checksum for `number`
:param number: string or int
:param chars: string
>>> luhn_checksum(1234)
4 | [
"Calculates",
"the",
"Luhn",
"checksum",
"for",
"number"
] | d7a1fc9de712f9bcf68884a80826a7977df356fb | https://github.com/tehmaze/natural/blob/d7a1fc9de712f9bcf68884a80826a7977df356fb/natural/util.py#L9-L25 | train |
tehmaze/natural | natural/util.py | luhn_calc | def luhn_calc(number, chars=DIGITS):
'''
Calculate the Luhn check digit for ``number``.
:param number: string
:param chars: string
>>> luhn_calc('42')
'2'
'''
checksum = luhn_checksum(str(number) + chars[0], chars)
return chars[-checksum] | python | def luhn_calc(number, chars=DIGITS):
'''
Calculate the Luhn check digit for ``number``.
:param number: string
:param chars: string
>>> luhn_calc('42')
'2'
'''
checksum = luhn_checksum(str(number) + chars[0], chars)
return chars[-checksum] | [
"def",
"luhn_calc",
"(",
"number",
",",
"chars",
"=",
"DIGITS",
")",
":",
"checksum",
"=",
"luhn_checksum",
"(",
"str",
"(",
"number",
")",
"+",
"chars",
"[",
"0",
"]",
",",
"chars",
")",
"return",
"chars",
"[",
"-",
"checksum",
"]"
] | Calculate the Luhn check digit for ``number``.
:param number: string
:param chars: string
>>> luhn_calc('42')
'2' | [
"Calculate",
"the",
"Luhn",
"check",
"digit",
"for",
"number",
"."
] | d7a1fc9de712f9bcf68884a80826a7977df356fb | https://github.com/tehmaze/natural/blob/d7a1fc9de712f9bcf68884a80826a7977df356fb/natural/util.py#L28-L41 | train |
tehmaze/natural | natural/util.py | to_decimal | def to_decimal(number, strip='- '):
'''
Converts a number to a string of decimals in base 10.
>>> to_decimal(123)
'123'
>>> to_decimal('o123')
'83'
>>> to_decimal('b101010')
'42'
>>> to_decimal('0x2a')
'42'
'''
if isinstance(number, six.integer_types):
return str... | python | def to_decimal(number, strip='- '):
'''
Converts a number to a string of decimals in base 10.
>>> to_decimal(123)
'123'
>>> to_decimal('o123')
'83'
>>> to_decimal('b101010')
'42'
>>> to_decimal('0x2a')
'42'
'''
if isinstance(number, six.integer_types):
return str... | [
"def",
"to_decimal",
"(",
"number",
",",
"strip",
"=",
"'- '",
")",
":",
"if",
"isinstance",
"(",
"number",
",",
"six",
".",
"integer_types",
")",
":",
"return",
"str",
"(",
"number",
")",
"number",
"=",
"str",
"(",
"number",
")",
"number",
"=",
"re"... | Converts a number to a string of decimals in base 10.
>>> to_decimal(123)
'123'
>>> to_decimal('o123')
'83'
>>> to_decimal('b101010')
'42'
>>> to_decimal('0x2a')
'42' | [
"Converts",
"a",
"number",
"to",
"a",
"string",
"of",
"decimals",
"in",
"base",
"10",
"."
] | d7a1fc9de712f9bcf68884a80826a7977df356fb | https://github.com/tehmaze/natural/blob/d7a1fc9de712f9bcf68884a80826a7977df356fb/natural/util.py#L71-L103 | train |
druids/django-chamber | chamber/utils/__init__.py | get_class_method | def get_class_method(cls_or_inst, method_name):
"""
Returns a method from a given class or instance. When the method doest not exist, it returns `None`. Also works with
properties and cached properties.
"""
cls = cls_or_inst if isinstance(cls_or_inst, type) else cls_or_inst.__class__
meth = geta... | python | def get_class_method(cls_or_inst, method_name):
"""
Returns a method from a given class or instance. When the method doest not exist, it returns `None`. Also works with
properties and cached properties.
"""
cls = cls_or_inst if isinstance(cls_or_inst, type) else cls_or_inst.__class__
meth = geta... | [
"def",
"get_class_method",
"(",
"cls_or_inst",
",",
"method_name",
")",
":",
"cls",
"=",
"cls_or_inst",
"if",
"isinstance",
"(",
"cls_or_inst",
",",
"type",
")",
"else",
"cls_or_inst",
".",
"__class__",
"meth",
"=",
"getattr",
"(",
"cls",
",",
"method_name",
... | Returns a method from a given class or instance. When the method doest not exist, it returns `None`. Also works with
properties and cached properties. | [
"Returns",
"a",
"method",
"from",
"a",
"given",
"class",
"or",
"instance",
".",
"When",
"the",
"method",
"doest",
"not",
"exist",
"it",
"returns",
"None",
".",
"Also",
"works",
"with",
"properties",
"and",
"cached",
"properties",
"."
] | eef4169923557e96877a664fa254e8c0814f3f23 | https://github.com/druids/django-chamber/blob/eef4169923557e96877a664fa254e8c0814f3f23/chamber/utils/__init__.py#L17-L28 | train |
guaix-ucm/numina | numina/frame/combine.py | manage_fits | def manage_fits(list_of_frame):
"""Manage a list of FITS resources"""
import astropy.io.fits as fits
import numina.types.dataframe as df
refs = []
for frame in list_of_frame:
if isinstance(frame, str):
ref = fits.open(frame)
refs.append(ref)
elif isinstance(... | python | def manage_fits(list_of_frame):
"""Manage a list of FITS resources"""
import astropy.io.fits as fits
import numina.types.dataframe as df
refs = []
for frame in list_of_frame:
if isinstance(frame, str):
ref = fits.open(frame)
refs.append(ref)
elif isinstance(... | [
"def",
"manage_fits",
"(",
"list_of_frame",
")",
":",
"import",
"astropy",
".",
"io",
".",
"fits",
"as",
"fits",
"import",
"numina",
".",
"types",
".",
"dataframe",
"as",
"df",
"refs",
"=",
"[",
"]",
"for",
"frame",
"in",
"list_of_frame",
":",
"if",
"i... | Manage a list of FITS resources | [
"Manage",
"a",
"list",
"of",
"FITS",
"resources"
] | 6c829495df8937f77c2de9383c1038ffb3e713e3 | https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/frame/combine.py#L185-L208 | train |
guaix-ucm/numina | numina/array/display/logging_from_debugplot.py | logging_from_debugplot | def logging_from_debugplot(debugplot):
"""Set debugging level based on debugplot value.
Parameters
----------
debugplot : int
Debugging level for messages and plots. For details see
'numina.array.display.pause_debugplot.py'.
"""
if isinstance(debugplot, int):
if... | python | def logging_from_debugplot(debugplot):
"""Set debugging level based on debugplot value.
Parameters
----------
debugplot : int
Debugging level for messages and plots. For details see
'numina.array.display.pause_debugplot.py'.
"""
if isinstance(debugplot, int):
if... | [
"def",
"logging_from_debugplot",
"(",
"debugplot",
")",
":",
"if",
"isinstance",
"(",
"debugplot",
",",
"int",
")",
":",
"if",
"abs",
"(",
"debugplot",
")",
">=",
"10",
":",
"logging",
".",
"basicConfig",
"(",
"level",
"=",
"logging",
".",
"DEBUG",
")",
... | Set debugging level based on debugplot value.
Parameters
----------
debugplot : int
Debugging level for messages and plots. For details see
'numina.array.display.pause_debugplot.py'. | [
"Set",
"debugging",
"level",
"based",
"on",
"debugplot",
"value",
"."
] | 6c829495df8937f77c2de9383c1038ffb3e713e3 | https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/array/display/logging_from_debugplot.py#L26-L42 | train |
guaix-ucm/numina | numina/array/display/ximplot.py | ximplot | def ximplot(ycut, title=None, show=True, plot_bbox=(0, 0),
geometry=(0, 0, 640, 480), tight_layout=True,
debugplot=None):
"""Auxiliary function to display 1d plot.
Parameters
----------
ycut : 1d numpy array, float
Array to be displayed.
title : string
Plot t... | python | def ximplot(ycut, title=None, show=True, plot_bbox=(0, 0),
geometry=(0, 0, 640, 480), tight_layout=True,
debugplot=None):
"""Auxiliary function to display 1d plot.
Parameters
----------
ycut : 1d numpy array, float
Array to be displayed.
title : string
Plot t... | [
"def",
"ximplot",
"(",
"ycut",
",",
"title",
"=",
"None",
",",
"show",
"=",
"True",
",",
"plot_bbox",
"=",
"(",
"0",
",",
"0",
")",
",",
"geometry",
"=",
"(",
"0",
",",
"0",
",",
"640",
",",
"480",
")",
",",
"tight_layout",
"=",
"True",
",",
... | Auxiliary function to display 1d plot.
Parameters
----------
ycut : 1d numpy array, float
Array to be displayed.
title : string
Plot title.
show : bool
If True, the function shows the displayed image. Otherwise
plt.show() is expected to be executed outside.
plot_... | [
"Auxiliary",
"function",
"to",
"display",
"1d",
"plot",
"."
] | 6c829495df8937f77c2de9383c1038ffb3e713e3 | https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/array/display/ximplot.py#L19-L112 | train |
guaix-ucm/numina | numina/array/wavecalib/resample.py | oversample1d | def oversample1d(sp, crval1, cdelt1, oversampling=1, debugplot=0):
"""Oversample spectrum.
Parameters
----------
sp : numpy array
Spectrum to be oversampled.
crval1 : float
Abscissae of the center of the first pixel in the original
spectrum 'sp'.
cdelt1 : float
A... | python | def oversample1d(sp, crval1, cdelt1, oversampling=1, debugplot=0):
"""Oversample spectrum.
Parameters
----------
sp : numpy array
Spectrum to be oversampled.
crval1 : float
Abscissae of the center of the first pixel in the original
spectrum 'sp'.
cdelt1 : float
A... | [
"def",
"oversample1d",
"(",
"sp",
",",
"crval1",
",",
"cdelt1",
",",
"oversampling",
"=",
"1",
",",
"debugplot",
"=",
"0",
")",
":",
"if",
"sp",
".",
"ndim",
"!=",
"1",
":",
"raise",
"ValueError",
"(",
"'Unexpected array dimensions'",
")",
"naxis1",
"=",... | Oversample spectrum.
Parameters
----------
sp : numpy array
Spectrum to be oversampled.
crval1 : float
Abscissae of the center of the first pixel in the original
spectrum 'sp'.
cdelt1 : float
Abscissae increment corresponding to 1 pixel in the original
spectr... | [
"Oversample",
"spectrum",
"."
] | 6c829495df8937f77c2de9383c1038ffb3e713e3 | https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/array/wavecalib/resample.py#L22-L78 | train |
guaix-ucm/numina | numina/array/wavecalib/resample.py | map_borders | def map_borders(wls):
"""Compute borders of pixels for interpolation.
The border of the pixel is assumed to be midway of the wls
"""
midpt_wl = 0.5 * (wls[1:] + wls[:-1])
all_borders = np.zeros((wls.shape[0] + 1,))
all_borders[1:-1] = midpt_wl
all_borders[0] = 2 * wls[0] - midpt_wl[0]
a... | python | def map_borders(wls):
"""Compute borders of pixels for interpolation.
The border of the pixel is assumed to be midway of the wls
"""
midpt_wl = 0.5 * (wls[1:] + wls[:-1])
all_borders = np.zeros((wls.shape[0] + 1,))
all_borders[1:-1] = midpt_wl
all_borders[0] = 2 * wls[0] - midpt_wl[0]
a... | [
"def",
"map_borders",
"(",
"wls",
")",
":",
"midpt_wl",
"=",
"0.5",
"*",
"(",
"wls",
"[",
"1",
":",
"]",
"+",
"wls",
"[",
":",
"-",
"1",
"]",
")",
"all_borders",
"=",
"np",
".",
"zeros",
"(",
"(",
"wls",
".",
"shape",
"[",
"0",
"]",
"+",
"1... | Compute borders of pixels for interpolation.
The border of the pixel is assumed to be midway of the wls | [
"Compute",
"borders",
"of",
"pixels",
"for",
"interpolation",
"."
] | 6c829495df8937f77c2de9383c1038ffb3e713e3 | https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/array/wavecalib/resample.py#L215-L225 | train |
guaix-ucm/numina | numina/util/objimport.py | import_object | def import_object(path):
"""Import an object given its fully qualified name."""
spl = path.split('.')
if len(spl) == 1:
return importlib.import_module(path)
# avoid last part for the moment
cls = spl[-1]
mods = '.'.join(spl[:-1])
mm = importlib.import_module(mods)
# try to get t... | python | def import_object(path):
"""Import an object given its fully qualified name."""
spl = path.split('.')
if len(spl) == 1:
return importlib.import_module(path)
# avoid last part for the moment
cls = spl[-1]
mods = '.'.join(spl[:-1])
mm = importlib.import_module(mods)
# try to get t... | [
"def",
"import_object",
"(",
"path",
")",
":",
"spl",
"=",
"path",
".",
"split",
"(",
"'.'",
")",
"if",
"len",
"(",
"spl",
")",
"==",
"1",
":",
"return",
"importlib",
".",
"import_module",
"(",
"path",
")",
"# avoid last part for the moment",
"cls",
"=",... | Import an object given its fully qualified name. | [
"Import",
"an",
"object",
"given",
"its",
"fully",
"qualified",
"name",
"."
] | 6c829495df8937f77c2de9383c1038ffb3e713e3 | https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/util/objimport.py#L17-L36 | train |
ckan/losser | losser/cli.py | make_parser | def make_parser(add_help=True, exclude_args=None):
"""Return an argparse.ArgumentParser object with losser's arguments.
Other projects can call this to get an ArgumentParser with losser's
command line interface to use as a parent parser for their own parser.
For example::
parent_parser = losse... | python | def make_parser(add_help=True, exclude_args=None):
"""Return an argparse.ArgumentParser object with losser's arguments.
Other projects can call this to get an ArgumentParser with losser's
command line interface to use as a parent parser for their own parser.
For example::
parent_parser = losse... | [
"def",
"make_parser",
"(",
"add_help",
"=",
"True",
",",
"exclude_args",
"=",
"None",
")",
":",
"if",
"exclude_args",
"is",
"None",
":",
"exclude_args",
"=",
"[",
"]",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"add_help",
"=",
"add_help",
")",... | Return an argparse.ArgumentParser object with losser's arguments.
Other projects can call this to get an ArgumentParser with losser's
command line interface to use as a parent parser for their own parser.
For example::
parent_parser = losser.cli.make_parser(
add_help=False, exclude_arg... | [
"Return",
"an",
"argparse",
".",
"ArgumentParser",
"object",
"with",
"losser",
"s",
"arguments",
"."
] | fd0832d9fa93cabe9ce9a9153dc923f2cf39cb5f | https://github.com/ckan/losser/blob/fd0832d9fa93cabe9ce9a9153dc923f2cf39cb5f/losser/cli.py#L153-L211 | train |
ckan/losser | losser/cli.py | parse | def parse(parser=None, args=None):
"""Parse the command line arguments, return an argparse namespace object.
Other projects can call this function and pass in their own ArgumentParser
object (which should have a losser ArgumentParser from make_parser() above
as parent) to do the argument parsing and ge... | python | def parse(parser=None, args=None):
"""Parse the command line arguments, return an argparse namespace object.
Other projects can call this function and pass in their own ArgumentParser
object (which should have a losser ArgumentParser from make_parser() above
as parent) to do the argument parsing and ge... | [
"def",
"parse",
"(",
"parser",
"=",
"None",
",",
"args",
"=",
"None",
")",
":",
"if",
"not",
"parser",
":",
"parser",
"=",
"make_parser",
"(",
")",
"try",
":",
"parsed_args",
"=",
"parser",
".",
"parse_args",
"(",
"args",
")",
"except",
"SystemExit",
... | Parse the command line arguments, return an argparse namespace object.
Other projects can call this function and pass in their own ArgumentParser
object (which should have a losser ArgumentParser from make_parser() above
as parent) to do the argument parsing and get the result (this does some
custom po... | [
"Parse",
"the",
"command",
"line",
"arguments",
"return",
"an",
"argparse",
"namespace",
"object",
"."
] | fd0832d9fa93cabe9ce9a9153dc923f2cf39cb5f | https://github.com/ckan/losser/blob/fd0832d9fa93cabe9ce9a9153dc923f2cf39cb5f/losser/cli.py#L214-L282 | train |
ckan/losser | losser/cli.py | do | def do(parser=None, args=None, in_=None, table_function=None):
"""Read command-line args and stdin, return the result.
Read the command line arguments and the input data from stdin, pass them to
the table() function to do the filter and transform, and return the string
of CSV- or JSON-formatted text th... | python | def do(parser=None, args=None, in_=None, table_function=None):
"""Read command-line args and stdin, return the result.
Read the command line arguments and the input data from stdin, pass them to
the table() function to do the filter and transform, and return the string
of CSV- or JSON-formatted text th... | [
"def",
"do",
"(",
"parser",
"=",
"None",
",",
"args",
"=",
"None",
",",
"in_",
"=",
"None",
",",
"table_function",
"=",
"None",
")",
":",
"in_",
"=",
"in_",
"or",
"sys",
".",
"stdin",
"table_function",
"=",
"table_function",
"or",
"losser",
".",
"tab... | Read command-line args and stdin, return the result.
Read the command line arguments and the input data from stdin, pass them to
the table() function to do the filter and transform, and return the string
of CSV- or JSON-formatted text that should be written to stdout.
Note that although the output dat... | [
"Read",
"command",
"-",
"line",
"args",
"and",
"stdin",
"return",
"the",
"result",
"."
] | fd0832d9fa93cabe9ce9a9153dc923f2cf39cb5f | https://github.com/ckan/losser/blob/fd0832d9fa93cabe9ce9a9153dc923f2cf39cb5f/losser/cli.py#L285-L314 | train |
guaix-ucm/numina | numina/instrument/simulation/atmosphere.py | generate_gaussian_profile | def generate_gaussian_profile(seeing_fwhm):
"""Generate a normalized Gaussian profile from its FWHM"""
FWHM_G = 2 * math.sqrt(2 * math.log(2))
sigma = seeing_fwhm / FWHM_G
amplitude = 1.0 / (2 * math.pi * sigma * sigma)
seeing_model = Gaussian2D(amplitude=amplitude,
x_m... | python | def generate_gaussian_profile(seeing_fwhm):
"""Generate a normalized Gaussian profile from its FWHM"""
FWHM_G = 2 * math.sqrt(2 * math.log(2))
sigma = seeing_fwhm / FWHM_G
amplitude = 1.0 / (2 * math.pi * sigma * sigma)
seeing_model = Gaussian2D(amplitude=amplitude,
x_m... | [
"def",
"generate_gaussian_profile",
"(",
"seeing_fwhm",
")",
":",
"FWHM_G",
"=",
"2",
"*",
"math",
".",
"sqrt",
"(",
"2",
"*",
"math",
".",
"log",
"(",
"2",
")",
")",
"sigma",
"=",
"seeing_fwhm",
"/",
"FWHM_G",
"amplitude",
"=",
"1.0",
"/",
"(",
"2",... | Generate a normalized Gaussian profile from its FWHM | [
"Generate",
"a",
"normalized",
"Gaussian",
"profile",
"from",
"its",
"FWHM"
] | 6c829495df8937f77c2de9383c1038ffb3e713e3 | https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/instrument/simulation/atmosphere.py#L65-L75 | train |
guaix-ucm/numina | numina/instrument/simulation/atmosphere.py | generate_moffat_profile | def generate_moffat_profile(seeing_fwhm, alpha):
"""Generate a normalized Moffat profile from its FWHM and alpha"""
scale = 2 * math.sqrt(2**(1.0 / alpha) - 1)
gamma = seeing_fwhm / scale
amplitude = 1.0 / math.pi * (alpha - 1) / gamma**2
seeing_model = Moffat2D(amplitude=amplitude,
... | python | def generate_moffat_profile(seeing_fwhm, alpha):
"""Generate a normalized Moffat profile from its FWHM and alpha"""
scale = 2 * math.sqrt(2**(1.0 / alpha) - 1)
gamma = seeing_fwhm / scale
amplitude = 1.0 / math.pi * (alpha - 1) / gamma**2
seeing_model = Moffat2D(amplitude=amplitude,
... | [
"def",
"generate_moffat_profile",
"(",
"seeing_fwhm",
",",
"alpha",
")",
":",
"scale",
"=",
"2",
"*",
"math",
".",
"sqrt",
"(",
"2",
"**",
"(",
"1.0",
"/",
"alpha",
")",
"-",
"1",
")",
"gamma",
"=",
"seeing_fwhm",
"/",
"scale",
"amplitude",
"=",
"1.0... | Generate a normalized Moffat profile from its FWHM and alpha | [
"Generate",
"a",
"normalized",
"Moffat",
"profile",
"from",
"its",
"FWHM",
"and",
"alpha"
] | 6c829495df8937f77c2de9383c1038ffb3e713e3 | https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/instrument/simulation/atmosphere.py#L78-L89 | train |
druids/django-chamber | chamber/models/__init__.py | field_to_dict | def field_to_dict(field, instance):
"""
Converts a model field to a dictionary
"""
# avoid a circular import
from django.db.models.fields.related import ManyToManyField
return (many_to_many_field_to_dict(field, instance) if isinstance(field, ManyToManyField)
else field.value_from_ob... | python | def field_to_dict(field, instance):
"""
Converts a model field to a dictionary
"""
# avoid a circular import
from django.db.models.fields.related import ManyToManyField
return (many_to_many_field_to_dict(field, instance) if isinstance(field, ManyToManyField)
else field.value_from_ob... | [
"def",
"field_to_dict",
"(",
"field",
",",
"instance",
")",
":",
"# avoid a circular import",
"from",
"django",
".",
"db",
".",
"models",
".",
"fields",
".",
"related",
"import",
"ManyToManyField",
"return",
"(",
"many_to_many_field_to_dict",
"(",
"field",
",",
... | Converts a model field to a dictionary | [
"Converts",
"a",
"model",
"field",
"to",
"a",
"dictionary"
] | eef4169923557e96877a664fa254e8c0814f3f23 | https://github.com/druids/django-chamber/blob/eef4169923557e96877a664fa254e8c0814f3f23/chamber/models/__init__.py#L37-L45 | train |
druids/django-chamber | chamber/models/__init__.py | model_to_dict | def model_to_dict(instance, fields=None, exclude=None):
"""
The same implementation as django model_to_dict but editable fields are allowed
"""
return {
field.name: field_to_dict(field, instance)
for field in chain(instance._meta.concrete_fields, instance._meta.many_to_many) # pylint: ... | python | def model_to_dict(instance, fields=None, exclude=None):
"""
The same implementation as django model_to_dict but editable fields are allowed
"""
return {
field.name: field_to_dict(field, instance)
for field in chain(instance._meta.concrete_fields, instance._meta.many_to_many) # pylint: ... | [
"def",
"model_to_dict",
"(",
"instance",
",",
"fields",
"=",
"None",
",",
"exclude",
"=",
"None",
")",
":",
"return",
"{",
"field",
".",
"name",
":",
"field_to_dict",
"(",
"field",
",",
"instance",
")",
"for",
"field",
"in",
"chain",
"(",
"instance",
"... | The same implementation as django model_to_dict but editable fields are allowed | [
"The",
"same",
"implementation",
"as",
"django",
"model_to_dict",
"but",
"editable",
"fields",
"are",
"allowed"
] | eef4169923557e96877a664fa254e8c0814f3f23 | https://github.com/druids/django-chamber/blob/eef4169923557e96877a664fa254e8c0814f3f23/chamber/models/__init__.py#L70-L79 | train |
druids/django-chamber | chamber/models/__init__.py | SmartQuerySet.change_and_save | def change_and_save(self, update_only_changed_fields=False, **changed_fields):
"""
Changes a given `changed_fields` on each object in the queryset, saves objects
and returns the changed objects in the queryset.
"""
bulk_change_and_save(self, update_only_changed_fields=update_only... | python | def change_and_save(self, update_only_changed_fields=False, **changed_fields):
"""
Changes a given `changed_fields` on each object in the queryset, saves objects
and returns the changed objects in the queryset.
"""
bulk_change_and_save(self, update_only_changed_fields=update_only... | [
"def",
"change_and_save",
"(",
"self",
",",
"update_only_changed_fields",
"=",
"False",
",",
"*",
"*",
"changed_fields",
")",
":",
"bulk_change_and_save",
"(",
"self",
",",
"update_only_changed_fields",
"=",
"update_only_changed_fields",
",",
"*",
"*",
"changed_fields... | Changes a given `changed_fields` on each object in the queryset, saves objects
and returns the changed objects in the queryset. | [
"Changes",
"a",
"given",
"changed_fields",
"on",
"each",
"object",
"in",
"the",
"queryset",
"saves",
"objects",
"and",
"returns",
"the",
"changed",
"objects",
"in",
"the",
"queryset",
"."
] | eef4169923557e96877a664fa254e8c0814f3f23 | https://github.com/druids/django-chamber/blob/eef4169923557e96877a664fa254e8c0814f3f23/chamber/models/__init__.py#L258-L264 | train |
guaix-ucm/numina | numina/array/bbox.py | BoundingBox.extent | def extent(self):
"""Helper for matplotlib imshow"""
return (
self.intervals[1].pix1 - 0.5,
self.intervals[1].pix2 - 0.5,
self.intervals[0].pix1 - 0.5,
self.intervals[0].pix2 - 0.5,
) | python | def extent(self):
"""Helper for matplotlib imshow"""
return (
self.intervals[1].pix1 - 0.5,
self.intervals[1].pix2 - 0.5,
self.intervals[0].pix1 - 0.5,
self.intervals[0].pix2 - 0.5,
) | [
"def",
"extent",
"(",
"self",
")",
":",
"return",
"(",
"self",
".",
"intervals",
"[",
"1",
"]",
".",
"pix1",
"-",
"0.5",
",",
"self",
".",
"intervals",
"[",
"1",
"]",
".",
"pix2",
"-",
"0.5",
",",
"self",
".",
"intervals",
"[",
"0",
"]",
".",
... | Helper for matplotlib imshow | [
"Helper",
"for",
"matplotlib",
"imshow"
] | 6c829495df8937f77c2de9383c1038ffb3e713e3 | https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/array/bbox.py#L214-L221 | train |
guaix-ucm/numina | numina/instrument/components/detector.py | DetectorBase.readout | def readout(self):
"""Readout the detector."""
elec = self.simulate_poisson_variate()
elec_pre = self.saturate(elec)
elec_f = self.pre_readout(elec_pre)
adu_r = self.base_readout(elec_f)
adu_p = self.post_readout(adu_r)
self.clean_up()
return adu_p | python | def readout(self):
"""Readout the detector."""
elec = self.simulate_poisson_variate()
elec_pre = self.saturate(elec)
elec_f = self.pre_readout(elec_pre)
adu_r = self.base_readout(elec_f)
adu_p = self.post_readout(adu_r)
self.clean_up()
return adu_p | [
"def",
"readout",
"(",
"self",
")",
":",
"elec",
"=",
"self",
".",
"simulate_poisson_variate",
"(",
")",
"elec_pre",
"=",
"self",
".",
"saturate",
"(",
"elec",
")",
"elec_f",
"=",
"self",
".",
"pre_readout",
"(",
"elec_pre",
")",
"adu_r",
"=",
"self",
... | Readout the detector. | [
"Readout",
"the",
"detector",
"."
] | 6c829495df8937f77c2de9383c1038ffb3e713e3 | https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/instrument/components/detector.py#L94-L109 | train |
guaix-ucm/numina | numina/util/parser.py | parse_arg_line | def parse_arg_line(fargs):
"""parse limited form of arguments of function
in the form a=1, b='c'
as a dictionary
"""
# Convert to literal dict
fargs = fargs.strip()
if fargs == '':
return {}
pairs = [s.strip() for s in fargs.split(',')]
# find first "="
result = []
... | python | def parse_arg_line(fargs):
"""parse limited form of arguments of function
in the form a=1, b='c'
as a dictionary
"""
# Convert to literal dict
fargs = fargs.strip()
if fargs == '':
return {}
pairs = [s.strip() for s in fargs.split(',')]
# find first "="
result = []
... | [
"def",
"parse_arg_line",
"(",
"fargs",
")",
":",
"# Convert to literal dict",
"fargs",
"=",
"fargs",
".",
"strip",
"(",
")",
"if",
"fargs",
"==",
"''",
":",
"return",
"{",
"}",
"pairs",
"=",
"[",
"s",
".",
"strip",
"(",
")",
"for",
"s",
"in",
"fargs"... | parse limited form of arguments of function
in the form a=1, b='c'
as a dictionary | [
"parse",
"limited",
"form",
"of",
"arguments",
"of",
"function"
] | 6c829495df8937f77c2de9383c1038ffb3e713e3 | https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/util/parser.py#L27-L54 | train |
druids/django-chamber | chamber/formatters/__init__.py | natural_number_with_currency | def natural_number_with_currency(number, currency, show_decimal_place=True, use_nbsp=True):
"""
Return a given `number` formatter a price for humans.
"""
humanized = '{} {}'.format(
numberformat.format(
number=number,
decimal_sep=',',
decimal_pos=2 if show_dec... | python | def natural_number_with_currency(number, currency, show_decimal_place=True, use_nbsp=True):
"""
Return a given `number` formatter a price for humans.
"""
humanized = '{} {}'.format(
numberformat.format(
number=number,
decimal_sep=',',
decimal_pos=2 if show_dec... | [
"def",
"natural_number_with_currency",
"(",
"number",
",",
"currency",
",",
"show_decimal_place",
"=",
"True",
",",
"use_nbsp",
"=",
"True",
")",
":",
"humanized",
"=",
"'{} {}'",
".",
"format",
"(",
"numberformat",
".",
"format",
"(",
"number",
"=",
"number",... | Return a given `number` formatter a price for humans. | [
"Return",
"a",
"given",
"number",
"formatter",
"a",
"price",
"for",
"humans",
"."
] | eef4169923557e96877a664fa254e8c0814f3f23 | https://github.com/druids/django-chamber/blob/eef4169923557e96877a664fa254e8c0814f3f23/chamber/formatters/__init__.py#L6-L21 | train |
guaix-ucm/numina | numina/types/frame.py | DataFrameType.extract_db_info | def extract_db_info(self, obj, keys):
"""Extract tags from serialized file"""
objl = self.convert(obj)
result = super(DataFrameType, self).extract_db_info(objl, keys)
ext = self.datamodel.extractor_map['fits']
if objl:
with objl.open() as hdulist:
fo... | python | def extract_db_info(self, obj, keys):
"""Extract tags from serialized file"""
objl = self.convert(obj)
result = super(DataFrameType, self).extract_db_info(objl, keys)
ext = self.datamodel.extractor_map['fits']
if objl:
with objl.open() as hdulist:
fo... | [
"def",
"extract_db_info",
"(",
"self",
",",
"obj",
",",
"keys",
")",
":",
"objl",
"=",
"self",
".",
"convert",
"(",
"obj",
")",
"result",
"=",
"super",
"(",
"DataFrameType",
",",
"self",
")",
".",
"extract_db_info",
"(",
"objl",
",",
"keys",
")",
"ex... | Extract tags from serialized file | [
"Extract",
"tags",
"from",
"serialized",
"file"
] | 6c829495df8937f77c2de9383c1038ffb3e713e3 | https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/types/frame.py#L101-L119 | train |
guaix-ucm/numina | numina/array/display/iofunctions.py | readc | def readc(prompt, default=None, valid=None, question_mark=True):
"""Return a single character read from keyboard
Parameters
----------
prompt : str
Prompt string.
default : str
Default value.
valid : str
String providing valid characters. If None, all characters are
... | python | def readc(prompt, default=None, valid=None, question_mark=True):
"""Return a single character read from keyboard
Parameters
----------
prompt : str
Prompt string.
default : str
Default value.
valid : str
String providing valid characters. If None, all characters are
... | [
"def",
"readc",
"(",
"prompt",
",",
"default",
"=",
"None",
",",
"valid",
"=",
"None",
",",
"question_mark",
"=",
"True",
")",
":",
"cresult",
"=",
"None",
"# Avoid PyCharm warning",
"# question mark",
"if",
"question_mark",
":",
"cquestion_mark",
"=",
"' ? '"... | Return a single character read from keyboard
Parameters
----------
prompt : str
Prompt string.
default : str
Default value.
valid : str
String providing valid characters. If None, all characters are
valid (default).
question_mark : bool
If True, display q... | [
"Return",
"a",
"single",
"character",
"read",
"from",
"keyboard"
] | 6c829495df8937f77c2de9383c1038ffb3e713e3 | https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/array/display/iofunctions.py#L7-L67 | train |
guaix-ucm/numina | numina/array/display/iofunctions.py | read_value | def read_value(ftype, prompt, default=None, minval=None, maxval=None,
allowed_single_chars=None, question_mark=True):
"""Return value read from keyboard
Parameters
----------
ftype : int() or float()
Function defining the expected type.
prompt : str
Prompt string.
... | python | def read_value(ftype, prompt, default=None, minval=None, maxval=None,
allowed_single_chars=None, question_mark=True):
"""Return value read from keyboard
Parameters
----------
ftype : int() or float()
Function defining the expected type.
prompt : str
Prompt string.
... | [
"def",
"read_value",
"(",
"ftype",
",",
"prompt",
",",
"default",
"=",
"None",
",",
"minval",
"=",
"None",
",",
"maxval",
"=",
"None",
",",
"allowed_single_chars",
"=",
"None",
",",
"question_mark",
"=",
"True",
")",
":",
"# avoid PyCharm warning 'might be ref... | Return value read from keyboard
Parameters
----------
ftype : int() or float()
Function defining the expected type.
prompt : str
Prompt string.
default : int or None
Default value.
minval : int or None
Mininum allowed value.
maxval : int or None
Maxim... | [
"Return",
"value",
"read",
"from",
"keyboard"
] | 6c829495df8937f77c2de9383c1038ffb3e713e3 | https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/array/display/iofunctions.py#L140-L256 | train |
guaix-ucm/numina | numina/core/pipeline.py | Pipeline.load_product_object | def load_product_object(self, name):
"""Load product object, according to name"""
product_entry = self.products[name]
product = self._get_base_object(product_entry)
return product | python | def load_product_object(self, name):
"""Load product object, according to name"""
product_entry = self.products[name]
product = self._get_base_object(product_entry)
return product | [
"def",
"load_product_object",
"(",
"self",
",",
"name",
")",
":",
"product_entry",
"=",
"self",
".",
"products",
"[",
"name",
"]",
"product",
"=",
"self",
".",
"_get_base_object",
"(",
"product_entry",
")",
"return",
"product"
] | Load product object, according to name | [
"Load",
"product",
"object",
"according",
"to",
"name"
] | 6c829495df8937f77c2de9383c1038ffb3e713e3 | https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/core/pipeline.py#L87-L94 | train |
guaix-ucm/numina | numina/core/pipeline.py | Pipeline.depsolve | def depsolve(self):
"""Load all recipes to search for products"""
# load everything
requires = {}
provides = {}
for mode, r in self.recipes.items():
l = self.load_recipe_object(mode)
for field, vv in l.requirements().items():
if vv.type.is... | python | def depsolve(self):
"""Load all recipes to search for products"""
# load everything
requires = {}
provides = {}
for mode, r in self.recipes.items():
l = self.load_recipe_object(mode)
for field, vv in l.requirements().items():
if vv.type.is... | [
"def",
"depsolve",
"(",
"self",
")",
":",
"# load everything",
"requires",
"=",
"{",
"}",
"provides",
"=",
"{",
"}",
"for",
"mode",
",",
"r",
"in",
"self",
".",
"recipes",
".",
"items",
"(",
")",
":",
"l",
"=",
"self",
".",
"load_recipe_object",
"(",... | Load all recipes to search for products | [
"Load",
"all",
"recipes",
"to",
"search",
"for",
"products"
] | 6c829495df8937f77c2de9383c1038ffb3e713e3 | https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/core/pipeline.py#L109-L129 | train |
guaix-ucm/numina | numina/core/pipeline.py | InstrumentDRP.search_mode_provides | def search_mode_provides(self, product, pipeline='default'):
"""Search the mode that provides a given product"""
pipeline = self.pipelines[pipeline]
for obj, mode, field in self.iterate_mode_provides(self.modes, pipeline):
# extract name from obj
if obj.name() == product... | python | def search_mode_provides(self, product, pipeline='default'):
"""Search the mode that provides a given product"""
pipeline = self.pipelines[pipeline]
for obj, mode, field in self.iterate_mode_provides(self.modes, pipeline):
# extract name from obj
if obj.name() == product... | [
"def",
"search_mode_provides",
"(",
"self",
",",
"product",
",",
"pipeline",
"=",
"'default'",
")",
":",
"pipeline",
"=",
"self",
".",
"pipelines",
"[",
"pipeline",
"]",
"for",
"obj",
",",
"mode",
",",
"field",
"in",
"self",
".",
"iterate_mode_provides",
"... | Search the mode that provides a given product | [
"Search",
"the",
"mode",
"that",
"provides",
"a",
"given",
"product"
] | 6c829495df8937f77c2de9383c1038ffb3e713e3 | https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/core/pipeline.py#L220-L229 | train |
guaix-ucm/numina | numina/core/pipeline.py | InstrumentDRP.select_configuration | def select_configuration(self, obresult):
"""Select instrument configuration based on OB"""
logger = logging.getLogger(__name__)
logger.debug('calling default configuration selector')
# get first possible image
ref = obresult.get_sample_frame()
extr = self.datamodel.ext... | python | def select_configuration(self, obresult):
"""Select instrument configuration based on OB"""
logger = logging.getLogger(__name__)
logger.debug('calling default configuration selector')
# get first possible image
ref = obresult.get_sample_frame()
extr = self.datamodel.ext... | [
"def",
"select_configuration",
"(",
"self",
",",
"obresult",
")",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
"logger",
".",
"debug",
"(",
"'calling default configuration selector'",
")",
"# get first possible image",
"ref",
"=",
"obresult... | Select instrument configuration based on OB | [
"Select",
"instrument",
"configuration",
"based",
"on",
"OB"
] | 6c829495df8937f77c2de9383c1038ffb3e713e3 | https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/core/pipeline.py#L251-L292 | train |
guaix-ucm/numina | numina/core/pipeline.py | InstrumentDRP.select_profile | def select_profile(self, obresult):
"""Select instrument profile based on OB"""
logger = logging.getLogger(__name__)
logger.debug('calling default profile selector')
# check configuration
insconf = obresult.configuration
if insconf != 'default':
key = insconf... | python | def select_profile(self, obresult):
"""Select instrument profile based on OB"""
logger = logging.getLogger(__name__)
logger.debug('calling default profile selector')
# check configuration
insconf = obresult.configuration
if insconf != 'default':
key = insconf... | [
"def",
"select_profile",
"(",
"self",
",",
"obresult",
")",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
"logger",
".",
"debug",
"(",
"'calling default profile selector'",
")",
"# check configuration",
"insconf",
"=",
"obresult",
".",
"... | Select instrument profile based on OB | [
"Select",
"instrument",
"profile",
"based",
"on",
"OB"
] | 6c829495df8937f77c2de9383c1038ffb3e713e3 | https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/core/pipeline.py#L294-L323 | train |
guaix-ucm/numina | numina/core/pipeline.py | InstrumentDRP.get_recipe_object | def get_recipe_object(self, mode_name, pipeline_name='default'):
"""Build a recipe object from a given mode name"""
active_mode = self.modes[mode_name]
active_pipeline = self.pipelines[pipeline_name]
recipe = active_pipeline.get_recipe_object(active_mode)
return recipe | python | def get_recipe_object(self, mode_name, pipeline_name='default'):
"""Build a recipe object from a given mode name"""
active_mode = self.modes[mode_name]
active_pipeline = self.pipelines[pipeline_name]
recipe = active_pipeline.get_recipe_object(active_mode)
return recipe | [
"def",
"get_recipe_object",
"(",
"self",
",",
"mode_name",
",",
"pipeline_name",
"=",
"'default'",
")",
":",
"active_mode",
"=",
"self",
".",
"modes",
"[",
"mode_name",
"]",
"active_pipeline",
"=",
"self",
".",
"pipelines",
"[",
"pipeline_name",
"]",
"recipe",... | Build a recipe object from a given mode name | [
"Build",
"a",
"recipe",
"object",
"from",
"a",
"given",
"mode",
"name"
] | 6c829495df8937f77c2de9383c1038ffb3e713e3 | https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/core/pipeline.py#L325-L330 | train |
guaix-ucm/numina | numina/array/display/pause_debugplot.py | pause_debugplot | def pause_debugplot(debugplot, optional_prompt=None, pltshow=False,
tight_layout=True):
"""Ask the user to press RETURN to continue after plotting.
Parameters
----------
debugplot : int
Determines whether intermediate computations and/or plots
are displayed:
... | python | def pause_debugplot(debugplot, optional_prompt=None, pltshow=False,
tight_layout=True):
"""Ask the user to press RETURN to continue after plotting.
Parameters
----------
debugplot : int
Determines whether intermediate computations and/or plots
are displayed:
... | [
"def",
"pause_debugplot",
"(",
"debugplot",
",",
"optional_prompt",
"=",
"None",
",",
"pltshow",
"=",
"False",
",",
"tight_layout",
"=",
"True",
")",
":",
"if",
"debugplot",
"not",
"in",
"DEBUGPLOT_CODES",
":",
"raise",
"ValueError",
"(",
"'Invalid debugplot val... | Ask the user to press RETURN to continue after plotting.
Parameters
----------
debugplot : int
Determines whether intermediate computations and/or plots
are displayed:
00 : no debug, no plots
01 : no debug, plots without pauses
02 : no debug, plots with pauses
... | [
"Ask",
"the",
"user",
"to",
"press",
"RETURN",
"to",
"continue",
"after",
"plotting",
"."
] | 6c829495df8937f77c2de9383c1038ffb3e713e3 | https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/array/display/pause_debugplot.py#L21-L82 | train |
guaix-ucm/numina | numina/array/mode.py | mode_half_sample | def mode_half_sample(a, is_sorted=False):
'''
Estimate the mode using the Half Sample mode.
A method to estimate the mode, as described in
D. R. Bickel and R. Frühwirth (contributed equally),
"On a fast, robust estimator of the mode: Comparisons to other
robust estimators with applications,"
... | python | def mode_half_sample(a, is_sorted=False):
'''
Estimate the mode using the Half Sample mode.
A method to estimate the mode, as described in
D. R. Bickel and R. Frühwirth (contributed equally),
"On a fast, robust estimator of the mode: Comparisons to other
robust estimators with applications,"
... | [
"def",
"mode_half_sample",
"(",
"a",
",",
"is_sorted",
"=",
"False",
")",
":",
"a",
"=",
"np",
".",
"asanyarray",
"(",
"a",
")",
"if",
"not",
"is_sorted",
":",
"sdata",
"=",
"np",
".",
"sort",
"(",
"a",
")",
"else",
":",
"sdata",
"=",
"a",
"n",
... | Estimate the mode using the Half Sample mode.
A method to estimate the mode, as described in
D. R. Bickel and R. Frühwirth (contributed equally),
"On a fast, robust estimator of the mode: Comparisons to other
robust estimators with applications,"
Computational Statistics and Data Analysis 50, 3500-... | [
"Estimate",
"the",
"mode",
"using",
"the",
"Half",
"Sample",
"mode",
"."
] | 6c829495df8937f77c2de9383c1038ffb3e713e3 | https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/array/mode.py#L21-L69 | train |
guaix-ucm/numina | numina/array/display/overplot_ds9reg.py | overplot_ds9reg | def overplot_ds9reg(filename, ax):
"""Overplot a ds9 region file.
Parameters
----------
filename : str
File name of the ds9 region file.
ax : matplotlib axes instance
Matplotlib axes instance.
"""
# read ds9 region file
with open(filename) as f:
file_content = ... | python | def overplot_ds9reg(filename, ax):
"""Overplot a ds9 region file.
Parameters
----------
filename : str
File name of the ds9 region file.
ax : matplotlib axes instance
Matplotlib axes instance.
"""
# read ds9 region file
with open(filename) as f:
file_content = ... | [
"def",
"overplot_ds9reg",
"(",
"filename",
",",
"ax",
")",
":",
"# read ds9 region file",
"with",
"open",
"(",
"filename",
")",
"as",
"f",
":",
"file_content",
"=",
"f",
".",
"read",
"(",
")",
".",
"splitlines",
"(",
")",
"# check first line",
"first_line",
... | Overplot a ds9 region file.
Parameters
----------
filename : str
File name of the ds9 region file.
ax : matplotlib axes instance
Matplotlib axes instance. | [
"Overplot",
"a",
"ds9",
"region",
"file",
"."
] | 6c829495df8937f77c2de9383c1038ffb3e713e3 | https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/array/display/overplot_ds9reg.py#L14-L64 | train |
guaix-ucm/numina | numina/array/peaks/peakdet.py | find_peaks_indexes | def find_peaks_indexes(arr, window_width=5, threshold=0.0, fpeak=0):
"""Find indexes of peaks in a 1d array.
Note that window_width must be an odd number. The function imposes that the
fluxes in the window_width /2 points to the left (and right) of the peak
decrease monotonously as one moves away from ... | python | def find_peaks_indexes(arr, window_width=5, threshold=0.0, fpeak=0):
"""Find indexes of peaks in a 1d array.
Note that window_width must be an odd number. The function imposes that the
fluxes in the window_width /2 points to the left (and right) of the peak
decrease monotonously as one moves away from ... | [
"def",
"find_peaks_indexes",
"(",
"arr",
",",
"window_width",
"=",
"5",
",",
"threshold",
"=",
"0.0",
",",
"fpeak",
"=",
"0",
")",
":",
"_check_window_width",
"(",
"window_width",
")",
"if",
"(",
"fpeak",
"<",
"0",
"or",
"fpeak",
"+",
"1",
">=",
"windo... | Find indexes of peaks in a 1d array.
Note that window_width must be an odd number. The function imposes that the
fluxes in the window_width /2 points to the left (and right) of the peak
decrease monotonously as one moves away from the peak, except that
it allows fpeak constant values around the peak.
... | [
"Find",
"indexes",
"of",
"peaks",
"in",
"a",
"1d",
"array",
"."
] | 6c829495df8937f77c2de9383c1038ffb3e713e3 | https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/array/peaks/peakdet.py#L61-L98 | train |
guaix-ucm/numina | numina/array/peaks/peakdet.py | refine_peaks | def refine_peaks(arr, ipeaks, window_width):
"""Refine the peak location previously found by find_peaks_indexes
Parameters
----------
arr : 1d numpy array, float
Input 1D spectrum.
ipeaks : 1d numpy array (int)
Indices of the input array arr in which the peaks were initially found.
... | python | def refine_peaks(arr, ipeaks, window_width):
"""Refine the peak location previously found by find_peaks_indexes
Parameters
----------
arr : 1d numpy array, float
Input 1D spectrum.
ipeaks : 1d numpy array (int)
Indices of the input array arr in which the peaks were initially found.
... | [
"def",
"refine_peaks",
"(",
"arr",
",",
"ipeaks",
",",
"window_width",
")",
":",
"_check_window_width",
"(",
"window_width",
")",
"step",
"=",
"window_width",
"//",
"2",
"ipeaks",
"=",
"filter_array_margins",
"(",
"arr",
",",
"ipeaks",
",",
"window_width",
")"... | Refine the peak location previously found by find_peaks_indexes
Parameters
----------
arr : 1d numpy array, float
Input 1D spectrum.
ipeaks : 1d numpy array (int)
Indices of the input array arr in which the peaks were initially found.
window_width : int
Width of the window w... | [
"Refine",
"the",
"peak",
"location",
"previously",
"found",
"by",
"find_peaks_indexes"
] | 6c829495df8937f77c2de9383c1038ffb3e713e3 | https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/array/peaks/peakdet.py#L137-L174 | train |
guaix-ucm/numina | numina/user/clirun.py | complete_config | def complete_config(config):
"""Complete config with default values"""
if not config.has_section('run'):
config.add_section('run')
values = {
'basedir': os.getcwd(),
'task_control': 'control.yaml',
}
for k, v in values.items():
if not config.has_option('run', k):
... | python | def complete_config(config):
"""Complete config with default values"""
if not config.has_section('run'):
config.add_section('run')
values = {
'basedir': os.getcwd(),
'task_control': 'control.yaml',
}
for k, v in values.items():
if not config.has_option('run', k):
... | [
"def",
"complete_config",
"(",
"config",
")",
":",
"if",
"not",
"config",
".",
"has_section",
"(",
"'run'",
")",
":",
"config",
".",
"add_section",
"(",
"'run'",
")",
"values",
"=",
"{",
"'basedir'",
":",
"os",
".",
"getcwd",
"(",
")",
",",
"'task_cont... | Complete config with default values | [
"Complete",
"config",
"with",
"default",
"values"
] | 6c829495df8937f77c2de9383c1038ffb3e713e3 | https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/user/clirun.py#L17-L32 | train |
guaix-ucm/numina | numina/array/recenter.py | centering_centroid | def centering_centroid(data, xi, yi, box, nloop=10, toldist=1e-3,
maxdist=10.0):
'''
returns x, y, background, status, message
status is:
* 0: not recentering
* 1: recentering successful
* 2: maximum distance reached
* 3: not converged
... | python | def centering_centroid(data, xi, yi, box, nloop=10, toldist=1e-3,
maxdist=10.0):
'''
returns x, y, background, status, message
status is:
* 0: not recentering
* 1: recentering successful
* 2: maximum distance reached
* 3: not converged
... | [
"def",
"centering_centroid",
"(",
"data",
",",
"xi",
",",
"yi",
",",
"box",
",",
"nloop",
"=",
"10",
",",
"toldist",
"=",
"1e-3",
",",
"maxdist",
"=",
"10.0",
")",
":",
"# Store original center",
"cxy",
"=",
"(",
"xi",
",",
"yi",
")",
"origin",
"=",
... | returns x, y, background, status, message
status is:
* 0: not recentering
* 1: recentering successful
* 2: maximum distance reached
* 3: not converged | [
"returns",
"x",
"y",
"background",
"status",
"message"
] | 6c829495df8937f77c2de9383c1038ffb3e713e3 | https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/array/recenter.py#L57-L94 | train |
twiebe/Flask-CacheControl | src/flask_cachecontrol/cache.py | cache_for | def cache_for(**timedelta_kw):
"""
Set Cache-Control headers and Expires-header.
Expects a timedelta instance.
"""
max_age_timedelta = timedelta(**timedelta_kw)
def decorate_func(func):
@wraps(func)
def decorate_func_call(*a, **kw):
callback = SetCacheControlHeaders... | python | def cache_for(**timedelta_kw):
"""
Set Cache-Control headers and Expires-header.
Expects a timedelta instance.
"""
max_age_timedelta = timedelta(**timedelta_kw)
def decorate_func(func):
@wraps(func)
def decorate_func_call(*a, **kw):
callback = SetCacheControlHeaders... | [
"def",
"cache_for",
"(",
"*",
"*",
"timedelta_kw",
")",
":",
"max_age_timedelta",
"=",
"timedelta",
"(",
"*",
"*",
"timedelta_kw",
")",
"def",
"decorate_func",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"decorate_func_call",
"(",
"*",
... | Set Cache-Control headers and Expires-header.
Expects a timedelta instance. | [
"Set",
"Cache",
"-",
"Control",
"headers",
"and",
"Expires",
"-",
"header",
"."
] | 8376156fafe3358b5a1201d348afb12994172962 | https://github.com/twiebe/Flask-CacheControl/blob/8376156fafe3358b5a1201d348afb12994172962/src/flask_cachecontrol/cache.py#L20-L37 | train |
twiebe/Flask-CacheControl | src/flask_cachecontrol/cache.py | cache | def cache(*cache_control_items, **cache_control_kw):
"""
Set Cache-Control headers.
Expects keyword arguments and/or an item list.
Each pair is used to set Flask Response.cache_control attributes,
where the key is the attribute name and the value is its value.
Use True as value for attributes... | python | def cache(*cache_control_items, **cache_control_kw):
"""
Set Cache-Control headers.
Expects keyword arguments and/or an item list.
Each pair is used to set Flask Response.cache_control attributes,
where the key is the attribute name and the value is its value.
Use True as value for attributes... | [
"def",
"cache",
"(",
"*",
"cache_control_items",
",",
"*",
"*",
"cache_control_kw",
")",
":",
"cache_control_kw",
".",
"update",
"(",
"cache_control_items",
")",
"def",
"decorate_func",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"decorate_... | Set Cache-Control headers.
Expects keyword arguments and/or an item list.
Each pair is used to set Flask Response.cache_control attributes,
where the key is the attribute name and the value is its value.
Use True as value for attributes without values.
In case of an invalid attribute, CacheContr... | [
"Set",
"Cache",
"-",
"Control",
"headers",
"."
] | 8376156fafe3358b5a1201d348afb12994172962 | https://github.com/twiebe/Flask-CacheControl/blob/8376156fafe3358b5a1201d348afb12994172962/src/flask_cachecontrol/cache.py#L41-L66 | train |
twiebe/Flask-CacheControl | src/flask_cachecontrol/cache.py | dont_cache | def dont_cache():
"""
Set Cache-Control headers for no caching
Will generate proxy-revalidate, no-cache, no-store, must-revalidate,
max-age=0.
"""
def decorate_func(func):
@wraps(func)
def decorate_func_call(*a, **kw):
callback = SetCacheControlHeadersForNoCachingCal... | python | def dont_cache():
"""
Set Cache-Control headers for no caching
Will generate proxy-revalidate, no-cache, no-store, must-revalidate,
max-age=0.
"""
def decorate_func(func):
@wraps(func)
def decorate_func_call(*a, **kw):
callback = SetCacheControlHeadersForNoCachingCal... | [
"def",
"dont_cache",
"(",
")",
":",
"def",
"decorate_func",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"decorate_func_call",
"(",
"*",
"a",
",",
"*",
"*",
"kw",
")",
":",
"callback",
"=",
"SetCacheControlHeadersForNoCachingCallback",
"("... | Set Cache-Control headers for no caching
Will generate proxy-revalidate, no-cache, no-store, must-revalidate,
max-age=0. | [
"Set",
"Cache",
"-",
"Control",
"headers",
"for",
"no",
"caching"
] | 8376156fafe3358b5a1201d348afb12994172962 | https://github.com/twiebe/Flask-CacheControl/blob/8376156fafe3358b5a1201d348afb12994172962/src/flask_cachecontrol/cache.py#L70-L86 | train |
inspirehep/inspire-schemas | inspire_schemas/utils.py | filter_empty_parameters | def filter_empty_parameters(func):
"""Decorator that is filtering empty parameters.
:param func: function that you want wrapping
:type func: function
"""
@wraps(func)
def func_wrapper(self, *args, **kwargs):
my_kwargs = {key: value for key, value in kwargs.items()
i... | python | def filter_empty_parameters(func):
"""Decorator that is filtering empty parameters.
:param func: function that you want wrapping
:type func: function
"""
@wraps(func)
def func_wrapper(self, *args, **kwargs):
my_kwargs = {key: value for key, value in kwargs.items()
i... | [
"def",
"filter_empty_parameters",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"func_wrapper",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"my_kwargs",
"=",
"{",
"key",
":",
"value",
"for",
"key",
",",
"value",
... | Decorator that is filtering empty parameters.
:param func: function that you want wrapping
:type func: function | [
"Decorator",
"that",
"is",
"filtering",
"empty",
"parameters",
"."
] | 34bc124b62fba565b6b40d1a3c15103a23a05edb | https://github.com/inspirehep/inspire-schemas/blob/34bc124b62fba565b6b40d1a3c15103a23a05edb/inspire_schemas/utils.py#L330-L348 | train |
inspirehep/inspire-schemas | inspire_schemas/utils.py | author_id_normalize_and_schema | def author_id_normalize_and_schema(uid, schema=None):
"""Detect and normalize an author UID schema.
Args:
uid (string): a UID string
schema (string): try to resolve to schema
Returns:
Tuple[string, string]: a tuple (uid, schema) where:
- uid: the UID normalized to comply wi... | python | def author_id_normalize_and_schema(uid, schema=None):
"""Detect and normalize an author UID schema.
Args:
uid (string): a UID string
schema (string): try to resolve to schema
Returns:
Tuple[string, string]: a tuple (uid, schema) where:
- uid: the UID normalized to comply wi... | [
"def",
"author_id_normalize_and_schema",
"(",
"uid",
",",
"schema",
"=",
"None",
")",
":",
"def",
"_get_uid_normalized_in_schema",
"(",
"_uid",
",",
"_schema",
")",
":",
"regex",
",",
"template",
"=",
"_RE_AUTHORS_UID",
"[",
"_schema",
"]",
"match",
"=",
"rege... | Detect and normalize an author UID schema.
Args:
uid (string): a UID string
schema (string): try to resolve to schema
Returns:
Tuple[string, string]: a tuple (uid, schema) where:
- uid: the UID normalized to comply with the id.json schema
- schema: a schema of the UID o... | [
"Detect",
"and",
"normalize",
"an",
"author",
"UID",
"schema",
"."
] | 34bc124b62fba565b6b40d1a3c15103a23a05edb | https://github.com/inspirehep/inspire-schemas/blob/34bc124b62fba565b6b40d1a3c15103a23a05edb/inspire_schemas/utils.py#L351-L401 | train |
inspirehep/inspire-schemas | inspire_schemas/utils.py | normalize_arxiv_category | def normalize_arxiv_category(category):
"""Normalize arXiv category to be schema compliant.
This properly capitalizes the category and replaces the dash by a dot if
needed. If the category is obsolete, it also gets converted it to its
current equivalent.
Example:
>>> from inspire_schemas.u... | python | def normalize_arxiv_category(category):
"""Normalize arXiv category to be schema compliant.
This properly capitalizes the category and replaces the dash by a dot if
needed. If the category is obsolete, it also gets converted it to its
current equivalent.
Example:
>>> from inspire_schemas.u... | [
"def",
"normalize_arxiv_category",
"(",
"category",
")",
":",
"category",
"=",
"_NEW_CATEGORIES",
".",
"get",
"(",
"category",
".",
"lower",
"(",
")",
",",
"category",
")",
"for",
"valid_category",
"in",
"valid_arxiv_categories",
"(",
")",
":",
"if",
"(",
"c... | Normalize arXiv category to be schema compliant.
This properly capitalizes the category and replaces the dash by a dot if
needed. If the category is obsolete, it also gets converted it to its
current equivalent.
Example:
>>> from inspire_schemas.utils import normalize_arxiv_category
>>... | [
"Normalize",
"arXiv",
"category",
"to",
"be",
"schema",
"compliant",
"."
] | 34bc124b62fba565b6b40d1a3c15103a23a05edb | https://github.com/inspirehep/inspire-schemas/blob/34bc124b62fba565b6b40d1a3c15103a23a05edb/inspire_schemas/utils.py#L404-L422 | train |
inspirehep/inspire-schemas | inspire_schemas/utils.py | valid_arxiv_categories | def valid_arxiv_categories():
"""List of all arXiv categories that ever existed.
Example:
>>> from inspire_schemas.utils import valid_arxiv_categories
>>> 'funct-an' in valid_arxiv_categories()
True
"""
schema = load_schema('elements/arxiv_categories')
categories = schema['... | python | def valid_arxiv_categories():
"""List of all arXiv categories that ever existed.
Example:
>>> from inspire_schemas.utils import valid_arxiv_categories
>>> 'funct-an' in valid_arxiv_categories()
True
"""
schema = load_schema('elements/arxiv_categories')
categories = schema['... | [
"def",
"valid_arxiv_categories",
"(",
")",
":",
"schema",
"=",
"load_schema",
"(",
"'elements/arxiv_categories'",
")",
"categories",
"=",
"schema",
"[",
"'enum'",
"]",
"categories",
".",
"extend",
"(",
"_NEW_CATEGORIES",
".",
"keys",
"(",
")",
")",
"return",
"... | List of all arXiv categories that ever existed.
Example:
>>> from inspire_schemas.utils import valid_arxiv_categories
>>> 'funct-an' in valid_arxiv_categories()
True | [
"List",
"of",
"all",
"arXiv",
"categories",
"that",
"ever",
"existed",
"."
] | 34bc124b62fba565b6b40d1a3c15103a23a05edb | https://github.com/inspirehep/inspire-schemas/blob/34bc124b62fba565b6b40d1a3c15103a23a05edb/inspire_schemas/utils.py#L425-L438 | train |
inspirehep/inspire-schemas | inspire_schemas/utils.py | classify_field | def classify_field(value):
"""Normalize ``value`` to an Inspire category.
Args:
value(str): an Inspire category to properly case, or an arXiv category
to translate to the corresponding Inspire category.
Returns:
str: ``None`` if ``value`` is not a non-empty string,
... | python | def classify_field(value):
"""Normalize ``value`` to an Inspire category.
Args:
value(str): an Inspire category to properly case, or an arXiv category
to translate to the corresponding Inspire category.
Returns:
str: ``None`` if ``value`` is not a non-empty string,
... | [
"def",
"classify_field",
"(",
"value",
")",
":",
"if",
"not",
"(",
"isinstance",
"(",
"value",
",",
"six",
".",
"string_types",
")",
"and",
"value",
")",
":",
"return",
"schema",
"=",
"load_schema",
"(",
"'elements/inspire_field'",
")",
"inspire_categories",
... | Normalize ``value`` to an Inspire category.
Args:
value(str): an Inspire category to properly case, or an arXiv category
to translate to the corresponding Inspire category.
Returns:
str: ``None`` if ``value`` is not a non-empty string,
otherwise the corresponding Inspir... | [
"Normalize",
"value",
"to",
"an",
"Inspire",
"category",
"."
] | 34bc124b62fba565b6b40d1a3c15103a23a05edb | https://github.com/inspirehep/inspire-schemas/blob/34bc124b62fba565b6b40d1a3c15103a23a05edb/inspire_schemas/utils.py#L441-L464 | train |
inspirehep/inspire-schemas | inspire_schemas/utils.py | split_pubnote | def split_pubnote(pubnote_str):
"""Split pubnote into journal information."""
pubnote = {}
parts = pubnote_str.split(',')
if len(parts) > 2:
pubnote['journal_title'] = parts[0]
pubnote['journal_volume'] = parts[1]
pubnote['page_start'], pubnote['page_end'], pubnote['artid'] = sp... | python | def split_pubnote(pubnote_str):
"""Split pubnote into journal information."""
pubnote = {}
parts = pubnote_str.split(',')
if len(parts) > 2:
pubnote['journal_title'] = parts[0]
pubnote['journal_volume'] = parts[1]
pubnote['page_start'], pubnote['page_end'], pubnote['artid'] = sp... | [
"def",
"split_pubnote",
"(",
"pubnote_str",
")",
":",
"pubnote",
"=",
"{",
"}",
"parts",
"=",
"pubnote_str",
".",
"split",
"(",
"','",
")",
"if",
"len",
"(",
"parts",
")",
">",
"2",
":",
"pubnote",
"[",
"'journal_title'",
"]",
"=",
"parts",
"[",
"0",... | Split pubnote into journal information. | [
"Split",
"pubnote",
"into",
"journal",
"information",
"."
] | 34bc124b62fba565b6b40d1a3c15103a23a05edb | https://github.com/inspirehep/inspire-schemas/blob/34bc124b62fba565b6b40d1a3c15103a23a05edb/inspire_schemas/utils.py#L501-L511 | train |
inspirehep/inspire-schemas | inspire_schemas/utils.py | get_schema_path | def get_schema_path(schema, resolved=False):
"""Retrieve the installed path for the given schema.
Args:
schema(str): relative or absolute url of the schema to validate, for
example, 'records/authors.json' or 'jobs.json', or just the name of the
schema, like 'jobs'.
resol... | python | def get_schema_path(schema, resolved=False):
"""Retrieve the installed path for the given schema.
Args:
schema(str): relative or absolute url of the schema to validate, for
example, 'records/authors.json' or 'jobs.json', or just the name of the
schema, like 'jobs'.
resol... | [
"def",
"get_schema_path",
"(",
"schema",
",",
"resolved",
"=",
"False",
")",
":",
"def",
"_strip_first_path_elem",
"(",
"path",
")",
":",
"\"\"\"Pass doctests.\n\n Strip the first element of the given path, returning an empty string if\n there are no more elements. For ... | Retrieve the installed path for the given schema.
Args:
schema(str): relative or absolute url of the schema to validate, for
example, 'records/authors.json' or 'jobs.json', or just the name of the
schema, like 'jobs'.
resolved(bool): if True, the returned path points to a fu... | [
"Retrieve",
"the",
"installed",
"path",
"for",
"the",
"given",
"schema",
"."
] | 34bc124b62fba565b6b40d1a3c15103a23a05edb | https://github.com/inspirehep/inspire-schemas/blob/34bc124b62fba565b6b40d1a3c15103a23a05edb/inspire_schemas/utils.py#L545-L598 | train |
inspirehep/inspire-schemas | inspire_schemas/utils.py | load_schema | def load_schema(schema_name, resolved=False):
"""Load the given schema from wherever it's installed.
Args:
schema_name(str): Name of the schema to load, for example 'authors'.
resolved(bool): If True will return the resolved schema, that is with
all the $refs replaced by their targe... | python | def load_schema(schema_name, resolved=False):
"""Load the given schema from wherever it's installed.
Args:
schema_name(str): Name of the schema to load, for example 'authors'.
resolved(bool): If True will return the resolved schema, that is with
all the $refs replaced by their targe... | [
"def",
"load_schema",
"(",
"schema_name",
",",
"resolved",
"=",
"False",
")",
":",
"schema_data",
"=",
"''",
"with",
"open",
"(",
"get_schema_path",
"(",
"schema_name",
",",
"resolved",
")",
")",
"as",
"schema_fd",
":",
"schema_data",
"=",
"json",
".",
"lo... | Load the given schema from wherever it's installed.
Args:
schema_name(str): Name of the schema to load, for example 'authors'.
resolved(bool): If True will return the resolved schema, that is with
all the $refs replaced by their targets.
Returns:
dict: the schema with the g... | [
"Load",
"the",
"given",
"schema",
"from",
"wherever",
"it",
"s",
"installed",
"."
] | 34bc124b62fba565b6b40d1a3c15103a23a05edb | https://github.com/inspirehep/inspire-schemas/blob/34bc124b62fba565b6b40d1a3c15103a23a05edb/inspire_schemas/utils.py#L601-L616 | train |
inspirehep/inspire-schemas | inspire_schemas/utils.py | _load_schema_for_record | def _load_schema_for_record(data, schema=None):
"""Load the schema from a given record.
Args:
data (dict): record data.
schema (Union[dict, str]): schema to validate against.
Returns:
dict: the loaded schema.
Raises:
SchemaNotFound: if the given schema was not found.
... | python | def _load_schema_for_record(data, schema=None):
"""Load the schema from a given record.
Args:
data (dict): record data.
schema (Union[dict, str]): schema to validate against.
Returns:
dict: the loaded schema.
Raises:
SchemaNotFound: if the given schema was not found.
... | [
"def",
"_load_schema_for_record",
"(",
"data",
",",
"schema",
"=",
"None",
")",
":",
"if",
"schema",
"is",
"None",
":",
"if",
"'$schema'",
"not",
"in",
"data",
":",
"raise",
"SchemaKeyNotFound",
"(",
"data",
"=",
"data",
")",
"schema",
"=",
"data",
"[",
... | Load the schema from a given record.
Args:
data (dict): record data.
schema (Union[dict, str]): schema to validate against.
Returns:
dict: the loaded schema.
Raises:
SchemaNotFound: if the given schema was not found.
SchemaKeyNotFound: if ``schema`` is ``None`` and... | [
"Load",
"the",
"schema",
"from",
"a",
"given",
"record",
"."
] | 34bc124b62fba565b6b40d1a3c15103a23a05edb | https://github.com/inspirehep/inspire-schemas/blob/34bc124b62fba565b6b40d1a3c15103a23a05edb/inspire_schemas/utils.py#L627-L650 | train |
inspirehep/inspire-schemas | inspire_schemas/utils.py | validate | def validate(data, schema=None):
"""Validate the given dictionary against the given schema.
Args:
data (dict): record to validate.
schema (Union[dict, str]): schema to validate against. If it is a
string, it is intepreted as the name of the schema to load (e.g.
``authors... | python | def validate(data, schema=None):
"""Validate the given dictionary against the given schema.
Args:
data (dict): record to validate.
schema (Union[dict, str]): schema to validate against. If it is a
string, it is intepreted as the name of the schema to load (e.g.
``authors... | [
"def",
"validate",
"(",
"data",
",",
"schema",
"=",
"None",
")",
":",
"schema",
"=",
"_load_schema_for_record",
"(",
"data",
",",
"schema",
")",
"return",
"jsonschema_validate",
"(",
"instance",
"=",
"data",
",",
"schema",
"=",
"schema",
",",
"resolver",
"... | Validate the given dictionary against the given schema.
Args:
data (dict): record to validate.
schema (Union[dict, str]): schema to validate against. If it is a
string, it is intepreted as the name of the schema to load (e.g.
``authors`` or ``jobs``). If it is ``None``, the ... | [
"Validate",
"the",
"given",
"dictionary",
"against",
"the",
"given",
"schema",
"."
] | 34bc124b62fba565b6b40d1a3c15103a23a05edb | https://github.com/inspirehep/inspire-schemas/blob/34bc124b62fba565b6b40d1a3c15103a23a05edb/inspire_schemas/utils.py#L653-L678 | train |
inspirehep/inspire-schemas | inspire_schemas/utils.py | get_validation_errors | def get_validation_errors(data, schema=None):
"""Validation errors for a given record.
Args:
data (dict): record to validate.
schema (Union[dict, str]): schema to validate against. If it is a
string, it is intepreted as the name of the schema to load (e.g.
``authors`` or... | python | def get_validation_errors(data, schema=None):
"""Validation errors for a given record.
Args:
data (dict): record to validate.
schema (Union[dict, str]): schema to validate against. If it is a
string, it is intepreted as the name of the schema to load (e.g.
``authors`` or... | [
"def",
"get_validation_errors",
"(",
"data",
",",
"schema",
"=",
"None",
")",
":",
"schema",
"=",
"_load_schema_for_record",
"(",
"data",
",",
"schema",
")",
"errors",
"=",
"Draft4Validator",
"(",
"schema",
",",
"resolver",
"=",
"LocalRefResolver",
".",
"from_... | Validation errors for a given record.
Args:
data (dict): record to validate.
schema (Union[dict, str]): schema to validate against. If it is a
string, it is intepreted as the name of the schema to load (e.g.
``authors`` or ``jobs``). If it is ``None``, the schema is taken
... | [
"Validation",
"errors",
"for",
"a",
"given",
"record",
"."
] | 34bc124b62fba565b6b40d1a3c15103a23a05edb | https://github.com/inspirehep/inspire-schemas/blob/34bc124b62fba565b6b40d1a3c15103a23a05edb/inspire_schemas/utils.py#L681-L707 | train |
inspirehep/inspire-schemas | inspire_schemas/utils.py | normalize_collaboration | def normalize_collaboration(collaboration):
"""Normalize collaboration string.
Args:
collaboration: a string containing collaboration(s) or None
Returns:
list: List of extracted and normalized collaborations
Examples:
>>> from inspire_schemas.utils import normalize_collaborati... | python | def normalize_collaboration(collaboration):
"""Normalize collaboration string.
Args:
collaboration: a string containing collaboration(s) or None
Returns:
list: List of extracted and normalized collaborations
Examples:
>>> from inspire_schemas.utils import normalize_collaborati... | [
"def",
"normalize_collaboration",
"(",
"collaboration",
")",
":",
"if",
"not",
"collaboration",
":",
"return",
"[",
"]",
"collaboration",
"=",
"collaboration",
".",
"strip",
"(",
")",
"if",
"collaboration",
".",
"startswith",
"(",
"'('",
")",
"and",
"collabora... | Normalize collaboration string.
Args:
collaboration: a string containing collaboration(s) or None
Returns:
list: List of extracted and normalized collaborations
Examples:
>>> from inspire_schemas.utils import normalize_collaboration
>>> normalize_collaboration('for the CMS... | [
"Normalize",
"collaboration",
"string",
"."
] | 34bc124b62fba565b6b40d1a3c15103a23a05edb | https://github.com/inspirehep/inspire-schemas/blob/34bc124b62fba565b6b40d1a3c15103a23a05edb/inspire_schemas/utils.py#L710-L737 | train |
inspirehep/inspire-schemas | inspire_schemas/utils.py | get_license_from_url | def get_license_from_url(url):
"""Get the license abbreviation from an URL.
Args:
url(str): canonical url of the license.
Returns:
str: the corresponding license abbreviation.
Raises:
ValueError: when the url is not recognized
"""
if not url:
return
split_... | python | def get_license_from_url(url):
"""Get the license abbreviation from an URL.
Args:
url(str): canonical url of the license.
Returns:
str: the corresponding license abbreviation.
Raises:
ValueError: when the url is not recognized
"""
if not url:
return
split_... | [
"def",
"get_license_from_url",
"(",
"url",
")",
":",
"if",
"not",
"url",
":",
"return",
"split_url",
"=",
"urlsplit",
"(",
"url",
",",
"scheme",
"=",
"'http'",
")",
"if",
"split_url",
".",
"netloc",
".",
"lower",
"(",
")",
"==",
"'creativecommons.org'",
... | Get the license abbreviation from an URL.
Args:
url(str): canonical url of the license.
Returns:
str: the corresponding license abbreviation.
Raises:
ValueError: when the url is not recognized | [
"Get",
"the",
"license",
"abbreviation",
"from",
"an",
"URL",
"."
] | 34bc124b62fba565b6b40d1a3c15103a23a05edb | https://github.com/inspirehep/inspire-schemas/blob/34bc124b62fba565b6b40d1a3c15103a23a05edb/inspire_schemas/utils.py#L740-L776 | train |
inspirehep/inspire-schemas | inspire_schemas/utils.py | convert_old_publication_info_to_new | def convert_old_publication_info_to_new(publication_infos):
"""Convert a ``publication_info`` value from the old format to the new.
On Legacy different series of the same journal were modeled by adding the
letter part of the name to the journal volume. For example, a paper published
in Physical Review ... | python | def convert_old_publication_info_to_new(publication_infos):
"""Convert a ``publication_info`` value from the old format to the new.
On Legacy different series of the same journal were modeled by adding the
letter part of the name to the journal volume. For example, a paper published
in Physical Review ... | [
"def",
"convert_old_publication_info_to_new",
"(",
"publication_infos",
")",
":",
"result",
"=",
"[",
"]",
"hidden_publication_infos",
"=",
"[",
"]",
"for",
"publication_info",
"in",
"publication_infos",
":",
"_publication_info",
"=",
"copy",
".",
"deepcopy",
"(",
"... | Convert a ``publication_info`` value from the old format to the new.
On Legacy different series of the same journal were modeled by adding the
letter part of the name to the journal volume. For example, a paper published
in Physical Review D contained::
{
'publication_info': [
... | [
"Convert",
"a",
"publication_info",
"value",
"from",
"the",
"old",
"format",
"to",
"the",
"new",
"."
] | 34bc124b62fba565b6b40d1a3c15103a23a05edb | https://github.com/inspirehep/inspire-schemas/blob/34bc124b62fba565b6b40d1a3c15103a23a05edb/inspire_schemas/utils.py#L779-L872 | train |
inspirehep/inspire-schemas | inspire_schemas/utils.py | convert_new_publication_info_to_old | def convert_new_publication_info_to_old(publication_infos):
"""Convert back a ``publication_info`` value from the new format to the old.
Does the inverse transformation of :func:`convert_old_publication_info_to_new`,
to be used whenever we are sending back records from Labs to Legacy.
Args:
pu... | python | def convert_new_publication_info_to_old(publication_infos):
"""Convert back a ``publication_info`` value from the new format to the old.
Does the inverse transformation of :func:`convert_old_publication_info_to_new`,
to be used whenever we are sending back records from Labs to Legacy.
Args:
pu... | [
"def",
"convert_new_publication_info_to_old",
"(",
"publication_infos",
")",
":",
"def",
"_needs_a_hidden_pubnote",
"(",
"journal_title",
",",
"journal_volume",
")",
":",
"return",
"(",
"journal_title",
"in",
"_JOURNALS_THAT_NEED_A_HIDDEN_PUBNOTE",
"and",
"journal_volume",
... | Convert back a ``publication_info`` value from the new format to the old.
Does the inverse transformation of :func:`convert_old_publication_info_to_new`,
to be used whenever we are sending back records from Labs to Legacy.
Args:
publication_infos: a ``publication_info`` in the new format.
Ret... | [
"Convert",
"back",
"a",
"publication_info",
"value",
"from",
"the",
"new",
"format",
"to",
"the",
"old",
"."
] | 34bc124b62fba565b6b40d1a3c15103a23a05edb | https://github.com/inspirehep/inspire-schemas/blob/34bc124b62fba565b6b40d1a3c15103a23a05edb/inspire_schemas/utils.py#L875-L934 | train |
inspirehep/inspire-schemas | inspire_schemas/utils.py | fix_reference_url | def fix_reference_url(url):
"""Used to parse an incorect url to try to fix it with the most common ocurrences for errors.
If the fixed url is still incorrect, it returns ``None``.
Returns:
String containing the fixed url or the original one if it could not be fixed.
"""
new_url = url
n... | python | def fix_reference_url(url):
"""Used to parse an incorect url to try to fix it with the most common ocurrences for errors.
If the fixed url is still incorrect, it returns ``None``.
Returns:
String containing the fixed url or the original one if it could not be fixed.
"""
new_url = url
n... | [
"def",
"fix_reference_url",
"(",
"url",
")",
":",
"new_url",
"=",
"url",
"new_url",
"=",
"fix_url_bars_instead_of_slashes",
"(",
"new_url",
")",
"new_url",
"=",
"fix_url_add_http_if_missing",
"(",
"new_url",
")",
"new_url",
"=",
"fix_url_replace_tilde",
"(",
"new_ur... | Used to parse an incorect url to try to fix it with the most common ocurrences for errors.
If the fixed url is still incorrect, it returns ``None``.
Returns:
String containing the fixed url or the original one if it could not be fixed. | [
"Used",
"to",
"parse",
"an",
"incorect",
"url",
"to",
"try",
"to",
"fix",
"it",
"with",
"the",
"most",
"common",
"ocurrences",
"for",
"errors",
".",
"If",
"the",
"fixed",
"url",
"is",
"still",
"incorrect",
"it",
"returns",
"None",
"."
] | 34bc124b62fba565b6b40d1a3c15103a23a05edb | https://github.com/inspirehep/inspire-schemas/blob/34bc124b62fba565b6b40d1a3c15103a23a05edb/inspire_schemas/utils.py#L957-L976 | train |
inspirehep/inspire-schemas | inspire_schemas/utils.py | is_arxiv | def is_arxiv(obj):
"""Return ``True`` if ``obj`` contains an arXiv identifier.
The ``idutils`` library's ``is_arxiv`` function has been
modified here to work with two regular expressions instead
of three and adding a check for valid arxiv categories only"""
arxiv_test = obj.split()
if not arxiv... | python | def is_arxiv(obj):
"""Return ``True`` if ``obj`` contains an arXiv identifier.
The ``idutils`` library's ``is_arxiv`` function has been
modified here to work with two regular expressions instead
of three and adding a check for valid arxiv categories only"""
arxiv_test = obj.split()
if not arxiv... | [
"def",
"is_arxiv",
"(",
"obj",
")",
":",
"arxiv_test",
"=",
"obj",
".",
"split",
"(",
")",
"if",
"not",
"arxiv_test",
":",
"return",
"False",
"matched_arxiv",
"=",
"(",
"RE_ARXIV_PRE_2007_CLASS",
".",
"match",
"(",
"arxiv_test",
"[",
"0",
"]",
")",
"or",... | Return ``True`` if ``obj`` contains an arXiv identifier.
The ``idutils`` library's ``is_arxiv`` function has been
modified here to work with two regular expressions instead
of three and adding a check for valid arxiv categories only | [
"Return",
"True",
"if",
"obj",
"contains",
"an",
"arXiv",
"identifier",
"."
] | 34bc124b62fba565b6b40d1a3c15103a23a05edb | https://github.com/inspirehep/inspire-schemas/blob/34bc124b62fba565b6b40d1a3c15103a23a05edb/inspire_schemas/utils.py#L987-L1009 | train |
inspirehep/inspire-schemas | inspire_schemas/utils.py | normalize_arxiv | def normalize_arxiv(obj):
"""Return a normalized arXiv identifier from ``obj``."""
obj = obj.split()[0]
matched_arxiv_pre = RE_ARXIV_PRE_2007_CLASS.match(obj)
if matched_arxiv_pre:
return ('/'.join(matched_arxiv_pre.group("extraidentifier", "identifier"))).lower()
matched_arxiv_post = RE_A... | python | def normalize_arxiv(obj):
"""Return a normalized arXiv identifier from ``obj``."""
obj = obj.split()[0]
matched_arxiv_pre = RE_ARXIV_PRE_2007_CLASS.match(obj)
if matched_arxiv_pre:
return ('/'.join(matched_arxiv_pre.group("extraidentifier", "identifier"))).lower()
matched_arxiv_post = RE_A... | [
"def",
"normalize_arxiv",
"(",
"obj",
")",
":",
"obj",
"=",
"obj",
".",
"split",
"(",
")",
"[",
"0",
"]",
"matched_arxiv_pre",
"=",
"RE_ARXIV_PRE_2007_CLASS",
".",
"match",
"(",
"obj",
")",
"if",
"matched_arxiv_pre",
":",
"return",
"(",
"'/'",
".",
"join... | Return a normalized arXiv identifier from ``obj``. | [
"Return",
"a",
"normalized",
"arXiv",
"identifier",
"from",
"obj",
"."
] | 34bc124b62fba565b6b40d1a3c15103a23a05edb | https://github.com/inspirehep/inspire-schemas/blob/34bc124b62fba565b6b40d1a3c15103a23a05edb/inspire_schemas/utils.py#L1012-L1024 | train |
inspirehep/inspire-schemas | inspire_schemas/utils.py | LocalRefResolver.resolve_remote | def resolve_remote(self, uri):
"""Resolve a uri or relative path to a schema."""
try:
return super(LocalRefResolver, self).resolve_remote(uri)
except ValueError:
return super(LocalRefResolver, self).resolve_remote(
'file://' + get_schema_path(uri.rsplit('.... | python | def resolve_remote(self, uri):
"""Resolve a uri or relative path to a schema."""
try:
return super(LocalRefResolver, self).resolve_remote(uri)
except ValueError:
return super(LocalRefResolver, self).resolve_remote(
'file://' + get_schema_path(uri.rsplit('.... | [
"def",
"resolve_remote",
"(",
"self",
",",
"uri",
")",
":",
"try",
":",
"return",
"super",
"(",
"LocalRefResolver",
",",
"self",
")",
".",
"resolve_remote",
"(",
"uri",
")",
"except",
"ValueError",
":",
"return",
"super",
"(",
"LocalRefResolver",
",",
"sel... | Resolve a uri or relative path to a schema. | [
"Resolve",
"a",
"uri",
"or",
"relative",
"path",
"to",
"a",
"schema",
"."
] | 34bc124b62fba565b6b40d1a3c15103a23a05edb | https://github.com/inspirehep/inspire-schemas/blob/34bc124b62fba565b6b40d1a3c15103a23a05edb/inspire_schemas/utils.py#L535-L542 | train |
pylp/pylp | pylp/lib/file.py | File.set_path | def set_path(self, path):
"""Set the path of the file."""
if os.path.isabs(path):
path = os.path.normpath(os.path.join(self.cwd, path))
self.path = path
self.relative = os.path.relpath(self.path, self.base) | python | def set_path(self, path):
"""Set the path of the file."""
if os.path.isabs(path):
path = os.path.normpath(os.path.join(self.cwd, path))
self.path = path
self.relative = os.path.relpath(self.path, self.base) | [
"def",
"set_path",
"(",
"self",
",",
"path",
")",
":",
"if",
"os",
".",
"path",
".",
"isabs",
"(",
"path",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"normpath",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"cwd",
",",
"path",
"... | Set the path of the file. | [
"Set",
"the",
"path",
"of",
"the",
"file",
"."
] | 7ebaa55fbaf61cb8175f211dd41ef2928c22d4d4 | https://github.com/pylp/pylp/blob/7ebaa55fbaf61cb8175f211dd41ef2928c22d4d4/pylp/lib/file.py#L44-L50 | train |
pylp/pylp | pylp/lib/file.py | File.clone | def clone(self, path = None, *, with_contents = True, **options):
"""Clone the file."""
file = File(path if path else self.path, cwd=options.get("cwd", self.cwd))
file.base = options.get("base", self.base)
if with_contents:
file.contents = options.get("contents", self.contents)
return file | python | def clone(self, path = None, *, with_contents = True, **options):
"""Clone the file."""
file = File(path if path else self.path, cwd=options.get("cwd", self.cwd))
file.base = options.get("base", self.base)
if with_contents:
file.contents = options.get("contents", self.contents)
return file | [
"def",
"clone",
"(",
"self",
",",
"path",
"=",
"None",
",",
"*",
",",
"with_contents",
"=",
"True",
",",
"*",
"*",
"options",
")",
":",
"file",
"=",
"File",
"(",
"path",
"if",
"path",
"else",
"self",
".",
"path",
",",
"cwd",
"=",
"options",
".",
... | Clone the file. | [
"Clone",
"the",
"file",
"."
] | 7ebaa55fbaf61cb8175f211dd41ef2928c22d4d4 | https://github.com/pylp/pylp/blob/7ebaa55fbaf61cb8175f211dd41ef2928c22d4d4/pylp/lib/file.py#L53-L61 | train |
pylp/pylp | pylp/cli/cli.py | launch_cli | def launch_cli():
"""Launch the CLI."""
# Create the CLI argument parser
parser = argparse.ArgumentParser(
prog="pylp",
description="Call some tasks defined in your pylpfile."
)
# Version of Pylp
parser.add_argument("-v", "--version",
action="version",
version="Pylp %s" % version,
help="get the Pylp ... | python | def launch_cli():
"""Launch the CLI."""
# Create the CLI argument parser
parser = argparse.ArgumentParser(
prog="pylp",
description="Call some tasks defined in your pylpfile."
)
# Version of Pylp
parser.add_argument("-v", "--version",
action="version",
version="Pylp %s" % version,
help="get the Pylp ... | [
"def",
"launch_cli",
"(",
")",
":",
"# Create the CLI argument parser",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"prog",
"=",
"\"pylp\"",
",",
"description",
"=",
"\"Call some tasks defined in your pylpfile.\"",
")",
"# Version of Pylp",
"parser",
".",
"ad... | Launch the CLI. | [
"Launch",
"the",
"CLI",
"."
] | 7ebaa55fbaf61cb8175f211dd41ef2928c22d4d4 | https://github.com/pylp/pylp/blob/7ebaa55fbaf61cb8175f211dd41ef2928c22d4d4/pylp/cli/cli.py#L29-L110 | train |
inspirehep/inspire-schemas | inspire_schemas/builders/signatures.py | SignatureBuilder.add_affiliation | def add_affiliation(self, value, curated_relation=None, record=None):
"""Add an affiliation.
Args:
value (string): affiliation value
curated_relation (bool): is relation curated
record (dict): affiliation JSON reference
"""
if value:
affil... | python | def add_affiliation(self, value, curated_relation=None, record=None):
"""Add an affiliation.
Args:
value (string): affiliation value
curated_relation (bool): is relation curated
record (dict): affiliation JSON reference
"""
if value:
affil... | [
"def",
"add_affiliation",
"(",
"self",
",",
"value",
",",
"curated_relation",
"=",
"None",
",",
"record",
"=",
"None",
")",
":",
"if",
"value",
":",
"affiliation",
"=",
"{",
"'value'",
":",
"value",
"}",
"if",
"record",
":",
"affiliation",
"[",
"'record'... | Add an affiliation.
Args:
value (string): affiliation value
curated_relation (bool): is relation curated
record (dict): affiliation JSON reference | [
"Add",
"an",
"affiliation",
"."
] | 34bc124b62fba565b6b40d1a3c15103a23a05edb | https://github.com/inspirehep/inspire-schemas/blob/34bc124b62fba565b6b40d1a3c15103a23a05edb/inspire_schemas/builders/signatures.py#L69-L85 | train |
inspirehep/inspire-schemas | inspire_schemas/builders/signatures.py | SignatureBuilder.set_uid | def set_uid(self, uid, schema=None):
"""Set a unique ID.
If a UID of a given schema already exists in a record it will
be overwritten, otherwise it will be appended to the record.
Args:
uid (string): unique identifier.
schema (Optional[string]): schema of the un... | python | def set_uid(self, uid, schema=None):
"""Set a unique ID.
If a UID of a given schema already exists in a record it will
be overwritten, otherwise it will be appended to the record.
Args:
uid (string): unique identifier.
schema (Optional[string]): schema of the un... | [
"def",
"set_uid",
"(",
"self",
",",
"uid",
",",
"schema",
"=",
"None",
")",
":",
"try",
":",
"uid",
",",
"schema",
"=",
"author_id_normalize_and_schema",
"(",
"uid",
",",
"schema",
")",
"except",
"UnknownUIDSchema",
":",
"# Explicit schema wasn't provided, and t... | Set a unique ID.
If a UID of a given schema already exists in a record it will
be overwritten, otherwise it will be appended to the record.
Args:
uid (string): unique identifier.
schema (Optional[string]): schema of the unique identifier. If
``None``, th... | [
"Set",
"a",
"unique",
"ID",
"."
] | 34bc124b62fba565b6b40d1a3c15103a23a05edb | https://github.com/inspirehep/inspire-schemas/blob/34bc124b62fba565b6b40d1a3c15103a23a05edb/inspire_schemas/builders/signatures.py#L111-L136 | train |
druids/django-chamber | chamber/utils/decorators.py | singleton | def singleton(klass):
"""
Create singleton from class
"""
instances = {}
def getinstance(*args, **kwargs):
if klass not in instances:
instances[klass] = klass(*args, **kwargs)
return instances[klass]
return wraps(klass)(getinstance) | python | def singleton(klass):
"""
Create singleton from class
"""
instances = {}
def getinstance(*args, **kwargs):
if klass not in instances:
instances[klass] = klass(*args, **kwargs)
return instances[klass]
return wraps(klass)(getinstance) | [
"def",
"singleton",
"(",
"klass",
")",
":",
"instances",
"=",
"{",
"}",
"def",
"getinstance",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"klass",
"not",
"in",
"instances",
":",
"instances",
"[",
"klass",
"]",
"=",
"klass",
"(",
"*",... | Create singleton from class | [
"Create",
"singleton",
"from",
"class"
] | eef4169923557e96877a664fa254e8c0814f3f23 | https://github.com/druids/django-chamber/blob/eef4169923557e96877a664fa254e8c0814f3f23/chamber/utils/decorators.py#L13-L23 | train |
druids/django-chamber | chamber/utils/decorators.py | translation_activate_block | def translation_activate_block(function=None, language=None):
"""
Activate language only for one method or function
"""
def _translation_activate_block(function):
def _decorator(*args, **kwargs):
tmp_language = translation.get_language()
try:
translation.... | python | def translation_activate_block(function=None, language=None):
"""
Activate language only for one method or function
"""
def _translation_activate_block(function):
def _decorator(*args, **kwargs):
tmp_language = translation.get_language()
try:
translation.... | [
"def",
"translation_activate_block",
"(",
"function",
"=",
"None",
",",
"language",
"=",
"None",
")",
":",
"def",
"_translation_activate_block",
"(",
"function",
")",
":",
"def",
"_decorator",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"tmp_languag... | Activate language only for one method or function | [
"Activate",
"language",
"only",
"for",
"one",
"method",
"or",
"function"
] | eef4169923557e96877a664fa254e8c0814f3f23 | https://github.com/druids/django-chamber/blob/eef4169923557e96877a664fa254e8c0814f3f23/chamber/utils/decorators.py#L26-L44 | train |
bachya/pyopenuv | pyopenuv/client.py | Client.uv_protection_window | async def uv_protection_window(
self, low: float = 3.5, high: float = 3.5) -> dict:
"""Get data on when a UV protection window is."""
return await self.request(
'get', 'protection', params={
'from': str(low),
'to': str(high)
}) | python | async def uv_protection_window(
self, low: float = 3.5, high: float = 3.5) -> dict:
"""Get data on when a UV protection window is."""
return await self.request(
'get', 'protection', params={
'from': str(low),
'to': str(high)
}) | [
"async",
"def",
"uv_protection_window",
"(",
"self",
",",
"low",
":",
"float",
"=",
"3.5",
",",
"high",
":",
"float",
"=",
"3.5",
")",
"->",
"dict",
":",
"return",
"await",
"self",
".",
"request",
"(",
"'get'",
",",
"'protection'",
",",
"params",
"=",
... | Get data on when a UV protection window is. | [
"Get",
"data",
"on",
"when",
"a",
"UV",
"protection",
"window",
"is",
"."
] | f7c2f9dd99dd4e3b8b1f9e501ea17ce62a7ace46 | https://github.com/bachya/pyopenuv/blob/f7c2f9dd99dd4e3b8b1f9e501ea17ce62a7ace46/pyopenuv/client.py#L69-L76 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.