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 |
|---|---|---|---|---|---|---|---|---|---|
kencochrane/django-defender | defender/utils.py | https://github.com/kencochrane/django-defender/blob/e3e547dbb83235e0d564a6d64652c7df00412ff2/defender/utils.py#L283-L301 | def lockout_response(request):
""" if we are locked out, here is the response """
if config.LOCKOUT_TEMPLATE:
context = {
'cooloff_time_seconds': config.COOLOFF_TIME,
'cooloff_time_minutes': config.COOLOFF_TIME / 60,
'failure_limit': config.FAILURE_LIMIT,
}
... | [
"def",
"lockout_response",
"(",
"request",
")",
":",
"if",
"config",
".",
"LOCKOUT_TEMPLATE",
":",
"context",
"=",
"{",
"'cooloff_time_seconds'",
":",
"config",
".",
"COOLOFF_TIME",
",",
"'cooloff_time_minutes'",
":",
"config",
".",
"COOLOFF_TIME",
"/",
"60",
",... | if we are locked out, here is the response | [
"if",
"we",
"are",
"locked",
"out",
"here",
"is",
"the",
"response"
] | python | train | 40 |
lrq3000/pyFileFixity | pyFileFixity/lib/sortedcontainers/sorteddict.py | https://github.com/lrq3000/pyFileFixity/blob/fd5ef23bb13835faf1e3baa773619b86a1cc9bdf/pyFileFixity/lib/sortedcontainers/sorteddict.py#L285-L298 | def pop(self, key, default=_NotGiven):
"""
If *key* is in the dictionary, remove it and return its value,
else return *default*. If *default* is not given and *key* is not in
the dictionary, a KeyError is raised.
"""
if key in self:
self._list_remove(key)
... | [
"def",
"pop",
"(",
"self",
",",
"key",
",",
"default",
"=",
"_NotGiven",
")",
":",
"if",
"key",
"in",
"self",
":",
"self",
".",
"_list_remove",
"(",
"key",
")",
"return",
"self",
".",
"_pop",
"(",
"key",
")",
"else",
":",
"if",
"default",
"is",
"... | If *key* is in the dictionary, remove it and return its value,
else return *default*. If *default* is not given and *key* is not in
the dictionary, a KeyError is raised. | [
"If",
"*",
"key",
"*",
"is",
"in",
"the",
"dictionary",
"remove",
"it",
"and",
"return",
"its",
"value",
"else",
"return",
"*",
"default",
"*",
".",
"If",
"*",
"default",
"*",
"is",
"not",
"given",
"and",
"*",
"key",
"*",
"is",
"not",
"in",
"the",
... | python | train | 33.714286 |
lukaszb/frogress | frogress/bars.py | https://github.com/lukaszb/frogress/blob/ab3a02a2e797884fe689642eb49ce984fe8f059b/frogress/bars.py#L82-L96 | def get_timedelta(self, now=None):
"""
Returns number of seconds that passed since ``self.started``, as float.
None is returned if ``self.started`` was not set yet.
"""
def datetime_to_time(timestamp):
atime = time.mktime(timestamp.timetuple())
atime += ti... | [
"def",
"get_timedelta",
"(",
"self",
",",
"now",
"=",
"None",
")",
":",
"def",
"datetime_to_time",
"(",
"timestamp",
")",
":",
"atime",
"=",
"time",
".",
"mktime",
"(",
"timestamp",
".",
"timetuple",
"(",
")",
")",
"atime",
"+=",
"timestamp",
".",
"mic... | Returns number of seconds that passed since ``self.started``, as float.
None is returned if ``self.started`` was not set yet. | [
"Returns",
"number",
"of",
"seconds",
"that",
"passed",
"since",
"self",
".",
"started",
"as",
"float",
".",
"None",
"is",
"returned",
"if",
"self",
".",
"started",
"was",
"not",
"set",
"yet",
"."
] | python | train | 40.8 |
juju/charm-helpers | charmhelpers/contrib/peerstorage/__init__.py | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/peerstorage/__init__.py#L143-L157 | def relation_get(attribute=None, unit=None, rid=None):
"""Attempt to use leader-get if supported in the current version of Juju,
otherwise falls back on relation-get.
Note that we only attempt to use leader-get if the provided rid is a peer
relation id or no relation id is provided (in which case we as... | [
"def",
"relation_get",
"(",
"attribute",
"=",
"None",
",",
"unit",
"=",
"None",
",",
"rid",
"=",
"None",
")",
":",
"try",
":",
"if",
"rid",
"in",
"relation_ids",
"(",
"'cluster'",
")",
":",
"return",
"leader_get",
"(",
"attribute",
",",
"rid",
")",
"... | Attempt to use leader-get if supported in the current version of Juju,
otherwise falls back on relation-get.
Note that we only attempt to use leader-get if the provided rid is a peer
relation id or no relation id is provided (in which case we assume we are
within the peer relation context). | [
"Attempt",
"to",
"use",
"leader",
"-",
"get",
"if",
"supported",
"in",
"the",
"current",
"version",
"of",
"Juju",
"otherwise",
"falls",
"back",
"on",
"relation",
"-",
"get",
"."
] | python | train | 41.066667 |
crocs-muni/roca | roca/detect_tls.py | https://github.com/crocs-muni/roca/blob/74ad6ce63c428d83dcffce9c5e26ef7b9e30faa5/roca/detect_tls.py#L45-L66 | def process_tls(self, data, name):
"""
Remote TLS processing - one address:port per line
:param data:
:param name:
:return:
"""
ret = []
try:
lines = [x.strip() for x in data.split('\n')]
for idx, line in enumerate(lines):
... | [
"def",
"process_tls",
"(",
"self",
",",
"data",
",",
"name",
")",
":",
"ret",
"=",
"[",
"]",
"try",
":",
"lines",
"=",
"[",
"x",
".",
"strip",
"(",
")",
"for",
"x",
"in",
"data",
".",
"split",
"(",
"'\\n'",
")",
"]",
"for",
"idx",
",",
"line"... | Remote TLS processing - one address:port per line
:param data:
:param name:
:return: | [
"Remote",
"TLS",
"processing",
"-",
"one",
"address",
":",
"port",
"per",
"line",
":",
"param",
"data",
":",
":",
"param",
"name",
":",
":",
"return",
":"
] | python | train | 29.318182 |
miguelgrinberg/slam | slam/cli.py | https://github.com/miguelgrinberg/slam/blob/cf68a4bbc16d909718f8a9e71072b822e0a3d94b/slam/cli.py#L335-L426 | def deploy(stage, lambda_package, no_lambda, rebuild_deps, config_file):
"""Deploy the project to the development stage."""
config = _load_config(config_file)
if stage is None:
stage = config['devstage']
s3 = boto3.client('s3')
cfn = boto3.client('cloudformation')
region = _get_aws_regi... | [
"def",
"deploy",
"(",
"stage",
",",
"lambda_package",
",",
"no_lambda",
",",
"rebuild_deps",
",",
"config_file",
")",
":",
"config",
"=",
"_load_config",
"(",
"config_file",
")",
"if",
"stage",
"is",
"None",
":",
"stage",
"=",
"config",
"[",
"'devstage'",
... | Deploy the project to the development stage. | [
"Deploy",
"the",
"project",
"to",
"the",
"development",
"stage",
"."
] | python | train | 38.369565 |
kristianfoerster/melodist | melodist/util/util.py | https://github.com/kristianfoerster/melodist/blob/ddc155c77b65f791be0021dbbaf68c6bac42ecbd/melodist/util/util.py#L268-L320 | def drop_incomplete_days(dataframe, shift=0):
"""truncates a given dataframe to full days only
This funtion truncates a given pandas dataframe (time series) to full days
only, thus dropping leading and tailing hours of incomplete days. Please
note that this methodology only applies to hourly time serie... | [
"def",
"drop_incomplete_days",
"(",
"dataframe",
",",
"shift",
"=",
"0",
")",
":",
"dropped",
"=",
"0",
"if",
"shift",
">",
"23",
"or",
"shift",
"<",
"0",
":",
"print",
"(",
"\"Invalid shift parameter setting! Using defaults.\"",
")",
"shift",
"=",
"0",
"fir... | truncates a given dataframe to full days only
This funtion truncates a given pandas dataframe (time series) to full days
only, thus dropping leading and tailing hours of incomplete days. Please
note that this methodology only applies to hourly time series.
Args:
dataframe: A pandas dataframe o... | [
"truncates",
"a",
"given",
"dataframe",
"to",
"full",
"days",
"only"
] | python | train | 33.849057 |
saltstack/salt | salt/cloud/clouds/qingcloud.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/qingcloud.py#L327-L368 | def show_image(kwargs, call=None):
'''
Show the details from QingCloud concerning an image.
CLI Examples:
.. code-block:: bash
salt-cloud -f show_image my-qingcloud image=trustysrvx64c
salt-cloud -f show_image my-qingcloud image=trustysrvx64c,coreos4
salt-cloud -f show_image m... | [
"def",
"show_image",
"(",
"kwargs",
",",
"call",
"=",
"None",
")",
":",
"if",
"call",
"!=",
"'function'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The show_images function must be called with '",
"'-f or --function'",
")",
"if",
"not",
"isinstance",
"(",
"kwargs"... | Show the details from QingCloud concerning an image.
CLI Examples:
.. code-block:: bash
salt-cloud -f show_image my-qingcloud image=trustysrvx64c
salt-cloud -f show_image my-qingcloud image=trustysrvx64c,coreos4
salt-cloud -f show_image my-qingcloud image=trustysrvx64c zone=ap1 | [
"Show",
"the",
"details",
"from",
"QingCloud",
"concerning",
"an",
"image",
"."
] | python | train | 26.190476 |
saltstack/salt | salt/utils/nacl.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/nacl.py#L241-L272 | def dec(data, **kwargs):
'''
Alias to `{box_type}_decrypt`
box_type: secretbox, sealedbox(default)
'''
if 'keyfile' in kwargs:
salt.utils.versions.warn_until(
'Neon',
'The \'keyfile\' argument has been deprecated and will be removed in Salt '
'{version}. ... | [
"def",
"dec",
"(",
"data",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'keyfile'",
"in",
"kwargs",
":",
"salt",
".",
"utils",
".",
"versions",
".",
"warn_until",
"(",
"'Neon'",
",",
"'The \\'keyfile\\' argument has been deprecated and will be removed in Salt '",
"'{... | Alias to `{box_type}_decrypt`
box_type: secretbox, sealedbox(default) | [
"Alias",
"to",
"{",
"box_type",
"}",
"_decrypt"
] | python | train | 33.34375 |
ambitioninc/django-query-builder | querybuilder/query.py | https://github.com/ambitioninc/django-query-builder/blob/113a7d845d3ddc6a45621b9880308e756f87c5bf/querybuilder/query.py#L1443-L1458 | def build_groups(self):
"""
Generates the sql for the GROUP BY portion of the query
:return: the GROUP BY portion of the query
:rtype: str
"""
# check if there are any groupings
if len(self.groups):
groups = []
# get the group sql for eac... | [
"def",
"build_groups",
"(",
"self",
")",
":",
"# check if there are any groupings",
"if",
"len",
"(",
"self",
".",
"groups",
")",
":",
"groups",
"=",
"[",
"]",
"# get the group sql for each grouping",
"for",
"group",
"in",
"self",
".",
"groups",
":",
"groups",
... | Generates the sql for the GROUP BY portion of the query
:return: the GROUP BY portion of the query
:rtype: str | [
"Generates",
"the",
"sql",
"for",
"the",
"GROUP",
"BY",
"portion",
"of",
"the",
"query"
] | python | train | 30 |
joshspeagle/dynesty | dynesty/nestedsamplers.py | https://github.com/joshspeagle/dynesty/blob/9e482aafeb5cf84bedb896fa6f07a761d917983e/dynesty/nestedsamplers.py#L175-L182 | def propose_unif(self):
"""Propose a new live point by sampling *uniformly*
within the unit cube."""
u = self.unitcube.sample(rstate=self.rstate)
ax = np.identity(self.npdim)
return u, ax | [
"def",
"propose_unif",
"(",
"self",
")",
":",
"u",
"=",
"self",
".",
"unitcube",
".",
"sample",
"(",
"rstate",
"=",
"self",
".",
"rstate",
")",
"ax",
"=",
"np",
".",
"identity",
"(",
"self",
".",
"npdim",
")",
"return",
"u",
",",
"ax"
] | Propose a new live point by sampling *uniformly*
within the unit cube. | [
"Propose",
"a",
"new",
"live",
"point",
"by",
"sampling",
"*",
"uniformly",
"*",
"within",
"the",
"unit",
"cube",
"."
] | python | train | 27.75 |
Erotemic/utool | utool/util_cplat.py | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_cplat.py#L1303-L1370 | def send_keyboard_input(text=None, key_list=None):
"""
Args:
text (None):
key_list (list):
References:
http://stackoverflow.com/questions/14788036/python-win32api-sendmesage
http://www.pinvoke.net/default.aspx/user32.sendinput
CommandLine:
python -m utool.util_c... | [
"def",
"send_keyboard_input",
"(",
"text",
"=",
"None",
",",
"key_list",
"=",
"None",
")",
":",
"#key_mapping = {",
"# 'enter':",
"#}",
"if",
"WIN32",
":",
"#raise NotImplementedError()",
"#import win32api",
"#import win32gui",
"#import win32con",
"#hwnd = win32gui.Get... | Args:
text (None):
key_list (list):
References:
http://stackoverflow.com/questions/14788036/python-win32api-sendmesage
http://www.pinvoke.net/default.aspx/user32.sendinput
CommandLine:
python -m utool.util_cplat --test-send_keyboard_input
Example:
>>> # DIS... | [
"Args",
":",
"text",
"(",
"None",
")",
":",
"key_list",
"(",
"list",
")",
":"
] | python | train | 31.117647 |
alexwlchan/specktre | src/specktre/utils.py | https://github.com/alexwlchan/specktre/blob/dcdd0d5486e5c3f612f64221b2e0dbc6fb7adafc/src/specktre/utils.py#L9-L21 | def _candidate_filenames():
"""Generates filenames of the form 'specktre_123AB.png'.
The random noise is five characters long, which allows for
62^5 = 916 million possible filenames.
"""
while True:
random_stub = ''.join([
random.choice(string.ascii_letters + string.digits)
... | [
"def",
"_candidate_filenames",
"(",
")",
":",
"while",
"True",
":",
"random_stub",
"=",
"''",
".",
"join",
"(",
"[",
"random",
".",
"choice",
"(",
"string",
".",
"ascii_letters",
"+",
"string",
".",
"digits",
")",
"for",
"_",
"in",
"range",
"(",
"5",
... | Generates filenames of the form 'specktre_123AB.png'.
The random noise is five characters long, which allows for
62^5 = 916 million possible filenames. | [
"Generates",
"filenames",
"of",
"the",
"form",
"specktre_123AB",
".",
"png",
"."
] | python | train | 30.076923 |
dmsimard/python-cachetclient | cachetclient/cachet.py | https://github.com/dmsimard/python-cachetclient/blob/31bbc6d17ba5de088846e1ffae259b6755e672a0/cachetclient/cachet.py#L23-L34 | def api_token_required(f, *args, **kwargs):
"""
Decorator helper function to ensure some methods aren't needlessly called
without an api_token configured.
"""
try:
if args[0].api_token is None:
raise AttributeError('Parameter api_token is required.')
except AttributeError:
... | [
"def",
"api_token_required",
"(",
"f",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"if",
"args",
"[",
"0",
"]",
".",
"api_token",
"is",
"None",
":",
"raise",
"AttributeError",
"(",
"'Parameter api_token is required.'",
")",
"except",
... | Decorator helper function to ensure some methods aren't needlessly called
without an api_token configured. | [
"Decorator",
"helper",
"function",
"to",
"ensure",
"some",
"methods",
"aren",
"t",
"needlessly",
"called",
"without",
"an",
"api_token",
"configured",
"."
] | python | train | 33.5 |
gdoermann/voicebase | voicebase/api/media.py | https://github.com/gdoermann/voicebase/blob/53cb4735327898a7a284dea3a60ace0b3956a8ec/voicebase/api/media.py#L270-L300 | def upload(self, filename, configuration=None, metadata=None, transcript=None):
"""
Upload new new media to the service as an attachment or from a url.
HTTP POST on /media
:param filename: Media file attached to the request.
:param configuration: VoicebaseMediaConfiguration
... | [
"def",
"upload",
"(",
"self",
",",
"filename",
",",
"configuration",
"=",
"None",
",",
"metadata",
"=",
"None",
",",
"transcript",
"=",
"None",
")",
":",
"data",
"=",
"{",
"}",
"if",
"metadata",
":",
"data",
"[",
"'metadata'",
"]",
"=",
"str",
"(",
... | Upload new new media to the service as an attachment or from a url.
HTTP POST on /media
:param filename: Media file attached to the request.
:param configuration: VoicebaseMediaConfiguration
:param metadata: VoicebaseMediaMeta
:param transcript: attached transcript
:retur... | [
"Upload",
"new",
"new",
"media",
"to",
"the",
"service",
"as",
"an",
"attachment",
"or",
"from",
"a",
"url",
".",
"HTTP",
"POST",
"on",
"/",
"media",
":",
"param",
"filename",
":",
"Media",
"file",
"attached",
"to",
"the",
"request",
".",
":",
"param",... | python | train | 40.709677 |
kurtbrose/pyjks | jks/util.py | https://github.com/kurtbrose/pyjks/blob/1cbe7f060e2ad076b6462f3273f11d635771ea3d/jks/util.py#L105-L116 | def _read_utf(cls, data, pos, kind=None):
"""
:param kind: Optional; a human-friendly identifier for the kind of UTF-8 data we're loading (e.g. is it a keystore alias? an algorithm identifier? something else?).
Used to construct more informative exception messages when a decoding er... | [
"def",
"_read_utf",
"(",
"cls",
",",
"data",
",",
"pos",
",",
"kind",
"=",
"None",
")",
":",
"size",
"=",
"b2",
".",
"unpack_from",
"(",
"data",
",",
"pos",
")",
"[",
"0",
"]",
"pos",
"+=",
"2",
"try",
":",
"return",
"data",
"[",
"pos",
":",
... | :param kind: Optional; a human-friendly identifier for the kind of UTF-8 data we're loading (e.g. is it a keystore alias? an algorithm identifier? something else?).
Used to construct more informative exception messages when a decoding error occurs. | [
":",
"param",
"kind",
":",
"Optional",
";",
"a",
"human",
"-",
"friendly",
"identifier",
"for",
"the",
"kind",
"of",
"UTF",
"-",
"8",
"data",
"we",
"re",
"loading",
"(",
"e",
".",
"g",
".",
"is",
"it",
"a",
"keystore",
"alias?",
"an",
"algorithm",
... | python | train | 62.5 |
boriel/zxbasic | zxbpp.py | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/zxbpp.py#L406-L418 | def p_define(p):
""" define : DEFINE ID params defs
"""
if ENABLED:
if p[4]:
if SPACES.match(p[4][0]):
p[4][0] = p[4][0][1:]
else:
warning(p.lineno(1), "missing whitespace after the macro name")
ID_TABLE.define(p[2], args=p[3], value=p... | [
"def",
"p_define",
"(",
"p",
")",
":",
"if",
"ENABLED",
":",
"if",
"p",
"[",
"4",
"]",
":",
"if",
"SPACES",
".",
"match",
"(",
"p",
"[",
"4",
"]",
"[",
"0",
"]",
")",
":",
"p",
"[",
"4",
"]",
"[",
"0",
"]",
"=",
"p",
"[",
"4",
"]",
"[... | define : DEFINE ID params defs | [
"define",
":",
"DEFINE",
"ID",
"params",
"defs"
] | python | train | 30.307692 |
pypa/setuptools | setuptools/dist.py | https://github.com/pypa/setuptools/blob/83c667e0b2a98193851c07115d1af65011ed0fb6/setuptools/dist.py#L900-L920 | def exclude_package(self, package):
"""Remove packages, modules, and extensions in named package"""
pfx = package + '.'
if self.packages:
self.packages = [
p for p in self.packages
if p != package and not p.startswith(pfx)
]
if se... | [
"def",
"exclude_package",
"(",
"self",
",",
"package",
")",
":",
"pfx",
"=",
"package",
"+",
"'.'",
"if",
"self",
".",
"packages",
":",
"self",
".",
"packages",
"=",
"[",
"p",
"for",
"p",
"in",
"self",
".",
"packages",
"if",
"p",
"!=",
"package",
"... | Remove packages, modules, and extensions in named package | [
"Remove",
"packages",
"modules",
"and",
"extensions",
"in",
"named",
"package"
] | python | train | 30.952381 |
RedFantom/ttkwidgets | ttkwidgets/timeline.py | https://github.com/RedFantom/ttkwidgets/blob/02150322060f867b6e59a175522ef84b09168019/ttkwidgets/timeline.py#L390-L400 | def draw_separators(self):
"""Draw the lines separating the categories on the Canvas"""
total = 1
self._timeline.create_line((0, 1, self.pixel_width, 1))
for index, (category, label) in enumerate(self._category_labels.items()):
height = label.winfo_reqheight()
sel... | [
"def",
"draw_separators",
"(",
"self",
")",
":",
"total",
"=",
"1",
"self",
".",
"_timeline",
".",
"create_line",
"(",
"(",
"0",
",",
"1",
",",
"self",
".",
"pixel_width",
",",
"1",
")",
")",
"for",
"index",
",",
"(",
"category",
",",
"label",
")",... | Draw the lines separating the categories on the Canvas | [
"Draw",
"the",
"lines",
"separating",
"the",
"categories",
"on",
"the",
"Canvas"
] | python | train | 48.818182 |
sods/paramz | paramz/param.py | https://github.com/sods/paramz/blob/ae6fc6274b70fb723d91e48fc5026a9bc5a06508/paramz/param.py#L275-L311 | def _repr_html_(self, indices=None, iops=None, lx=None, li=None, lls=None):
"""Representation of the parameter in html for notebook display."""
filter_ = self._current_slice_
vals = self.flat
if indices is None: indices = self._indices(filter_)
if iops is None:
ravi =... | [
"def",
"_repr_html_",
"(",
"self",
",",
"indices",
"=",
"None",
",",
"iops",
"=",
"None",
",",
"lx",
"=",
"None",
",",
"li",
"=",
"None",
",",
"lls",
"=",
"None",
")",
":",
"filter_",
"=",
"self",
".",
"_current_slice_",
"vals",
"=",
"self",
".",
... | Representation of the parameter in html for notebook display. | [
"Representation",
"of",
"the",
"parameter",
"in",
"html",
"for",
"notebook",
"display",
"."
] | python | train | 63.567568 |
nicolargo/glances | glances/config.py | https://github.com/nicolargo/glances/blob/5bd4d587a736e0d2b03170b56926841d2a3eb7ee/glances/config.py#L311-L316 | def get_bool_value(self, section, option, default=True):
"""Get the bool value of an option, if it exists."""
try:
return self.parser.getboolean(section, option)
except NoOptionError:
return bool(default) | [
"def",
"get_bool_value",
"(",
"self",
",",
"section",
",",
"option",
",",
"default",
"=",
"True",
")",
":",
"try",
":",
"return",
"self",
".",
"parser",
".",
"getboolean",
"(",
"section",
",",
"option",
")",
"except",
"NoOptionError",
":",
"return",
"boo... | Get the bool value of an option, if it exists. | [
"Get",
"the",
"bool",
"value",
"of",
"an",
"option",
"if",
"it",
"exists",
"."
] | python | train | 41.166667 |
GoogleCloudPlatform/cloud-debug-python | src/googleclouddebugger/backoff.py | https://github.com/GoogleCloudPlatform/cloud-debug-python/blob/89ce3782c98b814838a3ecb5479ed3882368cbee/src/googleclouddebugger/backoff.py#L49-L58 | def Failed(self):
"""Indicates that a request has failed.
Returns:
Time interval to wait before retrying (in seconds).
"""
interval = self._current_interval_sec
self._current_interval_sec = min(
self.max_interval_sec, self._current_interval_sec * self.multiplier)
return interval | [
"def",
"Failed",
"(",
"self",
")",
":",
"interval",
"=",
"self",
".",
"_current_interval_sec",
"self",
".",
"_current_interval_sec",
"=",
"min",
"(",
"self",
".",
"max_interval_sec",
",",
"self",
".",
"_current_interval_sec",
"*",
"self",
".",
"multiplier",
")... | Indicates that a request has failed.
Returns:
Time interval to wait before retrying (in seconds). | [
"Indicates",
"that",
"a",
"request",
"has",
"failed",
"."
] | python | train | 30.9 |
NICTA/revrand | revrand/optimize/sgd.py | https://github.com/NICTA/revrand/blob/4c1881b6c1772d2b988518e49dde954f165acfb6/revrand/optimize/sgd.py#L311-L425 | def sgd(fun, x0, data, args=(), bounds=None, batch_size=10, maxiter=5000,
updater=None, eval_obj=False, random_state=None):
"""
Stochastic Gradient Descent.
Parameters
----------
fun : callable
the function to *minimize*, this must have the signature ``[obj,]``
grad = fun(x,... | [
"def",
"sgd",
"(",
"fun",
",",
"x0",
",",
"data",
",",
"args",
"=",
"(",
")",
",",
"bounds",
"=",
"None",
",",
"batch_size",
"=",
"10",
",",
"maxiter",
"=",
"5000",
",",
"updater",
"=",
"None",
",",
"eval_obj",
"=",
"False",
",",
"random_state",
... | Stochastic Gradient Descent.
Parameters
----------
fun : callable
the function to *minimize*, this must have the signature ``[obj,]``
grad = fun(x, data, ...)`, where the ``eval_obj`` argument tells
``sgd`` if an objective function value is going to be returned by
``fun``.
... | [
"Stochastic",
"Gradient",
"Descent",
"."
] | python | train | 30.826087 |
Naught0/asyncurban | asyncurban/urbandictionary.py | https://github.com/Naught0/asyncurban/blob/ae571a13c52869399808ac88a46ea45888ac0181/asyncurban/urbandictionary.py#L138-L150 | async def search_raw(self, term: str, limit: int = 3) -> List[dict]:
"""Performs a search for a term and returns the raw response.
Args:
term: The term to be defined.
limit: The maximum amount of results you'd like.
Defaults to 3.
... | [
"async",
"def",
"search_raw",
"(",
"self",
",",
"term",
":",
"str",
",",
"limit",
":",
"int",
"=",
"3",
")",
"->",
"List",
"[",
"dict",
"]",
":",
"return",
"(",
"await",
"self",
".",
"_get",
"(",
"term",
"=",
"term",
")",
")",
"[",
"'list'",
"]... | Performs a search for a term and returns the raw response.
Args:
term: The term to be defined.
limit: The maximum amount of results you'd like.
Defaults to 3.
Returns:
A list of :class:`dict`\s which contain word information. | [
"Performs",
"a",
"search",
"for",
"a",
"term",
"and",
"returns",
"the",
"raw",
"response",
".",
"Args",
":",
"term",
":",
"The",
"term",
"to",
"be",
"defined",
".",
"limit",
":",
"The",
"maximum",
"amount",
"of",
"results",
"you",
"d",
"like",
".",
"... | python | train | 35.384615 |
glenfant/openxmllib | openxmllib/document.py | https://github.com/glenfant/openxmllib/blob/c8208f8ecd9fc3ef1e73c1db68081a65361afb3f/openxmllib/document.py#L123-L138 | def _tagValuedProperties(self, content_type):
"""Document properties for property files having constructs like
<ns:name>value</ns:name>
:param content_type: ``contenttypes.CT_CORE_PROPS`` or ``contenttypes.CT_EXT_PROPS``
:return: mapping like {'property name': 'property value', ...}
... | [
"def",
"_tagValuedProperties",
"(",
"self",
",",
"content_type",
")",
":",
"rval",
"=",
"{",
"}",
"if",
"not",
"content_type",
"in",
"self",
".",
"content_types",
".",
"listMetaContentTypes",
":",
"# We fail silently",
"return",
"rval",
"for",
"tree",
"in",
"s... | Document properties for property files having constructs like
<ns:name>value</ns:name>
:param content_type: ``contenttypes.CT_CORE_PROPS`` or ``contenttypes.CT_EXT_PROPS``
:return: mapping like {'property name': 'property value', ...} | [
"Document",
"properties",
"for",
"property",
"files",
"having",
"constructs",
"like",
"<ns",
":",
"name",
">",
"value<",
"/",
"ns",
":",
"name",
">"
] | python | train | 45.9375 |
cloudbase/python-hnvclient | hnv/client.py | https://github.com/cloudbase/python-hnvclient/blob/b019452af01db22629809b8930357a2ebf6494be/hnv/client.py#L2920-L2929 | def process_raw_data(cls, raw_data):
"""Create a new model using raw API response."""
properties = raw_data.get("properties", {})
raw_content = properties.get("statistics", None)
if raw_content is not None:
statistics = BGPPeersStatistics.from_raw_data(raw_content)
... | [
"def",
"process_raw_data",
"(",
"cls",
",",
"raw_data",
")",
":",
"properties",
"=",
"raw_data",
".",
"get",
"(",
"\"properties\"",
",",
"{",
"}",
")",
"raw_content",
"=",
"properties",
".",
"get",
"(",
"\"statistics\"",
",",
"None",
")",
"if",
"raw_conten... | Create a new model using raw API response. | [
"Create",
"a",
"new",
"model",
"using",
"raw",
"API",
"response",
"."
] | python | train | 41.5 |
mila/pyoo | pyoo.py | https://github.com/mila/pyoo/blob/1e024999f608c87ea72cd443e39c89eb0ba3cc62/pyoo.py#L97-L109 | def str_repr(klass):
"""
Implements string conversion methods for the given class.
The given class must implement the __str__ method. This decorat
will add __repr__ and __unicode__ (for Python 2).
"""
if PY2:
klass.__unicode__ = klass.__str__
klass.__str__ = lambda self: self._... | [
"def",
"str_repr",
"(",
"klass",
")",
":",
"if",
"PY2",
":",
"klass",
".",
"__unicode__",
"=",
"klass",
".",
"__str__",
"klass",
".",
"__str__",
"=",
"lambda",
"self",
":",
"self",
".",
"__unicode__",
"(",
")",
".",
"encode",
"(",
"'utf-8'",
")",
"kl... | Implements string conversion methods for the given class.
The given class must implement the __str__ method. This decorat
will add __repr__ and __unicode__ (for Python 2). | [
"Implements",
"string",
"conversion",
"methods",
"for",
"the",
"given",
"class",
"."
] | python | train | 33.615385 |
Unidata/MetPy | metpy/calc/basic.py | https://github.com/Unidata/MetPy/blob/16f68a94919b9a82dcf9cada2169cf039129e67b/metpy/calc/basic.py#L583-L620 | def sigma_to_pressure(sigma, psfc, ptop):
r"""Calculate pressure from sigma values.
Parameters
----------
sigma : ndarray
The sigma levels to be converted to pressure levels.
psfc : `pint.Quantity`
The surface pressure value.
ptop : `pint.Quantity`
The pressure value a... | [
"def",
"sigma_to_pressure",
"(",
"sigma",
",",
"psfc",
",",
"ptop",
")",
":",
"if",
"np",
".",
"any",
"(",
"sigma",
"<",
"0",
")",
"or",
"np",
".",
"any",
"(",
"sigma",
">",
"1",
")",
":",
"raise",
"ValueError",
"(",
"'Sigma values should be bounded by... | r"""Calculate pressure from sigma values.
Parameters
----------
sigma : ndarray
The sigma levels to be converted to pressure levels.
psfc : `pint.Quantity`
The surface pressure value.
ptop : `pint.Quantity`
The pressure value at the top of the model domain.
Returns
... | [
"r",
"Calculate",
"pressure",
"from",
"sigma",
"values",
"."
] | python | train | 28.052632 |
amirziai/flatten | flatten_json.py | https://github.com/amirziai/flatten/blob/e8e2cbbdd6fe21177bfc0ce034562463ae555799/flatten_json.py#L93-L115 | def unflatten(flat_dict, separator='_'):
"""
Creates a hierarchical dictionary from a flattened dictionary
Assumes no lists are present
:param flat_dict: a dictionary with no hierarchy
:param separator: a string that separates keys
:return: a dictionary with hierarchy
"""
_unflatten_asse... | [
"def",
"unflatten",
"(",
"flat_dict",
",",
"separator",
"=",
"'_'",
")",
":",
"_unflatten_asserts",
"(",
"flat_dict",
",",
"separator",
")",
"# This global dictionary is mutated and returned",
"unflattened_dict",
"=",
"dict",
"(",
")",
"def",
"_unflatten",
"(",
"dic... | Creates a hierarchical dictionary from a flattened dictionary
Assumes no lists are present
:param flat_dict: a dictionary with no hierarchy
:param separator: a string that separates keys
:return: a dictionary with hierarchy | [
"Creates",
"a",
"hierarchical",
"dictionary",
"from",
"a",
"flattened",
"dictionary",
"Assumes",
"no",
"lists",
"are",
"present",
":",
"param",
"flat_dict",
":",
"a",
"dictionary",
"with",
"no",
"hierarchy",
":",
"param",
"separator",
":",
"a",
"string",
"that... | python | train | 29.695652 |
benoitkugler/abstractDataLibrary | pyDLib/Core/groups.py | https://github.com/benoitkugler/abstractDataLibrary/blob/16be28e99837e40287a63803bbfdf67ac1806b7b/pyDLib/Core/groups.py#L102-L132 | def recherche(self, pattern, entete):
"""Performs a search field by field, using functions defined in formats.
Matchs are marked with info[`font`]
:param pattern: String to look for
:param entete: Fields to look into
:return: Nothing. The collection is changed in place
"... | [
"def",
"recherche",
"(",
"self",
",",
"pattern",
",",
"entete",
")",
":",
"new_liste",
"=",
"[",
"]",
"sub_patterns",
"=",
"pattern",
".",
"split",
"(",
"\" \"",
")",
"for",
"p",
"in",
"self",
":",
"d_font",
"=",
"{",
"att",
":",
"False",
"for",
"a... | Performs a search field by field, using functions defined in formats.
Matchs are marked with info[`font`]
:param pattern: String to look for
:param entete: Fields to look into
:return: Nothing. The collection is changed in place | [
"Performs",
"a",
"search",
"field",
"by",
"field",
"using",
"functions",
"defined",
"in",
"formats",
".",
"Matchs",
"are",
"marked",
"with",
"info",
"[",
"font",
"]"
] | python | train | 36.612903 |
cloud9ers/gurumate | environment/lib/python2.7/site-packages/IPython/zmq/session.py | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/zmq/session.py#L58-L70 | def squash_unicode(obj):
"""coerce unicode back to bytestrings."""
if isinstance(obj,dict):
for key in obj.keys():
obj[key] = squash_unicode(obj[key])
if isinstance(key, unicode):
obj[squash_unicode(key)] = obj.pop(key)
elif isinstance(obj, list):
for ... | [
"def",
"squash_unicode",
"(",
"obj",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"dict",
")",
":",
"for",
"key",
"in",
"obj",
".",
"keys",
"(",
")",
":",
"obj",
"[",
"key",
"]",
"=",
"squash_unicode",
"(",
"obj",
"[",
"key",
"]",
")",
"if",
... | coerce unicode back to bytestrings. | [
"coerce",
"unicode",
"back",
"to",
"bytestrings",
"."
] | python | test | 34.769231 |
NuGrid/NuGridPy | nugridpy/ppn.py | https://github.com/NuGrid/NuGridPy/blob/eee8047446e398be77362d82c1d8b3310054fab0/nugridpy/ppn.py#L692-L763 | def get(self, attri, fname=None, numtype='cycNum', decayed=False):
'''
In this method all data for an entire cycle (basically the
content of an iso_massfnnnn.DAT file) or a column of data for
the associated attribute is returned.
Parameters
----------
attri : str... | [
"def",
"get",
"(",
"self",
",",
"attri",
",",
"fname",
"=",
"None",
",",
"numtype",
"=",
"'cycNum'",
",",
"decayed",
"=",
"False",
")",
":",
"if",
"type",
"(",
"attri",
")",
"is",
"type",
"(",
"1",
")",
":",
"print",
"(",
"\"Calling get method in cyc... | In this method all data for an entire cycle (basically the
content of an iso_massfnnnn.DAT file) or a column of data for
the associated attribute is returned.
Parameters
----------
attri : string or integer
If attri is a string, attri is the cycle or name of the
... | [
"In",
"this",
"method",
"all",
"data",
"for",
"an",
"entire",
"cycle",
"(",
"basically",
"the",
"content",
"of",
"an",
"iso_massfnnnn",
".",
"DAT",
"file",
")",
"or",
"a",
"column",
"of",
"data",
"for",
"the",
"associated",
"attribute",
"is",
"returned",
... | python | train | 35.166667 |
dswah/pyGAM | pygam/pygam.py | https://github.com/dswah/pyGAM/blob/b3e5c3cd580f0a3ad69f9372861624f67760c325/pygam/pygam.py#L621-L664 | def _initial_estimate(self, y, modelmat):
"""
Makes an inital estimate for the model coefficients.
For a LinearGAM we simply initialize to small coefficients.
For other GAMs we transform the problem to the linear space
and solve an unpenalized version.
Parameters
... | [
"def",
"_initial_estimate",
"(",
"self",
",",
"y",
",",
"modelmat",
")",
":",
"# do a simple initialization for LinearGAMs",
"if",
"isinstance",
"(",
"self",
",",
"LinearGAM",
")",
":",
"n",
",",
"m",
"=",
"modelmat",
".",
"shape",
"return",
"np",
".",
"ones... | Makes an inital estimate for the model coefficients.
For a LinearGAM we simply initialize to small coefficients.
For other GAMs we transform the problem to the linear space
and solve an unpenalized version.
Parameters
---------
y : array-like of shape (n,)
... | [
"Makes",
"an",
"inital",
"estimate",
"for",
"the",
"model",
"coefficients",
"."
] | python | train | 34.363636 |
f3at/feat | src/feat/agents/base/agent.py | https://github.com/f3at/feat/blob/15da93fc9d6ec8154f52a9172824e25821195ef8/src/feat/agents/base/agent.py#L249-L255 | def get_full_id(self, state):
"""Return a global unique identifier for this agent instance.
It's a combination of agent_id and instance_id:
full_id = agent_id + '/' + instance_id
"""
desc = state.medium.get_descriptor()
return desc.doc_id + u"/" + unicode(desc.instance_... | [
"def",
"get_full_id",
"(",
"self",
",",
"state",
")",
":",
"desc",
"=",
"state",
".",
"medium",
".",
"get_descriptor",
"(",
")",
"return",
"desc",
".",
"doc_id",
"+",
"u\"/\"",
"+",
"unicode",
"(",
"desc",
".",
"instance_id",
")"
] | Return a global unique identifier for this agent instance.
It's a combination of agent_id and instance_id:
full_id = agent_id + '/' + instance_id | [
"Return",
"a",
"global",
"unique",
"identifier",
"for",
"this",
"agent",
"instance",
".",
"It",
"s",
"a",
"combination",
"of",
"agent_id",
"and",
"instance_id",
":",
"full_id",
"=",
"agent_id",
"+",
"/",
"+",
"instance_id"
] | python | train | 45.285714 |
pipermerriam/flex | flex/core.py | https://github.com/pipermerriam/flex/blob/233f8149fb851a6255753bcec948cb6fefb2723b/flex/core.py#L103-L111 | def validate(raw_schema, target=None, **kwargs):
"""
Given the python representation of a JSONschema as defined in the swagger
spec, validate that the schema complies to spec. If `target` is provided,
that target will be validated against the provided schema.
"""
schema = schema_validator(raw_s... | [
"def",
"validate",
"(",
"raw_schema",
",",
"target",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"schema",
"=",
"schema_validator",
"(",
"raw_schema",
",",
"*",
"*",
"kwargs",
")",
"if",
"target",
"is",
"not",
"None",
":",
"validate_object",
"(",
"... | Given the python representation of a JSONschema as defined in the swagger
spec, validate that the schema complies to spec. If `target` is provided,
that target will be validated against the provided schema. | [
"Given",
"the",
"python",
"representation",
"of",
"a",
"JSONschema",
"as",
"defined",
"in",
"the",
"swagger",
"spec",
"validate",
"that",
"the",
"schema",
"complies",
"to",
"spec",
".",
"If",
"target",
"is",
"provided",
"that",
"target",
"will",
"be",
"valid... | python | train | 45.777778 |
uber-common/opentracing-python-instrumentation | opentracing_instrumentation/http_server.py | https://github.com/uber-common/opentracing-python-instrumentation/blob/57b29fb9f647e073cde8c75155f4708cb5661d20/opentracing_instrumentation/http_server.py#L35-L86 | def before_request(request, tracer=None):
"""
Attempts to extract a tracing span from incoming request.
If no tracing context is passed in the headers, or the data
cannot be parsed, a new root span is started.
:param request: HTTP request with `.headers` property exposed
that satisfies a re... | [
"def",
"before_request",
"(",
"request",
",",
"tracer",
"=",
"None",
")",
":",
"if",
"tracer",
"is",
"None",
":",
"# pragma: no cover",
"tracer",
"=",
"opentracing",
".",
"tracer",
"# we need to prepare tags upfront, mainly because RPC_SERVER tag must be",
"# set when sta... | Attempts to extract a tracing span from incoming request.
If no tracing context is passed in the headers, or the data
cannot be parsed, a new root span is started.
:param request: HTTP request with `.headers` property exposed
that satisfies a regular dictionary interface
:param tracer: optional... | [
"Attempts",
"to",
"extract",
"a",
"tracing",
"span",
"from",
"incoming",
"request",
".",
"If",
"no",
"tracing",
"context",
"is",
"passed",
"in",
"the",
"headers",
"or",
"the",
"data",
"cannot",
"be",
"parsed",
"a",
"new",
"root",
"span",
"is",
"started",
... | python | train | 31.730769 |
Guake/guake | guake/gsettings.py | https://github.com/Guake/guake/blob/4153ef38f9044cbed6494075fce80acd5809df2b/guake/gsettings.py#L134-L139 | def size_changed(self, settings, key, user_data):
"""If the gconf var window_height or window_width are changed,
this method will be called and will call the resize function
in guake.
"""
RectCalculator.set_final_window_rect(self.settings, self.guake.window) | [
"def",
"size_changed",
"(",
"self",
",",
"settings",
",",
"key",
",",
"user_data",
")",
":",
"RectCalculator",
".",
"set_final_window_rect",
"(",
"self",
".",
"settings",
",",
"self",
".",
"guake",
".",
"window",
")"
] | If the gconf var window_height or window_width are changed,
this method will be called and will call the resize function
in guake. | [
"If",
"the",
"gconf",
"var",
"window_height",
"or",
"window_width",
"are",
"changed",
"this",
"method",
"will",
"be",
"called",
"and",
"will",
"call",
"the",
"resize",
"function",
"in",
"guake",
"."
] | python | train | 48.833333 |
cuihantao/andes | andes/models/pss.py | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/models/pss.py#L139-L148 | def set_flag(self, value, flag, reset_val=False):
"""Set a flag to 0 if the corresponding value is 0"""
if not self.__dict__[flag]:
self.__dict__[flag] = matrix(1.0, (len(self.__dict__[value]), 1),
'd')
for idx, item in enumerate(self.__dict__... | [
"def",
"set_flag",
"(",
"self",
",",
"value",
",",
"flag",
",",
"reset_val",
"=",
"False",
")",
":",
"if",
"not",
"self",
".",
"__dict__",
"[",
"flag",
"]",
":",
"self",
".",
"__dict__",
"[",
"flag",
"]",
"=",
"matrix",
"(",
"1.0",
",",
"(",
"len... | Set a flag to 0 if the corresponding value is 0 | [
"Set",
"a",
"flag",
"to",
"0",
"if",
"the",
"corresponding",
"value",
"is",
"0"
] | python | train | 47.1 |
stefanfoulis/django-sendsms | sendsms/message.py | https://github.com/stefanfoulis/django-sendsms/blob/375f469789866853253eceba936ebcff98e83c07/sendsms/message.py#L30-L39 | def send(self, fail_silently=False):
"""
Sends the sms message
"""
if not self.to:
# Don't bother creating the connection if there's nobody to send to
return 0
res = self.get_connection(fail_silently).send_messages([self])
sms_post_send.send(sender... | [
"def",
"send",
"(",
"self",
",",
"fail_silently",
"=",
"False",
")",
":",
"if",
"not",
"self",
".",
"to",
":",
"# Don't bother creating the connection if there's nobody to send to",
"return",
"0",
"res",
"=",
"self",
".",
"get_connection",
"(",
"fail_silently",
")... | Sends the sms message | [
"Sends",
"the",
"sms",
"message"
] | python | train | 39.2 |
Nixiware/viper | nx/viper/service/mysql.py | https://github.com/Nixiware/viper/blob/fbe6057facd8d46103e9955880dfd99e63b7acb3/nx/viper/service/mysql.py#L27-L82 | def _applicationStart(self, data):
"""
Initializes the database connection pool.
:param data: <object> event data object
:return: <void>
"""
checkup = False
if "viper.mysql" in self.application.config \
and isinstance(self.application.config["vipe... | [
"def",
"_applicationStart",
"(",
"self",
",",
"data",
")",
":",
"checkup",
"=",
"False",
"if",
"\"viper.mysql\"",
"in",
"self",
".",
"application",
".",
"config",
"and",
"isinstance",
"(",
"self",
".",
"application",
".",
"config",
"[",
"\"viper.mysql\"",
"]... | Initializes the database connection pool.
:param data: <object> event data object
:return: <void> | [
"Initializes",
"the",
"database",
"connection",
"pool",
"."
] | python | train | 40.946429 |
richardchien/python-cqhttp | cqhttp_helper.py | https://github.com/richardchien/python-cqhttp/blob/1869819a8f89001e3f70668e31afc6c78f7f5bc2/cqhttp_helper.py#L513-L526 | def set_friend_add_request(self, *, flag, approve=True, remark=None):
"""
处理加好友请求
------------
:param str flag: 加好友请求的 flag(需从上报的数据中获得)
:param bool approve: 是否同意请求
:param str remark: 添加后的好友备注(仅在同意时有效)
:return: None
:rtype: None
"""
return... | [
"def",
"set_friend_add_request",
"(",
"self",
",",
"*",
",",
"flag",
",",
"approve",
"=",
"True",
",",
"remark",
"=",
"None",
")",
":",
"return",
"super",
"(",
")",
".",
"__getattr__",
"(",
"'set_friend_add_request'",
")",
"(",
"flag",
"=",
"flag",
",",
... | 处理加好友请求
------------
:param str flag: 加好友请求的 flag(需从上报的数据中获得)
:param bool approve: 是否同意请求
:param str remark: 添加后的好友备注(仅在同意时有效)
:return: None
:rtype: None | [
"处理加好友请求"
] | python | valid | 29.357143 |
hvishwanath/libpaas | libpaas/drivers/heroku.py | https://github.com/hvishwanath/libpaas/blob/3df07adca59c003ee754c4e919cf506c13953be1/libpaas/drivers/heroku.py#L78-L84 | def getInstance(cls, *args):
'''
Returns a singleton instance of the class
'''
if not cls.__singleton:
cls.__singleton = Heroku(*args)
return cls.__singleton | [
"def",
"getInstance",
"(",
"cls",
",",
"*",
"args",
")",
":",
"if",
"not",
"cls",
".",
"__singleton",
":",
"cls",
".",
"__singleton",
"=",
"Heroku",
"(",
"*",
"args",
")",
"return",
"cls",
".",
"__singleton"
] | Returns a singleton instance of the class | [
"Returns",
"a",
"singleton",
"instance",
"of",
"the",
"class"
] | python | train | 29 |
alexhayes/django-toolkit | django_toolkit/templatetags/cache_helpers.py | https://github.com/alexhayes/django-toolkit/blob/b64106392fad596defc915b8235fe6e1d0013b5b/django_toolkit/templatetags/cache_helpers.py#L8-L18 | def expire_cache(fragment_name, *args):
"""
Expire a cache item.
@param url: The url object
@param product_names: A list of product names
@param start: The date from which the reporting should start.
@param stop: The date at which the reporting should stop.
"""
cache_key = make_temp... | [
"def",
"expire_cache",
"(",
"fragment_name",
",",
"*",
"args",
")",
":",
"cache_key",
"=",
"make_template_fragment_key",
"(",
"fragment_name",
",",
"args",
")",
"cache",
".",
"delete",
"(",
"cache_key",
")"
] | Expire a cache item.
@param url: The url object
@param product_names: A list of product names
@param start: The date from which the reporting should start.
@param stop: The date at which the reporting should stop. | [
"Expire",
"a",
"cache",
"item",
"."
] | python | train | 34.181818 |
clalancette/pycdlib | pycdlib/pycdlib.py | https://github.com/clalancette/pycdlib/blob/1e7b77a809e905d67dc71e12d70e850be26b6233/pycdlib/pycdlib.py#L2039-L2062 | def _check_rr_name(self, rr_name):
# type: (Optional[str]) -> bytes
'''
An internal method to check whether this ISO requires or does not
require a Rock Ridge path.
Parameters:
rr_name - The Rock Ridge name.
Returns:
The Rock Ridge name in bytes if this... | [
"def",
"_check_rr_name",
"(",
"self",
",",
"rr_name",
")",
":",
"# type: (Optional[str]) -> bytes",
"if",
"self",
".",
"rock_ridge",
":",
"if",
"not",
"rr_name",
":",
"raise",
"pycdlibexception",
".",
"PyCdlibInvalidInput",
"(",
"'A rock ridge name must be passed for a ... | An internal method to check whether this ISO requires or does not
require a Rock Ridge path.
Parameters:
rr_name - The Rock Ridge name.
Returns:
The Rock Ridge name in bytes if this is a Rock Ridge ISO, None otherwise. | [
"An",
"internal",
"method",
"to",
"check",
"whether",
"this",
"ISO",
"requires",
"or",
"does",
"not",
"require",
"a",
"Rock",
"Ridge",
"path",
"."
] | python | train | 35.833333 |
PyMySQL/PyMySQL | pymysql/cursors.py | https://github.com/PyMySQL/PyMySQL/blob/3674bc6fd064bf88524e839c07690e8c35223709/pymysql/cursors.py#L273-L280 | def fetchone(self):
"""Fetch the next row"""
self._check_executed()
if self._rows is None or self.rownumber >= len(self._rows):
return None
result = self._rows[self.rownumber]
self.rownumber += 1
return result | [
"def",
"fetchone",
"(",
"self",
")",
":",
"self",
".",
"_check_executed",
"(",
")",
"if",
"self",
".",
"_rows",
"is",
"None",
"or",
"self",
".",
"rownumber",
">=",
"len",
"(",
"self",
".",
"_rows",
")",
":",
"return",
"None",
"result",
"=",
"self",
... | Fetch the next row | [
"Fetch",
"the",
"next",
"row"
] | python | train | 32.75 |
drdoctr/doctr | doctr/local.py | https://github.com/drdoctr/doctr/blob/0f19ff78c8239efcc98d417f36b0a31d9be01ba5/doctr/local.py#L267-L288 | def generate_GitHub_token(*, note="Doctr token for pushing to gh-pages from Travis", scopes=None, **login_kwargs):
"""
Generate a GitHub token for pushing from Travis
The scope requested is public_repo.
If no password or OTP are provided, they will be requested from the
command line.
The toke... | [
"def",
"generate_GitHub_token",
"(",
"*",
",",
"note",
"=",
"\"Doctr token for pushing to gh-pages from Travis\"",
",",
"scopes",
"=",
"None",
",",
"*",
"*",
"login_kwargs",
")",
":",
"if",
"scopes",
"is",
"None",
":",
"scopes",
"=",
"[",
"'public_repo'",
"]",
... | Generate a GitHub token for pushing from Travis
The scope requested is public_repo.
If no password or OTP are provided, they will be requested from the
command line.
The token created here can be revoked at
https://github.com/settings/tokens. | [
"Generate",
"a",
"GitHub",
"token",
"for",
"pushing",
"from",
"Travis"
] | python | train | 32.272727 |
pandas-dev/pandas | pandas/core/generic.py | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/generic.py#L1514-L1529 | def bool(self):
"""
Return the bool of a single element PandasObject.
This must be a boolean scalar value, either True or False. Raise a
ValueError if the PandasObject does not have exactly 1 element, or that
element is not boolean
"""
v = self.squeeze()
... | [
"def",
"bool",
"(",
"self",
")",
":",
"v",
"=",
"self",
".",
"squeeze",
"(",
")",
"if",
"isinstance",
"(",
"v",
",",
"(",
"bool",
",",
"np",
".",
"bool_",
")",
")",
":",
"return",
"bool",
"(",
"v",
")",
"elif",
"is_scalar",
"(",
"v",
")",
":"... | Return the bool of a single element PandasObject.
This must be a boolean scalar value, either True or False. Raise a
ValueError if the PandasObject does not have exactly 1 element, or that
element is not boolean | [
"Return",
"the",
"bool",
"of",
"a",
"single",
"element",
"PandasObject",
"."
] | python | train | 35.6875 |
awslabs/serverless-application-model | samtranslator/model/s3_utils/uri_parser.py | https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/model/s3_utils/uri_parser.py#L30-L48 | def to_s3_uri(code_dict):
"""Constructs a S3 URI string from given code dictionary
:param dict code_dict: Dictionary containing Lambda function Code S3 location of the form
{S3Bucket, S3Key, S3ObjectVersion}
:return: S3 URI of form s3://bucket/key?versionId=version
:rtype stri... | [
"def",
"to_s3_uri",
"(",
"code_dict",
")",
":",
"try",
":",
"uri",
"=",
"\"s3://{bucket}/{key}\"",
".",
"format",
"(",
"bucket",
"=",
"code_dict",
"[",
"\"S3Bucket\"",
"]",
",",
"key",
"=",
"code_dict",
"[",
"\"S3Key\"",
"]",
")",
"version",
"=",
"code_dic... | Constructs a S3 URI string from given code dictionary
:param dict code_dict: Dictionary containing Lambda function Code S3 location of the form
{S3Bucket, S3Key, S3ObjectVersion}
:return: S3 URI of form s3://bucket/key?versionId=version
:rtype string | [
"Constructs",
"a",
"S3",
"URI",
"string",
"from",
"given",
"code",
"dictionary"
] | python | train | 34.315789 |
jeroyang/txttk | txttk/retools.py | https://github.com/jeroyang/txttk/blob/8e6daf9cbb7dfbc4900870fb365add17929bd4ab/txttk/retools.py#L141-L157 | def unpack(regex):
"""
Remove the outermost parens, keep the (?P...) one
>>> unpack(r'(abc)')
'abc'
>>> unpack(r'(?:abc)')
'abc'
>>> unpack(r'(?P<xyz>abc)')
'(?P<xyz>abc)'
>>> unpack(r'[abc]')
'[abc]'
"""
if is_packed(regex) and not regex.startswith('(?P<'):
retu... | [
"def",
"unpack",
"(",
"regex",
")",
":",
"if",
"is_packed",
"(",
"regex",
")",
"and",
"not",
"regex",
".",
"startswith",
"(",
"'(?P<'",
")",
":",
"return",
"re",
".",
"sub",
"(",
"r'^\\((\\?:)?(?P<content>.*?)\\)$'",
",",
"r'\\g<content>'",
",",
"regex",
"... | Remove the outermost parens, keep the (?P...) one
>>> unpack(r'(abc)')
'abc'
>>> unpack(r'(?:abc)')
'abc'
>>> unpack(r'(?P<xyz>abc)')
'(?P<xyz>abc)'
>>> unpack(r'[abc]')
'[abc]' | [
"Remove",
"the",
"outermost",
"parens",
"keep",
"the",
"(",
"?P",
"...",
")",
"one"
] | python | train | 23.529412 |
rehandalal/buchner | buchner/project-template/PROJECTMODULE/errors.py | https://github.com/rehandalal/buchner/blob/dc22a61c493b9d4a74d76e8b42a319aa13e385f3/buchner/project-template/PROJECTMODULE/errors.py#L19-L24 | def error(code, message, template):
"""A generic error handler"""
if json_requested():
return json_error(code, message)
else:
return render_template(template, message=message), code | [
"def",
"error",
"(",
"code",
",",
"message",
",",
"template",
")",
":",
"if",
"json_requested",
"(",
")",
":",
"return",
"json_error",
"(",
"code",
",",
"message",
")",
"else",
":",
"return",
"render_template",
"(",
"template",
",",
"message",
"=",
"mess... | A generic error handler | [
"A",
"generic",
"error",
"handler"
] | python | train | 34 |
googleads/googleads-python-lib | examples/adwords/v201809/campaign_management/add_campaign_groups_and_performance_targets.py | https://github.com/googleads/googleads-python-lib/blob/aa3b1b474b0f9789ca55ca46f4b2b57aeae38874/examples/adwords/v201809/campaign_management/add_campaign_groups_and_performance_targets.py#L76-L100 | def _AddCampaignsToGroup(client, campaign_group_id, campaign_ids):
"""Adds multiple campaigns to a campaign group.
Args:
client: an AdWordsClient instance.
campaign_group_id: an integer ID for the campaign group.
campaign_ids: a list of integer IDs for campaigns.
"""
# Get the CampaignService.
ca... | [
"def",
"_AddCampaignsToGroup",
"(",
"client",
",",
"campaign_group_id",
",",
"campaign_ids",
")",
":",
"# Get the CampaignService.",
"campaign_service",
"=",
"client",
".",
"GetService",
"(",
"'CampaignService'",
",",
"version",
"=",
"'v201809'",
")",
"# Create the oper... | Adds multiple campaigns to a campaign group.
Args:
client: an AdWordsClient instance.
campaign_group_id: an integer ID for the campaign group.
campaign_ids: a list of integer IDs for campaigns. | [
"Adds",
"multiple",
"campaigns",
"to",
"a",
"campaign",
"group",
"."
] | python | train | 31.36 |
rameshg87/pyremotevbox | pyremotevbox/ZSI/dispatch.py | https://github.com/rameshg87/pyremotevbox/blob/123dffff27da57c8faa3ac1dd4c68b1cf4558b1a/pyremotevbox/ZSI/dispatch.py#L213-L235 | def do_POST(self):
'''The POST command.
'''
try:
ct = self.headers['content-type']
if ct.startswith('multipart/'):
cid = resolvers.MIMEResolver(ct, self.rfile)
xml = cid.GetSOAPPart()
ps = ParsedSoap(xml, resolver=cid.Resolv... | [
"def",
"do_POST",
"(",
"self",
")",
":",
"try",
":",
"ct",
"=",
"self",
".",
"headers",
"[",
"'content-type'",
"]",
"if",
"ct",
".",
"startswith",
"(",
"'multipart/'",
")",
":",
"cid",
"=",
"resolvers",
".",
"MIMEResolver",
"(",
"ct",
",",
"self",
".... | The POST command. | [
"The",
"POST",
"command",
"."
] | python | train | 41.695652 |
fbcotter/py3nvml | py3nvml/py3nvml.py | https://github.com/fbcotter/py3nvml/blob/47f0f2c0eee56dec4e4beebec26b734e01d357b7/py3nvml/py3nvml.py#L5372-L5395 | def nvmlDeviceGetTopologyCommonAncestor(device1, device2):
r"""
/**
* Retrieve the common ancestor for two devices
* For all products.
* Supported on Linux only.
*
* @param device1 The identifier of the first device
* @param device2 ... | [
"def",
"nvmlDeviceGetTopologyCommonAncestor",
"(",
"device1",
",",
"device2",
")",
":",
"c_level",
"=",
"_nvmlGpuTopologyLevel_t",
"(",
")",
"fn",
"=",
"_nvmlGetFunctionPointer",
"(",
"\"nvmlDeviceGetTopologyCommonAncestor\"",
")",
"ret",
"=",
"fn",
"(",
"device1",
",... | r"""
/**
* Retrieve the common ancestor for two devices
* For all products.
* Supported on Linux only.
*
* @param device1 The identifier of the first device
* @param device2 The identifier of the second device
* @param path... | [
"r",
"/",
"**",
"*",
"Retrieve",
"the",
"common",
"ancestor",
"for",
"two",
"devices",
"*",
"For",
"all",
"products",
".",
"*",
"Supported",
"on",
"Linux",
"only",
".",
"*",
"*"
] | python | train | 48.791667 |
JukeboxPipeline/jukebox-core | src/jukeboxcore/gui/widgets/tooltip.py | https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/gui/widgets/tooltip.py#L169-L181 | def create_button(self, widget):
"""Create a button that has the given widget rendered as an icon
:param widget: the widget to render as icon
:type widget: QtGui.QWidget
:returns: the created button
:rtype: QtGui.QAbstractButton
:raises: None
"""
btn = Qt... | [
"def",
"create_button",
"(",
"self",
",",
"widget",
")",
":",
"btn",
"=",
"QtGui",
".",
"QToolButton",
"(",
"self",
")",
"btn",
".",
"setIconSize",
"(",
"QtCore",
".",
"QSize",
"(",
"self",
".",
"_iconw",
",",
"self",
".",
"_iconh",
")",
")",
"self",... | Create a button that has the given widget rendered as an icon
:param widget: the widget to render as icon
:type widget: QtGui.QWidget
:returns: the created button
:rtype: QtGui.QAbstractButton
:raises: None | [
"Create",
"a",
"button",
"that",
"has",
"the",
"given",
"widget",
"rendered",
"as",
"an",
"icon"
] | python | train | 34.769231 |
yatiml/yatiml | yatiml/helpers.py | https://github.com/yatiml/yatiml/blob/4f55c058b72388350f0af3076ac3ea9bc1c142b0/yatiml/helpers.py#L299-L308 | def unders_to_dashes_in_keys(self) -> None:
"""Replaces underscores with dashes in key names.
For each attribute in a mapping, this replaces any underscores \
in its keys with dashes. Handy because Python does not \
accept dashes in identifiers, while some YAML-based formats use \
... | [
"def",
"unders_to_dashes_in_keys",
"(",
"self",
")",
"->",
"None",
":",
"for",
"key_node",
",",
"_",
"in",
"self",
".",
"yaml_node",
".",
"value",
":",
"key_node",
".",
"value",
"=",
"key_node",
".",
"value",
".",
"replace",
"(",
"'_'",
",",
"'-'",
")"... | Replaces underscores with dashes in key names.
For each attribute in a mapping, this replaces any underscores \
in its keys with dashes. Handy because Python does not \
accept dashes in identifiers, while some YAML-based formats use \
dashes in their keys. | [
"Replaces",
"underscores",
"with",
"dashes",
"in",
"key",
"names",
"."
] | python | train | 45.8 |
urosjarc/decisionTable.py | decisionTable/core.py | https://github.com/urosjarc/decisionTable.py/blob/174a7e76da5d0ffe79b03a2fe0835e865da84f37/decisionTable/core.py#L233-L281 | def __getDecision(self, result, multiple=False, **values):
"""
The main method for decision picking.
Args:
result (array of str): What values you want to get in return array.
multiple (bolean, optional): Do you want multiple result if it finds many maching decisions.
**values (dict): What should finder ... | [
"def",
"__getDecision",
"(",
"self",
",",
"result",
",",
"multiple",
"=",
"False",
",",
"*",
"*",
"values",
")",
":",
"values",
"=",
"self",
".",
"__toString",
"(",
"values",
")",
"__valueKeyWithHeaderIndex",
"=",
"self",
".",
"__valueKeyWithHeaderIndex",
"(... | The main method for decision picking.
Args:
result (array of str): What values you want to get in return array.
multiple (bolean, optional): Do you want multiple result if it finds many maching decisions.
**values (dict): What should finder look for, (headerString : value).
Returns: Maped result values w... | [
"The",
"main",
"method",
"for",
"decision",
"picking",
"."
] | python | train | 28.428571 |
BD2KGenomics/protect | src/protect/pipeline/ProTECT.py | https://github.com/BD2KGenomics/protect/blob/06310682c50dcf8917b912c8e551299ff7ee41ce/src/protect/pipeline/ProTECT.py#L183-L211 | def _process_group(input_group, required_group, groupname, append_subgroups=None):
"""
Process one group from the input yaml. Ensure it has the required entries. If there is a
subgroup that should be processed and then appended to the rest of the subgroups in that group,
handle it accordingly.
:p... | [
"def",
"_process_group",
"(",
"input_group",
",",
"required_group",
",",
"groupname",
",",
"append_subgroups",
"=",
"None",
")",
":",
"if",
"append_subgroups",
"is",
"None",
":",
"append_subgroups",
"=",
"[",
"]",
"tool_options",
"=",
"{",
"}",
"for",
"key",
... | Process one group from the input yaml. Ensure it has the required entries. If there is a
subgroup that should be processed and then appended to the rest of the subgroups in that group,
handle it accordingly.
:param dict input_group: The dict of values of the input group
:param dict required_group: Th... | [
"Process",
"one",
"group",
"from",
"the",
"input",
"yaml",
".",
"Ensure",
"it",
"has",
"the",
"required",
"entries",
".",
"If",
"there",
"is",
"a",
"subgroup",
"that",
"should",
"be",
"processed",
"and",
"then",
"appended",
"to",
"the",
"rest",
"of",
"th... | python | train | 42.413793 |
Kortemme-Lab/klab | klab/deprecated/rosettadb.py | https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/deprecated/rosettadb.py#L660-L696 | def execQuery(self, sql, parameters = None, cursorClass = MySQLdb.cursors.Cursor, InnoDB = False):
"""Execute SQL query."""
i = 0
errcode = 0
caughte = None
while i < self.numTries:
i += 1
try:
cursor = self.connection.cursor(cursorClass)
if parameters:
errcode = cursor.execute(sql, parame... | [
"def",
"execQuery",
"(",
"self",
",",
"sql",
",",
"parameters",
"=",
"None",
",",
"cursorClass",
"=",
"MySQLdb",
".",
"cursors",
".",
"Cursor",
",",
"InnoDB",
"=",
"False",
")",
":",
"i",
"=",
"0",
"errcode",
"=",
"0",
"caughte",
"=",
"None",
"while"... | Execute SQL query. | [
"Execute",
"SQL",
"query",
"."
] | python | train | 29.297297 |
annoviko/pyclustering | pyclustering/cluster/bang.py | https://github.com/annoviko/pyclustering/blob/98aa0dd89fd36f701668fb1eb29c8fb5662bf7d0/pyclustering/cluster/bang.py#L1194-L1212 | def __store_clustering_results(self, amount_clusters, leaf_blocks):
"""!
@brief Stores clustering results in a convenient way.
@param[in] amount_clusters (uint): Amount of cluster that was allocated during processing.
@param[in] leaf_blocks (list): Leaf BANG-blocks (the smallest ce... | [
"def",
"__store_clustering_results",
"(",
"self",
",",
"amount_clusters",
",",
"leaf_blocks",
")",
":",
"self",
".",
"__clusters",
"=",
"[",
"[",
"]",
"for",
"_",
"in",
"range",
"(",
"amount_clusters",
")",
"]",
"for",
"block",
"in",
"leaf_blocks",
":",
"i... | !
@brief Stores clustering results in a convenient way.
@param[in] amount_clusters (uint): Amount of cluster that was allocated during processing.
@param[in] leaf_blocks (list): Leaf BANG-blocks (the smallest cells). | [
"!"
] | python | valid | 40.157895 |
hydrosquall/tiingo-python | tiingo/api.py | https://github.com/hydrosquall/tiingo-python/blob/9bb98ca9d24f2e4db651cf0590e4b47184546482/tiingo/api.py#L101-L116 | def list_tickers(self, assetType):
"""Return a list of dicts of metadata tickers for all supported tickers
of the specified asset type, as well as metadata about each ticker.
This includes supported date range, the exchange the ticker is traded
on, and the currency the stock ... | [
"def",
"list_tickers",
"(",
"self",
",",
"assetType",
")",
":",
"listing_file_url",
"=",
"\"https://apimedia.tiingo.com/docs/tiingo/daily/supported_tickers.zip\"",
"response",
"=",
"requests",
".",
"get",
"(",
"listing_file_url",
")",
"zipdata",
"=",
"get_zipfile_from_respo... | Return a list of dicts of metadata tickers for all supported tickers
of the specified asset type, as well as metadata about each ticker.
This includes supported date range, the exchange the ticker is traded
on, and the currency the stock is traded on.
Tickers for unrelated... | [
"Return",
"a",
"list",
"of",
"dicts",
"of",
"metadata",
"tickers",
"for",
"all",
"supported",
"tickers",
"of",
"the",
"specified",
"asset",
"type",
"as",
"well",
"as",
"metadata",
"about",
"each",
"ticker",
".",
"This",
"includes",
"supported",
"date",
"rang... | python | test | 54.875 |
Rapptz/discord.py | discord/user.py | https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/user.py#L361-L458 | async def edit(self, **fields):
"""|coro|
Edits the current profile of the client.
If a bot account is used then a password field is optional,
otherwise it is required.
Note
-----
To upload an avatar, a :term:`py:bytes-like object` must be passed in that
... | [
"async",
"def",
"edit",
"(",
"self",
",",
"*",
"*",
"fields",
")",
":",
"try",
":",
"avatar_bytes",
"=",
"fields",
"[",
"'avatar'",
"]",
"except",
"KeyError",
":",
"avatar",
"=",
"self",
".",
"avatar",
"else",
":",
"if",
"avatar_bytes",
"is",
"not",
... | |coro|
Edits the current profile of the client.
If a bot account is used then a password field is optional,
otherwise it is required.
Note
-----
To upload an avatar, a :term:`py:bytes-like object` must be passed in that
represents the image being uploaded. If t... | [
"|coro|"
] | python | train | 33.142857 |
weso/CWR-DataApi | cwr/grammar/field/special.py | https://github.com/weso/CWR-DataApi/blob/f3b6ba8308c901b6ab87073c155c08e30692333c/cwr/grammar/field/special.py#L419-L431 | def lookup_int(values, name=None):
"""
Lookup field which transforms the result into an integer.
:param values: values allowed
:param name: name for the field
:return: grammar for the lookup field
"""
field = basic.lookup(values, name)
field.addParseAction(lambda l: int(l[0]))
ret... | [
"def",
"lookup_int",
"(",
"values",
",",
"name",
"=",
"None",
")",
":",
"field",
"=",
"basic",
".",
"lookup",
"(",
"values",
",",
"name",
")",
"field",
".",
"addParseAction",
"(",
"lambda",
"l",
":",
"int",
"(",
"l",
"[",
"0",
"]",
")",
")",
"ret... | Lookup field which transforms the result into an integer.
:param values: values allowed
:param name: name for the field
:return: grammar for the lookup field | [
"Lookup",
"field",
"which",
"transforms",
"the",
"result",
"into",
"an",
"integer",
"."
] | python | train | 24.384615 |
awslabs/serverless-application-model | samtranslator/swagger/swagger.py | https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/swagger/swagger.py#L86-L97 | def get_method_contents(self, method):
"""
Returns the swagger contents of the given method. This checks to see if a conditional block
has been used inside of the method, and, if so, returns the method contents that are
inside of the conditional.
:param dict method: method dicti... | [
"def",
"get_method_contents",
"(",
"self",
",",
"method",
")",
":",
"if",
"self",
".",
"_CONDITIONAL_IF",
"in",
"method",
":",
"return",
"method",
"[",
"self",
".",
"_CONDITIONAL_IF",
"]",
"[",
"1",
":",
"]",
"return",
"[",
"method",
"]"
] | Returns the swagger contents of the given method. This checks to see if a conditional block
has been used inside of the method, and, if so, returns the method contents that are
inside of the conditional.
:param dict method: method dictionary
:return: list of swagger component dictionari... | [
"Returns",
"the",
"swagger",
"contents",
"of",
"the",
"given",
"method",
".",
"This",
"checks",
"to",
"see",
"if",
"a",
"conditional",
"block",
"has",
"been",
"used",
"inside",
"of",
"the",
"method",
"and",
"if",
"so",
"returns",
"the",
"method",
"contents... | python | train | 43 |
pulseenergy/vacation | vacation/rc.py | https://github.com/pulseenergy/vacation/blob/23c6122590852a5e55d84d366143469af6602839/vacation/rc.py#L9-L13 | def touch():
""" Create a .vacationrc file if none exists. """
if not os.path.isfile(get_rc_path()):
open(get_rc_path(), 'a').close()
print('Created file: {}'.format(get_rc_path())) | [
"def",
"touch",
"(",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"get_rc_path",
"(",
")",
")",
":",
"open",
"(",
"get_rc_path",
"(",
")",
",",
"'a'",
")",
".",
"close",
"(",
")",
"print",
"(",
"'Created file: {}'",
".",
"format",
... | Create a .vacationrc file if none exists. | [
"Create",
"a",
".",
"vacationrc",
"file",
"if",
"none",
"exists",
"."
] | python | train | 40.2 |
quantopian/zipline | zipline/finance/order.py | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/finance/order.py#L108-L122 | def check_triggers(self, price, dt):
"""
Update internal state based on price triggers and the
trade event's price.
"""
stop_reached, limit_reached, sl_stop_reached = \
self.check_order_triggers(price)
if (stop_reached, limit_reached) \
!= (sel... | [
"def",
"check_triggers",
"(",
"self",
",",
"price",
",",
"dt",
")",
":",
"stop_reached",
",",
"limit_reached",
",",
"sl_stop_reached",
"=",
"self",
".",
"check_order_triggers",
"(",
"price",
")",
"if",
"(",
"stop_reached",
",",
"limit_reached",
")",
"!=",
"(... | Update internal state based on price triggers and the
trade event's price. | [
"Update",
"internal",
"state",
"based",
"on",
"price",
"triggers",
"and",
"the",
"trade",
"event",
"s",
"price",
"."
] | python | train | 37.933333 |
jcrist/skein | skein/utils.py | https://github.com/jcrist/skein/blob/16f8b1d3b3d9f79f36e2f152e45893339a1793e8/skein/utils.py#L25-L35 | def lock_file(path):
"""File based lock on ``path``.
Creates a file based lock. When acquired, other processes or threads are
prevented from acquiring the same lock until it is released.
"""
with _paths_lock:
lock = _paths_to_locks.get(path)
if lock is None:
_paths_to_lo... | [
"def",
"lock_file",
"(",
"path",
")",
":",
"with",
"_paths_lock",
":",
"lock",
"=",
"_paths_to_locks",
".",
"get",
"(",
"path",
")",
"if",
"lock",
"is",
"None",
":",
"_paths_to_locks",
"[",
"path",
"]",
"=",
"lock",
"=",
"_FileLock",
"(",
"path",
")",
... | File based lock on ``path``.
Creates a file based lock. When acquired, other processes or threads are
prevented from acquiring the same lock until it is released. | [
"File",
"based",
"lock",
"on",
"path",
"."
] | python | train | 32.727273 |
davenquinn/Attitude | attitude/geom/conics.py | https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/attitude/geom/conics.py#L57-L67 | def contains(ell, p, shell_only=False):
"""
Check to see whether point is inside
conic.
:param exact: Only solutions exactly on conic
are considered (default: False).
"""
v = augment(p)
_ = ell.solve(v)
return N.allclose(_,0) if shell_only else ... | [
"def",
"contains",
"(",
"ell",
",",
"p",
",",
"shell_only",
"=",
"False",
")",
":",
"v",
"=",
"augment",
"(",
"p",
")",
"_",
"=",
"ell",
".",
"solve",
"(",
"v",
")",
"return",
"N",
".",
"allclose",
"(",
"_",
",",
"0",
")",
"if",
"shell_only",
... | Check to see whether point is inside
conic.
:param exact: Only solutions exactly on conic
are considered (default: False). | [
"Check",
"to",
"see",
"whether",
"point",
"is",
"inside",
"conic",
"."
] | python | train | 28.727273 |
rigetti/pyquil | pyquil/api/_base_connection.py | https://github.com/rigetti/pyquil/blob/ec98e453084b0037d69d8c3245f6822a5422593d/pyquil/api/_base_connection.py#L265-L282 | def quilc_compile_payload(quil_program, isa, specs):
"""REST payload for :py:func:`ForestConnection._quilc_compile`"""
if not quil_program:
raise ValueError("You have attempted to compile an empty program."
" Please provide an actual program.")
if not isinstance(quil_program... | [
"def",
"quilc_compile_payload",
"(",
"quil_program",
",",
"isa",
",",
"specs",
")",
":",
"if",
"not",
"quil_program",
":",
"raise",
"ValueError",
"(",
"\"You have attempted to compile an empty program.\"",
"\" Please provide an actual program.\"",
")",
"if",
"not",
"isins... | REST payload for :py:func:`ForestConnection._quilc_compile` | [
"REST",
"payload",
"for",
":",
"py",
":",
"func",
":",
"ForestConnection",
".",
"_quilc_compile"
] | python | train | 42.055556 |
erinxocon/spotify-local | src/spotify_local/utils.py | https://github.com/erinxocon/spotify-local/blob/8188eef221e3d8b9f408ff430d80e74560360459/src/spotify_local/utils.py#L27-L31 | def get_oauth_token():
"""Retrieve a simple OAuth Token for use with the local http client."""
url = "{0}/token".format(DEFAULT_ORIGIN["Origin"])
r = s.get(url=url)
return r.json()["t"] | [
"def",
"get_oauth_token",
"(",
")",
":",
"url",
"=",
"\"{0}/token\"",
".",
"format",
"(",
"DEFAULT_ORIGIN",
"[",
"\"Origin\"",
"]",
")",
"r",
"=",
"s",
".",
"get",
"(",
"url",
"=",
"url",
")",
"return",
"r",
".",
"json",
"(",
")",
"[",
"\"t\"",
"]"... | Retrieve a simple OAuth Token for use with the local http client. | [
"Retrieve",
"a",
"simple",
"OAuth",
"Token",
"for",
"use",
"with",
"the",
"local",
"http",
"client",
"."
] | python | train | 39.4 |
angr/angr | angr/analyses/cfg/cfg_fast.py | https://github.com/angr/angr/blob/4e2f97d56af5419ee73bdb30482c8dd8ff5f3e40/angr/analyses/cfg/cfg_fast.py#L2582-L2599 | def _remove_node(self, node):
"""
Remove a CFGNode from self.graph as well as from the function manager (if it is the beginning of a function)
:param CFGNode node: The CFGNode to remove from the graph.
:return: None
"""
self.graph.remove_node(node)
if node.addr ... | [
"def",
"_remove_node",
"(",
"self",
",",
"node",
")",
":",
"self",
".",
"graph",
".",
"remove_node",
"(",
"node",
")",
"if",
"node",
".",
"addr",
"in",
"self",
".",
"_nodes",
":",
"del",
"self",
".",
"_nodes",
"[",
"node",
".",
"addr",
"]",
"# We w... | Remove a CFGNode from self.graph as well as from the function manager (if it is the beginning of a function)
:param CFGNode node: The CFGNode to remove from the graph.
:return: None | [
"Remove",
"a",
"CFGNode",
"from",
"self",
".",
"graph",
"as",
"well",
"as",
"from",
"the",
"function",
"manager",
"(",
"if",
"it",
"is",
"the",
"beginning",
"of",
"a",
"function",
")"
] | python | train | 33.888889 |
koalalorenzo/python-digitalocean | digitalocean/LoadBalancer.py | https://github.com/koalalorenzo/python-digitalocean/blob/d0221b57856fb1e131cafecf99d826f7b07a947c/digitalocean/LoadBalancer.py#L322-L335 | def remove_forwarding_rules(self, forwarding_rules):
"""
Removes existing forwarding rules from a LoadBalancer.
Args:
forwarding_rules (obj:`list`): A list of `ForwrdingRules` objects
"""
rules_dict = [rule.__dict__ for rule in forwarding_rules]
return self.... | [
"def",
"remove_forwarding_rules",
"(",
"self",
",",
"forwarding_rules",
")",
":",
"rules_dict",
"=",
"[",
"rule",
".",
"__dict__",
"for",
"rule",
"in",
"forwarding_rules",
"]",
"return",
"self",
".",
"get_data",
"(",
"\"load_balancers/%s/forwarding_rules/\"",
"%",
... | Removes existing forwarding rules from a LoadBalancer.
Args:
forwarding_rules (obj:`list`): A list of `ForwrdingRules` objects | [
"Removes",
"existing",
"forwarding",
"rules",
"from",
"a",
"LoadBalancer",
"."
] | python | valid | 33.142857 |
aws/sagemaker-python-sdk | src/sagemaker/local/entities.py | https://github.com/aws/sagemaker-python-sdk/blob/a9e724c7d3f5572b68c3903548c792a59d99799a/src/sagemaker/local/entities.py#L193-L230 | def _get_container_environment(self, **kwargs):
"""Get all the Environment variables that will be passed to the container
Certain input fields such as BatchStrategy have different values for the API vs the Environment
variables, such as SingleRecord vs SINGLE_RECORD. This method also handles th... | [
"def",
"_get_container_environment",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"environment",
"=",
"{",
"}",
"environment",
".",
"update",
"(",
"self",
".",
"primary_container",
"[",
"'Environment'",
"]",
")",
"environment",
"[",
"'SAGEMAKER_BATCH'",
"]"... | Get all the Environment variables that will be passed to the container
Certain input fields such as BatchStrategy have different values for the API vs the Environment
variables, such as SingleRecord vs SINGLE_RECORD. This method also handles this conversion.
Args:
**kwargs: existin... | [
"Get",
"all",
"the",
"Environment",
"variables",
"that",
"will",
"be",
"passed",
"to",
"the",
"container"
] | python | train | 46.842105 |
offu/WeRoBot | werobot/config.py | https://github.com/offu/WeRoBot/blob/fd42109105b03f9acf45ebd9dcabb9d5cff98f3c/werobot/config.py#L25-L37 | def from_pyfile(self, filename):
"""
在一个 Python 文件中读取配置。
:param filename: 配置文件的文件名
:return: 如果读取成功,返回 ``True``,如果失败,会抛出错误异常
"""
d = types.ModuleType('config')
d.__file__ = filename
with open(filename) as config_file:
exec(compile(config_file.r... | [
"def",
"from_pyfile",
"(",
"self",
",",
"filename",
")",
":",
"d",
"=",
"types",
".",
"ModuleType",
"(",
"'config'",
")",
"d",
".",
"__file__",
"=",
"filename",
"with",
"open",
"(",
"filename",
")",
"as",
"config_file",
":",
"exec",
"(",
"compile",
"("... | 在一个 Python 文件中读取配置。
:param filename: 配置文件的文件名
:return: 如果读取成功,返回 ``True``,如果失败,会抛出错误异常 | [
"在一个",
"Python",
"文件中读取配置。"
] | python | train | 30.230769 |
cltl/KafNafParserPy | KafNafParserPy/KafNafParserMod.py | https://github.com/cltl/KafNafParserPy/blob/9bc32e803c176404b255ba317479b8780ed5f569/KafNafParserPy/KafNafParserMod.py#L1110-L1119 | def add_predicate(self, predicate_obj):
"""
Adds a predicate to the semantic layer
@type predicate_obj: L{Cpredicate}
@param predicate_obj: the predicate object
"""
if self.srl_layer is None:
self.srl_layer = Csrl()
self.root.append(self.srl_layer.... | [
"def",
"add_predicate",
"(",
"self",
",",
"predicate_obj",
")",
":",
"if",
"self",
".",
"srl_layer",
"is",
"None",
":",
"self",
".",
"srl_layer",
"=",
"Csrl",
"(",
")",
"self",
".",
"root",
".",
"append",
"(",
"self",
".",
"srl_layer",
".",
"get_node",... | Adds a predicate to the semantic layer
@type predicate_obj: L{Cpredicate}
@param predicate_obj: the predicate object | [
"Adds",
"a",
"predicate",
"to",
"the",
"semantic",
"layer"
] | python | train | 37.4 |
brmscheiner/ideogram | ideogram/writer.py | https://github.com/brmscheiner/ideogram/blob/422bf566c51fd56f7bbb6e75b16d18d52b4c7568/ideogram/writer.py#L199-L209 | def noEmptyNests(node):
'''recursively make sure that no dictionaries inside node contain empty children lists '''
if type(node)==list:
for i in node:
noEmptyNests(i)
if type(node)==dict:
for i in node.values():
noEmptyNests(i)
if node["children"] == []:
... | [
"def",
"noEmptyNests",
"(",
"node",
")",
":",
"if",
"type",
"(",
"node",
")",
"==",
"list",
":",
"for",
"i",
"in",
"node",
":",
"noEmptyNests",
"(",
"i",
")",
"if",
"type",
"(",
"node",
")",
"==",
"dict",
":",
"for",
"i",
"in",
"node",
".",
"va... | recursively make sure that no dictionaries inside node contain empty children lists | [
"recursively",
"make",
"sure",
"that",
"no",
"dictionaries",
"inside",
"node",
"contain",
"empty",
"children",
"lists"
] | python | train | 32.181818 |
astroduff/commah | commah/commah.py | https://github.com/astroduff/commah/blob/3ec70338c5123a053c79ddcf2cb3beac26bc9137/commah/commah.py#L441-L480 | def MAH(z, zi, Mi, **cosmo):
""" Calculate mass accretion history by looping function acc_rate
over redshift steps 'z' for halo of mass 'Mi' at redshift 'zi'
Parameters
----------
z : float / numpy array
Redshift to output MAH over. Note zi<z always
zi : float
Redshift
M... | [
"def",
"MAH",
"(",
"z",
",",
"zi",
",",
"Mi",
",",
"*",
"*",
"cosmo",
")",
":",
"# Ensure that z is a 1D NumPy array",
"z",
"=",
"np",
".",
"array",
"(",
"z",
",",
"ndmin",
"=",
"1",
",",
"dtype",
"=",
"float",
")",
"# Create a full array",
"dMdt_array... | Calculate mass accretion history by looping function acc_rate
over redshift steps 'z' for halo of mass 'Mi' at redshift 'zi'
Parameters
----------
z : float / numpy array
Redshift to output MAH over. Note zi<z always
zi : float
Redshift
Mi : float
Halo mass at redshi... | [
"Calculate",
"mass",
"accretion",
"history",
"by",
"looping",
"function",
"acc_rate",
"over",
"redshift",
"steps",
"z",
"for",
"halo",
"of",
"mass",
"Mi",
"at",
"redshift",
"zi"
] | python | train | 30.675 |
decryptus/sonicprobe | sonicprobe/helpers.py | https://github.com/decryptus/sonicprobe/blob/72f73f3a40d2982d79ad68686e36aa31d94b76f8/sonicprobe/helpers.py#L259-L269 | def file_writelines_flush_sync(path, lines):
"""
Fill file at @path with @lines then flush all buffers
(Python and system buffers)
"""
fp = open(path, 'w')
try:
fp.writelines(lines)
flush_sync_file_object(fp)
finally:
fp.close() | [
"def",
"file_writelines_flush_sync",
"(",
"path",
",",
"lines",
")",
":",
"fp",
"=",
"open",
"(",
"path",
",",
"'w'",
")",
"try",
":",
"fp",
".",
"writelines",
"(",
"lines",
")",
"flush_sync_file_object",
"(",
"fp",
")",
"finally",
":",
"fp",
".",
"clo... | Fill file at @path with @lines then flush all buffers
(Python and system buffers) | [
"Fill",
"file",
"at"
] | python | train | 24.545455 |
tbielawa/bitmath | bitmath/__init__.py | https://github.com/tbielawa/bitmath/blob/58ad3ac5f076cc6e53f36a91af055c6028c850a5/bitmath/__init__.py#L1201-L1331 | def query_device_capacity(device_fd):
"""Create bitmath instances of the capacity of a system block device
Make one or more ioctl request to query the capacity of a block
device. Perform any processing required to compute the final capacity
value. Return the device capacity in bytes as a :class:`bitmath.Byte`
inst... | [
"def",
"query_device_capacity",
"(",
"device_fd",
")",
":",
"if",
"os_name",
"(",
")",
"!=",
"'posix'",
":",
"raise",
"NotImplementedError",
"(",
"\"'bitmath.query_device_capacity' is not supported on this platform: %s\"",
"%",
"os_name",
"(",
")",
")",
"s",
"=",
"os"... | Create bitmath instances of the capacity of a system block device
Make one or more ioctl request to query the capacity of a block
device. Perform any processing required to compute the final capacity
value. Return the device capacity in bytes as a :class:`bitmath.Byte`
instance.
Thanks to the following resources for ... | [
"Create",
"bitmath",
"instances",
"of",
"the",
"capacity",
"of",
"a",
"system",
"block",
"device"
] | python | train | 45.854962 |
EventTeam/beliefs | src/beliefs/cells/posets.py | https://github.com/EventTeam/beliefs/blob/c07d22b61bebeede74a72800030dde770bf64208/src/beliefs/cells/posets.py#L98-L106 | def get_boundaries(self):
"""
Returns just the upper and lower boundaries
[upper, lower] representing the most general positive
boundaries and the most specific lower boundaries
"""
if not self.__values_computed:
self.__compute_values()
return set(self... | [
"def",
"get_boundaries",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"__values_computed",
":",
"self",
".",
"__compute_values",
"(",
")",
"return",
"set",
"(",
"self",
".",
"upper",
")",
",",
"set",
"(",
"self",
".",
"lower",
")"
] | Returns just the upper and lower boundaries
[upper, lower] representing the most general positive
boundaries and the most specific lower boundaries | [
"Returns",
"just",
"the",
"upper",
"and",
"lower",
"boundaries",
"[",
"upper",
"lower",
"]",
"representing",
"the",
"most",
"general",
"positive",
"boundaries",
"and",
"the",
"most",
"specific",
"lower",
"boundaries"
] | python | train | 37.333333 |
google/tangent | tangent/grad_util.py | https://github.com/google/tangent/blob/6533e83af09de7345d1b438512679992f080dcc9/tangent/grad_util.py#L393-L435 | def _create_joint(fwdbwd, func, wrt, input_derivative):
"""Create a user-friendly gradient function.
By default, gradient functions expect the stack to be passed to them
explicitly. This function modifies the function so that the stack doesn't
need to be passed and gets initialized in the function body instead... | [
"def",
"_create_joint",
"(",
"fwdbwd",
",",
"func",
",",
"wrt",
",",
"input_derivative",
")",
":",
"# Correct return to be a non-tuple if there's only one element",
"retval",
"=",
"fwdbwd",
".",
"body",
"[",
"-",
"1",
"]",
"if",
"len",
"(",
"retval",
".",
"value... | Create a user-friendly gradient function.
By default, gradient functions expect the stack to be passed to them
explicitly. This function modifies the function so that the stack doesn't
need to be passed and gets initialized in the function body instead.
For consistency, gradient functions always return a tupl... | [
"Create",
"a",
"user",
"-",
"friendly",
"gradient",
"function",
"."
] | python | train | 38.976744 |
kata198/AdvancedHTMLParser | AdvancedHTMLParser/Parser.py | https://github.com/kata198/AdvancedHTMLParser/blob/06aeea5d8e2ea86e155aae0fc237623d3e9b7f9d/AdvancedHTMLParser/Parser.py#L972-L995 | def createBlocksFromHTML(cls, html, encoding='utf-8'):
'''
createBlocksFromHTML - Returns the root level node (unless multiple nodes), and
a list of "blocks" added (text and nodes).
@return list< str/AdvancedTag > - List of blocks created. May be strings (text nodes) or... | [
"def",
"createBlocksFromHTML",
"(",
"cls",
",",
"html",
",",
"encoding",
"=",
"'utf-8'",
")",
":",
"parser",
"=",
"cls",
"(",
"encoding",
"=",
"encoding",
")",
"parser",
".",
"parseStr",
"(",
"html",
")",
"rootNode",
"=",
"parser",
".",
"getRoot",
"(",
... | createBlocksFromHTML - Returns the root level node (unless multiple nodes), and
a list of "blocks" added (text and nodes).
@return list< str/AdvancedTag > - List of blocks created. May be strings (text nodes) or AdvancedTag (tags)
NOTE:
Results may be checked b... | [
"createBlocksFromHTML",
"-",
"Returns",
"the",
"root",
"level",
"node",
"(",
"unless",
"multiple",
"nodes",
")",
"and",
"a",
"list",
"of",
"blocks",
"added",
"(",
"text",
"and",
"nodes",
")",
"."
] | python | train | 29.125 |
dmlc/gluon-nlp | scripts/parsing/common/utils.py | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/parsing/common/utils.py#L275-L320 | def bilinear(x, W, y, input_size, seq_len, batch_size, num_outputs=1, bias_x=False, bias_y=False):
"""Do xWy
Parameters
----------
x : NDArray
(input_size x seq_len) x batch_size
W : NDArray
(num_outputs x ny) x nx
y : NDArray
(input_size x seq_len) x batch_size
inpu... | [
"def",
"bilinear",
"(",
"x",
",",
"W",
",",
"y",
",",
"input_size",
",",
"seq_len",
",",
"batch_size",
",",
"num_outputs",
"=",
"1",
",",
"bias_x",
"=",
"False",
",",
"bias_y",
"=",
"False",
")",
":",
"if",
"bias_x",
":",
"x",
"=",
"nd",
".",
"co... | Do xWy
Parameters
----------
x : NDArray
(input_size x seq_len) x batch_size
W : NDArray
(num_outputs x ny) x nx
y : NDArray
(input_size x seq_len) x batch_size
input_size : int
input dimension
seq_len : int
sequence length
batch_size : int
... | [
"Do",
"xWy"
] | python | train | 30.673913 |
skorch-dev/skorch | skorch/callbacks/logging.py | https://github.com/skorch-dev/skorch/blob/5b9b8b7b7712cb6e5aaa759d9608ea6269d5bcd3/skorch/callbacks/logging.py#L109-L130 | def format_row(self, row, key, color):
"""For a given row from the table, format it (i.e. floating
points and color if applicable).
"""
value = row[key]
if isinstance(value, bool) or value is None:
return '+' if value else ''
if not isinstance(value, Number... | [
"def",
"format_row",
"(",
"self",
",",
"row",
",",
"key",
",",
"color",
")",
":",
"value",
"=",
"row",
"[",
"key",
"]",
"if",
"isinstance",
"(",
"value",
",",
"bool",
")",
"or",
"value",
"is",
"None",
":",
"return",
"'+'",
"if",
"value",
"else",
... | For a given row from the table, format it (i.e. floating
points and color if applicable). | [
"For",
"a",
"given",
"row",
"from",
"the",
"table",
"format",
"it",
"(",
"i",
".",
"e",
".",
"floating",
"points",
"and",
"color",
"if",
"applicable",
")",
"."
] | python | train | 32.227273 |
Erotemic/utool | utool/util_assert.py | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_assert.py#L213-L241 | def assert_almost_eq(arr_test, arr_target, thresh=1E-11):
r"""
Args:
arr_test (ndarray or list):
arr_target (ndarray or list):
thresh (scalar or ndarray or list):
"""
if util_arg.NO_ASSERTS:
return
import utool as ut
arr1 = np.array(arr_test)
arr2 = np.array(a... | [
"def",
"assert_almost_eq",
"(",
"arr_test",
",",
"arr_target",
",",
"thresh",
"=",
"1E-11",
")",
":",
"if",
"util_arg",
".",
"NO_ASSERTS",
":",
"return",
"import",
"utool",
"as",
"ut",
"arr1",
"=",
"np",
".",
"array",
"(",
"arr_test",
")",
"arr2",
"=",
... | r"""
Args:
arr_test (ndarray or list):
arr_target (ndarray or list):
thresh (scalar or ndarray or list): | [
"r",
"Args",
":",
"arr_test",
"(",
"ndarray",
"or",
"list",
")",
":",
"arr_target",
"(",
"ndarray",
"or",
"list",
")",
":",
"thresh",
"(",
"scalar",
"or",
"ndarray",
"or",
"list",
")",
":"
] | python | train | 33.896552 |
mdiener/grace | grace/py27/pyjsdoc.py | https://github.com/mdiener/grace/blob/2dab13a2cf636da5da989904c5885166fc94d36d/grace/py27/pyjsdoc.py#L257-L264 | def split_tag(section):
"""
Split the JSDoc tag text (everything following the @) at the first
whitespace. Returns a tuple of (tagname, body).
"""
splitval = re.split('\s+', section, 1)
tag, body = len(splitval) > 1 and splitval or (splitval[0], '')
return tag.strip(), body.strip() | [
"def",
"split_tag",
"(",
"section",
")",
":",
"splitval",
"=",
"re",
".",
"split",
"(",
"'\\s+'",
",",
"section",
",",
"1",
")",
"tag",
",",
"body",
"=",
"len",
"(",
"splitval",
")",
">",
"1",
"and",
"splitval",
"or",
"(",
"splitval",
"[",
"0",
"... | Split the JSDoc tag text (everything following the @) at the first
whitespace. Returns a tuple of (tagname, body). | [
"Split",
"the",
"JSDoc",
"tag",
"text",
"(",
"everything",
"following",
"the"
] | python | train | 38 |
airspeed-velocity/asv | asv/feed.py | https://github.com/airspeed-velocity/asv/blob/d23bb8b74e8adacbfa3cf5724bda55fb39d56ba6/asv/feed.py#L89-L169 | def write_atom(dest, entries, author, title, address, updated=None, link=None,
language="en"):
"""
Write an atom feed to a file.
Parameters
----------
dest : str
Destination file path, or a file-like object
entries : list of FeedEntry
Feed entries.
author : st... | [
"def",
"write_atom",
"(",
"dest",
",",
"entries",
",",
"author",
",",
"title",
",",
"address",
",",
"updated",
"=",
"None",
",",
"link",
"=",
"None",
",",
"language",
"=",
"\"en\"",
")",
":",
"if",
"updated",
"is",
"None",
":",
"if",
"entries",
":",
... | Write an atom feed to a file.
Parameters
----------
dest : str
Destination file path, or a file-like object
entries : list of FeedEntry
Feed entries.
author : str
Author of the feed.
title : str
Title for the feed.
address : str
Address (domain name o... | [
"Write",
"an",
"atom",
"feed",
"to",
"a",
"file",
"."
] | python | train | 26.320988 |
akfullfo/taskforce | taskforce/utils.py | https://github.com/akfullfo/taskforce/blob/bc6dd744bd33546447d085dbd18a350532220193/taskforce/utils.py#L373-L386 | def sys_maxfd():
"""
Returns the maximum file descriptor limit. This is guaranteed to
return a useful int value.
"""
maxfd = None
try:
maxfd = int(resource.getrlimit(resource.RLIMIT_NOFILE)[0])
if maxfd == resource.RLIM_INFINITY: #... | [
"def",
"sys_maxfd",
"(",
")",
":",
"maxfd",
"=",
"None",
"try",
":",
"maxfd",
"=",
"int",
"(",
"resource",
".",
"getrlimit",
"(",
"resource",
".",
"RLIMIT_NOFILE",
")",
"[",
"0",
"]",
")",
"if",
"maxfd",
"==",
"resource",
".",
"RLIM_INFINITY",
":",
"... | Returns the maximum file descriptor limit. This is guaranteed to
return a useful int value. | [
"Returns",
"the",
"maximum",
"file",
"descriptor",
"limit",
".",
"This",
"is",
"guaranteed",
"to",
"return",
"a",
"useful",
"int",
"value",
"."
] | python | train | 31.857143 |
bitesofcode/projexui | projexui/widgets/xtablewidget.py | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xtablewidget.py#L84-L116 | def dataCollector( self ):
"""
Returns a method or function that will be used to collect mime data \
for a list of tablewidgetitems. If set, the method should accept a \
single argument for a list of items and then return a QMimeData \
instance.
:usage |fro... | [
"def",
"dataCollector",
"(",
"self",
")",
":",
"func",
"=",
"None",
"if",
"(",
"self",
".",
"_dataCollectorRef",
")",
":",
"func",
"=",
"self",
".",
"_dataCollectorRef",
"(",
")",
"if",
"(",
"not",
"func",
")",
":",
"self",
".",
"_dataCollectorRef",
"=... | Returns a method or function that will be used to collect mime data \
for a list of tablewidgetitems. If set, the method should accept a \
single argument for a list of items and then return a QMimeData \
instance.
:usage |from projexui.qt.QtCore import QMimeData, QWidget
... | [
"Returns",
"a",
"method",
"or",
"function",
"that",
"will",
"be",
"used",
"to",
"collect",
"mime",
"data",
"\\",
"for",
"a",
"list",
"of",
"tablewidgetitems",
".",
"If",
"set",
"the",
"method",
"should",
"accept",
"a",
"\\",
"single",
"argument",
"for",
... | python | train | 39.181818 |
saltstack/salt | salt/utils/saltclass.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/saltclass.py#L86-L109 | def get_class_from_file(_file, saltclass_path):
'''
Converts the absolute path to a saltclass file back to the dotted notation.
.. code-block:: python
print(get_class_from_file('/srv/saltclass/classes/services/nginx/init.yml', '/srv/saltclass'))
# services.nginx
:param str _file: Absolu... | [
"def",
"get_class_from_file",
"(",
"_file",
",",
"saltclass_path",
")",
":",
"# remove classes path prefix",
"_file",
"=",
"_file",
"[",
"len",
"(",
"os",
".",
"path",
".",
"join",
"(",
"saltclass_path",
",",
"'classes'",
")",
")",
"+",
"len",
"(",
"os",
"... | Converts the absolute path to a saltclass file back to the dotted notation.
.. code-block:: python
print(get_class_from_file('/srv/saltclass/classes/services/nginx/init.yml', '/srv/saltclass'))
# services.nginx
:param str _file: Absolute path to file
:param str saltclass_path: Root to saltc... | [
"Converts",
"the",
"absolute",
"path",
"to",
"a",
"saltclass",
"file",
"back",
"to",
"the",
"dotted",
"notation",
"."
] | python | train | 32.166667 |
tornadoweb/tornado | tornado/routing.py | https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/routing.py#L334-L348 | def add_rules(self, rules: _RuleList) -> None:
"""Appends new rules to the router.
:arg rules: a list of Rule instances (or tuples of arguments, which are
passed to Rule constructor).
"""
for rule in rules:
if isinstance(rule, (tuple, list)):
asse... | [
"def",
"add_rules",
"(",
"self",
",",
"rules",
":",
"_RuleList",
")",
"->",
"None",
":",
"for",
"rule",
"in",
"rules",
":",
"if",
"isinstance",
"(",
"rule",
",",
"(",
"tuple",
",",
"list",
")",
")",
":",
"assert",
"len",
"(",
"rule",
")",
"in",
"... | Appends new rules to the router.
:arg rules: a list of Rule instances (or tuples of arguments, which are
passed to Rule constructor). | [
"Appends",
"new",
"rules",
"to",
"the",
"router",
"."
] | python | train | 38 |
rahiel/telegram-send | telegram_send.py | https://github.com/rahiel/telegram-send/blob/019162232bdc4fc9e986ffcf6e4c5572306c0b82/telegram_send.py#L135-L226 | def send(messages=None, conf=None, parse_mode=None, disable_web_page_preview=False, files=None, images=None,
captions=None, locations=None, timeout=30):
"""Send data over Telegram. All arguments are optional.
Always use this function with explicit keyword arguments. So
`send(messages=["Hello!"])` ... | [
"def",
"send",
"(",
"messages",
"=",
"None",
",",
"conf",
"=",
"None",
",",
"parse_mode",
"=",
"None",
",",
"disable_web_page_preview",
"=",
"False",
",",
"files",
"=",
"None",
",",
"images",
"=",
"None",
",",
"captions",
"=",
"None",
",",
"locations",
... | Send data over Telegram. All arguments are optional.
Always use this function with explicit keyword arguments. So
`send(messages=["Hello!"])` instead of `send(["Hello!"])` as the latter
will *break* when I change the order of the arguments.
The `file` type is the [file object][] returned by the `open(... | [
"Send",
"data",
"over",
"Telegram",
".",
"All",
"arguments",
"are",
"optional",
"."
] | python | train | 42.902174 |
github/octodns | octodns/provider/ovh.py | https://github.com/github/octodns/blob/65ee60491e22e6bb0a2aa08f7069c6ecf6c3fee6/octodns/provider/ovh.py#L393-L403 | def create_record(self, zone_name, params):
"""
Create a record
:param zone_name: Name of the zone
:param params: {'fieldType': 'A', 'ttl': 60, 'subDomain': 'www',
'target': '1.2.3.4'
"""
self.log.debug('Create record: zone: %s, id %s', zone_name,
... | [
"def",
"create_record",
"(",
"self",
",",
"zone_name",
",",
"params",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"'Create record: zone: %s, id %s'",
",",
"zone_name",
",",
"params",
")",
"return",
"self",
".",
"_client",
".",
"post",
"(",
"'/domain/zon... | Create a record
:param zone_name: Name of the zone
:param params: {'fieldType': 'A', 'ttl': 60, 'subDomain': 'www',
'target': '1.2.3.4' | [
"Create",
"a",
"record",
":",
"param",
"zone_name",
":",
"Name",
"of",
"the",
"zone",
":",
"param",
"params",
":",
"{",
"fieldType",
":",
"A",
"ttl",
":",
"60",
"subDomain",
":",
"www",
"target",
":",
"1",
".",
"2",
".",
"3",
".",
"4"
] | python | train | 40.363636 |
MozillaSecurity/laniakea | laniakea/core/providers/ec2/manager.py | https://github.com/MozillaSecurity/laniakea/blob/7e80adc6ae92c6c1332d4c08473bb271fb3b6833/laniakea/core/providers/ec2/manager.py#L94-L144 | def create_on_demand(self,
instance_type='default',
tags=None,
root_device_type='ebs',
size='default',
vol_type='gp2',
delete_on_termination=False):
"""Create one... | [
"def",
"create_on_demand",
"(",
"self",
",",
"instance_type",
"=",
"'default'",
",",
"tags",
"=",
"None",
",",
"root_device_type",
"=",
"'ebs'",
",",
"size",
"=",
"'default'",
",",
"vol_type",
"=",
"'gp2'",
",",
"delete_on_termination",
"=",
"False",
")",
":... | Create one or more EC2 on-demand instances.
:param size: Size of root device
:type size: int
:param delete_on_termination:
:type delete_on_termination: boolean
:param vol_type:
:type vol_type: str
:param root_device_type: The type of the root device.
:typ... | [
"Create",
"one",
"or",
"more",
"EC2",
"on",
"-",
"demand",
"instances",
"."
] | python | train | 39.666667 |
kkroening/ffmpeg-python | ffmpeg/_run.py | https://github.com/kkroening/ffmpeg-python/blob/ac111dc3a976ddbb872bc7d6d4fe24a267c1a956/ffmpeg/_run.py#L266-L296 | def run(
stream_spec, cmd='ffmpeg', capture_stdout=False, capture_stderr=False, input=None,
quiet=False, overwrite_output=False):
"""Invoke ffmpeg for the supplied node graph.
Args:
capture_stdout: if True, capture stdout (to be used with
``pipe:`` ffmpeg outputs).
c... | [
"def",
"run",
"(",
"stream_spec",
",",
"cmd",
"=",
"'ffmpeg'",
",",
"capture_stdout",
"=",
"False",
",",
"capture_stderr",
"=",
"False",
",",
"input",
"=",
"None",
",",
"quiet",
"=",
"False",
",",
"overwrite_output",
"=",
"False",
")",
":",
"process",
"=... | Invoke ffmpeg for the supplied node graph.
Args:
capture_stdout: if True, capture stdout (to be used with
``pipe:`` ffmpeg outputs).
capture_stderr: if True, capture stderr.
quiet: shorthand for setting ``capture_stdout`` and ``capture_stderr``.
input: text to be sent to... | [
"Invoke",
"ffmpeg",
"for",
"the",
"supplied",
"node",
"graph",
"."
] | python | train | 34.806452 |
xflows/rdm | rdm/wrappers/wordification/wordification.py | https://github.com/xflows/rdm/blob/d984e2a0297e5fa8d799953bbd0dba79b05d403d/rdm/wrappers/wordification/wordification.py#L175-L203 | def calculate_weights(self, measure='tfidf'):
"""
Counts word frequency and calculates tf-idf values for words in every document.
:param measure: example weights approach (can be one of ``tfidf, binary, tf``).
"""
from math import log
# TODO replace with spipy matri... | [
"def",
"calculate_weights",
"(",
"self",
",",
"measure",
"=",
"'tfidf'",
")",
":",
"from",
"math",
"import",
"log",
"# TODO replace with spipy matrices (and calculate with scikit)",
"if",
"measure",
"==",
"'tfidf'",
":",
"self",
".",
"calculate_idf",
"(",
")",
"for"... | Counts word frequency and calculates tf-idf values for words in every document.
:param measure: example weights approach (can be one of ``tfidf, binary, tf``). | [
"Counts",
"word",
"frequency",
"and",
"calculates",
"tf",
"-",
"idf",
"values",
"for",
"words",
"in",
"every",
"document",
"."
] | python | train | 35 |
Fantomas42/django-blog-zinnia | zinnia/views/search.py | https://github.com/Fantomas42/django-blog-zinnia/blob/b4949304b104a8e1a7a7a0773cbfd024313c3a15/zinnia/views/search.py#L20-L35 | def get_queryset(self):
"""
Overridde the get_queryset method to
do some validations and build the search queryset.
"""
entries = Entry.published.none()
if self.request.GET:
self.pattern = self.request.GET.get('pattern', '')
if len(self.pattern) <... | [
"def",
"get_queryset",
"(",
"self",
")",
":",
"entries",
"=",
"Entry",
".",
"published",
".",
"none",
"(",
")",
"if",
"self",
".",
"request",
".",
"GET",
":",
"self",
".",
"pattern",
"=",
"self",
".",
"request",
".",
"GET",
".",
"get",
"(",
"'patte... | Overridde the get_queryset method to
do some validations and build the search queryset. | [
"Overridde",
"the",
"get_queryset",
"method",
"to",
"do",
"some",
"validations",
"and",
"build",
"the",
"search",
"queryset",
"."
] | python | train | 33.875 |
elastic/elasticsearch-py | elasticsearch/client/xpack/watcher.py | https://github.com/elastic/elasticsearch-py/blob/2aab285c8f506f3863cbdaba3c90a685c510ba00/elasticsearch/client/xpack/watcher.py#L63-L76 | def execute_watch(self, id=None, body=None, params=None):
"""
`<http://www.elastic.co/guide/en/elasticsearch/reference/current/watcher-api-execute-watch.html>`_
:arg id: Watch ID
:arg body: Execution control
:arg debug: indicates whether the watch should execute in debug mode
... | [
"def",
"execute_watch",
"(",
"self",
",",
"id",
"=",
"None",
",",
"body",
"=",
"None",
",",
"params",
"=",
"None",
")",
":",
"return",
"self",
".",
"transport",
".",
"perform_request",
"(",
"\"PUT\"",
",",
"_make_path",
"(",
"\"_watcher\"",
",",
"\"watch... | `<http://www.elastic.co/guide/en/elasticsearch/reference/current/watcher-api-execute-watch.html>`_
:arg id: Watch ID
:arg body: Execution control
:arg debug: indicates whether the watch should execute in debug mode | [
"<http",
":",
"//",
"www",
".",
"elastic",
".",
"co",
"/",
"guide",
"/",
"en",
"/",
"elasticsearch",
"/",
"reference",
"/",
"current",
"/",
"watcher",
"-",
"api",
"-",
"execute",
"-",
"watch",
".",
"html",
">",
"_"
] | python | train | 35.928571 |
ConsenSys/mythril-classic | mythril/laser/ethereum/state/global_state.py | https://github.com/ConsenSys/mythril-classic/blob/27af71c34b2ce94f4fae5613ec457f93df1a8f56/mythril/laser/ethereum/state/global_state.py#L83-L90 | def get_current_instruction(self) -> Dict:
"""Gets the current instruction for this GlobalState.
:return:
"""
instructions = self.environment.code.instruction_list
return instructions[self.mstate.pc] | [
"def",
"get_current_instruction",
"(",
"self",
")",
"->",
"Dict",
":",
"instructions",
"=",
"self",
".",
"environment",
".",
"code",
".",
"instruction_list",
"return",
"instructions",
"[",
"self",
".",
"mstate",
".",
"pc",
"]"
] | Gets the current instruction for this GlobalState.
:return: | [
"Gets",
"the",
"current",
"instruction",
"for",
"this",
"GlobalState",
"."
] | python | train | 29.25 |
agile-geoscience/striplog | striplog/striplog.py | https://github.com/agile-geoscience/striplog/blob/8033b673a151f96c29802b43763e863519a3124c/striplog/striplog.py#L1447-L1571 | def plot(self,
legend=None,
width=1.5,
ladder=True,
aspect=10,
ticks=(1, 10),
match_only=None,
ax=None,
return_fig=False,
colour=None,
cmap='viridis',
default=None,
... | [
"def",
"plot",
"(",
"self",
",",
"legend",
"=",
"None",
",",
"width",
"=",
"1.5",
",",
"ladder",
"=",
"True",
",",
"aspect",
"=",
"10",
",",
"ticks",
"=",
"(",
"1",
",",
"10",
")",
",",
"match_only",
"=",
"None",
",",
"ax",
"=",
"None",
",",
... | Hands-free plotting.
Args:
legend (Legend): The Legend to use for colours, etc.
width (int): The width of the plot, in inches. Default 1.
ladder (bool): Whether to use widths or not. Default False.
aspect (int): The aspect ratio of the plot. Default 10.
... | [
"Hands",
"-",
"free",
"plotting",
"."
] | python | test | 35.168 |
inveniosoftware/invenio-migrator | invenio_migrator/records.py | https://github.com/inveniosoftware/invenio-migrator/blob/6902c6968a39b747d15e32363f43b7dffe2622c2/invenio_migrator/records.py#L143-L150 | def delete_record(cls, record):
"""Delete a record and it's persistent identifiers."""
record.delete()
PersistentIdentifier.query.filter_by(
object_type='rec', object_uuid=record.id,
).update({PersistentIdentifier.status: PIDStatus.DELETED})
cls.delete_buckets(record)... | [
"def",
"delete_record",
"(",
"cls",
",",
"record",
")",
":",
"record",
".",
"delete",
"(",
")",
"PersistentIdentifier",
".",
"query",
".",
"filter_by",
"(",
"object_type",
"=",
"'rec'",
",",
"object_uuid",
"=",
"record",
".",
"id",
",",
")",
".",
"update... | Delete a record and it's persistent identifiers. | [
"Delete",
"a",
"record",
"and",
"it",
"s",
"persistent",
"identifiers",
"."
] | python | test | 42.625 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.