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 |
|---|---|---|---|---|---|---|---|---|---|
mitsei/dlkit | dlkit/json_/commenting/sessions.py | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/json_/commenting/sessions.py#L2596-L2615 | def is_descendant_of_book(self, id_, book_id):
"""Tests if an ``Id`` is a descendant of a book.
arg: id (osid.id.Id): an ``Id``
arg: book_id (osid.id.Id): the ``Id`` of a book
return: (boolean) - ``true`` if the ``id`` is a descendant of
the ``book_id,`` ``false``... | [
"def",
"is_descendant_of_book",
"(",
"self",
",",
"id_",
",",
"book_id",
")",
":",
"# Implemented from template for",
"# osid.resource.BinHierarchySession.is_descendant_of_bin",
"if",
"self",
".",
"_catalog_session",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_ca... | Tests if an ``Id`` is a descendant of a book.
arg: id (osid.id.Id): an ``Id``
arg: book_id (osid.id.Id): the ``Id`` of a book
return: (boolean) - ``true`` if the ``id`` is a descendant of
the ``book_id,`` ``false`` otherwise
raise: NotFound - ``book_id`` is not f... | [
"Tests",
"if",
"an",
"Id",
"is",
"a",
"descendant",
"of",
"a",
"book",
"."
] | python | train | 51.55 |
FreshXOpenSource/wallaby-frontend-qt | wallaby/frontends/qt/reactor/threadedselect.py | https://github.com/FreshXOpenSource/wallaby-frontend-qt/blob/eee70d0ec4ce34827f62a1654e28dbff8a8afb1a/wallaby/frontends/qt/reactor/threadedselect.py#L159-L197 | def _doSelectInThread(self, timeout):
"""Run one iteration of the I/O monitor loop.
This will run all selectables who had input or output readiness
waiting for them.
"""
reads = self.reads
writes = self.writes
while 1:
try:
r, w, ignor... | [
"def",
"_doSelectInThread",
"(",
"self",
",",
"timeout",
")",
":",
"reads",
"=",
"self",
".",
"reads",
"writes",
"=",
"self",
".",
"writes",
"while",
"1",
":",
"try",
":",
"r",
",",
"w",
",",
"ignored",
"=",
"_select",
"(",
"reads",
".",
"keys",
"(... | Run one iteration of the I/O monitor loop.
This will run all selectables who had input or output readiness
waiting for them. | [
"Run",
"one",
"iteration",
"of",
"the",
"I",
"/",
"O",
"monitor",
"loop",
"."
] | python | train | 38.589744 |
melonmanchan/ResumeOS | resumeos/ResumeOs.py | https://github.com/melonmanchan/ResumeOS/blob/b7fbcdaa0b4bad27e06ca33eee9c10f5d89fe37c/resumeos/ResumeOs.py#L16-L23 | def render_template_file(file_name, context):
""" Renders and overrides Jinja2 template files """
with open(file_name, 'r+') as f:
template = Template(f.read())
output = template.render(context)
f.seek(0)
f.write(output)
f.truncate() | [
"def",
"render_template_file",
"(",
"file_name",
",",
"context",
")",
":",
"with",
"open",
"(",
"file_name",
",",
"'r+'",
")",
"as",
"f",
":",
"template",
"=",
"Template",
"(",
"f",
".",
"read",
"(",
")",
")",
"output",
"=",
"template",
".",
"render",
... | Renders and overrides Jinja2 template files | [
"Renders",
"and",
"overrides",
"Jinja2",
"template",
"files"
] | python | train | 34.25 |
RRZE-HPC/kerncraft | kerncraft/kernel.py | https://github.com/RRZE-HPC/kerncraft/blob/c60baf8043e4da8d8d66da7575021c2f4c6c78af/kerncraft/kernel.py#L1117-L1134 | def _build_array_declarations(self, with_init=True):
"""
Generate declaration statements for arrays.
Also transforming multi-dim to 1d arrays and initializing with malloc.
:param with_init: ommit malloc initialization
:return: list of declarations nodes, dictionary of array na... | [
"def",
"_build_array_declarations",
"(",
"self",
",",
"with_init",
"=",
"True",
")",
":",
"# copy array declarations from from kernel ast",
"array_declarations",
"=",
"deepcopy",
"(",
"self",
".",
"get_array_declarations",
"(",
")",
")",
"array_dict",
"=",
"[",
"]",
... | Generate declaration statements for arrays.
Also transforming multi-dim to 1d arrays and initializing with malloc.
:param with_init: ommit malloc initialization
:return: list of declarations nodes, dictionary of array names and original dimensions | [
"Generate",
"declaration",
"statements",
"for",
"arrays",
"."
] | python | test | 41.388889 |
aloetesting/aloe_webdriver | aloe_webdriver/util.py | https://github.com/aloetesting/aloe_webdriver/blob/65d847da4bdc63f9c015cb19d4efdee87df8ffad/aloe_webdriver/util.py#L156-L162 | def _elements(self):
"""
The cached list of elements.
"""
if not self.evaluated:
setattr(self, '_elements_cached', list(self._select()))
return self._elements_cached | [
"def",
"_elements",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"evaluated",
":",
"setattr",
"(",
"self",
",",
"'_elements_cached'",
",",
"list",
"(",
"self",
".",
"_select",
"(",
")",
")",
")",
"return",
"self",
".",
"_elements_cached"
] | The cached list of elements. | [
"The",
"cached",
"list",
"of",
"elements",
"."
] | python | train | 30.142857 |
ponty/confduino | confduino/hwpackinstall.py | https://github.com/ponty/confduino/blob/f4c261e5e84997f145a8bdd001f471db74c9054b/confduino/hwpackinstall.py#L29-L61 | def install_hwpack(url, replace_existing=False):
"""install hwpackrary from web or local files system.
:param url: web address or file path
:param replace_existing: bool
:rtype: None
"""
d = tmpdir(tmpdir())
f = download(url)
Archive(f).extractall(d)
clean_dir(d)
src_dhwpack =... | [
"def",
"install_hwpack",
"(",
"url",
",",
"replace_existing",
"=",
"False",
")",
":",
"d",
"=",
"tmpdir",
"(",
"tmpdir",
"(",
")",
")",
"f",
"=",
"download",
"(",
"url",
")",
"Archive",
"(",
"f",
")",
".",
"extractall",
"(",
"d",
")",
"clean_dir",
... | install hwpackrary from web or local files system.
:param url: web address or file path
:param replace_existing: bool
:rtype: None | [
"install",
"hwpackrary",
"from",
"web",
"or",
"local",
"files",
"system",
"."
] | python | train | 26.484848 |
saltstack/salt | salt/modules/napalm_network.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/napalm_network.py#L2585-L2670 | def patch(patchfile,
options='',
saltenv='base',
source_hash=None,
show_changes=True,
source='running',
path=None,
test=False,
commit=True,
debug=False,
replace=True):
'''
.. versionadded:: 2019.2.0
Apply a ... | [
"def",
"patch",
"(",
"patchfile",
",",
"options",
"=",
"''",
",",
"saltenv",
"=",
"'base'",
",",
"source_hash",
"=",
"None",
",",
"show_changes",
"=",
"True",
",",
"source",
"=",
"'running'",
",",
"path",
"=",
"None",
",",
"test",
"=",
"False",
",",
... | .. versionadded:: 2019.2.0
Apply a patch to the configuration source, and load the result into the
running config of the device.
patchfile
A patch file to apply to the configuration source.
options
Options to pass to patch.
source_hash
If the patch file (specified via the... | [
"..",
"versionadded",
"::",
"2019",
".",
"2",
".",
"0"
] | python | train | 34.651163 |
croach/Flask-Fixtures | flask_fixtures/utils.py | https://github.com/croach/Flask-Fixtures/blob/b34597d165b33cc47cdd632ac0f3cf8a07428675/flask_fixtures/utils.py#L65-L84 | def can_persist_fixtures():
"""Returns True if it's possible to persist fixtures across tests.
Flask-Fixtures uses the setUpClass and tearDownClass methods to persist
fixtures across tests. These methods were added to unittest.TestCase in
python 2.7. So, we can only persist fixtures when using python 2... | [
"def",
"can_persist_fixtures",
"(",
")",
":",
"# If we're running python 2.7 or greater, we're fine",
"if",
"sys",
".",
"hexversion",
">=",
"0x02070000",
":",
"return",
"True",
"# Otherwise, nose and py.test support the setUpClass and tearDownClass",
"# methods, so if we're using eit... | Returns True if it's possible to persist fixtures across tests.
Flask-Fixtures uses the setUpClass and tearDownClass methods to persist
fixtures across tests. These methods were added to unittest.TestCase in
python 2.7. So, we can only persist fixtures when using python 2.7.
However, the nose and py.te... | [
"Returns",
"True",
"if",
"it",
"s",
"possible",
"to",
"persist",
"fixtures",
"across",
"tests",
"."
] | python | train | 46.55 |
zeth/inputs | inputs.py | https://github.com/zeth/inputs/blob/a46681dbf77d6ab07834f550e5855c1f50701f99/inputs.py#L3190-L3200 | def _post_init(self):
"""Call the find devices method for the relevant platform."""
if WIN:
self._find_devices_win()
elif MAC:
self._find_devices_mac()
else:
self._find_devices()
self._update_all_devices()
if NIX:
self._find... | [
"def",
"_post_init",
"(",
"self",
")",
":",
"if",
"WIN",
":",
"self",
".",
"_find_devices_win",
"(",
")",
"elif",
"MAC",
":",
"self",
".",
"_find_devices_mac",
"(",
")",
"else",
":",
"self",
".",
"_find_devices",
"(",
")",
"self",
".",
"_update_all_devic... | Call the find devices method for the relevant platform. | [
"Call",
"the",
"find",
"devices",
"method",
"for",
"the",
"relevant",
"platform",
"."
] | python | train | 28.818182 |
nvdv/vprof | vprof/base_profiler.py | https://github.com/nvdv/vprof/blob/4c3ff78f8920ab10cb9c00b14143452aa09ff6bb/vprof/base_profiler.py#L110-L123 | def init_module(self, run_object):
"""Initializes profiler with a module."""
self.profile = self.profile_module
self._run_object, _, self._run_args = run_object.partition(' ')
self._object_name = '%s (module)' % self._run_object
self._globs = {
'__file__': self._run_o... | [
"def",
"init_module",
"(",
"self",
",",
"run_object",
")",
":",
"self",
".",
"profile",
"=",
"self",
".",
"profile_module",
"self",
".",
"_run_object",
",",
"_",
",",
"self",
".",
"_run_args",
"=",
"run_object",
".",
"partition",
"(",
"' '",
")",
"self",... | Initializes profiler with a module. | [
"Initializes",
"profiler",
"with",
"a",
"module",
"."
] | python | test | 40.428571 |
bwesterb/py-seccure | src/__init__.py | https://github.com/bwesterb/py-seccure/blob/944760744686dd0ad015bd90ecb13a3ce0d7c9c9/src/__init__.py#L643-L647 | def decrypt_from(self, f, mac_bytes=10):
""" Decrypts a message from f. """
ctx = DecryptionContext(self.curve, f, self, mac_bytes)
yield ctx
ctx.read() | [
"def",
"decrypt_from",
"(",
"self",
",",
"f",
",",
"mac_bytes",
"=",
"10",
")",
":",
"ctx",
"=",
"DecryptionContext",
"(",
"self",
".",
"curve",
",",
"f",
",",
"self",
",",
"mac_bytes",
")",
"yield",
"ctx",
"ctx",
".",
"read",
"(",
")"
] | Decrypts a message from f. | [
"Decrypts",
"a",
"message",
"from",
"f",
"."
] | python | train | 36 |
spotify/gordon | gordon/main.py | https://github.com/spotify/gordon/blob/8dbf54a032cfaa8f003264682456236b6a69c039/gordon/main.py#L68-L74 | def _deep_merge_dict(a, b):
"""Additively merge right side dict into left side dict."""
for k, v in b.items():
if k in a and isinstance(a[k], dict) and isinstance(v, dict):
_deep_merge_dict(a[k], v)
else:
a[k] = v | [
"def",
"_deep_merge_dict",
"(",
"a",
",",
"b",
")",
":",
"for",
"k",
",",
"v",
"in",
"b",
".",
"items",
"(",
")",
":",
"if",
"k",
"in",
"a",
"and",
"isinstance",
"(",
"a",
"[",
"k",
"]",
",",
"dict",
")",
"and",
"isinstance",
"(",
"v",
",",
... | Additively merge right side dict into left side dict. | [
"Additively",
"merge",
"right",
"side",
"dict",
"into",
"left",
"side",
"dict",
"."
] | python | train | 36.428571 |
proteanhq/protean | src/protean/core/exceptions.py | https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/core/exceptions.py#L52-L59 | def normalized_messages(self, no_field_name='_entity'):
"""Return all the error messages as a dictionary"""
if isinstance(self.messages, dict):
return self.messages
if not self.field_names:
return {no_field_name: self.messages}
return dict((name, self.messages) f... | [
"def",
"normalized_messages",
"(",
"self",
",",
"no_field_name",
"=",
"'_entity'",
")",
":",
"if",
"isinstance",
"(",
"self",
".",
"messages",
",",
"dict",
")",
":",
"return",
"self",
".",
"messages",
"if",
"not",
"self",
".",
"field_names",
":",
"return",... | Return all the error messages as a dictionary | [
"Return",
"all",
"the",
"error",
"messages",
"as",
"a",
"dictionary"
] | python | train | 42.625 |
KarchinLab/probabilistic2020 | prob2020/python/permutation.py | https://github.com/KarchinLab/probabilistic2020/blob/5d70583b0a7c07cfe32e95f3a70e05df412acb84/prob2020/python/permutation.py#L689-L783 | def maf_permutation(context_counts,
context_to_mut,
seq_context,
gene_seq,
num_permutations=10000,
drop_silent=False):
"""Performs null-permutations across all genes and records the results in
a format like a MAF... | [
"def",
"maf_permutation",
"(",
"context_counts",
",",
"context_to_mut",
",",
"seq_context",
",",
"gene_seq",
",",
"num_permutations",
"=",
"10000",
",",
"drop_silent",
"=",
"False",
")",
":",
"mycontexts",
"=",
"context_counts",
".",
"index",
".",
"tolist",
"(",... | Performs null-permutations across all genes and records the results in
a format like a MAF file. This could be useful for examining the null
permutations because the alternative approaches always summarize the results.
With the simulated null-permutations, novel metrics can be applied to create
an empir... | [
"Performs",
"null",
"-",
"permutations",
"across",
"all",
"genes",
"and",
"records",
"the",
"results",
"in",
"a",
"format",
"like",
"a",
"MAF",
"file",
".",
"This",
"could",
"be",
"useful",
"for",
"examining",
"the",
"null",
"permutations",
"because",
"the",... | python | train | 41.947368 |
Alignak-monitoring/alignak | alignak/dependencynode.py | https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/dependencynode.py#L693-L765 | def expand_expression(self, pattern, hosts, services, hostgroups, servicegroups, running=False):
# pylint: disable=too-many-locals
"""Expand a host or service expression into a dependency node tree
using (host|service)group membership, regex, or labels as item selector.
:param pattern: ... | [
"def",
"expand_expression",
"(",
"self",
",",
"pattern",
",",
"hosts",
",",
"services",
",",
"hostgroups",
",",
"servicegroups",
",",
"running",
"=",
"False",
")",
":",
"# pylint: disable=too-many-locals",
"error",
"=",
"None",
"node",
"=",
"DependencyNode",
"("... | Expand a host or service expression into a dependency node tree
using (host|service)group membership, regex, or labels as item selector.
:param pattern: pattern to parse
:type pattern: str
:param hosts: hosts list, used to find a specific host
:type hosts: alignak.objects.host.H... | [
"Expand",
"a",
"host",
"or",
"service",
"expression",
"into",
"a",
"dependency",
"node",
"tree",
"using",
"(",
"host|service",
")",
"group",
"membership",
"regex",
"or",
"labels",
"as",
"item",
"selector",
"."
] | python | train | 42.753425 |
rm-hull/luma.led_matrix | luma/led_matrix/device.py | https://github.com/rm-hull/luma.led_matrix/blob/62e90aa0c052c869856a936bd76d6d86baf4ad8e/luma/led_matrix/device.py#L449-L459 | def contrast(self, value):
"""
Sets the LED intensity to the desired level, in the range 0-255.
:param level: Desired contrast level in the range of 0-255.
:type level: int
"""
assert(0x00 <= value <= 0xFF)
self._brightness = value >> 4
if self._last_imag... | [
"def",
"contrast",
"(",
"self",
",",
"value",
")",
":",
"assert",
"(",
"0x00",
"<=",
"value",
"<=",
"0xFF",
")",
"self",
".",
"_brightness",
"=",
"value",
">>",
"4",
"if",
"self",
".",
"_last_image",
"is",
"not",
"None",
":",
"self",
".",
"display",
... | Sets the LED intensity to the desired level, in the range 0-255.
:param level: Desired contrast level in the range of 0-255.
:type level: int | [
"Sets",
"the",
"LED",
"intensity",
"to",
"the",
"desired",
"level",
"in",
"the",
"range",
"0",
"-",
"255",
"."
] | python | train | 33.363636 |
rodluger/everest | everest/mathutils.py | https://github.com/rodluger/everest/blob/6779591f9f8b3556847e2fbf761bdfac7520eaea/everest/mathutils.py#L58-L78 | def Chunks(l, n, all=False):
'''
Returns a generator of consecutive `n`-sized chunks of list `l`.
If `all` is `True`, returns **all** `n`-sized chunks in `l`
by iterating over the starting point.
'''
if all:
jarr = range(0, n - 1)
else:
jarr = [0]
for j in jarr:
... | [
"def",
"Chunks",
"(",
"l",
",",
"n",
",",
"all",
"=",
"False",
")",
":",
"if",
"all",
":",
"jarr",
"=",
"range",
"(",
"0",
",",
"n",
"-",
"1",
")",
"else",
":",
"jarr",
"=",
"[",
"0",
"]",
"for",
"j",
"in",
"jarr",
":",
"for",
"i",
"in",
... | Returns a generator of consecutive `n`-sized chunks of list `l`.
If `all` is `True`, returns **all** `n`-sized chunks in `l`
by iterating over the starting point. | [
"Returns",
"a",
"generator",
"of",
"consecutive",
"n",
"-",
"sized",
"chunks",
"of",
"list",
"l",
".",
"If",
"all",
"is",
"True",
"returns",
"**",
"all",
"**",
"n",
"-",
"sized",
"chunks",
"in",
"l",
"by",
"iterating",
"over",
"the",
"starting",
"point... | python | train | 23.809524 |
facelessuser/wcmatch | wcmatch/glob.py | https://github.com/facelessuser/wcmatch/blob/d153e7007cc73b994ae1ba553dc4584039f5c212/wcmatch/glob.py#L154-L157 | def _match_literal(self, a, b=None):
"""Match two names."""
return a.lower() == b if not self.case_sensitive else a == b | [
"def",
"_match_literal",
"(",
"self",
",",
"a",
",",
"b",
"=",
"None",
")",
":",
"return",
"a",
".",
"lower",
"(",
")",
"==",
"b",
"if",
"not",
"self",
".",
"case_sensitive",
"else",
"a",
"==",
"b"
] | Match two names. | [
"Match",
"two",
"names",
"."
] | python | train | 33.5 |
ailionx/cloudflare-ddns | cloudflare_ddns/cloudflare.py | https://github.com/ailionx/cloudflare-ddns/blob/e4808b8314e447f69fab77b5bd3880846e59adbe/cloudflare_ddns/cloudflare.py#L90-L111 | def setup_zone(self):
"""
Setup zone for current domain.
It will also setup the dns records of the zone
:return:
"""
# Initialize current zone
zones_content = self.request(self.api_url, 'get')
try:
if len(self.domain.split('.')) == 3:
... | [
"def",
"setup_zone",
"(",
"self",
")",
":",
"# Initialize current zone",
"zones_content",
"=",
"self",
".",
"request",
"(",
"self",
".",
"api_url",
",",
"'get'",
")",
"try",
":",
"if",
"len",
"(",
"self",
".",
"domain",
".",
"split",
"(",
"'.'",
")",
"... | Setup zone for current domain.
It will also setup the dns records of the zone
:return: | [
"Setup",
"zone",
"for",
"current",
"domain",
".",
"It",
"will",
"also",
"setup",
"the",
"dns",
"records",
"of",
"the",
"zone",
":",
"return",
":"
] | python | train | 39.681818 |
fabioz/PyDev.Debugger | third_party/pep8/lib2to3/lib2to3/pgen2/conv.py | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/third_party/pep8/lib2to3/lib2to3/pgen2/conv.py#L53-L82 | def parse_graminit_h(self, filename):
"""Parse the .h file written by pgen. (Internal)
This file is a sequence of #define statements defining the
nonterminals of the grammar as numbers. We build two tables
mapping the numbers to names and back.
"""
try:
f ... | [
"def",
"parse_graminit_h",
"(",
"self",
",",
"filename",
")",
":",
"try",
":",
"f",
"=",
"open",
"(",
"filename",
")",
"except",
"IOError",
",",
"err",
":",
"print",
"\"Can't open %s: %s\"",
"%",
"(",
"filename",
",",
"err",
")",
"return",
"False",
"self... | Parse the .h file written by pgen. (Internal)
This file is a sequence of #define statements defining the
nonterminals of the grammar as numbers. We build two tables
mapping the numbers to names and back. | [
"Parse",
"the",
".",
"h",
"file",
"written",
"by",
"pgen",
".",
"(",
"Internal",
")"
] | python | train | 37.233333 |
s1s5/django_busybody | django_busybody/views.py | https://github.com/s1s5/django_busybody/blob/5c6fd89824224f1de1be79ccd9a149f025af1b8f/django_busybody/views.py#L155-L161 | def form_valid(self, forms):
"""
If the form is valid, save the associated model.
"""
for key, form in forms.items():
setattr(self, '{}_object'.format(key), form.save())
return super(MultipleModelFormMixin, self).form_valid(forms) | [
"def",
"form_valid",
"(",
"self",
",",
"forms",
")",
":",
"for",
"key",
",",
"form",
"in",
"forms",
".",
"items",
"(",
")",
":",
"setattr",
"(",
"self",
",",
"'{}_object'",
".",
"format",
"(",
"key",
")",
",",
"form",
".",
"save",
"(",
")",
")",
... | If the form is valid, save the associated model. | [
"If",
"the",
"form",
"is",
"valid",
"save",
"the",
"associated",
"model",
"."
] | python | train | 39.428571 |
apache/incubator-heron | heron/tools/cli/src/python/submit.py | https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/cli/src/python/submit.py#L295-L333 | def submit_tar(cl_args, unknown_args, tmp_dir):
'''
Extract and execute the java files inside the tar and then add topology
definition file created by running submitTopology
We use the packer to make a package for the tar and dump it
to a well-known location. We then run the main method of class
with the s... | [
"def",
"submit_tar",
"(",
"cl_args",
",",
"unknown_args",
",",
"tmp_dir",
")",
":",
"# execute main of the topology to create the topology definition",
"topology_file",
"=",
"cl_args",
"[",
"'topology-file-name'",
"]",
"java_defines",
"=",
"cl_args",
"[",
"'topology_main_jv... | Extract and execute the java files inside the tar and then add topology
definition file created by running submitTopology
We use the packer to make a package for the tar and dump it
to a well-known location. We then run the main method of class
with the specified arguments. We pass arguments as an environment ... | [
"Extract",
"and",
"execute",
"the",
"java",
"files",
"inside",
"the",
"tar",
"and",
"then",
"add",
"topology",
"definition",
"file",
"created",
"by",
"running",
"submitTopology"
] | python | valid | 35.820513 |
ambitioninc/django-manager-utils | manager_utils/manager_utils.py | https://github.com/ambitioninc/django-manager-utils/blob/1f111cb4846ed6cd6b78eca320a9dcc27826bf97/manager_utils/manager_utils.py#L69-L76 | def _get_upserts(queryset, model_objs_updated, model_objs_created, unique_fields):
"""
Given a list of model objects that were updated and model objects that were created,
return the list of all model objects upserted. Doing this requires fetching all of
the models created with bulk create (since django... | [
"def",
"_get_upserts",
"(",
"queryset",
",",
"model_objs_updated",
",",
"model_objs_created",
",",
"unique_fields",
")",
":",
"updated",
",",
"created",
"=",
"_get_upserts_distinct",
"(",
"queryset",
",",
"model_objs_updated",
",",
"model_objs_created",
",",
"unique_f... | Given a list of model objects that were updated and model objects that were created,
return the list of all model objects upserted. Doing this requires fetching all of
the models created with bulk create (since django can't return bulk_create pks) | [
"Given",
"a",
"list",
"of",
"model",
"objects",
"that",
"were",
"updated",
"and",
"model",
"objects",
"that",
"were",
"created",
"return",
"the",
"list",
"of",
"all",
"model",
"objects",
"upserted",
".",
"Doing",
"this",
"requires",
"fetching",
"all",
"of",
... | python | train | 61.25 |
kronenthaler/mod-pbxproj | pbxproj/pbxextensions/ProjectFlags.py | https://github.com/kronenthaler/mod-pbxproj/blob/8de3cbdd3210480ddbb1fa0f50a4f4ea87de6e71/pbxproj/pbxextensions/ProjectFlags.py#L13-L23 | def add_flags(self, flag_name, flags, target_name=None, configuration_name=None):
"""
Adds the given flags to the flag_name section of the target on the configurations
:param flag_name: name of the flag to be added the values to
:param flags: A string or array of strings
:param t... | [
"def",
"add_flags",
"(",
"self",
",",
"flag_name",
",",
"flags",
",",
"target_name",
"=",
"None",
",",
"configuration_name",
"=",
"None",
")",
":",
"for",
"configuration",
"in",
"self",
".",
"objects",
".",
"get_configurations_on_targets",
"(",
"target_name",
... | Adds the given flags to the flag_name section of the target on the configurations
:param flag_name: name of the flag to be added the values to
:param flags: A string or array of strings
:param target_name: Target name or list of target names to add the flag to or None for every target
:p... | [
"Adds",
"the",
"given",
"flags",
"to",
"the",
"flag_name",
"section",
"of",
"the",
"target",
"on",
"the",
"configurations",
":",
"param",
"flag_name",
":",
"name",
"of",
"the",
"flag",
"to",
"be",
"added",
"the",
"values",
"to",
":",
"param",
"flags",
":... | python | train | 63.636364 |
linnarsson-lab/loompy | loompy/loompy.py | https://github.com/linnarsson-lab/loompy/blob/62c8373a92b058753baa3a95331fb541f560f599/loompy/loompy.py#L873-L934 | def aggregate(self, out_file: str = None, select: np.ndarray = None, group_by: Union[str, np.ndarray] = "Clusters", aggr_by: str = "mean", aggr_ca_by: Dict[str, str] = None) -> np.ndarray:
"""
Aggregate the Loom file by applying aggregation functions to the main matrix as well as to the column attributes
Args:
... | [
"def",
"aggregate",
"(",
"self",
",",
"out_file",
":",
"str",
"=",
"None",
",",
"select",
":",
"np",
".",
"ndarray",
"=",
"None",
",",
"group_by",
":",
"Union",
"[",
"str",
",",
"np",
".",
"ndarray",
"]",
"=",
"\"Clusters\"",
",",
"aggr_by",
":",
"... | Aggregate the Loom file by applying aggregation functions to the main matrix as well as to the column attributes
Args:
out_file The name of the output Loom file (will be appended to if it exists)
select Bool array giving the columns to include (or None, to include all)
group_by The column attribute to grou... | [
"Aggregate",
"the",
"Loom",
"file",
"by",
"applying",
"aggregation",
"functions",
"to",
"the",
"main",
"matrix",
"as",
"well",
"as",
"to",
"the",
"column",
"attributes"
] | python | train | 44.741935 |
fhcrc/seqmagick | seqmagick/transform.py | https://github.com/fhcrc/seqmagick/blob/1642bb87ba5c171fbd307f9da0f8a0ee1d69d5ed/seqmagick/transform.py#L70-L89 | def deduplicate_sequences(records, out_file):
"""
Remove any duplicate records with identical sequences, keep the first
instance seen and discard additional occurences.
"""
logging.info('Applying _deduplicate_sequences generator: '
'removing any duplicate records with identical seq... | [
"def",
"deduplicate_sequences",
"(",
"records",
",",
"out_file",
")",
":",
"logging",
".",
"info",
"(",
"'Applying _deduplicate_sequences generator: '",
"'removing any duplicate records with identical sequences.'",
")",
"checksum_sequences",
"=",
"collections",
".",
"defaultdic... | Remove any duplicate records with identical sequences, keep the first
instance seen and discard additional occurences. | [
"Remove",
"any",
"duplicate",
"records",
"with",
"identical",
"sequences",
"keep",
"the",
"first",
"instance",
"seen",
"and",
"discard",
"additional",
"occurences",
"."
] | python | train | 37.05 |
jjkester/django-auditlog | src/auditlog/receivers.py | https://github.com/jjkester/django-auditlog/blob/a22978e05b7ed43b87e4b6109550b86c738578fe/src/auditlog/receivers.py#L50-L63 | def log_delete(sender, instance, **kwargs):
"""
Signal receiver that creates a log entry when a model instance is deleted from the database.
Direct use is discouraged, connect your model through :py:func:`auditlog.registry.register` instead.
"""
if instance.pk is not None:
changes = model_i... | [
"def",
"log_delete",
"(",
"sender",
",",
"instance",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"instance",
".",
"pk",
"is",
"not",
"None",
":",
"changes",
"=",
"model_instance_diff",
"(",
"instance",
",",
"None",
")",
"log_entry",
"=",
"LogEntry",
".",
... | Signal receiver that creates a log entry when a model instance is deleted from the database.
Direct use is discouraged, connect your model through :py:func:`auditlog.registry.register` instead. | [
"Signal",
"receiver",
"that",
"creates",
"a",
"log",
"entry",
"when",
"a",
"model",
"instance",
"is",
"deleted",
"from",
"the",
"database",
"."
] | python | train | 35.785714 |
dropbox/stone | stone/ir/data_types.py | https://github.com/dropbox/stone/blob/2e95cbcd1c48e05cca68c919fd8d24adec6b0f58/stone/ir/data_types.py#L1979-L2001 | def unwrap(data_type):
"""
Convenience method to unwrap all Aliases and Nullables from around a
DataType. This checks for nullable wrapping aliases, as well as aliases
wrapping nullables.
Args:
data_type (DataType): The target to unwrap.
Return:
Tuple[DataType, bool, bool]: The... | [
"def",
"unwrap",
"(",
"data_type",
")",
":",
"unwrapped_nullable",
"=",
"False",
"unwrapped_alias",
"=",
"False",
"while",
"is_alias",
"(",
"data_type",
")",
"or",
"is_nullable_type",
"(",
"data_type",
")",
":",
"if",
"is_nullable_type",
"(",
"data_type",
")",
... | Convenience method to unwrap all Aliases and Nullables from around a
DataType. This checks for nullable wrapping aliases, as well as aliases
wrapping nullables.
Args:
data_type (DataType): The target to unwrap.
Return:
Tuple[DataType, bool, bool]: The underlying data type; a bool that ... | [
"Convenience",
"method",
"to",
"unwrap",
"all",
"Aliases",
"and",
"Nullables",
"from",
"around",
"a",
"DataType",
".",
"This",
"checks",
"for",
"nullable",
"wrapping",
"aliases",
"as",
"well",
"as",
"aliases",
"wrapping",
"nullables",
"."
] | python | train | 35.043478 |
PolicyStat/docx2html | docx2html/core.py | https://github.com/PolicyStat/docx2html/blob/2dc4afd1e3a3f2f0b357d0bff903eb58bcc94429/docx2html/core.py#L534-L544 | def is_underlined(r):
"""
The function will return True if the r tag passed in is considered
underlined.
"""
w_namespace = get_namespace(r, 'w')
rpr = r.find('%srPr' % w_namespace)
if rpr is None:
return False
underline = rpr.find('%su' % w_namespace)
return style_is_false(un... | [
"def",
"is_underlined",
"(",
"r",
")",
":",
"w_namespace",
"=",
"get_namespace",
"(",
"r",
",",
"'w'",
")",
"rpr",
"=",
"r",
".",
"find",
"(",
"'%srPr'",
"%",
"w_namespace",
")",
"if",
"rpr",
"is",
"None",
":",
"return",
"False",
"underline",
"=",
"r... | The function will return True if the r tag passed in is considered
underlined. | [
"The",
"function",
"will",
"return",
"True",
"if",
"the",
"r",
"tag",
"passed",
"in",
"is",
"considered",
"underlined",
"."
] | python | test | 28.909091 |
librosa/librosa | librosa/core/pitch.py | https://github.com/librosa/librosa/blob/180e8e6eb8f958fa6b20b8cba389f7945d508247/librosa/core/pitch.py#L167-L338 | def piptrack(y=None, sr=22050, S=None, n_fft=2048, hop_length=None,
fmin=150.0, fmax=4000.0, threshold=0.1,
win_length=None, window='hann', center=True, pad_mode='reflect',
ref=None):
'''Pitch tracking on thresholded parabolically-interpolated STFT.
This implementation us... | [
"def",
"piptrack",
"(",
"y",
"=",
"None",
",",
"sr",
"=",
"22050",
",",
"S",
"=",
"None",
",",
"n_fft",
"=",
"2048",
",",
"hop_length",
"=",
"None",
",",
"fmin",
"=",
"150.0",
",",
"fmax",
"=",
"4000.0",
",",
"threshold",
"=",
"0.1",
",",
"win_le... | Pitch tracking on thresholded parabolically-interpolated STFT.
This implementation uses the parabolic interpolation method described by [1]_.
.. [1] https://ccrma.stanford.edu/~jos/sasp/Sinusoidal_Peak_Interpolation.html
Parameters
----------
y: np.ndarray [shape=(n,)] or None
audio signa... | [
"Pitch",
"tracking",
"on",
"thresholded",
"parabolically",
"-",
"interpolated",
"STFT",
"."
] | python | test | 31.604651 |
jeremymcrae/denovonear | denovonear/ensembl_requester.py | https://github.com/jeremymcrae/denovonear/blob/feaab0fc77e89d70b31e8092899e4f0e68bac9fe/denovonear/ensembl_requester.py#L70-L103 | def open_url(self, url, headers):
""" open url with python libraries
"""
data = self.cache.get_cached_data(url)
if data is not None:
return data, 200, headers
self.rate_limit_ensembl_requests()
req = request.Request(url, headers=headers)
... | [
"def",
"open_url",
"(",
"self",
",",
"url",
",",
"headers",
")",
":",
"data",
"=",
"self",
".",
"cache",
".",
"get_cached_data",
"(",
"url",
")",
"if",
"data",
"is",
"not",
"None",
":",
"return",
"data",
",",
"200",
",",
"headers",
"self",
".",
"ra... | open url with python libraries | [
"open",
"url",
"with",
"python",
"libraries"
] | python | train | 38.823529 |
RudolfCardinal/pythonlib | cardinal_pythonlib/convert.py | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/convert.py#L101-L110 | def convert_attrs_to_uppercase(obj: Any, attrs: Iterable[str]) -> None:
"""
Converts the specified attributes of an object to upper case, modifying
the object in place.
"""
for a in attrs:
value = getattr(obj, a)
if value is None:
continue
setattr(obj, a, value.up... | [
"def",
"convert_attrs_to_uppercase",
"(",
"obj",
":",
"Any",
",",
"attrs",
":",
"Iterable",
"[",
"str",
"]",
")",
"->",
"None",
":",
"for",
"a",
"in",
"attrs",
":",
"value",
"=",
"getattr",
"(",
"obj",
",",
"a",
")",
"if",
"value",
"is",
"None",
":... | Converts the specified attributes of an object to upper case, modifying
the object in place. | [
"Converts",
"the",
"specified",
"attributes",
"of",
"an",
"object",
"to",
"upper",
"case",
"modifying",
"the",
"object",
"in",
"place",
"."
] | python | train | 31.7 |
osrg/ryu | ryu/app/rest_vtep.py | https://github.com/osrg/ryu/blob/6f906e72c92e10bd0264c9b91a2f7bb85b97780c/ryu/app/rest_vtep.py#L1177-L1226 | def add_speaker(self, **kwargs):
"""
Creates a new BGPSpeaker instance.
Usage:
======= ================
Method URI
======= ================
POST /vtep/speakers
======= ================
Request parameters:
===... | [
"def",
"add_speaker",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"body",
"=",
"self",
".",
"vtep_app",
".",
"add_speaker",
"(",
"*",
"*",
"kwargs",
")",
"except",
"DatapathNotFound",
"as",
"e",
":",
"return",
"e",
".",
"to_response",
... | Creates a new BGPSpeaker instance.
Usage:
======= ================
Method URI
======= ================
POST /vtep/speakers
======= ================
Request parameters:
========== ============================================
... | [
"Creates",
"a",
"new",
"BGPSpeaker",
"instance",
"."
] | python | train | 29.46 |
pmacosta/peng | peng/wave_functions.py | https://github.com/pmacosta/peng/blob/976935377adaa3de26fc5677aceb2cdfbd6f93a7/peng/wave_functions.py#L1394-L1414 | def group_delay(wave):
r"""
Return the group delay of a waveform.
:param wave: Waveform
:type wave: :py:class:`peng.eng.Waveform`
:rtype: :py:class:`peng.eng.Waveform`
.. [[[cog cog.out(exobj_eng.get_sphinx_autodoc(raised=True)) ]]]
.. Auto-generated exceptions documentation for
.. p... | [
"def",
"group_delay",
"(",
"wave",
")",
":",
"ret",
"=",
"-",
"derivative",
"(",
"phase",
"(",
"wave",
",",
"unwrap",
"=",
"True",
")",
"/",
"(",
"2",
"*",
"math",
".",
"pi",
")",
")",
"ret",
".",
"dep_name",
"=",
"\"group_delay({0})\"",
".",
"form... | r"""
Return the group delay of a waveform.
:param wave: Waveform
:type wave: :py:class:`peng.eng.Waveform`
:rtype: :py:class:`peng.eng.Waveform`
.. [[[cog cog.out(exobj_eng.get_sphinx_autodoc(raised=True)) ]]]
.. Auto-generated exceptions documentation for
.. peng.wave_functions.group_de... | [
"r",
"Return",
"the",
"group",
"delay",
"of",
"a",
"waveform",
"."
] | python | test | 27.666667 |
iterative/dvc | dvc/config.py | https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/config.py#L542-L564 | def unset(config, section, opt=None):
"""Unsets specified option and/or section in the config.
Args:
config (configobj.ConfigObj): config to work on.
section (str): section name.
opt (str): optional option name.
"""
if section not in config.keys():
... | [
"def",
"unset",
"(",
"config",
",",
"section",
",",
"opt",
"=",
"None",
")",
":",
"if",
"section",
"not",
"in",
"config",
".",
"keys",
"(",
")",
":",
"raise",
"ConfigError",
"(",
"\"section '{}' doesn't exist\"",
".",
"format",
"(",
"section",
")",
")",
... | Unsets specified option and/or section in the config.
Args:
config (configobj.ConfigObj): config to work on.
section (str): section name.
opt (str): optional option name. | [
"Unsets",
"specified",
"option",
"and",
"/",
"or",
"section",
"in",
"the",
"config",
"."
] | python | train | 30.652174 |
sorgerlab/indra | indra/sources/ndex_cx/api.py | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/ndex_cx/api.py#L33-L65 | def process_ndex_network(network_id, username=None, password=None,
require_grounding=True):
"""Process an NDEx network into Statements.
Parameters
----------
network_id : str
NDEx network ID.
username : str
NDEx username.
password : str
NDEx pass... | [
"def",
"process_ndex_network",
"(",
"network_id",
",",
"username",
"=",
"None",
",",
"password",
"=",
"None",
",",
"require_grounding",
"=",
"True",
")",
":",
"nd",
"=",
"ndex2",
".",
"client",
".",
"Ndex2",
"(",
"username",
"=",
"username",
",",
"password... | Process an NDEx network into Statements.
Parameters
----------
network_id : str
NDEx network ID.
username : str
NDEx username.
password : str
NDEx password.
require_grounding: bool
Whether network nodes lacking grounding information should be included
amo... | [
"Process",
"an",
"NDEx",
"network",
"into",
"Statements",
"."
] | python | train | 34.787879 |
mlperf/training | reinforcement/tensorflow/minigo/rl_loop/fsdb.py | https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/rl_loop/fsdb.py#L76-L87 | def get_models():
"""Finds all models, returning a list of model number and names
sorted increasing.
Returns: [(13, 000013-modelname), (17, 000017-modelname), ...etc]
"""
all_models = gfile.Glob(os.path.join(models_dir(), '*.meta'))
model_filenames = [os.path.basename(m) for m in all_models]
... | [
"def",
"get_models",
"(",
")",
":",
"all_models",
"=",
"gfile",
".",
"Glob",
"(",
"os",
".",
"path",
".",
"join",
"(",
"models_dir",
"(",
")",
",",
"'*.meta'",
")",
")",
"model_filenames",
"=",
"[",
"os",
".",
"path",
".",
"basename",
"(",
"m",
")"... | Finds all models, returning a list of model number and names
sorted increasing.
Returns: [(13, 000013-modelname), (17, 000017-modelname), ...etc] | [
"Finds",
"all",
"models",
"returning",
"a",
"list",
"of",
"model",
"number",
"and",
"names",
"sorted",
"increasing",
"."
] | python | train | 39.75 |
MaxStrange/AudioSegment | audiosegment.py | https://github.com/MaxStrange/AudioSegment/blob/1daefb8de626ddff3ff7016697c3ad31d262ecd6/audiosegment.py#L938-L948 | def serialize(self):
"""
Serializes into a bytestring.
:returns: An object of type Bytes.
"""
d = self.__getstate__()
return pickle.dumps({
'name': d['name'],
'seg': pickle.dumps(d['seg'], protocol=-1),
}, protocol=-1) | [
"def",
"serialize",
"(",
"self",
")",
":",
"d",
"=",
"self",
".",
"__getstate__",
"(",
")",
"return",
"pickle",
".",
"dumps",
"(",
"{",
"'name'",
":",
"d",
"[",
"'name'",
"]",
",",
"'seg'",
":",
"pickle",
".",
"dumps",
"(",
"d",
"[",
"'seg'",
"]"... | Serializes into a bytestring.
:returns: An object of type Bytes. | [
"Serializes",
"into",
"a",
"bytestring",
"."
] | python | test | 26.272727 |
numenta/nupic | src/nupic/algorithms/backtracking_tm.py | https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/backtracking_tm.py#L999-L1015 | def printState(self, aState):
"""
Print an integer array that is the same shape as activeState.
:param aState: TODO: document
"""
def formatRow(var, i):
s = ''
for c in range(self.numberOfCols):
if c > 0 and c % 10 == 0:
s += ' '
s += str(var[c, i])
s += ... | [
"def",
"printState",
"(",
"self",
",",
"aState",
")",
":",
"def",
"formatRow",
"(",
"var",
",",
"i",
")",
":",
"s",
"=",
"''",
"for",
"c",
"in",
"range",
"(",
"self",
".",
"numberOfCols",
")",
":",
"if",
"c",
">",
"0",
"and",
"c",
"%",
"10",
... | Print an integer array that is the same shape as activeState.
:param aState: TODO: document | [
"Print",
"an",
"integer",
"array",
"that",
"is",
"the",
"same",
"shape",
"as",
"activeState",
"."
] | python | valid | 23.411765 |
networks-lab/tidyextractors | tidyextractors/tidymbox/mbox_to_pandas.py | https://github.com/networks-lab/tidyextractors/blob/658448ed533beecf32adcc188fc64d1068d15ca6/tidyextractors/tidymbox/mbox_to_pandas.py#L128-L164 | def write_table(mboxfile, mailTable):
"""
Takes a list and extends it with lists of data, which is
extracted from mbox messages.
:param mboxfile: Mbox file name/path
:param mailTable: A list (of lists)
:return: An extended list of lists
"""
mail_box_contents = mailbox.mbox(mboxfile)
... | [
"def",
"write_table",
"(",
"mboxfile",
",",
"mailTable",
")",
":",
"mail_box_contents",
"=",
"mailbox",
".",
"mbox",
"(",
"mboxfile",
")",
"m_pbar",
"=",
"tqdm",
".",
"tqdm",
"(",
"range",
"(",
"0",
",",
"len",
"(",
"mail_box_contents",
")",
")",
")",
... | Takes a list and extends it with lists of data, which is
extracted from mbox messages.
:param mboxfile: Mbox file name/path
:param mailTable: A list (of lists)
:return: An extended list of lists | [
"Takes",
"a",
"list",
"and",
"extends",
"it",
"with",
"lists",
"of",
"data",
"which",
"is",
"extracted",
"from",
"mbox",
"messages",
".",
":",
"param",
"mboxfile",
":",
"Mbox",
"file",
"name",
"/",
"path",
":",
"param",
"mailTable",
":",
"A",
"list",
"... | python | train | 29.27027 |
genialis/resolwe | resolwe/elastic/composer.py | https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/elastic/composer.py#L37-L51 | def _get_class_path(self, klass_or_instance):
"""Return class path for a given class.
:param klass_or_instance: Class or instance of given class
:return: String containing the class path
"""
if inspect.isclass(klass_or_instance):
klass = '{}.{}'.format(klass_or_insta... | [
"def",
"_get_class_path",
"(",
"self",
",",
"klass_or_instance",
")",
":",
"if",
"inspect",
".",
"isclass",
"(",
"klass_or_instance",
")",
":",
"klass",
"=",
"'{}.{}'",
".",
"format",
"(",
"klass_or_instance",
".",
"__module__",
",",
"klass_or_instance",
".",
... | Return class path for a given class.
:param klass_or_instance: Class or instance of given class
:return: String containing the class path | [
"Return",
"class",
"path",
"for",
"a",
"given",
"class",
"."
] | python | train | 39.533333 |
owncloud/pyocclient | owncloud/owncloud.py | https://github.com/owncloud/pyocclient/blob/b9e1f04cdbde74588e86f1bebb6144571d82966c/owncloud/owncloud.py#L1510-L1531 | def set_attribute(self, app, key, value):
"""Sets an application attribute
:param app: application id
:param key: key of the attribute to set
:param value: value to set
:returns: True if the operation succeeded, False otherwise
:raises: HTTPResponseError in case an HTTP ... | [
"def",
"set_attribute",
"(",
"self",
",",
"app",
",",
"key",
",",
"value",
")",
":",
"path",
"=",
"'setattribute/'",
"+",
"parse",
".",
"quote",
"(",
"app",
",",
"''",
")",
"+",
"'/'",
"+",
"parse",
".",
"quote",
"(",
"self",
".",
"_encode_string",
... | Sets an application attribute
:param app: application id
:param key: key of the attribute to set
:param value: value to set
:returns: True if the operation succeeded, False otherwise
:raises: HTTPResponseError in case an HTTP error status was returned | [
"Sets",
"an",
"application",
"attribute"
] | python | train | 37.227273 |
tensorforce/tensorforce | tensorforce/contrib/deepmind_lab.py | https://github.com/tensorforce/tensorforce/blob/520a8d992230e382f08e315ede5fc477f5e26bfb/tensorforce/contrib/deepmind_lab.py#L102-L110 | def reset(self):
"""
Resets the environment to its initialization state. This method needs to be called to start a
new episode after the last episode ended.
:return: initial state
"""
self.level.reset() # optional: episode=-1, seed=None
return self.level.observa... | [
"def",
"reset",
"(",
"self",
")",
":",
"self",
".",
"level",
".",
"reset",
"(",
")",
"# optional: episode=-1, seed=None",
"return",
"self",
".",
"level",
".",
"observations",
"(",
")",
"[",
"self",
".",
"state_attribute",
"]"
] | Resets the environment to its initialization state. This method needs to be called to start a
new episode after the last episode ended.
:return: initial state | [
"Resets",
"the",
"environment",
"to",
"its",
"initialization",
"state",
".",
"This",
"method",
"needs",
"to",
"be",
"called",
"to",
"start",
"a",
"new",
"episode",
"after",
"the",
"last",
"episode",
"ended",
"."
] | python | valid | 37.888889 |
spulec/moto | moto/iam/models.py | https://github.com/spulec/moto/blob/4a286c4bc288933bb023396e2784a6fdbb966bc9/moto/iam/models.py#L639-L657 | def _validate_tag_key(self, tag_key, exception_param='tags.X.member.key'):
"""Validates the tag key.
:param all_tags: Dict to check if there is a duplicate tag.
:param tag_key: The tag key to check against.
:param exception_param: The exception parameter to send over to help format the ... | [
"def",
"_validate_tag_key",
"(",
"self",
",",
"tag_key",
",",
"exception_param",
"=",
"'tags.X.member.key'",
")",
":",
"# Validate that the key length is correct:",
"if",
"len",
"(",
"tag_key",
")",
">",
"128",
":",
"raise",
"TagKeyTooBig",
"(",
"tag_key",
",",
"p... | Validates the tag key.
:param all_tags: Dict to check if there is a duplicate tag.
:param tag_key: The tag key to check against.
:param exception_param: The exception parameter to send over to help format the message. This is to reflect
the difference between the... | [
"Validates",
"the",
"tag",
"key",
"."
] | python | train | 54.105263 |
econ-ark/HARK | HARK/ConsumptionSaving/ConsIndShockModel.py | https://github.com/econ-ark/HARK/blob/3d184153a189e618a87c9540df1cd12044039cc5/HARK/ConsumptionSaving/ConsIndShockModel.py#L2016-L2080 | def checkConditions(self,verbose=False,public_call=True):
'''
This method checks whether the instance's type satisfies the growth impatience condition
(GIC), return impatience condition (RIC), absolute impatience condition (AIC), weak return
impatience condition (WRIC), finite human weal... | [
"def",
"checkConditions",
"(",
"self",
",",
"verbose",
"=",
"False",
",",
"public_call",
"=",
"True",
")",
":",
"violated",
"=",
"PerfForesightConsumerType",
".",
"checkConditions",
"(",
"self",
",",
"verbose",
"=",
"verbose",
",",
"verbose_reference",
"=",
"F... | This method checks whether the instance's type satisfies the growth impatience condition
(GIC), return impatience condition (RIC), absolute impatience condition (AIC), weak return
impatience condition (WRIC), finite human wealth condition (FHWC) and finite value of
autarky condition (FVAC). Thes... | [
"This",
"method",
"checks",
"whether",
"the",
"instance",
"s",
"type",
"satisfies",
"the",
"growth",
"impatience",
"condition",
"(",
"GIC",
")",
"return",
"impatience",
"condition",
"(",
"RIC",
")",
"absolute",
"impatience",
"condition",
"(",
"AIC",
")",
"weak... | python | train | 56.153846 |
noirbizarre/django-absolute | absolute/templatetags/absolute.py | https://github.com/noirbizarre/django-absolute/blob/0358fd39c641afdb589f448c0dae72d816c4e5f2/absolute/templatetags/absolute.py#L24-L36 | def absolute(parser, token):
'''
Returns a full absolute URL based on the request host.
This template tag takes exactly the same paramters as url template tag.
'''
node = url(parser, token)
return AbsoluteUrlNode(
view_name=node.view_name,
args=node.args,
kwargs=node.kwa... | [
"def",
"absolute",
"(",
"parser",
",",
"token",
")",
":",
"node",
"=",
"url",
"(",
"parser",
",",
"token",
")",
"return",
"AbsoluteUrlNode",
"(",
"view_name",
"=",
"node",
".",
"view_name",
",",
"args",
"=",
"node",
".",
"args",
",",
"kwargs",
"=",
"... | Returns a full absolute URL based on the request host.
This template tag takes exactly the same paramters as url template tag. | [
"Returns",
"a",
"full",
"absolute",
"URL",
"based",
"on",
"the",
"request",
"host",
"."
] | python | train | 26.384615 |
jmgilman/Neolib | neolib/pyamf/remoting/gateway/__init__.py | https://github.com/jmgilman/Neolib/blob/228fafeaed0f3195676137732384a14820ae285c/neolib/pyamf/remoting/gateway/__init__.py#L488-L503 | def preprocessRequest(self, service_request, *args, **kwargs):
"""
Preprocesses a request.
"""
processor = self.getPreprocessor(service_request)
if processor is None:
return
args = (service_request,) + args
if hasattr(processor, '_pyamf_expose_reque... | [
"def",
"preprocessRequest",
"(",
"self",
",",
"service_request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"processor",
"=",
"self",
".",
"getPreprocessor",
"(",
"service_request",
")",
"if",
"processor",
"is",
"None",
":",
"return",
"args",
"="... | Preprocesses a request. | [
"Preprocesses",
"a",
"request",
"."
] | python | train | 27.8125 |
pypa/pipenv | pipenv/vendor/pyparsing.py | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pyparsing.py#L1936-L1964 | def searchString( self, instring, maxMatches=_MAX_INT ):
"""
Another extension to :class:`scanString`, simplifying the access to the tokens found
to match the given parse expression. May be called with optional
``maxMatches`` argument, to clip searching after 'n' matches are found.
... | [
"def",
"searchString",
"(",
"self",
",",
"instring",
",",
"maxMatches",
"=",
"_MAX_INT",
")",
":",
"try",
":",
"return",
"ParseResults",
"(",
"[",
"t",
"for",
"t",
",",
"s",
",",
"e",
"in",
"self",
".",
"scanString",
"(",
"instring",
",",
"maxMatches",... | Another extension to :class:`scanString`, simplifying the access to the tokens found
to match the given parse expression. May be called with optional
``maxMatches`` argument, to clip searching after 'n' matches are found.
Example::
# a capitalized word starts with an uppercase let... | [
"Another",
"extension",
"to",
":",
"class",
":",
"scanString",
"simplifying",
"the",
"access",
"to",
"the",
"tokens",
"found",
"to",
"match",
"the",
"given",
"parse",
"expression",
".",
"May",
"be",
"called",
"with",
"optional",
"maxMatches",
"argument",
"to",... | python | train | 45.965517 |
SheffieldML/GPyOpt | GPyOpt/interface/driver.py | https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/interface/driver.py#L58-L71 | def _get_acquisition(self, model, space):
"""
Imports the acquisition
"""
from copy import deepcopy
acqOpt_config = deepcopy(self.config['acquisition']['optimizer'])
acqOpt_name = acqOpt_config['name']
del acqOpt_config['name']
from ..opt... | [
"def",
"_get_acquisition",
"(",
"self",
",",
"model",
",",
"space",
")",
":",
"from",
"copy",
"import",
"deepcopy",
"acqOpt_config",
"=",
"deepcopy",
"(",
"self",
".",
"config",
"[",
"'acquisition'",
"]",
"[",
"'optimizer'",
"]",
")",
"acqOpt_name",
"=",
"... | Imports the acquisition | [
"Imports",
"the",
"acquisition"
] | python | train | 43.571429 |
jsommers/switchyard | switchyard/sim/cli.py | https://github.com/jsommers/switchyard/blob/fdcb3869c937dcedbd6ea7a7822ebd412bf1e2b0/switchyard/sim/cli.py#L531-L560 | def default(self, line):
'''
Implement short-cut commands: any unique command prefix should
work.'''
cmdargs = line.split()
remain = ' '.join(cmdargs[1:])
if 'show'.startswith(cmdargs[0]):
self.do_show(remain)
elif 'set'.startswith(cmdargs[0]):
... | [
"def",
"default",
"(",
"self",
",",
"line",
")",
":",
"cmdargs",
"=",
"line",
".",
"split",
"(",
")",
"remain",
"=",
"' '",
".",
"join",
"(",
"cmdargs",
"[",
"1",
":",
"]",
")",
"if",
"'show'",
".",
"startswith",
"(",
"cmdargs",
"[",
"0",
"]",
... | Implement short-cut commands: any unique command prefix should
work. | [
"Implement",
"short",
"-",
"cut",
"commands",
":",
"any",
"unique",
"command",
"prefix",
"should",
"work",
"."
] | python | train | 37.033333 |
bitesofcode/projexui | projexui/widgets/xorbrecordbox.py | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xorbrecordbox.py#L214-L222 | def acceptRecord(self, item):
"""
Closes the tree popup and sets the current record.
:param record | <orb.Table>
"""
record = item.record()
self.treePopupWidget().close()
self.setCurrentRecord(record) | [
"def",
"acceptRecord",
"(",
"self",
",",
"item",
")",
":",
"record",
"=",
"item",
".",
"record",
"(",
")",
"self",
".",
"treePopupWidget",
"(",
")",
".",
"close",
"(",
")",
"self",
".",
"setCurrentRecord",
"(",
"record",
")"
] | Closes the tree popup and sets the current record.
:param record | <orb.Table> | [
"Closes",
"the",
"tree",
"popup",
"and",
"sets",
"the",
"current",
"record",
".",
":",
"param",
"record",
"|",
"<orb",
".",
"Table",
">"
] | python | train | 30 |
aio-libs/aioredis | aioredis/pubsub.py | https://github.com/aio-libs/aioredis/blob/e8c33e39558d4cc91cf70dde490d8b330c97dc2e/aioredis/pubsub.py#L244-L283 | async def get(self, *, encoding=None, decoder=None):
"""Wait for and return pub/sub message from one of channels.
Return value is either:
* tuple of two elements: channel & message;
* tuple of three elements: pattern channel, (target channel & message);
* or None in case Rece... | [
"async",
"def",
"get",
"(",
"self",
",",
"*",
",",
"encoding",
"=",
"None",
",",
"decoder",
"=",
"None",
")",
":",
"# TODO: add note about raised exception and end marker.",
"# Flow before ClosableQueue:",
"# - ch.get() -> message",
"# - ch.close() -> ch.put(None)",
"... | Wait for and return pub/sub message from one of channels.
Return value is either:
* tuple of two elements: channel & message;
* tuple of three elements: pattern channel, (target channel & message);
* or None in case Receiver is not active or has just been stopped.
:raises ai... | [
"Wait",
"for",
"and",
"return",
"pub",
"/",
"sub",
"message",
"from",
"one",
"of",
"channels",
"."
] | python | train | 34.575 |
SmokinCaterpillar/pypet | pypet/environment.py | https://github.com/SmokinCaterpillar/pypet/blob/97ad3e80d46dbdea02deeb98ea41f05a19565826/pypet/environment.py#L99-L107 | def _frozen_pool_single_run(kwargs):
"""Single run wrapper for the frozen pool, makes a single run and passes kwargs"""
idx = kwargs.pop('idx')
frozen_kwargs = _frozen_pool_single_run.kwargs
frozen_kwargs.update(kwargs) # in case of `run_map`
# we need to update job's args and kwargs
traj = fro... | [
"def",
"_frozen_pool_single_run",
"(",
"kwargs",
")",
":",
"idx",
"=",
"kwargs",
".",
"pop",
"(",
"'idx'",
")",
"frozen_kwargs",
"=",
"_frozen_pool_single_run",
".",
"kwargs",
"frozen_kwargs",
".",
"update",
"(",
"kwargs",
")",
"# in case of `run_map`",
"# we need... | Single run wrapper for the frozen pool, makes a single run and passes kwargs | [
"Single",
"run",
"wrapper",
"for",
"the",
"frozen",
"pool",
"makes",
"a",
"single",
"run",
"and",
"passes",
"kwargs"
] | python | test | 45.444444 |
klen/muffin-session | muffin_session.py | https://github.com/klen/muffin-session/blob/f1d14d12b7d09d8cc40be14b0dfa0b1e2f4ae8e9/muffin_session.py#L130-L133 | async def login(self, request, id_):
"""Login an user by ID."""
session = await self.load(request)
session['id'] = id_ | [
"async",
"def",
"login",
"(",
"self",
",",
"request",
",",
"id_",
")",
":",
"session",
"=",
"await",
"self",
".",
"load",
"(",
"request",
")",
"session",
"[",
"'id'",
"]",
"=",
"id_"
] | Login an user by ID. | [
"Login",
"an",
"user",
"by",
"ID",
"."
] | python | train | 34.75 |
BlackEarth/bxml | bxml/schema.py | https://github.com/BlackEarth/bxml/blob/8fbea5dad7fadc7b854ddbeff6ecfb55aaceeb77/bxml/schema.py#L52-L119 | def xhtml(self, outfn=None, ext='.xhtml', css=None, **params):
"""convert the Schema to XHTML with the given output filename or with the given extension."""
from markdown import markdown
from copy import deepcopy
from bl.file import File
from .xslt import XSLT
from .rng i... | [
"def",
"xhtml",
"(",
"self",
",",
"outfn",
"=",
"None",
",",
"ext",
"=",
"'.xhtml'",
",",
"css",
"=",
"None",
",",
"*",
"*",
"params",
")",
":",
"from",
"markdown",
"import",
"markdown",
"from",
"copy",
"import",
"deepcopy",
"from",
"bl",
".",
"file"... | convert the Schema to XHTML with the given output filename or with the given extension. | [
"convert",
"the",
"Schema",
"to",
"XHTML",
"with",
"the",
"given",
"output",
"filename",
"or",
"with",
"the",
"given",
"extension",
"."
] | python | train | 50.367647 |
Roastero/freshroastsr700 | freshroastsr700/__init__.py | https://github.com/Roastero/freshroastsr700/blob/49cf4961444c0f56d051d5ac5088ace480b54f02/freshroastsr700/__init__.py#L1071-L1092 | def generate_bangbang_output(self):
"""Generates the latest on or off pulse in
the string of on (True) or off (False) pulses
according to the desired heat_level setting. Successive calls
to this function will return the next value in the
on/off array series. Call th... | [
"def",
"generate_bangbang_output",
"(",
"self",
")",
":",
"if",
"self",
".",
"_current_index",
">=",
"self",
".",
"_num_segments",
":",
"# we're due to switch over to the next",
"# commanded heat_level",
"self",
".",
"_heat_level_now",
"=",
"self",
".",
"_heat_level",
... | Generates the latest on or off pulse in
the string of on (True) or off (False) pulses
according to the desired heat_level setting. Successive calls
to this function will return the next value in the
on/off array series. Call this at control loop rate to
obtain th... | [
"Generates",
"the",
"latest",
"on",
"or",
"off",
"pulse",
"in",
"the",
"string",
"of",
"on",
"(",
"True",
")",
"or",
"off",
"(",
"False",
")",
"pulses",
"according",
"to",
"the",
"desired",
"heat_level",
"setting",
".",
"Successive",
"calls",
"to",
"this... | python | train | 52.545455 |
AtsushiSakai/SimpleTkGUIKit | SimpleTkGUIKit/SimpleTkGUIKit.py | https://github.com/AtsushiSakai/SimpleTkGUIKit/blob/e7cbb06ff32afb165cdaa4fe396ca2f172c66ff0/SimpleTkGUIKit/SimpleTkGUIKit.py#L134-L167 | def GetEntries(dataList, title="Select", msg=""):
"""
Get entries of the list
title: Window name
mag: Label of the check button
return data dictionary like:
{'y': '5.0', 'x': '100', 'z': 'save'}
"""
root = tkinter.Tk()
root.title(title)
label = tkinter.Label(root, text=msg)
... | [
"def",
"GetEntries",
"(",
"dataList",
",",
"title",
"=",
"\"Select\"",
",",
"msg",
"=",
"\"\"",
")",
":",
"root",
"=",
"tkinter",
".",
"Tk",
"(",
")",
"root",
".",
"title",
"(",
"title",
")",
"label",
"=",
"tkinter",
".",
"Label",
"(",
"root",
",",... | Get entries of the list
title: Window name
mag: Label of the check button
return data dictionary like:
{'y': '5.0', 'x': '100', 'z': 'save'} | [
"Get",
"entries",
"of",
"the",
"list"
] | python | train | 22.058824 |
Dallinger/Dallinger | dallinger/models.py | https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/models.py#L432-L450 | def infos(self, type=None, failed=False):
"""
Get infos in the network.
type specifies the type of info (defaults to Info). failed { False,
True, "all" } specifies the failed state of the infos. To get infos
from a specific node, see the infos() method in class
:class:`~... | [
"def",
"infos",
"(",
"self",
",",
"type",
"=",
"None",
",",
"failed",
"=",
"False",
")",
":",
"if",
"type",
"is",
"None",
":",
"type",
"=",
"Info",
"if",
"failed",
"not",
"in",
"[",
"\"all\"",
",",
"False",
",",
"True",
"]",
":",
"raise",
"ValueE... | Get infos in the network.
type specifies the type of info (defaults to Info). failed { False,
True, "all" } specifies the failed state of the infos. To get infos
from a specific node, see the infos() method in class
:class:`~dallinger.models.Node`. | [
"Get",
"infos",
"in",
"the",
"network",
"."
] | python | train | 36.631579 |
CalebBell/fluids | fluids/control_valve.py | https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/control_valve.py#L208-L256 | def control_valve_choke_P_g(xT, gamma, P1=None, P2=None):
r'''Calculates either the upstream or downstream pressure at which choked
flow though a gas control valve occurs, given either a set upstream or
downstream pressure. Implements an analytical solution of
the needed equations from the full functi... | [
"def",
"control_valve_choke_P_g",
"(",
"xT",
",",
"gamma",
",",
"P1",
"=",
"None",
",",
"P2",
"=",
"None",
")",
":",
"if",
"P2",
"is",
"None",
":",
"ans",
"=",
"P2",
"=",
"P1",
"*",
"(",
"-",
"5.0",
"*",
"gamma",
"*",
"xT",
"+",
"7.0",
")",
"... | r'''Calculates either the upstream or downstream pressure at which choked
flow though a gas control valve occurs, given either a set upstream or
downstream pressure. Implements an analytical solution of
the needed equations from the full function
:py:func:`~.size_control_valve_g`. A singularity arises... | [
"r",
"Calculates",
"either",
"the",
"upstream",
"or",
"downstream",
"pressure",
"at",
"which",
"choked",
"flow",
"though",
"a",
"gas",
"control",
"valve",
"occurs",
"given",
"either",
"a",
"set",
"upstream",
"or",
"downstream",
"pressure",
".",
"Implements",
"... | python | train | 30.102041 |
senaite/senaite.jsonapi | src/senaite/jsonapi/api.py | https://github.com/senaite/senaite.jsonapi/blob/871959f4b1c9edbb477e9456325527ca78e13ec6/src/senaite/jsonapi/api.py#L560-L570 | def search(**kw):
"""Search the catalog adapter
:returns: Catalog search results
:rtype: iterable
"""
portal = get_portal()
catalog = ICatalog(portal)
catalog_query = ICatalogQuery(catalog)
query = catalog_query.make_query(**kw)
return catalog(query) | [
"def",
"search",
"(",
"*",
"*",
"kw",
")",
":",
"portal",
"=",
"get_portal",
"(",
")",
"catalog",
"=",
"ICatalog",
"(",
"portal",
")",
"catalog_query",
"=",
"ICatalogQuery",
"(",
"catalog",
")",
"query",
"=",
"catalog_query",
".",
"make_query",
"(",
"*",... | Search the catalog adapter
:returns: Catalog search results
:rtype: iterable | [
"Search",
"the",
"catalog",
"adapter"
] | python | train | 25.181818 |
ralphbean/bugwarrior | bugwarrior/services/github.py | https://github.com/ralphbean/bugwarrior/blob/b2a5108f7b40cb0c437509b64eaa28f941f7ac8b/bugwarrior/services/github.py#L26-L32 | def _api_url(self, path, **context):
""" Build the full url to the API endpoint """
if self.host == 'github.com':
baseurl = "https://api.github.com"
else:
baseurl = "https://{}/api/v3".format(self.host)
return baseurl + path.format(**context) | [
"def",
"_api_url",
"(",
"self",
",",
"path",
",",
"*",
"*",
"context",
")",
":",
"if",
"self",
".",
"host",
"==",
"'github.com'",
":",
"baseurl",
"=",
"\"https://api.github.com\"",
"else",
":",
"baseurl",
"=",
"\"https://{}/api/v3\"",
".",
"format",
"(",
"... | Build the full url to the API endpoint | [
"Build",
"the",
"full",
"url",
"to",
"the",
"API",
"endpoint"
] | python | test | 41.714286 |
mcs07/ChemDataExtractor | chemdataextractor/text/processors.py | https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/text/processors.py#L159-L165 | def extract_emails(text):
"""Return a list of email addresses extracted from the string."""
text = text.replace(u'\u2024', '.')
emails = []
for m in EMAIL_RE.findall(text):
emails.append(m[0])
return emails | [
"def",
"extract_emails",
"(",
"text",
")",
":",
"text",
"=",
"text",
".",
"replace",
"(",
"u'\\u2024'",
",",
"'.'",
")",
"emails",
"=",
"[",
"]",
"for",
"m",
"in",
"EMAIL_RE",
".",
"findall",
"(",
"text",
")",
":",
"emails",
".",
"append",
"(",
"m"... | Return a list of email addresses extracted from the string. | [
"Return",
"a",
"list",
"of",
"email",
"addresses",
"extracted",
"from",
"the",
"string",
"."
] | python | train | 32.571429 |
droope/droopescan | dscan/common/functions.py | https://github.com/droope/droopescan/blob/424c48a0f9d12b4536dbef5a786f0fbd4ce9519a/dscan/common/functions.py#L246-L275 | def tail(f, window=20):
"""
Returns the last `window` lines of file `f` as a list.
@param window: the number of lines.
"""
if window == 0:
return []
BUFSIZ = 1024
f.seek(0, 2)
bytes = f.tell()
size = window + 1
block = -1
data = []
while size > 0 and bytes > 0:
... | [
"def",
"tail",
"(",
"f",
",",
"window",
"=",
"20",
")",
":",
"if",
"window",
"==",
"0",
":",
"return",
"[",
"]",
"BUFSIZ",
"=",
"1024",
"f",
".",
"seek",
"(",
"0",
",",
"2",
")",
"bytes",
"=",
"f",
".",
"tell",
"(",
")",
"size",
"=",
"windo... | Returns the last `window` lines of file `f` as a list.
@param window: the number of lines. | [
"Returns",
"the",
"last",
"window",
"lines",
"of",
"file",
"f",
"as",
"a",
"list",
"."
] | python | train | 28.833333 |
csparpa/pyowm | pyowm/commons/frontlinkedlist.py | https://github.com/csparpa/pyowm/blob/cdd59eb72f32f7238624ceef9b2e2329a5ebd472/pyowm/commons/frontlinkedlist.py#L203-L215 | def contains(self, data):
"""
Checks if the provided data is stored in at least one node of the list.
:param data: the seeked data
:type data: object
:returns: a boolean
"""
for item in self:
if item.data() == data:
return True
... | [
"def",
"contains",
"(",
"self",
",",
"data",
")",
":",
"for",
"item",
"in",
"self",
":",
"if",
"item",
".",
"data",
"(",
")",
"==",
"data",
":",
"return",
"True",
"return",
"False"
] | Checks if the provided data is stored in at least one node of the list.
:param data: the seeked data
:type data: object
:returns: a boolean | [
"Checks",
"if",
"the",
"provided",
"data",
"is",
"stored",
"in",
"at",
"least",
"one",
"node",
"of",
"the",
"list",
"."
] | python | train | 24.769231 |
pallets/werkzeug | src/werkzeug/security.py | https://github.com/pallets/werkzeug/blob/a220671d66755a94630a212378754bb432811158/src/werkzeug/security.py#L224-L241 | def safe_join(directory, *pathnames):
"""Safely join `directory` and one or more untrusted `pathnames`. If this
cannot be done, this function returns ``None``.
:param directory: the base directory.
:param pathnames: the untrusted pathnames relative to that directory.
"""
parts = [directory]
... | [
"def",
"safe_join",
"(",
"directory",
",",
"*",
"pathnames",
")",
":",
"parts",
"=",
"[",
"directory",
"]",
"for",
"filename",
"in",
"pathnames",
":",
"if",
"filename",
"!=",
"\"\"",
":",
"filename",
"=",
"posixpath",
".",
"normpath",
"(",
"filename",
")... | Safely join `directory` and one or more untrusted `pathnames`. If this
cannot be done, this function returns ``None``.
:param directory: the base directory.
:param pathnames: the untrusted pathnames relative to that directory. | [
"Safely",
"join",
"directory",
"and",
"one",
"or",
"more",
"untrusted",
"pathnames",
".",
"If",
"this",
"cannot",
"be",
"done",
"this",
"function",
"returns",
"None",
"."
] | python | train | 37.666667 |
althonos/pronto | pronto/synonym.py | https://github.com/althonos/pronto/blob/a768adcba19fb34f26f67cde4a03d317f932c274/pronto/synonym.py#L142-L150 | def obo(self):
"""str: the synonym serialized in obo format.
"""
return 'synonym: "{}" {} [{}]'.format(
self.desc,
' '.join([self.scope, self.syn_type.name])\
if self.syn_type else self.scope,
', '.join(self.xref)
) | [
"def",
"obo",
"(",
"self",
")",
":",
"return",
"'synonym: \"{}\" {} [{}]'",
".",
"format",
"(",
"self",
".",
"desc",
",",
"' '",
".",
"join",
"(",
"[",
"self",
".",
"scope",
",",
"self",
".",
"syn_type",
".",
"name",
"]",
")",
"if",
"self",
".",
"s... | str: the synonym serialized in obo format. | [
"str",
":",
"the",
"synonym",
"serialized",
"in",
"obo",
"format",
"."
] | python | train | 32.333333 |
robertpeteuil/aws-shortcuts | awss/core.py | https://github.com/robertpeteuil/aws-shortcuts/blob/cf453ca996978a4d88015d1cf6125bce8ca4873b/awss/core.py#L204-L242 | def cmd_ssh(options):
"""Connect to the specified instance via ssh.
Finds instances that match the user specified args that are also
in the 'running' state. The target instance is determined, the
required connection information is retreived (IP, key and ssh
user-name), then an 'ssh' connection is ... | [
"def",
"cmd_ssh",
"(",
"options",
")",
":",
"import",
"os",
"import",
"subprocess",
"from",
"os",
".",
"path",
"import",
"expanduser",
"options",
".",
"inst_state",
"=",
"\"running\"",
"(",
"i_info",
",",
"param_str",
")",
"=",
"gather_data",
"(",
"options",... | Connect to the specified instance via ssh.
Finds instances that match the user specified args that are also
in the 'running' state. The target instance is determined, the
required connection information is retreived (IP, key and ssh
user-name), then an 'ssh' connection is made to the instance.
Ar... | [
"Connect",
"to",
"the",
"specified",
"instance",
"via",
"ssh",
"."
] | python | train | 40.820513 |
googledatalab/pydatalab | google/datalab/utils/commands/_html.py | https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/utils/commands/_html.py#L64-L84 | def _repr_html_(self):
"""Generates the HTML representation.
"""
parts = []
if self._class:
parts.append('<div id="hh_%s" class="%s">%s</div>' % (self._id, self._class, self._markup))
else:
parts.append('<div id="hh_%s">%s</div>' % (self._id, self._markup))
if len(self._script) != 0... | [
"def",
"_repr_html_",
"(",
"self",
")",
":",
"parts",
"=",
"[",
"]",
"if",
"self",
".",
"_class",
":",
"parts",
".",
"append",
"(",
"'<div id=\"hh_%s\" class=\"%s\">%s</div>'",
"%",
"(",
"self",
".",
"_id",
",",
"self",
".",
"_class",
",",
"self",
".",
... | Generates the HTML representation. | [
"Generates",
"the",
"HTML",
"representation",
"."
] | python | train | 32.47619 |
gabstopper/smc-python | smc/base/model.py | https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/base/model.py#L162-L169 | def etag(self, href):
"""
ETag can be None if a subset of element json is using
this container, such as the case with Routing.
"""
if self and self._etag is None:
self._etag = LoadElement(href, only_etag=True)
return self._etag | [
"def",
"etag",
"(",
"self",
",",
"href",
")",
":",
"if",
"self",
"and",
"self",
".",
"_etag",
"is",
"None",
":",
"self",
".",
"_etag",
"=",
"LoadElement",
"(",
"href",
",",
"only_etag",
"=",
"True",
")",
"return",
"self",
".",
"_etag"
] | ETag can be None if a subset of element json is using
this container, such as the case with Routing. | [
"ETag",
"can",
"be",
"None",
"if",
"a",
"subset",
"of",
"element",
"json",
"is",
"using",
"this",
"container",
"such",
"as",
"the",
"case",
"with",
"Routing",
"."
] | python | train | 35 |
dslackw/slpkg | slpkg/init.py | https://github.com/dslackw/slpkg/blob/dd2e08a80e944d337d157b992167ba631a4343de/slpkg/init.py#L659-L664 | def down(self, path, link, repo):
"""Download files
"""
filename = link.split("/")[-1]
if not os.path.isfile(path + filename):
Download(path, link.split(), repo).start() | [
"def",
"down",
"(",
"self",
",",
"path",
",",
"link",
",",
"repo",
")",
":",
"filename",
"=",
"link",
".",
"split",
"(",
"\"/\"",
")",
"[",
"-",
"1",
"]",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"path",
"+",
"filename",
")",
":",
... | Download files | [
"Download",
"files"
] | python | train | 34.666667 |
apetrynet/pyfilemail | pyfilemail/users.py | https://github.com/apetrynet/pyfilemail/blob/eb81b0e69ff42f4335d5298833e4769b750bf397/pyfilemail/users.py#L592-L617 | def update_company(self, company):
"""Update company settings
:param company: updated settings
:type company: ``dict``
:rtype: ``bool``
"""
if not isinstance(company, dict):
raise AttributeError('company must be a <dict>')
method, url = get_URL('com... | [
"def",
"update_company",
"(",
"self",
",",
"company",
")",
":",
"if",
"not",
"isinstance",
"(",
"company",
",",
"dict",
")",
":",
"raise",
"AttributeError",
"(",
"'company must be a <dict>'",
")",
"method",
",",
"url",
"=",
"get_URL",
"(",
"'company_update'",
... | Update company settings
:param company: updated settings
:type company: ``dict``
:rtype: ``bool`` | [
"Update",
"company",
"settings"
] | python | train | 24.653846 |
Clinical-Genomics/scout | scout/server/blueprints/variants/controllers.py | https://github.com/Clinical-Genomics/scout/blob/90a551e2e1653a319e654c2405c2866f93d0ebb9/scout/server/blueprints/variants/controllers.py#L72-L75 | def str_variants(store, institute_obj, case_obj, variants_query, page=1, per_page=50):
"""Pre-process list of STR variants."""
# Nothing unique to STRs on this level. Inheritance?
return variants(store, institute_obj, case_obj, variants_query, page, per_page) | [
"def",
"str_variants",
"(",
"store",
",",
"institute_obj",
",",
"case_obj",
",",
"variants_query",
",",
"page",
"=",
"1",
",",
"per_page",
"=",
"50",
")",
":",
"# Nothing unique to STRs on this level. Inheritance?",
"return",
"variants",
"(",
"store",
",",
"instit... | Pre-process list of STR variants. | [
"Pre",
"-",
"process",
"list",
"of",
"STR",
"variants",
"."
] | python | test | 67 |
rackerlabs/fleece | fleece/cli/run/run.py | https://github.com/rackerlabs/fleece/blob/42d79dfa0777e99dbb09bc46105449a9be5dbaa9/fleece/cli/run/run.py#L80-L96 | def assume_role(credentials, account, role):
"""Use FAWS provided credentials to assume defined role."""
sts = boto3.client(
'sts',
aws_access_key_id=credentials['accessKeyId'],
aws_secret_access_key=credentials['secretAccessKey'],
aws_session_token=credentials['sessionToken'],
... | [
"def",
"assume_role",
"(",
"credentials",
",",
"account",
",",
"role",
")",
":",
"sts",
"=",
"boto3",
".",
"client",
"(",
"'sts'",
",",
"aws_access_key_id",
"=",
"credentials",
"[",
"'accessKeyId'",
"]",
",",
"aws_secret_access_key",
"=",
"credentials",
"[",
... | Use FAWS provided credentials to assume defined role. | [
"Use",
"FAWS",
"provided",
"credentials",
"to",
"assume",
"defined",
"role",
"."
] | python | train | 38.764706 |
tensorforce/tensorforce | tensorforce/models/model.py | https://github.com/tensorforce/tensorforce/blob/520a8d992230e382f08e315ede5fc477f5e26bfb/tensorforce/models/model.py#L1515-L1540 | def save(self, directory=None, append_timestep=True):
"""
Save TensorFlow model. If no checkpoint directory is given, the model's default saver
directory is used. Optionally appends current timestep to prevent overwriting previous
checkpoint files. Turn off to be able to load model from ... | [
"def",
"save",
"(",
"self",
",",
"directory",
"=",
"None",
",",
"append_timestep",
"=",
"True",
")",
":",
"if",
"self",
".",
"flush_summarizer",
"is",
"not",
"None",
":",
"self",
".",
"monitored_session",
".",
"run",
"(",
"fetches",
"=",
"self",
".",
"... | Save TensorFlow model. If no checkpoint directory is given, the model's default saver
directory is used. Optionally appends current timestep to prevent overwriting previous
checkpoint files. Turn off to be able to load model from the same given path argument as
given here.
Args:
... | [
"Save",
"TensorFlow",
"model",
".",
"If",
"no",
"checkpoint",
"directory",
"is",
"given",
"the",
"model",
"s",
"default",
"saver",
"directory",
"is",
"used",
".",
"Optionally",
"appends",
"current",
"timestep",
"to",
"prevent",
"overwriting",
"previous",
"checkp... | python | valid | 42.538462 |
Jajcus/pyxmpp2 | pyxmpp2/jid.py | https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/jid.py#L65-L90 | def _validate_ip_address(family, address):
"""Check if `address` is valid IP address and return it, in a normalized
form.
:Parameters:
- `family`: ``socket.AF_INET`` or ``socket.AF_INET6``
- `address`: the IP address to validate
"""
try:
info = socket.getaddrinfo(address, 0,... | [
"def",
"_validate_ip_address",
"(",
"family",
",",
"address",
")",
":",
"try",
":",
"info",
"=",
"socket",
".",
"getaddrinfo",
"(",
"address",
",",
"0",
",",
"family",
",",
"socket",
".",
"SOCK_STREAM",
",",
"0",
",",
"socket",
".",
"AI_NUMERICHOST",
")"... | Check if `address` is valid IP address and return it, in a normalized
form.
:Parameters:
- `family`: ``socket.AF_INET`` or ``socket.AF_INET6``
- `address`: the IP address to validate | [
"Check",
"if",
"address",
"is",
"valid",
"IP",
"address",
"and",
"return",
"it",
"in",
"a",
"normalized",
"form",
"."
] | python | valid | 36.653846 |
gwastro/pycbc | pycbc/_version_helper.py | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/_version_helper.py#L106-L113 | def get_git_branch(git_path='git'):
"""Returns the name of the current git branch
"""
branch_match = call((git_path, 'rev-parse', '--symbolic-full-name', 'HEAD'))
if branch_match == "HEAD":
return None
else:
return os.path.basename(branch_match) | [
"def",
"get_git_branch",
"(",
"git_path",
"=",
"'git'",
")",
":",
"branch_match",
"=",
"call",
"(",
"(",
"git_path",
",",
"'rev-parse'",
",",
"'--symbolic-full-name'",
",",
"'HEAD'",
")",
")",
"if",
"branch_match",
"==",
"\"HEAD\"",
":",
"return",
"None",
"e... | Returns the name of the current git branch | [
"Returns",
"the",
"name",
"of",
"the",
"current",
"git",
"branch"
] | python | train | 34.25 |
dakrauth/django-swingtime | swingtime/forms.py | https://github.com/dakrauth/django-swingtime/blob/d1cdd449bd5c6895c3ff182fd890c4d3452943fe/swingtime/forms.py#L126-L151 | def timeslot_offset_options(
interval=swingtime_settings.TIMESLOT_INTERVAL,
start_time=swingtime_settings.TIMESLOT_START_TIME,
end_delta=swingtime_settings.TIMESLOT_END_TIME_DURATION,
fmt=swingtime_settings.TIMESLOT_TIME_FORMAT
):
'''
Create a list of time slot options for use in swingtime forms... | [
"def",
"timeslot_offset_options",
"(",
"interval",
"=",
"swingtime_settings",
".",
"TIMESLOT_INTERVAL",
",",
"start_time",
"=",
"swingtime_settings",
".",
"TIMESLOT_START_TIME",
",",
"end_delta",
"=",
"swingtime_settings",
".",
"TIMESLOT_END_TIME_DURATION",
",",
"fmt",
"=... | Create a list of time slot options for use in swingtime forms.
The list is comprised of 2-tuples containing the number of seconds since the
start of the day and a 12-hour temporal representation of that offset. | [
"Create",
"a",
"list",
"of",
"time",
"slot",
"options",
"for",
"use",
"in",
"swingtime",
"forms",
"."
] | python | train | 33.961538 |
rameshg87/pyremotevbox | pyremotevbox/ZSI/TCtimes.py | https://github.com/rameshg87/pyremotevbox/blob/123dffff27da57c8faa3ac1dd4c68b1cf4558b1a/pyremotevbox/ZSI/TCtimes.py#L46-L51 | def utcoffset(self, dt):
"""datetime -> minutes east of UTC (negative for west of UTC)."""
tt = _localtime(_mktime((dt.year, dt.month, dt.day,
dt.hour, dt.minute, dt.second, dt.weekday(), 0, -1)))
if tt.tm_isdst > 0: return _dstoffset
return _stdoffset | [
"def",
"utcoffset",
"(",
"self",
",",
"dt",
")",
":",
"tt",
"=",
"_localtime",
"(",
"_mktime",
"(",
"(",
"dt",
".",
"year",
",",
"dt",
".",
"month",
",",
"dt",
".",
"day",
",",
"dt",
".",
"hour",
",",
"dt",
".",
"minute",
",",
"dt",
".",
"sec... | datetime -> minutes east of UTC (negative for west of UTC). | [
"datetime",
"-",
">",
"minutes",
"east",
"of",
"UTC",
"(",
"negative",
"for",
"west",
"of",
"UTC",
")",
"."
] | python | train | 49.333333 |
improbable-research/keanu | keanu-python/keanu/functional/biconsumer.py | https://github.com/improbable-research/keanu/blob/73189a8f569078e156168e795f82c7366c59574b/keanu-python/keanu/functional/biconsumer.py#L13-L19 | def accept(self, arg1: JavaObject, arg2: JavaObject) -> None:
"""
>>> c = BiConsumer(lambda x,y : print(x + y))
>>> c.accept("foo", "bar")
foobar
"""
self.lambda_function(arg1, arg2) | [
"def",
"accept",
"(",
"self",
",",
"arg1",
":",
"JavaObject",
",",
"arg2",
":",
"JavaObject",
")",
"->",
"None",
":",
"self",
".",
"lambda_function",
"(",
"arg1",
",",
"arg2",
")"
] | >>> c = BiConsumer(lambda x,y : print(x + y))
>>> c.accept("foo", "bar")
foobar | [
">>>",
"c",
"=",
"BiConsumer",
"(",
"lambda",
"x",
"y",
":",
"print",
"(",
"x",
"+",
"y",
"))",
">>>",
"c",
".",
"accept",
"(",
"foo",
"bar",
")",
"foobar"
] | python | train | 32 |
AguaClara/aide_document-DEPRECATED | aide_document/combine.py | https://github.com/AguaClara/aide_document-DEPRECATED/blob/3f3b5c9f321264e0e4d8ed68dfbc080762579815/aide_document/combine.py#L5-L37 | def render_document(template_name, data_name, output_name):
"""
Combines a MarkDown template file from the aide_document package with a local associated YAML data file, then outputs the rendered combination to a local MarkDown output file.
Parameters
==========
template_name : String
Exact ... | [
"def",
"render_document",
"(",
"template_name",
",",
"data_name",
",",
"output_name",
")",
":",
"# Set up environment and load templates from pip package",
"env",
"=",
"Environment",
"(",
"loader",
"=",
"PackageLoader",
"(",
"'aide_document'",
")",
")",
"#TODO: add custom... | Combines a MarkDown template file from the aide_document package with a local associated YAML data file, then outputs the rendered combination to a local MarkDown output file.
Parameters
==========
template_name : String
Exact name of the MarkDown template file from the aide_document/templates fold... | [
"Combines",
"a",
"MarkDown",
"template",
"file",
"from",
"the",
"aide_document",
"package",
"with",
"a",
"local",
"associated",
"YAML",
"data",
"file",
"then",
"outputs",
"the",
"rendered",
"combination",
"to",
"a",
"local",
"MarkDown",
"output",
"file",
"."
] | python | train | 44.181818 |
frascoweb/easywebassets | easywebassets/package.py | https://github.com/frascoweb/easywebassets/blob/02f84376067c827c84fc1773895bb2784e033949/easywebassets/package.py#L80-L94 | def _yield_bundle_contents(self, data):
"""Yield bundle contents from the given dict.
Each item yielded will be either a string representing a file path
or a bundle."""
if isinstance(data, list):
contents = data
else:
contents = data.get('contents', [])
... | [
"def",
"_yield_bundle_contents",
"(",
"self",
",",
"data",
")",
":",
"if",
"isinstance",
"(",
"data",
",",
"list",
")",
":",
"contents",
"=",
"data",
"else",
":",
"contents",
"=",
"data",
".",
"get",
"(",
"'contents'",
",",
"[",
"]",
")",
"if",
"isin... | Yield bundle contents from the given dict.
Each item yielded will be either a string representing a file path
or a bundle. | [
"Yield",
"bundle",
"contents",
"from",
"the",
"given",
"dict",
"."
] | python | test | 36.8 |
tensorflow/tensor2tensor | tensor2tensor/models/evolved_transformer.py | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/evolved_transformer.py#L759-L765 | def evolved_transformer_big_tpu():
"""Big parameters for Evolved Transformer model on TPU."""
hparams = add_evolved_transformer_hparams(transformer.transformer_big_tpu())
hparams.learning_rate_constant = 1 / hparams.learning_rate_warmup_steps ** 0.5
hparams.learning_rate_schedule = (
"constant*single_cycl... | [
"def",
"evolved_transformer_big_tpu",
"(",
")",
":",
"hparams",
"=",
"add_evolved_transformer_hparams",
"(",
"transformer",
".",
"transformer_big_tpu",
"(",
")",
")",
"hparams",
".",
"learning_rate_constant",
"=",
"1",
"/",
"hparams",
".",
"learning_rate_warmup_steps",
... | Big parameters for Evolved Transformer model on TPU. | [
"Big",
"parameters",
"for",
"Evolved",
"Transformer",
"model",
"on",
"TPU",
"."
] | python | train | 49.142857 |
IdentityPython/SATOSA | src/satosa/backends/openid_connect.py | https://github.com/IdentityPython/SATOSA/blob/49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb/src/satosa/backends/openid_connect.py#L238-L272 | def _create_client(provider_metadata, client_metadata, verify_ssl=True):
"""
Create a pyoidc client instance.
:param provider_metadata: provider configuration information
:type provider_metadata: Mapping[str, Union[str, Sequence[str]]]
:param client_metadata: client metadata
:type client_metadat... | [
"def",
"_create_client",
"(",
"provider_metadata",
",",
"client_metadata",
",",
"verify_ssl",
"=",
"True",
")",
":",
"client",
"=",
"oic",
".",
"Client",
"(",
"client_authn_method",
"=",
"CLIENT_AUTHN_METHOD",
",",
"verify_ssl",
"=",
"verify_ssl",
")",
"# Provider... | Create a pyoidc client instance.
:param provider_metadata: provider configuration information
:type provider_metadata: Mapping[str, Union[str, Sequence[str]]]
:param client_metadata: client metadata
:type client_metadata: Mapping[str, Union[str, Sequence[str]]]
:return: client instance to use for co... | [
"Create",
"a",
"pyoidc",
"client",
"instance",
".",
":",
"param",
"provider_metadata",
":",
"provider",
"configuration",
"information",
":",
"type",
"provider_metadata",
":",
"Mapping",
"[",
"str",
"Union",
"[",
"str",
"Sequence",
"[",
"str",
"]]]",
":",
"para... | python | train | 41.714286 |
pydanny-archive/dj-libcloud | djlibcloud/storage.py | https://github.com/pydanny-archive/dj-libcloud/blob/dc485ed56a8dec9f5f200e1effb91f6113353aa4/djlibcloud/storage.py#L116-L120 | def delete(self, name):
"""Delete object on remote"""
obj = self._get_object(name)
if obj:
return self.driver.delete_object(obj) | [
"def",
"delete",
"(",
"self",
",",
"name",
")",
":",
"obj",
"=",
"self",
".",
"_get_object",
"(",
"name",
")",
"if",
"obj",
":",
"return",
"self",
".",
"driver",
".",
"delete_object",
"(",
"obj",
")"
] | Delete object on remote | [
"Delete",
"object",
"on",
"remote"
] | python | train | 32 |
spacetelescope/synphot_refactor | synphot/utils.py | https://github.com/spacetelescope/synphot_refactor/blob/9c064f3cff0c41dd8acadc0f67c6350931275b9f/synphot/utils.py#L54-L73 | def validate_totalflux(totalflux):
"""Check integrated flux for invalid values.
Parameters
----------
totalflux : float
Integrated flux.
Raises
------
synphot.exceptions.SynphotError
Input is zero, negative, or not a number.
"""
if totalflux <= 0.0:
raise e... | [
"def",
"validate_totalflux",
"(",
"totalflux",
")",
":",
"if",
"totalflux",
"<=",
"0.0",
":",
"raise",
"exceptions",
".",
"SynphotError",
"(",
"'Integrated flux is <= 0'",
")",
"elif",
"np",
".",
"isnan",
"(",
"totalflux",
")",
":",
"raise",
"exceptions",
".",... | Check integrated flux for invalid values.
Parameters
----------
totalflux : float
Integrated flux.
Raises
------
synphot.exceptions.SynphotError
Input is zero, negative, or not a number. | [
"Check",
"integrated",
"flux",
"for",
"invalid",
"values",
"."
] | python | train | 27.15 |
doconix/django-mako-plus | django_mako_plus/management/mixins.py | https://github.com/doconix/django-mako-plus/blob/a90f9b4af19e5fa9f83452989cdcaed21569a181/django_mako_plus/management/mixins.py#L57-L60 | def message(self, msg='', level=1, tab=0):
'''Print a message to the console'''
if self.verbosity >= level:
self.stdout.write('{}{}'.format(' ' * tab, msg)) | [
"def",
"message",
"(",
"self",
",",
"msg",
"=",
"''",
",",
"level",
"=",
"1",
",",
"tab",
"=",
"0",
")",
":",
"if",
"self",
".",
"verbosity",
">=",
"level",
":",
"self",
".",
"stdout",
".",
"write",
"(",
"'{}{}'",
".",
"format",
"(",
"' '",
... | Print a message to the console | [
"Print",
"a",
"message",
"to",
"the",
"console"
] | python | train | 46 |
ozgurgunes/django-manifest | manifest/accounts/forms.py | https://github.com/ozgurgunes/django-manifest/blob/9873bbf2a475b76284ad7e36b2b26c92131e72dd/manifest/accounts/forms.py#L79-L91 | def save(self):
"""
Creates a new user and account. Returns the newly created user.
"""
username, email, password = (self.cleaned_data['username'],
self.cleaned_data['email'],
self.cleaned_data['password... | [
"def",
"save",
"(",
"self",
")",
":",
"username",
",",
"email",
",",
"password",
"=",
"(",
"self",
".",
"cleaned_data",
"[",
"'username'",
"]",
",",
"self",
".",
"cleaned_data",
"[",
"'email'",
"]",
",",
"self",
".",
"cleaned_data",
"[",
"'password1'",
... | Creates a new user and account. Returns the newly created user. | [
"Creates",
"a",
"new",
"user",
"and",
"account",
".",
"Returns",
"the",
"newly",
"created",
"user",
"."
] | python | train | 42.076923 |
aleontiev/dj | dj/application.py | https://github.com/aleontiev/dj/blob/0612d442fdd8d472aea56466568b9857556ecb51/dj/application.py#L349-L362 | def remove(self, addon, dev=False):
"""Remove a dependency and uninstall it."""
dependencies = self.get_dependency_manager(dev=dev)
other_dependencies = self.get_dependency_manager(dev=not dev)
self.stdout.write(style.format_command('Removing', addon))
removed = dependencies.remo... | [
"def",
"remove",
"(",
"self",
",",
"addon",
",",
"dev",
"=",
"False",
")",
":",
"dependencies",
"=",
"self",
".",
"get_dependency_manager",
"(",
"dev",
"=",
"dev",
")",
"other_dependencies",
"=",
"self",
".",
"get_dependency_manager",
"(",
"dev",
"=",
"not... | Remove a dependency and uninstall it. | [
"Remove",
"a",
"dependency",
"and",
"uninstall",
"it",
"."
] | python | train | 43.571429 |
tanghaibao/goatools | goatools/anno/factory.py | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/anno/factory.py#L13-L32 | def get_objanno(fin_anno, anno_type=None, **kws):
"""Read annotations in GAF, GPAD, Entrez gene2go, or text format."""
# kws get_objanno: taxids hdr_only prt allow_missing_symbol
anno_type = get_anno_desc(fin_anno, anno_type)
if anno_type is not None:
if anno_type == 'gene2go':
# kws... | [
"def",
"get_objanno",
"(",
"fin_anno",
",",
"anno_type",
"=",
"None",
",",
"*",
"*",
"kws",
")",
":",
"# kws get_objanno: taxids hdr_only prt allow_missing_symbol",
"anno_type",
"=",
"get_anno_desc",
"(",
"fin_anno",
",",
"anno_type",
")",
"if",
"anno_type",
"is",
... | Read annotations in GAF, GPAD, Entrez gene2go, or text format. | [
"Read",
"annotations",
"in",
"GAF",
"GPAD",
"Entrez",
"gene2go",
"or",
"text",
"format",
"."
] | python | train | 48.55 |
Grunny/zap-cli | zapcli/commands/policies.py | https://github.com/Grunny/zap-cli/blob/d58d4850ecfc5467badfac5e5bcc841d064bd419/zapcli/commands/policies.py#L29-L38 | def list_policies(zap_helper, policy_ids):
"""
Get a list of policies and whether or not they are enabled.
"""
policies = filter_by_ids(zap_helper.zap.ascan.policies(), policy_ids)
click.echo(tabulate([[p['id'], p['name'], p['enabled'], p['attackStrength'], p['alertThreshold']]
... | [
"def",
"list_policies",
"(",
"zap_helper",
",",
"policy_ids",
")",
":",
"policies",
"=",
"filter_by_ids",
"(",
"zap_helper",
".",
"zap",
".",
"ascan",
".",
"policies",
"(",
")",
",",
"policy_ids",
")",
"click",
".",
"echo",
"(",
"tabulate",
"(",
"[",
"["... | Get a list of policies and whether or not they are enabled. | [
"Get",
"a",
"list",
"of",
"policies",
"and",
"whether",
"or",
"not",
"they",
"are",
"enabled",
"."
] | python | train | 46.1 |
spyder-ide/spyder | spyder/plugins/findinfiles/widgets.py | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/findinfiles/widgets.py#L876-L904 | def append_result(self, results, num_matches):
"""Real-time update of search results"""
filename, lineno, colno, match_end, line = results
if filename not in self.files:
file_item = FileMatchItem(self, filename, self.sorting,
self.text_col... | [
"def",
"append_result",
"(",
"self",
",",
"results",
",",
"num_matches",
")",
":",
"filename",
",",
"lineno",
",",
"colno",
",",
"match_end",
",",
"line",
"=",
"results",
"if",
"filename",
"not",
"in",
"self",
".",
"files",
":",
"file_item",
"=",
"FileMa... | Real-time update of search results | [
"Real",
"-",
"time",
"update",
"of",
"search",
"results"
] | python | train | 40.137931 |
JdeRobot/base | src/drivers/MAVLinkServer/MAVProxy/tools/MAVExplorer.py | https://github.com/JdeRobot/base/blob/303b18992785b2fe802212f2d758a60873007f1f/src/drivers/MAVLinkServer/MAVProxy/tools/MAVExplorer.py#L311-L322 | def save_callback(operation, graphdef):
'''callback from save thread'''
if operation == 'test':
for e in graphdef.expressions:
if expression_ok(e):
graphdef.expression = e
display_graph(graphdef)
return
mestate.console.writeln('Invalid ... | [
"def",
"save_callback",
"(",
"operation",
",",
"graphdef",
")",
":",
"if",
"operation",
"==",
"'test'",
":",
"for",
"e",
"in",
"graphdef",
".",
"expressions",
":",
"if",
"expression_ok",
"(",
"e",
")",
":",
"graphdef",
".",
"expression",
"=",
"e",
"displ... | callback from save thread | [
"callback",
"from",
"save",
"thread"
] | python | train | 34.166667 |
gem/oq-engine | openquake/commonlib/hazard_writers.py | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/hazard_writers.py#L311-L422 | def rupture_to_element(rup, parent=None):
"""
Convert a rupture object into an Element object.
:param rup:
must have attributes .rupid, .events_by_ses and .seed
:param parent:
parent of the returned element, or None
"""
if parent is None:
parent = et.Element('root')
... | [
"def",
"rupture_to_element",
"(",
"rup",
",",
"parent",
"=",
"None",
")",
":",
"if",
"parent",
"is",
"None",
":",
"parent",
"=",
"et",
".",
"Element",
"(",
"'root'",
")",
"rup_elem",
"=",
"et",
".",
"SubElement",
"(",
"parent",
",",
"rup",
".",
"typo... | Convert a rupture object into an Element object.
:param rup:
must have attributes .rupid, .events_by_ses and .seed
:param parent:
parent of the returned element, or None | [
"Convert",
"a",
"rupture",
"object",
"into",
"an",
"Element",
"object",
"."
] | python | train | 42.401786 |
Alignak-monitoring/alignak | alignak/objects/config.py | https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/config.py#L2112-L2134 | def got_arbiter_module_type_defined(self, module_type):
"""Check if a module type is defined in one of the arbiters
Also check the module name
:param module_type: module type to search for
:type module_type: str
:return: True if mod_type is found else False
:rtype: bool
... | [
"def",
"got_arbiter_module_type_defined",
"(",
"self",
",",
"module_type",
")",
":",
"for",
"arbiter",
"in",
"self",
".",
"arbiters",
":",
"# Do like the linkify will do after....",
"for",
"module",
"in",
"getattr",
"(",
"arbiter",
",",
"'modules'",
",",
"[",
"]",... | Check if a module type is defined in one of the arbiters
Also check the module name
:param module_type: module type to search for
:type module_type: str
:return: True if mod_type is found else False
:rtype: bool
TODO: Factorize it with got_broker_module_type_defined: | [
"Check",
"if",
"a",
"module",
"type",
"is",
"defined",
"in",
"one",
"of",
"the",
"arbiters",
"Also",
"check",
"the",
"module",
"name"
] | python | train | 46.130435 |
OLC-LOC-Bioinformatics/GenomeQAML | genomeqaml/extract_features.py | https://github.com/OLC-LOC-Bioinformatics/GenomeQAML/blob/2953e574c185afab23075641da4ce5392bc003e9/genomeqaml/extract_features.py#L66-L79 | def filer(filelist):
"""
Helper script that creates a dictionary of the stain name: /sequencepath/strain_name.extension)
:param filelist: list of files to parse
:return filedict: dictionary of stain name: /sequencepath/strain_name.extension
"""
# Initialise the dictionary
filedict = dict()
... | [
"def",
"filer",
"(",
"filelist",
")",
":",
"# Initialise the dictionary",
"filedict",
"=",
"dict",
"(",
")",
"for",
"seqfile",
"in",
"filelist",
":",
"# Split off the file extension and remove the path from the name",
"strainname",
"=",
"os",
".",
"path",
".",
"splite... | Helper script that creates a dictionary of the stain name: /sequencepath/strain_name.extension)
:param filelist: list of files to parse
:return filedict: dictionary of stain name: /sequencepath/strain_name.extension | [
"Helper",
"script",
"that",
"creates",
"a",
"dictionary",
"of",
"the",
"stain",
"name",
":",
"/",
"sequencepath",
"/",
"strain_name",
".",
"extension",
")",
":",
"param",
"filelist",
":",
"list",
"of",
"files",
"to",
"parse",
":",
"return",
"filedict",
":"... | python | train | 40.571429 |
RobinNil/file_read_backwards | file_read_backwards/buffer_work_space.py | https://github.com/RobinNil/file_read_backwards/blob/e56443095b58aae309fbc43a0943eba867dc8500/file_read_backwards/buffer_work_space.py#L29-L40 | def add_to_buffer(self, content, read_position):
"""Add additional bytes content as read from the read_position.
Args:
content (bytes): data to be added to buffer working BufferWorkSpac.
read_position (int): where in the file pointer the data was read from.
"""
s... | [
"def",
"add_to_buffer",
"(",
"self",
",",
"content",
",",
"read_position",
")",
":",
"self",
".",
"read_position",
"=",
"read_position",
"if",
"self",
".",
"read_buffer",
"is",
"None",
":",
"self",
".",
"read_buffer",
"=",
"content",
"else",
":",
"self",
"... | Add additional bytes content as read from the read_position.
Args:
content (bytes): data to be added to buffer working BufferWorkSpac.
read_position (int): where in the file pointer the data was read from. | [
"Add",
"additional",
"bytes",
"content",
"as",
"read",
"from",
"the",
"read_position",
"."
] | python | train | 40.833333 |
airspeed-velocity/asv | asv/plugins/conda.py | https://github.com/airspeed-velocity/asv/blob/d23bb8b74e8adacbfa3cf5724bda55fb39d56ba6/asv/plugins/conda.py#L20-L48 | def _find_conda():
"""Find the conda executable robustly across conda versions.
Returns
-------
conda : str
Path to the conda executable.
Raises
------
IOError
If the executable cannot be found in either the CONDA_EXE environment
variable or in the PATH.
Notes
... | [
"def",
"_find_conda",
"(",
")",
":",
"if",
"'CONDA_EXE'",
"in",
"os",
".",
"environ",
":",
"conda",
"=",
"os",
".",
"environ",
"[",
"'CONDA_EXE'",
"]",
"else",
":",
"conda",
"=",
"util",
".",
"which",
"(",
"'conda'",
")",
"return",
"conda"
] | Find the conda executable robustly across conda versions.
Returns
-------
conda : str
Path to the conda executable.
Raises
------
IOError
If the executable cannot be found in either the CONDA_EXE environment
variable or in the PATH.
Notes
-----
In POSIX pla... | [
"Find",
"the",
"conda",
"executable",
"robustly",
"across",
"conda",
"versions",
"."
] | python | train | 30.344828 |
cloud9ers/gurumate | environment/lib/python2.7/site-packages/IPython/frontend/qt/console/ansi_code_processor.py | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/ansi_code_processor.py#L333-L356 | def get_format(self):
""" Returns a QTextCharFormat that encodes the current style attributes.
"""
format = QtGui.QTextCharFormat()
# Set foreground color
qcolor = self.get_color(self.foreground_color, self.intensity)
if qcolor is not None:
format.setForegrou... | [
"def",
"get_format",
"(",
"self",
")",
":",
"format",
"=",
"QtGui",
".",
"QTextCharFormat",
"(",
")",
"# Set foreground color",
"qcolor",
"=",
"self",
".",
"get_color",
"(",
"self",
".",
"foreground_color",
",",
"self",
".",
"intensity",
")",
"if",
"qcolor",... | Returns a QTextCharFormat that encodes the current style attributes. | [
"Returns",
"a",
"QTextCharFormat",
"that",
"encodes",
"the",
"current",
"style",
"attributes",
"."
] | python | test | 32.333333 |
bbusenius/Diablo-Python | commands.py | https://github.com/bbusenius/Diablo-Python/blob/646ac5a6f1c79cf9b928a4e2a7979988698b6c82/commands.py#L47-L117 | def run_excel_to_html():
"""
Run the excel_to_html function from the
command-line.
Args:
-p path to file
-s name of the sheet to convert
-css classes to apply
-m attempt to combine merged cells
-c caption for accessibility
-su summary for accessibility
... | [
"def",
"run_excel_to_html",
"(",
")",
":",
"# Capture commandline arguments. prog='' argument must",
"# match the command name in setup.py entry_points",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"prog",
"=",
"'excel_to_html'",
")",
"parser",
".",
"add_argument",
... | Run the excel_to_html function from the
command-line.
Args:
-p path to file
-s name of the sheet to convert
-css classes to apply
-m attempt to combine merged cells
-c caption for accessibility
-su summary for accessibility
-d details for accessibility
... | [
"Run",
"the",
"excel_to_html",
"function",
"from",
"the",
"command",
"-",
"line",
"."
] | python | valid | 30.873239 |
ryan-roemer/sphinx-bootstrap-theme | setup.py | https://github.com/ryan-roemer/sphinx-bootstrap-theme/blob/69585281a300116fa9da37c29c333ab1cc5462ce/setup.py#L21-L31 | def read_file(name):
"""Read file name (without extension) to string."""
cur_path = os.path.dirname(__file__)
exts = ('txt', 'rst')
for ext in exts:
path = os.path.join(cur_path, '.'.join((name, ext)))
if os.path.exists(path):
with open(path, 'rt') as file_obj:
... | [
"def",
"read_file",
"(",
"name",
")",
":",
"cur_path",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
"exts",
"=",
"(",
"'txt'",
",",
"'rst'",
")",
"for",
"ext",
"in",
"exts",
":",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
... | Read file name (without extension) to string. | [
"Read",
"file",
"name",
"(",
"without",
"extension",
")",
"to",
"string",
"."
] | python | train | 31.727273 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.