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 |
|---|---|---|---|---|---|---|---|---|---|
PyFilesystem/pyfilesystem2 | fs/ftpfs.py | https://github.com/PyFilesystem/pyfilesystem2/blob/047f3593f297d1442194cda3da7a7335bcc9c14a/fs/ftpfs.py#L397-L407 | def _parse_features(cls, feat_response):
# type: (Text) -> Dict[Text, Text]
"""Parse a dict of features from FTP feat response.
"""
features = {}
if feat_response.split("-")[0] == "211":
for line in feat_response.splitlines():
if line.startswith(" "):
... | [
"def",
"_parse_features",
"(",
"cls",
",",
"feat_response",
")",
":",
"# type: (Text) -> Dict[Text, Text]",
"features",
"=",
"{",
"}",
"if",
"feat_response",
".",
"split",
"(",
"\"-\"",
")",
"[",
"0",
"]",
"==",
"\"211\"",
":",
"for",
"line",
"in",
"feat_res... | Parse a dict of features from FTP feat response. | [
"Parse",
"a",
"dict",
"of",
"features",
"from",
"FTP",
"feat",
"response",
"."
] | python | train | 39.545455 |
sosy-lab/benchexec | benchexec/runexecutor.py | https://github.com/sosy-lab/benchexec/blob/44428f67f41384c03aea13e7e25f884764653617/benchexec/runexecutor.py#L408-L432 | def _kill_process(self, pid, cgroups=None, sig=signal.SIGKILL):
"""
Try to send signal to given process, either directly of with sudo.
Because we cannot send signals to the sudo process itself,
this method checks whether the target is the sudo process
and redirects the signal to ... | [
"def",
"_kill_process",
"(",
"self",
",",
"pid",
",",
"cgroups",
"=",
"None",
",",
"sig",
"=",
"signal",
".",
"SIGKILL",
")",
":",
"if",
"self",
".",
"_user",
"is",
"not",
"None",
":",
"if",
"not",
"cgroups",
":",
"cgroups",
"=",
"find_cgroups_of_proce... | Try to send signal to given process, either directly of with sudo.
Because we cannot send signals to the sudo process itself,
this method checks whether the target is the sudo process
and redirects the signal to sudo's child in this case. | [
"Try",
"to",
"send",
"signal",
"to",
"given",
"process",
"either",
"directly",
"of",
"with",
"sudo",
".",
"Because",
"we",
"cannot",
"send",
"signals",
"to",
"the",
"sudo",
"process",
"itself",
"this",
"method",
"checks",
"whether",
"the",
"target",
"is",
... | python | train | 45.4 |
ylogx/far | far/main.py | https://github.com/ylogx/far/blob/8d3b28edab10ada2edd7cb2b20c655e00fa3f8e4/far/main.py#L45-L63 | def main():
""" Main
"""
args, otherthings = parse_known_args()
if args.version:
print_version()
return 0
verbosity = 0
if args.verbose:
verbosity = 1
far = Far(verbosity=verbosity)
if args.dry_run:
far.dry_run(old=args.old)
else:
far.find_... | [
"def",
"main",
"(",
")",
":",
"args",
",",
"otherthings",
"=",
"parse_known_args",
"(",
")",
"if",
"args",
".",
"version",
":",
"print_version",
"(",
")",
"return",
"0",
"verbosity",
"=",
"0",
"if",
"args",
".",
"verbose",
":",
"verbosity",
"=",
"1",
... | Main | [
"Main"
] | python | train | 17.947368 |
iotile/coretools | iotilesensorgraph/iotile/sg/walker.py | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/walker.py#L228-L238 | def skip_all(self):
"""Skip all readings in this walker."""
storage, streaming = self.engine.count()
if self.selector.output:
self.offset = streaming
else:
self.offset = storage
self._count = 0 | [
"def",
"skip_all",
"(",
"self",
")",
":",
"storage",
",",
"streaming",
"=",
"self",
".",
"engine",
".",
"count",
"(",
")",
"if",
"self",
".",
"selector",
".",
"output",
":",
"self",
".",
"offset",
"=",
"streaming",
"else",
":",
"self",
".",
"offset",... | Skip all readings in this walker. | [
"Skip",
"all",
"readings",
"in",
"this",
"walker",
"."
] | python | train | 22.727273 |
WZBSocialScienceCenter/tmtoolkit | tmtoolkit/topicmod/model_stats.py | https://github.com/WZBSocialScienceCenter/tmtoolkit/blob/ca8b9d072e37ccc82b533f47d48bd9755722305b/tmtoolkit/topicmod/model_stats.py#L180-L187 | def get_most_relevant_words_for_topic(vocab, rel_mat, topic, n=None):
"""
Get words from `vocab` for `topic` ordered by most to least relevance (Sievert and Shirley 2014) using the relevance
matrix `rel_mat` obtained from `get_topic_word_relevance()`.
Optionally only return the `n` most relevant words.
... | [
"def",
"get_most_relevant_words_for_topic",
"(",
"vocab",
",",
"rel_mat",
",",
"topic",
",",
"n",
"=",
"None",
")",
":",
"_check_relevant_words_for_topic_args",
"(",
"vocab",
",",
"rel_mat",
",",
"topic",
")",
"return",
"_words_by_score",
"(",
"vocab",
",",
"rel... | Get words from `vocab` for `topic` ordered by most to least relevance (Sievert and Shirley 2014) using the relevance
matrix `rel_mat` obtained from `get_topic_word_relevance()`.
Optionally only return the `n` most relevant words. | [
"Get",
"words",
"from",
"vocab",
"for",
"topic",
"ordered",
"by",
"most",
"to",
"least",
"relevance",
"(",
"Sievert",
"and",
"Shirley",
"2014",
")",
"using",
"the",
"relevance",
"matrix",
"rel_mat",
"obtained",
"from",
"get_topic_word_relevance",
"()",
".",
"O... | python | train | 57.5 |
dswah/pyGAM | pygam/pygam.py | https://github.com/dswah/pyGAM/blob/b3e5c3cd580f0a3ad69f9372861624f67760c325/pygam/pygam.py#L2604-L2654 | def _exposure_to_weights(self, y, exposure=None, weights=None):
"""simple tool to create a common API
Parameters
----------
y : array-like, shape (n_samples,)
Target values (integers in classification, real numbers in
regression)
For classification, l... | [
"def",
"_exposure_to_weights",
"(",
"self",
",",
"y",
",",
"exposure",
"=",
"None",
",",
"weights",
"=",
"None",
")",
":",
"y",
"=",
"y",
".",
"ravel",
"(",
")",
"if",
"exposure",
"is",
"not",
"None",
":",
"exposure",
"=",
"np",
".",
"array",
"(",
... | simple tool to create a common API
Parameters
----------
y : array-like, shape (n_samples,)
Target values (integers in classification, real numbers in
regression)
For classification, labels must correspond to classes.
exposure : array-like shape (n_sa... | [
"simple",
"tool",
"to",
"create",
"a",
"common",
"API"
] | python | train | 35.117647 |
CTPUG/wafer | wafer/compare/admin.py | https://github.com/CTPUG/wafer/blob/a20af3c399267f76373dc342f4d542a9bc457c35/wafer/compare/admin.py#L156-L177 | def comparelist_view(self, request, object_id, extra_context=None):
"""Allow selecting versions to compare."""
opts = self.model._meta
object_id = unquote(object_id)
current = get_object_or_404(self.model, pk=object_id)
# As done by reversion's history_view
action_list = ... | [
"def",
"comparelist_view",
"(",
"self",
",",
"request",
",",
"object_id",
",",
"extra_context",
"=",
"None",
")",
":",
"opts",
"=",
"self",
".",
"model",
".",
"_meta",
"object_id",
"=",
"unquote",
"(",
"object_id",
")",
"current",
"=",
"get_object_or_404",
... | Allow selecting versions to compare. | [
"Allow",
"selecting",
"versions",
"to",
"compare",
"."
] | python | train | 51.136364 |
Robpol86/libnl | libnl/msg.py | https://github.com/Robpol86/libnl/blob/274e9fdaa39822d06ef70b799ed4a95937a4d923/libnl/msg.py#L540-L551 | def print_genl_hdr(ofd, start):
"""https://github.com/thom311/libnl/blob/libnl3_2_25/lib/msg.c#L821.
Positional arguments:
ofd -- function to call with arguments similar to `logging.debug`.
start -- bytearray() or bytearray_ptr() instance.
"""
ghdr = genlmsghdr(start)
ofd(' [GENERIC NETLIN... | [
"def",
"print_genl_hdr",
"(",
"ofd",
",",
"start",
")",
":",
"ghdr",
"=",
"genlmsghdr",
"(",
"start",
")",
"ofd",
"(",
"' [GENERIC NETLINK HEADER] %d octets'",
",",
"GENL_HDRLEN",
")",
"ofd",
"(",
"' .cmd = %d'",
",",
"ghdr",
".",
"cmd",
")",
"ofd",
"(",... | https://github.com/thom311/libnl/blob/libnl3_2_25/lib/msg.c#L821.
Positional arguments:
ofd -- function to call with arguments similar to `logging.debug`.
start -- bytearray() or bytearray_ptr() instance. | [
"https",
":",
"//",
"github",
".",
"com",
"/",
"thom311",
"/",
"libnl",
"/",
"blob",
"/",
"libnl3_2_25",
"/",
"lib",
"/",
"msg",
".",
"c#L821",
"."
] | python | train | 38.75 |
e3krisztian/pyrene | pyrene/shell.py | https://github.com/e3krisztian/pyrene/blob/ad9f2fb979f06930399c9c8214c3fe3c2d6efa06/pyrene/shell.py#L232-L244 | def do_http_repo(self, repo):
'''
[Re]define REPO as http package repository.
http_repo REPO
'''
self.abort_on_missing_effective_repo_name(repo, 'http_repo')
repo_name = self.get_effective_repo_name(repo)
try:
self.network.set(repo_name, REPO.TYPE, RE... | [
"def",
"do_http_repo",
"(",
"self",
",",
"repo",
")",
":",
"self",
".",
"abort_on_missing_effective_repo_name",
"(",
"repo",
",",
"'http_repo'",
")",
"repo_name",
"=",
"self",
".",
"get_effective_repo_name",
"(",
"repo",
")",
"try",
":",
"self",
".",
"network"... | [Re]define REPO as http package repository.
http_repo REPO | [
"[",
"Re",
"]",
"define",
"REPO",
"as",
"http",
"package",
"repository",
"."
] | python | train | 34.692308 |
mathandy/svgpathtools | svgpathtools/path.py | https://github.com/mathandy/svgpathtools/blob/fd7348a1dfd88b65ea61da02325c6605aedf8c4f/svgpathtools/path.py#L568-L571 | def point(self, t):
"""returns the coordinates of the Bezier curve evaluated at t."""
distance = self.end - self.start
return self.start + distance*t | [
"def",
"point",
"(",
"self",
",",
"t",
")",
":",
"distance",
"=",
"self",
".",
"end",
"-",
"self",
".",
"start",
"return",
"self",
".",
"start",
"+",
"distance",
"*",
"t"
] | returns the coordinates of the Bezier curve evaluated at t. | [
"returns",
"the",
"coordinates",
"of",
"the",
"Bezier",
"curve",
"evaluated",
"at",
"t",
"."
] | python | train | 42.5 |
Frzk/Ellis | ellis/action.py | https://github.com/Frzk/Ellis/blob/39ce8987cbc503354cf1f45927344186a8b18363/ellis/action.py#L143-L213 | def from_string(cls, action_str):
"""
Creates a new Action instance from the given string.
The given string **must** match one of those patterns:
* module.function
* module.function()
* module.function(arg1=value1, arg2=value2)
Any other form will t... | [
"def",
"from_string",
"(",
"cls",
",",
"action_str",
")",
":",
"args",
"=",
"{",
"}",
"try",
":",
"mod_obj",
"=",
"ast",
".",
"parse",
"(",
"action_str",
")",
"except",
"(",
"SyntaxError",
",",
"ValueError",
")",
"as",
"e",
":",
"raise",
"e",
"else",... | Creates a new Action instance from the given string.
The given string **must** match one of those patterns:
* module.function
* module.function()
* module.function(arg1=value1, arg2=value2)
Any other form will trigger an Exception.
The function parses the ... | [
"Creates",
"a",
"new",
"Action",
"instance",
"from",
"the",
"given",
"string",
"."
] | python | train | 37.647887 |
PredixDev/predixpy | predix/admin/app.py | https://github.com/PredixDev/predixpy/blob/a0cb34cf40f716229351bb6d90d6ecace958c81f/predix/admin/app.py#L222-L250 | def get_service_marketplace(self, available=True, unavailable=False,
deprecated=False):
"""
Returns a list of service names. Can return all services, just
those supported by PredixPy, or just those not yet supported by
PredixPy.
:param available: Return the services... | [
"def",
"get_service_marketplace",
"(",
"self",
",",
"available",
"=",
"True",
",",
"unavailable",
"=",
"False",
",",
"deprecated",
"=",
"False",
")",
":",
"supported",
"=",
"set",
"(",
"self",
".",
"supported",
".",
"keys",
"(",
")",
")",
"all_services",
... | Returns a list of service names. Can return all services, just
those supported by PredixPy, or just those not yet supported by
PredixPy.
:param available: Return the services that are
available in PredixPy. (Defaults to True)
:param unavailable: Return the services that a... | [
"Returns",
"a",
"list",
"of",
"service",
"names",
".",
"Can",
"return",
"all",
"services",
"just",
"those",
"supported",
"by",
"PredixPy",
"or",
"just",
"those",
"not",
"yet",
"supported",
"by",
"PredixPy",
"."
] | python | train | 34.586207 |
sernst/cauldron | cauldron/session/reloading.py | https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/session/reloading.py#L38-L67 | def do_reload(module: types.ModuleType, newer_than: int) -> bool:
"""
Executes the reload of the specified module if the source file that it was
loaded from was updated more recently than the specified time
:param module:
A module object to be reloaded
:param newer_than:
The time in... | [
"def",
"do_reload",
"(",
"module",
":",
"types",
".",
"ModuleType",
",",
"newer_than",
":",
"int",
")",
"->",
"bool",
":",
"path",
"=",
"getattr",
"(",
"module",
",",
"'__file__'",
")",
"directory",
"=",
"getattr",
"(",
"module",
",",
"'__path__'",
",",
... | Executes the reload of the specified module if the source file that it was
loaded from was updated more recently than the specified time
:param module:
A module object to be reloaded
:param newer_than:
The time in seconds since epoch that should be used to determine if
the module ne... | [
"Executes",
"the",
"reload",
"of",
"the",
"specified",
"module",
"if",
"the",
"source",
"file",
"that",
"it",
"was",
"loaded",
"from",
"was",
"updated",
"more",
"recently",
"than",
"the",
"specified",
"time"
] | python | train | 31.7 |
sony/nnabla | python/src/nnabla/models/utils.py | https://github.com/sony/nnabla/blob/aaf3d33b7cbb38f2a03aa754178ba8f7c8481320/python/src/nnabla/models/utils.py#L23-L30 | def get_model_home():
'''
Returns a root folder path for downloading models.
'''
d = os.path.join(get_data_home(), 'nnp_models')
if not os.path.isdir(d):
os.makedirs(d)
return d | [
"def",
"get_model_home",
"(",
")",
":",
"d",
"=",
"os",
".",
"path",
".",
"join",
"(",
"get_data_home",
"(",
")",
",",
"'nnp_models'",
")",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"d",
")",
":",
"os",
".",
"makedirs",
"(",
"d",
")",
... | Returns a root folder path for downloading models. | [
"Returns",
"a",
"root",
"folder",
"path",
"for",
"downloading",
"models",
"."
] | python | train | 25.25 |
bwohlberg/sporco | sporco/util.py | https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/util.py#L56-L73 | def ntpl2array(ntpl):
"""
Convert a :func:`collections.namedtuple` object to a :class:`numpy.ndarray`
object that can be saved using :func:`numpy.savez`.
Parameters
----------
ntpl : collections.namedtuple object
Named tuple object to be converted to ndarray
Returns
-------
a... | [
"def",
"ntpl2array",
"(",
"ntpl",
")",
":",
"return",
"np",
".",
"asarray",
"(",
"(",
"np",
".",
"hstack",
"(",
"[",
"col",
"for",
"col",
"in",
"ntpl",
"]",
")",
",",
"ntpl",
".",
"_fields",
",",
"ntpl",
".",
"__class__",
".",
"__name__",
")",
")... | Convert a :func:`collections.namedtuple` object to a :class:`numpy.ndarray`
object that can be saved using :func:`numpy.savez`.
Parameters
----------
ntpl : collections.namedtuple object
Named tuple object to be converted to ndarray
Returns
-------
arr : ndarray
Array represent... | [
"Convert",
"a",
":",
"func",
":",
"collections",
".",
"namedtuple",
"object",
"to",
"a",
":",
"class",
":",
"numpy",
".",
"ndarray",
"object",
"that",
"can",
"be",
"saved",
"using",
":",
"func",
":",
"numpy",
".",
"savez",
"."
] | python | train | 27.333333 |
ipazc/mtcnn | mtcnn/network.py | https://github.com/ipazc/mtcnn/blob/17029fe453a435f50c472ae2fd1c493341b5ede3/mtcnn/network.py#L99-L108 | def feed(self, image):
"""
Feeds the network with an image
:param image: image (perhaps loaded with CV2)
:return: network result
"""
network_name = self.__class__.__name__.lower()
with tf.variable_scope(network_name):
return self._feed(image) | [
"def",
"feed",
"(",
"self",
",",
"image",
")",
":",
"network_name",
"=",
"self",
".",
"__class__",
".",
"__name__",
".",
"lower",
"(",
")",
"with",
"tf",
".",
"variable_scope",
"(",
"network_name",
")",
":",
"return",
"self",
".",
"_feed",
"(",
"image"... | Feeds the network with an image
:param image: image (perhaps loaded with CV2)
:return: network result | [
"Feeds",
"the",
"network",
"with",
"an",
"image",
":",
"param",
"image",
":",
"image",
"(",
"perhaps",
"loaded",
"with",
"CV2",
")",
":",
"return",
":",
"network",
"result"
] | python | train | 30.2 |
limodou/uliweb | uliweb/manage.py | https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/manage.py#L1457-L1502 | def _find_template(self, template, tree, blocks, with_filename,
source, comment):
"""
If tree is true, then will display the track of template extend or include
"""
from uliweb import application
from uliweb.core.template import _format_code
de... | [
"def",
"_find_template",
"(",
"self",
",",
"template",
",",
"tree",
",",
"blocks",
",",
"with_filename",
",",
"source",
",",
"comment",
")",
":",
"from",
"uliweb",
"import",
"application",
"from",
"uliweb",
".",
"core",
".",
"template",
"import",
"_format_co... | If tree is true, then will display the track of template extend or include | [
"If",
"tree",
"is",
"true",
"then",
"will",
"display",
"the",
"track",
"of",
"template",
"extend",
"or",
"include"
] | python | train | 35.043478 |
calmjs/calmjs.parse | src/calmjs/parse/walkers.py | https://github.com/calmjs/calmjs.parse/blob/369f0ee346c5a84c4d5c35a7733a0e63b02eac59/src/calmjs/parse/walkers.py#L78-L92 | def filter(self, node, condition):
"""
This method accepts a node and the condition function; a
generator will be returned to yield the nodes that got matched
by the condition.
"""
if not isinstance(node, Node):
raise TypeError('not a node')
for chil... | [
"def",
"filter",
"(",
"self",
",",
"node",
",",
"condition",
")",
":",
"if",
"not",
"isinstance",
"(",
"node",
",",
"Node",
")",
":",
"raise",
"TypeError",
"(",
"'not a node'",
")",
"for",
"child",
"in",
"node",
":",
"if",
"condition",
"(",
"child",
... | This method accepts a node and the condition function; a
generator will be returned to yield the nodes that got matched
by the condition. | [
"This",
"method",
"accepts",
"a",
"node",
"and",
"the",
"condition",
"function",
";",
"a",
"generator",
"will",
"be",
"returned",
"to",
"yield",
"the",
"nodes",
"that",
"got",
"matched",
"by",
"the",
"condition",
"."
] | python | train | 31.133333 |
JoelBender/bacpypes | py34/bacpypes/analysis.py | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py34/bacpypes/analysis.py#L355-L379 | def decode_file(fname):
"""Given the name of a pcap file, open it, decode the contents and yield each packet."""
if _debug: decode_file._debug("decode_file %r", fname)
if not pcap:
raise RuntimeError("failed to import pcap")
# create a pcap object, reading from the file
p = pcap.pcap(fname... | [
"def",
"decode_file",
"(",
"fname",
")",
":",
"if",
"_debug",
":",
"decode_file",
".",
"_debug",
"(",
"\"decode_file %r\"",
",",
"fname",
")",
"if",
"not",
"pcap",
":",
"raise",
"RuntimeError",
"(",
"\"failed to import pcap\"",
")",
"# create a pcap object, readin... | Given the name of a pcap file, open it, decode the contents and yield each packet. | [
"Given",
"the",
"name",
"of",
"a",
"pcap",
"file",
"open",
"it",
"decode",
"the",
"contents",
"and",
"yield",
"each",
"packet",
"."
] | python | train | 31.12 |
sebdah/dynamic-dynamodb | dynamic_dynamodb/core/table.py | https://github.com/sebdah/dynamic-dynamodb/blob/bfd0ca806b1c3301e724696de90ef0f973410493/dynamic_dynamodb/core/table.py#L81-L121 | def __calculate_always_decrease_rw_values(
table_name, read_units, provisioned_reads,
write_units, provisioned_writes):
""" Calculate values for always-decrease-rw-together
This will only return reads and writes decreases if both reads and writes
are lower than the current provisioning
... | [
"def",
"__calculate_always_decrease_rw_values",
"(",
"table_name",
",",
"read_units",
",",
"provisioned_reads",
",",
"write_units",
",",
"provisioned_writes",
")",
":",
"if",
"read_units",
"<=",
"provisioned_reads",
"and",
"write_units",
"<=",
"provisioned_writes",
":",
... | Calculate values for always-decrease-rw-together
This will only return reads and writes decreases if both reads and writes
are lower than the current provisioning
:type table_name: str
:param table_name: Name of the DynamoDB table
:type read_units: int
:param read_units: New read unit provisi... | [
"Calculate",
"values",
"for",
"always",
"-",
"decrease",
"-",
"rw",
"-",
"together"
] | python | train | 35.756098 |
apragacz/django-rest-registration | rest_registration/api/views/login.py | https://github.com/apragacz/django-rest-registration/blob/7373571264dd567c2a73a97ff4c45b64f113605b/rest_registration/api/views/login.py#L25-L39 | def login(request):
'''
Logs in the user via given login and password.
'''
serializer_class = registration_settings.LOGIN_SERIALIZER_CLASS
serializer = serializer_class(data=request.data)
serializer.is_valid(raise_exception=True)
user = serializer.get_authenticated_user()
if not user:
... | [
"def",
"login",
"(",
"request",
")",
":",
"serializer_class",
"=",
"registration_settings",
".",
"LOGIN_SERIALIZER_CLASS",
"serializer",
"=",
"serializer_class",
"(",
"data",
"=",
"request",
".",
"data",
")",
"serializer",
".",
"is_valid",
"(",
"raise_exception",
... | Logs in the user via given login and password. | [
"Logs",
"in",
"the",
"user",
"via",
"given",
"login",
"and",
"password",
"."
] | python | train | 31.8 |
gabstopper/smc-python | smc/core/interfaces.py | https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/core/interfaces.py#L1205-L1227 | def static_arp_entry(self, ipaddress, macaddress, arp_type='static', netmask=32):
"""
Add an arp entry to this physical interface.
::
interface = engine.physical_interface.get(0)
interface.static_arp_entry(
ipaddress='23.23.23.23',
arp_typ... | [
"def",
"static_arp_entry",
"(",
"self",
",",
"ipaddress",
",",
"macaddress",
",",
"arp_type",
"=",
"'static'",
",",
"netmask",
"=",
"32",
")",
":",
"self",
".",
"data",
"[",
"'arp_entry'",
"]",
".",
"append",
"(",
"{",
"'ipaddress'",
":",
"ipaddress",
",... | Add an arp entry to this physical interface.
::
interface = engine.physical_interface.get(0)
interface.static_arp_entry(
ipaddress='23.23.23.23',
arp_type='static',
macaddress='02:02:02:02:04:04')
interface.save()
:par... | [
"Add",
"an",
"arp",
"entry",
"to",
"this",
"physical",
"interface",
".",
"::"
] | python | train | 37.043478 |
google/grr | grr/server/grr_response_server/gui/api_call_router_with_approval_checks.py | https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/gui/api_call_router_with_approval_checks.py#L118-L126 | def CheckIfCanStartClientFlow(self, username, flow_name):
"""Checks whether a given user can start a given flow."""
del username # Unused.
flow_cls = flow.GRRFlow.GetPlugin(flow_name)
if not flow_cls.category:
raise access_control.UnauthorizedAccess(
"Flow %s can't be started via the ... | [
"def",
"CheckIfCanStartClientFlow",
"(",
"self",
",",
"username",
",",
"flow_name",
")",
":",
"del",
"username",
"# Unused.",
"flow_cls",
"=",
"flow",
".",
"GRRFlow",
".",
"GetPlugin",
"(",
"flow_name",
")",
"if",
"not",
"flow_cls",
".",
"category",
":",
"ra... | Checks whether a given user can start a given flow. | [
"Checks",
"whether",
"a",
"given",
"user",
"can",
"start",
"a",
"given",
"flow",
"."
] | python | train | 36.666667 |
danilobellini/audiolazy | audiolazy/lazy_synth.py | https://github.com/danilobellini/audiolazy/blob/dba0a278937909980ed40b976d866b8e97c35dee/audiolazy/lazy_synth.py#L253-L297 | def attack(a, d, s):
"""
Linear ADS fading attack stream generator, useful to be multiplied with a
given stream.
Parameters
----------
a :
"Attack" time, in number of samples.
d :
"Decay" time, in number of samples.
s :
"Sustain" amplitude level (should be based on attack amplitude).
Th... | [
"def",
"attack",
"(",
"a",
",",
"d",
",",
"s",
")",
":",
"# Configure sustain possibilities",
"if",
"isinstance",
"(",
"s",
",",
"collections",
".",
"Iterable",
")",
":",
"it_s",
"=",
"iter",
"(",
"s",
")",
"s",
"=",
"next",
"(",
"it_s",
")",
"else",... | Linear ADS fading attack stream generator, useful to be multiplied with a
given stream.
Parameters
----------
a :
"Attack" time, in number of samples.
d :
"Decay" time, in number of samples.
s :
"Sustain" amplitude level (should be based on attack amplitude).
The sustain can be a Stream, if... | [
"Linear",
"ADS",
"fading",
"attack",
"stream",
"generator",
"useful",
"to",
"be",
"multiplied",
"with",
"a",
"given",
"stream",
"."
] | python | train | 21.133333 |
census-instrumentation/opencensus-python | opencensus/metrics/export/metric.py | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/opencensus/metrics/export/metric.py#L69-L79 | def _check_start_timestamp(self):
"""Check that starting timestamp exists for cumulative metrics."""
if self.descriptor.type in (
metric_descriptor.MetricDescriptorType.CUMULATIVE_INT64,
metric_descriptor.MetricDescriptorType.CUMULATIVE_DOUBLE,
metric_desc... | [
"def",
"_check_start_timestamp",
"(",
"self",
")",
":",
"if",
"self",
".",
"descriptor",
".",
"type",
"in",
"(",
"metric_descriptor",
".",
"MetricDescriptorType",
".",
"CUMULATIVE_INT64",
",",
"metric_descriptor",
".",
"MetricDescriptorType",
".",
"CUMULATIVE_DOUBLE",... | Check that starting timestamp exists for cumulative metrics. | [
"Check",
"that",
"starting",
"timestamp",
"exists",
"for",
"cumulative",
"metrics",
"."
] | python | train | 54.727273 |
ryanvarley/ExoData | exodata/astroclasses.py | https://github.com/ryanvarley/ExoData/blob/e0d3652117214d2377a707d6778f93b7eb201a41/exodata/astroclasses.py#L1197-L1250 | def _convert_to_from(self, to_mag, from_mag, fromVMag=None):
""" Converts from or to V mag using the conversion tables
:param to_mag: uppercase magnitude letter i.e. 'V' or 'K'
:param from_mag: uppercase magnitude letter i.e. 'V' or 'K'
:param fromVMag: MagV if from_mag is 'V'
... | [
"def",
"_convert_to_from",
"(",
"self",
",",
"to_mag",
",",
"from_mag",
",",
"fromVMag",
"=",
"None",
")",
":",
"lumtype",
"=",
"self",
".",
"spectral_type",
".",
"lumType",
"# rounds decimal types, TODO perhaps we should interpolate?",
"specClass",
"=",
"self",
"."... | Converts from or to V mag using the conversion tables
:param to_mag: uppercase magnitude letter i.e. 'V' or 'K'
:param from_mag: uppercase magnitude letter i.e. 'V' or 'K'
:param fromVMag: MagV if from_mag is 'V'
:return: estimated magnitude for to_mag from from_mag | [
"Converts",
"from",
"or",
"to",
"V",
"mag",
"using",
"the",
"conversion",
"tables"
] | python | train | 48.87037 |
HazardDede/dictmentor | dictmentor/extensions.py | https://github.com/HazardDede/dictmentor/blob/f50ca26ed04f7a924cde6e4d464c4f6ccba4e320/dictmentor/extensions.py#L294-L323 | def _apply(self, ctx: ExtensionContext) -> AugmentedDict:
"""
Replaces any {{env::*}} directives with it's actual environment variable value or a default.
Args:
ctx: The processing context.
Returns:
Returns the altered node key and value.
"""
nod... | [
"def",
"_apply",
"(",
"self",
",",
"ctx",
":",
"ExtensionContext",
")",
"->",
"AugmentedDict",
":",
"node_key",
",",
"node_value",
"=",
"ctx",
".",
"node",
"def",
"process",
"(",
"pattern",
":",
"Pattern",
"[",
"str",
"]",
",",
"_str",
":",
"str",
")",... | Replaces any {{env::*}} directives with it's actual environment variable value or a default.
Args:
ctx: The processing context.
Returns:
Returns the altered node key and value. | [
"Replaces",
"any",
"{{",
"env",
"::",
"*",
"}}",
"directives",
"with",
"it",
"s",
"actual",
"environment",
"variable",
"value",
"or",
"a",
"default",
"."
] | python | train | 37.7 |
log2timeline/plaso | plaso/parsers/filestat.py | https://github.com/log2timeline/plaso/blob/9c564698d2da3ffbe23607a3c54c0582ea18a6cc/plaso/parsers/filestat.py#L74-L137 | def ParseFileEntry(self, parser_mediator, file_entry):
"""Parses a file entry.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
file_entry (dfvfs.FileEntry): a file entry.
"""
stat_object = file_entry.Ge... | [
"def",
"ParseFileEntry",
"(",
"self",
",",
"parser_mediator",
",",
"file_entry",
")",
":",
"stat_object",
"=",
"file_entry",
".",
"GetStat",
"(",
")",
"if",
"not",
"stat_object",
":",
"return",
"file_system_type",
"=",
"self",
".",
"_GetFileSystemTypeFromFileEntry... | Parses a file entry.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
file_entry (dfvfs.FileEntry): a file entry. | [
"Parses",
"a",
"file",
"entry",
"."
] | python | train | 39.5625 |
volfpeter/graphscraper | src/graphscraper/spotifyartist.py | https://github.com/volfpeter/graphscraper/blob/11d407509956a282ee25190ed6491a162fc0fe7f/src/graphscraper/spotifyartist.py#L188-L211 | def _load_neighbors_from_external_source(self) -> None:
"""
Loads the neighbors of the node from the igraph `Graph` instance that is
wrapped by the graph that has this node.
"""
graph: SpotifyArtistGraph = self._graph
items: List[NameExternalIDPair] = graph.client.similar... | [
"def",
"_load_neighbors_from_external_source",
"(",
"self",
")",
"->",
"None",
":",
"graph",
":",
"SpotifyArtistGraph",
"=",
"self",
".",
"_graph",
"items",
":",
"List",
"[",
"NameExternalIDPair",
"]",
"=",
"graph",
".",
"client",
".",
"similar_artists",
"(",
... | Loads the neighbors of the node from the igraph `Graph` instance that is
wrapped by the graph that has this node. | [
"Loads",
"the",
"neighbors",
"of",
"the",
"node",
"from",
"the",
"igraph",
"Graph",
"instance",
"that",
"is",
"wrapped",
"by",
"the",
"graph",
"that",
"has",
"this",
"node",
"."
] | python | train | 52 |
BD2KGenomics/protect | src/protect/pipeline/ProTECT.py | https://github.com/BD2KGenomics/protect/blob/06310682c50dcf8917b912c8e551299ff7ee41ce/src/protect/pipeline/ProTECT.py#L940-L954 | def get_patient_mhc_haplotype(job, patient_dict):
"""
Convenience function to get the mhc haplotype from the patient dict
:param dict patient_dict: dict of patient info
:return: The MHCI and MHCII haplotypes
:rtype: toil.fileStore.FileID
"""
haplotype_archive = job.fileStore.readGlobalFile(... | [
"def",
"get_patient_mhc_haplotype",
"(",
"job",
",",
"patient_dict",
")",
":",
"haplotype_archive",
"=",
"job",
".",
"fileStore",
".",
"readGlobalFile",
"(",
"patient_dict",
"[",
"'hla_haplotype_files'",
"]",
")",
"haplotype_archive",
"=",
"untargz",
"(",
"haplotype... | Convenience function to get the mhc haplotype from the patient dict
:param dict patient_dict: dict of patient info
:return: The MHCI and MHCII haplotypes
:rtype: toil.fileStore.FileID | [
"Convenience",
"function",
"to",
"get",
"the",
"mhc",
"haplotype",
"from",
"the",
"patient",
"dict"
] | python | train | 46.2 |
trec-kba/streamcorpus-pipeline | streamcorpus_pipeline/_john_smith.py | https://github.com/trec-kba/streamcorpus-pipeline/blob/8bb82ea1beb83c6b40ed03fa1659df2897c2292a/streamcorpus_pipeline/_john_smith.py#L47-L117 | def generate_john_smith_chunk(path_to_original):
'''
This _looks_ like a Chunk only in that it generates StreamItem
instances when iterated upon.
'''
## Every StreamItem has a stream_time property. It usually comes
## from the document creation time. Here, we assume the JS corpus
## was cr... | [
"def",
"generate_john_smith_chunk",
"(",
"path_to_original",
")",
":",
"## Every StreamItem has a stream_time property. It usually comes",
"## from the document creation time. Here, we assume the JS corpus",
"## was created at one moment at the end of 1998:",
"creation_time",
"=",
"'1998-12-... | This _looks_ like a Chunk only in that it generates StreamItem
instances when iterated upon. | [
"This",
"_looks_",
"like",
"a",
"Chunk",
"only",
"in",
"that",
"it",
"generates",
"StreamItem",
"instances",
"when",
"iterated",
"upon",
"."
] | python | test | 43.253521 |
wandb/client | wandb/vendor/prompt_toolkit/document.py | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/document.py#L338-L370 | def find(self, sub, in_current_line=False, include_current_position=False,
ignore_case=False, count=1):
"""
Find `text` after the cursor, return position relative to the cursor
position. Return `None` if nothing was found.
:param count: Find the n-th occurance.
"""
... | [
"def",
"find",
"(",
"self",
",",
"sub",
",",
"in_current_line",
"=",
"False",
",",
"include_current_position",
"=",
"False",
",",
"ignore_case",
"=",
"False",
",",
"count",
"=",
"1",
")",
":",
"assert",
"isinstance",
"(",
"ignore_case",
",",
"bool",
")",
... | Find `text` after the cursor, return position relative to the cursor
position. Return `None` if nothing was found.
:param count: Find the n-th occurance. | [
"Find",
"text",
"after",
"the",
"cursor",
"return",
"position",
"relative",
"to",
"the",
"cursor",
"position",
".",
"Return",
"None",
"if",
"nothing",
"was",
"found",
"."
] | python | train | 33.393939 |
googleapis/google-cloud-python | bigquery/google/cloud/bigquery/job.py | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery/google/cloud/bigquery/job.py#L2692-L2718 | def referenced_tables(self):
"""Return referenced tables from job statistics, if present.
See:
https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#statistics.query.referencedTables
:rtype: list of dict
:returns: mappings describing the query plan, or an empty list
... | [
"def",
"referenced_tables",
"(",
"self",
")",
":",
"tables",
"=",
"[",
"]",
"datasets_by_project_name",
"=",
"{",
"}",
"for",
"table",
"in",
"self",
".",
"_job_statistics",
"(",
")",
".",
"get",
"(",
"\"referencedTables\"",
",",
"(",
")",
")",
":",
"t_pr... | Return referenced tables from job statistics, if present.
See:
https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#statistics.query.referencedTables
:rtype: list of dict
:returns: mappings describing the query plan, or an empty list
if the query has not yet ... | [
"Return",
"referenced",
"tables",
"from",
"job",
"statistics",
"if",
"present",
"."
] | python | train | 34.37037 |
vanheeringen-lab/gimmemotifs | gimmemotifs/genome_index.py | https://github.com/vanheeringen-lab/gimmemotifs/blob/1dc0572179e5d0c8f96958060133c1f8d92c6675/gimmemotifs/genome_index.py#L284-L297 | def _make_index(self, fasta, index):
""" Index a single, one-sequence fasta-file"""
out = open(index, "wb")
f = open(fasta)
# Skip first line of fasta-file
line = f.readline()
offset = f.tell()
line = f.readline()
while line:
out.write(pack(sel... | [
"def",
"_make_index",
"(",
"self",
",",
"fasta",
",",
"index",
")",
":",
"out",
"=",
"open",
"(",
"index",
",",
"\"wb\"",
")",
"f",
"=",
"open",
"(",
"fasta",
")",
"# Skip first line of fasta-file",
"line",
"=",
"f",
".",
"readline",
"(",
")",
"offset"... | Index a single, one-sequence fasta-file | [
"Index",
"a",
"single",
"one",
"-",
"sequence",
"fasta",
"-",
"file"
] | python | train | 30.571429 |
aequitas/python-rflink | rflink/protocol.py | https://github.com/aequitas/python-rflink/blob/46759ce8daf95cfc7cdb608ae17bc5501be9f6d8/rflink/protocol.py#L297-L301 | def handle_event(self, packet):
"""Handle incoming packet from rflink gateway."""
if packet.get('command'):
task = self.send_command_ack(packet['id'], packet['command'])
self.loop.create_task(task) | [
"def",
"handle_event",
"(",
"self",
",",
"packet",
")",
":",
"if",
"packet",
".",
"get",
"(",
"'command'",
")",
":",
"task",
"=",
"self",
".",
"send_command_ack",
"(",
"packet",
"[",
"'id'",
"]",
",",
"packet",
"[",
"'command'",
"]",
")",
"self",
"."... | Handle incoming packet from rflink gateway. | [
"Handle",
"incoming",
"packet",
"from",
"rflink",
"gateway",
"."
] | python | train | 46.6 |
thespacedoctor/neddy | neddy/_basesearch.py | https://github.com/thespacedoctor/neddy/blob/f32653b7d6a39a2c46c5845f83b3a29056311e5e/neddy/_basesearch.py#L88-L146 | def _parse_the_ned_position_results(
self,
ra,
dec,
nedResults):
"""
*parse the ned results*
**Key Arguments:**
- ``ra`` -- the search ra
- ``dec`` -- the search dec
**Return:**
- ``results`` -- list of... | [
"def",
"_parse_the_ned_position_results",
"(",
"self",
",",
"ra",
",",
"dec",
",",
"nedResults",
")",
":",
"self",
".",
"log",
".",
"info",
"(",
"'starting the ``_parse_the_ned_results`` method'",
")",
"results",
"=",
"[",
"]",
"resultLen",
"=",
"0",
"if",
"ne... | *parse the ned results*
**Key Arguments:**
- ``ra`` -- the search ra
- ``dec`` -- the search dec
**Return:**
- ``results`` -- list of result dictionaries | [
"*",
"parse",
"the",
"ned",
"results",
"*"
] | python | train | 37.067797 |
apache/incubator-mxnet | example/ctc/lstm.py | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/ctc/lstm.py#L116-L126 | def _add_ctc_loss(pred, seq_len, num_label, loss_type):
""" Adds CTC loss on top of pred symbol and returns the resulting symbol """
label = mx.sym.Variable('label')
if loss_type == 'warpctc':
print("Using WarpCTC Loss")
sm = _add_warp_ctc_loss(pred, seq_len, num_label, label)
else:
... | [
"def",
"_add_ctc_loss",
"(",
"pred",
",",
"seq_len",
",",
"num_label",
",",
"loss_type",
")",
":",
"label",
"=",
"mx",
".",
"sym",
".",
"Variable",
"(",
"'label'",
")",
"if",
"loss_type",
"==",
"'warpctc'",
":",
"print",
"(",
"\"Using WarpCTC Loss\"",
")",... | Adds CTC loss on top of pred symbol and returns the resulting symbol | [
"Adds",
"CTC",
"loss",
"on",
"top",
"of",
"pred",
"symbol",
"and",
"returns",
"the",
"resulting",
"symbol"
] | python | train | 40.545455 |
mikicz/arca | arca/backend/docker.py | https://github.com/mikicz/arca/blob/e67fdc00be473ecf8ec16d024e1a3f2c47ca882c/arca/backend/docker.py#L665-L684 | def start_container(self, image, container_name: str, repo_path: Path):
""" Starts a container with the image and name ``container_name`` and copies the repository into the container.
:type image: docker.models.images.Image
:rtype: docker.models.container.Container
"""
command =... | [
"def",
"start_container",
"(",
"self",
",",
"image",
",",
"container_name",
":",
"str",
",",
"repo_path",
":",
"Path",
")",
":",
"command",
"=",
"\"bash -i\"",
"if",
"self",
".",
"inherit_image",
":",
"command",
"=",
"\"sh -i\"",
"container",
"=",
"self",
... | Starts a container with the image and name ``container_name`` and copies the repository into the container.
:type image: docker.models.images.Image
:rtype: docker.models.container.Container | [
"Starts",
"a",
"container",
"with",
"the",
"image",
"and",
"name",
"container_name",
"and",
"copies",
"the",
"repository",
"into",
"the",
"container",
"."
] | python | train | 43.85 |
rocky/python-uncompyle6 | uncompyle6/semantics/pysource.py | https://github.com/rocky/python-uncompyle6/blob/c5d7944e657f0ad05a0e2edd34e1acb27001abc0/uncompyle6/semantics/pysource.py#L1816-L1934 | def template_engine(self, entry, startnode):
"""The format template interpetation engine. See the comment at the
beginning of this module for the how we interpret format
specifications such as %c, %C, and so on.
"""
# print("-----")
# print(startnode)
# print(en... | [
"def",
"template_engine",
"(",
"self",
",",
"entry",
",",
"startnode",
")",
":",
"# print(\"-----\")",
"# print(startnode)",
"# print(entry[0])",
"# print('======')",
"fmt",
"=",
"entry",
"[",
"0",
"]",
"arg",
"=",
"1",
"i",
"=",
"0",
"m",
"=",
"escape",
"."... | The format template interpetation engine. See the comment at the
beginning of this module for the how we interpret format
specifications such as %c, %C, and so on. | [
"The",
"format",
"template",
"interpetation",
"engine",
".",
"See",
"the",
"comment",
"at",
"the",
"beginning",
"of",
"this",
"module",
"for",
"the",
"how",
"we",
"interpret",
"format",
"specifications",
"such",
"as",
"%c",
"%C",
"and",
"so",
"on",
"."
] | python | train | 35.537815 |
zikzakmedia/python-mediawiki | mediawiki/wikimarkup/__init__.py | https://github.com/zikzakmedia/python-mediawiki/blob/7c26732efa520e16c35350815ce98cd7610a0bcb/mediawiki/wikimarkup/__init__.py#L1291-L1311 | def openList(self, char, mLastSection):
"""
These next three functions open, continue, and close the list
element appropriate to the prefix character passed into them.
"""
result = self.closeParagraph(mLastSection)
mDTopen = False
if char == u'*':
result += u'<ul><li>'
elif char == u'#':
result +... | [
"def",
"openList",
"(",
"self",
",",
"char",
",",
"mLastSection",
")",
":",
"result",
"=",
"self",
".",
"closeParagraph",
"(",
"mLastSection",
")",
"mDTopen",
"=",
"False",
"if",
"char",
"==",
"u'*'",
":",
"result",
"+=",
"u'<ul><li>'",
"elif",
"char",
"... | These next three functions open, continue, and close the list
element appropriate to the prefix character passed into them. | [
"These",
"next",
"three",
"functions",
"open",
"continue",
"and",
"close",
"the",
"list",
"element",
"appropriate",
"to",
"the",
"prefix",
"character",
"passed",
"into",
"them",
"."
] | python | train | 23.238095 |
klis87/django-cloudinary-storage | cloudinary_storage/storage.py | https://github.com/klis87/django-cloudinary-storage/blob/b8cabd2ebbf67b9cfbbf4defee1a750fea5950a9/cloudinary_storage/storage.py#L200-L212 | def _remove_extension_for_non_raw_file(self, name):
"""
Implemented as image and video files' Cloudinary public id
shouldn't contain file extensions, otherwise Cloudinary url
would contain doubled extension - Cloudinary adds extension to url
to allow file conversion to arbitrary ... | [
"def",
"_remove_extension_for_non_raw_file",
"(",
"self",
",",
"name",
")",
":",
"file_resource_type",
"=",
"self",
".",
"_get_resource_type",
"(",
"name",
")",
"if",
"file_resource_type",
"is",
"None",
"or",
"file_resource_type",
"==",
"self",
".",
"RESOURCE_TYPE",... | Implemented as image and video files' Cloudinary public id
shouldn't contain file extensions, otherwise Cloudinary url
would contain doubled extension - Cloudinary adds extension to url
to allow file conversion to arbitrary file, like png to jpg. | [
"Implemented",
"as",
"image",
"and",
"video",
"files",
"Cloudinary",
"public",
"id",
"shouldn",
"t",
"contain",
"file",
"extensions",
"otherwise",
"Cloudinary",
"url",
"would",
"contain",
"doubled",
"extension",
"-",
"Cloudinary",
"adds",
"extension",
"to",
"url",... | python | train | 47.923077 |
lrq3000/pyFileFixity | pyFileFixity/lib/profilers/visual/pympler/web.py | https://github.com/lrq3000/pyFileFixity/blob/fd5ef23bb13835faf1e3baa773619b86a1cc9bdf/pyFileFixity/lib/profilers/visual/pympler/web.py#L69-L83 | def get_ref(obj):
"""
Get string reference to object. Stores a weak reference in a dictionary
using the object's id as the key. If the object cannot be weakly
referenced (e.g. dictionaries, frame objects), store a strong references
in a classic dictionary.
Returns the object's id as a string.
... | [
"def",
"get_ref",
"(",
"obj",
")",
":",
"oid",
"=",
"id",
"(",
"obj",
")",
"try",
":",
"server",
".",
"id2ref",
"[",
"oid",
"]",
"=",
"obj",
"except",
"TypeError",
":",
"server",
".",
"id2obj",
"[",
"oid",
"]",
"=",
"obj",
"return",
"str",
"(",
... | Get string reference to object. Stores a weak reference in a dictionary
using the object's id as the key. If the object cannot be weakly
referenced (e.g. dictionaries, frame objects), store a strong references
in a classic dictionary.
Returns the object's id as a string. | [
"Get",
"string",
"reference",
"to",
"object",
".",
"Stores",
"a",
"weak",
"reference",
"in",
"a",
"dictionary",
"using",
"the",
"object",
"s",
"id",
"as",
"the",
"key",
".",
"If",
"the",
"object",
"cannot",
"be",
"weakly",
"referenced",
"(",
"e",
".",
... | python | train | 29.8 |
pgmpy/pgmpy | pgmpy/estimators/BayesianEstimator.py | https://github.com/pgmpy/pgmpy/blob/9381a66aba3c3871d3ccd00672b148d17d63239e/pgmpy/estimators/BayesianEstimator.py#L79-L154 | def estimate_cpd(self, node, prior_type='BDeu', pseudo_counts=[], equivalent_sample_size=5):
"""
Method to estimate the CPD for a given variable.
Parameters
----------
node: int, string (any hashable python object)
The name of the variable for which the CPD is to be ... | [
"def",
"estimate_cpd",
"(",
"self",
",",
"node",
",",
"prior_type",
"=",
"'BDeu'",
",",
"pseudo_counts",
"=",
"[",
"]",
",",
"equivalent_sample_size",
"=",
"5",
")",
":",
"node_cardinality",
"=",
"len",
"(",
"self",
".",
"state_names",
"[",
"node",
"]",
... | Method to estimate the CPD for a given variable.
Parameters
----------
node: int, string (any hashable python object)
The name of the variable for which the CPD is to be estimated.
prior_type: 'dirichlet', 'BDeu', 'K2',
string indicting which type of prior to us... | [
"Method",
"to",
"estimate",
"the",
"CPD",
"for",
"a",
"given",
"variable",
"."
] | python | train | 49.263158 |
mental32/spotify.py | spotify/models/library.py | https://github.com/mental32/spotify.py/blob/bb296cac7c3dd289908906b7069bd80f43950515/spotify/models/library.py#L90-L99 | async def remove_tracks(self, *tracks):
"""Remove one or more tracks from the current user’s ‘Your Music’ library.
Parameters
----------
tracks : Sequence[Union[Track, str]]
A sequence of track objects or spotify IDs
"""
_tracks = [(obj if isinstance(obj, str... | [
"async",
"def",
"remove_tracks",
"(",
"self",
",",
"*",
"tracks",
")",
":",
"_tracks",
"=",
"[",
"(",
"obj",
"if",
"isinstance",
"(",
"obj",
",",
"str",
")",
"else",
"obj",
".",
"id",
")",
"for",
"obj",
"in",
"tracks",
"]",
"await",
"self",
".",
... | Remove one or more tracks from the current user’s ‘Your Music’ library.
Parameters
----------
tracks : Sequence[Union[Track, str]]
A sequence of track objects or spotify IDs | [
"Remove",
"one",
"or",
"more",
"tracks",
"from",
"the",
"current",
"user’s",
"‘Your",
"Music’",
"library",
"."
] | python | test | 41.2 |
tensorflow/probability | tensorflow_probability/python/mcmc/internal/util.py | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/mcmc/internal/util.py#L176-L218 | def _value_and_gradients(fn, fn_arg_list, result=None, grads=None, name=None):
"""Helper to `maybe_call_fn_and_grads`."""
with tf.compat.v1.name_scope(name, 'value_and_gradients',
[fn_arg_list, result, grads]):
def _convert_to_tensor(x, name):
ctt = lambda x_: x_ if x_ is N... | [
"def",
"_value_and_gradients",
"(",
"fn",
",",
"fn_arg_list",
",",
"result",
"=",
"None",
",",
"grads",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"with",
"tf",
".",
"compat",
".",
"v1",
".",
"name_scope",
"(",
"name",
",",
"'value_and_gradients'",... | Helper to `maybe_call_fn_and_grads`. | [
"Helper",
"to",
"maybe_call_fn_and_grads",
"."
] | python | test | 39.27907 |
hid-io/layouts-python | layouts/__init__.py | https://github.com/hid-io/layouts-python/blob/b347578bfb4198fd812ecd7a2d9c7e551a856280/layouts/__init__.py#L462-L487 | def main(argv=None):
'''
Main entry-point for calling layouts directly as a program.
'''
# Prep argparse
ap = argparse.ArgumentParser(
description='Basic query options for Python HID-IO Layouts repository',
)
ap.add_argument('--list', action='store_true', help='List available layout ... | [
"def",
"main",
"(",
"argv",
"=",
"None",
")",
":",
"# Prep argparse",
"ap",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"'Basic query options for Python HID-IO Layouts repository'",
",",
")",
"ap",
".",
"add_argument",
"(",
"'--list'",
",",
"a... | Main entry-point for calling layouts directly as a program. | [
"Main",
"entry",
"-",
"point",
"for",
"calling",
"layouts",
"directly",
"as",
"a",
"program",
"."
] | python | train | 29.923077 |
spulec/moto | moto/sqs/responses.py | https://github.com/spulec/moto/blob/4a286c4bc288933bb023396e2784a6fdbb966bc9/moto/sqs/responses.py#L44-L57 | def _get_validated_visibility_timeout(self, timeout=None):
"""
:raises ValueError: If specified visibility timeout exceeds MAXIMUM_VISIBILTY_TIMEOUT
:raises TypeError: If visibility timeout was not specified
"""
if timeout is not None:
visibility_timeout = int(timeout... | [
"def",
"_get_validated_visibility_timeout",
"(",
"self",
",",
"timeout",
"=",
"None",
")",
":",
"if",
"timeout",
"is",
"not",
"None",
":",
"visibility_timeout",
"=",
"int",
"(",
"timeout",
")",
"else",
":",
"visibility_timeout",
"=",
"int",
"(",
"self",
".",... | :raises ValueError: If specified visibility timeout exceeds MAXIMUM_VISIBILTY_TIMEOUT
:raises TypeError: If visibility timeout was not specified | [
":",
"raises",
"ValueError",
":",
"If",
"specified",
"visibility",
"timeout",
"exceeds",
"MAXIMUM_VISIBILTY_TIMEOUT",
":",
"raises",
"TypeError",
":",
"If",
"visibility",
"timeout",
"was",
"not",
"specified"
] | python | train | 37.785714 |
jaraco/irc | irc/client.py | https://github.com/jaraco/irc/blob/571c1f448d5d5bb92bbe2605c33148bf6e698413/irc/client.py#L542-L544 | def part(self, channels, message=""):
"""Send a PART command."""
self.send_items('PART', ','.join(always_iterable(channels)), message) | [
"def",
"part",
"(",
"self",
",",
"channels",
",",
"message",
"=",
"\"\"",
")",
":",
"self",
".",
"send_items",
"(",
"'PART'",
",",
"','",
".",
"join",
"(",
"always_iterable",
"(",
"channels",
")",
")",
",",
"message",
")"
] | Send a PART command. | [
"Send",
"a",
"PART",
"command",
"."
] | python | train | 49.333333 |
valerymelou/django-active-link | active_link/templatetags/active_link_tags.py | https://github.com/valerymelou/django-active-link/blob/4791e7af2fb6d77d3ef2a3f3be0241b5c3019beb/active_link/templatetags/active_link_tags.py#L14-L48 | def active_link(context, viewnames, css_class=None, strict=None, *args, **kwargs):
"""
Renders the given CSS class if the request path matches the path of the view.
:param context: The context where the tag was called. Used to access the request object.
:param viewnames: The name of the view or views se... | [
"def",
"active_link",
"(",
"context",
",",
"viewnames",
",",
"css_class",
"=",
"None",
",",
"strict",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"css_class",
"is",
"None",
":",
"css_class",
"=",
"getattr",
"(",
"settings",
... | Renders the given CSS class if the request path matches the path of the view.
:param context: The context where the tag was called. Used to access the request object.
:param viewnames: The name of the view or views separated by || (include namespaces if any).
:param css_class: The CSS class to render.
:... | [
"Renders",
"the",
"given",
"CSS",
"class",
"if",
"the",
"request",
"path",
"matches",
"the",
"path",
"of",
"the",
"view",
".",
":",
"param",
"context",
":",
"The",
"context",
"where",
"the",
"tag",
"was",
"called",
".",
"Used",
"to",
"access",
"the",
"... | python | train | 34.771429 |
ethereum/vyper | vyper/utils.py | https://github.com/ethereum/vyper/blob/c21a40a4f651ebd8426b29b8e2bb7d8b72b57cdd/vyper/utils.py#L242-L256 | def check_valid_varname(varname,
custom_units,
custom_structs,
constants,
pos,
error_prefix="Variable name invalid.",
exc=None):
""" Handle invalid variable names """
e... | [
"def",
"check_valid_varname",
"(",
"varname",
",",
"custom_units",
",",
"custom_structs",
",",
"constants",
",",
"pos",
",",
"error_prefix",
"=",
"\"Variable name invalid.\"",
",",
"exc",
"=",
"None",
")",
":",
"exc",
"=",
"VariableDeclarationException",
"if",
"ex... | Handle invalid variable names | [
"Handle",
"invalid",
"variable",
"names"
] | python | train | 36.133333 |
TissueMAPS/TmDeploy | elasticluster/elasticluster/providers/libcloud_provider.py | https://github.com/TissueMAPS/TmDeploy/blob/f891b4ffb21431988bc4a063ae871da3bf284a45/elasticluster/elasticluster/providers/libcloud_provider.py#L167-L189 | def __import_pem(self, key_name, pem_file_path, password):
"""
Import PEM certificate with provider
:param key_name: name of the key to import
:param pem_file_path: path to the pem file
:param password: optional password for the pem file
"""
key_import = self.__ge... | [
"def",
"__import_pem",
"(",
"self",
",",
"key_name",
",",
"pem_file_path",
",",
"password",
")",
":",
"key_import",
"=",
"self",
".",
"__get_function_or_ex_function",
"(",
"'import_key_pair_from_file'",
")",
"pem_file",
"=",
"os",
".",
"path",
".",
"expandvars",
... | Import PEM certificate with provider
:param key_name: name of the key to import
:param pem_file_path: path to the pem file
:param password: optional password for the pem file | [
"Import",
"PEM",
"certificate",
"with",
"provider",
":",
"param",
"key_name",
":",
"name",
"of",
"the",
"key",
"to",
"import",
":",
"param",
"pem_file_path",
":",
"path",
"to",
"the",
"pem",
"file",
":",
"param",
"password",
":",
"optional",
"password",
"f... | python | train | 49.913043 |
hardbyte/python-can | can/bus.py | https://github.com/hardbyte/python-can/blob/cdc5254d96072df7739263623f3e920628a7d214/can/bus.py#L249-L256 | def stop_all_periodic_tasks(self, remove_tasks=True):
"""Stop sending any messages that were started using bus.send_periodic
:param bool remove_tasks:
Stop tracking the stopped tasks.
"""
for task in self._periodic_tasks:
task.stop(remove_task=remove_tasks) | [
"def",
"stop_all_periodic_tasks",
"(",
"self",
",",
"remove_tasks",
"=",
"True",
")",
":",
"for",
"task",
"in",
"self",
".",
"_periodic_tasks",
":",
"task",
".",
"stop",
"(",
"remove_task",
"=",
"remove_tasks",
")"
] | Stop sending any messages that were started using bus.send_periodic
:param bool remove_tasks:
Stop tracking the stopped tasks. | [
"Stop",
"sending",
"any",
"messages",
"that",
"were",
"started",
"using",
"bus",
".",
"send_periodic"
] | python | train | 38.375 |
Parisson/TimeSide | timeside/core/tools/package.py | https://github.com/Parisson/TimeSide/blob/0618d75cd2f16021afcfd3d5b77f692adad76ea5/timeside/core/tools/package.py#L115-L128 | def check_vamp():
"Check Vamp host availability"
try:
from timeside.plugins.analyzer.externals import vamp_plugin
except VampImportError:
warnings.warn('Vamp host is not available', ImportWarning,
stacklevel=2)
_WITH_VAMP = False
else:
_WITH_VAMP = ... | [
"def",
"check_vamp",
"(",
")",
":",
"try",
":",
"from",
"timeside",
".",
"plugins",
".",
"analyzer",
".",
"externals",
"import",
"vamp_plugin",
"except",
"VampImportError",
":",
"warnings",
".",
"warn",
"(",
"'Vamp host is not available'",
",",
"ImportWarning",
... | Check Vamp host availability | [
"Check",
"Vamp",
"host",
"availability"
] | python | train | 25.571429 |
adobe-apiplatform/umapi-client.py | umapi_client/api.py | https://github.com/adobe-apiplatform/umapi-client.py/blob/1c446d79643cc8615adaa23e12dce3ac5782cf76/umapi_client/api.py#L117-L128 | def execution_errors(self):
"""
Return a list of commands that encountered execution errors, with the error.
Each dictionary entry gives the command dictionary and the error dictionary
:return: list of commands that gave errors, with their error information
"""
if self.s... | [
"def",
"execution_errors",
"(",
"self",
")",
":",
"if",
"self",
".",
"split_actions",
":",
"# throttling split this action, get errors from the split",
"return",
"[",
"dict",
"(",
"e",
")",
"for",
"s",
"in",
"self",
".",
"split_actions",
"for",
"e",
"in",
"s",
... | Return a list of commands that encountered execution errors, with the error.
Each dictionary entry gives the command dictionary and the error dictionary
:return: list of commands that gave errors, with their error information | [
"Return",
"a",
"list",
"of",
"commands",
"that",
"encountered",
"execution",
"errors",
"with",
"the",
"error",
"."
] | python | train | 44.25 |
scarface-4711/denonavr | denonavr/denonavr.py | https://github.com/scarface-4711/denonavr/blob/59a136e27b43cb1d1e140cf67705087b3aa377cd/denonavr/denonavr.py#L390-L397 | def create_zones(self, add_zones):
"""Create instances of additional zones for the receiver."""
for zone, zname in add_zones.items():
# Name either set explicitly or name of Main Zone with suffix
zonename = "{} {}".format(self._name, zone) if (
zname is None) else... | [
"def",
"create_zones",
"(",
"self",
",",
"add_zones",
")",
":",
"for",
"zone",
",",
"zname",
"in",
"add_zones",
".",
"items",
"(",
")",
":",
"# Name either set explicitly or name of Main Zone with suffix",
"zonename",
"=",
"\"{} {}\"",
".",
"format",
"(",
"self",
... | Create instances of additional zones for the receiver. | [
"Create",
"instances",
"of",
"additional",
"zones",
"for",
"the",
"receiver",
"."
] | python | train | 52.625 |
IntegralDefense/critsapi | critsapi/critsdbapi.py | https://github.com/IntegralDefense/critsapi/blob/e770bd81e124eaaeb5f1134ba95f4a35ff345c5a/critsapi/critsdbapi.py#L91-L102 | def find_all(self, collection):
"""
Search a collection for all available items.
Args:
collection: The db collection. See main class documentation.
Returns:
List of all items in the collection.
"""
obj = getattr(self.db, collection)
result... | [
"def",
"find_all",
"(",
"self",
",",
"collection",
")",
":",
"obj",
"=",
"getattr",
"(",
"self",
".",
"db",
",",
"collection",
")",
"result",
"=",
"obj",
".",
"find",
"(",
")",
"return",
"result"
] | Search a collection for all available items.
Args:
collection: The db collection. See main class documentation.
Returns:
List of all items in the collection. | [
"Search",
"a",
"collection",
"for",
"all",
"available",
"items",
"."
] | python | train | 28.666667 |
kinegratii/borax | borax/calendars/festivals.py | https://github.com/kinegratii/borax/blob/921649f9277e3f657b6dea5a80e67de9ee5567f6/borax/calendars/festivals.py#L68-L76 | def resolve(self, year: int = YEAR_ANY) -> MDate:
"""Return the date object in the solar / lunar year.
:param year:
:return:
"""
year = year or self.year
if year:
return self._resolve(year)
raise ValueError('Unable resolve the date without a specified ... | [
"def",
"resolve",
"(",
"self",
",",
"year",
":",
"int",
"=",
"YEAR_ANY",
")",
"->",
"MDate",
":",
"year",
"=",
"year",
"or",
"self",
".",
"year",
"if",
"year",
":",
"return",
"self",
".",
"_resolve",
"(",
"year",
")",
"raise",
"ValueError",
"(",
"'... | Return the date object in the solar / lunar year.
:param year:
:return: | [
"Return",
"the",
"date",
"object",
"in",
"the",
"solar",
"/",
"lunar",
"year",
".",
":",
"param",
"year",
":",
":",
"return",
":"
] | python | train | 35.444444 |
FujiMakoto/AgentML | agentml/__init__.py | https://github.com/FujiMakoto/AgentML/blob/c8cb64b460d876666bf29ea2c682189874c7c403/agentml/__init__.py#L389-L411 | def clear_limit(self, identifier=None):
"""
Remove a single limit or all defined limits
:param identifier: The identifier to clear limits for, or if no identifier is supplied, clears ALL limits
:type identifier: int
:return: True if a limit was successfully found and removed, F... | [
"def",
"clear_limit",
"(",
"self",
",",
"identifier",
"=",
"None",
")",
":",
"# Remove a single limit",
"if",
"identifier",
":",
"if",
"identifier",
"in",
"self",
".",
"_limits",
":",
"del",
"self",
".",
"_limits",
"[",
"identifier",
"]",
"return",
"True",
... | Remove a single limit or all defined limits
:param identifier: The identifier to clear limits for, or if no identifier is supplied, clears ALL limits
:type identifier: int
:return: True if a limit was successfully found and removed, False if no limit could be matched for removal
:rtype... | [
"Remove",
"a",
"single",
"limit",
"or",
"all",
"defined",
"limits",
":",
"param",
"identifier",
":",
"The",
"identifier",
"to",
"clear",
"limits",
"for",
"or",
"if",
"no",
"identifier",
"is",
"supplied",
"clears",
"ALL",
"limits",
":",
"type",
"identifier",
... | python | train | 32.391304 |
cloudnull/cloudlib | cloudlib/shell.py | https://github.com/cloudnull/cloudlib/blob/5038111ce02521caa2558117e3bae9e1e806d315/cloudlib/shell.py#L112-L122 | def write_file(self, filename, content):
"""Write a file.
This is useful when writing a file that will fit within memory
:param filename: ``str``
:param content: ``str``
"""
with open(filename, 'wb') as f:
self.log.debug(content)
f.write(content) | [
"def",
"write_file",
"(",
"self",
",",
"filename",
",",
"content",
")",
":",
"with",
"open",
"(",
"filename",
",",
"'wb'",
")",
"as",
"f",
":",
"self",
".",
"log",
".",
"debug",
"(",
"content",
")",
"f",
".",
"write",
"(",
"content",
")"
] | Write a file.
This is useful when writing a file that will fit within memory
:param filename: ``str``
:param content: ``str`` | [
"Write",
"a",
"file",
"."
] | python | train | 28.181818 |
agoragames/haigha | haigha/writer.py | https://github.com/agoragames/haigha/blob/7b004e1c0316ec14b94fec1c54554654c38b1a25/haigha/writer.py#L96-L105 | def write_short_at(self, n, pos, pack_into=Struct('>H').pack_into):
'''
Write an unsigned 16bit value at a specific position in the buffer.
Used for writing tables and frames.
'''
if 0 <= n <= 0xFFFF:
pack_into(self._output_buffer, pos, n)
else:
ra... | [
"def",
"write_short_at",
"(",
"self",
",",
"n",
",",
"pos",
",",
"pack_into",
"=",
"Struct",
"(",
"'>H'",
")",
".",
"pack_into",
")",
":",
"if",
"0",
"<=",
"n",
"<=",
"0xFFFF",
":",
"pack_into",
"(",
"self",
".",
"_output_buffer",
",",
"pos",
",",
... | Write an unsigned 16bit value at a specific position in the buffer.
Used for writing tables and frames. | [
"Write",
"an",
"unsigned",
"16bit",
"value",
"at",
"a",
"specific",
"position",
"in",
"the",
"buffer",
".",
"Used",
"for",
"writing",
"tables",
"and",
"frames",
"."
] | python | train | 38.3 |
happyleavesaoc/aoc-mgz | mgz/enums.py | https://github.com/happyleavesaoc/aoc-mgz/blob/13fc379cc062d7640bfa028eed9c0d45d37a7b2b/mgz/enums.py#L310-L320 | def MyDiplomacyEnum(ctx):
"""Player's Diplomacy Enumeration."""
return Enum(
ctx,
gaia=0,
self=1,
ally=2,
neutral=3,
enemy=4,
invalid_player=-1
) | [
"def",
"MyDiplomacyEnum",
"(",
"ctx",
")",
":",
"return",
"Enum",
"(",
"ctx",
",",
"gaia",
"=",
"0",
",",
"self",
"=",
"1",
",",
"ally",
"=",
"2",
",",
"neutral",
"=",
"3",
",",
"enemy",
"=",
"4",
",",
"invalid_player",
"=",
"-",
"1",
")"
] | Player's Diplomacy Enumeration. | [
"Player",
"s",
"Diplomacy",
"Enumeration",
"."
] | python | train | 18.454545 |
nion-software/nionswift-io | nionswift_plugin/TIFF_IO/tifffile.py | https://github.com/nion-software/nionswift-io/blob/e9ae37f01faa9332c48b647f93afd5ef2166b155/nionswift_plugin/TIFF_IO/tifffile.py#L8128-L8131 | def read_numpy(fh, byteorder, dtype, count, offsetsize):
"""Read tag data from file and return as numpy array."""
dtype = 'b' if dtype[-1] == 's' else byteorder+dtype[-1]
return fh.read_array(dtype, count) | [
"def",
"read_numpy",
"(",
"fh",
",",
"byteorder",
",",
"dtype",
",",
"count",
",",
"offsetsize",
")",
":",
"dtype",
"=",
"'b'",
"if",
"dtype",
"[",
"-",
"1",
"]",
"==",
"'s'",
"else",
"byteorder",
"+",
"dtype",
"[",
"-",
"1",
"]",
"return",
"fh",
... | Read tag data from file and return as numpy array. | [
"Read",
"tag",
"data",
"from",
"file",
"and",
"return",
"as",
"numpy",
"array",
"."
] | python | train | 53.5 |
saltstack/salt | salt/utils/stringutils.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/stringutils.py#L457-L510 | def check_include_exclude(path_str, include_pat=None, exclude_pat=None):
'''
Check for glob or regexp patterns for include_pat and exclude_pat in the
'path_str' string and return True/False conditions as follows.
- Default: return 'True' if no include_pat or exclude_pat patterns are
supplied
... | [
"def",
"check_include_exclude",
"(",
"path_str",
",",
"include_pat",
"=",
"None",
",",
"exclude_pat",
"=",
"None",
")",
":",
"def",
"_pat_check",
"(",
"path_str",
",",
"check_pat",
")",
":",
"if",
"re",
".",
"match",
"(",
"'E@'",
",",
"check_pat",
")",
"... | Check for glob or regexp patterns for include_pat and exclude_pat in the
'path_str' string and return True/False conditions as follows.
- Default: return 'True' if no include_pat or exclude_pat patterns are
supplied
- If only include_pat or exclude_pat is supplied: return 'True' if string
... | [
"Check",
"for",
"glob",
"or",
"regexp",
"patterns",
"for",
"include_pat",
"and",
"exclude_pat",
"in",
"the",
"path_str",
"string",
"and",
"return",
"True",
"/",
"False",
"conditions",
"as",
"follows",
".",
"-",
"Default",
":",
"return",
"True",
"if",
"no",
... | python | train | 36.259259 |
smnorris/pgdata | pgdata/table.py | https://github.com/smnorris/pgdata/blob/8b0294024d5ef30b4ae9184888e2cc7004d1784e/pgdata/table.py#L232-L244 | def insert(self, row):
"""
Add a row (type: dict) by inserting it into the table.
Columns must exist.
::
data = dict(title='I am a banana!')
table.insert(data)
Returns the inserted row's primary key.
"""
self._check_dropped()
res = ... | [
"def",
"insert",
"(",
"self",
",",
"row",
")",
":",
"self",
".",
"_check_dropped",
"(",
")",
"res",
"=",
"self",
".",
"engine",
".",
"execute",
"(",
"self",
".",
"table",
".",
"insert",
"(",
"row",
")",
")",
"if",
"len",
"(",
"res",
".",
"inserte... | Add a row (type: dict) by inserting it into the table.
Columns must exist.
::
data = dict(title='I am a banana!')
table.insert(data)
Returns the inserted row's primary key. | [
"Add",
"a",
"row",
"(",
"type",
":",
"dict",
")",
"by",
"inserting",
"it",
"into",
"the",
"table",
".",
"Columns",
"must",
"exist",
".",
"::",
"data",
"=",
"dict",
"(",
"title",
"=",
"I",
"am",
"a",
"banana!",
")",
"table",
".",
"insert",
"(",
"d... | python | train | 34.153846 |
pantsbuild/pants | src/python/pants/backend/jvm/subsystems/shader.py | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/backend/jvm/subsystems/shader.py#L410-L428 | def binary_shader_for_rules(self, output_jar, jar, rules, jvm_options=None):
"""Yields an `Executor.Runner` that will perform shading of the binary `jar` when `run()`.
No default rules are applied; only the rules passed in as a parameter will be used.
:param unicode output_jar: The path to dump the shaded... | [
"def",
"binary_shader_for_rules",
"(",
"self",
",",
"output_jar",
",",
"jar",
",",
"rules",
",",
"jvm_options",
"=",
"None",
")",
":",
"with",
"self",
".",
"temporary_rules_file",
"(",
"rules",
")",
"as",
"rules_file",
":",
"logger",
".",
"debug",
"(",
"'R... | Yields an `Executor.Runner` that will perform shading of the binary `jar` when `run()`.
No default rules are applied; only the rules passed in as a parameter will be used.
:param unicode output_jar: The path to dump the shaded jar to; will be over-written if it
exists.
:para... | [
"Yields",
"an",
"Executor",
".",
"Runner",
"that",
"will",
"perform",
"shading",
"of",
"the",
"binary",
"jar",
"when",
"run",
"()",
"."
] | python | train | 60.894737 |
dropbox/stone | stone/frontend/ir_generator.py | https://github.com/dropbox/stone/blob/2e95cbcd1c48e05cca68c919fd8d24adec6b0f58/stone/frontend/ir_generator.py#L650-L712 | def _populate_type_attributes(self):
"""
Converts each struct, union, and route from a forward reference to a
full definition.
"""
for namespace in self.api.namespaces.values():
env = self._get_or_create_env(namespace.name)
# do annotations before everyth... | [
"def",
"_populate_type_attributes",
"(",
"self",
")",
":",
"for",
"namespace",
"in",
"self",
".",
"api",
".",
"namespaces",
".",
"values",
"(",
")",
":",
"env",
"=",
"self",
".",
"_get_or_create_env",
"(",
"namespace",
".",
"name",
")",
"# do annotations bef... | Converts each struct, union, and route from a forward reference to a
full definition. | [
"Converts",
"each",
"struct",
"union",
"and",
"route",
"from",
"a",
"forward",
"reference",
"to",
"a",
"full",
"definition",
"."
] | python | train | 48.746032 |
noobermin/pys | pys/__init__.py | https://github.com/noobermin/pys/blob/e01b74210c65eb96d019bb42e0a3c9e6676da943/pys/__init__.py#L110-L121 | def parse_numtuple(s,intype,length=2,scale=1):
'''parse a string into a list of numbers of a type'''
if intype == int:
numrx = intrx_s;
elif intype == float:
numrx = fltrx_s;
else:
raise NotImplementedError("Not implemented for type: {}".format(
intype));
if parse... | [
"def",
"parse_numtuple",
"(",
"s",
",",
"intype",
",",
"length",
"=",
"2",
",",
"scale",
"=",
"1",
")",
":",
"if",
"intype",
"==",
"int",
":",
"numrx",
"=",
"intrx_s",
"elif",
"intype",
"==",
"float",
":",
"numrx",
"=",
"fltrx_s",
"else",
":",
"rai... | parse a string into a list of numbers of a type | [
"parse",
"a",
"string",
"into",
"a",
"list",
"of",
"numbers",
"of",
"a",
"type"
] | python | train | 38.416667 |
pypa/pipenv | pipenv/vendor/vistir/misc.py | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/vistir/misc.py#L470-L489 | def divide(n, iterable):
"""
split an iterable into n groups, per https://more-itertools.readthedocs.io/en/latest/api.html#grouping
:param int n: Number of unique groups
:param iter iterable: An iterable to split up
:return: a list of new iterables derived from the original iterable
:rtype: lis... | [
"def",
"divide",
"(",
"n",
",",
"iterable",
")",
":",
"seq",
"=",
"tuple",
"(",
"iterable",
")",
"q",
",",
"r",
"=",
"divmod",
"(",
"len",
"(",
"seq",
")",
",",
"n",
")",
"ret",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"n",
")",
":",
... | split an iterable into n groups, per https://more-itertools.readthedocs.io/en/latest/api.html#grouping
:param int n: Number of unique groups
:param iter iterable: An iterable to split up
:return: a list of new iterables derived from the original iterable
:rtype: list | [
"split",
"an",
"iterable",
"into",
"n",
"groups",
"per",
"https",
":",
"//",
"more",
"-",
"itertools",
".",
"readthedocs",
".",
"io",
"/",
"en",
"/",
"latest",
"/",
"api",
".",
"html#grouping"
] | python | train | 28.4 |
yandex/yandex-tank | yandextank/plugins/JMeter/reader.py | https://github.com/yandex/yandex-tank/blob/d71d63b6ab5de8b8a5ea2b728b6ab9ac0b1ba71b/yandextank/plugins/JMeter/reader.py#L35-L53 | def _exc_to_net(param1, success):
""" translate http code to net code. if accertion failed, set net code to 314 """
if len(param1) <= 3:
# FIXME: we're unable to use better logic here, because we should support non-http codes
# but, we should look for core.util.HTTP or some other common logic
... | [
"def",
"_exc_to_net",
"(",
"param1",
",",
"success",
")",
":",
"if",
"len",
"(",
"param1",
")",
"<=",
"3",
":",
"# FIXME: we're unable to use better logic here, because we should support non-http codes",
"# but, we should look for core.util.HTTP or some other common logic",
"# he... | translate http code to net code. if accertion failed, set net code to 314 | [
"translate",
"http",
"code",
"to",
"net",
"code",
".",
"if",
"accertion",
"failed",
"set",
"net",
"code",
"to",
"314"
] | python | test | 33.421053 |
IrvKalb/pygwidgets | pygwidgets/pygwidgets.py | https://github.com/IrvKalb/pygwidgets/blob/a830d8885d4d209e471cb53816277d30db56273c/pygwidgets/pygwidgets.py#L470-L477 | def _debug(self):
"""This is just for debugging, so we can see what buttons would be drawn.
Not intended to be used in production."""
self.window.blit(self.surfaceUp, (self.loc[0], 10))
self.window.blit(self.surfaceOver, (self.loc[0], 60))
self.window.blit(self.surfaceDown... | [
"def",
"_debug",
"(",
"self",
")",
":",
"self",
".",
"window",
".",
"blit",
"(",
"self",
".",
"surfaceUp",
",",
"(",
"self",
".",
"loc",
"[",
"0",
"]",
",",
"10",
")",
")",
"self",
".",
"window",
".",
"blit",
"(",
"self",
".",
"surfaceOver",
",... | This is just for debugging, so we can see what buttons would be drawn.
Not intended to be used in production. | [
"This",
"is",
"just",
"for",
"debugging",
"so",
"we",
"can",
"see",
"what",
"buttons",
"would",
"be",
"drawn",
".",
"Not",
"intended",
"to",
"be",
"used",
"in",
"production",
"."
] | python | train | 50.25 |
radjkarl/fancyTools | fancytools/math/blockshaped.py | https://github.com/radjkarl/fancyTools/blob/4c4d961003dc4ed6e46429a0c24f7e2bb52caa8b/fancytools/math/blockshaped.py#L42-L49 | def into2dBlocks(arr, n0, n1):
"""
similar to blockshaped
but splits an array into n0*n1 blocks
"""
s0, s1 = arr.shape
b = blockshaped(arr, s0// n0, s1// n1)
return b.reshape(n0, n1, *b.shape[1:]) | [
"def",
"into2dBlocks",
"(",
"arr",
",",
"n0",
",",
"n1",
")",
":",
"s0",
",",
"s1",
"=",
"arr",
".",
"shape",
"b",
"=",
"blockshaped",
"(",
"arr",
",",
"s0",
"//",
"n0",
",",
"s1",
"//",
"n1",
")",
"return",
"b",
".",
"reshape",
"(",
"n0",
",... | similar to blockshaped
but splits an array into n0*n1 blocks | [
"similar",
"to",
"blockshaped",
"but",
"splits",
"an",
"array",
"into",
"n0",
"*",
"n1",
"blocks"
] | python | train | 27.125 |
galactics/beyond | beyond/frames/stations.py | https://github.com/galactics/beyond/blob/7a7590ff0fd4c0bac3e8e383ecca03caa98e5742/beyond/frames/stations.py#L73-L80 | def _to_parent_frame(self, *args, **kwargs):
"""Conversion from Topocentric Frame to parent frame
"""
lat, lon, _ = self.latlonalt
m = rot3(-lon) @ rot2(lat - np.pi / 2.) @ rot3(self.heading)
offset = np.zeros(6)
offset[:3] = self.coordinates
return self._convert(... | [
"def",
"_to_parent_frame",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"lat",
",",
"lon",
",",
"_",
"=",
"self",
".",
"latlonalt",
"m",
"=",
"rot3",
"(",
"-",
"lon",
")",
"@",
"rot2",
"(",
"lat",
"-",
"np",
".",
"pi",
"/... | Conversion from Topocentric Frame to parent frame | [
"Conversion",
"from",
"Topocentric",
"Frame",
"to",
"parent",
"frame"
] | python | train | 40.75 |
quantopian/pyfolio | pyfolio/timeseries.py | https://github.com/quantopian/pyfolio/blob/712716ab0cdebbec9fabb25eea3bf40e4354749d/pyfolio/timeseries.py#L606-L623 | def gross_lev(positions):
"""
Calculates the gross leverage of a strategy.
Parameters
----------
positions : pd.DataFrame
Daily net position values.
- See full explanation in tears.create_full_tear_sheet.
Returns
-------
pd.Series
Gross leverage.
"""
e... | [
"def",
"gross_lev",
"(",
"positions",
")",
":",
"exposure",
"=",
"positions",
".",
"drop",
"(",
"'cash'",
",",
"axis",
"=",
"1",
")",
".",
"abs",
"(",
")",
".",
"sum",
"(",
"axis",
"=",
"1",
")",
"return",
"exposure",
"/",
"positions",
".",
"sum",
... | Calculates the gross leverage of a strategy.
Parameters
----------
positions : pd.DataFrame
Daily net position values.
- See full explanation in tears.create_full_tear_sheet.
Returns
-------
pd.Series
Gross leverage. | [
"Calculates",
"the",
"gross",
"leverage",
"of",
"a",
"strategy",
"."
] | python | valid | 22.5 |
SheffieldML/GPyOpt | GPyOpt/util/general.py | https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/util/general.py#L131-L142 | def best_value(Y,sign=1):
'''
Returns a vector whose components i are the minimum (default) or maximum of Y[:i]
'''
n = Y.shape[0]
Y_best = np.ones(n)
for i in range(n):
if sign == 1:
Y_best[i]=Y[:(i+1)].min()
else:
Y_best[i]=Y[:(i+1)].max()
return Y_b... | [
"def",
"best_value",
"(",
"Y",
",",
"sign",
"=",
"1",
")",
":",
"n",
"=",
"Y",
".",
"shape",
"[",
"0",
"]",
"Y_best",
"=",
"np",
".",
"ones",
"(",
"n",
")",
"for",
"i",
"in",
"range",
"(",
"n",
")",
":",
"if",
"sign",
"==",
"1",
":",
"Y_b... | Returns a vector whose components i are the minimum (default) or maximum of Y[:i] | [
"Returns",
"a",
"vector",
"whose",
"components",
"i",
"are",
"the",
"minimum",
"(",
"default",
")",
"or",
"maximum",
"of",
"Y",
"[",
":",
"i",
"]"
] | python | train | 26 |
bcbio/bcbio-nextgen | bcbio/distributed/resources.py | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/distributed/resources.py#L100-L117 | def _scale_cores_to_memory(cores, mem_per_core, sysinfo, system_memory):
"""Scale multicore usage to avoid excessive memory usage based on system information.
"""
total_mem = "%.2f" % (cores * mem_per_core + system_memory)
if "cores" not in sysinfo:
return cores, total_mem, 1.0
total_mem = ... | [
"def",
"_scale_cores_to_memory",
"(",
"cores",
",",
"mem_per_core",
",",
"sysinfo",
",",
"system_memory",
")",
":",
"total_mem",
"=",
"\"%.2f\"",
"%",
"(",
"cores",
"*",
"mem_per_core",
"+",
"system_memory",
")",
"if",
"\"cores\"",
"not",
"in",
"sysinfo",
":",... | Scale multicore usage to avoid excessive memory usage based on system information. | [
"Scale",
"multicore",
"usage",
"to",
"avoid",
"excessive",
"memory",
"usage",
"based",
"on",
"system",
"information",
"."
] | python | train | 40.944444 |
djordon/queueing-tool | queueing_tool/queues/queue_servers.py | https://github.com/djordon/queueing-tool/blob/ccd418cf647ac03a54f78ba5e3725903f541b808/queueing_tool/queues/queue_servers.py#L555-L624 | def next_event(self):
"""Simulates the queue forward one event.
Use :meth:`.simulate` instead.
Returns
-------
out : :class:`.Agent` (sometimes)
If the next event is a departure then the departing agent
is returned, otherwise nothing is returned.
... | [
"def",
"next_event",
"(",
"self",
")",
":",
"if",
"self",
".",
"_departures",
"[",
"0",
"]",
".",
"_time",
"<",
"self",
".",
"_arrivals",
"[",
"0",
"]",
".",
"_time",
":",
"new_depart",
"=",
"heappop",
"(",
"self",
".",
"_departures",
")",
"self",
... | Simulates the queue forward one event.
Use :meth:`.simulate` instead.
Returns
-------
out : :class:`.Agent` (sometimes)
If the next event is a departure then the departing agent
is returned, otherwise nothing is returned.
See Also
--------
... | [
"Simulates",
"the",
"queue",
"forward",
"one",
"event",
"."
] | python | valid | 34.8 |
saltstack/salt | salt/modules/dpkg_lowpkg.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/dpkg_lowpkg.py#L172-L211 | def file_list(*packages, **kwargs):
'''
List the files that belong to a package. Not specifying any packages will
return a list of _every_ file on the system's package database (not
generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' lowpkg.file_list httpd
salt... | [
"def",
"file_list",
"(",
"*",
"packages",
",",
"*",
"*",
"kwargs",
")",
":",
"errors",
"=",
"[",
"]",
"ret",
"=",
"set",
"(",
"[",
"]",
")",
"pkgs",
"=",
"{",
"}",
"cmd",
"=",
"'dpkg -l {0}'",
".",
"format",
"(",
"' '",
".",
"join",
"(",
"packa... | List the files that belong to a package. Not specifying any packages will
return a list of _every_ file on the system's package database (not
generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' lowpkg.file_list httpd
salt '*' lowpkg.file_list httpd postfix
salt... | [
"List",
"the",
"files",
"that",
"belong",
"to",
"a",
"package",
".",
"Not",
"specifying",
"any",
"packages",
"will",
"return",
"a",
"list",
"of",
"_every_",
"file",
"on",
"the",
"system",
"s",
"package",
"database",
"(",
"not",
"generally",
"recommended",
... | python | train | 31.125 |
JarryShaw/PyPCAPKit | src/protocols/application/httpv2.py | https://github.com/JarryShaw/PyPCAPKit/blob/c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e/src/protocols/application/httpv2.py#L616-L666 | def _read_http_goaway(self, size, kind, flag):
"""Read HTTP/2 GOAWAY frames.
Structure of HTTP/2 GOAWAY frame [RFC 7540]:
+-----------------------------------------------+
| Length (24) |
+---------------+---------------+------------... | [
"def",
"_read_http_goaway",
"(",
"self",
",",
"size",
",",
"kind",
",",
"flag",
")",
":",
"_dlen",
"=",
"size",
"-",
"8",
"if",
"_dlen",
"<",
"0",
":",
"raise",
"ProtocolError",
"(",
"f'HTTP/2: [Type {kind}] invalid format'",
",",
"quiet",
"=",
"True",
")"... | Read HTTP/2 GOAWAY frames.
Structure of HTTP/2 GOAWAY frame [RFC 7540]:
+-----------------------------------------------+
| Length (24) |
+---------------+---------------+---------------+
| Type (8) | Flags (8) |
... | [
"Read",
"HTTP",
"/",
"2",
"GOAWAY",
"frames",
"."
] | python | train | 47.784314 |
phfaist/pylatexenc | pylatexenc/latexwalker.py | https://github.com/phfaist/pylatexenc/blob/0c1788d1349e749501e67a6fba54d79e6e0d54f6/pylatexenc/latexwalker.py#L1312-L1323 | def get_latex_environment(s, pos, environmentname=None, **parse_flags):
"""
Reads a latex expression enclosed in a \\begin{environment}...\\end{environment}. The first
token in the stream must be the \\begin{environment}.
Returns a tuple (node, pos, len) with node being a :py:class:`LatexEnvironmentNod... | [
"def",
"get_latex_environment",
"(",
"s",
",",
"pos",
",",
"environmentname",
"=",
"None",
",",
"*",
"*",
"parse_flags",
")",
":",
"return",
"LatexWalker",
"(",
"s",
",",
"*",
"*",
"parse_flags",
")",
".",
"get_latex_environment",
"(",
"pos",
"=",
"pos",
... | Reads a latex expression enclosed in a \\begin{environment}...\\end{environment}. The first
token in the stream must be the \\begin{environment}.
Returns a tuple (node, pos, len) with node being a :py:class:`LatexEnvironmentNode`.
.. deprecated:: 1.0
Please use :py:meth:`LatexWalker.get_latex_envir... | [
"Reads",
"a",
"latex",
"expression",
"enclosed",
"in",
"a",
"\\\\",
"begin",
"{",
"environment",
"}",
"...",
"\\\\",
"end",
"{",
"environment",
"}",
".",
"The",
"first",
"token",
"in",
"the",
"stream",
"must",
"be",
"the",
"\\\\",
"begin",
"{",
"environm... | python | test | 43.75 |
saltstack/salt | salt/states/boto_datapipeline.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_datapipeline.py#L469-L482 | def _parameter_values(parameter_values_from_pillars, parameter_value_overrides):
'''
Return a dictionary of parameter values that configure the pipeline
parameter_values_from_pillars
The pillar key to use for lookup
parameter_value_overrides
Parameter values to use. Will override value... | [
"def",
"_parameter_values",
"(",
"parameter_values_from_pillars",
",",
"parameter_value_overrides",
")",
":",
"from_pillars",
"=",
"copy",
".",
"deepcopy",
"(",
"__salt__",
"[",
"'pillar.get'",
"]",
"(",
"parameter_values_from_pillars",
")",
")",
"from_pillars",
".",
... | Return a dictionary of parameter values that configure the pipeline
parameter_values_from_pillars
The pillar key to use for lookup
parameter_value_overrides
Parameter values to use. Will override values read from pillars. | [
"Return",
"a",
"dictionary",
"of",
"parameter",
"values",
"that",
"configure",
"the",
"pipeline"
] | python | train | 42.142857 |
maas/python-libmaas | maas/client/viscera/vlans.py | https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/viscera/vlans.py#L255-L263 | def get_default(self):
"""Return the default VLAN from the set."""
length = len(self)
if length == 0:
return None
elif length == 1:
return self[0]
else:
return sorted(self, key=attrgetter('id'))[0] | [
"def",
"get_default",
"(",
"self",
")",
":",
"length",
"=",
"len",
"(",
"self",
")",
"if",
"length",
"==",
"0",
":",
"return",
"None",
"elif",
"length",
"==",
"1",
":",
"return",
"self",
"[",
"0",
"]",
"else",
":",
"return",
"sorted",
"(",
"self",
... | Return the default VLAN from the set. | [
"Return",
"the",
"default",
"VLAN",
"from",
"the",
"set",
"."
] | python | train | 29.444444 |
mitsei/dlkit | dlkit/json_/repository/sessions.py | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/json_/repository/sessions.py#L1047-L1091 | def get_assets_by_search(self, asset_query, asset_search):
"""Gets the search results matching the given search query using the given search.
arg: asset_query (osid.repository.AssetQuery): the asset
query
arg: asset_search (osid.repository.AssetSearch): the asset
... | [
"def",
"get_assets_by_search",
"(",
"self",
",",
"asset_query",
",",
"asset_search",
")",
":",
"# Implemented from template for",
"# osid.resource.ResourceSearchSession.get_resources_by_search_template",
"# Copied from osid.resource.ResourceQuerySession.get_resources_by_query_template",
"a... | Gets the search results matching the given search query using the given search.
arg: asset_query (osid.repository.AssetQuery): the asset
query
arg: asset_search (osid.repository.AssetSearch): the asset
search
return: (osid.repository.AssetSearchResults) - t... | [
"Gets",
"the",
"search",
"results",
"matching",
"the",
"given",
"search",
"query",
"using",
"the",
"given",
"search",
"."
] | python | train | 49.177778 |
lrq3000/pyFileFixity | pyFileFixity/lib/profilers/visual/debug.py | https://github.com/lrq3000/pyFileFixity/blob/fd5ef23bb13835faf1e3baa773619b86a1cc9bdf/pyFileFixity/lib/profilers/visual/debug.py#L106-L118 | def callgraph(func):
''' Makes a call graph
Note: be sure to install GraphViz prior to printing the dot graph!
'''
import pycallgraph
@functools.wraps(func)
def wrapper(*args, **kwargs):
pycallgraph.start_trace()
func(*args, **kwargs)
pycallgraph.save_dot('callgraph.log')... | [
"def",
"callgraph",
"(",
"func",
")",
":",
"import",
"pycallgraph",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"pycallgraph",
".",
"start_trace",
"(",
")",
"func",
"(",
"*"... | Makes a call graph
Note: be sure to install GraphViz prior to printing the dot graph! | [
"Makes",
"a",
"call",
"graph",
"Note",
":",
"be",
"sure",
"to",
"install",
"GraphViz",
"prior",
"to",
"printing",
"the",
"dot",
"graph!"
] | python | train | 35.384615 |
zachwill/fred | fred/core.py | https://github.com/zachwill/fred/blob/8fb8975e8b4fd8a550f586027dd75cbc2fe225f0/fred/core.py#L32-L36 | def _create_path(self, *args):
"""Create the URL path with the Fred endpoint and given arguments."""
args = filter(None, args)
path = self.endpoint + '/'.join(args)
return path | [
"def",
"_create_path",
"(",
"self",
",",
"*",
"args",
")",
":",
"args",
"=",
"filter",
"(",
"None",
",",
"args",
")",
"path",
"=",
"self",
".",
"endpoint",
"+",
"'/'",
".",
"join",
"(",
"args",
")",
"return",
"path"
] | Create the URL path with the Fred endpoint and given arguments. | [
"Create",
"the",
"URL",
"path",
"with",
"the",
"Fred",
"endpoint",
"and",
"given",
"arguments",
"."
] | python | train | 40.8 |
hobson/aima | aima/agents.py | https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/agents.py#L234-L244 | def step(self):
"""Run the environment for one time step. If the
actions and exogenous changes are independent, this method will
do. If there are interactions between them, you'll need to
override this method."""
if not self.is_done():
actions = [agent.program(self.p... | [
"def",
"step",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"is_done",
"(",
")",
":",
"actions",
"=",
"[",
"agent",
".",
"program",
"(",
"self",
".",
"percept",
"(",
"agent",
")",
")",
"for",
"agent",
"in",
"self",
".",
"agents",
"]",
"for",
... | Run the environment for one time step. If the
actions and exogenous changes are independent, this method will
do. If there are interactions between them, you'll need to
override this method. | [
"Run",
"the",
"environment",
"for",
"one",
"time",
"step",
".",
"If",
"the",
"actions",
"and",
"exogenous",
"changes",
"are",
"independent",
"this",
"method",
"will",
"do",
".",
"If",
"there",
"are",
"interactions",
"between",
"them",
"you",
"ll",
"need",
... | python | valid | 47.454545 |
Phyks/libbmc | libbmc/fetcher.py | https://github.com/Phyks/libbmc/blob/9ef1a29d2514157d1edd6c13ecbd61b07ae9315e/libbmc/fetcher.py#L80-L132 | def download(url, proxies=None):
"""
Download a PDF or DJVU document from a url, eventually using proxies.
:params url: The URL to the PDF/DJVU document to fetch.
:params proxies: An optional list of proxies to use. Proxies will be \
used sequentially. Proxies should be a list of proxy stri... | [
"def",
"download",
"(",
"url",
",",
"proxies",
"=",
"None",
")",
":",
"# Handle default argument",
"if",
"proxies",
"is",
"None",
":",
"proxies",
"=",
"[",
"\"\"",
"]",
"# Loop over all available connections",
"for",
"proxy",
"in",
"proxies",
":",
"# Handle no p... | Download a PDF or DJVU document from a url, eventually using proxies.
:params url: The URL to the PDF/DJVU document to fetch.
:params proxies: An optional list of proxies to use. Proxies will be \
used sequentially. Proxies should be a list of proxy strings. \
Do not forget to include `... | [
"Download",
"a",
"PDF",
"or",
"DJVU",
"document",
"from",
"a",
"url",
"eventually",
"using",
"proxies",
"."
] | python | train | 35.622642 |
django-leonardo/django-leonardo | leonardo/module/media/server/views.py | https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/module/media/server/views.py#L14-L28 | def serve_protected_file(request, path):
"""
Serve protected files to authenticated users with read permissions.
"""
path = path.rstrip('/')
try:
file_obj = File.objects.get(file=path)
except File.DoesNotExist:
raise Http404('File not found %s' % path)
if not file_obj.has_rea... | [
"def",
"serve_protected_file",
"(",
"request",
",",
"path",
")",
":",
"path",
"=",
"path",
".",
"rstrip",
"(",
"'/'",
")",
"try",
":",
"file_obj",
"=",
"File",
".",
"objects",
".",
"get",
"(",
"file",
"=",
"path",
")",
"except",
"File",
".",
"DoesNot... | Serve protected files to authenticated users with read permissions. | [
"Serve",
"protected",
"files",
"to",
"authenticated",
"users",
"with",
"read",
"permissions",
"."
] | python | train | 35.333333 |
apache/incubator-mxnet | tools/rec2idx.py | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/tools/rec2idx.py#L58-L63 | def close(self):
"""Closes the record and index files."""
if not self.is_open:
return
super(IndexCreator, self).close()
self.fidx.close() | [
"def",
"close",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"is_open",
":",
"return",
"super",
"(",
"IndexCreator",
",",
"self",
")",
".",
"close",
"(",
")",
"self",
".",
"fidx",
".",
"close",
"(",
")"
] | Closes the record and index files. | [
"Closes",
"the",
"record",
"and",
"index",
"files",
"."
] | python | train | 29.333333 |
shoebot/shoebot | lib/web/BeautifulSoup.py | https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/web/BeautifulSoup.py#L1524-L1569 | def start_meta(self, attrs):
"""Beautiful Soup can detect a charset included in a META tag,
try to convert the document to that charset, and re-parse the
document from the beginning."""
httpEquiv = None
contentType = None
contentTypeIndex = None
tagNeedsEncodingSu... | [
"def",
"start_meta",
"(",
"self",
",",
"attrs",
")",
":",
"httpEquiv",
"=",
"None",
"contentType",
"=",
"None",
"contentTypeIndex",
"=",
"None",
"tagNeedsEncodingSubstitution",
"=",
"False",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"attrs",
")... | Beautiful Soup can detect a charset included in a META tag,
try to convert the document to that charset, and re-parse the
document from the beginning. | [
"Beautiful",
"Soup",
"can",
"detect",
"a",
"charset",
"included",
"in",
"a",
"META",
"tag",
"try",
"to",
"convert",
"the",
"document",
"to",
"that",
"charset",
"and",
"re",
"-",
"parse",
"the",
"document",
"from",
"the",
"beginning",
"."
] | python | valid | 47.217391 |
ska-sa/katcp-python | katcp/resource_client.py | https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/katcp/resource_client.py#L1169-L1249 | def wait(self, sensor_name, condition_or_value, timeout=5.0, quorum=None,
max_grace_period=1.0):
"""Wait for sensor present on all group clients to satisfy a condition.
Parameters
----------
sensor_name : string
The name of the sensor to check
condition_... | [
"def",
"wait",
"(",
"self",
",",
"sensor_name",
",",
"condition_or_value",
",",
"timeout",
"=",
"5.0",
",",
"quorum",
"=",
"None",
",",
"max_grace_period",
"=",
"1.0",
")",
":",
"if",
"quorum",
"is",
"None",
":",
"quorum",
"=",
"len",
"(",
"self",
".",... | Wait for sensor present on all group clients to satisfy a condition.
Parameters
----------
sensor_name : string
The name of the sensor to check
condition_or_value : obj or callable, or seq of objs or callables
If obj, sensor.value is compared with obj. If callabl... | [
"Wait",
"for",
"sensor",
"present",
"on",
"all",
"group",
"clients",
"to",
"satisfy",
"a",
"condition",
"."
] | python | train | 49.08642 |
aaugustin/websockets | src/websockets/protocol.py | https://github.com/aaugustin/websockets/blob/17b3f47549b6f752a1be07fa1ba3037cb59c7d56/src/websockets/protocol.py#L770-L841 | async def read_message(self) -> Optional[Data]:
"""
Read a single message from the connection.
Re-assemble data frames if the message is fragmented.
Return ``None`` when the closing handshake is started.
"""
frame = await self.read_data_frame(max_size=self.max_size)
... | [
"async",
"def",
"read_message",
"(",
"self",
")",
"->",
"Optional",
"[",
"Data",
"]",
":",
"frame",
"=",
"await",
"self",
".",
"read_data_frame",
"(",
"max_size",
"=",
"self",
".",
"max_size",
")",
"# A close frame was received.",
"if",
"frame",
"is",
"None"... | Read a single message from the connection.
Re-assemble data frames if the message is fragmented.
Return ``None`` when the closing handshake is started. | [
"Read",
"a",
"single",
"message",
"from",
"the",
"connection",
"."
] | python | train | 32.263889 |
Karaage-Cluster/karaage | karaage/common/decorators.py | https://github.com/Karaage-Cluster/karaage/blob/2f4c8b4e2d728b3fcbb151160c49000f1c04f5c9/karaage/common/decorators.py#L30-L50 | def admin_required(function=None):
"""
Decorator for views that checks that the user is an administrator,
redirecting to the log-in page if necessary.
"""
def check_perms(user):
# if user not logged in, show login form
if not user.is_authenticated:
return False
# ... | [
"def",
"admin_required",
"(",
"function",
"=",
"None",
")",
":",
"def",
"check_perms",
"(",
"user",
")",
":",
"# if user not logged in, show login form",
"if",
"not",
"user",
".",
"is_authenticated",
":",
"return",
"False",
"# if this site doesn't allow admin access, fa... | Decorator for views that checks that the user is an administrator,
redirecting to the log-in page if necessary. | [
"Decorator",
"for",
"views",
"that",
"checks",
"that",
"the",
"user",
"is",
"an",
"administrator",
"redirecting",
"to",
"the",
"log",
"-",
"in",
"page",
"if",
"necessary",
"."
] | python | train | 33.714286 |
huggingface/pytorch-pretrained-BERT | examples/extract_features.py | https://github.com/huggingface/pytorch-pretrained-BERT/blob/b832d5bb8a6dfc5965015b828e577677eace601e/examples/extract_features.py#L167-L188 | def read_examples(input_file):
"""Read a list of `InputExample`s from an input file."""
examples = []
unique_id = 0
with open(input_file, "r", encoding='utf-8') as reader:
while True:
line = reader.readline()
if not line:
break
line = line.stri... | [
"def",
"read_examples",
"(",
"input_file",
")",
":",
"examples",
"=",
"[",
"]",
"unique_id",
"=",
"0",
"with",
"open",
"(",
"input_file",
",",
"\"r\"",
",",
"encoding",
"=",
"'utf-8'",
")",
"as",
"reader",
":",
"while",
"True",
":",
"line",
"=",
"reade... | Read a list of `InputExample`s from an input file. | [
"Read",
"a",
"list",
"of",
"InputExample",
"s",
"from",
"an",
"input",
"file",
"."
] | python | train | 32.318182 |
tfoxy/graphene-django-optimizer | graphene_django_optimizer/query.py | https://github.com/tfoxy/graphene-django-optimizer/blob/f9ecbf8952312c46c0b1820253ee824d594ae4a6/graphene_django_optimizer/query.py#L382-L404 | def _get_path_from_parent(self, parent):
"""
Return a list of PathInfos containing the path from the parent
model to the current model, or an empty list if parent is not a
parent of the current model.
"""
if hasattr(self, 'get_path_from_parent'):
return self.get_path_from_parent(parent)
... | [
"def",
"_get_path_from_parent",
"(",
"self",
",",
"parent",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"'get_path_from_parent'",
")",
":",
"return",
"self",
".",
"get_path_from_parent",
"(",
"parent",
")",
"if",
"self",
".",
"model",
"is",
"parent",
":",
... | Return a list of PathInfos containing the path from the parent
model to the current model, or an empty list if parent is not a
parent of the current model. | [
"Return",
"a",
"list",
"of",
"PathInfos",
"containing",
"the",
"path",
"from",
"the",
"parent",
"model",
"to",
"the",
"current",
"model",
"or",
"an",
"empty",
"list",
"if",
"parent",
"is",
"not",
"a",
"parent",
"of",
"the",
"current",
"model",
"."
] | python | train | 36.173913 |
faucamp/python-gsmmodem | gsmmodem/pdu.py | https://github.com/faucamp/python-gsmmodem/blob/834c68b1387ca2c91e2210faa8f75526b39723b5/gsmmodem/pdu.py#L456-L469 | def _decodeRelativeValidityPeriod(tpVp):
""" Calculates the relative SMS validity period (based on the table in section 9.2.3.12 of GSM 03.40)
:rtype: datetime.timedelta
"""
if tpVp <= 143:
return timedelta(minutes=((tpVp + 1) * 5))
elif 144 <= tpVp <= 167:
return timedelta(hours=12,... | [
"def",
"_decodeRelativeValidityPeriod",
"(",
"tpVp",
")",
":",
"if",
"tpVp",
"<=",
"143",
":",
"return",
"timedelta",
"(",
"minutes",
"=",
"(",
"(",
"tpVp",
"+",
"1",
")",
"*",
"5",
")",
")",
"elif",
"144",
"<=",
"tpVp",
"<=",
"167",
":",
"return",
... | Calculates the relative SMS validity period (based on the table in section 9.2.3.12 of GSM 03.40)
:rtype: datetime.timedelta | [
"Calculates",
"the",
"relative",
"SMS",
"validity",
"period",
"(",
"based",
"on",
"the",
"table",
"in",
"section",
"9",
".",
"2",
".",
"3",
".",
"12",
"of",
"GSM",
"03",
".",
"40",
")",
":",
"rtype",
":",
"datetime",
".",
"timedelta"
] | python | train | 39.428571 |
MillionIntegrals/vel | vel/phase/cycle.py | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/phase/cycle.py#L55-L73 | def on_batch_begin(self, batch_info: BatchInfo):
""" Set proper learning rate """
cycle_length = self.cycle_lengths[batch_info.local_epoch_number - 1]
cycle_start = self.cycle_starts[batch_info.local_epoch_number - 1]
numerator = (batch_info.local_epoch_number - cycle_start - 1) * batch... | [
"def",
"on_batch_begin",
"(",
"self",
",",
"batch_info",
":",
"BatchInfo",
")",
":",
"cycle_length",
"=",
"self",
".",
"cycle_lengths",
"[",
"batch_info",
".",
"local_epoch_number",
"-",
"1",
"]",
"cycle_start",
"=",
"self",
".",
"cycle_starts",
"[",
"batch_in... | Set proper learning rate | [
"Set",
"proper",
"learning",
"rate"
] | python | train | 49.736842 |
raymondEhlers/pachyderm | pachyderm/generic_config.py | https://github.com/raymondEhlers/pachyderm/blob/aaa1d8374fd871246290ce76f1796f2f7582b01d/pachyderm/generic_config.py#L249-L293 | def create_key_index_object(key_index_name: str, iterables: Dict[str, Any]) -> Any:
""" Create a ``KeyIndex`` class based on the passed attributes.
This is wrapped into a helper function to allow for the ``__itter__`` to be specified for the object.
Further, this allows it to be called outside the package ... | [
"def",
"create_key_index_object",
"(",
"key_index_name",
":",
"str",
",",
"iterables",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
")",
"->",
"Any",
":",
"# Validation",
"# We are going to use the iterators when determining the fields, so we need to notify if an iterator was",
... | Create a ``KeyIndex`` class based on the passed attributes.
This is wrapped into a helper function to allow for the ``__itter__`` to be specified for the object.
Further, this allows it to be called outside the package when it is needed in analysis tasks..
Args:
key_index_name: Name of the iterabl... | [
"Create",
"a",
"KeyIndex",
"class",
"based",
"on",
"the",
"passed",
"attributes",
"."
] | python | train | 56.866667 |
saltstack/salt | salt/cloud/clouds/nova.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/nova.py#L503-L511 | def managedcloud(vm_):
'''
Determine if we should wait for the managed cloud automation before
running. Either 'False' (default) or 'True'.
'''
return config.get_cloud_config_value(
'managedcloud', vm_, __opts__, default=False,
search_global=False
) | [
"def",
"managedcloud",
"(",
"vm_",
")",
":",
"return",
"config",
".",
"get_cloud_config_value",
"(",
"'managedcloud'",
",",
"vm_",
",",
"__opts__",
",",
"default",
"=",
"False",
",",
"search_global",
"=",
"False",
")"
] | Determine if we should wait for the managed cloud automation before
running. Either 'False' (default) or 'True'. | [
"Determine",
"if",
"we",
"should",
"wait",
"for",
"the",
"managed",
"cloud",
"automation",
"before",
"running",
".",
"Either",
"False",
"(",
"default",
")",
"or",
"True",
"."
] | python | train | 31.222222 |
keflavich/plfit | plfit/plfit_py.py | https://github.com/keflavich/plfit/blob/7dafa6302b427ba8c89651148e3e9d29add436c3/plfit/plfit_py.py#L54-L71 | def alpha_(self,x):
""" Create a mappable function alpha to apply to each xmin in a list of xmins.
This is essentially the slow version of fplfit/cplfit, though I bet it could
be speeded up with a clever use of parellel_map. Not intended to be used by users."""
def alpha(xmin,x=x):
... | [
"def",
"alpha_",
"(",
"self",
",",
"x",
")",
":",
"def",
"alpha",
"(",
"xmin",
",",
"x",
"=",
"x",
")",
":",
"\"\"\"\n given a sorted data set and a minimum, returns power law MLE fit\n data is passed as a keyword parameter so that it can be vectorized\n ... | Create a mappable function alpha to apply to each xmin in a list of xmins.
This is essentially the slow version of fplfit/cplfit, though I bet it could
be speeded up with a clever use of parellel_map. Not intended to be used by users. | [
"Create",
"a",
"mappable",
"function",
"alpha",
"to",
"apply",
"to",
"each",
"xmin",
"in",
"a",
"list",
"of",
"xmins",
".",
"This",
"is",
"essentially",
"the",
"slow",
"version",
"of",
"fplfit",
"/",
"cplfit",
"though",
"I",
"bet",
"it",
"could",
"be",
... | python | test | 46.611111 |
heikomuller/sco-datastore | scodata/experiment.py | https://github.com/heikomuller/sco-datastore/blob/7180a6b51150667e47629da566aedaa742e39342/scodata/experiment.py#L153-L181 | def from_dict(self, document):
"""Create experiment object from JSON document retrieved from database.
Parameters
----------
document : JSON
Json document in database
Returns
-------
ExperimentHandle
Handle for experiment object
"... | [
"def",
"from_dict",
"(",
"self",
",",
"document",
")",
":",
"identifier",
"=",
"str",
"(",
"document",
"[",
"'_id'",
"]",
")",
"active",
"=",
"document",
"[",
"'active'",
"]",
"timestamp",
"=",
"datetime",
".",
"datetime",
".",
"strptime",
"(",
"document... | Create experiment object from JSON document retrieved from database.
Parameters
----------
document : JSON
Json document in database
Returns
-------
ExperimentHandle
Handle for experiment object | [
"Create",
"experiment",
"object",
"from",
"JSON",
"document",
"retrieved",
"from",
"database",
"."
] | python | train | 31.413793 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.