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 |
|---|---|---|---|---|---|---|---|---|---|
spyder-ide/spyder | spyder/plugins/console/widgets/shell.py | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/console/widgets/shell.py#L283-L287 | def on_new_line(self):
"""On new input line"""
self.set_cursor_position('eof')
self.current_prompt_pos = self.get_position('cursor')
self.new_input_line = False | [
"def",
"on_new_line",
"(",
"self",
")",
":",
"self",
".",
"set_cursor_position",
"(",
"'eof'",
")",
"self",
".",
"current_prompt_pos",
"=",
"self",
".",
"get_position",
"(",
"'cursor'",
")",
"self",
".",
"new_input_line",
"=",
"False"
] | On new input line | [
"On",
"new",
"input",
"line"
] | python | train | 38.4 |
HDI-Project/BTB | btb/selection/pure.py | https://github.com/HDI-Project/BTB/blob/7f489ebc5591bd0886652ef743098c022d7f7460/btb/selection/pure.py#L23-L36 | def compute_rewards(self, scores):
"""
Compute the "velocity" of (average distance between) the k+1 best
scores. Return a list with those k velocities padded out with zeros so
that the count remains the same.
"""
# get the k + 1 best scores in descending order
bes... | [
"def",
"compute_rewards",
"(",
"self",
",",
"scores",
")",
":",
"# get the k + 1 best scores in descending order",
"best_scores",
"=",
"sorted",
"(",
"scores",
",",
"reverse",
"=",
"True",
")",
"[",
":",
"self",
".",
"k",
"+",
"1",
"]",
"velocities",
"=",
"[... | Compute the "velocity" of (average distance between) the k+1 best
scores. Return a list with those k velocities padded out with zeros so
that the count remains the same. | [
"Compute",
"the",
"velocity",
"of",
"(",
"average",
"distance",
"between",
")",
"the",
"k",
"+",
"1",
"best",
"scores",
".",
"Return",
"a",
"list",
"with",
"those",
"k",
"velocities",
"padded",
"out",
"with",
"zeros",
"so",
"that",
"the",
"count",
"remai... | python | train | 45 |
wonambi-python/wonambi | wonambi/ioeeg/bci2000.py | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/ioeeg/bci2000.py#L38-L99 | def return_hdr(self):
"""Return the header for further use.
Returns
-------
subj_id : str
subject identification code
start_time : datetime
start time of the dataset
s_freq : float
sampling frequency
chan_name : list of str
... | [
"def",
"return_hdr",
"(",
"self",
")",
":",
"orig",
"=",
"{",
"}",
"orig",
"=",
"_read_header",
"(",
"self",
".",
"filename",
")",
"nchan",
"=",
"int",
"(",
"orig",
"[",
"'SourceCh'",
"]",
")",
"chan_name",
"=",
"[",
"'ch{:03d}'",
".",
"format",
"(",... | Return the header for further use.
Returns
-------
subj_id : str
subject identification code
start_time : datetime
start time of the dataset
s_freq : float
sampling frequency
chan_name : list of str
list of all the channels... | [
"Return",
"the",
"header",
"for",
"further",
"use",
"."
] | python | train | 36.096774 |
SITools2/pySitools2_1.0 | sitools2/core/query.py | https://github.com/SITools2/pySitools2_1.0/blob/acd13198162456ba401a0b923af989bb29feb3b6/sitools2/core/query.py#L264-L274 | def _getParameters(self):
"""Returns the result of this decorator."""
param = self.query._getParameters()
index = self._getFilterIndex()
param.update({
'filter['+str(index)+'][columnAlias]' : self.__column,
'filter['+str(index)+'][data][type]' : self.__type,
'fil... | [
"def",
"_getParameters",
"(",
"self",
")",
":",
"param",
"=",
"self",
".",
"query",
".",
"_getParameters",
"(",
")",
"index",
"=",
"self",
".",
"_getFilterIndex",
"(",
")",
"param",
".",
"update",
"(",
"{",
"'filter['",
"+",
"str",
"(",
"index",
")",
... | Returns the result of this decorator. | [
"Returns",
"the",
"result",
"of",
"this",
"decorator",
"."
] | python | train | 45.545455 |
mitsei/dlkit | dlkit/json_/__init__.py | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/json_/__init__.py#L74-L84 | def _notify_receiver(self, receiver, params, doc):
"""Send notification to the receiver"""
verb = VMAP[doc['op']]
ns = doc['ns']
notification_id = Id(ns + 'Notification:' + str(ObjectId()) + '@' + params['authority'])
object_id = Id(ns + ':' + str(doc['o']['_id']) + '@' + params[... | [
"def",
"_notify_receiver",
"(",
"self",
",",
"receiver",
",",
"params",
",",
"doc",
")",
":",
"verb",
"=",
"VMAP",
"[",
"doc",
"[",
"'op'",
"]",
"]",
"ns",
"=",
"doc",
"[",
"'ns'",
"]",
"notification_id",
"=",
"Id",
"(",
"ns",
"+",
"'Notification:'",... | Send notification to the receiver | [
"Send",
"notification",
"to",
"the",
"receiver"
] | python | train | 47.272727 |
codenerix/django-codenerix-invoicing | codenerix_invoicing/models_sales.py | https://github.com/codenerix/django-codenerix-invoicing/blob/7db5c62f335f9215a8b308603848625208b48698/codenerix_invoicing/models_sales.py#L2372-L2407 | def create_ticket_from_albaran(pk, list_lines):
MODEL_SOURCE = SalesAlbaran
MODEL_FINAL = SalesTicket
url_reverse = 'CDNX_invoicing_ticketsaless_list'
# type_doc
msg_error_relation = _("Hay lineas asignadas a ticket")
msg_error_not_found = _('Sales albaran not found')
... | [
"def",
"create_ticket_from_albaran",
"(",
"pk",
",",
"list_lines",
")",
":",
"MODEL_SOURCE",
"=",
"SalesAlbaran",
"MODEL_FINAL",
"=",
"SalesTicket",
"url_reverse",
"=",
"'CDNX_invoicing_ticketsaless_list'",
"# type_doc",
"msg_error_relation",
"=",
"_",
"(",
"\"Hay lineas ... | context = {}
if list_lines:
new_list_lines = SalesLines.objects.filter(
pk__in=[int(x) for x in list_lines]
).exclude(
invoice__isnull=True
).values_list('pk')
if new_list_lines:
new_pk = SalesLines.objects.values_l... | [
"context",
"=",
"{}",
"if",
"list_lines",
":",
"new_list_lines",
"=",
"SalesLines",
".",
"objects",
".",
"filter",
"(",
"pk__in",
"=",
"[",
"int",
"(",
"x",
")",
"for",
"x",
"in",
"list_lines",
"]",
")",
".",
"exclude",
"(",
"invoice__isnull",
"=",
"Tr... | python | train | 43.055556 |
Microsoft/nni | examples/trials/kaggle-tgs-salt/models.py | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/examples/trials/kaggle-tgs-salt/models.py#L210-L214 | def freeze_bn(self):
'''Freeze BatchNorm layers.'''
for layer in self.modules():
if isinstance(layer, nn.BatchNorm2d):
layer.eval() | [
"def",
"freeze_bn",
"(",
"self",
")",
":",
"for",
"layer",
"in",
"self",
".",
"modules",
"(",
")",
":",
"if",
"isinstance",
"(",
"layer",
",",
"nn",
".",
"BatchNorm2d",
")",
":",
"layer",
".",
"eval",
"(",
")"
] | Freeze BatchNorm layers. | [
"Freeze",
"BatchNorm",
"layers",
"."
] | python | train | 34.2 |
deepmind/sonnet | sonnet/python/modules/batch_norm.py | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/batch_norm.py#L400-L442 | def _batch_norm_op(self, input_batch, mean, variance, use_batch_stats,
stat_dtype):
"""Creates a batch normalization op.
It uses the tf.nn.batch_normalization op by default and the
tf.nn.fused_batch_norm op to support fused batch normalization.
Args:
input_batch: A input Ten... | [
"def",
"_batch_norm_op",
"(",
"self",
",",
"input_batch",
",",
"mean",
",",
"variance",
",",
"use_batch_stats",
",",
"stat_dtype",
")",
":",
"if",
"self",
".",
"_fused",
":",
"# For the non-training case where not using batch stats,",
"# pass in the moving statistic varia... | Creates a batch normalization op.
It uses the tf.nn.batch_normalization op by default and the
tf.nn.fused_batch_norm op to support fused batch normalization.
Args:
input_batch: A input Tensor of arbitrary dimension.
mean: A mean tensor, of the same dtype as `input_batch`.
variance: A var... | [
"Creates",
"a",
"batch",
"normalization",
"op",
"."
] | python | train | 40.418605 |
theno/fabsetup | fabsetup/addons.py | https://github.com/theno/fabsetup/blob/ced728abff93551ba5677e63bc1bdc0ef5ca5777/fabsetup/addons.py#L126-L145 | def load_repo_addons(_globals):
'''Load all fabsetup addons which are stored under ~/.fabsetup-addon-repos
as git repositories.
Args:
_globals(dict): the globals() namespace of the fabric script.
Return: None
'''
repos_dir = os.path.expanduser('~/.fabsetup-addon-repos')
if os.path.... | [
"def",
"load_repo_addons",
"(",
"_globals",
")",
":",
"repos_dir",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"'~/.fabsetup-addon-repos'",
")",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"repos_dir",
")",
":",
"basedir",
",",
"repos",
",",
"_",
"="... | Load all fabsetup addons which are stored under ~/.fabsetup-addon-repos
as git repositories.
Args:
_globals(dict): the globals() namespace of the fabric script.
Return: None | [
"Load",
"all",
"fabsetup",
"addons",
"which",
"are",
"stored",
"under",
"~",
"/",
".",
"fabsetup",
"-",
"addon",
"-",
"repos",
"as",
"git",
"repositories",
"."
] | python | train | 40.3 |
fermiPy/fermipy | fermipy/tsmap.py | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/tsmap.py#L507-L523 | def f_cash(x, counts, bkg, model):
"""
Wrapper for cash statistics, that defines the model function.
Parameters
----------
x : float
Model amplitude.
counts : `~numpy.ndarray`
Count map slice, where model is defined.
bkg : `~numpy.ndarray`
Background map slice, where... | [
"def",
"f_cash",
"(",
"x",
",",
"counts",
",",
"bkg",
",",
"model",
")",
":",
"return",
"2.0",
"*",
"poisson_log_like",
"(",
"counts",
",",
"bkg",
"+",
"x",
"*",
"model",
")"
] | Wrapper for cash statistics, that defines the model function.
Parameters
----------
x : float
Model amplitude.
counts : `~numpy.ndarray`
Count map slice, where model is defined.
bkg : `~numpy.ndarray`
Background map slice, where model is defined.
model : `~numpy.ndarray`... | [
"Wrapper",
"for",
"cash",
"statistics",
"that",
"defines",
"the",
"model",
"function",
"."
] | python | train | 27.705882 |
watson-developer-cloud/python-sdk | ibm_watson/compare_comply_v1.py | https://github.com/watson-developer-cloud/python-sdk/blob/4c2c9df4466fcde88975da9ecd834e6ba95eb353/ibm_watson/compare_comply_v1.py#L4573-L4586 | def _from_dict(cls, _dict):
"""Initialize a TableReturn object from a json dictionary."""
args = {}
if 'document' in _dict:
args['document'] = DocInfo._from_dict(_dict.get('document'))
if 'model_id' in _dict:
args['model_id'] = _dict.get('model_id')
if 'mo... | [
"def",
"_from_dict",
"(",
"cls",
",",
"_dict",
")",
":",
"args",
"=",
"{",
"}",
"if",
"'document'",
"in",
"_dict",
":",
"args",
"[",
"'document'",
"]",
"=",
"DocInfo",
".",
"_from_dict",
"(",
"_dict",
".",
"get",
"(",
"'document'",
")",
")",
"if",
... | Initialize a TableReturn object from a json dictionary. | [
"Initialize",
"a",
"TableReturn",
"object",
"from",
"a",
"json",
"dictionary",
"."
] | python | train | 40.142857 |
stephenmcd/gnotty | gnotty/bots/rss.py | https://github.com/stephenmcd/gnotty/blob/bea3762dc9cbc3cb21a5ae7224091cf027273c40/gnotty/bots/rss.py#L30-L45 | def parse_feeds(self, message_channel=True):
"""
Iterates through each of the feed URLs, parses their items, and
sends any items to the channel that have not been previously
been parsed.
"""
if parse:
for feed_url in self.feeds:
feed = parse(fe... | [
"def",
"parse_feeds",
"(",
"self",
",",
"message_channel",
"=",
"True",
")",
":",
"if",
"parse",
":",
"for",
"feed_url",
"in",
"self",
".",
"feeds",
":",
"feed",
"=",
"parse",
"(",
"feed_url",
")",
"for",
"item",
"in",
"feed",
".",
"entries",
":",
"i... | Iterates through each of the feed URLs, parses their items, and
sends any items to the channel that have not been previously
been parsed. | [
"Iterates",
"through",
"each",
"of",
"the",
"feed",
"URLs",
"parses",
"their",
"items",
"and",
"sends",
"any",
"items",
"to",
"the",
"channel",
"that",
"have",
"not",
"been",
"previously",
"been",
"parsed",
"."
] | python | train | 42.5 |
iotaledger/iota.lib.py | iota/api.py | https://github.com/iotaledger/iota.lib.py/blob/97cdd1e241498446b46157b79b2a1ea2ec6d387a/iota/api.py#L520-L581 | def get_account_data(self, start=0, stop=None, inclusion_states=False, security_level=None):
# type: (int, Optional[int], bool, Optional[int]) -> dict
"""
More comprehensive version of :py:meth:`get_transfers` that
returns addresses and account balance in addition to bundles.
Th... | [
"def",
"get_account_data",
"(",
"self",
",",
"start",
"=",
"0",
",",
"stop",
"=",
"None",
",",
"inclusion_states",
"=",
"False",
",",
"security_level",
"=",
"None",
")",
":",
"# type: (int, Optional[int], bool, Optional[int]) -> dict",
"return",
"extended",
".",
"... | More comprehensive version of :py:meth:`get_transfers` that
returns addresses and account balance in addition to bundles.
This function is useful in getting all the relevant information
of your account.
:param start:
Starting key index.
:param stop:
Sto... | [
"More",
"comprehensive",
"version",
"of",
":",
"py",
":",
"meth",
":",
"get_transfers",
"that",
"returns",
"addresses",
"and",
"account",
"balance",
"in",
"addition",
"to",
"bundles",
"."
] | python | test | 33.66129 |
jamesturk/scrapelib | scrapelib/cache.py | https://github.com/jamesturk/scrapelib/blob/dcae9fa86f1fdcc4b4e90dbca12c8063bcb36525/scrapelib/cache.py#L117-L161 | def get(self, orig_key):
"""Get cache entry for key, or return None."""
resp = requests.Response()
key = self._clean_key(orig_key)
path = os.path.join(self.cache_dir, key)
try:
with open(path, 'rb') as f:
# read lines one at a time
wh... | [
"def",
"get",
"(",
"self",
",",
"orig_key",
")",
":",
"resp",
"=",
"requests",
".",
"Response",
"(",
")",
"key",
"=",
"self",
".",
"_clean_key",
"(",
"orig_key",
")",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"cache_dir",
",",
... | Get cache entry for key, or return None. | [
"Get",
"cache",
"entry",
"for",
"key",
"or",
"return",
"None",
"."
] | python | train | 42.444444 |
thiagopbueno/pyrddl | pyrddl/parser.py | https://github.com/thiagopbueno/pyrddl/blob/3bcfa850b1a7532c7744358f3c6b9e0f8ab978c9/pyrddl/parser.py#L278-L286 | def p_req_section(self, p):
'''req_section : REQUIREMENTS ASSIGN_EQUAL LCURLY string_list RCURLY SEMI
| REQUIREMENTS LCURLY string_list RCURLY SEMI
| empty'''
if len(p) == 7:
p[0] = p[4]
elif len(p) == 6:
p[0] = p[3]
s... | [
"def",
"p_req_section",
"(",
"self",
",",
"p",
")",
":",
"if",
"len",
"(",
"p",
")",
"==",
"7",
":",
"p",
"[",
"0",
"]",
"=",
"p",
"[",
"4",
"]",
"elif",
"len",
"(",
"p",
")",
"==",
"6",
":",
"p",
"[",
"0",
"]",
"=",
"p",
"[",
"3",
"]... | req_section : REQUIREMENTS ASSIGN_EQUAL LCURLY string_list RCURLY SEMI
| REQUIREMENTS LCURLY string_list RCURLY SEMI
| empty | [
"req_section",
":",
"REQUIREMENTS",
"ASSIGN_EQUAL",
"LCURLY",
"string_list",
"RCURLY",
"SEMI",
"|",
"REQUIREMENTS",
"LCURLY",
"string_list",
"RCURLY",
"SEMI",
"|",
"empty"
] | python | train | 38.444444 |
Rapptz/discord.py | discord/ext/commands/core.py | https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/ext/commands/core.py#L1430-L1453 | def bot_has_any_role(*items):
"""Similar to :func:`.has_any_role` except checks if the bot itself has
any of the roles listed.
This check raises one of two special exceptions, :exc:`.BotMissingAnyRole` if the bot
is missing all roles, or :exc:`.NoPrivateMessage` if it is used in a private message.
... | [
"def",
"bot_has_any_role",
"(",
"*",
"items",
")",
":",
"def",
"predicate",
"(",
"ctx",
")",
":",
"ch",
"=",
"ctx",
".",
"channel",
"if",
"not",
"isinstance",
"(",
"ch",
",",
"discord",
".",
"abc",
".",
"GuildChannel",
")",
":",
"raise",
"NoPrivateMess... | Similar to :func:`.has_any_role` except checks if the bot itself has
any of the roles listed.
This check raises one of two special exceptions, :exc:`.BotMissingAnyRole` if the bot
is missing all roles, or :exc:`.NoPrivateMessage` if it is used in a private message.
Both inherit from :exc:`.CheckFailure... | [
"Similar",
"to",
":",
"func",
":",
".",
"has_any_role",
"except",
"checks",
"if",
"the",
"bot",
"itself",
"has",
"any",
"of",
"the",
"roles",
"listed",
"."
] | python | train | 38.791667 |
aestrivex/bctpy | bct/algorithms/degree.py | https://github.com/aestrivex/bctpy/blob/4cb0e759eb4a038750b07e23bd29958c400684b8/bct/algorithms/degree.py#L6-L35 | def degrees_dir(CIJ):
'''
Node degree is the number of links connected to the node. The indegree
is the number of inward links and the outdegree is the number of
outward links.
Parameters
----------
CIJ : NxN np.ndarray
directed binary/weighted connection matrix
Returns
---... | [
"def",
"degrees_dir",
"(",
"CIJ",
")",
":",
"CIJ",
"=",
"binarize",
"(",
"CIJ",
",",
"copy",
"=",
"True",
")",
"# ensure CIJ is binary",
"id",
"=",
"np",
".",
"sum",
"(",
"CIJ",
",",
"axis",
"=",
"0",
")",
"# indegree = column sum of CIJ",
"od",
"=",
"... | Node degree is the number of links connected to the node. The indegree
is the number of inward links and the outdegree is the number of
outward links.
Parameters
----------
CIJ : NxN np.ndarray
directed binary/weighted connection matrix
Returns
-------
id : Nx1 np.ndarray
... | [
"Node",
"degree",
"is",
"the",
"number",
"of",
"links",
"connected",
"to",
"the",
"node",
".",
"The",
"indegree",
"is",
"the",
"number",
"of",
"inward",
"links",
"and",
"the",
"outdegree",
"is",
"the",
"number",
"of",
"outward",
"links",
"."
] | python | train | 28.233333 |
cackharot/suds-py3 | suds/servicedefinition.py | https://github.com/cackharot/suds-py3/blob/7387ec7806e9be29aad0a711bea5cb3c9396469c/suds/servicedefinition.py#L172-L186 | def getprefix(self, u):
"""
Get the prefix for the specified namespace (uri)
@param u: A namespace uri.
@type u: str
@return: The namspace.
@rtype: (prefix, uri).
"""
for ns in Namespace.all:
if u == ns[1]:
return ns[0]
... | [
"def",
"getprefix",
"(",
"self",
",",
"u",
")",
":",
"for",
"ns",
"in",
"Namespace",
".",
"all",
":",
"if",
"u",
"==",
"ns",
"[",
"1",
"]",
":",
"return",
"ns",
"[",
"0",
"]",
"for",
"ns",
"in",
"self",
".",
"prefixes",
":",
"if",
"u",
"==",
... | Get the prefix for the specified namespace (uri)
@param u: A namespace uri.
@type u: str
@return: The namspace.
@rtype: (prefix, uri). | [
"Get",
"the",
"prefix",
"for",
"the",
"specified",
"namespace",
"(",
"uri",
")"
] | python | train | 29.066667 |
twilio/twilio-python | twilio/rest/api/v2010/account/usage/trigger.py | https://github.com/twilio/twilio-python/blob/c867895f55dcc29f522e6e8b8868d0d18483132f/twilio/rest/api/v2010/account/usage/trigger.py#L71-L101 | def stream(self, recurring=values.unset, trigger_by=values.unset,
usage_category=values.unset, limit=None, page_size=None):
"""
Streams TriggerInstance records from the API as a generator stream.
This operation lazily loads records as efficiently as possible until the limit
... | [
"def",
"stream",
"(",
"self",
",",
"recurring",
"=",
"values",
".",
"unset",
",",
"trigger_by",
"=",
"values",
".",
"unset",
",",
"usage_category",
"=",
"values",
".",
"unset",
",",
"limit",
"=",
"None",
",",
"page_size",
"=",
"None",
")",
":",
"limits... | Streams TriggerInstance records from the API as a generator stream.
This operation lazily loads records as efficiently as possible until the limit
is reached.
The results are returned as a generator, so this operation is memory efficient.
:param TriggerInstance.Recurring recurring: The ... | [
"Streams",
"TriggerInstance",
"records",
"from",
"the",
"API",
"as",
"a",
"generator",
"stream",
".",
"This",
"operation",
"lazily",
"loads",
"records",
"as",
"efficiently",
"as",
"possible",
"until",
"the",
"limit",
"is",
"reached",
".",
"The",
"results",
"ar... | python | train | 56.032258 |
daviddrysdale/python-phonenumbers | python/phonenumbers/phonenumberutil.py | https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/phonenumberutil.py#L1830-L1853 | def example_number_for_non_geo_entity(country_calling_code):
"""Gets a valid number for the specified country calling code for a non-geographical entity.
Arguments:
country_calling_code -- The country calling code for a non-geographical entity.
Returns a valid number for the non-geographical entity. R... | [
"def",
"example_number_for_non_geo_entity",
"(",
"country_calling_code",
")",
":",
"metadata",
"=",
"PhoneMetadata",
".",
"metadata_for_nongeo_region",
"(",
"country_calling_code",
",",
"None",
")",
"if",
"metadata",
"is",
"not",
"None",
":",
"# For geographical entities,... | Gets a valid number for the specified country calling code for a non-geographical entity.
Arguments:
country_calling_code -- The country calling code for a non-geographical entity.
Returns a valid number for the non-geographical entity. Returns None when
the metadata does not contain such information,... | [
"Gets",
"a",
"valid",
"number",
"for",
"the",
"specified",
"country",
"calling",
"code",
"for",
"a",
"non",
"-",
"geographical",
"entity",
"."
] | python | train | 58.75 |
hydraplatform/hydra-base | hydra_base/lib/users.py | https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/users.py#L278-L292 | def delete_role_perm(role_id, perm_id,**kwargs):
"""
Remove a permission from a role
"""
#check_perm(kwargs.get('user_id'), 'edit_perm')
_get_perm(perm_id)
_get_role(role_id)
try:
roleperm_i = db.DBSession.query(RolePerm).filter(RolePerm.role_id==role_id, RolePerm.perm_id==perm_... | [
"def",
"delete_role_perm",
"(",
"role_id",
",",
"perm_id",
",",
"*",
"*",
"kwargs",
")",
":",
"#check_perm(kwargs.get('user_id'), 'edit_perm')",
"_get_perm",
"(",
"perm_id",
")",
"_get_role",
"(",
"role_id",
")",
"try",
":",
"roleperm_i",
"=",
"db",
".",
"DBSess... | Remove a permission from a role | [
"Remove",
"a",
"permission",
"from",
"a",
"role"
] | python | train | 30.8 |
inspirehep/harvesting-kit | harvestingkit/utils.py | https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/utils.py#L476-L482 | def return_letters_from_string(text):
"""Get letters from string only."""
out = ""
for letter in text:
if letter.isalpha():
out += letter
return out | [
"def",
"return_letters_from_string",
"(",
"text",
")",
":",
"out",
"=",
"\"\"",
"for",
"letter",
"in",
"text",
":",
"if",
"letter",
".",
"isalpha",
"(",
")",
":",
"out",
"+=",
"letter",
"return",
"out"
] | Get letters from string only. | [
"Get",
"letters",
"from",
"string",
"only",
"."
] | python | valid | 25.428571 |
osfclient/osfclient | osfclient/api.py | https://github.com/osfclient/osfclient/blob/44b9a87e8c1ae6b63cdecd27a924af3fc2bf94cf/osfclient/api.py#L22-L28 | def project(self, project_id):
"""Fetch project `project_id`."""
type_ = self.guid(project_id)
url = self._build_url(type_, project_id)
if type_ in Project._types:
return Project(self._json(self._get(url), 200), self.session)
raise OSFException('{} is unrecognized typ... | [
"def",
"project",
"(",
"self",
",",
"project_id",
")",
":",
"type_",
"=",
"self",
".",
"guid",
"(",
"project_id",
")",
"url",
"=",
"self",
".",
"_build_url",
"(",
"type_",
",",
"project_id",
")",
"if",
"type_",
"in",
"Project",
".",
"_types",
":",
"r... | Fetch project `project_id`. | [
"Fetch",
"project",
"project_id",
"."
] | python | valid | 55.571429 |
asphalt-framework/asphalt | asphalt/core/context.py | https://github.com/asphalt-framework/asphalt/blob/4114b3ac9743cbd9facb374a3f53e19d3afef22d/asphalt/core/context.py#L176-L184 | def context_chain(self) -> List['Context']:
"""Return a list of contexts starting from this one, its parent and so on."""
contexts = []
ctx = self # type: Optional[Context]
while ctx is not None:
contexts.append(ctx)
ctx = ctx.parent
return contexts | [
"def",
"context_chain",
"(",
"self",
")",
"->",
"List",
"[",
"'Context'",
"]",
":",
"contexts",
"=",
"[",
"]",
"ctx",
"=",
"self",
"# type: Optional[Context]",
"while",
"ctx",
"is",
"not",
"None",
":",
"contexts",
".",
"append",
"(",
"ctx",
")",
"ctx",
... | Return a list of contexts starting from this one, its parent and so on. | [
"Return",
"a",
"list",
"of",
"contexts",
"starting",
"from",
"this",
"one",
"its",
"parent",
"and",
"so",
"on",
"."
] | python | train | 34.111111 |
ml4ai/delphi | delphi/utils/fp.py | https://github.com/ml4ai/delphi/blob/6d03d8aafeab99610387c51b89c99738ff2abbe3/delphi/utils/fp.py#L56-L80 | def append(x: T, xs: Iterable[T]) -> Iterator[T]:
""" Append a value to an iterable.
Parameters
----------
x
An element of type T.
xs
An iterable of elements of type T.
Returns
-------
Iterator
An iterator that yields elements of *xs*, then yields *x*.
Exa... | [
"def",
"append",
"(",
"x",
":",
"T",
",",
"xs",
":",
"Iterable",
"[",
"T",
"]",
")",
"->",
"Iterator",
"[",
"T",
"]",
":",
"return",
"chain",
"(",
"xs",
",",
"[",
"x",
"]",
")"
] | Append a value to an iterable.
Parameters
----------
x
An element of type T.
xs
An iterable of elements of type T.
Returns
-------
Iterator
An iterator that yields elements of *xs*, then yields *x*.
Examples
--------
>>> from delphi.utils.fp import app... | [
"Append",
"a",
"value",
"to",
"an",
"iterable",
"."
] | python | train | 17.56 |
davidfokkema/artist | artist/plot.py | https://github.com/davidfokkema/artist/blob/26ae7987522622710f2910980770c50012fda47d/artist/plot.py#L952-L993 | def _calc_position_for_pin(self, x, y, relative_position):
"""Determine position at fraction of x, y path.
:param x,y: two equal length lists of values describing a path.
:param relative_position: value between 0 and 1
:returns: the x, y position of the fraction (relative_position)
... | [
"def",
"_calc_position_for_pin",
"(",
"self",
",",
"x",
",",
"y",
",",
"relative_position",
")",
":",
"try",
":",
"max_idx_x",
"=",
"len",
"(",
"x",
")",
"-",
"1",
"max_idx_y",
"=",
"len",
"(",
"y",
")",
"-",
"1",
"except",
"TypeError",
":",
"return"... | Determine position at fraction of x, y path.
:param x,y: two equal length lists of values describing a path.
:param relative_position: value between 0 and 1
:returns: the x, y position of the fraction (relative_position)
of the path length. | [
"Determine",
"position",
"at",
"fraction",
"of",
"x",
"y",
"path",
"."
] | python | train | 37.285714 |
slarse/pdfebc-core | pdfebc_core/compress.py | https://github.com/slarse/pdfebc-core/blob/fc40857bc42365b7434714333e37d7a3487603a0/pdfebc_core/compress.py#L54-L85 | def compress_pdf(filepath, output_path, ghostscript_binary):
"""Compress a single PDF file.
Args:
filepath (str): Path to the PDF file.
output_path (str): Output path.
ghostscript_binary (str): Name/alias of the Ghostscript binary.
Raises:
ValueError
FileNotFoundErr... | [
"def",
"compress_pdf",
"(",
"filepath",
",",
"output_path",
",",
"ghostscript_binary",
")",
":",
"if",
"not",
"filepath",
".",
"endswith",
"(",
"PDF_EXTENSION",
")",
":",
"raise",
"ValueError",
"(",
"\"Filename must end with .pdf!\\n%s does not.\"",
"%",
"filepath",
... | Compress a single PDF file.
Args:
filepath (str): Path to the PDF file.
output_path (str): Output path.
ghostscript_binary (str): Name/alias of the Ghostscript binary.
Raises:
ValueError
FileNotFoundError | [
"Compress",
"a",
"single",
"PDF",
"file",
"."
] | python | train | 39.125 |
bloomreach/s4cmd | s4cmd.py | https://github.com/bloomreach/s4cmd/blob/bb51075bf43703e7cd95aa39288cf7732ec13a6d/s4cmd.py#L410-L420 | def get_legal_params(self, method):
'''Given a API name, list all legal parameters using boto3 service model.'''
if method not in self.client.meta.method_to_api_mapping:
# Injected methods. Ignore.
return []
api = self.client.meta.method_to_api_mapping[method]
shape = self.client.meta.servic... | [
"def",
"get_legal_params",
"(",
"self",
",",
"method",
")",
":",
"if",
"method",
"not",
"in",
"self",
".",
"client",
".",
"meta",
".",
"method_to_api_mapping",
":",
"# Injected methods. Ignore.",
"return",
"[",
"]",
"api",
"=",
"self",
".",
"client",
".",
... | Given a API name, list all legal parameters using boto3 service model. | [
"Given",
"a",
"API",
"name",
"list",
"all",
"legal",
"parameters",
"using",
"boto3",
"service",
"model",
"."
] | python | test | 41.727273 |
Spinmob/spinmob | egg/_gui.py | https://github.com/Spinmob/spinmob/blob/f037f5df07f194bcd4a01f4d9916e57b9e8fb45a/egg/_gui.py#L1206-L1210 | def get_all_items(self):
"""
Returns all items in the combobox dictionary.
"""
return [self._widget.itemText(k) for k in range(self._widget.count())] | [
"def",
"get_all_items",
"(",
"self",
")",
":",
"return",
"[",
"self",
".",
"_widget",
".",
"itemText",
"(",
"k",
")",
"for",
"k",
"in",
"range",
"(",
"self",
".",
"_widget",
".",
"count",
"(",
")",
")",
"]"
] | Returns all items in the combobox dictionary. | [
"Returns",
"all",
"items",
"in",
"the",
"combobox",
"dictionary",
"."
] | python | train | 35.4 |
honzamach/pynspect | pynspect/traversers.py | https://github.com/honzamach/pynspect/blob/0582dcc1f7aafe50e25a21c792ea1b3367ea5881/pynspect/traversers.py#L467-L477 | def binary_operation_comparison(self, rule, left, right, **kwargs):
"""
Callback method for rule tree traversing. Will be called at proper time
from :py:class:`pynspect.rules.ComparisonBinOpRule.traverse` method.
:param pynspect.rules.Rule rule: Reference to rule.
:param left: L... | [
"def",
"binary_operation_comparison",
"(",
"self",
",",
"rule",
",",
"left",
",",
"right",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"'<div class=\"pynspect-rule-operation pynspect-rule-operation-comparison\"><h3 class=\"pynspect-rule-operation-name\">{}</h3><ul class=\"pynspect... | Callback method for rule tree traversing. Will be called at proper time
from :py:class:`pynspect.rules.ComparisonBinOpRule.traverse` method.
:param pynspect.rules.Rule rule: Reference to rule.
:param left: Left operand for operation.
:param right: right operand for operation.
:p... | [
"Callback",
"method",
"for",
"rule",
"tree",
"traversing",
".",
"Will",
"be",
"called",
"at",
"proper",
"time",
"from",
":",
"py",
":",
"class",
":",
"pynspect",
".",
"rules",
".",
"ComparisonBinOpRule",
".",
"traverse",
"method",
"."
] | python | train | 72.909091 |
facelessuser/soupsieve | soupsieve/css_match.py | https://github.com/facelessuser/soupsieve/blob/24859cc3e756ebf46b75547d49c6b4a7bf35ee82/soupsieve/css_match.py#L1422-L1426 | def iselect(self, tag, limit=0):
"""Iterate the specified tags."""
for el in CSSMatch(self.selectors, tag, self.namespaces, self.flags).select(limit):
yield el | [
"def",
"iselect",
"(",
"self",
",",
"tag",
",",
"limit",
"=",
"0",
")",
":",
"for",
"el",
"in",
"CSSMatch",
"(",
"self",
".",
"selectors",
",",
"tag",
",",
"self",
".",
"namespaces",
",",
"self",
".",
"flags",
")",
".",
"select",
"(",
"limit",
")... | Iterate the specified tags. | [
"Iterate",
"the",
"specified",
"tags",
"."
] | python | train | 36.8 |
ManiacalLabs/BiblioPixel | bibliopixel/layout/matrix_drawing.py | https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/layout/matrix_drawing.py#L244-L249 | def draw_rect(setter, x, y, w, h, color=None, aa=False):
"""Draw rectangle with top-left corner at x,y, width w and height h"""
_draw_fast_hline(setter, x, y, w, color, aa)
_draw_fast_hline(setter, x, y + h - 1, w, color, aa)
_draw_fast_vline(setter, x, y, h, color, aa)
_draw_fast_vline(setter, x + ... | [
"def",
"draw_rect",
"(",
"setter",
",",
"x",
",",
"y",
",",
"w",
",",
"h",
",",
"color",
"=",
"None",
",",
"aa",
"=",
"False",
")",
":",
"_draw_fast_hline",
"(",
"setter",
",",
"x",
",",
"y",
",",
"w",
",",
"color",
",",
"aa",
")",
"_draw_fast_... | Draw rectangle with top-left corner at x,y, width w and height h | [
"Draw",
"rectangle",
"with",
"top",
"-",
"left",
"corner",
"at",
"x",
"y",
"width",
"w",
"and",
"height",
"h"
] | python | valid | 56.333333 |
vijayvarma392/surfinBH | surfinBH/surfinBH.py | https://github.com/vijayvarma392/surfinBH/blob/9f2d25d00f894ee2ce9ffbb02f4e4a41fa7989eb/surfinBH/surfinBH.py#L103-L121 | def _load_scalar_fit(self, fit_key=None, h5file=None, fit_data=None):
""" Loads a single fit
"""
if (fit_key is None) ^ (h5file is None):
raise ValueError("Either specify both fit_key and h5file, or"
" neither")
if not ((fit_key is None) ^ (fit_data is None))... | [
"def",
"_load_scalar_fit",
"(",
"self",
",",
"fit_key",
"=",
"None",
",",
"h5file",
"=",
"None",
",",
"fit_data",
"=",
"None",
")",
":",
"if",
"(",
"fit_key",
"is",
"None",
")",
"^",
"(",
"h5file",
"is",
"None",
")",
":",
"raise",
"ValueError",
"(",
... | Loads a single fit | [
"Loads",
"a",
"single",
"fit"
] | python | train | 38.105263 |
disqus/django-mailviews | mailviews/previews.py | https://github.com/disqus/django-mailviews/blob/9993d5e911d545b3bc038433986c5f6812e7e965/mailviews/previews.py#L167-L213 | def detail_view(self, request):
"""
Renders the message view to a response.
"""
context = {
'preview': self,
}
kwargs = {}
if self.form_class:
if request.GET:
form = self.form_class(data=request.GET)
else:
... | [
"def",
"detail_view",
"(",
"self",
",",
"request",
")",
":",
"context",
"=",
"{",
"'preview'",
":",
"self",
",",
"}",
"kwargs",
"=",
"{",
"}",
"if",
"self",
".",
"form_class",
":",
"if",
"request",
".",
"GET",
":",
"form",
"=",
"self",
".",
"form_c... | Renders the message view to a response. | [
"Renders",
"the",
"message",
"view",
"to",
"a",
"response",
"."
] | python | valid | 30.765957 |
kakwa/ldapcherry | ldapcherry/__init__.py | https://github.com/kakwa/ldapcherry/blob/b5e7cb6a44065abc30d164e72981b3713a172dda/ldapcherry/__init__.py#L891-L931 | def login(self, login, password, url=None):
"""login page
"""
auth = self._auth(login, password)
cherrypy.session['isadmin'] = auth['isadmin']
cherrypy.session['connected'] = auth['connected']
if auth['connected']:
if auth['isadmin']:
message ... | [
"def",
"login",
"(",
"self",
",",
"login",
",",
"password",
",",
"url",
"=",
"None",
")",
":",
"auth",
"=",
"self",
".",
"_auth",
"(",
"login",
",",
"password",
")",
"cherrypy",
".",
"session",
"[",
"'isadmin'",
"]",
"=",
"auth",
"[",
"'isadmin'",
... | login page | [
"login",
"page"
] | python | train | 33.04878 |
deepmipt/DeepPavlov | deeppavlov/core/models/keras_model.py | https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/core/models/keras_model.py#L156-L165 | def train_on_batch(self, *args) -> None:
"""Trains the model on a single batch.
Args:
*args: the list of network inputs.
Last element of `args` is the batch of targets,
all previous elements are training data batches
"""
*data, labels = args
s... | [
"def",
"train_on_batch",
"(",
"self",
",",
"*",
"args",
")",
"->",
"None",
":",
"*",
"data",
",",
"labels",
"=",
"args",
"self",
".",
"_net",
".",
"train_on_batch",
"(",
"data",
",",
"labels",
")"
] | Trains the model on a single batch.
Args:
*args: the list of network inputs.
Last element of `args` is the batch of targets,
all previous elements are training data batches | [
"Trains",
"the",
"model",
"on",
"a",
"single",
"batch",
"."
] | python | test | 34.8 |
tanghaibao/jcvi | jcvi/annotation/reformat.py | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/annotation/reformat.py#L934-L1101 | def reindex(args):
"""
%prog reindex gffile pep.fasta ref.pep.fasta
Reindex the splice isoforms (mRNA) in input GFF file, preferably
generated after PASA annotation update
In the input GFF file, there can be several types of mRNA within a locus:
* CDS matches reference, UTR extended, inherits ... | [
"def",
"reindex",
"(",
"args",
")",
":",
"from",
"jcvi",
".",
"formats",
".",
"gff",
"import",
"make_index",
"from",
"jcvi",
".",
"formats",
".",
"fasta",
"import",
"Fasta",
"from",
"jcvi",
".",
"apps",
".",
"emboss",
"import",
"needle",
"from",
"jcvi",
... | %prog reindex gffile pep.fasta ref.pep.fasta
Reindex the splice isoforms (mRNA) in input GFF file, preferably
generated after PASA annotation update
In the input GFF file, there can be several types of mRNA within a locus:
* CDS matches reference, UTR extended, inherits reference mRNA ID
* CDS (sl... | [
"%prog",
"reindex",
"gffile",
"pep",
".",
"fasta",
"ref",
".",
"pep",
".",
"fasta"
] | python | train | 39.803571 |
PureStorage-OpenConnect/rest-client | purestorage/purestorage.py | https://github.com/PureStorage-OpenConnect/rest-client/blob/097d5f2bc6facf607d7e4a92567b09fb8cf5cb34/purestorage/purestorage.py#L2448-L2478 | def connect_array(self, address, connection_key, connection_type, **kwargs):
"""Connect this array with another one.
:param address: IP address or DNS name of other array.
:type address: str
:param connection_key: Connection key of other array.
:type connection_key: str
... | [
"def",
"connect_array",
"(",
"self",
",",
"address",
",",
"connection_key",
",",
"connection_type",
",",
"*",
"*",
"kwargs",
")",
":",
"data",
"=",
"{",
"\"management_address\"",
":",
"address",
",",
"\"connection_key\"",
":",
"connection_key",
",",
"\"type\"",
... | Connect this array with another one.
:param address: IP address or DNS name of other array.
:type address: str
:param connection_key: Connection key of other array.
:type connection_key: str
:param connection_type: Type(s) of connection desired.
:type connection_type: li... | [
"Connect",
"this",
"array",
"with",
"another",
"one",
"."
] | python | train | 35.677419 |
ByteInternet/amqpconsumer | amqpconsumer/events.py | https://github.com/ByteInternet/amqpconsumer/blob/144ab16b3fbba8ad30f8688ae1c58e3a6423b88b/amqpconsumer/events.py#L278-L304 | def on_message(self, _, basic_deliver, properties, body):
"""Invoked by pika when a message is delivered from RabbitMQ.
The channel is passed for your convenience. The basic_deliver object
that is passed in carries the exchange, routing key, delivery tag
and a redelivered flag for the m... | [
"def",
"on_message",
"(",
"self",
",",
"_",
",",
"basic_deliver",
",",
"properties",
",",
"body",
")",
":",
"logger",
".",
"debug",
"(",
"'Received message # %s from %s: %s'",
",",
"basic_deliver",
".",
"delivery_tag",
",",
"properties",
".",
"app_id",
",",
"b... | Invoked by pika when a message is delivered from RabbitMQ.
The channel is passed for your convenience. The basic_deliver object
that is passed in carries the exchange, routing key, delivery tag
and a redelivered flag for the message. The properties passed in is
an instance of BasicPrope... | [
"Invoked",
"by",
"pika",
"when",
"a",
"message",
"is",
"delivered",
"from",
"RabbitMQ",
"."
] | python | train | 44.888889 |
floydhub/floyd-cli | floyd/cli/experiment.py | https://github.com/floydhub/floyd-cli/blob/ea6b9521119cbde2dfc71ce0cc87c0d9c143fc6c/floyd/cli/experiment.py#L82-L97 | def status(id):
"""
View status of all jobs in a project.
The command also accepts a specific job name.
"""
if id:
try:
experiment = ExperimentClient().get(normalize_job_name(id))
except FloydException:
experiment = ExperimentClient().get(id)
print_e... | [
"def",
"status",
"(",
"id",
")",
":",
"if",
"id",
":",
"try",
":",
"experiment",
"=",
"ExperimentClient",
"(",
")",
".",
"get",
"(",
"normalize_job_name",
"(",
"id",
")",
")",
"except",
"FloydException",
":",
"experiment",
"=",
"ExperimentClient",
"(",
"... | View status of all jobs in a project.
The command also accepts a specific job name. | [
"View",
"status",
"of",
"all",
"jobs",
"in",
"a",
"project",
"."
] | python | train | 26.8125 |
shmir/PyIxExplorer | ixexplorer/ixe_port.py | https://github.com/shmir/PyIxExplorer/blob/d6946b9ce0e8961507cc912062e10c365d4beee2/ixexplorer/ixe_port.py#L344-L352 | def set_phy_mode(self, mode=IxePhyMode.ignore):
""" Set phy mode to copper or fiber.
:param mode: requested PHY mode.
"""
if isinstance(mode, IxePhyMode):
if mode.value:
self.api.call_rc('port setPhyMode {} {}'.format(mode.value, self.uri))
else:
... | [
"def",
"set_phy_mode",
"(",
"self",
",",
"mode",
"=",
"IxePhyMode",
".",
"ignore",
")",
":",
"if",
"isinstance",
"(",
"mode",
",",
"IxePhyMode",
")",
":",
"if",
"mode",
".",
"value",
":",
"self",
".",
"api",
".",
"call_rc",
"(",
"'port setPhyMode {} {}'"... | Set phy mode to copper or fiber.
:param mode: requested PHY mode. | [
"Set",
"phy",
"mode",
"to",
"copper",
"or",
"fiber",
".",
":",
"param",
"mode",
":",
"requested",
"PHY",
"mode",
"."
] | python | train | 42.555556 |
JNRowe/upoints | upoints/utils.py | https://github.com/JNRowe/upoints/blob/1e4b7a53ed2a06cd854523d54c36aabdccea3830/upoints/utils.py#L1002-L1026 | def sun_events(latitude, longitude, date, timezone=0, zenith=None):
"""Convenience function for calculating sunrise and sunset.
Civil twilight starts/ends when the Sun's centre is 6 degrees below
the horizon.
Nautical twilight starts/ends when the Sun's centre is 12 degrees
below the horizon.
... | [
"def",
"sun_events",
"(",
"latitude",
",",
"longitude",
",",
"date",
",",
"timezone",
"=",
"0",
",",
"zenith",
"=",
"None",
")",
":",
"return",
"(",
"sun_rise_set",
"(",
"latitude",
",",
"longitude",
",",
"date",
",",
"'rise'",
",",
"timezone",
",",
"z... | Convenience function for calculating sunrise and sunset.
Civil twilight starts/ends when the Sun's centre is 6 degrees below
the horizon.
Nautical twilight starts/ends when the Sun's centre is 12 degrees
below the horizon.
Astronomical twilight starts/ends when the Sun's centre is 18 degrees belo... | [
"Convenience",
"function",
"for",
"calculating",
"sunrise",
"and",
"sunset",
"."
] | python | train | 38.32 |
ranaroussi/qtpylib | qtpylib/tools.py | https://github.com/ranaroussi/qtpylib/blob/0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd/qtpylib/tools.py#L375-L414 | def backdate(res, date=None, as_datetime=False, fmt='%Y-%m-%d'):
""" get past date based on currect date """
if res is None:
return None
if date is None:
date = datetime.datetime.now()
else:
try:
date = parse_date(date)
except Exception as e:
pass... | [
"def",
"backdate",
"(",
"res",
",",
"date",
"=",
"None",
",",
"as_datetime",
"=",
"False",
",",
"fmt",
"=",
"'%Y-%m-%d'",
")",
":",
"if",
"res",
"is",
"None",
":",
"return",
"None",
"if",
"date",
"is",
"None",
":",
"date",
"=",
"datetime",
".",
"da... | get past date based on currect date | [
"get",
"past",
"date",
"based",
"on",
"currect",
"date"
] | python | train | 29.425 |
jbeluch/xbmcswift2 | xbmcswift2/listitem.py | https://github.com/jbeluch/xbmcswift2/blob/0e7a3642499554edc8265fdf1ba6c5ee567daa78/xbmcswift2/listitem.py#L186-L221 | def from_dict(cls, label=None, label2=None, icon=None, thumbnail=None,
path=None, selected=None, info=None, properties=None,
context_menu=None, replace_context_menu=False,
is_playable=None, info_type='video', stream_info=None):
'''A ListItem constructor for ... | [
"def",
"from_dict",
"(",
"cls",
",",
"label",
"=",
"None",
",",
"label2",
"=",
"None",
",",
"icon",
"=",
"None",
",",
"thumbnail",
"=",
"None",
",",
"path",
"=",
"None",
",",
"selected",
"=",
"None",
",",
"info",
"=",
"None",
",",
"properties",
"="... | A ListItem constructor for setting a lot of properties not
available in the regular __init__ method. Useful to collect all
the properties in a dict and then use the **dct to call this
method. | [
"A",
"ListItem",
"constructor",
"for",
"setting",
"a",
"lot",
"of",
"properties",
"not",
"available",
"in",
"the",
"regular",
"__init__",
"method",
".",
"Useful",
"to",
"collect",
"all",
"the",
"properties",
"in",
"a",
"dict",
"and",
"then",
"use",
"the",
... | python | train | 37.527778 |
ninuxorg/nodeshot | nodeshot/community/notifications/registrars/nodes.py | https://github.com/ninuxorg/nodeshot/blob/2466f0a55f522b2696026f196436ce7ba3f1e5c6/nodeshot/community/notifications/registrars/nodes.py#L42-L62 | def node_status_changed_handler(**kwargs):
""" send notification when the status of a node changes according to users's settings """
obj = kwargs['instance']
obj.old_status = kwargs['old_status'].name
obj.new_status = kwargs['new_status'].name
queryset = exclude_owner_of_node(obj)
create_notific... | [
"def",
"node_status_changed_handler",
"(",
"*",
"*",
"kwargs",
")",
":",
"obj",
"=",
"kwargs",
"[",
"'instance'",
"]",
"obj",
".",
"old_status",
"=",
"kwargs",
"[",
"'old_status'",
"]",
".",
"name",
"obj",
".",
"new_status",
"=",
"kwargs",
"[",
"'new_statu... | send notification when the status of a node changes according to users's settings | [
"send",
"notification",
"when",
"the",
"status",
"of",
"a",
"node",
"changes",
"according",
"to",
"users",
"s",
"settings"
] | python | train | 37.714286 |
hhatto/autopep8 | autopep8.py | https://github.com/hhatto/autopep8/blob/fda3bb39181437b6b8a0aa0185f21ae5f14385dd/autopep8.py#L3544-L3558 | def extract_code_from_function(function):
"""Return code handled by function."""
if not function.__name__.startswith('fix_'):
return None
code = re.sub('^fix_', '', function.__name__)
if not code:
return None
try:
int(code[1:])
except ValueError:
return None
... | [
"def",
"extract_code_from_function",
"(",
"function",
")",
":",
"if",
"not",
"function",
".",
"__name__",
".",
"startswith",
"(",
"'fix_'",
")",
":",
"return",
"None",
"code",
"=",
"re",
".",
"sub",
"(",
"'^fix_'",
",",
"''",
",",
"function",
".",
"__nam... | Return code handled by function. | [
"Return",
"code",
"handled",
"by",
"function",
"."
] | python | train | 21.266667 |
maxfischer2781/chainlet | chainlet/genlink.py | https://github.com/maxfischer2781/chainlet/blob/4e17f9992b4780bd0d9309202e2847df640bffe8/chainlet/genlink.py#L203-L239 | def genlet(generator_function=None, prime=True):
"""
Decorator to convert a generator function to a :py:class:`~chainlink.ChainLink`
:param generator_function: the generator function to convert
:type generator_function: generator
:param prime: advance the generator to the next/first yield
:type... | [
"def",
"genlet",
"(",
"generator_function",
"=",
"None",
",",
"prime",
"=",
"True",
")",
":",
"if",
"generator_function",
"is",
"None",
":",
"return",
"GeneratorLink",
".",
"wraplet",
"(",
"prime",
"=",
"prime",
")",
"elif",
"not",
"callable",
"(",
"genera... | Decorator to convert a generator function to a :py:class:`~chainlink.ChainLink`
:param generator_function: the generator function to convert
:type generator_function: generator
:param prime: advance the generator to the next/first yield
:type prime: bool
When used as a decorator, this function can... | [
"Decorator",
"to",
"convert",
"a",
"generator",
"function",
"to",
"a",
":",
"py",
":",
"class",
":",
"~chainlink",
".",
"ChainLink"
] | python | train | 31.459459 |
RiotGames/cloud-inquisitor | backend/cloud_inquisitor/utils.py | https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/backend/cloud_inquisitor/utils.py#L187-L203 | def parse_bucket_info(domain):
"""Parse a domain name to gather the bucket name and region for an S3 bucket. Returns a tuple
(bucket_name, bucket_region) if a valid domain name, else `None`
>>> parse_bucket_info('www.riotgames.com.br.s3-website-us-west-2.amazonaws.com')
('www.riotgames.com.br', 'us-w... | [
"def",
"parse_bucket_info",
"(",
"domain",
")",
":",
"match",
"=",
"RGX_BUCKET",
".",
"match",
"(",
"domain",
")",
"if",
"match",
":",
"data",
"=",
"match",
".",
"groupdict",
"(",
")",
"return",
"data",
"[",
"'bucket'",
"]",
",",
"data",
"[",
"'region'... | Parse a domain name to gather the bucket name and region for an S3 bucket. Returns a tuple
(bucket_name, bucket_region) if a valid domain name, else `None`
>>> parse_bucket_info('www.riotgames.com.br.s3-website-us-west-2.amazonaws.com')
('www.riotgames.com.br', 'us-west-2')
Args:
domain (`st... | [
"Parse",
"a",
"domain",
"name",
"to",
"gather",
"the",
"bucket",
"name",
"and",
"region",
"for",
"an",
"S3",
"bucket",
".",
"Returns",
"a",
"tuple",
"(",
"bucket_name",
"bucket_region",
")",
"if",
"a",
"valid",
"domain",
"name",
"else",
"None"
] | python | train | 33.941176 |
standage/tag | tag/transcript.py | https://github.com/standage/tag/blob/94686adf57115cea1c5235e99299e691f80ba10b/tag/transcript.py#L46-L74 | def primary_mrna(entrystream, parenttype='gene'):
"""
Select a single mRNA as a representative for each protein-coding gene.
The primary mRNA is the one with the longest translation product. In cases
where multiple isoforms have the same translated length, the feature ID is
used for sorting.
T... | [
"def",
"primary_mrna",
"(",
"entrystream",
",",
"parenttype",
"=",
"'gene'",
")",
":",
"for",
"entry",
"in",
"entrystream",
":",
"if",
"not",
"isinstance",
"(",
"entry",
",",
"tag",
".",
"Feature",
")",
":",
"yield",
"entry",
"continue",
"for",
"parent",
... | Select a single mRNA as a representative for each protein-coding gene.
The primary mRNA is the one with the longest translation product. In cases
where multiple isoforms have the same translated length, the feature ID is
used for sorting.
This function **does not** return only mRNA features, it return... | [
"Select",
"a",
"single",
"mRNA",
"as",
"a",
"representative",
"for",
"each",
"protein",
"-",
"coding",
"gene",
"."
] | python | train | 40.172414 |
saltstack/salt | salt/modules/zfs.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zfs.py#L1158-L1264 | def get(*dataset, **kwargs):
'''
Displays properties for the given datasets.
dataset : string
name of snapshot(s), filesystem(s), or volume(s)
properties : string
comma-separated list of properties to list, defaults to all
recursive : boolean
recursively list children
de... | [
"def",
"get",
"(",
"*",
"dataset",
",",
"*",
"*",
"kwargs",
")",
":",
"## Configure command",
"# NOTE: initialize the defaults",
"flags",
"=",
"[",
"'-H'",
"]",
"opts",
"=",
"{",
"}",
"# NOTE: set extra config from kwargs",
"if",
"kwargs",
".",
"get",
"(",
"'d... | Displays properties for the given datasets.
dataset : string
name of snapshot(s), filesystem(s), or volume(s)
properties : string
comma-separated list of properties to list, defaults to all
recursive : boolean
recursively list children
depth : int
recursively list childr... | [
"Displays",
"properties",
"for",
"the",
"given",
"datasets",
"."
] | python | train | 32.654206 |
sdss/sdss_access | python/sdss_access/path/path.py | https://github.com/sdss/sdss_access/blob/76375bbf37d39d2e4ccbed90bdfa9a4298784470/python/sdss_access/path/path.py#L69-L78 | def _input_templates(self):
"""Read the path template file.
"""
foo = self._config.read([self._pathfile])
if len(foo) == 1:
for k, v in self._config.items('paths'):
self.templates[k] = v
else:
raise ValueError("Could not read {0}!".format(s... | [
"def",
"_input_templates",
"(",
"self",
")",
":",
"foo",
"=",
"self",
".",
"_config",
".",
"read",
"(",
"[",
"self",
".",
"_pathfile",
"]",
")",
"if",
"len",
"(",
"foo",
")",
"==",
"1",
":",
"for",
"k",
",",
"v",
"in",
"self",
".",
"_config",
"... | Read the path template file. | [
"Read",
"the",
"path",
"template",
"file",
"."
] | python | train | 34.1 |
BDNYC/astrodbkit | astrodbkit/astrodb.py | https://github.com/BDNYC/astrodbkit/blob/02c03c5e91aa7c7b0f3b5fa95bcf71e33ffcee09/astrodbkit/astrodb.py#L274-L478 | def add_data(self, data, table, delimiter='|', bands='', clean_up=True, rename_columns={}, column_fill={}, verbose=False):
"""
Adds data to the specified database table. Column names must match table fields to insert,
however order and completeness don't matter.
Parameters
... | [
"def",
"add_data",
"(",
"self",
",",
"data",
",",
"table",
",",
"delimiter",
"=",
"'|'",
",",
"bands",
"=",
"''",
",",
"clean_up",
"=",
"True",
",",
"rename_columns",
"=",
"{",
"}",
",",
"column_fill",
"=",
"{",
"}",
",",
"verbose",
"=",
"False",
"... | Adds data to the specified database table. Column names must match table fields to insert,
however order and completeness don't matter.
Parameters
----------
data: str, array-like, astropy.table.Table
The path to an ascii file, array-like object, or table. The first ... | [
"Adds",
"data",
"to",
"the",
"specified",
"database",
"table",
".",
"Column",
"names",
"must",
"match",
"table",
"fields",
"to",
"insert",
"however",
"order",
"and",
"completeness",
"don",
"t",
"matter",
".",
"Parameters",
"----------",
"data",
":",
"str",
"... | python | train | 46.887805 |
FujiMakoto/IPS-Vagrant | ips_vagrant/commands/setup/__init__.py | https://github.com/FujiMakoto/IPS-Vagrant/blob/7b1d6d095034dd8befb026d9315ecc6494d52269/ips_vagrant/commands/setup/__init__.py#L20-L201 | def cli(ctx):
"""
Run setup after a fresh Vagrant installation.
"""
log = logging.getLogger('ipsv.setup')
assert isinstance(ctx, Context)
lock_path = os.path.join(ctx.config.get('Paths', 'Data'), 'setup.lck')
if os.path.exists(lock_path):
raise Exception('Setup is locked, please rem... | [
"def",
"cli",
"(",
"ctx",
")",
":",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"'ipsv.setup'",
")",
"assert",
"isinstance",
"(",
"ctx",
",",
"Context",
")",
"lock_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"ctx",
".",
"config",
".",
"get",
... | Run setup after a fresh Vagrant installation. | [
"Run",
"setup",
"after",
"a",
"fresh",
"Vagrant",
"installation",
"."
] | python | train | 35.510989 |
scottrice/pysteam | pysteam/winutils.py | https://github.com/scottrice/pysteam/blob/1eb2254b5235a053a953e596fa7602d0b110245d/pysteam/winutils.py#L10-L20 | def find_steam_location():
"""
Finds the location of the current Steam installation on Windows machines.
Returns None for any non-Windows machines, or for Windows machines where
Steam is not installed.
"""
if registry is None:
return None
key = registry.CreateKey(registry.HKEY_CURRENT_USER,"Software\... | [
"def",
"find_steam_location",
"(",
")",
":",
"if",
"registry",
"is",
"None",
":",
"return",
"None",
"key",
"=",
"registry",
".",
"CreateKey",
"(",
"registry",
".",
"HKEY_CURRENT_USER",
",",
"\"Software\\Valve\\Steam\"",
")",
"return",
"registry",
".",
"QueryValu... | Finds the location of the current Steam installation on Windows machines.
Returns None for any non-Windows machines, or for Windows machines where
Steam is not installed. | [
"Finds",
"the",
"location",
"of",
"the",
"current",
"Steam",
"installation",
"on",
"Windows",
"machines",
".",
"Returns",
"None",
"for",
"any",
"non",
"-",
"Windows",
"machines",
"or",
"for",
"Windows",
"machines",
"where",
"Steam",
"is",
"not",
"installed",
... | python | train | 34 |
SiLab-Bonn/pyBAR | pybar/utils/utils.py | https://github.com/SiLab-Bonn/pyBAR/blob/5ad95bbcd41cd358825823fb78f396cfce23593e/pybar/utils/utils.py#L285-L291 | def get_float_time():
'''returns time as double precision floats - Time64 in pytables - mapping to and from python datetime's
'''
t1 = time.time()
t2 = datetime.datetime.fromtimestamp(t1)
return time.mktime(t2.timetuple()) + 1e-6 * t2.microsecond | [
"def",
"get_float_time",
"(",
")",
":",
"t1",
"=",
"time",
".",
"time",
"(",
")",
"t2",
"=",
"datetime",
".",
"datetime",
".",
"fromtimestamp",
"(",
"t1",
")",
"return",
"time",
".",
"mktime",
"(",
"t2",
".",
"timetuple",
"(",
")",
")",
"+",
"1e-6"... | returns time as double precision floats - Time64 in pytables - mapping to and from python datetime's | [
"returns",
"time",
"as",
"double",
"precision",
"floats",
"-",
"Time64",
"in",
"pytables",
"-",
"mapping",
"to",
"and",
"from",
"python",
"datetime",
"s"
] | python | train | 38.142857 |
TrafficSenseMSD/SumoTools | traci/_vehicle.py | https://github.com/TrafficSenseMSD/SumoTools/blob/8607b4f885f1d1798e43240be643efe6dccccdaa/traci/_vehicle.py#L936-L957 | def rerouteTraveltime(self, vehID, currentTravelTimes=True):
"""rerouteTraveltime(string, bool) -> None Reroutes a vehicle. If
currentTravelTimes is True (default) then the current traveltime of the
edges is loaded and used for rerouting. If currentTravelTimes is False
custom travel time... | [
"def",
"rerouteTraveltime",
"(",
"self",
",",
"vehID",
",",
"currentTravelTimes",
"=",
"True",
")",
":",
"if",
"currentTravelTimes",
":",
"time",
"=",
"self",
".",
"_connection",
".",
"simulation",
".",
"getCurrentTime",
"(",
")",
"if",
"time",
"!=",
"self",... | rerouteTraveltime(string, bool) -> None Reroutes a vehicle. If
currentTravelTimes is True (default) then the current traveltime of the
edges is loaded and used for rerouting. If currentTravelTimes is False
custom travel times are used. The various functions and options for
customizing tr... | [
"rerouteTraveltime",
"(",
"string",
"bool",
")",
"-",
">",
"None",
"Reroutes",
"a",
"vehicle",
".",
"If",
"currentTravelTimes",
"is",
"True",
"(",
"default",
")",
"then",
"the",
"current",
"traveltime",
"of",
"the",
"edges",
"is",
"loaded",
"and",
"used",
... | python | train | 59.454545 |
googleapis/google-cloud-python | datalabeling/google/cloud/datalabeling_v1beta1/gapic/data_labeling_service_client.py | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/datalabeling/google/cloud/datalabeling_v1beta1/gapic/data_labeling_service_client.py#L119-L127 | def example_path(cls, project, dataset, annotated_dataset, example):
"""Return a fully-qualified example string."""
return google.api_core.path_template.expand(
"projects/{project}/datasets/{dataset}/annotatedDatasets/{annotated_dataset}/examples/{example}",
project=project,
... | [
"def",
"example_path",
"(",
"cls",
",",
"project",
",",
"dataset",
",",
"annotated_dataset",
",",
"example",
")",
":",
"return",
"google",
".",
"api_core",
".",
"path_template",
".",
"expand",
"(",
"\"projects/{project}/datasets/{dataset}/annotatedDatasets/{annotated_da... | Return a fully-qualified example string. | [
"Return",
"a",
"fully",
"-",
"qualified",
"example",
"string",
"."
] | python | train | 47.111111 |
tariqdaouda/pyGeno | pyGeno/bootstrap.py | https://github.com/tariqdaouda/pyGeno/blob/474b1250bf78ce5c7e7c3bbbfdbad9635d5a7d14/pyGeno/bootstrap.py#L19-L47 | def printRemoteDatawraps(location = conf.pyGeno_REMOTE_LOCATION) :
"""
print all available datawraps from a remote location the location must have a datawraps.json in the following format::
{
"Ordered": {
"Reference genomes": {
"Human" : ["GRCh37.75", "GRCh38.78"],
"Mouse" : ["GRCm38.78"],
}... | [
"def",
"printRemoteDatawraps",
"(",
"location",
"=",
"conf",
".",
"pyGeno_REMOTE_LOCATION",
")",
":",
"l",
"=",
"listRemoteDatawraps",
"(",
"location",
")",
"printf",
"(",
"\"Available datawraps for bootstraping\\n\"",
")",
"print",
"json",
".",
"dumps",
"(",
"l",
... | print all available datawraps from a remote location the location must have a datawraps.json in the following format::
{
"Ordered": {
"Reference genomes": {
"Human" : ["GRCh37.75", "GRCh38.78"],
"Mouse" : ["GRCm38.78"],
},
"SNPs":{
}
},
"Flat":{
"Reference genomes": {
"G... | [
"print",
"all",
"available",
"datawraps",
"from",
"a",
"remote",
"location",
"the",
"location",
"must",
"have",
"a",
"datawraps",
".",
"json",
"in",
"the",
"following",
"format",
"::"
] | python | train | 24.172414 |
dmlc/gluon-nlp | scripts/bert/fp16_utils.py | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/bert/fp16_utils.py#L236-L253 | def update_scale(self, overflow):
"""dynamically update loss scale"""
iter_since_rescale = self._num_steps - self._last_rescale_iter
if overflow:
self._last_overflow_iter = self._num_steps
self._overflows_since_rescale += 1
percentage = self._overflows_since_r... | [
"def",
"update_scale",
"(",
"self",
",",
"overflow",
")",
":",
"iter_since_rescale",
"=",
"self",
".",
"_num_steps",
"-",
"self",
".",
"_last_rescale_iter",
"if",
"overflow",
":",
"self",
".",
"_last_overflow_iter",
"=",
"self",
".",
"_num_steps",
"self",
".",... | dynamically update loss scale | [
"dynamically",
"update",
"loss",
"scale"
] | python | train | 54.388889 |
pysal/spglm | spglm/family.py | https://github.com/pysal/spglm/blob/1339898adcb7e1638f1da83d57aa37392525f018/spglm/family.py#L800-L831 | def deviance(self, endog, mu, freq_weights=1, scale=1., axis=None):
r'''
Deviance function for either Bernoulli or Binomial data.
Parameters
----------
endog : array-like
Endogenous response variable (already transformed to a probability
if appropriate).
... | [
"def",
"deviance",
"(",
"self",
",",
"endog",
",",
"mu",
",",
"freq_weights",
"=",
"1",
",",
"scale",
"=",
"1.",
",",
"axis",
"=",
"None",
")",
":",
"if",
"np",
".",
"shape",
"(",
"self",
".",
"n",
")",
"==",
"(",
")",
"and",
"self",
".",
"n"... | r'''
Deviance function for either Bernoulli or Binomial data.
Parameters
----------
endog : array-like
Endogenous response variable (already transformed to a probability
if appropriate).
mu : array
Fitted mean response variable
freq_we... | [
"r",
"Deviance",
"function",
"for",
"either",
"Bernoulli",
"or",
"Binomial",
"data",
"."
] | python | train | 36.34375 |
CalebBell/fluids | fluids/jet_pump.py | https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/jet_pump.py#L33-L163 | def liquid_jet_pump_ancillary(rhop, rhos, Kp, Ks, d_nozzle=None, d_mixing=None,
Qp=None, Qs=None, P1=None, P2=None):
r'''Calculates the remaining variable in a liquid jet pump when solving for
one if the inlet variables only and the rest of them are known. The
equation comes f... | [
"def",
"liquid_jet_pump_ancillary",
"(",
"rhop",
",",
"rhos",
",",
"Kp",
",",
"Ks",
",",
"d_nozzle",
"=",
"None",
",",
"d_mixing",
"=",
"None",
",",
"Qp",
"=",
"None",
",",
"Qs",
"=",
"None",
",",
"P1",
"=",
"None",
",",
"P2",
"=",
"None",
")",
"... | r'''Calculates the remaining variable in a liquid jet pump when solving for
one if the inlet variables only and the rest of them are known. The
equation comes from conservation of energy and momentum in the mixing
chamber.
The variable to be solved for must be one of `d_nozzle`, `d_mixing`,
`Qp... | [
"r",
"Calculates",
"the",
"remaining",
"variable",
"in",
"a",
"liquid",
"jet",
"pump",
"when",
"solving",
"for",
"one",
"if",
"the",
"inlet",
"variables",
"only",
"and",
"the",
"rest",
"of",
"them",
"are",
"known",
".",
"The",
"equation",
"comes",
"from",
... | python | train | 39.21374 |
thefactory/marathon-python | marathon/models/constraint.py | https://github.com/thefactory/marathon-python/blob/592b253aa8edf2475c97ca438ad7b6936652caf2/marathon/models/constraint.py#L45-L57 | def from_json(cls, obj):
"""Construct a MarathonConstraint from a parsed response.
:param dict attributes: object attributes from parsed response
:rtype: :class:`MarathonConstraint`
"""
if len(obj) == 2:
(field, operator) = obj
return cls(field, operator... | [
"def",
"from_json",
"(",
"cls",
",",
"obj",
")",
":",
"if",
"len",
"(",
"obj",
")",
"==",
"2",
":",
"(",
"field",
",",
"operator",
")",
"=",
"obj",
"return",
"cls",
"(",
"field",
",",
"operator",
")",
"if",
"len",
"(",
"obj",
")",
">",
"2",
"... | Construct a MarathonConstraint from a parsed response.
:param dict attributes: object attributes from parsed response
:rtype: :class:`MarathonConstraint` | [
"Construct",
"a",
"MarathonConstraint",
"from",
"a",
"parsed",
"response",
"."
] | python | train | 32.615385 |
davidfokkema/artist | artist/plot.py | https://github.com/davidfokkema/artist/blob/26ae7987522622710f2910980770c50012fda47d/artist/plot.py#L460-L481 | def scatter_table(self, x, y, c, s, mark='*'):
"""Add a data series to the plot.
:param x: array containing x-values.
:param y: array containing y-values.
:param c: array containing values for the color of the mark.
:param s: array containing values for the size of the mark.
... | [
"def",
"scatter_table",
"(",
"self",
",",
"x",
",",
"y",
",",
"c",
",",
"s",
",",
"mark",
"=",
"'*'",
")",
":",
"# clear the background of the marks",
"# self._clear_plot_mark_background(x, y, mark, markstyle)",
"# draw the plot series over the background",
"options",
"="... | Add a data series to the plot.
:param x: array containing x-values.
:param y: array containing y-values.
:param c: array containing values for the color of the mark.
:param s: array containing values for the size of the mark.
:param mark: the symbol used to mark the data point. ... | [
"Add",
"a",
"data",
"series",
"to",
"the",
"plot",
"."
] | python | train | 43.636364 |
ellmetha/django-machina | machina/core/loading.py | https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/core/loading.py#L62-L79 | def _import_module(module_path, classnames):
""" Tries to import the given Python module path. """
try:
imported_module = __import__(module_path, fromlist=classnames)
return imported_module
except ImportError:
# In case of an ImportError, the module being loaded generally does not ex... | [
"def",
"_import_module",
"(",
"module_path",
",",
"classnames",
")",
":",
"try",
":",
"imported_module",
"=",
"__import__",
"(",
"module_path",
",",
"fromlist",
"=",
"classnames",
")",
"return",
"imported_module",
"except",
"ImportError",
":",
"# In case of an Impor... | Tries to import the given Python module path. | [
"Tries",
"to",
"import",
"the",
"given",
"Python",
"module",
"path",
"."
] | python | train | 51.166667 |
msoulier/tftpy | tftpy/TftpStates.py | https://github.com/msoulier/tftpy/blob/af2f2fe89a3bf45748b78703820efb0986a8207a/tftpy/TftpStates.py#L82-L111 | def sendDAT(self):
"""This method sends the next DAT packet based on the data in the
context. It returns a boolean indicating whether the transfer is
finished."""
finished = False
blocknumber = self.context.next_block
# Test hook
if DELAY_BLOCK and DELAY_BLOCK == ... | [
"def",
"sendDAT",
"(",
"self",
")",
":",
"finished",
"=",
"False",
"blocknumber",
"=",
"self",
".",
"context",
".",
"next_block",
"# Test hook",
"if",
"DELAY_BLOCK",
"and",
"DELAY_BLOCK",
"==",
"blocknumber",
":",
"import",
"time",
"log",
".",
"debug",
"(",
... | This method sends the next DAT packet based on the data in the
context. It returns a boolean indicating whether the transfer is
finished. | [
"This",
"method",
"sends",
"the",
"next",
"DAT",
"packet",
"based",
"on",
"the",
"data",
"in",
"the",
"context",
".",
"It",
"returns",
"a",
"boolean",
"indicating",
"whether",
"the",
"transfer",
"is",
"finished",
"."
] | python | train | 40.733333 |
knipknap/SpiffWorkflow | SpiffWorkflow/bpmn/parser/BpmnParser.py | https://github.com/knipknap/SpiffWorkflow/blob/f0af7f59a332e0619e4f3c00a7d4a3d230760e00/SpiffWorkflow/bpmn/parser/BpmnParser.py#L119-L128 | def add_bpmn_files(self, filenames):
"""
Add all filenames in the given list to the parser's set.
"""
for filename in filenames:
f = open(filename, 'r')
try:
self.add_bpmn_xml(ET.parse(f), filename=filename)
finally:
f.c... | [
"def",
"add_bpmn_files",
"(",
"self",
",",
"filenames",
")",
":",
"for",
"filename",
"in",
"filenames",
":",
"f",
"=",
"open",
"(",
"filename",
",",
"'r'",
")",
"try",
":",
"self",
".",
"add_bpmn_xml",
"(",
"ET",
".",
"parse",
"(",
"f",
")",
",",
"... | Add all filenames in the given list to the parser's set. | [
"Add",
"all",
"filenames",
"in",
"the",
"given",
"list",
"to",
"the",
"parser",
"s",
"set",
"."
] | python | valid | 31.7 |
brocade/pynos | pynos/versions/ver_6/ver_6_0_1/yang/brocade_system.py | https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_6/ver_6_0_1/yang/brocade_system.py#L103-L114 | def get_system_uptime_output_cmd_error(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_system_uptime = ET.Element("get_system_uptime")
config = get_system_uptime
output = ET.SubElement(get_system_uptime, "output")
cmd_error = ET.SubEl... | [
"def",
"get_system_uptime_output_cmd_error",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"get_system_uptime",
"=",
"ET",
".",
"Element",
"(",
"\"get_system_uptime\"",
")",
"config",
"=",
"get_sys... | Auto Generated Code | [
"Auto",
"Generated",
"Code"
] | python | train | 39.583333 |
GoogleCloudPlatform/appengine-mapreduce | python/src/mapreduce/shuffler.py | https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/python/src/mapreduce/shuffler.py#L429-L444 | def validate(cls, mapper_spec):
"""Validates mapper specification.
Args:
mapper_spec: an instance of model.MapperSpec to validate.
Raises:
BadWriterParamsError: when Output writer class mismatch.
"""
if mapper_spec.output_writer_class() != cls:
raise errors.BadWriterParamsError("O... | [
"def",
"validate",
"(",
"cls",
",",
"mapper_spec",
")",
":",
"if",
"mapper_spec",
".",
"output_writer_class",
"(",
")",
"!=",
"cls",
":",
"raise",
"errors",
".",
"BadWriterParamsError",
"(",
"\"Output writer class mismatch\"",
")",
"params",
"=",
"output_writers",... | Validates mapper specification.
Args:
mapper_spec: an instance of model.MapperSpec to validate.
Raises:
BadWriterParamsError: when Output writer class mismatch. | [
"Validates",
"mapper",
"specification",
"."
] | python | train | 37.25 |
kxgames/kxg | kxg/multiplayer.py | https://github.com/kxgames/kxg/blob/a68c01dc4aa1abf6b3780ba2c65a7828282566aa/kxg/multiplayer.py#L274-L283 | def _relay_message(self, message):
"""
Relay messages from the forum on the server to the client represented
by this actor.
"""
info("relaying message: {message}")
if not message.was_sent_by(self._id_factory):
self.pipe.send(message)
self.pipe.de... | [
"def",
"_relay_message",
"(",
"self",
",",
"message",
")",
":",
"info",
"(",
"\"relaying message: {message}\"",
")",
"if",
"not",
"message",
".",
"was_sent_by",
"(",
"self",
".",
"_id_factory",
")",
":",
"self",
".",
"pipe",
".",
"send",
"(",
"message",
")... | Relay messages from the forum on the server to the client represented
by this actor. | [
"Relay",
"messages",
"from",
"the",
"forum",
"on",
"the",
"server",
"to",
"the",
"client",
"represented",
"by",
"this",
"actor",
"."
] | python | valid | 31.8 |
SUNCAT-Center/CatHub | cathub/reaction_networks.py | https://github.com/SUNCAT-Center/CatHub/blob/324625d1d8e740673f139658b2de4c9e1059739e/cathub/reaction_networks.py#L276-L293 | def get_ZPE(viblist):
"""Returns the zero point energy from a list of frequencies.
Parameters
----------
viblist : List of numbers or string of list of numbers.
Returns
-------
ZPE : Zero point energy in eV.
"""
if type(viblist) is str:
l = ast.literal_eval(viblist)
els... | [
"def",
"get_ZPE",
"(",
"viblist",
")",
":",
"if",
"type",
"(",
"viblist",
")",
"is",
"str",
":",
"l",
"=",
"ast",
".",
"literal_eval",
"(",
"viblist",
")",
"else",
":",
"l",
"=",
"viblist",
"l",
"=",
"[",
"float",
"(",
"w",
")",
"for",
"w",
"in... | Returns the zero point energy from a list of frequencies.
Parameters
----------
viblist : List of numbers or string of list of numbers.
Returns
-------
ZPE : Zero point energy in eV. | [
"Returns",
"the",
"zero",
"point",
"energy",
"from",
"a",
"list",
"of",
"frequencies",
"."
] | python | train | 22.111111 |
SFDO-Tooling/CumulusCI | cumulusci/core/config/BaseTaskFlowConfig.py | https://github.com/SFDO-Tooling/CumulusCI/blob/e19047921ca771a297e045f22f0bb201651bb6f7/cumulusci/core/config/BaseTaskFlowConfig.py#L32-L37 | def get_task(self, name):
""" Returns a TaskConfig """
config = getattr(self, "tasks__{}".format(name))
if not config:
raise TaskNotFoundError("Task not found: {}".format(name))
return TaskConfig(config) | [
"def",
"get_task",
"(",
"self",
",",
"name",
")",
":",
"config",
"=",
"getattr",
"(",
"self",
",",
"\"tasks__{}\"",
".",
"format",
"(",
"name",
")",
")",
"if",
"not",
"config",
":",
"raise",
"TaskNotFoundError",
"(",
"\"Task not found: {}\"",
".",
"format"... | Returns a TaskConfig | [
"Returns",
"a",
"TaskConfig"
] | python | train | 40.333333 |
JensRantil/rewind | rewind/server/eventstores.py | https://github.com/JensRantil/rewind/blob/7f645d20186c1db55cfe53a0310c9fd6292f91ea/rewind/server/eventstores.py#L785-L797 | def rotate(self):
"""Rotate the files to disk.
This is done by calling `store.close()` on each store, bumping the
batchno and reopening the stores using their factories.
"""
self._logger.info('Rotating data files. New batch number will be: %s',
self.ba... | [
"def",
"rotate",
"(",
"self",
")",
":",
"self",
".",
"_logger",
".",
"info",
"(",
"'Rotating data files. New batch number will be: %s'",
",",
"self",
".",
"batchno",
"+",
"1",
")",
"self",
".",
"estore",
".",
"close",
"(",
")",
"self",
".",
"estore",
"=",
... | Rotate the files to disk.
This is done by calling `store.close()` on each store, bumping the
batchno and reopening the stores using their factories. | [
"Rotate",
"the",
"files",
"to",
"disk",
"."
] | python | train | 34.307692 |
hootnot/postcode-api-wrapper | postcodepy/postcodepy.py | https://github.com/hootnot/postcode-api-wrapper/blob/42359cb9402f84a06f7d58f889f1156d653f5ea9/postcodepy/postcodepy.py#L14-L51 | def get_postcodedata(self, postcode, nr, addition="", **params):
"""get_postcodedata - fetch information for 'postcode'.
Parameters
----------
postcode : string
The full (dutch) postcode
nr : int
The housenumber
addition : string (optional)
... | [
"def",
"get_postcodedata",
"(",
"self",
",",
"postcode",
",",
"nr",
",",
"addition",
"=",
"\"\"",
",",
"*",
"*",
"params",
")",
":",
"endpoint",
"=",
"'rest/addresses/%s/%s'",
"%",
"(",
"postcode",
",",
"nr",
")",
"if",
"addition",
":",
"endpoint",
"+=",... | get_postcodedata - fetch information for 'postcode'.
Parameters
----------
postcode : string
The full (dutch) postcode
nr : int
The housenumber
addition : string (optional)
the extension to a housenumber
params : dict (optional)
... | [
"get_postcodedata",
"-",
"fetch",
"information",
"for",
"postcode",
"."
] | python | train | 32.842105 |
jessamynsmith/pipreq | pipreq/command.py | https://github.com/jessamynsmith/pipreq/blob/4081c1238722166445f58ae57e939207f8a6fb83/pipreq/command.py#L129-L144 | def _parse_requirements(self, input):
""" Parse a list of requirements specifications.
Lines that look like "foobar==1.0" are parsed; all other lines are
silently ignored.
Returns a tuple of tuples, where each inner tuple is:
(package, version) """
r... | [
"def",
"_parse_requirements",
"(",
"self",
",",
"input",
")",
":",
"results",
"=",
"[",
"]",
"for",
"line",
"in",
"input",
":",
"(",
"package",
",",
"version",
")",
"=",
"self",
".",
"_parse_line",
"(",
"line",
")",
"if",
"package",
":",
"results",
"... | Parse a list of requirements specifications.
Lines that look like "foobar==1.0" are parsed; all other lines are
silently ignored.
Returns a tuple of tuples, where each inner tuple is:
(package, version) | [
"Parse",
"a",
"list",
"of",
"requirements",
"specifications",
".",
"Lines",
"that",
"look",
"like",
"foobar",
"==",
"1",
".",
"0",
"are",
"parsed",
";",
"all",
"other",
"lines",
"are",
"silently",
"ignored",
"."
] | python | train | 31.625 |
prompt-toolkit/pyvim | pyvim/window_arrangement.py | https://github.com/prompt-toolkit/pyvim/blob/5928b53b9d700863c1a06d2181a034a955f94594/pyvim/window_arrangement.py#L303-L308 | def keep_only_current_window(self):
"""
Close all other windows, except the current one.
"""
self.tab_pages = [TabPage(self.active_tab.active_window)]
self.active_tab_index = 0 | [
"def",
"keep_only_current_window",
"(",
"self",
")",
":",
"self",
".",
"tab_pages",
"=",
"[",
"TabPage",
"(",
"self",
".",
"active_tab",
".",
"active_window",
")",
"]",
"self",
".",
"active_tab_index",
"=",
"0"
] | Close all other windows, except the current one. | [
"Close",
"all",
"other",
"windows",
"except",
"the",
"current",
"one",
"."
] | python | train | 35.166667 |
jaredLunde/vital-tools | vital/security/__init__.py | https://github.com/jaredLunde/vital-tools/blob/ea924c9bbb6ec22aa66f8095f018b1ee0099ac04/vital/security/__init__.py#L31-L52 | def aes_b64_encrypt(value, secret, block_size=AES.block_size):
""" AES encrypt @value with @secret using the |CFB| mode of AES
with a cryptographically secure initialization vector.
-> (#str) AES encrypted @value
..
from vital.security import aes_encrypt, aes_decrypt
... | [
"def",
"aes_b64_encrypt",
"(",
"value",
",",
"secret",
",",
"block_size",
"=",
"AES",
".",
"block_size",
")",
":",
"# iv = randstr(block_size * 2, rng=random)",
"iv",
"=",
"randstr",
"(",
"block_size",
"*",
"2",
")",
"cipher",
"=",
"AES",
".",
"new",
"(",
"s... | AES encrypt @value with @secret using the |CFB| mode of AES
with a cryptographically secure initialization vector.
-> (#str) AES encrypted @value
..
from vital.security import aes_encrypt, aes_decrypt
aes_encrypt("Hello, world",
"aLWEFlwgwlreWELF... | [
"AES",
"encrypt",
"@value",
"with",
"@secret",
"using",
"the",
"|CFB|",
"mode",
"of",
"AES",
"with",
"a",
"cryptographically",
"secure",
"initialization",
"vector",
"."
] | python | train | 41.045455 |
troeger/opensubmit | web/opensubmit/cmdline.py | https://github.com/troeger/opensubmit/blob/384a95b7c6fa41e3f949a129d25dafd9a1c54859/web/opensubmit/cmdline.py#L229-L244 | def check_web_config(config_fname):
'''
Try to load the Django settings.
If this does not work, than settings file does not exist.
Returns:
Loaded configuration, or None.
'''
print("Looking for config file at {0} ...".format(config_fname))
config = RawConfigParser()
... | [
"def",
"check_web_config",
"(",
"config_fname",
")",
":",
"print",
"(",
"\"Looking for config file at {0} ...\"",
".",
"format",
"(",
"config_fname",
")",
")",
"config",
"=",
"RawConfigParser",
"(",
")",
"try",
":",
"config",
".",
"readfp",
"(",
"open",
"(",
"... | Try to load the Django settings.
If this does not work, than settings file does not exist.
Returns:
Loaded configuration, or None. | [
"Try",
"to",
"load",
"the",
"Django",
"settings",
".",
"If",
"this",
"does",
"not",
"work",
"than",
"settings",
"file",
"does",
"not",
"exist",
"."
] | python | train | 36.0625 |
saltstack/salt | salt/beacons/__init__.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/beacons/__init__.py#L381-L393 | def disable_beacons(self):
'''
Enable beacons
'''
self.opts['beacons']['enabled'] = False
# Fire the complete event back along with updated list of beacons
evt = salt.utils.event.get_event('minion', opts=self.opts)
evt.fire_event({'complete': True, 'beacons': se... | [
"def",
"disable_beacons",
"(",
"self",
")",
":",
"self",
".",
"opts",
"[",
"'beacons'",
"]",
"[",
"'enabled'",
"]",
"=",
"False",
"# Fire the complete event back along with updated list of beacons",
"evt",
"=",
"salt",
".",
"utils",
".",
"event",
".",
"get_event",... | Enable beacons | [
"Enable",
"beacons"
] | python | train | 32.692308 |
ihgazni2/edict | edict/edict.py | https://github.com/ihgazni2/edict/blob/44a08ccc10b196aa3854619b4c51ddb246778a34/edict/edict.py#L921-L940 | def _diff_internal(d1,d2):
'''
d1 = {'a':'x','b':'y','c':'z'}
d2 = {'a':'x','b':'u','d':'v'}
_diff_internal(d1,d2)
_diff_internald2,d1)
'''
same =[]
kdiff =[]
vdiff = []
for key in d1:
value = d1[key]
if(key in d2):
if(value == d2[key])... | [
"def",
"_diff_internal",
"(",
"d1",
",",
"d2",
")",
":",
"same",
"=",
"[",
"]",
"kdiff",
"=",
"[",
"]",
"vdiff",
"=",
"[",
"]",
"for",
"key",
"in",
"d1",
":",
"value",
"=",
"d1",
"[",
"key",
"]",
"if",
"(",
"key",
"in",
"d2",
")",
":",
"if"... | d1 = {'a':'x','b':'y','c':'z'}
d2 = {'a':'x','b':'u','d':'v'}
_diff_internal(d1,d2)
_diff_internald2,d1) | [
"d1",
"=",
"{",
"a",
":",
"x",
"b",
":",
"y",
"c",
":",
"z",
"}",
"d2",
"=",
"{",
"a",
":",
"x",
"b",
":",
"u",
"d",
":",
"v",
"}",
"_diff_internal",
"(",
"d1",
"d2",
")",
"_diff_internald2",
"d1",
")"
] | python | train | 24.25 |
RJT1990/pyflux | pyflux/families/exponential.py | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/families/exponential.py#L251-L275 | def neg_loglikelihood(y, mean, scale, shape, skewness):
""" Negative loglikelihood function
Parameters
----------
y : np.ndarray
univariate time series
mean : np.ndarray
array of location parameters for the Exponential distribution
scale : float... | [
"def",
"neg_loglikelihood",
"(",
"y",
",",
"mean",
",",
"scale",
",",
"shape",
",",
"skewness",
")",
":",
"return",
"-",
"np",
".",
"sum",
"(",
"ss",
".",
"expon",
".",
"logpdf",
"(",
"x",
"=",
"y",
",",
"scale",
"=",
"1",
"/",
"mean",
")",
")"... | Negative loglikelihood function
Parameters
----------
y : np.ndarray
univariate time series
mean : np.ndarray
array of location parameters for the Exponential distribution
scale : float
scale parameter for the Exponential distribution
... | [
"Negative",
"loglikelihood",
"function"
] | python | train | 28.24 |
google/grumpy | third_party/stdlib/csv.py | https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/csv.py#L189-L215 | def sniff(self, sample, delimiters=None):
"""
Returns a dialect (or None) corresponding to the sample
"""
quotechar, doublequote, delimiter, skipinitialspace = \
self._guess_quote_and_delimiter(sample, delimiters)
if not delimiter:
delimiter, skipi... | [
"def",
"sniff",
"(",
"self",
",",
"sample",
",",
"delimiters",
"=",
"None",
")",
":",
"quotechar",
",",
"doublequote",
",",
"delimiter",
",",
"skipinitialspace",
"=",
"self",
".",
"_guess_quote_and_delimiter",
"(",
"sample",
",",
"delimiters",
")",
"if",
"no... | Returns a dialect (or None) corresponding to the sample | [
"Returns",
"a",
"dialect",
"(",
"or",
"None",
")",
"corresponding",
"to",
"the",
"sample"
] | python | valid | 33.962963 |
mromanello/hucitlib | knowledge_base/__init__.py | https://github.com/mromanello/hucitlib/blob/6587d1b04eb7e5b48ad7359be845e5d3b444d6fa/knowledge_base/__init__.py#L114-L127 | def author_names(self):
"""
Returns a dictionary like this:
{
"urn:cts:greekLit:tlg0012$$n1" : "Homer"
, "urn:cts:greekLit:tlg0012$$n2" : "Omero"
, ...
}
"""
return {"%s$$n%i" % (author.get_urn(), i): name[1]
for author... | [
"def",
"author_names",
"(",
"self",
")",
":",
"return",
"{",
"\"%s$$n%i\"",
"%",
"(",
"author",
".",
"get_urn",
"(",
")",
",",
"i",
")",
":",
"name",
"[",
"1",
"]",
"for",
"author",
"in",
"self",
".",
"get_authors",
"(",
")",
"for",
"i",
",",
"na... | Returns a dictionary like this:
{
"urn:cts:greekLit:tlg0012$$n1" : "Homer"
, "urn:cts:greekLit:tlg0012$$n2" : "Omero"
, ...
} | [
"Returns",
"a",
"dictionary",
"like",
"this",
":"
] | python | train | 31.357143 |
novopl/peltak | src/peltak/extra/pypi/logic.py | https://github.com/novopl/peltak/blob/b627acc019e3665875fe76cdca0a14773b69beaa/src/peltak/extra/pypi/logic.py#L31-L44 | def upload(target):
# type: (str) -> None
""" Upload the release to a pypi server.
TODO: Make sure the git directory is clean before allowing a release.
Args:
target (str):
pypi target as defined in ~/.pypirc
"""
log.info("Uploading to pypi server <33>{}".format(target))
... | [
"def",
"upload",
"(",
"target",
")",
":",
"# type: (str) -> None",
"log",
".",
"info",
"(",
"\"Uploading to pypi server <33>{}\"",
".",
"format",
"(",
"target",
")",
")",
"with",
"conf",
".",
"within_proj_dir",
"(",
")",
":",
"shell",
".",
"run",
"(",
"'pyth... | Upload the release to a pypi server.
TODO: Make sure the git directory is clean before allowing a release.
Args:
target (str):
pypi target as defined in ~/.pypirc | [
"Upload",
"the",
"release",
"to",
"a",
"pypi",
"server",
"."
] | python | train | 34.642857 |
Hypex/hyppy | hyppy/hapi.py | https://github.com/Hypex/hyppy/blob/a425619c2a102b0e598fd6cac8aa0f6b766f542d/hyppy/hapi.py#L204-L234 | def parse(response):
"""Parse a postdata-style response format from the API into usable data"""
"""Split a a=1b=2c=3 string into a dictionary of pairs"""
tokens = {r[0]: r[1] for r in [r.split('=') for r in response.split("&")]}
# The odd dummy parameter is of no use to us
if '... | [
"def",
"parse",
"(",
"response",
")",
":",
"\"\"\"Split a a=1b=2c=3 string into a dictionary of pairs\"\"\"",
"tokens",
"=",
"{",
"r",
"[",
"0",
"]",
":",
"r",
"[",
"1",
"]",
"for",
"r",
"in",
"[",
"r",
".",
"split",
"(",
"'='",
")",
"for",
"r",
"in",
... | Parse a postdata-style response format from the API into usable data | [
"Parse",
"a",
"postdata",
"-",
"style",
"response",
"format",
"from",
"the",
"API",
"into",
"usable",
"data"
] | python | train | 41.419355 |
QUANTAXIS/QUANTAXIS | QUANTAXIS/QAIndicator/base.py | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAIndicator/base.py#L160-L172 | def LAST(COND, N1, N2):
"""表达持续性
从前N1日到前N2日一直满足COND条件
Arguments:
COND {[type]} -- [description]
N1 {[type]} -- [description]
N2 {[type]} -- [description]
"""
N2 = 1 if N2 == 0 else N2
assert N2 > 0
assert N1 > N2
return COND.iloc[-N1:-N2].all() | [
"def",
"LAST",
"(",
"COND",
",",
"N1",
",",
"N2",
")",
":",
"N2",
"=",
"1",
"if",
"N2",
"==",
"0",
"else",
"N2",
"assert",
"N2",
">",
"0",
"assert",
"N1",
">",
"N2",
"return",
"COND",
".",
"iloc",
"[",
"-",
"N1",
":",
"-",
"N2",
"]",
".",
... | 表达持续性
从前N1日到前N2日一直满足COND条件
Arguments:
COND {[type]} -- [description]
N1 {[type]} -- [description]
N2 {[type]} -- [description] | [
"表达持续性",
"从前N1日到前N2日一直满足COND条件"
] | python | train | 22.230769 |
openeemeter/eemeter | eemeter/transform.py | https://github.com/openeemeter/eemeter/blob/e03b1cc5f4906e8f4f7fd16183bc037107d1dfa0/eemeter/transform.py#L62-L138 | def as_freq(data_series, freq, atomic_freq="1 Min", series_type="cumulative"):
"""Resample data to a different frequency.
This method can be used to upsample or downsample meter data. The
assumption it makes to do so is that meter data is constant and averaged
over the given periods. For instance, to c... | [
"def",
"as_freq",
"(",
"data_series",
",",
"freq",
",",
"atomic_freq",
"=",
"\"1 Min\"",
",",
"series_type",
"=",
"\"cumulative\"",
")",
":",
"# TODO(philngo): make sure this complies with CalTRACK 2.2.2.1",
"if",
"not",
"isinstance",
"(",
"data_series",
",",
"pd",
".... | Resample data to a different frequency.
This method can be used to upsample or downsample meter data. The
assumption it makes to do so is that meter data is constant and averaged
over the given periods. For instance, to convert billing-period data to
daily data, this method first upsamples to the atomi... | [
"Resample",
"data",
"to",
"a",
"different",
"frequency",
"."
] | python | train | 44.480519 |
MacHu-GWU/constant2-project | constant2/_constant2.py | https://github.com/MacHu-GWU/constant2-project/blob/ccf7e14b0e23f9f4bfd13a3e2ce4a1142e570d4f/constant2/_constant2.py#L373-L432 | def BackAssign(cls,
other_entity_klass,
this_entity_backpopulate_field,
other_entity_backpopulate_field,
is_many_to_one=False):
"""
Assign defined one side mapping relationship to other side.
For example, each employee ... | [
"def",
"BackAssign",
"(",
"cls",
",",
"other_entity_klass",
",",
"this_entity_backpopulate_field",
",",
"other_entity_backpopulate_field",
",",
"is_many_to_one",
"=",
"False",
")",
":",
"data",
"=",
"dict",
"(",
")",
"for",
"_",
",",
"other_klass",
"in",
"other_en... | Assign defined one side mapping relationship to other side.
For example, each employee belongs to one department, then one department
includes many employees. If you defined each employee's department,
this method will assign employees to ``Department.employees`` field.
This is an one t... | [
"Assign",
"defined",
"one",
"side",
"mapping",
"relationship",
"to",
"other",
"side",
"."
] | python | train | 39.8 |
quantumlib/Cirq | cirq/contrib/acquaintance/executor.py | https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/contrib/acquaintance/executor.py#L61-L65 | def get_operations(self,
indices: Sequence[LogicalIndex],
qubits: Sequence[ops.Qid]
) -> ops.OP_TREE:
"""Gets the logical operations to apply to qubits.""" | [
"def",
"get_operations",
"(",
"self",
",",
"indices",
":",
"Sequence",
"[",
"LogicalIndex",
"]",
",",
"qubits",
":",
"Sequence",
"[",
"ops",
".",
"Qid",
"]",
")",
"->",
"ops",
".",
"OP_TREE",
":"
] | Gets the logical operations to apply to qubits. | [
"Gets",
"the",
"logical",
"operations",
"to",
"apply",
"to",
"qubits",
"."
] | python | train | 45.6 |
Erotemic/utool | utool/util_dbg.py | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_dbg.py#L112-L203 | def execstr_dict(dict_, local_name=None, exclude_list=None, explicit=False):
"""
returns execable python code that declares variables using keys and values
execstr_dict
Args:
dict_ (dict):
local_name (str): optional: local name of dictionary. Specifying this
is much safer
... | [
"def",
"execstr_dict",
"(",
"dict_",
",",
"local_name",
"=",
"None",
",",
"exclude_list",
"=",
"None",
",",
"explicit",
"=",
"False",
")",
":",
"import",
"utool",
"as",
"ut",
"if",
"explicit",
":",
"expr_list",
"=",
"[",
"]",
"for",
"(",
"key",
",",
... | returns execable python code that declares variables using keys and values
execstr_dict
Args:
dict_ (dict):
local_name (str): optional: local name of dictionary. Specifying this
is much safer
exclude_list (list):
Returns:
str: execstr --- the executable string ... | [
"returns",
"execable",
"python",
"code",
"that",
"declares",
"variables",
"using",
"keys",
"and",
"values"
] | python | train | 35.858696 |
python-astrodynamics/spacetrack | spacetrack/base.py | https://github.com/python-astrodynamics/spacetrack/blob/18f63b7de989a31b983d140a11418e01bd6fd398/spacetrack/base.py#L415-L441 | def _ratelimited_get(self, *args, **kwargs):
"""Perform get request, handling rate limiting."""
with self._ratelimiter:
resp = self.session.get(*args, **kwargs)
# It's possible that Space-Track will return HTTP status 500 with a
# query rate limit violation. This can happen ... | [
"def",
"_ratelimited_get",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"with",
"self",
".",
"_ratelimiter",
":",
"resp",
"=",
"self",
".",
"session",
".",
"get",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"# It's possible t... | Perform get request, handling rate limiting. | [
"Perform",
"get",
"request",
"handling",
"rate",
"limiting",
"."
] | python | train | 43.518519 |
log2timeline/plaso | plaso/multi_processing/task_manager.py | https://github.com/log2timeline/plaso/blob/9c564698d2da3ffbe23607a3c54c0582ea18a6cc/plaso/multi_processing/task_manager.py#L197-L212 | def _AbandonQueuedTasks(self):
"""Marks queued tasks abandoned.
This method does not lock the manager and should be called by a method
holding the manager lock.
"""
# Abandon all tasks after they're identified so as not to modify the
# dict while iterating over it.
tasks_to_abandon = []
... | [
"def",
"_AbandonQueuedTasks",
"(",
"self",
")",
":",
"# Abandon all tasks after they're identified so as not to modify the",
"# dict while iterating over it.",
"tasks_to_abandon",
"=",
"[",
"]",
"for",
"task_identifier",
",",
"task",
"in",
"iter",
"(",
"self",
".",
"_tasks_... | Marks queued tasks abandoned.
This method does not lock the manager and should be called by a method
holding the manager lock. | [
"Marks",
"queued",
"tasks",
"abandoned",
"."
] | python | train | 40.5625 |
ekalinin/marktime.py | marktime.py | https://github.com/ekalinin/marktime.py/blob/111897cfa30f570155bb009ea653ce402457b17d/marktime.py#L103-L120 | def stop(label, at=None, remove_from_labels=False, stop_once=True):
"""Stops the countdown"""
t = at if at is not None else time.time()
if label not in labels:
return None
timer = Marker().loads(labels[label])
if timer.is_running() or (timer.is_stopped() and not stop_once):
timer.... | [
"def",
"stop",
"(",
"label",
",",
"at",
"=",
"None",
",",
"remove_from_labels",
"=",
"False",
",",
"stop_once",
"=",
"True",
")",
":",
"t",
"=",
"at",
"if",
"at",
"is",
"not",
"None",
"else",
"time",
".",
"time",
"(",
")",
"if",
"label",
"not",
"... | Stops the countdown | [
"Stops",
"the",
"countdown"
] | python | train | 24.5 |
moonlitesolutions/SolrClient | SolrClient/zk.py | https://github.com/moonlitesolutions/SolrClient/blob/19c5280c9f8e97ee104d22ae883c4ccfd7c4f43b/SolrClient/zk.py#L114-L124 | def download_collection_configs(self, collection, fs_path):
'''
Downloads ZK Directory to the FileSystem.
:param collection str: Name of the collection (zk config name)
:param fs_path str: Destination filesystem path.
'''
if not self.kz.exists('/configs/{}'.for... | [
"def",
"download_collection_configs",
"(",
"self",
",",
"collection",
",",
"fs_path",
")",
":",
"if",
"not",
"self",
".",
"kz",
".",
"exists",
"(",
"'/configs/{}'",
".",
"format",
"(",
"collection",
")",
")",
":",
"raise",
"ZookeeperError",
"(",
"\"Collectio... | Downloads ZK Directory to the FileSystem.
:param collection str: Name of the collection (zk config name)
:param fs_path str: Destination filesystem path. | [
"Downloads",
"ZK",
"Directory",
"to",
"the",
"FileSystem",
"."
] | python | train | 51.272727 |
tetframework/Tonnikala | tonnikala/languages/javascript/jslex.py | https://github.com/tetframework/Tonnikala/blob/99d168657da1b2372ff898254f80808ea8d1b83f/tonnikala/languages/javascript/jslex.py#L52-L75 | def lex(self, text, start=0):
"""Lexically analyze `text`.
Yields pairs (`name`, `tokentext`).
"""
max = len(text)
eaten = start
s = self.state
r = self.regexes
toks = self.toks
while eaten < max:
for match in r[s].finditer(text, eate... | [
"def",
"lex",
"(",
"self",
",",
"text",
",",
"start",
"=",
"0",
")",
":",
"max",
"=",
"len",
"(",
"text",
")",
"eaten",
"=",
"start",
"s",
"=",
"self",
".",
"state",
"r",
"=",
"self",
".",
"regexes",
"toks",
"=",
"self",
".",
"toks",
"while",
... | Lexically analyze `text`.
Yields pairs (`name`, `tokentext`). | [
"Lexically",
"analyze",
"text",
"."
] | python | train | 25.375 |
dhermes/bezier | src/bezier/_geometric_intersection.py | https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/_geometric_intersection.py#L906-L970 | def tangent_bbox_intersection(first, second, intersections):
r"""Check if two curves with tangent bounding boxes intersect.
.. note::
This is a helper for :func:`intersect_one_round`. These
functions are used (directly or indirectly) by
:func:`_all_intersections` exclusively, and that fun... | [
"def",
"tangent_bbox_intersection",
"(",
"first",
",",
"second",
",",
"intersections",
")",
":",
"node_first1",
"=",
"first",
".",
"nodes",
"[",
":",
",",
"0",
"]",
"node_first2",
"=",
"first",
".",
"nodes",
"[",
":",
",",
"-",
"1",
"]",
"node_second1",
... | r"""Check if two curves with tangent bounding boxes intersect.
.. note::
This is a helper for :func:`intersect_one_round`. These
functions are used (directly or indirectly) by
:func:`_all_intersections` exclusively, and that function has a
Fortran equivalent.
If the bounding boxes... | [
"r",
"Check",
"if",
"two",
"curves",
"with",
"tangent",
"bounding",
"boxes",
"intersect",
"."
] | python | train | 34.046154 |
J535D165/recordlinkage | recordlinkage/api.py | https://github.com/J535D165/recordlinkage/blob/87a5f4af904e0834047cd07ff1c70146b1e6d693/recordlinkage/api.py#L211-L225 | def date(self, *args, **kwargs):
"""Compare attributes of pairs with date algorithm.
Shortcut of :class:`recordlinkage.compare.Date`::
from recordlinkage.compare import Date
indexer = recordlinkage.Compare()
indexer.add(Date())
"""
compare = Date(*... | [
"def",
"date",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"compare",
"=",
"Date",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"self",
".",
"add",
"(",
"compare",
")",
"return",
"self"
] | Compare attributes of pairs with date algorithm.
Shortcut of :class:`recordlinkage.compare.Date`::
from recordlinkage.compare import Date
indexer = recordlinkage.Compare()
indexer.add(Date()) | [
"Compare",
"attributes",
"of",
"pairs",
"with",
"date",
"algorithm",
"."
] | python | train | 24.533333 |
jimzhan/pyx | rex/debug/function.py | https://github.com/jimzhan/pyx/blob/819e8251323a7923e196c0c438aa8524f5aaee6e/rex/debug/function.py#L20-L33 | def attr(**context):
"""
Decorator that add attributes into func.
Added attributes can be access outside via function's `func_dict` property.
"""
#TODO(Jim Zhan) FIXME
def decorator(func):
def wrapped_func(*args, **kwargs):
for key, value in context.items():
... | [
"def",
"attr",
"(",
"*",
"*",
"context",
")",
":",
"#TODO(Jim Zhan) FIXME",
"def",
"decorator",
"(",
"func",
")",
":",
"def",
"wrapped_func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"key",
",",
"value",
"in",
"context",
".",
"item... | Decorator that add attributes into func.
Added attributes can be access outside via function's `func_dict` property. | [
"Decorator",
"that",
"add",
"attributes",
"into",
"func",
"."
] | python | train | 30.214286 |
fabioz/PyDev.Debugger | pydevd_attach_to_process/winappdbg/win32/kernel32.py | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/win32/kernel32.py#L4659-L4670 | def Wow64EnableWow64FsRedirection(Wow64FsEnableRedirection):
"""
This function may not work reliably when there are nested calls. Therefore,
this function has been replaced by the L{Wow64DisableWow64FsRedirection}
and L{Wow64RevertWow64FsRedirection} functions.
@see: U{http://msdn.microsoft.com/en-... | [
"def",
"Wow64EnableWow64FsRedirection",
"(",
"Wow64FsEnableRedirection",
")",
":",
"_Wow64EnableWow64FsRedirection",
"=",
"windll",
".",
"kernel32",
".",
"Wow64EnableWow64FsRedirection",
"_Wow64EnableWow64FsRedirection",
".",
"argtypes",
"=",
"[",
"BOOLEAN",
"]",
"_Wow64Enabl... | This function may not work reliably when there are nested calls. Therefore,
this function has been replaced by the L{Wow64DisableWow64FsRedirection}
and L{Wow64RevertWow64FsRedirection} functions.
@see: U{http://msdn.microsoft.com/en-us/library/windows/desktop/aa365744(v=vs.85).aspx} | [
"This",
"function",
"may",
"not",
"work",
"reliably",
"when",
"there",
"are",
"nested",
"calls",
".",
"Therefore",
"this",
"function",
"has",
"been",
"replaced",
"by",
"the",
"L",
"{",
"Wow64DisableWow64FsRedirection",
"}",
"and",
"L",
"{",
"Wow64RevertWow64FsRe... | python | train | 51.5 |
noxdafox/pebble | pebble/pool/process.py | https://github.com/noxdafox/pebble/blob/d8f3d989655715754f0a65d7419cfa584491f614/pebble/pool/process.py#L410-L419 | def task_transaction(channel):
"""Ensures a task is fetched and acknowledged atomically."""
with channel.lock:
if channel.poll(0):
task = channel.recv()
channel.send(Acknowledgement(os.getpid(), task.id))
else:
raise RuntimeError("Race condition between worker... | [
"def",
"task_transaction",
"(",
"channel",
")",
":",
"with",
"channel",
".",
"lock",
":",
"if",
"channel",
".",
"poll",
"(",
"0",
")",
":",
"task",
"=",
"channel",
".",
"recv",
"(",
")",
"channel",
".",
"send",
"(",
"Acknowledgement",
"(",
"os",
".",... | Ensures a task is fetched and acknowledged atomically. | [
"Ensures",
"a",
"task",
"is",
"fetched",
"and",
"acknowledged",
"atomically",
"."
] | python | train | 33.1 |
spyder-ide/conda-manager | conda_manager/api/conda_api.py | https://github.com/spyder-ide/conda-manager/blob/89a2126cbecefc92185cf979347ccac1c5ee5d9d/conda_manager/api/conda_api.py#L655-L661 | def remove_environment(self, name=None, path=None, **kwargs):
"""
Remove an environment entirely.
See ``remove``.
"""
return self.remove(name=name, path=path, all=True, **kwargs) | [
"def",
"remove_environment",
"(",
"self",
",",
"name",
"=",
"None",
",",
"path",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"remove",
"(",
"name",
"=",
"name",
",",
"path",
"=",
"path",
",",
"all",
"=",
"True",
",",
"*... | Remove an environment entirely.
See ``remove``. | [
"Remove",
"an",
"environment",
"entirely",
"."
] | python | train | 30.428571 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.