repo stringlengths 7 54 | path stringlengths 4 192 | url stringlengths 87 284 | code stringlengths 78 104k | code_tokens list | docstring stringlengths 1 46.9k | docstring_tokens list | language stringclasses 1
value | partition stringclasses 3
values |
|---|---|---|---|---|---|---|---|---|
spacetelescope/pysynphot | pysynphot/units.py | https://github.com/spacetelescope/pysynphot/blob/a125ff956f4d94beb157bd51899747a13234bb97/pysynphot/units.py#L1933-L1938 | def unitResponse(self,band):
"""This is used internally for :ref:`pysynphot-formula-effstim`
calculations."""
sp=band*self.vegaspec
total=sp.integrate()
return 2.5*math.log10(total) | [
"def",
"unitResponse",
"(",
"self",
",",
"band",
")",
":",
"sp",
"=",
"band",
"*",
"self",
".",
"vegaspec",
"total",
"=",
"sp",
".",
"integrate",
"(",
")",
"return",
"2.5",
"*",
"math",
".",
"log10",
"(",
"total",
")"
] | This is used internally for :ref:`pysynphot-formula-effstim`
calculations. | [
"This",
"is",
"used",
"internally",
"for",
":",
"ref",
":",
"pysynphot",
"-",
"formula",
"-",
"effstim",
"calculations",
"."
] | python | train |
datacamp/protowhat | protowhat/State.py | https://github.com/datacamp/protowhat/blob/a392b4e51e07a2e50e7b7f6ad918b3f5cbb63edc/protowhat/State.py#L120-L137 | def to_child(self, append_message="", **kwargs):
"""Basic implementation of returning a child state"""
bad_pars = set(kwargs) - set(self._child_params)
if bad_pars:
raise KeyError("Invalid init params for State: %s" % ", ".join(bad_pars))
child = copy(self)
for k, v... | [
"def",
"to_child",
"(",
"self",
",",
"append_message",
"=",
"\"\"",
",",
"*",
"*",
"kwargs",
")",
":",
"bad_pars",
"=",
"set",
"(",
"kwargs",
")",
"-",
"set",
"(",
"self",
".",
"_child_params",
")",
"if",
"bad_pars",
":",
"raise",
"KeyError",
"(",
"\... | Basic implementation of returning a child state | [
"Basic",
"implementation",
"of",
"returning",
"a",
"child",
"state"
] | python | train |
pebble/libpebble2 | libpebble2/communication/__init__.py | https://github.com/pebble/libpebble2/blob/23e2eb92cfc084e6f9e8c718711ac994ef606d18/libpebble2/communication/__init__.py#L65-L77 | def pump_reader(self):
"""
Synchronously reads one message from the watch, blocking until a message is available.
All events caused by the message read will be processed before this method returns.
.. note::
You usually don't need to invoke this method manually; instead, see ... | [
"def",
"pump_reader",
"(",
"self",
")",
":",
"origin",
",",
"message",
"=",
"self",
".",
"transport",
".",
"read_packet",
"(",
")",
"if",
"isinstance",
"(",
"origin",
",",
"MessageTargetWatch",
")",
":",
"self",
".",
"_handle_watch_message",
"(",
"message",
... | Synchronously reads one message from the watch, blocking until a message is available.
All events caused by the message read will be processed before this method returns.
.. note::
You usually don't need to invoke this method manually; instead, see :meth:`run_sync` and :meth:`run_async`. | [
"Synchronously",
"reads",
"one",
"message",
"from",
"the",
"watch",
"blocking",
"until",
"a",
"message",
"is",
"available",
".",
"All",
"events",
"caused",
"by",
"the",
"message",
"read",
"will",
"be",
"processed",
"before",
"this",
"method",
"returns",
"."
] | python | train |
hiposfer/o2g | o2g/osm/builders/stop_builder.py | https://github.com/hiposfer/o2g/blob/1165ba75a5eb64b3091e9b71ebd589507ae1ebf3/o2g/osm/builders/stop_builder.py#L71-L92 | def extract_stops(relation, nodes, visited_stop_ids, stop_to_station_map):
"""Extract stops in a relation."""
# member_role: stop, halt, platform, terminal, etc.
for member_type, member_id, member_role in relation.member_info:
if member_id not in visited_stop_ids and \
member_id in node... | [
"def",
"extract_stops",
"(",
"relation",
",",
"nodes",
",",
"visited_stop_ids",
",",
"stop_to_station_map",
")",
":",
"# member_role: stop, halt, platform, terminal, etc.",
"for",
"member_type",
",",
"member_id",
",",
"member_role",
"in",
"relation",
".",
"member_info",
... | Extract stops in a relation. | [
"Extract",
"stops",
"in",
"a",
"relation",
"."
] | python | test |
globocom/GloboNetworkAPI-client-python | networkapiclient/Equipamento.py | https://github.com/globocom/GloboNetworkAPI-client-python/blob/cf34f913da48d9abbf750114f5d2ac4b2dde137d/networkapiclient/Equipamento.py#L596-L612 | def get_all(self):
"""Return all equipments in database
:return: Dictionary with the following structure:
::
{'equipaments': {'name' :< name_equipament >}, {... demais equipamentos ...} }
:raise DataBaseError: Networkapi failed to access the database.
:raise XMLErr... | [
"def",
"get_all",
"(",
"self",
")",
":",
"url",
"=",
"'equipment/all'",
"code",
",",
"xml",
"=",
"self",
".",
"submit",
"(",
"None",
",",
"'GET'",
",",
"url",
")",
"return",
"self",
".",
"response",
"(",
"code",
",",
"xml",
")"
] | Return all equipments in database
:return: Dictionary with the following structure:
::
{'equipaments': {'name' :< name_equipament >}, {... demais equipamentos ...} }
:raise DataBaseError: Networkapi failed to access the database.
:raise XMLError: Networkapi failed to gener... | [
"Return",
"all",
"equipments",
"in",
"database"
] | python | train |
thunder-project/thunder-registration | registration/utils.py | https://github.com/thunder-project/thunder-registration/blob/286f091e6c402d592e9686d4821e0fd80dbf86ec/registration/utils.py#L4-L17 | def check_images(data):
"""
Check and reformat input images if needed
"""
if isinstance(data, ndarray):
data = fromarray(data)
if not isinstance(data, Images):
data = fromarray(asarray(data))
if len(data.shape) not in set([3, 4]):
raise Exception('Number of image di... | [
"def",
"check_images",
"(",
"data",
")",
":",
"if",
"isinstance",
"(",
"data",
",",
"ndarray",
")",
":",
"data",
"=",
"fromarray",
"(",
"data",
")",
"if",
"not",
"isinstance",
"(",
"data",
",",
"Images",
")",
":",
"data",
"=",
"fromarray",
"(",
"asar... | Check and reformat input images if needed | [
"Check",
"and",
"reformat",
"input",
"images",
"if",
"needed"
] | python | train |
NiklasRosenstein-Python/nr-deprecated | nr/stream.py | https://github.com/NiklasRosenstein-Python/nr-deprecated/blob/f9f8b89ea1b084841a8ab65784eaf68852686b2a/nr/stream.py#L96-L105 | def concat(cls, iterables):
"""
Similar to #itertools.chain.from_iterable().
"""
def generator():
for it in iterables:
for element in it:
yield element
return cls(generator()) | [
"def",
"concat",
"(",
"cls",
",",
"iterables",
")",
":",
"def",
"generator",
"(",
")",
":",
"for",
"it",
"in",
"iterables",
":",
"for",
"element",
"in",
"it",
":",
"yield",
"element",
"return",
"cls",
"(",
"generator",
"(",
")",
")"
] | Similar to #itertools.chain.from_iterable(). | [
"Similar",
"to",
"#itertools",
".",
"chain",
".",
"from_iterable",
"()",
"."
] | python | train |
bitcraze/crazyflie-lib-python | cflib/crazyflie/__init__.py | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crazyflie/__init__.py#L165-L171 | def _param_toc_updated_cb(self):
"""Called when the param TOC has been fully updated"""
logger.info('Param TOC finished updating')
self.connected_ts = datetime.datetime.now()
self.connected.call(self.link_uri)
# Trigger the update for all the parameters
self.param.request... | [
"def",
"_param_toc_updated_cb",
"(",
"self",
")",
":",
"logger",
".",
"info",
"(",
"'Param TOC finished updating'",
")",
"self",
".",
"connected_ts",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
"self",
".",
"connected",
".",
"call",
"(",
"self",
... | Called when the param TOC has been fully updated | [
"Called",
"when",
"the",
"param",
"TOC",
"has",
"been",
"fully",
"updated"
] | python | train |
resonai/ybt | yabt/builders/custom_installer.py | https://github.com/resonai/ybt/blob/5b40df0922ef3383eb85f2b04a26a2db4b81b3fd/yabt/builders/custom_installer.py#L121-L134 | def fetch_url(url, dest, parent_to_remove_before_fetch):
"""Helper function to fetch a file from a URL."""
logger.debug('Downloading file {} from {}', dest, url)
try:
shutil.rmtree(parent_to_remove_before_fetch)
except FileNotFoundError:
pass
os.makedirs(parent_to_remove_before_fetch... | [
"def",
"fetch_url",
"(",
"url",
",",
"dest",
",",
"parent_to_remove_before_fetch",
")",
":",
"logger",
".",
"debug",
"(",
"'Downloading file {} from {}'",
",",
"dest",
",",
"url",
")",
"try",
":",
"shutil",
".",
"rmtree",
"(",
"parent_to_remove_before_fetch",
")... | Helper function to fetch a file from a URL. | [
"Helper",
"function",
"to",
"fetch",
"a",
"file",
"from",
"a",
"URL",
"."
] | python | train |
kata198/NamedAtomicLock | NamedAtomicLock/__init__.py | https://github.com/kata198/NamedAtomicLock/blob/82d480b81daf4deea926964f18bb2e47d4f30f6c/NamedAtomicLock/__init__.py#L128-L162 | def release(self, forceRelease=False):
'''
release - Release the lock.
@param forceRelease <bool> default False - If True, will release the lock even if we don't hold it.
@return - True if lock is released, otherwise False
'''
if not self.held:
i... | [
"def",
"release",
"(",
"self",
",",
"forceRelease",
"=",
"False",
")",
":",
"if",
"not",
"self",
".",
"held",
":",
"if",
"forceRelease",
"is",
"False",
":",
"return",
"False",
"# We were not holding the lock",
"else",
":",
"self",
".",
"held",
"=",
"True",... | release - Release the lock.
@param forceRelease <bool> default False - If True, will release the lock even if we don't hold it.
@return - True if lock is released, otherwise False | [
"release",
"-",
"Release",
"the",
"lock",
"."
] | python | train |
onyxfish/clan | clan/report.py | https://github.com/onyxfish/clan/blob/415ddd027ea81013f2d62d75aec6da70703df49c/clan/report.py#L225-L292 | def report(self):
"""
Query analytics and stash data in a format suitable for serializing.
"""
output = OrderedDict()
for arg in GLOBAL_ARGUMENTS:
output[arg] = getattr(self.args, arg) or self.config.get(arg, None)
output['title'] = getattr(self.args, 'title... | [
"def",
"report",
"(",
"self",
")",
":",
"output",
"=",
"OrderedDict",
"(",
")",
"for",
"arg",
"in",
"GLOBAL_ARGUMENTS",
":",
"output",
"[",
"arg",
"]",
"=",
"getattr",
"(",
"self",
".",
"args",
",",
"arg",
")",
"or",
"self",
".",
"config",
".",
"ge... | Query analytics and stash data in a format suitable for serializing. | [
"Query",
"analytics",
"and",
"stash",
"data",
"in",
"a",
"format",
"suitable",
"for",
"serializing",
"."
] | python | train |
yola/hashcache | hashcache/hashcache.py | https://github.com/yola/hashcache/blob/0a42e3f7f0bd7ada2a34266d4aa06b8d61b2f038/hashcache/hashcache.py#L29-L31 | def set(self, key, *args):
"""Hash the key and set it in the cache"""
return self.cache.set(self._hashed(key), *args) | [
"def",
"set",
"(",
"self",
",",
"key",
",",
"*",
"args",
")",
":",
"return",
"self",
".",
"cache",
".",
"set",
"(",
"self",
".",
"_hashed",
"(",
"key",
")",
",",
"*",
"args",
")"
] | Hash the key and set it in the cache | [
"Hash",
"the",
"key",
"and",
"set",
"it",
"in",
"the",
"cache"
] | python | train |
casacore/python-casacore | casacore/images/image.py | https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/images/image.py#L292-L304 | def getdata(self, blc=(), trc=(), inc=()):
"""Get image data.
Using the arguments blc (bottom left corner), trc (top right corner),
and inc (stride) it is possible to get a data slice.
The data is returned as a numpy array. Its dimensionality is the same
as the dimensionality o... | [
"def",
"getdata",
"(",
"self",
",",
"blc",
"=",
"(",
")",
",",
"trc",
"=",
"(",
")",
",",
"inc",
"=",
"(",
")",
")",
":",
"return",
"self",
".",
"_getdata",
"(",
"self",
".",
"_adjustBlc",
"(",
"blc",
")",
",",
"self",
".",
"_adjustTrc",
"(",
... | Get image data.
Using the arguments blc (bottom left corner), trc (top right corner),
and inc (stride) it is possible to get a data slice.
The data is returned as a numpy array. Its dimensionality is the same
as the dimensionality of the image, even if an axis has length 1. | [
"Get",
"image",
"data",
"."
] | python | train |
bcbio/bcbio-nextgen | bcbio/qc/multiqc.py | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/qc/multiqc.py#L195-L222 | def _work_path_to_rel_final_path(path, upload_path_mapping, upload_base_dir):
""" Check if `path` is a work-rooted path, and convert to a relative final-rooted path
"""
if not path or not isinstance(path, str):
return path
upload_path = None
# First, check in the mapping: if it's there is a... | [
"def",
"_work_path_to_rel_final_path",
"(",
"path",
",",
"upload_path_mapping",
",",
"upload_base_dir",
")",
":",
"if",
"not",
"path",
"or",
"not",
"isinstance",
"(",
"path",
",",
"str",
")",
":",
"return",
"path",
"upload_path",
"=",
"None",
"# First, check in ... | Check if `path` is a work-rooted path, and convert to a relative final-rooted path | [
"Check",
"if",
"path",
"is",
"a",
"work",
"-",
"rooted",
"path",
"and",
"convert",
"to",
"a",
"relative",
"final",
"-",
"rooted",
"path"
] | python | train |
senseobservationsystems/commonsense-python-lib | senseapi.py | https://github.com/senseobservationsystems/commonsense-python-lib/blob/aac59a1751ef79eb830b3ca1fab6ef2c83931f87/senseapi.py#L850-L863 | def SensorsDataPost(self, parameters):
"""
Post sensor data to multiple sensors in CommonSense simultaneously.
@param parameters (dictionary) - Data to post to the sensors.
@note - http://www.sense-os.nl/59?nodeId=59&selectedId=11887
... | [
"def",
"SensorsDataPost",
"(",
"self",
",",
"parameters",
")",
":",
"if",
"self",
".",
"__SenseApiCall__",
"(",
"'/sensors/data.json'",
",",
"'POST'",
",",
"parameters",
"=",
"parameters",
")",
":",
"return",
"True",
"else",
":",
"self",
".",
"__error__",
"=... | Post sensor data to multiple sensors in CommonSense simultaneously.
@param parameters (dictionary) - Data to post to the sensors.
@note - http://www.sense-os.nl/59?nodeId=59&selectedId=11887
@return (bool) - Boolean indicating whether Se... | [
"Post",
"sensor",
"data",
"to",
"multiple",
"sensors",
"in",
"CommonSense",
"simultaneously",
"."
] | python | train |
googleads/googleads-python-lib | googleads/ad_manager.py | https://github.com/googleads/googleads-python-lib/blob/aa3b1b474b0f9789ca55ca46f4b2b57aeae38874/googleads/ad_manager.py#L418-L444 | def AdManagerDateTimePacker(cls, value, version):
"""Returns dicts formatted for Ad Manager SOAP based on date/datetime.
Args:
value: A date or datetime object to be converted.
version: the version of the current API, e.g. 'v201811'
Returns:
The value object correctly represented for Ad ... | [
"def",
"AdManagerDateTimePacker",
"(",
"cls",
",",
"value",
",",
"version",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"datetime",
".",
"datetime",
")",
":",
"if",
"value",
".",
"tzinfo",
"is",
"None",
":",
"raise",
"googleads",
".",
"errors",
".",... | Returns dicts formatted for Ad Manager SOAP based on date/datetime.
Args:
value: A date or datetime object to be converted.
version: the version of the current API, e.g. 'v201811'
Returns:
The value object correctly represented for Ad Manager SOAP. | [
"Returns",
"dicts",
"formatted",
"for",
"Ad",
"Manager",
"SOAP",
"based",
"on",
"date",
"/",
"datetime",
"."
] | python | train |
acutesoftware/AIKIF | aikif/dataTools/cls_data.py | https://github.com/acutesoftware/AIKIF/blob/fcf1582dc5f884b9a4fa7c6e20e9de9d94d21d03/aikif/dataTools/cls_data.py#L120-L138 | def _calc_size_stats(self):
"""
get the size in bytes and num records of the content
"""
self.total_records = 0
self.total_length = 0
self.total_nodes = 0
if type(self.content['data']) is dict:
self.total_length += len(str(self.content['data']))
... | [
"def",
"_calc_size_stats",
"(",
"self",
")",
":",
"self",
".",
"total_records",
"=",
"0",
"self",
".",
"total_length",
"=",
"0",
"self",
".",
"total_nodes",
"=",
"0",
"if",
"type",
"(",
"self",
".",
"content",
"[",
"'data'",
"]",
")",
"is",
"dict",
"... | get the size in bytes and num records of the content | [
"get",
"the",
"size",
"in",
"bytes",
"and",
"num",
"records",
"of",
"the",
"content"
] | python | train |
saltstack/salt | salt/modules/redismod.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/redismod.py#L270-L283 | def hexists(key, field, host=None, port=None, db=None, password=None):
'''
Determine if a hash fields exists.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hexists foo_hash bar_field
'''
server = _connect(host, port, db, password)
return server.h... | [
"def",
"hexists",
"(",
"key",
",",
"field",
",",
"host",
"=",
"None",
",",
"port",
"=",
"None",
",",
"db",
"=",
"None",
",",
"password",
"=",
"None",
")",
":",
"server",
"=",
"_connect",
"(",
"host",
",",
"port",
",",
"db",
",",
"password",
")",
... | Determine if a hash fields exists.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hexists foo_hash bar_field | [
"Determine",
"if",
"a",
"hash",
"fields",
"exists",
"."
] | python | train |
wangsix/vmo | vmo/generate.py | https://github.com/wangsix/vmo/blob/bb1cc4cf1f33f0bb49e38c91126c1be1a0cdd09d/vmo/generate.py#L67-L99 | def improvise(oracle, seq_len, k=1, LRS=0, weight=None, continuity=1):
""" Given an oracle and length, generate an improvised sequence of the given length.
:param oracle: an indexed vmo object
:param seq_len: the length of the returned improvisation sequence
:param k: the starting improvisation time st... | [
"def",
"improvise",
"(",
"oracle",
",",
"seq_len",
",",
"k",
"=",
"1",
",",
"LRS",
"=",
"0",
",",
"weight",
"=",
"None",
",",
"continuity",
"=",
"1",
")",
":",
"s",
"=",
"[",
"]",
"if",
"k",
"+",
"continuity",
"<",
"oracle",
".",
"n_states",
"-... | Given an oracle and length, generate an improvised sequence of the given length.
:param oracle: an indexed vmo object
:param seq_len: the length of the returned improvisation sequence
:param k: the starting improvisation time step in oracle
:param LRS: the length of minimum longest repeated suffixes al... | [
"Given",
"an",
"oracle",
"and",
"length",
"generate",
"an",
"improvised",
"sequence",
"of",
"the",
"given",
"length",
"."
] | python | train |
log2timeline/plaso | plaso/parsers/winreg.py | https://github.com/log2timeline/plaso/blob/9c564698d2da3ffbe23607a3c54c0582ea18a6cc/plaso/parsers/winreg.py#L187-L198 | def _ParseRecurseKeys(self, parser_mediator, root_key):
"""Parses the Registry keys recursively.
Args:
parser_mediator (ParserMediator): parser mediator.
root_key (dfwinreg.WinRegistryKey): root Windows Registry key.
"""
for registry_key in root_key.RecurseKeys():
if parser_mediator.a... | [
"def",
"_ParseRecurseKeys",
"(",
"self",
",",
"parser_mediator",
",",
"root_key",
")",
":",
"for",
"registry_key",
"in",
"root_key",
".",
"RecurseKeys",
"(",
")",
":",
"if",
"parser_mediator",
".",
"abort",
":",
"break",
"self",
".",
"_ParseKey",
"(",
"parse... | Parses the Registry keys recursively.
Args:
parser_mediator (ParserMediator): parser mediator.
root_key (dfwinreg.WinRegistryKey): root Windows Registry key. | [
"Parses",
"the",
"Registry",
"keys",
"recursively",
"."
] | python | train |
cloud9ers/gurumate | environment/lib/python2.7/site-packages/IPython/core/magic_arguments.py | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/magic_arguments.py#L130-L136 | def real_name(magic_func):
""" Find the real name of the magic.
"""
magic_name = magic_func.__name__
if magic_name.startswith('magic_'):
magic_name = magic_name[len('magic_'):]
return getattr(magic_func, 'argcmd_name', magic_name) | [
"def",
"real_name",
"(",
"magic_func",
")",
":",
"magic_name",
"=",
"magic_func",
".",
"__name__",
"if",
"magic_name",
".",
"startswith",
"(",
"'magic_'",
")",
":",
"magic_name",
"=",
"magic_name",
"[",
"len",
"(",
"'magic_'",
")",
":",
"]",
"return",
"get... | Find the real name of the magic. | [
"Find",
"the",
"real",
"name",
"of",
"the",
"magic",
"."
] | python | test |
polyaxon/polyaxon-cli | polyaxon_cli/cli/upload.py | https://github.com/polyaxon/polyaxon-cli/blob/a7f5eed74d4d909cad79059f3c21c58606881449/polyaxon_cli/cli/upload.py#L23-L51 | def upload(sync=True): # pylint:disable=assign-to-new-keyword
"""Upload code of the current directory while respecting the .polyaxonignore file."""
project = ProjectManager.get_config_or_raise()
files = IgnoreManager.get_unignored_file_paths()
try:
with create_tarfile(files, project.name) as fi... | [
"def",
"upload",
"(",
"sync",
"=",
"True",
")",
":",
"# pylint:disable=assign-to-new-keyword",
"project",
"=",
"ProjectManager",
".",
"get_config_or_raise",
"(",
")",
"files",
"=",
"IgnoreManager",
".",
"get_unignored_file_paths",
"(",
")",
"try",
":",
"with",
"cr... | Upload code of the current directory while respecting the .polyaxonignore file. | [
"Upload",
"code",
"of",
"the",
"current",
"directory",
"while",
"respecting",
"the",
".",
"polyaxonignore",
"file",
"."
] | python | valid |
biosustain/optlang | optlang/scipy_interface.py | https://github.com/biosustain/optlang/blob/13673ac26f6b3ba37a2ef392489722c52e3c5ff1/optlang/scipy_interface.py#L178-L182 | def set_constraint_bound(self, name, value):
"""Set the upper bound of a constraint."""
index = self._get_constraint_index(name)
self.upper_bounds[index] = value
self._reset_solution() | [
"def",
"set_constraint_bound",
"(",
"self",
",",
"name",
",",
"value",
")",
":",
"index",
"=",
"self",
".",
"_get_constraint_index",
"(",
"name",
")",
"self",
".",
"upper_bounds",
"[",
"index",
"]",
"=",
"value",
"self",
".",
"_reset_solution",
"(",
")"
] | Set the upper bound of a constraint. | [
"Set",
"the",
"upper",
"bound",
"of",
"a",
"constraint",
"."
] | python | train |
sphinx-contrib/spelling | sphinxcontrib/spelling/checker.py | https://github.com/sphinx-contrib/spelling/blob/3108cd86b5935f458ec80e87f8e37f924725d15f/sphinxcontrib/spelling/checker.py#L41-L49 | def check(self, text):
"""Yields bad words and suggested alternate spellings.
"""
for word, pos in self.tokenizer(text):
correct = self.dictionary.check(word)
if correct:
continue
yield word, self.dictionary.suggest(word) if self.suggest else [... | [
"def",
"check",
"(",
"self",
",",
"text",
")",
":",
"for",
"word",
",",
"pos",
"in",
"self",
".",
"tokenizer",
"(",
"text",
")",
":",
"correct",
"=",
"self",
".",
"dictionary",
".",
"check",
"(",
"word",
")",
"if",
"correct",
":",
"continue",
"yiel... | Yields bad words and suggested alternate spellings. | [
"Yields",
"bad",
"words",
"and",
"suggested",
"alternate",
"spellings",
"."
] | python | train |
realestate-com-au/dashmat | dashmat/core_modules/splunk/splunk-sdk-1.3.0/splunklib/client.py | https://github.com/realestate-com-au/dashmat/blob/433886e52698f0ddb9956f087b76041966c3bcd1/dashmat/core_modules/splunk/splunk-sdk-1.3.0/splunklib/client.py#L2358-L2396 | def kindpath(self, kind):
"""Returns a path to the resources for a given input kind.
:param `kind`: The kind of input:
- "ad": Active Directory
- "monitor": Files and directories
- "registry": Windows Registry
- "script": Scripts
- "splun... | [
"def",
"kindpath",
"(",
"self",
",",
"kind",
")",
":",
"if",
"kind",
"in",
"self",
".",
"kinds",
":",
"return",
"UrlEncoded",
"(",
"kind",
",",
"skip_encode",
"=",
"True",
")",
"# Special cases",
"elif",
"kind",
"==",
"'tcp'",
":",
"return",
"UrlEncoded"... | Returns a path to the resources for a given input kind.
:param `kind`: The kind of input:
- "ad": Active Directory
- "monitor": Files and directories
- "registry": Windows Registry
- "script": Scripts
- "splunktcp": TCP, processed
- ... | [
"Returns",
"a",
"path",
"to",
"the",
"resources",
"for",
"a",
"given",
"input",
"kind",
"."
] | python | train |
polysquare/polysquare-generic-file-linter | polysquarelinter/lint_spelling_only.py | https://github.com/polysquare/polysquare-generic-file-linter/blob/cfc88771acd3d5551c28fa5d917bb0aeb584c4cc/polysquarelinter/lint_spelling_only.py#L82-L105 | def _parse_arguments(arguments=None):
"""Return a parser context result."""
dir_hash = hashlib.sha1(os.getcwd().encode("utf-8")).hexdigest()
parser = argparse.ArgumentParser(description="""Find spelling errors""")
parser.add_argument("files",
nargs="*",
m... | [
"def",
"_parse_arguments",
"(",
"arguments",
"=",
"None",
")",
":",
"dir_hash",
"=",
"hashlib",
".",
"sha1",
"(",
"os",
".",
"getcwd",
"(",
")",
".",
"encode",
"(",
"\"utf-8\"",
")",
")",
".",
"hexdigest",
"(",
")",
"parser",
"=",
"argparse",
".",
"A... | Return a parser context result. | [
"Return",
"a",
"parser",
"context",
"result",
"."
] | python | train |
agile-geoscience/welly | welly/curve.py | https://github.com/agile-geoscience/welly/blob/ed4c991011d6290938fef365553041026ba29f42/welly/curve.py#L761-L792 | def _rolling_window(self, window_length, func1d, step=1, return_rolled=False):
"""
Private function. Smoother for other smoothing/conditioning functions.
Args:
window_length (int): the window length.
func1d (function): a function that takes a 1D array and returns a
... | [
"def",
"_rolling_window",
"(",
"self",
",",
"window_length",
",",
"func1d",
",",
"step",
"=",
"1",
",",
"return_rolled",
"=",
"False",
")",
":",
"# Force odd.",
"if",
"window_length",
"%",
"2",
"==",
"0",
":",
"window_length",
"+=",
"1",
"shape",
"=",
"s... | Private function. Smoother for other smoothing/conditioning functions.
Args:
window_length (int): the window length.
func1d (function): a function that takes a 1D array and returns a
scalar.
step (int): if you want to skip samples in the shifted versions.
... | [
"Private",
"function",
".",
"Smoother",
"for",
"other",
"smoothing",
"/",
"conditioning",
"functions",
"."
] | python | train |
markchil/gptools | gptools/utils.py | https://github.com/markchil/gptools/blob/225db52bfe6baef1516529ad22177aa2cf7b71e4/gptools/utils.py#L732-L753 | def elementwise_cdf(self, p):
r"""Convert a sample to random variates uniform on :math:`[0, 1]`.
For a univariate distribution, this is simply evaluating the CDF. To
facilitate efficient sampling, this function returns a *vector* of CDF
values, one value for each variable. Basic... | [
"def",
"elementwise_cdf",
"(",
"self",
",",
"p",
")",
":",
"p",
"=",
"scipy",
".",
"atleast_1d",
"(",
"p",
")",
"if",
"len",
"(",
"p",
")",
"!=",
"len",
"(",
"self",
".",
"univariate_priors",
")",
":",
"raise",
"ValueError",
"(",
"\"length of p must eq... | r"""Convert a sample to random variates uniform on :math:`[0, 1]`.
For a univariate distribution, this is simply evaluating the CDF. To
facilitate efficient sampling, this function returns a *vector* of CDF
values, one value for each variable. Basically, the idea is that, given
... | [
"r",
"Convert",
"a",
"sample",
"to",
"random",
"variates",
"uniform",
"on",
":",
"math",
":",
"[",
"0",
"1",
"]",
".",
"For",
"a",
"univariate",
"distribution",
"this",
"is",
"simply",
"evaluating",
"the",
"CDF",
".",
"To",
"facilitate",
"efficient",
"sa... | python | train |
nok/sklearn-porter | sklearn_porter/estimator/classifier/MLPClassifier/__init__.py | https://github.com/nok/sklearn-porter/blob/04673f768310bde31f9747a68a5e070592441ef2/sklearn_porter/estimator/classifier/MLPClassifier/__init__.py#L221-L249 | def export_data(self, directory, filename, with_md5_hash=False):
"""
Save model data in a JSON file.
Parameters
----------
:param directory : string
The directory.
:param filename : string
The filename.
:param with_md5_hash : bool, default... | [
"def",
"export_data",
"(",
"self",
",",
"directory",
",",
"filename",
",",
"with_md5_hash",
"=",
"False",
")",
":",
"model_data",
"=",
"{",
"'layers'",
":",
"[",
"int",
"(",
"l",
")",
"for",
"l",
"in",
"list",
"(",
"self",
".",
"_get_activations",
"(",... | Save model data in a JSON file.
Parameters
----------
:param directory : string
The directory.
:param filename : string
The filename.
:param with_md5_hash : bool, default: False
Whether to append the checksum to the filename or not. | [
"Save",
"model",
"data",
"in",
"a",
"JSON",
"file",
"."
] | python | train |
sorgerlab/indra | indra/belief/wm_scorer.py | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/belief/wm_scorer.py#L11-L21 | def load_eidos_curation_table():
"""Return a pandas table of Eidos curation data."""
url = 'https://raw.githubusercontent.com/clulab/eidos/master/' + \
'src/main/resources/org/clulab/wm/eidos/english/confidence/' + \
'rule_summary.tsv'
# Load the table of scores from the URL above into a dat... | [
"def",
"load_eidos_curation_table",
"(",
")",
":",
"url",
"=",
"'https://raw.githubusercontent.com/clulab/eidos/master/'",
"+",
"'src/main/resources/org/clulab/wm/eidos/english/confidence/'",
"+",
"'rule_summary.tsv'",
"# Load the table of scores from the URL above into a data frame",
"res... | Return a pandas table of Eidos curation data. | [
"Return",
"a",
"pandas",
"table",
"of",
"Eidos",
"curation",
"data",
"."
] | python | train |
quantmind/dynts | dynts/api/timeseries.py | https://github.com/quantmind/dynts/blob/21ac57c648bfec402fa6b1fe569496cf098fb5e8/dynts/api/timeseries.py#L461-L479 | def var(self, ddof=0):
'''Calculate variance of timeseries. Return a vector containing
the variances of each series in the timeseries.
:parameter ddof: delta degree of freedom, the divisor used in the calculation
is given by ``N - ddof`` where ``N`` represents the length
... | [
"def",
"var",
"(",
"self",
",",
"ddof",
"=",
"0",
")",
":",
"N",
"=",
"len",
"(",
"self",
")",
"if",
"N",
":",
"v",
"=",
"self",
".",
"values",
"(",
")",
"mu",
"=",
"sum",
"(",
"v",
")",
"return",
"(",
"sum",
"(",
"v",
"*",
"v",
")",
"-... | Calculate variance of timeseries. Return a vector containing
the variances of each series in the timeseries.
:parameter ddof: delta degree of freedom, the divisor used in the calculation
is given by ``N - ddof`` where ``N`` represents the length
of timeseries. Default ``0``.
.... | [
"Calculate",
"variance",
"of",
"timeseries",
".",
"Return",
"a",
"vector",
"containing",
"the",
"variances",
"of",
"each",
"series",
"in",
"the",
"timeseries",
".",
":",
"parameter",
"ddof",
":",
"delta",
"degree",
"of",
"freedom",
"the",
"divisor",
"used",
... | python | train |
angr/angr | angr/analyses/cfg/cfg_emulated.py | https://github.com/angr/angr/blob/4e2f97d56af5419ee73bdb30482c8dd8ff5f3e40/angr/analyses/cfg/cfg_emulated.py#L2641-L2696 | def _get_symbolic_function_initial_state(self, function_addr, fastpath_mode_state=None):
"""
Symbolically execute the first basic block of the specified function,
then returns it. We prepares the state using the already existing
state in fastpath mode (if avaiable).
:param functi... | [
"def",
"_get_symbolic_function_initial_state",
"(",
"self",
",",
"function_addr",
",",
"fastpath_mode_state",
"=",
"None",
")",
":",
"if",
"function_addr",
"is",
"None",
":",
"return",
"None",
"if",
"function_addr",
"in",
"self",
".",
"_symbolic_function_initial_state... | Symbolically execute the first basic block of the specified function,
then returns it. We prepares the state using the already existing
state in fastpath mode (if avaiable).
:param function_addr: The function address
:return: A symbolic state if succeeded, None otherwise | [
"Symbolically",
"execute",
"the",
"first",
"basic",
"block",
"of",
"the",
"specified",
"function",
"then",
"returns",
"it",
".",
"We",
"prepares",
"the",
"state",
"using",
"the",
"already",
"existing",
"state",
"in",
"fastpath",
"mode",
"(",
"if",
"avaiable",
... | python | train |
denisenkom/pytds | src/pytds/tds_base.py | https://github.com/denisenkom/pytds/blob/7d875cab29134afdef719406831c1c6a0d7af48a/src/pytds/tds_base.py#L496-L517 | def skipall(stm, size):
""" Skips exactly size bytes in stm
If EOF is reached before size bytes are skipped
will raise :class:`ClosedConnectionError`
:param stm: Stream to skip bytes in, should have read method
this read method can return less than requested
number of b... | [
"def",
"skipall",
"(",
"stm",
",",
"size",
")",
":",
"res",
"=",
"stm",
".",
"recv",
"(",
"size",
")",
"if",
"len",
"(",
"res",
")",
"==",
"size",
":",
"return",
"elif",
"len",
"(",
"res",
")",
"==",
"0",
":",
"raise",
"ClosedConnectionError",
"(... | Skips exactly size bytes in stm
If EOF is reached before size bytes are skipped
will raise :class:`ClosedConnectionError`
:param stm: Stream to skip bytes in, should have read method
this read method can return less than requested
number of bytes.
:param size: Number of... | [
"Skips",
"exactly",
"size",
"bytes",
"in",
"stm"
] | python | train |
inasafe/inasafe | safe/gui/tools/options_dialog.py | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/options_dialog.py#L498-L507 | def open_user_directory_path(self):
"""Open File dialog to choose the user directory path."""
# noinspection PyCallByClass,PyTypeChecker
directory_name = QFileDialog.getExistingDirectory(
self,
self.tr('Results directory'),
self.leUserDirectoryPath.text(),
... | [
"def",
"open_user_directory_path",
"(",
"self",
")",
":",
"# noinspection PyCallByClass,PyTypeChecker",
"directory_name",
"=",
"QFileDialog",
".",
"getExistingDirectory",
"(",
"self",
",",
"self",
".",
"tr",
"(",
"'Results directory'",
")",
",",
"self",
".",
"leUserDi... | Open File dialog to choose the user directory path. | [
"Open",
"File",
"dialog",
"to",
"choose",
"the",
"user",
"directory",
"path",
"."
] | python | train |
bitesofcode/projexui | projexui/widgets/xviewwidget/xviewwidget.py | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xviewwidget/xviewwidget.py#L101-L129 | def createMenu(self, parent):
"""
Creates a new menu for the inputed parent item.
:param parent | <QMenu>
"""
menu = QtGui.QMenu(parent)
menu.setTitle('&View')
act = menu.addAction('&Lock/Unlock Layout')
act.setIcon(QtGui.QIcon(projexui.reso... | [
"def",
"createMenu",
"(",
"self",
",",
"parent",
")",
":",
"menu",
"=",
"QtGui",
".",
"QMenu",
"(",
"parent",
")",
"menu",
".",
"setTitle",
"(",
"'&View'",
")",
"act",
"=",
"menu",
".",
"addAction",
"(",
"'&Lock/Unlock Layout'",
")",
"act",
".",
"setIc... | Creates a new menu for the inputed parent item.
:param parent | <QMenu> | [
"Creates",
"a",
"new",
"menu",
"for",
"the",
"inputed",
"parent",
"item",
".",
":",
"param",
"parent",
"|",
"<QMenu",
">"
] | python | train |
mwouts/jupytext | jupytext/header.py | https://github.com/mwouts/jupytext/blob/eb7d6aee889f80ad779cfc53441c648f0db9246d/jupytext/header.py#L51-L70 | def encoding_and_executable(notebook, metadata, ext):
"""Return encoding and executable lines for a notebook, if applicable"""
lines = []
comment = _SCRIPT_EXTENSIONS.get(ext, {}).get('comment')
jupytext_metadata = metadata.get('jupytext', {})
if ext not in ['.Rmd', '.md'] and 'executable' in jupyt... | [
"def",
"encoding_and_executable",
"(",
"notebook",
",",
"metadata",
",",
"ext",
")",
":",
"lines",
"=",
"[",
"]",
"comment",
"=",
"_SCRIPT_EXTENSIONS",
".",
"get",
"(",
"ext",
",",
"{",
"}",
")",
".",
"get",
"(",
"'comment'",
")",
"jupytext_metadata",
"=... | Return encoding and executable lines for a notebook, if applicable | [
"Return",
"encoding",
"and",
"executable",
"lines",
"for",
"a",
"notebook",
"if",
"applicable"
] | python | train |
chrisspen/dtree | dtree.py | https://github.com/chrisspen/dtree/blob/9e9c9992b22ad9a7e296af7e6837666b05db43ef/dtree.py#L1525-L1533 | def _grow_trees(self):
"""
Adds new trees to the forest according to the specified growth method.
"""
if self.grow_method == GROW_AUTO_INCREMENTAL:
self.tree_kwargs['auto_grow'] = True
while len(self.trees) < self.size:
self.trees.append(Tree(data... | [
"def",
"_grow_trees",
"(",
"self",
")",
":",
"if",
"self",
".",
"grow_method",
"==",
"GROW_AUTO_INCREMENTAL",
":",
"self",
".",
"tree_kwargs",
"[",
"'auto_grow'",
"]",
"=",
"True",
"while",
"len",
"(",
"self",
".",
"trees",
")",
"<",
"self",
".",
"size",... | Adds new trees to the forest according to the specified growth method. | [
"Adds",
"new",
"trees",
"to",
"the",
"forest",
"according",
"to",
"the",
"specified",
"growth",
"method",
"."
] | python | train |
gc3-uzh-ch/elasticluster | elasticluster/providers/gce.py | https://github.com/gc3-uzh-ch/elasticluster/blob/e6345633308c76de13b889417df572815aabe744/elasticluster/providers/gce.py#L684-L694 | def is_instance_running(self, instance_id):
"""Check whether the instance is up and running.
:param str instance_id: instance identifier
:reutrn: True if instance is running, False otherwise
"""
items = self.list_instances(filter=('name eq "%s"' % instance_id))
for item ... | [
"def",
"is_instance_running",
"(",
"self",
",",
"instance_id",
")",
":",
"items",
"=",
"self",
".",
"list_instances",
"(",
"filter",
"=",
"(",
"'name eq \"%s\"'",
"%",
"instance_id",
")",
")",
"for",
"item",
"in",
"items",
":",
"if",
"item",
"[",
"'status'... | Check whether the instance is up and running.
:param str instance_id: instance identifier
:reutrn: True if instance is running, False otherwise | [
"Check",
"whether",
"the",
"instance",
"is",
"up",
"and",
"running",
"."
] | python | train |
limpyd/redis-limpyd | limpyd/collection.py | https://github.com/limpyd/redis-limpyd/blob/3c745dde1390a0bd09690b77a089dcc08c6c7e43/limpyd/collection.py#L436-L442 | def _field_is_pk(self, field_name):
"""Check if the given name is the pk field, suffixed or not with "__eq" """
if self.cls._field_is_pk(field_name):
return True
if field_name.endswith('__eq') and self.cls._field_is_pk(field_name[:-4]):
return True
return False | [
"def",
"_field_is_pk",
"(",
"self",
",",
"field_name",
")",
":",
"if",
"self",
".",
"cls",
".",
"_field_is_pk",
"(",
"field_name",
")",
":",
"return",
"True",
"if",
"field_name",
".",
"endswith",
"(",
"'__eq'",
")",
"and",
"self",
".",
"cls",
".",
"_fi... | Check if the given name is the pk field, suffixed or not with "__eq" | [
"Check",
"if",
"the",
"given",
"name",
"is",
"the",
"pk",
"field",
"suffixed",
"or",
"not",
"with",
"__eq"
] | python | train |
quodlibet/mutagen | mutagen/flac.py | https://github.com/quodlibet/mutagen/blob/e393df5971ba41ba5a50de9c2c9e7e5484d82c4e/mutagen/flac.py#L822-L826 | def clear_pictures(self):
"""Delete all pictures from the file."""
blocks = [b for b in self.metadata_blocks if b.code != Picture.code]
self.metadata_blocks = blocks | [
"def",
"clear_pictures",
"(",
"self",
")",
":",
"blocks",
"=",
"[",
"b",
"for",
"b",
"in",
"self",
".",
"metadata_blocks",
"if",
"b",
".",
"code",
"!=",
"Picture",
".",
"code",
"]",
"self",
".",
"metadata_blocks",
"=",
"blocks"
] | Delete all pictures from the file. | [
"Delete",
"all",
"pictures",
"from",
"the",
"file",
"."
] | python | train |
dmwm/DBS | Server/Python/src/dbs/business/DBSPrimaryDataset.py | https://github.com/dmwm/DBS/blob/9619bafce3783b3e77f0415f8f9a258e33dd1e6f/Server/Python/src/dbs/business/DBSPrimaryDataset.py#L55-L99 | def insertPrimaryDataset(self, businput):
"""
Input dictionary has to have the following keys:
primary_ds_name, primary_ds_type, creation_date, create_by.
it builds the correct dictionary for dao input and executes the dao
"""
conn = self.dbi.connection()
tran = c... | [
"def",
"insertPrimaryDataset",
"(",
"self",
",",
"businput",
")",
":",
"conn",
"=",
"self",
".",
"dbi",
".",
"connection",
"(",
")",
"tran",
"=",
"conn",
".",
"begin",
"(",
")",
"#checking for required fields",
"if",
"\"primary_ds_name\"",
"not",
"in",
"busi... | Input dictionary has to have the following keys:
primary_ds_name, primary_ds_type, creation_date, create_by.
it builds the correct dictionary for dao input and executes the dao | [
"Input",
"dictionary",
"has",
"to",
"have",
"the",
"following",
"keys",
":",
"primary_ds_name",
"primary_ds_type",
"creation_date",
"create_by",
".",
"it",
"builds",
"the",
"correct",
"dictionary",
"for",
"dao",
"input",
"and",
"executes",
"the",
"dao"
] | python | train |
fjwCode/cerium | cerium/androiddriver.py | https://github.com/fjwCode/cerium/blob/f6e06e0dcf83a0bc924828e9d6cb81383ed2364f/cerium/androiddriver.py#L538-L546 | def send_keys(self, text: str = 'cerium') -> None:
'''Simulates typing keys.'''
for char in text:
if '\u4e00' <= char <= '\u9fff':
raise CharactersException(
f'Text cannot contain non-English characters, such as {char!r}.')
text = re.escape(text)
... | [
"def",
"send_keys",
"(",
"self",
",",
"text",
":",
"str",
"=",
"'cerium'",
")",
"->",
"None",
":",
"for",
"char",
"in",
"text",
":",
"if",
"'\\u4e00'",
"<=",
"char",
"<=",
"'\\u9fff'",
":",
"raise",
"CharactersException",
"(",
"f'Text cannot contain non-Engl... | Simulates typing keys. | [
"Simulates",
"typing",
"keys",
"."
] | python | train |
iqbal-lab-org/cluster_vcf_records | cluster_vcf_records/vcf_clusterer.py | https://github.com/iqbal-lab-org/cluster_vcf_records/blob/0db26af36b6da97a7361364457d2152dc756055c/cluster_vcf_records/vcf_clusterer.py#L127-L149 | def _expand_alts_and_remove_duplicates_in_list(cls, vcf_records, ref_seq, indel_gap=100):
'''Input: list of VCF records, all from the same CHROM. ref_seq = sequence
of that CHROM. Expands any record in the list that has >ALT, into
one record per ALT. Removes duplicated records, where REF and ALT... | [
"def",
"_expand_alts_and_remove_duplicates_in_list",
"(",
"cls",
",",
"vcf_records",
",",
"ref_seq",
",",
"indel_gap",
"=",
"100",
")",
":",
"expanded_vcf_records",
"=",
"VcfClusterer",
".",
"_expand_alts_in_vcf_record_list",
"(",
"vcf_records",
")",
"new_vcf_records",
... | Input: list of VCF records, all from the same CHROM. ref_seq = sequence
of that CHROM. Expands any record in the list that has >ALT, into
one record per ALT. Removes duplicated records, where REF and ALT
are the same (at the same position!), or where there is the same
indel more than onc... | [
"Input",
":",
"list",
"of",
"VCF",
"records",
"all",
"from",
"the",
"same",
"CHROM",
".",
"ref_seq",
"=",
"sequence",
"of",
"that",
"CHROM",
".",
"Expands",
"any",
"record",
"in",
"the",
"list",
"that",
"has",
">",
"ALT",
"into",
"one",
"record",
"per"... | python | train |
avalente/appmetrics | appmetrics/statistics.py | https://github.com/avalente/appmetrics/blob/366fc7e1ca897e49a2227cbfa43bfa02a47f1acc/appmetrics/statistics.py#L160-L175 | def counts(data):
"""
Generate a table of sorted (value, frequency) pairs.
"""
if data is None:
raise TypeError('None is not iterable')
table = collections.Counter(data).most_common()
if not table:
return table
# Extract the values with the highest frequency.
maxfreq ... | [
"def",
"counts",
"(",
"data",
")",
":",
"if",
"data",
"is",
"None",
":",
"raise",
"TypeError",
"(",
"'None is not iterable'",
")",
"table",
"=",
"collections",
".",
"Counter",
"(",
"data",
")",
".",
"most_common",
"(",
")",
"if",
"not",
"table",
":",
"... | Generate a table of sorted (value, frequency) pairs. | [
"Generate",
"a",
"table",
"of",
"sorted",
"(",
"value",
"frequency",
")",
"pairs",
"."
] | python | train |
mayfield/shellish | shellish/session.py | https://github.com/mayfield/shellish/blob/df0f0e4612d138c34d8cb99b66ab5b8e47f1414a/shellish/session.py#L241-L249 | def run_loop(self):
""" Main entry point for running in interactive mode. """
self.root_command.prog = ''
history_file = self.load_history()
rendering.vtmlprint(self.intro)
try:
self.loop()
finally:
readline.write_history_file(history_file) | [
"def",
"run_loop",
"(",
"self",
")",
":",
"self",
".",
"root_command",
".",
"prog",
"=",
"''",
"history_file",
"=",
"self",
".",
"load_history",
"(",
")",
"rendering",
".",
"vtmlprint",
"(",
"self",
".",
"intro",
")",
"try",
":",
"self",
".",
"loop",
... | Main entry point for running in interactive mode. | [
"Main",
"entry",
"point",
"for",
"running",
"in",
"interactive",
"mode",
"."
] | python | train |
klahnakoski/mo-logs | mo_logs/strings.py | https://github.com/klahnakoski/mo-logs/blob/0971277ac9caf28a755b766b70621916957d4fea/mo_logs/strings.py#L184-L198 | def tab(value):
"""
convert single value to tab-delimited form, including a header
:param value:
:return:
"""
if is_data(value):
h, d = transpose(*wrap(value).leaves())
return (
"\t".join(map(value2json, h)) +
CR +
"\t".join(map(value2json, d))... | [
"def",
"tab",
"(",
"value",
")",
":",
"if",
"is_data",
"(",
"value",
")",
":",
"h",
",",
"d",
"=",
"transpose",
"(",
"*",
"wrap",
"(",
"value",
")",
".",
"leaves",
"(",
")",
")",
"return",
"(",
"\"\\t\"",
".",
"join",
"(",
"map",
"(",
"value2js... | convert single value to tab-delimited form, including a header
:param value:
:return: | [
"convert",
"single",
"value",
"to",
"tab",
"-",
"delimited",
"form",
"including",
"a",
"header",
":",
"param",
"value",
":",
":",
"return",
":"
] | python | train |
PyFilesystem/pyfilesystem2 | fs/path.py | https://github.com/PyFilesystem/pyfilesystem2/blob/047f3593f297d1442194cda3da7a7335bcc9c14a/fs/path.py#L50-L90 | def normpath(path):
# type: (Text) -> Text
"""Normalize a path.
This function simplifies a path by collapsing back-references
and removing duplicated separators.
Arguments:
path (str): Path to normalize.
Returns:
str: A valid FS path.
Example:
>>> normpath("/foo//... | [
"def",
"normpath",
"(",
"path",
")",
":",
"# type: (Text) -> Text",
"if",
"path",
"in",
"\"/\"",
":",
"return",
"path",
"# An early out if there is no need to normalize this path",
"if",
"not",
"_requires_normalization",
"(",
"path",
")",
":",
"return",
"path",
".",
... | Normalize a path.
This function simplifies a path by collapsing back-references
and removing duplicated separators.
Arguments:
path (str): Path to normalize.
Returns:
str: A valid FS path.
Example:
>>> normpath("/foo//bar/frob/../baz")
'/foo/bar/baz'
>>> n... | [
"Normalize",
"a",
"path",
"."
] | python | train |
ApproxEng/approxeng.input | src/python/approxeng/input/__init__.py | https://github.com/ApproxEng/approxeng.input/blob/0cdf8eed6bfd26ca3b20b4478f352787f60ae8ef/src/python/approxeng/input/__init__.py#L879-L901 | def button_pressed(self, key_code, prefix=None):
"""
Called from the controller classes to update the state of this button manager when a button is pressed.
:internal:
:param key_code:
The code specified when populating Button instances
:param prefix:
Ap... | [
"def",
"button_pressed",
"(",
"self",
",",
"key_code",
",",
"prefix",
"=",
"None",
")",
":",
"if",
"prefix",
"is",
"not",
"None",
":",
"state",
"=",
"self",
".",
"buttons_by_code",
".",
"get",
"(",
"prefix",
"+",
"str",
"(",
"key_code",
")",
")",
"el... | Called from the controller classes to update the state of this button manager when a button is pressed.
:internal:
:param key_code:
The code specified when populating Button instances
:param prefix:
Applied to key code if present | [
"Called",
"from",
"the",
"controller",
"classes",
"to",
"update",
"the",
"state",
"of",
"this",
"button",
"manager",
"when",
"a",
"button",
"is",
"pressed",
"."
] | python | train |
Unity-Technologies/ml-agents | ml-agents/mlagents/trainers/meta_curriculum.py | https://github.com/Unity-Technologies/ml-agents/blob/37d139af636e4a2351751fbf0f2fca5a9ed7457f/ml-agents/mlagents/trainers/meta_curriculum.py#L134-L147 | def get_config(self):
"""Get the combined configuration of all curriculums in this
MetaCurriculum.
Returns:
A dict from parameter to value.
"""
config = {}
for _, curriculum in self.brains_to_curriculums.items():
curr_config = curriculum.get_conf... | [
"def",
"get_config",
"(",
"self",
")",
":",
"config",
"=",
"{",
"}",
"for",
"_",
",",
"curriculum",
"in",
"self",
".",
"brains_to_curriculums",
".",
"items",
"(",
")",
":",
"curr_config",
"=",
"curriculum",
".",
"get_config",
"(",
")",
"config",
".",
"... | Get the combined configuration of all curriculums in this
MetaCurriculum.
Returns:
A dict from parameter to value. | [
"Get",
"the",
"combined",
"configuration",
"of",
"all",
"curriculums",
"in",
"this",
"MetaCurriculum",
"."
] | python | train |
mlperf/training | rnn_translator/pytorch/seq2seq/utils.py | https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/rnn_translator/pytorch/seq2seq/utils.py#L293-L335 | def reduce(self, op):
"""
Reduces average value over all workers.
:param op: 'sum' or 'mean', reduction operator
"""
if op not in ('sum', 'mean'):
raise NotImplementedError
distributed = (get_world_size() > 1)
if distributed:
# Backward/f... | [
"def",
"reduce",
"(",
"self",
",",
"op",
")",
":",
"if",
"op",
"not",
"in",
"(",
"'sum'",
",",
"'mean'",
")",
":",
"raise",
"NotImplementedError",
"distributed",
"=",
"(",
"get_world_size",
"(",
")",
">",
"1",
")",
"if",
"distributed",
":",
"# Backward... | Reduces average value over all workers.
:param op: 'sum' or 'mean', reduction operator | [
"Reduces",
"average",
"value",
"over",
"all",
"workers",
"."
] | python | train |
soravux/scoop | scoop/launcher.py | https://github.com/soravux/scoop/blob/d391dfa62f47e49d48328ee9cf08aa114256fd33/scoop/launcher.py#L138-L149 | def initLogging(self):
"""Configures the logger."""
verbose_levels = {
0: logging.WARNING,
1: logging.INFO,
2: logging.DEBUG,
}
logging.basicConfig(
level=verbose_levels[self.verbose],
format="[%(asctime)-15s] %(module)-9s %(lev... | [
"def",
"initLogging",
"(",
"self",
")",
":",
"verbose_levels",
"=",
"{",
"0",
":",
"logging",
".",
"WARNING",
",",
"1",
":",
"logging",
".",
"INFO",
",",
"2",
":",
"logging",
".",
"DEBUG",
",",
"}",
"logging",
".",
"basicConfig",
"(",
"level",
"=",
... | Configures the logger. | [
"Configures",
"the",
"logger",
"."
] | python | train |
inspirehep/inspire-dojson | inspire_dojson/hep/rules/bd0xx.py | https://github.com/inspirehep/inspire-dojson/blob/17f3789cd3d5ae58efa1190dc0eea9efb9c8ca59/inspire_dojson/hep/rules/bd0xx.py#L429-L431 | def languages2marc(self, key, value):
"""Populate the ``041`` MARC field."""
return {'a': pycountry.languages.get(alpha_2=value).name.lower()} | [
"def",
"languages2marc",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"return",
"{",
"'a'",
":",
"pycountry",
".",
"languages",
".",
"get",
"(",
"alpha_2",
"=",
"value",
")",
".",
"name",
".",
"lower",
"(",
")",
"}"
] | Populate the ``041`` MARC field. | [
"Populate",
"the",
"041",
"MARC",
"field",
"."
] | python | train |
sernst/cauldron | cauldron/session/exposed.py | https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/session/exposed.py#L102-L123 | def stop(self, message: str = None, silent: bool = False):
"""
Stops the execution of the project at the current step immediately
without raising an error. Use this to abort running the project in
situations where some critical branching action should prevent the
project from con... | [
"def",
"stop",
"(",
"self",
",",
"message",
":",
"str",
"=",
"None",
",",
"silent",
":",
"bool",
"=",
"False",
")",
":",
"me",
"=",
"self",
".",
"get_internal_project",
"(",
")",
"if",
"not",
"me",
"or",
"not",
"me",
".",
"current_step",
":",
"retu... | Stops the execution of the project at the current step immediately
without raising an error. Use this to abort running the project in
situations where some critical branching action should prevent the
project from continuing to run.
:param message:
A custom display message t... | [
"Stops",
"the",
"execution",
"of",
"the",
"project",
"at",
"the",
"current",
"step",
"immediately",
"without",
"raising",
"an",
"error",
".",
"Use",
"this",
"to",
"abort",
"running",
"the",
"project",
"in",
"situations",
"where",
"some",
"critical",
"branching... | python | train |
AoiKuiyuyou/AoikLiveReload | tools/waf/aoikwafutil.py | https://github.com/AoiKuiyuyou/AoikLiveReload/blob/0d5adb12118a33749e6690a8165fdb769cff7d5c/tools/waf/aoikwafutil.py#L1066-L1370 | def create_cmd_task(
ctx,
parts,
inputs=None,
outputs=None,
env=None,
cwd=None,
task_name=None,
cache_key=None,
always=False,
add_to_group=True,
):
"""
Create task that runs given command.
:param ctx: BuildContext object.
:param parts: Command parts list.
... | [
"def",
"create_cmd_task",
"(",
"ctx",
",",
"parts",
",",
"inputs",
"=",
"None",
",",
"outputs",
"=",
"None",
",",
"env",
"=",
"None",
",",
"cwd",
"=",
"None",
",",
"task_name",
"=",
"None",
",",
"cache_key",
"=",
"None",
",",
"always",
"=",
"False",
... | Create task that runs given command.
:param ctx: BuildContext object.
:param parts: Command parts list.
Each part can be:
- **None**: Will be ignored.
- **String**: Will be used as-is.
- **Node object**: Will be converted to absolute path.
- **List of t... | [
"Create",
"task",
"that",
"runs",
"given",
"command",
"."
] | python | train |
SeabornGames/Table | seaborn_table/table.py | https://github.com/SeabornGames/Table/blob/0c474ef2fb00db0e7cf47e8af91e3556c2e7485a/seaborn_table/table.py#L554-L575 | def obj_to_mark_down(self, file_path=None, title_columns=False,
quote_numbers=True, quote_empty_str=False):
"""
This will return a str of a mark down table.
:param title_columns: bool if True will title all headers
:param file_path: str of the path to the... | [
"def",
"obj_to_mark_down",
"(",
"self",
",",
"file_path",
"=",
"None",
",",
"title_columns",
"=",
"False",
",",
"quote_numbers",
"=",
"True",
",",
"quote_empty_str",
"=",
"False",
")",
":",
"md",
",",
"column_widths",
"=",
"self",
".",
"get_data_and_shared_col... | This will return a str of a mark down table.
:param title_columns: bool if True will title all headers
:param file_path: str of the path to the file to write to
:param quote_numbers: bool if True will quote numbers that are strings
:param quote_empty_str: bool if True will quot... | [
"This",
"will",
"return",
"a",
"str",
"of",
"a",
"mark",
"down",
"table",
".",
":",
"param",
"title_columns",
":",
"bool",
"if",
"True",
"will",
"title",
"all",
"headers",
":",
"param",
"file_path",
":",
"str",
"of",
"the",
"path",
"to",
"the",
"file",... | python | train |
softlayer/softlayer-python | SoftLayer/CLI/securitygroup/edit.py | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/securitygroup/edit.py#L18-L28 | def cli(env, group_id, name, description):
"""Edit details of a security group."""
mgr = SoftLayer.NetworkManager(env.client)
data = {}
if name:
data['name'] = name
if description:
data['description'] = description
if not mgr.edit_securitygroup(group_id, **data):
raise e... | [
"def",
"cli",
"(",
"env",
",",
"group_id",
",",
"name",
",",
"description",
")",
":",
"mgr",
"=",
"SoftLayer",
".",
"NetworkManager",
"(",
"env",
".",
"client",
")",
"data",
"=",
"{",
"}",
"if",
"name",
":",
"data",
"[",
"'name'",
"]",
"=",
"name",... | Edit details of a security group. | [
"Edit",
"details",
"of",
"a",
"security",
"group",
"."
] | python | train |
RedFantom/ttkwidgets | ttkwidgets/color/colorsquare.py | https://github.com/RedFantom/ttkwidgets/blob/02150322060f867b6e59a175522ef84b09168019/ttkwidgets/color/colorsquare.py#L129-L137 | def _on_move(self, event):
"""Make the cross follow the cursor."""
w = self.winfo_width()
h = self.winfo_height()
x = min(max(event.x, 0), w)
y = min(max(event.y, 0), h)
self.coords('cross_h', 0, y, w, y)
self.coords('cross_v', x, 0, x, h)
self.event_gener... | [
"def",
"_on_move",
"(",
"self",
",",
"event",
")",
":",
"w",
"=",
"self",
".",
"winfo_width",
"(",
")",
"h",
"=",
"self",
".",
"winfo_height",
"(",
")",
"x",
"=",
"min",
"(",
"max",
"(",
"event",
".",
"x",
",",
"0",
")",
",",
"w",
")",
"y",
... | Make the cross follow the cursor. | [
"Make",
"the",
"cross",
"follow",
"the",
"cursor",
"."
] | python | train |
lrq3000/pyFileFixity | pyFileFixity/lib/brownanrs/rs.py | https://github.com/lrq3000/pyFileFixity/blob/fd5ef23bb13835faf1e3baa773619b86a1cc9bdf/pyFileFixity/lib/brownanrs/rs.py#L862-L888 | def _chien_search_faster(self, sigma):
'''Faster chien search, processing only useful coefficients (the ones in the messages) instead of the whole 2^8 range.
Besides the speed boost, this also allows to fix a number of issue: correctly decoding when the last ecc byte is corrupted, and accepting messages... | [
"def",
"_chien_search_faster",
"(",
"self",
",",
"sigma",
")",
":",
"n",
"=",
"self",
".",
"n",
"X",
"=",
"[",
"]",
"j",
"=",
"[",
"]",
"p",
"=",
"GF2int",
"(",
"self",
".",
"generator",
")",
"# Normally we should try all 2^8 possible values, but here we opt... | Faster chien search, processing only useful coefficients (the ones in the messages) instead of the whole 2^8 range.
Besides the speed boost, this also allows to fix a number of issue: correctly decoding when the last ecc byte is corrupted, and accepting messages of length n > 2^8. | [
"Faster",
"chien",
"search",
"processing",
"only",
"useful",
"coefficients",
"(",
"the",
"ones",
"in",
"the",
"messages",
")",
"instead",
"of",
"the",
"whole",
"2^8",
"range",
".",
"Besides",
"the",
"speed",
"boost",
"this",
"also",
"allows",
"to",
"fix",
... | python | train |
instaloader/instaloader | instaloader/instaloader.py | https://github.com/instaloader/instaloader/blob/87d877e650cd8020b04b8b51be120599a441fd5b/instaloader/instaloader.py#L639-L658 | def get_feed_posts(self) -> Iterator[Post]:
"""Get Posts of the user's feed.
:return: Iterator over Posts of the user's feed.
"""
data = self.context.graphql_query("d6f4427fbe92d846298cf93df0b937d3", {})["data"]
while True:
feed = data["user"]["edge_web_feed_timeli... | [
"def",
"get_feed_posts",
"(",
"self",
")",
"->",
"Iterator",
"[",
"Post",
"]",
":",
"data",
"=",
"self",
".",
"context",
".",
"graphql_query",
"(",
"\"d6f4427fbe92d846298cf93df0b937d3\"",
",",
"{",
"}",
")",
"[",
"\"data\"",
"]",
"while",
"True",
":",
"fee... | Get Posts of the user's feed.
:return: Iterator over Posts of the user's feed. | [
"Get",
"Posts",
"of",
"the",
"user",
"s",
"feed",
"."
] | python | train |
gem/oq-engine | openquake/hazardlib/source/rupture.py | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/source/rupture.py#L496-L510 | def get_eids(rup_array, samples_by_grp, num_rlzs_by_grp):
"""
:param rup_array: a composite array with fields serial, n_occ and grp_id
:param samples_by_grp: a dictionary grp_id -> samples
:param num_rlzs_by_grp: a dictionary grp_id -> num_rlzs
"""
all_eids = []
for rup in rup_array:
... | [
"def",
"get_eids",
"(",
"rup_array",
",",
"samples_by_grp",
",",
"num_rlzs_by_grp",
")",
":",
"all_eids",
"=",
"[",
"]",
"for",
"rup",
"in",
"rup_array",
":",
"grp_id",
"=",
"rup",
"[",
"'grp_id'",
"]",
"samples",
"=",
"samples_by_grp",
"[",
"grp_id",
"]",... | :param rup_array: a composite array with fields serial, n_occ and grp_id
:param samples_by_grp: a dictionary grp_id -> samples
:param num_rlzs_by_grp: a dictionary grp_id -> num_rlzs | [
":",
"param",
"rup_array",
":",
"a",
"composite",
"array",
"with",
"fields",
"serial",
"n_occ",
"and",
"grp_id",
":",
"param",
"samples_by_grp",
":",
"a",
"dictionary",
"grp_id",
"-",
">",
"samples",
":",
"param",
"num_rlzs_by_grp",
":",
"a",
"dictionary",
"... | python | train |
quantumlib/Cirq | cirq/sim/density_matrix_utils.py | https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/sim/density_matrix_utils.py#L24-L74 | def to_valid_density_matrix(
density_matrix_rep: Union[int, np.ndarray],
num_qubits: int,
dtype: Type[np.number] = np.complex64) -> np.ndarray:
"""Verifies the density_matrix_rep is valid and converts it to ndarray form.
This method is used to support passing a matrix, a vector (wave function),
... | [
"def",
"to_valid_density_matrix",
"(",
"density_matrix_rep",
":",
"Union",
"[",
"int",
",",
"np",
".",
"ndarray",
"]",
",",
"num_qubits",
":",
"int",
",",
"dtype",
":",
"Type",
"[",
"np",
".",
"number",
"]",
"=",
"np",
".",
"complex64",
")",
"->",
"np"... | Verifies the density_matrix_rep is valid and converts it to ndarray form.
This method is used to support passing a matrix, a vector (wave function),
or a computational basis state as a representation of a state.
Args:
density_matrix_rep: If an numpy array, if it is of rank 2 (a matrix),
... | [
"Verifies",
"the",
"density_matrix_rep",
"is",
"valid",
"and",
"converts",
"it",
"to",
"ndarray",
"form",
"."
] | python | train |
delph-in/pydelphin | delphin/itsdb.py | https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/itsdb.py#L2126-L2179 | def write_profile(self, profile_directory, relations_filename=None,
key_filter=True,
append=False, gzip=None):
"""
Write all tables (as specified by the relations) to a profile.
Args:
profile_directory: The directory of the output profile
... | [
"def",
"write_profile",
"(",
"self",
",",
"profile_directory",
",",
"relations_filename",
"=",
"None",
",",
"key_filter",
"=",
"True",
",",
"append",
"=",
"False",
",",
"gzip",
"=",
"None",
")",
":",
"if",
"relations_filename",
":",
"src_rels",
"=",
"os",
... | Write all tables (as specified by the relations) to a profile.
Args:
profile_directory: The directory of the output profile
relations_filename: If given, read and use the relations
at this path instead of the current profile's
relations
key_fi... | [
"Write",
"all",
"tables",
"(",
"as",
"specified",
"by",
"the",
"relations",
")",
"to",
"a",
"profile",
"."
] | python | train |
phaethon/kamene | kamene/contrib/gsm_um.py | https://github.com/phaethon/kamene/blob/11d4064844f4f68ac5d7546f5633ac7d02082914/kamene/contrib/gsm_um.py#L1344-L1355 | def cmReestablishmentRequest(LocalAreaId_presence=0):
"""CM RE-ESTABLISHMENT REQUEST Section 9.2.4"""
a = TpPd(pd=0x5)
b = MessageType(mesType=0x28) # 00101000
c = CiphKeySeqNrAndSpareHalfOctets()
e = MobileStationClassmark2()
f = MobileId()
if LocalAreaId_presence is 1:
g = LocalAr... | [
"def",
"cmReestablishmentRequest",
"(",
"LocalAreaId_presence",
"=",
"0",
")",
":",
"a",
"=",
"TpPd",
"(",
"pd",
"=",
"0x5",
")",
"b",
"=",
"MessageType",
"(",
"mesType",
"=",
"0x28",
")",
"# 00101000",
"c",
"=",
"CiphKeySeqNrAndSpareHalfOctets",
"(",
")",
... | CM RE-ESTABLISHMENT REQUEST Section 9.2.4 | [
"CM",
"RE",
"-",
"ESTABLISHMENT",
"REQUEST",
"Section",
"9",
".",
"2",
".",
"4"
] | python | train |
edx/edx-enterprise | enterprise/admin/forms.py | https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/admin/forms.py#L388-L398 | def clean(self):
"""
Clean form fields prior to database entry.
In this case, the major cleaning operation is substituting a None value for a blank
value in the Catalog field.
"""
cleaned_data = super(EnterpriseCustomerAdminForm, self).clean()
if 'catalog' in cle... | [
"def",
"clean",
"(",
"self",
")",
":",
"cleaned_data",
"=",
"super",
"(",
"EnterpriseCustomerAdminForm",
",",
"self",
")",
".",
"clean",
"(",
")",
"if",
"'catalog'",
"in",
"cleaned_data",
"and",
"not",
"cleaned_data",
"[",
"'catalog'",
"]",
":",
"cleaned_dat... | Clean form fields prior to database entry.
In this case, the major cleaning operation is substituting a None value for a blank
value in the Catalog field. | [
"Clean",
"form",
"fields",
"prior",
"to",
"database",
"entry",
"."
] | python | valid |
juju/python-libjuju | juju/client/_client8.py | https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/client/_client8.py#L1009-L1024 | async def Set(self, application, options):
'''
application : str
options : typing.Mapping[str, str]
Returns -> None
'''
# map input types to rpc msg
_params = dict()
msg = dict(type='Application',
request='Set',
versio... | [
"async",
"def",
"Set",
"(",
"self",
",",
"application",
",",
"options",
")",
":",
"# map input types to rpc msg",
"_params",
"=",
"dict",
"(",
")",
"msg",
"=",
"dict",
"(",
"type",
"=",
"'Application'",
",",
"request",
"=",
"'Set'",
",",
"version",
"=",
... | application : str
options : typing.Mapping[str, str]
Returns -> None | [
"application",
":",
"str",
"options",
":",
"typing",
".",
"Mapping",
"[",
"str",
"str",
"]",
"Returns",
"-",
">",
"None"
] | python | train |
inveniosoftware/invenio-files-rest | invenio_files_rest/admin.py | https://github.com/inveniosoftware/invenio-files-rest/blob/59a950da61cc8d5882a03c6fde6db2e2ed10befd/invenio_files_rest/admin.py#L209-L227 | def action_verify_checksum(self, ids):
"""Inactivate users."""
try:
count = 0
for file_id in ids:
f = FileInstance.query.filter_by(
id=uuid.UUID(file_id)).one_or_none()
if f is None:
raise ValueError(_("Canno... | [
"def",
"action_verify_checksum",
"(",
"self",
",",
"ids",
")",
":",
"try",
":",
"count",
"=",
"0",
"for",
"file_id",
"in",
"ids",
":",
"f",
"=",
"FileInstance",
".",
"query",
".",
"filter_by",
"(",
"id",
"=",
"uuid",
".",
"UUID",
"(",
"file_id",
")",... | Inactivate users. | [
"Inactivate",
"users",
"."
] | python | train |
bcbio/bcbio-nextgen | bcbio/pipeline/run_info.py | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/run_info.py#L710-L721 | def _check_svcaller(item):
"""Ensure the provide structural variant caller is valid.
"""
allowed = set(reduce(operator.add, [list(d.keys()) for d in structural._CALLERS.values()]) + [None, False])
svs = item["algorithm"].get("svcaller")
if not isinstance(svs, (list, tuple)):
svs = [svs]
... | [
"def",
"_check_svcaller",
"(",
"item",
")",
":",
"allowed",
"=",
"set",
"(",
"reduce",
"(",
"operator",
".",
"add",
",",
"[",
"list",
"(",
"d",
".",
"keys",
"(",
")",
")",
"for",
"d",
"in",
"structural",
".",
"_CALLERS",
".",
"values",
"(",
")",
... | Ensure the provide structural variant caller is valid. | [
"Ensure",
"the",
"provide",
"structural",
"variant",
"caller",
"is",
"valid",
"."
] | python | train |
urinieto/msaf | examples/compute_features.py | https://github.com/urinieto/msaf/blob/9dbb57d77a1310465a65cc40f1641d083ca74385/examples/compute_features.py#L28-L34 | def compute_all_features(file_struct, framesync):
"""Computes all features for the given file."""
for feature_id in msaf.features_registry:
logging.info("Computing %s for file %s" % (feature_id,
file_struct.audio_file))
feats = Features.select_f... | [
"def",
"compute_all_features",
"(",
"file_struct",
",",
"framesync",
")",
":",
"for",
"feature_id",
"in",
"msaf",
".",
"features_registry",
":",
"logging",
".",
"info",
"(",
"\"Computing %s for file %s\"",
"%",
"(",
"feature_id",
",",
"file_struct",
".",
"audio_fi... | Computes all features for the given file. | [
"Computes",
"all",
"features",
"for",
"the",
"given",
"file",
"."
] | python | test |
chrisrink10/basilisp | src/basilisp/lang/reader.py | https://github.com/chrisrink10/basilisp/blob/3d82670ee218ec64eb066289c82766d14d18cc92/src/basilisp/lang/reader.py#L1083-L1101 | def read_file(
filename: str,
resolver: Resolver = None,
data_readers: DataReaders = None,
eof: Any = None,
is_eof_error: bool = False,
) -> Iterable[ReaderForm]:
"""Read the contents of a file as a Lisp expression.
Keyword arguments to this function have the same meanings as those of
b... | [
"def",
"read_file",
"(",
"filename",
":",
"str",
",",
"resolver",
":",
"Resolver",
"=",
"None",
",",
"data_readers",
":",
"DataReaders",
"=",
"None",
",",
"eof",
":",
"Any",
"=",
"None",
",",
"is_eof_error",
":",
"bool",
"=",
"False",
",",
")",
"->",
... | Read the contents of a file as a Lisp expression.
Keyword arguments to this function have the same meanings as those of
basilisp.lang.reader.read. | [
"Read",
"the",
"contents",
"of",
"a",
"file",
"as",
"a",
"Lisp",
"expression",
"."
] | python | test |
gem/oq-engine | openquake/baselib/node.py | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/baselib/node.py#L736-L747 | def node_to_ini(node, output=sys.stdout):
"""
Convert a Node object with the right structure into a .ini file.
:params node: a Node object
:params output: a file-like object opened in write mode
"""
for subnode in node:
output.write(u'\n[%s]\n' % subnode.tag)
for name, value in ... | [
"def",
"node_to_ini",
"(",
"node",
",",
"output",
"=",
"sys",
".",
"stdout",
")",
":",
"for",
"subnode",
"in",
"node",
":",
"output",
".",
"write",
"(",
"u'\\n[%s]\\n'",
"%",
"subnode",
".",
"tag",
")",
"for",
"name",
",",
"value",
"in",
"sorted",
"(... | Convert a Node object with the right structure into a .ini file.
:params node: a Node object
:params output: a file-like object opened in write mode | [
"Convert",
"a",
"Node",
"object",
"with",
"the",
"right",
"structure",
"into",
"a",
".",
"ini",
"file",
"."
] | python | train |
saltstack/salt | salt/modules/splunk_search.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/splunk_search.py#L173-L186 | def delete(name, profile="splunk"):
'''
Delete a splunk search
CLI Example:
splunk_search.delete 'my search name'
'''
client = _get_splunk(profile)
try:
client.saved_searches.delete(name)
return True
except KeyError:
return None | [
"def",
"delete",
"(",
"name",
",",
"profile",
"=",
"\"splunk\"",
")",
":",
"client",
"=",
"_get_splunk",
"(",
"profile",
")",
"try",
":",
"client",
".",
"saved_searches",
".",
"delete",
"(",
"name",
")",
"return",
"True",
"except",
"KeyError",
":",
"retu... | Delete a splunk search
CLI Example:
splunk_search.delete 'my search name' | [
"Delete",
"a",
"splunk",
"search"
] | python | train |
pazz/urwidtrees | docs/examples/example4.filesystem.py | https://github.com/pazz/urwidtrees/blob/d1fa38ce4f37db00bdfc574b856023b5db4c7ead/docs/examples/example4.filesystem.py#L50-L59 | def _list_dir(self, path):
"""returns absolute paths for all entries in a directory"""
try:
elements = [
os.path.join(path, x) for x in os.listdir(path)
] if os.path.isdir(path) else []
elements.sort()
except OSError:
elements = Non... | [
"def",
"_list_dir",
"(",
"self",
",",
"path",
")",
":",
"try",
":",
"elements",
"=",
"[",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"x",
")",
"for",
"x",
"in",
"os",
".",
"listdir",
"(",
"path",
")",
"]",
"if",
"os",
".",
"path",
".",... | returns absolute paths for all entries in a directory | [
"returns",
"absolute",
"paths",
"for",
"all",
"entries",
"in",
"a",
"directory"
] | python | train |
9wfox/tornadoweb | tornadoweb/web.py | https://github.com/9wfox/tornadoweb/blob/2286b66fbe10e4d9f212b979664c15fa17adf378/tornadoweb/web.py#L74-L79 | def render_string(self, template_name, **kwargs):
"""
添加注入模板的自定义参数等信息
"""
if hasattr(self, "session"): kwargs["session"] = self.session
return super(BaseHandler, self).render_string(template_name, **kwargs) | [
"def",
"render_string",
"(",
"self",
",",
"template_name",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"\"session\"",
")",
":",
"kwargs",
"[",
"\"session\"",
"]",
"=",
"self",
".",
"session",
"return",
"super",
"(",
"BaseHandler... | 添加注入模板的自定义参数等信息 | [
"添加注入模板的自定义参数等信息"
] | python | train |
matthew-brett/delocate | delocate/libsana.py | https://github.com/matthew-brett/delocate/blob/ed48de15fce31c3f52f1a9f32cae1b02fc55aa60/delocate/libsana.py#L107-L124 | def get_prefix_stripper(strip_prefix):
""" Return function to strip `strip_prefix` prefix from string if present
Parameters
----------
prefix : str
Prefix to strip from the beginning of string if present
Returns
-------
stripper : func
function such that ``stripper(a_string... | [
"def",
"get_prefix_stripper",
"(",
"strip_prefix",
")",
":",
"n",
"=",
"len",
"(",
"strip_prefix",
")",
"def",
"stripper",
"(",
"path",
")",
":",
"return",
"path",
"if",
"not",
"path",
".",
"startswith",
"(",
"strip_prefix",
")",
"else",
"path",
"[",
"n"... | Return function to strip `strip_prefix` prefix from string if present
Parameters
----------
prefix : str
Prefix to strip from the beginning of string if present
Returns
-------
stripper : func
function such that ``stripper(a_string)`` will strip `prefix` from
``a_string... | [
"Return",
"function",
"to",
"strip",
"strip_prefix",
"prefix",
"from",
"string",
"if",
"present"
] | python | train |
gem/oq-engine | openquake/hmtk/seismicity/selector.py | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/seismicity/selector.py#L63-L89 | def _check_depth_limits(input_dict):
'''Returns the default upper and lower depth values if not in dictionary
:param input_dict:
Dictionary corresponding to the kwargs dictionary of calling function
:returns:
'upper_depth': Upper seismogenic depth (float)
'lower_depth': Lower seism... | [
"def",
"_check_depth_limits",
"(",
"input_dict",
")",
":",
"if",
"(",
"'upper_depth'",
"in",
"input_dict",
".",
"keys",
"(",
")",
")",
"and",
"input_dict",
"[",
"'upper_depth'",
"]",
":",
"if",
"input_dict",
"[",
"'upper_depth'",
"]",
"<",
"0.",
":",
"rais... | Returns the default upper and lower depth values if not in dictionary
:param input_dict:
Dictionary corresponding to the kwargs dictionary of calling function
:returns:
'upper_depth': Upper seismogenic depth (float)
'lower_depth': Lower seismogenic depth (float) | [
"Returns",
"the",
"default",
"upper",
"and",
"lower",
"depth",
"values",
"if",
"not",
"in",
"dictionary"
] | python | train |
AndrewAnnex/SpiceyPy | spiceypy/spiceypy.py | https://github.com/AndrewAnnex/SpiceyPy/blob/fc20a9b9de68b58eed5b332f0c051fb343a6e335/spiceypy/spiceypy.py#L11863-L11894 | def spkez(targ, et, ref, abcorr, obs):
"""
Return the state (position and velocity) of a target body
relative to an observing body, optionally corrected for light
time (planetary aberration) and stellar aberration.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/spkez_c.html
:param tar... | [
"def",
"spkez",
"(",
"targ",
",",
"et",
",",
"ref",
",",
"abcorr",
",",
"obs",
")",
":",
"targ",
"=",
"ctypes",
".",
"c_int",
"(",
"targ",
")",
"et",
"=",
"ctypes",
".",
"c_double",
"(",
"et",
")",
"ref",
"=",
"stypes",
".",
"stringToCharP",
"(",... | Return the state (position and velocity) of a target body
relative to an observing body, optionally corrected for light
time (planetary aberration) and stellar aberration.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/spkez_c.html
:param targ: Target body.
:type targ: int
:param et: ... | [
"Return",
"the",
"state",
"(",
"position",
"and",
"velocity",
")",
"of",
"a",
"target",
"body",
"relative",
"to",
"an",
"observing",
"body",
"optionally",
"corrected",
"for",
"light",
"time",
"(",
"planetary",
"aberration",
")",
"and",
"stellar",
"aberration",... | python | train |
readbeyond/aeneas | aeneas/tools/execute_task.py | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/tools/execute_task.py#L443-L680 | def perform_command(self):
"""
Perform command and return the appropriate exit code.
:rtype: int
"""
if len(self.actual_arguments) < 1:
return self.print_help()
if self.has_option([u"-e", u"--examples"]):
return self.print_examples(False)
... | [
"def",
"perform_command",
"(",
"self",
")",
":",
"if",
"len",
"(",
"self",
".",
"actual_arguments",
")",
"<",
"1",
":",
"return",
"self",
".",
"print_help",
"(",
")",
"if",
"self",
".",
"has_option",
"(",
"[",
"u\"-e\"",
",",
"u\"--examples\"",
"]",
")... | Perform command and return the appropriate exit code.
:rtype: int | [
"Perform",
"command",
"and",
"return",
"the",
"appropriate",
"exit",
"code",
"."
] | python | train |
trevisanj/a99 | a99/gui/xmisc.py | https://github.com/trevisanj/a99/blob/193e6e3c9b3e4f4a0ba7eb3eece846fe7045c539/a99/gui/xmisc.py#L275-L294 | def get_matplotlib_layout(widget, flag_toolbar=True):
"""
Creates figure, toolbar, layout, sets widget layout
Returns figure, canvas, layout
Reference: http://stackoverflow.com/questions/12459811
"""
fig = plt.figure()
canvas = FigureCanvas(fig)
# self.canvas.mpl_con... | [
"def",
"get_matplotlib_layout",
"(",
"widget",
",",
"flag_toolbar",
"=",
"True",
")",
":",
"fig",
"=",
"plt",
".",
"figure",
"(",
")",
"canvas",
"=",
"FigureCanvas",
"(",
"fig",
")",
"# self.canvas.mpl_connect('button_press_event', self.on_plot_click)\r",
"layo... | Creates figure, toolbar, layout, sets widget layout
Returns figure, canvas, layout
Reference: http://stackoverflow.com/questions/12459811 | [
"Creates",
"figure",
"toolbar",
"layout",
"sets",
"widget",
"layout",
"Returns",
"figure",
"canvas",
"layout",
"Reference",
":",
"http",
":",
"//",
"stackoverflow",
".",
"com",
"/",
"questions",
"/",
"12459811"
] | python | train |
pypa/twine | twine/package.py | https://github.com/pypa/twine/blob/c854b2a7b451bf13878f709900261dbcbaf59ca0/twine/package.py#L223-L229 | def hash(self):
"""Hash the file contents."""
with open(self.filename, "rb") as fp:
for content in iter(lambda: fp.read(io.DEFAULT_BUFFER_SIZE), b''):
self._md5_update(content)
self._sha2_update(content)
self._blake_update(content) | [
"def",
"hash",
"(",
"self",
")",
":",
"with",
"open",
"(",
"self",
".",
"filename",
",",
"\"rb\"",
")",
"as",
"fp",
":",
"for",
"content",
"in",
"iter",
"(",
"lambda",
":",
"fp",
".",
"read",
"(",
"io",
".",
"DEFAULT_BUFFER_SIZE",
")",
",",
"b''",
... | Hash the file contents. | [
"Hash",
"the",
"file",
"contents",
"."
] | python | train |
thumbor/thumbor | thumbor/server.py | https://github.com/thumbor/thumbor/blob/558ccdd6e3bc29e1c9ee3687372c4b3eb05ac607/thumbor/server.py#L132-L150 | def main(arguments=None):
'''Runs thumbor server with the specified arguments.'''
if arguments is None:
arguments = sys.argv[1:]
server_parameters = get_server_parameters(arguments)
config = get_config(server_parameters.config_path, server_parameters.use_environment)
configure_log(config, s... | [
"def",
"main",
"(",
"arguments",
"=",
"None",
")",
":",
"if",
"arguments",
"is",
"None",
":",
"arguments",
"=",
"sys",
".",
"argv",
"[",
"1",
":",
"]",
"server_parameters",
"=",
"get_server_parameters",
"(",
"arguments",
")",
"config",
"=",
"get_config",
... | Runs thumbor server with the specified arguments. | [
"Runs",
"thumbor",
"server",
"with",
"the",
"specified",
"arguments",
"."
] | python | train |
Zsailer/phylopandas | phylopandas/treeio/write.py | https://github.com/Zsailer/phylopandas/blob/f163c4a2b9369eb32f6c8f3793f711f6fe4e6130/phylopandas/treeio/write.py#L31-L126 | def _pandas_df_to_dendropy_tree(
df,
taxon_col='uid',
taxon_annotations=[],
node_col='uid',
node_annotations=[],
branch_lengths=True,
):
"""Turn a phylopandas dataframe into a dendropy tree.
Parameters
----------
df : DataFrame
DataFrame containing tree data.
ta... | [
"def",
"_pandas_df_to_dendropy_tree",
"(",
"df",
",",
"taxon_col",
"=",
"'uid'",
",",
"taxon_annotations",
"=",
"[",
"]",
",",
"node_col",
"=",
"'uid'",
",",
"node_annotations",
"=",
"[",
"]",
",",
"branch_lengths",
"=",
"True",
",",
")",
":",
"if",
"isins... | Turn a phylopandas dataframe into a dendropy tree.
Parameters
----------
df : DataFrame
DataFrame containing tree data.
taxon_col : str (optional)
Column in dataframe to label the taxon. If None, the index will be used.
taxon_annotations : str
List of columns to annotation... | [
"Turn",
"a",
"phylopandas",
"dataframe",
"into",
"a",
"dendropy",
"tree",
"."
] | python | train |
SoftwareDefinedBuildings/XBOS | apps/Data_quality_analysis/Wrapper.py | https://github.com/SoftwareDefinedBuildings/XBOS/blob/c12d4fb14518ea3ae98c471c28e0710fdf74dd25/apps/Data_quality_analysis/Wrapper.py#L439-L543 | def clean_data(self, data, rename_col=None, drop_col=None,
resample=True, freq='h', resampler='mean',
interpolate=True, limit=1, method='linear',
remove_na=True, remove_na_how='any',
remove_outliers=True, sd_val=3,
remov... | [
"def",
"clean_data",
"(",
"self",
",",
"data",
",",
"rename_col",
"=",
"None",
",",
"drop_col",
"=",
"None",
",",
"resample",
"=",
"True",
",",
"freq",
"=",
"'h'",
",",
"resampler",
"=",
"'mean'",
",",
"interpolate",
"=",
"True",
",",
"limit",
"=",
"... | Cleans dataframe according to user specifications and stores result in self.cleaned_data.
Parameters
----------
data : pd.DataFrame()
Dataframe to be cleaned.
rename_col : list(str)
List of new column names.
drop_col ... | [
"Cleans",
"dataframe",
"according",
"to",
"user",
"specifications",
"and",
"stores",
"result",
"in",
"self",
".",
"cleaned_data",
"."
] | python | train |
persephone-tools/persephone | persephone/corpus.py | https://github.com/persephone-tools/persephone/blob/f94c63e4d5fe719fb1deba449b177bb299d225fb/persephone/corpus.py#L357-L366 | def initialize_labels(self, labels: Set[str]) -> Tuple[dict, dict]:
"""Create mappings from label to index and index to label"""
logger.debug("Creating mappings for labels")
label_to_index = {label: index for index, label in enumerate(
["pad"] + sorted(list(labe... | [
"def",
"initialize_labels",
"(",
"self",
",",
"labels",
":",
"Set",
"[",
"str",
"]",
")",
"->",
"Tuple",
"[",
"dict",
",",
"dict",
"]",
":",
"logger",
".",
"debug",
"(",
"\"Creating mappings for labels\"",
")",
"label_to_index",
"=",
"{",
"label",
":",
"... | Create mappings from label to index and index to label | [
"Create",
"mappings",
"from",
"label",
"to",
"index",
"and",
"index",
"to",
"label"
] | python | train |
mbj4668/pyang | pyang/statements.py | https://github.com/mbj4668/pyang/blob/f2a5cc3142162e5b9ee4e18d154568d939ff63dd/pyang/statements.py#L3171-L3190 | def get_qualified_type(stmt):
"""Gets the qualified, top-level type of the node.
This enters the typedef if defined instead of using the prefix
to ensure absolute distinction.
"""
type_obj = stmt.search_one('type')
fq_type_name = None
if type_obj:
if getattr(type_obj, 'i_typedef', No... | [
"def",
"get_qualified_type",
"(",
"stmt",
")",
":",
"type_obj",
"=",
"stmt",
".",
"search_one",
"(",
"'type'",
")",
"fq_type_name",
"=",
"None",
"if",
"type_obj",
":",
"if",
"getattr",
"(",
"type_obj",
",",
"'i_typedef'",
",",
"None",
")",
":",
"# If type_... | Gets the qualified, top-level type of the node.
This enters the typedef if defined instead of using the prefix
to ensure absolute distinction. | [
"Gets",
"the",
"qualified",
"top",
"-",
"level",
"type",
"of",
"the",
"node",
".",
"This",
"enters",
"the",
"typedef",
"if",
"defined",
"instead",
"of",
"using",
"the",
"prefix",
"to",
"ensure",
"absolute",
"distinction",
"."
] | python | train |
pbrisk/mathtoolspy | mathtoolspy/distribution/normal_distribution.py | https://github.com/pbrisk/mathtoolspy/blob/d0d35b45d20f346ba8a755e53ed0aa182fab43dd/mathtoolspy/distribution/normal_distribution.py#L30-L58 | def cdf_abramowitz_stegun(x):
"""
The cumulative distribution function of the standard normal distribution.
The standard implementation, following Abramowitz/Stegun, (26.2.17).
"""
if x >= 0:
# if x > 7.0:
# return 1 - ONE_OVER_SQRT_OF_TWO_PI * exp(-0.5*x*x)/sqrt(1.0+x*x)
... | [
"def",
"cdf_abramowitz_stegun",
"(",
"x",
")",
":",
"if",
"x",
">=",
"0",
":",
"# if x > 7.0:",
"# return 1 - ONE_OVER_SQRT_OF_TWO_PI * exp(-0.5*x*x)/sqrt(1.0+x*x)",
"result",
"=",
"1.0",
"/",
"(",
"1.0",
"+",
"0.2316419",
"*",
"x",
")",
"ret",
"=",
"1.0",
"-... | The cumulative distribution function of the standard normal distribution.
The standard implementation, following Abramowitz/Stegun, (26.2.17). | [
"The",
"cumulative",
"distribution",
"function",
"of",
"the",
"standard",
"normal",
"distribution",
".",
"The",
"standard",
"implementation",
"following",
"Abramowitz",
"/",
"Stegun",
"(",
"26",
".",
"2",
".",
"17",
")",
"."
] | python | train |
jlmadurga/permabots | permabots/views/api/state.py | https://github.com/jlmadurga/permabots/blob/781a91702529a23fe7bc2aa84c5d88e961412466/permabots/views/api/state.py#L259-L270 | def post(self, request, bot_id, format=None):
"""
Add a new chat state
---
serializer: KikChatStateSerializer
responseMessages:
- code: 401
message: Not authenticated
- code: 400
message: Not valid request
"""
re... | [
"def",
"post",
"(",
"self",
",",
"request",
",",
"bot_id",
",",
"format",
"=",
"None",
")",
":",
"return",
"super",
"(",
"KikChatStateList",
",",
"self",
")",
".",
"post",
"(",
"request",
",",
"bot_id",
",",
"format",
")"
] | Add a new chat state
---
serializer: KikChatStateSerializer
responseMessages:
- code: 401
message: Not authenticated
- code: 400
message: Not valid request | [
"Add",
"a",
"new",
"chat",
"state",
"---",
"serializer",
":",
"KikChatStateSerializer",
"responseMessages",
":",
"-",
"code",
":",
"401",
"message",
":",
"Not",
"authenticated",
"-",
"code",
":",
"400",
"message",
":",
"Not",
"valid",
"request"
] | python | train |
victorlei/smop | smop/parse.py | https://github.com/victorlei/smop/blob/bdad96b715d1dd75ce8ab4724f76b9b1bb1f61cd/smop/parse.py#L592-L602 | def p_if_stmt(p):
"""
if_stmt : IF expr sep stmt_list_opt elseif_stmt END_STMT
| IF LPAREN expr RPAREN stmt_list_opt elseif_stmt END_STMT
"""
if len(p) == 7:
p[0] = node.if_stmt(cond_expr=p[2], then_stmt=p[4], else_stmt=p[5])
elif len(p) == 8:
p[0] = node.if_stmt(cond_exp... | [
"def",
"p_if_stmt",
"(",
"p",
")",
":",
"if",
"len",
"(",
"p",
")",
"==",
"7",
":",
"p",
"[",
"0",
"]",
"=",
"node",
".",
"if_stmt",
"(",
"cond_expr",
"=",
"p",
"[",
"2",
"]",
",",
"then_stmt",
"=",
"p",
"[",
"4",
"]",
",",
"else_stmt",
"="... | if_stmt : IF expr sep stmt_list_opt elseif_stmt END_STMT
| IF LPAREN expr RPAREN stmt_list_opt elseif_stmt END_STMT | [
"if_stmt",
":",
"IF",
"expr",
"sep",
"stmt_list_opt",
"elseif_stmt",
"END_STMT",
"|",
"IF",
"LPAREN",
"expr",
"RPAREN",
"stmt_list_opt",
"elseif_stmt",
"END_STMT"
] | python | train |
hollenstein/maspy | maspy/_proteindb_refactoring.py | https://github.com/hollenstein/maspy/blob/f15fcfd24df306d8420540460d902aa3073ec133/maspy/_proteindb_refactoring.py#L496-L509 | def _idFromHeaderInfo(headerInfo, isDecoy, decoyTag):
"""Generates a protein id from headerInfo. If "isDecoy" is True, the
"decoyTag" is added to beginning of the generated protein id.
:param headerInfo: dict, must contain a key "id"
:param isDecoy: bool, determines if the "decoyTag" is added or not.
... | [
"def",
"_idFromHeaderInfo",
"(",
"headerInfo",
",",
"isDecoy",
",",
"decoyTag",
")",
":",
"proteinId",
"=",
"headerInfo",
"[",
"'id'",
"]",
"if",
"isDecoy",
":",
"proteinId",
"=",
"''",
".",
"join",
"(",
"(",
"decoyTag",
",",
"proteinId",
")",
")",
"retu... | Generates a protein id from headerInfo. If "isDecoy" is True, the
"decoyTag" is added to beginning of the generated protein id.
:param headerInfo: dict, must contain a key "id"
:param isDecoy: bool, determines if the "decoyTag" is added or not.
:param decoyTag: str, a tag that identifies decoy / revers... | [
"Generates",
"a",
"protein",
"id",
"from",
"headerInfo",
".",
"If",
"isDecoy",
"is",
"True",
"the",
"decoyTag",
"is",
"added",
"to",
"beginning",
"of",
"the",
"generated",
"protein",
"id",
"."
] | python | train |
craffel/mir_eval | mir_eval/separation.py | https://github.com/craffel/mir_eval/blob/f41c8dafaea04b411252a516d1965af43c7d531b/mir_eval/separation.py#L130-L241 | def bss_eval_sources(reference_sources, estimated_sources,
compute_permutation=True):
"""
Ordering and measurement of the separation quality for estimated source
signals in terms of filtered true source, interference and artifacts.
The decomposition allows a time-invariant filter d... | [
"def",
"bss_eval_sources",
"(",
"reference_sources",
",",
"estimated_sources",
",",
"compute_permutation",
"=",
"True",
")",
":",
"# make sure the input is of shape (nsrc, nsampl)",
"if",
"estimated_sources",
".",
"ndim",
"==",
"1",
":",
"estimated_sources",
"=",
"estimat... | Ordering and measurement of the separation quality for estimated source
signals in terms of filtered true source, interference and artifacts.
The decomposition allows a time-invariant filter distortion of length
512, as described in Section III.B of [#vincent2006performance]_.
Passing ``False`` for ``... | [
"Ordering",
"and",
"measurement",
"of",
"the",
"separation",
"quality",
"for",
"estimated",
"source",
"signals",
"in",
"terms",
"of",
"filtered",
"true",
"source",
"interference",
"and",
"artifacts",
"."
] | python | train |
vertexproject/synapse | synapse/lib/certdir.py | https://github.com/vertexproject/synapse/blob/22e67c5a8f6d7caddbcf34b39ab1bd2d6c4a6e0b/synapse/lib/certdir.py#L207-L244 | def genClientCert(self, name, outp=None):
'''
Generates a user PKCS #12 archive.
Please note that the resulting file will contain private key material.
Args:
name (str): The name of the user keypair.
outp (synapse.lib.output.Output): The output buffer.
E... | [
"def",
"genClientCert",
"(",
"self",
",",
"name",
",",
"outp",
"=",
"None",
")",
":",
"ucert",
"=",
"self",
".",
"getUserCert",
"(",
"name",
")",
"if",
"not",
"ucert",
":",
"raise",
"s_exc",
".",
"NoSuchFile",
"(",
"'missing User cert'",
")",
"cacert",
... | Generates a user PKCS #12 archive.
Please note that the resulting file will contain private key material.
Args:
name (str): The name of the user keypair.
outp (synapse.lib.output.Output): The output buffer.
Examples:
Make the PKC12 object for user "myuser":
... | [
"Generates",
"a",
"user",
"PKCS",
"#12",
"archive",
".",
"Please",
"note",
"that",
"the",
"resulting",
"file",
"will",
"contain",
"private",
"key",
"material",
"."
] | python | train |
gwastro/pycbc | pycbc/distributions/arbitrary.py | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/distributions/arbitrary.py#L85-L122 | def _pdf(self, **kwargs):
"""Returns the pdf at the given values. The keyword arguments must
contain all of parameters in self's params. Unrecognized arguments are
ignored.
"""
for p in self._params:
if p not in kwargs.keys():
raise ValueError('Missing... | [
"def",
"_pdf",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"p",
"in",
"self",
".",
"_params",
":",
"if",
"p",
"not",
"in",
"kwargs",
".",
"keys",
"(",
")",
":",
"raise",
"ValueError",
"(",
"'Missing parameter {} to construct pdf.'",
".",
"fo... | Returns the pdf at the given values. The keyword arguments must
contain all of parameters in self's params. Unrecognized arguments are
ignored. | [
"Returns",
"the",
"pdf",
"at",
"the",
"given",
"values",
".",
"The",
"keyword",
"arguments",
"must",
"contain",
"all",
"of",
"parameters",
"in",
"self",
"s",
"params",
".",
"Unrecognized",
"arguments",
"are",
"ignored",
"."
] | python | train |
KnuVerse/knuverse-sdk-python | knuverse/knufactor.py | https://github.com/KnuVerse/knuverse-sdk-python/blob/00f1275a452a4dcf9bc92ef345f6985504226d8e/knuverse/knufactor.py#L675-L700 | def settings_module_update(self,
mode_audiopin_enable=None,
mode_audiopass_enable=None,
mode_default=None):
"""
Set Module settings. Uses PUT to /settings/modules interface.
:Args:
* *mode_audiopin_en... | [
"def",
"settings_module_update",
"(",
"self",
",",
"mode_audiopin_enable",
"=",
"None",
",",
"mode_audiopass_enable",
"=",
"None",
",",
"mode_default",
"=",
"None",
")",
":",
"body",
"=",
"{",
"\"auth_password\"",
":",
"self",
".",
"_password",
"}",
"if",
"mod... | Set Module settings. Uses PUT to /settings/modules interface.
:Args:
* *mode_audiopin_enable*: (bool) Turn on and off the AudioPIN feature
* *mode_audiopass_enable*: (bool) Turn on and off the AudioPass feature
* *mode_default*: (str) Set the default verification mode. Either '... | [
"Set",
"Module",
"settings",
".",
"Uses",
"PUT",
"to",
"/",
"settings",
"/",
"modules",
"interface",
"."
] | python | train |
saltstack/salt | salt/modules/osquery.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/osquery.py#L224-L236 | def apt_sources(attrs=None, where=None):
'''
Return apt_sources information from osquery
CLI Example:
.. code-block:: bash
salt '*' osquery.apt_sources
'''
if __grains__['os_family'] == 'Debian':
return _osquery_cmd(table='apt_sources', attrs=attrs, where=where)
return {'r... | [
"def",
"apt_sources",
"(",
"attrs",
"=",
"None",
",",
"where",
"=",
"None",
")",
":",
"if",
"__grains__",
"[",
"'os_family'",
"]",
"==",
"'Debian'",
":",
"return",
"_osquery_cmd",
"(",
"table",
"=",
"'apt_sources'",
",",
"attrs",
"=",
"attrs",
",",
"wher... | Return apt_sources information from osquery
CLI Example:
.. code-block:: bash
salt '*' osquery.apt_sources | [
"Return",
"apt_sources",
"information",
"from",
"osquery"
] | python | train |
google/grr | appveyor/windows_templates/build_windows_templates.py | https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/appveyor/windows_templates/build_windows_templates.py#L250-L282 | def _RepackTemplates(self):
"""Repack templates with a dummy config."""
dummy_config = os.path.join(
args.grr_src, "grr/test/grr_response_test/test_data/dummyconfig.yaml")
if args.build_32:
template_i386 = glob.glob(os.path.join(args.output_dir,
"*_... | [
"def",
"_RepackTemplates",
"(",
"self",
")",
":",
"dummy_config",
"=",
"os",
".",
"path",
".",
"join",
"(",
"args",
".",
"grr_src",
",",
"\"grr/test/grr_response_test/test_data/dummyconfig.yaml\"",
")",
"if",
"args",
".",
"build_32",
":",
"template_i386",
"=",
"... | Repack templates with a dummy config. | [
"Repack",
"templates",
"with",
"a",
"dummy",
"config",
"."
] | python | train |
jxtech/wechatpy | wechatpy/enterprise/client/api/chat.py | https://github.com/jxtech/wechatpy/blob/4df0da795618c0895a10f1c2cde9e9d5c0a93aaa/wechatpy/enterprise/client/api/chat.py#L220-L229 | def send_group_image(self, sender, receiver, media_id):
"""
发送群聊图片消息
:param sender: 发送人
:param receiver: 会话 ID
:param media_id: 图片媒体文件id,可以调用上传素材文件接口获取
:return: 返回的 JSON 数据包
"""
return self.send_image(sender, 'group', receiver, media_id) | [
"def",
"send_group_image",
"(",
"self",
",",
"sender",
",",
"receiver",
",",
"media_id",
")",
":",
"return",
"self",
".",
"send_image",
"(",
"sender",
",",
"'group'",
",",
"receiver",
",",
"media_id",
")"
] | 发送群聊图片消息
:param sender: 发送人
:param receiver: 会话 ID
:param media_id: 图片媒体文件id,可以调用上传素材文件接口获取
:return: 返回的 JSON 数据包 | [
"发送群聊图片消息"
] | python | train |
nuSTORM/gnomon | gnomon/Graph.py | https://github.com/nuSTORM/gnomon/blob/7616486ecd6e26b76f677c380e62db1c0ade558a/gnomon/Graph.py#L71-L82 | def GetFarthestNode(self, gr, node):
"""node is start node"""
# Remember: weights are negative
distance = minmax.shortest_path_bellman_ford(gr, node)[1]
# Find the farthest node, which is end of track
min_key = None
for key, value in distance.iteritems():
if ... | [
"def",
"GetFarthestNode",
"(",
"self",
",",
"gr",
",",
"node",
")",
":",
"# Remember: weights are negative",
"distance",
"=",
"minmax",
".",
"shortest_path_bellman_ford",
"(",
"gr",
",",
"node",
")",
"[",
"1",
"]",
"# Find the farthest node, which is end of track",
... | node is start node | [
"node",
"is",
"start",
"node"
] | python | train |
annoviko/pyclustering | pyclustering/cluster/rock.py | https://github.com/annoviko/pyclustering/blob/98aa0dd89fd36f701668fb1eb29c8fb5662bf7d0/pyclustering/cluster/rock.py#L152-L174 | def __find_pair_clusters(self, clusters):
"""!
@brief Returns pair of clusters that are best candidates for merging in line with goodness measure.
The pair of clusters for which the above goodness measure is maximum is the best pair of clusters to be merged.
@... | [
"def",
"__find_pair_clusters",
"(",
"self",
",",
"clusters",
")",
":",
"maximum_goodness",
"=",
"0.0",
"cluster_indexes",
"=",
"[",
"-",
"1",
",",
"-",
"1",
"]",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"clusters",
")",
")",
":",
"for",
... | !
@brief Returns pair of clusters that are best candidates for merging in line with goodness measure.
The pair of clusters for which the above goodness measure is maximum is the best pair of clusters to be merged.
@param[in] clusters (list): List of clusters that have ... | [
"!"
] | python | valid |
nerdvegas/rez | src/rez/package_repository.py | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/package_repository.py#L455-L459 | def clear_caches(self):
"""Clear all cached data."""
self.get_repository.cache_clear()
self._get_repository.cache_clear()
self.pool.clear_caches() | [
"def",
"clear_caches",
"(",
"self",
")",
":",
"self",
".",
"get_repository",
".",
"cache_clear",
"(",
")",
"self",
".",
"_get_repository",
".",
"cache_clear",
"(",
")",
"self",
".",
"pool",
".",
"clear_caches",
"(",
")"
] | Clear all cached data. | [
"Clear",
"all",
"cached",
"data",
"."
] | python | train |
mosesschwartz/scrypture | scrypture/scrypture.py | https://github.com/mosesschwartz/scrypture/blob/d51eb0c9835a5122a655078268185ce8ab9ec86a/scrypture/scrypture.py#L113-L122 | def script_input(module_name):
'''Render a module's input page. Forms are created based on objects in
the module's WebAPI class.'''
if module_name not in registered_modules:
return page_not_found(module_name)
form = registered_modules[module_name].WebAPI()
return render_template('script_inde... | [
"def",
"script_input",
"(",
"module_name",
")",
":",
"if",
"module_name",
"not",
"in",
"registered_modules",
":",
"return",
"page_not_found",
"(",
"module_name",
")",
"form",
"=",
"registered_modules",
"[",
"module_name",
"]",
".",
"WebAPI",
"(",
")",
"return",
... | Render a module's input page. Forms are created based on objects in
the module's WebAPI class. | [
"Render",
"a",
"module",
"s",
"input",
"page",
".",
"Forms",
"are",
"created",
"based",
"on",
"objects",
"in",
"the",
"module",
"s",
"WebAPI",
"class",
"."
] | python | train |
KelSolaar/Umbra | umbra/ui/widgets/application_QToolBar.py | https://github.com/KelSolaar/Umbra/blob/66f45f08d9d723787f1191989f8b0dda84b412ce/umbra/ui/widgets/application_QToolBar.py#L363-L390 | def set_toolbar_children_widgets(self):
"""
Sets the toolBar children widgets.
:return: Method success.
:rtype: bool
"""
LOGGER.debug("> Adding 'Application_Logo_label' widget!")
self.addWidget(self.get_application_logo_label())
LOGGER.debug("> Adding '... | [
"def",
"set_toolbar_children_widgets",
"(",
"self",
")",
":",
"LOGGER",
".",
"debug",
"(",
"\"> Adding 'Application_Logo_label' widget!\"",
")",
"self",
".",
"addWidget",
"(",
"self",
".",
"get_application_logo_label",
"(",
")",
")",
"LOGGER",
".",
"debug",
"(",
"... | Sets the toolBar children widgets.
:return: Method success.
:rtype: bool | [
"Sets",
"the",
"toolBar",
"children",
"widgets",
"."
] | python | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.