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 |
|---|---|---|---|---|---|---|---|---|
Jammy2211/PyAutoLens | autolens/data/ccd.py | https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/data/ccd.py#L656-L677 | def convolve(self, array):
"""
Convolve an array with this PSF
Parameters
----------
image : ndarray
An array representing the image the PSF is convolved with.
Returns
-------
convolved_image : ndarray
An array representing the im... | [
"def",
"convolve",
"(",
"self",
",",
"array",
")",
":",
"if",
"self",
".",
"shape",
"[",
"0",
"]",
"%",
"2",
"==",
"0",
"or",
"self",
".",
"shape",
"[",
"1",
"]",
"%",
"2",
"==",
"0",
":",
"raise",
"exc",
".",
"KernelException",
"(",
"\"PSF Ker... | Convolve an array with this PSF
Parameters
----------
image : ndarray
An array representing the image the PSF is convolved with.
Returns
-------
convolved_image : ndarray
An array representing the image after convolution.
Raises
... | [
"Convolve",
"an",
"array",
"with",
"this",
"PSF"
] | python | valid |
dswah/pyGAM | pygam/utils.py | https://github.com/dswah/pyGAM/blob/b3e5c3cd580f0a3ad69f9372861624f67760c325/pygam/utils.py#L402-L417 | def get_link_domain(link, dist):
"""
tool to identify the domain of a given monotonic link function
Parameters
----------
link : Link object
dist : Distribution object
Returns
-------
domain : list of length 2, representing the interval of the domain.
"""
domain = np.array(... | [
"def",
"get_link_domain",
"(",
"link",
",",
"dist",
")",
":",
"domain",
"=",
"np",
".",
"array",
"(",
"[",
"-",
"np",
".",
"inf",
",",
"-",
"1",
",",
"0",
",",
"1",
",",
"np",
".",
"inf",
"]",
")",
"domain",
"=",
"domain",
"[",
"~",
"np",
"... | tool to identify the domain of a given monotonic link function
Parameters
----------
link : Link object
dist : Distribution object
Returns
-------
domain : list of length 2, representing the interval of the domain. | [
"tool",
"to",
"identify",
"the",
"domain",
"of",
"a",
"given",
"monotonic",
"link",
"function"
] | python | train |
sci-bots/pygtkhelpers | pygtkhelpers/schema.py | https://github.com/sci-bots/pygtkhelpers/blob/3a6e6d6340221c686229cd1c951d7537dae81b07/pygtkhelpers/schema.py#L57-L87 | def flatten_dict(root, parents=None, sep='.'):
'''
Args:
root (dict) : Nested dictionary (e.g., JSON object).
parents (list) : List of ancestor keys.
Returns
-------
list
List of ``(key, value)`` tuples, where ``key`` corresponds to the
ancestor keys of the respecti... | [
"def",
"flatten_dict",
"(",
"root",
",",
"parents",
"=",
"None",
",",
"sep",
"=",
"'.'",
")",
":",
"if",
"parents",
"is",
"None",
":",
"parents",
"=",
"[",
"]",
"result",
"=",
"[",
"]",
"for",
"i",
",",
"(",
"k",
",",
"v",
")",
"in",
"enumerate... | Args:
root (dict) : Nested dictionary (e.g., JSON object).
parents (list) : List of ancestor keys.
Returns
-------
list
List of ``(key, value)`` tuples, where ``key`` corresponds to the
ancestor keys of the respective value joined by ``'.'``. For example,
for the i... | [
"Args",
":"
] | python | train |
Cognexa/cxflow | cxflow/hooks/show_progress.py | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/hooks/show_progress.py#L134-L144 | def after_epoch(self, **_) -> None:
"""
Reset progress counters. Save ``total_batch_count`` after the 1st epoch.
"""
if not self._total_batch_count_saved:
self._total_batch_count = self._current_batch_count.copy()
self._total_batch_count_saved = True
self.... | [
"def",
"after_epoch",
"(",
"self",
",",
"*",
"*",
"_",
")",
"->",
"None",
":",
"if",
"not",
"self",
".",
"_total_batch_count_saved",
":",
"self",
".",
"_total_batch_count",
"=",
"self",
".",
"_current_batch_count",
".",
"copy",
"(",
")",
"self",
".",
"_t... | Reset progress counters. Save ``total_batch_count`` after the 1st epoch. | [
"Reset",
"progress",
"counters",
".",
"Save",
"total_batch_count",
"after",
"the",
"1st",
"epoch",
"."
] | python | train |
GoogleCloudPlatform/appengine-mapreduce | python/src/mapreduce/records.py | https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/python/src/mapreduce/records.py#L239-L278 | def __try_read_record(self):
"""Try reading a record.
Returns:
(data, record_type) tuple.
Raises:
EOFError: when end of file was reached.
InvalidRecordError: when valid record could not be read.
"""
block_remaining = _BLOCK_SIZE - self.__reader.tell() % _BLOCK_SIZE
if block_re... | [
"def",
"__try_read_record",
"(",
"self",
")",
":",
"block_remaining",
"=",
"_BLOCK_SIZE",
"-",
"self",
".",
"__reader",
".",
"tell",
"(",
")",
"%",
"_BLOCK_SIZE",
"if",
"block_remaining",
"<",
"_HEADER_LENGTH",
":",
"return",
"(",
"''",
",",
"_RECORD_TYPE_NONE... | Try reading a record.
Returns:
(data, record_type) tuple.
Raises:
EOFError: when end of file was reached.
InvalidRecordError: when valid record could not be read. | [
"Try",
"reading",
"a",
"record",
"."
] | python | train |
Jajcus/pyxmpp2 | pyxmpp2/mainloop/glib.py | https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/mainloop/glib.py#L206-L214 | def _add_timeout_handler(self, handler):
"""Add a `TimeoutHandler` to the main loop."""
# pylint: disable=W0212
for dummy, method in inspect.getmembers(handler, callable):
if not hasattr(method, "_pyxmpp_timeout"):
continue
tag = glib.timeout_add(int(metho... | [
"def",
"_add_timeout_handler",
"(",
"self",
",",
"handler",
")",
":",
"# pylint: disable=W0212",
"for",
"dummy",
",",
"method",
"in",
"inspect",
".",
"getmembers",
"(",
"handler",
",",
"callable",
")",
":",
"if",
"not",
"hasattr",
"(",
"method",
",",
"\"_pyx... | Add a `TimeoutHandler` to the main loop. | [
"Add",
"a",
"TimeoutHandler",
"to",
"the",
"main",
"loop",
"."
] | python | valid |
intel-analytics/BigDL | pyspark/bigdl/nn/layer.py | https://github.com/intel-analytics/BigDL/blob/e9c19788285986ab789a2e2998f9a85d7524779f/pyspark/bigdl/nn/layer.py#L177-L185 | def from_jvalue(jvalue, bigdl_type="float"):
"""
Create a Python Model base on the given java value
:param jvalue: Java object create by Py4j
:return: A Python Model
"""
model = Layer(jvalue=jvalue, bigdl_type=bigdl_type)
model.value = jvalue
return model | [
"def",
"from_jvalue",
"(",
"jvalue",
",",
"bigdl_type",
"=",
"\"float\"",
")",
":",
"model",
"=",
"Layer",
"(",
"jvalue",
"=",
"jvalue",
",",
"bigdl_type",
"=",
"bigdl_type",
")",
"model",
".",
"value",
"=",
"jvalue",
"return",
"model"
] | Create a Python Model base on the given java value
:param jvalue: Java object create by Py4j
:return: A Python Model | [
"Create",
"a",
"Python",
"Model",
"base",
"on",
"the",
"given",
"java",
"value",
":",
"param",
"jvalue",
":",
"Java",
"object",
"create",
"by",
"Py4j",
":",
"return",
":",
"A",
"Python",
"Model"
] | python | test |
thumbor/thumbor | thumbor/transformer.py | https://github.com/thumbor/thumbor/blob/558ccdd6e3bc29e1c9ee3687372c4b3eb05ac607/thumbor/transformer.py#L219-L233 | def do_image_operations(self):
"""
If ENGINE_THREADPOOL_SIZE > 0, this will schedule the image operations
into a threadpool. If not, it just executes them synchronously, and
calls self.done_callback when it's finished.
The actual work happens in self.img_operation_worker
... | [
"def",
"do_image_operations",
"(",
"self",
")",
":",
"def",
"inner",
"(",
"future",
")",
":",
"self",
".",
"done_callback",
"(",
")",
"self",
".",
"context",
".",
"thread_pool",
".",
"queue",
"(",
"operation",
"=",
"self",
".",
"img_operation_worker",
",",... | If ENGINE_THREADPOOL_SIZE > 0, this will schedule the image operations
into a threadpool. If not, it just executes them synchronously, and
calls self.done_callback when it's finished.
The actual work happens in self.img_operation_worker | [
"If",
"ENGINE_THREADPOOL_SIZE",
">",
"0",
"this",
"will",
"schedule",
"the",
"image",
"operations",
"into",
"a",
"threadpool",
".",
"If",
"not",
"it",
"just",
"executes",
"them",
"synchronously",
"and",
"calls",
"self",
".",
"done_callback",
"when",
"it",
"s",... | python | train |
dhermes/bezier | src/bezier/surface.py | https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/surface.py#L600-L658 | def evaluate_cartesian_multi(self, param_vals, _verify=True):
r"""Compute multiple points on the surface.
Assumes ``param_vals`` has two columns of Cartesian coordinates.
See :meth:`evaluate_cartesian` for more details on how each row of
parameter values is evaluated.
.. image:... | [
"def",
"evaluate_cartesian_multi",
"(",
"self",
",",
"param_vals",
",",
"_verify",
"=",
"True",
")",
":",
"if",
"_verify",
":",
"if",
"param_vals",
".",
"ndim",
"!=",
"2",
":",
"raise",
"ValueError",
"(",
"\"Parameter values must be 2D array\"",
")",
"for",
"s... | r"""Compute multiple points on the surface.
Assumes ``param_vals`` has two columns of Cartesian coordinates.
See :meth:`evaluate_cartesian` for more details on how each row of
parameter values is evaluated.
.. image:: ../../images/surface_evaluate_cartesian_multi.png
:align:... | [
"r",
"Compute",
"multiple",
"points",
"on",
"the",
"surface",
"."
] | python | train |
joferkington/mplstereonet | mplstereonet/stereonet_axes.py | https://github.com/joferkington/mplstereonet/blob/f6d78ca49807915d4223e864e12bb24d497cc2d6/mplstereonet/stereonet_axes.py#L500-L524 | def _point_plot_defaults(self, args, kwargs):
"""To avoid confusion for new users, this ensures that "scattered"
points are plotted by by `plot` instead of points joined by a line.
Parameters
----------
args : tuple
Arguments representing additional parameters to be ... | [
"def",
"_point_plot_defaults",
"(",
"self",
",",
"args",
",",
"kwargs",
")",
":",
"if",
"args",
":",
"return",
"args",
",",
"kwargs",
"if",
"'ls'",
"not",
"in",
"kwargs",
"and",
"'linestyle'",
"not",
"in",
"kwargs",
":",
"kwargs",
"[",
"'linestyle'",
"]"... | To avoid confusion for new users, this ensures that "scattered"
points are plotted by by `plot` instead of points joined by a line.
Parameters
----------
args : tuple
Arguments representing additional parameters to be passed to
`self.plot`.
kwargs : dict
... | [
"To",
"avoid",
"confusion",
"for",
"new",
"users",
"this",
"ensures",
"that",
"scattered",
"points",
"are",
"plotted",
"by",
"by",
"plot",
"instead",
"of",
"points",
"joined",
"by",
"a",
"line",
"."
] | python | train |
materialsproject/pymatgen | pymatgen/io/feff/inputs.py | https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/io/feff/inputs.py#L558-L603 | def from_file(filename="feff.inp"):
"""
Creates a Feff_tag dictionary from a PARAMETER or feff.inp file.
Args:
filename: Filename for either PARAMETER or feff.inp file
Returns:
Feff_tag object
"""
with zopen(filename, "rt") as f:
line... | [
"def",
"from_file",
"(",
"filename",
"=",
"\"feff.inp\"",
")",
":",
"with",
"zopen",
"(",
"filename",
",",
"\"rt\"",
")",
"as",
"f",
":",
"lines",
"=",
"list",
"(",
"clean_lines",
"(",
"f",
".",
"readlines",
"(",
")",
")",
")",
"params",
"=",
"{",
... | Creates a Feff_tag dictionary from a PARAMETER or feff.inp file.
Args:
filename: Filename for either PARAMETER or feff.inp file
Returns:
Feff_tag object | [
"Creates",
"a",
"Feff_tag",
"dictionary",
"from",
"a",
"PARAMETER",
"or",
"feff",
".",
"inp",
"file",
"."
] | python | train |
fastai/fastai | fastai/vision/image.py | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/image.py#L299-L303 | def pixel(self, func:PixelFunc, *args, **kwargs)->'ImagePoints':
"Equivalent to `self = func_flow(self)`."
self = func(self, *args, **kwargs)
self.transformed=True
return self | [
"def",
"pixel",
"(",
"self",
",",
"func",
":",
"PixelFunc",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"->",
"'ImagePoints'",
":",
"self",
"=",
"func",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"self",
".",
"transformed",
... | Equivalent to `self = func_flow(self)`. | [
"Equivalent",
"to",
"self",
"=",
"func_flow",
"(",
"self",
")",
"."
] | python | train |
pkgw/pwkit | pwkit/lmmin.py | https://github.com/pkgw/pwkit/blob/d40957a1c3d2ea34e7ceac2267ee9635135f2793/pwkit/lmmin.py#L774-L815 | def _qrd_solve_full(a, b, ddiag, dtype=np.float):
"""Solve the equation A^T x = B, D x = 0.
Parameters:
a - an n-by-m array, m >= n
b - an m-vector
ddiag - an n-vector giving the diagonal of D. (The rest of D is 0.)
Returns:
x - n-vector solving the equation.
s - the n-by-n supplementary matrix s.
p... | [
"def",
"_qrd_solve_full",
"(",
"a",
",",
"b",
",",
"ddiag",
",",
"dtype",
"=",
"np",
".",
"float",
")",
":",
"a",
"=",
"np",
".",
"asarray",
"(",
"a",
",",
"dtype",
")",
"b",
"=",
"np",
".",
"asarray",
"(",
"b",
",",
"dtype",
")",
"ddiag",
"=... | Solve the equation A^T x = B, D x = 0.
Parameters:
a - an n-by-m array, m >= n
b - an m-vector
ddiag - an n-vector giving the diagonal of D. (The rest of D is 0.)
Returns:
x - n-vector solving the equation.
s - the n-by-n supplementary matrix s.
pmut - n-element permutation vector defining the permutati... | [
"Solve",
"the",
"equation",
"A^T",
"x",
"=",
"B",
"D",
"x",
"=",
"0",
"."
] | python | train |
edeposit/edeposit.amqp.aleph | src/edeposit/amqp/aleph/export.py | https://github.com/edeposit/edeposit.amqp.aleph/blob/360342c0504d5daa2344e864762cdf938d4149c7/src/edeposit/amqp/aleph/export.py#L321-L343 | def _sendPostDict(post_dict):
"""
Send `post_dict` to the :attr:`.ALEPH_EXPORT_URL`.
Args:
post_dict (dict): dictionary from :class:`PostData.get_POST_data()`
Returns:
str: Reponse from webform.
"""
downer = Downloader()
downer.headers["Referer"] = settings.EDEPOSIT_EXPORT_... | [
"def",
"_sendPostDict",
"(",
"post_dict",
")",
":",
"downer",
"=",
"Downloader",
"(",
")",
"downer",
".",
"headers",
"[",
"\"Referer\"",
"]",
"=",
"settings",
".",
"EDEPOSIT_EXPORT_REFERER",
"data",
"=",
"downer",
".",
"download",
"(",
"settings",
".",
"ALEP... | Send `post_dict` to the :attr:`.ALEPH_EXPORT_URL`.
Args:
post_dict (dict): dictionary from :class:`PostData.get_POST_data()`
Returns:
str: Reponse from webform. | [
"Send",
"post_dict",
"to",
"the",
":",
"attr",
":",
".",
"ALEPH_EXPORT_URL",
"."
] | python | train |
saltstack/salt | salt/modules/redismod.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/redismod.py#L574-L585 | def save(host=None, port=None, db=None, password=None):
'''
Synchronously save the dataset to disk
CLI Example:
.. code-block:: bash
salt '*' redis.save
'''
server = _connect(host, port, db, password)
return server.save() | [
"def",
"save",
"(",
"host",
"=",
"None",
",",
"port",
"=",
"None",
",",
"db",
"=",
"None",
",",
"password",
"=",
"None",
")",
":",
"server",
"=",
"_connect",
"(",
"host",
",",
"port",
",",
"db",
",",
"password",
")",
"return",
"server",
".",
"sav... | Synchronously save the dataset to disk
CLI Example:
.. code-block:: bash
salt '*' redis.save | [
"Synchronously",
"save",
"the",
"dataset",
"to",
"disk"
] | python | train |
ska-sa/katcp-python | katcp/resource_client.py | https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/katcp/resource_client.py#L407-L426 | def start(self):
"""Start the client and connect"""
# TODO (NM 2015-03-12) Some checking to prevent multiple calls to start()
host, port = self.address
ic = self._inspecting_client = self.inspecting_client_factory(
host, port, self._ioloop_set_to)
self.ioloop = ic.iol... | [
"def",
"start",
"(",
"self",
")",
":",
"# TODO (NM 2015-03-12) Some checking to prevent multiple calls to start()",
"host",
",",
"port",
"=",
"self",
".",
"address",
"ic",
"=",
"self",
".",
"_inspecting_client",
"=",
"self",
".",
"inspecting_client_factory",
"(",
"hos... | Start the client and connect | [
"Start",
"the",
"client",
"and",
"connect"
] | python | train |
materialsproject/pymatgen | pymatgen/analysis/local_env.py | https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/analysis/local_env.py#L778-L792 | def _is_in_targets(self, site, targets):
"""
Test whether a site contains elements in the target list
Args:
site (Site): Site to assess
targets ([Element]) List of elements
Returns:
(boolean) Whether this site contains a certain list of elements
... | [
"def",
"_is_in_targets",
"(",
"self",
",",
"site",
",",
"targets",
")",
":",
"elems",
"=",
"self",
".",
"_get_elements",
"(",
"site",
")",
"for",
"elem",
"in",
"elems",
":",
"if",
"elem",
"not",
"in",
"targets",
":",
"return",
"False",
"return",
"True"... | Test whether a site contains elements in the target list
Args:
site (Site): Site to assess
targets ([Element]) List of elements
Returns:
(boolean) Whether this site contains a certain list of elements | [
"Test",
"whether",
"a",
"site",
"contains",
"elements",
"in",
"the",
"target",
"list"
] | python | train |
rfk/django-supervisor | djsupervisor/config.py | https://github.com/rfk/django-supervisor/blob/545a379d4a73ed2ae21c4aee6b8009ded8aeedc6/djsupervisor/config.py#L33-L138 | def get_merged_config(**options):
"""Get the final merged configuration for supvervisord, as a string.
This is the top-level function exported by this module. It combines
the config file from the main project with default settings and those
specified in the command-line, processes various special sect... | [
"def",
"get_merged_config",
"(",
"*",
"*",
"options",
")",
":",
"# Find and load the containing project module.",
"# This can be specified explicity using the --project-dir option.",
"# Otherwise, we attempt to guess by looking for the manage.py file.",
"project_dir",
"=",
"options",
... | Get the final merged configuration for supvervisord, as a string.
This is the top-level function exported by this module. It combines
the config file from the main project with default settings and those
specified in the command-line, processes various special section names,
and returns the resulting ... | [
"Get",
"the",
"final",
"merged",
"configuration",
"for",
"supvervisord",
"as",
"a",
"string",
"."
] | python | train |
noahbenson/pimms | pimms/calculation.py | https://github.com/noahbenson/pimms/blob/9051b86d6b858a7a13511b72c48dc21bc903dab2/pimms/calculation.py#L125-L136 | def discard_defaults(self, *args):
'''
node.discard_defaults(a, b...) yields a new calculation node identical to the given node
except that the default values for the given afferent parameters named by the arguments a,
b, etc. have been removed. In the new node that is returned, these pa... | [
"def",
"discard_defaults",
"(",
"self",
",",
"*",
"args",
")",
":",
"rms",
"=",
"set",
"(",
"arg",
"for",
"aa",
"in",
"args",
"for",
"arg",
"in",
"(",
"[",
"aa",
"]",
"if",
"isinstance",
"(",
"aa",
",",
"six",
".",
"string_types",
")",
"else",
"a... | node.discard_defaults(a, b...) yields a new calculation node identical to the given node
except that the default values for the given afferent parameters named by the arguments a,
b, etc. have been removed. In the new node that is returned, these parameters will be
required. | [
"node",
".",
"discard_defaults",
"(",
"a",
"b",
"...",
")",
"yields",
"a",
"new",
"calculation",
"node",
"identical",
"to",
"the",
"given",
"node",
"except",
"that",
"the",
"default",
"values",
"for",
"the",
"given",
"afferent",
"parameters",
"named",
"by",
... | python | train |
acoomans/flask-autodoc | flask_autodoc/autodoc.py | https://github.com/acoomans/flask-autodoc/blob/6c77c8935b71fbf3243b5e589c5c255d0299d853/flask_autodoc/autodoc.py#L64-L111 | def doc(self, groups=None, set_location=True, **properties):
"""Add flask route to autodoc for automatic documentation
Any route decorated with this method will be added to the list of
routes to be documented by the generate() or html() methods.
By default, the route is added to the 'a... | [
"def",
"doc",
"(",
"self",
",",
"groups",
"=",
"None",
",",
"set_location",
"=",
"True",
",",
"*",
"*",
"properties",
")",
":",
"def",
"decorator",
"(",
"f",
")",
":",
"# Get previous group list (if any)",
"if",
"f",
"in",
"self",
".",
"func_groups",
":"... | Add flask route to autodoc for automatic documentation
Any route decorated with this method will be added to the list of
routes to be documented by the generate() or html() methods.
By default, the route is added to the 'all' group.
By specifying group or groups argument, the route can... | [
"Add",
"flask",
"route",
"to",
"autodoc",
"for",
"automatic",
"documentation"
] | python | train |
saltstack/salt | salt/modules/glusterfs.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/glusterfs.py#L545-L589 | def add_volume_bricks(name, bricks):
'''
Add brick(s) to an existing volume
name
Volume name
bricks
List of bricks to add to the volume
CLI Example:
.. code-block:: bash
salt '*' glusterfs.add_volume_bricks <volume> <bricks>
'''
volinfo = info()
if name ... | [
"def",
"add_volume_bricks",
"(",
"name",
",",
"bricks",
")",
":",
"volinfo",
"=",
"info",
"(",
")",
"if",
"name",
"not",
"in",
"volinfo",
":",
"log",
".",
"error",
"(",
"'Volume %s does not exist, cannot add bricks'",
",",
"name",
")",
"return",
"False",
"ne... | Add brick(s) to an existing volume
name
Volume name
bricks
List of bricks to add to the volume
CLI Example:
.. code-block:: bash
salt '*' glusterfs.add_volume_bricks <volume> <bricks> | [
"Add",
"brick",
"(",
"s",
")",
"to",
"an",
"existing",
"volume"
] | python | train |
Sliim/soundcloud-syncer | ssyncer/strack.py | https://github.com/Sliim/soundcloud-syncer/blob/f15142677bf8e5fb54f40b0eb9a36f21ba940ab6/ssyncer/strack.py#L162-L217 | def download(self, localdir, max_retry):
""" Download a track in local directory. """
local_file = self.gen_localdir(localdir) + self.gen_filename()
if self.track_exists(localdir):
print("Track {0} already downloaded, skipping!".format(
self.get("id")))
r... | [
"def",
"download",
"(",
"self",
",",
"localdir",
",",
"max_retry",
")",
":",
"local_file",
"=",
"self",
".",
"gen_localdir",
"(",
"localdir",
")",
"+",
"self",
".",
"gen_filename",
"(",
")",
"if",
"self",
".",
"track_exists",
"(",
"localdir",
")",
":",
... | Download a track in local directory. | [
"Download",
"a",
"track",
"in",
"local",
"directory",
"."
] | python | train |
skymill/automated-ebs-snapshots | automated_ebs_snapshots/__init__.py | https://github.com/skymill/automated-ebs-snapshots/blob/9595bc49d458f6ffb93430722757d2284e878fab/automated_ebs_snapshots/__init__.py#L109-L171 | def main():
""" Main function """
# Read configuration from the config file if present, else fall back to
# command line options
if args.config:
config = config_file_parser.get_configuration(args.config)
access_key_id = config['access-key-id']
secret_access_key = config['secret-a... | [
"def",
"main",
"(",
")",
":",
"# Read configuration from the config file if present, else fall back to",
"# command line options",
"if",
"args",
".",
"config",
":",
"config",
"=",
"config_file_parser",
".",
"get_configuration",
"(",
"args",
".",
"config",
")",
"access_key... | Main function | [
"Main",
"function"
] | python | train |
gabstopper/smc-python | smc/examples/ip_lists.py | https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/examples/ip_lists.py#L42-L54 | def upload_as_zip(name, filename):
"""
Upload an IPList as a zip file. Useful when IPList is very large.
This is the default upload format for IPLists.
:param str name: name of IPList
:param str filename: name of zip file to upload, full path
:return: None
"""
location = list(IPList.obj... | [
"def",
"upload_as_zip",
"(",
"name",
",",
"filename",
")",
":",
"location",
"=",
"list",
"(",
"IPList",
".",
"objects",
".",
"filter",
"(",
"name",
")",
")",
"if",
"location",
":",
"iplist",
"=",
"location",
"[",
"0",
"]",
"return",
"iplist",
".",
"u... | Upload an IPList as a zip file. Useful when IPList is very large.
This is the default upload format for IPLists.
:param str name: name of IPList
:param str filename: name of zip file to upload, full path
:return: None | [
"Upload",
"an",
"IPList",
"as",
"a",
"zip",
"file",
".",
"Useful",
"when",
"IPList",
"is",
"very",
"large",
".",
"This",
"is",
"the",
"default",
"upload",
"format",
"for",
"IPLists",
"."
] | python | train |
thanethomson/statik | statik/utils.py | https://github.com/thanethomson/statik/blob/56b1b5a2cb05a97afa81f428bfcefc833e935b8d/statik/utils.py#L102-L124 | def deep_merge_dict(a, b):
"""Deep merges dictionary b into dictionary a."""
if not isinstance(a, dict):
raise TypeError("a must be a dict, but found %s" % a.__class__.__name__)
if not isinstance(b, dict):
raise TypeError("b must be a dict, but found %s" % b.__class__.__name__)
_a = cop... | [
"def",
"deep_merge_dict",
"(",
"a",
",",
"b",
")",
":",
"if",
"not",
"isinstance",
"(",
"a",
",",
"dict",
")",
":",
"raise",
"TypeError",
"(",
"\"a must be a dict, but found %s\"",
"%",
"a",
".",
"__class__",
".",
"__name__",
")",
"if",
"not",
"isinstance"... | Deep merges dictionary b into dictionary a. | [
"Deep",
"merges",
"dictionary",
"b",
"into",
"dictionary",
"a",
"."
] | python | train |
lpantano/seqcluster | seqcluster/libs/thinkbayes.py | https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/libs/thinkbayes.py#L1530-L1535 | def EvalBinomialPmf(k, n, p):
"""Evaluates the binomial pmf.
Returns the probabily of k successes in n trials with probability p.
"""
return scipy.stats.binom.pmf(k, n, p) | [
"def",
"EvalBinomialPmf",
"(",
"k",
",",
"n",
",",
"p",
")",
":",
"return",
"scipy",
".",
"stats",
".",
"binom",
".",
"pmf",
"(",
"k",
",",
"n",
",",
"p",
")"
] | Evaluates the binomial pmf.
Returns the probabily of k successes in n trials with probability p. | [
"Evaluates",
"the",
"binomial",
"pmf",
"."
] | python | train |
rajeevs1992/pyhealthvault | src/healthvaultlib/objects/vocabularykey.py | https://github.com/rajeevs1992/pyhealthvault/blob/2b6fa7c1687300bcc2e501368883fbb13dc80495/src/healthvaultlib/objects/vocabularykey.py#L34-L67 | def write_xml(self):
'''
Writes a VocabularyKey Xml as per Healthvault schema.
:returns: lxml.etree.Element representing a single VocabularyKey
'''
key = None
if self. language is not None:
lang = {}
lang['{http://www.w3.org/XML/1998/names... | [
"def",
"write_xml",
"(",
"self",
")",
":",
"key",
"=",
"None",
"if",
"self",
".",
"language",
"is",
"not",
"None",
":",
"lang",
"=",
"{",
"}",
"lang",
"[",
"'{http://www.w3.org/XML/1998/namespace}lang'",
"]",
"=",
"self",
".",
"language",
"key",
"=",
"et... | Writes a VocabularyKey Xml as per Healthvault schema.
:returns: lxml.etree.Element representing a single VocabularyKey | [
"Writes",
"a",
"VocabularyKey",
"Xml",
"as",
"per",
"Healthvault",
"schema",
"."
] | python | train |
brocade/pynos | pynos/versions/ver_6/ver_6_0_1/yang/brocade_system_monitor.py | https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_6/ver_6_0_1/yang/brocade_system_monitor.py#L155-L166 | def system_monitor_cid_card_threshold_down_threshold(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
system_monitor = ET.SubElement(config, "system-monitor", xmlns="urn:brocade.com:mgmt:brocade-system-monitor")
cid_card = ET.SubElement(system_monitor, "c... | [
"def",
"system_monitor_cid_card_threshold_down_threshold",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"system_monitor",
"=",
"ET",
".",
"SubElement",
"(",
"config",
",",
"\"system-monitor\"",
",",... | Auto Generated Code | [
"Auto",
"Generated",
"Code"
] | python | train |
cloudera/cm_api | python/src/cm_api/endpoints/services.py | https://github.com/cloudera/cm_api/blob/5d2512375bd94684b4da36df9e0d9177865ffcbb/python/src/cm_api/endpoints/services.py#L1190-L1204 | def failover_hdfs(self, active_name, standby_name, force=False):
"""
Initiate a failover of an HDFS NameNode HA pair.
This will make the given stand-by NameNode active, and vice-versa.
@param active_name: name of currently active NameNode.
@param standby_name: name of NameNode currently in stand-b... | [
"def",
"failover_hdfs",
"(",
"self",
",",
"active_name",
",",
"standby_name",
",",
"force",
"=",
"False",
")",
":",
"params",
"=",
"{",
"\"force\"",
":",
"\"true\"",
"and",
"force",
"or",
"\"false\"",
"}",
"args",
"=",
"{",
"ApiList",
".",
"LIST_KEY",
":... | Initiate a failover of an HDFS NameNode HA pair.
This will make the given stand-by NameNode active, and vice-versa.
@param active_name: name of currently active NameNode.
@param standby_name: name of NameNode currently in stand-by.
@param force: whether to force failover.
@return: Reference to the... | [
"Initiate",
"a",
"failover",
"of",
"an",
"HDFS",
"NameNode",
"HA",
"pair",
"."
] | python | train |
raamana/mrivis | mrivis/workflow.py | https://github.com/raamana/mrivis/blob/199ad096b8a1d825f69109e7218a81b2f1cec756/mrivis/workflow.py#L699-L711 | def check_images(img_spec1, img_spec2, bkground_thresh=0.05):
"""Reads the two images and assers identical shape."""
img1 = read_image(img_spec1, bkground_thresh)
img2 = read_image(img_spec2, bkground_thresh)
if img1.shape != img2.shape:
raise ValueError('size mismatch! First image: {} Second ... | [
"def",
"check_images",
"(",
"img_spec1",
",",
"img_spec2",
",",
"bkground_thresh",
"=",
"0.05",
")",
":",
"img1",
"=",
"read_image",
"(",
"img_spec1",
",",
"bkground_thresh",
")",
"img2",
"=",
"read_image",
"(",
"img_spec2",
",",
"bkground_thresh",
")",
"if",
... | Reads the two images and assers identical shape. | [
"Reads",
"the",
"two",
"images",
"and",
"assers",
"identical",
"shape",
"."
] | python | train |
mikedh/trimesh | trimesh/exchange/load.py | https://github.com/mikedh/trimesh/blob/25e059bf6d4caa74f62ffd58ce4f61a90ee4e518/trimesh/exchange/load.py#L331-L361 | def load_remote(url, **kwargs):
"""
Load a mesh at a remote URL into a local trimesh object.
This must be called explicitly rather than automatically
from trimesh.load to ensure users don't accidentally make
network requests.
Parameters
------------
url : string
URL containing me... | [
"def",
"load_remote",
"(",
"url",
",",
"*",
"*",
"kwargs",
")",
":",
"# import here to keep requirement soft",
"import",
"requests",
"# download the mesh",
"response",
"=",
"requests",
".",
"get",
"(",
"url",
")",
"# wrap as file object",
"file_obj",
"=",
"util",
... | Load a mesh at a remote URL into a local trimesh object.
This must be called explicitly rather than automatically
from trimesh.load to ensure users don't accidentally make
network requests.
Parameters
------------
url : string
URL containing mesh file
**kwargs : passed to `load` | [
"Load",
"a",
"mesh",
"at",
"a",
"remote",
"URL",
"into",
"a",
"local",
"trimesh",
"object",
"."
] | python | train |
ggaughan/pipe2py | pipe2py/modules/pipetruncate.py | https://github.com/ggaughan/pipe2py/blob/4767d6d1fd354d2a35e6528594b8deb8a033eed4/pipe2py/modules/pipetruncate.py#L20-L49 | def asyncPipeUniq(context=None, _INPUT=None, conf=None, **kwargs):
"""An operator that asynchronously returns a specified number of items from
the top of a feed. Not loopable.
Parameters
----------
context : pipe2py.Context object
_INPUT : twisted Deferred iterable of items
conf : {
... | [
"def",
"asyncPipeUniq",
"(",
"context",
"=",
"None",
",",
"_INPUT",
"=",
"None",
",",
"conf",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"_input",
"=",
"yield",
"_INPUT",
"asyncFuncs",
"=",
"yield",
"asyncGetSplits",
"(",
"None",
",",
"conf",
",",... | An operator that asynchronously returns a specified number of items from
the top of a feed. Not loopable.
Parameters
----------
context : pipe2py.Context object
_INPUT : twisted Deferred iterable of items
conf : {
'start': {'type': 'number', value': <starting location>}
'count':... | [
"An",
"operator",
"that",
"asynchronously",
"returns",
"a",
"specified",
"number",
"of",
"items",
"from",
"the",
"top",
"of",
"a",
"feed",
".",
"Not",
"loopable",
"."
] | python | train |
ihmeuw/vivarium | src/vivarium/interface/interactive.py | https://github.com/ihmeuw/vivarium/blob/c5f5d50f775c8bf337d3aae1ff7c57c025a8e258/src/vivarium/interface/interactive.py#L113-L128 | def step(self, step_size: Timedelta=None):
"""Advance the simulation one step.
Parameters
----------
step_size
An optional size of step to take. Must be the same type as the
simulation clock's step size (usually a pandas.Timedelta).
"""
old_step_s... | [
"def",
"step",
"(",
"self",
",",
"step_size",
":",
"Timedelta",
"=",
"None",
")",
":",
"old_step_size",
"=",
"self",
".",
"clock",
".",
"step_size",
"if",
"step_size",
"is",
"not",
"None",
":",
"if",
"not",
"isinstance",
"(",
"step_size",
",",
"type",
... | Advance the simulation one step.
Parameters
----------
step_size
An optional size of step to take. Must be the same type as the
simulation clock's step size (usually a pandas.Timedelta). | [
"Advance",
"the",
"simulation",
"one",
"step",
"."
] | python | train |
zomux/deepy | deepy/dataset/sequence.py | https://github.com/zomux/deepy/blob/090fbad22a08a809b12951cd0d4984f5bd432698/deepy/dataset/sequence.py#L15-L24 | def _pad(self, side, length):
"""
Pad sequences to given length in the left or right side.
"""
if self._train_set:
self._train_set = pad_dataset(self._train_set, side, length)
if self._valid_set:
self._valid_set = pad_dataset(self._valid_set, side, length)... | [
"def",
"_pad",
"(",
"self",
",",
"side",
",",
"length",
")",
":",
"if",
"self",
".",
"_train_set",
":",
"self",
".",
"_train_set",
"=",
"pad_dataset",
"(",
"self",
".",
"_train_set",
",",
"side",
",",
"length",
")",
"if",
"self",
".",
"_valid_set",
"... | Pad sequences to given length in the left or right side. | [
"Pad",
"sequences",
"to",
"given",
"length",
"in",
"the",
"left",
"or",
"right",
"side",
"."
] | python | test |
trailofbits/manticore | manticore/native/manticore.py | https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/manticore.py#L121-L136 | def add_hook(self, pc, callback):
"""
Add a callback to be invoked on executing a program counter. Pass `None`
for pc to invoke callback on every instruction. `callback` should be a callable
that takes one :class:`~manticore.core.state.State` argument.
:param pc: Address of inst... | [
"def",
"add_hook",
"(",
"self",
",",
"pc",
",",
"callback",
")",
":",
"if",
"not",
"(",
"isinstance",
"(",
"pc",
",",
"int",
")",
"or",
"pc",
"is",
"None",
")",
":",
"raise",
"TypeError",
"(",
"f\"pc must be either an int or None, not {pc.__class__.__name__}\"... | Add a callback to be invoked on executing a program counter. Pass `None`
for pc to invoke callback on every instruction. `callback` should be a callable
that takes one :class:`~manticore.core.state.State` argument.
:param pc: Address of instruction to hook
:type pc: int or None
... | [
"Add",
"a",
"callback",
"to",
"be",
"invoked",
"on",
"executing",
"a",
"program",
"counter",
".",
"Pass",
"None",
"for",
"pc",
"to",
"invoke",
"callback",
"on",
"every",
"instruction",
".",
"callback",
"should",
"be",
"a",
"callable",
"that",
"takes",
"one... | python | valid |
hyperledger/indy-plenum | plenum/server/replica.py | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/plenum/server/replica.py#L2785-L2800 | def revert_unordered_batches(self):
"""
Revert changes to ledger (uncommitted) and state made by any requests
that have not been ordered.
"""
i = 0
for key in sorted(self.batches.keys(), reverse=True):
if compare_3PC_keys(self.last_ordered_3pc, key) > 0:
... | [
"def",
"revert_unordered_batches",
"(",
"self",
")",
":",
"i",
"=",
"0",
"for",
"key",
"in",
"sorted",
"(",
"self",
".",
"batches",
".",
"keys",
"(",
")",
",",
"reverse",
"=",
"True",
")",
":",
"if",
"compare_3PC_keys",
"(",
"self",
".",
"last_ordered_... | Revert changes to ledger (uncommitted) and state made by any requests
that have not been ordered. | [
"Revert",
"changes",
"to",
"ledger",
"(",
"uncommitted",
")",
"and",
"state",
"made",
"by",
"any",
"requests",
"that",
"have",
"not",
"been",
"ordered",
"."
] | python | train |
PonteIneptique/collatinus-python | pycollatinus/lemmatiseur.py | https://github.com/PonteIneptique/collatinus-python/blob/fca37b0b77bc60f47d3c24ab42f6d0bdca6ba0f5/pycollatinus/lemmatiseur.py#L176-L187 | def _lemmatise_assims(self, f, *args, **kwargs):
""" Lemmatise un mot f avec son assimilation
:param f: Mot à lemmatiser
:param pos: Récupère la POS
:param get_lemma_object: Retrieve Lemma object instead of string representation of lemma
:param results: Current results
"... | [
"def",
"_lemmatise_assims",
"(",
"self",
",",
"f",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"forme_assimilee",
"=",
"self",
".",
"assims",
"(",
"f",
")",
"if",
"forme_assimilee",
"!=",
"f",
":",
"for",
"proposal",
"in",
"self",
".",
"_lem... | Lemmatise un mot f avec son assimilation
:param f: Mot à lemmatiser
:param pos: Récupère la POS
:param get_lemma_object: Retrieve Lemma object instead of string representation of lemma
:param results: Current results | [
"Lemmatise",
"un",
"mot",
"f",
"avec",
"son",
"assimilation"
] | python | train |
pantsbuild/pex | pex/vendor/_vendored/wheel/wheel/tool/__init__.py | https://github.com/pantsbuild/pex/blob/87b2129d860250d3b9edce75b9cb62f9789ee521/pex/vendor/_vendored/wheel/wheel/tool/__init__.py#L53-L77 | def keygen(get_keyring=get_keyring):
"""Generate a public/private key pair."""
warn_signatures()
WheelKeys, keyring = get_keyring()
ed25519ll = signatures.get_ed25519ll()
wk = WheelKeys().load()
keypair = ed25519ll.crypto_sign_keypair()
vk = native(urlsafe_b64encode(keypair.vk))
sk = ... | [
"def",
"keygen",
"(",
"get_keyring",
"=",
"get_keyring",
")",
":",
"warn_signatures",
"(",
")",
"WheelKeys",
",",
"keyring",
"=",
"get_keyring",
"(",
")",
"ed25519ll",
"=",
"signatures",
".",
"get_ed25519ll",
"(",
")",
"wk",
"=",
"WheelKeys",
"(",
")",
"."... | Generate a public/private key pair. | [
"Generate",
"a",
"public",
"/",
"private",
"key",
"pair",
"."
] | python | train |
blockstack/pybitcoin | pybitcoin/wallet.py | https://github.com/blockstack/pybitcoin/blob/92c8da63c40f7418594b1ce395990c3f5a4787cc/pybitcoin/wallet.py#L45-L59 | def keypair(self, i, keypair_class):
""" Return the keypair that corresponds to the provided sequence number
and keypair class (BitcoinKeypair, etc.).
"""
# Make sure keypair_class is a valid cryptocurrency keypair
if not is_cryptocurrency_keypair_class(keypair_class):
... | [
"def",
"keypair",
"(",
"self",
",",
"i",
",",
"keypair_class",
")",
":",
"# Make sure keypair_class is a valid cryptocurrency keypair",
"if",
"not",
"is_cryptocurrency_keypair_class",
"(",
"keypair_class",
")",
":",
"raise",
"Exception",
"(",
"_messages",
"[",
"\"INVALI... | Return the keypair that corresponds to the provided sequence number
and keypair class (BitcoinKeypair, etc.). | [
"Return",
"the",
"keypair",
"that",
"corresponds",
"to",
"the",
"provided",
"sequence",
"number",
"and",
"keypair",
"class",
"(",
"BitcoinKeypair",
"etc",
".",
")",
"."
] | python | train |
tcalmant/ipopo | pelix/internals/registry.py | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/internals/registry.py#L785-L801 | def remove_service_listener(self, listener):
"""
Unregisters a service listener
:param listener: The service listener
:return: True if the listener has been unregistered
"""
with self.__svc_lock:
try:
data = self.__listeners_data.pop(listener)... | [
"def",
"remove_service_listener",
"(",
"self",
",",
"listener",
")",
":",
"with",
"self",
".",
"__svc_lock",
":",
"try",
":",
"data",
"=",
"self",
".",
"__listeners_data",
".",
"pop",
"(",
"listener",
")",
"spec_listeners",
"=",
"self",
".",
"__svc_listeners... | Unregisters a service listener
:param listener: The service listener
:return: True if the listener has been unregistered | [
"Unregisters",
"a",
"service",
"listener"
] | python | train |
inspirehep/inspire-dojson | inspire_dojson/utils/geo.py | https://github.com/inspirehep/inspire-dojson/blob/17f3789cd3d5ae58efa1190dc0eea9efb9c8ca59/inspire_dojson/utils/geo.py#L545-L573 | def parse_institution_address(address, city, state_province,
country, postal_code, country_code):
"""Parse an institution address."""
address_list = force_list(address)
state_province = match_us_state(state_province) or state_province
postal_code = force_list(postal_code)
... | [
"def",
"parse_institution_address",
"(",
"address",
",",
"city",
",",
"state_province",
",",
"country",
",",
"postal_code",
",",
"country_code",
")",
":",
"address_list",
"=",
"force_list",
"(",
"address",
")",
"state_province",
"=",
"match_us_state",
"(",
"state_... | Parse an institution address. | [
"Parse",
"an",
"institution",
"address",
"."
] | python | train |
bitesofcode/projexui | projexui/windows/xdkwindow/xdkitem.py | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/windows/xdkwindow/xdkitem.py#L204-L230 | def titleForFilepath( url ):
"""
Returns a gui title for this url.
:return <str>
"""
url = nativestring(url)
if url in XdkEntryItem.TITLE_MAP:
return XdkEntryItem.TITLE_MAP.get(url)
url = nativestring(url).replace('... | [
"def",
"titleForFilepath",
"(",
"url",
")",
":",
"url",
"=",
"nativestring",
"(",
"url",
")",
"if",
"url",
"in",
"XdkEntryItem",
".",
"TITLE_MAP",
":",
"return",
"XdkEntryItem",
".",
"TITLE_MAP",
".",
"get",
"(",
"url",
")",
"url",
"=",
"nativestring",
"... | Returns a gui title for this url.
:return <str> | [
"Returns",
"a",
"gui",
"title",
"for",
"this",
"url",
".",
":",
"return",
"<str",
">"
] | python | train |
brocade/pynos | pynos/versions/ver_6/ver_6_0_1/yang/brocade_rmon.py | https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_6/ver_6_0_1/yang/brocade_rmon.py#L38-L49 | def rmon_event_entry_log(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
rmon = ET.SubElement(config, "rmon", xmlns="urn:brocade.com:mgmt:brocade-rmon")
event_entry = ET.SubElement(rmon, "event-entry")
event_index_key = ET.SubElement(event_entry,... | [
"def",
"rmon_event_entry_log",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"rmon",
"=",
"ET",
".",
"SubElement",
"(",
"config",
",",
"\"rmon\"",
",",
"xmlns",
"=",
"\"urn:brocade.com:mgmt:bro... | Auto Generated Code | [
"Auto",
"Generated",
"Code"
] | python | train |
wummel/linkchecker | third_party/miniboa-r42/miniboa/telnet.py | https://github.com/wummel/linkchecker/blob/c2ce810c3fb00b895a841a7be6b2e78c64e7b042/third_party/miniboa-r42/miniboa/telnet.py#L696-L700 | def _check_remote_option(self, option):
"""Test the status of remote negotiated Telnet options."""
if not self.telnet_opt_dict.has_key(option):
self.telnet_opt_dict[option] = TelnetOption()
return self.telnet_opt_dict[option].remote_option | [
"def",
"_check_remote_option",
"(",
"self",
",",
"option",
")",
":",
"if",
"not",
"self",
".",
"telnet_opt_dict",
".",
"has_key",
"(",
"option",
")",
":",
"self",
".",
"telnet_opt_dict",
"[",
"option",
"]",
"=",
"TelnetOption",
"(",
")",
"return",
"self",
... | Test the status of remote negotiated Telnet options. | [
"Test",
"the",
"status",
"of",
"remote",
"negotiated",
"Telnet",
"options",
"."
] | python | train |
aychedee/unchained | unchained/fields.py | https://github.com/aychedee/unchained/blob/11d03451ee5247e66b3d6a454e1bde71f81ae357/unchained/fields.py#L152-L162 | def get_prep_value(self, value):
'''The psycopg adaptor returns Python objects,
but we also have to handle conversion ourselves
'''
if isinstance(value, JSON.JsonDict):
return json.dumps(value, cls=JSON.Encoder)
if isinstance(value, JSON.JsonList):
ret... | [
"def",
"get_prep_value",
"(",
"self",
",",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"JSON",
".",
"JsonDict",
")",
":",
"return",
"json",
".",
"dumps",
"(",
"value",
",",
"cls",
"=",
"JSON",
".",
"Encoder",
")",
"if",
"isinstance",
"(... | The psycopg adaptor returns Python objects,
but we also have to handle conversion ourselves | [
"The",
"psycopg",
"adaptor",
"returns",
"Python",
"objects",
"but",
"we",
"also",
"have",
"to",
"handle",
"conversion",
"ourselves"
] | python | train |
saltstack/salt | salt/cloud/clouds/xen.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/xen.py#L217-L260 | def get_vm_ip(name=None, session=None, call=None):
'''
Get the IP address of the VM
.. code-block:: bash
salt-cloud -a get_vm_ip xenvm01
.. note:: Requires xen guest tools to be installed in VM
'''
if call == 'function':
raise SaltCloudException(
'This function mu... | [
"def",
"get_vm_ip",
"(",
"name",
"=",
"None",
",",
"session",
"=",
"None",
",",
"call",
"=",
"None",
")",
":",
"if",
"call",
"==",
"'function'",
":",
"raise",
"SaltCloudException",
"(",
"'This function must be called with -a or --action.'",
")",
"if",
"session",... | Get the IP address of the VM
.. code-block:: bash
salt-cloud -a get_vm_ip xenvm01
.. note:: Requires xen guest tools to be installed in VM | [
"Get",
"the",
"IP",
"address",
"of",
"the",
"VM"
] | python | train |
ecederstrand/exchangelib | exchangelib/services.py | https://github.com/ecederstrand/exchangelib/blob/736347b337c239fcd6d592db5b29e819f753c1ba/exchangelib/services.py#L1478-L1510 | def call(self, folder, additional_fields, restriction, order_fields, shape, query_string, depth, max_items, offset):
"""
Find items in an account.
:param folder: the Folder object to query
:param additional_fields: the extra fields that should be returned with the item, as FieldPath obj... | [
"def",
"call",
"(",
"self",
",",
"folder",
",",
"additional_fields",
",",
"restriction",
",",
"order_fields",
",",
"shape",
",",
"query_string",
",",
"depth",
",",
"max_items",
",",
"offset",
")",
":",
"from",
".",
"items",
"import",
"Persona",
",",
"ID_ON... | Find items in an account.
:param folder: the Folder object to query
:param additional_fields: the extra fields that should be returned with the item, as FieldPath objects
:param restriction: a Restriction object for
:param order_fields: the fields to sort the results by
:param s... | [
"Find",
"items",
"in",
"an",
"account",
"."
] | python | train |
mbj4668/pyang | pyang/statements.py | https://github.com/mbj4668/pyang/blob/f2a5cc3142162e5b9ee4e18d154568d939ff63dd/pyang/statements.py#L1852-L1862 | def v_unique_name_leaf_list(ctx, stmt):
"""Make sure config true leaf-lists do nothave duplicate defaults"""
if not stmt.i_config:
return
seen = []
for defval in stmt.i_default:
if defval in seen:
err_add(ctx.errors, stmt.pos, 'DUPLICATE_DEFAULT', (defval))
else:
... | [
"def",
"v_unique_name_leaf_list",
"(",
"ctx",
",",
"stmt",
")",
":",
"if",
"not",
"stmt",
".",
"i_config",
":",
"return",
"seen",
"=",
"[",
"]",
"for",
"defval",
"in",
"stmt",
".",
"i_default",
":",
"if",
"defval",
"in",
"seen",
":",
"err_add",
"(",
... | Make sure config true leaf-lists do nothave duplicate defaults | [
"Make",
"sure",
"config",
"true",
"leaf",
"-",
"lists",
"do",
"nothave",
"duplicate",
"defaults"
] | python | train |
O365/python-o365 | O365/connection.py | https://github.com/O365/python-o365/blob/02a71cf3775cc6a3c042e003365d6a07c8c75a73/O365/connection.py#L380-L426 | def get_authorization_url(self, requested_scopes=None,
redirect_uri=OAUTH_REDIRECT_URL, **kwargs):
""" Initializes the oauth authorization flow, getting the
authorization url that the user must approve.
:param list[str] requested_scopes: list of scopes to request a... | [
"def",
"get_authorization_url",
"(",
"self",
",",
"requested_scopes",
"=",
"None",
",",
"redirect_uri",
"=",
"OAUTH_REDIRECT_URL",
",",
"*",
"*",
"kwargs",
")",
":",
"# TODO: remove this warning in future releases",
"if",
"redirect_uri",
"==",
"OAUTH_REDIRECT_URL",
":",... | Initializes the oauth authorization flow, getting the
authorization url that the user must approve.
:param list[str] requested_scopes: list of scopes to request access for
:param str redirect_uri: redirect url configured in registered app
:param kwargs: allow to pass unused params in co... | [
"Initializes",
"the",
"oauth",
"authorization",
"flow",
"getting",
"the",
"authorization",
"url",
"that",
"the",
"user",
"must",
"approve",
"."
] | python | train |
yjzhang/uncurl_python | uncurl/state_estimation.py | https://github.com/yjzhang/uncurl_python/blob/55c58ca5670f87699d3bd5752fdfa4baa07724dd/uncurl/state_estimation.py#L353-L420 | def update_m(data, old_M, old_W, selected_genes, disp=False, inner_max_iters=100, parallel=True, threads=4, write_progress_file=None, tol=0.0, regularization=0.0, **kwargs):
"""
This returns a new M matrix that contains all genes, given an M that was
created from running state estimation with a subset of ge... | [
"def",
"update_m",
"(",
"data",
",",
"old_M",
",",
"old_W",
",",
"selected_genes",
",",
"disp",
"=",
"False",
",",
"inner_max_iters",
"=",
"100",
",",
"parallel",
"=",
"True",
",",
"threads",
"=",
"4",
",",
"write_progress_file",
"=",
"None",
",",
"tol",... | This returns a new M matrix that contains all genes, given an M that was
created from running state estimation with a subset of genes.
Args:
data (sparse matrix or dense array): data matrix of shape (genes, cells), containing all genes
old_M (array): shape is (selected_genes, k)
old_W (... | [
"This",
"returns",
"a",
"new",
"M",
"matrix",
"that",
"contains",
"all",
"genes",
"given",
"an",
"M",
"that",
"was",
"created",
"from",
"running",
"state",
"estimation",
"with",
"a",
"subset",
"of",
"genes",
"."
] | python | train |
ulule/django-linguist | linguist/utils.py | https://github.com/ulule/django-linguist/blob/d2b95a6ab921039d56d5eeb352badfe5be9e8f77/linguist/utils.py#L85-L93 | def activate_language(instances, language):
"""
Activates the given language for the given instances.
"""
language = (
language if language in get_supported_languages() else get_fallback_language()
)
for instance in instances:
instance.activate_language(language) | [
"def",
"activate_language",
"(",
"instances",
",",
"language",
")",
":",
"language",
"=",
"(",
"language",
"if",
"language",
"in",
"get_supported_languages",
"(",
")",
"else",
"get_fallback_language",
"(",
")",
")",
"for",
"instance",
"in",
"instances",
":",
"... | Activates the given language for the given instances. | [
"Activates",
"the",
"given",
"language",
"for",
"the",
"given",
"instances",
"."
] | python | train |
alexa/alexa-skills-kit-sdk-for-python | ask-sdk/ask_sdk/standard.py | https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/097b6406aa12d5ca0b825b00c936861b530cbf39/ask-sdk/ask_sdk/standard.py#L82-L102 | def skill_configuration(self):
# type: () -> SkillConfiguration
"""Create the skill configuration object using the registered
components.
"""
skill_config = super(StandardSkillBuilder, self).skill_configuration
skill_config.api_client = DefaultApiClient()
if self... | [
"def",
"skill_configuration",
"(",
"self",
")",
":",
"# type: () -> SkillConfiguration",
"skill_config",
"=",
"super",
"(",
"StandardSkillBuilder",
",",
"self",
")",
".",
"skill_configuration",
"skill_config",
".",
"api_client",
"=",
"DefaultApiClient",
"(",
")",
"if"... | Create the skill configuration object using the registered
components. | [
"Create",
"the",
"skill",
"configuration",
"object",
"using",
"the",
"registered",
"components",
"."
] | python | train |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_text.py | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_text.py#L515-L525 | def dictlist_convert_to_datetime(dict_list: Iterable[Dict],
key: str,
datetime_format_string: str) -> None:
"""
Process an iterable of dictionaries. For each dictionary ``d``, convert
(in place) ``d[key]`` to a ``datetime.datetime`` form, usi... | [
"def",
"dictlist_convert_to_datetime",
"(",
"dict_list",
":",
"Iterable",
"[",
"Dict",
"]",
",",
"key",
":",
"str",
",",
"datetime_format_string",
":",
"str",
")",
"->",
"None",
":",
"for",
"d",
"in",
"dict_list",
":",
"d",
"[",
"key",
"]",
"=",
"datetim... | Process an iterable of dictionaries. For each dictionary ``d``, convert
(in place) ``d[key]`` to a ``datetime.datetime`` form, using
``datetime_format_string`` as the format parameter to
:func:`datetime.datetime.strptime`. | [
"Process",
"an",
"iterable",
"of",
"dictionaries",
".",
"For",
"each",
"dictionary",
"d",
"convert",
"(",
"in",
"place",
")",
"d",
"[",
"key",
"]",
"to",
"a",
"datetime",
".",
"datetime",
"form",
"using",
"datetime_format_string",
"as",
"the",
"format",
"p... | python | train |
sernst/cauldron | cauldron/invoke/parser.py | https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/invoke/parser.py#L11-L42 | def add_shell_action(sub_parser: ArgumentParser) -> ArgumentParser:
"""Populates the sub parser with the shell arguments"""
sub_parser.add_argument(
'-p', '--project',
dest='project_directory',
type=str,
default=None
)
sub_parser.add_argument(
'-l', '--log',
... | [
"def",
"add_shell_action",
"(",
"sub_parser",
":",
"ArgumentParser",
")",
"->",
"ArgumentParser",
":",
"sub_parser",
".",
"add_argument",
"(",
"'-p'",
",",
"'--project'",
",",
"dest",
"=",
"'project_directory'",
",",
"type",
"=",
"str",
",",
"default",
"=",
"N... | Populates the sub parser with the shell arguments | [
"Populates",
"the",
"sub",
"parser",
"with",
"the",
"shell",
"arguments"
] | python | train |
tanghaibao/jcvi | jcvi/utils/progressbar.py | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/utils/progressbar.py#L293-L306 | def update(self, pbar, width):
'Updates the progress bar and its subcomponents'
left, marker, right = (format_updatable(i, pbar) for i in
(self.left, self.marker, self.right))
width -= len(left) + len(right)
# Marker must *always* have length of 1
... | [
"def",
"update",
"(",
"self",
",",
"pbar",
",",
"width",
")",
":",
"left",
",",
"marker",
",",
"right",
"=",
"(",
"format_updatable",
"(",
"i",
",",
"pbar",
")",
"for",
"i",
"in",
"(",
"self",
".",
"left",
",",
"self",
".",
"marker",
",",
"self",... | Updates the progress bar and its subcomponents | [
"Updates",
"the",
"progress",
"bar",
"and",
"its",
"subcomponents"
] | python | train |
pymc-devs/pymc | pymc/Model.py | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/Model.py#L114-L125 | def seed(self):
"""
Seed new initial values for the stochastics.
"""
for generation in self.generations:
for s in generation:
try:
if s.rseed is not None:
value = s.random(**s.parents.value)
except:
... | [
"def",
"seed",
"(",
"self",
")",
":",
"for",
"generation",
"in",
"self",
".",
"generations",
":",
"for",
"s",
"in",
"generation",
":",
"try",
":",
"if",
"s",
".",
"rseed",
"is",
"not",
"None",
":",
"value",
"=",
"s",
".",
"random",
"(",
"*",
"*",... | Seed new initial values for the stochastics. | [
"Seed",
"new",
"initial",
"values",
"for",
"the",
"stochastics",
"."
] | python | train |
saimn/sigal | sigal/plugins/nomedia.py | https://github.com/saimn/sigal/blob/912ca39991355d358dc85fd55c7aeabdd7acc386/sigal/plugins/nomedia.py#L82-L120 | def filter_nomedia(album, settings=None):
"""Removes all filtered Media and subdirs from an Album"""
nomediapath = os.path.join(album.src_path, ".nomedia")
if os.path.isfile(nomediapath):
if os.path.getsize(nomediapath) == 0:
logger.info("Ignoring album '%s' because of present 0-byte "
... | [
"def",
"filter_nomedia",
"(",
"album",
",",
"settings",
"=",
"None",
")",
":",
"nomediapath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"album",
".",
"src_path",
",",
"\".nomedia\"",
")",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"nomediapath",
")",... | Removes all filtered Media and subdirs from an Album | [
"Removes",
"all",
"filtered",
"Media",
"and",
"subdirs",
"from",
"an",
"Album"
] | python | valid |
Karaage-Cluster/python-tldap | tldap/modlist.py | https://github.com/Karaage-Cluster/python-tldap/blob/61f1af74a3648cb6491e7eeb1ee2eb395d67bf59/tldap/modlist.py#L52-L64 | def addModlist(entry: dict, ignore_attr_types: Optional[List[str]] = None) -> Dict[str, List[bytes]]:
"""Build modify list for call of method LDAPObject.add()"""
ignore_attr_types = _list_dict(map(str.lower, (ignore_attr_types or [])))
modlist: Dict[str, List[bytes]] = {}
for attrtype in entry.keys():
... | [
"def",
"addModlist",
"(",
"entry",
":",
"dict",
",",
"ignore_attr_types",
":",
"Optional",
"[",
"List",
"[",
"str",
"]",
"]",
"=",
"None",
")",
"->",
"Dict",
"[",
"str",
",",
"List",
"[",
"bytes",
"]",
"]",
":",
"ignore_attr_types",
"=",
"_list_dict",
... | Build modify list for call of method LDAPObject.add() | [
"Build",
"modify",
"list",
"for",
"call",
"of",
"method",
"LDAPObject",
".",
"add",
"()"
] | python | train |
eddieantonio/perfection | perfection/getty.py | https://github.com/eddieantonio/perfection/blob/69b7a06b31a15bd9534c69d4bdcc2e48e8ddfc43/perfection/getty.py#L220-L244 | def check_columns_fit(unoccupied_columns, row, offset, row_length):
"""
Checks if all the occupied columns in the row fit in the indices
given by free columns.
>>> check_columns_fit({0,1,2,3}, [(0, True), (2, True)], 0, 4)
True
>>> check_columns_fit({0,2,3}, [(2, True), (3, True)], 0, 4)
Tr... | [
"def",
"check_columns_fit",
"(",
"unoccupied_columns",
",",
"row",
",",
"offset",
",",
"row_length",
")",
":",
"for",
"index",
",",
"item",
"in",
"row",
":",
"adjusted_index",
"=",
"(",
"index",
"+",
"offset",
")",
"%",
"row_length",
"# Check if the index is i... | Checks if all the occupied columns in the row fit in the indices
given by free columns.
>>> check_columns_fit({0,1,2,3}, [(0, True), (2, True)], 0, 4)
True
>>> check_columns_fit({0,2,3}, [(2, True), (3, True)], 0, 4)
True
>>> check_columns_fit({}, [(2, True), (3, True)], 0, 4)
False
>>>... | [
"Checks",
"if",
"all",
"the",
"occupied",
"columns",
"in",
"the",
"row",
"fit",
"in",
"the",
"indices",
"given",
"by",
"free",
"columns",
"."
] | python | train |
aio-libs/aioredis | aioredis/pool.py | https://github.com/aio-libs/aioredis/blob/e8c33e39558d4cc91cf70dde490d8b330c97dc2e/aioredis/pool.py#L184-L199 | def execute(self, command, *args, **kw):
"""Executes redis command in a free connection and returns
future waiting for result.
Picks connection from free pool and send command through
that connection.
If no connection is found, returns coroutine waiting for
free connecti... | [
"def",
"execute",
"(",
"self",
",",
"command",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"conn",
",",
"address",
"=",
"self",
".",
"get_connection",
"(",
"command",
",",
"args",
")",
"if",
"conn",
"is",
"not",
"None",
":",
"fut",
"=",
"con... | Executes redis command in a free connection and returns
future waiting for result.
Picks connection from free pool and send command through
that connection.
If no connection is found, returns coroutine waiting for
free connection to execute command. | [
"Executes",
"redis",
"command",
"in",
"a",
"free",
"connection",
"and",
"returns",
"future",
"waiting",
"for",
"result",
"."
] | python | train |
MuhammedHasan/sklearn_utils | sklearn_utils/preprocessing/dict_input.py | https://github.com/MuhammedHasan/sklearn_utils/blob/337c3b7a27f4921d12da496f66a2b83ef582b413/sklearn_utils/preprocessing/dict_input.py#L29-L39 | def transform(self, X):
'''
:param X: features.
'''
inverser_tranformer = self.dict_vectorizer_
if self.feature_selection:
inverser_tranformer = self.clone_dict_vectorizer_
return inverser_tranformer.inverse_transform(
self.transformer.transform(
... | [
"def",
"transform",
"(",
"self",
",",
"X",
")",
":",
"inverser_tranformer",
"=",
"self",
".",
"dict_vectorizer_",
"if",
"self",
".",
"feature_selection",
":",
"inverser_tranformer",
"=",
"self",
".",
"clone_dict_vectorizer_",
"return",
"inverser_tranformer",
".",
... | :param X: features. | [
":",
"param",
"X",
":",
"features",
"."
] | python | test |
pgjones/quart | quart/wrappers/response.py | https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/wrappers/response.py#L341-L360 | def set_cookie( # type: ignore
self,
key: str,
value: AnyStr='',
max_age: Optional[Union[int, timedelta]]=None,
expires: Optional[datetime]=None,
path: str='/',
domain: Optional[str]=None,
secure: bool=False,
ht... | [
"def",
"set_cookie",
"(",
"# type: ignore",
"self",
",",
"key",
":",
"str",
",",
"value",
":",
"AnyStr",
"=",
"''",
",",
"max_age",
":",
"Optional",
"[",
"Union",
"[",
"int",
",",
"timedelta",
"]",
"]",
"=",
"None",
",",
"expires",
":",
"Optional",
"... | Set a cookie in the response headers.
The arguments are the standard cookie morsels and this is a
wrapper around the stdlib SimpleCookie code. | [
"Set",
"a",
"cookie",
"in",
"the",
"response",
"headers",
"."
] | python | train |
jrief/django-websocket-redis | ws4redis/subscriber.py | https://github.com/jrief/django-websocket-redis/blob/abcddaad2f579d71dbf375e5e34bc35eef795a81/ws4redis/subscriber.py#L23-L49 | def set_pubsub_channels(self, request, channels):
"""
Initialize the channels used for publishing and subscribing messages through the message queue.
"""
facility = request.path_info.replace(settings.WEBSOCKET_URL, '', 1)
# initialize publishers
audience = {
... | [
"def",
"set_pubsub_channels",
"(",
"self",
",",
"request",
",",
"channels",
")",
":",
"facility",
"=",
"request",
".",
"path_info",
".",
"replace",
"(",
"settings",
".",
"WEBSOCKET_URL",
",",
"''",
",",
"1",
")",
"# initialize publishers",
"audience",
"=",
"... | Initialize the channels used for publishing and subscribing messages through the message queue. | [
"Initialize",
"the",
"channels",
"used",
"for",
"publishing",
"and",
"subscribing",
"messages",
"through",
"the",
"message",
"queue",
"."
] | python | train |
edx/bok-choy | bok_choy/query.py | https://github.com/edx/bok-choy/blob/cdd0d423419fc0c49d56a9226533aa1490b60afc/bok_choy/query.py#L148-L194 | def filter(self, filter_fn=None, desc=None, **kwargs):
"""
Return a copy of this query, with some values removed.
Example usages:
.. code:: python
# Returns a query that matches even numbers
q.filter(filter_fn=lambda x: x % 2)
# Returns a query tha... | [
"def",
"filter",
"(",
"self",
",",
"filter_fn",
"=",
"None",
",",
"desc",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"filter_fn",
"is",
"not",
"None",
"and",
"kwargs",
":",
"raise",
"TypeError",
"(",
"'Must supply either a filter_fn or attribute f... | Return a copy of this query, with some values removed.
Example usages:
.. code:: python
# Returns a query that matches even numbers
q.filter(filter_fn=lambda x: x % 2)
# Returns a query that matches elements with el.description == "foo"
q.filter(descri... | [
"Return",
"a",
"copy",
"of",
"this",
"query",
"with",
"some",
"values",
"removed",
"."
] | python | train |
anteater/anteater | anteater/src/project_scan.py | https://github.com/anteater/anteater/blob/a980adbed8563ef92494f565acd371e91f50f155/anteater/src/project_scan.py#L41-L89 | def prepare_project(project, project_dir, binaries, ips, urls):
"""
Generates blacklists / whitelists
"""
# Get Various Lists / Project Waivers
lists = get_lists.GetLists()
# Get file name black list and project waivers
file_audit_list, file_audit_project_list = lists.file_audit_list(proje... | [
"def",
"prepare_project",
"(",
"project",
",",
"project_dir",
",",
"binaries",
",",
"ips",
",",
"urls",
")",
":",
"# Get Various Lists / Project Waivers",
"lists",
"=",
"get_lists",
".",
"GetLists",
"(",
")",
"# Get file name black list and project waivers",
"file_audit... | Generates blacklists / whitelists | [
"Generates",
"blacklists",
"/",
"whitelists"
] | python | train |
NASA-AMMOS/AIT-Core | ait/core/bsc.py | https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/bsc.py#L712-L731 | def _route(self):
''' Handles server route instantiation. '''
self._app.route('/',
method='GET',
callback=self._get_logger_list)
self._app.route('/stats',
method='GET',
callback=self._fetch_handler_st... | [
"def",
"_route",
"(",
"self",
")",
":",
"self",
".",
"_app",
".",
"route",
"(",
"'/'",
",",
"method",
"=",
"'GET'",
",",
"callback",
"=",
"self",
".",
"_get_logger_list",
")",
"self",
".",
"_app",
".",
"route",
"(",
"'/stats'",
",",
"method",
"=",
... | Handles server route instantiation. | [
"Handles",
"server",
"route",
"instantiation",
"."
] | python | train |
intake/intake | intake/source/utils.py | https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/source/utils.py#L258-L285 | def path_to_pattern(path, metadata=None):
"""
Remove source information from path when using chaching
Returns None if path is not str
Parameters
----------
path : str
Path to data optionally containing format_strings
metadata : dict, optional
Extra arguments to the class, c... | [
"def",
"path_to_pattern",
"(",
"path",
",",
"metadata",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"path",
",",
"str",
")",
":",
"return",
"pattern",
"=",
"path",
"if",
"metadata",
":",
"cache",
"=",
"metadata",
".",
"get",
"(",
"'cache'",
... | Remove source information from path when using chaching
Returns None if path is not str
Parameters
----------
path : str
Path to data optionally containing format_strings
metadata : dict, optional
Extra arguments to the class, contains any cache information
Returns
-------... | [
"Remove",
"source",
"information",
"from",
"path",
"when",
"using",
"chaching"
] | python | train |
Kortemme-Lab/klab | klab/bio/bonsai.py | https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/bio/bonsai.py#L550-L552 | def prune_loop_for_kic(self, loops_segments, search_radius, expected_min_loop_length = None, expected_max_loop_length = None, generate_pymol_session = False):
'''A wrapper for prune_structure_according_to_loop_definitions suitable for the Rosetta kinematic closure (KIC) loop modeling method.'''
return s... | [
"def",
"prune_loop_for_kic",
"(",
"self",
",",
"loops_segments",
",",
"search_radius",
",",
"expected_min_loop_length",
"=",
"None",
",",
"expected_max_loop_length",
"=",
"None",
",",
"generate_pymol_session",
"=",
"False",
")",
":",
"return",
"self",
".",
"prune_st... | A wrapper for prune_structure_according_to_loop_definitions suitable for the Rosetta kinematic closure (KIC) loop modeling method. | [
"A",
"wrapper",
"for",
"prune_structure_according_to_loop_definitions",
"suitable",
"for",
"the",
"Rosetta",
"kinematic",
"closure",
"(",
"KIC",
")",
"loop",
"modeling",
"method",
"."
] | python | train |
ga4gh/ga4gh-server | ga4gh/server/datamodel/obo_parser.py | https://github.com/ga4gh/ga4gh-server/blob/1aa18922ef136db8604f6f098cb1732cba6f2a76/ga4gh/server/datamodel/obo_parser.py#L522-L556 | def paths_to_top(self, term):
""" Returns all possible paths to the root node
Each path includes the term given. The order of the path is
top -> bottom, i.e. it starts with the root and ends with the
given term (inclusively).
Parameters:
-----------
... | [
"def",
"paths_to_top",
"(",
"self",
",",
"term",
")",
":",
"# error handling consistent with original authors",
"if",
"term",
"not",
"in",
"self",
":",
"print",
"(",
"\"Term %s not found!\"",
"%",
"term",
",",
"file",
"=",
"sys",
".",
"stderr",
")",
"return",
... | Returns all possible paths to the root node
Each path includes the term given. The order of the path is
top -> bottom, i.e. it starts with the root and ends with the
given term (inclusively).
Parameters:
-----------
- term:
the id... | [
"Returns",
"all",
"possible",
"paths",
"to",
"the",
"root",
"node"
] | python | train |
Dallinger/Dallinger | demos/dlgr/demos/rogers/models.py | https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/demos/dlgr/demos/rogers/models.py#L127-L138 | def update(self, infos):
"""Process received infos."""
genes = [i for i in infos if isinstance(i, LearningGene)]
for gene in genes:
if (
self.network.role == "experiment"
and self.generation > 0
and random.random() < 0.10
):... | [
"def",
"update",
"(",
"self",
",",
"infos",
")",
":",
"genes",
"=",
"[",
"i",
"for",
"i",
"in",
"infos",
"if",
"isinstance",
"(",
"i",
",",
"LearningGene",
")",
"]",
"for",
"gene",
"in",
"genes",
":",
"if",
"(",
"self",
".",
"network",
".",
"role... | Process received infos. | [
"Process",
"received",
"infos",
"."
] | python | train |
zalando/patroni | patroni/ctl.py | https://github.com/zalando/patroni/blob/f6d29081c90af52064b981cdd877a07338d86038/patroni/ctl.py#L970-L985 | def temporary_file(contents, suffix='', prefix='tmp'):
"""Creates a temporary file with specified contents that persists for the context.
:param contents: binary string that will be written to the file.
:param prefix: will be prefixed to the filename.
:param suffix: will be appended to the filename.
... | [
"def",
"temporary_file",
"(",
"contents",
",",
"suffix",
"=",
"''",
",",
"prefix",
"=",
"'tmp'",
")",
":",
"tmp",
"=",
"tempfile",
".",
"NamedTemporaryFile",
"(",
"suffix",
"=",
"suffix",
",",
"prefix",
"=",
"prefix",
",",
"delete",
"=",
"False",
")",
... | Creates a temporary file with specified contents that persists for the context.
:param contents: binary string that will be written to the file.
:param prefix: will be prefixed to the filename.
:param suffix: will be appended to the filename.
:returns path of the created file. | [
"Creates",
"a",
"temporary",
"file",
"with",
"specified",
"contents",
"that",
"persists",
"for",
"the",
"context",
"."
] | python | train |
rytilahti/python-eq3bt | eq3bt/eq3btsmart.py | https://github.com/rytilahti/python-eq3bt/blob/595459d9885920cf13b7059a1edd2cf38cede1f0/eq3bt/eq3btsmart.py#L108-L113 | def parse_schedule(self, data):
"""Parses the device sent schedule."""
sched = Schedule.parse(data)
_LOGGER.debug("Got schedule data for day '%s'", sched.day)
return sched | [
"def",
"parse_schedule",
"(",
"self",
",",
"data",
")",
":",
"sched",
"=",
"Schedule",
".",
"parse",
"(",
"data",
")",
"_LOGGER",
".",
"debug",
"(",
"\"Got schedule data for day '%s'\"",
",",
"sched",
".",
"day",
")",
"return",
"sched"
] | Parses the device sent schedule. | [
"Parses",
"the",
"device",
"sent",
"schedule",
"."
] | python | train |
softlayer/softlayer-python | SoftLayer/managers/dedicated_host.py | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/dedicated_host.py#L431-L438 | def _get_item(self, package, flavor):
"""Returns the item for ordering a dedicated host."""
for item in package['items']:
if item['keyName'] == flavor:
return item
raise SoftLayer.SoftLayerError("Could not find valid item for: '%s'" % flavor) | [
"def",
"_get_item",
"(",
"self",
",",
"package",
",",
"flavor",
")",
":",
"for",
"item",
"in",
"package",
"[",
"'items'",
"]",
":",
"if",
"item",
"[",
"'keyName'",
"]",
"==",
"flavor",
":",
"return",
"item",
"raise",
"SoftLayer",
".",
"SoftLayerError",
... | Returns the item for ordering a dedicated host. | [
"Returns",
"the",
"item",
"for",
"ordering",
"a",
"dedicated",
"host",
"."
] | python | train |
LLNL/scraper | scraper/github/queryManager.py | https://github.com/LLNL/scraper/blob/881a316e4c04dfa5a9cf491b7c7f9f997a7c56ea/scraper/github/queryManager.py#L480-L504 | def fileSave(self, filePath=None, updatePath=False):
"""Write the internal JSON data dictionary to a JSON data file.
If no file path is provided, the stored data file path will be used.
Args:
filePath (Optional[str]): A relative or absolute path to a
'.json' file. D... | [
"def",
"fileSave",
"(",
"self",
",",
"filePath",
"=",
"None",
",",
"updatePath",
"=",
"False",
")",
":",
"if",
"not",
"filePath",
":",
"filePath",
"=",
"self",
".",
"filePath",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"filePath",
")",
":",... | Write the internal JSON data dictionary to a JSON data file.
If no file path is provided, the stored data file path will be used.
Args:
filePath (Optional[str]): A relative or absolute path to a
'.json' file. Defaults to None.
updatePath (Optional[bool]): Specif... | [
"Write",
"the",
"internal",
"JSON",
"data",
"dictionary",
"to",
"a",
"JSON",
"data",
"file",
"."
] | python | test |
google/grr | grr/client/grr_response_client/fleetspeak_client.py | https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/client/grr_response_client/fleetspeak_client.py#L131-L149 | def _SendMessages(self, grr_msgs, background=False):
"""Sends a block of messages through Fleetspeak."""
message_list = rdf_flows.PackedMessageList()
communicator.Communicator.EncodeMessageList(
rdf_flows.MessageList(job=grr_msgs), message_list)
fs_msg = fs_common_pb2.Message(
message_ty... | [
"def",
"_SendMessages",
"(",
"self",
",",
"grr_msgs",
",",
"background",
"=",
"False",
")",
":",
"message_list",
"=",
"rdf_flows",
".",
"PackedMessageList",
"(",
")",
"communicator",
".",
"Communicator",
".",
"EncodeMessageList",
"(",
"rdf_flows",
".",
"MessageL... | Sends a block of messages through Fleetspeak. | [
"Sends",
"a",
"block",
"of",
"messages",
"through",
"Fleetspeak",
"."
] | python | train |
DataBiosphere/toil | src/toil/serviceManager.py | https://github.com/DataBiosphere/toil/blob/a8252277ff814e7bee0971139c2344f88e44b644/src/toil/serviceManager.py#L138-L143 | def isRunning(self, serviceJobNode):
"""
Returns true if the service job has started and is active
:rtype: boolean
"""
return (not self.jobStore.fileExists(serviceJobNode.startJobStoreID)) and self.isActive(serviceJobNode) | [
"def",
"isRunning",
"(",
"self",
",",
"serviceJobNode",
")",
":",
"return",
"(",
"not",
"self",
".",
"jobStore",
".",
"fileExists",
"(",
"serviceJobNode",
".",
"startJobStoreID",
")",
")",
"and",
"self",
".",
"isActive",
"(",
"serviceJobNode",
")"
] | Returns true if the service job has started and is active
:rtype: boolean | [
"Returns",
"true",
"if",
"the",
"service",
"job",
"has",
"started",
"and",
"is",
"active",
":",
"rtype",
":",
"boolean"
] | python | train |
ARMmbed/mbed-cloud-sdk-python | src/mbed_cloud/_backends/enrollment/models/enrollment_identity.py | https://github.com/ARMmbed/mbed-cloud-sdk-python/blob/c0af86fb2cdd4dc7ed26f236139241067d293509/src/mbed_cloud/_backends/enrollment/models/enrollment_identity.py#L160-L173 | def enrolled_device_id(self, enrolled_device_id):
"""
Sets the enrolled_device_id of this EnrollmentIdentity.
The ID of the device in the Device Directory once it has been registered.
:param enrolled_device_id: The enrolled_device_id of this EnrollmentIdentity.
:type: str
... | [
"def",
"enrolled_device_id",
"(",
"self",
",",
"enrolled_device_id",
")",
":",
"if",
"enrolled_device_id",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"Invalid value for `enrolled_device_id`, must not be `None`\"",
")",
"if",
"enrolled_device_id",
"is",
"not",
"None"... | Sets the enrolled_device_id of this EnrollmentIdentity.
The ID of the device in the Device Directory once it has been registered.
:param enrolled_device_id: The enrolled_device_id of this EnrollmentIdentity.
:type: str | [
"Sets",
"the",
"enrolled_device_id",
"of",
"this",
"EnrollmentIdentity",
".",
"The",
"ID",
"of",
"the",
"device",
"in",
"the",
"Device",
"Directory",
"once",
"it",
"has",
"been",
"registered",
"."
] | python | train |
RiotGames/cloud-inquisitor | backend/cloud_inquisitor/plugins/types/issues.py | https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/backend/cloud_inquisitor/plugins/types/issues.py#L570-L589 | def update(self, data):
"""Updates the object information based on live data, if there were any changes made. Any changes will be
automatically applied to the object, but will not be automatically persisted. You must manually call
`db.session.add(instance)` on the object.
Args:
... | [
"def",
"update",
"(",
"self",
",",
"data",
")",
":",
"# If the instance was terminated, remove it",
"updated",
"=",
"self",
".",
"set_property",
"(",
"'state'",
",",
"data",
"[",
"'state'",
"]",
")",
"updated",
"|=",
"self",
".",
"set_property",
"(",
"'notes'"... | Updates the object information based on live data, if there were any changes made. Any changes will be
automatically applied to the object, but will not be automatically persisted. You must manually call
`db.session.add(instance)` on the object.
Args:
data (:obj:): AWS API Resource ... | [
"Updates",
"the",
"object",
"information",
"based",
"on",
"live",
"data",
"if",
"there",
"were",
"any",
"changes",
"made",
".",
"Any",
"changes",
"will",
"be",
"automatically",
"applied",
"to",
"the",
"object",
"but",
"will",
"not",
"be",
"automatically",
"p... | python | train |
Erotemic/utool | utool/util_iter.py | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_iter.py#L512-L549 | def random_product(items, num=None, rng=None):
"""
Yields `num` items from the cartesian product of items in a random order.
Args:
items (list of sequences): items to get caresian product of
packed in a list or tuple.
(note this deviates from api of it.product)
Example:... | [
"def",
"random_product",
"(",
"items",
",",
"num",
"=",
"None",
",",
"rng",
"=",
"None",
")",
":",
"import",
"utool",
"as",
"ut",
"rng",
"=",
"ut",
".",
"ensure_rng",
"(",
"rng",
",",
"'python'",
")",
"seen",
"=",
"set",
"(",
")",
"items",
"=",
"... | Yields `num` items from the cartesian product of items in a random order.
Args:
items (list of sequences): items to get caresian product of
packed in a list or tuple.
(note this deviates from api of it.product)
Example:
import utool as ut
items = [(1, 2, 3), (4,... | [
"Yields",
"num",
"items",
"from",
"the",
"cartesian",
"product",
"of",
"items",
"in",
"a",
"random",
"order",
"."
] | python | train |
carpedm20/ndrive | ndrive/client.py | https://github.com/carpedm20/ndrive/blob/ac58eaf8a8d46292ad752bb38047f65838b8ad2b/ndrive/client.py#L694-L725 | def getVersionList(self, full_path, startnum = 0, pagingrow = 50, dummy = 54213):
"""Get a version list of a file or dierectory.
:param full_path: The full path to get the file or directory property. Path should start with '/'
:param startnum: Start version index.
:param pagingrow: Max ... | [
"def",
"getVersionList",
"(",
"self",
",",
"full_path",
",",
"startnum",
"=",
"0",
",",
"pagingrow",
"=",
"50",
",",
"dummy",
"=",
"54213",
")",
":",
"data",
"=",
"{",
"'orgresource'",
":",
"full_path",
",",
"'startnum'",
":",
"startnum",
",",
"'pagingro... | Get a version list of a file or dierectory.
:param full_path: The full path to get the file or directory property. Path should start with '/'
:param startnum: Start version index.
:param pagingrow: Max # of version list in one page.
:returns: ``metadata`` if succcess or ``False`` (fail... | [
"Get",
"a",
"version",
"list",
"of",
"a",
"file",
"or",
"dierectory",
"."
] | python | train |
DataONEorg/d1_python | gmn/src/d1_gmn/app/did.py | https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/gmn/src/d1_gmn/app/did.py#L231-L239 | def _is_did(did):
"""Return True if ``did`` is recorded in a local context.
``did``=None is supported and returns False.
A DID can be classified with classify_identifier().
"""
return d1_gmn.app.models.IdNamespace.objects.filter(did=did).exists() | [
"def",
"_is_did",
"(",
"did",
")",
":",
"return",
"d1_gmn",
".",
"app",
".",
"models",
".",
"IdNamespace",
".",
"objects",
".",
"filter",
"(",
"did",
"=",
"did",
")",
".",
"exists",
"(",
")"
] | Return True if ``did`` is recorded in a local context.
``did``=None is supported and returns False.
A DID can be classified with classify_identifier(). | [
"Return",
"True",
"if",
"did",
"is",
"recorded",
"in",
"a",
"local",
"context",
"."
] | python | train |
saltstack/salt | salt/modules/elasticsearch.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/elasticsearch.py#L375-L405 | def document_create(index, doc_type, body=None, id=None, hosts=None, profile=None, source=None):
'''
Create a document in a specified index
index
Index name where the document should reside
doc_type
Type of the document
body
Document to store
source
URL of file s... | [
"def",
"document_create",
"(",
"index",
",",
"doc_type",
",",
"body",
"=",
"None",
",",
"id",
"=",
"None",
",",
"hosts",
"=",
"None",
",",
"profile",
"=",
"None",
",",
"source",
"=",
"None",
")",
":",
"es",
"=",
"_get_instance",
"(",
"hosts",
",",
... | Create a document in a specified index
index
Index name where the document should reside
doc_type
Type of the document
body
Document to store
source
URL of file specifying document to store. Cannot be used in combination with ``body``.
id
Optional unique docu... | [
"Create",
"a",
"document",
"in",
"a",
"specified",
"index"
] | python | train |
plivo/plivohelper-python | plivohelper.py | https://github.com/plivo/plivohelper-python/blob/a2f706d69e2138fbb973f792041341f662072d26/plivohelper.py#L258-L263 | def sound_touch(self, call_params):
"""REST Add soundtouch audio effects to a Call
"""
path = '/' + self.api_version + '/SoundTouch/'
method = 'POST'
return self.request(path, method, call_params) | [
"def",
"sound_touch",
"(",
"self",
",",
"call_params",
")",
":",
"path",
"=",
"'/'",
"+",
"self",
".",
"api_version",
"+",
"'/SoundTouch/'",
"method",
"=",
"'POST'",
"return",
"self",
".",
"request",
"(",
"path",
",",
"method",
",",
"call_params",
")"
] | REST Add soundtouch audio effects to a Call | [
"REST",
"Add",
"soundtouch",
"audio",
"effects",
"to",
"a",
"Call"
] | python | valid |
junzis/pyModeS | pyModeS/decoder/bds/bds40.py | https://github.com/junzis/pyModeS/blob/8cd5655a04b08171a9ad5f1ffd232b7e0178ea53/pyModeS/decoder/bds/bds40.py#L104-L119 | def p40baro(msg):
"""Barometric pressure setting
Args:
msg (String): 28 bytes hexadecimal message (BDS40) string
Returns:
float: pressure in millibar
"""
d = hex2bin(data(msg))
if d[26] == '0':
return None
p = bin2int(d[27:39]) * 0.1 + 800 # millibar
return... | [
"def",
"p40baro",
"(",
"msg",
")",
":",
"d",
"=",
"hex2bin",
"(",
"data",
"(",
"msg",
")",
")",
"if",
"d",
"[",
"26",
"]",
"==",
"'0'",
":",
"return",
"None",
"p",
"=",
"bin2int",
"(",
"d",
"[",
"27",
":",
"39",
"]",
")",
"*",
"0.1",
"+",
... | Barometric pressure setting
Args:
msg (String): 28 bytes hexadecimal message (BDS40) string
Returns:
float: pressure in millibar | [
"Barometric",
"pressure",
"setting"
] | python | train |
zeroSteiner/AdvancedHTTPServer | advancedhttpserver.py | https://github.com/zeroSteiner/AdvancedHTTPServer/blob/8c53cf7e1ddbf7ae9f573c82c5fe5f6992db7b5a/advancedhttpserver.py#L1206-L1217 | def cookie_get(self, name):
"""
Check for a cookie value by name.
:param str name: Name of the cookie value to retreive.
:return: Returns the cookie value if it's set or None if it's not found.
"""
if not hasattr(self, 'cookies'):
return None
if self.cookies.get(name):
return self.cookies.get(name)... | [
"def",
"cookie_get",
"(",
"self",
",",
"name",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'cookies'",
")",
":",
"return",
"None",
"if",
"self",
".",
"cookies",
".",
"get",
"(",
"name",
")",
":",
"return",
"self",
".",
"cookies",
".",
"get... | Check for a cookie value by name.
:param str name: Name of the cookie value to retreive.
:return: Returns the cookie value if it's set or None if it's not found. | [
"Check",
"for",
"a",
"cookie",
"value",
"by",
"name",
"."
] | python | train |
Erotemic/utool | utool/util_str.py | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_str.py#L2563-L2586 | def bubbletext(text, font='cybermedium'):
r"""
Uses pyfiglet to create bubble text.
Args:
font (str): default=cybermedium, other fonts include: cybersmall and
cyberlarge.
References:
http://www.figlet.org/
Example:
>>> # ENABLE_DOCTEST
>>> import utool ... | [
"def",
"bubbletext",
"(",
"text",
",",
"font",
"=",
"'cybermedium'",
")",
":",
"import",
"utool",
"as",
"ut",
"pyfiglet",
"=",
"ut",
".",
"tryimport",
"(",
"'pyfiglet'",
",",
"'git+https://github.com/pwaller/pyfiglet'",
")",
"if",
"pyfiglet",
"is",
"None",
":"... | r"""
Uses pyfiglet to create bubble text.
Args:
font (str): default=cybermedium, other fonts include: cybersmall and
cyberlarge.
References:
http://www.figlet.org/
Example:
>>> # ENABLE_DOCTEST
>>> import utool as ut
>>> bubble_text = ut.bubbletext(... | [
"r",
"Uses",
"pyfiglet",
"to",
"create",
"bubble",
"text",
"."
] | python | train |
pyca/pyopenssl | src/OpenSSL/crypto.py | https://github.com/pyca/pyopenssl/blob/1fbe064c50fd030948141d7d630673761525b0d0/src/OpenSSL/crypto.py#L1477-L1491 | def add_extensions(self, extensions):
"""
Add extensions to the certificate.
:param extensions: The extensions to add.
:type extensions: An iterable of :py:class:`X509Extension` objects.
:return: ``None``
"""
for ext in extensions:
if not isinstance(e... | [
"def",
"add_extensions",
"(",
"self",
",",
"extensions",
")",
":",
"for",
"ext",
"in",
"extensions",
":",
"if",
"not",
"isinstance",
"(",
"ext",
",",
"X509Extension",
")",
":",
"raise",
"ValueError",
"(",
"\"One of the elements is not an X509Extension\"",
")",
"... | Add extensions to the certificate.
:param extensions: The extensions to add.
:type extensions: An iterable of :py:class:`X509Extension` objects.
:return: ``None`` | [
"Add",
"extensions",
"to",
"the",
"certificate",
"."
] | python | test |
s0md3v/Photon | core/utils.py | https://github.com/s0md3v/Photon/blob/6a29f2c9782ea9b3dc090db1774a259033600e39/core/utils.py#L87-L96 | def timer(diff, processed):
"""Return the passed time."""
# Changes seconds into minutes and seconds
minutes, seconds = divmod(diff, 60)
try:
# Finds average time taken by requests
time_per_request = diff / float(len(processed))
except ZeroDivisionError:
time_per_request = 0
... | [
"def",
"timer",
"(",
"diff",
",",
"processed",
")",
":",
"# Changes seconds into minutes and seconds",
"minutes",
",",
"seconds",
"=",
"divmod",
"(",
"diff",
",",
"60",
")",
"try",
":",
"# Finds average time taken by requests",
"time_per_request",
"=",
"diff",
"/",
... | Return the passed time. | [
"Return",
"the",
"passed",
"time",
"."
] | python | train |
sdispater/eloquent | eloquent/orm/builder.py | https://github.com/sdispater/eloquent/blob/0638b688d5fd0c1a46b7471dd465eeb4c2f84666/eloquent/orm/builder.py#L758-L767 | def _call_scope(self, scope, *args, **kwargs):
"""
Call the given model scope.
:param scope: The scope to call
:type scope: str
"""
result = getattr(self._model, scope)(self, *args, **kwargs)
return result or self | [
"def",
"_call_scope",
"(",
"self",
",",
"scope",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"result",
"=",
"getattr",
"(",
"self",
".",
"_model",
",",
"scope",
")",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
... | Call the given model scope.
:param scope: The scope to call
:type scope: str | [
"Call",
"the",
"given",
"model",
"scope",
"."
] | python | train |
reorx/torext | torext/handlers/base.py | https://github.com/reorx/torext/blob/84c4300ebc7fab0dbd11cf8b020bc7d4d1570171/torext/handlers/base.py#L112-L139 | def _handle_request_exception(self, e):
"""This method handle HTTPError exceptions the same as how tornado does,
leave other exceptions to be handled by user defined handler function
maped in class attribute `EXCEPTION_HANDLERS`
Common HTTP status codes:
200 OK
3... | [
"def",
"_handle_request_exception",
"(",
"self",
",",
"e",
")",
":",
"handle_func",
"=",
"self",
".",
"_exception_default_handler",
"if",
"self",
".",
"EXCEPTION_HANDLERS",
":",
"for",
"excs",
",",
"func_name",
"in",
"self",
".",
"EXCEPTION_HANDLERS",
".",
"item... | This method handle HTTPError exceptions the same as how tornado does,
leave other exceptions to be handled by user defined handler function
maped in class attribute `EXCEPTION_HANDLERS`
Common HTTP status codes:
200 OK
301 Moved Permanently
302 Found
... | [
"This",
"method",
"handle",
"HTTPError",
"exceptions",
"the",
"same",
"as",
"how",
"tornado",
"does",
"leave",
"other",
"exceptions",
"to",
"be",
"handled",
"by",
"user",
"defined",
"handler",
"function",
"maped",
"in",
"class",
"attribute",
"EXCEPTION_HANDLERS"
] | python | train |
gwastro/pycbc | pycbc/cosmology.py | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/cosmology.py#L238-L252 | def setup_interpolant(self):
"""Initializes the z(d) interpolation."""
# for computing nearby (z < 1) redshifts
zs = numpy.linspace(0., 1., num=self.numpoints)
ds = self.cosmology.luminosity_distance(zs).value
self.nearby_d2z = interpolate.interp1d(ds, zs, kind='linear',
... | [
"def",
"setup_interpolant",
"(",
"self",
")",
":",
"# for computing nearby (z < 1) redshifts",
"zs",
"=",
"numpy",
".",
"linspace",
"(",
"0.",
",",
"1.",
",",
"num",
"=",
"self",
".",
"numpoints",
")",
"ds",
"=",
"self",
".",
"cosmology",
".",
"luminosity_di... | Initializes the z(d) interpolation. | [
"Initializes",
"the",
"z",
"(",
"d",
")",
"interpolation",
"."
] | python | train |
iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Builder.py | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Builder.py#L282-L329 | def _node_errors(builder, env, tlist, slist):
"""Validate that the lists of target and source nodes are
legal for this builder and environment. Raise errors or
issue warnings as appropriate.
"""
# First, figure out if there are any errors in the way the targets
# were specified.
for t in t... | [
"def",
"_node_errors",
"(",
"builder",
",",
"env",
",",
"tlist",
",",
"slist",
")",
":",
"# First, figure out if there are any errors in the way the targets",
"# were specified.",
"for",
"t",
"in",
"tlist",
":",
"if",
"t",
".",
"side_effect",
":",
"raise",
"UserErro... | Validate that the lists of target and source nodes are
legal for this builder and environment. Raise errors or
issue warnings as appropriate. | [
"Validate",
"that",
"the",
"lists",
"of",
"target",
"and",
"source",
"nodes",
"are",
"legal",
"for",
"this",
"builder",
"and",
"environment",
".",
"Raise",
"errors",
"or",
"issue",
"warnings",
"as",
"appropriate",
"."
] | python | train |
molmod/molmod | molmod/io/cml.py | https://github.com/molmod/molmod/blob/a7b5b4364ed514ad4c465856c05b5eda1cb561e0/molmod/io/cml.py#L149-L163 | def load_cml(cml_filename):
"""Load the molecules from a CML file
Argument:
| ``cml_filename`` -- The filename of a CML file.
Returns a list of molecule objects with optional molecular graph
attribute and extra attributes.
"""
parser = make_parser()
parser.setFeature(fea... | [
"def",
"load_cml",
"(",
"cml_filename",
")",
":",
"parser",
"=",
"make_parser",
"(",
")",
"parser",
".",
"setFeature",
"(",
"feature_namespaces",
",",
"0",
")",
"dh",
"=",
"CMLMoleculeLoader",
"(",
")",
"parser",
".",
"setContentHandler",
"(",
"dh",
")",
"... | Load the molecules from a CML file
Argument:
| ``cml_filename`` -- The filename of a CML file.
Returns a list of molecule objects with optional molecular graph
attribute and extra attributes. | [
"Load",
"the",
"molecules",
"from",
"a",
"CML",
"file"
] | python | train |
regardscitoyens/cpc-api | cpc_api/api.py | https://github.com/regardscitoyens/cpc-api/blob/4621dcbda3f3bb8fae1cc094fa58e054df24269d/cpc_api/api.py#L42-L55 | def synthese(self, month=None):
"""
month format: YYYYMM
"""
if month is None and self.legislature == '2012-2017':
raise AssertionError('Global Synthesis on legislature does not work, see https://github.com/regardscitoyens/nosdeputes.fr/issues/69')
if month is None:
... | [
"def",
"synthese",
"(",
"self",
",",
"month",
"=",
"None",
")",
":",
"if",
"month",
"is",
"None",
"and",
"self",
".",
"legislature",
"==",
"'2012-2017'",
":",
"raise",
"AssertionError",
"(",
"'Global Synthesis on legislature does not work, see https://github.com/regar... | month format: YYYYMM | [
"month",
"format",
":",
"YYYYMM"
] | python | test |
apple/turicreate | src/unity/python/turicreate/toolkits/_decision_tree.py | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/_decision_tree.py#L125-L138 | def to_dict(self):
"""
Return the node as a dictionary.
Returns
-------
dict: All the attributes of this node as a dictionary (minus the left
and right).
"""
out = {}
for key in self.__dict__.keys():
if key not in ['left', 'right... | [
"def",
"to_dict",
"(",
"self",
")",
":",
"out",
"=",
"{",
"}",
"for",
"key",
"in",
"self",
".",
"__dict__",
".",
"keys",
"(",
")",
":",
"if",
"key",
"not",
"in",
"[",
"'left'",
",",
"'right'",
",",
"'missing'",
",",
"'parent'",
"]",
":",
"out",
... | Return the node as a dictionary.
Returns
-------
dict: All the attributes of this node as a dictionary (minus the left
and right). | [
"Return",
"the",
"node",
"as",
"a",
"dictionary",
"."
] | python | train |
smarie/python-parsyfiles | parsyfiles/type_inspection_tools.py | https://github.com/smarie/python-parsyfiles/blob/344b37e1151e8d4e7c2ee49ae09d6568715ae64e/parsyfiles/type_inspection_tools.py#L573-L624 | def get_constructor_attributes_types(item_type) -> Dict[str, Tuple[Type[Any], bool]]:
"""
Utility method to return a dictionary of attribute name > attribute type from the constructor of a given type
It supports PEP484 and 'attrs' declaration, see https://github.com/python-attrs/attrs.
:param item_type... | [
"def",
"get_constructor_attributes_types",
"(",
"item_type",
")",
"->",
"Dict",
"[",
"str",
",",
"Tuple",
"[",
"Type",
"[",
"Any",
"]",
",",
"bool",
"]",
"]",
":",
"res",
"=",
"dict",
"(",
")",
"try",
":",
"# -- Try to read an 'attr' declaration and to extract... | Utility method to return a dictionary of attribute name > attribute type from the constructor of a given type
It supports PEP484 and 'attrs' declaration, see https://github.com/python-attrs/attrs.
:param item_type:
:return: a dictionary containing for each attr name, a tuple (type, is_mandatory) | [
"Utility",
"method",
"to",
"return",
"a",
"dictionary",
"of",
"attribute",
"name",
">",
"attribute",
"type",
"from",
"the",
"constructor",
"of",
"a",
"given",
"type",
"It",
"supports",
"PEP484",
"and",
"attrs",
"declaration",
"see",
"https",
":",
"//",
"gith... | python | train |
msoulier/tftpy | tftpy/TftpPacketTypes.py | https://github.com/msoulier/tftpy/blob/af2f2fe89a3bf45748b78703820efb0986a8207a/tftpy/TftpPacketTypes.py#L292-L305 | def encode(self):
"""Encode the DAT packet. This method populates self.buffer, and
returns self for easy method chaining."""
if len(self.data) == 0:
log.debug("Encoding an empty DAT packet")
data = self.data
if not isinstance(self.data, bytes):
data = self... | [
"def",
"encode",
"(",
"self",
")",
":",
"if",
"len",
"(",
"self",
".",
"data",
")",
"==",
"0",
":",
"log",
".",
"debug",
"(",
"\"Encoding an empty DAT packet\"",
")",
"data",
"=",
"self",
".",
"data",
"if",
"not",
"isinstance",
"(",
"self",
".",
"dat... | Encode the DAT packet. This method populates self.buffer, and
returns self for easy method chaining. | [
"Encode",
"the",
"DAT",
"packet",
".",
"This",
"method",
"populates",
"self",
".",
"buffer",
"and",
"returns",
"self",
"for",
"easy",
"method",
"chaining",
"."
] | python | train |
ga4gh/ga4gh-server | ga4gh/server/datamodel/variants.py | https://github.com/ga4gh/ga4gh-server/blob/1aa18922ef136db8604f6f098cb1732cba6f2a76/ga4gh/server/datamodel/variants.py#L1297-L1326 | def convertTranscriptEffect(self, annStr, hgvsG):
"""
Takes the ANN string of a SnpEff generated VCF, splits it
and returns a populated GA4GH transcript effect object.
:param annStr: String
:param hgvsG: String
:return: effect protocol.TranscriptEffect()
"""
... | [
"def",
"convertTranscriptEffect",
"(",
"self",
",",
"annStr",
",",
"hgvsG",
")",
":",
"effect",
"=",
"self",
".",
"_createGaTranscriptEffect",
"(",
")",
"effect",
".",
"hgvs_annotation",
".",
"CopyFrom",
"(",
"protocol",
".",
"HGVSAnnotation",
"(",
")",
")",
... | Takes the ANN string of a SnpEff generated VCF, splits it
and returns a populated GA4GH transcript effect object.
:param annStr: String
:param hgvsG: String
:return: effect protocol.TranscriptEffect() | [
"Takes",
"the",
"ANN",
"string",
"of",
"a",
"SnpEff",
"generated",
"VCF",
"splits",
"it",
"and",
"returns",
"a",
"populated",
"GA4GH",
"transcript",
"effect",
"object",
".",
":",
"param",
"annStr",
":",
"String",
":",
"param",
"hgvsG",
":",
"String",
":",
... | python | train |
pjuren/pyokit | src/pyokit/scripts/conservationProfile.py | https://github.com/pjuren/pyokit/blob/fddae123b5d817daa39496183f19c000d9c3791f/src/pyokit/scripts/conservationProfile.py#L177-L204 | def conservtion_profile_pid(region, genome_alignment,
mi_seqs=MissingSequenceHandler.TREAT_AS_ALL_GAPS,
species=None):
"""
build a conservation profile for the given region using the genome alignment.
The scores in the profile will be the percent of bases i... | [
"def",
"conservtion_profile_pid",
"(",
"region",
",",
"genome_alignment",
",",
"mi_seqs",
"=",
"MissingSequenceHandler",
".",
"TREAT_AS_ALL_GAPS",
",",
"species",
"=",
"None",
")",
":",
"res",
"=",
"[",
"]",
"s",
"=",
"region",
".",
"start",
"if",
"region",
... | build a conservation profile for the given region using the genome alignment.
The scores in the profile will be the percent of bases identical to the
reference sequence.
:param miss_seqs: how to treat sequence with no actual sequence data for
the column.
:return: a list of the same length ... | [
"build",
"a",
"conservation",
"profile",
"for",
"the",
"given",
"region",
"using",
"the",
"genome",
"alignment",
"."
] | python | train |
eyurtsev/fcsparser | fcsparser/api.py | https://github.com/eyurtsev/fcsparser/blob/710e8e31d4b09ff6e73d47d86770be6ca2f4282c/fcsparser/api.py#L226-L293 | def read_text(self, file_handle):
"""Parse the TEXT segment of the FCS file.
The TEXT segment contains meta data associated with the FCS file.
Converting all meta keywords to lower case.
"""
header = self.annotation['__header__'] # For convenience
#####
# Read ... | [
"def",
"read_text",
"(",
"self",
",",
"file_handle",
")",
":",
"header",
"=",
"self",
".",
"annotation",
"[",
"'__header__'",
"]",
"# For convenience",
"#####",
"# Read in the TEXT segment of the FCS file",
"# There are some differences in how the",
"file_handle",
".",
"s... | Parse the TEXT segment of the FCS file.
The TEXT segment contains meta data associated with the FCS file.
Converting all meta keywords to lower case. | [
"Parse",
"the",
"TEXT",
"segment",
"of",
"the",
"FCS",
"file",
"."
] | python | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.