repo stringlengths 7 54 | path stringlengths 4 192 | url stringlengths 87 284 | code stringlengths 78 104k | code_tokens list | docstring stringlengths 1 46.9k | docstring_tokens list | language stringclasses 1
value | partition stringclasses 3
values |
|---|---|---|---|---|---|---|---|---|
klmitch/framer | framer/framers.py | https://github.com/klmitch/framer/blob/bd34cee9737793dab61d1d8973930b64bd08acb4/framer/framers.py#L838-L854 | def to_bytes(self, frame, state):
"""
Convert a single frame into bytes that can be transmitted on
the stream.
:param frame: The frame to convert. Should be the same type
of object returned by ``to_frame()``.
:param state: An instance of ``FramerState``. ... | [
"def",
"to_bytes",
"(",
"self",
",",
"frame",
",",
"state",
")",
":",
"# Encode the frame and append the delimiter",
"return",
"six",
".",
"binary_type",
"(",
"self",
".",
"variant",
".",
"encode",
"(",
"six",
".",
"binary_type",
"(",
"frame",
")",
")",
")",... | Convert a single frame into bytes that can be transmitted on
the stream.
:param frame: The frame to convert. Should be the same type
of object returned by ``to_frame()``.
:param state: An instance of ``FramerState``. This object may
be used to track... | [
"Convert",
"a",
"single",
"frame",
"into",
"bytes",
"that",
"can",
"be",
"transmitted",
"on",
"the",
"stream",
"."
] | python | train |
yvesalexandre/bandicoot | bandicoot/helper/stops.py | https://github.com/yvesalexandre/bandicoot/blob/73a658f6f17331541cf0b1547028db9b70e8d58a/bandicoot/helper/stops.py#L46-L86 | def dbscan(points, eps, minpts):
"""
Implementation of [DBSCAN]_ (*A density-based algorithm for discovering
clusters in large spatial databases with noise*). It accepts a list of
points (lat, lon) and returns the labels associated with the points.
References
----------
.. [DBSCAN] Ester, M... | [
"def",
"dbscan",
"(",
"points",
",",
"eps",
",",
"minpts",
")",
":",
"next_label",
"=",
"0",
"n",
"=",
"len",
"(",
"points",
")",
"labels",
"=",
"[",
"None",
"]",
"*",
"n",
"distance_matrix",
"=",
"compute_distance_matrix",
"(",
"points",
")",
"neighbo... | Implementation of [DBSCAN]_ (*A density-based algorithm for discovering
clusters in large spatial databases with noise*). It accepts a list of
points (lat, lon) and returns the labels associated with the points.
References
----------
.. [DBSCAN] Ester, M., Kriegel, H. P., Sander, J., & Xu, X. (1996... | [
"Implementation",
"of",
"[",
"DBSCAN",
"]",
"_",
"(",
"*",
"A",
"density",
"-",
"based",
"algorithm",
"for",
"discovering",
"clusters",
"in",
"large",
"spatial",
"databases",
"with",
"noise",
"*",
")",
".",
"It",
"accepts",
"a",
"list",
"of",
"points",
"... | python | train |
merll/docker-fabric | dockerfabric/tasks.py | https://github.com/merll/docker-fabric/blob/785d84e40e17265b667d8b11a6e30d8e6b2bf8d4/dockerfabric/tasks.py#L116-L126 | def list_images(list_all=False, full_ids=False):
"""
Lists images on the Docker remote host, similar to ``docker images``.
:param list_all: Lists all images (e.g. dependencies). Default is ``False``, only shows named images.
:type list_all: bool
:param full_ids: Shows the full ids. When ``False`` (... | [
"def",
"list_images",
"(",
"list_all",
"=",
"False",
",",
"full_ids",
"=",
"False",
")",
":",
"images",
"=",
"docker_fabric",
"(",
")",
".",
"images",
"(",
"all",
"=",
"list_all",
")",
"_format_output_table",
"(",
"images",
",",
"IMAGE_COLUMNS",
",",
"full... | Lists images on the Docker remote host, similar to ``docker images``.
:param list_all: Lists all images (e.g. dependencies). Default is ``False``, only shows named images.
:type list_all: bool
:param full_ids: Shows the full ids. When ``False`` (default) only shows the first 12 characters.
:type full_i... | [
"Lists",
"images",
"on",
"the",
"Docker",
"remote",
"host",
"similar",
"to",
"docker",
"images",
"."
] | python | train |
PmagPy/PmagPy | pmagpy/builder2.py | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/pmagpy/builder2.py#L833-L877 | def read_magic_file(self, path, sort_by_this_name, sort_by_file_type=False):
"""
read a magic-formatted tab-delimited file.
return a dictionary of dictionaries, with this format:
{'Z35.5a': {'specimen_weight': '1.000e-03', 'er_citation_names': 'This study', 'specimen_volume': '', 'er_loc... | [
"def",
"read_magic_file",
"(",
"self",
",",
"path",
",",
"sort_by_this_name",
",",
"sort_by_file_type",
"=",
"False",
")",
":",
"DATA",
"=",
"{",
"}",
"with",
"open",
"(",
"path",
",",
"'r'",
")",
"as",
"fin",
":",
"lines",
"=",
"list",
"(",
"fin",
"... | read a magic-formatted tab-delimited file.
return a dictionary of dictionaries, with this format:
{'Z35.5a': {'specimen_weight': '1.000e-03', 'er_citation_names': 'This study', 'specimen_volume': '', 'er_location_name': '', 'er_site_name': 'Z35.', 'er_sample_name': 'Z35.5', 'specimen_class': '', 'er_spe... | [
"read",
"a",
"magic",
"-",
"formatted",
"tab",
"-",
"delimited",
"file",
".",
"return",
"a",
"dictionary",
"of",
"dictionaries",
"with",
"this",
"format",
":",
"{",
"Z35",
".",
"5a",
":",
"{",
"specimen_weight",
":",
"1",
".",
"000e",
"-",
"03",
"er_ci... | python | train |
trendels/rhino | rhino/http.py | https://github.com/trendels/rhino/blob/f1f0ef21b6080a2bd130b38b5bef163074c94aed/rhino/http.py#L60-L79 | def match_etag(etag, header, weak=False):
"""Try to match an ETag against a header value.
If `weak` is True, uses the weak comparison function.
"""
if etag is None:
return False
m = etag_re.match(etag)
if not m:
raise ValueError("Not a well-formed ETag: '%s'" % etag)
(is_wea... | [
"def",
"match_etag",
"(",
"etag",
",",
"header",
",",
"weak",
"=",
"False",
")",
":",
"if",
"etag",
"is",
"None",
":",
"return",
"False",
"m",
"=",
"etag_re",
".",
"match",
"(",
"etag",
")",
"if",
"not",
"m",
":",
"raise",
"ValueError",
"(",
"\"Not... | Try to match an ETag against a header value.
If `weak` is True, uses the weak comparison function. | [
"Try",
"to",
"match",
"an",
"ETag",
"against",
"a",
"header",
"value",
"."
] | python | train |
BeyondTheClouds/enoslib | enoslib/api.py | https://github.com/BeyondTheClouds/enoslib/blob/fb00be58e56a7848cfe482187d659744919fe2f7/enoslib/api.py#L782-L807 | def wait_ssh(roles, retries=100, interval=30):
"""Wait for all the machines to be ssh-reachable
Let ansible initiates a communication and retries if needed.
Args:
inventory (string): path to the inventoy file to test
retries (int): Number of time we'll be retrying an SSH connection
... | [
"def",
"wait_ssh",
"(",
"roles",
",",
"retries",
"=",
"100",
",",
"interval",
"=",
"30",
")",
":",
"utils_playbook",
"=",
"os",
".",
"path",
".",
"join",
"(",
"ANSIBLE_DIR",
",",
"'utils.yml'",
")",
"options",
"=",
"{",
"'enos_action'",
":",
"'ping'",
... | Wait for all the machines to be ssh-reachable
Let ansible initiates a communication and retries if needed.
Args:
inventory (string): path to the inventoy file to test
retries (int): Number of time we'll be retrying an SSH connection
interval (int): Interval to wait in seconds between t... | [
"Wait",
"for",
"all",
"the",
"machines",
"to",
"be",
"ssh",
"-",
"reachable"
] | python | train |
QInfer/python-qinfer | src/qinfer/simple_est.py | https://github.com/QInfer/python-qinfer/blob/8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3/src/qinfer/simple_est.py#L70-L106 | def data_to_params(data,
expparams_dtype,
col_outcomes=(0, 'counts'),
cols_expparams=None
):
"""
Given data as a NumPy array, separates out each column either as
the outcomes, or as a field of an expparams array. Columns may be specified
either as indices into a two-axis scal... | [
"def",
"data_to_params",
"(",
"data",
",",
"expparams_dtype",
",",
"col_outcomes",
"=",
"(",
"0",
",",
"'counts'",
")",
",",
"cols_expparams",
"=",
"None",
")",
":",
"BY_IDX",
",",
"BY_NAME",
"=",
"range",
"(",
"2",
")",
"is_exp_scalar",
"=",
"np",
".",
... | Given data as a NumPy array, separates out each column either as
the outcomes, or as a field of an expparams array. Columns may be specified
either as indices into a two-axis scalar array, or as field names for a one-axis
record array.
Since scalar arrays are homogenous in type, this may result in loss... | [
"Given",
"data",
"as",
"a",
"NumPy",
"array",
"separates",
"out",
"each",
"column",
"either",
"as",
"the",
"outcomes",
"or",
"as",
"a",
"field",
"of",
"an",
"expparams",
"array",
".",
"Columns",
"may",
"be",
"specified",
"either",
"as",
"indices",
"into",
... | python | train |
Parisson/TimeSide | timeside/plugins/grapher/utils.py | https://github.com/Parisson/TimeSide/blob/0618d75cd2f16021afcfd3d5b77f692adad76ea5/timeside/plugins/grapher/utils.py#L72-L81 | def downsample(vector, factor):
"""
downsample(vector, factor):
Downsample (by averaging) a vector by an integer factor.
"""
if (len(vector) % factor):
print "Length of 'vector' is not divisible by 'factor'=%d!" % factor
return 0
vector.shape = (len(vector) / factor, factor)
... | [
"def",
"downsample",
"(",
"vector",
",",
"factor",
")",
":",
"if",
"(",
"len",
"(",
"vector",
")",
"%",
"factor",
")",
":",
"print",
"\"Length of 'vector' is not divisible by 'factor'=%d!\"",
"%",
"factor",
"return",
"0",
"vector",
".",
"shape",
"=",
"(",
"l... | downsample(vector, factor):
Downsample (by averaging) a vector by an integer factor. | [
"downsample",
"(",
"vector",
"factor",
")",
":",
"Downsample",
"(",
"by",
"averaging",
")",
"a",
"vector",
"by",
"an",
"integer",
"factor",
"."
] | python | train |
riptano/ccm | ccmlib/cluster.py | https://github.com/riptano/ccm/blob/275699f79d102b5039b79cc17fa6305dccf18412/ccmlib/cluster.py#L677-L701 | def timed_grep_nodes_for_patterns(self, versions_to_patterns, timeout_seconds, filename="system.log"):
"""
Searches all nodes in the cluster for a specific regular expression based on the node's version.
Params:
@versions_to_patterns : an instance of LogPatternToVersionMap, specifying th... | [
"def",
"timed_grep_nodes_for_patterns",
"(",
"self",
",",
"versions_to_patterns",
",",
"timeout_seconds",
",",
"filename",
"=",
"\"system.log\"",
")",
":",
"end_time",
"=",
"time",
".",
"time",
"(",
")",
"+",
"timeout_seconds",
"while",
"True",
":",
"if",
"time"... | Searches all nodes in the cluster for a specific regular expression based on the node's version.
Params:
@versions_to_patterns : an instance of LogPatternToVersionMap, specifying the different log patterns based on a node's version.
@version : the earliest version the new pattern was introduced.... | [
"Searches",
"all",
"nodes",
"in",
"the",
"cluster",
"for",
"a",
"specific",
"regular",
"expression",
"based",
"on",
"the",
"node",
"s",
"version",
".",
"Params",
":",
"@versions_to_patterns",
":",
"an",
"instance",
"of",
"LogPatternToVersionMap",
"specifying",
"... | python | train |
lemieuxl/pyGenClean | pyGenClean/LaTeX/merge_reports.py | https://github.com/lemieuxl/pyGenClean/blob/6173a48ccc0cf3a3bd711b1f2a1fa16248b8bf55/pyGenClean/LaTeX/merge_reports.py#L288-L321 | def checkArgs(args):
"""Checks the arguments and options.
:param args: an object containing the options of the program.
:type args: argparse.Namespace
:returns: ``True`` if everything was OK.
If there is a problem with an option, an exception is raised using the
:py:class:`ProgramError` clas... | [
"def",
"checkArgs",
"(",
"args",
")",
":",
"# For all input directories",
"for",
"dn",
"in",
"args",
".",
"qc_dir",
":",
"# Checking that all the directories exists",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"dn",
")",
":",
"raise",
"ProgramError",
"... | Checks the arguments and options.
:param args: an object containing the options of the program.
:type args: argparse.Namespace
:returns: ``True`` if everything was OK.
If there is a problem with an option, an exception is raised using the
:py:class:`ProgramError` class, a message is printed to t... | [
"Checks",
"the",
"arguments",
"and",
"options",
"."
] | python | train |
SheffieldML/GPy | GPy/kern/src/stationary.py | https://github.com/SheffieldML/GPy/blob/54c32d79d289d622fb18b898aee65a2a431d90cf/GPy/kern/src/stationary.py#L193-L213 | def update_gradients_full(self, dL_dK, X, X2=None, reset=True):
"""
Given the derivative of the objective wrt the covariance matrix
(dL_dK), compute the gradient wrt the parameters of this kernel,
and store in the parameters object as e.g. self.variance.gradient
"""
self.... | [
"def",
"update_gradients_full",
"(",
"self",
",",
"dL_dK",
",",
"X",
",",
"X2",
"=",
"None",
",",
"reset",
"=",
"True",
")",
":",
"self",
".",
"variance",
".",
"gradient",
"=",
"np",
".",
"sum",
"(",
"self",
".",
"K",
"(",
"X",
",",
"X2",
")",
... | Given the derivative of the objective wrt the covariance matrix
(dL_dK), compute the gradient wrt the parameters of this kernel,
and store in the parameters object as e.g. self.variance.gradient | [
"Given",
"the",
"derivative",
"of",
"the",
"objective",
"wrt",
"the",
"covariance",
"matrix",
"(",
"dL_dK",
")",
"compute",
"the",
"gradient",
"wrt",
"the",
"parameters",
"of",
"this",
"kernel",
"and",
"store",
"in",
"the",
"parameters",
"object",
"as",
"e",... | python | train |
CiscoDevNet/webexteamssdk | webexteamssdk/utils.py | https://github.com/CiscoDevNet/webexteamssdk/blob/6fc2cc3557e080ba4b2a380664cb2a0532ae45cd/webexteamssdk/utils.py#L234-L255 | def json_dict(json_data):
"""Given a dictionary or JSON string; return a dictionary.
Args:
json_data(dict, str): Input JSON object.
Returns:
A Python dictionary with the contents of the JSON object.
Raises:
TypeError: If the input object is not a dictionary or string.
"""... | [
"def",
"json_dict",
"(",
"json_data",
")",
":",
"if",
"isinstance",
"(",
"json_data",
",",
"dict",
")",
":",
"return",
"json_data",
"elif",
"isinstance",
"(",
"json_data",
",",
"basestring",
")",
":",
"return",
"json",
".",
"loads",
"(",
"json_data",
",",
... | Given a dictionary or JSON string; return a dictionary.
Args:
json_data(dict, str): Input JSON object.
Returns:
A Python dictionary with the contents of the JSON object.
Raises:
TypeError: If the input object is not a dictionary or string. | [
"Given",
"a",
"dictionary",
"or",
"JSON",
"string",
";",
"return",
"a",
"dictionary",
"."
] | python | test |
inveniosoftware/invenio-oaiserver | invenio_oaiserver/ext.py | https://github.com/inveniosoftware/invenio-oaiserver/blob/eae765e32bd816ddc5612d4b281caf205518b512/invenio_oaiserver/ext.py#L58-L65 | def register_signals_oaiset(self):
"""Register OAISet signals to update records."""
from .models import OAISet
from .receivers import after_insert_oai_set, \
after_update_oai_set, after_delete_oai_set
listen(OAISet, 'after_insert', after_insert_oai_set)
listen(OAISet,... | [
"def",
"register_signals_oaiset",
"(",
"self",
")",
":",
"from",
".",
"models",
"import",
"OAISet",
"from",
".",
"receivers",
"import",
"after_insert_oai_set",
",",
"after_update_oai_set",
",",
"after_delete_oai_set",
"listen",
"(",
"OAISet",
",",
"'after_insert'",
... | Register OAISet signals to update records. | [
"Register",
"OAISet",
"signals",
"to",
"update",
"records",
"."
] | python | train |
thebjorn/pydeps | pydeps/render_context.py | https://github.com/thebjorn/pydeps/blob/1e6715b7bea47a40e8042821b57937deaaa0fdc3/pydeps/render_context.py#L47-L52 | def text(self):
"""Get value of output stream (StringIO).
"""
if self.out:
self.out.close() # pragma: nocover
return self.fp.getvalue() | [
"def",
"text",
"(",
"self",
")",
":",
"if",
"self",
".",
"out",
":",
"self",
".",
"out",
".",
"close",
"(",
")",
"# pragma: nocover",
"return",
"self",
".",
"fp",
".",
"getvalue",
"(",
")"
] | Get value of output stream (StringIO). | [
"Get",
"value",
"of",
"output",
"stream",
"(",
"StringIO",
")",
"."
] | python | train |
LionelAuroux/pyrser | pyrser/grammar.py | https://github.com/LionelAuroux/pyrser/blob/f153a97ef2b6bf915a1ed468c0252a9a59b754d5/pyrser/grammar.py#L191-L203 | def from_file(fn: str, entry=None, *optional_inherit) -> Grammar:
"""
Create a Grammar from a file
"""
import os.path
if os.path.exists(fn):
f = open(fn, 'r')
bnf = f.read()
f.close()
inherit = [Grammar] + list(optional_inherit)
scope = {'grammar': bnf, 'entry... | [
"def",
"from_file",
"(",
"fn",
":",
"str",
",",
"entry",
"=",
"None",
",",
"*",
"optional_inherit",
")",
"->",
"Grammar",
":",
"import",
"os",
".",
"path",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"fn",
")",
":",
"f",
"=",
"open",
"(",
"fn",
... | Create a Grammar from a file | [
"Create",
"a",
"Grammar",
"from",
"a",
"file"
] | python | test |
python-bonobo/bonobo | bonobo/commands/__init__.py | https://github.com/python-bonobo/bonobo/blob/70c8e62c4a88576976e5b52e58d380d6e3227ab4/bonobo/commands/__init__.py#L9-L64 | def entrypoint(args=None):
"""
Main callable for "bonobo" entrypoint.
Will load commands from "bonobo.commands" entrypoints, using stevedore.
"""
mondrian.setup(excepthook=True)
logger = logging.getLogger()
logger.setLevel(settings.LOGGING_LEVEL.get())
parser = argparse.ArgumentParse... | [
"def",
"entrypoint",
"(",
"args",
"=",
"None",
")",
":",
"mondrian",
".",
"setup",
"(",
"excepthook",
"=",
"True",
")",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
")",
"logger",
".",
"setLevel",
"(",
"settings",
".",
"LOGGING_LEVEL",
".",
"get",
... | Main callable for "bonobo" entrypoint.
Will load commands from "bonobo.commands" entrypoints, using stevedore. | [
"Main",
"callable",
"for",
"bonobo",
"entrypoint",
"."
] | python | train |
bkjones/pyrabbit | pyrabbit/api.py | https://github.com/bkjones/pyrabbit/blob/e8a9f74ed5c6bba958994fb9a72c396e6a99ea0f/pyrabbit/api.py#L218-L230 | def get_vhost(self, vname):
"""
Returns the attributes of a single named vhost in a dict.
:param string vname: Name of the vhost to get.
:returns dict vhost: Attribute dict for the named vhost
"""
vname = quote(vname, '')
path = Client.urls['vhosts_by_name'] % ... | [
"def",
"get_vhost",
"(",
"self",
",",
"vname",
")",
":",
"vname",
"=",
"quote",
"(",
"vname",
",",
"''",
")",
"path",
"=",
"Client",
".",
"urls",
"[",
"'vhosts_by_name'",
"]",
"%",
"vname",
"vhost",
"=",
"self",
".",
"_call",
"(",
"path",
",",
"'GE... | Returns the attributes of a single named vhost in a dict.
:param string vname: Name of the vhost to get.
:returns dict vhost: Attribute dict for the named vhost | [
"Returns",
"the",
"attributes",
"of",
"a",
"single",
"named",
"vhost",
"in",
"a",
"dict",
"."
] | python | train |
ethereum/py-trie | trie/binary.py | https://github.com/ethereum/py-trie/blob/d33108d21b54d59ee311f61d978496c84a6f1f8b/trie/binary.py#L297-L303 | def delete(self, key):
"""
Equals to setting the value to None
"""
validate_is_bytes(key)
self.root_hash = self._set(self.root_hash, encode_to_bin(key), b'') | [
"def",
"delete",
"(",
"self",
",",
"key",
")",
":",
"validate_is_bytes",
"(",
"key",
")",
"self",
".",
"root_hash",
"=",
"self",
".",
"_set",
"(",
"self",
".",
"root_hash",
",",
"encode_to_bin",
"(",
"key",
")",
",",
"b''",
")"
] | Equals to setting the value to None | [
"Equals",
"to",
"setting",
"the",
"value",
"to",
"None"
] | python | train |
grycap/RADL | radl/radl_parse.py | https://github.com/grycap/RADL/blob/03ccabb0313a48a5aa0e20c1f7983fddcb95e9cb/radl/radl_parse.py#L236-L246 | def p_contextualize_items(self, t):
"""contextualize_items : contextualize_items contextualize_item
| contextualize_item
| empty"""
if len(t) == 3:
t[0] = t[1]
t[0].append(t[2])
elif t[1]:
t[0] = [t... | [
"def",
"p_contextualize_items",
"(",
"self",
",",
"t",
")",
":",
"if",
"len",
"(",
"t",
")",
"==",
"3",
":",
"t",
"[",
"0",
"]",
"=",
"t",
"[",
"1",
"]",
"t",
"[",
"0",
"]",
".",
"append",
"(",
"t",
"[",
"2",
"]",
")",
"elif",
"t",
"[",
... | contextualize_items : contextualize_items contextualize_item
| contextualize_item
| empty | [
"contextualize_items",
":",
"contextualize_items",
"contextualize_item",
"|",
"contextualize_item",
"|",
"empty"
] | python | train |
saltstack/salt | salt/modules/win_iis.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_iis.py#L1749-L1784 | def create_backup(name):
r'''
Backup an IIS Configuration on the System.
.. versionadded:: 2017.7.0
.. note::
Backups are stored in the ``$env:Windir\System32\inetsrv\backup``
folder.
Args:
name (str): The name to give the backup
Returns:
bool: True if success... | [
"def",
"create_backup",
"(",
"name",
")",
":",
"if",
"name",
"in",
"list_backups",
"(",
")",
":",
"raise",
"CommandExecutionError",
"(",
"'Backup already present: {0}'",
".",
"format",
"(",
"name",
")",
")",
"ps_cmd",
"=",
"[",
"'Backup-WebConfiguration'",
",",
... | r'''
Backup an IIS Configuration on the System.
.. versionadded:: 2017.7.0
.. note::
Backups are stored in the ``$env:Windir\System32\inetsrv\backup``
folder.
Args:
name (str): The name to give the backup
Returns:
bool: True if successful, otherwise False
CLI... | [
"r",
"Backup",
"an",
"IIS",
"Configuration",
"on",
"the",
"System",
"."
] | python | train |
gear11/pypelogs | pypeout/mysql_out.py | https://github.com/gear11/pypelogs/blob/da5dc0fee5373a4be294798b5e32cd0a803d8bbe/pypeout/mysql_out.py#L43-L53 | def get_existing_keys(self, events):
"""Returns the list of keys from the given event source that are already in the DB"""
data = [e[self.key] for e in events]
ss = ','.join(['%s' for _ in data])
query = 'SELECT %s FROM %s WHERE %s IN (%s)' % (self.key, self.table, self.key, ss)
... | [
"def",
"get_existing_keys",
"(",
"self",
",",
"events",
")",
":",
"data",
"=",
"[",
"e",
"[",
"self",
".",
"key",
"]",
"for",
"e",
"in",
"events",
"]",
"ss",
"=",
"','",
".",
"join",
"(",
"[",
"'%s'",
"for",
"_",
"in",
"data",
"]",
")",
"query"... | Returns the list of keys from the given event source that are already in the DB | [
"Returns",
"the",
"list",
"of",
"keys",
"from",
"the",
"given",
"event",
"source",
"that",
"are",
"already",
"in",
"the",
"DB"
] | python | train |
grundic/yagocd | yagocd/resources/pipeline.py | https://github.com/grundic/yagocd/blob/4c75336ae6f107c8723d37b15e52169151822127/yagocd/resources/pipeline.py#L642-L653 | def stages(self):
"""
Method for getting stages from pipeline instance.
:return: arrays of stages
:rtype: list of yagocd.resources.stage.StageInstance
"""
stages = list()
for data in self.data.stages:
stages.append(StageInstance(session=self._session,... | [
"def",
"stages",
"(",
"self",
")",
":",
"stages",
"=",
"list",
"(",
")",
"for",
"data",
"in",
"self",
".",
"data",
".",
"stages",
":",
"stages",
".",
"append",
"(",
"StageInstance",
"(",
"session",
"=",
"self",
".",
"_session",
",",
"data",
"=",
"d... | Method for getting stages from pipeline instance.
:return: arrays of stages
:rtype: list of yagocd.resources.stage.StageInstance | [
"Method",
"for",
"getting",
"stages",
"from",
"pipeline",
"instance",
"."
] | python | train |
bcbio/bcbio-nextgen | bcbio/distributed/ipython.py | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/distributed/ipython.py#L33-L65 | def create(parallel, dirs, config):
"""Create a cluster based on the provided parallel arguments.
Returns an IPython view on the cluster, enabling processing on jobs.
Adds a mincores specification if he have machines with a larger
number of cores to allow jobs to be batched together for shared
mem... | [
"def",
"create",
"(",
"parallel",
",",
"dirs",
",",
"config",
")",
":",
"profile_dir",
"=",
"utils",
".",
"safe_makedir",
"(",
"os",
".",
"path",
".",
"join",
"(",
"dirs",
"[",
"\"work\"",
"]",
",",
"get_log_dir",
"(",
"config",
")",
",",
"\"ipython\""... | Create a cluster based on the provided parallel arguments.
Returns an IPython view on the cluster, enabling processing on jobs.
Adds a mincores specification if he have machines with a larger
number of cores to allow jobs to be batched together for shared
memory usage. | [
"Create",
"a",
"cluster",
"based",
"on",
"the",
"provided",
"parallel",
"arguments",
"."
] | python | train |
DLR-RM/RAFCON | source/rafcon/gui/mygaphas/items/ports.py | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/mygaphas/items/ports.py#L856-L877 | def _get_port_center_position(self, width):
"""Calculates the center position of the port rectangle
The port itself can be positioned in the corner, the center of the port rectangle however is restricted by
the width of the rectangle. This method therefore calculates the center, depending on th... | [
"def",
"_get_port_center_position",
"(",
"self",
",",
"width",
")",
":",
"x",
",",
"y",
"=",
"self",
".",
"pos",
".",
"x",
".",
"value",
",",
"self",
".",
"pos",
".",
"y",
".",
"value",
"if",
"self",
".",
"side",
"is",
"SnappedSide",
".",
"TOP",
... | Calculates the center position of the port rectangle
The port itself can be positioned in the corner, the center of the port rectangle however is restricted by
the width of the rectangle. This method therefore calculates the center, depending on the position of the
port and the width of the rec... | [
"Calculates",
"the",
"center",
"position",
"of",
"the",
"port",
"rectangle"
] | python | train |
bitcraze/crazyflie-lib-python | cflib/crazyflie/localization.py | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crazyflie/localization.py#L113-L122 | def send_short_lpp_packet(self, dest_id, data):
"""
Send ultra-wide-band LPP packet to dest_id
"""
pk = CRTPPacket()
pk.port = CRTPPort.LOCALIZATION
pk.channel = self.GENERIC_CH
pk.data = struct.pack('<BB', self.LPS_SHORT_LPP_PACKET, dest_id) + data
self.... | [
"def",
"send_short_lpp_packet",
"(",
"self",
",",
"dest_id",
",",
"data",
")",
":",
"pk",
"=",
"CRTPPacket",
"(",
")",
"pk",
".",
"port",
"=",
"CRTPPort",
".",
"LOCALIZATION",
"pk",
".",
"channel",
"=",
"self",
".",
"GENERIC_CH",
"pk",
".",
"data",
"="... | Send ultra-wide-band LPP packet to dest_id | [
"Send",
"ultra",
"-",
"wide",
"-",
"band",
"LPP",
"packet",
"to",
"dest_id"
] | python | train |
swharden/SWHLab | scripts/old/helper.py | https://github.com/swharden/SWHLab/blob/a86c3c65323cec809a4bd4f81919644927094bf5/scripts/old/helper.py#L12-L25 | def newVersion():
"""increments version counter in swhlab/version.py"""
version=None
fname='../swhlab/version.py'
with open(fname) as f:
raw=f.read().split("\n")
for i,line in enumerate(raw):
if line.startswith("__counter__"):
if version is None:
... | [
"def",
"newVersion",
"(",
")",
":",
"version",
"=",
"None",
"fname",
"=",
"'../swhlab/version.py'",
"with",
"open",
"(",
"fname",
")",
"as",
"f",
":",
"raw",
"=",
"f",
".",
"read",
"(",
")",
".",
"split",
"(",
"\"\\n\"",
")",
"for",
"i",
",",
"line... | increments version counter in swhlab/version.py | [
"increments",
"version",
"counter",
"in",
"swhlab",
"/",
"version",
".",
"py"
] | python | valid |
moralrecordings/mrcrowbar | mrcrowbar/utils.py | https://github.com/moralrecordings/mrcrowbar/blob/b1ed882c4555552e7656b2d84aca543184577fa3/mrcrowbar/utils.py#L592-L627 | def put_bits( self, value, count ):
"""Push bits into the target.
value
Integer containing bits to push, ordered from least-significant bit to
most-significant bit.
count
Number of bits to push to the target.
"""
for _ in range( count ):
... | [
"def",
"put_bits",
"(",
"self",
",",
"value",
",",
"count",
")",
":",
"for",
"_",
"in",
"range",
"(",
"count",
")",
":",
"# bits are retrieved from the source LSB first",
"bit",
"=",
"(",
"value",
"&",
"1",
")",
"value",
">>=",
"1",
"# however, bits are put ... | Push bits into the target.
value
Integer containing bits to push, ordered from least-significant bit to
most-significant bit.
count
Number of bits to push to the target. | [
"Push",
"bits",
"into",
"the",
"target",
"."
] | python | train |
collectiveacuity/labPack | labpack/databases/sql.py | https://github.com/collectiveacuity/labPack/blob/52949ece35e72e3cc308f54d9ffa6bfbd96805b8/labpack/databases/sql.py#L574-L733 | def list(self, query_criteria=None, order_criteria=None):
'''
a generator method to list records in table which match query criteria
:param query_criteria: dictionary with schema dot-path field names and query qualifiers
:param order_criteria: list of single key... | [
"def",
"list",
"(",
"self",
",",
"query_criteria",
"=",
"None",
",",
"order_criteria",
"=",
"None",
")",
":",
"title",
"=",
"'%s.list'",
"%",
"self",
".",
"__class__",
".",
"__name__",
"from",
"sqlalchemy",
"import",
"desc",
"as",
"order_desc",
"# validate i... | a generator method to list records in table which match query criteria
:param query_criteria: dictionary with schema dot-path field names and query qualifiers
:param order_criteria: list of single keypair dictionaries with field names to order by
:return: generator object with stri... | [
"a",
"generator",
"method",
"to",
"list",
"records",
"in",
"table",
"which",
"match",
"query",
"criteria",
":",
"param",
"query_criteria",
":",
"dictionary",
"with",
"schema",
"dot",
"-",
"path",
"field",
"names",
"and",
"query",
"qualifiers",
":",
"param",
... | python | train |
riga/tfdeploy | tfdeploy.py | https://github.com/riga/tfdeploy/blob/8481f657d6e3a51d76185a195b993e45f448828a/tfdeploy.py#L115-L123 | def get(self, *names, **kwargs):
""" get(*names, key=None)
Returns one or more :py:class:`Tensor` instances given by *names* using a deep lookup within
the model. If *key* is not *None*, only the root tensor with that *key* is traversed. *None*
is returned when no tensor was found. In ca... | [
"def",
"get",
"(",
"self",
",",
"*",
"names",
",",
"*",
"*",
"kwargs",
")",
":",
"tensors",
"=",
"tuple",
"(",
"self",
".",
"_get",
"(",
"name",
",",
"*",
"*",
"kwargs",
")",
"for",
"name",
"in",
"names",
")",
"return",
"tensors",
"[",
"0",
"]"... | get(*names, key=None)
Returns one or more :py:class:`Tensor` instances given by *names* using a deep lookup within
the model. If *key* is not *None*, only the root tensor with that *key* is traversed. *None*
is returned when no tensor was found. In case a tensor is passed, it's name is used for ... | [
"get",
"(",
"*",
"names",
"key",
"=",
"None",
")",
"Returns",
"one",
"or",
"more",
":",
"py",
":",
"class",
":",
"Tensor",
"instances",
"given",
"by",
"*",
"names",
"*",
"using",
"a",
"deep",
"lookup",
"within",
"the",
"model",
".",
"If",
"*",
"key... | python | train |
xtuml/pyxtuml | xtuml/tools.py | https://github.com/xtuml/pyxtuml/blob/7dd9343b9a0191d1db1887ab9288d0a026608d9a/xtuml/tools.py#L227-L236 | def default_accept(self, node, **kwargs):
'''
The default accept behaviour is to decend into the iterable member
*node.children* (if available).
'''
if not hasattr(node, 'children'):
return
for child in node.children:
self.accept(child, **... | [
"def",
"default_accept",
"(",
"self",
",",
"node",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"hasattr",
"(",
"node",
",",
"'children'",
")",
":",
"return",
"for",
"child",
"in",
"node",
".",
"children",
":",
"self",
".",
"accept",
"(",
"child",... | The default accept behaviour is to decend into the iterable member
*node.children* (if available). | [
"The",
"default",
"accept",
"behaviour",
"is",
"to",
"decend",
"into",
"the",
"iterable",
"member",
"*",
"node",
".",
"children",
"*",
"(",
"if",
"available",
")",
"."
] | python | test |
saltstack/salt | salt/states/boto_vpc.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_vpc.py#L1649-L1736 | def vpc_peering_connection_present(name, requester_vpc_id=None, requester_vpc_name=None,
peer_vpc_id=None, peer_vpc_name=None, conn_name=None,
peer_owner_id=None, peer_region=None, region=None,
key=None, keyid=None,... | [
"def",
"vpc_peering_connection_present",
"(",
"name",
",",
"requester_vpc_id",
"=",
"None",
",",
"requester_vpc_name",
"=",
"None",
",",
"peer_vpc_id",
"=",
"None",
",",
"peer_vpc_name",
"=",
"None",
",",
"conn_name",
"=",
"None",
",",
"peer_owner_id",
"=",
"Non... | name
Name of the state
requester_vpc_id
ID of the requesting VPC. Exclusive with requester_vpc_name.
requester_vpc_name
Name tag of the requesting VPC. Exclusive with requester_vpc_id.
peer_vpc_id
ID of the VPC tp crete VPC peering connection with. This can be a VPC in
... | [
"name",
"Name",
"of",
"the",
"state"
] | python | train |
dshean/demcoreg | demcoreg/dem_mask.py | https://github.com/dshean/demcoreg/blob/abd6be75d326b35f52826ee30dff01f9e86b4b52/demcoreg/dem_mask.py#L34-L49 | def get_nlcd_fn():
"""Calls external shell script `get_nlcd.sh` to fetch:
2011 Land Use Land Cover (nlcd) grids, 30 m
http://www.mrlc.gov/nlcd11_leg.php
"""
#This is original filename, which requires ~17 GB
#nlcd_fn = os.path.join(datadir, 'nlcd_2011_landcover_2011_edition_2014_10_10/nlcd_... | [
"def",
"get_nlcd_fn",
"(",
")",
":",
"#This is original filename, which requires ~17 GB",
"#nlcd_fn = os.path.join(datadir, 'nlcd_2011_landcover_2011_edition_2014_10_10/nlcd_2011_landcover_2011_edition_2014_10_10.img')",
"#get_nlcd.sh now creates a compressed GTiff, which is 1.1 GB",
"nlcd_fn",
"=... | Calls external shell script `get_nlcd.sh` to fetch:
2011 Land Use Land Cover (nlcd) grids, 30 m
http://www.mrlc.gov/nlcd11_leg.php | [
"Calls",
"external",
"shell",
"script",
"get_nlcd",
".",
"sh",
"to",
"fetch",
":"
] | python | train |
JarryShaw/PyPCAPKit | src/const/ipv4/tos_del.py | https://github.com/JarryShaw/PyPCAPKit/blob/c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e/src/const/ipv4/tos_del.py#L16-L22 | def get(key, default=-1):
"""Backport support for original codes."""
if isinstance(key, int):
return TOS_DEL(key)
if key not in TOS_DEL._member_map_:
extend_enum(TOS_DEL, key, default)
return TOS_DEL[key] | [
"def",
"get",
"(",
"key",
",",
"default",
"=",
"-",
"1",
")",
":",
"if",
"isinstance",
"(",
"key",
",",
"int",
")",
":",
"return",
"TOS_DEL",
"(",
"key",
")",
"if",
"key",
"not",
"in",
"TOS_DEL",
".",
"_member_map_",
":",
"extend_enum",
"(",
"TOS_D... | Backport support for original codes. | [
"Backport",
"support",
"for",
"original",
"codes",
"."
] | python | train |
saltstack/salt | salt/modules/tls.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/tls.py#L1857-L2035 | def revoke_cert(
ca_name,
CN,
cacert_path=None,
ca_filename=None,
cert_path=None,
cert_filename=None,
crl_file=None,
digest='sha256',
):
'''
Revoke a certificate.
.. versionadded:: 2015.8.0
ca_name
Name of the CA.
CN
... | [
"def",
"revoke_cert",
"(",
"ca_name",
",",
"CN",
",",
"cacert_path",
"=",
"None",
",",
"ca_filename",
"=",
"None",
",",
"cert_path",
"=",
"None",
",",
"cert_filename",
"=",
"None",
",",
"crl_file",
"=",
"None",
",",
"digest",
"=",
"'sha256'",
",",
")",
... | Revoke a certificate.
.. versionadded:: 2015.8.0
ca_name
Name of the CA.
CN
Common name matching the certificate signing request.
cacert_path
Absolute path to ca certificates root directory.
ca_filename
Alternative filename for the CA.
cert_path
Path... | [
"Revoke",
"a",
"certificate",
"."
] | python | train |
facebook/pyre-check | sapp/sapp/models.py | https://github.com/facebook/pyre-check/blob/4a9604d943d28ef20238505a51acfb1f666328d7/sapp/sapp/models.py#L108-L171 | def _merge_by_keys(cls, session, items, hash_item, *attrs):
"""An object can have multiple attributes as its key. This merges the
items to be added with existing items in the database based on their
key(s).
session: Session object for querying the DB.
items: Iterator of items to... | [
"def",
"_merge_by_keys",
"(",
"cls",
",",
"session",
",",
"items",
",",
"hash_item",
",",
"*",
"attrs",
")",
":",
"# Note: items is an iterator, not an iterable, 'tee' is a must.",
"items_iter1",
",",
"items_iter2",
"=",
"tee",
"(",
"items",
")",
"keys",
"=",
"{",... | An object can have multiple attributes as its key. This merges the
items to be added with existing items in the database based on their
key(s).
session: Session object for querying the DB.
items: Iterator of items to be added to the DB.
hash_item: Function that takes as in put t... | [
"An",
"object",
"can",
"have",
"multiple",
"attributes",
"as",
"its",
"key",
".",
"This",
"merges",
"the",
"items",
"to",
"be",
"added",
"with",
"existing",
"items",
"in",
"the",
"database",
"based",
"on",
"their",
"key",
"(",
"s",
")",
"."
] | python | train |
mkouhei/tonicdnscli | src/tonicdnscli/command.py | https://github.com/mkouhei/tonicdnscli/blob/df2d6fb2104ae4d49fa89d1bba2f3ccd2fed388c/src/tonicdnscli/command.py#L485-L512 | def conn_options(prs, conn):
"""Set options of connecting to TonicDNS API server
Arguments:
prs: parser object of argparse
conn: dictionary of connection information
"""
if conn.get('server') and conn.get('username') and conn.get('password'):
prs.set_defaults(server=conn.get('... | [
"def",
"conn_options",
"(",
"prs",
",",
"conn",
")",
":",
"if",
"conn",
".",
"get",
"(",
"'server'",
")",
"and",
"conn",
".",
"get",
"(",
"'username'",
")",
"and",
"conn",
".",
"get",
"(",
"'password'",
")",
":",
"prs",
".",
"set_defaults",
"(",
"s... | Set options of connecting to TonicDNS API server
Arguments:
prs: parser object of argparse
conn: dictionary of connection information | [
"Set",
"options",
"of",
"connecting",
"to",
"TonicDNS",
"API",
"server"
] | python | train |
juju/python-libjuju | juju/model.py | https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/model.py#L924-L936 | async def _wait_for_new(self, entity_type, entity_id):
"""Wait for a new object to appear in the Model and return it.
Waits for an object of type ``entity_type`` with id ``entity_id``
to appear in the model. This is similar to watching for the
object using ``block_until``, but uses the... | [
"async",
"def",
"_wait_for_new",
"(",
"self",
",",
"entity_type",
",",
"entity_id",
")",
":",
"# if the entity is already in the model, just return it",
"if",
"entity_id",
"in",
"self",
".",
"state",
".",
"_live_entity_map",
"(",
"entity_type",
")",
":",
"return",
"... | Wait for a new object to appear in the Model and return it.
Waits for an object of type ``entity_type`` with id ``entity_id``
to appear in the model. This is similar to watching for the
object using ``block_until``, but uses the watcher rather than
polling. | [
"Wait",
"for",
"a",
"new",
"object",
"to",
"appear",
"in",
"the",
"Model",
"and",
"return",
"it",
"."
] | python | train |
saltstack/salt | salt/modules/xapi_virt.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/xapi_virt.py#L761-L784 | def is_hyper():
'''
Returns a bool whether or not this node is a hypervisor of any kind
CLI Example:
.. code-block:: bash
salt '*' virt.is_hyper
'''
try:
if __grains__['virtual_subtype'] != 'Xen Dom0':
return False
except KeyError:
# virtual_subtype isn... | [
"def",
"is_hyper",
"(",
")",
":",
"try",
":",
"if",
"__grains__",
"[",
"'virtual_subtype'",
"]",
"!=",
"'Xen Dom0'",
":",
"return",
"False",
"except",
"KeyError",
":",
"# virtual_subtype isn't set everywhere.",
"return",
"False",
"try",
":",
"with",
"salt",
".",... | Returns a bool whether or not this node is a hypervisor of any kind
CLI Example:
.. code-block:: bash
salt '*' virt.is_hyper | [
"Returns",
"a",
"bool",
"whether",
"or",
"not",
"this",
"node",
"is",
"a",
"hypervisor",
"of",
"any",
"kind"
] | python | train |
sentinel-hub/sentinel2-cloud-detector | s2cloudless/PixelClassifier.py | https://github.com/sentinel-hub/sentinel2-cloud-detector/blob/7130a4a6af90a92f28592d11da692bbb0dc1dc01/s2cloudless/PixelClassifier.py#L81-L96 | def image_predict_proba(self, X):
"""
Predicts class probabilities for the entire image.
:param X: Array of images to be classified.
:type X: numpy array, shape = [n_images, n_pixels_y, n_pixels_x, n_bands]
:return: classification probability map
:rtype: numpy array, [n... | [
"def",
"image_predict_proba",
"(",
"self",
",",
"X",
")",
":",
"pixels",
"=",
"self",
".",
"extract_pixels",
"(",
"X",
")",
"probabilities",
"=",
"self",
".",
"classifier",
".",
"predict_proba",
"(",
"pixels",
")",
"return",
"probabilities",
".",
"reshape",
... | Predicts class probabilities for the entire image.
:param X: Array of images to be classified.
:type X: numpy array, shape = [n_images, n_pixels_y, n_pixels_x, n_bands]
:return: classification probability map
:rtype: numpy array, [n_samples, n_pixels_y, n_pixels_x] | [
"Predicts",
"class",
"probabilities",
"for",
"the",
"entire",
"image",
"."
] | python | train |
mozilla/taar | taar/recommenders/ensemble_recommender.py | https://github.com/mozilla/taar/blob/4002eb395f0b7ad837f1578e92d590e2cf82bdca/taar/recommenders/ensemble_recommender.py#L81-L150 | def _recommend(self, client_data, limit, extra_data={}):
"""
Ensemble recommendations are aggregated from individual
recommenders. The ensemble recommender applies a weight to
the recommendation outputs of each recommender to reorder the
recommendations to be a better fit.
... | [
"def",
"_recommend",
"(",
"self",
",",
"client_data",
",",
"limit",
",",
"extra_data",
"=",
"{",
"}",
")",
":",
"self",
".",
"logger",
".",
"info",
"(",
"\"Ensemble recommend invoked\"",
")",
"preinstalled_addon_ids",
"=",
"client_data",
".",
"get",
"(",
"\"... | Ensemble recommendations are aggregated from individual
recommenders. The ensemble recommender applies a weight to
the recommendation outputs of each recommender to reorder the
recommendations to be a better fit.
The intuitive understanding is that the total space of
recommende... | [
"Ensemble",
"recommendations",
"are",
"aggregated",
"from",
"individual",
"recommenders",
".",
"The",
"ensemble",
"recommender",
"applies",
"a",
"weight",
"to",
"the",
"recommendation",
"outputs",
"of",
"each",
"recommender",
"to",
"reorder",
"the",
"recommendations",... | python | train |
deepmind/sonnet | sonnet/python/modules/util.py | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/util.py#L1039-L1099 | def supports_kwargs(module_or_fn, kwargs_list):
"""Determines whether the provided callable supports all the kwargs.
This is useful when you have a module that might or might not support a
kwarg such as `is_training`. Rather than calling the module and catching the
error, risking the potential modification of ... | [
"def",
"supports_kwargs",
"(",
"module_or_fn",
",",
"kwargs_list",
")",
":",
"if",
"isinstance",
"(",
"kwargs_list",
",",
"six",
".",
"string_types",
")",
":",
"kwargs_list",
"=",
"[",
"kwargs_list",
"]",
"# If it's not a function or method, then assume it's a module, s... | Determines whether the provided callable supports all the kwargs.
This is useful when you have a module that might or might not support a
kwarg such as `is_training`. Rather than calling the module and catching the
error, risking the potential modification of underlying state, this function
introspects the mod... | [
"Determines",
"whether",
"the",
"provided",
"callable",
"supports",
"all",
"the",
"kwargs",
"."
] | python | train |
pysathq/pysat | pysat/solvers.py | https://github.com/pysathq/pysat/blob/522742e8f2d4c6ac50ecd9087f7a346206774c67/pysat/solvers.py#L2710-L2732 | def solve_limited(self, assumptions=[]):
"""
Solve internal formula using given budgets for conflicts and
propagations.
"""
if self.minicard:
if self.use_timer:
start_time = time.clock()
# saving default SIGINT handler
... | [
"def",
"solve_limited",
"(",
"self",
",",
"assumptions",
"=",
"[",
"]",
")",
":",
"if",
"self",
".",
"minicard",
":",
"if",
"self",
".",
"use_timer",
":",
"start_time",
"=",
"time",
".",
"clock",
"(",
")",
"# saving default SIGINT handler",
"def_sigint_handl... | Solve internal formula using given budgets for conflicts and
propagations. | [
"Solve",
"internal",
"formula",
"using",
"given",
"budgets",
"for",
"conflicts",
"and",
"propagations",
"."
] | python | train |
inveniosoftware-attic/invenio-utils | invenio_utils/shell.py | https://github.com/inveniosoftware-attic/invenio-utils/blob/9a1c6db4e3f1370901f329f510480dd8df188296/invenio_utils/shell.py#L309-L327 | def escape_shell_arg(shell_arg):
"""Escape shell argument shell_arg by placing it within
single-quotes. Any single quotes found within the shell argument
string will be escaped.
@param shell_arg: The shell argument to be escaped.
@type shell_arg: string
@return: The single-quote-escaped value ... | [
"def",
"escape_shell_arg",
"(",
"shell_arg",
")",
":",
"if",
"isinstance",
"(",
"shell_arg",
",",
"six",
".",
"text_type",
")",
":",
"msg",
"=",
"\"ERROR: escape_shell_arg() expected string argument but \"",
"\"got '%s' of type '%s'.\"",
"%",
"(",
"repr",
"(",
"shell_... | Escape shell argument shell_arg by placing it within
single-quotes. Any single quotes found within the shell argument
string will be escaped.
@param shell_arg: The shell argument to be escaped.
@type shell_arg: string
@return: The single-quote-escaped value of the shell argument.
@rtype: strin... | [
"Escape",
"shell",
"argument",
"shell_arg",
"by",
"placing",
"it",
"within",
"single",
"-",
"quotes",
".",
"Any",
"single",
"quotes",
"found",
"within",
"the",
"shell",
"argument",
"string",
"will",
"be",
"escaped",
"."
] | python | train |
tornadoweb/tornado | tornado/websocket.py | https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/websocket.py#L995-L1013 | def _get_compressor_options(
self,
side: str,
agreed_parameters: Dict[str, Any],
compression_options: Dict[str, Any] = None,
) -> Dict[str, Any]:
"""Converts a websocket agreed_parameters set to keyword arguments
for our compressor objects.
"""
options... | [
"def",
"_get_compressor_options",
"(",
"self",
",",
"side",
":",
"str",
",",
"agreed_parameters",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
",",
"compression_options",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
"=",
"None",
",",
")",
"->",
"Dict",
"[",
... | Converts a websocket agreed_parameters set to keyword arguments
for our compressor objects. | [
"Converts",
"a",
"websocket",
"agreed_parameters",
"set",
"to",
"keyword",
"arguments",
"for",
"our",
"compressor",
"objects",
"."
] | python | train |
GeospatialPython/pyshp | shapefile.py | https://github.com/GeospatialPython/pyshp/blob/71231ddc5aa54f155d4f0563c56006fffbfc84e7/shapefile.py#L820-L840 | def __shapeIndex(self, i=None):
"""Returns the offset in a .shp file for a shape based on information
in the .shx index file."""
shx = self.shx
if not shx:
return None
if not self._offsets:
# File length (16-bit word * 2 = bytes) - header length
... | [
"def",
"__shapeIndex",
"(",
"self",
",",
"i",
"=",
"None",
")",
":",
"shx",
"=",
"self",
".",
"shx",
"if",
"not",
"shx",
":",
"return",
"None",
"if",
"not",
"self",
".",
"_offsets",
":",
"# File length (16-bit word * 2 = bytes) - header length\r",
"shx",
"."... | Returns the offset in a .shp file for a shape based on information
in the .shx index file. | [
"Returns",
"the",
"offset",
"in",
"a",
".",
"shp",
"file",
"for",
"a",
"shape",
"based",
"on",
"information",
"in",
"the",
".",
"shx",
"index",
"file",
"."
] | python | train |
inveniosoftware/invenio-oaiserver | invenio_oaiserver/tasks.py | https://github.com/inveniosoftware/invenio-oaiserver/blob/eae765e32bd816ddc5612d4b281caf205518b512/invenio_oaiserver/tasks.py#L25-L29 | def _records_commit(record_ids):
"""Commit all records."""
for record_id in record_ids:
record = Record.get_record(record_id)
record.commit() | [
"def",
"_records_commit",
"(",
"record_ids",
")",
":",
"for",
"record_id",
"in",
"record_ids",
":",
"record",
"=",
"Record",
".",
"get_record",
"(",
"record_id",
")",
"record",
".",
"commit",
"(",
")"
] | Commit all records. | [
"Commit",
"all",
"records",
"."
] | python | train |
PyThaiNLP/pythainlp | pythainlp/tokenize/longest.py | https://github.com/PyThaiNLP/pythainlp/blob/e9a300b8a99dfd1a67a955e7c06f62e4afe0fbca/pythainlp/tokenize/longest.py#L142-L150 | def segment(text: str, custom_dict: Trie = None) -> List[str]:
"""ตัดคำภาษาไทยด้วยวิธี longest matching"""
if not text or not isinstance(text, str):
return []
if not custom_dict:
custom_dict = DEFAULT_DICT_TRIE
return LongestMatchTokenizer(custom_dict).tokenize(text) | [
"def",
"segment",
"(",
"text",
":",
"str",
",",
"custom_dict",
":",
"Trie",
"=",
"None",
")",
"->",
"List",
"[",
"str",
"]",
":",
"if",
"not",
"text",
"or",
"not",
"isinstance",
"(",
"text",
",",
"str",
")",
":",
"return",
"[",
"]",
"if",
"not",
... | ตัดคำภาษาไทยด้วยวิธี longest matching | [
"ตัดคำภาษาไทยด้วยวิธี",
"longest",
"matching"
] | python | train |
sveetch/boussole | boussole/conf/discovery.py | https://github.com/sveetch/boussole/blob/22cc644e9d633f41ebfc167d427a71c1726cee21/boussole/conf/discovery.py#L141-L191 | def search(self, filepath=None, basedir=None, kind=None):
"""
Search for a settings file.
Keyword Arguments:
filepath (string): Path to a config file, either absolute or
relative. If absolute set its directory as basedir (omitting
given basedir argume... | [
"def",
"search",
"(",
"self",
",",
"filepath",
"=",
"None",
",",
"basedir",
"=",
"None",
",",
"kind",
"=",
"None",
")",
":",
"# None values would cause trouble with path joining",
"if",
"filepath",
"is",
"None",
":",
"filepath",
"=",
"''",
"if",
"basedir",
"... | Search for a settings file.
Keyword Arguments:
filepath (string): Path to a config file, either absolute or
relative. If absolute set its directory as basedir (omitting
given basedir argument). If relative join it to basedir.
basedir (string): Directory p... | [
"Search",
"for",
"a",
"settings",
"file",
"."
] | python | train |
zhanglab/psamm | psamm/util.py | https://github.com/zhanglab/psamm/blob/dc427848c4f9d109ca590f0afa024c63b685b3f4/psamm/util.py#L54-L58 | def write(self, s):
"""Write message to logger."""
for line in re.split(r'\n+', s):
if line != '':
self._logger.log(self._level, line) | [
"def",
"write",
"(",
"self",
",",
"s",
")",
":",
"for",
"line",
"in",
"re",
".",
"split",
"(",
"r'\\n+'",
",",
"s",
")",
":",
"if",
"line",
"!=",
"''",
":",
"self",
".",
"_logger",
".",
"log",
"(",
"self",
".",
"_level",
",",
"line",
")"
] | Write message to logger. | [
"Write",
"message",
"to",
"logger",
"."
] | python | train |
loganasherjones/yapconf | yapconf/items.py | https://github.com/loganasherjones/yapconf/blob/d2970e6e7e3334615d4d978d8b0ca33006d79d16/yapconf/items.py#L256-L279 | def migrate_config(self, current_config, config_to_migrate,
always_update, update_defaults):
"""Migrate config value in current_config, updating config_to_migrate.
Given the current_config object, it will attempt to find a value
based on all the names given. If no name co... | [
"def",
"migrate_config",
"(",
"self",
",",
"current_config",
",",
"config_to_migrate",
",",
"always_update",
",",
"update_defaults",
")",
":",
"value",
"=",
"self",
".",
"_search_config_for_possible_names",
"(",
"current_config",
")",
"self",
".",
"_update_config",
... | Migrate config value in current_config, updating config_to_migrate.
Given the current_config object, it will attempt to find a value
based on all the names given. If no name could be found, then it
will simply set the value to the default.
If a value is found and is in the list of prev... | [
"Migrate",
"config",
"value",
"in",
"current_config",
"updating",
"config_to_migrate",
"."
] | python | train |
guaix-ucm/pyemir | emirdrp/instrument/dtu_configuration.py | https://github.com/guaix-ucm/pyemir/blob/fef6bbabcb13f80123cafd1800a0f508a3c21702/emirdrp/instrument/dtu_configuration.py#L208-L236 | def average_dtu_configurations(list_of_objects):
"""Return DtuConfiguration instance with averaged values.
Parameters
----------
list_of_objects : python list
List of DtuConfiguration instances to be averaged.
Returns
-------
result : DtuConfiguration instance
Object with a... | [
"def",
"average_dtu_configurations",
"(",
"list_of_objects",
")",
":",
"result",
"=",
"DtuConfiguration",
"(",
")",
"if",
"len",
"(",
"list_of_objects",
")",
"==",
"0",
":",
"return",
"result",
"list_of_members",
"=",
"result",
".",
"__dict__",
".",
"keys",
"(... | Return DtuConfiguration instance with averaged values.
Parameters
----------
list_of_objects : python list
List of DtuConfiguration instances to be averaged.
Returns
-------
result : DtuConfiguration instance
Object with averaged values. | [
"Return",
"DtuConfiguration",
"instance",
"with",
"averaged",
"values",
"."
] | python | train |
taxpon/pymesh | pymesh/base.py | https://github.com/taxpon/pymesh/blob/a90b3b2ed1408d793f3b5208dd8087b08fb7c92e/pymesh/base.py#L107-L119 | def translate_y(self, d):
"""Translate mesh for y-direction
:param float d: Amount to translate
"""
mat = numpy.array([
[1, 0, 0, 0],
[0, 1, 0, 0],
[0, 0, 1, 0],
[0, d, 0, 1]
])
self.vectors = self.vectors.dot(mat)
... | [
"def",
"translate_y",
"(",
"self",
",",
"d",
")",
":",
"mat",
"=",
"numpy",
".",
"array",
"(",
"[",
"[",
"1",
",",
"0",
",",
"0",
",",
"0",
"]",
",",
"[",
"0",
",",
"1",
",",
"0",
",",
"0",
"]",
",",
"[",
"0",
",",
"0",
",",
"1",
",",... | Translate mesh for y-direction
:param float d: Amount to translate | [
"Translate",
"mesh",
"for",
"y",
"-",
"direction"
] | python | train |
tanghaibao/goatools | goatools/go_enrichment.py | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/go_enrichment.py#L136-L143 | def set_goterm(self, go2obj):
"""Set goterm and copy GOTerm's name and namespace."""
if self.GO in go2obj:
goterm = go2obj[self.GO]
self.goterm = goterm
self.name = goterm.name
self.depth = goterm.depth
self.NS = self.namespace2NS[self.goterm.n... | [
"def",
"set_goterm",
"(",
"self",
",",
"go2obj",
")",
":",
"if",
"self",
".",
"GO",
"in",
"go2obj",
":",
"goterm",
"=",
"go2obj",
"[",
"self",
".",
"GO",
"]",
"self",
".",
"goterm",
"=",
"goterm",
"self",
".",
"name",
"=",
"goterm",
".",
"name",
... | Set goterm and copy GOTerm's name and namespace. | [
"Set",
"goterm",
"and",
"copy",
"GOTerm",
"s",
"name",
"and",
"namespace",
"."
] | python | train |
CI-WATER/gsshapy | gsshapy/orm/prj.py | https://github.com/CI-WATER/gsshapy/blob/00fd4af0fd65f1614d75a52fe950a04fb0867f4c/gsshapy/orm/prj.py#L2024-L2051 | def write(self, originalPrefix, newPrefix=None):
"""
Write project card to string.
Args:
originalPrefix (str): Original name to give to files that follow the project naming convention
(e.g: prefix.gag).
newPrefix (str, optional): If new prefix is desired,... | [
"def",
"write",
"(",
"self",
",",
"originalPrefix",
",",
"newPrefix",
"=",
"None",
")",
":",
"# Determine number of spaces between card and value for nice alignment",
"numSpaces",
"=",
"max",
"(",
"2",
",",
"25",
"-",
"len",
"(",
"self",
".",
"name",
")",
")",
... | Write project card to string.
Args:
originalPrefix (str): Original name to give to files that follow the project naming convention
(e.g: prefix.gag).
newPrefix (str, optional): If new prefix is desired, pass in this parameter. Defaults to None.
Returns:
... | [
"Write",
"project",
"card",
"to",
"string",
"."
] | python | train |
bokeh/bokeh | bokeh/transform.py | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/transform.py#L127-L155 | def factor_hatch(field_name, patterns, factors, start=0, end=None):
''' Create a ``DataSpec`` dict that applies a client-side
``CategoricalPatternMapper`` transformation to a ``ColumnDataSource``
column.
Args:
field_name (str) : a field name to configure ``DataSpec`` with
patterns (seq... | [
"def",
"factor_hatch",
"(",
"field_name",
",",
"patterns",
",",
"factors",
",",
"start",
"=",
"0",
",",
"end",
"=",
"None",
")",
":",
"return",
"field",
"(",
"field_name",
",",
"CategoricalPatternMapper",
"(",
"patterns",
"=",
"patterns",
",",
"factors",
"... | Create a ``DataSpec`` dict that applies a client-side
``CategoricalPatternMapper`` transformation to a ``ColumnDataSource``
column.
Args:
field_name (str) : a field name to configure ``DataSpec`` with
patterns (seq[string]) : a list of hatch patterns to use to map to
factors (seq)... | [
"Create",
"a",
"DataSpec",
"dict",
"that",
"applies",
"a",
"client",
"-",
"side",
"CategoricalPatternMapper",
"transformation",
"to",
"a",
"ColumnDataSource",
"column",
"."
] | python | train |
expfactory/expfactory | expfactory/experiment.py | https://github.com/expfactory/expfactory/blob/27ce6cc93e17231df8a8024f18e631336afd3501/expfactory/experiment.py#L84-L97 | def load_experiment(folder, return_path=False):
'''load_experiment:
reads in the config.json for a folder, returns None if not found.
:param folder: full path to experiment folder
:param return_path: if True, don't load the config.json, but return it
'''
fullpath = os.path.abspath(folder)
co... | [
"def",
"load_experiment",
"(",
"folder",
",",
"return_path",
"=",
"False",
")",
":",
"fullpath",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"folder",
")",
"config",
"=",
"\"%s/config.json\"",
"%",
"(",
"fullpath",
")",
"if",
"not",
"os",
".",
"path",
... | load_experiment:
reads in the config.json for a folder, returns None if not found.
:param folder: full path to experiment folder
:param return_path: if True, don't load the config.json, but return it | [
"load_experiment",
":",
"reads",
"in",
"the",
"config",
".",
"json",
"for",
"a",
"folder",
"returns",
"None",
"if",
"not",
"found",
".",
":",
"param",
"folder",
":",
"full",
"path",
"to",
"experiment",
"folder",
":",
"param",
"return_path",
":",
"if",
"T... | python | train |
ttinies/sc2ladderMgmt | sc2ladderMgmt/ladders.py | https://github.com/ttinies/sc2ladderMgmt/blob/230292e18c54e43129c162116bbdf743b3e9dcf1/sc2ladderMgmt/ladders.py#L64-L69 | def load(self, ladderName):
"""retrieve the ladder settings from saved disk file"""
self.name = ladderName # preset value to load self.filename
with open(self.filename, "rb") as f:
data = f.read()
self.__dict__.update( json.loads(data) ) | [
"def",
"load",
"(",
"self",
",",
"ladderName",
")",
":",
"self",
".",
"name",
"=",
"ladderName",
"# preset value to load self.filename",
"with",
"open",
"(",
"self",
".",
"filename",
",",
"\"rb\"",
")",
"as",
"f",
":",
"data",
"=",
"f",
".",
"read",
"(",... | retrieve the ladder settings from saved disk file | [
"retrieve",
"the",
"ladder",
"settings",
"from",
"saved",
"disk",
"file"
] | python | train |
keenlabs/KeenClient-Python | keen/__init__.py | https://github.com/keenlabs/KeenClient-Python/blob/266387c3376d1e000d117e17c45045ae3439d43f/keen/__init__.py#L109-L139 | def sum(event_collection, target_property, timeframe=None, timezone=None, interval=None, filters=None,
group_by=None, order_by=None, max_age=None, limit=None):
""" Performs a sum query
Adds the values of a target property for events that meet the given criteria.
:param event_collection: string, th... | [
"def",
"sum",
"(",
"event_collection",
",",
"target_property",
",",
"timeframe",
"=",
"None",
",",
"timezone",
"=",
"None",
",",
"interval",
"=",
"None",
",",
"filters",
"=",
"None",
",",
"group_by",
"=",
"None",
",",
"order_by",
"=",
"None",
",",
"max_a... | Performs a sum query
Adds the values of a target property for events that meet the given criteria.
:param event_collection: string, the name of the collection to query
:param target_property: string, the name of the event property you would like use
:param timeframe: string or dict, the timeframe in w... | [
"Performs",
"a",
"sum",
"query"
] | python | train |
limodou/uliweb | uliweb/core/SimpleFrame.py | https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/core/SimpleFrame.py#L222-L261 | def CORS(func=None):
"""
CORS support
"""
def w(r=None):
from uliweb import request, response
if request.method == 'OPTIONS':
response = Response(status=204)
response.headers['Access-Control-Allow-Credentials'] = 'true'
response.headers['Access-Contr... | [
"def",
"CORS",
"(",
"func",
"=",
"None",
")",
":",
"def",
"w",
"(",
"r",
"=",
"None",
")",
":",
"from",
"uliweb",
"import",
"request",
",",
"response",
"if",
"request",
".",
"method",
"==",
"'OPTIONS'",
":",
"response",
"=",
"Response",
"(",
"status"... | CORS support | [
"CORS",
"support"
] | python | train |
qubell/contrib-python-qubell-client | qubell/api/private/platform.py | https://github.com/qubell/contrib-python-qubell-client/blob/4586ea11d5103c2ff9607d3ed922b5a0991b8845/qubell/api/private/platform.py#L95-L101 | def get_organization(self, id=None, name=None):
"""
Gets existing and accessible organization
:rtype: Organization
"""
log.info("Picking organization: %s (%s)" % (name, id))
return self.organizations[id or name] | [
"def",
"get_organization",
"(",
"self",
",",
"id",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"log",
".",
"info",
"(",
"\"Picking organization: %s (%s)\"",
"%",
"(",
"name",
",",
"id",
")",
")",
"return",
"self",
".",
"organizations",
"[",
"id",
... | Gets existing and accessible organization
:rtype: Organization | [
"Gets",
"existing",
"and",
"accessible",
"organization",
":",
"rtype",
":",
"Organization"
] | python | train |
openvax/pyensembl | pyensembl/transcript.py | https://github.com/openvax/pyensembl/blob/4b995fb72e848206d6fbf11950cf30964cd9b3aa/pyensembl/transcript.py#L254-L267 | def exon_intervals(self):
"""List of (start,end) tuples for each exon of this transcript,
in the order specified by the 'exon_number' column of the
exon table.
"""
results = self.db.query(
select_column_names=["exon_number", "start", "end"],
filter_column=... | [
"def",
"exon_intervals",
"(",
"self",
")",
":",
"results",
"=",
"self",
".",
"db",
".",
"query",
"(",
"select_column_names",
"=",
"[",
"\"exon_number\"",
",",
"\"start\"",
",",
"\"end\"",
"]",
",",
"filter_column",
"=",
"\"transcript_id\"",
",",
"filter_value"... | List of (start,end) tuples for each exon of this transcript,
in the order specified by the 'exon_number' column of the
exon table. | [
"List",
"of",
"(",
"start",
"end",
")",
"tuples",
"for",
"each",
"exon",
"of",
"this",
"transcript",
"in",
"the",
"order",
"specified",
"by",
"the",
"exon_number",
"column",
"of",
"the",
"exon",
"table",
"."
] | python | train |
google/grr | grr/server/grr_response_server/rdfvalues/objects.py | https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/rdfvalues/objects.py#L573-L586 | def ToURN(self):
"""Converts a reference into an URN."""
if self.path_type in [PathInfo.PathType.OS, PathInfo.PathType.TSK]:
return rdfvalue.RDFURN(self.client_id).Add("fs").Add(
self.path_type.name.lower()).Add("/".join(self.path_components))
elif self.path_type == PathInfo.PathType.REGIST... | [
"def",
"ToURN",
"(",
"self",
")",
":",
"if",
"self",
".",
"path_type",
"in",
"[",
"PathInfo",
".",
"PathType",
".",
"OS",
",",
"PathInfo",
".",
"PathType",
".",
"TSK",
"]",
":",
"return",
"rdfvalue",
".",
"RDFURN",
"(",
"self",
".",
"client_id",
")",... | Converts a reference into an URN. | [
"Converts",
"a",
"reference",
"into",
"an",
"URN",
"."
] | python | train |
umutbozkurt/django-rest-framework-mongoengine | rest_framework_mongoengine/serializers.py | https://github.com/umutbozkurt/django-rest-framework-mongoengine/blob/2fe6de53907b31a5e8b742e4c6b728942b5fa4f0/rest_framework_mongoengine/serializers.py#L457-L540 | def get_customization_for_nested_field(self, field_name):
""" Support of nested fields customization for:
* EmbeddedDocumentField
* NestedReference
* Compound fields with EmbeddedDocument as a child:
* ListField(EmbeddedDocument)/EmbeddedDocumentListField
* Map... | [
"def",
"get_customization_for_nested_field",
"(",
"self",
",",
"field_name",
")",
":",
"# This method is supposed to be called after self.get_fields(),",
"# thus it assumes that fields and exclude are mutually exclusive",
"# and at least one of them is set.",
"#",
"# Also, all the sanity che... | Support of nested fields customization for:
* EmbeddedDocumentField
* NestedReference
* Compound fields with EmbeddedDocument as a child:
* ListField(EmbeddedDocument)/EmbeddedDocumentListField
* MapField(EmbeddedDocument)
Extracts fields, exclude, extra_kwarg... | [
"Support",
"of",
"nested",
"fields",
"customization",
"for",
":",
"*",
"EmbeddedDocumentField",
"*",
"NestedReference",
"*",
"Compound",
"fields",
"with",
"EmbeddedDocument",
"as",
"a",
"child",
":",
"*",
"ListField",
"(",
"EmbeddedDocument",
")",
"/",
"EmbeddedDo... | python | train |
myint/autoflake | autoflake.py | https://github.com/myint/autoflake/blob/68fea68646922b920d55975f9f2adaeafd84df4f/autoflake.py#L85-L94 | def standard_package_names():
"""Yield standard module names."""
for name in standard_paths():
if name.startswith('_') or '-' in name:
continue
if '.' in name and name.rsplit('.')[-1] not in ['so', 'py', 'pyc']:
continue
yield name.split('.')[0] | [
"def",
"standard_package_names",
"(",
")",
":",
"for",
"name",
"in",
"standard_paths",
"(",
")",
":",
"if",
"name",
".",
"startswith",
"(",
"'_'",
")",
"or",
"'-'",
"in",
"name",
":",
"continue",
"if",
"'.'",
"in",
"name",
"and",
"name",
".",
"rsplit",... | Yield standard module names. | [
"Yield",
"standard",
"module",
"names",
"."
] | python | test |
SHTOOLS/SHTOOLS | examples/python/GlobalSpectralAnalysis/GlobalSpectralAnalysis.py | https://github.com/SHTOOLS/SHTOOLS/blob/9a115cf83002df2ddec6b7f41aeb6be688e285de/examples/python/GlobalSpectralAnalysis/GlobalSpectralAnalysis.py#L30-L63 | def example():
"""
example that plots the power spectrum of Mars topography data
"""
# --- input data filename ---
infile = os.path.join(os.path.dirname(__file__),
'../../ExampleDataFiles/MarsTopo719.shape')
coeffs, lmax = shio.shread(infile)
# --- plot grid ---
... | [
"def",
"example",
"(",
")",
":",
"# --- input data filename ---",
"infile",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
",",
"'../../ExampleDataFiles/MarsTopo719.shape'",
")",
"coeffs",
",",
"lmax",
"=",
... | example that plots the power spectrum of Mars topography data | [
"example",
"that",
"plots",
"the",
"power",
"spectrum",
"of",
"Mars",
"topography",
"data"
] | python | train |
secdev/scapy | scapy/automaton.py | https://github.com/secdev/scapy/blob/3ffe757c184017dd46464593a8f80f85abc1e79a/scapy/automaton.py#L123-L127 | def _release_all(self):
"""Releases all locks to kill all threads"""
for i in self.inputs:
i.call_release(True)
self.available_lock.release() | [
"def",
"_release_all",
"(",
"self",
")",
":",
"for",
"i",
"in",
"self",
".",
"inputs",
":",
"i",
".",
"call_release",
"(",
"True",
")",
"self",
".",
"available_lock",
".",
"release",
"(",
")"
] | Releases all locks to kill all threads | [
"Releases",
"all",
"locks",
"to",
"kill",
"all",
"threads"
] | python | train |
iamjarret/pystockfish | pystockfish.py | https://github.com/iamjarret/pystockfish/blob/ae34a4b4d29c577c888b72691fcf0cb5a89b1792/pystockfish.py#L280-L287 | def _get_info_pv(info):
"""
Helper function for _bestmove_get_info.
Extracts "pv" field from bestmove's info and returns move sequence in UCI notation.
"""
search = re.search(pattern=PV_REGEX, string=info)
return {"pv": search.group("move_list")} | [
"def",
"_get_info_pv",
"(",
"info",
")",
":",
"search",
"=",
"re",
".",
"search",
"(",
"pattern",
"=",
"PV_REGEX",
",",
"string",
"=",
"info",
")",
"return",
"{",
"\"pv\"",
":",
"search",
".",
"group",
"(",
"\"move_list\"",
")",
"}"
] | Helper function for _bestmove_get_info.
Extracts "pv" field from bestmove's info and returns move sequence in UCI notation. | [
"Helper",
"function",
"for",
"_bestmove_get_info",
"."
] | python | train |
aboSamoor/polyglot | polyglot/mapping/base.py | https://github.com/aboSamoor/polyglot/blob/d0d2aa8d06cec4e03bd96618ae960030f7069a17/polyglot/mapping/base.py#L246-L255 | def from_vocabfile(filename):
""" Construct a CountedVocabulary out of a vocabulary file.
Note:
File has the following format word1 count1
word2 count2
"""
word_count = [x.strip().split() for x in _open(filename, 'r').read().splitlines()]
word_count = {w:in... | [
"def",
"from_vocabfile",
"(",
"filename",
")",
":",
"word_count",
"=",
"[",
"x",
".",
"strip",
"(",
")",
".",
"split",
"(",
")",
"for",
"x",
"in",
"_open",
"(",
"filename",
",",
"'r'",
")",
".",
"read",
"(",
")",
".",
"splitlines",
"(",
")",
"]",... | Construct a CountedVocabulary out of a vocabulary file.
Note:
File has the following format word1 count1
word2 count2 | [
"Construct",
"a",
"CountedVocabulary",
"out",
"of",
"a",
"vocabulary",
"file",
"."
] | python | train |
Autodesk/aomi | aomi/validation.py | https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/validation.py#L100-L111 | def specific_path_check(path, opt):
"""Will make checks against include/exclude to determine if we
actually care about the path in question."""
if opt.exclude:
if path in opt.exclude:
return False
if opt.include:
if path not in opt.include:
return False
retu... | [
"def",
"specific_path_check",
"(",
"path",
",",
"opt",
")",
":",
"if",
"opt",
".",
"exclude",
":",
"if",
"path",
"in",
"opt",
".",
"exclude",
":",
"return",
"False",
"if",
"opt",
".",
"include",
":",
"if",
"path",
"not",
"in",
"opt",
".",
"include",
... | Will make checks against include/exclude to determine if we
actually care about the path in question. | [
"Will",
"make",
"checks",
"against",
"include",
"/",
"exclude",
"to",
"determine",
"if",
"we",
"actually",
"care",
"about",
"the",
"path",
"in",
"question",
"."
] | python | train |
jonathf/chaospy | chaospy/descriptives/expected.py | https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/descriptives/expected.py#L7-L69 | def E(poly, dist=None, **kws):
"""
Expected value operator.
1st order statistics of a probability distribution or polynomial on a given
probability space.
Args:
poly (Poly, Dist):
Input to take expected value on.
dist (Dist):
Defines the space the expected v... | [
"def",
"E",
"(",
"poly",
",",
"dist",
"=",
"None",
",",
"*",
"*",
"kws",
")",
":",
"if",
"not",
"isinstance",
"(",
"poly",
",",
"(",
"distributions",
".",
"Dist",
",",
"polynomials",
".",
"Poly",
")",
")",
":",
"print",
"(",
"type",
"(",
"poly",
... | Expected value operator.
1st order statistics of a probability distribution or polynomial on a given
probability space.
Args:
poly (Poly, Dist):
Input to take expected value on.
dist (Dist):
Defines the space the expected value is taken on. It is ignored if
... | [
"Expected",
"value",
"operator",
"."
] | python | train |
IdentityPython/SATOSA | src/satosa/frontends/saml2.py | https://github.com/IdentityPython/SATOSA/blob/49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb/src/satosa/frontends/saml2.py#L621-L635 | def handle_authn_request(self, context, binding_in):
"""
Loads approved endpoints dynamically
See super class satosa.frontends.saml2.SAMLFrontend#handle_authn_request
:type context: satosa.context.Context
:type binding_in: str
:rtype: satosa.response.Response
"""... | [
"def",
"handle_authn_request",
"(",
"self",
",",
"context",
",",
"binding_in",
")",
":",
"target_entity_id",
"=",
"context",
".",
"target_entity_id_from_path",
"(",
")",
"target_entity_id",
"=",
"urlsafe_b64decode",
"(",
"target_entity_id",
")",
".",
"decode",
"(",
... | Loads approved endpoints dynamically
See super class satosa.frontends.saml2.SAMLFrontend#handle_authn_request
:type context: satosa.context.Context
:type binding_in: str
:rtype: satosa.response.Response | [
"Loads",
"approved",
"endpoints",
"dynamically",
"See",
"super",
"class",
"satosa",
".",
"frontends",
".",
"saml2",
".",
"SAMLFrontend#handle_authn_request"
] | python | train |
pypa/pipenv | pipenv/vendor/six.py | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/six.py#L497-L505 | def remove_move(name):
"""Remove item from six.moves."""
try:
delattr(_MovedItems, name)
except AttributeError:
try:
del moves.__dict__[name]
except KeyError:
raise AttributeError("no such move, %r" % (name,)) | [
"def",
"remove_move",
"(",
"name",
")",
":",
"try",
":",
"delattr",
"(",
"_MovedItems",
",",
"name",
")",
"except",
"AttributeError",
":",
"try",
":",
"del",
"moves",
".",
"__dict__",
"[",
"name",
"]",
"except",
"KeyError",
":",
"raise",
"AttributeError",
... | Remove item from six.moves. | [
"Remove",
"item",
"from",
"six",
".",
"moves",
"."
] | python | train |
kytos/python-openflow | pyof/foundation/basic_types.py | https://github.com/kytos/python-openflow/blob/4f2d0d08ab28e102ed88fe57a4ee17729f1e1bb7/pyof/foundation/basic_types.py#L724-L743 | def append(self, item):
"""Append one item to the list.
Args:
item: Item to be appended.
Raises:
:exc:`~.exceptions.WrongListItemType`: If an item has a different
type than the first item to be stored.
"""
if isinstance(item, list):
... | [
"def",
"append",
"(",
"self",
",",
"item",
")",
":",
"if",
"isinstance",
"(",
"item",
",",
"list",
")",
":",
"self",
".",
"extend",
"(",
"item",
")",
"elif",
"not",
"self",
":",
"list",
".",
"append",
"(",
"self",
",",
"item",
")",
"elif",
"item"... | Append one item to the list.
Args:
item: Item to be appended.
Raises:
:exc:`~.exceptions.WrongListItemType`: If an item has a different
type than the first item to be stored. | [
"Append",
"one",
"item",
"to",
"the",
"list",
"."
] | python | train |
briancappello/flask-unchained | flask_unchained/bundles/security/commands/users.py | https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/security/commands/users.py#L168-L179 | def add_role_to_user(user, role):
"""
Add a role to a user.
"""
user = _query_to_user(user)
role = _query_to_role(role)
if click.confirm(f'Are you sure you want to add {role!r} to {user!r}?'):
user.roles.append(role)
user_manager.save(user, commit=True)
click.echo(f'Succe... | [
"def",
"add_role_to_user",
"(",
"user",
",",
"role",
")",
":",
"user",
"=",
"_query_to_user",
"(",
"user",
")",
"role",
"=",
"_query_to_role",
"(",
"role",
")",
"if",
"click",
".",
"confirm",
"(",
"f'Are you sure you want to add {role!r} to {user!r}?'",
")",
":"... | Add a role to a user. | [
"Add",
"a",
"role",
"to",
"a",
"user",
"."
] | python | train |
bio2bel/bio2bel | src/bio2bel/cli.py | https://github.com/bio2bel/bio2bel/blob/d80762d891fa18b248709ff0b0f97ebb65ec64c2/src/bio2bel/cli.py#L45-L56 | def _iterate_managers(connection, skip):
"""Iterate over instantiated managers."""
for idx, name, manager_cls in _iterate_manage_classes(skip):
if name in skip:
continue
try:
manager = manager_cls(connection=connection)
except TypeError as e:
click.se... | [
"def",
"_iterate_managers",
"(",
"connection",
",",
"skip",
")",
":",
"for",
"idx",
",",
"name",
",",
"manager_cls",
"in",
"_iterate_manage_classes",
"(",
"skip",
")",
":",
"if",
"name",
"in",
"skip",
":",
"continue",
"try",
":",
"manager",
"=",
"manager_c... | Iterate over instantiated managers. | [
"Iterate",
"over",
"instantiated",
"managers",
"."
] | python | valid |
insightindustry/validator-collection | validator_collection/checkers.py | https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/checkers.py#L1454-L1473 | def is_ip_address(value, **kwargs):
"""Indicate whether ``value`` is a valid IP address (version 4 or version 6).
:param value: The value to evaluate.
:returns: ``True`` if ``value`` is valid, ``False`` if it is not.
:rtype: :class:`bool <python:bool>`
:raises SyntaxError: if ``kwargs`` contains ... | [
"def",
"is_ip_address",
"(",
"value",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"value",
"=",
"validators",
".",
"ip_address",
"(",
"value",
",",
"*",
"*",
"kwargs",
")",
"except",
"SyntaxError",
"as",
"error",
":",
"raise",
"error",
"except",
"Ex... | Indicate whether ``value`` is a valid IP address (version 4 or version 6).
:param value: The value to evaluate.
:returns: ``True`` if ``value`` is valid, ``False`` if it is not.
:rtype: :class:`bool <python:bool>`
:raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates
... | [
"Indicate",
"whether",
"value",
"is",
"a",
"valid",
"IP",
"address",
"(",
"version",
"4",
"or",
"version",
"6",
")",
"."
] | python | train |
aeguana/PyFileMaker | PyFileMaker/FMServer.py | https://github.com/aeguana/PyFileMaker/blob/ef269b52a97e329d91da3c4851ddac800d7fd7e6/PyFileMaker/FMServer.py#L190-L208 | def _addSortParam(self, field, order=''):
"""Adds a sort parameter, order have to be in ['ascend', 'ascending','descend', 'descending','custom']"""
if order != '':
validSortOrders = {
'ascend':'ascend',
'ascending':'ascend',
'<':'ascend',
'descend':'descend',
'descending':'descend',
'>':... | [
"def",
"_addSortParam",
"(",
"self",
",",
"field",
",",
"order",
"=",
"''",
")",
":",
"if",
"order",
"!=",
"''",
":",
"validSortOrders",
"=",
"{",
"'ascend'",
":",
"'ascend'",
",",
"'ascending'",
":",
"'ascend'",
",",
"'<'",
":",
"'ascend'",
",",
"'des... | Adds a sort parameter, order have to be in ['ascend', 'ascending','descend', 'descending','custom'] | [
"Adds",
"a",
"sort",
"parameter",
"order",
"have",
"to",
"be",
"in",
"[",
"ascend",
"ascending",
"descend",
"descending",
"custom",
"]"
] | python | train |
galaxy-genome-annotation/python-apollo | arrow/commands/cannedkeys/add_key.py | https://github.com/galaxy-genome-annotation/python-apollo/blob/2bc9991302abe4402ec2885dcaac35915475b387/arrow/commands/cannedkeys/add_key.py#L16-L23 | def cli(ctx, key, metadata=""):
"""Add a canned key
Output:
A dictionnary containing canned key description
"""
return ctx.gi.cannedkeys.add_key(key, metadata=metadata) | [
"def",
"cli",
"(",
"ctx",
",",
"key",
",",
"metadata",
"=",
"\"\"",
")",
":",
"return",
"ctx",
".",
"gi",
".",
"cannedkeys",
".",
"add_key",
"(",
"key",
",",
"metadata",
"=",
"metadata",
")"
] | Add a canned key
Output:
A dictionnary containing canned key description | [
"Add",
"a",
"canned",
"key"
] | python | train |
nyergler/hieroglyph | src/hieroglyph/html.py | https://github.com/nyergler/hieroglyph/blob/1ef062fad5060006566f8d6bd3b5a231ac7e0488/src/hieroglyph/html.py#L92-L100 | def slide_path(builder, pagename=None):
"""Calculate the relative path to the Slides for pagename."""
return builder.get_relative_uri(
pagename or builder.current_docname,
os.path.join(
builder.app.config.slide_relative_path,
pagename or builder.current_docname,
... | [
"def",
"slide_path",
"(",
"builder",
",",
"pagename",
"=",
"None",
")",
":",
"return",
"builder",
".",
"get_relative_uri",
"(",
"pagename",
"or",
"builder",
".",
"current_docname",
",",
"os",
".",
"path",
".",
"join",
"(",
"builder",
".",
"app",
".",
"co... | Calculate the relative path to the Slides for pagename. | [
"Calculate",
"the",
"relative",
"path",
"to",
"the",
"Slides",
"for",
"pagename",
"."
] | python | train |
portfors-lab/sparkle | sparkle/gui/stim/qauto_parameter_model.py | https://github.com/portfors-lab/sparkle/blob/5fad1cf2bec58ec6b15d91da20f6236a74826110/sparkle/gui/stim/qauto_parameter_model.py#L220-L223 | def toggleSelection(self, index, comp):
"""Toggles a component in or out of the currently
selected parameter's compnents list"""
self.model.toggleSelection(index.row(), comp) | [
"def",
"toggleSelection",
"(",
"self",
",",
"index",
",",
"comp",
")",
":",
"self",
".",
"model",
".",
"toggleSelection",
"(",
"index",
".",
"row",
"(",
")",
",",
"comp",
")"
] | Toggles a component in or out of the currently
selected parameter's compnents list | [
"Toggles",
"a",
"component",
"in",
"or",
"out",
"of",
"the",
"currently",
"selected",
"parameter",
"s",
"compnents",
"list"
] | python | train |
bohea/sanic-limiter | sanic_limiter/extension.py | https://github.com/bohea/sanic-limiter/blob/54c9fc4a3a3f1a9bb69367262637d07701ae5694/sanic_limiter/extension.py#L318-L335 | def shared_limit(self, limit_value, scope, key_func=None,
error_message=None, exempt_when=None):
"""
decorator to be applied to multiple routes sharing the same rate limit.
:param limit_value: rate limit string or a callable that returns a string.
:ref:`ratelimit-s... | [
"def",
"shared_limit",
"(",
"self",
",",
"limit_value",
",",
"scope",
",",
"key_func",
"=",
"None",
",",
"error_message",
"=",
"None",
",",
"exempt_when",
"=",
"None",
")",
":",
"return",
"self",
".",
"__limit_decorator",
"(",
"limit_value",
",",
"key_func",... | decorator to be applied to multiple routes sharing the same rate limit.
:param limit_value: rate limit string or a callable that returns a string.
:ref:`ratelimit-string` for more details.
:param scope: a string or callable that returns a string
for defining the rate limiting scope.
... | [
"decorator",
"to",
"be",
"applied",
"to",
"multiple",
"routes",
"sharing",
"the",
"same",
"rate",
"limit",
"."
] | python | train |
agile-geoscience/welly | welly/curve.py | https://github.com/agile-geoscience/welly/blob/ed4c991011d6290938fef365553041026ba29f42/welly/curve.py#L817-L836 | def apply(self, window_length, samples=True, func1d=None):
"""
Runs any kind of function over a window.
Args:
window_length (int): the window length. Required.
samples (bool): window length is in samples. Use False for a window
length given in metres.
... | [
"def",
"apply",
"(",
"self",
",",
"window_length",
",",
"samples",
"=",
"True",
",",
"func1d",
"=",
"None",
")",
":",
"window_length",
"/=",
"1",
"if",
"samples",
"else",
"self",
".",
"step",
"if",
"func1d",
"is",
"None",
":",
"func1d",
"=",
"np",
".... | Runs any kind of function over a window.
Args:
window_length (int): the window length. Required.
samples (bool): window length is in samples. Use False for a window
length given in metres.
func1d (function): a function that takes a 1D array and returns a
... | [
"Runs",
"any",
"kind",
"of",
"function",
"over",
"a",
"window",
"."
] | python | train |
RudolfCardinal/pythonlib | cardinal_pythonlib/sphinxtools.py | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sphinxtools.py#L709-L737 | def get_sorted_source_files(
self,
source_filenames_or_globs: Union[str, List[str]],
recursive: bool = True) -> List[str]:
"""
Returns a sorted list of filenames to process, from a filename,
a glob string, or a list of filenames/globs.
Args:
... | [
"def",
"get_sorted_source_files",
"(",
"self",
",",
"source_filenames_or_globs",
":",
"Union",
"[",
"str",
",",
"List",
"[",
"str",
"]",
"]",
",",
"recursive",
":",
"bool",
"=",
"True",
")",
"->",
"List",
"[",
"str",
"]",
":",
"if",
"isinstance",
"(",
... | Returns a sorted list of filenames to process, from a filename,
a glob string, or a list of filenames/globs.
Args:
source_filenames_or_globs: filename/glob, or list of them
recursive: use :func:`glob.glob` in recursive mode?
Returns:
sorted list of files to ... | [
"Returns",
"a",
"sorted",
"list",
"of",
"filenames",
"to",
"process",
"from",
"a",
"filename",
"a",
"glob",
"string",
"or",
"a",
"list",
"of",
"filenames",
"/",
"globs",
"."
] | python | train |
PythonCharmers/python-future | src/future/backports/xmlrpc/server.py | https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/xmlrpc/server.py#L128-L150 | def resolve_dotted_attribute(obj, attr, allow_dotted_names=True):
"""resolve_dotted_attribute(a, 'b.c.d') => a.b.c.d
Resolves a dotted attribute name to an object. Raises
an AttributeError if any attribute in the chain starts with a '_'.
If the optional allow_dotted_names argument is false, dots are ... | [
"def",
"resolve_dotted_attribute",
"(",
"obj",
",",
"attr",
",",
"allow_dotted_names",
"=",
"True",
")",
":",
"if",
"allow_dotted_names",
":",
"attrs",
"=",
"attr",
".",
"split",
"(",
"'.'",
")",
"else",
":",
"attrs",
"=",
"[",
"attr",
"]",
"for",
"i",
... | resolve_dotted_attribute(a, 'b.c.d') => a.b.c.d
Resolves a dotted attribute name to an object. Raises
an AttributeError if any attribute in the chain starts with a '_'.
If the optional allow_dotted_names argument is false, dots are not
supported and this function operates similar to getattr(obj, attr... | [
"resolve_dotted_attribute",
"(",
"a",
"b",
".",
"c",
".",
"d",
")",
"=",
">",
"a",
".",
"b",
".",
"c",
".",
"d"
] | python | train |
iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/MSCommon/vc.py | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/MSCommon/vc.py#L302-L341 | def find_batch_file(env,msvc_version,host_arch,target_arch):
"""
Find the location of the batch script which should set up the compiler
for any TARGET_ARCH whose compilers were installed by Visual Studio/VCExpress
"""
pdir = find_vc_pdir(msvc_version)
if pdir is None:
raise NoVersionFoun... | [
"def",
"find_batch_file",
"(",
"env",
",",
"msvc_version",
",",
"host_arch",
",",
"target_arch",
")",
":",
"pdir",
"=",
"find_vc_pdir",
"(",
"msvc_version",
")",
"if",
"pdir",
"is",
"None",
":",
"raise",
"NoVersionFound",
"(",
"\"No version of Visual Studio found\... | Find the location of the batch script which should set up the compiler
for any TARGET_ARCH whose compilers were installed by Visual Studio/VCExpress | [
"Find",
"the",
"location",
"of",
"the",
"batch",
"script",
"which",
"should",
"set",
"up",
"the",
"compiler",
"for",
"any",
"TARGET_ARCH",
"whose",
"compilers",
"were",
"installed",
"by",
"Visual",
"Studio",
"/",
"VCExpress"
] | python | train |
bede/tictax | tictax/cli.py | https://github.com/bede/tictax/blob/acc9811be3a8b5ad905daf4b5d413f2c5e6ad06c/tictax/cli.py#L66-L73 | def matrix(fasta_path: 'path to tictax annotated fasta input',
scafstats_path: 'path to BBMap scaftstats file'):
'''
Generate taxonomic count matrix from tictax classified contigs
'''
records = SeqIO.parse(fasta_path, 'fasta')
df = tictax.matrix(records, scafstats_path)
df.to_csv(sys.... | [
"def",
"matrix",
"(",
"fasta_path",
":",
"'path to tictax annotated fasta input'",
",",
"scafstats_path",
":",
"'path to BBMap scaftstats file'",
")",
":",
"records",
"=",
"SeqIO",
".",
"parse",
"(",
"fasta_path",
",",
"'fasta'",
")",
"df",
"=",
"tictax",
".",
"ma... | Generate taxonomic count matrix from tictax classified contigs | [
"Generate",
"taxonomic",
"count",
"matrix",
"from",
"tictax",
"classified",
"contigs"
] | python | train |
edx/edx-oauth2-provider | edx_oauth2_provider/oidc/handlers.py | https://github.com/edx/edx-oauth2-provider/blob/73e7569a8369e74c345022ccba634365e24befab/edx_oauth2_provider/oidc/handlers.py#L83-L88 | def now(self):
""" Capture time. """
if self._now is None:
# Compute the current time only once per instance
self._now = datetime.utcnow()
return self._now | [
"def",
"now",
"(",
"self",
")",
":",
"if",
"self",
".",
"_now",
"is",
"None",
":",
"# Compute the current time only once per instance",
"self",
".",
"_now",
"=",
"datetime",
".",
"utcnow",
"(",
")",
"return",
"self",
".",
"_now"
] | Capture time. | [
"Capture",
"time",
"."
] | python | train |
albu/albumentations | albumentations/augmentations/bbox_utils.py | https://github.com/albu/albumentations/blob/b31393cd6126516d37a84e44c879bd92c68ffc93/albumentations/augmentations/bbox_utils.py#L122-L152 | def convert_bbox_from_albumentations(bbox, target_format, rows, cols, check_validity=False):
"""Convert a bounding box from the format used by albumentations to a format, specified in `target_format`.
Args:
bbox (list): bounding box with coordinates in the format used by albumentations
target_f... | [
"def",
"convert_bbox_from_albumentations",
"(",
"bbox",
",",
"target_format",
",",
"rows",
",",
"cols",
",",
"check_validity",
"=",
"False",
")",
":",
"if",
"target_format",
"not",
"in",
"{",
"'coco'",
",",
"'pascal_voc'",
"}",
":",
"raise",
"ValueError",
"(",... | Convert a bounding box from the format used by albumentations to a format, specified in `target_format`.
Args:
bbox (list): bounding box with coordinates in the format used by albumentations
target_format (str): required format of the output bounding box. Should be 'coco' or 'pascal_voc'.
r... | [
"Convert",
"a",
"bounding",
"box",
"from",
"the",
"format",
"used",
"by",
"albumentations",
"to",
"a",
"format",
"specified",
"in",
"target_format",
"."
] | python | train |
pypa/pipenv | pipenv/vendor/jinja2/compiler.py | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/compiler.py#L353-L358 | def start_write(self, frame, node=None):
"""Yield or write into the frame buffer."""
if frame.buffer is None:
self.writeline('yield ', node)
else:
self.writeline('%s.append(' % frame.buffer, node) | [
"def",
"start_write",
"(",
"self",
",",
"frame",
",",
"node",
"=",
"None",
")",
":",
"if",
"frame",
".",
"buffer",
"is",
"None",
":",
"self",
".",
"writeline",
"(",
"'yield '",
",",
"node",
")",
"else",
":",
"self",
".",
"writeline",
"(",
"'%s.append... | Yield or write into the frame buffer. | [
"Yield",
"or",
"write",
"into",
"the",
"frame",
"buffer",
"."
] | python | train |
MechanicalSoup/MechanicalSoup | mechanicalsoup/form.py | https://github.com/MechanicalSoup/MechanicalSoup/blob/027a270febf5bcda6a75db60ea9838d631370f4b/mechanicalsoup/form.py#L239-L278 | def set(self, name, value, force=False):
"""Set a form element identified by ``name`` to a specified ``value``.
The type of element (input, textarea, select, ...) does not
need to be given; it is inferred by the following methods:
:func:`~Form.set_checkbox`,
:func:`~Form.set_radi... | [
"def",
"set",
"(",
"self",
",",
"name",
",",
"value",
",",
"force",
"=",
"False",
")",
":",
"for",
"func",
"in",
"(",
"\"checkbox\"",
",",
"\"radio\"",
",",
"\"input\"",
",",
"\"textarea\"",
",",
"\"select\"",
")",
":",
"try",
":",
"getattr",
"(",
"s... | Set a form element identified by ``name`` to a specified ``value``.
The type of element (input, textarea, select, ...) does not
need to be given; it is inferred by the following methods:
:func:`~Form.set_checkbox`,
:func:`~Form.set_radio`,
:func:`~Form.set_input`,
:func:`... | [
"Set",
"a",
"form",
"element",
"identified",
"by",
"name",
"to",
"a",
"specified",
"value",
".",
"The",
"type",
"of",
"element",
"(",
"input",
"textarea",
"select",
"...",
")",
"does",
"not",
"need",
"to",
"be",
"given",
";",
"it",
"is",
"inferred",
"b... | python | train |
dask/dask-ml | dask_ml/model_selection/_search.py | https://github.com/dask/dask-ml/blob/cc4837c2c2101f9302cac38354b55754263cd1f3/dask_ml/model_selection/_search.py#L225-L240 | def normalize_params(params):
"""Take a list of dictionaries, and tokenize/normalize."""
# Collect a set of all fields
fields = set()
for p in params:
fields.update(p)
fields = sorted(fields)
params2 = list(pluck(fields, params, MISSING))
# Non-basic types (including MISSING) are un... | [
"def",
"normalize_params",
"(",
"params",
")",
":",
"# Collect a set of all fields",
"fields",
"=",
"set",
"(",
")",
"for",
"p",
"in",
"params",
":",
"fields",
".",
"update",
"(",
"p",
")",
"fields",
"=",
"sorted",
"(",
"fields",
")",
"params2",
"=",
"li... | Take a list of dictionaries, and tokenize/normalize. | [
"Take",
"a",
"list",
"of",
"dictionaries",
"and",
"tokenize",
"/",
"normalize",
"."
] | python | train |
zerok/zs.bibtex | src/zs/bibtex/parser.py | https://github.com/zerok/zs.bibtex/blob/ac9594b36b9d4ec9a3593c0dc7c1a35e5aea04d9/src/zs/bibtex/parser.py#L37-L52 | def parse_entry(source, loc, tokens):
"""
Converts the tokens of an entry into an Entry instance. If no applicable
type is available, an UnsupportedEntryType exception is raised.
"""
type_ = tokens[1].lower()
entry_type = structures.TypeRegistry.get_type(type_)
if entry_type is None or not i... | [
"def",
"parse_entry",
"(",
"source",
",",
"loc",
",",
"tokens",
")",
":",
"type_",
"=",
"tokens",
"[",
"1",
"]",
".",
"lower",
"(",
")",
"entry_type",
"=",
"structures",
".",
"TypeRegistry",
".",
"get_type",
"(",
"type_",
")",
"if",
"entry_type",
"is",... | Converts the tokens of an entry into an Entry instance. If no applicable
type is available, an UnsupportedEntryType exception is raised. | [
"Converts",
"the",
"tokens",
"of",
"an",
"entry",
"into",
"an",
"Entry",
"instance",
".",
"If",
"no",
"applicable",
"type",
"is",
"available",
"an",
"UnsupportedEntryType",
"exception",
"is",
"raised",
"."
] | python | train |
Robpol86/terminaltables | terminaltables/base_table.py | https://github.com/Robpol86/terminaltables/blob/ad8f46e50afdbaea377fc1f713bc0e7a31c4fccc/terminaltables/base_table.py#L112-L169 | def gen_row_lines(self, row, style, inner_widths, height):
r"""Combine cells in row and group them into lines with vertical borders.
Caller is expected to pass yielded lines to ''.join() to combine them into a printable line. Caller must append
newline character to the end of joined line.
... | [
"def",
"gen_row_lines",
"(",
"self",
",",
"row",
",",
"style",
",",
"inner_widths",
",",
"height",
")",
":",
"cells_in_row",
"=",
"list",
"(",
")",
"# Resize row if it doesn't have enough cells.",
"if",
"len",
"(",
"row",
")",
"!=",
"len",
"(",
"inner_widths",... | r"""Combine cells in row and group them into lines with vertical borders.
Caller is expected to pass yielded lines to ''.join() to combine them into a printable line. Caller must append
newline character to the end of joined line.
In:
['Row One Column One', 'Two', 'Three']
Out:... | [
"r",
"Combine",
"cells",
"in",
"row",
"and",
"group",
"them",
"into",
"lines",
"with",
"vertical",
"borders",
"."
] | python | train |
clalancette/pycdlib | pycdlib/eltorito.py | https://github.com/clalancette/pycdlib/blob/1e7b77a809e905d67dc71e12d70e850be26b6233/pycdlib/eltorito.py#L873-L966 | def hdmbrcheck(disk_mbr, sector_count, bootable):
# type: (bytes, int, bool) -> int
'''
A function to sanity check an El Torito Hard Drive Master Boot Record (HDMBR).
On success, it returns the system_type (also known as the partition type) that
should be fed into the rest of the El Torito methods. ... | [
"def",
"hdmbrcheck",
"(",
"disk_mbr",
",",
"sector_count",
",",
"bootable",
")",
":",
"# type: (bytes, int, bool) -> int",
"# The MBR that we want to see to do hd emulation boot for El Torito is a standard",
"# x86 MBR, documented here:",
"# https://en.wikipedia.org/wiki/Master_boot_record... | A function to sanity check an El Torito Hard Drive Master Boot Record (HDMBR).
On success, it returns the system_type (also known as the partition type) that
should be fed into the rest of the El Torito methods. On failure, it raises
an exception.
Parameters:
disk_mbr - The data to look in.
... | [
"A",
"function",
"to",
"sanity",
"check",
"an",
"El",
"Torito",
"Hard",
"Drive",
"Master",
"Boot",
"Record",
"(",
"HDMBR",
")",
".",
"On",
"success",
"it",
"returns",
"the",
"system_type",
"(",
"also",
"known",
"as",
"the",
"partition",
"type",
")",
"tha... | python | train |
ArduPilot/MAVProxy | MAVProxy/modules/mavproxy_example.py | https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/mavproxy_example.py#L74-L83 | def idle_task(self):
'''called rapidly by mavproxy'''
now = time.time()
if now-self.last_bored > self.boredom_interval:
self.last_bored = now
message = self.boredom_message()
self.say("%s: %s" % (self.name,message))
# See if whatever we're connecte... | [
"def",
"idle_task",
"(",
"self",
")",
":",
"now",
"=",
"time",
".",
"time",
"(",
")",
"if",
"now",
"-",
"self",
".",
"last_bored",
">",
"self",
".",
"boredom_interval",
":",
"self",
".",
"last_bored",
"=",
"now",
"message",
"=",
"self",
".",
"boredom... | called rapidly by mavproxy | [
"called",
"rapidly",
"by",
"mavproxy"
] | python | train |
trsqxyz/glitch | glitch/glitch.py | https://github.com/trsqxyz/glitch/blob/b2cef7700a09660ff8a79ae587480680bef65a88/glitch/glitch.py#L114-L123 | def decrease(self, infile):
'''Decrease: 任意の箇所のバイト列を 削除する
'''
gf = infile[31:]
try:
index = random.randint(len(gf)-1, 31)
except ValueError:
return infile
gf = gf[:index] + gf[index+1:]
return infile[:31] + gf | [
"def",
"decrease",
"(",
"self",
",",
"infile",
")",
":",
"gf",
"=",
"infile",
"[",
"31",
":",
"]",
"try",
":",
"index",
"=",
"random",
".",
"randint",
"(",
"len",
"(",
"gf",
")",
"-",
"1",
",",
"31",
")",
"except",
"ValueError",
":",
"return",
... | Decrease: 任意の箇所のバイト列を 削除する | [
"Decrease",
":",
"任意の箇所のバイト列を",
"削除する"
] | python | train |
kivy/python-for-android | pythonforandroid/bootstraps/pygame/build/buildlib/jinja2.egg/jinja2/ext.py | https://github.com/kivy/python-for-android/blob/8e0e8056bc22e4d5bd3398a6b0301f38ff167933/pythonforandroid/bootstraps/pygame/build/buildlib/jinja2.egg/jinja2/ext.py#L486-L545 | def babel_extract(fileobj, keywords, comment_tags, options):
"""Babel extraction method for Jinja templates.
.. versionchanged:: 2.3
Basic support for translation comments was added. If `comment_tags`
is now set to a list of keywords for extraction, the extractor will
try to find the best... | [
"def",
"babel_extract",
"(",
"fileobj",
",",
"keywords",
",",
"comment_tags",
",",
"options",
")",
":",
"extensions",
"=",
"set",
"(",
")",
"for",
"extension",
"in",
"options",
".",
"get",
"(",
"'extensions'",
",",
"''",
")",
".",
"split",
"(",
"','",
... | Babel extraction method for Jinja templates.
.. versionchanged:: 2.3
Basic support for translation comments was added. If `comment_tags`
is now set to a list of keywords for extraction, the extractor will
try to find the best preceeding comment that begins with one of the
keywords. Fo... | [
"Babel",
"extraction",
"method",
"for",
"Jinja",
"templates",
"."
] | python | train |
mk-fg/python-onedrive | onedrive/conf.py | https://github.com/mk-fg/python-onedrive/blob/74d3f6605b0e8a9031a2aab8092f551293ffb533/onedrive/conf.py#L36-L80 | def from_conf(cls, path=None, **overrides):
'''Initialize instance from YAML configuration file,
writing updates (only to keys, specified by "conf_update_keys") back to it.'''
from onedrive import portalocker
import yaml
if path is None:
path = cls.conf_path_default
log.debug('Using default state-file... | [
"def",
"from_conf",
"(",
"cls",
",",
"path",
"=",
"None",
",",
"*",
"*",
"overrides",
")",
":",
"from",
"onedrive",
"import",
"portalocker",
"import",
"yaml",
"if",
"path",
"is",
"None",
":",
"path",
"=",
"cls",
".",
"conf_path_default",
"log",
".",
"d... | Initialize instance from YAML configuration file,
writing updates (only to keys, specified by "conf_update_keys") back to it. | [
"Initialize",
"instance",
"from",
"YAML",
"configuration",
"file",
"writing",
"updates",
"(",
"only",
"to",
"keys",
"specified",
"by",
"conf_update_keys",
")",
"back",
"to",
"it",
"."
] | python | test |
OnroerendErfgoed/pyramid_urireferencer | pyramid_urireferencer/protected_resources.py | https://github.com/OnroerendErfgoed/pyramid_urireferencer/blob/c6ee4ba863e32ced304b9cf00f3f5b450757a29a/pyramid_urireferencer/protected_resources.py#L83-L103 | def protected_operation(fn):
"""
Use this decorator to prevent an operation from being executed
when the related uri resource is still in use.
The parent_object must contain:
* a request
* with a registry.queryUtility(IReferencer)
:raises pyramid.httpexceptions.HTTPConflict: Sign... | [
"def",
"protected_operation",
"(",
"fn",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"fn",
")",
"def",
"advice",
"(",
"parent_object",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"response",
"=",
"_advice",
"(",
"parent_object",
".",
"request",... | Use this decorator to prevent an operation from being executed
when the related uri resource is still in use.
The parent_object must contain:
* a request
* with a registry.queryUtility(IReferencer)
:raises pyramid.httpexceptions.HTTPConflict: Signals that we don't want to
delete ... | [
"Use",
"this",
"decorator",
"to",
"prevent",
"an",
"operation",
"from",
"being",
"executed",
"when",
"the",
"related",
"uri",
"resource",
"is",
"still",
"in",
"use",
".",
"The",
"parent_object",
"must",
"contain",
":",
"*",
"a",
"request",
"*",
"with",
"a"... | python | train |
astrorafael/twisted-mqtt | mqtt/pdu.py | https://github.com/astrorafael/twisted-mqtt/blob/5b322f7c2b82a502b1e1b70703ae45f1f668d07d/mqtt/pdu.py#L511-L542 | def encode(self):
'''
Encode and store a PUBLISH control packet.
@raise e: C{ValueError} if encoded topic string exceeds 65535 bytes.
@raise e: C{ValueError} if encoded packet size exceeds 268435455 bytes.
@raise e: C{TypeError} if C{data} is not a string, bytearray, int, boolean... | [
"def",
"encode",
"(",
"self",
")",
":",
"header",
"=",
"bytearray",
"(",
"1",
")",
"varHeader",
"=",
"bytearray",
"(",
")",
"payload",
"=",
"bytearray",
"(",
")",
"if",
"self",
".",
"qos",
":",
"header",
"[",
"0",
"]",
"=",
"0x30",
"|",
"self",
"... | Encode and store a PUBLISH control packet.
@raise e: C{ValueError} if encoded topic string exceeds 65535 bytes.
@raise e: C{ValueError} if encoded packet size exceeds 268435455 bytes.
@raise e: C{TypeError} if C{data} is not a string, bytearray, int, boolean or float. | [
"Encode",
"and",
"store",
"a",
"PUBLISH",
"control",
"packet",
"."
] | python | test |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.