repo
stringlengths
7
55
path
stringlengths
4
223
url
stringlengths
87
315
code
stringlengths
75
104k
code_tokens
list
docstring
stringlengths
1
46.9k
docstring_tokens
list
language
stringclasses
1 value
partition
stringclasses
3 values
avg_line_len
float64
7.91
980
jay-johnson/spylunking
spylunking/splunk_publisher.py
https://github.com/jay-johnson/spylunking/blob/95cc86776f04ec5935cf04e291cf18798345d6cb/spylunking/splunk_publisher.py#L349-L368
def start_worker_thread( self, sleep_interval=1.0): """start_worker_thread Start the helper worker thread to publish queued messages to Splunk :param sleep_interval: sleep in seconds before reading from the queue again """ ...
[ "def", "start_worker_thread", "(", "self", ",", "sleep_interval", "=", "1.0", ")", ":", "# Start a worker thread responsible for sending logs", "if", "self", ".", "sleep_interval", ">", "0", ":", "self", ".", "debug_log", "(", "'starting worker thread'", ")", "self", ...
start_worker_thread Start the helper worker thread to publish queued messages to Splunk :param sleep_interval: sleep in seconds before reading from the queue again
[ "start_worker_thread" ]
python
train
33.8
inveniosoftware/invenio-records-rest
invenio_records_rest/views.py
https://github.com/inveniosoftware/invenio-records-rest/blob/e7b63c5f72cef03d06d3f1b4c12c0d37e3a628b9/invenio_records_rest/views.py#L757-L794
def put(self, pid, record, **kwargs): """Replace a record. Permissions: ``update_permission_factory`` The body should be a JSON object, which will fully replace the current record metadata. Procedure description: #. The ETag is checked. #. The record is updat...
[ "def", "put", "(", "self", ",", "pid", ",", "record", ",", "*", "*", "kwargs", ")", ":", "if", "request", ".", "mimetype", "not", "in", "self", ".", "loaders", ":", "raise", "UnsupportedMediaRESTError", "(", "request", ".", "mimetype", ")", "data", "="...
Replace a record. Permissions: ``update_permission_factory`` The body should be a JSON object, which will fully replace the current record metadata. Procedure description: #. The ETag is checked. #. The record is updated by calling the record API `clear()`, ...
[ "Replace", "a", "record", "." ]
python
train
29.868421
rvswift/EB
EB/builder/postanalysis/postanalysis.py
https://github.com/rvswift/EB/blob/341880b79faf8147dc9fa6e90438531cd09fabcc/EB/builder/postanalysis/postanalysis.py#L190-L201
def error_check(options): """ Error check :rtype : object """ compare = options.compare ensemble_paths = options.ensemble_paths if compare and len(ensemble_paths) > 2: print("\n Only 2 ensembles can be compared, {d} were specified\n".format(d=len(ensemble_paths))) sys.exit(...
[ "def", "error_check", "(", "options", ")", ":", "compare", "=", "options", ".", "compare", "ensemble_paths", "=", "options", ".", "ensemble_paths", "if", "compare", "and", "len", "(", "ensemble_paths", ")", ">", "2", ":", "print", "(", "\"\\n Only 2 ensembles ...
Error check :rtype : object
[ "Error", "check", ":", "rtype", ":", "object" ]
python
train
25.916667
seomoz/qless-py
qless/workers/__init__.py
https://github.com/seomoz/qless-py/blob/3eda4ffcd4c0016c9a7e44f780d6155e1a354dda/qless/workers/__init__.py#L52-L60
def divide(cls, jobs, count): '''Divide up the provided jobs into count evenly-sized groups''' jobs = list(zip(*zip_longest(*[iter(jobs)] * count))) # If we had no jobs to resume, then we get an empty list jobs = jobs or [()] * count for index in range(count): # Filte...
[ "def", "divide", "(", "cls", ",", "jobs", ",", "count", ")", ":", "jobs", "=", "list", "(", "zip", "(", "*", "zip_longest", "(", "*", "[", "iter", "(", "jobs", ")", "]", "*", "count", ")", ")", ")", "# If we had no jobs to resume, then we get an empty li...
Divide up the provided jobs into count evenly-sized groups
[ "Divide", "up", "the", "provided", "jobs", "into", "count", "evenly", "-", "sized", "groups" ]
python
train
48.222222
StackStorm/pybind
pybind/slxos/v17s_1_02/isis_state/__init__.py
https://github.com/StackStorm/pybind/blob/44c467e71b2b425be63867aba6e6fa28b2cfe7fb/pybind/slxos/v17s_1_02/isis_state/__init__.py#L110-L133
def _set_global_isis_info(self, v, load=False): """ Setter method for global_isis_info, mapped from YANG variable /isis_state/global_isis_info (container) If this variable is read-only (config: false) in the source YANG file, then _set_global_isis_info is considered as a private method. Backends loo...
[ "def", "_set_global_isis_info", "(", "self", ",", "v", ",", "load", "=", "False", ")", ":", "if", "hasattr", "(", "v", ",", "\"_utype\"", ")", ":", "v", "=", "v", ".", "_utype", "(", "v", ")", "try", ":", "t", "=", "YANGDynClass", "(", "v", ",", ...
Setter method for global_isis_info, mapped from YANG variable /isis_state/global_isis_info (container) If this variable is read-only (config: false) in the source YANG file, then _set_global_isis_info is considered as a private method. Backends looking to populate this variable should do so via calling ...
[ "Setter", "method", "for", "global_isis_info", "mapped", "from", "YANG", "variable", "/", "isis_state", "/", "global_isis_info", "(", "container", ")", "If", "this", "variable", "is", "read", "-", "only", "(", "config", ":", "false", ")", "in", "the", "sourc...
python
train
75.333333
log2timeline/plaso
plaso/cli/helpers/interface.py
https://github.com/log2timeline/plaso/blob/9c564698d2da3ffbe23607a3c54c0582ea18a6cc/plaso/cli/helpers/interface.py#L53-L94
def _ParseStringOption(cls, options, argument_name, default_value=None): """Parses a string command line argument. Args: options (argparse.Namespace): parser options. argument_name (str): name of the command line argument. default_value (Optional[str]): default value of the command line argum...
[ "def", "_ParseStringOption", "(", "cls", ",", "options", ",", "argument_name", ",", "default_value", "=", "None", ")", ":", "argument_value", "=", "getattr", "(", "options", ",", "argument_name", ",", "None", ")", "if", "argument_value", "is", "None", ":", "...
Parses a string command line argument. Args: options (argparse.Namespace): parser options. argument_name (str): name of the command line argument. default_value (Optional[str]): default value of the command line argument. Returns: str: command line argument value or the default value i...
[ "Parses", "a", "string", "command", "line", "argument", "." ]
python
train
34.238095
scheibler/khard
khard/carddav_object.py
https://github.com/scheibler/khard/blob/0f69430c2680f1ff5f073a977a3c5b753b96cc17/khard/carddav_object.py#L670-L678
def _get_webpages(self): """ :rtype: list(list(str)) """ urls = [] for child in self.vcard.getChildren(): if child.name == "URL": urls.append(child.value) return sorted(urls)
[ "def", "_get_webpages", "(", "self", ")", ":", "urls", "=", "[", "]", "for", "child", "in", "self", ".", "vcard", ".", "getChildren", "(", ")", ":", "if", "child", ".", "name", "==", "\"URL\"", ":", "urls", ".", "append", "(", "child", ".", "value"...
:rtype: list(list(str))
[ ":", "rtype", ":", "list", "(", "list", "(", "str", "))" ]
python
test
26.888889
click-contrib/click-configfile
click_configfile.py
https://github.com/click-contrib/click-configfile/blob/a616204cb9944125fd5051556f27a7ccef611e22/click_configfile.py#L81-L126
def assign_param_names(cls=None, param_class=None): """Class decorator to assign parameter name to instances of :class:`Param`. .. sourcecode:: @assign_param_names class ConfigSectionSchema(object): alice = Param(type=str) bob = Param(type=str) assert ConfigS...
[ "def", "assign_param_names", "(", "cls", "=", "None", ",", "param_class", "=", "None", ")", ":", "if", "param_class", "is", "None", ":", "param_class", "=", "Param", "def", "decorate_class", "(", "cls", ")", ":", "for", "name", ",", "value", "in", "selec...
Class decorator to assign parameter name to instances of :class:`Param`. .. sourcecode:: @assign_param_names class ConfigSectionSchema(object): alice = Param(type=str) bob = Param(type=str) assert ConfigSectionSchema.alice.name == "alice" assert ConfigSec...
[ "Class", "decorator", "to", "assign", "parameter", "name", "to", "instances", "of", ":", "class", ":", "Param", "." ]
python
train
32.913043
petl-developers/petl
petl/transform/hashjoins.py
https://github.com/petl-developers/petl/blob/1d33ca055f7e04e0d28a772041c9fd30c8d415d6/petl/transform/hashjoins.py#L316-L331
def hashantijoin(left, right, key=None, lkey=None, rkey=None): """Alternative implementation of :func:`petl.transform.joins.antijoin`, where the join is executed by constructing an in-memory set for all keys found in the right hand table, then iterating over rows from the left hand table. May b...
[ "def", "hashantijoin", "(", "left", ",", "right", ",", "key", "=", "None", ",", "lkey", "=", "None", ",", "rkey", "=", "None", ")", ":", "lkey", ",", "rkey", "=", "keys_from_args", "(", "left", ",", "right", ",", "key", ",", "lkey", ",", "rkey", ...
Alternative implementation of :func:`petl.transform.joins.antijoin`, where the join is executed by constructing an in-memory set for all keys found in the right hand table, then iterating over rows from the left hand table. May be faster and/or more resource efficient where the right table is small...
[ "Alternative", "implementation", "of", ":", "func", ":", "petl", ".", "transform", ".", "joins", ".", "antijoin", "where", "the", "join", "is", "executed", "by", "constructing", "an", "in", "-", "memory", "set", "for", "all", "keys", "found", "in", "the", ...
python
train
40.625
hobson/pug-invest
pug/invest/sandbox/sim.py
https://github.com/hobson/pug-invest/blob/836911258a0e920083a88c91beae88eefdebb20c/pug/invest/sandbox/sim.py#L437-L475
def buy_on_drop(symbol_set="sp5002012", dataobj=dataobj, start=datetime.datetime(2008, 1, 3), end=datetime.datetime(2009, 12, 28), market_sym='$SPX', threshold=6, sell_delay=5, ): '''Compute and display an "event profile" for mul...
[ "def", "buy_on_drop", "(", "symbol_set", "=", "\"sp5002012\"", ",", "dataobj", "=", "dataobj", ",", "start", "=", "datetime", ".", "datetime", "(", "2008", ",", "1", ",", "3", ")", ",", "end", "=", "datetime", ".", "datetime", "(", "2009", ",", "12", ...
Compute and display an "event profile" for multiple sets of symbols
[ "Compute", "and", "display", "an", "event", "profile", "for", "multiple", "sets", "of", "symbols" ]
python
train
49.333333
django-json-api/django-rest-framework-json-api
rest_framework_json_api/filters.py
https://github.com/django-json-api/django-rest-framework-json-api/blob/de7021f9e011615ce8b65d0cb38227c6c12721b6/rest_framework_json_api/filters.py#L75-L89
def validate_query_params(self, request): """ Validate that query params are in the list of valid query keywords in :py:attr:`query_regex` :raises ValidationError: if not. """ # TODO: For jsonapi error object conformance, must set jsonapi errors "parameter" for #...
[ "def", "validate_query_params", "(", "self", ",", "request", ")", ":", "# TODO: For jsonapi error object conformance, must set jsonapi errors \"parameter\" for", "# the ValidationError. This requires extending DRF/DJA Exceptions.", "for", "qp", "in", "request", ".", "query_params", "...
Validate that query params are in the list of valid query keywords in :py:attr:`query_regex` :raises ValidationError: if not.
[ "Validate", "that", "query", "params", "are", "in", "the", "list", "of", "valid", "query", "keywords", "in", ":", "py", ":", "attr", ":", "query_regex" ]
python
train
47.8
guaix-ucm/pyemir
emirdrp/processing/wavecal/rectwv_coeff_from_mos_library.py
https://github.com/guaix-ucm/pyemir/blob/fef6bbabcb13f80123cafd1800a0f508a3c21702/emirdrp/processing/wavecal/rectwv_coeff_from_mos_library.py#L55-L410
def rectwv_coeff_from_mos_library(reduced_image, master_rectwv, ignore_dtu_configuration=True, debugplot=0): """Evaluate rect.+wavecal. coefficients from MOS library Parameters ---------- reduced_image...
[ "def", "rectwv_coeff_from_mos_library", "(", "reduced_image", ",", "master_rectwv", ",", "ignore_dtu_configuration", "=", "True", ",", "debugplot", "=", "0", ")", ":", "logger", "=", "logging", ".", "getLogger", "(", "__name__", ")", "logger", ".", "info", "(", ...
Evaluate rect.+wavecal. coefficients from MOS library Parameters ---------- reduced_image : HDUList object Image with preliminary basic reduction: bpm, bias, dark and flatfield. master_rectwv : MasterRectWave instance Rectification and Wavelength Calibrartion Library product. ...
[ "Evaluate", "rect", ".", "+", "wavecal", ".", "coefficients", "from", "MOS", "library" ]
python
train
47.075843
saltstack/salt
salt/modules/hadoop.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/hadoop.py#L30-L57
def _hadoop_cmd(module, command, *args): ''' Hadoop/hdfs command wrapper As Hadoop command has been deprecated this module will default to use hdfs command and fall back to hadoop if it is not found In order to prevent random execution the module name is checked Follows hadoop ...
[ "def", "_hadoop_cmd", "(", "module", ",", "command", ",", "*", "args", ")", ":", "tool", "=", "'hadoop'", "if", "salt", ".", "utils", ".", "path", ".", "which", "(", "'hdfs'", ")", ":", "tool", "=", "'hdfs'", "out", "=", "None", "if", "module", "an...
Hadoop/hdfs command wrapper As Hadoop command has been deprecated this module will default to use hdfs command and fall back to hadoop if it is not found In order to prevent random execution the module name is checked Follows hadoop command template: hadoop module -command args ...
[ "Hadoop", "/", "hdfs", "command", "wrapper" ]
python
train
33.107143
spyder-ide/conda-manager
conda_manager/api/conda_api.py
https://github.com/spyder-ide/conda-manager/blob/89a2126cbecefc92185cf979347ccac1c5ee5d9d/conda_manager/api/conda_api.py#L1094-L1108
def _pip_search(stdout, stderr): """Callback for pip search.""" result = {} lines = to_text_string(stdout).split('\n') while '' in lines: lines.remove('') for line in lines: if ' - ' in line: parts = line.split(' - ') name ...
[ "def", "_pip_search", "(", "stdout", ",", "stderr", ")", ":", "result", "=", "{", "}", "lines", "=", "to_text_string", "(", "stdout", ")", ".", "split", "(", "'\\n'", ")", "while", "''", "in", "lines", ":", "lines", ".", "remove", "(", "''", ")", "...
Callback for pip search.
[ "Callback", "for", "pip", "search", "." ]
python
train
29.133333
ulule/django-badgify
badgify/registry.py
https://github.com/ulule/django-badgify/blob/1bf233ffeb6293ee659454de7b3794682128b6ca/badgify/registry.py#L61-L69
def get_recipe_instance(self, badge): """ Returns the recipe instance for the given badge slug. If badge has not been registered, raises ``exceptions.BadgeNotFound``. """ from .exceptions import BadgeNotFound if badge in self._registry: return self.recipes[bad...
[ "def", "get_recipe_instance", "(", "self", ",", "badge", ")", ":", "from", ".", "exceptions", "import", "BadgeNotFound", "if", "badge", "in", "self", ".", "_registry", ":", "return", "self", ".", "recipes", "[", "badge", "]", "raise", "BadgeNotFound", "(", ...
Returns the recipe instance for the given badge slug. If badge has not been registered, raises ``exceptions.BadgeNotFound``.
[ "Returns", "the", "recipe", "instance", "for", "the", "given", "badge", "slug", ".", "If", "badge", "has", "not", "been", "registered", "raises", "exceptions", ".", "BadgeNotFound", "." ]
python
train
38.333333
jgorset/fandjango
fandjango/middleware.py
https://github.com/jgorset/fandjango/blob/01334a76c1d9f0629842aa6830678ae097756551/fandjango/middleware.py#L277-L297
def process_response(self, request, response): """ Set compact P3P policies and save auth token to cookie. P3P is a WC3 standard (see http://www.w3.org/TR/P3P/), and although largely ignored by most browsers it is considered by IE before accepting third-party cookies (ie. cookies set by...
[ "def", "process_response", "(", "self", ",", "request", ",", "response", ")", ":", "if", "hasattr", "(", "request", ",", "\"facebook\"", ")", "and", "request", ".", "facebook", "and", "request", ".", "facebook", ".", "oauth_token", ":", "if", "\"code\"", "...
Set compact P3P policies and save auth token to cookie. P3P is a WC3 standard (see http://www.w3.org/TR/P3P/), and although largely ignored by most browsers it is considered by IE before accepting third-party cookies (ie. cookies set by documents in iframes). If they are not set correctly, IE w...
[ "Set", "compact", "P3P", "policies", "and", "save", "auth", "token", "to", "cookie", "." ]
python
train
47.047619
jahuth/litus
spikes.py
https://github.com/jahuth/litus/blob/712b016ea2dbb1cf0a30bfdbb0a136945a7b7c5e/spikes.py#L145-L151
def find(self,cell_designation,cell_filter=lambda x,c: 'c' in x and x['c'] == c): """ finds spike containers in a multi spike containers collection """ res = [i for i,sc in enumerate(self.spike_containers) if cell_filter(sc.meta,cell_designation)] if len(res) > 0: ...
[ "def", "find", "(", "self", ",", "cell_designation", ",", "cell_filter", "=", "lambda", "x", ",", "c", ":", "'c'", "in", "x", "and", "x", "[", "'c'", "]", "==", "c", ")", ":", "res", "=", "[", "i", "for", "i", ",", "sc", "in", "enumerate", "(",...
finds spike containers in a multi spike containers collection
[ "finds", "spike", "containers", "in", "a", "multi", "spike", "containers", "collection" ]
python
train
46.857143
christophertbrown/bioscripts
ctbBio/rRNA_insertions_gff.py
https://github.com/christophertbrown/bioscripts/blob/83b2566b3a5745437ec651cd6cafddd056846240/ctbBio/rRNA_insertions_gff.py#L42-L76
def parse_orf(insertion, gff): """ parse ORF to gff format """ offset = insertion['offset'] if type(insertion['orf']) is not str: return gff for orf in parse_fasta(insertion['orf'].split('|')): ID = orf[0].split('>')[1].split()[0] Start, End, strand = [int(i) for i in orf...
[ "def", "parse_orf", "(", "insertion", ",", "gff", ")", ":", "offset", "=", "insertion", "[", "'offset'", "]", "if", "type", "(", "insertion", "[", "'orf'", "]", ")", "is", "not", "str", ":", "return", "gff", "for", "orf", "in", "parse_fasta", "(", "i...
parse ORF to gff format
[ "parse", "ORF", "to", "gff", "format" ]
python
train
33.2
ThreatResponse/margaritashotgun
margaritashotgun/remote_shell.py
https://github.com/ThreatResponse/margaritashotgun/blob/6dee53ef267959b214953439968244cc46a19690/margaritashotgun/remote_shell.py#L160-L183
def execute_async(self, command, callback=None): """ Executes command on remote hosts without blocking :type command: str :param command: command to be run on remote host :type callback: function :param callback: function to call when execution completes """ ...
[ "def", "execute_async", "(", "self", ",", "command", ",", "callback", "=", "None", ")", ":", "try", ":", "logger", ".", "debug", "(", "(", "'{0}: execute async \"{1}\"'", "'with callback {2}'", ".", "format", "(", "self", ".", "target_address", ",", "command",...
Executes command on remote hosts without blocking :type command: str :param command: command to be run on remote host :type callback: function :param callback: function to call when execution completes
[ "Executes", "command", "on", "remote", "hosts", "without", "blocking" ]
python
train
46.458333
tensorflow/tensorboard
tensorboard/manager.py
https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/manager.py#L273-L286
def remove_info_file(): """Remove the current process's TensorBoardInfo file, if it exists. If the file does not exist, no action is taken and no error is raised. """ try: os.unlink(_get_info_file_path()) except OSError as e: if e.errno == errno.ENOENT: # The user may have wiped their temporary...
[ "def", "remove_info_file", "(", ")", ":", "try", ":", "os", ".", "unlink", "(", "_get_info_file_path", "(", ")", ")", "except", "OSError", "as", "e", ":", "if", "e", ".", "errno", "==", "errno", ".", "ENOENT", ":", "# The user may have wiped their temporary ...
Remove the current process's TensorBoardInfo file, if it exists. If the file does not exist, no action is taken and no error is raised.
[ "Remove", "the", "current", "process", "s", "TensorBoardInfo", "file", "if", "it", "exists", "." ]
python
train
31.214286
ArchiveTeam/wpull
wpull/url.py
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/url.py#L685-L697
def urljoin(base_url, url, allow_fragments=True): '''Join URLs like ``urllib.parse.urljoin`` but allow scheme-relative URL.''' if url.startswith('//') and len(url) > 2: scheme = base_url.partition(':')[0] if scheme: return urllib.parse.urljoin( base_url, ...
[ "def", "urljoin", "(", "base_url", ",", "url", ",", "allow_fragments", "=", "True", ")", ":", "if", "url", ".", "startswith", "(", "'//'", ")", "and", "len", "(", "url", ")", ">", "2", ":", "scheme", "=", "base_url", ".", "partition", "(", "':'", "...
Join URLs like ``urllib.parse.urljoin`` but allow scheme-relative URL.
[ "Join", "URLs", "like", "urllib", ".", "parse", ".", "urljoin", "but", "allow", "scheme", "-", "relative", "URL", "." ]
python
train
37.923077
google/grr
grr/server/grr_response_server/databases/mem_events.py
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/databases/mem_events.py#L63-L67
def WriteAPIAuditEntry(self, entry): """Writes an audit entry to the database.""" copy = entry.Copy() copy.timestamp = rdfvalue.RDFDatetime.Now() self.api_audit_entries.append(copy)
[ "def", "WriteAPIAuditEntry", "(", "self", ",", "entry", ")", ":", "copy", "=", "entry", ".", "Copy", "(", ")", "copy", ".", "timestamp", "=", "rdfvalue", ".", "RDFDatetime", ".", "Now", "(", ")", "self", ".", "api_audit_entries", ".", "append", "(", "c...
Writes an audit entry to the database.
[ "Writes", "an", "audit", "entry", "to", "the", "database", "." ]
python
train
38.6
bouncer-app/bouncer
bouncer/__init__.py
https://github.com/bouncer-app/bouncer/blob/2d645dce18e3849d338d21380529abf8db5eeb9d/bouncer/__init__.py#L37-L41
def ensure(user, action, subject): """ Similar to ``can`` but will raise a AccessDenied Exception if does not have access""" ability = Ability(user, get_authorization_method()) if ability.cannot(action, subject): raise AccessDenied()
[ "def", "ensure", "(", "user", ",", "action", ",", "subject", ")", ":", "ability", "=", "Ability", "(", "user", ",", "get_authorization_method", "(", ")", ")", "if", "ability", ".", "cannot", "(", "action", ",", "subject", ")", ":", "raise", "AccessDenied...
Similar to ``can`` but will raise a AccessDenied Exception if does not have access
[ "Similar", "to", "can", "but", "will", "raise", "a", "AccessDenied", "Exception", "if", "does", "not", "have", "access" ]
python
train
49.8
pandas-dev/pandas
pandas/util/_validators.py
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/util/_validators.py#L221-L227
def validate_bool_kwarg(value, arg_name): """ Ensures that argument passed in arg_name is of type bool. """ if not (is_bool(value) or value is None): raise ValueError('For argument "{arg}" expected type bool, received ' 'type {typ}.'.format(arg=arg_name, ...
[ "def", "validate_bool_kwarg", "(", "value", ",", "arg_name", ")", ":", "if", "not", "(", "is_bool", "(", "value", ")", "or", "value", "is", "None", ")", ":", "raise", "ValueError", "(", "'For argument \"{arg}\" expected type bool, received '", "'type {typ}.'", "."...
Ensures that argument passed in arg_name is of type bool.
[ "Ensures", "that", "argument", "passed", "in", "arg_name", "is", "of", "type", "bool", "." ]
python
train
54.142857
jobovy/galpy
galpy/potential/Potential.py
https://github.com/jobovy/galpy/blob/9c5b9fe65d58835624dffe432be282060918ee08/galpy/potential/Potential.py#L1316-L1356
def conc(self,H=70.,Om=0.3,overdens=200.,wrtcrit=False, ro=None,vo=None): """ NAME: conc PURPOSE: return the concentration INPUT: H= (default: 70) Hubble constant in km/s/Mpc Om= (default: 0.3) Omega matter ...
[ "def", "conc", "(", "self", ",", "H", "=", "70.", ",", "Om", "=", "0.3", ",", "overdens", "=", "200.", ",", "wrtcrit", "=", "False", ",", "ro", "=", "None", ",", "vo", "=", "None", ")", ":", "if", "ro", "is", "None", ":", "ro", "=", "self", ...
NAME: conc PURPOSE: return the concentration INPUT: H= (default: 70) Hubble constant in km/s/Mpc Om= (default: 0.3) Omega matter overdens= (200) overdensity which defines the virial radius wrtcrit= (False) if Tru...
[ "NAME", ":" ]
python
train
30.512195
MrTango/RISparser
RISparser/parser.py
https://github.com/MrTango/RISparser/blob/d133d74022d3edbbdec19ef72bd34c8902a0bad1/RISparser/parser.py#L180-L204
def read(filelines, mapping=None, wok=False): """Parse a ris lines and return a list of entries. Entries are codified as dictionaries whose keys are the different tags. For single line and singly occurring tags, the content is codified as a string. In the case of multiline or multiple key occurrenc...
[ "def", "read", "(", "filelines", ",", "mapping", "=", "None", ",", "wok", "=", "False", ")", ":", "if", "wok", ":", "if", "not", "mapping", ":", "mapping", "=", "WOK_TAG_KEY_MAPPING", "return", "Wok", "(", "filelines", ",", "mapping", ")", ".", "parse"...
Parse a ris lines and return a list of entries. Entries are codified as dictionaries whose keys are the different tags. For single line and singly occurring tags, the content is codified as a string. In the case of multiline or multiple key occurrences, the content is returned as a list of strings....
[ "Parse", "a", "ris", "lines", "and", "return", "a", "list", "of", "entries", "." ]
python
train
32.92
openthread/openthread
tools/harness-thci/OpenThread.py
https://github.com/openthread/openthread/blob/0208d10563aa21c518092985c78ecf9cd223ab74/tools/harness-thci/OpenThread.py#L443-L483
def __convertRlocToRouterId(self, xRloc16): """mapping Rloc16 to router id Args: xRloc16: hex rloc16 short address Returns: actual router id allocated by leader """ routerList = [] routerList = self.__sendCommand('router list')[0].split() ...
[ "def", "__convertRlocToRouterId", "(", "self", ",", "xRloc16", ")", ":", "routerList", "=", "[", "]", "routerList", "=", "self", ".", "__sendCommand", "(", "'router list'", ")", "[", "0", "]", ".", "split", "(", ")", "print", "routerList", "print", "xRloc1...
mapping Rloc16 to router id Args: xRloc16: hex rloc16 short address Returns: actual router id allocated by leader
[ "mapping", "Rloc16", "to", "router", "id" ]
python
train
28
awslabs/serverless-application-model
samtranslator/plugins/globals/globals.py
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/plugins/globals/globals.py#L362-L384
def _token_of(self, input): """ Returns the token type of the input. :param input: Input whose type is to be determined :return TOKENS: Token type of the input """ if isinstance(input, dict): # Intrinsic functions are always dicts if is_intrinsi...
[ "def", "_token_of", "(", "self", ",", "input", ")", ":", "if", "isinstance", "(", "input", ",", "dict", ")", ":", "# Intrinsic functions are always dicts", "if", "is_intrinsics", "(", "input", ")", ":", "# Intrinsic functions are handled *exactly* like a primitive type ...
Returns the token type of the input. :param input: Input whose type is to be determined :return TOKENS: Token type of the input
[ "Returns", "the", "token", "type", "of", "the", "input", "." ]
python
train
31.347826
DLR-RM/RAFCON
source/rafcon/core/global_variable_manager.py
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/core/global_variable_manager.py#L243-L250
def set_locked_variable(self, key, access_key, value): """Set an already locked global variable :param key: the key of the global variable to be set :param access_key: the access key to the already locked global variable :param value: the new value of the global variable """ ...
[ "def", "set_locked_variable", "(", "self", ",", "key", ",", "access_key", ",", "value", ")", ":", "return", "self", ".", "set_variable", "(", "key", ",", "value", ",", "per_reference", "=", "False", ",", "access_key", "=", "access_key", ")" ]
Set an already locked global variable :param key: the key of the global variable to be set :param access_key: the access key to the already locked global variable :param value: the new value of the global variable
[ "Set", "an", "already", "locked", "global", "variable" ]
python
train
49.75
markovmodel/PyEMMA
pyemma/coordinates/transform/vamp.py
https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/coordinates/transform/vamp.py#L264-L301
def _diagonalize(self): """Performs SVD on covariance matrices and save left, right singular vectors and values in the model. Parameters ---------- scaling : None or string, default=None Scaling to be applied to the VAMP modes upon transformation * None: no scali...
[ "def", "_diagonalize", "(", "self", ")", ":", "L0", "=", "spd_inv_split", "(", "self", ".", "C00", ",", "epsilon", "=", "self", ".", "epsilon", ")", "self", ".", "_rank0", "=", "L0", ".", "shape", "[", "1", "]", "if", "L0", ".", "ndim", "==", "2"...
Performs SVD on covariance matrices and save left, right singular vectors and values in the model. Parameters ---------- scaling : None or string, default=None Scaling to be applied to the VAMP modes upon transformation * None: no scaling will be applied, variance of the...
[ "Performs", "SVD", "on", "covariance", "matrices", "and", "save", "left", "right", "singular", "vectors", "and", "values", "in", "the", "model", "." ]
python
train
40.921053
Cymmetria/honeycomb
honeycomb/integrationmanager/tasks.py
https://github.com/Cymmetria/honeycomb/blob/33ea91b5cf675000e4e85dd02efe580ea6e95c86/honeycomb/integrationmanager/tasks.py#L74-L89
def get_valid_configured_integrations(alert): """Return a list of integrations for alert filtered by alert_type. :returns: A list of relevant integrations """ if not configured_integrations: return [] # Collect all integrations that are configured for specific alert_type # or have no s...
[ "def", "get_valid_configured_integrations", "(", "alert", ")", ":", "if", "not", "configured_integrations", ":", "return", "[", "]", "# Collect all integrations that are configured for specific alert_type", "# or have no specific supported_event_types (i.e., all alert types)", "valid_c...
Return a list of integrations for alert filtered by alert_type. :returns: A list of relevant integrations
[ "Return", "a", "list", "of", "integrations", "for", "alert", "filtered", "by", "alert_type", "." ]
python
train
42
lrq3000/pyFileFixity
pyFileFixity/lib/sortedcontainers/sortedlistwithkey.py
https://github.com/lrq3000/pyFileFixity/blob/fd5ef23bb13835faf1e3baa773619b86a1cc9bdf/pyFileFixity/lib/sortedcontainers/sortedlistwithkey.py#L254-L312
def _delete(self, pos, idx): """ Delete the item at the given (pos, idx). Combines lists that are less than half the load level. Updates the index when the sublist length is more than half the load level. This requires decrementing the nodes in a traversal from the leaf ...
[ "def", "_delete", "(", "self", ",", "pos", ",", "idx", ")", ":", "_maxes", ",", "_lists", ",", "_keys", ",", "_index", "=", "self", ".", "_maxes", ",", "self", ".", "_lists", ",", "self", ".", "_keys", ",", "self", ".", "_index", "keys_pos", "=", ...
Delete the item at the given (pos, idx). Combines lists that are less than half the load level. Updates the index when the sublist length is more than half the load level. This requires decrementing the nodes in a traversal from the leaf node to the root. For an example traversal see s...
[ "Delete", "the", "item", "at", "the", "given", "(", "pos", "idx", ")", "." ]
python
train
25.033898
SmokinCaterpillar/pypet
pypet/storageservice.py
https://github.com/SmokinCaterpillar/pypet/blob/97ad3e80d46dbdea02deeb98ea41f05a19565826/pypet/storageservice.py#L3848-L3996
def _prm_store_parameter_or_result(self, instance, store_data=pypetconstants.STORE_DATA, store_flags=None, overwrite=None, wi...
[ "def", "_prm_store_parameter_or_result", "(", "self", ",", "instance", ",", "store_data", "=", "pypetconstants", ".", "STORE_DATA", ",", "store_flags", "=", "None", ",", "overwrite", "=", "None", ",", "with_links", "=", "False", ",", "recursive", "=", "False", ...
Stores a parameter or result to hdf5. :param instance: The instance to be stored :param store_data: How to store data :param store_flags: Dictionary containing how to store individual data, usually empty. :param overwrite: Instructi...
[ "Stores", "a", "parameter", "or", "result", "to", "hdf5", "." ]
python
test
41.060403
openvax/mhctools
mhctools/netmhc_pan.py
https://github.com/openvax/mhctools/blob/b329b4dccd60fae41296816b8cbfe15d6ca07e67/mhctools/netmhc_pan.py#L28-L64
def NetMHCpan( alleles, program_name="netMHCpan", process_limit=-1, default_peptide_lengths=[9], extra_flags=[]): """ This function wraps NetMHCpan28 and NetMHCpan3 to automatically detect which class to use, with the help of the miraculous and strange '--version' net...
[ "def", "NetMHCpan", "(", "alleles", ",", "program_name", "=", "\"netMHCpan\"", ",", "process_limit", "=", "-", "1", ",", "default_peptide_lengths", "=", "[", "9", "]", ",", "extra_flags", "=", "[", "]", ")", ":", "# convert to str since Python3 returns a `bytes` o...
This function wraps NetMHCpan28 and NetMHCpan3 to automatically detect which class to use, with the help of the miraculous and strange '--version' netmhcpan argument.
[ "This", "function", "wraps", "NetMHCpan28", "and", "NetMHCpan3", "to", "automatically", "detect", "which", "class", "to", "use", "with", "the", "help", "of", "the", "miraculous", "and", "strange", "--", "version", "netmhcpan", "argument", "." ]
python
valid
36.837838
senaite/senaite.core
bika/lims/api/__init__.py
https://github.com/senaite/senaite.core/blob/7602ce2ea2f9e81eb34e20ce17b98a3e70713f85/bika/lims/api/__init__.py#L545-L558
def get_parent_path(brain_or_object): """Calculate the physical parent path of this object :param brain_or_object: A single catalog brain or content object :type brain_or_object: ATContentType/DexterityContentType/CatalogBrain :returns: Physical path of the parent object :rtype: string """ ...
[ "def", "get_parent_path", "(", "brain_or_object", ")", ":", "if", "is_portal", "(", "brain_or_object", ")", ":", "return", "get_path", "(", "get_portal", "(", ")", ")", "if", "is_brain", "(", "brain_or_object", ")", ":", "path", "=", "get_path", "(", "brain_...
Calculate the physical parent path of this object :param brain_or_object: A single catalog brain or content object :type brain_or_object: ATContentType/DexterityContentType/CatalogBrain :returns: Physical path of the parent object :rtype: string
[ "Calculate", "the", "physical", "parent", "path", "of", "this", "object" ]
python
train
39.142857
KnorrFG/pyparadigm
pyparadigm/eventlistener.py
https://github.com/KnorrFG/pyparadigm/blob/69944cdf3ce2f6414ae1aa1d27a0d8c6e5fb3fd3/pyparadigm/eventlistener.py#L295-L303
def wait_for_unicode_char(self, ignored_chars=None, timeout=0): """Returns a str that contains the single character that was pressed. This already respects modifier keys and keyboard layouts. If timeout is not none and no key is pressed within the specified timeout, None is returned. If ...
[ "def", "wait_for_unicode_char", "(", "self", ",", "ignored_chars", "=", "None", ",", "timeout", "=", "0", ")", ":", "return", "self", ".", "listen_until_return", "(", "Handler", ".", "unicode_char", "(", "ignored_chars", ")", ",", "timeout", "=", "timeout", ...
Returns a str that contains the single character that was pressed. This already respects modifier keys and keyboard layouts. If timeout is not none and no key is pressed within the specified timeout, None is returned. If a key is ingnored_chars it will be ignored. As argument for irgnore...
[ "Returns", "a", "str", "that", "contains", "the", "single", "character", "that", "was", "pressed", ".", "This", "already", "respects", "modifier", "keys", "and", "keyboard", "layouts", ".", "If", "timeout", "is", "not", "none", "and", "no", "key", "is", "p...
python
train
70
abilian/abilian-core
abilian/web/frontend.py
https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/web/frontend.py#L178-L183
def _check_view_permission(self, view): """ :param view: a :class:`ObjectView` class or instance """ security = get_service("security") return security.has_permission(current_user, view.permission, self.obj)
[ "def", "_check_view_permission", "(", "self", ",", "view", ")", ":", "security", "=", "get_service", "(", "\"security\"", ")", "return", "security", ".", "has_permission", "(", "current_user", ",", "view", ".", "permission", ",", "self", ".", "obj", ")" ]
:param view: a :class:`ObjectView` class or instance
[ ":", "param", "view", ":", "a", ":", "class", ":", "ObjectView", "class", "or", "instance" ]
python
train
40.333333
timothyb0912/pylogit
pylogit/base_multinomial_cm_v2.py
https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/base_multinomial_cm_v2.py#L1341-L1375
def _adjust_inferential_results_for_parameter_constraints(self, constraints): """ Ensure that parameters that were constrained during estimation do not have any values showed for inferential results. After all, no inference wa...
[ "def", "_adjust_inferential_results_for_parameter_constraints", "(", "self", ",", "constraints", ")", ":", "if", "constraints", "is", "not", "None", ":", "# Ensure the model object has inferential results", "inferential_attributes", "=", "[", "\"standard_errors\"", ",", "\"tv...
Ensure that parameters that were constrained during estimation do not have any values showed for inferential results. After all, no inference was performed. Parameters ---------- constraints : list of ints, or None. If list, should contain the positions in the array ...
[ "Ensure", "that", "parameters", "that", "were", "constrained", "during", "estimation", "do", "not", "have", "any", "values", "showed", "for", "inferential", "results", ".", "After", "all", "no", "inference", "was", "performed", "." ]
python
train
39.371429
PmagPy/PmagPy
dialogs/magic_grid3.py
https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/dialogs/magic_grid3.py#L236-L249
def on_edit_grid(self, event): """sets self.changes to true when user edits the grid. provides down and up key functionality for exiting the editor""" if not self.changes: self.changes = {event.Row} else: self.changes.add(event.Row) #self.changes = True ...
[ "def", "on_edit_grid", "(", "self", ",", "event", ")", ":", "if", "not", "self", ".", "changes", ":", "self", ".", "changes", "=", "{", "event", ".", "Row", "}", "else", ":", "self", ".", "changes", ".", "add", "(", "event", ".", "Row", ")", "#se...
sets self.changes to true when user edits the grid. provides down and up key functionality for exiting the editor
[ "sets", "self", ".", "changes", "to", "true", "when", "user", "edits", "the", "grid", ".", "provides", "down", "and", "up", "key", "functionality", "for", "exiting", "the", "editor" ]
python
train
39.214286
smarie/python-parsyfiles
parsyfiles/parsing_core_api.py
https://github.com/smarie/python-parsyfiles/blob/344b37e1151e8d4e7c2ee49ae09d6568715ae64e/parsyfiles/parsing_core_api.py#L243-L269
def create_for_caught_error(parser: _BaseParserDeclarationForRegistries, desired_type: Type[T], obj: PersistedObject, caught: Exception, options: Dict[str, Dict[str, Any]]): """ Helper method provided because we actually can't put that in the constructor, it creates a bug...
[ "def", "create_for_caught_error", "(", "parser", ":", "_BaseParserDeclarationForRegistries", ",", "desired_type", ":", "Type", "[", "T", "]", ",", "obj", ":", "PersistedObject", ",", "caught", ":", "Exception", ",", "options", ":", "Dict", "[", "str", ",", "Di...
Helper method provided because we actually can't put that in the constructor, it creates a bug in Nose tests https://github.com/nose-devs/nose/issues/725 :param parser: :param desired_type: :param obj: :param caught: :param options: :return:
[ "Helper", "method", "provided", "because", "we", "actually", "can", "t", "put", "that", "in", "the", "constructor", "it", "creates", "a", "bug", "in", "Nose", "tests", "https", ":", "//", "github", ".", "com", "/", "nose", "-", "devs", "/", "nose", "/"...
python
train
44.888889
FutunnOpen/futuquant
futuquant/common/event/eventEngine.py
https://github.com/FutunnOpen/futuquant/blob/1512b321845f92ec9c578ce2689aa4e8482669e4/futuquant/common/event/eventEngine.py#L176-L179
def unregisterGeneralHandler(self, handler): """注销通用事件处理函数监听""" if handler in self.__generalHandlers: self.__generalHandlers.remove(handler)
[ "def", "unregisterGeneralHandler", "(", "self", ",", "handler", ")", ":", "if", "handler", "in", "self", ".", "__generalHandlers", ":", "self", ".", "__generalHandlers", ".", "remove", "(", "handler", ")" ]
注销通用事件处理函数监听
[ "注销通用事件处理函数监听" ]
python
train
41.25
shakefu/pyconfig
pyconfig/__init__.py
https://github.com/shakefu/pyconfig/blob/000cb127db51e03cb4070aae6943e956193cbad5/pyconfig/__init__.py#L603-L619
def env(key, default): """ Helper to try to get a setting from the environment, or pyconfig, or finally use a provided default. """ value = os.environ.get(key, None) if value is not None: log.info(' %s = %r', key.lower().replace('_', '.'), value) return value key = key.l...
[ "def", "env", "(", "key", ",", "default", ")", ":", "value", "=", "os", ".", "environ", ".", "get", "(", "key", ",", "None", ")", "if", "value", "is", "not", "None", ":", "log", ".", "info", "(", "' %s = %r'", ",", "key", ".", "lower", "(", ...
Helper to try to get a setting from the environment, or pyconfig, or finally use a provided default.
[ "Helper", "to", "try", "to", "get", "a", "setting", "from", "the", "environment", "or", "pyconfig", "or", "finally", "use", "a", "provided", "default", "." ]
python
valid
24.470588
jobovy/galpy
galpy/util/bovy_plot.py
https://github.com/jobovy/galpy/blob/9c5b9fe65d58835624dffe432be282060918ee08/galpy/util/bovy_plot.py#L121-L183
def bovy_hist(x,xlabel=None,ylabel=None,overplot=False,**kwargs): """ NAME: bovy_hist PURPOSE: wrapper around matplotlib's hist function INPUT: x - array to histogram xlabel - (raw string!) x-axis label, LaTeX math mode, no $s needed ylabel - (raw string!) y-axi...
[ "def", "bovy_hist", "(", "x", ",", "xlabel", "=", "None", ",", "ylabel", "=", "None", ",", "overplot", "=", "False", ",", "*", "*", "kwargs", ")", ":", "if", "not", "overplot", ":", "pyplot", ".", "figure", "(", ")", "if", "'xrange'", "in", "kwargs...
NAME: bovy_hist PURPOSE: wrapper around matplotlib's hist function INPUT: x - array to histogram xlabel - (raw string!) x-axis label, LaTeX math mode, no $s needed ylabel - (raw string!) y-axis label, LaTeX math mode, no $s needed yrange - set the y-axis range ...
[ "NAME", ":" ]
python
train
24.31746
AtteqCom/zsl
src/zsl/interface/cli.py
https://github.com/AtteqCom/zsl/blob/ab51a96da1780ff642912396d4b85bdcb72560c1/src/zsl/interface/cli.py#L22-L32
def _get_version(ctx, _, value): """Click callback for option to show current ZSL version.""" if not value or ctx.resilient_parsing: return message = 'Zsl %(version)s\nPython %(python_version)s' click.echo(message % { 'version': version, 'python_version': sys.version, }, col...
[ "def", "_get_version", "(", "ctx", ",", "_", ",", "value", ")", ":", "if", "not", "value", "or", "ctx", ".", "resilient_parsing", ":", "return", "message", "=", "'Zsl %(version)s\\nPython %(python_version)s'", "click", ".", "echo", "(", "message", "%", "{", ...
Click callback for option to show current ZSL version.
[ "Click", "callback", "for", "option", "to", "show", "current", "ZSL", "version", "." ]
python
train
30.727273
justinmayer/django-autoslug
autoslug/fields.py
https://github.com/justinmayer/django-autoslug/blob/b3991daddf5a476a829b48c28afad4ae08a18179/autoslug/fields.py#L308-L315
def south_field_triple(self): "Returns a suitable description of this field for South." args, kwargs = introspector(self) kwargs.update({ 'populate_from': 'None' if callable(self.populate_from) else repr(self.populate_from), 'unique_with': repr(self.unique_with) }...
[ "def", "south_field_triple", "(", "self", ")", ":", "args", ",", "kwargs", "=", "introspector", "(", "self", ")", "kwargs", ".", "update", "(", "{", "'populate_from'", ":", "'None'", "if", "callable", "(", "self", ".", "populate_from", ")", "else", "repr",...
Returns a suitable description of this field for South.
[ "Returns", "a", "suitable", "description", "of", "this", "field", "for", "South", "." ]
python
train
47.125
zqfang/GSEApy
gseapy/enrichr.py
https://github.com/zqfang/GSEApy/blob/673e9ec1391e3b14d3e8a4353117151fd2cb9345/gseapy/enrichr.py#L250-L300
def enrich(self, gmt): """use local mode p = p-value computed using the Fisher exact test (Hypergeometric test) Not implemented here: combine score = log(p)·z see here: http://amp.pharm.mssm.edu/Enrichr/help#background&q=4 columns contain: ...
[ "def", "enrich", "(", "self", ",", "gmt", ")", ":", "if", "isscalar", "(", "self", ".", "background", ")", ":", "if", "isinstance", "(", "self", ".", "background", ",", "int", ")", "or", "self", ".", "background", ".", "isdigit", "(", ")", ":", "se...
use local mode p = p-value computed using the Fisher exact test (Hypergeometric test) Not implemented here: combine score = log(p)·z see here: http://amp.pharm.mssm.edu/Enrichr/help#background&q=4 columns contain: Term Overlap ...
[ "use", "local", "mode", "p", "=", "p", "-", "value", "computed", "using", "the", "Fisher", "exact", "test", "(", "Hypergeometric", "test", ")" ]
python
test
40.529412
tensorflow/datasets
tensorflow_datasets/core/registered.py
https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/core/registered.py#L137-L172
def builder(name, **builder_init_kwargs): """Fetches a `tfds.core.DatasetBuilder` by string name. Args: name: `str`, the registered name of the `DatasetBuilder` (the snake case version of the class name). This can be either `"dataset_name"` or `"dataset_name/config_name"` for datasets with `Builder...
[ "def", "builder", "(", "name", ",", "*", "*", "builder_init_kwargs", ")", ":", "name", ",", "builder_kwargs", "=", "_dataset_name_and_kwargs_from_name_str", "(", "name", ")", "builder_kwargs", ".", "update", "(", "builder_init_kwargs", ")", "if", "name", "in", "...
Fetches a `tfds.core.DatasetBuilder` by string name. Args: name: `str`, the registered name of the `DatasetBuilder` (the snake case version of the class name). This can be either `"dataset_name"` or `"dataset_name/config_name"` for datasets with `BuilderConfig`s. As a convenience, this string m...
[ "Fetches", "a", "tfds", ".", "core", ".", "DatasetBuilder", "by", "string", "name", "." ]
python
train
41.833333
veripress/veripress
veripress/helpers.py
https://github.com/veripress/veripress/blob/9e3df3a10eb1db32da596bf52118fe6acbe4b14a/veripress/helpers.py#L60-L78
def timezone_from_str(tz_str): """ Convert a timezone string to a timezone object. :param tz_str: string with format 'Asia/Shanghai' or 'UTC±[hh]:[mm]' :return: a timezone object (tzinfo) """ m = re.match(r'UTC([+|-]\d{1,2}):(\d{2})', tz_str) if m: # in format 'UTC±[hh]:[mm]' ...
[ "def", "timezone_from_str", "(", "tz_str", ")", ":", "m", "=", "re", ".", "match", "(", "r'UTC([+|-]\\d{1,2}):(\\d{2})'", ",", "tz_str", ")", "if", "m", ":", "# in format 'UTC±[hh]:[mm]'", "delta_h", "=", "int", "(", "m", ".", "group", "(", "1", ")", ")", ...
Convert a timezone string to a timezone object. :param tz_str: string with format 'Asia/Shanghai' or 'UTC±[hh]:[mm]' :return: a timezone object (tzinfo)
[ "Convert", "a", "timezone", "string", "to", "a", "timezone", "object", "." ]
python
train
32.421053
LabKey/labkey-api-python
labkey/security.py
https://github.com/LabKey/labkey-api-python/blob/3c8d393384d7cbb2785f8a7f5fe34007b17a76b8/labkey/security.py#L123-L141
def get_user_by_email(server_context, email): """ Get the user with the provided email. Throws a ValueError if not found. :param server_context: A LabKey server context. See utils.create_server_context. :param email: :return: """ url = server_context.build_url(user_controller, 'getUsers.api'...
[ "def", "get_user_by_email", "(", "server_context", ",", "email", ")", ":", "url", "=", "server_context", ".", "build_url", "(", "user_controller", ",", "'getUsers.api'", ")", "payload", "=", "dict", "(", "includeDeactivatedAccounts", "=", "True", ")", "result", ...
Get the user with the provided email. Throws a ValueError if not found. :param server_context: A LabKey server context. See utils.create_server_context. :param email: :return:
[ "Get", "the", "user", "with", "the", "provided", "email", ".", "Throws", "a", "ValueError", "if", "not", "found", ".", ":", "param", "server_context", ":", "A", "LabKey", "server", "context", ".", "See", "utils", ".", "create_server_context", ".", ":", "pa...
python
train
35.526316
kataev/flake8-rst
flake8_rst/sourceblock.py
https://github.com/kataev/flake8-rst/blob/ca6d41c7a309b9e8cd4fa6f428b82db96b6a986f/flake8_rst/sourceblock.py#L72-L84
def merge(cls, source_blocks): """Merge multiple SourceBlocks together""" if len(source_blocks) == 1: return source_blocks[0] source_blocks.sort(key=operator.attrgetter('start_line_number')) main_block = source_blocks[0] boot_lines = main_block.boot_lines so...
[ "def", "merge", "(", "cls", ",", "source_blocks", ")", ":", "if", "len", "(", "source_blocks", ")", "==", "1", ":", "return", "source_blocks", "[", "0", "]", "source_blocks", ".", "sort", "(", "key", "=", "operator", ".", "attrgetter", "(", "'start_line_...
Merge multiple SourceBlocks together
[ "Merge", "multiple", "SourceBlocks", "together" ]
python
train
43.384615
prompt-toolkit/ptpython
ptpython/key_bindings.py
https://github.com/prompt-toolkit/ptpython/blob/b1bba26a491324cd65e0ef46c7b818c4b88fd993/ptpython/key_bindings.py#L260-L289
def auto_newline(buffer): r""" Insert \n at the cursor position. Also add necessary padding. """ insert_text = buffer.insert_text if buffer.document.current_line_after_cursor: # When we are in the middle of a line. Always insert a newline. insert_text('\n') else: # Go to...
[ "def", "auto_newline", "(", "buffer", ")", ":", "insert_text", "=", "buffer", ".", "insert_text", "if", "buffer", ".", "document", ".", "current_line_after_cursor", ":", "# When we are in the middle of a line. Always insert a newline.", "insert_text", "(", "'\\n'", ")", ...
r""" Insert \n at the cursor position. Also add necessary padding.
[ "r", "Insert", "\\", "n", "at", "the", "cursor", "position", ".", "Also", "add", "necessary", "padding", "." ]
python
train
32.666667
getsentry/responses
responses.py
https://github.com/getsentry/responses/blob/b7ab59513ffd52bf28808f45005f492f7d1bbd50/responses.py#L436-L487
def add( self, method=None, # method or ``Response`` url=None, body="", adding_headers=None, *args, **kwargs ): """ A basic request: >>> responses.add(responses.GET, 'http://example.com') You can also directly pass an object ...
[ "def", "add", "(", "self", ",", "method", "=", "None", ",", "# method or ``Response``", "url", "=", "None", ",", "body", "=", "\"\"", ",", "adding_headers", "=", "None", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "isinstance", "(", "m...
A basic request: >>> responses.add(responses.GET, 'http://example.com') You can also directly pass an object which implements the ``BaseResponse`` interface: >>> responses.add(Response(...)) A JSON payload: >>> responses.add( >>> method='GET', >>>...
[ "A", "basic", "request", ":" ]
python
train
23.596154
softlayer/softlayer-python
SoftLayer/managers/hardware.py
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/hardware.py#L688-L703
def _get_default_price_id(items, option, hourly, location): """Returns a 'free' price id given an option.""" for item in items: if utils.lookup(item, 'itemCategory', 'categoryCode') != option: continue for price in item['prices']: if all([float(price.get('hourlyRecurrin...
[ "def", "_get_default_price_id", "(", "items", ",", "option", ",", "hourly", ",", "location", ")", ":", "for", "item", "in", "items", ":", "if", "utils", ".", "lookup", "(", "item", ",", "'itemCategory'", ",", "'categoryCode'", ")", "!=", "option", ":", "...
Returns a 'free' price id given an option.
[ "Returns", "a", "free", "price", "id", "given", "an", "option", "." ]
python
train
39.5625
PmagPy/PmagPy
programs/demag_gui.py
https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/programs/demag_gui.py#L3668-L3692
def select_specimen(self, specimen): """ Goes through the calculations necessary to plot measurement data for specimen and sets specimen as current GUI specimen, also attempts to handle changing current fit. """ try: fit_index = self.pmag_results_data['specime...
[ "def", "select_specimen", "(", "self", ",", "specimen", ")", ":", "try", ":", "fit_index", "=", "self", ".", "pmag_results_data", "[", "'specimens'", "]", "[", "self", ".", "s", "]", ".", "index", "(", "self", ".", "current_fit", ")", "except", "KeyError...
Goes through the calculations necessary to plot measurement data for specimen and sets specimen as current GUI specimen, also attempts to handle changing current fit.
[ "Goes", "through", "the", "calculations", "necessary", "to", "plot", "measurement", "data", "for", "specimen", "and", "sets", "specimen", "as", "current", "GUI", "specimen", "also", "attempts", "to", "handle", "changing", "current", "fit", "." ]
python
train
39.96
dask/dask-kubernetes
dask_kubernetes/core.py
https://github.com/dask/dask-kubernetes/blob/8a4883ecd902460b446bb1f43ed97efe398a135e/dask_kubernetes/core.py#L522-L535
def _namespace_default(): """ Get current namespace if running in a k8s cluster If not in a k8s cluster with service accounts enabled, default to 'default' Taken from https://github.com/jupyterhub/kubespawner/blob/master/kubespawner/spawner.py#L125 """ ns_path = '/var/run/secrets/kubernete...
[ "def", "_namespace_default", "(", ")", ":", "ns_path", "=", "'/var/run/secrets/kubernetes.io/serviceaccount/namespace'", "if", "os", ".", "path", ".", "exists", "(", "ns_path", ")", ":", "with", "open", "(", "ns_path", ")", "as", "f", ":", "return", "f", ".", ...
Get current namespace if running in a k8s cluster If not in a k8s cluster with service accounts enabled, default to 'default' Taken from https://github.com/jupyterhub/kubespawner/blob/master/kubespawner/spawner.py#L125
[ "Get", "current", "namespace", "if", "running", "in", "a", "k8s", "cluster" ]
python
train
32.785714
mushkevych/scheduler
synergy/db/dao/unit_of_work_dao.py
https://github.com/mushkevych/scheduler/blob/6740331360f49083c208085fb5a60ce80ebf418b/synergy/db/dao/unit_of_work_dao.py#L147-L150
def run_query(self, query): """ method runs the query and returns a list of filtered UnitOfWork records """ cursor = self.ds.filter(COLLECTION_UNIT_OF_WORK, query) return [UnitOfWork.from_json(document) for document in cursor]
[ "def", "run_query", "(", "self", ",", "query", ")", ":", "cursor", "=", "self", ".", "ds", ".", "filter", "(", "COLLECTION_UNIT_OF_WORK", ",", "query", ")", "return", "[", "UnitOfWork", ".", "from_json", "(", "document", ")", "for", "document", "in", "cu...
method runs the query and returns a list of filtered UnitOfWork records
[ "method", "runs", "the", "query", "and", "returns", "a", "list", "of", "filtered", "UnitOfWork", "records" ]
python
train
61.75
angr/angr
angr/analyses/reassembler.py
https://github.com/angr/angr/blob/4e2f97d56af5419ee73bdb30482c8dd8ff5f3e40/angr/analyses/reassembler.py#L2615-L2639
def _cgc_package_list_identifier(self, data_addr, data_size): """ Identifies the CGC package list associated with the CGC binary. :param int data_addr: Address of the data in memory. :param int data_size: Maximum size possible. :return: A 2-tuple of data type and size. :...
[ "def", "_cgc_package_list_identifier", "(", "self", ",", "data_addr", ",", "data_size", ")", ":", "if", "data_size", "<", "100", ":", "return", "None", ",", "None", "data", "=", "self", ".", "fast_memory_load", "(", "data_addr", ",", "data_size", ",", "str",...
Identifies the CGC package list associated with the CGC binary. :param int data_addr: Address of the data in memory. :param int data_size: Maximum size possible. :return: A 2-tuple of data type and size. :rtype: tuple
[ "Identifies", "the", "CGC", "package", "list", "associated", "with", "the", "CGC", "binary", "." ]
python
train
31.4
explosion/spaCy
spacy/pipeline/entityruler.py
https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/pipeline/entityruler.py#L186-L198
def to_disk(self, path, **kwargs): """Save the entity ruler patterns to a directory. The patterns will be saved as newline-delimited JSON (JSONL). path (unicode / Path): The JSONL file to load. **kwargs: Other config paramters, mostly for consistency. RETURNS (EntityRuler): The ...
[ "def", "to_disk", "(", "self", ",", "path", ",", "*", "*", "kwargs", ")", ":", "path", "=", "ensure_path", "(", "path", ")", "path", "=", "path", ".", "with_suffix", "(", "\".jsonl\"", ")", "srsly", ".", "write_jsonl", "(", "path", ",", "self", ".", ...
Save the entity ruler patterns to a directory. The patterns will be saved as newline-delimited JSON (JSONL). path (unicode / Path): The JSONL file to load. **kwargs: Other config paramters, mostly for consistency. RETURNS (EntityRuler): The loaded entity ruler. DOCS: https://sp...
[ "Save", "the", "entity", "ruler", "patterns", "to", "a", "directory", ".", "The", "patterns", "will", "be", "saved", "as", "newline", "-", "delimited", "JSON", "(", "JSONL", ")", "." ]
python
train
39.846154
tradenity/python-sdk
tradenity/resources/variant.py
https://github.com/tradenity/python-sdk/blob/d13fbe23f4d6ff22554c6d8d2deaf209371adaf1/tradenity/resources/variant.py#L1066-L1087
def update_variant_by_id(cls, variant_id, variant, **kwargs): """Update Variant Update attributes of Variant This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.update_variant_by_id(variant_id, va...
[ "def", "update_variant_by_id", "(", "cls", ",", "variant_id", ",", "variant", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async'", ")", ":", "return", "cls", ".", "_up...
Update Variant Update attributes of Variant This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.update_variant_by_id(variant_id, variant, async=True) >>> result = thread.get() :param asyn...
[ "Update", "Variant" ]
python
train
43.727273
iclab/centinel
centinel/primitives/http.py
https://github.com/iclab/centinel/blob/9a25dcf30c6a1db3c046f7ccb8ab8873e455c1a4/centinel/primitives/http.py#L244-L344
def get_requests_batch(input_list, results={}, delay_time=0.5, max_threads=100): """ This is a parallel version of the HTTP GET primitive. :param input_list: the input is a list of either dictionaries containing query information, or just domain names (and NOT URLs). :param delay...
[ "def", "get_requests_batch", "(", "input_list", ",", "results", "=", "{", "}", ",", "delay_time", "=", "0.5", ",", "max_threads", "=", "100", ")", ":", "threads", "=", "[", "]", "thread_error", "=", "False", "thread_wait_timeout", "=", "200", "ind", "=", ...
This is a parallel version of the HTTP GET primitive. :param input_list: the input is a list of either dictionaries containing query information, or just domain names (and NOT URLs). :param delay_time: delay before starting each thread :param max_threads: maximum number of concurrent...
[ "This", "is", "a", "parallel", "version", "of", "the", "HTTP", "GET", "primitive", "." ]
python
train
32.90099
pantsbuild/pants
src/python/pants/engine/native.py
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/engine/native.py#L296-L298
def extern_equals(self, context_handle, val1, val2): """Return true if the given Handles are __eq__.""" return self._ffi.from_handle(val1[0]) == self._ffi.from_handle(val2[0])
[ "def", "extern_equals", "(", "self", ",", "context_handle", ",", "val1", ",", "val2", ")", ":", "return", "self", ".", "_ffi", ".", "from_handle", "(", "val1", "[", "0", "]", ")", "==", "self", ".", "_ffi", ".", "from_handle", "(", "val2", "[", "0", ...
Return true if the given Handles are __eq__.
[ "Return", "true", "if", "the", "given", "Handles", "are", "__eq__", "." ]
python
train
60.333333
westurner/pyrpo
pyrpo/pyrpo.py
https://github.com/westurner/pyrpo/blob/2a910af055dc405b761571a52ef87842397ddadf/pyrpo/pyrpo.py#L596-L606
def hgsub_report(self): """ Yields: str: .hgsubs line for this repository """ if self.relpath == '.': return yield "%s = [%s]%s" % ( self.fpath.lstrip('./'), self.label, self.remote_url)
[ "def", "hgsub_report", "(", "self", ")", ":", "if", "self", ".", "relpath", "==", "'.'", ":", "return", "yield", "\"%s = [%s]%s\"", "%", "(", "self", ".", "fpath", ".", "lstrip", "(", "'./'", ")", ",", "self", ".", "label", ",", "self", ".", "remote_...
Yields: str: .hgsubs line for this repository
[ "Yields", ":", "str", ":", ".", "hgsubs", "line", "for", "this", "repository" ]
python
train
25.090909
jrigden/pyPodcastParser
pyPodcastParser/Podcast.py
https://github.com/jrigden/pyPodcastParser/blob/b21e027bb56ec77986d76fc1990f4e420c6de869/pyPodcastParser/Podcast.py#L289-L294
def set_itunes_author_name(self): """Parses author name from itunes tags and sets value""" try: self.itunes_author_name = self.soup.find('itunes:author').string except AttributeError: self.itunes_author_name = None
[ "def", "set_itunes_author_name", "(", "self", ")", ":", "try", ":", "self", ".", "itunes_author_name", "=", "self", ".", "soup", ".", "find", "(", "'itunes:author'", ")", ".", "string", "except", "AttributeError", ":", "self", ".", "itunes_author_name", "=", ...
Parses author name from itunes tags and sets value
[ "Parses", "author", "name", "from", "itunes", "tags", "and", "sets", "value" ]
python
train
42.833333
halcy/Mastodon.py
mastodon/Mastodon.py
https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L742-L752
def status(self, id): """ Fetch information about a single toot. Does not require authentication for publicly visible statuses. Returns a `toot dict`_. """ id = self.__unpack_id(id) url = '/api/v1/statuses/{0}'.format(str(id)) return self.__api_request('...
[ "def", "status", "(", "self", ",", "id", ")", ":", "id", "=", "self", ".", "__unpack_id", "(", "id", ")", "url", "=", "'/api/v1/statuses/{0}'", ".", "format", "(", "str", "(", "id", ")", ")", "return", "self", ".", "__api_request", "(", "'GET'", ",",...
Fetch information about a single toot. Does not require authentication for publicly visible statuses. Returns a `toot dict`_.
[ "Fetch", "information", "about", "a", "single", "toot", "." ]
python
train
29.090909
twilio/twilio-python
twilio/rest/api/v2010/account/call/feedback.py
https://github.com/twilio/twilio-python/blob/c867895f55dcc29f522e6e8b8868d0d18483132f/twilio/rest/api/v2010/account/call/feedback.py#L259-L273
def _proxy(self): """ Generate an instance context for the instance, the context is capable of performing various actions. All instance actions are proxied to the context :returns: FeedbackContext for this FeedbackInstance :rtype: twilio.rest.api.v2010.account.call.feedback.Fee...
[ "def", "_proxy", "(", "self", ")", ":", "if", "self", ".", "_context", "is", "None", ":", "self", ".", "_context", "=", "FeedbackContext", "(", "self", ".", "_version", ",", "account_sid", "=", "self", ".", "_solution", "[", "'account_sid'", "]", ",", ...
Generate an instance context for the instance, the context is capable of performing various actions. All instance actions are proxied to the context :returns: FeedbackContext for this FeedbackInstance :rtype: twilio.rest.api.v2010.account.call.feedback.FeedbackContext
[ "Generate", "an", "instance", "context", "for", "the", "instance", "the", "context", "is", "capable", "of", "performing", "various", "actions", ".", "All", "instance", "actions", "are", "proxied", "to", "the", "context" ]
python
train
39.666667
inasafe/inasafe
safe/gis/raster/contour.py
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gis/raster/contour.py#L53-L68
def gaussian_kernel(sigma, truncate=4.0): """Return Gaussian that truncates at the given number of std deviations. Adapted from https://github.com/nicjhan/gaussian-filter """ sigma = float(sigma) radius = int(truncate * sigma + 0.5) x, y = np.mgrid[-radius:radius + 1, -radius:radius + 1] ...
[ "def", "gaussian_kernel", "(", "sigma", ",", "truncate", "=", "4.0", ")", ":", "sigma", "=", "float", "(", "sigma", ")", "radius", "=", "int", "(", "truncate", "*", "sigma", "+", "0.5", ")", "x", ",", "y", "=", "np", ".", "mgrid", "[", "-", "radi...
Return Gaussian that truncates at the given number of std deviations. Adapted from https://github.com/nicjhan/gaussian-filter
[ "Return", "Gaussian", "that", "truncates", "at", "the", "given", "number", "of", "std", "deviations", "." ]
python
train
25.8125
peri-source/peri
peri/conf.py
https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/conf.py#L55-L61
def read_environment(): """ Read all environment variables to see if they contain PERI """ out = {} for k,v in iteritems(os.environ): if transform(k) in default_conf: out[transform(k)] = v return out
[ "def", "read_environment", "(", ")", ":", "out", "=", "{", "}", "for", "k", ",", "v", "in", "iteritems", "(", "os", ".", "environ", ")", ":", "if", "transform", "(", "k", ")", "in", "default_conf", ":", "out", "[", "transform", "(", "k", ")", "]"...
Read all environment variables to see if they contain PERI
[ "Read", "all", "environment", "variables", "to", "see", "if", "they", "contain", "PERI" ]
python
valid
32.714286
spookey/photon
photon/util/locations.py
https://github.com/spookey/photon/blob/57212a26ce713ab7723910ee49e3d0ba1697799f/photon/util/locations.py#L105-L162
def search_location(loc, locations=None, critical=False, create_in=None, verbose=True): ''' Locates files with a twist: * Check the existence of a file using the full path in `loc` * Search for the filename `loc` in `locations` * Create it's enclosing folders if th...
[ "def", "search_location", "(", "loc", ",", "locations", "=", "None", ",", "critical", "=", "False", ",", "create_in", "=", "None", ",", "verbose", "=", "True", ")", ":", "from", "photon", ".", "util", ".", "structures", "import", "to_list", "from", "phot...
Locates files with a twist: * Check the existence of a file using the full path in `loc` * Search for the filename `loc` in `locations` * Create it's enclosing folders if the file does not exist. \ use `create_in` :param loc: Filename to search :param locations: ...
[ "Locates", "files", "with", "a", "twist", ":" ]
python
train
30.086207
oceanprotocol/squid-py
squid_py/keeper/multi_event_listener.py
https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/keeper/multi_event_listener.py#L33-L43
def make_event_filter(self, filter_key, filter_value): """Create a new event filter.""" event_filter = EventFilter( self.event_name, self.event, {filter_key: filter_value}, from_block=self.from_block, to_block=self.to_block ) ev...
[ "def", "make_event_filter", "(", "self", ",", "filter_key", ",", "filter_value", ")", ":", "event_filter", "=", "EventFilter", "(", "self", ".", "event_name", ",", "self", ".", "event", ",", "{", "filter_key", ":", "filter_value", "}", ",", "from_block", "="...
Create a new event filter.
[ "Create", "a", "new", "event", "filter", "." ]
python
train
33.727273
caktus/django-timepiece
timepiece/entries/views.py
https://github.com/caktus/django-timepiece/blob/52515dec027664890efbc535429e1ba1ee152f40/timepiece/entries/views.py#L286-L315
def delete_entry(request, entry_id): """ Give the user the ability to delete a log entry, with a confirmation beforehand. If this method is invoked via a GET request, a form asking for a confirmation of intent will be presented to the user. If this method is invoked via a POST request, the entry wi...
[ "def", "delete_entry", "(", "request", ",", "entry_id", ")", ":", "try", ":", "entry", "=", "Entry", ".", "no_join", ".", "get", "(", "pk", "=", "entry_id", ",", "user", "=", "request", ".", "user", ")", "except", "Entry", ".", "DoesNotExist", ":", "...
Give the user the ability to delete a log entry, with a confirmation beforehand. If this method is invoked via a GET request, a form asking for a confirmation of intent will be presented to the user. If this method is invoked via a POST request, the entry will be deleted.
[ "Give", "the", "user", "the", "ability", "to", "delete", "a", "log", "entry", "with", "a", "confirmation", "beforehand", ".", "If", "this", "method", "is", "invoked", "via", "a", "GET", "request", "a", "form", "asking", "for", "a", "confirmation", "of", ...
python
train
40.366667
aws/sagemaker-python-sdk
src/sagemaker/workflow/airflow.py
https://github.com/aws/sagemaker-python-sdk/blob/a9e724c7d3f5572b68c3903548c792a59d99799a/src/sagemaker/workflow/airflow.py#L60-L83
def prepare_amazon_algorithm_estimator(estimator, inputs, mini_batch_size=None): """ Set up amazon algorithm estimator, adding the required `feature_dim` hyperparameter from training data. Args: estimator (sagemaker.amazon.amazon_estimator.AmazonAlgorithmEstimatorBase): An estimator for a b...
[ "def", "prepare_amazon_algorithm_estimator", "(", "estimator", ",", "inputs", ",", "mini_batch_size", "=", "None", ")", ":", "if", "isinstance", "(", "inputs", ",", "list", ")", ":", "for", "record", "in", "inputs", ":", "if", "isinstance", "(", "record", ",...
Set up amazon algorithm estimator, adding the required `feature_dim` hyperparameter from training data. Args: estimator (sagemaker.amazon.amazon_estimator.AmazonAlgorithmEstimatorBase): An estimator for a built-in Amazon algorithm to get information from and update. inputs: The training...
[ "Set", "up", "amazon", "algorithm", "estimator", "adding", "the", "required", "feature_dim", "hyperparameter", "from", "training", "data", "." ]
python
train
56.458333
juiceinc/recipe
recipe/validators.py
https://github.com/juiceinc/recipe/blob/2e60c2242aeaea3029a2274b31bc3a937761e568/recipe/validators.py#L66-L72
def _normalize_coerce_to_format_with_lookup(self, v): """ Replace a format with a default """ try: return self.format_lookup.get(v, v) except TypeError: # v is something we can't lookup (like a list) return v
[ "def", "_normalize_coerce_to_format_with_lookup", "(", "self", ",", "v", ")", ":", "try", ":", "return", "self", ".", "format_lookup", ".", "get", "(", "v", ",", "v", ")", "except", "TypeError", ":", "# v is something we can't lookup (like a list)", "return", "v" ...
Replace a format with a default
[ "Replace", "a", "format", "with", "a", "default" ]
python
train
37.428571
useblocks/sphinxcontrib-needs
sphinxcontrib/needs/functions/functions.py
https://github.com/useblocks/sphinxcontrib-needs/blob/f49af4859a74e9fe76de5b9133c01335ac6ae191/sphinxcontrib/needs/functions/functions.py#L210-L272
def _analyze_func_string(func_string): """ Analyze given functiion string an extract: * function name * function arguments * function keyword arguments All given arguments must by of type string, int/float or list. :param func_string: string of the function :return: function name, arg...
[ "def", "_analyze_func_string", "(", "func_string", ")", ":", "func", "=", "ast", ".", "parse", "(", "func_string", ")", "try", ":", "func_call", "=", "func", ".", "body", "[", "0", "]", ".", "value", "func_name", "=", "func_call", ".", "func", ".", "id...
Analyze given functiion string an extract: * function name * function arguments * function keyword arguments All given arguments must by of type string, int/float or list. :param func_string: string of the function :return: function name, arguments, keyword arguments
[ "Analyze", "given", "functiion", "string", "an", "extract", ":" ]
python
train
34.206349
pypa/pipenv
pipenv/patched/pipfile/api.py
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/pipfile/api.py#L157-L162
def load(klass, filename, inject_env=True): """Load a Pipfile from a given filename.""" p = PipfileParser(filename=filename) pipfile = klass(filename=filename) pipfile.data = p.parse(inject_env=inject_env) return pipfile
[ "def", "load", "(", "klass", ",", "filename", ",", "inject_env", "=", "True", ")", ":", "p", "=", "PipfileParser", "(", "filename", "=", "filename", ")", "pipfile", "=", "klass", "(", "filename", "=", "filename", ")", "pipfile", ".", "data", "=", "p", ...
Load a Pipfile from a given filename.
[ "Load", "a", "Pipfile", "from", "a", "given", "filename", "." ]
python
train
42.5
numenta/htmresearch
htmresearch/frameworks/layers/laminar_network.py
https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/frameworks/layers/laminar_network.py#L50-L73
def createNetwork(networkConfig): """ Create and initialize the specified network instance. @param networkConfig: (dict) the configuration of this network. @return network: (Network) The actual network """ registerAllResearchRegions() network = Network() if networkConfig["networkType"] == "L4L2Colum...
[ "def", "createNetwork", "(", "networkConfig", ")", ":", "registerAllResearchRegions", "(", ")", "network", "=", "Network", "(", ")", "if", "networkConfig", "[", "\"networkType\"", "]", "==", "\"L4L2Column\"", ":", "return", "createL4L2Column", "(", "network", ",",...
Create and initialize the specified network instance. @param networkConfig: (dict) the configuration of this network. @return network: (Network) The actual network
[ "Create", "and", "initialize", "the", "specified", "network", "instance", "." ]
python
train
41.125
projectatomic/atomic-reactor
atomic_reactor/plugins/pre_resolve_composes.py
https://github.com/projectatomic/atomic-reactor/blob/fd31c01b964097210bf169960d051e5f04019a80/atomic_reactor/plugins/pre_resolve_composes.py#L281-L303
def resolve_signing_intent(self): """Determine the correct signing intent Regardless of what was requested, or provided as signing_intent plugin parameter, consult sigkeys of the actual composes used to guarantee information accuracy. """ all_signing_intents = [ sel...
[ "def", "resolve_signing_intent", "(", "self", ")", ":", "all_signing_intents", "=", "[", "self", ".", "odcs_config", ".", "get_signing_intent_by_keys", "(", "compose_info", ".", "get", "(", "'sigkeys'", ",", "[", "]", ")", ")", "for", "compose_info", "in", "se...
Determine the correct signing intent Regardless of what was requested, or provided as signing_intent plugin parameter, consult sigkeys of the actual composes used to guarantee information accuracy.
[ "Determine", "the", "correct", "signing", "intent" ]
python
train
45.26087
williballenthin/ida-settings
ida_settings/ui/ida_settings_viewer.py
https://github.com/williballenthin/ida-settings/blob/ddfeab5bd0b6f6f177d0d50f8078c585602b1d9e/ida_settings/ui/ida_settings_viewer.py#L19-L64
def PopulateForm(self): """ +-----------------------------------------------------------------------+ | +--- splitter ------------------------------------------------------+ | | | +-- list widget--------------+ +- IdaSettingsView -------------+ | | | | | ...
[ "def", "PopulateForm", "(", "self", ")", ":", "hbox", "=", "QtWidgets", ".", "QHBoxLayout", "(", "self", ".", "parent", ")", "self", ".", "_splitter", "=", "QtWidgets", ".", "QSplitter", "(", "QtCore", ".", "Qt", ".", "Horizontal", ")", "self", ".", "_...
+-----------------------------------------------------------------------+ | +--- splitter ------------------------------------------------------+ | | | +-- list widget--------------+ +- IdaSettingsView -------------+ | | | | | | | | |...
[ "+", "-----------------------------------------------------------------------", "+", "|", "+", "---", "splitter", "------------------------------------------------------", "+", "|", "|", "|", "+", "--", "list", "widget", "--------------", "+", "+", "-", "IdaSettingsView", "...
python
test
61.913043
MisterY/gnucash-portfolio
gnucash_portfolio/scheduledtxaggregate.py
https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/scheduledtxaggregate.py#L173-L212
def handle_friday(next_date: Datum, period: str, mult: int, start_date: Datum): """ Extracted the calculation for when the next_day is Friday """ assert isinstance(next_date, Datum) assert isinstance(start_date, Datum) # Starting from line 220. tmp_sat = next_date.clone() tmp_sat.add_days(1) ...
[ "def", "handle_friday", "(", "next_date", ":", "Datum", ",", "period", ":", "str", ",", "mult", ":", "int", ",", "start_date", ":", "Datum", ")", ":", "assert", "isinstance", "(", "next_date", ",", "Datum", ")", "assert", "isinstance", "(", "start_date", ...
Extracted the calculation for when the next_day is Friday
[ "Extracted", "the", "calculation", "for", "when", "the", "next_day", "is", "Friday" ]
python
train
36.15
tensorflow/tensor2tensor
tensor2tensor/models/research/glow_ops.py
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/glow_ops.py#L804-L843
def temporal_latent_to_dist(name, x, hparams, output_channels=None): """Network that maps a time-indexed list of 3-D latents to a gaussian. Args: name: variable scope. x: List of 4-D Tensors indexed by time, (NHWC) hparams: tf.contrib.training.Hparams. output_channels: int, Number of channels of th...
[ "def", "temporal_latent_to_dist", "(", "name", ",", "x", ",", "hparams", ",", "output_channels", "=", "None", ")", ":", "_", ",", "_", ",", "width", ",", "_", ",", "res_channels", "=", "common_layers", ".", "shape_list", "(", "x", ")", "if", "output_chan...
Network that maps a time-indexed list of 3-D latents to a gaussian. Args: name: variable scope. x: List of 4-D Tensors indexed by time, (NHWC) hparams: tf.contrib.training.Hparams. output_channels: int, Number of channels of the output gaussian mean. Returns: dist: tfp.distributions.Normal
[ "Network", "that", "maps", "a", "time", "-", "indexed", "list", "of", "3", "-", "D", "latents", "to", "a", "gaussian", "." ]
python
train
44.35
fastai/fastai
fastai/vision/gan.py
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/gan.py#L28-L39
def basic_generator(in_size:int, n_channels:int, noise_sz:int=100, n_features:int=64, n_extra_layers=0, **conv_kwargs): "A basic generator from `noise_sz` to images `n_channels` x `in_size` x `in_size`." cur_size, cur_ftrs = 4, n_features//2 while cur_size < in_size: cur_size *= 2; cur_ftrs *= 2 layers...
[ "def", "basic_generator", "(", "in_size", ":", "int", ",", "n_channels", ":", "int", ",", "noise_sz", ":", "int", "=", "100", ",", "n_features", ":", "int", "=", "64", ",", "n_extra_layers", "=", "0", ",", "*", "*", "conv_kwargs", ")", ":", "cur_size",...
A basic generator from `noise_sz` to images `n_channels` x `in_size` x `in_size`.
[ "A", "basic", "generator", "from", "noise_sz", "to", "images", "n_channels", "x", "in_size", "x", "in_size", "." ]
python
train
66.916667
wummel/linkchecker
third_party/miniboa-r42/chat_demo.py
https://github.com/wummel/linkchecker/blob/c2ce810c3fb00b895a841a7be6b2e78c64e7b042/third_party/miniboa-r42/chat_demo.py#L37-L44
def on_disconnect(client): """ Sample on_disconnect function. Handles lost connections. """ print "-- Lost connection to %s" % client.addrport() CLIENT_LIST.remove(client) broadcast('%s leaves the conversation.\n' % client.addrport() )
[ "def", "on_disconnect", "(", "client", ")", ":", "print", "\"-- Lost connection to %s\"", "%", "client", ".", "addrport", "(", ")", "CLIENT_LIST", ".", "remove", "(", "client", ")", "broadcast", "(", "'%s leaves the conversation.\\n'", "%", "client", ".", "addrpor...
Sample on_disconnect function. Handles lost connections.
[ "Sample", "on_disconnect", "function", ".", "Handles", "lost", "connections", "." ]
python
train
32
myint/autoflake
autoflake.py
https://github.com/myint/autoflake/blob/68fea68646922b920d55975f9f2adaeafd84df4f/autoflake.py#L726-L728
def _split_comma_separated(string): """Return a set of strings.""" return set(text.strip() for text in string.split(',') if text.strip())
[ "def", "_split_comma_separated", "(", "string", ")", ":", "return", "set", "(", "text", ".", "strip", "(", ")", "for", "text", "in", "string", ".", "split", "(", "','", ")", "if", "text", ".", "strip", "(", ")", ")" ]
Return a set of strings.
[ "Return", "a", "set", "of", "strings", "." ]
python
test
47.666667
ninuxorg/nodeshot
nodeshot/networking/net/models/device.py
https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/networking/net/models/device.py#L60-L99
def save(self, *args, **kwargs): """ Custom save method does the following: * automatically inherit node coordinates and elevation * save shortcuts if HSTORE is enabled """ custom_checks = kwargs.pop('custom_checks', True) super(Device, self).save(*args, ...
[ "def", "save", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "custom_checks", "=", "kwargs", ".", "pop", "(", "'custom_checks'", ",", "True", ")", "super", "(", "Device", ",", "self", ")", ".", "save", "(", "*", "args", ",", "...
Custom save method does the following: * automatically inherit node coordinates and elevation * save shortcuts if HSTORE is enabled
[ "Custom", "save", "method", "does", "the", "following", ":", "*", "automatically", "inherit", "node", "coordinates", "and", "elevation", "*", "save", "shortcuts", "if", "HSTORE", "is", "enabled" ]
python
train
28.3
sorgerlab/indra
indra/literature/pubmed_client.py
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/literature/pubmed_client.py#L303-L364
def get_metadata_from_xml_tree(tree, get_issns_from_nlm=False, get_abstracts=False, prepend_title=False, mesh_annotations=False): """Get metadata for an XML tree containing PubmedArticle elements. Documentation on the XML structure can be found at: ...
[ "def", "get_metadata_from_xml_tree", "(", "tree", ",", "get_issns_from_nlm", "=", "False", ",", "get_abstracts", "=", "False", ",", "prepend_title", "=", "False", ",", "mesh_annotations", "=", "False", ")", ":", "# Iterate over the articles and build the results dict", ...
Get metadata for an XML tree containing PubmedArticle elements. Documentation on the XML structure can be found at: - https://www.nlm.nih.gov/bsd/licensee/elements_descriptions.html - https://www.nlm.nih.gov/bsd/licensee/elements_alphabetical.html Parameters ---------- tree : xml.etree...
[ "Get", "metadata", "for", "an", "XML", "tree", "containing", "PubmedArticle", "elements", "." ]
python
train
40.080645
glitchassassin/lackey
lackey/__init__.py
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/__init__.py#L204-L214
def inputText(message="", title="Lackey Input", lines=9, width=20, text=""): """ Creates a textarea dialog with the specified message and default text. Returns the entered value. """ root = tk.Tk() input_text = tk.StringVar() input_text.set(text) PopupTextarea(root, message, title, lines, width...
[ "def", "inputText", "(", "message", "=", "\"\"", ",", "title", "=", "\"Lackey Input\"", ",", "lines", "=", "9", ",", "width", "=", "20", ",", "text", "=", "\"\"", ")", ":", "root", "=", "tk", ".", "Tk", "(", ")", "input_text", "=", "tk", ".", "St...
Creates a textarea dialog with the specified message and default text. Returns the entered value.
[ "Creates", "a", "textarea", "dialog", "with", "the", "specified", "message", "and", "default", "text", "." ]
python
train
36.272727
explosion/spaCy
spacy/lang/de/syntax_iterators.py
https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/lang/de/syntax_iterators.py#L7-L46
def noun_chunks(obj): """ Detect base noun phrases from a dependency parse. Works on both Doc and Span. """ # this iterator extracts spans headed by NOUNs starting from the left-most # syntactic dependent until the NOUN itself for close apposition and # measurement construction, the span is some...
[ "def", "noun_chunks", "(", "obj", ")", ":", "# this iterator extracts spans headed by NOUNs starting from the left-most", "# syntactic dependent until the NOUN itself for close apposition and", "# measurement construction, the span is sometimes extended to the right of", "# the NOUN. Example: \"ei...
Detect base noun phrases from a dependency parse. Works on both Doc and Span.
[ "Detect", "base", "noun", "phrases", "from", "a", "dependency", "parse", ".", "Works", "on", "both", "Doc", "and", "Span", "." ]
python
train
34.875
chaoss/grimoirelab-elk
grimoire_elk/enriched/study_ceres_onion.py
https://github.com/chaoss/grimoirelab-elk/blob/64e08b324b36d9f6909bf705145d6451c8d34e65/grimoire_elk/enriched/study_ceres_onion.py#L133-L180
def write(self, items): """Write items into ElasticSearch. :param items: Pandas DataFrame """ if self._read_only: raise IOError("Cannot write, Connector created as Read Only") if len(items) == 0: logger.info(self.__log_prefix + " Nothing to write") ...
[ "def", "write", "(", "self", ",", "items", ")", ":", "if", "self", ".", "_read_only", ":", "raise", "IOError", "(", "\"Cannot write, Connector created as Read Only\"", ")", "if", "len", "(", "items", ")", "==", "0", ":", "logger", ".", "info", "(", "self",...
Write items into ElasticSearch. :param items: Pandas DataFrame
[ "Write", "items", "into", "ElasticSearch", "." ]
python
train
37.9375
GuiltyTargets/ppi-network-annotation
src/ppi_network_annotation/model/filtered_network.py
https://github.com/GuiltyTargets/ppi-network-annotation/blob/4d7b6713485f2d0a0957e6457edc1b1b5a237460/src/ppi_network_annotation/model/filtered_network.py#L27-L41
def get_upregulated_genes_network(self) -> Graph: """Get the graph of up-regulated genes. :return Graph: Graph of up-regulated genes. """ logger.info("In get_upregulated_genes_network()") deg_graph = self.graph.copy() # deep copy graph not_diff_expr = self.graph.vs(up_...
[ "def", "get_upregulated_genes_network", "(", "self", ")", "->", "Graph", ":", "logger", ".", "info", "(", "\"In get_upregulated_genes_network()\"", ")", "deg_graph", "=", "self", ".", "graph", ".", "copy", "(", ")", "# deep copy graph", "not_diff_expr", "=", "self...
Get the graph of up-regulated genes. :return Graph: Graph of up-regulated genes.
[ "Get", "the", "graph", "of", "up", "-", "regulated", "genes", "." ]
python
train
38.2
spulec/moto
moto/batch/models.py
https://github.com/spulec/moto/blob/4a286c4bc288933bb023396e2784a6fdbb966bc9/moto/batch/models.py#L669-L716
def _validate_compute_resources(self, cr): """ Checks contents of sub dictionary for managed clusters :param cr: computeResources :type cr: dict """ for param in ('instanceRole', 'maxvCpus', 'minvCpus', 'instanceTypes', 'securityGroupIds', 'subnets', 'type'): ...
[ "def", "_validate_compute_resources", "(", "self", ",", "cr", ")", ":", "for", "param", "in", "(", "'instanceRole'", ",", "'maxvCpus'", ",", "'minvCpus'", ",", "'instanceTypes'", ",", "'securityGroupIds'", ",", "'subnets'", ",", "'type'", ")", ":", "if", "para...
Checks contents of sub dictionary for managed clusters :param cr: computeResources :type cr: dict
[ "Checks", "contents", "of", "sub", "dictionary", "for", "managed", "clusters" ]
python
train
49.833333
skelsec/minidump
minidump/minidumpreader.py
https://github.com/skelsec/minidump/blob/0c4dcabe6f11d7a403440919ffa9e3c9889c5212/minidump/minidumpreader.py#L172-L184
def find_all(self, pattern): """ Searches for all occurrences of a pattern in the current memory segment, returns all occurrences as a list """ pos = [] last_found = -1 while True: last_found = self.current_segment.data.find(pattern, last_found + 1) if last_found == -1: break pos.append(last_fo...
[ "def", "find_all", "(", "self", ",", "pattern", ")", ":", "pos", "=", "[", "]", "last_found", "=", "-", "1", "while", "True", ":", "last_found", "=", "self", ".", "current_segment", ".", "data", ".", "find", "(", "pattern", ",", "last_found", "+", "1...
Searches for all occurrences of a pattern in the current memory segment, returns all occurrences as a list
[ "Searches", "for", "all", "occurrences", "of", "a", "pattern", "in", "the", "current", "memory", "segment", "returns", "all", "occurrences", "as", "a", "list" ]
python
train
28.153846
ibis-project/ibis
ibis/clickhouse/client.py
https://github.com/ibis-project/ibis/blob/1e39a5fd9ef088b45c155e8a5f541767ee8ef2e7/ibis/clickhouse/client.py#L266-L294
def list_tables(self, like=None, database=None): """ List tables in the current (or indicated) database. Like the SHOW TABLES command in the clickhouse-shell. Parameters ---------- like : string, default None e.g. 'foo*' to match all tables starting with 'foo' ...
[ "def", "list_tables", "(", "self", ",", "like", "=", "None", ",", "database", "=", "None", ")", ":", "statement", "=", "'SHOW TABLES'", "if", "database", ":", "statement", "+=", "\" FROM `{0}`\"", ".", "format", "(", "database", ")", "if", "like", ":", "...
List tables in the current (or indicated) database. Like the SHOW TABLES command in the clickhouse-shell. Parameters ---------- like : string, default None e.g. 'foo*' to match all tables starting with 'foo' database : string, default None If not passed, uses...
[ "List", "tables", "in", "the", "current", "(", "or", "indicated", ")", "database", ".", "Like", "the", "SHOW", "TABLES", "command", "in", "the", "clickhouse", "-", "shell", "." ]
python
train
33.241379
apple/turicreate
src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/json_format.py
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/json_format.py#L285-L299
def _ValueMessageToJsonObject(self, message): """Converts Value message according to Proto3 JSON Specification.""" which = message.WhichOneof('kind') # If the Value message is not set treat as null_value when serialize # to JSON. The parse back result will be different from original message. if whic...
[ "def", "_ValueMessageToJsonObject", "(", "self", ",", "message", ")", ":", "which", "=", "message", ".", "WhichOneof", "(", "'kind'", ")", "# If the Value message is not set treat as null_value when serialize", "# to JSON. The parse back result will be different from original messa...
Converts Value message according to Proto3 JSON Specification.
[ "Converts", "Value", "message", "according", "to", "Proto3", "JSON", "Specification", "." ]
python
train
46.4
twoolie/NBT
nbt/region.py
https://github.com/twoolie/NBT/blob/b06dd6cc8117d2788da1d8416e642d58bad45762/nbt/region.py#L754-L759
def _classname(self): """Return the fully qualified class name.""" if self.__class__.__module__ in (None,): return self.__class__.__name__ else: return "%s.%s" % (self.__class__.__module__, self.__class__.__name__)
[ "def", "_classname", "(", "self", ")", ":", "if", "self", ".", "__class__", ".", "__module__", "in", "(", "None", ",", ")", ":", "return", "self", ".", "__class__", ".", "__name__", "else", ":", "return", "\"%s.%s\"", "%", "(", "self", ".", "__class__"...
Return the fully qualified class name.
[ "Return", "the", "fully", "qualified", "class", "name", "." ]
python
train
42.833333
oauthlib/oauthlib
oauthlib/oauth1/rfc5849/__init__.py
https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth1/rfc5849/__init__.py#L188-L223
def _render(self, request, formencode=False, realm=None): """Render a signed request according to signature type Returns a 3-tuple containing the request URI, headers, and body. If the formencode argument is True and the body contains parameters, it is escaped and returned as a valid f...
[ "def", "_render", "(", "self", ",", "request", ",", "formencode", "=", "False", ",", "realm", "=", "None", ")", ":", "# TODO what if there are body params on a header-type auth?", "# TODO what if there are query params on a body-type auth?", "uri", ",", "headers", ",", "b...
Render a signed request according to signature type Returns a 3-tuple containing the request URI, headers, and body. If the formencode argument is True and the body contains parameters, it is escaped and returned as a valid formencoded string.
[ "Render", "a", "signed", "request", "according", "to", "signature", "type" ]
python
train
51.527778
gwpy/gwpy
gwpy/table/io/fetch.py
https://github.com/gwpy/gwpy/blob/7a92b917e7dd2d99b15895293a1fa1d66cdb210a/gwpy/table/io/fetch.py#L67-L95
def get_fetcher(data_format, data_class): """Return the :meth:`~EventTable.fetch` function for the given format Parameters ---------- data_format : `str` name of the format data_class : `type` the class that the fetcher returns Raises ------ astropy.io.registry.IORegis...
[ "def", "get_fetcher", "(", "data_format", ",", "data_class", ")", ":", "# this is a copy of astropy.io.regsitry.get_reader", "fetchers", "=", "[", "(", "fmt", ",", "cls", ")", "for", "fmt", ",", "cls", "in", "_FETCHERS", "if", "fmt", "==", "data_format", "]", ...
Return the :meth:`~EventTable.fetch` function for the given format Parameters ---------- data_format : `str` name of the format data_class : `type` the class that the fetcher returns Raises ------ astropy.io.registry.IORegistryError if not registration is found mat...
[ "Return", "the", ":", "meth", ":", "~EventTable", ".", "fetch", "function", "for", "the", "given", "format" ]
python
train
36.655172
mfcloud/python-zvm-sdk
zvmsdk/smtclient.py
https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/zvmsdk/smtclient.py#L2125-L2132
def get_guest_connection_status(self, userid): '''Get guest vm connection status.''' rd = ' '.join(('getvm', userid, 'isreachable')) results = self._request(rd) if results['rs'] == 1: return True else: return False
[ "def", "get_guest_connection_status", "(", "self", ",", "userid", ")", ":", "rd", "=", "' '", ".", "join", "(", "(", "'getvm'", ",", "userid", ",", "'isreachable'", ")", ")", "results", "=", "self", ".", "_request", "(", "rd", ")", "if", "results", "["...
Get guest vm connection status.
[ "Get", "guest", "vm", "connection", "status", "." ]
python
train
33.875
pytroll/posttroll
posttroll/listener.py
https://github.com/pytroll/posttroll/blob/8e811a0544b5182c4a72aed074b2ff8c4324e94d/posttroll/listener.py#L105-L115
def create_subscriber(self): '''Create a subscriber instance using specified addresses and message types. ''' if self.subscriber is None: if self.topics: self.subscriber = NSSubscriber(self.services, self.topics, ...
[ "def", "create_subscriber", "(", "self", ")", ":", "if", "self", ".", "subscriber", "is", "None", ":", "if", "self", ".", "topics", ":", "self", ".", "subscriber", "=", "NSSubscriber", "(", "self", ".", "services", ",", "self", ".", "topics", ",", "add...
Create a subscriber instance using specified addresses and message types.
[ "Create", "a", "subscriber", "instance", "using", "specified", "addresses", "and", "message", "types", "." ]
python
train
48.545455
cggh/scikit-allel
allel/model/ndarray.py
https://github.com/cggh/scikit-allel/blob/3c979a57a100240ba959dd13f98839349530f215/allel/model/ndarray.py#L2358-L2404
def count_alleles(self, max_allele=None, subpop=None): """Count the number of calls of each allele per variant. Parameters ---------- max_allele : int, optional The highest allele index to count. Alleles greater than this index will be ignored. subpop : a...
[ "def", "count_alleles", "(", "self", ",", "max_allele", "=", "None", ",", "subpop", "=", "None", ")", ":", "# check inputs", "subpop", "=", "_normalize_subpop_arg", "(", "subpop", ",", "self", ".", "shape", "[", "1", "]", ")", "# determine alleles to count", ...
Count the number of calls of each allele per variant. Parameters ---------- max_allele : int, optional The highest allele index to count. Alleles greater than this index will be ignored. subpop : array_like, int, optional Indices of haplotypes to incl...
[ "Count", "the", "number", "of", "calls", "of", "each", "allele", "per", "variant", "." ]
python
train
28.531915
ontio/ontology-python-sdk
ontology/io/binary_reader.py
https://github.com/ontio/ontology-python-sdk/blob/ac88bdda941896c5d2ced08422a9c5179d3f9b19/ontology/io/binary_reader.py#L375-L388
def read_hashes(self): """ Read Hash values from the stream. Returns: list: a list of hash values. Each value is of the bytearray type. """ var_len = self.read_var_int() items = [] for _ in range(0, var_len): ba = bytearray(self.read_bytes...
[ "def", "read_hashes", "(", "self", ")", ":", "var_len", "=", "self", ".", "read_var_int", "(", ")", "items", "=", "[", "]", "for", "_", "in", "range", "(", "0", ",", "var_len", ")", ":", "ba", "=", "bytearray", "(", "self", ".", "read_bytes", "(", ...
Read Hash values from the stream. Returns: list: a list of hash values. Each value is of the bytearray type.
[ "Read", "Hash", "values", "from", "the", "stream", "." ]
python
train
28.071429
pyopenapi/pyswagger
pyswagger/scanner/v1_2/validate.py
https://github.com/pyopenapi/pyswagger/blob/333c4ca08e758cd2194943d9904a3eda3fe43977/pyswagger/scanner/v1_2/validate.py#L115-L122
def _validate_granttype(self, path, obj, _): """ make sure either implicit or authorization_code is defined """ errs = [] if not obj.implicit and not obj.authorization_code: errs.append('Either implicit or authorization_code should be defined.') return path, obj.__class__._...
[ "def", "_validate_granttype", "(", "self", ",", "path", ",", "obj", ",", "_", ")", ":", "errs", "=", "[", "]", "if", "not", "obj", ".", "implicit", "and", "not", "obj", ".", "authorization_code", ":", "errs", ".", "append", "(", "'Either implicit or auth...
make sure either implicit or authorization_code is defined
[ "make", "sure", "either", "implicit", "or", "authorization_code", "is", "defined" ]
python
train
40.75