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 |
|---|---|---|---|---|---|---|---|---|---|
pyapi-gitlab/pyapi-gitlab | gitlab/__init__.py | https://github.com/pyapi-gitlab/pyapi-gitlab/blob/f74b6fb5c13cecae9524997847e928905cc60acf/gitlab/__init__.py#L1190-L1209 | def acceptmergerequest(self, project_id, mergerequest_id, merge_commit_message=None):
"""
Update an existing merge request.
:param project_id: ID of the project originating the merge request
:param mergerequest_id: ID of the merge request to accept
:param merge_commit_message: C... | [
"def",
"acceptmergerequest",
"(",
"self",
",",
"project_id",
",",
"mergerequest_id",
",",
"merge_commit_message",
"=",
"None",
")",
":",
"data",
"=",
"{",
"'merge_commit_message'",
":",
"merge_commit_message",
"}",
"request",
"=",
"requests",
".",
"put",
"(",
"'... | Update an existing merge request.
:param project_id: ID of the project originating the merge request
:param mergerequest_id: ID of the merge request to accept
:param merge_commit_message: Custom merge commit message
:return: dict of the modified merge request | [
"Update",
"an",
"existing",
"merge",
"request",
"."
] | python | train | 40.45 |
azavea/django-tinsel | django_tinsel/decorators.py | https://github.com/azavea/django-tinsel/blob/ef9e70750d98907b8f72248c1ba4c4423f04f60f/django_tinsel/decorators.py#L141-L156 | def username_matches_request_user(view_fn):
"""Checks if the username matches the request user, and if so replaces
username with the actual user object.
Returns 404 if the username does not exist, and 403 if it doesn't match.
"""
@wraps(view_fn)
def wrapper(request, username, *args, **kwargs):
... | [
"def",
"username_matches_request_user",
"(",
"view_fn",
")",
":",
"@",
"wraps",
"(",
"view_fn",
")",
"def",
"wrapper",
"(",
"request",
",",
"username",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"User",
"=",
"get_user_model",
"(",
")",
"user",
... | Checks if the username matches the request user, and if so replaces
username with the actual user object.
Returns 404 if the username does not exist, and 403 if it doesn't match. | [
"Checks",
"if",
"the",
"username",
"matches",
"the",
"request",
"user",
"and",
"if",
"so",
"replaces",
"username",
"with",
"the",
"actual",
"user",
"object",
".",
"Returns",
"404",
"if",
"the",
"username",
"does",
"not",
"exist",
"and",
"403",
"if",
"it",
... | python | train | 35.1875 |
cocaine/cocaine-tools | cocaine/tools/dispatch.py | https://github.com/cocaine/cocaine-tools/blob/d8834f8e04ca42817d5f4e368d471484d4b3419f/cocaine/tools/dispatch.py#L663-L673 | def app_view(name, **kwargs):
"""
Show manifest content for an application.
If application is not uploaded, an error will be displayed.
"""
ctx = Context(**kwargs)
ctx.execute_action('app:view', **{
'storage': ctx.repo.create_secure_service('storage'),
'name': name,
}) | [
"def",
"app_view",
"(",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"ctx",
"=",
"Context",
"(",
"*",
"*",
"kwargs",
")",
"ctx",
".",
"execute_action",
"(",
"'app:view'",
",",
"*",
"*",
"{",
"'storage'",
":",
"ctx",
".",
"repo",
".",
"create_secure_ser... | Show manifest content for an application.
If application is not uploaded, an error will be displayed. | [
"Show",
"manifest",
"content",
"for",
"an",
"application",
"."
] | python | train | 27.636364 |
SoCo/SoCo | soco/alarms.py | https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/alarms.py#L179-L183 | def volume(self, volume):
"""See `volume`."""
# max 100
volume = int(volume)
self._volume = max(0, min(volume, 100)) | [
"def",
"volume",
"(",
"self",
",",
"volume",
")",
":",
"# max 100",
"volume",
"=",
"int",
"(",
"volume",
")",
"self",
".",
"_volume",
"=",
"max",
"(",
"0",
",",
"min",
"(",
"volume",
",",
"100",
")",
")"
] | See `volume`. | [
"See",
"volume",
"."
] | python | train | 28.8 |
rgs1/zk_shell | zk_shell/keys.py | https://github.com/rgs1/zk_shell/blob/bbf34fdfcf1f81100e2a5816fad8af6afc782a54/zk_shell/keys.py#L95-L104 | def validate(cls, keystr):
""" raises cls.Bad if keys has errors """
if "#{" in keystr:
# it's a template with keys vars
keys = cls.from_template(keystr)
for k in keys:
cls.validate_one(cls.extract(k))
else:
# plain keys str
... | [
"def",
"validate",
"(",
"cls",
",",
"keystr",
")",
":",
"if",
"\"#{\"",
"in",
"keystr",
":",
"# it's a template with keys vars",
"keys",
"=",
"cls",
".",
"from_template",
"(",
"keystr",
")",
"for",
"k",
"in",
"keys",
":",
"cls",
".",
"validate_one",
"(",
... | raises cls.Bad if keys has errors | [
"raises",
"cls",
".",
"Bad",
"if",
"keys",
"has",
"errors"
] | python | train | 34 |
sqlalchemy-redshift/sqlalchemy-redshift | sqlalchemy_redshift/commands.py | https://github.com/sqlalchemy-redshift/sqlalchemy-redshift/blob/b1a24872da0c8151aa60da4524605b6243d8d765/sqlalchemy_redshift/commands.py#L217-L306 | def visit_unload_from_select(element, compiler, **kw):
"""Returns the actual sql query for the UnloadFromSelect class."""
template = """
UNLOAD (:select) TO :unload_location
CREDENTIALS :credentials
{manifest}
{header}
{delimiter}
{encrypted}
{fixed_width}
... | [
"def",
"visit_unload_from_select",
"(",
"element",
",",
"compiler",
",",
"*",
"*",
"kw",
")",
":",
"template",
"=",
"\"\"\"\n UNLOAD (:select) TO :unload_location\n CREDENTIALS :credentials\n {manifest}\n {header}\n {delimiter}\n {encrypted}\n {f... | Returns the actual sql query for the UnloadFromSelect class. | [
"Returns",
"the",
"actual",
"sql",
"query",
"for",
"the",
"UnloadFromSelect",
"class",
"."
] | python | train | 30.088889 |
Alveo/pyalveo | pyalveo/cache.py | https://github.com/Alveo/pyalveo/blob/1e9eec22bc031bc9a08066f9966565a546e6242e/pyalveo/cache.py#L175-L194 | def has_document(self, doc_url):
""" Check if the content of the given document is present
in the cache
If the max_age attribute of this Cache is set to a nonzero value,
entries older than the value of max_age in seconds will be ignored
:type doc_url: String or Document
... | [
"def",
"has_document",
"(",
"self",
",",
"doc_url",
")",
":",
"c",
"=",
"self",
".",
"conn",
".",
"cursor",
"(",
")",
"c",
".",
"execute",
"(",
"\"SELECT * FROM documents WHERE url=?\"",
",",
"(",
"str",
"(",
"doc_url",
")",
",",
")",
")",
"row",
"=",
... | Check if the content of the given document is present
in the cache
If the max_age attribute of this Cache is set to a nonzero value,
entries older than the value of max_age in seconds will be ignored
:type doc_url: String or Document
:param doc_url: the URL of the document, or ... | [
"Check",
"if",
"the",
"content",
"of",
"the",
"given",
"document",
"is",
"present",
"in",
"the",
"cache"
] | python | train | 33.25 |
ctuning/ck | ck/kernel.py | https://github.com/ctuning/ck/blob/7e009814e975f8742790d3106340088a46223714/ck/kernel.py#L6309-L6471 | def rm(i):
"""
Input: {
(repo_uoa) - repo UOA ; can be wild cards
module_uoa - module UOA ; can be wild cards
data_uoa - data UOA ; can be wild cards
(force) - if 'yes', force deleting without questions
or... | [
"def",
"rm",
"(",
"i",
")",
":",
"a",
"=",
"i",
".",
"get",
"(",
"'repo_uoa'",
",",
"''",
")",
"# Check if global writing is allowed",
"r",
"=",
"check_writing",
"(",
"{",
"'repo_uoa'",
":",
"a",
",",
"'delete'",
":",
"'yes'",
"}",
")",
"if",
"r",
"[... | Input: {
(repo_uoa) - repo UOA ; can be wild cards
module_uoa - module UOA ; can be wild cards
data_uoa - data UOA ; can be wild cards
(force) - if 'yes', force deleting without questions
or
(f) ... | [
"Input",
":",
"{",
"(",
"repo_uoa",
")",
"-",
"repo",
"UOA",
";",
"can",
"be",
"wild",
"cards",
"module_uoa",
"-",
"module",
"UOA",
";",
"can",
"be",
"wild",
"cards",
"data_uoa",
"-",
"data",
"UOA",
";",
"can",
"be",
"wild",
"cards"
] | python | train | 29.092025 |
mapbox/rio-color | rio_color/operations.py | https://github.com/mapbox/rio-color/blob/4e9d7a9348608e66f9381fcdba98c13050e91c83/rio_color/operations.py#L207-L286 | def parse_operations(ops_string):
"""Takes a string of operations written with a handy DSL
"OPERATION-NAME BANDS ARG1 ARG2 OPERATION-NAME BANDS ARG"
And returns a list of functions, each of which take and return ndarrays
"""
band_lookup = {"r": 1, "g": 2, "b": 3}
count = len(band_lookup)
... | [
"def",
"parse_operations",
"(",
"ops_string",
")",
":",
"band_lookup",
"=",
"{",
"\"r\"",
":",
"1",
",",
"\"g\"",
":",
"2",
",",
"\"b\"",
":",
"3",
"}",
"count",
"=",
"len",
"(",
"band_lookup",
")",
"opfuncs",
"=",
"{",
"\"saturation\"",
":",
"saturati... | Takes a string of operations written with a handy DSL
"OPERATION-NAME BANDS ARG1 ARG2 OPERATION-NAME BANDS ARG"
And returns a list of functions, each of which take and return ndarrays | [
"Takes",
"a",
"string",
"of",
"operations",
"written",
"with",
"a",
"handy",
"DSL"
] | python | train | 28.825 |
lrq3000/pyFileFixity | pyFileFixity/lib/profilers/visual/pympler/refgraph.py | https://github.com/lrq3000/pyFileFixity/blob/fd5ef23bb13835faf1e3baa773619b86a1cc9bdf/pyFileFixity/lib/profilers/visual/pympler/refgraph.py#L171-L199 | def _annotate_groups(self):
"""
Annotate the objects belonging to separate (non-connected) graphs with
individual indices.
"""
g = {}
for x in self.metadata:
g[x.id] = x
idx = 0
for x in self.metadata:
if not hasattr(x, 'group'):
... | [
"def",
"_annotate_groups",
"(",
"self",
")",
":",
"g",
"=",
"{",
"}",
"for",
"x",
"in",
"self",
".",
"metadata",
":",
"g",
"[",
"x",
".",
"id",
"]",
"=",
"x",
"idx",
"=",
"0",
"for",
"x",
"in",
"self",
".",
"metadata",
":",
"if",
"not",
"hasa... | Annotate the objects belonging to separate (non-connected) graphs with
individual indices. | [
"Annotate",
"the",
"objects",
"belonging",
"to",
"separate",
"(",
"non",
"-",
"connected",
")",
"graphs",
"with",
"individual",
"indices",
"."
] | python | train | 31.551724 |
bububa/pyTOP | pyTOP/fenxiao.py | https://github.com/bububa/pyTOP/blob/1e48009bcfe886be392628244b370e6374e1f2b2/pyTOP/fenxiao.py#L104-L113 | def update(self, distributor_id, grade_id, session, trade_type=None):
'''taobao.fenxiao.cooperation.update 更新合作关系等级
供应商更新合作的分销商等级'''
request = TOPRequest('taobao.fenxiao.cooperation.update')
request['distributor_id'] = distributor_id
request['grade_id'] = grade_id
... | [
"def",
"update",
"(",
"self",
",",
"distributor_id",
",",
"grade_id",
",",
"session",
",",
"trade_type",
"=",
"None",
")",
":",
"request",
"=",
"TOPRequest",
"(",
"'taobao.fenxiao.cooperation.update'",
")",
"request",
"[",
"'distributor_id'",
"]",
"=",
"distribu... | taobao.fenxiao.cooperation.update 更新合作关系等级
供应商更新合作的分销商等级 | [
"taobao",
".",
"fenxiao",
".",
"cooperation",
".",
"update",
"更新合作关系等级",
"供应商更新合作的分销商等级"
] | python | train | 47.4 |
Miserlou/Zappa | zappa/cli.py | https://github.com/Miserlou/Zappa/blob/3ccf7490a8d8b8fa74a61ee39bf44234f3567739/zappa/cli.py#L2605-L2641 | def execute_prebuild_script(self):
"""
Parse and execute the prebuild_script from the zappa_settings.
"""
(pb_mod_path, pb_func) = self.prebuild_script.rsplit('.', 1)
try: # Prefer prebuild script in working directory
if pb_mod_path.count('.') >= 1: # Prebuild sc... | [
"def",
"execute_prebuild_script",
"(",
"self",
")",
":",
"(",
"pb_mod_path",
",",
"pb_func",
")",
"=",
"self",
".",
"prebuild_script",
".",
"rsplit",
"(",
"'.'",
",",
"1",
")",
"try",
":",
"# Prefer prebuild script in working directory",
"if",
"pb_mod_path",
"."... | Parse and execute the prebuild_script from the zappa_settings. | [
"Parse",
"and",
"execute",
"the",
"prebuild_script",
"from",
"the",
"zappa_settings",
"."
] | python | train | 46.891892 |
d0c-s4vage/pfp | pfp/bitwrap.py | https://github.com/d0c-s4vage/pfp/blob/32f2d34fdec1c70019fa83c7006d5e3be0f92fcd/pfp/bitwrap.py#L219-L241 | def unconsumed_ranges(self):
"""Return an IntervalTree of unconsumed ranges, of the format
(start, end] with the end value not being included
"""
res = IntervalTree()
prev = None
# normal iteration is not in a predictable order
ranges = sorted([x for x in self.r... | [
"def",
"unconsumed_ranges",
"(",
"self",
")",
":",
"res",
"=",
"IntervalTree",
"(",
")",
"prev",
"=",
"None",
"# normal iteration is not in a predictable order",
"ranges",
"=",
"sorted",
"(",
"[",
"x",
"for",
"x",
"in",
"self",
".",
"range_set",
"]",
",",
"k... | Return an IntervalTree of unconsumed ranges, of the format
(start, end] with the end value not being included | [
"Return",
"an",
"IntervalTree",
"of",
"unconsumed",
"ranges",
"of",
"the",
"format",
"(",
"start",
"end",
"]",
"with",
"the",
"end",
"value",
"not",
"being",
"included"
] | python | train | 29.913043 |
toumorokoshi/transmute-core | transmute_core/object_serializers/cattrs_serializer/__init__.py | https://github.com/toumorokoshi/transmute-core/blob/a2c26625d5d8bab37e00038f9d615a26167fc7f4/transmute_core/object_serializers/cattrs_serializer/__init__.py#L17-L25 | def can_handle(self, cls):
"""
this will theoretically be compatible with everything,
as cattrs can handle many basic types as well.
"""
# cattrs uses a Singledispatch like function
# under the hood.
f = self._cattrs_converter._structure_func.dispatch(cls)
... | [
"def",
"can_handle",
"(",
"self",
",",
"cls",
")",
":",
"# cattrs uses a Singledispatch like function",
"# under the hood.",
"f",
"=",
"self",
".",
"_cattrs_converter",
".",
"_structure_func",
".",
"dispatch",
"(",
"cls",
")",
"return",
"f",
"!=",
"self",
".",
"... | this will theoretically be compatible with everything,
as cattrs can handle many basic types as well. | [
"this",
"will",
"theoretically",
"be",
"compatible",
"with",
"everything",
"as",
"cattrs",
"can",
"handle",
"many",
"basic",
"types",
"as",
"well",
"."
] | python | train | 40.666667 |
googleads/googleads-python-lib | googleads/ad_manager.py | https://github.com/googleads/googleads-python-lib/blob/aa3b1b474b0f9789ca55ca46f4b2b57aeae38874/googleads/ad_manager.py#L828-L868 | def DownloadReportToFile(self, report_job_id, export_format, outfile,
include_report_properties=False,
include_totals_row=None, use_gzip_compression=True):
"""Downloads report data and writes it to a file.
The report job must be completed before calling thi... | [
"def",
"DownloadReportToFile",
"(",
"self",
",",
"report_job_id",
",",
"export_format",
",",
"outfile",
",",
"include_report_properties",
"=",
"False",
",",
"include_totals_row",
"=",
"None",
",",
"use_gzip_compression",
"=",
"True",
")",
":",
"service",
"=",
"sel... | Downloads report data and writes it to a file.
The report job must be completed before calling this function.
Args:
report_job_id: The ID of the report job to wait for, as a string.
export_format: The export format for the report file, as a string.
outfile: A writeable, file-like object to w... | [
"Downloads",
"report",
"data",
"and",
"writes",
"it",
"to",
"a",
"file",
"."
] | python | train | 41.926829 |
LionelAuroux/pyrser | pyrser/ast/state.py | https://github.com/LionelAuroux/pyrser/blob/f153a97ef2b6bf915a1ed468c0252a9a59b754d5/pyrser/ast/state.py#L101-L115 | def to_fmt(self) -> str:
"""
Provide a useful representation of the register.
"""
infos = fmt.end(";\n", [])
s = fmt.sep(', ', [])
for ids in sorted(self.states.keys()):
s.lsdata.append(str(ids))
infos.lsdata.append(fmt.block('(', ')', [s]))
in... | [
"def",
"to_fmt",
"(",
"self",
")",
"->",
"str",
":",
"infos",
"=",
"fmt",
".",
"end",
"(",
"\";\\n\"",
",",
"[",
"]",
")",
"s",
"=",
"fmt",
".",
"sep",
"(",
"', '",
",",
"[",
"]",
")",
"for",
"ids",
"in",
"sorted",
"(",
"self",
".",
"states",... | Provide a useful representation of the register. | [
"Provide",
"a",
"useful",
"representation",
"of",
"the",
"register",
"."
] | python | test | 37.4 |
fastai/fastai | fastai/vision/image.py | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/image.py#L275-L285 | def flow(self)->FlowField:
"Access the flow-field grid after applying queued affine and coord transforms."
if self._affine_mat is not None:
self._flow = _affine_inv_mult(self._flow, self._affine_mat)
self._affine_mat = None
self.transformed = True
if len(self.... | [
"def",
"flow",
"(",
"self",
")",
"->",
"FlowField",
":",
"if",
"self",
".",
"_affine_mat",
"is",
"not",
"None",
":",
"self",
".",
"_flow",
"=",
"_affine_inv_mult",
"(",
"self",
".",
"_flow",
",",
"self",
".",
"_affine_mat",
")",
"self",
".",
"_affine_m... | Access the flow-field grid after applying queued affine and coord transforms. | [
"Access",
"the",
"flow",
"-",
"field",
"grid",
"after",
"applying",
"queued",
"affine",
"and",
"coord",
"transforms",
"."
] | python | train | 44.545455 |
lra/mackup | mackup/application.py | https://github.com/lra/mackup/blob/ed0b5626b033f232868900bfd5108df448873725/mackup/application.py#L33-L44 | def getFilepaths(self, filename):
"""
Get home and mackup filepaths for given file
Args:
filename (str)
Returns:
home_filepath, mackup_filepath (str, str)
"""
return (os.path.join(os.environ['HOME'], filename),
os.path.join(self.m... | [
"def",
"getFilepaths",
"(",
"self",
",",
"filename",
")",
":",
"return",
"(",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"environ",
"[",
"'HOME'",
"]",
",",
"filename",
")",
",",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"mackup",
".... | Get home and mackup filepaths for given file
Args:
filename (str)
Returns:
home_filepath, mackup_filepath (str, str) | [
"Get",
"home",
"and",
"mackup",
"filepaths",
"for",
"given",
"file"
] | python | train | 28.333333 |
saltstack/salt | salt/modules/drac.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/drac.py#L121-L139 | def syslog(server, enable=True):
'''
Configure syslog remote logging, by default syslog will automatically be
enabled if a server is specified. However, if you want to disable syslog
you will need to specify a server followed by False
CLI Example:
.. code-block:: bash
salt dell drac.s... | [
"def",
"syslog",
"(",
"server",
",",
"enable",
"=",
"True",
")",
":",
"if",
"enable",
"and",
"__execute_cmd",
"(",
"'config -g cfgRemoteHosts -o \\\n cfgRhostsSyslogEnable 1'",
")",
":",
"return",
"__execute_cmd",
"(",
"'config -g cfgRemoteHosts -o \\\n ... | Configure syslog remote logging, by default syslog will automatically be
enabled if a server is specified. However, if you want to disable syslog
you will need to specify a server followed by False
CLI Example:
.. code-block:: bash
salt dell drac.syslog [SYSLOG IP] [ENABLE/DISABLE]
sa... | [
"Configure",
"syslog",
"remote",
"logging",
"by",
"default",
"syslog",
"will",
"automatically",
"be",
"enabled",
"if",
"a",
"server",
"is",
"specified",
".",
"However",
"if",
"you",
"want",
"to",
"disable",
"syslog",
"you",
"will",
"need",
"to",
"specify",
"... | python | train | 36.578947 |
cltk/cltk | cltk/corpus/readers.py | https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/corpus/readers.py#L454-L461 | def sents(self: object, fileids: str):
"""
Tokenizes documents in the corpus by sentence
"""
for para in self.paras(fileids):
for sent in sent_tokenize(para):
yield sent | [
"def",
"sents",
"(",
"self",
":",
"object",
",",
"fileids",
":",
"str",
")",
":",
"for",
"para",
"in",
"self",
".",
"paras",
"(",
"fileids",
")",
":",
"for",
"sent",
"in",
"sent_tokenize",
"(",
"para",
")",
":",
"yield",
"sent"
] | Tokenizes documents in the corpus by sentence | [
"Tokenizes",
"documents",
"in",
"the",
"corpus",
"by",
"sentence"
] | python | train | 27.875 |
vtkiorg/vtki | vtki/export.py | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/export.py#L78-L85 | def get_range_info(array, component):
"""Get the data range of the array's component"""
r = array.GetRange(component)
comp_range = {}
comp_range['min'] = r[0]
comp_range['max'] = r[1]
comp_range['component'] = array.GetComponentName(component)
return comp_range | [
"def",
"get_range_info",
"(",
"array",
",",
"component",
")",
":",
"r",
"=",
"array",
".",
"GetRange",
"(",
"component",
")",
"comp_range",
"=",
"{",
"}",
"comp_range",
"[",
"'min'",
"]",
"=",
"r",
"[",
"0",
"]",
"comp_range",
"[",
"'max'",
"]",
"=",... | Get the data range of the array's component | [
"Get",
"the",
"data",
"range",
"of",
"the",
"array",
"s",
"component"
] | python | train | 35.25 |
ironfroggy/straight.plugin | straight/plugin/manager.py | https://github.com/ironfroggy/straight.plugin/blob/aaaf68db51b823d164cf714b1be2262a75ee2a79/straight/plugin/manager.py#L26-L33 | def call(self, methodname, *args, **kwargs):
"""Call a common method on all the plugins, if it exists."""
for plugin in self._plugins:
method = getattr(plugin, methodname, None)
if method is None:
continue
yield method(*args, **kwargs) | [
"def",
"call",
"(",
"self",
",",
"methodname",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"plugin",
"in",
"self",
".",
"_plugins",
":",
"method",
"=",
"getattr",
"(",
"plugin",
",",
"methodname",
",",
"None",
")",
"if",
"method",
"... | Call a common method on all the plugins, if it exists. | [
"Call",
"a",
"common",
"method",
"on",
"all",
"the",
"plugins",
"if",
"it",
"exists",
"."
] | python | train | 37.125 |
Othernet-Project/squery-pg | squery_pg/migrations.py | https://github.com/Othernet-Project/squery-pg/blob/eaa695c3719e2d2b7e1b049bb58c987c132b6b34/squery_pg/migrations.py#L108-L113 | def unpack_version(version):
"""Unpack a single version integer into the two major and minor
components."""
minor_version = version % VERSION_MULTIPLIER
major_version = (version - minor_version) / VERSION_MULTIPLIER
return (major_version, minor_version) | [
"def",
"unpack_version",
"(",
"version",
")",
":",
"minor_version",
"=",
"version",
"%",
"VERSION_MULTIPLIER",
"major_version",
"=",
"(",
"version",
"-",
"minor_version",
")",
"/",
"VERSION_MULTIPLIER",
"return",
"(",
"major_version",
",",
"minor_version",
")"
] | Unpack a single version integer into the two major and minor
components. | [
"Unpack",
"a",
"single",
"version",
"integer",
"into",
"the",
"two",
"major",
"and",
"minor",
"components",
"."
] | python | train | 44.666667 |
LudovicRousseau/pyscard | smartcard/pcsc/PCSCCardConnection.py | https://github.com/LudovicRousseau/pyscard/blob/62e675028086c75656444cc21d563d9f08ebf8e7/smartcard/pcsc/PCSCCardConnection.py#L33-L45 | def translateprotocolmask(protocol):
"""Translate CardConnection protocol mask into PCSC protocol mask."""
pcscprotocol = 0
if None != protocol:
if CardConnection.T0_protocol & protocol:
pcscprotocol |= SCARD_PROTOCOL_T0
if CardConnection.T1_protocol & protocol:
pcscp... | [
"def",
"translateprotocolmask",
"(",
"protocol",
")",
":",
"pcscprotocol",
"=",
"0",
"if",
"None",
"!=",
"protocol",
":",
"if",
"CardConnection",
".",
"T0_protocol",
"&",
"protocol",
":",
"pcscprotocol",
"|=",
"SCARD_PROTOCOL_T0",
"if",
"CardConnection",
".",
"T... | Translate CardConnection protocol mask into PCSC protocol mask. | [
"Translate",
"CardConnection",
"protocol",
"mask",
"into",
"PCSC",
"protocol",
"mask",
"."
] | python | train | 42.769231 |
pycontribs/pyrax | pyrax/object_storage.py | https://github.com/pycontribs/pyrax/blob/9ddfd5064b3a292d7337906f3b2d5dce95b50b99/pyrax/object_storage.py#L2920-L2934 | def change_object_content_type(self, container, obj, new_ctype,
guess=False, extra_info=None):
"""
Copies object to itself, but applies a new content-type. The guess
feature requires the container to be CDN-enabled. If not then the
content-type must be supplied. If using gues... | [
"def",
"change_object_content_type",
"(",
"self",
",",
"container",
",",
"obj",
",",
"new_ctype",
",",
"guess",
"=",
"False",
",",
"extra_info",
"=",
"None",
")",
":",
"return",
"self",
".",
"_manager",
".",
"change_object_content_type",
"(",
"container",
",",... | Copies object to itself, but applies a new content-type. The guess
feature requires the container to be CDN-enabled. If not then the
content-type must be supplied. If using guess with a CDN-enabled
container, new_ctype can be set to None. Failure during the put will
result in a swift exc... | [
"Copies",
"object",
"to",
"itself",
"but",
"applies",
"a",
"new",
"content",
"-",
"type",
".",
"The",
"guess",
"feature",
"requires",
"the",
"container",
"to",
"be",
"CDN",
"-",
"enabled",
".",
"If",
"not",
"then",
"the",
"content",
"-",
"type",
"must",
... | python | train | 51.6 |
openstack/networking-cisco | networking_cisco/ml2_drivers/ucsm/ucsm_db.py | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/ml2_drivers/ucsm/ucsm_db.py#L122-L133 | def add_vnic_template(self, vlan_id, ucsm_ip, vnic_template, physnet):
"""Adds an entry for a vlan_id on a SP template to the table."""
if not self.get_vnic_template_vlan_entry(vlan_id, vnic_template,
ucsm_ip, physnet):
vnic_t = ucsm_model.VnicTemplate(vlan_id=vlan_id,
... | [
"def",
"add_vnic_template",
"(",
"self",
",",
"vlan_id",
",",
"ucsm_ip",
",",
"vnic_template",
",",
"physnet",
")",
":",
"if",
"not",
"self",
".",
"get_vnic_template_vlan_entry",
"(",
"vlan_id",
",",
"vnic_template",
",",
"ucsm_ip",
",",
"physnet",
")",
":",
... | Adds an entry for a vlan_id on a SP template to the table. | [
"Adds",
"an",
"entry",
"for",
"a",
"vlan_id",
"on",
"a",
"SP",
"template",
"to",
"the",
"table",
"."
] | python | train | 57.583333 |
molmod/molmod | molmod/graphs.py | https://github.com/molmod/molmod/blob/a7b5b4364ed514ad4c465856c05b5eda1cb561e0/molmod/graphs.py#L1597-L1612 | def _iter_candidate_groups(self, init_match, edges0, edges1):
"""Divide the edges into groups"""
# collect all end vertices0 and end vertices1 that belong to the same
# group.
sources = {}
for start_vertex0, end_vertex0 in edges0:
l = sources.setdefault(start_vertex0,... | [
"def",
"_iter_candidate_groups",
"(",
"self",
",",
"init_match",
",",
"edges0",
",",
"edges1",
")",
":",
"# collect all end vertices0 and end vertices1 that belong to the same",
"# group.",
"sources",
"=",
"{",
"}",
"for",
"start_vertex0",
",",
"end_vertex0",
"in",
"edg... | Divide the edges into groups | [
"Divide",
"the",
"edges",
"into",
"groups"
] | python | train | 45.3125 |
NetworkAutomation/jaide | jaide/wrap.py | https://github.com/NetworkAutomation/jaide/blob/8571b987a8c24c246dc09f1bcc11cb0f045ec33f/jaide/wrap.py#L32-L103 | def open_connection(ip, username, password, function, args, write=False,
conn_timeout=5, sess_timeout=300, port=22):
""" Open a Jaide session with the device.
To open a Jaide session to the device, and run the appropriate function
against the device. Arguments for the downstream functio... | [
"def",
"open_connection",
"(",
"ip",
",",
"username",
",",
"password",
",",
"function",
",",
"args",
",",
"write",
"=",
"False",
",",
"conn_timeout",
"=",
"5",
",",
"sess_timeout",
"=",
"300",
",",
"port",
"=",
"22",
")",
":",
"# start with the header line... | Open a Jaide session with the device.
To open a Jaide session to the device, and run the appropriate function
against the device. Arguments for the downstream function are passed
through.
@param ip: String of the IP or hostname of the device to connect to.
@type ip: str
@param username: The st... | [
"Open",
"a",
"Jaide",
"session",
"with",
"the",
"device",
"."
] | python | train | 48.444444 |
onelogin/python3-saml | src/onelogin/saml2/auth.py | https://github.com/onelogin/python3-saml/blob/064b7275fba1e5f39a9116ba1cdcc5d01fc34daa/src/onelogin/saml2/auth.py#L469-L492 | def __build_sign_query(saml_data, relay_state, algorithm, saml_type, lowercase_urlencoding=False):
"""
Build sign query
:param saml_data: The Request data
:type saml_data: str
:param relay_state: The Relay State
:type relay_state: str
:param algorithm: The Sign... | [
"def",
"__build_sign_query",
"(",
"saml_data",
",",
"relay_state",
",",
"algorithm",
",",
"saml_type",
",",
"lowercase_urlencoding",
"=",
"False",
")",
":",
"sign_data",
"=",
"[",
"'%s=%s'",
"%",
"(",
"saml_type",
",",
"OneLogin_Saml2_Utils",
".",
"escape_url",
... | Build sign query
:param saml_data: The Request data
:type saml_data: str
:param relay_state: The Relay State
:type relay_state: str
:param algorithm: The Signature Algorithm
:type algorithm: str
:param saml_type: The target URL the user should be redirected to... | [
"Build",
"sign",
"query"
] | python | train | 41.333333 |
mitsei/dlkit | dlkit/json_/assessment_authoring/sessions.py | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/json_/assessment_authoring/sessions.py#L2312-L2329 | def get_sequence_rules(self):
"""Gets all ``SequenceRules``.
return: (osid.assessment.authoring.SequenceRuleList) - the
returned ``SequenceRule`` list
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
*complianc... | [
"def",
"get_sequence_rules",
"(",
"self",
")",
":",
"# Implemented from template for",
"# osid.resource.ResourceLookupSession.get_resources",
"# NOTE: This implementation currently ignores plenary view",
"collection",
"=",
"JSONClientValidated",
"(",
"'assessment_authoring'",
",",
"col... | Gets all ``SequenceRules``.
return: (osid.assessment.authoring.SequenceRuleList) - the
returned ``SequenceRule`` list
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
*compliance: mandatory -- This method must be imple... | [
"Gets",
"all",
"SequenceRules",
"."
] | python | train | 49.833333 |
pypa/pipenv | pipenv/patched/notpip/_internal/resolve.py | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/resolve.py#L96-L144 | def resolve(self, requirement_set):
# type: (RequirementSet) -> None
"""Resolve what operations need to be done
As a side-effect of this method, the packages (and their dependencies)
are downloaded, unpacked and prepared for installation. This
preparation is done by ``pip.operat... | [
"def",
"resolve",
"(",
"self",
",",
"requirement_set",
")",
":",
"# type: (RequirementSet) -> None",
"# make the wheelhouse",
"if",
"self",
".",
"preparer",
".",
"wheel_download_dir",
":",
"ensure_dir",
"(",
"self",
".",
"preparer",
".",
"wheel_download_dir",
")",
"... | Resolve what operations need to be done
As a side-effect of this method, the packages (and their dependencies)
are downloaded, unpacked and prepared for installation. This
preparation is done by ``pip.operations.prepare``.
Once PyPI has static dependency metadata available, it would be... | [
"Resolve",
"what",
"operations",
"need",
"to",
"be",
"done"
] | python | train | 38.591837 |
bcbio/bcbio-nextgen | bcbio/variation/qsnp.py | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/qsnp.py#L147-L185 | def _filter_vcf(out_file):
"""Fix sample names, FILTER and FORMAT fields. Remove lines with ambiguous reference.
"""
in_file = out_file.replace(".vcf", "-ori.vcf")
FILTER_line = ('##FILTER=<ID=SBIAS,Description="Due to bias">\n'
'##FILTER=<ID=5BP,Description="Due to 5BP">\n'
... | [
"def",
"_filter_vcf",
"(",
"out_file",
")",
":",
"in_file",
"=",
"out_file",
".",
"replace",
"(",
"\".vcf\"",
",",
"\"-ori.vcf\"",
")",
"FILTER_line",
"=",
"(",
"'##FILTER=<ID=SBIAS,Description=\"Due to bias\">\\n'",
"'##FILTER=<ID=5BP,Description=\"Due to 5BP\">\\n'",
"'##... | Fix sample names, FILTER and FORMAT fields. Remove lines with ambiguous reference. | [
"Fix",
"sample",
"names",
"FILTER",
"and",
"FORMAT",
"fields",
".",
"Remove",
"lines",
"with",
"ambiguous",
"reference",
"."
] | python | train | 52.358974 |
saltstack/salt | salt/states/jboss7.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/jboss7.py#L203-L261 | def bindings_exist(name, jboss_config, bindings, profile=None):
'''
Ensures that given JNDI binding are present on the server.
If a binding doesn't exist on the server it will be created.
If it already exists its value will be changed.
jboss_config:
Dict with connection properties (see stat... | [
"def",
"bindings_exist",
"(",
"name",
",",
"jboss_config",
",",
"bindings",
",",
"profile",
"=",
"None",
")",
":",
"log",
".",
"debug",
"(",
"\" ======================== STATE: jboss7.bindings_exist (name: %s) (profile: %s) \"",
",",
"name",
",",
"profile",
")",
"log"... | Ensures that given JNDI binding are present on the server.
If a binding doesn't exist on the server it will be created.
If it already exists its value will be changed.
jboss_config:
Dict with connection properties (see state description)
bindings:
Dict with bindings to set.
profile:... | [
"Ensures",
"that",
"given",
"JNDI",
"binding",
"are",
"present",
"on",
"the",
"server",
".",
"If",
"a",
"binding",
"doesn",
"t",
"exist",
"on",
"the",
"server",
"it",
"will",
"be",
"created",
".",
"If",
"it",
"already",
"exists",
"its",
"value",
"will",
... | python | train | 42.491525 |
tensorflow/tensorboard | tensorboard/plugins/image/images_demo.py | https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/plugins/image/images_demo.py#L268-L276 | def run_all(logdir, verbose=False):
"""Run simulations on a reasonable set of parameters.
Arguments:
logdir: the directory into which to store all the runs' data
verbose: if true, print out each run's name as it begins
"""
run_box_to_gaussian(logdir, verbose=verbose)
run_sobel(logdir, verbose=verbose... | [
"def",
"run_all",
"(",
"logdir",
",",
"verbose",
"=",
"False",
")",
":",
"run_box_to_gaussian",
"(",
"logdir",
",",
"verbose",
"=",
"verbose",
")",
"run_sobel",
"(",
"logdir",
",",
"verbose",
"=",
"verbose",
")"
] | Run simulations on a reasonable set of parameters.
Arguments:
logdir: the directory into which to store all the runs' data
verbose: if true, print out each run's name as it begins | [
"Run",
"simulations",
"on",
"a",
"reasonable",
"set",
"of",
"parameters",
"."
] | python | train | 34.777778 |
Grk0/python-libconf | libconf.py | https://github.com/Grk0/python-libconf/blob/9c4cf5f56d56ebbc1fe0e1596807218b7d5d5da4/libconf.py#L286-L304 | def accept(self, *args):
'''Consume and return the next token if it has the correct type
Multiple token types (as strings, e.g. 'integer64') can be given
as arguments. If the next token is one of them, consume and return it.
If the token type doesn't match, return None.
'''
... | [
"def",
"accept",
"(",
"self",
",",
"*",
"args",
")",
":",
"token",
"=",
"self",
".",
"peek",
"(",
")",
"if",
"token",
"is",
"None",
":",
"return",
"None",
"for",
"arg",
"in",
"args",
":",
"if",
"token",
".",
"type",
"==",
"arg",
":",
"self",
".... | Consume and return the next token if it has the correct type
Multiple token types (as strings, e.g. 'integer64') can be given
as arguments. If the next token is one of them, consume and return it.
If the token type doesn't match, return None. | [
"Consume",
"and",
"return",
"the",
"next",
"token",
"if",
"it",
"has",
"the",
"correct",
"type"
] | python | train | 27.473684 |
inveniosoftware/invenio-indexer | invenio_indexer/api.py | https://github.com/inveniosoftware/invenio-indexer/blob/1460aa8976b449d9a3a99d356322b158e9be6f80/invenio_indexer/api.py#L166-L193 | def process_bulk_queue(self, es_bulk_kwargs=None):
"""Process bulk indexing queue.
:param dict es_bulk_kwargs: Passed to
:func:`elasticsearch:elasticsearch.helpers.bulk`.
"""
with current_celery_app.pool.acquire(block=True) as conn:
consumer = Consumer(
... | [
"def",
"process_bulk_queue",
"(",
"self",
",",
"es_bulk_kwargs",
"=",
"None",
")",
":",
"with",
"current_celery_app",
".",
"pool",
".",
"acquire",
"(",
"block",
"=",
"True",
")",
"as",
"conn",
":",
"consumer",
"=",
"Consumer",
"(",
"connection",
"=",
"conn... | Process bulk indexing queue.
:param dict es_bulk_kwargs: Passed to
:func:`elasticsearch:elasticsearch.helpers.bulk`. | [
"Process",
"bulk",
"indexing",
"queue",
"."
] | python | train | 31.678571 |
mottosso/be | be/vendor/click/core.py | https://github.com/mottosso/be/blob/0f3d4f3597c71223f616d78c6d9b2c8dffcd8a71/be/vendor/click/core.py#L758-L765 | def make_parser(self, ctx):
"""Creates the underlying option parser for this command."""
parser = OptionParser(ctx)
parser.allow_interspersed_args = ctx.allow_interspersed_args
parser.ignore_unknown_options = ctx.ignore_unknown_options
for param in self.get_params(ctx):
... | [
"def",
"make_parser",
"(",
"self",
",",
"ctx",
")",
":",
"parser",
"=",
"OptionParser",
"(",
"ctx",
")",
"parser",
".",
"allow_interspersed_args",
"=",
"ctx",
".",
"allow_interspersed_args",
"parser",
".",
"ignore_unknown_options",
"=",
"ctx",
".",
"ignore_unkno... | Creates the underlying option parser for this command. | [
"Creates",
"the",
"underlying",
"option",
"parser",
"for",
"this",
"command",
"."
] | python | train | 46.25 |
ultrabug/py3status | py3status/autodoc.py | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/autodoc.py#L150-L178 | def create_module_docs():
"""
Create documentation for modules.
"""
data = core_module_docstrings(format="rst")
# get screenshot data
screenshots_data = {}
samples = get_samples()
for sample in samples.keys():
module = sample.split("-")[0]
if module not in screenshots_dat... | [
"def",
"create_module_docs",
"(",
")",
":",
"data",
"=",
"core_module_docstrings",
"(",
"format",
"=",
"\"rst\"",
")",
"# get screenshot data",
"screenshots_data",
"=",
"{",
"}",
"samples",
"=",
"get_samples",
"(",
")",
"for",
"sample",
"in",
"samples",
".",
"... | Create documentation for modules. | [
"Create",
"documentation",
"for",
"modules",
"."
] | python | train | 33.137931 |
bioidiap/bob.ip.facedetect | bob/ip/facedetect/train/utils.py | https://github.com/bioidiap/bob.ip.facedetect/blob/601da5141ca7302ad36424d1421b33190ba46779/bob/ip/facedetect/train/utils.py#L156-L181 | def parallel_part(data, parallel):
"""parallel_part(data, parallel) -> part
Splits off samples from the the given data list and the given number of parallel jobs based on the ``SGE_TASK_ID`` environment variable.
**Parameters:**
``data`` : [object]
A list of data that should be split up into ``parallel``... | [
"def",
"parallel_part",
"(",
"data",
",",
"parallel",
")",
":",
"if",
"parallel",
"is",
"None",
"or",
"\"SGE_TASK_ID\"",
"not",
"in",
"os",
".",
"environ",
":",
"return",
"data",
"data_per_job",
"=",
"int",
"(",
"math",
".",
"ceil",
"(",
"float",
"(",
... | parallel_part(data, parallel) -> part
Splits off samples from the the given data list and the given number of parallel jobs based on the ``SGE_TASK_ID`` environment variable.
**Parameters:**
``data`` : [object]
A list of data that should be split up into ``parallel`` parts
``parallel`` : int or ``None``... | [
"parallel_part",
"(",
"data",
"parallel",
")",
"-",
">",
"part"
] | python | train | 30.346154 |
scanny/python-pptx | pptx/oxml/simpletypes.py | https://github.com/scanny/python-pptx/blob/d6ab8234f8b03953d2f831ff9394b1852db34130/pptx/oxml/simpletypes.py#L582-L593 | def convert_to_xml(cls, degrees):
"""Convert signed angle float like -427.42 to int 60000 per degree.
Value is normalized to a positive value less than 360 degrees.
"""
if degrees < 0.0:
degrees %= -360
degrees += 360
elif degrees > 0.0:
degre... | [
"def",
"convert_to_xml",
"(",
"cls",
",",
"degrees",
")",
":",
"if",
"degrees",
"<",
"0.0",
":",
"degrees",
"%=",
"-",
"360",
"degrees",
"+=",
"360",
"elif",
"degrees",
">",
"0.0",
":",
"degrees",
"%=",
"360",
"return",
"str",
"(",
"int",
"(",
"round... | Convert signed angle float like -427.42 to int 60000 per degree.
Value is normalized to a positive value less than 360 degrees. | [
"Convert",
"signed",
"angle",
"float",
"like",
"-",
"427",
".",
"42",
"to",
"int",
"60000",
"per",
"degree",
"."
] | python | train | 31.916667 |
etcher-be/epab | epab/utils/_repo.py | https://github.com/etcher-be/epab/blob/024cde74d058281aa66e6e4b7b71dccbe803b1c1/epab/utils/_repo.py#L271-L286 | def add_skip_ci_to_commit_msg(message: str) -> str:
"""
Adds a "[skip ci]" tag at the end of a (possibly multi-line) commit message
:param message: commit message
:type message: str
:return: edited commit message
:rtype: str
"""
first_line_index = message... | [
"def",
"add_skip_ci_to_commit_msg",
"(",
"message",
":",
"str",
")",
"->",
"str",
":",
"first_line_index",
"=",
"message",
".",
"find",
"(",
"'\\n'",
")",
"if",
"first_line_index",
"==",
"-",
"1",
":",
"edited_message",
"=",
"message",
"+",
"' [skip ci]'",
"... | Adds a "[skip ci]" tag at the end of a (possibly multi-line) commit message
:param message: commit message
:type message: str
:return: edited commit message
:rtype: str | [
"Adds",
"a",
"[",
"skip",
"ci",
"]",
"tag",
"at",
"the",
"end",
"of",
"a",
"(",
"possibly",
"multi",
"-",
"line",
")",
"commit",
"message"
] | python | train | 38.3125 |
JdeRobot/base | src/drivers/MAVLinkServer/MAVProxy/modules/mavproxy_wp.py | https://github.com/JdeRobot/base/blob/303b18992785b2fe802212f2d758a60873007f1f/src/drivers/MAVLinkServer/MAVProxy/modules/mavproxy_wp.py#L55-L102 | def mavlink_packet(self, m):
'''handle an incoming mavlink packet'''
mtype = m.get_type()
if mtype in ['WAYPOINT_COUNT','MISSION_COUNT']:
if self.wp_op is None:
self.console.error("No waypoint load started")
else:
self.wploader.clear()
... | [
"def",
"mavlink_packet",
"(",
"self",
",",
"m",
")",
":",
"mtype",
"=",
"m",
".",
"get_type",
"(",
")",
"if",
"mtype",
"in",
"[",
"'WAYPOINT_COUNT'",
",",
"'MISSION_COUNT'",
"]",
":",
"if",
"self",
".",
"wp_op",
"is",
"None",
":",
"self",
".",
"conso... | handle an incoming mavlink packet | [
"handle",
"an",
"incoming",
"mavlink",
"packet"
] | python | train | 50.166667 |
CalebBell/thermo | thermo/activity.py | https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/activity.py#L825-L841 | def bubble_at_T(zs, Psats, fugacities=None, gammas=None):
'''
>>> bubble_at_T([0.5, 0.5], [1400, 7000])
4200.0
>>> bubble_at_T([0.5, 0.5], [1400, 7000], gammas=[1.1, .75])
3395.0
>>> bubble_at_T([0.5, 0.5], [1400, 7000], gammas=[1.1, .75], fugacities=[.995, 0.98])
3452.440775305097
'''
... | [
"def",
"bubble_at_T",
"(",
"zs",
",",
"Psats",
",",
"fugacities",
"=",
"None",
",",
"gammas",
"=",
"None",
")",
":",
"if",
"not",
"fugacities",
":",
"fugacities",
"=",
"[",
"1",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"Psats",
")",
")",
"]",
... | >>> bubble_at_T([0.5, 0.5], [1400, 7000])
4200.0
>>> bubble_at_T([0.5, 0.5], [1400, 7000], gammas=[1.1, .75])
3395.0
>>> bubble_at_T([0.5, 0.5], [1400, 7000], gammas=[1.1, .75], fugacities=[.995, 0.98])
3452.440775305097 | [
">>>",
"bubble_at_T",
"(",
"[",
"0",
".",
"5",
"0",
".",
"5",
"]",
"[",
"1400",
"7000",
"]",
")",
"4200",
".",
"0",
">>>",
"bubble_at_T",
"(",
"[",
"0",
".",
"5",
"0",
".",
"5",
"]",
"[",
"1400",
"7000",
"]",
"gammas",
"=",
"[",
"1",
".",
... | python | valid | 41.117647 |
bfontaine/crosswords | crosswords/dictionnaries.py | https://github.com/bfontaine/crosswords/blob/042b3cdd00a59d193ee559368910a8faa54565f5/crosswords/dictionnaries.py#L44-L53 | def init_storage():
"""
Initialize the local dictionnaries cache in ~/.crosswords/dicts.
"""
# http://stackoverflow.com/a/600612/735926
try:
os.makedirs(DICTS_PATH)
except OSError as ex:
if ex.errno != errno.EEXIST or not os.path.isdir(DICTS_PATH):
raise | [
"def",
"init_storage",
"(",
")",
":",
"# http://stackoverflow.com/a/600612/735926",
"try",
":",
"os",
".",
"makedirs",
"(",
"DICTS_PATH",
")",
"except",
"OSError",
"as",
"ex",
":",
"if",
"ex",
".",
"errno",
"!=",
"errno",
".",
"EEXIST",
"or",
"not",
"os",
... | Initialize the local dictionnaries cache in ~/.crosswords/dicts. | [
"Initialize",
"the",
"local",
"dictionnaries",
"cache",
"in",
"~",
"/",
".",
"crosswords",
"/",
"dicts",
"."
] | python | train | 29.7 |
consbio/parserutils | parserutils/elements.py | https://github.com/consbio/parserutils/blob/f13f80db99ed43479336b116e38512e3566e4623/parserutils/elements.py#L658-L669 | def set_elements_tail(parent_to_parse, element_path=None, tail_values=None):
"""
Assigns an array of tail values to each of the elements parsed from the parent. The
tail values are assigned in the same order they are provided.
If there are less values then elements, the remaining elements are skipped; b... | [
"def",
"set_elements_tail",
"(",
"parent_to_parse",
",",
"element_path",
"=",
"None",
",",
"tail_values",
"=",
"None",
")",
":",
"if",
"tail_values",
"is",
"None",
":",
"tail_values",
"=",
"[",
"]",
"return",
"_set_elements_property",
"(",
"parent_to_parse",
","... | Assigns an array of tail values to each of the elements parsed from the parent. The
tail values are assigned in the same order they are provided.
If there are less values then elements, the remaining elements are skipped; but if
there are more, new elements will be inserted for each with the remaining tail ... | [
"Assigns",
"an",
"array",
"of",
"tail",
"values",
"to",
"each",
"of",
"the",
"elements",
"parsed",
"from",
"the",
"parent",
".",
"The",
"tail",
"values",
"are",
"assigned",
"in",
"the",
"same",
"order",
"they",
"are",
"provided",
".",
"If",
"there",
"are... | python | train | 46.5 |
un33k/django-toolware | toolware/utils/generic.py | https://github.com/un33k/django-toolware/blob/973f3e003dc38b812897dab88455bee37dcaf931/toolware/utils/generic.py#L134-L138 | def get_domain(url):
""" Returns domain name portion of a URL """
if 'http' not in url.lower():
url = 'http://{}'.format(url)
return urllib.parse.urlparse(url).hostname | [
"def",
"get_domain",
"(",
"url",
")",
":",
"if",
"'http'",
"not",
"in",
"url",
".",
"lower",
"(",
")",
":",
"url",
"=",
"'http://{}'",
".",
"format",
"(",
"url",
")",
"return",
"urllib",
".",
"parse",
".",
"urlparse",
"(",
"url",
")",
".",
"hostnam... | Returns domain name portion of a URL | [
"Returns",
"domain",
"name",
"portion",
"of",
"a",
"URL"
] | python | test | 36.8 |
RudolfCardinal/pythonlib | cardinal_pythonlib/tsv.py | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/tsv.py#L55-L66 | def dictlist_to_tsv(dictlist: List[Dict[str, Any]]) -> str:
"""
From a consistent list of dictionaries mapping fieldnames to values,
make a TSV file.
"""
if not dictlist:
return ""
fieldnames = dictlist[0].keys()
tsv = "\t".join([tsv_escape(f) for f in fieldnames]) + "\n"
for d i... | [
"def",
"dictlist_to_tsv",
"(",
"dictlist",
":",
"List",
"[",
"Dict",
"[",
"str",
",",
"Any",
"]",
"]",
")",
"->",
"str",
":",
"if",
"not",
"dictlist",
":",
"return",
"\"\"",
"fieldnames",
"=",
"dictlist",
"[",
"0",
"]",
".",
"keys",
"(",
")",
"tsv"... | From a consistent list of dictionaries mapping fieldnames to values,
make a TSV file. | [
"From",
"a",
"consistent",
"list",
"of",
"dictionaries",
"mapping",
"fieldnames",
"to",
"values",
"make",
"a",
"TSV",
"file",
"."
] | python | train | 33.666667 |
LuminosoInsight/python-ftfy | ftfy/fixes.py | https://github.com/LuminosoInsight/python-ftfy/blob/476acc6ad270bffe07f97d4f7cf2139acdc69633/ftfy/fixes.py#L457-L466 | def convert_surrogate_pair(match):
"""
Convert a surrogate pair to the single codepoint it represents.
This implements the formula described at:
http://en.wikipedia.org/wiki/Universal_Character_Set_characters#Surrogates
"""
pair = match.group(0)
codept = 0x10000 + (ord(pair[0]) - 0xd800) * ... | [
"def",
"convert_surrogate_pair",
"(",
"match",
")",
":",
"pair",
"=",
"match",
".",
"group",
"(",
"0",
")",
"codept",
"=",
"0x10000",
"+",
"(",
"ord",
"(",
"pair",
"[",
"0",
"]",
")",
"-",
"0xd800",
")",
"*",
"0x400",
"+",
"(",
"ord",
"(",
"pair"... | Convert a surrogate pair to the single codepoint it represents.
This implements the formula described at:
http://en.wikipedia.org/wiki/Universal_Character_Set_characters#Surrogates | [
"Convert",
"a",
"surrogate",
"pair",
"to",
"the",
"single",
"codepoint",
"it",
"represents",
"."
] | python | train | 36.5 |
ellethee/argparseinator | argparseinator/__main__.py | https://github.com/ellethee/argparseinator/blob/05e9c00dfaa938b9c4ee2aadc6206f5e0918e24e/argparseinator/__main__.py#L115-L145 | def init(name, subnames, dest, skeleton, description, project_type, skip_core):
"""Creates a standalone, subprojects or submodules script sctrucure"""
dest = dest or CUR_DIR
skeleton = join(skeleton or SKEL_PATH, project_type)
project = join(dest, name)
script = join(project, name + '.py')
core ... | [
"def",
"init",
"(",
"name",
",",
"subnames",
",",
"dest",
",",
"skeleton",
",",
"description",
",",
"project_type",
",",
"skip_core",
")",
":",
"dest",
"=",
"dest",
"or",
"CUR_DIR",
"skeleton",
"=",
"join",
"(",
"skeleton",
"or",
"SKEL_PATH",
",",
"proje... | Creates a standalone, subprojects or submodules script sctrucure | [
"Creates",
"a",
"standalone",
"subprojects",
"or",
"submodules",
"script",
"sctrucure"
] | python | train | 43.258065 |
Unidata/MetPy | metpy/io/_tools.py | https://github.com/Unidata/MetPy/blob/16f68a94919b9a82dcf9cada2169cf039129e67b/metpy/io/_tools.py#L153-L155 | def unpack(self, s):
"""Parse bytes and return a namedtuple."""
return self._create(super(DictStruct, self).unpack(s)) | [
"def",
"unpack",
"(",
"self",
",",
"s",
")",
":",
"return",
"self",
".",
"_create",
"(",
"super",
"(",
"DictStruct",
",",
"self",
")",
".",
"unpack",
"(",
"s",
")",
")"
] | Parse bytes and return a namedtuple. | [
"Parse",
"bytes",
"and",
"return",
"a",
"namedtuple",
"."
] | python | train | 44 |
bokeh/bokeh | bokeh/server/connection.py | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/server/connection.py#L62-L66 | def detach_session(self):
"""Allow the session to be discarded and don't get change notifications from it anymore"""
if self._session is not None:
self._session.unsubscribe(self)
self._session = None | [
"def",
"detach_session",
"(",
"self",
")",
":",
"if",
"self",
".",
"_session",
"is",
"not",
"None",
":",
"self",
".",
"_session",
".",
"unsubscribe",
"(",
"self",
")",
"self",
".",
"_session",
"=",
"None"
] | Allow the session to be discarded and don't get change notifications from it anymore | [
"Allow",
"the",
"session",
"to",
"be",
"discarded",
"and",
"don",
"t",
"get",
"change",
"notifications",
"from",
"it",
"anymore"
] | python | train | 47 |
teepark/greenhouse | greenhouse/ext/zmq.py | https://github.com/teepark/greenhouse/blob/8fd1be4f5443ba090346b5ec82fdbeb0a060d956/greenhouse/ext/zmq.py#L12-L79 | def wait_socks(sock_events, inmask=1, outmask=2, timeout=None):
"""wait on a combination of zeromq sockets, normal sockets, and fds
.. note:: this method can block
it will return once there is relevant activity on any of the
descriptors or sockets, or the timeout expires
:param sock_event... | [
"def",
"wait_socks",
"(",
"sock_events",
",",
"inmask",
"=",
"1",
",",
"outmask",
"=",
"2",
",",
"timeout",
"=",
"None",
")",
":",
"results",
"=",
"[",
"]",
"for",
"sock",
",",
"mask",
"in",
"sock_events",
":",
"if",
"isinstance",
"(",
"sock",
",",
... | wait on a combination of zeromq sockets, normal sockets, and fds
.. note:: this method can block
it will return once there is relevant activity on any of the
descriptors or sockets, or the timeout expires
:param sock_events:
two-tuples, the first item is either a zeromq socket, a sock... | [
"wait",
"on",
"a",
"combination",
"of",
"zeromq",
"sockets",
"normal",
"sockets",
"and",
"fds"
] | python | train | 32.544118 |
brutasse/graphite-api | graphite_api/functions.py | https://github.com/brutasse/graphite-api/blob/0886b7adcf985a1e8bcb084f6dd1dc166a3f3dff/graphite_api/functions.py#L3443-L3470 | def isNonNull(requestContext, seriesList):
"""
Takes a metric or wild card seriesList and counts up how many
non-null values are specified. This is useful for understanding
which metrics have data at a given point in time (ie, to count
which servers are alive).
Example::
&target=isNonN... | [
"def",
"isNonNull",
"(",
"requestContext",
",",
"seriesList",
")",
":",
"def",
"transform",
"(",
"v",
")",
":",
"if",
"v",
"is",
"None",
":",
"return",
"0",
"else",
":",
"return",
"1",
"for",
"series",
"in",
"seriesList",
":",
"series",
".",
"name",
... | Takes a metric or wild card seriesList and counts up how many
non-null values are specified. This is useful for understanding
which metrics have data at a given point in time (ie, to count
which servers are alive).
Example::
&target=isNonNull(webapp.pages.*.views)
Returns a seriesList whe... | [
"Takes",
"a",
"metric",
"or",
"wild",
"card",
"seriesList",
"and",
"counts",
"up",
"how",
"many",
"non",
"-",
"null",
"values",
"are",
"specified",
".",
"This",
"is",
"useful",
"for",
"understanding",
"which",
"metrics",
"have",
"data",
"at",
"a",
"given",... | python | train | 28.464286 |
zyga/json-schema-validator | json_schema_validator/schema.py | https://github.com/zyga/json-schema-validator/blob/0504605da5c0a9a5b5b05c41b37661aec9652144/json_schema_validator/schema.py#L340-L354 | def format(self):
"""Format of the (string) object."""
value = self._schema.get("format", None)
if value is None:
return
if not isinstance(value, basestring):
raise SchemaError(
"format value {0!r} is not a string".format(value))
if value i... | [
"def",
"format",
"(",
"self",
")",
":",
"value",
"=",
"self",
".",
"_schema",
".",
"get",
"(",
"\"format\"",
",",
"None",
")",
"if",
"value",
"is",
"None",
":",
"return",
"if",
"not",
"isinstance",
"(",
"value",
",",
"basestring",
")",
":",
"raise",
... | Format of the (string) object. | [
"Format",
"of",
"the",
"(",
"string",
")",
"object",
"."
] | python | train | 32.733333 |
eventbrite/pysoa | pysoa/common/logging.py | https://github.com/eventbrite/pysoa/blob/9c052cae2397d13de3df8ae2c790846a70b53f18/pysoa/common/logging.py#L376-L399 | def _cleanly_slice_encoded_string(encoded_string, length_limit):
"""
Takes a byte string (a UTF-8 encoded string) and splits it into two pieces such that the first slice is no
longer than argument `length_limit`, then returns a tuple containing the first slice and remainder of the
byte s... | [
"def",
"_cleanly_slice_encoded_string",
"(",
"encoded_string",
",",
"length_limit",
")",
":",
"sliced",
",",
"remaining",
"=",
"encoded_string",
"[",
":",
"length_limit",
"]",
",",
"encoded_string",
"[",
"length_limit",
":",
"]",
"try",
":",
"sliced",
".",
"deco... | Takes a byte string (a UTF-8 encoded string) and splits it into two pieces such that the first slice is no
longer than argument `length_limit`, then returns a tuple containing the first slice and remainder of the
byte string, respectively. The first slice may actually be shorter than `length_limit`, bec... | [
"Takes",
"a",
"byte",
"string",
"(",
"a",
"UTF",
"-",
"8",
"encoded",
"string",
")",
"and",
"splits",
"it",
"into",
"two",
"pieces",
"such",
"that",
"the",
"first",
"slice",
"is",
"no",
"longer",
"than",
"argument",
"length_limit",
"then",
"returns",
"a"... | python | train | 55.666667 |
Unidata/siphon | siphon/ncss.py | https://github.com/Unidata/siphon/blob/53fb0d84fbce1c18c8e81c9e68bc81620ee0a6ac/siphon/ncss.py#L315-L318 | def parse_xml(data, handle_units):
"""Parse XML data returned by NCSS."""
root = ET.fromstring(data)
return squish(parse_xml_dataset(root, handle_units)) | [
"def",
"parse_xml",
"(",
"data",
",",
"handle_units",
")",
":",
"root",
"=",
"ET",
".",
"fromstring",
"(",
"data",
")",
"return",
"squish",
"(",
"parse_xml_dataset",
"(",
"root",
",",
"handle_units",
")",
")"
] | Parse XML data returned by NCSS. | [
"Parse",
"XML",
"data",
"returned",
"by",
"NCSS",
"."
] | python | train | 40.5 |
Kraymer/high | high/__init__.py | https://github.com/Kraymer/high/blob/11bb86733875ec708264ffb92bf5ef09a9d2f08c/high/__init__.py#L100-L118 | def high_cli(repo_name, login, with_blog, as_list, role):
"""Extract mails from stargazers, collaborators and people involved with issues of given
repository.
"""
passw = getpass.getpass()
github = gh_login(login, passw)
repo = github.repository(login, repo_name)
role = [ROLES[k] for k in ro... | [
"def",
"high_cli",
"(",
"repo_name",
",",
"login",
",",
"with_blog",
",",
"as_list",
",",
"role",
")",
":",
"passw",
"=",
"getpass",
".",
"getpass",
"(",
")",
"github",
"=",
"gh_login",
"(",
"login",
",",
"passw",
")",
"repo",
"=",
"github",
".",
"re... | Extract mails from stargazers, collaborators and people involved with issues of given
repository. | [
"Extract",
"mails",
"from",
"stargazers",
"collaborators",
"and",
"people",
"involved",
"with",
"issues",
"of",
"given",
"repository",
"."
] | python | train | 31.526316 |
dh1tw/pyhamtools | pyhamtools/qsl.py | https://github.com/dh1tw/pyhamtools/blob/ee7e4b8732e23c298da10e07163748156c16d0fa/pyhamtools/qsl.py#L159-L206 | def get_eqsl_users(**kwargs):
"""Download the latest official list of `EQSL.cc`__ users. The list of users can be found here_.
Args:
url (str, optional): Download URL
Returns:
list: List containing the callsigns of EQSL users (unicode)
Raises:
IOError: ... | [
"def",
"get_eqsl_users",
"(",
"*",
"*",
"kwargs",
")",
":",
"url",
"=",
"\"\"",
"eqsl",
"=",
"[",
"]",
"try",
":",
"url",
"=",
"kwargs",
"[",
"'url'",
"]",
"except",
"KeyError",
":",
"url",
"=",
"\"http://www.eqsl.cc/QSLCard/DownloadedFiles/AGMemberlist.txt\""... | Download the latest official list of `EQSL.cc`__ users. The list of users can be found here_.
Args:
url (str, optional): Download URL
Returns:
list: List containing the callsigns of EQSL users (unicode)
Raises:
IOError: When network is unavailable, file can... | [
"Download",
"the",
"latest",
"official",
"list",
"of",
"EQSL",
".",
"cc",
"__",
"users",
".",
"The",
"list",
"of",
"users",
"can",
"be",
"found",
"here_",
"."
] | python | train | 27.291667 |
ergo/ziggurat_foundations | ziggurat_foundations/migrations/env.py | https://github.com/ergo/ziggurat_foundations/blob/9eeec894d08e8d7defa60ddc04b63f69cd4cbeba/ziggurat_foundations/migrations/env.py#L51-L71 | def run_migrations_offline():
"""Run migrations in 'offline' mode.
This configures the context with just a URL
and not an Engine, though an Engine is acceptable
here as well. By skipping the Engine creation
we don't even need a DBAPI to be available.
Calls to context.execute() here emit the g... | [
"def",
"run_migrations_offline",
"(",
")",
":",
"url",
"=",
"get_url",
"(",
")",
"context",
".",
"configure",
"(",
"url",
"=",
"url",
",",
"version_table",
"=",
"\"alembic_ziggurat_foundations_version\"",
",",
"transaction_per_migration",
"=",
"True",
",",
")",
... | Run migrations in 'offline' mode.
This configures the context with just a URL
and not an Engine, though an Engine is acceptable
here as well. By skipping the Engine creation
we don't even need a DBAPI to be available.
Calls to context.execute() here emit the given string to the
script output. | [
"Run",
"migrations",
"in",
"offline",
"mode",
"."
] | python | train | 27.904762 |
docker/docker-py | docker/api/container.py | https://github.com/docker/docker-py/blob/613d6aad83acc9931ff2ecfd6a6c7bd8061dc125/docker/api/container.py#L114-L147 | def commit(self, container, repository=None, tag=None, message=None,
author=None, changes=None, conf=None):
"""
Commit a container to an image. Similar to the ``docker commit``
command.
Args:
container (str): The image hash of the container
reposit... | [
"def",
"commit",
"(",
"self",
",",
"container",
",",
"repository",
"=",
"None",
",",
"tag",
"=",
"None",
",",
"message",
"=",
"None",
",",
"author",
"=",
"None",
",",
"changes",
"=",
"None",
",",
"conf",
"=",
"None",
")",
":",
"params",
"=",
"{",
... | Commit a container to an image. Similar to the ``docker commit``
command.
Args:
container (str): The image hash of the container
repository (str): The repository to push the image to
tag (str): The tag to push
message (str): A commit message
a... | [
"Commit",
"a",
"container",
"to",
"an",
"image",
".",
"Similar",
"to",
"the",
"docker",
"commit",
"command",
"."
] | python | train | 36.558824 |
bcbio/bcbio-nextgen | bcbio/illumina/flowcell.py | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/illumina/flowcell.py#L28-L37 | def get_qseq_dir(fc_dir):
"""Retrieve the qseq directory within Solexa flowcell output.
"""
machine_bc = os.path.join(fc_dir, "Data", "Intensities", "BaseCalls")
if os.path.exists(machine_bc):
return machine_bc
# otherwise assume we are in the qseq directory
# XXX What other cases can we... | [
"def",
"get_qseq_dir",
"(",
"fc_dir",
")",
":",
"machine_bc",
"=",
"os",
".",
"path",
".",
"join",
"(",
"fc_dir",
",",
"\"Data\"",
",",
"\"Intensities\"",
",",
"\"BaseCalls\"",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"machine_bc",
")",
":",
"... | Retrieve the qseq directory within Solexa flowcell output. | [
"Retrieve",
"the",
"qseq",
"directory",
"within",
"Solexa",
"flowcell",
"output",
"."
] | python | train | 36.1 |
gem/oq-engine | openquake/commonlib/rlzs_assoc.py | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/rlzs_assoc.py#L102-L126 | def get_rlzs_by_gsim(self, trt_or_grp_id, sm_id=None):
"""
:param trt_or_grp_id: a tectonic region type or a source group ID
:param sm_id: source model ordinal (or None)
:returns: a dictionary gsim -> rlzs
"""
if isinstance(trt_or_grp_id, (int, U16, U32)): # grp_id
... | [
"def",
"get_rlzs_by_gsim",
"(",
"self",
",",
"trt_or_grp_id",
",",
"sm_id",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"trt_or_grp_id",
",",
"(",
"int",
",",
"U16",
",",
"U32",
")",
")",
":",
"# grp_id",
"trt",
"=",
"self",
".",
"csm_info",
".",
... | :param trt_or_grp_id: a tectonic region type or a source group ID
:param sm_id: source model ordinal (or None)
:returns: a dictionary gsim -> rlzs | [
":",
"param",
"trt_or_grp_id",
":",
"a",
"tectonic",
"region",
"type",
"or",
"a",
"source",
"group",
"ID",
":",
"param",
"sm_id",
":",
"source",
"model",
"ordinal",
"(",
"or",
"None",
")",
":",
"returns",
":",
"a",
"dictionary",
"gsim",
"-",
">",
"rlzs... | python | train | 48.92 |
jaredLunde/redis_structures | redis_structures/__init__.py | https://github.com/jaredLunde/redis_structures/blob/b9cce5f5c85db5e12c292633ff8d04e3ae053294/redis_structures/__init__.py#L2179-L2198 | def itemsbyscore(self, min='-inf', max='+inf', start=None, num=None,
reverse=None):
""" Return a range of |(member, score)| pairs from the sorted set name
with scores between @min and @max.
If @start and @num are specified, then return a slice
of the ran... | [
"def",
"itemsbyscore",
"(",
"self",
",",
"min",
"=",
"'-inf'",
",",
"max",
"=",
"'+inf'",
",",
"start",
"=",
"None",
",",
"num",
"=",
"None",
",",
"reverse",
"=",
"None",
")",
":",
"reverse",
"=",
"reverse",
"if",
"reverse",
"is",
"not",
"None",
"e... | Return a range of |(member, score)| pairs from the sorted set name
with scores between @min and @max.
If @start and @num are specified, then return a slice
of the range.
@min: #int minimum score, or #str '-inf'
@max: #int minimum score, or #str '+inf'
... | [
"Return",
"a",
"range",
"of",
"|",
"(",
"member",
"score",
")",
"|",
"pairs",
"from",
"the",
"sorted",
"set",
"name",
"with",
"scores",
"between",
"@min",
"and",
"@max",
"."
] | python | train | 42.85 |
jaredLunde/vital-tools | vital/debug/stats.py | https://github.com/jaredLunde/vital-tools/blob/ea924c9bbb6ec22aa66f8095f018b1ee0099ac04/vital/debug/stats.py#L36-L44 | def pstdev(data):
"""Calculates the population standard deviation."""
#: http://stackoverflow.com/a/27758326
n = len(data)
if n < 2:
raise ValueError('variance requires at least two data points')
ss = _ss(data)
pvar = ss/n # the population variance
return pvar**0.5 | [
"def",
"pstdev",
"(",
"data",
")",
":",
"#: http://stackoverflow.com/a/27758326",
"n",
"=",
"len",
"(",
"data",
")",
"if",
"n",
"<",
"2",
":",
"raise",
"ValueError",
"(",
"'variance requires at least two data points'",
")",
"ss",
"=",
"_ss",
"(",
"data",
")",
... | Calculates the population standard deviation. | [
"Calculates",
"the",
"population",
"standard",
"deviation",
"."
] | python | train | 32.666667 |
astropy/photutils | photutils/datasets/make.py | https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/datasets/make.py#L26-L78 | def apply_poisson_noise(data, random_state=None):
"""
Apply Poisson noise to an array, where the value of each element in
the input array represents the expected number of counts.
Each pixel in the output array is generated by drawing a random
sample from a Poisson distribution whose expectation va... | [
"def",
"apply_poisson_noise",
"(",
"data",
",",
"random_state",
"=",
"None",
")",
":",
"data",
"=",
"np",
".",
"asanyarray",
"(",
"data",
")",
"if",
"np",
".",
"any",
"(",
"data",
"<",
"0",
")",
":",
"raise",
"ValueError",
"(",
"'data must not contain an... | Apply Poisson noise to an array, where the value of each element in
the input array represents the expected number of counts.
Each pixel in the output array is generated by drawing a random
sample from a Poisson distribution whose expectation value is given
by the pixel value in the input array.
P... | [
"Apply",
"Poisson",
"noise",
"to",
"an",
"array",
"where",
"the",
"value",
"of",
"each",
"element",
"in",
"the",
"input",
"array",
"represents",
"the",
"expected",
"number",
"of",
"counts",
"."
] | python | train | 31.622642 |
prometheus/client_python | prometheus_client/registry.py | https://github.com/prometheus/client_python/blob/31f5557e2e84ca4ffa9a03abf6e3f4d0c8b8c3eb/prometheus_client/registry.py#L69-L76 | def collect(self):
"""Yields metrics from the collectors in the registry."""
collectors = None
with self._lock:
collectors = copy.copy(self._collector_to_names)
for collector in collectors:
for metric in collector.collect():
yield metric | [
"def",
"collect",
"(",
"self",
")",
":",
"collectors",
"=",
"None",
"with",
"self",
".",
"_lock",
":",
"collectors",
"=",
"copy",
".",
"copy",
"(",
"self",
".",
"_collector_to_names",
")",
"for",
"collector",
"in",
"collectors",
":",
"for",
"metric",
"in... | Yields metrics from the collectors in the registry. | [
"Yields",
"metrics",
"from",
"the",
"collectors",
"in",
"the",
"registry",
"."
] | python | train | 37.75 |
Microsoft/azure-devops-python-api | azure-devops/azure/devops/v5_0/task_agent/task_agent_client.py | https://github.com/Microsoft/azure-devops-python-api/blob/4777ffda2f5052fabbaddb2abe9cb434e0cf1aa8/azure-devops/azure/devops/v5_0/task_agent/task_agent_client.py#L337-L353 | def add_task_group(self, task_group, project):
"""AddTaskGroup.
[Preview API] Create a task group.
:param :class:`<TaskGroupCreateParameter> <azure.devops.v5_0.task_agent.models.TaskGroupCreateParameter>` task_group: Task group object to create.
:param str project: Project ID or project ... | [
"def",
"add_task_group",
"(",
"self",
",",
"task_group",
",",
"project",
")",
":",
"route_values",
"=",
"{",
"}",
"if",
"project",
"is",
"not",
"None",
":",
"route_values",
"[",
"'project'",
"]",
"=",
"self",
".",
"_serialize",
".",
"url",
"(",
"'project... | AddTaskGroup.
[Preview API] Create a task group.
:param :class:`<TaskGroupCreateParameter> <azure.devops.v5_0.task_agent.models.TaskGroupCreateParameter>` task_group: Task group object to create.
:param str project: Project ID or project name
:rtype: :class:`<TaskGroup> <azure.devops.v5_... | [
"AddTaskGroup",
".",
"[",
"Preview",
"API",
"]",
"Create",
"a",
"task",
"group",
".",
":",
"param",
":",
"class",
":",
"<TaskGroupCreateParameter",
">",
"<azure",
".",
"devops",
".",
"v5_0",
".",
"task_agent",
".",
"models",
".",
"TaskGroupCreateParameter",
... | python | train | 57.294118 |
Kautenja/nes-py | nes_py/nes_env.py | https://github.com/Kautenja/nes-py/blob/a113885198d418f38fcf24b8f79ac508975788c2/nes_py/nes_env.py#L152-L167 | def _screen_buffer(self):
"""Setup the screen buffer from the C++ code."""
# get the address of the screen
address = _LIB.Screen(self._env)
# create a buffer from the contents of the address location
buffer_ = ctypes.cast(address, ctypes.POINTER(SCREEN_TENSOR)).contents
#... | [
"def",
"_screen_buffer",
"(",
"self",
")",
":",
"# get the address of the screen",
"address",
"=",
"_LIB",
".",
"Screen",
"(",
"self",
".",
"_env",
")",
"# create a buffer from the contents of the address location",
"buffer_",
"=",
"ctypes",
".",
"cast",
"(",
"address... | Setup the screen buffer from the C++ code. | [
"Setup",
"the",
"screen",
"buffer",
"from",
"the",
"C",
"++",
"code",
"."
] | python | train | 52.625 |
trehn/termdown | termdown.py | https://github.com/trehn/termdown/blob/aa0c4e39d9864fd1466ef9d76947fb93d0cf5be2/termdown.py#L201-L232 | def parse_timestr(timestr):
"""
Parse a string describing a point in time.
"""
timedelta_secs = parse_timedelta(timestr)
sync_start = datetime.now()
if timedelta_secs:
target = datetime.now() + timedelta(seconds=timedelta_secs)
elif timestr.isdigit():
target = datetime.now()... | [
"def",
"parse_timestr",
"(",
"timestr",
")",
":",
"timedelta_secs",
"=",
"parse_timedelta",
"(",
"timestr",
")",
"sync_start",
"=",
"datetime",
".",
"now",
"(",
")",
"if",
"timedelta_secs",
":",
"target",
"=",
"datetime",
".",
"now",
"(",
")",
"+",
"timede... | Parse a string describing a point in time. | [
"Parse",
"a",
"string",
"describing",
"a",
"point",
"in",
"time",
"."
] | python | train | 38.34375 |
romanz/trezor-agent | libagent/util.py | https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/util.py#L219-L234 | def memoize_method(method):
"""Simple caching decorator."""
cache = {}
@functools.wraps(method)
def wrapper(self, *args, **kwargs):
"""Caching wrapper."""
key = (args, tuple(sorted(kwargs.items())))
if key in cache:
return cache[key]
else:
result ... | [
"def",
"memoize_method",
"(",
"method",
")",
":",
"cache",
"=",
"{",
"}",
"@",
"functools",
".",
"wraps",
"(",
"method",
")",
"def",
"wrapper",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"\"\"\"Caching wrapper.\"\"\"",
"key",
"="... | Simple caching decorator. | [
"Simple",
"caching",
"decorator",
"."
] | python | train | 25.875 |
OSSOS/MOP | src/jjk/preproc/MOPplot.py | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/jjk/preproc/MOPplot.py#L454-L460 | def updateObj(self,event):
"""Put this object in the search box"""
name=w.objList.get("active")
w.SearchVar.set(name)
w.ObjInfo.set(objInfoDict[name])
return | [
"def",
"updateObj",
"(",
"self",
",",
"event",
")",
":",
"name",
"=",
"w",
".",
"objList",
".",
"get",
"(",
"\"active\"",
")",
"w",
".",
"SearchVar",
".",
"set",
"(",
"name",
")",
"w",
".",
"ObjInfo",
".",
"set",
"(",
"objInfoDict",
"[",
"name",
... | Put this object in the search box | [
"Put",
"this",
"object",
"in",
"the",
"search",
"box"
] | python | train | 28.571429 |
kytos/python-openflow | pyof/foundation/base.py | https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/foundation/base.py#L414-L478 | def get_pyof_obj_new_version(name, obj, new_version):
r"""Return a class attribute on a different pyof version.
This method receives the name of a class attribute, the class attribute
itself (object) and an openflow version.
The attribute will be evaluated and from it we will recover it... | [
"def",
"get_pyof_obj_new_version",
"(",
"name",
",",
"obj",
",",
"new_version",
")",
":",
"if",
"new_version",
"is",
"None",
":",
"return",
"(",
"name",
",",
"obj",
")",
"cls",
"=",
"obj",
".",
"__class__",
"cls_name",
"=",
"cls",
".",
"__name__",
"cls_m... | r"""Return a class attribute on a different pyof version.
This method receives the name of a class attribute, the class attribute
itself (object) and an openflow version.
The attribute will be evaluated and from it we will recover its class
and the module where the class was defined.
... | [
"r",
"Return",
"a",
"class",
"attribute",
"on",
"a",
"different",
"pyof",
"version",
"."
] | python | train | 42.292308 |
odlgroup/odl | odl/tomo/backends/astra_setup.py | https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/tomo/backends/astra_setup.py#L428-L502 | def astra_projection_geometry(geometry):
"""Create an ASTRA projection geometry from an ODL geometry object.
As of ASTRA version 1.7, the length values are not required any more to be
rescaled for 3D geometries and non-unit (but isotropic) voxel sizes.
Parameters
----------
geometry : `Geometr... | [
"def",
"astra_projection_geometry",
"(",
"geometry",
")",
":",
"if",
"not",
"isinstance",
"(",
"geometry",
",",
"Geometry",
")",
":",
"raise",
"TypeError",
"(",
"'`geometry` {!r} is not a `Geometry` instance'",
"''",
".",
"format",
"(",
"geometry",
")",
")",
"if",... | Create an ASTRA projection geometry from an ODL geometry object.
As of ASTRA version 1.7, the length values are not required any more to be
rescaled for 3D geometries and non-unit (but isotropic) voxel sizes.
Parameters
----------
geometry : `Geometry`
ODL projection geometry from which to... | [
"Create",
"an",
"ASTRA",
"projection",
"geometry",
"from",
"an",
"ODL",
"geometry",
"object",
"."
] | python | train | 43.293333 |
SBRG/ssbio | ssbio/protein/sequence/seqprop.py | https://github.com/SBRG/ssbio/blob/e9449e64ffc1a1f5ad07e5849aa12a650095f8a2/ssbio/protein/sequence/seqprop.py#L375-L389 | def feature_path_unset(self):
"""Copy features to memory and remove the association of the feature file."""
if not self.feature_file:
raise IOError('No feature file to unset')
with open(self.feature_path) as handle:
feats = list(GFF.parse(handle))
if len(feat... | [
"def",
"feature_path_unset",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"feature_file",
":",
"raise",
"IOError",
"(",
"'No feature file to unset'",
")",
"with",
"open",
"(",
"self",
".",
"feature_path",
")",
"as",
"handle",
":",
"feats",
"=",
"list",
... | Copy features to memory and remove the association of the feature file. | [
"Copy",
"features",
"to",
"memory",
"and",
"remove",
"the",
"association",
"of",
"the",
"feature",
"file",
"."
] | python | train | 34.8 |
gebn/nibble | nibble/expression/parser.py | https://github.com/gebn/nibble/blob/e82a2c43509ed38f3d039040591cc630fa676cb0/nibble/expression/parser.py#L94-L97 | def p_duration_number_duration_unit(self, p):
'duration : NUMBER DURATION_UNIT'
logger.debug('duration = number %s, duration unit %s', p[1], p[2])
p[0] = Duration.from_quantity_unit(p[1], p[2]) | [
"def",
"p_duration_number_duration_unit",
"(",
"self",
",",
"p",
")",
":",
"logger",
".",
"debug",
"(",
"'duration = number %s, duration unit %s'",
",",
"p",
"[",
"1",
"]",
",",
"p",
"[",
"2",
"]",
")",
"p",
"[",
"0",
"]",
"=",
"Duration",
".",
"from_qua... | duration : NUMBER DURATION_UNIT | [
"duration",
":",
"NUMBER",
"DURATION_UNIT"
] | python | train | 53.5 |
cackharot/suds-py3 | suds/sax/date.py | https://github.com/cackharot/suds-py3/blob/7387ec7806e9be29aad0a711bea5cb3c9396469c/suds/sax/date.py#L131-L152 | def parse(value):
"""Parse the string date.
This supports the subset of ISO8601 used by xsd:time, but is lenient
with what is accepted, handling most reasonable syntax.
@param value: A time string.
@type value: str
@return: A time object.
@rtype: B{datetime}.I{t... | [
"def",
"parse",
"(",
"value",
")",
":",
"match_result",
"=",
"RE_TIME",
".",
"match",
"(",
"value",
")",
"if",
"match_result",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"'date data has invalid format \"%s\"'",
"%",
"(",
"value",
",",
")",
")",
"date",
... | Parse the string date.
This supports the subset of ISO8601 used by xsd:time, but is lenient
with what is accepted, handling most reasonable syntax.
@param value: A time string.
@type value: str
@return: A time object.
@rtype: B{datetime}.I{time} | [
"Parse",
"the",
"string",
"date",
"."
] | python | train | 28.772727 |
ryanmcgrath/twython | twython/endpoints.py | https://github.com/ryanmcgrath/twython/blob/7366de80efcbbdfaf615d3f1fea72546196916fc/twython/endpoints.py#L134-L147 | def update_status_with_media(self, **params): # pragma: no cover
"""Updates the authenticating user's current status and attaches media
for upload. In other words, it creates a Tweet with a picture attached.
Docs:
https://developer.twitter.com/en/docs/tweets/post-and-engage/api-referen... | [
"def",
"update_status_with_media",
"(",
"self",
",",
"*",
"*",
"params",
")",
":",
"# pragma: no cover",
"warnings",
".",
"warn",
"(",
"'This method is deprecated. You should use Twython.upload_media instead.'",
",",
"TwythonDeprecationWarning",
",",
"stacklevel",
"=",
"2",... | Updates the authenticating user's current status and attaches media
for upload. In other words, it creates a Tweet with a picture attached.
Docs:
https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update_with_media | [
"Updates",
"the",
"authenticating",
"user",
"s",
"current",
"status",
"and",
"attaches",
"media",
"for",
"upload",
".",
"In",
"other",
"words",
"it",
"creates",
"a",
"Tweet",
"with",
"a",
"picture",
"attached",
"."
] | python | train | 43.428571 |
ianepperson/pyredminews | redmine/redmine.py | https://github.com/ianepperson/pyredminews/blob/b2b0581483632738a3acca3b4e093c181847b813/redmine/redmine.py#L239-L256 | def journals(self):
"""
Retrieve journals attribute for this very Issue
"""
try:
target = self._item_path
json_data = self._redmine.get(target % str(self.id),
parms={'include': 'journals'})
data = self._redmine... | [
"def",
"journals",
"(",
"self",
")",
":",
"try",
":",
"target",
"=",
"self",
".",
"_item_path",
"json_data",
"=",
"self",
".",
"_redmine",
".",
"get",
"(",
"target",
"%",
"str",
"(",
"self",
".",
"id",
")",
",",
"parms",
"=",
"{",
"'include'",
":",... | Retrieve journals attribute for this very Issue | [
"Retrieve",
"journals",
"attribute",
"for",
"this",
"very",
"Issue"
] | python | train | 35.055556 |
willemarcel/osmcha | osmcha/changeset.py | https://github.com/willemarcel/osmcha/blob/9a22ed11834ed20c6b91e7b5685f66880ea09350/osmcha/changeset.py#L210-L225 | def read_file(self, changeset_file):
"""Download the replication changeset file or read it directly from the
filesystem (to test purposes).
"""
if isfile(changeset_file):
self.filename = changeset_file
else:
self.path = mkdtemp()
self.filename ... | [
"def",
"read_file",
"(",
"self",
",",
"changeset_file",
")",
":",
"if",
"isfile",
"(",
"changeset_file",
")",
":",
"self",
".",
"filename",
"=",
"changeset_file",
"else",
":",
"self",
".",
"path",
"=",
"mkdtemp",
"(",
")",
"self",
".",
"filename",
"=",
... | Download the replication changeset file or read it directly from the
filesystem (to test purposes). | [
"Download",
"the",
"replication",
"changeset",
"file",
"or",
"read",
"it",
"directly",
"from",
"the",
"filesystem",
"(",
"to",
"test",
"purposes",
")",
"."
] | python | valid | 36.625 |
NASA-AMMOS/AIT-Core | ait/core/val.py | https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/val.py#L60-L77 | def load(self, ymlfile=None):
"""Load and process the YAML file"""
if ymlfile is not None:
self.ymlfile = ymlfile
try:
# If yaml should be 'cleaned' of document references
if self._clean:
self.data = self.process(self.ymlfile)
else... | [
"def",
"load",
"(",
"self",
",",
"ymlfile",
"=",
"None",
")",
":",
"if",
"ymlfile",
"is",
"not",
"None",
":",
"self",
".",
"ymlfile",
"=",
"ymlfile",
"try",
":",
"# If yaml should be 'cleaned' of document references",
"if",
"self",
".",
"_clean",
":",
"self"... | Load and process the YAML file | [
"Load",
"and",
"process",
"the",
"YAML",
"file"
] | python | train | 36.111111 |
PhilipTrauner/Meh | meh/__init__.py | https://github.com/PhilipTrauner/Meh/blob/c9bb695c1cfbc645c3ccceb27e40dadba7678815/meh/__init__.py#L294-L305 | def remove(self, option):
"""
Removes an option from a Config instance
IN: option (type: Option)
"""
if option.__class__ == Option:
if option in self.options:
del self.options[self.options.index(option)]
else:
raise OptionNotFoundError(option.name)
else:
raise TypeError("invalid type suppli... | [
"def",
"remove",
"(",
"self",
",",
"option",
")",
":",
"if",
"option",
".",
"__class__",
"==",
"Option",
":",
"if",
"option",
"in",
"self",
".",
"options",
":",
"del",
"self",
".",
"options",
"[",
"self",
".",
"options",
".",
"index",
"(",
"option",
... | Removes an option from a Config instance
IN: option (type: Option) | [
"Removes",
"an",
"option",
"from",
"a",
"Config",
"instance",
"IN",
":",
"option",
"(",
"type",
":",
"Option",
")"
] | python | train | 26.083333 |
mikedh/trimesh | trimesh/visual/resolvers.py | https://github.com/mikedh/trimesh/blob/25e059bf6d4caa74f62ffd58ce4f61a90ee4e518/trimesh/visual/resolvers.py#L91-L126 | def get(self, name):
"""
Get an asset from the ZIP archive.
Parameters
-------------
name : str
Name of the asset
Returns
-------------
data : bytes
Loaded data from asset
"""
# not much we can do with that
if ... | [
"def",
"get",
"(",
"self",
",",
"name",
")",
":",
"# not much we can do with that",
"if",
"name",
"is",
"None",
":",
"return",
"# if name isn't in archive try some similar values",
"if",
"name",
"not",
"in",
"self",
".",
"archive",
":",
"if",
"hasattr",
"(",
"na... | Get an asset from the ZIP archive.
Parameters
-------------
name : str
Name of the asset
Returns
-------------
data : bytes
Loaded data from asset | [
"Get",
"an",
"asset",
"from",
"the",
"ZIP",
"archive",
"."
] | python | train | 27.944444 |
theonion/django-bulbs | bulbs/contributions/email.py | https://github.com/theonion/django-bulbs/blob/0c0e6e3127a7dc487b96677fab95cacd2b3806da/bulbs/contributions/email.py#L90-L96 | def line_items(self):
"""Apply a datetime filter against the contributors's line item queryset."""
if self._line_items is None:
self._line_items = self.contributor.line_items.filter(
payment_date__range=(self.start, self.end)
)
return self._line_items | [
"def",
"line_items",
"(",
"self",
")",
":",
"if",
"self",
".",
"_line_items",
"is",
"None",
":",
"self",
".",
"_line_items",
"=",
"self",
".",
"contributor",
".",
"line_items",
".",
"filter",
"(",
"payment_date__range",
"=",
"(",
"self",
".",
"start",
",... | Apply a datetime filter against the contributors's line item queryset. | [
"Apply",
"a",
"datetime",
"filter",
"against",
"the",
"contributors",
"s",
"line",
"item",
"queryset",
"."
] | python | train | 44.142857 |
HewlettPackard/python-hpOneView | hpOneView/resources/networking/logical_interconnects.py | https://github.com/HewlettPackard/python-hpOneView/blob/3c6219723ef25e6e0c83d44a89007f89bc325b89/hpOneView/resources/networking/logical_interconnects.py#L449-L464 | def update_qos_aggregated_configuration(self, qos_configuration, timeout=-1):
"""
Updates the QoS aggregated configuration for the logical interconnect.
Args:
qos_configuration:
QOS configuration.
timeout:
Timeout in seconds. Wait for task... | [
"def",
"update_qos_aggregated_configuration",
"(",
"self",
",",
"qos_configuration",
",",
"timeout",
"=",
"-",
"1",
")",
":",
"uri",
"=",
"\"{}{}\"",
".",
"format",
"(",
"self",
".",
"data",
"[",
"\"uri\"",
"]",
",",
"self",
".",
"QOS_AGGREGATED_CONFIGURATION"... | Updates the QoS aggregated configuration for the logical interconnect.
Args:
qos_configuration:
QOS configuration.
timeout:
Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation in
OneView, just ... | [
"Updates",
"the",
"QoS",
"aggregated",
"configuration",
"for",
"the",
"logical",
"interconnect",
"."
] | python | train | 41.6875 |
decryptus/sonicprobe | sonicprobe/libs/anysql.py | https://github.com/decryptus/sonicprobe/blob/72f73f3a40d2982d79ad68686e36aa31d94b76f8/sonicprobe/libs/anysql.py#L403-L419 | def commit(self):
"""
As in DBAPI2.0:
Commit any pending transaction to the database. Note that
if the database supports an auto-commit feature, this must
be initially off. An interface method may be provided to
turn it back on.
Database modules that do not suppo... | [
"def",
"commit",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"__dbapi2_conn",
".",
"commit",
"(",
")",
"except",
"Exception",
",",
"e",
":",
"# try to reconnect",
"self",
".",
"reconnect",
"(",
"None",
")",
"self",
".",
"__dbapi2_conn",
".",
"commit"... | As in DBAPI2.0:
Commit any pending transaction to the database. Note that
if the database supports an auto-commit feature, this must
be initially off. An interface method may be provided to
turn it back on.
Database modules that do not support transactions should
impleme... | [
"As",
"in",
"DBAPI2",
".",
"0",
":",
"Commit",
"any",
"pending",
"transaction",
"to",
"the",
"database",
".",
"Note",
"that",
"if",
"the",
"database",
"supports",
"an",
"auto",
"-",
"commit",
"feature",
"this",
"must",
"be",
"initially",
"off",
".",
"An"... | python | train | 34.058824 |
coldfix/doc2md | setup.py | https://github.com/coldfix/doc2md/blob/afd2876316a715d3401adb442d46c9a07cd7e806/setup.py#L5-L17 | def long_description():
"""Generate .rst document for PyPi."""
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--doc', dest="doc",
action="store_true", default=False)
args, sys.argv = parser.parse_known_args(sys.argv)
if args.doc:
import doc2md, pypand... | [
"def",
"long_description",
"(",
")",
":",
"import",
"argparse",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
")",
"parser",
".",
"add_argument",
"(",
"'--doc'",
",",
"dest",
"=",
"\"doc\"",
",",
"action",
"=",
"\"store_true\"",
",",
"default",
"=",... | Generate .rst document for PyPi. | [
"Generate",
".",
"rst",
"document",
"for",
"PyPi",
"."
] | python | valid | 36.307692 |
lemieuxl/pyGenClean | pyGenClean/run_data_clean_up.py | https://github.com/lemieuxl/pyGenClean/blob/6173a48ccc0cf3a3bd711b1f2a1fa16248b8bf55/pyGenClean/run_data_clean_up.py#L2387-L2483 | def run_flag_maf_zero(in_prefix, in_type, out_prefix, base_dir, options):
"""Runs step11 (flag MAF zero).
:param in_prefix: the prefix of the input files.
:param in_type: the type of the input files.
:param out_prefix: the output prefix.
:param base_dir: the output directory.
:param options: th... | [
"def",
"run_flag_maf_zero",
"(",
"in_prefix",
",",
"in_type",
",",
"out_prefix",
",",
"base_dir",
",",
"options",
")",
":",
"# Creating the output directory",
"os",
".",
"mkdir",
"(",
"out_prefix",
")",
"# We know we need bfile",
"required_type",
"=",
"\"bfile\"",
"... | Runs step11 (flag MAF zero).
:param in_prefix: the prefix of the input files.
:param in_type: the type of the input files.
:param out_prefix: the output prefix.
:param base_dir: the output directory.
:param options: the options needed.
:type in_prefix: str
:type in_type: str
:type out_... | [
"Runs",
"step11",
"(",
"flag",
"MAF",
"zero",
")",
"."
] | python | train | 36.206186 |
hannes-brt/hebel | hebel/utils/string_utils.py | https://github.com/hannes-brt/hebel/blob/1e2c3a9309c2646103901b26a55be4e312dd5005/hebel/utils/string_utils.py#L26-L77 | def preprocess(string):
"""
Preprocesses a string, by replacing ${VARNAME} with
os.environ['VARNAME']
Parameters
----------
string: the str object to preprocess
Returns
-------
the preprocessed string
"""
split = string.split('${')
rval = [split[0]]
for candidate... | [
"def",
"preprocess",
"(",
"string",
")",
":",
"split",
"=",
"string",
".",
"split",
"(",
"'${'",
")",
"rval",
"=",
"[",
"split",
"[",
"0",
"]",
"]",
"for",
"candidate",
"in",
"split",
"[",
"1",
":",
"]",
":",
"subsplit",
"=",
"candidate",
".",
"s... | Preprocesses a string, by replacing ${VARNAME} with
os.environ['VARNAME']
Parameters
----------
string: the str object to preprocess
Returns
-------
the preprocessed string | [
"Preprocesses",
"a",
"string",
"by",
"replacing",
"$",
"{",
"VARNAME",
"}",
"with",
"os",
".",
"environ",
"[",
"VARNAME",
"]"
] | python | train | 26.923077 |
koalalorenzo/python-digitalocean | digitalocean/FloatingIP.py | https://github.com/koalalorenzo/python-digitalocean/blob/d0221b57856fb1e131cafecf99d826f7b07a947c/digitalocean/FloatingIP.py#L88-L99 | def assign(self, droplet_id):
"""
Assign a FloatingIP to a Droplet.
Args:
droplet_id: int - droplet id
"""
return self.get_data(
"floating_ips/%s/actions/" % self.ip,
type=POST,
params={"type": "assign", "droplet_id": d... | [
"def",
"assign",
"(",
"self",
",",
"droplet_id",
")",
":",
"return",
"self",
".",
"get_data",
"(",
"\"floating_ips/%s/actions/\"",
"%",
"self",
".",
"ip",
",",
"type",
"=",
"POST",
",",
"params",
"=",
"{",
"\"type\"",
":",
"\"assign\"",
",",
"\"droplet_id\... | Assign a FloatingIP to a Droplet.
Args:
droplet_id: int - droplet id | [
"Assign",
"a",
"FloatingIP",
"to",
"a",
"Droplet",
"."
] | python | valid | 27.416667 |
taborlab/FlowCal | FlowCal/excel_ui.py | https://github.com/taborlab/FlowCal/blob/031a7af82acb1d46879a8e384a1a00f27f0bdc7a/FlowCal/excel_ui.py#L1396-L1437 | def generate_about_table(extra_info={}):
"""
Make a table with information about FlowCal and the current analysis.
Parameters
----------
extra_info : dict, optional
Additional keyword:value pairs to include in the table.
Returns
-------
about_table : DataFrame
Table wit... | [
"def",
"generate_about_table",
"(",
"extra_info",
"=",
"{",
"}",
")",
":",
"# Make keyword and value arrays",
"keywords",
"=",
"[",
"]",
"values",
"=",
"[",
"]",
"# FlowCal version",
"keywords",
".",
"append",
"(",
"'FlowCal version'",
")",
"values",
".",
"appen... | Make a table with information about FlowCal and the current analysis.
Parameters
----------
extra_info : dict, optional
Additional keyword:value pairs to include in the table.
Returns
-------
about_table : DataFrame
Table with information about FlowCal and the current analysis,... | [
"Make",
"a",
"table",
"with",
"information",
"about",
"FlowCal",
"and",
"the",
"current",
"analysis",
"."
] | python | train | 29.714286 |
kislyuk/aegea | aegea/packages/github3/issues/issue.py | https://github.com/kislyuk/aegea/blob/94957e9dba036eae3052e2662c208b259c08399a/aegea/packages/github3/issues/issue.py#L248-L258 | def remove_label(self, name):
"""Removes label ``name`` from this issue.
:param str name: (required), name of the label to remove
:returns: bool
"""
url = self._build_url('labels', name, base_url=self._api)
# Docs say it should be a list of strings returned, practice say... | [
"def",
"remove_label",
"(",
"self",
",",
"name",
")",
":",
"url",
"=",
"self",
".",
"_build_url",
"(",
"'labels'",
",",
"name",
",",
"base_url",
"=",
"self",
".",
"_api",
")",
"# Docs say it should be a list of strings returned, practice says it",
"# is just a 204/4... | Removes label ``name`` from this issue.
:param str name: (required), name of the label to remove
:returns: bool | [
"Removes",
"label",
"name",
"from",
"this",
"issue",
"."
] | python | train | 43.727273 |
benoitkugler/abstractDataLibrary | pyDLib/GUI/list_views.py | https://github.com/benoitkugler/abstractDataLibrary/blob/16be28e99837e40287a63803bbfdf67ac1806b7b/pyDLib/GUI/list_views.py#L361-L367 | def _draw_placeholder(self):
"""To be used in QTreeView"""
if self.model().rowCount() == 0:
painter = QPainter(self.viewport())
painter.setFont(_custom_font(is_italic=True))
painter.drawText(self.rect().adjusted(0, 0, -5, -5), Qt.AlignCenter | Qt.TextWordWrap,
... | [
"def",
"_draw_placeholder",
"(",
"self",
")",
":",
"if",
"self",
".",
"model",
"(",
")",
".",
"rowCount",
"(",
")",
"==",
"0",
":",
"painter",
"=",
"QPainter",
"(",
"self",
".",
"viewport",
"(",
")",
")",
"painter",
".",
"setFont",
"(",
"_custom_font... | To be used in QTreeView | [
"To",
"be",
"used",
"in",
"QTreeView"
] | python | train | 50.428571 |
ael-code/pyFsdb | fsdb/fsdb.py | https://github.com/ael-code/pyFsdb/blob/de33a0d41373307cb32cdd7ba1991b85ff495ee3/fsdb/fsdb.py#L215-L224 | def get_file_path(self, digest):
"""Retrieve the absolute path to the file with the given digest
Args:
digest -- digest of the file
Returns:
String rapresenting the absolute path of the file
"""
relPath = Fsdb.generate_tree_path(digest, self._conf['de... | [
"def",
"get_file_path",
"(",
"self",
",",
"digest",
")",
":",
"relPath",
"=",
"Fsdb",
".",
"generate_tree_path",
"(",
"digest",
",",
"self",
".",
"_conf",
"[",
"'depth'",
"]",
")",
"return",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"fsdbRoot",... | Retrieve the absolute path to the file with the given digest
Args:
digest -- digest of the file
Returns:
String rapresenting the absolute path of the file | [
"Retrieve",
"the",
"absolute",
"path",
"to",
"the",
"file",
"with",
"the",
"given",
"digest"
] | python | train | 36.9 |
lingthio/Flask-User | flask_user/db_adapters/sql_db_adapter.py | https://github.com/lingthio/Flask-User/blob/a379fa0a281789618c484b459cb41236779b95b1/flask_user/db_adapters/sql_db_adapter.py#L91-L116 | def ifind_first_object(self, ObjectClass, **kwargs):
""" Retrieve the first object of type ``ObjectClass``,
matching the specified filters in ``**kwargs`` -- case insensitive.
| If USER_IFIND_MODE is 'nocase_collation' this method maps to find_first_object().
| If USER_IFIND_MODE is 'if... | [
"def",
"ifind_first_object",
"(",
"self",
",",
"ObjectClass",
",",
"*",
"*",
"kwargs",
")",
":",
"# Call regular find() if USER_IFIND_MODE is nocase_collation",
"if",
"self",
".",
"user_manager",
".",
"USER_IFIND_MODE",
"==",
"'nocase_collation'",
":",
"return",
"self",... | Retrieve the first object of type ``ObjectClass``,
matching the specified filters in ``**kwargs`` -- case insensitive.
| If USER_IFIND_MODE is 'nocase_collation' this method maps to find_first_object().
| If USER_IFIND_MODE is 'ifind' this method performs a case insensitive find. | [
"Retrieve",
"the",
"first",
"object",
"of",
"type",
"ObjectClass",
"matching",
"the",
"specified",
"filters",
"in",
"**",
"kwargs",
"--",
"case",
"insensitive",
"."
] | python | train | 45.961538 |
jrief/django-angular | djng/forms/angular_base.py | https://github.com/jrief/django-angular/blob/9f2f8247027173e3b3ad3b245ca299a9c9f31b40/djng/forms/angular_base.py#L168-L175 | def errors(self):
"""
Returns a TupleErrorList for this field. This overloaded method adds additional error lists
to the errors as detected by the form validator.
"""
if not hasattr(self, '_errors_cache'):
self._errors_cache = self.form.get_field_errors(self)
... | [
"def",
"errors",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'_errors_cache'",
")",
":",
"self",
".",
"_errors_cache",
"=",
"self",
".",
"form",
".",
"get_field_errors",
"(",
"self",
")",
"return",
"self",
".",
"_errors_cache"
] | Returns a TupleErrorList for this field. This overloaded method adds additional error lists
to the errors as detected by the form validator. | [
"Returns",
"a",
"TupleErrorList",
"for",
"this",
"field",
".",
"This",
"overloaded",
"method",
"adds",
"additional",
"error",
"lists",
"to",
"the",
"errors",
"as",
"detected",
"by",
"the",
"form",
"validator",
"."
] | python | train | 42.25 |
XuShaohua/bcloud | bcloud/BTBrowserDialog.py | https://github.com/XuShaohua/bcloud/blob/4b54e0fdccf2b3013285fef05c97354cfa31697b/bcloud/BTBrowserDialog.py#L74-L115 | def request_data(self):
'''在调用dialog.run()之前先调用这个函数来获取数据'''
def on_tasks_received(info, error=None):
if error or not info:
logger.error('BTBrowserDialog.on_tasks_received: %s, %s.' %
(info, error))
return
if 'magnet_inf... | [
"def",
"request_data",
"(",
"self",
")",
":",
"def",
"on_tasks_received",
"(",
"info",
",",
"error",
"=",
"None",
")",
":",
"if",
"error",
"or",
"not",
"info",
":",
"logger",
".",
"error",
"(",
"'BTBrowserDialog.on_tasks_received: %s, %s.'",
"%",
"(",
"info"... | 在调用dialog.run()之前先调用这个函数来获取数据 | [
"在调用dialog",
".",
"run",
"()",
"之前先调用这个函数来获取数据"
] | python | train | 44.357143 |
datasift/datasift-python | datasift/client.py | https://github.com/datasift/datasift-python/blob/bfaca1a47501a18e11065ecf630d9c31df818f65/datasift/client.py#L304-L317 | def compile(self, csdl):
""" Compile the given CSDL.
Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/compile
Raises a DataSiftApiException for any error given by the REST API, including CSDL compilation.
:param csdl: CSDL to compile
:... | [
"def",
"compile",
"(",
"self",
",",
"csdl",
")",
":",
"return",
"self",
".",
"request",
".",
"post",
"(",
"'compile'",
",",
"data",
"=",
"dict",
"(",
"csdl",
"=",
"csdl",
")",
")"
] | Compile the given CSDL.
Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/compile
Raises a DataSiftApiException for any error given by the REST API, including CSDL compilation.
:param csdl: CSDL to compile
:type csdl: str
:returns: ... | [
"Compile",
"the",
"given",
"CSDL",
"."
] | python | train | 44.5 |
spotify/luigi | luigi/contrib/mongodb.py | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/mongodb.py#L139-L155 | def write(self, values):
"""
Write values to the targeted documents
Values need to be a dict as : {document_id: value}
"""
# Insert only for docs targeted by the target
filtered = {_id: value for _id, value in values.items() if _id in self._document_ids}
if not f... | [
"def",
"write",
"(",
"self",
",",
"values",
")",
":",
"# Insert only for docs targeted by the target",
"filtered",
"=",
"{",
"_id",
":",
"value",
"for",
"_id",
",",
"value",
"in",
"values",
".",
"items",
"(",
")",
"if",
"_id",
"in",
"self",
".",
"_document... | Write values to the targeted documents
Values need to be a dict as : {document_id: value} | [
"Write",
"values",
"to",
"the",
"targeted",
"documents",
"Values",
"need",
"to",
"be",
"a",
"dict",
"as",
":",
"{",
"document_id",
":",
"value",
"}"
] | python | train | 33.941176 |
gwastro/pycbc | pycbc/workflow/core.py | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/workflow/core.py#L1430-L1436 | def find_output_without_tag(self, tag):
"""
Find all files who do not have tag in self.tags
"""
# Enforce upper case
tag = tag.upper()
return FileList([i for i in self if tag not in i.tags]) | [
"def",
"find_output_without_tag",
"(",
"self",
",",
"tag",
")",
":",
"# Enforce upper case",
"tag",
"=",
"tag",
".",
"upper",
"(",
")",
"return",
"FileList",
"(",
"[",
"i",
"for",
"i",
"in",
"self",
"if",
"tag",
"not",
"in",
"i",
".",
"tags",
"]",
")... | Find all files who do not have tag in self.tags | [
"Find",
"all",
"files",
"who",
"do",
"not",
"have",
"tag",
"in",
"self",
".",
"tags"
] | python | train | 33.142857 |
splunk/splunk-sdk-python | examples/analytics/bottle.py | https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/examples/analytics/bottle.py#L613-L615 | def delete(self, path=None, method='DELETE', **options):
""" Equals :meth:`route` with a ``DELETE`` method parameter. """
return self.route(path, method, **options) | [
"def",
"delete",
"(",
"self",
",",
"path",
"=",
"None",
",",
"method",
"=",
"'DELETE'",
",",
"*",
"*",
"options",
")",
":",
"return",
"self",
".",
"route",
"(",
"path",
",",
"method",
",",
"*",
"*",
"options",
")"
] | Equals :meth:`route` with a ``DELETE`` method parameter. | [
"Equals",
":",
"meth",
":",
"route",
"with",
"a",
"DELETE",
"method",
"parameter",
"."
] | python | train | 59.333333 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.