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 |
|---|---|---|---|---|---|---|---|---|---|
UCBerkeleySETI/blimpy | blimpy/file_wrapper.py | https://github.com/UCBerkeleySETI/blimpy/blob/b8822d3e3e911944370d84371a91fa0c29e9772e/blimpy/file_wrapper.py#L282-L291 | def isheavy(self):
""" Check if the current selection is too large.
"""
selection_size_bytes = self._calc_selection_size()
if selection_size_bytes > self.MAX_DATA_ARRAY_SIZE:
return True
else:
return False | [
"def",
"isheavy",
"(",
"self",
")",
":",
"selection_size_bytes",
"=",
"self",
".",
"_calc_selection_size",
"(",
")",
"if",
"selection_size_bytes",
">",
"self",
".",
"MAX_DATA_ARRAY_SIZE",
":",
"return",
"True",
"else",
":",
"return",
"False"
] | Check if the current selection is too large. | [
"Check",
"if",
"the",
"current",
"selection",
"is",
"too",
"large",
"."
] | python | test | 26.2 |
carlosp420/primer-designer | primer_designer/utils.py | https://github.com/carlosp420/primer-designer/blob/586cb7fecf41fedbffe6563c8b79a3156c6066ae/primer_designer/utils.py#L4-L15 | def is_fasta(filename):
"""Check if filename is FASTA based on extension
Return:
Boolean
"""
if re.search("\.fa*s[ta]*$", filename, flags=re.I):
return True
elif re.search("\.fa$", filename, flags=re.I):
return True
else:
return False | [
"def",
"is_fasta",
"(",
"filename",
")",
":",
"if",
"re",
".",
"search",
"(",
"\"\\.fa*s[ta]*$\"",
",",
"filename",
",",
"flags",
"=",
"re",
".",
"I",
")",
":",
"return",
"True",
"elif",
"re",
".",
"search",
"(",
"\"\\.fa$\"",
",",
"filename",
",",
"... | Check if filename is FASTA based on extension
Return:
Boolean | [
"Check",
"if",
"filename",
"is",
"FASTA",
"based",
"on",
"extension"
] | python | train | 23.25 |
SBRG/ssbio | ssbio/core/protein.py | https://github.com/SBRG/ssbio/blob/e9449e64ffc1a1f5ad07e5849aa12a650095f8a2/ssbio/core/protein.py#L1917-L2175 | def set_representative_structure(self, seq_outdir=None, struct_outdir=None, pdb_file_type=None,
engine='needle', always_use_homology=False, rez_cutoff=0.0,
seq_ident_cutoff=0.5, allow_missing_on_termini=0.2,
a... | [
"def",
"set_representative_structure",
"(",
"self",
",",
"seq_outdir",
"=",
"None",
",",
"struct_outdir",
"=",
"None",
",",
"pdb_file_type",
"=",
"None",
",",
"engine",
"=",
"'needle'",
",",
"always_use_homology",
"=",
"False",
",",
"rez_cutoff",
"=",
"0.0",
"... | Set a representative structure from a structure in the structures attribute.
Each gene can have a combination of the following, which will be analyzed to set a representative structure.
* Homology model(s)
* Ranked PDBs
* BLASTed PDBs
If the ``always_use_homology`` ... | [
"Set",
"a",
"representative",
"structure",
"from",
"a",
"structure",
"in",
"the",
"structures",
"attribute",
"."
] | python | train | 60.903475 |
standage/tag | tag/select.py | https://github.com/standage/tag/blob/94686adf57115cea1c5235e99299e691f80ba10b/tag/select.py#L13-L37 | def features(entrystream, type=None, traverse=False):
"""
Pull features out of the specified entry stream.
:param entrystream: a stream of entries
:param type: retrieve only features of the specified type; set to
:code:`None` to retrieve all features
:param traverse: by default, on... | [
"def",
"features",
"(",
"entrystream",
",",
"type",
"=",
"None",
",",
"traverse",
"=",
"False",
")",
":",
"for",
"feature",
"in",
"entry_type_filter",
"(",
"entrystream",
",",
"tag",
".",
"Feature",
")",
":",
"if",
"traverse",
":",
"if",
"type",
"is",
... | Pull features out of the specified entry stream.
:param entrystream: a stream of entries
:param type: retrieve only features of the specified type; set to
:code:`None` to retrieve all features
:param traverse: by default, only top-level features are selected; set
to :c... | [
"Pull",
"features",
"out",
"of",
"the",
"specified",
"entry",
"stream",
"."
] | python | train | 40.12 |
saltstack/salt | salt/_compat.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/_compat.py#L90-L103 | def native_(s, encoding='latin-1', errors='strict'):
'''
Python 3: If ``s`` is an instance of ``text_type``, return ``s``, otherwise
return ``str(s, encoding, errors)``
Python 2: If ``s`` is an instance of ``text_type``, return
``s.encode(encoding, errors)``, otherwise return ``str(s)``
'''
... | [
"def",
"native_",
"(",
"s",
",",
"encoding",
"=",
"'latin-1'",
",",
"errors",
"=",
"'strict'",
")",
":",
"if",
"PY3",
":",
"out",
"=",
"s",
"if",
"isinstance",
"(",
"s",
",",
"text_type",
")",
"else",
"str",
"(",
"s",
",",
"encoding",
",",
"errors"... | Python 3: If ``s`` is an instance of ``text_type``, return ``s``, otherwise
return ``str(s, encoding, errors)``
Python 2: If ``s`` is an instance of ``text_type``, return
``s.encode(encoding, errors)``, otherwise return ``str(s)`` | [
"Python",
"3",
":",
"If",
"s",
"is",
"an",
"instance",
"of",
"text_type",
"return",
"s",
"otherwise",
"return",
"str",
"(",
"s",
"encoding",
"errors",
")"
] | python | train | 35.428571 |
GNS3/gns3-server | gns3server/controller/gns3vm/virtualbox_gns3_vm.py | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/gns3vm/virtualbox_gns3_vm.py#L304-L312 | def set_ram(self, ram):
"""
Set the RAM amount for the GNS3 VM.
:param ram: amount of memory
"""
yield from self._execute("modifyvm", [self._vmname, "--memory", str(ram)], timeout=3)
log.info("GNS3 VM RAM amount set to {}".format(ram)) | [
"def",
"set_ram",
"(",
"self",
",",
"ram",
")",
":",
"yield",
"from",
"self",
".",
"_execute",
"(",
"\"modifyvm\"",
",",
"[",
"self",
".",
"_vmname",
",",
"\"--memory\"",
",",
"str",
"(",
"ram",
")",
"]",
",",
"timeout",
"=",
"3",
")",
"log",
".",
... | Set the RAM amount for the GNS3 VM.
:param ram: amount of memory | [
"Set",
"the",
"RAM",
"amount",
"for",
"the",
"GNS3",
"VM",
"."
] | python | train | 30.777778 |
drj11/pypng | code/iccp.py | https://github.com/drj11/pypng/blob/b8220ca9f58e4c5bc1d507e713744fcb8c049225/code/iccp.py#L147-L157 | def write(self, out):
"""Write ICC Profile to the file."""
if not self.rawtagtable:
self.rawtagtable = self.rawtagdict.items()
tags = tagblock(self.rawtagtable)
self.writeHeader(out, 128 + len(tags))
out.write(tags)
out.flush()
return self | [
"def",
"write",
"(",
"self",
",",
"out",
")",
":",
"if",
"not",
"self",
".",
"rawtagtable",
":",
"self",
".",
"rawtagtable",
"=",
"self",
".",
"rawtagdict",
".",
"items",
"(",
")",
"tags",
"=",
"tagblock",
"(",
"self",
".",
"rawtagtable",
")",
"self"... | Write ICC Profile to the file. | [
"Write",
"ICC",
"Profile",
"to",
"the",
"file",
"."
] | python | train | 27.181818 |
ChrisBeaumont/smother | smother/cli.py | https://github.com/ChrisBeaumont/smother/blob/65d1ea6ae0060d213b0dcbb983c5aa8e7fee07bb/smother/cli.py#L48-L53 | def lookup(ctx, path):
"""
Determine which tests intersect a source interval.
"""
regions = parse_intervals(path, as_context=ctx.obj['semantic'])
_report_from_regions(regions, ctx.obj) | [
"def",
"lookup",
"(",
"ctx",
",",
"path",
")",
":",
"regions",
"=",
"parse_intervals",
"(",
"path",
",",
"as_context",
"=",
"ctx",
".",
"obj",
"[",
"'semantic'",
"]",
")",
"_report_from_regions",
"(",
"regions",
",",
"ctx",
".",
"obj",
")"
] | Determine which tests intersect a source interval. | [
"Determine",
"which",
"tests",
"intersect",
"a",
"source",
"interval",
"."
] | python | train | 33.166667 |
pantsbuild/pants | src/python/pants/util/contextutil.py | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/util/contextutil.py#L194-L206 | def temporary_file_path(root_dir=None, cleanup=True, suffix='', permissions=None):
"""
A with-context that creates a temporary file and returns its path.
:API: public
You may specify the following keyword args:
:param str root_dir: The parent directory to create the temporary file.
:param bool c... | [
"def",
"temporary_file_path",
"(",
"root_dir",
"=",
"None",
",",
"cleanup",
"=",
"True",
",",
"suffix",
"=",
"''",
",",
"permissions",
"=",
"None",
")",
":",
"with",
"temporary_file",
"(",
"root_dir",
",",
"cleanup",
"=",
"cleanup",
",",
"suffix",
"=",
"... | A with-context that creates a temporary file and returns its path.
:API: public
You may specify the following keyword args:
:param str root_dir: The parent directory to create the temporary file.
:param bool cleanup: Whether or not to clean up the temporary file. | [
"A",
"with",
"-",
"context",
"that",
"creates",
"a",
"temporary",
"file",
"and",
"returns",
"its",
"path",
"."
] | python | train | 38.230769 |
quintusdias/glymur | glymur/codestream.py | https://github.com/quintusdias/glymur/blob/8b8fb091130fff00f1028dc82219e69e3f9baf6d/glymur/codestream.py#L367-L406 | def _parse_cod_segment(cls, fptr):
"""Parse the COD segment.
Parameters
----------
fptr : file
Open file object.
Returns
-------
CODSegment
The current COD segment.
"""
offset = fptr.tell() - 2
read_buffer = fptr.... | [
"def",
"_parse_cod_segment",
"(",
"cls",
",",
"fptr",
")",
":",
"offset",
"=",
"fptr",
".",
"tell",
"(",
")",
"-",
"2",
"read_buffer",
"=",
"fptr",
".",
"read",
"(",
"2",
")",
"length",
",",
"=",
"struct",
".",
"unpack",
"(",
"'>H'",
",",
"read_buf... | Parse the COD segment.
Parameters
----------
fptr : file
Open file object.
Returns
-------
CODSegment
The current COD segment. | [
"Parse",
"the",
"COD",
"segment",
"."
] | python | train | 25.55 |
ansible/tower-cli | tower_cli/cli/resource.py | https://github.com/ansible/tower-cli/blob/a2b151fed93c47725018d3034848cb3a1814bed7/tower_cli/cli/resource.py#L59-L95 | def _auto_help_text(self, help_text):
"""Given a method with a docstring, convert the docstring
to more CLI appropriate wording, and also disambiguate the
word "object" on the base class docstrings.
"""
# Delete API docs if there are any.
api_doc_delimiter = '=====API DOC... | [
"def",
"_auto_help_text",
"(",
"self",
",",
"help_text",
")",
":",
"# Delete API docs if there are any.",
"api_doc_delimiter",
"=",
"'=====API DOCS====='",
"begin_api_doc",
"=",
"help_text",
".",
"find",
"(",
"api_doc_delimiter",
")",
"if",
"begin_api_doc",
">=",
"0",
... | Given a method with a docstring, convert the docstring
to more CLI appropriate wording, and also disambiguate the
word "object" on the base class docstrings. | [
"Given",
"a",
"method",
"with",
"a",
"docstring",
"convert",
"the",
"docstring",
"to",
"more",
"CLI",
"appropriate",
"wording",
"and",
"also",
"disambiguate",
"the",
"word",
"object",
"on",
"the",
"base",
"class",
"docstrings",
"."
] | python | valid | 47.675676 |
hcpl/xkbgroup | xkbgroup/core.py | https://github.com/hcpl/xkbgroup/blob/fcf4709a3c8221e0cdf62c09e5cccda232b0104c/xkbgroup/core.py#L228-L239 | def groups_data(self):
"""All data about all groups (get-only).
:getter: Returns all data about all groups
:type: list of GroupData
"""
return _ListProxy(GroupData(num, name, symbol, variant)
for (num, name, symbol, variant)
in... | [
"def",
"groups_data",
"(",
"self",
")",
":",
"return",
"_ListProxy",
"(",
"GroupData",
"(",
"num",
",",
"name",
",",
"symbol",
",",
"variant",
")",
"for",
"(",
"num",
",",
"name",
",",
"symbol",
",",
"variant",
")",
"in",
"zip",
"(",
"range",
"(",
... | All data about all groups (get-only).
:getter: Returns all data about all groups
:type: list of GroupData | [
"All",
"data",
"about",
"all",
"groups",
"(",
"get",
"-",
"only",
")",
"."
] | python | train | 41.75 |
PMEAL/OpenPNM | openpnm/algorithms/GenericTransport.py | https://github.com/PMEAL/OpenPNM/blob/0547b5724ffedc0a593aae48639d36fe10e0baed/openpnm/algorithms/GenericTransport.py#L244-L298 | def _set_BC(self, pores, bctype, bcvalues=None, mode='merge'):
r"""
Apply boundary conditions to specified pores
Parameters
----------
pores : array_like
The pores where the boundary conditions should be applied
bctype : string
Specifies the type... | [
"def",
"_set_BC",
"(",
"self",
",",
"pores",
",",
"bctype",
",",
"bcvalues",
"=",
"None",
",",
"mode",
"=",
"'merge'",
")",
":",
"# Hijack the parse_mode function to verify bctype argument",
"bctype",
"=",
"self",
".",
"_parse_mode",
"(",
"bctype",
",",
"allowed... | r"""
Apply boundary conditions to specified pores
Parameters
----------
pores : array_like
The pores where the boundary conditions should be applied
bctype : string
Specifies the type or the name of boundary condition to apply. The
types can ... | [
"r",
"Apply",
"boundary",
"conditions",
"to",
"specified",
"pores"
] | python | train | 40.818182 |
inasafe/inasafe | safe/messaging/item/abstract_list.py | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/messaging/item/abstract_list.py#L50-L71 | def add(self, item):
"""add a Text MessageElement to the existing Text
Strings can be passed and are automatically converted in to
item.Text()
:param item: Text text, an element to add to the text
"""
if self._is_stringable(item) or self._is_qstring(item):
... | [
"def",
"add",
"(",
"self",
",",
"item",
")",
":",
"if",
"self",
".",
"_is_stringable",
"(",
"item",
")",
"or",
"self",
".",
"_is_qstring",
"(",
"item",
")",
":",
"self",
".",
"items",
".",
"append",
"(",
"PlainText",
"(",
"item",
")",
")",
"elif",
... | add a Text MessageElement to the existing Text
Strings can be passed and are automatically converted in to
item.Text()
:param item: Text text, an element to add to the text | [
"add",
"a",
"Text",
"MessageElement",
"to",
"the",
"existing",
"Text"
] | python | train | 37.181818 |
brocade/pynos | pynos/versions/ver_6/ver_6_0_1/yang/brocade_mac_address_table.py | https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_6/ver_6_0_1/yang/brocade_mac_address_table.py#L265-L279 | def get_mac_address_table_input_request_type_get_next_request_last_mac_address_details_last_mac_address(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_mac_address_table = ET.Element("get_mac_address_table")
config = get_mac_address_table
inp... | [
"def",
"get_mac_address_table_input_request_type_get_next_request_last_mac_address_details_last_mac_address",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"get_mac_address_table",
"=",
"ET",
".",
"Element",
... | Auto Generated Code | [
"Auto",
"Generated",
"Code"
] | python | train | 55.133333 |
pantsbuild/pants | src/python/pants/scm/git.py | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/scm/git.py#L207-L209 | def merge_base(self, left='master', right='HEAD'):
"""Returns the merge-base of master and HEAD in bash: `git merge-base left right`"""
return self._check_output(['merge-base', left, right], raise_type=Scm.LocalException) | [
"def",
"merge_base",
"(",
"self",
",",
"left",
"=",
"'master'",
",",
"right",
"=",
"'HEAD'",
")",
":",
"return",
"self",
".",
"_check_output",
"(",
"[",
"'merge-base'",
",",
"left",
",",
"right",
"]",
",",
"raise_type",
"=",
"Scm",
".",
"LocalException",... | Returns the merge-base of master and HEAD in bash: `git merge-base left right` | [
"Returns",
"the",
"merge",
"-",
"base",
"of",
"master",
"and",
"HEAD",
"in",
"bash",
":",
"git",
"merge",
"-",
"base",
"left",
"right"
] | python | train | 75.666667 |
uw-it-aca/uw-restclients | restclients/grad/committee.py | https://github.com/uw-it-aca/uw-restclients/blob/e12dcd32bf5296b6ebdf71798031594afb7852cb/restclients/grad/committee.py#L31-L68 | def _process_json(data):
"""
return a list of GradCommittee objects.
"""
requests = []
for item in data:
committee = GradCommittee()
committee.status = item.get('status')
committee.committee_type = item.get('committeeType')
committee.dept = item.get('dept')
co... | [
"def",
"_process_json",
"(",
"data",
")",
":",
"requests",
"=",
"[",
"]",
"for",
"item",
"in",
"data",
":",
"committee",
"=",
"GradCommittee",
"(",
")",
"committee",
".",
"status",
"=",
"item",
".",
"get",
"(",
"'status'",
")",
"committee",
".",
"commi... | return a list of GradCommittee objects. | [
"return",
"a",
"list",
"of",
"GradCommittee",
"objects",
"."
] | python | train | 39.131579 |
DataDog/integrations-core | sqlserver/datadog_checks/sqlserver/sqlserver.py | https://github.com/DataDog/integrations-core/blob/ebd41c873cf9f97a8c51bf9459bc6a7536af8acd/sqlserver/datadog_checks/sqlserver/sqlserver.py#L365-L389 | def _conn_string_odbc(self, db_key, instance=None, conn_key=None, db_name=None):
''' Return a connection string to use with odbc
'''
if instance:
dsn, host, username, password, database, driver = self._get_access_info(instance, db_key, db_name)
elif conn_key:
dsn,... | [
"def",
"_conn_string_odbc",
"(",
"self",
",",
"db_key",
",",
"instance",
"=",
"None",
",",
"conn_key",
"=",
"None",
",",
"db_name",
"=",
"None",
")",
":",
"if",
"instance",
":",
"dsn",
",",
"host",
",",
"username",
",",
"password",
",",
"database",
","... | Return a connection string to use with odbc | [
"Return",
"a",
"connection",
"string",
"to",
"use",
"with",
"odbc"
] | python | train | 36.48 |
jpweiser/cuts | cuts/main.py | https://github.com/jpweiser/cuts/blob/5baf7f2e145045942ee8dcaccbc47f8f821fcb56/cuts/main.py#L34-L60 | def _parse_args(args):
"""Setup argparser to process arguments and generate help"""
# parser uses custom usage string, with 'usage: ' removed, as it is
# added automatically via argparser.
parser = argparse.ArgumentParser(description="Remove and/or rearrange "
+ "se... | [
"def",
"_parse_args",
"(",
"args",
")",
":",
"# parser uses custom usage string, with 'usage: ' removed, as it is",
"# added automatically via argparser.",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"\"Remove and/or rearrange \"",
"+",
"\"sections ... | Setup argparser to process arguments and generate help | [
"Setup",
"argparser",
"to",
"process",
"arguments",
"and",
"generate",
"help"
] | python | valid | 56.703704 |
juju/charm-helpers | charmhelpers/contrib/openstack/cert_utils.py | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/cert_utils.py#L244-L263 | def get_requests_for_local_unit(relation_name=None):
"""Extract any certificates data targeted at this unit down relation_name.
:param relation_name: str Name of relation to check for data.
:returns: List of bundles of certificates.
:rtype: List of dicts
"""
local_name = local_unit().replace('/... | [
"def",
"get_requests_for_local_unit",
"(",
"relation_name",
"=",
"None",
")",
":",
"local_name",
"=",
"local_unit",
"(",
")",
".",
"replace",
"(",
"'/'",
",",
"'_'",
")",
"raw_certs_key",
"=",
"'{}.processed_requests'",
".",
"format",
"(",
"local_name",
")",
"... | Extract any certificates data targeted at this unit down relation_name.
:param relation_name: str Name of relation to check for data.
:returns: List of bundles of certificates.
:rtype: List of dicts | [
"Extract",
"any",
"certificates",
"data",
"targeted",
"at",
"this",
"unit",
"down",
"relation_name",
"."
] | python | train | 40.85 |
proteanhq/protean | src/protean/services/email/utils.py | https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/services/email/utils.py#L8-L15 | def get_connection(backend=None, fail_silently=False, **kwargs):
"""Load an email backend and return an instance of it.
If backend is None (default), use settings.EMAIL_BACKEND.
Both fail_silently and other keyword arguments are used in the
constructor of the backend.
"""
klass = perform_import(... | [
"def",
"get_connection",
"(",
"backend",
"=",
"None",
",",
"fail_silently",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"klass",
"=",
"perform_import",
"(",
"backend",
"or",
"active_config",
".",
"EMAIL_BACKEND",
")",
"return",
"klass",
"(",
"fail_silen... | Load an email backend and return an instance of it.
If backend is None (default), use settings.EMAIL_BACKEND.
Both fail_silently and other keyword arguments are used in the
constructor of the backend. | [
"Load",
"an",
"email",
"backend",
"and",
"return",
"an",
"instance",
"of",
"it",
".",
"If",
"backend",
"is",
"None",
"(",
"default",
")",
"use",
"settings",
".",
"EMAIL_BACKEND",
".",
"Both",
"fail_silently",
"and",
"other",
"keyword",
"arguments",
"are",
... | python | train | 51 |
Morrolan/surrealism | surrealism.py | https://github.com/Morrolan/surrealism/blob/7fdd2eae534410df16ee1f9d7e9bb77aa10decab/surrealism.py#L814-L841 | def __check_spaces(sentence):
"""
Here we check to see that we have the correct number of spaces in the correct locations.
:param _sentence:
:return:
"""
# We have to run the process multiple times:
# Once to search for all spaces, and check if there are adjoining spaces;
# The seco... | [
"def",
"__check_spaces",
"(",
"sentence",
")",
":",
"# We have to run the process multiple times:",
"# Once to search for all spaces, and check if there are adjoining spaces;",
"# The second time to check for 2 spaces after sentence-ending characters such as . and ! and ?",
"if",
"sentence",... | Here we check to see that we have the correct number of spaces in the correct locations.
:param _sentence:
:return: | [
"Here",
"we",
"check",
"to",
"see",
"that",
"we",
"have",
"the",
"correct",
"number",
"of",
"spaces",
"in",
"the",
"correct",
"locations",
"."
] | python | train | 27.535714 |
numenta/htmresearch | htmresearch/support/union_temporal_pooler_monitor_mixin.py | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/support/union_temporal_pooler_monitor_mixin.py#L291-L308 | def mmGetPlotStability(self, title="Stability", showReset=False,
resetShading=0.25):
"""
Returns plot of the overlap metric between union SDRs within a sequence.
@param title an optional title for the figure
@return (Plot) plot
"""
plot = Plot(self, title)
self._mmCo... | [
"def",
"mmGetPlotStability",
"(",
"self",
",",
"title",
"=",
"\"Stability\"",
",",
"showReset",
"=",
"False",
",",
"resetShading",
"=",
"0.25",
")",
":",
"plot",
"=",
"Plot",
"(",
"self",
",",
"title",
")",
"self",
".",
"_mmComputeSequenceRepresentationData",
... | Returns plot of the overlap metric between union SDRs within a sequence.
@param title an optional title for the figure
@return (Plot) plot | [
"Returns",
"plot",
"of",
"the",
"overlap",
"metric",
"between",
"union",
"SDRs",
"within",
"a",
"sequence",
"."
] | python | train | 38.444444 |
YeoLab/anchor | anchor/infotheory.py | https://github.com/YeoLab/anchor/blob/1f9c9d6d30235b1e77b945e6ef01db5a0e55d53a/anchor/infotheory.py#L190-L215 | def binify_and_jsd(df1, df2, bins, pair=None):
"""Binify and calculate jensen-shannon divergence between two dataframes
Parameters
----------
df1, df2 : pandas.DataFrames
Dataframes to calculate JSD between columns of. Must have overlapping
column names
bins : array-like
Bin... | [
"def",
"binify_and_jsd",
"(",
"df1",
",",
"df2",
",",
"bins",
",",
"pair",
"=",
"None",
")",
":",
"binned1",
"=",
"binify",
"(",
"df1",
",",
"bins",
"=",
"bins",
")",
".",
"dropna",
"(",
"how",
"=",
"'all'",
",",
"axis",
"=",
"1",
")",
"binned2",... | Binify and calculate jensen-shannon divergence between two dataframes
Parameters
----------
df1, df2 : pandas.DataFrames
Dataframes to calculate JSD between columns of. Must have overlapping
column names
bins : array-like
Bins to use for transforming df{1,2} into probability dis... | [
"Binify",
"and",
"calculate",
"jensen",
"-",
"shannon",
"divergence",
"between",
"two",
"dataframes"
] | python | train | 32.846154 |
brocade/pynos | pynos/versions/ver_6/ver_6_0_1/yang/brocade_aaa.py | https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_6/ver_6_0_1/yang/brocade_aaa.py#L631-L642 | def rule_action(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
rule = ET.SubElement(config, "rule", xmlns="urn:brocade.com:mgmt:brocade-aaa")
index_key = ET.SubElement(rule, "index")
index_key.text = kwargs.pop('index')
action = ET.SubEl... | [
"def",
"rule_action",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"rule",
"=",
"ET",
".",
"SubElement",
"(",
"config",
",",
"\"rule\"",
",",
"xmlns",
"=",
"\"urn:brocade.com:mgmt:brocade-aaa\... | Auto Generated Code | [
"Auto",
"Generated",
"Code"
] | python | train | 38.666667 |
zhanglab/psamm | psamm/balancecheck.py | https://github.com/zhanglab/psamm/blob/dc427848c4f9d109ca590f0afa024c63b685b3f4/psamm/balancecheck.py#L91-L117 | def formula_balance(model):
"""Calculate formula compositions for each reaction.
Call :func:`reaction_formula` for each reaction.
Yield (reaction, result) pairs, where result has two formula compositions
or `None`.
Args:
model: :class:`psamm.datasource.native.NativeModel`.
"""
# M... | [
"def",
"formula_balance",
"(",
"model",
")",
":",
"# Mapping from compound id to formula",
"compound_formula",
"=",
"{",
"}",
"for",
"compound",
"in",
"model",
".",
"compounds",
":",
"if",
"compound",
".",
"formula",
"is",
"not",
"None",
":",
"try",
":",
"f",
... | Calculate formula compositions for each reaction.
Call :func:`reaction_formula` for each reaction.
Yield (reaction, result) pairs, where result has two formula compositions
or `None`.
Args:
model: :class:`psamm.datasource.native.NativeModel`. | [
"Calculate",
"formula",
"compositions",
"for",
"each",
"reaction",
"."
] | python | train | 36.37037 |
jf-parent/brome | brome/runner/local_runner.py | https://github.com/jf-parent/brome/blob/784f45d96b83b703dd2181cb59ca8ea777c2510e/brome/runner/local_runner.py#L43-L78 | def run(self):
"""Run the test batch
"""
self.info_log("The test batch is ready.")
self.executed_tests = []
for test in self.tests:
localhost_instance = LocalhostInstance(
runner=self,
browser_config=self.browser_config,
... | [
"def",
"run",
"(",
"self",
")",
":",
"self",
".",
"info_log",
"(",
"\"The test batch is ready.\"",
")",
"self",
".",
"executed_tests",
"=",
"[",
"]",
"for",
"test",
"in",
"self",
".",
"tests",
":",
"localhost_instance",
"=",
"LocalhostInstance",
"(",
"runner... | Run the test batch | [
"Run",
"the",
"test",
"batch"
] | python | train | 31.138889 |
danilobellini/audiolazy | examples/play_bach_choral.py | https://github.com/danilobellini/audiolazy/blob/dba0a278937909980ed40b976d866b8e97c35dee/examples/play_bach_choral.py#L33-L40 | def ks_synth(freq):
"""
Synthesize the given frequency into a Stream by using a model based on
Karplus-Strong.
"""
ks_mem = (sum(lz.sinusoid(x * freq) for x in [1, 3, 9]) +
lz.white_noise() + lz.Stream(-1, 1)) / 5
return lz.karplus_strong(freq, memory=ks_mem) | [
"def",
"ks_synth",
"(",
"freq",
")",
":",
"ks_mem",
"=",
"(",
"sum",
"(",
"lz",
".",
"sinusoid",
"(",
"x",
"*",
"freq",
")",
"for",
"x",
"in",
"[",
"1",
",",
"3",
",",
"9",
"]",
")",
"+",
"lz",
".",
"white_noise",
"(",
")",
"+",
"lz",
".",
... | Synthesize the given frequency into a Stream by using a model based on
Karplus-Strong. | [
"Synthesize",
"the",
"given",
"frequency",
"into",
"a",
"Stream",
"by",
"using",
"a",
"model",
"based",
"on",
"Karplus",
"-",
"Strong",
"."
] | python | train | 34.5 |
gem/oq-engine | openquake/hazardlib/gsim/abrahamson_2014.py | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/abrahamson_2014.py#L231-L283 | def _get_hanging_wall_term(self, C, dists, rup):
"""
Compute and return hanging wall model term, see page 1038.
"""
if rup.dip == 90.0:
return np.zeros_like(dists.rx)
else:
Fhw = np.zeros_like(dists.rx)
Fhw[dists.rx > 0] = 1.
# Comp... | [
"def",
"_get_hanging_wall_term",
"(",
"self",
",",
"C",
",",
"dists",
",",
"rup",
")",
":",
"if",
"rup",
".",
"dip",
"==",
"90.0",
":",
"return",
"np",
".",
"zeros_like",
"(",
"dists",
".",
"rx",
")",
"else",
":",
"Fhw",
"=",
"np",
".",
"zeros_like... | Compute and return hanging wall model term, see page 1038. | [
"Compute",
"and",
"return",
"hanging",
"wall",
"model",
"term",
"see",
"page",
"1038",
"."
] | python | train | 41.018868 |
arne-cl/discoursegraphs | src/discoursegraphs/readwrite/conll.py | https://github.com/arne-cl/discoursegraphs/blob/842f0068a3190be2c75905754521b176b25a54fb/src/discoursegraphs/readwrite/conll.py#L201-L224 | def __add_sentence_root_node(self, sent_number):
"""
adds the root node of a sentence to the graph and the list of sentences
(``self.sentences``). the node has a ``tokens` attribute, which
contains a list of the tokens (token node IDs) of this sentence.
Parameters
------... | [
"def",
"__add_sentence_root_node",
"(",
"self",
",",
"sent_number",
")",
":",
"sent_id",
"=",
"'s{}'",
".",
"format",
"(",
"sent_number",
")",
"self",
".",
"add_node",
"(",
"sent_id",
",",
"layers",
"=",
"{",
"self",
".",
"ns",
",",
"self",
".",
"ns",
... | adds the root node of a sentence to the graph and the list of sentences
(``self.sentences``). the node has a ``tokens` attribute, which
contains a list of the tokens (token node IDs) of this sentence.
Parameters
----------
sent_number : int
the index of the sentence ... | [
"adds",
"the",
"root",
"node",
"of",
"a",
"sentence",
"to",
"the",
"graph",
"and",
"the",
"list",
"of",
"sentences",
"(",
"self",
".",
"sentences",
")",
".",
"the",
"node",
"has",
"a",
"tokens",
"attribute",
"which",
"contains",
"a",
"list",
"of",
"the... | python | train | 35.875 |
bitlabstudio/django-calendarium | calendarium/utils.py | https://github.com/bitlabstudio/django-calendarium/blob/cabe69eff965dff80893012fb4dfe724e995807a/calendarium/utils.py#L57-L64 | def get_occurrence(self, occ):
"""
Return a persisted occurrences matching the occ and remove it from
lookup since it has already been matched
"""
return self.lookup.pop(
(occ.event, occ.original_start, occ.original_end),
occ) | [
"def",
"get_occurrence",
"(",
"self",
",",
"occ",
")",
":",
"return",
"self",
".",
"lookup",
".",
"pop",
"(",
"(",
"occ",
".",
"event",
",",
"occ",
".",
"original_start",
",",
"occ",
".",
"original_end",
")",
",",
"occ",
")"
] | Return a persisted occurrences matching the occ and remove it from
lookup since it has already been matched | [
"Return",
"a",
"persisted",
"occurrences",
"matching",
"the",
"occ",
"and",
"remove",
"it",
"from",
"lookup",
"since",
"it",
"has",
"already",
"been",
"matched"
] | python | train | 35.375 |
pyviz/holoviews | holoviews/plotting/bokeh/sankey.py | https://github.com/pyviz/holoviews/blob/ae0dd2f3de448b0ca5e9065aabd6ef8d84c7e655/holoviews/plotting/bokeh/sankey.py#L117-L178 | def _compute_labels(self, element, data, mapping):
"""
Computes labels for the nodes and adds it to the data.
"""
if element.vdims:
edges = Dataset(element)[element[element.vdims[0].name]>0]
nodes = list(np.unique([edges.dimension_values(i) for i in range(2)]))
... | [
"def",
"_compute_labels",
"(",
"self",
",",
"element",
",",
"data",
",",
"mapping",
")",
":",
"if",
"element",
".",
"vdims",
":",
"edges",
"=",
"Dataset",
"(",
"element",
")",
"[",
"element",
"[",
"element",
".",
"vdims",
"[",
"0",
"]",
".",
"name",
... | Computes labels for the nodes and adds it to the data. | [
"Computes",
"labels",
"for",
"the",
"nodes",
"and",
"adds",
"it",
"to",
"the",
"data",
"."
] | python | train | 38.5 |
redhat-cip/python-dciclient | dciclient/v1/shell_commands/topic.py | https://github.com/redhat-cip/python-dciclient/blob/a4aa5899062802bbe4c30a075d8447f8d222d214/dciclient/v1/shell_commands/topic.py#L57-L76 | def create(context, name, component_types, active, product_id, data):
"""create(context, name, component_types, active, product_id, data)
Create a topic.
>>> dcictl topic-create [OPTIONS]
:param string name: Name of the topic [required]
:param string component_types: list of component types separ... | [
"def",
"create",
"(",
"context",
",",
"name",
",",
"component_types",
",",
"active",
",",
"product_id",
",",
"data",
")",
":",
"if",
"component_types",
":",
"component_types",
"=",
"component_types",
".",
"split",
"(",
"','",
")",
"state",
"=",
"utils",
".... | create(context, name, component_types, active, product_id, data)
Create a topic.
>>> dcictl topic-create [OPTIONS]
:param string name: Name of the topic [required]
:param string component_types: list of component types separated by commas
:param boolean active: Set the topic in the (in)active sta... | [
"create",
"(",
"context",
"name",
"component_types",
"active",
"product_id",
"data",
")"
] | python | train | 40.8 |
apache/incubator-mxnet | python/mxnet/contrib/onnx/mx2onnx/export_onnx.py | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/contrib/onnx/mx2onnx/export_onnx.py#L86-L92 | def convert_layer(node, **kwargs):
"""Convert MXNet layer to ONNX"""
op = str(node["op"])
if op not in MXNetGraph.registry_:
raise AttributeError("No conversion function registered for op type %s yet." % op)
convert_func = MXNetGraph.registry_[op]
return convert_func(... | [
"def",
"convert_layer",
"(",
"node",
",",
"*",
"*",
"kwargs",
")",
":",
"op",
"=",
"str",
"(",
"node",
"[",
"\"op\"",
"]",
")",
"if",
"op",
"not",
"in",
"MXNetGraph",
".",
"registry_",
":",
"raise",
"AttributeError",
"(",
"\"No conversion function register... | Convert MXNet layer to ONNX | [
"Convert",
"MXNet",
"layer",
"to",
"ONNX"
] | python | train | 47 |
onicagroup/runway | runway/module/terraform.py | https://github.com/onicagroup/runway/blob/3f3549ec3bf6e39b9f27d9738a1847f3a4369e7f/runway/module/terraform.py#L58-L64 | def get_backend_init_list(backend_vals):
"""Turn backend config dict into command line items."""
cmd_list = []
for (key, val) in backend_vals.items():
cmd_list.append('-backend-config')
cmd_list.append(key + '=' + val)
return cmd_list | [
"def",
"get_backend_init_list",
"(",
"backend_vals",
")",
":",
"cmd_list",
"=",
"[",
"]",
"for",
"(",
"key",
",",
"val",
")",
"in",
"backend_vals",
".",
"items",
"(",
")",
":",
"cmd_list",
".",
"append",
"(",
"'-backend-config'",
")",
"cmd_list",
".",
"a... | Turn backend config dict into command line items. | [
"Turn",
"backend",
"config",
"dict",
"into",
"command",
"line",
"items",
"."
] | python | train | 37.142857 |
Hackerfleet/hfos | hfos/tool/user.py | https://github.com/Hackerfleet/hfos/blob/b6df14eacaffb6be5c844108873ff8763ec7f0c9/hfos/tool/user.py#L207-L225 | def add_role(ctx, role):
"""Grant a role to an existing user"""
if role is None:
log('Specify the role with --role')
return
if ctx.obj['username'] is None:
log('Specify the username with --username')
return
change_user = ctx.obj['db'].objectmodels['user'].find_one({
... | [
"def",
"add_role",
"(",
"ctx",
",",
"role",
")",
":",
"if",
"role",
"is",
"None",
":",
"log",
"(",
"'Specify the role with --role'",
")",
"return",
"if",
"ctx",
".",
"obj",
"[",
"'username'",
"]",
"is",
"None",
":",
"log",
"(",
"'Specify the username with ... | Grant a role to an existing user | [
"Grant",
"a",
"role",
"to",
"an",
"existing",
"user"
] | python | train | 27.789474 |
PmagPy/PmagPy | dialogs/magic_grid2.py | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/dialogs/magic_grid2.py#L276-L297 | def remove_row(self, row_num=None):
"""
Remove a row from the grid
"""
#DeleteRows(self, pos, numRows, updateLabel
if not row_num and row_num != 0:
row_num = self.GetNumberRows() - 1
label = self.GetCellValue(row_num, 0)
self.DeleteRows(pos=row_num, nu... | [
"def",
"remove_row",
"(",
"self",
",",
"row_num",
"=",
"None",
")",
":",
"#DeleteRows(self, pos, numRows, updateLabel",
"if",
"not",
"row_num",
"and",
"row_num",
"!=",
"0",
":",
"row_num",
"=",
"self",
".",
"GetNumberRows",
"(",
")",
"-",
"1",
"label",
"=",
... | Remove a row from the grid | [
"Remove",
"a",
"row",
"from",
"the",
"grid"
] | python | train | 36 |
matthewdeanmartin/jiggle_version | jiggle_version/find_version_by_package.py | https://github.com/matthewdeanmartin/jiggle_version/blob/963656a0a47b7162780a5f6c8f4b8bbbebc148f5/jiggle_version/find_version_by_package.py#L58-L74 | def guess_version_by_running_live_package(
pkg_key, default="?"
): # type: (str,str) -> Any
"""Guess the version of a pkg when pip doesn't provide it.
:param str pkg_key: key of the package
:param str default: default version to return if unable to find
:returns: version
:rtype: string
""... | [
"def",
"guess_version_by_running_live_package",
"(",
"pkg_key",
",",
"default",
"=",
"\"?\"",
")",
":",
"# type: (str,str) -> Any",
"try",
":",
"m",
"=",
"import_module",
"(",
"pkg_key",
")",
"except",
"ImportError",
":",
"return",
"default",
"else",
":",
"return"... | Guess the version of a pkg when pip doesn't provide it.
:param str pkg_key: key of the package
:param str default: default version to return if unable to find
:returns: version
:rtype: string | [
"Guess",
"the",
"version",
"of",
"a",
"pkg",
"when",
"pip",
"doesn",
"t",
"provide",
"it",
"."
] | python | train | 26.823529 |
dims/etcd3-gateway | etcd3gw/lease.py | https://github.com/dims/etcd3-gateway/blob/ad566c29cbde135aee20cfd32e0a4815ca3b5ee6/etcd3gw/lease.py#L66-L75 | def keys(self):
"""Get the keys associated with this lease.
:return:
"""
result = self.client.post(self.client.get_url("/kv/lease/timetolive"),
json={"ID": self.id,
"keys": True})
keys = result['keys'] if ... | [
"def",
"keys",
"(",
"self",
")",
":",
"result",
"=",
"self",
".",
"client",
".",
"post",
"(",
"self",
".",
"client",
".",
"get_url",
"(",
"\"/kv/lease/timetolive\"",
")",
",",
"json",
"=",
"{",
"\"ID\"",
":",
"self",
".",
"id",
",",
"\"keys\"",
":",
... | Get the keys associated with this lease.
:return: | [
"Get",
"the",
"keys",
"associated",
"with",
"this",
"lease",
"."
] | python | train | 38.1 |
googledatalab/pydatalab | google/datalab/storage/_object.py | https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/storage/_object.py#L69-L72 | def updated_on(self):
"""The updated timestamp of the object as a datetime.datetime."""
s = self._info.get('updated', None)
return dateutil.parser.parse(s) if s else None | [
"def",
"updated_on",
"(",
"self",
")",
":",
"s",
"=",
"self",
".",
"_info",
".",
"get",
"(",
"'updated'",
",",
"None",
")",
"return",
"dateutil",
".",
"parser",
".",
"parse",
"(",
"s",
")",
"if",
"s",
"else",
"None"
] | The updated timestamp of the object as a datetime.datetime. | [
"The",
"updated",
"timestamp",
"of",
"the",
"object",
"as",
"a",
"datetime",
".",
"datetime",
"."
] | python | train | 44.75 |
brocade/pynos | pynos/versions/ver_7/ver_7_1_0/yang/brocade_tunnels.py | https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_7/ver_7_1_0/yang/brocade_tunnels.py#L258-L271 | def overlay_gateway_map_vlan_vni_auto(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
overlay_gateway = ET.SubElement(config, "overlay-gateway", xmlns="urn:brocade.com:mgmt:brocade-tunnels")
name_key = ET.SubElement(overlay_gateway, "name")
name_... | [
"def",
"overlay_gateway_map_vlan_vni_auto",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"overlay_gateway",
"=",
"ET",
".",
"SubElement",
"(",
"config",
",",
"\"overlay-gateway\"",
",",
"xmlns",
... | Auto Generated Code | [
"Auto",
"Generated",
"Code"
] | python | train | 43.142857 |
funkybob/knights-templater | knights/tags.py | https://github.com/funkybob/knights-templater/blob/b15cdbaae7d824d02f7f03ca04599ae94bb759dd/knights/tags.py#L225-L245 | def use(parser, token):
'''
Counterpart to `macro`, lets you render any block/macro in place.
'''
args, kwargs = parser.parse_args(token)
assert isinstance(args[0], ast.Str), \
'First argument to "include" tag must be a string'
name = args[0].s
action = ast.YieldFrom(
value... | [
"def",
"use",
"(",
"parser",
",",
"token",
")",
":",
"args",
",",
"kwargs",
"=",
"parser",
".",
"parse_args",
"(",
"token",
")",
"assert",
"isinstance",
"(",
"args",
"[",
"0",
"]",
",",
"ast",
".",
"Str",
")",
",",
"'First argument to \"include\" tag mus... | Counterpart to `macro`, lets you render any block/macro in place. | [
"Counterpart",
"to",
"macro",
"lets",
"you",
"render",
"any",
"block",
"/",
"macro",
"in",
"place",
"."
] | python | train | 25.571429 |
SoCo/SoCo | soco/plugins/wimp.py | https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/plugins/wimp.py#L452-L482 | def _base_body(self):
"""Return the base XML body, which has the following form:
.. code :: xml
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
<s:Header>
<credentials xmlns="http://www.sonos.com/Services/1.1">
<sessionId>self._session_i... | [
"def",
"_base_body",
"(",
"self",
")",
":",
"item_attrib",
"=",
"{",
"'xmlns:s'",
":",
"'http://schemas.xmlsoap.org/soap/envelope/'",
",",
"}",
"xml",
"=",
"XML",
".",
"Element",
"(",
"'s:Envelope'",
",",
"item_attrib",
")",
"# Add the Header part",
"XML",
".",
... | Return the base XML body, which has the following form:
.. code :: xml
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
<s:Header>
<credentials xmlns="http://www.sonos.com/Services/1.1">
<sessionId>self._session_id</sessionId>
<dev... | [
"Return",
"the",
"base",
"XML",
"body",
"which",
"has",
"the",
"following",
"form",
":"
] | python | train | 36.322581 |
pauleveritt/kaybee | kaybee/plugins/references/base_reference.py | https://github.com/pauleveritt/kaybee/blob/a00a718aaaa23b2d12db30dfacb6b2b6ec84459c/kaybee/plugins/references/base_reference.py#L23-L33 | def get_sources(self, resources):
""" Filter resources based on which have this reference """
rtype = self.rtype # E.g. category
label = self.props.label # E.g. category1
result = [
resource
for resource in resources.values()
if is_reference_target(... | [
"def",
"get_sources",
"(",
"self",
",",
"resources",
")",
":",
"rtype",
"=",
"self",
".",
"rtype",
"# E.g. category",
"label",
"=",
"self",
".",
"props",
".",
"label",
"# E.g. category1",
"result",
"=",
"[",
"resource",
"for",
"resource",
"in",
"resources",
... | Filter resources based on which have this reference | [
"Filter",
"resources",
"based",
"on",
"which",
"have",
"this",
"reference"
] | python | train | 33.181818 |
phoebe-project/phoebe2 | phoebe/parameters/constraint.py | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/parameters/constraint.py#L126-L130 | def roche_requiv_contact_L1(q, sma, compno=1):
"""
TODO: add documentation
"""
return ConstraintParameter(q._bundle, "requiv_contact_L1(%s, %d)" % (", ".join(["{%s}" % (param.uniquetwig if hasattr(param, 'uniquetwig') else param.expr) for param in (q, sma)]), compno)) | [
"def",
"roche_requiv_contact_L1",
"(",
"q",
",",
"sma",
",",
"compno",
"=",
"1",
")",
":",
"return",
"ConstraintParameter",
"(",
"q",
".",
"_bundle",
",",
"\"requiv_contact_L1(%s, %d)\"",
"%",
"(",
"\", \"",
".",
"join",
"(",
"[",
"\"{%s}\"",
"%",
"(",
"pa... | TODO: add documentation | [
"TODO",
":",
"add",
"documentation"
] | python | train | 56 |
tsroten/dragonmapper | dragonmapper/transcriptions.py | https://github.com/tsroten/dragonmapper/blob/68eaf43c32725f4b4923c01284cfc0112079e8ab/dragonmapper/transcriptions.py#L417-L435 | def to_pinyin(s, accented=True):
"""Convert *s* to Pinyin.
If *accented* is ``True``, diacritics are added to the Pinyin syllables. If
it's ``False``, numbers are used to indicate tone.
"""
identity = identify(s)
if identity == PINYIN:
if _has_accented_vowels(s):
return s i... | [
"def",
"to_pinyin",
"(",
"s",
",",
"accented",
"=",
"True",
")",
":",
"identity",
"=",
"identify",
"(",
"s",
")",
"if",
"identity",
"==",
"PINYIN",
":",
"if",
"_has_accented_vowels",
"(",
"s",
")",
":",
"return",
"s",
"if",
"accented",
"else",
"accente... | Convert *s* to Pinyin.
If *accented* is ``True``, diacritics are added to the Pinyin syllables. If
it's ``False``, numbers are used to indicate tone. | [
"Convert",
"*",
"s",
"*",
"to",
"Pinyin",
"."
] | python | train | 34.736842 |
KvasirSecurity/kvasirapi-python | KvasirAPI/jsonrpc/services.py | https://github.com/KvasirSecurity/kvasirapi-python/blob/ec8c5818bd5913f3afd150f25eaec6e7cc732f4c/KvasirAPI/jsonrpc/services.py#L89-L99 | def report_list(self, service_id=None, service_port=None, hostfilter=None):
"""
Returns a list of ports with IPs, banners and vulnerabilities (warning, slow!)
:param service_id: t_services.id
:param service_port: Port (tcp/#, udp/#, info/#)
:param hostfilter: Valid hostfilter or... | [
"def",
"report_list",
"(",
"self",
",",
"service_id",
"=",
"None",
",",
"service_port",
"=",
"None",
",",
"hostfilter",
"=",
"None",
")",
":",
"return",
"self",
".",
"send",
".",
"service_report_list",
"(",
"service_id",
",",
"service_port",
",",
"hostfilter... | Returns a list of ports with IPs, banners and vulnerabilities (warning, slow!)
:param service_id: t_services.id
:param service_port: Port (tcp/#, udp/#, info/#)
:param hostfilter: Valid hostfilter or None
:return: { 'port': [t_hosts.f_ipaddr, t_services.f_banner,
(t_vulndata... | [
"Returns",
"a",
"list",
"of",
"ports",
"with",
"IPs",
"banners",
"and",
"vulnerabilities",
"(",
"warning",
"slow!",
")"
] | python | train | 53.181818 |
materialsproject/pymatgen | pymatgen/analysis/magnetism/analyzer.py | https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/analysis/magnetism/analyzer.py#L1170-L1207 | def magnetic_deformation(structure_A, structure_B):
"""
Calculates 'magnetic deformation proxy',
a measure of deformation (norm of finite strain)
between 'non-magnetic' (non-spin-polarized) and
ferromagnetic structures.
Adapted from Bocarsly et al. 2017,
doi: 10.1021/acs.chemmater.6b04729
... | [
"def",
"magnetic_deformation",
"(",
"structure_A",
",",
"structure_B",
")",
":",
"# retrieve orderings of both input structures",
"ordering_a",
"=",
"CollinearMagneticStructureAnalyzer",
"(",
"structure_A",
",",
"overwrite_magmom_mode",
"=",
"\"none\"",
")",
".",
"ordering",
... | Calculates 'magnetic deformation proxy',
a measure of deformation (norm of finite strain)
between 'non-magnetic' (non-spin-polarized) and
ferromagnetic structures.
Adapted from Bocarsly et al. 2017,
doi: 10.1021/acs.chemmater.6b04729
:param structure_A: Structure
:param structure_B: Struct... | [
"Calculates",
"magnetic",
"deformation",
"proxy",
"a",
"measure",
"of",
"deformation",
"(",
"norm",
"of",
"finite",
"strain",
")",
"between",
"non",
"-",
"magnetic",
"(",
"non",
"-",
"spin",
"-",
"polarized",
")",
"and",
"ferromagnetic",
"structures",
"."
] | python | train | 35.605263 |
pgmpy/pgmpy | pgmpy/readwrite/PomdpX.py | https://github.com/pgmpy/pgmpy/blob/9381a66aba3c3871d3ccd00672b148d17d63239e/pgmpy/readwrite/PomdpX.py#L314-L328 | def get_parameter_tbl(self, parameter):
"""
This method returns parameters as list of dict in case of table type
parameter
"""
par = []
for entry in parameter.findall('Entry'):
instance = defaultdict(list)
instance['Instance'] = entry.find('Instanc... | [
"def",
"get_parameter_tbl",
"(",
"self",
",",
"parameter",
")",
":",
"par",
"=",
"[",
"]",
"for",
"entry",
"in",
"parameter",
".",
"findall",
"(",
"'Entry'",
")",
":",
"instance",
"=",
"defaultdict",
"(",
"list",
")",
"instance",
"[",
"'Instance'",
"]",
... | This method returns parameters as list of dict in case of table type
parameter | [
"This",
"method",
"returns",
"parameters",
"as",
"list",
"of",
"dict",
"in",
"case",
"of",
"table",
"type",
"parameter"
] | python | train | 39.733333 |
squeaky-pl/japronto | misc/cpu.py | https://github.com/squeaky-pl/japronto/blob/a526277a2f59100388c9f39d4ca22bfb4909955b/misc/cpu.py#L105-L151 | def dump():
"""
dump function
"""
try:
sensors = subprocess.check_output('sensors').decode('utf-8')
except (FileNotFoundError, subprocess.CalledProcessError):
print("Couldn't read CPU temp")
else:
cores = []
for line in sensors.splitlines():
if lin... | [
"def",
"dump",
"(",
")",
":",
"try",
":",
"sensors",
"=",
"subprocess",
".",
"check_output",
"(",
"'sensors'",
")",
".",
"decode",
"(",
"'utf-8'",
")",
"except",
"(",
"FileNotFoundError",
",",
"subprocess",
".",
"CalledProcessError",
")",
":",
"print",
"("... | dump function | [
"dump",
"function"
] | python | train | 22.531915 |
saltstack/salt | salt/modules/pkg_resource.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/pkg_resource.py#L180-L214 | def version(*names, **kwargs):
'''
Common interface for obtaining the version of installed packages.
CLI Example:
.. code-block:: bash
salt '*' pkg_resource.version vim
salt '*' pkg_resource.version foo bar baz
salt '*' pkg_resource.version 'python*'
'''
ret = {}
v... | [
"def",
"version",
"(",
"*",
"names",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"{",
"}",
"versions_as_list",
"=",
"salt",
".",
"utils",
".",
"data",
".",
"is_true",
"(",
"kwargs",
".",
"pop",
"(",
"'versions_as_list'",
",",
"False",
")",
")",
... | Common interface for obtaining the version of installed packages.
CLI Example:
.. code-block:: bash
salt '*' pkg_resource.version vim
salt '*' pkg_resource.version foo bar baz
salt '*' pkg_resource.version 'python*' | [
"Common",
"interface",
"for",
"obtaining",
"the",
"version",
"of",
"installed",
"packages",
"."
] | python | train | 30.885714 |
nvdv/vprof | vprof/memory_profiler.py | https://github.com/nvdv/vprof/blob/4c3ff78f8920ab10cb9c00b14143452aa09ff6bb/vprof/memory_profiler.py#L65-L75 | def _format_obj_count(objects):
"""Formats object count."""
result = []
regex = re.compile(r'<(?P<type>\w+) \'(?P<name>\S+)\'>')
for obj_type, obj_count in objects.items():
if obj_count != 0:
match = re.findall(regex, repr(obj_type))
if match:
obj_type, ob... | [
"def",
"_format_obj_count",
"(",
"objects",
")",
":",
"result",
"=",
"[",
"]",
"regex",
"=",
"re",
".",
"compile",
"(",
"r'<(?P<type>\\w+) \\'(?P<name>\\S+)\\'>'",
")",
"for",
"obj_type",
",",
"obj_count",
"in",
"objects",
".",
"items",
"(",
")",
":",
"if",
... | Formats object count. | [
"Formats",
"object",
"count",
"."
] | python | test | 42.727273 |
njouanin/repool | repool/pool.py | https://github.com/njouanin/repool/blob/27102cf84cb382c0b2d935f8b8651aa7f8c2777e/repool/pool.py#L123-L133 | def release_pool(self):
"""Release pool and all its connection"""
if self._current_acquired > 0:
raise PoolException("Can't release pool: %d connection(s) still acquired" % self._current_acquired)
while not self._pool.empty():
conn = self.acquire()
conn.close(... | [
"def",
"release_pool",
"(",
"self",
")",
":",
"if",
"self",
".",
"_current_acquired",
">",
"0",
":",
"raise",
"PoolException",
"(",
"\"Can't release pool: %d connection(s) still acquired\"",
"%",
"self",
".",
"_current_acquired",
")",
"while",
"not",
"self",
".",
... | Release pool and all its connection | [
"Release",
"pool",
"and",
"all",
"its",
"connection"
] | python | train | 41.727273 |
saltstack/salt | salt/modules/git.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/git.py#L63-L110 | def _config_getter(get_opt,
key,
value_regex=None,
cwd=None,
user=None,
password=None,
ignore_retcode=False,
output_encoding=None,
**kwargs):
'''
Common code fo... | [
"def",
"_config_getter",
"(",
"get_opt",
",",
"key",
",",
"value_regex",
"=",
"None",
",",
"cwd",
"=",
"None",
",",
"user",
"=",
"None",
",",
"password",
"=",
"None",
",",
"ignore_retcode",
"=",
"False",
",",
"output_encoding",
"=",
"None",
",",
"*",
"... | Common code for config.get_* functions, builds and runs the git CLI command
and returns the result dict for the calling function to parse. | [
"Common",
"code",
"for",
"config",
".",
"get_",
"*",
"functions",
"builds",
"and",
"runs",
"the",
"git",
"CLI",
"command",
"and",
"returns",
"the",
"result",
"dict",
"for",
"the",
"calling",
"function",
"to",
"parse",
"."
] | python | train | 33.145833 |
toumorokoshi/sprinter | sprinter/lib/request.py | https://github.com/toumorokoshi/sprinter/blob/846697a7a087e69c61d075232e754d6975a64152/sprinter/lib/request.py#L34-L39 | def cleaned_request(request_type, *args, **kwargs):
""" Perform a cleaned requests request """
s = requests.Session()
# this removes netrc checking
s.trust_env = False
return s.request(request_type, *args, **kwargs) | [
"def",
"cleaned_request",
"(",
"request_type",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"s",
"=",
"requests",
".",
"Session",
"(",
")",
"# this removes netrc checking",
"s",
".",
"trust_env",
"=",
"False",
"return",
"s",
".",
"request",
"(",
... | Perform a cleaned requests request | [
"Perform",
"a",
"cleaned",
"requests",
"request"
] | python | train | 38.333333 |
praekeltfoundation/molo | molo/core/api/endpoints.py | https://github.com/praekeltfoundation/molo/blob/57702fda4fab261d67591415f7d46bc98fa38525/molo/core/api/endpoints.py#L84-L90 | def get_queryset(self):
'''
Only serve site-specific languages
'''
request = self.request
return (Languages.for_site(request.site)
.languages.filter().order_by('pk')) | [
"def",
"get_queryset",
"(",
"self",
")",
":",
"request",
"=",
"self",
".",
"request",
"return",
"(",
"Languages",
".",
"for_site",
"(",
"request",
".",
"site",
")",
".",
"languages",
".",
"filter",
"(",
")",
".",
"order_by",
"(",
"'pk'",
")",
")"
] | Only serve site-specific languages | [
"Only",
"serve",
"site",
"-",
"specific",
"languages"
] | python | train | 32.142857 |
sdispater/pendulum | pendulum/helpers.py | https://github.com/sdispater/pendulum/blob/94d28b0d3cb524ae02361bd1ed7ea03e2e655e4e/pendulum/helpers.py#L46-L122 | def add_duration(
dt, # type: Union[datetime, date]
years=0, # type: int
months=0, # type: int
weeks=0, # type: int
days=0, # type: int
hours=0, # type: int
minutes=0, # type: int
seconds=0, # type: int
microseconds=0,
): # type: (...) -> Union[datetime, date]
"""
A... | [
"def",
"add_duration",
"(",
"dt",
",",
"# type: Union[datetime, date]",
"years",
"=",
"0",
",",
"# type: int",
"months",
"=",
"0",
",",
"# type: int",
"weeks",
"=",
"0",
",",
"# type: int",
"days",
"=",
"0",
",",
"# type: int",
"hours",
"=",
"0",
",",
"# ... | Adds a duration to a date/datetime instance. | [
"Adds",
"a",
"duration",
"to",
"a",
"date",
"/",
"datetime",
"instance",
"."
] | python | train | 23.727273 |
intuition-io/intuition | intuition/api/context.py | https://github.com/intuition-io/intuition/blob/cd517e6b3b315a743eb4d0d0dc294e264ab913ce/intuition/api/context.py#L86-L103 | def _normalize_data_types(self, strategy):
''' some contexts only retrieves strings, giving back right type '''
for k, v in strategy.iteritems():
if not isinstance(v, str):
# There is probably nothing to do
continue
if v == 'true':
... | [
"def",
"_normalize_data_types",
"(",
"self",
",",
"strategy",
")",
":",
"for",
"k",
",",
"v",
"in",
"strategy",
".",
"iteritems",
"(",
")",
":",
"if",
"not",
"isinstance",
"(",
"v",
",",
"str",
")",
":",
"# There is probably nothing to do",
"continue",
"if... | some contexts only retrieves strings, giving back right type | [
"some",
"contexts",
"only",
"retrieves",
"strings",
"giving",
"back",
"right",
"type"
] | python | train | 36.555556 |
ejeschke/ginga | ginga/canvas/transform.py | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/canvas/transform.py#L219-L241 | def from_(self, win_pts):
"""Reverse of :meth:`to_`."""
# make relative to center pixel to convert from window
# graphics space to standard X/Y coordinate space
win_pts = np.asarray(win_pts, dtype=np.float)
has_z = (win_pts.shape[-1] > 2)
ctr_pt = list(self.viewer.get_ce... | [
"def",
"from_",
"(",
"self",
",",
"win_pts",
")",
":",
"# make relative to center pixel to convert from window",
"# graphics space to standard X/Y coordinate space",
"win_pts",
"=",
"np",
".",
"asarray",
"(",
"win_pts",
",",
"dtype",
"=",
"np",
".",
"float",
")",
"has... | Reverse of :meth:`to_`. | [
"Reverse",
"of",
":",
"meth",
":",
"to_",
"."
] | python | train | 29.652174 |
johnnoone/json-spec | src/jsonspec/validators/draft04.py | https://github.com/johnnoone/json-spec/blob/f91981724cea0c366bd42a6670eb07bbe31c0e0c/src/jsonspec/validators/draft04.py#L32-L251 | def compile(schema, pointer, context, scope=None):
"""
Compiles schema with `JSON Schema`_ draft-04.
:param schema: obj to compile
:type schema: Mapping
:param pointer: uri of the schema
:type pointer: Pointer, str
:param context: context of this schema
:type context: Context
.. _`... | [
"def",
"compile",
"(",
"schema",
",",
"pointer",
",",
"context",
",",
"scope",
"=",
"None",
")",
":",
"schm",
"=",
"deepcopy",
"(",
"schema",
")",
"scope",
"=",
"urljoin",
"(",
"scope",
"or",
"str",
"(",
"pointer",
")",
",",
"schm",
".",
"pop",
"("... | Compiles schema with `JSON Schema`_ draft-04.
:param schema: obj to compile
:type schema: Mapping
:param pointer: uri of the schema
:type pointer: Pointer, str
:param context: context of this schema
:type context: Context
.. _`JSON Schema`: http://json-schema.org | [
"Compiles",
"schema",
"with",
"JSON",
"Schema",
"_",
"draft",
"-",
"04",
"."
] | python | train | 44 |
olt/scriptine | scriptine/command.py | https://github.com/olt/scriptine/blob/f4cfea939f2f3ad352b24c5f6410f79e78723d0e/scriptine/command.py#L241-L274 | def parse_rst_params(doc):
"""
Parse a reStructuredText docstring and return a dictionary
with parameter names and descriptions.
>>> doc = '''
... :param foo: foo parameter
... foo parameter
...
... :param bar: bar parameter
... :param baz: baz parameter
... ... | [
"def",
"parse_rst_params",
"(",
"doc",
")",
":",
"param_re",
"=",
"re",
".",
"compile",
"(",
"r\"\"\"^([ \\t]*):param\\ \n (?P<param>\\w+):\\ \n (?P<body>.*\\n(\\1[ \\t]+\\w.*\\n)*)\"\"\"",
",",
"re",
".",
"MULTILINE",
"|",
... | Parse a reStructuredText docstring and return a dictionary
with parameter names and descriptions.
>>> doc = '''
... :param foo: foo parameter
... foo parameter
...
... :param bar: bar parameter
... :param baz: baz parameter
... baz parameter
... baz parameter... | [
"Parse",
"a",
"reStructuredText",
"docstring",
"and",
"return",
"a",
"dictionary",
"with",
"parameter",
"names",
"and",
"descriptions",
".",
">>>",
"doc",
"=",
"...",
":",
"param",
"foo",
":",
"foo",
"parameter",
"...",
"foo",
"parameter",
"...",
"...",
":",... | python | train | 30.235294 |
pandas-dev/pandas | pandas/io/html.py | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/io/html.py#L498-L518 | def _handle_hidden_tables(self, tbl_list, attr_name):
"""
Return list of tables, potentially removing hidden elements
Parameters
----------
tbl_list : list of node-like
Type of list elements will vary depending upon parser used
attr_name : str
Nam... | [
"def",
"_handle_hidden_tables",
"(",
"self",
",",
"tbl_list",
",",
"attr_name",
")",
":",
"if",
"not",
"self",
".",
"displayed_only",
":",
"return",
"tbl_list",
"return",
"[",
"x",
"for",
"x",
"in",
"tbl_list",
"if",
"\"display:none\"",
"not",
"in",
"getattr... | Return list of tables, potentially removing hidden elements
Parameters
----------
tbl_list : list of node-like
Type of list elements will vary depending upon parser used
attr_name : str
Name of the accessor for retrieving HTML attributes
Returns
... | [
"Return",
"list",
"of",
"tables",
"potentially",
"removing",
"hidden",
"elements"
] | python | train | 31.47619 |
dj-stripe/dj-stripe | djstripe/models/payment_methods.py | https://github.com/dj-stripe/dj-stripe/blob/a5308a3808cd6e2baba49482f7a699f3a8992518/djstripe/models/payment_methods.py#L442-L461 | def detach(self):
"""
Detach the source from its customer.
"""
# First, wipe default source on all customers that use this.
Customer.objects.filter(default_source=self.id).update(default_source=None)
try:
# TODO - we could use the return value of sync_from_stripe_data
# or call its internals - self... | [
"def",
"detach",
"(",
"self",
")",
":",
"# First, wipe default source on all customers that use this.",
"Customer",
".",
"objects",
".",
"filter",
"(",
"default_source",
"=",
"self",
".",
"id",
")",
".",
"update",
"(",
"default_source",
"=",
"None",
")",
"try",
... | Detach the source from its customer. | [
"Detach",
"the",
"source",
"from",
"its",
"customer",
"."
] | python | train | 36.8 |
tensorforce/tensorforce | docs/mistune.py | https://github.com/tensorforce/tensorforce/blob/520a8d992230e382f08e315ede5fc477f5e26bfb/docs/mistune.py#L817-L823 | def codespan(self, text):
"""Rendering inline `code` text.
:param text: text content for inline code.
"""
text = escape(text.rstrip(), smart_amp=False)
return '<code>%s</code>' % text | [
"def",
"codespan",
"(",
"self",
",",
"text",
")",
":",
"text",
"=",
"escape",
"(",
"text",
".",
"rstrip",
"(",
")",
",",
"smart_amp",
"=",
"False",
")",
"return",
"'<code>%s</code>'",
"%",
"text"
] | Rendering inline `code` text.
:param text: text content for inline code. | [
"Rendering",
"inline",
"code",
"text",
"."
] | python | valid | 31.142857 |
numenta/nupic | scripts/profiling/tm_profile.py | https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/scripts/profiling/tm_profile.py#L31-L54 | def profileTM(tmClass, tmDim, nRuns):
"""
profiling performance of TemporalMemory (TM)
using the python cProfile module and ordered by cumulative time,
see how to run on command-line above.
@param tmClass implementation of TM (cpp, py, ..)
@param tmDim number of columns in TM
@param nRuns number of calls... | [
"def",
"profileTM",
"(",
"tmClass",
",",
"tmDim",
",",
"nRuns",
")",
":",
"# create TM instance to measure",
"tm",
"=",
"tmClass",
"(",
"numberOfCols",
"=",
"tmDim",
")",
"# generate input data",
"data",
"=",
"numpy",
".",
"random",
".",
"randint",
"(",
"0",
... | profiling performance of TemporalMemory (TM)
using the python cProfile module and ordered by cumulative time,
see how to run on command-line above.
@param tmClass implementation of TM (cpp, py, ..)
@param tmDim number of columns in TM
@param nRuns number of calls of the profiled code (epochs) | [
"profiling",
"performance",
"of",
"TemporalMemory",
"(",
"TM",
")",
"using",
"the",
"python",
"cProfile",
"module",
"and",
"ordered",
"by",
"cumulative",
"time",
"see",
"how",
"to",
"run",
"on",
"command",
"-",
"line",
"above",
"."
] | python | valid | 31.541667 |
saltstack/salt | salt/modules/mac_system.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_system.py#L362-L387 | def set_subnet_name(name):
'''
Set the local subnet name
:param str name: The new local subnet name
.. note::
Spaces are changed to dashes. Other special characters are removed.
:return: True if successful, False if not
:rtype: bool
CLI Example:
.. code-block:: bash
... | [
"def",
"set_subnet_name",
"(",
"name",
")",
":",
"cmd",
"=",
"'systemsetup -setlocalsubnetname \"{0}\"'",
".",
"format",
"(",
"name",
")",
"__utils__",
"[",
"'mac_utils.execute_return_success'",
"]",
"(",
"cmd",
")",
"return",
"__utils__",
"[",
"'mac_utils.confirm_upd... | Set the local subnet name
:param str name: The new local subnet name
.. note::
Spaces are changed to dashes. Other special characters are removed.
:return: True if successful, False if not
:rtype: bool
CLI Example:
.. code-block:: bash
The following will be set as 'Mikes-Mac... | [
"Set",
"the",
"local",
"subnet",
"name"
] | python | train | 23.5 |
kalefranz/auxlib | auxlib/collection.py | https://github.com/kalefranz/auxlib/blob/6ff2d6b57d128d0b9ed8f01ad83572e938da064f/auxlib/collection.py#L87-L117 | def first(seq, key=lambda x: bool(x), default=None, apply=lambda x: x):
"""Give the first value that satisfies the key test.
Args:
seq (iterable):
key (callable): test for each element of iterable
default: returned when all elements fail test
apply (callable): applied to element... | [
"def",
"first",
"(",
"seq",
",",
"key",
"=",
"lambda",
"x",
":",
"bool",
"(",
"x",
")",
",",
"default",
"=",
"None",
",",
"apply",
"=",
"lambda",
"x",
":",
"x",
")",
":",
"return",
"next",
"(",
"(",
"apply",
"(",
"x",
")",
"for",
"x",
"in",
... | Give the first value that satisfies the key test.
Args:
seq (iterable):
key (callable): test for each element of iterable
default: returned when all elements fail test
apply (callable): applied to element before return, but not to default value
Returns: first element in seq tha... | [
"Give",
"the",
"first",
"value",
"that",
"satisfies",
"the",
"key",
"test",
"."
] | python | train | 36.612903 |
tkf/rash | rash/init.py | https://github.com/tkf/rash/blob/585da418ec37dd138f1a4277718b6f507e9536a2/rash/init.py#L37-L77 | def init_run(shell, no_daemon, daemon_options, daemon_outfile):
"""
Configure your shell.
Add the following line in your shell RC file and then you are
ready to go::
eval $(%(prog)s)
To check if your shell is supported, simply run::
%(prog)s --no-daemon
If you want to specify sh... | [
"def",
"init_run",
"(",
"shell",
",",
"no_daemon",
",",
"daemon_options",
",",
"daemon_outfile",
")",
":",
"import",
"sys",
"from",
".",
"__init__",
"import",
"__version__",
"init_file",
"=",
"find_init",
"(",
"shell",
")",
"if",
"os",
".",
"path",
".",
"e... | Configure your shell.
Add the following line in your shell RC file and then you are
ready to go::
eval $(%(prog)s)
To check if your shell is supported, simply run::
%(prog)s --no-daemon
If you want to specify shell other than $SHELL, you can give
--shell option::
eval $(%(pro... | [
"Configure",
"your",
"shell",
"."
] | python | train | 28.146341 |
openstack/networking-hyperv | networking_hyperv/neutron/agent/layer2.py | https://github.com/openstack/networking-hyperv/blob/7a89306ab0586c95b99debb44d898f70834508b9/networking_hyperv/neutron/agent/layer2.py#L389-L392 | def _treat_devices_removed(self):
"""Process the removed devices."""
for device in self._removed_ports.copy():
eventlet.spawn_n(self._process_removed_port, device) | [
"def",
"_treat_devices_removed",
"(",
"self",
")",
":",
"for",
"device",
"in",
"self",
".",
"_removed_ports",
".",
"copy",
"(",
")",
":",
"eventlet",
".",
"spawn_n",
"(",
"self",
".",
"_process_removed_port",
",",
"device",
")"
] | Process the removed devices. | [
"Process",
"the",
"removed",
"devices",
"."
] | python | train | 47 |
log2timeline/plaso | plaso/preprocessors/macos.py | https://github.com/log2timeline/plaso/blob/9c564698d2da3ffbe23607a3c54c0582ea18a6cc/plaso/preprocessors/macos.py#L267-L311 | def _ParseFileEntry(self, knowledge_base, file_entry):
"""Parses artifact file system data for a preprocessing attribute.
Args:
knowledge_base (KnowledgeBase): to fill with preprocessing information.
file_entry (dfvfs.FileEntry): file entry that contains the artifact
value data.
Rais... | [
"def",
"_ParseFileEntry",
"(",
"self",
",",
"knowledge_base",
",",
"file_entry",
")",
":",
"root_key",
"=",
"self",
".",
"_GetPlistRootKey",
"(",
"file_entry",
")",
"if",
"not",
"root_key",
":",
"location",
"=",
"getattr",
"(",
"file_entry",
".",
"path_spec",
... | Parses artifact file system data for a preprocessing attribute.
Args:
knowledge_base (KnowledgeBase): to fill with preprocessing information.
file_entry (dfvfs.FileEntry): file entry that contains the artifact
value data.
Raises:
errors.PreProcessFail: if the preprocessing fails. | [
"Parses",
"artifact",
"file",
"system",
"data",
"for",
"a",
"preprocessing",
"attribute",
"."
] | python | train | 36.533333 |
saltstack/salt | salt/modules/win_groupadd.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_groupadd.py#L70-L82 | def _get_all_groups():
'''
A helper function that gets a list of group objects for all groups on the
machine
Returns:
iter: A list of objects for all groups on the machine
'''
with salt.utils.winapi.Com():
nt = win32com.client.Dispatch('AdsNameSpaces')
results = nt.GetObject... | [
"def",
"_get_all_groups",
"(",
")",
":",
"with",
"salt",
".",
"utils",
".",
"winapi",
".",
"Com",
"(",
")",
":",
"nt",
"=",
"win32com",
".",
"client",
".",
"Dispatch",
"(",
"'AdsNameSpaces'",
")",
"results",
"=",
"nt",
".",
"GetObject",
"(",
"''",
",... | A helper function that gets a list of group objects for all groups on the
machine
Returns:
iter: A list of objects for all groups on the machine | [
"A",
"helper",
"function",
"that",
"gets",
"a",
"list",
"of",
"group",
"objects",
"for",
"all",
"groups",
"on",
"the",
"machine"
] | python | train | 28.846154 |
biolink/ontobio | ontobio/util/go_utils.py | https://github.com/biolink/ontobio/blob/4e512a7831cfe6bc1b32f2c3be2ba41bc5cf7345/ontobio/util/go_utils.py#L68-L81 | def go_aspect(self, go_term):
"""
For GO terms, returns F, C, or P corresponding to its aspect
"""
if not go_term.startswith("GO:"):
return None
else:
# Check ancestors for root terms
if self.is_molecular_function(go_term):
retu... | [
"def",
"go_aspect",
"(",
"self",
",",
"go_term",
")",
":",
"if",
"not",
"go_term",
".",
"startswith",
"(",
"\"GO:\"",
")",
":",
"return",
"None",
"else",
":",
"# Check ancestors for root terms",
"if",
"self",
".",
"is_molecular_function",
"(",
"go_term",
")",
... | For GO terms, returns F, C, or P corresponding to its aspect | [
"For",
"GO",
"terms",
"returns",
"F",
"C",
"or",
"P",
"corresponding",
"to",
"its",
"aspect"
] | python | train | 33.928571 |
PGower/PyCanvas | pycanvas/apis/content_migrations.py | https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/content_migrations.py#L293-L321 | def update_migration_issue_users(self, id, user_id, workflow_state, content_migration_id):
"""
Update a migration issue.
Update the workflow_state of a migration issue
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - user_id
"""... | [
"def",
"update_migration_issue_users",
"(",
"self",
",",
"id",
",",
"user_id",
",",
"workflow_state",
",",
"content_migration_id",
")",
":",
"path",
"=",
"{",
"}",
"data",
"=",
"{",
"}",
"params",
"=",
"{",
"}",
"# REQUIRED - PATH - user_id\r",
"\"\"\"ID\"\"\"",... | Update a migration issue.
Update the workflow_state of a migration issue | [
"Update",
"a",
"migration",
"issue",
".",
"Update",
"the",
"workflow_state",
"of",
"a",
"migration",
"issue"
] | python | train | 39.931034 |
dereneaton/ipyrad | ipyrad/assemble/cluster_within.py | https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/assemble/cluster_within.py#L1429-L1508 | def run(data, samples, noreverse, maxindels, force, ipyclient):
""" run the major functions for clustering within samples """
## list of samples to submit to queue
subsamples = []
## if sample is already done skip
for sample in samples:
## If sample not in state 2 don't try to cluster it.
... | [
"def",
"run",
"(",
"data",
",",
"samples",
",",
"noreverse",
",",
"maxindels",
",",
"force",
",",
"ipyclient",
")",
":",
"## list of samples to submit to queue",
"subsamples",
"=",
"[",
"]",
"## if sample is already done skip",
"for",
"sample",
"in",
"samples",
":... | run the major functions for clustering within samples | [
"run",
"the",
"major",
"functions",
"for",
"clustering",
"within",
"samples"
] | python | valid | 36.3125 |
Carbonara-Project/Guanciale | guanciale/idblib.py | https://github.com/Carbonara-Project/Guanciale/blob/c239ffac6fb481d09c4071d1de1a09f60dc584ab/guanciale/idblib.py#L1002-L1014 | def name(self, id):
"""
resolves a name, both short and long names.
"""
data = self.bytes(id, 'N')
if not data:
print("%x has no name" % id)
return
if data[:1] == b'\x00':
nameid, = struct.unpack_from(">" + self.fmt, data, 1)
... | [
"def",
"name",
"(",
"self",
",",
"id",
")",
":",
"data",
"=",
"self",
".",
"bytes",
"(",
"id",
",",
"'N'",
")",
"if",
"not",
"data",
":",
"print",
"(",
"\"%x has no name\"",
"%",
"id",
")",
"return",
"if",
"data",
"[",
":",
"1",
"]",
"==",
"b'\... | resolves a name, both short and long names. | [
"resolves",
"a",
"name",
"both",
"short",
"and",
"long",
"names",
"."
] | python | train | 39 |
jpscaletti/solution | solution/fields/splitted_datetime.py | https://github.com/jpscaletti/solution/blob/eabafd8e695bbb0209242e002dbcc05ffb327f43/solution/fields/splitted_datetime.py#L69-L74 | def _to_timezone(self, dt):
"""Takes a naive timezone with an utc value and return it formatted as a
local timezone."""
tz = self._get_tz()
utc_dt = pytz.utc.localize(dt)
return utc_dt.astimezone(tz) | [
"def",
"_to_timezone",
"(",
"self",
",",
"dt",
")",
":",
"tz",
"=",
"self",
".",
"_get_tz",
"(",
")",
"utc_dt",
"=",
"pytz",
".",
"utc",
".",
"localize",
"(",
"dt",
")",
"return",
"utc_dt",
".",
"astimezone",
"(",
"tz",
")"
] | Takes a naive timezone with an utc value and return it formatted as a
local timezone. | [
"Takes",
"a",
"naive",
"timezone",
"with",
"an",
"utc",
"value",
"and",
"return",
"it",
"formatted",
"as",
"a",
"local",
"timezone",
"."
] | python | train | 39 |
boriel/zxbasic | arch/zx48k/backend/__32bit.py | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/backend/__32bit.py#L725-L733 | def _abs32(ins):
""" Absolute value of top of the stack (32 bits in DEHL)
"""
output = _32bit_oper(ins.quad[2])
output.append('call __ABS32')
output.append('push de')
output.append('push hl')
REQUIRES.add('abs32.asm')
return output | [
"def",
"_abs32",
"(",
"ins",
")",
":",
"output",
"=",
"_32bit_oper",
"(",
"ins",
".",
"quad",
"[",
"2",
"]",
")",
"output",
".",
"append",
"(",
"'call __ABS32'",
")",
"output",
".",
"append",
"(",
"'push de'",
")",
"output",
".",
"append",
"(",
"'pus... | Absolute value of top of the stack (32 bits in DEHL) | [
"Absolute",
"value",
"of",
"top",
"of",
"the",
"stack",
"(",
"32",
"bits",
"in",
"DEHL",
")"
] | python | train | 28.333333 |
pyviz/holoviews | holoviews/core/util.py | https://github.com/pyviz/holoviews/blob/ae0dd2f3de448b0ca5e9065aabd6ef8d84c7e655/holoviews/core/util.py#L1190-L1212 | def dimension_sort(odict, kdims, vdims, key_index):
"""
Sorts data by key using usual Python tuple sorting semantics
or sorts in categorical order for any categorical Dimensions.
"""
sortkws = {}
ndims = len(kdims)
dimensions = kdims+vdims
indexes = [(dimensions[i], int(i not in range(nd... | [
"def",
"dimension_sort",
"(",
"odict",
",",
"kdims",
",",
"vdims",
",",
"key_index",
")",
":",
"sortkws",
"=",
"{",
"}",
"ndims",
"=",
"len",
"(",
"kdims",
")",
"dimensions",
"=",
"kdims",
"+",
"vdims",
"indexes",
"=",
"[",
"(",
"dimensions",
"[",
"i... | Sorts data by key using usual Python tuple sorting semantics
or sorts in categorical order for any categorical Dimensions. | [
"Sorts",
"data",
"by",
"key",
"using",
"usual",
"Python",
"tuple",
"sorting",
"semantics",
"or",
"sorts",
"in",
"categorical",
"order",
"for",
"any",
"categorical",
"Dimensions",
"."
] | python | train | 42 |
Othernet-Project/hwd | hwd/storage.py | https://github.com/Othernet-Project/hwd/blob/7f4445bac61aa2305806aa80338e2ce5baa1093c/hwd/storage.py#L114-L122 | def partitions(self):
"""
Iterable containing disk's partition objects. Objects in the iterable
are :py:class:`~hwd.storage.Partition` instances.
"""
if not self._partitions:
self._partitions = [Partition(d, self)
for d in self.device.c... | [
"def",
"partitions",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_partitions",
":",
"self",
".",
"_partitions",
"=",
"[",
"Partition",
"(",
"d",
",",
"self",
")",
"for",
"d",
"in",
"self",
".",
"device",
".",
"children",
"]",
"return",
"self",
... | Iterable containing disk's partition objects. Objects in the iterable
are :py:class:`~hwd.storage.Partition` instances. | [
"Iterable",
"containing",
"disk",
"s",
"partition",
"objects",
".",
"Objects",
"in",
"the",
"iterable",
"are",
":",
"py",
":",
"class",
":",
"~hwd",
".",
"storage",
".",
"Partition",
"instances",
"."
] | python | train | 39.111111 |
artefactual-labs/agentarchives | agentarchives/atom/client.py | https://github.com/artefactual-labs/agentarchives/blob/af19ade56a90c64069cf46b50972fe72b6f10a45/agentarchives/atom/client.py#L692-L747 | def add_child(
self,
parent_slug=None,
title="",
level="",
start_date=None,
end_date=None,
date_expression=None,
notes=[],
):
"""
Adds a new resource component parented within `parent`.
:param str parent_slug: The parent's slug... | [
"def",
"add_child",
"(",
"self",
",",
"parent_slug",
"=",
"None",
",",
"title",
"=",
"\"\"",
",",
"level",
"=",
"\"\"",
",",
"start_date",
"=",
"None",
",",
"end_date",
"=",
"None",
",",
"date_expression",
"=",
"None",
",",
"notes",
"=",
"[",
"]",
",... | Adds a new resource component parented within `parent`.
:param str parent_slug: The parent's slug.
:param str title: A title for the record.
:param str level: The level of description.
:return: The ID of the newly-created record. | [
"Adds",
"a",
"new",
"resource",
"component",
"parented",
"within",
"parent",
"."
] | python | train | 28.517857 |
MSchnei/pyprf_feature | pyprf_feature/analysis/load_config.py | https://github.com/MSchnei/pyprf_feature/blob/49004ede7ae1ddee07a30afe9ce3e2776750805c/pyprf_feature/analysis/load_config.py#L12-L277 | def load_config(strCsvCnfg, lgcTest=False, lgcPrint=True):
"""
Load py_pRF_mapping config file.
Parameters
----------
strCsvCnfg : string
Absolute file path of config file.
lgcTest : Boolean
Whether this is a test (pytest). If yes, absolute path of this function
will be ... | [
"def",
"load_config",
"(",
"strCsvCnfg",
",",
"lgcTest",
"=",
"False",
",",
"lgcPrint",
"=",
"True",
")",
":",
"# Dictionary with config information:",
"dicCnfg",
"=",
"{",
"}",
"# Open file with parameter configuration:",
"# fleConfig = open(strCsvCnfg, 'r')",
"with",
"o... | Load py_pRF_mapping config file.
Parameters
----------
strCsvCnfg : string
Absolute file path of config file.
lgcTest : Boolean
Whether this is a test (pytest). If yes, absolute path of this function
will be prepended to config file paths.
lgcPrint : Boolean
Print co... | [
"Load",
"py_pRF_mapping",
"config",
"file",
"."
] | python | train | 39.349624 |
StackStorm/pybind | pybind/nos/v7_2_0/interface/hundredgigabitethernet/__init__.py | https://github.com/StackStorm/pybind/blob/44c467e71b2b425be63867aba6e6fa28b2cfe7fb/pybind/nos/v7_2_0/interface/hundredgigabitethernet/__init__.py#L1672-L1693 | def _set_bpdu_drop(self, v, load=False):
"""
Setter method for bpdu_drop, mapped from YANG variable /interface/hundredgigabitethernet/bpdu_drop (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_bpdu_drop is considered as a private
method. Backends looking t... | [
"def",
"_set_bpdu_drop",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",
"base... | Setter method for bpdu_drop, mapped from YANG variable /interface/hundredgigabitethernet/bpdu_drop (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_bpdu_drop is considered as a private
method. Backends looking to populate this variable should
do so via calling... | [
"Setter",
"method",
"for",
"bpdu_drop",
"mapped",
"from",
"YANG",
"variable",
"/",
"interface",
"/",
"hundredgigabitethernet",
"/",
"bpdu_drop",
"(",
"container",
")",
"If",
"this",
"variable",
"is",
"read",
"-",
"only",
"(",
"config",
":",
"false",
")",
"in... | python | train | 89.727273 |
qiniu/python-sdk | qiniu/services/compute/qcos_api.py | https://github.com/qiniu/python-sdk/blob/a69fbef4e3e6ea1ebe09f4610a5b18bb2c17de59/qiniu/services/compute/qcos_api.py#L623-L638 | def disable_ap_port(self, apid, port):
"""临时关闭接入点端口
临时关闭接入点端口,仅对公网域名,公网ip有效。
Args:
- apid: 接入点ID
- port: 要设置的端口号
Returns:
返回一个tuple对象,其格式为(<result>, <ResponseInfo>)
- result 成功返回空dict{},失败返回{"error": "<errMsg string>"}
... | [
"def",
"disable_ap_port",
"(",
"self",
",",
"apid",
",",
"port",
")",
":",
"url",
"=",
"'{0}/v3/aps/{1}/{2}/disable'",
".",
"format",
"(",
"self",
".",
"host",
",",
"apid",
",",
"port",
")",
"return",
"self",
".",
"__post",
"(",
"url",
")"
] | 临时关闭接入点端口
临时关闭接入点端口,仅对公网域名,公网ip有效。
Args:
- apid: 接入点ID
- port: 要设置的端口号
Returns:
返回一个tuple对象,其格式为(<result>, <ResponseInfo>)
- result 成功返回空dict{},失败返回{"error": "<errMsg string>"}
- ResponseInfo 请求的Response信息 | [
"临时关闭接入点端口"
] | python | train | 28.5 |
ladybug-tools/ladybug | ladybug/datatype/mass.py | https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/datatype/mass.py#L59-L66 | def to_si(self, values, from_unit):
"""Return values in SI and the units to which the values have been converted."""
if from_unit in self.si_units:
return values, from_unit
elif from_unit == 'ton':
return self.to_unit(values, 'tonne', from_unit), 'tonne'
else:
... | [
"def",
"to_si",
"(",
"self",
",",
"values",
",",
"from_unit",
")",
":",
"if",
"from_unit",
"in",
"self",
".",
"si_units",
":",
"return",
"values",
",",
"from_unit",
"elif",
"from_unit",
"==",
"'ton'",
":",
"return",
"self",
".",
"to_unit",
"(",
"values",... | Return values in SI and the units to which the values have been converted. | [
"Return",
"values",
"in",
"SI",
"and",
"the",
"units",
"to",
"which",
"the",
"values",
"have",
"been",
"converted",
"."
] | python | train | 46.5 |
dmlc/gluon-nlp | src/gluonnlp/model/sampled_block.py | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/sampled_block.py#L52-L95 | def hybrid_forward(self, F, x, sampled_values, label, w_all, b_all):
"""Forward computation."""
sampled_candidates, expected_count_sampled, expected_count_true = sampled_values
# (num_sampled, in_unit)
w_sampled = w_all.slice(begin=(0, 0), end=(self._num_sampled, None))
w_true = ... | [
"def",
"hybrid_forward",
"(",
"self",
",",
"F",
",",
"x",
",",
"sampled_values",
",",
"label",
",",
"w_all",
",",
"b_all",
")",
":",
"sampled_candidates",
",",
"expected_count_sampled",
",",
"expected_count_true",
"=",
"sampled_values",
"# (num_sampled, in_unit)",
... | Forward computation. | [
"Forward",
"computation",
"."
] | python | train | 47.272727 |
etingof/pyasn1 | pyasn1/type/namedtype.py | https://github.com/etingof/pyasn1/blob/25cf116ef8d11bb0e08454c0f3635c9f4002c2d6/pyasn1/type/namedtype.py#L406-L437 | def getPositionNearType(self, tagSet, idx):
"""Return the closest field position where given ASN.1 type is allowed.
Some ASN.1 serialisation allow for skipping optional and defaulted fields.
Some constructed ASN.1 types allow reordering of the fields. When recovering
such objects it may... | [
"def",
"getPositionNearType",
"(",
"self",
",",
"tagSet",
",",
"idx",
")",
":",
"try",
":",
"return",
"idx",
"+",
"self",
".",
"__ambiguousTypes",
"[",
"idx",
"]",
".",
"getPositionByType",
"(",
"tagSet",
")",
"except",
"KeyError",
":",
"raise",
"error",
... | Return the closest field position where given ASN.1 type is allowed.
Some ASN.1 serialisation allow for skipping optional and defaulted fields.
Some constructed ASN.1 types allow reordering of the fields. When recovering
such objects it may be important to know at which field position, in field... | [
"Return",
"the",
"closest",
"field",
"position",
"where",
"given",
"ASN",
".",
"1",
"type",
"is",
"allowed",
"."
] | python | train | 35.96875 |
PythonSanSebastian/docstamp | docstamp/file_utils.py | https://github.com/PythonSanSebastian/docstamp/blob/b43808f2e15351b0b2f0b7eade9c7ef319c9e646/docstamp/file_utils.py#L138-L170 | def csv_to_json(csv_filepath, json_filepath, fieldnames, ignore_first_line=True):
""" Convert a CSV file in `csv_filepath` into a JSON file in `json_filepath`.
Parameters
----------
csv_filepath: str
Path to the input CSV file.
json_filepath: str
Path to the output JSON file. Will ... | [
"def",
"csv_to_json",
"(",
"csv_filepath",
",",
"json_filepath",
",",
"fieldnames",
",",
"ignore_first_line",
"=",
"True",
")",
":",
"import",
"csv",
"import",
"json",
"csvfile",
"=",
"open",
"(",
"csv_filepath",
",",
"'r'",
")",
"jsonfile",
"=",
"open",
"("... | Convert a CSV file in `csv_filepath` into a JSON file in `json_filepath`.
Parameters
----------
csv_filepath: str
Path to the input CSV file.
json_filepath: str
Path to the output JSON file. Will be overwritten if exists.
fieldnames: List[str]
Names of the fields in the CS... | [
"Convert",
"a",
"CSV",
"file",
"in",
"csv_filepath",
"into",
"a",
"JSON",
"file",
"in",
"json_filepath",
"."
] | python | test | 23.151515 |
ThomasChiroux/attowiki | src/attowiki/rst_directives.py | https://github.com/ThomasChiroux/attowiki/blob/6c93c420305490d324fdc95a7b40b2283a222183/src/attowiki/rst_directives.py#L30-L49 | def add_node(node, **kwds):
"""add_node from Sphinx
"""
nodes._add_node_class_names([node.__name__])
for key, val in kwds.iteritems():
try:
visit, depart = val
except ValueError:
raise ValueError('Value for key %r must be a '
'(vis... | [
"def",
"add_node",
"(",
"node",
",",
"*",
"*",
"kwds",
")",
":",
"nodes",
".",
"_add_node_class_names",
"(",
"[",
"node",
".",
"__name__",
"]",
")",
"for",
"key",
",",
"val",
"in",
"kwds",
".",
"iteritems",
"(",
")",
":",
"try",
":",
"visit",
",",
... | add_node from Sphinx | [
"add_node",
"from",
"Sphinx"
] | python | train | 38.95 |
tango-controls/pytango | tango/asyncio_executor.py | https://github.com/tango-controls/pytango/blob/9cf78c517c9cdc1081ff6d080a9646a740cc1d36/tango/asyncio_executor.py#L88-L94 | def execute(self, fn, *args, **kwargs):
"""Execute an operation and return the result."""
if self.in_executor_context():
corofn = asyncio.coroutine(lambda: fn(*args, **kwargs))
return corofn()
future = self.submit(fn, *args, **kwargs)
return future.result() | [
"def",
"execute",
"(",
"self",
",",
"fn",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"in_executor_context",
"(",
")",
":",
"corofn",
"=",
"asyncio",
".",
"coroutine",
"(",
"lambda",
":",
"fn",
"(",
"*",
"args",
",",
"... | Execute an operation and return the result. | [
"Execute",
"an",
"operation",
"and",
"return",
"the",
"result",
"."
] | python | train | 43.857143 |
boriel/zxbasic | arch/zx48k/optimizer.py | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/optimizer.py#L641-L653 | def rl(self, r):
""" Like the above, bus uses carry
"""
if self.C is None or not is_number(self.regs[r]):
self.set(r, None)
self.set_flag(None)
return
self.rlc(r)
tmp = self.C
v_ = self.getv(self.regs[r])
self.C = v_ & 1
... | [
"def",
"rl",
"(",
"self",
",",
"r",
")",
":",
"if",
"self",
".",
"C",
"is",
"None",
"or",
"not",
"is_number",
"(",
"self",
".",
"regs",
"[",
"r",
"]",
")",
":",
"self",
".",
"set",
"(",
"r",
",",
"None",
")",
"self",
".",
"set_flag",
"(",
"... | Like the above, bus uses carry | [
"Like",
"the",
"above",
"bus",
"uses",
"carry"
] | python | train | 26.692308 |
selenol/selenol-python | selenol_python/params.py | https://github.com/selenol/selenol-python/blob/53775fdfc95161f4aca350305cb3459e6f2f808d/selenol_python/params.py#L40-L51 | def _get_value(data_structure, key):
"""Return the value of a data_structure given a path.
:param data_structure: Dictionary, list or subscriptable object.
:param key: Array with the defined path ordered.
"""
if len(key) == 0:
raise KeyError()
value = data_structure[key[0]]
if len(k... | [
"def",
"_get_value",
"(",
"data_structure",
",",
"key",
")",
":",
"if",
"len",
"(",
"key",
")",
"==",
"0",
":",
"raise",
"KeyError",
"(",
")",
"value",
"=",
"data_structure",
"[",
"key",
"[",
"0",
"]",
"]",
"if",
"len",
"(",
"key",
")",
">",
"1",... | Return the value of a data_structure given a path.
:param data_structure: Dictionary, list or subscriptable object.
:param key: Array with the defined path ordered. | [
"Return",
"the",
"value",
"of",
"a",
"data_structure",
"given",
"a",
"path",
"."
] | python | train | 31.333333 |
madprime/vcf2clinvar | vcf2clinvar/clinvar.py | https://github.com/madprime/vcf2clinvar/blob/d5bbf6df2902c6cabe9ef1894cfac527e90fa32a/vcf2clinvar/clinvar.py#L91-L122 | def _parse_allele_data(self):
"""Parse alleles for ClinVar VCF, overrides parent method."""
# Get allele frequencies if they exist.
pref_freq, frequencies = self._parse_frequencies()
info_clnvar_single_tags = ['ALLELEID', 'CLNSIG', 'CLNHGVS']
cln_data = {x.lower(): self.info[x]... | [
"def",
"_parse_allele_data",
"(",
"self",
")",
":",
"# Get allele frequencies if they exist.",
"pref_freq",
",",
"frequencies",
"=",
"self",
".",
"_parse_frequencies",
"(",
")",
"info_clnvar_single_tags",
"=",
"[",
"'ALLELEID'",
",",
"'CLNSIG'",
",",
"'CLNHGVS'",
"]",... | Parse alleles for ClinVar VCF, overrides parent method. | [
"Parse",
"alleles",
"for",
"ClinVar",
"VCF",
"overrides",
"parent",
"method",
"."
] | python | valid | 39.78125 |
ynop/audiomate | audiomate/corpus/subset/selection.py | https://github.com/ynop/audiomate/blob/61727920b23a708293c3d526fa3000d4de9c6c21/audiomate/corpus/subset/selection.py#L107-L141 | def random_subsets(self, relative_sizes, by_duration=False, balance_labels=False, label_list_ids=None):
"""
Create a bunch of subsets with the given sizes relative to the size or duration of the full corpus.
Basically the same as calling ``random_subset`` or ``random_subset_by_duration`` multipl... | [
"def",
"random_subsets",
"(",
"self",
",",
"relative_sizes",
",",
"by_duration",
"=",
"False",
",",
"balance_labels",
"=",
"False",
",",
"label_list_ids",
"=",
"None",
")",
":",
"resulting_sets",
"=",
"{",
"}",
"next_bigger_subset",
"=",
"self",
".",
"corpus",... | Create a bunch of subsets with the given sizes relative to the size or duration of the full corpus.
Basically the same as calling ``random_subset`` or ``random_subset_by_duration`` multiple times
with different values. But this method makes sure that every subset contains only utterances,
that a... | [
"Create",
"a",
"bunch",
"of",
"subsets",
"with",
"the",
"given",
"sizes",
"relative",
"to",
"the",
"size",
"or",
"duration",
"of",
"the",
"full",
"corpus",
".",
"Basically",
"the",
"same",
"as",
"calling",
"random_subset",
"or",
"random_subset_by_duration",
"m... | python | train | 55.685714 |
edx/edx-enterprise | enterprise/utils.py | https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/utils.py#L414-L443 | def get_course_track_selection_url(course_run, query_parameters):
"""
Return track selection url for the given course.
Arguments:
course_run (dict): A dictionary containing course run metadata.
query_parameters (dict): A dictionary containing query parameters to be added to course selection... | [
"def",
"get_course_track_selection_url",
"(",
"course_run",
",",
"query_parameters",
")",
":",
"try",
":",
"course_root",
"=",
"reverse",
"(",
"'course_modes_choose'",
",",
"kwargs",
"=",
"{",
"'course_id'",
":",
"course_run",
"[",
"'key'",
"]",
"}",
")",
"excep... | Return track selection url for the given course.
Arguments:
course_run (dict): A dictionary containing course run metadata.
query_parameters (dict): A dictionary containing query parameters to be added to course selection url.
Raises:
(KeyError): Raised when course run dict does not ha... | [
"Return",
"track",
"selection",
"url",
"for",
"the",
"given",
"course",
"."
] | python | valid | 29.566667 |
UpCloudLtd/upcloud-python-api | upcloud_api/server.py | https://github.com/UpCloudLtd/upcloud-python-api/blob/954b0ad7c4b932b2be31a95d88975f6b0eeac8ed/upcloud_api/server.py#L272-L278 | def remove_tags(self, tags):
"""
Add tags to a server. Accepts tags as strings or Tag objects.
"""
if self.cloud_manager.remove_tags(self, tags):
new_tags = [tag for tag in self.tags if tag not in tags]
object.__setattr__(self, 'tags', new_tags) | [
"def",
"remove_tags",
"(",
"self",
",",
"tags",
")",
":",
"if",
"self",
".",
"cloud_manager",
".",
"remove_tags",
"(",
"self",
",",
"tags",
")",
":",
"new_tags",
"=",
"[",
"tag",
"for",
"tag",
"in",
"self",
".",
"tags",
"if",
"tag",
"not",
"in",
"t... | Add tags to a server. Accepts tags as strings or Tag objects. | [
"Add",
"tags",
"to",
"a",
"server",
".",
"Accepts",
"tags",
"as",
"strings",
"or",
"Tag",
"objects",
"."
] | python | train | 42.142857 |
astropy/pyregion | pyregion/region_to_filter.py | https://github.com/astropy/pyregion/blob/913af7ea4917855cb2e43d5086d1c8dd99c31363/pyregion/region_to_filter.py#L6-L117 | def as_region_filter(shape_list, origin=1):
"""
Often, the regions files implicitly assume the lower-left corner
of the image as a coordinate (1,1). However, the python convetion
is that the array index starts from 0. By default (origin = 1),
coordinates of the returned mpl artists have coordinate s... | [
"def",
"as_region_filter",
"(",
"shape_list",
",",
"origin",
"=",
"1",
")",
":",
"filter_list",
"=",
"[",
"]",
"for",
"shape",
"in",
"shape_list",
":",
"if",
"shape",
".",
"name",
"==",
"\"composite\"",
":",
"continue",
"if",
"shape",
".",
"name",
"==",
... | Often, the regions files implicitly assume the lower-left corner
of the image as a coordinate (1,1). However, the python convetion
is that the array index starts from 0. By default (origin = 1),
coordinates of the returned mpl artists have coordinate shifted by
(1, 1). If you do not want this shift, use... | [
"Often",
"the",
"regions",
"files",
"implicitly",
"assume",
"the",
"lower",
"-",
"left",
"corner",
"of",
"the",
"image",
"as",
"a",
"coordinate",
"(",
"1",
"1",
")",
".",
"However",
"the",
"python",
"convetion",
"is",
"that",
"the",
"array",
"index",
"st... | python | train | 38.25 |
rstoneback/pysat | pysat/instruments/cosmic2013_gps.py | https://github.com/rstoneback/pysat/blob/4ae1afd80e15e4449397d39dce8c3e969c32c422/pysat/instruments/cosmic2013_gps.py#L172-L224 | def load_files(files, tag=None, sat_id=None, altitude_bin=None):
'''Loads a list of COSMIC data files, supplied by user.
Returns a list of dicts, a dict for each file.
'''
output = [None]*len(files)
drop_idx = []
for (i,file) in enumerate(files):
try:
#data = net... | [
"def",
"load_files",
"(",
"files",
",",
"tag",
"=",
"None",
",",
"sat_id",
"=",
"None",
",",
"altitude_bin",
"=",
"None",
")",
":",
"output",
"=",
"[",
"None",
"]",
"*",
"len",
"(",
"files",
")",
"drop_idx",
"=",
"[",
"]",
"for",
"(",
"i",
",",
... | Loads a list of COSMIC data files, supplied by user.
Returns a list of dicts, a dict for each file. | [
"Loads",
"a",
"list",
"of",
"COSMIC",
"data",
"files",
"supplied",
"by",
"user",
".",
"Returns",
"a",
"list",
"of",
"dicts",
"a",
"dict",
"for",
"each",
"file",
"."
] | python | train | 38.056604 |
uuazed/numerapi | numerapi/numerapi.py | https://github.com/uuazed/numerapi/blob/fc9dcc53b32ede95bfda1ceeb62aec1d67d26697/numerapi/numerapi.py#L412-L435 | def get_nmr_prize_pool(self, round_num=0, tournament=1):
"""Get NMR prize pool for the given round and tournament.
Args:
round_num (int, optional): The round you are interested in,
defaults to current round.
tournament (int, optional): ID of the tournament, defau... | [
"def",
"get_nmr_prize_pool",
"(",
"self",
",",
"round_num",
"=",
"0",
",",
"tournament",
"=",
"1",
")",
":",
"tournaments",
"=",
"self",
".",
"get_competitions",
"(",
"tournament",
")",
"tournaments",
".",
"sort",
"(",
"key",
"=",
"lambda",
"t",
":",
"t"... | Get NMR prize pool for the given round and tournament.
Args:
round_num (int, optional): The round you are interested in,
defaults to current round.
tournament (int, optional): ID of the tournament, defaults to 1
Returns:
decimal.Decimal: prize pool i... | [
"Get",
"NMR",
"prize",
"pool",
"for",
"the",
"given",
"round",
"and",
"tournament",
"."
] | python | train | 36.458333 |
JarryShaw/DictDumper | src/json.py | https://github.com/JarryShaw/DictDumper/blob/430efcfdff18bb2421c3f27059ff94c93e621483/src/json.py#L237-L253 | def _append_bytes(self, value, _file): # pylint: disable=no-self-use
"""Call this function to write bytes contents.
Keyword arguments:
* value - dict, content to be dumped
* _file - FileIO, output file
"""
# binascii.b2a_base64(value) -> plistlib.Data
#... | [
"def",
"_append_bytes",
"(",
"self",
",",
"value",
",",
"_file",
")",
":",
"# pylint: disable=no-self-use",
"# binascii.b2a_base64(value) -> plistlib.Data",
"# binascii.a2b_base64(Data) -> value(bytes)",
"_text",
"=",
"' '",
".",
"join",
"(",
"textwrap",
".",
"wrap",
"(",... | Call this function to write bytes contents.
Keyword arguments:
* value - dict, content to be dumped
* _file - FileIO, output file | [
"Call",
"this",
"function",
"to",
"write",
"bytes",
"contents",
"."
] | python | train | 39 |
jplusplus/statscraper | statscraper/base_scraper.py | https://github.com/jplusplus/statscraper/blob/932ec048b23d15b3dbdaf829facc55fd78ec0109/statscraper/base_scraper.py#L493-L497 | def shape(self):
"""Compute the shape of the dataset as (rows, cols)."""
if not self.data:
return (0, 0)
return (len(self.data), len(self.dimensions)) | [
"def",
"shape",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"data",
":",
"return",
"(",
"0",
",",
"0",
")",
"return",
"(",
"len",
"(",
"self",
".",
"data",
")",
",",
"len",
"(",
"self",
".",
"dimensions",
")",
")"
] | Compute the shape of the dataset as (rows, cols). | [
"Compute",
"the",
"shape",
"of",
"the",
"dataset",
"as",
"(",
"rows",
"cols",
")",
"."
] | python | train | 36.4 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.