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 |
|---|---|---|---|---|---|---|---|---|---|
faucamp/python-gsmmodem | tools/gsmtermlib/terminal.py | https://github.com/faucamp/python-gsmmodem/blob/834c68b1387ca2c91e2210faa8f75526b39723b5/tools/gsmtermlib/terminal.py#L343-L350 | def _handleBackspace(self):
""" Handles backspace characters """
if self.cursorPos > 0:
#print( 'cp:',self.cursorPos,'was:', self.inputBuffer)
self.inputBuffer = self.inputBuffer[0:self.cursorPos-1] + self.inputBuffer[self.cursorPos:]
self.cursorPos -= 1
#... | [
"def",
"_handleBackspace",
"(",
"self",
")",
":",
"if",
"self",
".",
"cursorPos",
">",
"0",
":",
"#print( 'cp:',self.cursorPos,'was:', self.inputBuffer)",
"self",
".",
"inputBuffer",
"=",
"self",
".",
"inputBuffer",
"[",
"0",
":",
"self",
".",
"cursorPos",
"-",
... | Handles backspace characters | [
"Handles",
"backspace",
"characters"
] | python | train | 56.5 |
BerkeleyAutomation/autolab_core | autolab_core/transformations.py | https://github.com/BerkeleyAutomation/autolab_core/blob/8f3813f6401972868cc5e3981ba1b4382d4418d5/autolab_core/transformations.py#L1649-L1662 | def concatenate_matrices(*matrices):
"""Return concatenation of series of transformation matrices.
>>> M = numpy.random.rand(16).reshape((4, 4)) - 0.5
>>> numpy.allclose(M, concatenate_matrices(M))
True
>>> numpy.allclose(numpy.dot(M, M.T), concatenate_matrices(M, M.T))
True
"""
M = nu... | [
"def",
"concatenate_matrices",
"(",
"*",
"matrices",
")",
":",
"M",
"=",
"numpy",
".",
"identity",
"(",
"4",
")",
"for",
"i",
"in",
"matrices",
":",
"M",
"=",
"numpy",
".",
"dot",
"(",
"M",
",",
"i",
")",
"return",
"M"
] | Return concatenation of series of transformation matrices.
>>> M = numpy.random.rand(16).reshape((4, 4)) - 0.5
>>> numpy.allclose(M, concatenate_matrices(M))
True
>>> numpy.allclose(numpy.dot(M, M.T), concatenate_matrices(M, M.T))
True | [
"Return",
"concatenation",
"of",
"series",
"of",
"transformation",
"matrices",
"."
] | python | train | 27.571429 |
scott-griffiths/bitstring | bitstring.py | https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L1687-L1699 | def _getse(self):
"""Return data as signed exponential-Golomb code.
Raises InterpretError if bitstring is not a single exponential-Golomb code.
"""
try:
value, newpos = self._readse(0)
if value is None or newpos != self.len:
raise ReadError
... | [
"def",
"_getse",
"(",
"self",
")",
":",
"try",
":",
"value",
",",
"newpos",
"=",
"self",
".",
"_readse",
"(",
"0",
")",
"if",
"value",
"is",
"None",
"or",
"newpos",
"!=",
"self",
".",
"len",
":",
"raise",
"ReadError",
"except",
"ReadError",
":",
"r... | Return data as signed exponential-Golomb code.
Raises InterpretError if bitstring is not a single exponential-Golomb code. | [
"Return",
"data",
"as",
"signed",
"exponential",
"-",
"Golomb",
"code",
"."
] | python | train | 33.538462 |
gem/oq-engine | openquake/hazardlib/sourcewriter.py | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/sourcewriter.py#L271-L285 | def build_hypo_depth_dist(hdd):
"""
Returns the hypocentral depth distribution as a Node instance
:param hdd:
Hypocentral depth distribution as an instance of :class:
`openquake.hzardlib.pmf.PMF`
:returns:
Instance of :class:`openquake.baselib.node.Node`
"""
hdds = []
... | [
"def",
"build_hypo_depth_dist",
"(",
"hdd",
")",
":",
"hdds",
"=",
"[",
"]",
"for",
"(",
"prob",
",",
"depth",
")",
"in",
"hdd",
".",
"data",
":",
"hdds",
".",
"append",
"(",
"Node",
"(",
"\"hypoDepth\"",
",",
"{",
"\"depth\"",
":",
"depth",
",",
"... | Returns the hypocentral depth distribution as a Node instance
:param hdd:
Hypocentral depth distribution as an instance of :class:
`openquake.hzardlib.pmf.PMF`
:returns:
Instance of :class:`openquake.baselib.node.Node` | [
"Returns",
"the",
"hypocentral",
"depth",
"distribution",
"as",
"a",
"Node",
"instance"
] | python | train | 31.6 |
aheadley/python-crunchyroll | crunchyroll/apis/meta.py | https://github.com/aheadley/python-crunchyroll/blob/9bf2eb644f0d0f3e9dc21b95b8e355c6e2050178/crunchyroll/apis/meta.py#L91-L104 | def require_ajax_logged_in(func):
"""Check if ajax API is logged in and login if not
"""
@functools.wraps(func)
def inner_func(self, *pargs, **kwargs):
if not self._ajax_api.logged_in:
logger.info('Logging into AJAX API for required meta method')
if not self.has_credentia... | [
"def",
"require_ajax_logged_in",
"(",
"func",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"inner_func",
"(",
"self",
",",
"*",
"pargs",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"self",
".",
"_ajax_api",
".",
"logged_in",
... | Check if ajax API is logged in and login if not | [
"Check",
"if",
"ajax",
"API",
"is",
"logged",
"in",
"and",
"login",
"if",
"not"
] | python | train | 43.357143 |
alex-kostirin/pyatomac | atomac/AXClasses.py | https://github.com/alex-kostirin/pyatomac/blob/3f46f6feb4504315eec07abb18bb41be4d257aeb/atomac/AXClasses.py#L673-L677 | def _getActions(self):
"""Retrieve a list of actions supported by the object."""
actions = _a11y.AXUIElement._getActions(self)
# strip leading AX from actions - help distinguish them from attributes
return [action[2:] for action in actions] | [
"def",
"_getActions",
"(",
"self",
")",
":",
"actions",
"=",
"_a11y",
".",
"AXUIElement",
".",
"_getActions",
"(",
"self",
")",
"# strip leading AX from actions - help distinguish them from attributes",
"return",
"[",
"action",
"[",
"2",
":",
"]",
"for",
"action",
... | Retrieve a list of actions supported by the object. | [
"Retrieve",
"a",
"list",
"of",
"actions",
"supported",
"by",
"the",
"object",
"."
] | python | valid | 53.6 |
joshuaduffy/dota2api | dota2api/src/parse.py | https://github.com/joshuaduffy/dota2api/blob/03c9e1c609ec36728805bbd3ada0a53ec8f51e86/dota2api/src/parse.py#L40-L56 | def item_id(response):
"""
Parse the item ids, will be available as ``item_0_name``, ``item_1_name``,
``item_2_name`` and so on
"""
dict_keys = ['item_0', 'item_1', 'item_2',
'item_3', 'item_4', 'item_5']
new_keys = ['item_0_name', 'item_1_name', 'item_2_name',
'... | [
"def",
"item_id",
"(",
"response",
")",
":",
"dict_keys",
"=",
"[",
"'item_0'",
",",
"'item_1'",
",",
"'item_2'",
",",
"'item_3'",
",",
"'item_4'",
",",
"'item_5'",
"]",
"new_keys",
"=",
"[",
"'item_0_name'",
",",
"'item_1_name'",
",",
"'item_2_name'",
",",
... | Parse the item ids, will be available as ``item_0_name``, ``item_1_name``,
``item_2_name`` and so on | [
"Parse",
"the",
"item",
"ids",
"will",
"be",
"available",
"as",
"item_0_name",
"item_1_name",
"item_2_name",
"and",
"so",
"on"
] | python | train | 35.823529 |
CenturyLinkCloud/clc-python-sdk | src/clc/APIv1/api.py | https://github.com/CenturyLinkCloud/clc-python-sdk/blob/f4dba40c627cb08dd4b7d0d277e8d67578010b05/src/clc/APIv1/api.py#L76-L137 | def Call(method,url,payload,silent=False,hide_errors=[],session=None,recursion_cnt=0,debug=False):
"""Execute v1 API call.
:param url: URL paths associated with the API call
:param payload: dict containing all parameters to submit with POST call
:param hide_errors: list of API error codes to ignore. These are... | [
"def",
"Call",
"(",
"method",
",",
"url",
",",
"payload",
",",
"silent",
"=",
"False",
",",
"hide_errors",
"=",
"[",
"]",
",",
"session",
"=",
"None",
",",
"recursion_cnt",
"=",
"0",
",",
"debug",
"=",
"False",
")",
":",
"if",
"not",
"clc",
".",
... | Execute v1 API call.
:param url: URL paths associated with the API call
:param payload: dict containing all parameters to submit with POST call
:param hide_errors: list of API error codes to ignore. These are not http error codes but returned from the API itself
:param recursion_cnt: recursion counter. This ... | [
"Execute",
"v1",
"API",
"call",
"."
] | python | train | 48.322581 |
ambitioninc/django-entity | entity/models.py | https://github.com/ambitioninc/django-entity/blob/ebc61f34313c52f4ef5819eb1da25b2ad837e80c/entity/models.py#L170-L177 | def delete_for_obj(self, entity_model_obj):
"""
Delete the entities associated with a model object.
"""
return self.filter(
entity_type=ContentType.objects.get_for_model(
entity_model_obj, for_concrete_model=False), entity_id=entity_model_obj.id).delete(
... | [
"def",
"delete_for_obj",
"(",
"self",
",",
"entity_model_obj",
")",
":",
"return",
"self",
".",
"filter",
"(",
"entity_type",
"=",
"ContentType",
".",
"objects",
".",
"get_for_model",
"(",
"entity_model_obj",
",",
"for_concrete_model",
"=",
"False",
")",
",",
... | Delete the entities associated with a model object. | [
"Delete",
"the",
"entities",
"associated",
"with",
"a",
"model",
"object",
"."
] | python | train | 41.375 |
uogbuji/amara3-xml | pylib/uxml/uxpath/functions.py | https://github.com/uogbuji/amara3-xml/blob/88c18876418cffc89bb85b4a3193e5002b6b39a6/pylib/uxml/uxpath/functions.py#L119-L127 | def concat(ctx, *strings):
'''
Yields one string, concatenation of argument strings
'''
strings = flatten([ (s.compute(ctx) if callable(s) else s) for s in strings ])
strings = (next(string_arg(ctx, s), '') for s in strings)
#assert(all(map(lambda x: isinstance(x, str), strings)))
#FIXME: Ch... | [
"def",
"concat",
"(",
"ctx",
",",
"*",
"strings",
")",
":",
"strings",
"=",
"flatten",
"(",
"[",
"(",
"s",
".",
"compute",
"(",
"ctx",
")",
"if",
"callable",
"(",
"s",
")",
"else",
"s",
")",
"for",
"s",
"in",
"strings",
"]",
")",
"strings",
"="... | Yields one string, concatenation of argument strings | [
"Yields",
"one",
"string",
"concatenation",
"of",
"argument",
"strings"
] | python | test | 39.111111 |
konstantinstadler/pymrio | pymrio/tools/ioutil.py | https://github.com/konstantinstadler/pymrio/blob/d764aa0dd2150200e867a9713a98ddae203e12d4/pymrio/tools/ioutil.py#L324-L333 | def unique_element(ll):
""" returns unique elements from a list preserving the original order """
seen = {}
result = []
for item in ll:
if item in seen:
continue
seen[item] = 1
result.append(item)
return result | [
"def",
"unique_element",
"(",
"ll",
")",
":",
"seen",
"=",
"{",
"}",
"result",
"=",
"[",
"]",
"for",
"item",
"in",
"ll",
":",
"if",
"item",
"in",
"seen",
":",
"continue",
"seen",
"[",
"item",
"]",
"=",
"1",
"result",
".",
"append",
"(",
"item",
... | returns unique elements from a list preserving the original order | [
"returns",
"unique",
"elements",
"from",
"a",
"list",
"preserving",
"the",
"original",
"order"
] | python | train | 25.7 |
iotaledger/iota.lib.py | iota/commands/extended/get_new_addresses.py | https://github.com/iotaledger/iota.lib.py/blob/97cdd1e241498446b46157b79b2a1ea2ec6d387a/iota/commands/extended/get_new_addresses.py#L53-L73 | def _find_addresses(self, seed, index, count, security_level, checksum):
# type: (Seed, int, Optional[int], int, bool) -> List[Address]
"""
Find addresses matching the command parameters.
"""
generator = AddressGenerator(seed, security_level, checksum)
if count is None:
... | [
"def",
"_find_addresses",
"(",
"self",
",",
"seed",
",",
"index",
",",
"count",
",",
"security_level",
",",
"checksum",
")",
":",
"# type: (Seed, int, Optional[int], int, bool) -> List[Address]",
"generator",
"=",
"AddressGenerator",
"(",
"seed",
",",
"security_level",
... | Find addresses matching the command parameters. | [
"Find",
"addresses",
"matching",
"the",
"command",
"parameters",
"."
] | python | test | 41.428571 |
DLR-RM/RAFCON | source/rafcon/core/execution/execution_engine.py | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/core/execution/execution_engine.py#L82-L91 | def finished_or_stopped(self):
""" Condition check on finished or stopped status
The method returns a value which is equivalent with not 'active' status of the current state machine.
:return: outcome of condition check stopped or finished
:rtype: bool
"""
return (self._... | [
"def",
"finished_or_stopped",
"(",
"self",
")",
":",
"return",
"(",
"self",
".",
"_status",
".",
"execution_mode",
"is",
"StateMachineExecutionStatus",
".",
"STOPPED",
")",
"or",
"(",
"self",
".",
"_status",
".",
"execution_mode",
"is",
"StateMachineExecutionStatu... | Condition check on finished or stopped status
The method returns a value which is equivalent with not 'active' status of the current state machine.
:return: outcome of condition check stopped or finished
:rtype: bool | [
"Condition",
"check",
"on",
"finished",
"or",
"stopped",
"status"
] | python | train | 46.2 |
invenia/Arbiter | arbiter/task.py | https://github.com/invenia/Arbiter/blob/51008393ae8797da85bcd67807259a157f941dfd/arbiter/task.py#L14-L50 | def create_task(function, *args, **kwargs):
"""
Create a task object
name: The name of the task.
function: The actual task function. It should take no arguments,
and return a False-y value if it fails.
dependencies: (optional, ()) Any dependencies that this task relies
on.
"""
... | [
"def",
"create_task",
"(",
"function",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"name",
"=",
"\"{}\"",
".",
"format",
"(",
"uuid4",
"(",
")",
")",
"handler",
"=",
"None",
"deps",
"=",
"set",
"(",
")",
"if",
"'name'",
"in",
"kwargs",
"... | Create a task object
name: The name of the task.
function: The actual task function. It should take no arguments,
and return a False-y value if it fails.
dependencies: (optional, ()) Any dependencies that this task relies
on. | [
"Create",
"a",
"task",
"object",
"name",
":",
"The",
"name",
"of",
"the",
"task",
".",
"function",
":",
"The",
"actual",
"task",
"function",
".",
"It",
"should",
"take",
"no",
"arguments",
"and",
"return",
"a",
"False",
"-",
"y",
"value",
"if",
"it",
... | python | train | 27.459459 |
elijahr/lk | lk.py | https://github.com/elijahr/lk/blob/78f10909b1d8bb3ebe16223dd5438a1201b7db97/lk.py#L14-L66 | def build_parser():
"""
Returns an argparse.ArgumentParser instance to parse the command line
arguments for lk
"""
import argparse
description = "A programmer's search tool, parallel and fast"
parser = argparse.ArgumentParser(description=description)
parser.add_argument('pattern', metava... | [
"def",
"build_parser",
"(",
")",
":",
"import",
"argparse",
"description",
"=",
"\"A programmer's search tool, parallel and fast\"",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"description",
")",
"parser",
".",
"add_argument",
"(",
"'pa... | Returns an argparse.ArgumentParser instance to parse the command line
arguments for lk | [
"Returns",
"an",
"argparse",
".",
"ArgumentParser",
"instance",
"to",
"parse",
"the",
"command",
"line",
"arguments",
"for",
"lk"
] | python | train | 59.622642 |
dhylands/rshell | rshell/main.py | https://github.com/dhylands/rshell/blob/a92a8fa8074ac792241c83c640a51b394667c324/rshell/main.py#L482-L491 | def process_pattern(fn):
"""Return a list of paths matching a pattern (or None on error).
"""
directory, pattern = validate_pattern(fn)
if directory is not None:
filenames = fnmatch.filter(auto(listdir, directory), pattern)
if filenames:
return [directory + '/' + sfn for sfn ... | [
"def",
"process_pattern",
"(",
"fn",
")",
":",
"directory",
",",
"pattern",
"=",
"validate_pattern",
"(",
"fn",
")",
"if",
"directory",
"is",
"not",
"None",
":",
"filenames",
"=",
"fnmatch",
".",
"filter",
"(",
"auto",
"(",
"listdir",
",",
"directory",
"... | Return a list of paths matching a pattern (or None on error). | [
"Return",
"a",
"list",
"of",
"paths",
"matching",
"a",
"pattern",
"(",
"or",
"None",
"on",
"error",
")",
"."
] | python | train | 42 |
RetailMeNotSandbox/acky | acky/s3.py | https://github.com/RetailMeNotSandbox/acky/blob/fcd4d092c42892ede7c924cafc41e9cf4be3fb9f/acky/s3.py#L36-L58 | def get(self, url=None, delimiter="/"):
"""Path is an s3 url. Ommiting the path or providing "s3://" as the
path will return a list of all buckets. Otherwise, all subdirectories
and their contents will be shown.
"""
params = {'Delimiter': delimiter}
bucket, obj_key = _par... | [
"def",
"get",
"(",
"self",
",",
"url",
"=",
"None",
",",
"delimiter",
"=",
"\"/\"",
")",
":",
"params",
"=",
"{",
"'Delimiter'",
":",
"delimiter",
"}",
"bucket",
",",
"obj_key",
"=",
"_parse_url",
"(",
"url",
")",
"if",
"bucket",
":",
"params",
"[",
... | Path is an s3 url. Ommiting the path or providing "s3://" as the
path will return a list of all buckets. Otherwise, all subdirectories
and their contents will be shown. | [
"Path",
"is",
"an",
"s3",
"url",
".",
"Ommiting",
"the",
"path",
"or",
"providing",
"s3",
":",
"//",
"as",
"the",
"path",
"will",
"return",
"a",
"list",
"of",
"all",
"buckets",
".",
"Otherwise",
"all",
"subdirectories",
"and",
"their",
"contents",
"will"... | python | train | 33.608696 |
ArduPilot/MAVProxy | MAVProxy/modules/mavproxy_output.py | https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/mavproxy_output.py#L21-L41 | def cmd_output(self, args):
'''handle output commands'''
if len(args) < 1 or args[0] == "list":
self.cmd_output_list()
elif args[0] == "add":
if len(args) != 2:
print("Usage: output add OUTPUT")
return
self.cmd_output_add(args[1... | [
"def",
"cmd_output",
"(",
"self",
",",
"args",
")",
":",
"if",
"len",
"(",
"args",
")",
"<",
"1",
"or",
"args",
"[",
"0",
"]",
"==",
"\"list\"",
":",
"self",
".",
"cmd_output_list",
"(",
")",
"elif",
"args",
"[",
"0",
"]",
"==",
"\"add\"",
":",
... | handle output commands | [
"handle",
"output",
"commands"
] | python | train | 35.761905 |
elmotec/massedit | massedit.py | https://github.com/elmotec/massedit/blob/57e22787354896d63a8850312314b19aa0308906/massedit.py#L164-L168 | def edit_line(self, line):
"""Edit a single line using the code expression."""
for code, code_obj in self.code_objs.items():
line = self.__edit_line(line, code, code_obj)
return line | [
"def",
"edit_line",
"(",
"self",
",",
"line",
")",
":",
"for",
"code",
",",
"code_obj",
"in",
"self",
".",
"code_objs",
".",
"items",
"(",
")",
":",
"line",
"=",
"self",
".",
"__edit_line",
"(",
"line",
",",
"code",
",",
"code_obj",
")",
"return",
... | Edit a single line using the code expression. | [
"Edit",
"a",
"single",
"line",
"using",
"the",
"code",
"expression",
"."
] | python | train | 42.8 |
Bystroushaak/zeo_connector | src/zeo_connector/transaction_manager.py | https://github.com/Bystroushaak/zeo_connector/blob/93f86447204efc8e33d3112907cd221daf6bce3b/src/zeo_connector/transaction_manager.py#L13-L22 | def transaction_manager(fn):
"""
Decorator which wraps whole function into ``with transaction.manager:``.
"""
@wraps(fn)
def transaction_manager_decorator(*args, **kwargs):
with transaction.manager:
return fn(*args, **kwargs)
return transaction_manager_decorator | [
"def",
"transaction_manager",
"(",
"fn",
")",
":",
"@",
"wraps",
"(",
"fn",
")",
"def",
"transaction_manager_decorator",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"with",
"transaction",
".",
"manager",
":",
"return",
"fn",
"(",
"*",
"args",
... | Decorator which wraps whole function into ``with transaction.manager:``. | [
"Decorator",
"which",
"wraps",
"whole",
"function",
"into",
"with",
"transaction",
".",
"manager",
":",
"."
] | python | train | 29.8 |
joe513/django-cool-pagination | django_cool_paginator/templatetags/paginator_tags.py | https://github.com/joe513/django-cool-pagination/blob/ed75a151a016aef0f5216fdb1e3610597872a3ef/django_cool_paginator/templatetags/paginator_tags.py#L57-L70 | def url_replace(context, field, value):
"""
To avoid GET params losing
:param context: context_obj
:param field: str
:param value: str
:return: dict-like object
"""
query_string = context['request'].GET.copy()
query_string[field] = value
return query_string.urlencode() | [
"def",
"url_replace",
"(",
"context",
",",
"field",
",",
"value",
")",
":",
"query_string",
"=",
"context",
"[",
"'request'",
"]",
".",
"GET",
".",
"copy",
"(",
")",
"query_string",
"[",
"field",
"]",
"=",
"value",
"return",
"query_string",
".",
"urlenco... | To avoid GET params losing
:param context: context_obj
:param field: str
:param value: str
:return: dict-like object | [
"To",
"avoid",
"GET",
"params",
"losing"
] | python | train | 21.357143 |
wtsi-hgi/python-capturewrap | capturewrap/builders.py | https://github.com/wtsi-hgi/python-capturewrap/blob/4ee5f709dee15eb8fd29a57b314ad88c2b5d2247/capturewrap/builders.py#L64-L78 | def _create_capture_exceptions(capture_decider: Callable[[BaseException], bool]) -> Callable:
"""
Creates exception capturer using given capture decider.
:param capture_decider: given the exception as the first arguments, decides whether it should be captured or
not (and hence raised)
... | [
"def",
"_create_capture_exceptions",
"(",
"capture_decider",
":",
"Callable",
"[",
"[",
"BaseException",
"]",
",",
"bool",
"]",
")",
"->",
"Callable",
":",
"def",
"wrapped",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"result",
"=",
"CaptureWrapBu... | Creates exception capturer using given capture decider.
:param capture_decider: given the exception as the first arguments, decides whether it should be captured or
not (and hence raised)
:return: | [
"Creates",
"exception",
"capturer",
"using",
"given",
"capture",
"decider",
".",
":",
"param",
"capture_decider",
":",
"given",
"the",
"exception",
"as",
"the",
"first",
"arguments",
"decides",
"whether",
"it",
"should",
"be",
"captured",
"or",
"not",
"(",
"an... | python | train | 42.866667 |
apache/spark | python/pyspark/mllib/linalg/__init__.py | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/mllib/linalg/__init__.py#L86-L118 | def _vector_size(v):
"""
Returns the size of the vector.
>>> _vector_size([1., 2., 3.])
3
>>> _vector_size((1., 2., 3.))
3
>>> _vector_size(array.array('d', [1., 2., 3.]))
3
>>> _vector_size(np.zeros(3))
3
>>> _vector_size(np.zeros((3, 1)))
3
>>> _vector_size(np.zero... | [
"def",
"_vector_size",
"(",
"v",
")",
":",
"if",
"isinstance",
"(",
"v",
",",
"Vector",
")",
":",
"return",
"len",
"(",
"v",
")",
"elif",
"type",
"(",
"v",
")",
"in",
"(",
"array",
".",
"array",
",",
"list",
",",
"tuple",
",",
"xrange",
")",
":... | Returns the size of the vector.
>>> _vector_size([1., 2., 3.])
3
>>> _vector_size((1., 2., 3.))
3
>>> _vector_size(array.array('d', [1., 2., 3.]))
3
>>> _vector_size(np.zeros(3))
3
>>> _vector_size(np.zeros((3, 1)))
3
>>> _vector_size(np.zeros((1, 3)))
Traceback (most re... | [
"Returns",
"the",
"size",
"of",
"the",
"vector",
"."
] | python | train | 30.212121 |
chrisspen/burlap | burlap/files.py | https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/files.py#L334-L340 | def remove(self, path, recursive=False, use_sudo=False):
"""
Remove a file or directory
"""
func = use_sudo and run_as_root or self.run
options = '-r ' if recursive else ''
func('/bin/rm {0}{1}'.format(options, quote(path))) | [
"def",
"remove",
"(",
"self",
",",
"path",
",",
"recursive",
"=",
"False",
",",
"use_sudo",
"=",
"False",
")",
":",
"func",
"=",
"use_sudo",
"and",
"run_as_root",
"or",
"self",
".",
"run",
"options",
"=",
"'-r '",
"if",
"recursive",
"else",
"''",
"func... | Remove a file or directory | [
"Remove",
"a",
"file",
"or",
"directory"
] | python | valid | 38 |
postmanlabs/httpbin | httpbin/core.py | https://github.com/postmanlabs/httpbin/blob/f8ec666b4d1b654e4ff6aedd356f510dcac09f83/httpbin/core.py#L1315-L1344 | def cache():
"""Returns a 304 if an If-Modified-Since header or If-None-Match is present. Returns the same as a GET otherwise.
---
tags:
- Response inspection
parameters:
- in: header
name: If-Modified-Since
- in: header
name: If-None-Match
produces:
- applica... | [
"def",
"cache",
"(",
")",
":",
"is_conditional",
"=",
"request",
".",
"headers",
".",
"get",
"(",
"\"If-Modified-Since\"",
")",
"or",
"request",
".",
"headers",
".",
"get",
"(",
"\"If-None-Match\"",
")",
"if",
"is_conditional",
"is",
"None",
":",
"response",... | Returns a 304 if an If-Modified-Since header or If-None-Match is present. Returns the same as a GET otherwise.
---
tags:
- Response inspection
parameters:
- in: header
name: If-Modified-Since
- in: header
name: If-None-Match
produces:
- application/json
respon... | [
"Returns",
"a",
"304",
"if",
"an",
"If",
"-",
"Modified",
"-",
"Since",
"header",
"or",
"If",
"-",
"None",
"-",
"Match",
"is",
"present",
".",
"Returns",
"the",
"same",
"as",
"a",
"GET",
"otherwise",
".",
"---",
"tags",
":",
"-",
"Response",
"inspect... | python | train | 25.5 |
neovim/pynvim | pynvim/plugin/decorators.py | https://github.com/neovim/pynvim/blob/5e577188e6d7133f597ad0ce60dc6a4b1314064a/pynvim/plugin/decorators.py#L121-L149 | def function(name, range=False, sync=False, allow_nested=False, eval=None):
"""Tag a function or plugin method as a Nvim function handler."""
def dec(f):
f._nvim_rpc_method_name = 'function:{}'.format(name)
f._nvim_rpc_sync = sync
f._nvim_bind = True
f._nvim_prefix_plugin_path = ... | [
"def",
"function",
"(",
"name",
",",
"range",
"=",
"False",
",",
"sync",
"=",
"False",
",",
"allow_nested",
"=",
"False",
",",
"eval",
"=",
"None",
")",
":",
"def",
"dec",
"(",
"f",
")",
":",
"f",
".",
"_nvim_rpc_method_name",
"=",
"'function:{}'",
"... | Tag a function or plugin method as a Nvim function handler. | [
"Tag",
"a",
"function",
"or",
"plugin",
"method",
"as",
"a",
"Nvim",
"function",
"handler",
"."
] | python | train | 25.724138 |
guaix-ucm/numina | numina/array/display/polfit_residuals.py | https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/array/display/polfit_residuals.py#L463-L658 | def polfit_residuals_with_cook_rejection(
x, y, deg, times_sigma_cook,
color='b', size=75,
xlim=None, ylim=None,
xlabel=None, ylabel=None, title=None,
use_r=None,
geometry=(0,0,640,480),
debugplot=0):
"""Polynomial fit with iterative rejection of points.
... | [
"def",
"polfit_residuals_with_cook_rejection",
"(",
"x",
",",
"y",
",",
"deg",
",",
"times_sigma_cook",
",",
"color",
"=",
"'b'",
",",
"size",
"=",
"75",
",",
"xlim",
"=",
"None",
",",
"ylim",
"=",
"None",
",",
"xlabel",
"=",
"None",
",",
"ylabel",
"="... | Polynomial fit with iterative rejection of points.
This function makes use of function polfit_residuals for display
purposes.
Parameters
----------
x : 1d numpy array, float
X coordinates of the data being fitted.
y : 1d numpy array, float
Y coordinates of the data being fitted... | [
"Polynomial",
"fit",
"with",
"iterative",
"rejection",
"of",
"points",
"."
] | python | train | 43 |
Xython/Linq.py | linq/standard/dict.py | https://github.com/Xython/Linq.py/blob/ffb65f92f1df0d8161d5f835f5947554f6f33d72/linq/standard/dict.py#L184-L199 | def Skip(self: dict, n):
"""
[
{
'self': [1, 2, 3, 4, 5],
'n': 3,
'assert': lambda ret: list(ret) == [4, 5]
}
]
"""
con = self.items()
for i, _ in enumerate(con):
if i == n:
break
return... | [
"def",
"Skip",
"(",
"self",
":",
"dict",
",",
"n",
")",
":",
"con",
"=",
"self",
".",
"items",
"(",
")",
"for",
"i",
",",
"_",
"in",
"enumerate",
"(",
"con",
")",
":",
"if",
"i",
"==",
"n",
":",
"break",
"return",
"con"
] | [
{
'self': [1, 2, 3, 4, 5],
'n': 3,
'assert': lambda ret: list(ret) == [4, 5]
}
] | [
"[",
"{",
"self",
":",
"[",
"1",
"2",
"3",
"4",
"5",
"]",
"n",
":",
"3",
"assert",
":",
"lambda",
"ret",
":",
"list",
"(",
"ret",
")",
"==",
"[",
"4",
"5",
"]",
"}",
"]"
] | python | train | 19.3125 |
IBM/ibm-cos-sdk-python-s3transfer | ibm_s3transfer/aspera/futures.py | https://github.com/IBM/ibm-cos-sdk-python-s3transfer/blob/24ba53137213e26e6b8fc2c3ec1e8198d507d22b/ibm_s3transfer/aspera/futures.py#L361-L372 | def set_bytes_transferred(self, bytes_transferred):
''' set the number of bytes transferred - if it has changed return True '''
_changed = False
if bytes_transferred:
_changed = (self._bytes_transferred != int(bytes_transferred))
if _changed:
self._bytes_t... | [
"def",
"set_bytes_transferred",
"(",
"self",
",",
"bytes_transferred",
")",
":",
"_changed",
"=",
"False",
"if",
"bytes_transferred",
":",
"_changed",
"=",
"(",
"self",
".",
"_bytes_transferred",
"!=",
"int",
"(",
"bytes_transferred",
")",
")",
"if",
"_changed",... | set the number of bytes transferred - if it has changed return True | [
"set",
"the",
"number",
"of",
"bytes",
"transferred",
"-",
"if",
"it",
"has",
"changed",
"return",
"True"
] | python | train | 48.5 |
iotaledger/iota.lib.py | iota/transaction/creation.py | https://github.com/iotaledger/iota.lib.py/blob/97cdd1e241498446b46157b79b2a1ea2ec6d387a/iota/transaction/creation.py#L440-L464 | def sign_input_at(self, start_index, private_key):
# type: (int, PrivateKey) -> None
"""
Signs the input at the specified index.
:param start_index:
The index of the first input transaction.
If necessary, the resulting signature will be split across
... | [
"def",
"sign_input_at",
"(",
"self",
",",
"start_index",
",",
"private_key",
")",
":",
"# type: (int, PrivateKey) -> None",
"if",
"not",
"self",
".",
"hash",
":",
"raise",
"RuntimeError",
"(",
"'Cannot sign inputs until bundle is finalized.'",
")",
"private_key",
".",
... | Signs the input at the specified index.
:param start_index:
The index of the first input transaction.
If necessary, the resulting signature will be split across
multiple transactions automatically (i.e., if an input has
``security_level=2``, you still only need ... | [
"Signs",
"the",
"input",
"at",
"the",
"specified",
"index",
"."
] | python | test | 37.24 |
Azure/azure-sdk-for-python | azure-servicebus/azure/servicebus/aio/async_receive_handler.py | https://github.com/Azure/azure-sdk-for-python/blob/d7306fde32f60a293a7567678692bdad31e4b667/azure-servicebus/azure/servicebus/aio/async_receive_handler.py#L625-L667 | async def receive_deferred_messages(self, sequence_numbers, mode=ReceiveSettleMode.PeekLock):
"""Receive messages that have previously been deferred.
This operation can only receive deferred messages from the current session.
When receiving deferred messages from a partitioned entity, all of th... | [
"async",
"def",
"receive_deferred_messages",
"(",
"self",
",",
"sequence_numbers",
",",
"mode",
"=",
"ReceiveSettleMode",
".",
"PeekLock",
")",
":",
"if",
"not",
"sequence_numbers",
":",
"raise",
"ValueError",
"(",
"\"At least one sequence number must be specified.\"",
... | Receive messages that have previously been deferred.
This operation can only receive deferred messages from the current session.
When receiving deferred messages from a partitioned entity, all of the supplied
sequence numbers must be messages from the same partition.
:param sequence_nu... | [
"Receive",
"messages",
"that",
"have",
"previously",
"been",
"deferred",
"."
] | python | test | 46.651163 |
pydata/xarray | xarray/core/combine.py | https://github.com/pydata/xarray/blob/6d93a95d05bdbfc33fff24064f67d29dd891ab58/xarray/core/combine.py#L444-L477 | def _combine_nd(combined_ids, concat_dims, data_vars='all',
coords='different', compat='no_conflicts'):
"""
Concatenates and merges an N-dimensional structure of datasets.
No checks are performed on the consistency of the datasets, concat_dims or
tile_IDs, because it is assumed that thi... | [
"def",
"_combine_nd",
"(",
"combined_ids",
",",
"concat_dims",
",",
"data_vars",
"=",
"'all'",
",",
"coords",
"=",
"'different'",
",",
"compat",
"=",
"'no_conflicts'",
")",
":",
"# Perform N-D dimensional concatenation",
"# Each iteration of this loop reduces the length of ... | Concatenates and merges an N-dimensional structure of datasets.
No checks are performed on the consistency of the datasets, concat_dims or
tile_IDs, because it is assumed that this has already been done.
Parameters
----------
combined_ids : Dict[Tuple[int, ...]], xarray.Dataset]
Structure ... | [
"Concatenates",
"and",
"merges",
"an",
"N",
"-",
"dimensional",
"structure",
"of",
"datasets",
"."
] | python | train | 43.617647 |
tritemio/PyBroMo | pybromo/iter_chunks.py | https://github.com/tritemio/PyBroMo/blob/b75f82a4551ff37e7c7a7e6954c536451f3e6d06/pybromo/iter_chunks.py#L18-L27 | def iter_chunksize(num_samples, chunksize):
"""Iterator used to iterate in chunks over an array of size `num_samples`.
At each iteration returns `chunksize` except for the last iteration.
"""
last_chunksize = int(np.mod(num_samples, chunksize))
chunksize = int(chunksize)
for _ in range(int(num_s... | [
"def",
"iter_chunksize",
"(",
"num_samples",
",",
"chunksize",
")",
":",
"last_chunksize",
"=",
"int",
"(",
"np",
".",
"mod",
"(",
"num_samples",
",",
"chunksize",
")",
")",
"chunksize",
"=",
"int",
"(",
"chunksize",
")",
"for",
"_",
"in",
"range",
"(",
... | Iterator used to iterate in chunks over an array of size `num_samples`.
At each iteration returns `chunksize` except for the last iteration. | [
"Iterator",
"used",
"to",
"iterate",
"in",
"chunks",
"over",
"an",
"array",
"of",
"size",
"num_samples",
".",
"At",
"each",
"iteration",
"returns",
"chunksize",
"except",
"for",
"the",
"last",
"iteration",
"."
] | python | valid | 41.3 |
AustralianSynchrotron/lightflow | lightflow/tasks/bash_task.py | https://github.com/AustralianSynchrotron/lightflow/blob/dc53dbc1d961e20fb144273baca258060705c03e/lightflow/tasks/bash_task.py#L293-L389 | def run(self, data, store, signal, context, **kwargs):
""" The main run method of the Python task.
Args:
data (:class:`.MultiTaskData`): The data object that has been passed from the
predecessor task.
store (:class:`.DataStoreDocument`): The persistent data store... | [
"def",
"run",
"(",
"self",
",",
"data",
",",
"store",
",",
"signal",
",",
"context",
",",
"*",
"*",
"kwargs",
")",
":",
"params",
"=",
"self",
".",
"params",
".",
"eval",
"(",
"data",
",",
"store",
",",
"exclude",
"=",
"[",
"'command'",
"]",
")",... | The main run method of the Python task.
Args:
data (:class:`.MultiTaskData`): The data object that has been passed from the
predecessor task.
store (:class:`.DataStoreDocument`): The persistent data store object that allows the
task to store data for acce... | [
"The",
"main",
"run",
"method",
"of",
"the",
"Python",
"task",
"."
] | python | train | 41.835052 |
persandstrom/python-vasttrafik | vasttrafik/__main__.py | https://github.com/persandstrom/python-vasttrafik/blob/9c657fde1e91229c5878ea25530260596d296d37/vasttrafik/__main__.py#L60-L93 | def print_trip_table(document):
""" Print trip table """
headers = [
'Alt.',
'Name',
'Time',
'Track',
'Direction',
'Dest.',
'Track',
'Arrival']
table = []
altnr = 0
for alternative in document:
altnr += 1
first_trip_in_a... | [
"def",
"print_trip_table",
"(",
"document",
")",
":",
"headers",
"=",
"[",
"'Alt.'",
",",
"'Name'",
",",
"'Time'",
",",
"'Track'",
",",
"'Direction'",
",",
"'Dest.'",
",",
"'Track'",
",",
"'Arrival'",
"]",
"table",
"=",
"[",
"]",
"altnr",
"=",
"0",
"fo... | Print trip table | [
"Print",
"trip",
"table"
] | python | train | 30.911765 |
mayfield/shellish | shellish/layout/table.py | https://github.com/mayfield/shellish/blob/df0f0e4612d138c34d8cb99b66ab5b8e47f1414a/shellish/layout/table.py#L1018-L1041 | def tabulate(data, header=True, headers=None, accessors=None,
**table_options):
""" Shortcut function to produce tabular output of data without the
need to create and configure a Table instance directly. The function
does however return a table instance when it's done for any further use
by... | [
"def",
"tabulate",
"(",
"data",
",",
"header",
"=",
"True",
",",
"headers",
"=",
"None",
",",
"accessors",
"=",
"None",
",",
"*",
"*",
"table_options",
")",
":",
"if",
"header",
"and",
"not",
"headers",
":",
"data",
"=",
"iter",
"(",
"data",
")",
"... | Shortcut function to produce tabular output of data without the
need to create and configure a Table instance directly. The function
does however return a table instance when it's done for any further use
by the user. | [
"Shortcut",
"function",
"to",
"produce",
"tabular",
"output",
"of",
"data",
"without",
"the",
"need",
"to",
"create",
"and",
"configure",
"a",
"Table",
"instance",
"directly",
".",
"The",
"function",
"does",
"however",
"return",
"a",
"table",
"instance",
"when... | python | train | 39.458333 |
deepmind/sonnet | sonnet/python/modules/gated_rnn.py | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/gated_rnn.py#L1748-L1768 | def highway_core_with_recurrent_dropout(
hidden_size,
num_layers,
keep_prob=0.5,
**kwargs):
"""Highway core with recurrent dropout.
Args:
hidden_size: (int) Hidden size dimensionality.
num_layers: (int) Number of highway layers.
keep_prob: the probability to keep an entry when applying ... | [
"def",
"highway_core_with_recurrent_dropout",
"(",
"hidden_size",
",",
"num_layers",
",",
"keep_prob",
"=",
"0.5",
",",
"*",
"*",
"kwargs",
")",
":",
"core",
"=",
"HighwayCore",
"(",
"hidden_size",
",",
"num_layers",
",",
"*",
"*",
"kwargs",
")",
"return",
"... | Highway core with recurrent dropout.
Args:
hidden_size: (int) Hidden size dimensionality.
num_layers: (int) Number of highway layers.
keep_prob: the probability to keep an entry when applying dropout.
**kwargs: Extra keyword arguments to pass to the highway core.
Returns:
A tuple (train_core, ... | [
"Highway",
"core",
"with",
"recurrent",
"dropout",
"."
] | python | train | 33.571429 |
oscarbranson/latools | latools/D_obj.py | https://github.com/oscarbranson/latools/blob/cd25a650cfee318152f234d992708511f7047fbe/latools/D_obj.py#L653-L702 | def filter_gradient_threshold(self, analyte, win, threshold, recalc=True):
"""
Apply gradient threshold filter.
Generates threshold filters for the given analytes above and below
the specified threshold.
Two filters are created with prefixes '_above' and '_below'.
'... | [
"def",
"filter_gradient_threshold",
"(",
"self",
",",
"analyte",
",",
"win",
",",
"threshold",
",",
"recalc",
"=",
"True",
")",
":",
"params",
"=",
"locals",
"(",
")",
"del",
"(",
"params",
"[",
"'self'",
"]",
")",
"# calculate absolute gradient",
"if",
"r... | Apply gradient threshold filter.
Generates threshold filters for the given analytes above and below
the specified threshold.
Two filters are created with prefixes '_above' and '_below'.
'_above' keeps all the data above the threshold.
'_below' keeps all the data below t... | [
"Apply",
"gradient",
"threshold",
"filter",
"."
] | python | test | 33.58 |
tcalmant/ipopo | pelix/ipopo/instance.py | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/instance.py#L667-L710 | def __safe_validation_callback(self, event):
# type: (str) -> Any
"""
Calls the ``@ValidateComponent`` or ``@InvalidateComponent`` callback,
ignoring raised exceptions
:param event: The kind of life-cycle callback (in/validation)
:return: The callback result, or None
... | [
"def",
"__safe_validation_callback",
"(",
"self",
",",
"event",
")",
":",
"# type: (str) -> Any",
"if",
"self",
".",
"state",
"==",
"StoredInstance",
".",
"KILLED",
":",
"# Invalid state",
"return",
"None",
"try",
":",
"return",
"self",
".",
"__validation_callback... | Calls the ``@ValidateComponent`` or ``@InvalidateComponent`` callback,
ignoring raised exceptions
:param event: The kind of life-cycle callback (in/validation)
:return: The callback result, or None | [
"Calls",
"the",
"@ValidateComponent",
"or",
"@InvalidateComponent",
"callback",
"ignoring",
"raised",
"exceptions"
] | python | train | 32.863636 |
jeffh/sniffer | sniffer/scanner/base.py | https://github.com/jeffh/sniffer/blob/8e4c3e77743aef08109ea0225b4a6536d4e60270/sniffer/scanner/base.py#L129-L138 | def in_repo(self, filepath):
"""
This excludes repository directories because they cause some exceptions
occationally.
"""
filepath = set(filepath.replace('\\', '/').split('/'))
for p in ('.git', '.hg', '.svn', '.cvs', '.bzr'):
if p in filepath:
... | [
"def",
"in_repo",
"(",
"self",
",",
"filepath",
")",
":",
"filepath",
"=",
"set",
"(",
"filepath",
".",
"replace",
"(",
"'\\\\'",
",",
"'/'",
")",
".",
"split",
"(",
"'/'",
")",
")",
"for",
"p",
"in",
"(",
"'.git'",
",",
"'.hg'",
",",
"'.svn'",
"... | This excludes repository directories because they cause some exceptions
occationally. | [
"This",
"excludes",
"repository",
"directories",
"because",
"they",
"cause",
"some",
"exceptions",
"occationally",
"."
] | python | train | 34.5 |
xiongchiamiov/pyfixit | pyfixit/guide.py | https://github.com/xiongchiamiov/pyfixit/blob/808a0c852a26e4211b2e3a72da972ab34a586dc4/pyfixit/guide.py#L56-L93 | def refresh(self):
'''Refetch instance data from the API.
'''
response = requests.get('%s/guides/%s' % (API_BASE_URL, self.id))
attributes = response.json()
self.category = Category(attributes['category'])
self.url = attributes['url']
self.title = attributes['titl... | [
"def",
"refresh",
"(",
"self",
")",
":",
"response",
"=",
"requests",
".",
"get",
"(",
"'%s/guides/%s'",
"%",
"(",
"API_BASE_URL",
",",
"self",
".",
"id",
")",
")",
"attributes",
"=",
"response",
".",
"json",
"(",
")",
"self",
".",
"category",
"=",
"... | Refetch instance data from the API. | [
"Refetch",
"instance",
"data",
"from",
"the",
"API",
"."
] | python | train | 48.657895 |
toomore/goristock | grs/timeser.py | https://github.com/toomore/goristock/blob/e61f57f11a626cfbc4afbf66337fd9d1c51e3e71/grs/timeser.py#L41-L98 | def overall(goback = 0, case = 1):
""" To run all over the stock and to find who match the 'case'
'goback' is back to what days ago.
0 is the last day.
"""
from twseno import twseno
for i in twseno().allstock:
#timetest(i)
try:
if case == 1:
try:
a = goristock(i)
... | [
"def",
"overall",
"(",
"goback",
"=",
"0",
",",
"case",
"=",
"1",
")",
":",
"from",
"twseno",
"import",
"twseno",
"for",
"i",
"in",
"twseno",
"(",
")",
".",
"allstock",
":",
"#timetest(i)",
"try",
":",
"if",
"case",
"==",
"1",
":",
"try",
":",
"a... | To run all over the stock and to find who match the 'case'
'goback' is back to what days ago.
0 is the last day. | [
"To",
"run",
"all",
"over",
"the",
"stock",
"and",
"to",
"find",
"who",
"match",
"the",
"case",
"goback",
"is",
"back",
"to",
"what",
"days",
"ago",
".",
"0",
"is",
"the",
"last",
"day",
"."
] | python | train | 34.844828 |
resonai/ybt | yabt/target_utils.py | https://github.com/resonai/ybt/blob/5b40df0922ef3383eb85f2b04a26a2db4b81b3fd/yabt/target_utils.py#L75-L92 | def norm_name(build_module: str, target_name: str):
"""Return a normalized canonical target name for the `target_name`
observed in build module `build_module`.
A normalized canonical target name is of the form "<build module>:<name>",
where <build module> is the relative normalized path from the pro... | [
"def",
"norm_name",
"(",
"build_module",
":",
"str",
",",
"target_name",
":",
"str",
")",
":",
"if",
"':'",
"not",
"in",
"target_name",
":",
"raise",
"ValueError",
"(",
"\"Must provide fully-qualified target name (with `:') to avoid \"",
"\"possible ambiguity - `{}' not v... | Return a normalized canonical target name for the `target_name`
observed in build module `build_module`.
A normalized canonical target name is of the form "<build module>:<name>",
where <build module> is the relative normalized path from the project root
to the target build module (POSIX), and <name... | [
"Return",
"a",
"normalized",
"canonical",
"target",
"name",
"for",
"the",
"target_name",
"observed",
"in",
"build",
"module",
"build_module",
"."
] | python | train | 44.111111 |
jaraco/jaraco.windows | jaraco/windows/filesystem/__init__.py | https://github.com/jaraco/jaraco.windows/blob/51811efed50b46ad08daa25408a1cc806bc8d519/jaraco/windows/filesystem/__init__.py#L306-L343 | def resolve_path(target, start=os.path.curdir):
r"""
Find a path from start to target where target is relative to start.
>>> tmp = str(getfixture('tmpdir_as_cwd'))
>>> findpath('d:\\')
'd:\\'
>>> findpath('d:\\', tmp)
'd:\\'
>>> findpath('\\bar', 'd:\\')
'd:\\bar'
>>> findpath('\\bar', 'd:\\foo') # fails... | [
"def",
"resolve_path",
"(",
"target",
",",
"start",
"=",
"os",
".",
"path",
".",
"curdir",
")",
":",
"return",
"os",
".",
"path",
".",
"normpath",
"(",
"join",
"(",
"start",
",",
"target",
")",
")"
] | r"""
Find a path from start to target where target is relative to start.
>>> tmp = str(getfixture('tmpdir_as_cwd'))
>>> findpath('d:\\')
'd:\\'
>>> findpath('d:\\', tmp)
'd:\\'
>>> findpath('\\bar', 'd:\\')
'd:\\bar'
>>> findpath('\\bar', 'd:\\foo') # fails with '\\bar'
'd:\\bar'
>>> findpath('bar', 'd... | [
"r",
"Find",
"a",
"path",
"from",
"start",
"to",
"target",
"where",
"target",
"is",
"relative",
"to",
"start",
"."
] | python | train | 19.263158 |
pycontribs/pyrax | pyrax/object_storage.py | https://github.com/pycontribs/pyrax/blob/9ddfd5064b3a292d7337906f3b2d5dce95b50b99/pyrax/object_storage.py#L1707-L1712 | def remove_metadata_key(self, key, prefix=None):
"""
Removes the specified key from the storage object's metadata. If the
key does not exist in the metadata, nothing is done.
"""
self.manager.remove_metadata_key(self, key, prefix=prefix) | [
"def",
"remove_metadata_key",
"(",
"self",
",",
"key",
",",
"prefix",
"=",
"None",
")",
":",
"self",
".",
"manager",
".",
"remove_metadata_key",
"(",
"self",
",",
"key",
",",
"prefix",
"=",
"prefix",
")"
] | Removes the specified key from the storage object's metadata. If the
key does not exist in the metadata, nothing is done. | [
"Removes",
"the",
"specified",
"key",
"from",
"the",
"storage",
"object",
"s",
"metadata",
".",
"If",
"the",
"key",
"does",
"not",
"exist",
"in",
"the",
"metadata",
"nothing",
"is",
"done",
"."
] | python | train | 45.333333 |
SBRG/ssbio | ssbio/protein/structure/properties/residues.py | https://github.com/SBRG/ssbio/blob/e9449e64ffc1a1f5ad07e5849aa12a650095f8a2/ssbio/protein/structure/properties/residues.py#L92-L120 | def resname_in_proximity(resname, model, chains, resnums, threshold=5):
"""Search within the proximity of a defined list of residue numbers and their chains for any specifed residue name.
Args:
resname (str): Residue name to search for in proximity of specified chains + resnums
model: Biopython... | [
"def",
"resname_in_proximity",
"(",
"resname",
",",
"model",
",",
"chains",
",",
"resnums",
",",
"threshold",
"=",
"5",
")",
":",
"residues",
"=",
"[",
"r",
"for",
"r",
"in",
"model",
".",
"get_residues",
"(",
")",
"if",
"r",
".",
"get_resname",
"(",
... | Search within the proximity of a defined list of residue numbers and their chains for any specifed residue name.
Args:
resname (str): Residue name to search for in proximity of specified chains + resnums
model: Biopython Model object
chains (str, list): Chain ID or IDs to check
resn... | [
"Search",
"within",
"the",
"proximity",
"of",
"a",
"defined",
"list",
"of",
"residue",
"numbers",
"and",
"their",
"chains",
"for",
"any",
"specifed",
"residue",
"name",
"."
] | python | train | 39.344828 |
pypa/setuptools_scm | src/setuptools_scm/file_finder.py | https://github.com/pypa/setuptools_scm/blob/6e99dc1afdce38dc0c3fb1a31bd50a152fc55cce/src/setuptools_scm/file_finder.py#L4-L56 | def scm_find_files(path, scm_files, scm_dirs):
""" setuptools compatible file finder that follows symlinks
- path: the root directory from which to search
- scm_files: set of scm controlled files and symlinks
(including symlinks to directories)
- scm_dirs: set of scm controlled directories
... | [
"def",
"scm_find_files",
"(",
"path",
",",
"scm_files",
",",
"scm_dirs",
")",
":",
"realpath",
"=",
"os",
".",
"path",
".",
"normcase",
"(",
"os",
".",
"path",
".",
"realpath",
"(",
"path",
")",
")",
"seen",
"=",
"set",
"(",
")",
"res",
"=",
"[",
... | setuptools compatible file finder that follows symlinks
- path: the root directory from which to search
- scm_files: set of scm controlled files and symlinks
(including symlinks to directories)
- scm_dirs: set of scm controlled directories
(including directories containing no scm controlled fil... | [
"setuptools",
"compatible",
"file",
"finder",
"that",
"follows",
"symlinks"
] | python | train | 40.924528 |
openstack/quark | quark/worker_plugins/base_worker.py | https://github.com/openstack/quark/blob/1112e6a66917d3e98e44cb7b33b107fd5a74bb2e/quark/worker_plugins/base_worker.py#L42-L50 | def start_rpc_listeners(self):
"""Configure all listeners here"""
self._setup_rpc()
if not self.endpoints:
return []
self.conn = n_rpc.create_connection()
self.conn.create_consumer(self.topic, self.endpoints,
fanout=False)
ret... | [
"def",
"start_rpc_listeners",
"(",
"self",
")",
":",
"self",
".",
"_setup_rpc",
"(",
")",
"if",
"not",
"self",
".",
"endpoints",
":",
"return",
"[",
"]",
"self",
".",
"conn",
"=",
"n_rpc",
".",
"create_connection",
"(",
")",
"self",
".",
"conn",
".",
... | Configure all listeners here | [
"Configure",
"all",
"listeners",
"here"
] | python | valid | 38.444444 |
pandas-dev/pandas | pandas/io/parsers.py | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/io/parsers.py#L1208-L1218 | def _evaluate_usecols(usecols, names):
"""
Check whether or not the 'usecols' parameter
is a callable. If so, enumerates the 'names'
parameter and returns a set of indices for
each entry in 'names' that evaluates to True.
If not a callable, returns 'usecols'.
"""
if callable(usecols):
... | [
"def",
"_evaluate_usecols",
"(",
"usecols",
",",
"names",
")",
":",
"if",
"callable",
"(",
"usecols",
")",
":",
"return",
"{",
"i",
"for",
"i",
",",
"name",
"in",
"enumerate",
"(",
"names",
")",
"if",
"usecols",
"(",
"name",
")",
"}",
"return",
"usec... | Check whether or not the 'usecols' parameter
is a callable. If so, enumerates the 'names'
parameter and returns a set of indices for
each entry in 'names' that evaluates to True.
If not a callable, returns 'usecols'. | [
"Check",
"whether",
"or",
"not",
"the",
"usecols",
"parameter",
"is",
"a",
"callable",
".",
"If",
"so",
"enumerates",
"the",
"names",
"parameter",
"and",
"returns",
"a",
"set",
"of",
"indices",
"for",
"each",
"entry",
"in",
"names",
"that",
"evaluates",
"t... | python | train | 35.909091 |
log2timeline/plaso | plaso/preprocessors/windows.py | https://github.com/log2timeline/plaso/blob/9c564698d2da3ffbe23607a3c54c0582ea18a6cc/plaso/preprocessors/windows.py#L267-L295 | def Collect(self, knowledge_base):
"""Collects values from the knowledge base.
Args:
knowledge_base (KnowledgeBase): to fill with preprocessing information.
Raises:
PreProcessFail: if the preprocessing fails.
"""
environment_variable = knowledge_base.GetEnvironmentVariable(
'pr... | [
"def",
"Collect",
"(",
"self",
",",
"knowledge_base",
")",
":",
"environment_variable",
"=",
"knowledge_base",
".",
"GetEnvironmentVariable",
"(",
"'programdata'",
")",
"allusersprofile",
"=",
"getattr",
"(",
"environment_variable",
",",
"'value'",
",",
"None",
")",... | Collects values from the knowledge base.
Args:
knowledge_base (KnowledgeBase): to fill with preprocessing information.
Raises:
PreProcessFail: if the preprocessing fails. | [
"Collects",
"values",
"from",
"the",
"knowledge",
"base",
"."
] | python | train | 36.034483 |
readbeyond/aeneas | aeneas/plotter.py | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/plotter.py#L389-L485 | def draw_png(self, image, h_zoom, v_zoom, current_y):
"""
Draw this set of labels to PNG.
:param image: the image to draw onto
:param int h_zoom: the horizontal zoom
:param int v_zoom: the vertical zoom
:param int current_y: the current y offset, in modules
:type... | [
"def",
"draw_png",
"(",
"self",
",",
"image",
",",
"h_zoom",
",",
"v_zoom",
",",
"current_y",
")",
":",
"# PIL object",
"draw",
"=",
"ImageDraw",
".",
"Draw",
"(",
"image",
")",
"mws",
"=",
"self",
".",
"rconf",
".",
"mws",
"pixels_per_second",
"=",
"i... | Draw this set of labels to PNG.
:param image: the image to draw onto
:param int h_zoom: the horizontal zoom
:param int v_zoom: the vertical zoom
:param int current_y: the current y offset, in modules
:type image: :class:`PIL.Image` | [
"Draw",
"this",
"set",
"of",
"labels",
"to",
"PNG",
"."
] | python | train | 40.391753 |
rigetti/pyquil | pyquil/quil.py | https://github.com/rigetti/pyquil/blob/ec98e453084b0037d69d8c3245f6822a5422593d/pyquil/quil.py#L1024-L1035 | def validate_protoquil(program: Program) -> None:
"""
Ensure that a program is valid ProtoQuil, otherwise raise a ValueError.
Protoquil is a subset of Quil which excludes control flow and classical instructions.
:param program: The Quil program to validate.
"""
valid_instruction_types = tuple([... | [
"def",
"validate_protoquil",
"(",
"program",
":",
"Program",
")",
"->",
"None",
":",
"valid_instruction_types",
"=",
"tuple",
"(",
"[",
"Pragma",
",",
"Declare",
",",
"Halt",
",",
"Gate",
",",
"Reset",
",",
"ResetQubit",
",",
"Measurement",
"]",
")",
"for"... | Ensure that a program is valid ProtoQuil, otherwise raise a ValueError.
Protoquil is a subset of Quil which excludes control flow and classical instructions.
:param program: The Quil program to validate. | [
"Ensure",
"that",
"a",
"program",
"is",
"valid",
"ProtoQuil",
"otherwise",
"raise",
"a",
"ValueError",
".",
"Protoquil",
"is",
"a",
"subset",
"of",
"Quil",
"which",
"excludes",
"control",
"flow",
"and",
"classical",
"instructions",
"."
] | python | train | 52.5 |
blackecho/Deep-Learning-TensorFlow | yadlt/models/linear/logistic_regression.py | https://github.com/blackecho/Deep-Learning-TensorFlow/blob/ddeb1f2848da7b7bee166ad2152b4afc46bb2086/yadlt/models/linear/logistic_regression.py#L42-L58 | def build_model(self, n_features, n_classes):
"""Create the computational graph.
:param n_features: number of features
:param n_classes: number of classes
:return: self
"""
self._create_placeholders(n_features, n_classes)
self._create_variables(n_features, n_clas... | [
"def",
"build_model",
"(",
"self",
",",
"n_features",
",",
"n_classes",
")",
":",
"self",
".",
"_create_placeholders",
"(",
"n_features",
",",
"n_classes",
")",
"self",
".",
"_create_variables",
"(",
"n_features",
",",
"n_classes",
")",
"self",
".",
"mod_y",
... | Create the computational graph.
:param n_features: number of features
:param n_classes: number of classes
:return: self | [
"Create",
"the",
"computational",
"graph",
"."
] | python | train | 39.352941 |
jmgilman/Neolib | neolib/pyamf/amf0.py | https://github.com/jmgilman/Neolib/blob/228fafeaed0f3195676137732384a14820ae285c/neolib/pyamf/amf0.py#L359-L367 | def readLongString(self):
"""
Read UTF8 string.
"""
l = self.stream.read_ulong()
bytes = self.stream.read(l)
return self.context.getStringForBytes(bytes) | [
"def",
"readLongString",
"(",
"self",
")",
":",
"l",
"=",
"self",
".",
"stream",
".",
"read_ulong",
"(",
")",
"bytes",
"=",
"self",
".",
"stream",
".",
"read",
"(",
"l",
")",
"return",
"self",
".",
"context",
".",
"getStringForBytes",
"(",
"bytes",
"... | Read UTF8 string. | [
"Read",
"UTF8",
"string",
"."
] | python | train | 21.666667 |
koehlma/pygrooveshark | src/grooveshark/classes/album.py | https://github.com/koehlma/pygrooveshark/blob/17673758ac12f54dc26ac879c30ea44f13b81057/src/grooveshark/classes/album.py#L67-L73 | def artist(self):
"""
:class:`Artist` object of album's artist
"""
if not self._artist:
self._artist = Artist(self._artist_id, self._artist_name, self._connection)
return self._artist | [
"def",
"artist",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_artist",
":",
"self",
".",
"_artist",
"=",
"Artist",
"(",
"self",
".",
"_artist_id",
",",
"self",
".",
"_artist_name",
",",
"self",
".",
"_connection",
")",
"return",
"self",
".",
"_... | :class:`Artist` object of album's artist | [
":",
"class",
":",
"Artist",
"object",
"of",
"album",
"s",
"artist"
] | python | train | 32.714286 |
mixcloud/django-experiments | experiments/admin.py | https://github.com/mixcloud/django-experiments/blob/1f45e9f8a108b51e44918daa647269b2b8d43f1d/experiments/admin.py#L112-L128 | def set_alternative_view(self, request):
"""
Allows the admin user to change their assigned alternative
"""
if not request.user.has_perm('experiments.change_experiment'):
return HttpResponseForbidden()
experiment_name = request.POST.get("experiment")
alternat... | [
"def",
"set_alternative_view",
"(",
"self",
",",
"request",
")",
":",
"if",
"not",
"request",
".",
"user",
".",
"has_perm",
"(",
"'experiments.change_experiment'",
")",
":",
"return",
"HttpResponseForbidden",
"(",
")",
"experiment_name",
"=",
"request",
".",
"PO... | Allows the admin user to change their assigned alternative | [
"Allows",
"the",
"admin",
"user",
"to",
"change",
"their",
"assigned",
"alternative"
] | python | train | 39.823529 |
cloud9ers/gurumate | environment/lib/python2.7/site-packages/IPython/parallel/controller/mongodb.py | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/parallel/controller/mongodb.py#L63-L67 | def add_record(self, msg_id, rec):
"""Add a new Task Record, by msg_id."""
# print rec
rec = self._binary_buffers(rec)
self._records.insert(rec) | [
"def",
"add_record",
"(",
"self",
",",
"msg_id",
",",
"rec",
")",
":",
"# print rec",
"rec",
"=",
"self",
".",
"_binary_buffers",
"(",
"rec",
")",
"self",
".",
"_records",
".",
"insert",
"(",
"rec",
")"
] | Add a new Task Record, by msg_id. | [
"Add",
"a",
"new",
"Task",
"Record",
"by",
"msg_id",
"."
] | python | test | 34.4 |
BerkeleyAutomation/perception | perception/image.py | https://github.com/BerkeleyAutomation/perception/blob/03d9b37dd6b66896cdfe173905c9413c8c3c5df6/perception/image.py#L1405-L1424 | def open(filename, frame='unspecified'):
"""Creates a ColorImage from a file.
Parameters
----------
filename : :obj:`str`
The file to load the data from. Must be one of .png, .jpg,
.npy, or .npz.
frame : :obj:`str`
A string representing the f... | [
"def",
"open",
"(",
"filename",
",",
"frame",
"=",
"'unspecified'",
")",
":",
"data",
"=",
"Image",
".",
"load_data",
"(",
"filename",
")",
".",
"astype",
"(",
"np",
".",
"uint8",
")",
"return",
"ColorImage",
"(",
"data",
",",
"frame",
")"
] | Creates a ColorImage from a file.
Parameters
----------
filename : :obj:`str`
The file to load the data from. Must be one of .png, .jpg,
.npy, or .npz.
frame : :obj:`str`
A string representing the frame of reference in which the new image
... | [
"Creates",
"a",
"ColorImage",
"from",
"a",
"file",
"."
] | python | train | 28 |
robotools/fontParts | Lib/fontParts/base/component.py | https://github.com/robotools/fontParts/blob/d2ff106fe95f9d566161d936a645157626568712/Lib/fontParts/base/component.py#L351-L363 | def _isCompatible(self, other, reporter):
"""
This is the environment implementation of
:meth:`BaseComponent.isCompatible`.
Subclasses may override this method.
"""
component1 = self
component2 = other
# base glyphs
if component1.baseName != compo... | [
"def",
"_isCompatible",
"(",
"self",
",",
"other",
",",
"reporter",
")",
":",
"component1",
"=",
"self",
"component2",
"=",
"other",
"# base glyphs",
"if",
"component1",
".",
"baseName",
"!=",
"component2",
".",
"baseName",
":",
"reporter",
".",
"baseDifferenc... | This is the environment implementation of
:meth:`BaseComponent.isCompatible`.
Subclasses may override this method. | [
"This",
"is",
"the",
"environment",
"implementation",
"of",
":",
"meth",
":",
"BaseComponent",
".",
"isCompatible",
"."
] | python | train | 30.923077 |
saltstack/salt | salt/modules/neutron.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/neutron.py#L689-L705 | def add_interface_router(router, subnet, profile=None):
'''
Adds an internal network interface to the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.add_interface_router router-name subnet-name
:param router: ID or name of the router
:param subnet: ID or name of ... | [
"def",
"add_interface_router",
"(",
"router",
",",
"subnet",
",",
"profile",
"=",
"None",
")",
":",
"conn",
"=",
"_auth",
"(",
"profile",
")",
"return",
"conn",
".",
"add_interface_router",
"(",
"router",
",",
"subnet",
")"
] | Adds an internal network interface to the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.add_interface_router router-name subnet-name
:param router: ID or name of the router
:param subnet: ID or name of the subnet
:param profile: Profile to build on (Optional)
:r... | [
"Adds",
"an",
"internal",
"network",
"interface",
"to",
"the",
"specified",
"router"
] | python | train | 29 |
gem/oq-engine | openquake/hazardlib/gsim/mcverry_2006.py | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/mcverry_2006.py#L471-L497 | def _compute_mean_on_rock(self, C, mag, rrup, rvol, hypo_depth, CN, CR,
f4HW):
"""
Compute mean value on site class A/B (equation 2 on page 22)
"""
# Define subduction flag (page 23)
# SI=1 for subduction interface, 0 otherwise
# DS=1 for su... | [
"def",
"_compute_mean_on_rock",
"(",
"self",
",",
"C",
",",
"mag",
",",
"rrup",
",",
"rvol",
",",
"hypo_depth",
",",
"CN",
",",
"CR",
",",
"f4HW",
")",
":",
"# Define subduction flag (page 23)",
"# SI=1 for subduction interface, 0 otherwise",
"# DS=1 for subduction in... | Compute mean value on site class A/B (equation 2 on page 22) | [
"Compute",
"mean",
"value",
"on",
"site",
"class",
"A",
"/",
"B",
"(",
"equation",
"2",
"on",
"page",
"22",
")"
] | python | train | 31.148148 |
KelSolaar/Umbra | umbra/components/addons/projects_explorer/projects_explorer.py | https://github.com/KelSolaar/Umbra/blob/66f45f08d9d723787f1191989f8b0dda84b412ce/umbra/components/addons/projects_explorer/projects_explorer.py#L915-L927 | def __set_authoring_nodes(self, source, target):
"""
Sets given editor authoring nodes.
:param source: Source file.
:type source: unicode
:param target: Target file.
:type target: unicode
"""
editor = self.__script_editor.get_editor(source)
edito... | [
"def",
"__set_authoring_nodes",
"(",
"self",
",",
"source",
",",
"target",
")",
":",
"editor",
"=",
"self",
".",
"__script_editor",
".",
"get_editor",
"(",
"source",
")",
"editor",
".",
"set_file",
"(",
"target",
")",
"self",
".",
"__script_editor",
".",
"... | Sets given editor authoring nodes.
:param source: Source file.
:type source: unicode
:param target: Target file.
:type target: unicode | [
"Sets",
"given",
"editor",
"authoring",
"nodes",
"."
] | python | train | 30.153846 |
faucamp/python-gsmmodem | gsmmodem/modem.py | https://github.com/faucamp/python-gsmmodem/blob/834c68b1387ca2c91e2210faa8f75526b39723b5/gsmmodem/modem.py#L532-L543 | def _setSmsMemory(self, readDelete=None, write=None):
""" Set the current SMS memory to use for read/delete/write operations """
# Switch to the correct memory type if required
if write != None and write != self._smsMemWrite:
self.write()
readDel = readDelete or self._sms... | [
"def",
"_setSmsMemory",
"(",
"self",
",",
"readDelete",
"=",
"None",
",",
"write",
"=",
"None",
")",
":",
"# Switch to the correct memory type if required",
"if",
"write",
"!=",
"None",
"and",
"write",
"!=",
"self",
".",
"_smsMemWrite",
":",
"self",
".",
"writ... | Set the current SMS memory to use for read/delete/write operations | [
"Set",
"the",
"current",
"SMS",
"memory",
"to",
"use",
"for",
"read",
"/",
"delete",
"/",
"write",
"operations"
] | python | train | 54.583333 |
davebridges/mousedb | mousedb/animal/views.py | https://github.com/davebridges/mousedb/blob/2a33f6d15d88b1540b05f7232b154fdbf8568580/mousedb/animal/views.py#L118-L120 | def dispatch(self, *args, **kwargs):
"""This decorator sets this view to have restricted permissions."""
return super(AnimalDelete, self).dispatch(*args, **kwargs) | [
"def",
"dispatch",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"super",
"(",
"AnimalDelete",
",",
"self",
")",
".",
"dispatch",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | This decorator sets this view to have restricted permissions. | [
"This",
"decorator",
"sets",
"this",
"view",
"to",
"have",
"restricted",
"permissions",
"."
] | python | train | 59 |
mushkevych/scheduler | synergy/scheduler/tree_node.py | https://github.com/mushkevych/scheduler/blob/6740331360f49083c208085fb5a60ce80ebf418b/synergy/scheduler/tree_node.py#L119-L138 | def find_counterpart_in(self, tree_b):
""" Finds a TreeNode counterpart for this node in tree_b
:param tree_b: target tree that hosts counterpart to this node
:return: TreeNode from tree_b that has the same timeperiod as self.timeperiod,
or None if no counterpart ware fou... | [
"def",
"find_counterpart_in",
"(",
"self",
",",
"tree_b",
")",
":",
"tree_b_hierarchy_entry",
"=",
"tree_b",
".",
"process_hierarchy",
".",
"get_by_qualifier",
"(",
"self",
".",
"time_qualifier",
")",
"if",
"not",
"tree_b_hierarchy_entry",
":",
"# special case when tr... | Finds a TreeNode counterpart for this node in tree_b
:param tree_b: target tree that hosts counterpart to this node
:return: TreeNode from tree_b that has the same timeperiod as self.timeperiod,
or None if no counterpart ware found | [
"Finds",
"a",
"TreeNode",
"counterpart",
"for",
"this",
"node",
"in",
"tree_b",
":",
"param",
"tree_b",
":",
"target",
"tree",
"that",
"hosts",
"counterpart",
"to",
"this",
"node",
":",
"return",
":",
"TreeNode",
"from",
"tree_b",
"that",
"has",
"the",
"sa... | python | train | 55.9 |
brocade/pynos | pynos/versions/ver_6/ver_6_0_1/yang/brocade_ip_policy.py | https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_6/ver_6_0_1/yang/brocade_ip_policy.py#L1100-L1119 | def hide_routemap_holder_route_map_content_set_local_preference_local_preference_value(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
hide_routemap_holder = ET.SubElement(config, "hide-routemap-holder", xmlns="urn:brocade.com:mgmt:brocade-ip-policy")
ro... | [
"def",
"hide_routemap_holder_route_map_content_set_local_preference_local_preference_value",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"hide_routemap_holder",
"=",
"ET",
".",
"SubElement",
"(",
"config... | Auto Generated Code | [
"Auto",
"Generated",
"Code"
] | python | train | 55.05 |
PmagPy/PmagPy | SPD/lib/lib_ptrm_statistics.py | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/SPD/lib/lib_ptrm_statistics.py#L154-L178 | def get_diffs(ptrms_vectors, ptrm_checks_vectors, ptrms_orig, checks_orig):
"""
input: ptrms_vectors, ptrm_checks_vectors, ptrms_orig, checks_orig
output: vector diffs between original and ptrm check, C
"""
ptrm_temps = numpy.array(ptrms_orig)[:,0]
check_temps = numpy.array(checks_orig)[:,0]
... | [
"def",
"get_diffs",
"(",
"ptrms_vectors",
",",
"ptrm_checks_vectors",
",",
"ptrms_orig",
",",
"checks_orig",
")",
":",
"ptrm_temps",
"=",
"numpy",
".",
"array",
"(",
"ptrms_orig",
")",
"[",
":",
",",
"0",
"]",
"check_temps",
"=",
"numpy",
".",
"array",
"("... | input: ptrms_vectors, ptrm_checks_vectors, ptrms_orig, checks_orig
output: vector diffs between original and ptrm check, C | [
"input",
":",
"ptrms_vectors",
"ptrm_checks_vectors",
"ptrms_orig",
"checks_orig",
"output",
":",
"vector",
"diffs",
"between",
"original",
"and",
"ptrm",
"check",
"C"
] | python | train | 39.08 |
PmagPy/PmagPy | pmagpy/ipmag.py | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/pmagpy/ipmag.py#L1426-L1440 | def inc_from_lat(lat):
"""
Calculate inclination predicted from latitude using the dipole equation
Parameter
----------
lat : latitude in degrees
Returns
-------
inc : inclination calculated using the dipole equation
"""
rad = old_div(np.pi, 180.)
inc = old_div(np.arctan(2 ... | [
"def",
"inc_from_lat",
"(",
"lat",
")",
":",
"rad",
"=",
"old_div",
"(",
"np",
".",
"pi",
",",
"180.",
")",
"inc",
"=",
"old_div",
"(",
"np",
".",
"arctan",
"(",
"2",
"*",
"np",
".",
"tan",
"(",
"lat",
"*",
"rad",
")",
")",
",",
"rad",
")",
... | Calculate inclination predicted from latitude using the dipole equation
Parameter
----------
lat : latitude in degrees
Returns
-------
inc : inclination calculated using the dipole equation | [
"Calculate",
"inclination",
"predicted",
"from",
"latitude",
"using",
"the",
"dipole",
"equation"
] | python | train | 23.133333 |
Shizmob/pydle | pydle/features/tls.py | https://github.com/Shizmob/pydle/blob/7ec7d65d097318ed0bcdc5d8401470287d8c7cf7/pydle/features/tls.py#L28-L35 | async def connect(self, hostname=None, port=None, tls=False, **kwargs):
""" Connect to a server, optionally over TLS. See pydle.features.RFC1459Support.connect for misc parameters. """
if not port:
if tls:
port = DEFAULT_TLS_PORT
else:
port = rfc14... | [
"async",
"def",
"connect",
"(",
"self",
",",
"hostname",
"=",
"None",
",",
"port",
"=",
"None",
",",
"tls",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"port",
":",
"if",
"tls",
":",
"port",
"=",
"DEFAULT_TLS_PORT",
"else",
":",
... | Connect to a server, optionally over TLS. See pydle.features.RFC1459Support.connect for misc parameters. | [
"Connect",
"to",
"a",
"server",
"optionally",
"over",
"TLS",
".",
"See",
"pydle",
".",
"features",
".",
"RFC1459Support",
".",
"connect",
"for",
"misc",
"parameters",
"."
] | python | train | 51.125 |
Microsoft/ApplicationInsights-Python | applicationinsights/channel/contracts/PageViewPerfData.py | https://github.com/Microsoft/ApplicationInsights-Python/blob/8452ab7126f9bb6964637d4aa1258c2af17563d6/applicationinsights/channel/contracts/PageViewPerfData.py#L93-L102 | def perf_total(self, value):
"""The perf_total property.
Args:
value (string). the property value.
"""
if value == self._defaults['perfTotal'] and 'perfTotal' in self._values:
del self._values['perfTotal']
else:
self._values['perfTotal... | [
"def",
"perf_total",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"==",
"self",
".",
"_defaults",
"[",
"'perfTotal'",
"]",
"and",
"'perfTotal'",
"in",
"self",
".",
"_values",
":",
"del",
"self",
".",
"_values",
"[",
"'perfTotal'",
"]",
"else",
"... | The perf_total property.
Args:
value (string). the property value. | [
"The",
"perf_total",
"property",
".",
"Args",
":",
"value",
"(",
"string",
")",
".",
"the",
"property",
"value",
"."
] | python | train | 32.1 |
gmr/rejected | rejected/process.py | https://github.com/gmr/rejected/blob/610a3e1401122ecb98d891b6795cca0255e5b044/rejected/process.py#L523-L536 | def report_stats(self):
"""Create the dict of stats data for the MCP stats queue"""
if not self.previous:
self.previous = dict()
for key in self.counters:
self.previous[key] = 0
values = {
'name': self.name,
'consumer_name': self.co... | [
"def",
"report_stats",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"previous",
":",
"self",
".",
"previous",
"=",
"dict",
"(",
")",
"for",
"key",
"in",
"self",
".",
"counters",
":",
"self",
".",
"previous",
"[",
"key",
"]",
"=",
"0",
"values",... | Create the dict of stats data for the MCP stats queue | [
"Create",
"the",
"dict",
"of",
"stats",
"data",
"for",
"the",
"MCP",
"stats",
"queue"
] | python | train | 34.428571 |
VingtCinq/python-mailchimp | mailchimp3/helpers.py | https://github.com/VingtCinq/python-mailchimp/blob/1b472f1b64fdde974732ac4b7ed48908bb707260/mailchimp3/helpers.py#L103-L125 | def merge_results(x, y):
"""
Given two dicts, x and y, merge them into a new dict as a shallow copy.
The result only differs from `x.update(y)` in the way that it handles list
values when both x and y have list values for the same key. In which case
the returned dictionary, z, has a value according... | [
"def",
"merge_results",
"(",
"x",
",",
"y",
")",
":",
"z",
"=",
"x",
".",
"copy",
"(",
")",
"for",
"key",
",",
"value",
"in",
"y",
".",
"items",
"(",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"list",
")",
"and",
"isinstance",
"(",
"z",
... | Given two dicts, x and y, merge them into a new dict as a shallow copy.
The result only differs from `x.update(y)` in the way that it handles list
values when both x and y have list values for the same key. In which case
the returned dictionary, z, has a value according to:
z[key] = x[key] + z[key]
... | [
"Given",
"two",
"dicts",
"x",
"and",
"y",
"merge",
"them",
"into",
"a",
"new",
"dict",
"as",
"a",
"shallow",
"copy",
"."
] | python | valid | 32.130435 |
HDI-Project/MLPrimitives | mlprimitives/datasets.py | https://github.com/HDI-Project/MLPrimitives/blob/bf415f9f751724ff545a1156ddfd7524e320f469/mlprimitives/datasets.py#L482-L491 | def load_boston_multitask():
"""Boston House Prices Dataset with a synthetic multitask output.
The multitask output is obtained by applying a linear transformation
to the original y and adding it as a second output column.
"""
dataset = datasets.load_boston()
y = dataset.target
target = np.... | [
"def",
"load_boston_multitask",
"(",
")",
":",
"dataset",
"=",
"datasets",
".",
"load_boston",
"(",
")",
"y",
"=",
"dataset",
".",
"target",
"target",
"=",
"np",
".",
"column_stack",
"(",
"[",
"y",
",",
"2",
"*",
"y",
"+",
"5",
"]",
")",
"return",
... | Boston House Prices Dataset with a synthetic multitask output.
The multitask output is obtained by applying a linear transformation
to the original y and adding it as a second output column. | [
"Boston",
"House",
"Prices",
"Dataset",
"with",
"a",
"synthetic",
"multitask",
"output",
"."
] | python | train | 41.1 |
angr/angr | angr/sim_manager.py | https://github.com/angr/angr/blob/4e2f97d56af5419ee73bdb30482c8dd8ff5f3e40/angr/sim_manager.py#L171-L191 | def use_technique(self, tech):
"""
Use an exploration technique with this SimulationManager.
Techniques can be found in :mod:`angr.exploration_techniques`.
:param tech: An ExplorationTechnique object that contains code to modify
this SimulationManager's behav... | [
"def",
"use_technique",
"(",
"self",
",",
"tech",
")",
":",
"if",
"not",
"isinstance",
"(",
"tech",
",",
"ExplorationTechnique",
")",
":",
"raise",
"SimulationManagerError",
"# XXX: as promised",
"tech",
".",
"project",
"=",
"self",
".",
"_project",
"tech",
".... | Use an exploration technique with this SimulationManager.
Techniques can be found in :mod:`angr.exploration_techniques`.
:param tech: An ExplorationTechnique object that contains code to modify
this SimulationManager's behavior.
:type tech: ExplorationTechnique
... | [
"Use",
"an",
"exploration",
"technique",
"with",
"this",
"SimulationManager",
"."
] | python | train | 34.904762 |
mfcovington/django-project-home-templatetags | project_home_tags/templatetags/project_home.py | https://github.com/mfcovington/django-project-home-templatetags/blob/abc660906086088792c5e5e7be6ecd151c2ccddb/project_home_tags/templatetags/project_home.py#L86-L122 | def project_home_breadcrumb_bs3(label):
"""A template tag to return the project's home URL and label
formatted as a Bootstrap 3 breadcrumb.
PROJECT_HOME_NAMESPACE must be defined in settings, for example:
PROJECT_HOME_NAMESPACE = 'project_name:index_view'
Usage Example:
{% load project... | [
"def",
"project_home_breadcrumb_bs3",
"(",
"label",
")",
":",
"url",
"=",
"home_url",
"(",
")",
"if",
"url",
":",
"return",
"format_html",
"(",
"'<li><a href=\"{}\">{}</a></li>'",
",",
"url",
",",
"label",
")",
"else",
":",
"return",
"format_html",
"(",
"'<li>... | A template tag to return the project's home URL and label
formatted as a Bootstrap 3 breadcrumb.
PROJECT_HOME_NAMESPACE must be defined in settings, for example:
PROJECT_HOME_NAMESPACE = 'project_name:index_view'
Usage Example:
{% load project_home_tags %}
<ol class="breadcrumb">
... | [
"A",
"template",
"tag",
"to",
"return",
"the",
"project",
"s",
"home",
"URL",
"and",
"label",
"formatted",
"as",
"a",
"Bootstrap",
"3",
"breadcrumb",
"."
] | python | test | 35.243243 |
fulfilio/python-magento | magento/catalog.py | https://github.com/fulfilio/python-magento/blob/720ec136a6e438a9ee4ee92848a9820b91732750/magento/catalog.py#L95-L106 | def move(self, category_id, parent_id, after_id=None):
"""
Move category in tree
:param category_id: ID of category to move
:param parent_id: New parent of the category
:param after_id: Category ID after what position it will be moved
:return: Boolean
"""
... | [
"def",
"move",
"(",
"self",
",",
"category_id",
",",
"parent_id",
",",
"after_id",
"=",
"None",
")",
":",
"return",
"bool",
"(",
"self",
".",
"call",
"(",
"'catalog_category.move'",
",",
"[",
"category_id",
",",
"parent_id",
",",
"after_id",
"]",
")",
")... | Move category in tree
:param category_id: ID of category to move
:param parent_id: New parent of the category
:param after_id: Category ID after what position it will be moved
:return: Boolean | [
"Move",
"category",
"in",
"tree"
] | python | train | 34.583333 |
silas/ops | ops.py | https://github.com/silas/ops/blob/8a62686b4e410ac599c4c15dcc41548b0296aeb3/ops.py#L113-L157 | def chown(path, user=None, group=None, recursive=False):
"""Change file owner and group.
>>> if chown('/tmp/one', user='root', group='wheel'):
... print('OK')
OK
"""
successful = True
uid = -1
gid = -1
if user is not None:
if isinstance(user, basestring_type):
... | [
"def",
"chown",
"(",
"path",
",",
"user",
"=",
"None",
",",
"group",
"=",
"None",
",",
"recursive",
"=",
"False",
")",
":",
"successful",
"=",
"True",
"uid",
"=",
"-",
"1",
"gid",
"=",
"-",
"1",
"if",
"user",
"is",
"not",
"None",
":",
"if",
"is... | Change file owner and group.
>>> if chown('/tmp/one', user='root', group='wheel'):
... print('OK')
OK | [
"Change",
"file",
"owner",
"and",
"group",
"."
] | python | train | 31.088889 |
gwastro/pycbc | pycbc/events/coinc.py | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/events/coinc.py#L579-L593 | def data(self, buffer_index):
"""Return the data vector for a given ring buffer"""
# Check for expired elements and discard if they exist
expired = self.time - self.max_time
exp = self.buffer_expire[buffer_index]
j = 0
while j < len(exp):
# Everything bef... | [
"def",
"data",
"(",
"self",
",",
"buffer_index",
")",
":",
"# Check for expired elements and discard if they exist",
"expired",
"=",
"self",
".",
"time",
"-",
"self",
".",
"max_time",
"exp",
"=",
"self",
".",
"buffer_expire",
"[",
"buffer_index",
"]",
"j",
"=",
... | Return the data vector for a given ring buffer | [
"Return",
"the",
"data",
"vector",
"for",
"a",
"given",
"ring",
"buffer"
] | python | train | 40.2 |
JdeRobot/base | src/drivers/MAVLinkServer/MAVProxy/modules/mavproxy_speech.py | https://github.com/JdeRobot/base/blob/303b18992785b2fe802212f2d758a60873007f1f/src/drivers/MAVLinkServer/MAVProxy/modules/mavproxy_speech.py#L27-L42 | def kill_speech_dispatcher(self):
'''kill speech dispatcher processs'''
if not 'HOME' in os.environ:
return
pidpath = os.path.join(os.environ['HOME'], '.speech-dispatcher',
'pid', 'speech-dispatcher.pid')
if os.path.exists(pidpath):
... | [
"def",
"kill_speech_dispatcher",
"(",
"self",
")",
":",
"if",
"not",
"'HOME'",
"in",
"os",
".",
"environ",
":",
"return",
"pidpath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"environ",
"[",
"'HOME'",
"]",
",",
"'.speech-dispatcher'",
",",
"... | kill speech dispatcher processs | [
"kill",
"speech",
"dispatcher",
"processs"
] | python | train | 40.5625 |
morngrar/ui | ui/ui.py | https://github.com/morngrar/ui/blob/93e160b55ff7d486a53dba7a8c0f2d46e6f95ed9/ui/ui.py#L20-L52 | def menu(items, heading):
'''Takes list of dictionaries and prints a menu.
items parameter should be in the form of a list, containing
dictionaries with the keys: {"key", "text", "function"}.
Typing the key for a menuitem, followed by return, will run
"function".
'''
headin... | [
"def",
"menu",
"(",
"items",
",",
"heading",
")",
":",
"heading",
"=",
"\"\\n\"",
"*",
"5",
"+",
"heading",
"# A little vertical padding",
"while",
"True",
":",
"keydict",
"=",
"{",
"}",
"clear_screen",
"(",
")",
"print",
"(",
"heading",
")",
"for",
"ite... | Takes list of dictionaries and prints a menu.
items parameter should be in the form of a list, containing
dictionaries with the keys: {"key", "text", "function"}.
Typing the key for a menuitem, followed by return, will run
"function". | [
"Takes",
"list",
"of",
"dictionaries",
"and",
"prints",
"a",
"menu",
".",
"items",
"parameter",
"should",
"be",
"in",
"the",
"form",
"of",
"a",
"list",
"containing",
"dictionaries",
"with",
"the",
"keys",
":",
"{",
"key",
"text",
"function",
"}",
"."
] | python | train | 29.181818 |
chaimleib/intervaltree | intervaltree/intervaltree.py | https://github.com/chaimleib/intervaltree/blob/ffb2b1667f8b832e89324a75a175be8440504c9d/intervaltree/intervaltree.py#L788-L800 | def at(self, p):
"""
Returns the set of all intervals that contain p.
Completes in O(m + log n) time, where:
* n = size of the tree
* m = number of matches
:rtype: set of Interval
"""
root = self.top_node
if not root:
return set()
... | [
"def",
"at",
"(",
"self",
",",
"p",
")",
":",
"root",
"=",
"self",
".",
"top_node",
"if",
"not",
"root",
":",
"return",
"set",
"(",
")",
"return",
"root",
".",
"search_point",
"(",
"p",
",",
"set",
"(",
")",
")"
] | Returns the set of all intervals that contain p.
Completes in O(m + log n) time, where:
* n = size of the tree
* m = number of matches
:rtype: set of Interval | [
"Returns",
"the",
"set",
"of",
"all",
"intervals",
"that",
"contain",
"p",
"."
] | python | train | 26.923077 |
linkhub-sdk/popbill.py | popbill/base.py | https://github.com/linkhub-sdk/popbill.py/blob/68a0dd7f7a937603318e93be321fde73c50b96cc/popbill/base.py#L166-L178 | def checkIsMember(self, CorpNum):
""" 회원가입여부 확인
args
CorpNum : 회원 사업자번호
return
회원가입여부 True/False
raise
PopbillException
"""
if CorpNum == None or CorpNum == '':
raise PopbillException(-99999999, "사업자번... | [
"def",
"checkIsMember",
"(",
"self",
",",
"CorpNum",
")",
":",
"if",
"CorpNum",
"==",
"None",
"or",
"CorpNum",
"==",
"''",
":",
"raise",
"PopbillException",
"(",
"-",
"99999999",
",",
"\"사업자번호가 입력되지 않았습니다.\")",
"",
"return",
"self",
".",
"_httpget",
"(",
"... | 회원가입여부 확인
args
CorpNum : 회원 사업자번호
return
회원가입여부 True/False
raise
PopbillException | [
"회원가입여부",
"확인",
"args",
"CorpNum",
":",
"회원",
"사업자번호",
"return",
"회원가입여부",
"True",
"/",
"False",
"raise",
"PopbillException"
] | python | train | 32.307692 |
CityOfZion/neo-python | neo/Implementations/Blockchains/LevelDB/LevelDBBlockchain.py | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Implementations/Blockchains/LevelDB/LevelDBBlockchain.py#L491-L506 | def GetBlockHash(self, height):
"""
Get the block hash by its block height
Args:
height(int): height of the block to retrieve hash from.
Returns:
bytes: a non-raw block hash (e.g. b'6dd83ed8a3fc02e322f91f30431bf3662a8c8e8ebe976c3565f0d21c70620991', but not b'\x6d... | [
"def",
"GetBlockHash",
"(",
"self",
",",
"height",
")",
":",
"if",
"self",
".",
"_current_block_height",
"<",
"height",
":",
"return",
"if",
"len",
"(",
"self",
".",
"_header_index",
")",
"<=",
"height",
":",
"return",
"return",
"self",
".",
"_header_index... | Get the block hash by its block height
Args:
height(int): height of the block to retrieve hash from.
Returns:
bytes: a non-raw block hash (e.g. b'6dd83ed8a3fc02e322f91f30431bf3662a8c8e8ebe976c3565f0d21c70620991', but not b'\x6d\xd8...etc' | [
"Get",
"the",
"block",
"hash",
"by",
"its",
"block",
"height",
"Args",
":",
"height",
"(",
"int",
")",
":",
"height",
"of",
"the",
"block",
"to",
"retrieve",
"hash",
"from",
"."
] | python | train | 31.5 |
apple/turicreate | src/unity/python/turicreate/toolkits/image_analysis/image_analysis.py | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/image_analysis/image_analysis.py#L76-L161 | def resize(image, width, height, channels=None, decode=False,
resample='nearest'):
"""
Resizes the image or SArray of Images to a specific width, height, and
number of channels.
Parameters
----------
image : turicreate.Image | SArray
The image or SArray of images to be resiz... | [
"def",
"resize",
"(",
"image",
",",
"width",
",",
"height",
",",
"channels",
"=",
"None",
",",
"decode",
"=",
"False",
",",
"resample",
"=",
"'nearest'",
")",
":",
"if",
"height",
"<",
"0",
"or",
"width",
"<",
"0",
":",
"raise",
"ValueError",
"(",
... | Resizes the image or SArray of Images to a specific width, height, and
number of channels.
Parameters
----------
image : turicreate.Image | SArray
The image or SArray of images to be resized.
width : int
The width the image is resized to.
height : int
The height the ima... | [
"Resizes",
"the",
"image",
"or",
"SArray",
"of",
"Images",
"to",
"a",
"specific",
"width",
"height",
"and",
"number",
"of",
"channels",
"."
] | python | train | 35.674419 |
lcharleux/argiope | argiope/mesh.py | https://github.com/lcharleux/argiope/blob/8170e431362dc760589f7d141090fd133dece259/argiope/mesh.py#L1181-L1224 | def structured_mesh(shape = (2,2,2), dim = (1.,1.,1.)):
"""
Returns a structured mesh.
:arg shape: 2 or 3 integers (eg: shape = (10, 10, 10)).
:type shape: tuple
:arg dim: 2 or 3 floats (eg: dim = (4., 2., 1.))
:type dim: tuple
.. note::
This function does not use GMSH for... | [
"def",
"structured_mesh",
"(",
"shape",
"=",
"(",
"2",
",",
"2",
",",
"2",
")",
",",
"dim",
"=",
"(",
"1.",
",",
"1.",
",",
"1.",
")",
")",
":",
"# PREPROCESSING",
"shape",
"=",
"np",
".",
"array",
"(",
"shape",
")",
"dim",
"=",
"np",
".",
"a... | Returns a structured mesh.
:arg shape: 2 or 3 integers (eg: shape = (10, 10, 10)).
:type shape: tuple
:arg dim: 2 or 3 floats (eg: dim = (4., 2., 1.))
:type dim: tuple
.. note::
This function does not use GMSH for mesh generation.
>>> import argiope as ag
>>> mesh =... | [
"Returns",
"a",
"structured",
"mesh",
".",
":",
"arg",
"shape",
":",
"2",
"or",
"3",
"integers",
"(",
"eg",
":",
"shape",
"=",
"(",
"10",
"10",
"10",
"))",
".",
":",
"type",
"shape",
":",
"tuple",
":",
"arg",
"dim",
":",
"2",
"or",
"3",
"floats... | python | test | 29.454545 |
OSSOS/MOP | src/ossos/core/ossos/mopheader.py | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/mopheader.py#L99-L122 | def crpix(self):
"""
The location of the reference coordinate in the pixel frame.
First simple respond with the header values, if they don't exist try usnig the DETSEC values
@rtype: float, float
"""
try:
return self.wcs.crpix1, self.wcs.crpix2
except... | [
"def",
"crpix",
"(",
"self",
")",
":",
"try",
":",
"return",
"self",
".",
"wcs",
".",
"crpix1",
",",
"self",
".",
"wcs",
".",
"crpix2",
"except",
"Exception",
"as",
"ex",
":",
"logging",
".",
"debug",
"(",
"\"Couldn't get CRPIX from WCS: {}\"",
".",
"for... | The location of the reference coordinate in the pixel frame.
First simple respond with the header values, if they don't exist try usnig the DETSEC values
@rtype: float, float | [
"The",
"location",
"of",
"the",
"reference",
"coordinate",
"in",
"the",
"pixel",
"frame",
"."
] | python | train | 39.5 |
wind-python/windpowerlib | windpowerlib/wind_turbine.py | https://github.com/wind-python/windpowerlib/blob/421b316139743311b7cb68a69f6b53d2665f7e23/windpowerlib/wind_turbine.py#L193-L265 | def get_turbine_data_from_file(turbine_type, file_):
r"""
Fetches power (coefficient) curve data from a csv file.
See `example_power_curves.csv' and `example_power_coefficient_curves.csv`
in example/data for the required format of a csv file. The self-provided
csv file may contain more columns than... | [
"def",
"get_turbine_data_from_file",
"(",
"turbine_type",
",",
"file_",
")",
":",
"def",
"isfloat",
"(",
"x",
")",
":",
"try",
":",
"float",
"(",
"x",
")",
"return",
"x",
"except",
"ValueError",
":",
"return",
"False",
"try",
":",
"df",
"=",
"pd",
".",... | r"""
Fetches power (coefficient) curve data from a csv file.
See `example_power_curves.csv' and `example_power_coefficient_curves.csv`
in example/data for the required format of a csv file. The self-provided
csv file may contain more columns than the example files. Only columns
containing wind spee... | [
"r",
"Fetches",
"power",
"(",
"coefficient",
")",
"curve",
"data",
"from",
"a",
"csv",
"file",
"."
] | python | train | 36.821918 |
jobovy/galpy | galpy/potential/EllipticalDiskPotential.py | https://github.com/jobovy/galpy/blob/9c5b9fe65d58835624dffe432be282060918ee08/galpy/potential/EllipticalDiskPotential.py#L104-L132 | def _evaluate(self,R,phi=0.,t=0.):
"""
NAME:
_evaluate
PURPOSE:
evaluate the potential at R,phi,t
INPUT:
R - Galactocentric cylindrical radius
phi - azimuth
t - time
OUTPUT:
Phi(R,phi,t)
HISTORY:
... | [
"def",
"_evaluate",
"(",
"self",
",",
"R",
",",
"phi",
"=",
"0.",
",",
"t",
"=",
"0.",
")",
":",
"#Calculate relevant time",
"if",
"not",
"self",
".",
"_tform",
"is",
"None",
":",
"if",
"t",
"<",
"self",
".",
"_tform",
":",
"smooth",
"=",
"0.",
"... | NAME:
_evaluate
PURPOSE:
evaluate the potential at R,phi,t
INPUT:
R - Galactocentric cylindrical radius
phi - azimuth
t - time
OUTPUT:
Phi(R,phi,t)
HISTORY:
2011-10-19 - Started - Bovy (IAS) | [
"NAME",
":",
"_evaluate",
"PURPOSE",
":",
"evaluate",
"the",
"potential",
"at",
"R",
"phi",
"t",
"INPUT",
":",
"R",
"-",
"Galactocentric",
"cylindrical",
"radius",
"phi",
"-",
"azimuth",
"t",
"-",
"time",
"OUTPUT",
":",
"Phi",
"(",
"R",
"phi",
"t",
")"... | python | train | 29.310345 |
pyupio/changelogs | changelogs/parser.py | https://github.com/pyupio/changelogs/blob/0cdb929ac4546c766cd7eef9ae4eb4baaa08f452/changelogs/parser.py#L40-L123 | def get_head(name, line, releases):
"""
Checks if `line` is a head
:param name: str, package name
:param line: str, line
:param releases: list, releases
:return: str, version if this is a valid head, False otherwise
"""
if not line:
return False
# if this line begins with an ... | [
"def",
"get_head",
"(",
"name",
",",
"line",
",",
"releases",
")",
":",
"if",
"not",
"line",
":",
"return",
"False",
"# if this line begins with an invalid starting character, return early.",
"# invalid characters are those used by various markup languages to introduce a new",
"#... | Checks if `line` is a head
:param name: str, package name
:param line: str, line
:param releases: list, releases
:return: str, version if this is a valid head, False otherwise | [
"Checks",
"if",
"line",
"is",
"a",
"head",
":",
"param",
"name",
":",
"str",
"package",
"name",
":",
"param",
"line",
":",
"str",
"line",
":",
"param",
"releases",
":",
"list",
"releases",
":",
"return",
":",
"str",
"version",
"if",
"this",
"is",
"a"... | python | train | 44.22619 |
spyder-ide/spyder | spyder/widgets/calltip.py | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/widgets/calltip.py#L208-L212 | def leaveEvent(self, event):
""" Reimplemented to start the hide timer.
"""
super(CallTipWidget, self).leaveEvent(event)
self._leave_event_hide() | [
"def",
"leaveEvent",
"(",
"self",
",",
"event",
")",
":",
"super",
"(",
"CallTipWidget",
",",
"self",
")",
".",
"leaveEvent",
"(",
"event",
")",
"self",
".",
"_leave_event_hide",
"(",
")"
] | Reimplemented to start the hide timer. | [
"Reimplemented",
"to",
"start",
"the",
"hide",
"timer",
"."
] | python | train | 34.6 |
kylewm/flask-micropub | flask_micropub.py | https://github.com/kylewm/flask-micropub/blob/897c75848c441758d61c11e36c02ae9c1f786950/flask_micropub.py#L82-L104 | def authorize(self, me, state=None, next_url=None, scope='read'):
"""Authorize a user via Micropub.
Args:
me (string): the authing user's URL. if it does not begin with
https?://, http:// will be prepended.
state (string, optional): passed through the whole auth process,... | [
"def",
"authorize",
"(",
"self",
",",
"me",
",",
"state",
"=",
"None",
",",
"next_url",
"=",
"None",
",",
"scope",
"=",
"'read'",
")",
":",
"redirect_url",
"=",
"flask",
".",
"url_for",
"(",
"self",
".",
"flask_endpoint_for_function",
"(",
"self",
".",
... | Authorize a user via Micropub.
Args:
me (string): the authing user's URL. if it does not begin with
https?://, http:// will be prepended.
state (string, optional): passed through the whole auth process,
useful if you want to maintain some state, e.g. the starting pag... | [
"Authorize",
"a",
"user",
"via",
"Micropub",
"."
] | python | train | 46 |
ml4ai/delphi | delphi/AnalysisGraph.py | https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/AnalysisGraph.py#L675-L719 | def map_concepts_to_indicators(
self, n: int = 1, min_temporal_res: Optional[str] = None
):
""" Map each concept node in the AnalysisGraph instance to one or more
tangible quantities, known as 'indicators'.
Args:
n: Number of matches to keep
min_temporal_res:... | [
"def",
"map_concepts_to_indicators",
"(",
"self",
",",
"n",
":",
"int",
"=",
"1",
",",
"min_temporal_res",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
")",
":",
"for",
"node",
"in",
"self",
".",
"nodes",
"(",
"data",
"=",
"True",
")",
":",
"query_... | Map each concept node in the AnalysisGraph instance to one or more
tangible quantities, known as 'indicators'.
Args:
n: Number of matches to keep
min_temporal_res: Minimum temporal resolution that the indicators
must have data for. | [
"Map",
"each",
"concept",
"node",
"in",
"the",
"AnalysisGraph",
"instance",
"to",
"one",
"or",
"more",
"tangible",
"quantities",
"known",
"as",
"indicators",
"."
] | python | train | 35.8 |
mikedh/trimesh | trimesh/path/path.py | https://github.com/mikedh/trimesh/blob/25e059bf6d4caa74f62ffd58ce4f61a90ee4e518/trimesh/path/path.py#L1336-L1365 | def plot_entities(self, show=False, annotations=True, color=None):
"""
Plot the entities of the path, with no notion of topology
"""
import matplotlib.pyplot as plt
plt.axes().set_aspect('equal', 'datalim')
eformat = {'Line0': {'color': 'g', 'linewidth': 1},
... | [
"def",
"plot_entities",
"(",
"self",
",",
"show",
"=",
"False",
",",
"annotations",
"=",
"True",
",",
"color",
"=",
"None",
")",
":",
"import",
"matplotlib",
".",
"pyplot",
"as",
"plt",
"plt",
".",
"axes",
"(",
")",
".",
"set_aspect",
"(",
"'equal'",
... | Plot the entities of the path, with no notion of topology | [
"Plot",
"the",
"entities",
"of",
"the",
"path",
"with",
"no",
"notion",
"of",
"topology"
] | python | train | 45.9 |
pjuren/pyokit | src/pyokit/util/fileUtils.py | https://github.com/pjuren/pyokit/blob/fddae123b5d817daa39496183f19c000d9c3791f/src/pyokit/util/fileUtils.py#L65-L77 | def getUniqueFilename(dir=None, base=None):
"""
DESCRP: Generate a filename in the directory <dir> which is
unique (i.e. not in use at the moment)
PARAMS: dir -- the directory to look in. If None, use CWD
base -- use this as the base name for the filename
RETURN: string -- the fil... | [
"def",
"getUniqueFilename",
"(",
"dir",
"=",
"None",
",",
"base",
"=",
"None",
")",
":",
"while",
"True",
":",
"fn",
"=",
"str",
"(",
"random",
".",
"randint",
"(",
"0",
",",
"100000",
")",
")",
"+",
"\".tmp\"",
"if",
"not",
"os",
".",
"path",
".... | DESCRP: Generate a filename in the directory <dir> which is
unique (i.e. not in use at the moment)
PARAMS: dir -- the directory to look in. If None, use CWD
base -- use this as the base name for the filename
RETURN: string -- the filename generated | [
"DESCRP",
":",
"Generate",
"a",
"filename",
"in",
"the",
"directory",
"<dir",
">",
"which",
"is",
"unique",
"(",
"i",
".",
"e",
".",
"not",
"in",
"use",
"at",
"the",
"moment",
")",
"PARAMS",
":",
"dir",
"--",
"the",
"directory",
"to",
"look",
"in",
... | python | train | 34.384615 |
treycucco/bidon | lib/generate_models.py | https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/lib/generate_models.py#L21-L46 | def parse_args():
"""Parses command line arguments."""
parser = ArgumentParser(description="ModelBase builder")
subparsers = parser.add_subparsers()
sql_parser = subparsers.add_parser(
"get-query",
description="Usage: e.g. psql -c \"copy ($(python3 lib/generate_models.py get-query)) to " +
... | [
"def",
"parse_args",
"(",
")",
":",
"parser",
"=",
"ArgumentParser",
"(",
"description",
"=",
"\"ModelBase builder\"",
")",
"subparsers",
"=",
"parser",
".",
"add_subparsers",
"(",
")",
"sql_parser",
"=",
"subparsers",
".",
"add_parser",
"(",
"\"get-query\"",
",... | Parses command line arguments. | [
"Parses",
"command",
"line",
"arguments",
"."
] | python | train | 38.307692 |
marrow/util | marrow/util/compat.py | https://github.com/marrow/util/blob/abb8163dbd1fa0692d42a44d129b12ae2b39cdf2/marrow/util/compat.py#L130-L141 | def uvalues(a, encoding='utf-8', fallback='iso-8859-1'):
"""Return a list of decoded values from an iterator.
If any of the values fail to decode, re-decode all values using the
fallback.
"""
try:
return encoding, [s.decode(encoding) for s in a]
except UnicodeError:
return fal... | [
"def",
"uvalues",
"(",
"a",
",",
"encoding",
"=",
"'utf-8'",
",",
"fallback",
"=",
"'iso-8859-1'",
")",
":",
"try",
":",
"return",
"encoding",
",",
"[",
"s",
".",
"decode",
"(",
"encoding",
")",
"for",
"s",
"in",
"a",
"]",
"except",
"UnicodeError",
"... | Return a list of decoded values from an iterator.
If any of the values fail to decode, re-decode all values using the
fallback. | [
"Return",
"a",
"list",
"of",
"decoded",
"values",
"from",
"an",
"iterator",
"."
] | python | train | 28.916667 |
frascoweb/frasco | frasco/decorators.py | https://github.com/frascoweb/frasco/blob/ea519d69dd5ca6deaf3650175692ee4a1a02518f/frasco/decorators.py#L81-L98 | def with_actions(actions_or_group_name, actions=None):
"""Executes the list of actions before/after the function
Actions should be a list where items are action names as
strings or a dict. See frasco.actions.loaders.load_action().
"""
group = None
if isinstance(actions_or_group_name, str):
... | [
"def",
"with_actions",
"(",
"actions_or_group_name",
",",
"actions",
"=",
"None",
")",
":",
"group",
"=",
"None",
"if",
"isinstance",
"(",
"actions_or_group_name",
",",
"str",
")",
":",
"group",
"=",
"actions_or_group_name",
"else",
":",
"actions",
"=",
"actio... | Executes the list of actions before/after the function
Actions should be a list where items are action names as
strings or a dict. See frasco.actions.loaders.load_action(). | [
"Executes",
"the",
"list",
"of",
"actions",
"before",
"/",
"after",
"the",
"function",
"Actions",
"should",
"be",
"a",
"list",
"where",
"items",
"are",
"action",
"names",
"as",
"strings",
"or",
"a",
"dict",
".",
"See",
"frasco",
".",
"actions",
".",
"loa... | python | train | 35.222222 |
django-fluent/django-fluent-contents | fluent_contents/rendering/core.py | https://github.com/django-fluent/django-fluent-contents/blob/896f14add58471b98d7aa295b2c9e6abedec9003/fluent_contents/rendering/core.py#L389-L436 | def render_placeholder(self, placeholder, parent_object=None, template_name=None, cachable=None, limit_parent_language=True, fallback_language=None):
"""
The main rendering sequence for placeholders.
This will do all the magic for caching, and call :func:`render_items` in the end.
"""
... | [
"def",
"render_placeholder",
"(",
"self",
",",
"placeholder",
",",
"parent_object",
"=",
"None",
",",
"template_name",
"=",
"None",
",",
"cachable",
"=",
"None",
",",
"limit_parent_language",
"=",
"True",
",",
"fallback_language",
"=",
"None",
")",
":",
"place... | The main rendering sequence for placeholders.
This will do all the magic for caching, and call :func:`render_items` in the end. | [
"The",
"main",
"rendering",
"sequence",
"for",
"placeholders",
".",
"This",
"will",
"do",
"all",
"the",
"magic",
"for",
"caching",
"and",
"call",
":",
"func",
":",
"render_items",
"in",
"the",
"end",
"."
] | python | train | 50.9375 |
Vito2015/pyextend | pyextend/formula/lbstools.py | https://github.com/Vito2015/pyextend/blob/36861dfe1087e437ffe9b5a1da9345c85b4fa4a1/pyextend/formula/lbstools.py#L13-L29 | def haversine(lng1, lat1, lng2, lat2):
"""Compute km by geo-coordinates
See also: haversine define https://en.wikipedia.org/wiki/Haversine_formula
"""
# Convert coordinates to floats.
lng1, lat1, lng2, lat2 = map(float, [lng1, lat1, lng2, lat2])
# Convert to radians from degrees
lng1, lat1,... | [
"def",
"haversine",
"(",
"lng1",
",",
"lat1",
",",
"lng2",
",",
"lat2",
")",
":",
"# Convert coordinates to floats.",
"lng1",
",",
"lat1",
",",
"lng2",
",",
"lat2",
"=",
"map",
"(",
"float",
",",
"[",
"lng1",
",",
"lat1",
",",
"lng2",
",",
"lat2",
"]... | Compute km by geo-coordinates
See also: haversine define https://en.wikipedia.org/wiki/Haversine_formula | [
"Compute",
"km",
"by",
"geo",
"-",
"coordinates",
"See",
"also",
":",
"haversine",
"define",
"https",
":",
"//",
"en",
".",
"wikipedia",
".",
"org",
"/",
"wiki",
"/",
"Haversine_formula"
] | python | train | 34.294118 |
CalebBell/fluids | fluids/flow_meter.py | https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/flow_meter.py#L438-L484 | def discharge_coefficient_to_K(D, Do, C):
r'''Converts a discharge coefficient to a standard loss coefficient,
for use in computation of the actual pressure drop of an orifice or other
device.
.. math::
K = \left[\frac{\sqrt{1-\beta^4(1-C^2)}}{C\beta^2} - 1\right]^2
Parameters
... | [
"def",
"discharge_coefficient_to_K",
"(",
"D",
",",
"Do",
",",
"C",
")",
":",
"beta",
"=",
"Do",
"/",
"D",
"beta2",
"=",
"beta",
"*",
"beta",
"beta4",
"=",
"beta2",
"*",
"beta2",
"return",
"(",
"(",
"1.0",
"-",
"beta4",
"*",
"(",
"1.0",
"-",
"C",... | r'''Converts a discharge coefficient to a standard loss coefficient,
for use in computation of the actual pressure drop of an orifice or other
device.
.. math::
K = \left[\frac{\sqrt{1-\beta^4(1-C^2)}}{C\beta^2} - 1\right]^2
Parameters
----------
D : float
Upstream inte... | [
"r",
"Converts",
"a",
"discharge",
"coefficient",
"to",
"a",
"standard",
"loss",
"coefficient",
"for",
"use",
"in",
"computation",
"of",
"the",
"actual",
"pressure",
"drop",
"of",
"an",
"orifice",
"or",
"other",
"device",
"."
] | python | train | 33.680851 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.