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 |
|---|---|---|---|---|---|---|---|---|
jupyter-widgets/jupyterlab-sidecar | setupbase.py | https://github.com/jupyter-widgets/jupyterlab-sidecar/blob/8889d09f1a0933e2cbee06d4874f720b075b29e8/setupbase.py#L502-L540 | def _get_data_files(data_specs, existing):
"""Expand data file specs into valid data files metadata.
Parameters
----------
data_specs: list of tuples
See [createcmdclass] for description.
existing: list of tuples
The existing distribution data_files metadata.
Returns
-------
A valid list of data_files items.
"""
# Extract the existing data files into a staging object.
file_data = defaultdict(list)
for (path, files) in existing or []:
file_data[path] = files
# Extract the files and assign them to the proper data
# files path.
for (path, dname, pattern) in data_specs or []:
dname = dname.replace(os.sep, '/')
offset = len(dname) + 1
files = _get_files(pjoin(dname, pattern))
for fname in files:
# Normalize the path.
root = os.path.dirname(fname)
full_path = '/'.join([path, root[offset:]])
if full_path.endswith('/'):
full_path = full_path[:-1]
file_data[full_path].append(fname)
# Construct the data files spec.
data_files = []
for (path, files) in file_data.items():
data_files.append((path, files))
return data_files | [
"def",
"_get_data_files",
"(",
"data_specs",
",",
"existing",
")",
":",
"# Extract the existing data files into a staging object.",
"file_data",
"=",
"defaultdict",
"(",
"list",
")",
"for",
"(",
"path",
",",
"files",
")",
"in",
"existing",
"or",
"[",
"]",
":",
"... | Expand data file specs into valid data files metadata.
Parameters
----------
data_specs: list of tuples
See [createcmdclass] for description.
existing: list of tuples
The existing distribution data_files metadata.
Returns
-------
A valid list of data_files items. | [
"Expand",
"data",
"file",
"specs",
"into",
"valid",
"data",
"files",
"metadata",
"."
] | python | test |
flask-restful/flask-restful | flask_restful/__init__.py | https://github.com/flask-restful/flask-restful/blob/25544d697c1f82bafbd1320960df459f58a58e03/flask_restful/__init__.py#L271-L341 | def handle_error(self, e):
"""Error handler for the API transforms a raised exception into a Flask
response, with the appropriate HTTP status code and body.
:param e: the raised Exception object
:type e: Exception
"""
got_request_exception.send(current_app._get_current_object(), exception=e)
if not isinstance(e, HTTPException) and current_app.propagate_exceptions:
exc_type, exc_value, tb = sys.exc_info()
if exc_value is e:
raise
else:
raise e
headers = Headers()
if isinstance(e, HTTPException):
code = e.code
default_data = {
'message': getattr(e, 'description', http_status_message(code))
}
headers = e.get_response().headers
else:
code = 500
default_data = {
'message': http_status_message(code),
}
# Werkzeug exceptions generate a content-length header which is added
# to the response in addition to the actual content-length header
# https://github.com/flask-restful/flask-restful/issues/534
remove_headers = ('Content-Length',)
for header in remove_headers:
headers.pop(header, None)
data = getattr(e, 'data', default_data)
if code and code >= 500:
exc_info = sys.exc_info()
if exc_info[1] is None:
exc_info = None
current_app.log_exception(exc_info)
error_cls_name = type(e).__name__
if error_cls_name in self.errors:
custom_data = self.errors.get(error_cls_name, {})
code = custom_data.get('status', 500)
data.update(custom_data)
if code == 406 and self.default_mediatype is None:
# if we are handling NotAcceptable (406), make sure that
# make_response uses a representation we support as the
# default mediatype (so that make_response doesn't throw
# another NotAcceptable error).
supported_mediatypes = list(self.representations.keys())
fallback_mediatype = supported_mediatypes[0] if supported_mediatypes else "text/plain"
resp = self.make_response(
data,
code,
headers,
fallback_mediatype = fallback_mediatype
)
else:
resp = self.make_response(data, code, headers)
if code == 401:
resp = self.unauthorized(resp)
return resp | [
"def",
"handle_error",
"(",
"self",
",",
"e",
")",
":",
"got_request_exception",
".",
"send",
"(",
"current_app",
".",
"_get_current_object",
"(",
")",
",",
"exception",
"=",
"e",
")",
"if",
"not",
"isinstance",
"(",
"e",
",",
"HTTPException",
")",
"and",
... | Error handler for the API transforms a raised exception into a Flask
response, with the appropriate HTTP status code and body.
:param e: the raised Exception object
:type e: Exception | [
"Error",
"handler",
"for",
"the",
"API",
"transforms",
"a",
"raised",
"exception",
"into",
"a",
"Flask",
"response",
"with",
"the",
"appropriate",
"HTTP",
"status",
"code",
"and",
"body",
"."
] | python | train |
data-8/datascience | datascience/tables.py | https://github.com/data-8/datascience/blob/4cee38266903ca169cea4a53b8cc39502d85c464/datascience/tables.py#L2854-L2859 | def _collected_label(collect, label):
"""Label of a collected column."""
if not collect.__name__.startswith('<'):
return label + ' ' + collect.__name__
else:
return label | [
"def",
"_collected_label",
"(",
"collect",
",",
"label",
")",
":",
"if",
"not",
"collect",
".",
"__name__",
".",
"startswith",
"(",
"'<'",
")",
":",
"return",
"label",
"+",
"' '",
"+",
"collect",
".",
"__name__",
"else",
":",
"return",
"label"
] | Label of a collected column. | [
"Label",
"of",
"a",
"collected",
"column",
"."
] | python | train |
randomsync/robotframework-mqttlibrary | src/MQTTLibrary/MQTTKeywords.py | https://github.com/randomsync/robotframework-mqttlibrary/blob/14f20038ccdbb576cc1057ec6736e3685138f59e/src/MQTTLibrary/MQTTKeywords.py#L28-L75 | def connect(self, broker, port=1883, client_id="", clean_session=True):
""" Connect to an MQTT broker. This is a pre-requisite step for publish
and subscribe keywords.
`broker` MQTT broker host
`port` broker port (default 1883)
`client_id` if not specified, a random id is generated
`clean_session` specifies the clean session flag for the connection
Examples:
Connect to a broker with default port and client id
| Connect | 127.0.0.1 |
Connect to a broker by specifying the port and client id explicitly
| Connect | 127.0.0.1 | 1883 | test.client |
Connect to a broker with clean session flag set to false
| Connect | 127.0.0.1 | clean_session=${false} |
"""
logger.info('Connecting to %s at port %s' % (broker, port))
self._connected = False
self._unexpected_disconnect = False
self._mqttc = mqtt.Client(client_id, clean_session)
# set callbacks
self._mqttc.on_connect = self._on_connect
self._mqttc.on_disconnect = self._on_disconnect
if self._username:
self._mqttc.username_pw_set(self._username, self._password)
self._mqttc.connect(broker, int(port))
timer_start = time.time()
while time.time() < timer_start + self._loop_timeout:
if self._connected or self._unexpected_disconnect:
break;
self._mqttc.loop()
if self._unexpected_disconnect:
raise RuntimeError("The client disconnected unexpectedly")
logger.debug('client_id: %s' % self._mqttc._client_id)
return self._mqttc | [
"def",
"connect",
"(",
"self",
",",
"broker",
",",
"port",
"=",
"1883",
",",
"client_id",
"=",
"\"\"",
",",
"clean_session",
"=",
"True",
")",
":",
"logger",
".",
"info",
"(",
"'Connecting to %s at port %s'",
"%",
"(",
"broker",
",",
"port",
")",
")",
... | Connect to an MQTT broker. This is a pre-requisite step for publish
and subscribe keywords.
`broker` MQTT broker host
`port` broker port (default 1883)
`client_id` if not specified, a random id is generated
`clean_session` specifies the clean session flag for the connection
Examples:
Connect to a broker with default port and client id
| Connect | 127.0.0.1 |
Connect to a broker by specifying the port and client id explicitly
| Connect | 127.0.0.1 | 1883 | test.client |
Connect to a broker with clean session flag set to false
| Connect | 127.0.0.1 | clean_session=${false} | | [
"Connect",
"to",
"an",
"MQTT",
"broker",
".",
"This",
"is",
"a",
"pre",
"-",
"requisite",
"step",
"for",
"publish",
"and",
"subscribe",
"keywords",
"."
] | python | train |
alpacahq/pylivetrader | examples/q01/algo.py | https://github.com/alpacahq/pylivetrader/blob/fd328b6595428c0789d9f218df34623f83a02b8b/examples/q01/algo.py#L291-L304 | def my_record_vars(context, data):
"""
Record variables at the end of each day.
"""
# Record our variables.
record(leverage=context.account.leverage)
record(positions=len(context.portfolio.positions))
if 0 < len(context.age):
MaxAge = context.age[max(
list(context.age.keys()), key=(lambda k: context.age[k]))]
print(MaxAge)
record(MaxAge=MaxAge)
record(LowestPrice=context.LowestPrice) | [
"def",
"my_record_vars",
"(",
"context",
",",
"data",
")",
":",
"# Record our variables.",
"record",
"(",
"leverage",
"=",
"context",
".",
"account",
".",
"leverage",
")",
"record",
"(",
"positions",
"=",
"len",
"(",
"context",
".",
"portfolio",
".",
"positi... | Record variables at the end of each day. | [
"Record",
"variables",
"at",
"the",
"end",
"of",
"each",
"day",
"."
] | python | train |
pandas-dev/pandas | pandas/core/generic.py | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/generic.py#L9877-L9891 | def _check_percentile(self, q):
"""
Validate percentiles (used by describe and quantile).
"""
msg = ("percentiles should all be in the interval [0, 1]. "
"Try {0} instead.")
q = np.asarray(q)
if q.ndim == 0:
if not 0 <= q <= 1:
raise ValueError(msg.format(q / 100.0))
else:
if not all(0 <= qs <= 1 for qs in q):
raise ValueError(msg.format(q / 100.0))
return q | [
"def",
"_check_percentile",
"(",
"self",
",",
"q",
")",
":",
"msg",
"=",
"(",
"\"percentiles should all be in the interval [0, 1]. \"",
"\"Try {0} instead.\"",
")",
"q",
"=",
"np",
".",
"asarray",
"(",
"q",
")",
"if",
"q",
".",
"ndim",
"==",
"0",
":",
"if",
... | Validate percentiles (used by describe and quantile). | [
"Validate",
"percentiles",
"(",
"used",
"by",
"describe",
"and",
"quantile",
")",
"."
] | python | train |
bbitmaster/ale_python_interface | ale_python_interface/ale_python_interface.py | https://github.com/bbitmaster/ale_python_interface/blob/253062be8e07fb738ea25982387b20af3712b615/ale_python_interface/ale_python_interface.py#L75-L88 | def getScreen(self,screen_data=None):
"""This function fills screen_data with the RAW Pixel data
screen_data MUST be a numpy array of uint8/int8. This could be initialized like so:
screen_data = np.array(w*h,dtype=np.uint8)
Notice, it must be width*height in size also
If it is None, then this function will initialize it
Note: This is the raw pixel values from the atari, before any RGB palette transformation takes place
"""
if(screen_data is None):
width = ale_lib.getScreenWidth(self.obj)
height = ale_lib.getScreenWidth(self.obj)
screen_data = np.zeros(width*height,dtype=np.uint8)
ale_lib.getScreen(self.obj,as_ctypes(screen_data))
return screen_data | [
"def",
"getScreen",
"(",
"self",
",",
"screen_data",
"=",
"None",
")",
":",
"if",
"(",
"screen_data",
"is",
"None",
")",
":",
"width",
"=",
"ale_lib",
".",
"getScreenWidth",
"(",
"self",
".",
"obj",
")",
"height",
"=",
"ale_lib",
".",
"getScreenWidth",
... | This function fills screen_data with the RAW Pixel data
screen_data MUST be a numpy array of uint8/int8. This could be initialized like so:
screen_data = np.array(w*h,dtype=np.uint8)
Notice, it must be width*height in size also
If it is None, then this function will initialize it
Note: This is the raw pixel values from the atari, before any RGB palette transformation takes place | [
"This",
"function",
"fills",
"screen_data",
"with",
"the",
"RAW",
"Pixel",
"data",
"screen_data",
"MUST",
"be",
"a",
"numpy",
"array",
"of",
"uint8",
"/",
"int8",
".",
"This",
"could",
"be",
"initialized",
"like",
"so",
":",
"screen_data",
"=",
"np",
".",
... | python | train |
pysathq/pysat | examples/rc2.py | https://github.com/pysathq/pysat/blob/522742e8f2d4c6ac50ecd9087f7a346206774c67/examples/rc2.py#L895-L935 | def process_sums(self):
"""
Process cardinality sums participating in a new core.
Whenever necessary, some of the sum assumptions are
removed or split (depending on the value of
``self.minw``). Deleted sums are marked as garbage and are
dealt with in :func:`filter_assumps`.
In some cases, the process involves updating the
right-hand sides of the existing cardinality sums (see the
call to :func:`update_sum`). The overall procedure is
detailed in [1]_.
"""
for l in self.core_sums:
if self.wght[l] == self.minw:
# marking variable as being a part of the core
# so that next time it is not used as an assump
self.garbage.add(l)
else:
# do not remove this variable from assumps
# since it has a remaining non-zero weight
self.wght[l] -= self.minw
# increase bound for the sum
t, b = self.update_sum(l)
# updating bounds and weights
if b < len(t.rhs):
lnew = -t.rhs[b]
if lnew in self.garbage:
self.garbage.remove(lnew)
self.wght[lnew] = 0
if lnew not in self.wght:
self.set_bound(t, b)
else:
self.wght[lnew] += self.minw
# put this assumption to relaxation vars
self.rels.append(-l) | [
"def",
"process_sums",
"(",
"self",
")",
":",
"for",
"l",
"in",
"self",
".",
"core_sums",
":",
"if",
"self",
".",
"wght",
"[",
"l",
"]",
"==",
"self",
".",
"minw",
":",
"# marking variable as being a part of the core",
"# so that next time it is not used as an ass... | Process cardinality sums participating in a new core.
Whenever necessary, some of the sum assumptions are
removed or split (depending on the value of
``self.minw``). Deleted sums are marked as garbage and are
dealt with in :func:`filter_assumps`.
In some cases, the process involves updating the
right-hand sides of the existing cardinality sums (see the
call to :func:`update_sum`). The overall procedure is
detailed in [1]_. | [
"Process",
"cardinality",
"sums",
"participating",
"in",
"a",
"new",
"core",
".",
"Whenever",
"necessary",
"some",
"of",
"the",
"sum",
"assumptions",
"are",
"removed",
"or",
"split",
"(",
"depending",
"on",
"the",
"value",
"of",
"self",
".",
"minw",
")",
"... | python | train |
janpipek/physt | physt/examples/__init__.py | https://github.com/janpipek/physt/blob/6dd441b073514e7728235f50b2352d56aacf38d4/physt/examples/__init__.py#L25-L34 | def normal_h2(size: int = 10000) -> Histogram2D:
"""A simple 2D histogram with normal distribution.
Parameters
----------
size : Number of points
"""
data1 = np.random.normal(0, 1, (size,))
data2 = np.random.normal(0, 1, (size,))
return h2(data1, data2, name="normal", axis_names=tuple("xy"), title="2D normal distribution") | [
"def",
"normal_h2",
"(",
"size",
":",
"int",
"=",
"10000",
")",
"->",
"Histogram2D",
":",
"data1",
"=",
"np",
".",
"random",
".",
"normal",
"(",
"0",
",",
"1",
",",
"(",
"size",
",",
")",
")",
"data2",
"=",
"np",
".",
"random",
".",
"normal",
"... | A simple 2D histogram with normal distribution.
Parameters
----------
size : Number of points | [
"A",
"simple",
"2D",
"histogram",
"with",
"normal",
"distribution",
"."
] | python | train |
batiste/django-page-cms | pages/utils.py | https://github.com/batiste/django-page-cms/blob/3c72111eb7c3997a63c462c1776ffd8ce8c50a5d/pages/utils.py#L63-L113 | def _placeholders_recursif(nodelist, plist, blist):
"""Recursively search into a template node list for PlaceholderNode
node."""
# I needed to do this lazy import to compile the documentation
from django.template.loader_tags import BlockNode
if len(blist):
block = blist[-1]
else:
block = None
for node in nodelist:
if isinstance(node, BlockNode):
if node not in blist:
blist.append(node)
if not block:
block = node
if block:
if isinstance(node, template.base.VariableNode):
if(node.filter_expression.var.var == u'block.super'):
block.has_super_var = True
# extends node?
if hasattr(node, 'parent_name'):
# I do not know why I did this... but the tests are guarding it
dummy_context2 = Context()
dummy_context2.template = template.Template("")
_placeholders_recursif(node.get_parent(dummy_context2).nodelist,
plist, blist)
# include node?
elif hasattr(node, 'template') and hasattr(node.template, 'nodelist'):
_placeholders_recursif(node.template.nodelist, plist, blist)
# Is it a placeholder?
if hasattr(node, 'page') and hasattr(node, 'parsed') and \
hasattr(node, 'as_varname') and hasattr(node, 'name') \
and hasattr(node, 'section'):
if block:
node.found_in_block = block
plist.append(node)
node.render(dummy_context)
for key in ('nodelist', 'nodelist_true', 'nodelist_false'):
if hasattr(node, key):
try:
_placeholders_recursif(getattr(node, key), plist, blist)
except:
pass | [
"def",
"_placeholders_recursif",
"(",
"nodelist",
",",
"plist",
",",
"blist",
")",
":",
"# I needed to do this lazy import to compile the documentation",
"from",
"django",
".",
"template",
".",
"loader_tags",
"import",
"BlockNode",
"if",
"len",
"(",
"blist",
")",
":",... | Recursively search into a template node list for PlaceholderNode
node. | [
"Recursively",
"search",
"into",
"a",
"template",
"node",
"list",
"for",
"PlaceholderNode",
"node",
"."
] | python | train |
adrianliaw/PyCuber | pycuber/solver/cfop/pll.py | https://github.com/adrianliaw/PyCuber/blob/e44b5ba48c831b964ce73d046fb813222771853f/pycuber/solver/cfop/pll.py#L32-L43 | def recognise(self):
"""
Recognise the PLL case of Cube.
"""
result = ""
for side in "LFRB":
for square in self.cube.get_face(side)[0]:
for _side in "LFRB":
if square.colour == self.cube[_side].colour:
result += _side
break
return result | [
"def",
"recognise",
"(",
"self",
")",
":",
"result",
"=",
"\"\"",
"for",
"side",
"in",
"\"LFRB\"",
":",
"for",
"square",
"in",
"self",
".",
"cube",
".",
"get_face",
"(",
"side",
")",
"[",
"0",
"]",
":",
"for",
"_side",
"in",
"\"LFRB\"",
":",
"if",
... | Recognise the PLL case of Cube. | [
"Recognise",
"the",
"PLL",
"case",
"of",
"Cube",
"."
] | python | train |
rollbar/pyrollbar | rollbar/contrib/django/middleware.py | https://github.com/rollbar/pyrollbar/blob/33ef2e723a33d09dd6302f978f4a3908be95b9d2/rollbar/contrib/django/middleware.py#L236-L246 | def _ensure_log_handler(self):
"""
If there's no log configuration, set up a default handler.
"""
if log.handlers:
return
handler = logging.StreamHandler()
formatter = logging.Formatter(
'%(asctime)s %(levelname)-5.5s [%(name)s][%(threadName)s] %(message)s')
handler.setFormatter(formatter)
log.addHandler(handler) | [
"def",
"_ensure_log_handler",
"(",
"self",
")",
":",
"if",
"log",
".",
"handlers",
":",
"return",
"handler",
"=",
"logging",
".",
"StreamHandler",
"(",
")",
"formatter",
"=",
"logging",
".",
"Formatter",
"(",
"'%(asctime)s %(levelname)-5.5s [%(name)s][%(threadName)s... | If there's no log configuration, set up a default handler. | [
"If",
"there",
"s",
"no",
"log",
"configuration",
"set",
"up",
"a",
"default",
"handler",
"."
] | python | test |
CamDavidsonPilon/lifelines | lifelines/utils/concordance.py | https://github.com/CamDavidsonPilon/lifelines/blob/bdf6be6f1d10eea4c46365ee0ee6a47d8c30edf8/lifelines/utils/concordance.py#L203-L228 | def _naive_concordance_summary_statistics(event_times, predicted_event_times, event_observed):
"""
Fallback, simpler method to compute concordance.
Assumes the data has been verified by lifelines.utils.concordance_index first.
"""
num_pairs = 0.0
num_correct = 0.0
num_tied = 0.0
for a, time_a in enumerate(event_times):
pred_a = predicted_event_times[a]
event_a = event_observed[a]
# Don't want to double count
for b in range(a + 1, len(event_times)):
time_b = event_times[b]
pred_b = predicted_event_times[b]
event_b = event_observed[b]
if _valid_comparison(time_a, time_b, event_a, event_b):
num_pairs += 1.0
crct, ties = _concordance_value(time_a, time_b, pred_a, pred_b, event_a, event_b)
num_correct += crct
num_tied += ties
return (num_correct, num_tied, num_pairs) | [
"def",
"_naive_concordance_summary_statistics",
"(",
"event_times",
",",
"predicted_event_times",
",",
"event_observed",
")",
":",
"num_pairs",
"=",
"0.0",
"num_correct",
"=",
"0.0",
"num_tied",
"=",
"0.0",
"for",
"a",
",",
"time_a",
"in",
"enumerate",
"(",
"event... | Fallback, simpler method to compute concordance.
Assumes the data has been verified by lifelines.utils.concordance_index first. | [
"Fallback",
"simpler",
"method",
"to",
"compute",
"concordance",
"."
] | python | train |
KelSolaar/Foundations | foundations/cache.py | https://github.com/KelSolaar/Foundations/blob/5c141330faf09dad70a12bc321f4c564917d0a91/foundations/cache.py#L103-L123 | def get_content(self, key):
"""
Gets given content from the cache.
Usage::
>>> cache = Cache()
>>> cache.add_content(John="Doe", Luke="Skywalker")
True
>>> cache.get_content("Luke")
'Skywalker'
:param key: Content to retrieve.
:type key: object
:return: Content.
:rtype: object
"""
LOGGER.debug("> Retrieving '{0}' content from the cache.".format(self.__class__.__name__, key))
return self.get(key) | [
"def",
"get_content",
"(",
"self",
",",
"key",
")",
":",
"LOGGER",
".",
"debug",
"(",
"\"> Retrieving '{0}' content from the cache.\"",
".",
"format",
"(",
"self",
".",
"__class__",
".",
"__name__",
",",
"key",
")",
")",
"return",
"self",
".",
"get",
"(",
... | Gets given content from the cache.
Usage::
>>> cache = Cache()
>>> cache.add_content(John="Doe", Luke="Skywalker")
True
>>> cache.get_content("Luke")
'Skywalker'
:param key: Content to retrieve.
:type key: object
:return: Content.
:rtype: object | [
"Gets",
"given",
"content",
"from",
"the",
"cache",
"."
] | python | train |
vingd/encrypted-pickle-python | encryptedpickle/encryptedpickle.py | https://github.com/vingd/encrypted-pickle-python/blob/7656233598e02e65971f69e11849a0f288b2b2a5/encryptedpickle/encryptedpickle.py#L490-L505 | def _unserialize_data(self, data, options):
'''Unserialize data'''
serialization_algorithm_id = options['serialization_algorithm_id']
if serialization_algorithm_id not in self.serialization_algorithms:
raise Exception('Unknown serialization algorithm id: %d'
% serialization_algorithm_id)
serialization_algorithm = \
self.serialization_algorithms[serialization_algorithm_id]
algorithm = self._get_algorithm_info(serialization_algorithm)
data = self._decode(data, algorithm)
return data | [
"def",
"_unserialize_data",
"(",
"self",
",",
"data",
",",
"options",
")",
":",
"serialization_algorithm_id",
"=",
"options",
"[",
"'serialization_algorithm_id'",
"]",
"if",
"serialization_algorithm_id",
"not",
"in",
"self",
".",
"serialization_algorithms",
":",
"rais... | Unserialize data | [
"Unserialize",
"data"
] | python | valid |
esheldon/fitsio | fitsio/hdu/table.py | https://github.com/esheldon/fitsio/blob/a6f07919f457a282fe240adad9d2c30906b71a15/fitsio/hdu/table.py#L1258-L1279 | def _fix_range(self, num, isslice=True):
"""
Ensure the input is within range.
If el=True, then don't treat as a slice element
"""
nrows = self._info['nrows']
if isslice:
# include the end
if num < 0:
num = nrows + (1+num)
elif num > nrows:
num = nrows
else:
# single element
if num < 0:
num = nrows + num
elif num > (nrows-1):
num = nrows-1
return num | [
"def",
"_fix_range",
"(",
"self",
",",
"num",
",",
"isslice",
"=",
"True",
")",
":",
"nrows",
"=",
"self",
".",
"_info",
"[",
"'nrows'",
"]",
"if",
"isslice",
":",
"# include the end",
"if",
"num",
"<",
"0",
":",
"num",
"=",
"nrows",
"+",
"(",
"1",... | Ensure the input is within range.
If el=True, then don't treat as a slice element | [
"Ensure",
"the",
"input",
"is",
"within",
"range",
"."
] | python | train |
jtwhite79/pyemu | pyemu/utils/gw_utils.py | https://github.com/jtwhite79/pyemu/blob/c504d8e7a4097cec07655a6318d275739bd8148a/pyemu/utils/gw_utils.py#L2379-L2447 | def write_hfb_template(m):
"""write a template file for an hfb (yuck!)
Parameters
----------
m : flopy.modflow.Modflow instance with an HFB file
Returns
-------
(tpl_filename, df) : (str, pandas.DataFrame)
the name of the template file and a dataframe with useful info.
"""
assert m.hfb6 is not None
hfb_file = os.path.join(m.model_ws,m.hfb6.file_name[0])
assert os.path.exists(hfb_file),"couldn't find hfb_file {0}".format(hfb_file)
f_in = open(hfb_file,'r')
tpl_file = hfb_file+".tpl"
f_tpl = open(tpl_file,'w')
f_tpl.write("ptf ~\n")
parnme,parval1,xs,ys = [],[],[],[]
iis,jjs,kks = [],[],[]
xc = m.sr.xcentergrid
yc = m.sr.ycentergrid
while True:
line = f_in.readline()
if line == "":
break
f_tpl.write(line)
if not line.startswith("#"):
raw = line.strip().split()
nphfb = int(raw[0])
mxfb = int(raw[1])
nhfbnp = int(raw[2])
if nphfb > 0 or mxfb > 0:
raise Exception("not supporting terrible HFB pars")
for i in range(nhfbnp):
line = f_in.readline()
if line == "":
raise Exception("EOF")
raw = line.strip().split()
k = int(raw[0]) - 1
i = int(raw[1]) - 1
j = int(raw[2]) - 1
pn = "hb{0:02}{1:04d}{2:04}".format(k,i,j)
pv = float(raw[5])
raw[5] = "~ {0} ~".format(pn)
line = ' '.join(raw)+'\n'
f_tpl.write(line)
parnme.append(pn)
parval1.append(pv)
xs.append(xc[i,j])
ys.append(yc[i,j])
iis.append(i)
jjs.append(j)
kks.append(k)
break
f_tpl.close()
f_in.close()
df = pd.DataFrame({"parnme":parnme,"parval1":parval1,"x":xs,"y":ys,
"i":iis,"j":jjs,"k":kks},index=parnme)
df.loc[:,"pargp"] = "hfb_hydfac"
df.loc[:,"parubnd"] = df.parval1.max() * 10.0
df.loc[:,"parlbnd"] = df.parval1.min() * 0.1
return tpl_file,df | [
"def",
"write_hfb_template",
"(",
"m",
")",
":",
"assert",
"m",
".",
"hfb6",
"is",
"not",
"None",
"hfb_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"m",
".",
"model_ws",
",",
"m",
".",
"hfb6",
".",
"file_name",
"[",
"0",
"]",
")",
"assert",
"... | write a template file for an hfb (yuck!)
Parameters
----------
m : flopy.modflow.Modflow instance with an HFB file
Returns
-------
(tpl_filename, df) : (str, pandas.DataFrame)
the name of the template file and a dataframe with useful info. | [
"write",
"a",
"template",
"file",
"for",
"an",
"hfb",
"(",
"yuck!",
")"
] | python | train |
PMBio/limix-backup | limix/mtSet/core/splitter_bed.py | https://github.com/PMBio/limix-backup/blob/1e201fdb5c694d0d5506f207f3de65d8ef66146c/limix/mtSet/core/splitter_bed.py#L41-L77 | def splitGenoSlidingWindow(pos,out_file,size=5e4,step=None):
"""
split into windows using a slide criterion
Args:
size: window size
step: moving step (default: 0.5*size)
Returns:
wnd_i: number of windows
nSnps: vector of per-window number of SNPs
"""
if step is None: step = 0.5*size
chroms = SP.unique(pos[:,0])
RV = []
wnd_i = 0
wnd_file = csv.writer(open(out_file,'w'),delimiter='\t')
nSnps = []
for chrom_i in chroms:
Ichrom = pos[:,0]==chrom_i
idx_chrom_start = SP.where(Ichrom)[0][0]
pos_chr = pos[Ichrom,1]
start = pos_chr.min()
pos_chr_max = pos_chr.max()
while 1:
if start>pos_chr_max: break
end = start+size
Ir = (pos_chr>=start)*(pos_chr<end)
_nSnps = Ir.sum()
if _nSnps>0:
idx_wnd_start = idx_chrom_start+SP.where(Ir)[0][0]
nSnps.append(_nSnps)
line = SP.array([wnd_i,chrom_i,start,end,idx_wnd_start,_nSnps],dtype=int)
wnd_file.writerow(line)
wnd_i+=1
start += step
nSnps = SP.array(nSnps)
return wnd_i,nSnps | [
"def",
"splitGenoSlidingWindow",
"(",
"pos",
",",
"out_file",
",",
"size",
"=",
"5e4",
",",
"step",
"=",
"None",
")",
":",
"if",
"step",
"is",
"None",
":",
"step",
"=",
"0.5",
"*",
"size",
"chroms",
"=",
"SP",
".",
"unique",
"(",
"pos",
"[",
":",
... | split into windows using a slide criterion
Args:
size: window size
step: moving step (default: 0.5*size)
Returns:
wnd_i: number of windows
nSnps: vector of per-window number of SNPs | [
"split",
"into",
"windows",
"using",
"a",
"slide",
"criterion",
"Args",
":",
"size",
":",
"window",
"size",
"step",
":",
"moving",
"step",
"(",
"default",
":",
"0",
".",
"5",
"*",
"size",
")",
"Returns",
":",
"wnd_i",
":",
"number",
"of",
"windows",
... | python | train |
ghackebeil/PyORAM | src/pyoram/util/virtual_heap.py | https://github.com/ghackebeil/PyORAM/blob/b8832c1b753c0b2148ef7a143c5f5dd3bbbb61e7/src/pyoram/util/virtual_heap.py#L379-L417 | def write_as_dot(self, f, data=None, max_levels=None):
"Write the tree in the dot language format to f."
assert (max_levels is None) or (max_levels >= 0)
def visit_node(n, levels):
lbl = "{"
if data is None:
if self.k <= max_k_labeled:
lbl = repr(n.label()).\
replace("{","\{").\
replace("}","\}").\
replace("|","\|").\
replace("<","\<").\
replace(">","\>")
else:
lbl = str(n)
else:
s = self.bucket_to_block(n.bucket)
for i in xrange(self.blocks_per_bucket):
lbl += "{%s}" % (data[s+i])
if i + 1 != self.blocks_per_bucket:
lbl += "|"
lbl += "}"
f.write(" %s [penwidth=%s,label=\"%s\"];\n"
% (n.bucket, 1, lbl))
levels += 1
if (max_levels is None) or (levels <= max_levels):
for i in xrange(self.k):
cn = n.child_node(i)
if not self.is_nil_node(cn):
visit_node(cn, levels)
f.write(" %s -> %s ;\n" % (n.bucket, cn.bucket))
f.write("// Created by SizedVirtualHeap.write_as_dot(...)\n")
f.write("digraph heaptree {\n")
f.write("node [shape=record]\n")
if (max_levels is None) or (max_levels > 0):
visit_node(self.root_node(), 1)
f.write("}\n") | [
"def",
"write_as_dot",
"(",
"self",
",",
"f",
",",
"data",
"=",
"None",
",",
"max_levels",
"=",
"None",
")",
":",
"assert",
"(",
"max_levels",
"is",
"None",
")",
"or",
"(",
"max_levels",
">=",
"0",
")",
"def",
"visit_node",
"(",
"n",
",",
"levels",
... | Write the tree in the dot language format to f. | [
"Write",
"the",
"tree",
"in",
"the",
"dot",
"language",
"format",
"to",
"f",
"."
] | python | train |
mitsei/dlkit | dlkit/json_/grading/objects.py | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/json_/grading/objects.py#L491-L504 | def get_numeric_score_increment(self):
"""Gets the incremental step.
return: (decimal) - the increment
raise: IllegalState - ``is_based_on_grades()`` is ``true``
*compliance: mandatory -- This method must be implemented.*
"""
if self.is_based_on_grades():
raise errors.IllegalState('This GradeSystem is based on grades')
if self._my_map['numericScoreIncrement'] is None:
return None
else:
return Decimal(str(self._my_map['numericScoreIncrement'])) | [
"def",
"get_numeric_score_increment",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_based_on_grades",
"(",
")",
":",
"raise",
"errors",
".",
"IllegalState",
"(",
"'This GradeSystem is based on grades'",
")",
"if",
"self",
".",
"_my_map",
"[",
"'numericScoreIncrement... | Gets the incremental step.
return: (decimal) - the increment
raise: IllegalState - ``is_based_on_grades()`` is ``true``
*compliance: mandatory -- This method must be implemented.* | [
"Gets",
"the",
"incremental",
"step",
"."
] | python | train |
kylejusticemagnuson/pyti | pyti/commodity_channel_index.py | https://github.com/kylejusticemagnuson/pyti/blob/2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2/pyti/commodity_channel_index.py#L10-L22 | def commodity_channel_index(close_data, high_data, low_data, period):
"""
Commodity Channel Index.
Formula:
CCI = (TP - SMA(TP)) / (0.015 * Mean Deviation)
"""
catch_errors.check_for_input_len_diff(close_data, high_data, low_data)
catch_errors.check_for_period_error(close_data, period)
tp = typical_price(close_data, high_data, low_data)
cci = ((tp - sma(tp, period)) /
(0.015 * np.mean(np.absolute(tp - np.mean(tp)))))
return cci | [
"def",
"commodity_channel_index",
"(",
"close_data",
",",
"high_data",
",",
"low_data",
",",
"period",
")",
":",
"catch_errors",
".",
"check_for_input_len_diff",
"(",
"close_data",
",",
"high_data",
",",
"low_data",
")",
"catch_errors",
".",
"check_for_period_error",
... | Commodity Channel Index.
Formula:
CCI = (TP - SMA(TP)) / (0.015 * Mean Deviation) | [
"Commodity",
"Channel",
"Index",
"."
] | python | train |
aws/sagemaker-python-sdk | src/sagemaker/tuner.py | https://github.com/aws/sagemaker-python-sdk/blob/a9e724c7d3f5572b68c3903548c792a59d99799a/src/sagemaker/tuner.py#L559-L581 | def identical_dataset_and_algorithm_tuner(self, additional_parents=None):
"""Creates a new ``HyperparameterTuner`` by copying the request fields from the provided parent to the new
instance of ``HyperparameterTuner``. Followed by addition of warm start configuration with the type as
"IdenticalDataAndAlgorithm" and parents as the union of provided list of ``additional_parents`` and the ``self``
Args:
additional_parents (set{str}): Set of additional parents along with the self to be used in warm starting
the identical dataset and algorithm tuner.
Returns:
sagemaker.tuner.HyperparameterTuner: HyperparameterTuner instance which can be used to launch identical
dataset and algorithm tuning job.
Examples:
>>> parent_tuner = HyperparameterTuner.attach(tuning_job_name="parent-job-1")
>>> identical_dataset_algo_tuner = parent_tuner.identical_dataset_and_algorithm_tuner(
>>> additional_parents={"parent-job-2"})
Later On:
>>> identical_dataset_algo_tuner.fit(inputs={})
"""
return self._create_warm_start_tuner(additional_parents=additional_parents,
warm_start_type=WarmStartTypes.IDENTICAL_DATA_AND_ALGORITHM) | [
"def",
"identical_dataset_and_algorithm_tuner",
"(",
"self",
",",
"additional_parents",
"=",
"None",
")",
":",
"return",
"self",
".",
"_create_warm_start_tuner",
"(",
"additional_parents",
"=",
"additional_parents",
",",
"warm_start_type",
"=",
"WarmStartTypes",
".",
"I... | Creates a new ``HyperparameterTuner`` by copying the request fields from the provided parent to the new
instance of ``HyperparameterTuner``. Followed by addition of warm start configuration with the type as
"IdenticalDataAndAlgorithm" and parents as the union of provided list of ``additional_parents`` and the ``self``
Args:
additional_parents (set{str}): Set of additional parents along with the self to be used in warm starting
the identical dataset and algorithm tuner.
Returns:
sagemaker.tuner.HyperparameterTuner: HyperparameterTuner instance which can be used to launch identical
dataset and algorithm tuning job.
Examples:
>>> parent_tuner = HyperparameterTuner.attach(tuning_job_name="parent-job-1")
>>> identical_dataset_algo_tuner = parent_tuner.identical_dataset_and_algorithm_tuner(
>>> additional_parents={"parent-job-2"})
Later On:
>>> identical_dataset_algo_tuner.fit(inputs={}) | [
"Creates",
"a",
"new",
"HyperparameterTuner",
"by",
"copying",
"the",
"request",
"fields",
"from",
"the",
"provided",
"parent",
"to",
"the",
"new",
"instance",
"of",
"HyperparameterTuner",
".",
"Followed",
"by",
"addition",
"of",
"warm",
"start",
"configuration",
... | python | train |
cartologic/cartoview | pavement.py | https://github.com/cartologic/cartoview/blob/8eea73a7e363ac806dbfca3ca61f7e9d2c839b6b/pavement.py#L139-L157 | def _robust_rmtree(path, logger=None, max_retries=5):
"""Try to delete paths robustly .
Retries several times (with increasing delays) if an OSError
occurs. If the final attempt fails, the Exception is propagated
to the caller. Taken from https://github.com/hashdist/hashdist/pull/116
"""
for i in range(max_retries):
try:
shutil.rmtree(path)
return
except OSError as e:
if logger:
info('Unable to remove path: %s' % path)
info('Retrying after %d seconds' % i)
time.sleep(i)
# Final attempt, pass any Exceptions up to caller.
shutil.rmtree(path) | [
"def",
"_robust_rmtree",
"(",
"path",
",",
"logger",
"=",
"None",
",",
"max_retries",
"=",
"5",
")",
":",
"for",
"i",
"in",
"range",
"(",
"max_retries",
")",
":",
"try",
":",
"shutil",
".",
"rmtree",
"(",
"path",
")",
"return",
"except",
"OSError",
"... | Try to delete paths robustly .
Retries several times (with increasing delays) if an OSError
occurs. If the final attempt fails, the Exception is propagated
to the caller. Taken from https://github.com/hashdist/hashdist/pull/116 | [
"Try",
"to",
"delete",
"paths",
"robustly",
".",
"Retries",
"several",
"times",
"(",
"with",
"increasing",
"delays",
")",
"if",
"an",
"OSError",
"occurs",
".",
"If",
"the",
"final",
"attempt",
"fails",
"the",
"Exception",
"is",
"propagated",
"to",
"the",
"... | python | train |
edx/XBlock | xblock/runtime.py | https://github.com/edx/XBlock/blob/368bf46e2c0ee69bbb21817f428c4684936e18ee/xblock/runtime.py#L738-L749 | def _aside_from_xml(self, node, block_def_id, block_usage_id, id_generator):
"""
Create an aside from the xml and attach it to the given block
"""
id_generator = id_generator or self.id_generator
aside_type = node.tag
aside_class = self.load_aside_type(aside_type)
aside_def_id, aside_usage_id = id_generator.create_aside(block_def_id, block_usage_id, aside_type)
keys = ScopeIds(None, aside_type, aside_def_id, aside_usage_id)
aside = aside_class.parse_xml(node, self, keys, id_generator)
aside.save() | [
"def",
"_aside_from_xml",
"(",
"self",
",",
"node",
",",
"block_def_id",
",",
"block_usage_id",
",",
"id_generator",
")",
":",
"id_generator",
"=",
"id_generator",
"or",
"self",
".",
"id_generator",
"aside_type",
"=",
"node",
".",
"tag",
"aside_class",
"=",
"s... | Create an aside from the xml and attach it to the given block | [
"Create",
"an",
"aside",
"from",
"the",
"xml",
"and",
"attach",
"it",
"to",
"the",
"given",
"block"
] | python | train |
wavycloud/pyboto3 | pyboto3/opsworks.py | https://github.com/wavycloud/pyboto3/blob/924957ccf994303713a4eed90b775ff2ab95b2e5/pyboto3/opsworks.py#L3431-L3623 | def update_layer(LayerId=None, Name=None, Shortname=None, Attributes=None, CloudWatchLogsConfiguration=None, CustomInstanceProfileArn=None, CustomJson=None, CustomSecurityGroupIds=None, Packages=None, VolumeConfigurations=None, EnableAutoHealing=None, AutoAssignElasticIps=None, AutoAssignPublicIps=None, CustomRecipes=None, InstallUpdatesOnBoot=None, UseEbsOptimizedInstances=None, LifecycleEventConfiguration=None):
"""
Updates a specified layer.
See also: AWS API Documentation
:example: response = client.update_layer(
LayerId='string',
Name='string',
Shortname='string',
Attributes={
'string': 'string'
},
CloudWatchLogsConfiguration={
'Enabled': True|False,
'LogStreams': [
{
'LogGroupName': 'string',
'DatetimeFormat': 'string',
'TimeZone': 'LOCAL'|'UTC',
'File': 'string',
'FileFingerprintLines': 'string',
'MultiLineStartPattern': 'string',
'InitialPosition': 'start_of_file'|'end_of_file',
'Encoding': 'ascii'|'big5'|'big5hkscs'|'cp037'|'cp424'|'cp437'|'cp500'|'cp720'|'cp737'|'cp775'|'cp850'|'cp852'|'cp855'|'cp856'|'cp857'|'cp858'|'cp860'|'cp861'|'cp862'|'cp863'|'cp864'|'cp865'|'cp866'|'cp869'|'cp874'|'cp875'|'cp932'|'cp949'|'cp950'|'cp1006'|'cp1026'|'cp1140'|'cp1250'|'cp1251'|'cp1252'|'cp1253'|'cp1254'|'cp1255'|'cp1256'|'cp1257'|'cp1258'|'euc_jp'|'euc_jis_2004'|'euc_jisx0213'|'euc_kr'|'gb2312'|'gbk'|'gb18030'|'hz'|'iso2022_jp'|'iso2022_jp_1'|'iso2022_jp_2'|'iso2022_jp_2004'|'iso2022_jp_3'|'iso2022_jp_ext'|'iso2022_kr'|'latin_1'|'iso8859_2'|'iso8859_3'|'iso8859_4'|'iso8859_5'|'iso8859_6'|'iso8859_7'|'iso8859_8'|'iso8859_9'|'iso8859_10'|'iso8859_13'|'iso8859_14'|'iso8859_15'|'iso8859_16'|'johab'|'koi8_r'|'koi8_u'|'mac_cyrillic'|'mac_greek'|'mac_iceland'|'mac_latin2'|'mac_roman'|'mac_turkish'|'ptcp154'|'shift_jis'|'shift_jis_2004'|'shift_jisx0213'|'utf_32'|'utf_32_be'|'utf_32_le'|'utf_16'|'utf_16_be'|'utf_16_le'|'utf_7'|'utf_8'|'utf_8_sig',
'BufferDuration': 123,
'BatchCount': 123,
'BatchSize': 123
},
]
},
CustomInstanceProfileArn='string',
CustomJson='string',
CustomSecurityGroupIds=[
'string',
],
Packages=[
'string',
],
VolumeConfigurations=[
{
'MountPoint': 'string',
'RaidLevel': 123,
'NumberOfDisks': 123,
'Size': 123,
'VolumeType': 'string',
'Iops': 123
},
],
EnableAutoHealing=True|False,
AutoAssignElasticIps=True|False,
AutoAssignPublicIps=True|False,
CustomRecipes={
'Setup': [
'string',
],
'Configure': [
'string',
],
'Deploy': [
'string',
],
'Undeploy': [
'string',
],
'Shutdown': [
'string',
]
},
InstallUpdatesOnBoot=True|False,
UseEbsOptimizedInstances=True|False,
LifecycleEventConfiguration={
'Shutdown': {
'ExecutionTimeout': 123,
'DelayUntilElbConnectionsDrained': True|False
}
}
)
:type LayerId: string
:param LayerId: [REQUIRED]
The layer ID.
:type Name: string
:param Name: The layer name, which is used by the console.
:type Shortname: string
:param Shortname: For custom layers only, use this parameter to specify the layer's short name, which is used internally by AWS OpsWorks Stacks and by Chef. The short name is also used as the name for the directory where your app files are installed. It can have a maximum of 200 characters and must be in the following format: /A[a-z0-9-_.]+Z/.
The built-in layers' short names are defined by AWS OpsWorks Stacks. For more information, see the Layer Reference
:type Attributes: dict
:param Attributes: One or more user-defined key/value pairs to be added to the stack attributes.
(string) --
(string) --
:type CloudWatchLogsConfiguration: dict
:param CloudWatchLogsConfiguration: Specifies CloudWatch Logs configuration options for the layer. For more information, see CloudWatchLogsLogStream .
Enabled (boolean) --Whether CloudWatch Logs is enabled for a layer.
LogStreams (list) --A list of configuration options for CloudWatch Logs.
(dict) --Describes the Amazon CloudWatch logs configuration for a layer. For detailed information about members of this data type, see the CloudWatch Logs Agent Reference .
LogGroupName (string) --Specifies the destination log group. A log group is created automatically if it doesn't already exist. Log group names can be between 1 and 512 characters long. Allowed characters include a-z, A-Z, 0-9, '_' (underscore), '-' (hyphen), '/' (forward slash), and '.' (period).
DatetimeFormat (string) --Specifies how the time stamp is extracted from logs. For more information, see the CloudWatch Logs Agent Reference .
TimeZone (string) --Specifies the time zone of log event time stamps.
File (string) --Specifies log files that you want to push to CloudWatch Logs.
File can point to a specific file or multiple files (by using wild card characters such as /var/log/system.log* ). Only the latest file is pushed to CloudWatch Logs, based on file modification time. We recommend that you use wild card characters to specify a series of files of the same type, such as access_log.2014-06-01-01 , access_log.2014-06-01-02 , and so on by using a pattern like access_log.* . Don't use a wildcard to match multiple file types, such as access_log_80 and access_log_443 . To specify multiple, different file types, add another log stream entry to the configuration file, so that each log file type is stored in a different log group.
Zipped files are not supported.
FileFingerprintLines (string) --Specifies the range of lines for identifying a file. The valid values are one number, or two dash-delimited numbers, such as '1', '2-5'. The default value is '1', meaning the first line is used to calculate the fingerprint. Fingerprint lines are not sent to CloudWatch Logs unless all specified lines are available.
MultiLineStartPattern (string) --Specifies the pattern for identifying the start of a log message.
InitialPosition (string) --Specifies where to start to read data (start_of_file or end_of_file). The default is start_of_file. This setting is only used if there is no state persisted for that log stream.
Encoding (string) --Specifies the encoding of the log file so that the file can be read correctly. The default is utf_8 . Encodings supported by Python codecs.decode() can be used here.
BufferDuration (integer) --Specifies the time duration for the batching of log events. The minimum value is 5000ms and default value is 5000ms.
BatchCount (integer) --Specifies the max number of log events in a batch, up to 10000. The default value is 1000.
BatchSize (integer) --Specifies the maximum size of log events in a batch, in bytes, up to 1048576 bytes. The default value is 32768 bytes. This size is calculated as the sum of all event messages in UTF-8, plus 26 bytes for each log event.
:type CustomInstanceProfileArn: string
:param CustomInstanceProfileArn: The ARN of an IAM profile to be used for all of the layer's EC2 instances. For more information about IAM ARNs, see Using Identifiers .
:type CustomJson: string
:param CustomJson: A JSON-formatted string containing custom stack configuration and deployment attributes to be installed on the layer's instances. For more information, see Using Custom JSON .
:type CustomSecurityGroupIds: list
:param CustomSecurityGroupIds: An array containing the layer's custom security group IDs.
(string) --
:type Packages: list
:param Packages: An array of Package objects that describe the layer's packages.
(string) --
:type VolumeConfigurations: list
:param VolumeConfigurations: A VolumeConfigurations object that describes the layer's Amazon EBS volumes.
(dict) --Describes an Amazon EBS volume configuration.
MountPoint (string) -- [REQUIRED]The volume mount point. For example '/dev/sdh'.
RaidLevel (integer) --The volume RAID level .
NumberOfDisks (integer) -- [REQUIRED]The number of disks in the volume.
Size (integer) -- [REQUIRED]The volume size.
VolumeType (string) --The volume type:
standard - Magnetic
io1 - Provisioned IOPS (SSD)
gp2 - General Purpose (SSD)
Iops (integer) --For PIOPS volumes, the IOPS per disk.
:type EnableAutoHealing: boolean
:param EnableAutoHealing: Whether to disable auto healing for the layer.
:type AutoAssignElasticIps: boolean
:param AutoAssignElasticIps: Whether to automatically assign an Elastic IP address to the layer's instances. For more information, see How to Edit a Layer .
:type AutoAssignPublicIps: boolean
:param AutoAssignPublicIps: For stacks that are running in a VPC, whether to automatically assign a public IP address to the layer's instances. For more information, see How to Edit a Layer .
:type CustomRecipes: dict
:param CustomRecipes: A LayerCustomRecipes object that specifies the layer's custom recipes.
Setup (list) --An array of custom recipe names to be run following a setup event.
(string) --
Configure (list) --An array of custom recipe names to be run following a configure event.
(string) --
Deploy (list) --An array of custom recipe names to be run following a deploy event.
(string) --
Undeploy (list) --An array of custom recipe names to be run following a undeploy event.
(string) --
Shutdown (list) --An array of custom recipe names to be run following a shutdown event.
(string) --
:type InstallUpdatesOnBoot: boolean
:param InstallUpdatesOnBoot: Whether to install operating system and package updates when the instance boots. The default value is true . To control when updates are installed, set this value to false . You must then update your instances manually by using CreateDeployment to run the update_dependencies stack command or manually running yum (Amazon Linux) or apt-get (Ubuntu) on the instances.
Note
We strongly recommend using the default value of true , to ensure that your instances have the latest security updates.
:type UseEbsOptimizedInstances: boolean
:param UseEbsOptimizedInstances: Whether to use Amazon EBS-optimized instances.
:type LifecycleEventConfiguration: dict
:param LifecycleEventConfiguration:
Shutdown (dict) --A ShutdownEventConfiguration object that specifies the Shutdown event configuration.
ExecutionTimeout (integer) --The time, in seconds, that AWS OpsWorks Stacks will wait after triggering a Shutdown event before shutting down an instance.
DelayUntilElbConnectionsDrained (boolean) --Whether to enable Elastic Load Balancing connection draining. For more information, see Connection Draining
"""
pass | [
"def",
"update_layer",
"(",
"LayerId",
"=",
"None",
",",
"Name",
"=",
"None",
",",
"Shortname",
"=",
"None",
",",
"Attributes",
"=",
"None",
",",
"CloudWatchLogsConfiguration",
"=",
"None",
",",
"CustomInstanceProfileArn",
"=",
"None",
",",
"CustomJson",
"=",
... | Updates a specified layer.
See also: AWS API Documentation
:example: response = client.update_layer(
LayerId='string',
Name='string',
Shortname='string',
Attributes={
'string': 'string'
},
CloudWatchLogsConfiguration={
'Enabled': True|False,
'LogStreams': [
{
'LogGroupName': 'string',
'DatetimeFormat': 'string',
'TimeZone': 'LOCAL'|'UTC',
'File': 'string',
'FileFingerprintLines': 'string',
'MultiLineStartPattern': 'string',
'InitialPosition': 'start_of_file'|'end_of_file',
'Encoding': 'ascii'|'big5'|'big5hkscs'|'cp037'|'cp424'|'cp437'|'cp500'|'cp720'|'cp737'|'cp775'|'cp850'|'cp852'|'cp855'|'cp856'|'cp857'|'cp858'|'cp860'|'cp861'|'cp862'|'cp863'|'cp864'|'cp865'|'cp866'|'cp869'|'cp874'|'cp875'|'cp932'|'cp949'|'cp950'|'cp1006'|'cp1026'|'cp1140'|'cp1250'|'cp1251'|'cp1252'|'cp1253'|'cp1254'|'cp1255'|'cp1256'|'cp1257'|'cp1258'|'euc_jp'|'euc_jis_2004'|'euc_jisx0213'|'euc_kr'|'gb2312'|'gbk'|'gb18030'|'hz'|'iso2022_jp'|'iso2022_jp_1'|'iso2022_jp_2'|'iso2022_jp_2004'|'iso2022_jp_3'|'iso2022_jp_ext'|'iso2022_kr'|'latin_1'|'iso8859_2'|'iso8859_3'|'iso8859_4'|'iso8859_5'|'iso8859_6'|'iso8859_7'|'iso8859_8'|'iso8859_9'|'iso8859_10'|'iso8859_13'|'iso8859_14'|'iso8859_15'|'iso8859_16'|'johab'|'koi8_r'|'koi8_u'|'mac_cyrillic'|'mac_greek'|'mac_iceland'|'mac_latin2'|'mac_roman'|'mac_turkish'|'ptcp154'|'shift_jis'|'shift_jis_2004'|'shift_jisx0213'|'utf_32'|'utf_32_be'|'utf_32_le'|'utf_16'|'utf_16_be'|'utf_16_le'|'utf_7'|'utf_8'|'utf_8_sig',
'BufferDuration': 123,
'BatchCount': 123,
'BatchSize': 123
},
]
},
CustomInstanceProfileArn='string',
CustomJson='string',
CustomSecurityGroupIds=[
'string',
],
Packages=[
'string',
],
VolumeConfigurations=[
{
'MountPoint': 'string',
'RaidLevel': 123,
'NumberOfDisks': 123,
'Size': 123,
'VolumeType': 'string',
'Iops': 123
},
],
EnableAutoHealing=True|False,
AutoAssignElasticIps=True|False,
AutoAssignPublicIps=True|False,
CustomRecipes={
'Setup': [
'string',
],
'Configure': [
'string',
],
'Deploy': [
'string',
],
'Undeploy': [
'string',
],
'Shutdown': [
'string',
]
},
InstallUpdatesOnBoot=True|False,
UseEbsOptimizedInstances=True|False,
LifecycleEventConfiguration={
'Shutdown': {
'ExecutionTimeout': 123,
'DelayUntilElbConnectionsDrained': True|False
}
}
)
:type LayerId: string
:param LayerId: [REQUIRED]
The layer ID.
:type Name: string
:param Name: The layer name, which is used by the console.
:type Shortname: string
:param Shortname: For custom layers only, use this parameter to specify the layer's short name, which is used internally by AWS OpsWorks Stacks and by Chef. The short name is also used as the name for the directory where your app files are installed. It can have a maximum of 200 characters and must be in the following format: /A[a-z0-9-_.]+Z/.
The built-in layers' short names are defined by AWS OpsWorks Stacks. For more information, see the Layer Reference
:type Attributes: dict
:param Attributes: One or more user-defined key/value pairs to be added to the stack attributes.
(string) --
(string) --
:type CloudWatchLogsConfiguration: dict
:param CloudWatchLogsConfiguration: Specifies CloudWatch Logs configuration options for the layer. For more information, see CloudWatchLogsLogStream .
Enabled (boolean) --Whether CloudWatch Logs is enabled for a layer.
LogStreams (list) --A list of configuration options for CloudWatch Logs.
(dict) --Describes the Amazon CloudWatch logs configuration for a layer. For detailed information about members of this data type, see the CloudWatch Logs Agent Reference .
LogGroupName (string) --Specifies the destination log group. A log group is created automatically if it doesn't already exist. Log group names can be between 1 and 512 characters long. Allowed characters include a-z, A-Z, 0-9, '_' (underscore), '-' (hyphen), '/' (forward slash), and '.' (period).
DatetimeFormat (string) --Specifies how the time stamp is extracted from logs. For more information, see the CloudWatch Logs Agent Reference .
TimeZone (string) --Specifies the time zone of log event time stamps.
File (string) --Specifies log files that you want to push to CloudWatch Logs.
File can point to a specific file or multiple files (by using wild card characters such as /var/log/system.log* ). Only the latest file is pushed to CloudWatch Logs, based on file modification time. We recommend that you use wild card characters to specify a series of files of the same type, such as access_log.2014-06-01-01 , access_log.2014-06-01-02 , and so on by using a pattern like access_log.* . Don't use a wildcard to match multiple file types, such as access_log_80 and access_log_443 . To specify multiple, different file types, add another log stream entry to the configuration file, so that each log file type is stored in a different log group.
Zipped files are not supported.
FileFingerprintLines (string) --Specifies the range of lines for identifying a file. The valid values are one number, or two dash-delimited numbers, such as '1', '2-5'. The default value is '1', meaning the first line is used to calculate the fingerprint. Fingerprint lines are not sent to CloudWatch Logs unless all specified lines are available.
MultiLineStartPattern (string) --Specifies the pattern for identifying the start of a log message.
InitialPosition (string) --Specifies where to start to read data (start_of_file or end_of_file). The default is start_of_file. This setting is only used if there is no state persisted for that log stream.
Encoding (string) --Specifies the encoding of the log file so that the file can be read correctly. The default is utf_8 . Encodings supported by Python codecs.decode() can be used here.
BufferDuration (integer) --Specifies the time duration for the batching of log events. The minimum value is 5000ms and default value is 5000ms.
BatchCount (integer) --Specifies the max number of log events in a batch, up to 10000. The default value is 1000.
BatchSize (integer) --Specifies the maximum size of log events in a batch, in bytes, up to 1048576 bytes. The default value is 32768 bytes. This size is calculated as the sum of all event messages in UTF-8, plus 26 bytes for each log event.
:type CustomInstanceProfileArn: string
:param CustomInstanceProfileArn: The ARN of an IAM profile to be used for all of the layer's EC2 instances. For more information about IAM ARNs, see Using Identifiers .
:type CustomJson: string
:param CustomJson: A JSON-formatted string containing custom stack configuration and deployment attributes to be installed on the layer's instances. For more information, see Using Custom JSON .
:type CustomSecurityGroupIds: list
:param CustomSecurityGroupIds: An array containing the layer's custom security group IDs.
(string) --
:type Packages: list
:param Packages: An array of Package objects that describe the layer's packages.
(string) --
:type VolumeConfigurations: list
:param VolumeConfigurations: A VolumeConfigurations object that describes the layer's Amazon EBS volumes.
(dict) --Describes an Amazon EBS volume configuration.
MountPoint (string) -- [REQUIRED]The volume mount point. For example '/dev/sdh'.
RaidLevel (integer) --The volume RAID level .
NumberOfDisks (integer) -- [REQUIRED]The number of disks in the volume.
Size (integer) -- [REQUIRED]The volume size.
VolumeType (string) --The volume type:
standard - Magnetic
io1 - Provisioned IOPS (SSD)
gp2 - General Purpose (SSD)
Iops (integer) --For PIOPS volumes, the IOPS per disk.
:type EnableAutoHealing: boolean
:param EnableAutoHealing: Whether to disable auto healing for the layer.
:type AutoAssignElasticIps: boolean
:param AutoAssignElasticIps: Whether to automatically assign an Elastic IP address to the layer's instances. For more information, see How to Edit a Layer .
:type AutoAssignPublicIps: boolean
:param AutoAssignPublicIps: For stacks that are running in a VPC, whether to automatically assign a public IP address to the layer's instances. For more information, see How to Edit a Layer .
:type CustomRecipes: dict
:param CustomRecipes: A LayerCustomRecipes object that specifies the layer's custom recipes.
Setup (list) --An array of custom recipe names to be run following a setup event.
(string) --
Configure (list) --An array of custom recipe names to be run following a configure event.
(string) --
Deploy (list) --An array of custom recipe names to be run following a deploy event.
(string) --
Undeploy (list) --An array of custom recipe names to be run following a undeploy event.
(string) --
Shutdown (list) --An array of custom recipe names to be run following a shutdown event.
(string) --
:type InstallUpdatesOnBoot: boolean
:param InstallUpdatesOnBoot: Whether to install operating system and package updates when the instance boots. The default value is true . To control when updates are installed, set this value to false . You must then update your instances manually by using CreateDeployment to run the update_dependencies stack command or manually running yum (Amazon Linux) or apt-get (Ubuntu) on the instances.
Note
We strongly recommend using the default value of true , to ensure that your instances have the latest security updates.
:type UseEbsOptimizedInstances: boolean
:param UseEbsOptimizedInstances: Whether to use Amazon EBS-optimized instances.
:type LifecycleEventConfiguration: dict
:param LifecycleEventConfiguration:
Shutdown (dict) --A ShutdownEventConfiguration object that specifies the Shutdown event configuration.
ExecutionTimeout (integer) --The time, in seconds, that AWS OpsWorks Stacks will wait after triggering a Shutdown event before shutting down an instance.
DelayUntilElbConnectionsDrained (boolean) --Whether to enable Elastic Load Balancing connection draining. For more information, see Connection Draining | [
"Updates",
"a",
"specified",
"layer",
".",
"See",
"also",
":",
"AWS",
"API",
"Documentation",
":",
"example",
":",
"response",
"=",
"client",
".",
"update_layer",
"(",
"LayerId",
"=",
"string",
"Name",
"=",
"string",
"Shortname",
"=",
"string",
"Attributes",... | python | train |
etingof/pysnmpcrypto | pysnmpcrypto/aes.py | https://github.com/etingof/pysnmpcrypto/blob/9b92959f5e2fce833fa220343ca12add3134a77c/pysnmpcrypto/aes.py#L27-L39 | def _cryptography_cipher(key, iv):
"""Build a cryptography AES Cipher object.
:param bytes key: Encryption key
:param bytes iv: Initialization vector
:returns: AES Cipher instance
:rtype: cryptography.hazmat.primitives.ciphers.Cipher
"""
return Cipher(
algorithm=algorithms.AES(key),
mode=modes.CFB(iv),
backend=default_backend()
) | [
"def",
"_cryptography_cipher",
"(",
"key",
",",
"iv",
")",
":",
"return",
"Cipher",
"(",
"algorithm",
"=",
"algorithms",
".",
"AES",
"(",
"key",
")",
",",
"mode",
"=",
"modes",
".",
"CFB",
"(",
"iv",
")",
",",
"backend",
"=",
"default_backend",
"(",
... | Build a cryptography AES Cipher object.
:param bytes key: Encryption key
:param bytes iv: Initialization vector
:returns: AES Cipher instance
:rtype: cryptography.hazmat.primitives.ciphers.Cipher | [
"Build",
"a",
"cryptography",
"AES",
"Cipher",
"object",
"."
] | python | train |
rackerlabs/fastfood | fastfood/utils.py | https://github.com/rackerlabs/fastfood/blob/543970c4cedbb3956e84a7986469fdd7e4ee8fc8/fastfood/utils.py#L49-L60 | def ruby_lines(text):
"""Tidy up lines from a file, honor # comments.
Does not honor ruby block comments (yet).
"""
if isinstance(text, basestring):
text = text.splitlines()
elif not isinstance(text, list):
raise TypeError("text should be a list or a string, not %s"
% type(text))
return [l.strip() for l in text if l.strip() and not
l.strip().startswith('#')] | [
"def",
"ruby_lines",
"(",
"text",
")",
":",
"if",
"isinstance",
"(",
"text",
",",
"basestring",
")",
":",
"text",
"=",
"text",
".",
"splitlines",
"(",
")",
"elif",
"not",
"isinstance",
"(",
"text",
",",
"list",
")",
":",
"raise",
"TypeError",
"(",
"\... | Tidy up lines from a file, honor # comments.
Does not honor ruby block comments (yet). | [
"Tidy",
"up",
"lines",
"from",
"a",
"file",
"honor",
"#",
"comments",
"."
] | python | train |
defunkt/pystache | pystache/parser.py | https://github.com/defunkt/pystache/blob/17a5dfdcd56eb76af731d141de395a7632a905b8/pystache/parser.py#L21-L41 | def parse(template, delimiters=None):
"""
Parse a unicode template string and return a ParsedTemplate instance.
Arguments:
template: a unicode template string.
delimiters: a 2-tuple of delimiters. Defaults to the package default.
Examples:
>>> parsed = parse(u"Hey {{#who}}{{name}}!{{/who}}")
>>> print str(parsed).replace('u', '') # This is a hack to get the test to pass both in Python 2 and 3.
['Hey ', _SectionNode(key='who', index_begin=12, index_end=21, parsed=[_EscapeNode(key='name'), '!'])]
"""
if type(template) is not unicode:
raise Exception("Template is not unicode: %s" % type(template))
parser = _Parser(delimiters)
return parser.parse(template) | [
"def",
"parse",
"(",
"template",
",",
"delimiters",
"=",
"None",
")",
":",
"if",
"type",
"(",
"template",
")",
"is",
"not",
"unicode",
":",
"raise",
"Exception",
"(",
"\"Template is not unicode: %s\"",
"%",
"type",
"(",
"template",
")",
")",
"parser",
"=",... | Parse a unicode template string and return a ParsedTemplate instance.
Arguments:
template: a unicode template string.
delimiters: a 2-tuple of delimiters. Defaults to the package default.
Examples:
>>> parsed = parse(u"Hey {{#who}}{{name}}!{{/who}}")
>>> print str(parsed).replace('u', '') # This is a hack to get the test to pass both in Python 2 and 3.
['Hey ', _SectionNode(key='who', index_begin=12, index_end=21, parsed=[_EscapeNode(key='name'), '!'])] | [
"Parse",
"a",
"unicode",
"template",
"string",
"and",
"return",
"a",
"ParsedTemplate",
"instance",
"."
] | python | train |
vaexio/vaex | packages/vaex-core/vaex/ext/jprops.py | https://github.com/vaexio/vaex/blob/a45b672f8287afca2ada8e36b74b604b9b28dd85/packages/vaex-core/vaex/ext/jprops.py#L33-L53 | def store_properties(fh, props, comment=None, timestamp=True):
"""
Writes properties to the file in Java properties format.
:param fh: a writable file-like object
:param props: a mapping (dict) or iterable of key/value pairs
:param comment: comment to write to the beginning of the file
:param timestamp: boolean indicating whether to write a timestamp comment
"""
if comment is not None:
write_comment(fh, comment)
if timestamp:
write_comment(fh, time.strftime('%a %b %d %H:%M:%S %Z %Y'))
if hasattr(props, 'keys'):
for key in props:
write_property(fh, key, props[key])
else:
for key, value in props:
write_property(fh, key, value) | [
"def",
"store_properties",
"(",
"fh",
",",
"props",
",",
"comment",
"=",
"None",
",",
"timestamp",
"=",
"True",
")",
":",
"if",
"comment",
"is",
"not",
"None",
":",
"write_comment",
"(",
"fh",
",",
"comment",
")",
"if",
"timestamp",
":",
"write_comment",... | Writes properties to the file in Java properties format.
:param fh: a writable file-like object
:param props: a mapping (dict) or iterable of key/value pairs
:param comment: comment to write to the beginning of the file
:param timestamp: boolean indicating whether to write a timestamp comment | [
"Writes",
"properties",
"to",
"the",
"file",
"in",
"Java",
"properties",
"format",
"."
] | python | test |
aio-libs/aiohttp | aiohttp/web_urldispatcher.py | https://github.com/aio-libs/aiohttp/blob/9504fe2affaaff673fa4f3754c1c44221f8ba47d/aiohttp/web_urldispatcher.py#L1036-L1059 | def add_static(self, prefix: str, path: PathLike, *,
name: Optional[str]=None,
expect_handler: Optional[_ExpectHandler]=None,
chunk_size: int=256 * 1024,
show_index: bool=False, follow_symlinks: bool=False,
append_version: bool=False) -> AbstractResource:
"""Add static files view.
prefix - url prefix
path - folder with files
"""
assert prefix.startswith('/')
if prefix.endswith('/'):
prefix = prefix[:-1]
resource = StaticResource(prefix, path,
name=name,
expect_handler=expect_handler,
chunk_size=chunk_size,
show_index=show_index,
follow_symlinks=follow_symlinks,
append_version=append_version)
self.register_resource(resource)
return resource | [
"def",
"add_static",
"(",
"self",
",",
"prefix",
":",
"str",
",",
"path",
":",
"PathLike",
",",
"*",
",",
"name",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"expect_handler",
":",
"Optional",
"[",
"_ExpectHandler",
"]",
"=",
"None",
",",
"ch... | Add static files view.
prefix - url prefix
path - folder with files | [
"Add",
"static",
"files",
"view",
"."
] | python | train |
ulf1/oxyba | oxyba/rand_imancon.py | https://github.com/ulf1/oxyba/blob/b3043116050de275124365cb11e7df91fb40169d/oxyba/rand_imancon.py#L2-L59 | def rand_imancon(X, rho):
"""Iman-Conover Method to generate random ordinal variables
(Implementation adopted from Ekstrom, 2005)
x : ndarray
<obs x cols> matrix with "cols" ordinal variables
that are uncorrelated.
rho : ndarray
Spearman Rank Correlation Matrix
Links
* Iman, R.L., Conover, W.J., 1982. A distribution-free approach to
inducing rank correlation among input variables. Communications
in Statistics - Simulation and Computation 11, 311–334.
https://doi.org/10.1080/03610918208812265
* Ekstrom, P.-A., n.d. A Simulation Toolbox for Sensitivity Analysis 57.
http://ecolego.facilia.se/ecolego/files/Eikos_thesis.pdf
"""
import numpy as np
import scipy.stats as sstat
import scipy.special as sspec
# data prep
n, d = X.shape
# Ordering
T = np.corrcoef(X, rowvar=0) # T
Q = np.linalg.cholesky(T) # Q
invQ = np.linalg.inv(Q) # inv(Q)
P = np.linalg.cholesky(rho) # P
S = np.dot(invQ, P) # S=P*inv(Q)
# get ranks of 'X'
rnks = np.nan * np.empty((n, d))
for k in range(0, d):
rnks[:, k] = sstat.rankdata(X[:, k], method='average')
# create Rank Scores
rnkscore = -np.sqrt(2.0) * sspec.erfcinv(2.0 * rnks / (n + 1))
# the 'Y' variables have the same correlation matrix
Y = np.dot(rnkscore, S.T)
# get ranks of 'Y'
rnks = np.nan * np.empty((n, d))
for k in range(0, d):
rnks[:, k] = sstat.rankdata(Y[:, k], method='average')
rnks = rnks.astype(int)
# Sort X what will decorrelated X
X = np.sort(X, axis=0)
# Rerank X
Z = np.nan * np.empty((n, d))
for k in range(0, d):
Z[:, k] = X[rnks[:, k] - 1, k]
# done
return Z | [
"def",
"rand_imancon",
"(",
"X",
",",
"rho",
")",
":",
"import",
"numpy",
"as",
"np",
"import",
"scipy",
".",
"stats",
"as",
"sstat",
"import",
"scipy",
".",
"special",
"as",
"sspec",
"# data prep",
"n",
",",
"d",
"=",
"X",
".",
"shape",
"# Ordering",
... | Iman-Conover Method to generate random ordinal variables
(Implementation adopted from Ekstrom, 2005)
x : ndarray
<obs x cols> matrix with "cols" ordinal variables
that are uncorrelated.
rho : ndarray
Spearman Rank Correlation Matrix
Links
* Iman, R.L., Conover, W.J., 1982. A distribution-free approach to
inducing rank correlation among input variables. Communications
in Statistics - Simulation and Computation 11, 311–334.
https://doi.org/10.1080/03610918208812265
* Ekstrom, P.-A., n.d. A Simulation Toolbox for Sensitivity Analysis 57.
http://ecolego.facilia.se/ecolego/files/Eikos_thesis.pdf | [
"Iman",
"-",
"Conover",
"Method",
"to",
"generate",
"random",
"ordinal",
"variables",
"(",
"Implementation",
"adopted",
"from",
"Ekstrom",
"2005",
")"
] | python | train |
iqbal-lab-org/cluster_vcf_records | cluster_vcf_records/vcf_record_cluster.py | https://github.com/iqbal-lab-org/cluster_vcf_records/blob/0db26af36b6da97a7361364457d2152dc756055c/cluster_vcf_records/vcf_record_cluster.py#L140-L156 | def make_simple_merged_vcf_with_no_combinations(self, ref_seq):
'''Does a simple merging of all variants in this cluster.
Assumes one ALT in each variant. Uses the ALT for each
variant, making one new vcf_record that has all the variants
put together'''
if len(self) <= 1:
return
merged_vcf_record = self.vcf_records[0]
for i in range(1, len(self.vcf_records), 1):
if self.vcf_records[i].intersects(merged_vcf_record):
return
else:
merged_vcf_record = merged_vcf_record.merge(self.vcf_records[i], ref_seq)
self.vcf_records = [merged_vcf_record] | [
"def",
"make_simple_merged_vcf_with_no_combinations",
"(",
"self",
",",
"ref_seq",
")",
":",
"if",
"len",
"(",
"self",
")",
"<=",
"1",
":",
"return",
"merged_vcf_record",
"=",
"self",
".",
"vcf_records",
"[",
"0",
"]",
"for",
"i",
"in",
"range",
"(",
"1",
... | Does a simple merging of all variants in this cluster.
Assumes one ALT in each variant. Uses the ALT for each
variant, making one new vcf_record that has all the variants
put together | [
"Does",
"a",
"simple",
"merging",
"of",
"all",
"variants",
"in",
"this",
"cluster",
".",
"Assumes",
"one",
"ALT",
"in",
"each",
"variant",
".",
"Uses",
"the",
"ALT",
"for",
"each",
"variant",
"making",
"one",
"new",
"vcf_record",
"that",
"has",
"all",
"t... | python | train |
GNS3/gns3-server | gns3server/compute/virtualbox/virtualbox_vm.py | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/virtualbox/virtualbox_vm.py#L627-L647 | def set_vmname(self, vmname):
"""
Renames the VirtualBox VM.
:param vmname: VirtualBox VM name
"""
if vmname == self._vmname:
return
if self.linked_clone:
if self.status == "started":
raise VirtualBoxError("You can't change the name of running VM {}".format(self._name))
# We can't rename a VM to name that already exists
vms = yield from self.manager.list_vms(allow_clone=True)
if vmname in [vm["vmname"] for vm in vms]:
raise VirtualBoxError("You can't change the name to {} it's already use in VirtualBox".format(vmname))
yield from self._modify_vm('--name "{}"'.format(vmname))
log.info("VirtualBox VM '{name}' [{id}] has set the VM name to '{vmname}'".format(name=self.name, id=self.id, vmname=vmname))
self._vmname = vmname | [
"def",
"set_vmname",
"(",
"self",
",",
"vmname",
")",
":",
"if",
"vmname",
"==",
"self",
".",
"_vmname",
":",
"return",
"if",
"self",
".",
"linked_clone",
":",
"if",
"self",
".",
"status",
"==",
"\"started\"",
":",
"raise",
"VirtualBoxError",
"(",
"\"You... | Renames the VirtualBox VM.
:param vmname: VirtualBox VM name | [
"Renames",
"the",
"VirtualBox",
"VM",
"."
] | python | train |
apache/incubator-mxnet | python/mxnet/profiler.py | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/profiler.py#L70-L86 | def profiler_set_config(mode='symbolic', filename='profile.json'):
"""Set up the configure of profiler (Deprecated).
Parameters
----------
mode : string, optional
Indicates whether to enable the profiler, can
be 'symbolic', or 'all'. Defaults to `symbolic`.
filename : string, optional
The name of output trace file. Defaults to 'profile.json'.
"""
warnings.warn('profiler.profiler_set_config() is deprecated. '
'Please use profiler.set_config() instead')
keys = c_str_array([key for key in ["profile_" + mode, "filename"]])
values = c_str_array([str(val) for val in [True, filename]])
assert len(keys) == len(values)
check_call(_LIB.MXSetProcessProfilerConfig(len(keys), keys, values, profiler_kvstore_handle)) | [
"def",
"profiler_set_config",
"(",
"mode",
"=",
"'symbolic'",
",",
"filename",
"=",
"'profile.json'",
")",
":",
"warnings",
".",
"warn",
"(",
"'profiler.profiler_set_config() is deprecated. '",
"'Please use profiler.set_config() instead'",
")",
"keys",
"=",
"c_str_array",
... | Set up the configure of profiler (Deprecated).
Parameters
----------
mode : string, optional
Indicates whether to enable the profiler, can
be 'symbolic', or 'all'. Defaults to `symbolic`.
filename : string, optional
The name of output trace file. Defaults to 'profile.json'. | [
"Set",
"up",
"the",
"configure",
"of",
"profiler",
"(",
"Deprecated",
")",
"."
] | python | train |
sorgerlab/indra | indra/tools/assemble_corpus.py | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/tools/assemble_corpus.py#L962-L1039 | def filter_by_db_refs(stmts_in, namespace, values, policy, **kwargs):
"""Filter to Statements whose agents are grounded to a matching entry.
Statements are filtered so that the db_refs entry (of the given namespace)
of their Agent/Concept arguments take a value in the given list of values.
Parameters
----------
stmts_in : list[indra.statements.Statement]
A list of Statements to filter.
namespace : str
The namespace in db_refs to which the filter should apply.
values : list[str]
A list of values in the given namespace to which the filter should
apply.
policy : str
The policy to apply when filtering for the db_refs. "one": keep
Statements that contain at least one of the list of db_refs and
possibly others not in the list "all": keep Statements that only
contain db_refs given in the list
save : Optional[str]
The name of a pickle file to save the results (stmts_out) into.
invert : Optional[bool]
If True, the Statements that do not match according to the policy
are returned. Default: False
match_suffix : Optional[bool]
If True, the suffix of the db_refs entry is matches agains the list
of entries
Returns
-------
stmts_out : list[indra.statements.Statement]
A list of filtered Statements.
"""
invert = kwargs.get('invert', False)
match_suffix = kwargs.get('match_suffix', False)
if policy not in ('one', 'all'):
logger.error('Policy %s is invalid, not applying filter.' % policy)
return
else:
name_str = ', '.join(values)
rev_mod = 'not ' if invert else ''
logger.info(('Filtering %d statements for those with %s agents %s'
'grounded to: %s in the %s namespace...') %
(len(stmts_in), policy, rev_mod, name_str, namespace))
def meets_criterion(agent):
if namespace not in agent.db_refs:
return False
entry = agent.db_refs[namespace]
if isinstance(entry, list):
entry = entry[0][0]
ret = False
# Match suffix or entire entry
if match_suffix:
if any([entry.endswith(e) for e in values]):
ret = True
else:
if entry in values:
ret = True
# Invert if needed
if invert:
return not ret
else:
return ret
enough = all if policy == 'all' else any
stmts_out = [s for s in stmts_in
if enough([meets_criterion(ag) for ag in s.agent_list()
if ag is not None])]
logger.info('%d Statements after filter...' % len(stmts_out))
dump_pkl = kwargs.get('save')
if dump_pkl:
dump_statements(stmts_out, dump_pkl)
return stmts_out | [
"def",
"filter_by_db_refs",
"(",
"stmts_in",
",",
"namespace",
",",
"values",
",",
"policy",
",",
"*",
"*",
"kwargs",
")",
":",
"invert",
"=",
"kwargs",
".",
"get",
"(",
"'invert'",
",",
"False",
")",
"match_suffix",
"=",
"kwargs",
".",
"get",
"(",
"'m... | Filter to Statements whose agents are grounded to a matching entry.
Statements are filtered so that the db_refs entry (of the given namespace)
of their Agent/Concept arguments take a value in the given list of values.
Parameters
----------
stmts_in : list[indra.statements.Statement]
A list of Statements to filter.
namespace : str
The namespace in db_refs to which the filter should apply.
values : list[str]
A list of values in the given namespace to which the filter should
apply.
policy : str
The policy to apply when filtering for the db_refs. "one": keep
Statements that contain at least one of the list of db_refs and
possibly others not in the list "all": keep Statements that only
contain db_refs given in the list
save : Optional[str]
The name of a pickle file to save the results (stmts_out) into.
invert : Optional[bool]
If True, the Statements that do not match according to the policy
are returned. Default: False
match_suffix : Optional[bool]
If True, the suffix of the db_refs entry is matches agains the list
of entries
Returns
-------
stmts_out : list[indra.statements.Statement]
A list of filtered Statements. | [
"Filter",
"to",
"Statements",
"whose",
"agents",
"are",
"grounded",
"to",
"a",
"matching",
"entry",
"."
] | python | train |
edx/edx-django-extensions | edx_management_commands/management_commands/management/commands/manage_user.py | https://github.com/edx/edx-django-extensions/blob/35bbf7f95453c0e2c07acf3539722a92e7b6f548/edx_management_commands/management_commands/management/commands/manage_user.py#L26-L38 | def _maybe_update(self, user, attribute, new_value):
"""
DRY helper. If the specified attribute of the user differs from the
specified value, it will be updated.
"""
old_value = getattr(user, attribute)
if new_value != old_value:
self.stderr.write(
_('Setting {attribute} for user "{username}" to "{new_value}"').format(
attribute=attribute, username=user.username, new_value=new_value
)
)
setattr(user, attribute, new_value) | [
"def",
"_maybe_update",
"(",
"self",
",",
"user",
",",
"attribute",
",",
"new_value",
")",
":",
"old_value",
"=",
"getattr",
"(",
"user",
",",
"attribute",
")",
"if",
"new_value",
"!=",
"old_value",
":",
"self",
".",
"stderr",
".",
"write",
"(",
"_",
"... | DRY helper. If the specified attribute of the user differs from the
specified value, it will be updated. | [
"DRY",
"helper",
".",
"If",
"the",
"specified",
"attribute",
"of",
"the",
"user",
"differs",
"from",
"the",
"specified",
"value",
"it",
"will",
"be",
"updated",
"."
] | python | train |
pdkit/pdkit | pdkit/tremor_processor.py | https://github.com/pdkit/pdkit/blob/c7120263da2071bb139815fbdb56ca77b544f340/pdkit/tremor_processor.py#L192-L217 | def approximate_entropy(self, x, m=None, r=None):
"""
As in tsfresh \
`approximate_entropy <https://github.com/blue-yonder/tsfresh/blob/master/tsfresh/feature_extraction/\
feature_calculators.py#L1601>`_
Implements a `vectorized approximate entropy algorithm <https://en.wikipedia.org/wiki/Approximate_entropy>`_
For short time-series this method is highly dependent on the parameters,
but should be stable for N > 2000, see :cite:`Yentes2013`. Other shortcomings and alternatives discussed in \
:cite:`Richman2000`
:param x: the time series to calculate the feature of
:type x: pandas.Series
:param m: Length of compared run of data
:type m: int
:param r: Filtering level, must be positive
:type r: float
:return: Approximate entropy
:rtype: float
"""
if m is None or r is None:
m = 2
r = 0.3
entropy = feature_calculators.approximate_entropy(x, m, r)
logging.debug("approximate entropy by tsfresh calculated")
return entropy | [
"def",
"approximate_entropy",
"(",
"self",
",",
"x",
",",
"m",
"=",
"None",
",",
"r",
"=",
"None",
")",
":",
"if",
"m",
"is",
"None",
"or",
"r",
"is",
"None",
":",
"m",
"=",
"2",
"r",
"=",
"0.3",
"entropy",
"=",
"feature_calculators",
".",
"appro... | As in tsfresh \
`approximate_entropy <https://github.com/blue-yonder/tsfresh/blob/master/tsfresh/feature_extraction/\
feature_calculators.py#L1601>`_
Implements a `vectorized approximate entropy algorithm <https://en.wikipedia.org/wiki/Approximate_entropy>`_
For short time-series this method is highly dependent on the parameters,
but should be stable for N > 2000, see :cite:`Yentes2013`. Other shortcomings and alternatives discussed in \
:cite:`Richman2000`
:param x: the time series to calculate the feature of
:type x: pandas.Series
:param m: Length of compared run of data
:type m: int
:param r: Filtering level, must be positive
:type r: float
:return: Approximate entropy
:rtype: float | [
"As",
"in",
"tsfresh",
"\\",
"approximate_entropy",
"<https",
":",
"//",
"github",
".",
"com",
"/",
"blue",
"-",
"yonder",
"/",
"tsfresh",
"/",
"blob",
"/",
"master",
"/",
"tsfresh",
"/",
"feature_extraction",
"/",
"\\",
"feature_calculators",
".",
"py#L1601... | python | train |
oscarbranson/latools | latools/D_obj.py | https://github.com/oscarbranson/latools/blob/cd25a650cfee318152f234d992708511f7047fbe/latools/D_obj.py#L593-L606 | def ablation_times(self):
"""
Function for calculating the ablation time for each
ablation.
Returns
-------
dict of times for each ablation.
"""
ats = {}
for n in np.arange(self.n) + 1:
t = self.Time[self.ns == n]
ats[n - 1] = t.max() - t.min()
return ats | [
"def",
"ablation_times",
"(",
"self",
")",
":",
"ats",
"=",
"{",
"}",
"for",
"n",
"in",
"np",
".",
"arange",
"(",
"self",
".",
"n",
")",
"+",
"1",
":",
"t",
"=",
"self",
".",
"Time",
"[",
"self",
".",
"ns",
"==",
"n",
"]",
"ats",
"[",
"n",
... | Function for calculating the ablation time for each
ablation.
Returns
-------
dict of times for each ablation. | [
"Function",
"for",
"calculating",
"the",
"ablation",
"time",
"for",
"each",
"ablation",
"."
] | python | test |
ARMmbed/icetea | icetea_lib/ResourceProvider/ResourceConfig.py | https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/ResourceProvider/ResourceConfig.py#L193-L204 | def __replace_base_variables(text, req_len, idx):
"""
Replace i and n in text with index+1 and req_len.
:param text: base text to modify
:param req_len: amount of required resources
:param idx: index of resource we are working on
:return: modified string
"""
return text \
.replace("{i}", str(idx + 1)) \
.replace("{n}", str(req_len)) | [
"def",
"__replace_base_variables",
"(",
"text",
",",
"req_len",
",",
"idx",
")",
":",
"return",
"text",
".",
"replace",
"(",
"\"{i}\"",
",",
"str",
"(",
"idx",
"+",
"1",
")",
")",
".",
"replace",
"(",
"\"{n}\"",
",",
"str",
"(",
"req_len",
")",
")"
] | Replace i and n in text with index+1 and req_len.
:param text: base text to modify
:param req_len: amount of required resources
:param idx: index of resource we are working on
:return: modified string | [
"Replace",
"i",
"and",
"n",
"in",
"text",
"with",
"index",
"+",
"1",
"and",
"req_len",
"."
] | python | train |
AltSchool/dynamic-rest | dynamic_rest/viewsets.py | https://github.com/AltSchool/dynamic-rest/blob/5b0338c3dd8bc638d60c3bb92645857c5b89c920/dynamic_rest/viewsets.py#L178-L205 | def _extract_object_params(self, name):
"""
Extract object params, return as dict
"""
params = self.request.query_params.lists()
params_map = {}
prefix = name[:-1]
offset = len(prefix)
for name, value in params:
if name.startswith(prefix):
if name.endswith('}'):
name = name[offset:-1]
elif name.endswith('}[]'):
# strip off trailing []
# this fixes an Ember queryparams issue
name = name[offset:-3]
else:
# malformed argument like:
# filter{foo=bar
raise exceptions.ParseError(
'"%s" is not a well-formed filter key.' % name
)
else:
continue
params_map[name] = value
return params_map | [
"def",
"_extract_object_params",
"(",
"self",
",",
"name",
")",
":",
"params",
"=",
"self",
".",
"request",
".",
"query_params",
".",
"lists",
"(",
")",
"params_map",
"=",
"{",
"}",
"prefix",
"=",
"name",
"[",
":",
"-",
"1",
"]",
"offset",
"=",
"len"... | Extract object params, return as dict | [
"Extract",
"object",
"params",
"return",
"as",
"dict"
] | python | train |
fedora-python/pyp2rpm | pyp2rpm/dependency_parser.py | https://github.com/fedora-python/pyp2rpm/blob/853eb3d226689a5ccdcdb9358b1a3394fafbd2b5/pyp2rpm/dependency_parser.py#L47-L72 | def deps_from_pyp_format(requires, runtime=True):
"""Parses dependencies extracted from setup.py.
Args:
requires: list of dependencies as written in setup.py of the package.
runtime: are the dependencies runtime (True) or build time (False)?
Returns:
List of semi-SPECFILE dependencies (see dependency_to_rpm for format).
"""
parsed = []
logger.debug("Dependencies from setup.py: {0} runtime: {1}.".format(
requires, runtime))
for req in requires:
try:
parsed.append(Requirement.parse(req))
except ValueError:
logger.warn("Unparsable dependency {0}.".format(req),
exc_info=True)
in_rpm_format = []
for dep in parsed:
in_rpm_format.extend(dependency_to_rpm(dep, runtime))
logger.debug("Dependencies from setup.py in rpm format: {0}.".format(
in_rpm_format))
return in_rpm_format | [
"def",
"deps_from_pyp_format",
"(",
"requires",
",",
"runtime",
"=",
"True",
")",
":",
"parsed",
"=",
"[",
"]",
"logger",
".",
"debug",
"(",
"\"Dependencies from setup.py: {0} runtime: {1}.\"",
".",
"format",
"(",
"requires",
",",
"runtime",
")",
")",
"for",
"... | Parses dependencies extracted from setup.py.
Args:
requires: list of dependencies as written in setup.py of the package.
runtime: are the dependencies runtime (True) or build time (False)?
Returns:
List of semi-SPECFILE dependencies (see dependency_to_rpm for format). | [
"Parses",
"dependencies",
"extracted",
"from",
"setup",
".",
"py",
".",
"Args",
":",
"requires",
":",
"list",
"of",
"dependencies",
"as",
"written",
"in",
"setup",
".",
"py",
"of",
"the",
"package",
".",
"runtime",
":",
"are",
"the",
"dependencies",
"runti... | python | train |
textmagic/textmagic-rest-python | textmagic/rest/models/user.py | https://github.com/textmagic/textmagic-rest-python/blob/15d679cb985b88b1cb2153ef2ba80d9749f9e281/textmagic/rest/models/user.py#L61-L75 | def update(self, **kwargs):
"""
Update an current User via a PUT request.
Returns True if success.
:Example:
client.user.update(firstName="John", lastName="Doe", company="TextMagic")
:param str firstName: User first name. Required.
:param str lastName: User last name. Required.
:param str company: User company. Required.
"""
response, instance = self.request("PUT", self.uri, data=kwargs)
return response.status == 201 | [
"def",
"update",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"response",
",",
"instance",
"=",
"self",
".",
"request",
"(",
"\"PUT\"",
",",
"self",
".",
"uri",
",",
"data",
"=",
"kwargs",
")",
"return",
"response",
".",
"status",
"==",
"201"
] | Update an current User via a PUT request.
Returns True if success.
:Example:
client.user.update(firstName="John", lastName="Doe", company="TextMagic")
:param str firstName: User first name. Required.
:param str lastName: User last name. Required.
:param str company: User company. Required. | [
"Update",
"an",
"current",
"User",
"via",
"a",
"PUT",
"request",
".",
"Returns",
"True",
"if",
"success",
"."
] | python | train |
IntegralDefense/critsapi | critsapi/critsdbapi.py | https://github.com/IntegralDefense/critsapi/blob/e770bd81e124eaaeb5f1134ba95f4a35ff345c5a/critsapi/critsdbapi.py#L134-L171 | def add_embedded_campaign(self, id, collection, campaign, confidence,
analyst, date, description):
"""
Adds an embedded campaign to the TLO.
Args:
id: the CRITs object id of the TLO
collection: The db collection. See main class documentation.
campaign: The campaign to assign.
confidence: The campaign confidence
analyst: The analyst making the assignment
date: The date of the assignment
description: A description
Returns:
The resulting mongo object
"""
if type(id) is not ObjectId:
id = ObjectId(id)
# TODO: Make sure the object does not already have the campaign
# Return if it does. Add it if it doesn't
obj = getattr(self.db, collection)
result = obj.find({'_id': id, 'campaign.name': campaign})
if result.count() > 0:
return
else:
log.debug('Adding campaign to set: {}'.format(campaign))
campaign_obj = {
'analyst': analyst,
'confidence': confidence,
'date': date,
'description': description,
'name': campaign
}
result = obj.update(
{'_id': id},
{'$push': {'campaign': campaign_obj}}
)
return result | [
"def",
"add_embedded_campaign",
"(",
"self",
",",
"id",
",",
"collection",
",",
"campaign",
",",
"confidence",
",",
"analyst",
",",
"date",
",",
"description",
")",
":",
"if",
"type",
"(",
"id",
")",
"is",
"not",
"ObjectId",
":",
"id",
"=",
"ObjectId",
... | Adds an embedded campaign to the TLO.
Args:
id: the CRITs object id of the TLO
collection: The db collection. See main class documentation.
campaign: The campaign to assign.
confidence: The campaign confidence
analyst: The analyst making the assignment
date: The date of the assignment
description: A description
Returns:
The resulting mongo object | [
"Adds",
"an",
"embedded",
"campaign",
"to",
"the",
"TLO",
"."
] | python | train |
log2timeline/dfvfs | dfvfs/volume/volume_system.py | https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/volume/volume_system.py#L59-L74 | def _AddAttribute(self, attribute):
"""Adds an attribute.
Args:
attribute (VolumeAttribute): a volume attribute.
Raises:
KeyError: if volume attribute is already set for the corresponding volume
attribute identifier.
"""
if attribute.identifier in self._attributes:
raise KeyError((
'Volume attribute object already set for volume attribute '
'identifier: {0:s}.').format(attribute.identifier))
self._attributes[attribute.identifier] = attribute | [
"def",
"_AddAttribute",
"(",
"self",
",",
"attribute",
")",
":",
"if",
"attribute",
".",
"identifier",
"in",
"self",
".",
"_attributes",
":",
"raise",
"KeyError",
"(",
"(",
"'Volume attribute object already set for volume attribute '",
"'identifier: {0:s}.'",
")",
"."... | Adds an attribute.
Args:
attribute (VolumeAttribute): a volume attribute.
Raises:
KeyError: if volume attribute is already set for the corresponding volume
attribute identifier. | [
"Adds",
"an",
"attribute",
"."
] | python | train |
secdev/scapy | scapy/arch/windows/__init__.py | https://github.com/secdev/scapy/blob/3ffe757c184017dd46464593a8f80f85abc1e79a/scapy/arch/windows/__init__.py#L174-L183 | def _exec_cmd(command):
"""Call a CMD command and return the output and returncode"""
proc = sp.Popen(command,
stdout=sp.PIPE,
shell=True)
if six.PY2:
res = proc.communicate()[0]
else:
res = proc.communicate(timeout=5)[0]
return res, proc.returncode | [
"def",
"_exec_cmd",
"(",
"command",
")",
":",
"proc",
"=",
"sp",
".",
"Popen",
"(",
"command",
",",
"stdout",
"=",
"sp",
".",
"PIPE",
",",
"shell",
"=",
"True",
")",
"if",
"six",
".",
"PY2",
":",
"res",
"=",
"proc",
".",
"communicate",
"(",
")",
... | Call a CMD command and return the output and returncode | [
"Call",
"a",
"CMD",
"command",
"and",
"return",
"the",
"output",
"and",
"returncode"
] | python | train |
fchauvel/MAD | mad/parsing.py | https://github.com/fchauvel/MAD/blob/806d5174848b1a502e5c683894995602478c448b/mad/parsing.py#L243-L253 | def p_operation_list(p):
"""
operation_list : define_operation operation_list
| define_operation
"""
if len(p) == 3:
p[0] = p[1] + p[2]
elif len(p) == 2:
p[0] = p[1]
else:
raise RuntimeError("Invalid production rules 'p_operation_list'") | [
"def",
"p_operation_list",
"(",
"p",
")",
":",
"if",
"len",
"(",
"p",
")",
"==",
"3",
":",
"p",
"[",
"0",
"]",
"=",
"p",
"[",
"1",
"]",
"+",
"p",
"[",
"2",
"]",
"elif",
"len",
"(",
"p",
")",
"==",
"2",
":",
"p",
"[",
"0",
"]",
"=",
"p... | operation_list : define_operation operation_list
| define_operation | [
"operation_list",
":",
"define_operation",
"operation_list",
"|",
"define_operation"
] | python | train |
samstav/requests-chef | requests_chef/mixlib_auth.py | https://github.com/samstav/requests-chef/blob/a0bf013b925abd0cf76eeaf6300cf32659632773/requests_chef/mixlib_auth.py#L38-L48 | def digester(data):
"""Create SHA-1 hash, get digest, b64 encode, split every 60 char."""
if not isinstance(data, six.binary_type):
data = data.encode('utf_8')
hashof = hashlib.sha1(data).digest()
encoded_hash = base64.b64encode(hashof)
if not isinstance(encoded_hash, six.string_types):
encoded_hash = encoded_hash.decode('utf_8')
chunked = splitter(encoded_hash, chunksize=60)
lines = '\n'.join(chunked)
return lines | [
"def",
"digester",
"(",
"data",
")",
":",
"if",
"not",
"isinstance",
"(",
"data",
",",
"six",
".",
"binary_type",
")",
":",
"data",
"=",
"data",
".",
"encode",
"(",
"'utf_8'",
")",
"hashof",
"=",
"hashlib",
".",
"sha1",
"(",
"data",
")",
".",
"dige... | Create SHA-1 hash, get digest, b64 encode, split every 60 char. | [
"Create",
"SHA",
"-",
"1",
"hash",
"get",
"digest",
"b64",
"encode",
"split",
"every",
"60",
"char",
"."
] | python | train |
sentinel-hub/sentinelhub-py | sentinelhub/aws.py | https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/aws.py#L516-L532 | def get_requests(self):
"""
Creates tile structure and returns list of files for download.
:return: List of download requests and list of empty folders that need to be created
:rtype: (list(download.DownloadRequest), list(str))
"""
self.download_list = []
for data_name in [band for band in self.bands if self._band_exists(band)] + self.metafiles:
if data_name in AwsConstants.TILE_FILES:
url = self.get_url(data_name)
filename = self.get_filepath(data_name)
self.download_list.append(DownloadRequest(url=url, filename=filename,
data_type=AwsConstants.AWS_FILES[data_name],
data_name=data_name))
self.sort_download_list()
return self.download_list, self.folder_list | [
"def",
"get_requests",
"(",
"self",
")",
":",
"self",
".",
"download_list",
"=",
"[",
"]",
"for",
"data_name",
"in",
"[",
"band",
"for",
"band",
"in",
"self",
".",
"bands",
"if",
"self",
".",
"_band_exists",
"(",
"band",
")",
"]",
"+",
"self",
".",
... | Creates tile structure and returns list of files for download.
:return: List of download requests and list of empty folders that need to be created
:rtype: (list(download.DownloadRequest), list(str)) | [
"Creates",
"tile",
"structure",
"and",
"returns",
"list",
"of",
"files",
"for",
"download",
"."
] | python | train |
ZELLMECHANIK-DRESDEN/dclab | dclab/isoelastics/__init__.py | https://github.com/ZELLMECHANIK-DRESDEN/dclab/blob/79002c4356e7020c2ba73ab0a3819c9abd4affec/dclab/isoelastics/__init__.py#L33-L41 | def _add(self, isoel, col1, col2, method, meta):
"""Convenience method for population self._data"""
self._data[method][col1][col2]["isoelastics"] = isoel
self._data[method][col1][col2]["meta"] = meta
# Use advanced slicing to flip the data columns
isoel_flip = [iso[:, [1, 0, 2]] for iso in isoel]
self._data[method][col2][col1]["isoelastics"] = isoel_flip
self._data[method][col2][col1]["meta"] = meta | [
"def",
"_add",
"(",
"self",
",",
"isoel",
",",
"col1",
",",
"col2",
",",
"method",
",",
"meta",
")",
":",
"self",
".",
"_data",
"[",
"method",
"]",
"[",
"col1",
"]",
"[",
"col2",
"]",
"[",
"\"isoelastics\"",
"]",
"=",
"isoel",
"self",
".",
"_data... | Convenience method for population self._data | [
"Convenience",
"method",
"for",
"population",
"self",
".",
"_data"
] | python | train |
mozilla/funfactory | funfactory/cmd.py | https://github.com/mozilla/funfactory/blob/c9bbf1c534eaa15641265bc75fa87afca52b7dd6/funfactory/cmd.py#L225-L230 | def dir_path(dir):
"""with dir_path(path) to change into a directory."""
old_dir = os.getcwd()
os.chdir(dir)
yield
os.chdir(old_dir) | [
"def",
"dir_path",
"(",
"dir",
")",
":",
"old_dir",
"=",
"os",
".",
"getcwd",
"(",
")",
"os",
".",
"chdir",
"(",
"dir",
")",
"yield",
"os",
".",
"chdir",
"(",
"old_dir",
")"
] | with dir_path(path) to change into a directory. | [
"with",
"dir_path",
"(",
"path",
")",
"to",
"change",
"into",
"a",
"directory",
"."
] | python | train |
rikrd/inspire | inspirespeech/htk.py | https://github.com/rikrd/inspire/blob/e281c0266a9a9633f34ab70f9c3ad58036c19b59/inspirespeech/htk.py#L223-L242 | def load_mlf(filename, utf8_normalization=None):
"""Load an HTK Master Label File.
:param filename: The filename of the MLF file.
:param utf8_normalization: None
"""
with codecs.open(filename, 'r', 'string_escape') as f:
data = f.read().decode('utf8')
if utf8_normalization:
data = unicodedata.normalize(utf8_normalization, data)
mlfs = {}
for mlf_object in HTK_MLF_RE.finditer(data):
mlfs[mlf_object.group('file')] = [[Label(**mo.groupdict())
for mo
in HTK_HYPOTHESIS_RE.finditer(recognition_data)]
for recognition_data
in re.split(r'\n///\n', mlf_object.group('hypotheses'))]
return mlfs | [
"def",
"load_mlf",
"(",
"filename",
",",
"utf8_normalization",
"=",
"None",
")",
":",
"with",
"codecs",
".",
"open",
"(",
"filename",
",",
"'r'",
",",
"'string_escape'",
")",
"as",
"f",
":",
"data",
"=",
"f",
".",
"read",
"(",
")",
".",
"decode",
"("... | Load an HTK Master Label File.
:param filename: The filename of the MLF file.
:param utf8_normalization: None | [
"Load",
"an",
"HTK",
"Master",
"Label",
"File",
"."
] | python | train |
openspending/ckanext-budgets | ckanext/budgets/plugin.py | https://github.com/openspending/ckanext-budgets/blob/07dde5a4fdec6b36ceb812b70f0c31cdecb40cfc/ckanext/budgets/plugin.py#L263-L282 | def before_create(self, context, resource):
"""
When triggered the resource which can either be uploaded or linked
to will be parsed and analysed to see if it possibly is a budget
data package resource (checking if all required headers and any of
the recommended headers exist in the csv).
The budget data package specific fields are then appended to the
resource which makes it useful for export the dataset as a budget
data package.
"""
# If the resource is being uploaded we load the uploaded file
# If not we load the provided url
if resource.get('upload', '') == '':
self.data.load(resource['url'])
else:
self.data.load(resource['upload'].file)
self.generate_budget_data_package(resource) | [
"def",
"before_create",
"(",
"self",
",",
"context",
",",
"resource",
")",
":",
"# If the resource is being uploaded we load the uploaded file",
"# If not we load the provided url",
"if",
"resource",
".",
"get",
"(",
"'upload'",
",",
"''",
")",
"==",
"''",
":",
"self"... | When triggered the resource which can either be uploaded or linked
to will be parsed and analysed to see if it possibly is a budget
data package resource (checking if all required headers and any of
the recommended headers exist in the csv).
The budget data package specific fields are then appended to the
resource which makes it useful for export the dataset as a budget
data package. | [
"When",
"triggered",
"the",
"resource",
"which",
"can",
"either",
"be",
"uploaded",
"or",
"linked",
"to",
"will",
"be",
"parsed",
"and",
"analysed",
"to",
"see",
"if",
"it",
"possibly",
"is",
"a",
"budget",
"data",
"package",
"resource",
"(",
"checking",
"... | python | train |
CyberReboot/vent | vent/menus/add.py | https://github.com/CyberReboot/vent/blob/9956a09146b11a89a0eabab3bc7ce8906d124885/vent/menus/add.py#L18-L69 | def create(self):
""" Create widgets for AddForm """
self.add_handlers({'^T': self.quit, '^Q': self.quit})
self.add(npyscreen.Textfield,
value='Add a plugin from a Git repository or an image from a '
'Docker registry.',
editable=False,
color='STANDOUT')
self.add(npyscreen.Textfield,
value='For Git repositories, you can optionally specify a '
'username and password',
editable=False,
color='STANDOUT')
self.add(npyscreen.Textfield,
value='for private repositories.',
editable=False,
color='STANDOUT')
self.add(npyscreen.Textfield,
value='For Docker images, specify a name for referencing the '
'image that is being',
editable=False,
color='STANDOUT')
self.add(npyscreen.Textfield,
value='added and optionally override the tag and/or the '
'registry and specify',
editable=False,
color='STANDOUT')
self.add(npyscreen.Textfield,
value='comma-separated groups this image should belong to.',
editable=False,
color='STANDOUT')
self.nextrely += 1
self.repo = self.add(npyscreen.TitleText,
name='Repository',
value=self.default_repo)
self.user = self.add(npyscreen.TitleText, name='Username')
self.pw = self.add(npyscreen.TitlePassword, name='Password')
self.nextrely += 1
self.add(npyscreen.TitleText,
name='OR',
editable=False,
labelColor='STANDOUT')
self.nextrely += 1
self.image = self.add(npyscreen.TitleText, name='Image')
self.link_name = self.add(npyscreen.TitleText,
name='Name')
self.tag = self.add(npyscreen.TitleText, name='Tag', value='latest')
self.registry = self.add(npyscreen.TitleText,
name='Registry',
value='docker.io')
self.groups = self.add(npyscreen.TitleText, name='Groups')
self.repo.when_value_edited() | [
"def",
"create",
"(",
"self",
")",
":",
"self",
".",
"add_handlers",
"(",
"{",
"'^T'",
":",
"self",
".",
"quit",
",",
"'^Q'",
":",
"self",
".",
"quit",
"}",
")",
"self",
".",
"add",
"(",
"npyscreen",
".",
"Textfield",
",",
"value",
"=",
"'Add a plu... | Create widgets for AddForm | [
"Create",
"widgets",
"for",
"AddForm"
] | python | train |
gangverk/flask-swagger | flask_swagger.py | https://github.com/gangverk/flask-swagger/blob/fa4eb7d4cbebfd30d4033626160881b77ad2b156/flask_swagger.py#L20-L37 | def _find_from_file(full_doc, from_file_keyword):
"""
Finds a line in <full_doc> like
<from_file_keyword> <colon> <path>
and return path
"""
path = None
for line in full_doc.splitlines():
if from_file_keyword in line:
parts = line.strip().split(':')
if len(parts) == 2 and parts[0].strip() == from_file_keyword:
path = parts[1].strip()
break
return path | [
"def",
"_find_from_file",
"(",
"full_doc",
",",
"from_file_keyword",
")",
":",
"path",
"=",
"None",
"for",
"line",
"in",
"full_doc",
".",
"splitlines",
"(",
")",
":",
"if",
"from_file_keyword",
"in",
"line",
":",
"parts",
"=",
"line",
".",
"strip",
"(",
... | Finds a line in <full_doc> like
<from_file_keyword> <colon> <path>
and return path | [
"Finds",
"a",
"line",
"in",
"<full_doc",
">",
"like"
] | python | train |
gem/oq-engine | openquake/calculators/base.py | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/base.py#L931-L956 | def save_gmf_data(dstore, sitecol, gmfs, imts, events=()):
"""
:param dstore: a :class:`openquake.baselib.datastore.DataStore` instance
:param sitecol: a :class:`openquake.hazardlib.site.SiteCollection` instance
:param gmfs: an array of shape (N, E, M)
:param imts: a list of IMT strings
:param events: E event IDs or the empty tuple
"""
if len(events) == 0:
E = gmfs.shape[1]
events = numpy.zeros(E, rupture.events_dt)
events['eid'] = numpy.arange(E, dtype=U64)
dstore['events'] = events
offset = 0
gmfa = get_gmv_data(sitecol.sids, gmfs, events)
dstore['gmf_data/data'] = gmfa
dic = general.group_array(gmfa, 'sid')
lst = []
all_sids = sitecol.complete.sids
for sid in all_sids:
rows = dic.get(sid, ())
n = len(rows)
lst.append((offset, offset + n))
offset += n
dstore['gmf_data/imts'] = ' '.join(imts)
dstore['gmf_data/indices'] = numpy.array(lst, U32) | [
"def",
"save_gmf_data",
"(",
"dstore",
",",
"sitecol",
",",
"gmfs",
",",
"imts",
",",
"events",
"=",
"(",
")",
")",
":",
"if",
"len",
"(",
"events",
")",
"==",
"0",
":",
"E",
"=",
"gmfs",
".",
"shape",
"[",
"1",
"]",
"events",
"=",
"numpy",
"."... | :param dstore: a :class:`openquake.baselib.datastore.DataStore` instance
:param sitecol: a :class:`openquake.hazardlib.site.SiteCollection` instance
:param gmfs: an array of shape (N, E, M)
:param imts: a list of IMT strings
:param events: E event IDs or the empty tuple | [
":",
"param",
"dstore",
":",
"a",
":",
"class",
":",
"openquake",
".",
"baselib",
".",
"datastore",
".",
"DataStore",
"instance",
":",
"param",
"sitecol",
":",
"a",
":",
"class",
":",
"openquake",
".",
"hazardlib",
".",
"site",
".",
"SiteCollection",
"in... | python | train |
quantopian/empyrical | empyrical/stats.py | https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/stats.py#L963-L992 | def _aligned_series(*many_series):
"""
Return a new list of series containing the data in the input series, but
with their indices aligned. NaNs will be filled in for missing values.
Parameters
----------
*many_series
The series to align.
Returns
-------
aligned_series : iterable[array-like]
A new list of series containing the data in the input series, but
with their indices aligned. NaNs will be filled in for missing values.
"""
head = many_series[0]
tail = many_series[1:]
n = len(head)
if (isinstance(head, np.ndarray) and
all(len(s) == n and isinstance(s, np.ndarray) for s in tail)):
# optimization: ndarrays of the same length are already aligned
return many_series
# dataframe has no ``itervalues``
return (
v
for _, v in iteritems(pd.concat(map(_to_pandas, many_series), axis=1))
) | [
"def",
"_aligned_series",
"(",
"*",
"many_series",
")",
":",
"head",
"=",
"many_series",
"[",
"0",
"]",
"tail",
"=",
"many_series",
"[",
"1",
":",
"]",
"n",
"=",
"len",
"(",
"head",
")",
"if",
"(",
"isinstance",
"(",
"head",
",",
"np",
".",
"ndarra... | Return a new list of series containing the data in the input series, but
with their indices aligned. NaNs will be filled in for missing values.
Parameters
----------
*many_series
The series to align.
Returns
-------
aligned_series : iterable[array-like]
A new list of series containing the data in the input series, but
with their indices aligned. NaNs will be filled in for missing values. | [
"Return",
"a",
"new",
"list",
"of",
"series",
"containing",
"the",
"data",
"in",
"the",
"input",
"series",
"but",
"with",
"their",
"indices",
"aligned",
".",
"NaNs",
"will",
"be",
"filled",
"in",
"for",
"missing",
"values",
"."
] | python | train |
marshmallow-code/marshmallow | src/marshmallow/schema.py | https://github.com/marshmallow-code/marshmallow/blob/a6b6c4151f1fbf16f3774d4052ca2bddf6903750/src/marshmallow/schema.py#L986-L1008 | def _bind_field(self, field_name, field_obj):
"""Bind field to the schema, setting any necessary attributes on the
field (e.g. parent and name).
Also set field load_only and dump_only values if field_name was
specified in ``class Meta``.
"""
try:
if field_name in self.load_only:
field_obj.load_only = True
if field_name in self.dump_only:
field_obj.dump_only = True
field_obj._bind_to_schema(field_name, self)
self.on_bind_field(field_name, field_obj)
except TypeError:
# field declared as a class, not an instance
if (isinstance(field_obj, type) and
issubclass(field_obj, base.FieldABC)):
msg = ('Field for "{}" must be declared as a '
'Field instance, not a class. '
'Did you mean "fields.{}()"?'
.format(field_name, field_obj.__name__))
raise TypeError(msg) | [
"def",
"_bind_field",
"(",
"self",
",",
"field_name",
",",
"field_obj",
")",
":",
"try",
":",
"if",
"field_name",
"in",
"self",
".",
"load_only",
":",
"field_obj",
".",
"load_only",
"=",
"True",
"if",
"field_name",
"in",
"self",
".",
"dump_only",
":",
"f... | Bind field to the schema, setting any necessary attributes on the
field (e.g. parent and name).
Also set field load_only and dump_only values if field_name was
specified in ``class Meta``. | [
"Bind",
"field",
"to",
"the",
"schema",
"setting",
"any",
"necessary",
"attributes",
"on",
"the",
"field",
"(",
"e",
".",
"g",
".",
"parent",
"and",
"name",
")",
"."
] | python | train |
StackStorm/pybind | pybind/slxos/v17s_1_02/overlay_policy_map_state/__init__.py | https://github.com/StackStorm/pybind/blob/44c467e71b2b425be63867aba6e6fa28b2cfe7fb/pybind/slxos/v17s_1_02/overlay_policy_map_state/__init__.py#L141-L164 | def _set_active_on(self, v, load=False):
"""
Setter method for active_on, mapped from YANG variable /overlay_policy_map_state/active_on (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_active_on is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_active_on() directly.
YANG Description: Active Interfaces
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=active_on.active_on, is_container='container', presence=False, yang_name="active-on", rest_name="active-on", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'callpoint': u'ssm-overlay-policy-map-applied-intf', u'cli-suppress-show-path': None}}, namespace='urn:brocade.com:mgmt:brocade-ssm-operational', defining_module='brocade-ssm-operational', yang_type='container', is_config=False)
except (TypeError, ValueError):
raise ValueError({
'error-string': """active_on must be of a type compatible with container""",
'defined-type': "container",
'generated-type': """YANGDynClass(base=active_on.active_on, is_container='container', presence=False, yang_name="active-on", rest_name="active-on", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'callpoint': u'ssm-overlay-policy-map-applied-intf', u'cli-suppress-show-path': None}}, namespace='urn:brocade.com:mgmt:brocade-ssm-operational', defining_module='brocade-ssm-operational', yang_type='container', is_config=False)""",
})
self.__active_on = t
if hasattr(self, '_set'):
self._set() | [
"def",
"_set_active_on",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",
"base... | Setter method for active_on, mapped from YANG variable /overlay_policy_map_state/active_on (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_active_on is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_active_on() directly.
YANG Description: Active Interfaces | [
"Setter",
"method",
"for",
"active_on",
"mapped",
"from",
"YANG",
"variable",
"/",
"overlay_policy_map_state",
"/",
"active_on",
"(",
"container",
")",
"If",
"this",
"variable",
"is",
"read",
"-",
"only",
"(",
"config",
":",
"false",
")",
"in",
"the",
"sourc... | python | train |
happyleavesaoc/python-orvibo | orvibo/s20.py | https://github.com/happyleavesaoc/python-orvibo/blob/27210dfe0c44a9e4f2ef4edf2dac221977d7f5c9/orvibo/s20.py#L167-L188 | def _discover_mac(self):
""" Discovers MAC address of device.
Discovery is done by sending a UDP broadcast.
All configured devices reply. The response contains
the MAC address in both needed formats.
Discovery of multiple switches must be done synchronously.
:returns: Tuple of MAC address and reversed MAC address.
"""
mac = None
mac_reversed = None
cmd = MAGIC + DISCOVERY
resp = self._udp_transact(cmd, self._discovery_resp,
broadcast=True,
timeout=DISCOVERY_TIMEOUT)
if resp:
(mac, mac_reversed) = resp
if mac is None:
raise S20Exception("Couldn't discover {}".format(self.host))
return (mac, mac_reversed) | [
"def",
"_discover_mac",
"(",
"self",
")",
":",
"mac",
"=",
"None",
"mac_reversed",
"=",
"None",
"cmd",
"=",
"MAGIC",
"+",
"DISCOVERY",
"resp",
"=",
"self",
".",
"_udp_transact",
"(",
"cmd",
",",
"self",
".",
"_discovery_resp",
",",
"broadcast",
"=",
"Tru... | Discovers MAC address of device.
Discovery is done by sending a UDP broadcast.
All configured devices reply. The response contains
the MAC address in both needed formats.
Discovery of multiple switches must be done synchronously.
:returns: Tuple of MAC address and reversed MAC address. | [
"Discovers",
"MAC",
"address",
"of",
"device",
"."
] | python | train |
trentm/cmdln | examples/svn.py | https://github.com/trentm/cmdln/blob/55e980cf52c9b03e62d2349a7e62c9101d08ae10/examples/svn.py#L518-L549 | def do_log(self, subcmd, opts, *args):
"""Show the log messages for a set of revision(s) and/or file(s).
usage:
1. log [PATH]
2. log URL [PATH...]
1. Print the log messages for a local PATH (default: '.').
The default revision range is BASE:1.
2. Print the log messages for the PATHs (default: '.') under URL.
The default revision range is HEAD:1.
With -v, also print all affected paths with each log message.
With -q, don't print the log message body itself (note that this is
compatible with -v).
Each log message is printed just once, even if more than one of the
affected paths for that revision were explicitly requested. Logs
follow copy history by default. Use --stop-on-copy to disable this
behavior, which can be useful for determining branchpoints.
Examples:
svn log
svn log foo.c
svn log http://www.example.com/repo/project/foo.c
svn log http://www.example.com/repo/project foo.c bar.c
${cmd_option_list}
"""
print "'svn %s' opts: %s" % (subcmd, opts)
print "'svn %s' args: %s" % (subcmd, args) | [
"def",
"do_log",
"(",
"self",
",",
"subcmd",
",",
"opts",
",",
"*",
"args",
")",
":",
"print",
"\"'svn %s' opts: %s\"",
"%",
"(",
"subcmd",
",",
"opts",
")",
"print",
"\"'svn %s' args: %s\"",
"%",
"(",
"subcmd",
",",
"args",
")"
] | Show the log messages for a set of revision(s) and/or file(s).
usage:
1. log [PATH]
2. log URL [PATH...]
1. Print the log messages for a local PATH (default: '.').
The default revision range is BASE:1.
2. Print the log messages for the PATHs (default: '.') under URL.
The default revision range is HEAD:1.
With -v, also print all affected paths with each log message.
With -q, don't print the log message body itself (note that this is
compatible with -v).
Each log message is printed just once, even if more than one of the
affected paths for that revision were explicitly requested. Logs
follow copy history by default. Use --stop-on-copy to disable this
behavior, which can be useful for determining branchpoints.
Examples:
svn log
svn log foo.c
svn log http://www.example.com/repo/project/foo.c
svn log http://www.example.com/repo/project foo.c bar.c
${cmd_option_list} | [
"Show",
"the",
"log",
"messages",
"for",
"a",
"set",
"of",
"revision",
"(",
"s",
")",
"and",
"/",
"or",
"file",
"(",
"s",
")",
"."
] | python | train |
rytilahti/python-songpal | songpal/device.py | https://github.com/rytilahti/python-songpal/blob/0443de6b3d960b9067a851d82261ca00e46b4618/songpal/device.py#L304-L307 | async def set_custom_eq(self, target: str, value: str) -> None:
"""Set custom EQ settings."""
params = {"settings": [{"target": target, "value": value}]}
return await self.services["audio"]["setCustomEqualizerSettings"](params) | [
"async",
"def",
"set_custom_eq",
"(",
"self",
",",
"target",
":",
"str",
",",
"value",
":",
"str",
")",
"->",
"None",
":",
"params",
"=",
"{",
"\"settings\"",
":",
"[",
"{",
"\"target\"",
":",
"target",
",",
"\"value\"",
":",
"value",
"}",
"]",
"}",
... | Set custom EQ settings. | [
"Set",
"custom",
"EQ",
"settings",
"."
] | python | train |
silver-castle/mach9 | mach9/response.py | https://github.com/silver-castle/mach9/blob/7a623aab3c70d89d36ade6901b6307e115400c5e/mach9/response.py#L376-L394 | def redirect(to, headers=None, status=302,
content_type='text/html; charset=utf-8'):
'''Abort execution and cause a 302 redirect (by default).
:param to: path or fully qualified URL to redirect to
:param headers: optional dict of headers to include in the new request
:param status: status code (int) of the new request, defaults to 302
:param content_type: the content type (string) of the response
:returns: the redirecting Response
'''
headers = headers or {}
# According to RFC 7231, a relative URI is now permitted.
headers['Location'] = to
return HTTPResponse(
status=status,
headers=headers,
content_type=content_type) | [
"def",
"redirect",
"(",
"to",
",",
"headers",
"=",
"None",
",",
"status",
"=",
"302",
",",
"content_type",
"=",
"'text/html; charset=utf-8'",
")",
":",
"headers",
"=",
"headers",
"or",
"{",
"}",
"# According to RFC 7231, a relative URI is now permitted.",
"headers",... | Abort execution and cause a 302 redirect (by default).
:param to: path or fully qualified URL to redirect to
:param headers: optional dict of headers to include in the new request
:param status: status code (int) of the new request, defaults to 302
:param content_type: the content type (string) of the response
:returns: the redirecting Response | [
"Abort",
"execution",
"and",
"cause",
"a",
"302",
"redirect",
"(",
"by",
"default",
")",
"."
] | python | train |
jonathansick/paperweight | paperweight/texutils.py | https://github.com/jonathansick/paperweight/blob/803535b939a56d375967cefecd5fdca81323041e/paperweight/texutils.py#L57-L61 | def iter_tex_documents(base_dir="."):
"""Iterate through all .tex documents in the current directory."""
for path, dirlist, filelist in os.walk(base_dir):
for name in fnmatch.filter(filelist, "*.tex"):
yield os.path.join(path, name) | [
"def",
"iter_tex_documents",
"(",
"base_dir",
"=",
"\".\"",
")",
":",
"for",
"path",
",",
"dirlist",
",",
"filelist",
"in",
"os",
".",
"walk",
"(",
"base_dir",
")",
":",
"for",
"name",
"in",
"fnmatch",
".",
"filter",
"(",
"filelist",
",",
"\"*.tex\"",
... | Iterate through all .tex documents in the current directory. | [
"Iterate",
"through",
"all",
".",
"tex",
"documents",
"in",
"the",
"current",
"directory",
"."
] | python | train |
AkihikoITOH/capybara | capybara/virtualenv/lib/python2.7/site-packages/lxml/html/diff.py | https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site-packages/lxml/html/diff.py#L71-L77 | def tokenize_annotated(doc, annotation):
"""Tokenize a document and add an annotation attribute to each token
"""
tokens = tokenize(doc, include_hrefs=False)
for tok in tokens:
tok.annotation = annotation
return tokens | [
"def",
"tokenize_annotated",
"(",
"doc",
",",
"annotation",
")",
":",
"tokens",
"=",
"tokenize",
"(",
"doc",
",",
"include_hrefs",
"=",
"False",
")",
"for",
"tok",
"in",
"tokens",
":",
"tok",
".",
"annotation",
"=",
"annotation",
"return",
"tokens"
] | Tokenize a document and add an annotation attribute to each token | [
"Tokenize",
"a",
"document",
"and",
"add",
"an",
"annotation",
"attribute",
"to",
"each",
"token"
] | python | test |
RobotStudio/bors | bors/api/adapter/api.py | https://github.com/RobotStudio/bors/blob/38bf338fc6905d90819faa56bd832140116720f0/bors/api/adapter/api.py#L34-L53 | def call(self, callname, arguments=None):
"""Executed on each scheduled iteration"""
# See if a method override exists
action = getattr(self.api, callname, None)
if action is None:
try:
action = self.api.ENDPOINT_OVERRIDES.get(callname, None)
except AttributeError:
action = callname
if not callable(action):
request = self._generate_request(action, arguments)
if action is None:
return self._generate_result(
callname, self.api.call(*call_args(callname, arguments)))
return self._generate_result(
callname, self.api.call(*call_args(action, arguments)))
request = self._generate_request(callname, arguments)
return self._generate_result(callname, action(request)) | [
"def",
"call",
"(",
"self",
",",
"callname",
",",
"arguments",
"=",
"None",
")",
":",
"# See if a method override exists",
"action",
"=",
"getattr",
"(",
"self",
".",
"api",
",",
"callname",
",",
"None",
")",
"if",
"action",
"is",
"None",
":",
"try",
":"... | Executed on each scheduled iteration | [
"Executed",
"on",
"each",
"scheduled",
"iteration"
] | python | train |
PmagPy/PmagPy | pmagpy/builder2.py | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/pmagpy/builder2.py#L1193-L1207 | def validate_data(self):
"""
Validate specimen, sample, site, and location data.
"""
warnings = {}
spec_warnings, samp_warnings, site_warnings, loc_warnings = {}, {}, {}, {}
if self.specimens:
spec_warnings = self.validate_items(self.specimens, 'specimen')
if self.samples:
samp_warnings = self.validate_items(self.samples, 'sample')
if self.sites:
site_warnings = self.validate_items(self.sites, 'site')
if self.locations:
loc_warnings = self.validate_items(self.locations, 'location')
return spec_warnings, samp_warnings, site_warnings, loc_warnings | [
"def",
"validate_data",
"(",
"self",
")",
":",
"warnings",
"=",
"{",
"}",
"spec_warnings",
",",
"samp_warnings",
",",
"site_warnings",
",",
"loc_warnings",
"=",
"{",
"}",
",",
"{",
"}",
",",
"{",
"}",
",",
"{",
"}",
"if",
"self",
".",
"specimens",
":... | Validate specimen, sample, site, and location data. | [
"Validate",
"specimen",
"sample",
"site",
"and",
"location",
"data",
"."
] | python | train |
chrisrink10/basilisp | src/basilisp/lang/compiler/optimizer.py | https://github.com/chrisrink10/basilisp/blob/3d82670ee218ec64eb066289c82766d14d18cc92/src/basilisp/lang/compiler/optimizer.py#L75-L86 | def visit_While(self, node: ast.While) -> Optional[ast.AST]:
"""Eliminate dead code from while bodies."""
new_node = self.generic_visit(node)
assert isinstance(new_node, ast.While)
return ast.copy_location(
ast.While(
test=new_node.test,
body=_filter_dead_code(new_node.body),
orelse=_filter_dead_code(new_node.orelse),
),
new_node,
) | [
"def",
"visit_While",
"(",
"self",
",",
"node",
":",
"ast",
".",
"While",
")",
"->",
"Optional",
"[",
"ast",
".",
"AST",
"]",
":",
"new_node",
"=",
"self",
".",
"generic_visit",
"(",
"node",
")",
"assert",
"isinstance",
"(",
"new_node",
",",
"ast",
"... | Eliminate dead code from while bodies. | [
"Eliminate",
"dead",
"code",
"from",
"while",
"bodies",
"."
] | python | test |
duniter/duniter-python-api | duniterpy/api/client.py | https://github.com/duniter/duniter-python-api/blob/3a1e5d61a2f72f5afaf29d010c6cf4dff3648165/duniterpy/api/client.py#L277-L285 | def connect_ws(self, path: str) -> _WSRequestContextManager:
"""
Connect to a websocket in order to use API parameters
:param path: the url path
:return:
"""
client = API(self.endpoint.conn_handler(self.session, self.proxy))
return client.connect_ws(path) | [
"def",
"connect_ws",
"(",
"self",
",",
"path",
":",
"str",
")",
"->",
"_WSRequestContextManager",
":",
"client",
"=",
"API",
"(",
"self",
".",
"endpoint",
".",
"conn_handler",
"(",
"self",
".",
"session",
",",
"self",
".",
"proxy",
")",
")",
"return",
... | Connect to a websocket in order to use API parameters
:param path: the url path
:return: | [
"Connect",
"to",
"a",
"websocket",
"in",
"order",
"to",
"use",
"API",
"parameters"
] | python | train |
bootphon/h5features | h5features/convert2h5features.py | https://github.com/bootphon/h5features/blob/d5f95db0f1cee58ac1ba4575d1212e796c39e1f9/h5features/convert2h5features.py#L50-L56 | def main():
"""Main function of the converter command-line tool,
``convert2h5features --help`` for a more complete doc."""
args = parse_args()
converter = h5f.Converter(args.output, args.group, args.chunk)
for infile in args.file:
converter.convert(infile) | [
"def",
"main",
"(",
")",
":",
"args",
"=",
"parse_args",
"(",
")",
"converter",
"=",
"h5f",
".",
"Converter",
"(",
"args",
".",
"output",
",",
"args",
".",
"group",
",",
"args",
".",
"chunk",
")",
"for",
"infile",
"in",
"args",
".",
"file",
":",
... | Main function of the converter command-line tool,
``convert2h5features --help`` for a more complete doc. | [
"Main",
"function",
"of",
"the",
"converter",
"command",
"-",
"line",
"tool",
"convert2h5features",
"--",
"help",
"for",
"a",
"more",
"complete",
"doc",
"."
] | python | train |
openstax/cnx-publishing | cnxpublishing/db.py | https://github.com/openstax/cnx-publishing/blob/f55b4a2c45d8618737288f1b74b4139d5ac74154/cnxpublishing/db.py#L1187-L1202 | def remove_role_requests(cursor, uuid_, roles):
"""Given a ``uuid`` and list of dicts containing the ``uid``
(user identifiers) and ``role`` for removal of the identified
users' role acceptance entries.
"""
if not isinstance(roles, (list, set, tuple,)):
raise TypeError("``roles`` is an invalid type: {}".format(type(roles)))
acceptors = set([(x['uid'], x['role'],) for x in roles])
# Remove the the entries.
for uid, role_type in acceptors:
cursor.execute("""\
DELETE FROM role_acceptances
WHERE uuid = %s AND user_id = %s AND role_type = %s""",
(uuid_, uid, role_type,)) | [
"def",
"remove_role_requests",
"(",
"cursor",
",",
"uuid_",
",",
"roles",
")",
":",
"if",
"not",
"isinstance",
"(",
"roles",
",",
"(",
"list",
",",
"set",
",",
"tuple",
",",
")",
")",
":",
"raise",
"TypeError",
"(",
"\"``roles`` is an invalid type: {}\"",
... | Given a ``uuid`` and list of dicts containing the ``uid``
(user identifiers) and ``role`` for removal of the identified
users' role acceptance entries. | [
"Given",
"a",
"uuid",
"and",
"list",
"of",
"dicts",
"containing",
"the",
"uid",
"(",
"user",
"identifiers",
")",
"and",
"role",
"for",
"removal",
"of",
"the",
"identified",
"users",
"role",
"acceptance",
"entries",
"."
] | python | valid |
bukun/TorCMS | torcms/handlers/post_handler.py | https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/handlers/post_handler.py#L622-L647 | def _delete(self, *args, **kwargs):
'''
delete the post.
'''
_ = kwargs
uid = args[0]
current_infor = MPost.get_by_uid(uid)
if MPost.delete(uid):
tslug = MCategory.get_by_uid(current_infor.extinfo['def_cat_uid'])
MCategory.update_count(current_infor.extinfo['def_cat_uid'])
if router_post[self.kind] == 'info':
url = "filter"
id_dk8 = current_infor.extinfo['def_cat_uid']
else:
url = "list"
id_dk8 = tslug.slug
self.redirect('/{0}/{1}'.format(url, id_dk8))
else:
self.redirect('/{0}/{1}'.format(router_post[self.kind], uid)) | [
"def",
"_delete",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"_",
"=",
"kwargs",
"uid",
"=",
"args",
"[",
"0",
"]",
"current_infor",
"=",
"MPost",
".",
"get_by_uid",
"(",
"uid",
")",
"if",
"MPost",
".",
"delete",
"(",
"uid"... | delete the post. | [
"delete",
"the",
"post",
"."
] | python | train |
PmagPy/PmagPy | programs/demag_gui.py | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/programs/demag_gui.py#L6166-L6175 | def update_GUI_with_new_interpretation(self):
"""
update statistics boxes and figures with a new interpretatiom when
selecting new temperature bound
"""
self.update_fit_bounds_and_statistics()
self.draw_interpretations()
self.calculate_high_levels_data()
self.plot_high_levels_data() | [
"def",
"update_GUI_with_new_interpretation",
"(",
"self",
")",
":",
"self",
".",
"update_fit_bounds_and_statistics",
"(",
")",
"self",
".",
"draw_interpretations",
"(",
")",
"self",
".",
"calculate_high_levels_data",
"(",
")",
"self",
".",
"plot_high_levels_data",
"("... | update statistics boxes and figures with a new interpretatiom when
selecting new temperature bound | [
"update",
"statistics",
"boxes",
"and",
"figures",
"with",
"a",
"new",
"interpretatiom",
"when",
"selecting",
"new",
"temperature",
"bound"
] | python | train |
useblocks/sphinxcontrib-needs | sphinxcontrib/needs/filter_common.py | https://github.com/useblocks/sphinxcontrib-needs/blob/f49af4859a74e9fe76de5b9133c01335ac6ae191/sphinxcontrib/needs/filter_common.py#L68-L117 | def procces_filters(all_needs, current_needlist):
"""
Filters all needs with given configuration
:param current_needlist: needlist object, which stores all filters
:param all_needs: List of all needs inside document
:return: list of needs, which passed the filters
"""
if current_needlist["sort_by"] is not None:
if current_needlist["sort_by"] == "id":
all_needs = sorted(all_needs, key=lambda node: node["id"])
elif current_needlist["sort_by"] == "status":
all_needs = sorted(all_needs, key=status_sorter)
found_needs_by_options = []
# Add all need_parts of given needs to the search list
all_needs_incl_parts = prepare_need_list(all_needs)
for need_info in all_needs_incl_parts:
status_filter_passed = False
if current_needlist["status"] is None or len(current_needlist["status"]) == 0:
# Filtering for status was not requested
status_filter_passed = True
elif need_info["status"] is not None and need_info["status"] in current_needlist["status"]:
# Match was found
status_filter_passed = True
tags_filter_passed = False
if len(set(need_info["tags"]) & set(current_needlist["tags"])) > 0 or len(current_needlist["tags"]) == 0:
tags_filter_passed = True
type_filter_passed = False
if need_info["type"] in current_needlist["types"] \
or need_info["type_name"] in current_needlist["types"] \
or len(current_needlist["types"]) == 0:
type_filter_passed = True
if status_filter_passed and tags_filter_passed and type_filter_passed:
found_needs_by_options.append(need_info)
found_needs_by_string = filter_needs(all_needs_incl_parts, current_needlist["filter"])
# found_needs = [x for x in found_needs_by_string if x in found_needs_by_options]
found_needs = check_need_list(found_needs_by_options, found_needs_by_string)
return found_needs | [
"def",
"procces_filters",
"(",
"all_needs",
",",
"current_needlist",
")",
":",
"if",
"current_needlist",
"[",
"\"sort_by\"",
"]",
"is",
"not",
"None",
":",
"if",
"current_needlist",
"[",
"\"sort_by\"",
"]",
"==",
"\"id\"",
":",
"all_needs",
"=",
"sorted",
"(",... | Filters all needs with given configuration
:param current_needlist: needlist object, which stores all filters
:param all_needs: List of all needs inside document
:return: list of needs, which passed the filters | [
"Filters",
"all",
"needs",
"with",
"given",
"configuration"
] | python | train |
sergiocorreia/panflute | panflute/io.py | https://github.com/sergiocorreia/panflute/blob/65c2d570c26a190deb600cab5e2ad8a828a3302e/panflute/io.py#L96-L165 | def dump(doc, output_stream=None):
"""
Dump a :class:`.Doc` object into a JSON-encoded text string.
The output will be sent to :data:`sys.stdout` unless an alternative
text stream is given.
To dump to :data:`sys.stdout` just do:
>>> import panflute as pf
>>> doc = pf.Doc(Para(Str('a'))) # Create sample document
>>> pf.dump(doc)
To dump to file:
>>> with open('some-document.json', 'w'. encoding='utf-8') as f:
>>> pf.dump(doc, f)
To dump to a string:
>>> import io
>>> with io.StringIO() as f:
>>> pf.dump(doc, f)
>>> contents = f.getvalue()
:param doc: document, usually created with :func:`.load`
:type doc: :class:`.Doc`
:param output_stream: text stream used as output
(default is :data:`sys.stdout`)
"""
assert type(doc) == Doc, "panflute.dump needs input of type panflute.Doc"
if output_stream is None:
sys.stdout = codecs.getwriter("utf-8")(sys.stdout) if py2 else codecs.getwriter("utf-8")(sys.stdout.detach())
output_stream = sys.stdout
# Switch to legacy JSON output; eg: {'t': 'Space', 'c': []}
if doc.api_version is None:
# Switch .to_json() to legacy
Citation.backup = Citation.to_json
Citation.to_json = Citation.to_json_legacy
# Switch ._slots_to_json() to legacy
for E in [Table, OrderedList, Quoted, Math]:
E.backup = E._slots_to_json
E._slots_to_json = E._slots_to_json_legacy
# Switch .to_json() to method of base class
for E in EMPTY_ELEMENTS:
E.backup = E.to_json
E.to_json = Element.to_json
json_serializer = lambda elem: elem.to_json()
output_stream.write(json.dumps(
obj=doc,
default=json_serializer, # Serializer
check_circular=False,
separators=(',', ':'), # Compact separators, like Pandoc
ensure_ascii=False # For Pandoc compat
))
# Undo legacy changes
if doc.api_version is None:
Citation.to_json = Citation.backup
for E in [Table, OrderedList, Quoted, Math]:
E._slots_to_json = E.backup
for E in EMPTY_ELEMENTS:
E.to_json = E.backup | [
"def",
"dump",
"(",
"doc",
",",
"output_stream",
"=",
"None",
")",
":",
"assert",
"type",
"(",
"doc",
")",
"==",
"Doc",
",",
"\"panflute.dump needs input of type panflute.Doc\"",
"if",
"output_stream",
"is",
"None",
":",
"sys",
".",
"stdout",
"=",
"codecs",
... | Dump a :class:`.Doc` object into a JSON-encoded text string.
The output will be sent to :data:`sys.stdout` unless an alternative
text stream is given.
To dump to :data:`sys.stdout` just do:
>>> import panflute as pf
>>> doc = pf.Doc(Para(Str('a'))) # Create sample document
>>> pf.dump(doc)
To dump to file:
>>> with open('some-document.json', 'w'. encoding='utf-8') as f:
>>> pf.dump(doc, f)
To dump to a string:
>>> import io
>>> with io.StringIO() as f:
>>> pf.dump(doc, f)
>>> contents = f.getvalue()
:param doc: document, usually created with :func:`.load`
:type doc: :class:`.Doc`
:param output_stream: text stream used as output
(default is :data:`sys.stdout`) | [
"Dump",
"a",
":",
"class",
":",
".",
"Doc",
"object",
"into",
"a",
"JSON",
"-",
"encoded",
"text",
"string",
"."
] | python | train |
Alignak-monitoring/alignak | alignak/objects/escalation.py | https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/escalation.py#L349-L366 | def linkify_es_by_h(self, hosts):
"""Add each escalation object into host.escalation attribute
:param hosts: host list, used to look for a specific host
:type hosts: alignak.objects.host.Hosts
:return: None
"""
for escal in self:
# If no host, no hope of having a service
if (not hasattr(escal, 'host_name') or escal.host_name.strip() == '' or
(hasattr(escal, 'service_description')
and escal.service_description.strip() != '')):
continue
# I must be NOT a escalation on for service
for hname in strip_and_uniq(escal.host_name.split(',')):
host = hosts.find_by_name(hname)
if host is not None:
host.escalations.append(escal.uuid) | [
"def",
"linkify_es_by_h",
"(",
"self",
",",
"hosts",
")",
":",
"for",
"escal",
"in",
"self",
":",
"# If no host, no hope of having a service",
"if",
"(",
"not",
"hasattr",
"(",
"escal",
",",
"'host_name'",
")",
"or",
"escal",
".",
"host_name",
".",
"strip",
... | Add each escalation object into host.escalation attribute
:param hosts: host list, used to look for a specific host
:type hosts: alignak.objects.host.Hosts
:return: None | [
"Add",
"each",
"escalation",
"object",
"into",
"host",
".",
"escalation",
"attribute"
] | python | train |
aaren/notedown | notedown/notedown.py | https://github.com/aaren/notedown/blob/1e920c7e4ecbe47420c12eed3d5bcae735121222/notedown/notedown.py#L648-L679 | def get_caption_comments(content):
"""Retrieve an id and a caption from a code cell.
If the code cell content begins with a commented
block that looks like
## fig:id
# multi-line or single-line
# caption
then the 'fig:id' and the caption will be returned.
The '#' are stripped.
"""
if not content.startswith('## fig:'):
return None, None
content = content.splitlines()
id = content[0].strip('## ')
caption = []
for line in content[1:]:
if not line.startswith('# ') or line.startswith('##'):
break
else:
caption.append(line.lstrip('# ').rstrip())
# add " around the caption. TODO: consider doing this upstream
# in pandoc-attributes
caption = '"' + ' '.join(caption) + '"'
return id, caption | [
"def",
"get_caption_comments",
"(",
"content",
")",
":",
"if",
"not",
"content",
".",
"startswith",
"(",
"'## fig:'",
")",
":",
"return",
"None",
",",
"None",
"content",
"=",
"content",
".",
"splitlines",
"(",
")",
"id",
"=",
"content",
"[",
"0",
"]",
... | Retrieve an id and a caption from a code cell.
If the code cell content begins with a commented
block that looks like
## fig:id
# multi-line or single-line
# caption
then the 'fig:id' and the caption will be returned.
The '#' are stripped. | [
"Retrieve",
"an",
"id",
"and",
"a",
"caption",
"from",
"a",
"code",
"cell",
"."
] | python | train |
edx/bok-choy | bok_choy/promise.py | https://github.com/edx/bok-choy/blob/cdd0d423419fc0c49d56a9226533aa1490b60afc/bok_choy/promise.py#L111-L136 | def _check_fulfilled(self):
"""
Return tuple `(is_fulfilled, result)` where
`is_fulfilled` is a boolean indicating whether the promise has been fulfilled
and `result` is the value to pass to the `with` block.
"""
is_fulfilled = False
result = None
start_time = time.time()
# Check whether the promise has been fulfilled until we run out of time or attempts
while self._has_time_left(start_time) and self._has_more_tries():
# Keep track of how many attempts we've made so far
self._num_tries += 1
is_fulfilled, result = self._check_func()
# If the promise is satisfied, then continue execution
if is_fulfilled:
break
# Delay between checks
time.sleep(self._try_interval)
return is_fulfilled, result | [
"def",
"_check_fulfilled",
"(",
"self",
")",
":",
"is_fulfilled",
"=",
"False",
"result",
"=",
"None",
"start_time",
"=",
"time",
".",
"time",
"(",
")",
"# Check whether the promise has been fulfilled until we run out of time or attempts",
"while",
"self",
".",
"_has_ti... | Return tuple `(is_fulfilled, result)` where
`is_fulfilled` is a boolean indicating whether the promise has been fulfilled
and `result` is the value to pass to the `with` block. | [
"Return",
"tuple",
"(",
"is_fulfilled",
"result",
")",
"where",
"is_fulfilled",
"is",
"a",
"boolean",
"indicating",
"whether",
"the",
"promise",
"has",
"been",
"fulfilled",
"and",
"result",
"is",
"the",
"value",
"to",
"pass",
"to",
"the",
"with",
"block",
".... | python | train |
seleniumbase/SeleniumBase | seleniumbase/fixtures/page_utils.py | https://github.com/seleniumbase/SeleniumBase/blob/62e5b43ee1f90a9ed923841bdd53b1b38358f43a/seleniumbase/fixtures/page_utils.py#L25-L32 | def is_xpath_selector(selector):
"""
A basic method to determine if a selector is an xpath selector.
"""
if (selector.startswith('/') or selector.startswith('./') or (
selector.startswith('('))):
return True
return False | [
"def",
"is_xpath_selector",
"(",
"selector",
")",
":",
"if",
"(",
"selector",
".",
"startswith",
"(",
"'/'",
")",
"or",
"selector",
".",
"startswith",
"(",
"'./'",
")",
"or",
"(",
"selector",
".",
"startswith",
"(",
"'('",
")",
")",
")",
":",
"return",... | A basic method to determine if a selector is an xpath selector. | [
"A",
"basic",
"method",
"to",
"determine",
"if",
"a",
"selector",
"is",
"an",
"xpath",
"selector",
"."
] | python | train |
quantopian/pyfolio | pyfolio/plotting.py | https://github.com/quantopian/pyfolio/blob/712716ab0cdebbec9fabb25eea3bf40e4354749d/pyfolio/plotting.py#L346-L400 | def plot_long_short_holdings(returns, positions,
legend_loc='upper left', ax=None, **kwargs):
"""
Plots total amount of stocks with an active position, breaking out
short and long into transparent filled regions.
Parameters
----------
returns : pd.Series
Daily returns of the strategy, noncumulative.
- See full explanation in tears.create_full_tear_sheet.
positions : pd.DataFrame, optional
Daily net position values.
- See full explanation in tears.create_full_tear_sheet.
legend_loc : matplotlib.loc, optional
The location of the legend on the plot.
ax : matplotlib.Axes, optional
Axes upon which to plot.
**kwargs, optional
Passed to plotting function.
Returns
-------
ax : matplotlib.Axes
The axes that were plotted on.
"""
if ax is None:
ax = plt.gca()
positions = positions.drop('cash', axis='columns')
positions = positions.replace(0, np.nan)
df_longs = positions[positions > 0].count(axis=1)
df_shorts = positions[positions < 0].count(axis=1)
lf = ax.fill_between(df_longs.index, 0, df_longs.values,
color='g', alpha=0.5, lw=2.0)
sf = ax.fill_between(df_shorts.index, 0, df_shorts.values,
color='r', alpha=0.5, lw=2.0)
bf = patches.Rectangle([0, 0], 1, 1, color='darkgoldenrod')
leg = ax.legend([lf, sf, bf],
['Long (max: %s, min: %s)' % (df_longs.max(),
df_longs.min()),
'Short (max: %s, min: %s)' % (df_shorts.max(),
df_shorts.min()),
'Overlap'], loc=legend_loc, frameon=True,
framealpha=0.5)
leg.get_frame().set_edgecolor('black')
ax.set_xlim((returns.index[0], returns.index[-1]))
ax.set_title('Long and short holdings')
ax.set_ylabel('Holdings')
ax.set_xlabel('')
return ax | [
"def",
"plot_long_short_holdings",
"(",
"returns",
",",
"positions",
",",
"legend_loc",
"=",
"'upper left'",
",",
"ax",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"ax",
"is",
"None",
":",
"ax",
"=",
"plt",
".",
"gca",
"(",
")",
"positions",
... | Plots total amount of stocks with an active position, breaking out
short and long into transparent filled regions.
Parameters
----------
returns : pd.Series
Daily returns of the strategy, noncumulative.
- See full explanation in tears.create_full_tear_sheet.
positions : pd.DataFrame, optional
Daily net position values.
- See full explanation in tears.create_full_tear_sheet.
legend_loc : matplotlib.loc, optional
The location of the legend on the plot.
ax : matplotlib.Axes, optional
Axes upon which to plot.
**kwargs, optional
Passed to plotting function.
Returns
-------
ax : matplotlib.Axes
The axes that were plotted on. | [
"Plots",
"total",
"amount",
"of",
"stocks",
"with",
"an",
"active",
"position",
"breaking",
"out",
"short",
"and",
"long",
"into",
"transparent",
"filled",
"regions",
"."
] | python | valid |
brocade/pynos | pynos/versions/ver_7/ver_7_1_0/yang/brocade_tunnels.py | https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_7/ver_7_1_0/yang/brocade_tunnels.py#L662-L676 | def overlay_gateway_access_lists_mac_in_cg_mac_acl_in_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
overlay_gateway = ET.SubElement(config, "overlay-gateway", xmlns="urn:brocade.com:mgmt:brocade-tunnels")
name_key = ET.SubElement(overlay_gateway, "name")
name_key.text = kwargs.pop('name')
access_lists = ET.SubElement(overlay_gateway, "access-lists")
mac = ET.SubElement(access_lists, "mac")
in_cg = ET.SubElement(mac, "in")
mac_acl_in_name = ET.SubElement(in_cg, "mac-acl-in-name")
mac_acl_in_name.text = kwargs.pop('mac_acl_in_name')
callback = kwargs.pop('callback', self._callback)
return callback(config) | [
"def",
"overlay_gateway_access_lists_mac_in_cg_mac_acl_in_name",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"overlay_gateway",
"=",
"ET",
".",
"SubElement",
"(",
"config",
",",
"\"overlay-gateway\""... | Auto Generated Code | [
"Auto",
"Generated",
"Code"
] | python | train |
Element-34/py.saunter | saunter/matchers.py | https://github.com/Element-34/py.saunter/blob/bdc8480b1453e082872c80d3382d42565b8ed9c0/saunter/matchers.py#L398-L412 | def verify_visible(self, locator, msg=None):
"""
Soft assert for whether and element is present and visible in the current window/frame
:params locator: the locator of the element to search for
:params msg: (Optional) msg explaining the difference
"""
try:
self.assert_visible(locator, msg)
except AssertionError, e:
if msg:
m = "%s:\n%s" % (msg, str(e))
else:
m = str(e)
self.verification_erorrs.append(m) | [
"def",
"verify_visible",
"(",
"self",
",",
"locator",
",",
"msg",
"=",
"None",
")",
":",
"try",
":",
"self",
".",
"assert_visible",
"(",
"locator",
",",
"msg",
")",
"except",
"AssertionError",
",",
"e",
":",
"if",
"msg",
":",
"m",
"=",
"\"%s:\\n%s\"",
... | Soft assert for whether and element is present and visible in the current window/frame
:params locator: the locator of the element to search for
:params msg: (Optional) msg explaining the difference | [
"Soft",
"assert",
"for",
"whether",
"and",
"element",
"is",
"present",
"and",
"visible",
"in",
"the",
"current",
"window",
"/",
"frame"
] | python | train |
sdispater/orator | orator/schema/blueprint.py | https://github.com/sdispater/orator/blob/bd90bf198ee897751848f9a92e49d18e60a74136/orator/schema/blueprint.py#L443-L454 | def unsigned_integer(self, column, auto_increment=False):
"""
Create a new unisgned integer column on the table.
:param column: The column
:type column: str
:type auto_increment: bool
:rtype: Fluent
"""
return self.integer(column, auto_increment, True) | [
"def",
"unsigned_integer",
"(",
"self",
",",
"column",
",",
"auto_increment",
"=",
"False",
")",
":",
"return",
"self",
".",
"integer",
"(",
"column",
",",
"auto_increment",
",",
"True",
")"
] | Create a new unisgned integer column on the table.
:param column: The column
:type column: str
:type auto_increment: bool
:rtype: Fluent | [
"Create",
"a",
"new",
"unisgned",
"integer",
"column",
"on",
"the",
"table",
"."
] | python | train |
SKA-ScienceDataProcessor/integration-prototype | sip/execution_control/configuration_db/sip_config_db/_events/pubsub.py | https://github.com/SKA-ScienceDataProcessor/integration-prototype/blob/8c8006de6ad71dcd44114b0338780738079c87d4/sip/execution_control/configuration_db/sip_config_db/_events/pubsub.py#L169-L188 | def _get_event_id(object_type: str) -> str:
"""Return an event key for the event on the object type.
This must be a unique event id for the object.
Args:
object_type (str): Type of object
Returns:
str, event id
"""
key = _keys.event_counter(object_type)
DB.watch(key, pipeline=True)
count = DB.get_value(key)
DB.increment(key)
DB.execute()
if count is None:
count = 0
return '{}_event_{:08d}'.format(object_type, int(count)) | [
"def",
"_get_event_id",
"(",
"object_type",
":",
"str",
")",
"->",
"str",
":",
"key",
"=",
"_keys",
".",
"event_counter",
"(",
"object_type",
")",
"DB",
".",
"watch",
"(",
"key",
",",
"pipeline",
"=",
"True",
")",
"count",
"=",
"DB",
".",
"get_value",
... | Return an event key for the event on the object type.
This must be a unique event id for the object.
Args:
object_type (str): Type of object
Returns:
str, event id | [
"Return",
"an",
"event",
"key",
"for",
"the",
"event",
"on",
"the",
"object",
"type",
"."
] | python | train |
saltstack/salt | salt/modules/mysql.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mysql.py#L1116-L1166 | def db_create(name, character_set=None, collate=None, **connection_args):
'''
Adds a databases to the MySQL server.
name
The name of the database to manage
character_set
The character set, if left empty the MySQL default will be used
collate
The collation, if left empty the MySQL default will be used
CLI Example:
.. code-block:: bash
salt '*' mysql.db_create 'dbname'
salt '*' mysql.db_create 'dbname' 'utf8' 'utf8_general_ci'
'''
# check if db exists
if db_exists(name, **connection_args):
log.info('DB \'%s\' already exists', name)
return False
# db doesn't exist, proceed
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor()
s_name = quote_identifier(name)
# identifiers cannot be used as values
qry = 'CREATE DATABASE IF NOT EXISTS {0}'.format(s_name)
args = {}
if character_set is not None:
qry += ' CHARACTER SET %(character_set)s'
args['character_set'] = character_set
if collate is not None:
qry += ' COLLATE %(collate)s'
args['collate'] = collate
qry += ';'
try:
if _execute(cur, qry, args):
log.info('DB \'%s\' created', name)
return True
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc.args)
__context__['mysql.error'] = err
log.error(err)
return False | [
"def",
"db_create",
"(",
"name",
",",
"character_set",
"=",
"None",
",",
"collate",
"=",
"None",
",",
"*",
"*",
"connection_args",
")",
":",
"# check if db exists",
"if",
"db_exists",
"(",
"name",
",",
"*",
"*",
"connection_args",
")",
":",
"log",
".",
"... | Adds a databases to the MySQL server.
name
The name of the database to manage
character_set
The character set, if left empty the MySQL default will be used
collate
The collation, if left empty the MySQL default will be used
CLI Example:
.. code-block:: bash
salt '*' mysql.db_create 'dbname'
salt '*' mysql.db_create 'dbname' 'utf8' 'utf8_general_ci' | [
"Adds",
"a",
"databases",
"to",
"the",
"MySQL",
"server",
"."
] | python | train |
bcbio/bcbio-nextgen | bcbio/variation/population.py | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/population.py#L348-L356 | def get_gemini_files(data):
"""Enumerate available gemini data files in a standard installation.
"""
try:
from gemini import annotations, config
except ImportError:
return {}
return {"base": config.read_gemini_config()["annotation_dir"],
"files": annotations.get_anno_files().values()} | [
"def",
"get_gemini_files",
"(",
"data",
")",
":",
"try",
":",
"from",
"gemini",
"import",
"annotations",
",",
"config",
"except",
"ImportError",
":",
"return",
"{",
"}",
"return",
"{",
"\"base\"",
":",
"config",
".",
"read_gemini_config",
"(",
")",
"[",
"\... | Enumerate available gemini data files in a standard installation. | [
"Enumerate",
"available",
"gemini",
"data",
"files",
"in",
"a",
"standard",
"installation",
"."
] | python | train |
OpenHydrology/floodestimation | floodestimation/analysis.py | https://github.com/OpenHydrology/floodestimation/blob/782da7c5abd1348923129efe89fb70003ebb088c/floodestimation/analysis.py#L310-L322 | def _qmed_from_area(self):
"""
Return QMED estimate based on catchment area.
TODO: add source of method
:return: QMED in m³/s
:rtype: float
"""
try:
return 1.172 * self.catchment.descriptors.dtm_area ** self._area_exponent() # Area in km²
except (TypeError, KeyError):
raise InsufficientDataError("Catchment `descriptors` attribute must be set first.") | [
"def",
"_qmed_from_area",
"(",
"self",
")",
":",
"try",
":",
"return",
"1.172",
"*",
"self",
".",
"catchment",
".",
"descriptors",
".",
"dtm_area",
"**",
"self",
".",
"_area_exponent",
"(",
")",
"# Area in km²",
"except",
"(",
"TypeError",
",",
"KeyError",
... | Return QMED estimate based on catchment area.
TODO: add source of method
:return: QMED in m³/s
:rtype: float | [
"Return",
"QMED",
"estimate",
"based",
"on",
"catchment",
"area",
"."
] | python | train |
pteichman/cobe | cobe/brain.py | https://github.com/pteichman/cobe/blob/b0dc2a707035035b9a689105c8f833894fb59eb7/cobe/brain.py#L154-L165 | def _to_graph(self, contexts):
"""This is an iterator that returns each edge of our graph
with its two nodes"""
prev = None
for context in contexts:
if prev is None:
prev = context
continue
yield prev[0], context[1], context[0]
prev = context | [
"def",
"_to_graph",
"(",
"self",
",",
"contexts",
")",
":",
"prev",
"=",
"None",
"for",
"context",
"in",
"contexts",
":",
"if",
"prev",
"is",
"None",
":",
"prev",
"=",
"context",
"continue",
"yield",
"prev",
"[",
"0",
"]",
",",
"context",
"[",
"1",
... | This is an iterator that returns each edge of our graph
with its two nodes | [
"This",
"is",
"an",
"iterator",
"that",
"returns",
"each",
"edge",
"of",
"our",
"graph",
"with",
"its",
"two",
"nodes"
] | python | train |
joshspeagle/dynesty | dynesty/sampler.py | https://github.com/joshspeagle/dynesty/blob/9e482aafeb5cf84bedb896fa6f07a761d917983e/dynesty/sampler.py#L761-L861 | def run_nested(self, maxiter=None, maxcall=None, dlogz=None,
logl_max=np.inf, add_live=True, print_progress=True,
print_func=None, save_bounds=True):
"""
**A wrapper that executes the main nested sampling loop.**
Iteratively replace the worst live point with a sample drawn
uniformly from the prior until the provided stopping criteria
are reached.
Parameters
----------
maxiter : int, optional
Maximum number of iterations. Iteration may stop earlier if the
termination condition is reached. Default is `sys.maxsize`
(no limit).
maxcall : int, optional
Maximum number of likelihood evaluations. Iteration may stop
earlier if termination condition is reached. Default is
`sys.maxsize` (no limit).
dlogz : float, optional
Iteration will stop when the estimated contribution of the
remaining prior volume to the total evidence falls below
this threshold. Explicitly, the stopping criterion is
`ln(z + z_est) - ln(z) < dlogz`, where `z` is the current
evidence from all saved samples and `z_est` is the estimated
contribution from the remaining volume. If `add_live` is `True`,
the default is `1e-3 * (nlive - 1) + 0.01`. Otherwise, the
default is `0.01`.
logl_max : float, optional
Iteration will stop when the sampled ln(likelihood) exceeds the
threshold set by `logl_max`. Default is no bound (`np.inf`).
add_live : bool, optional
Whether or not to add the remaining set of live points to
the list of samples at the end of each run. Default is `True`.
print_progress : bool, optional
Whether or not to output a simple summary of the current run that
updates with each iteration. Default is `True`.
print_func : function, optional
A function that prints out the current state of the sampler.
If not provided, the default :meth:`results.print_fn` is used.
save_bounds : bool, optional
Whether or not to save past bounding distributions used to bound
the live points internally. Default is *True*.
"""
# Initialize quantities/
if print_func is None:
print_func = print_fn
# Define our stopping criteria.
if dlogz is None:
if add_live:
dlogz = 1e-3 * (self.nlive - 1.) + 0.01
else:
dlogz = 0.01
# Run the main nested sampling loop.
ncall = self.ncall
for it, results in enumerate(self.sample(maxiter=maxiter,
maxcall=maxcall, dlogz=dlogz,
logl_max=logl_max,
save_bounds=save_bounds,
save_samples=True)):
(worst, ustar, vstar, loglstar, logvol, logwt,
logz, logzvar, h, nc, worst_it, boundidx, bounditer,
eff, delta_logz) = results
ncall += nc
if delta_logz > 1e6:
delta_logz = np.inf
if logz <= -1e6:
logz = -np.inf
# Print progress.
if print_progress:
i = self.it - 1
print_func(results, i, ncall, dlogz=dlogz, logl_max=logl_max)
# Add remaining live points to samples.
if add_live:
it = self.it - 1
for i, results in enumerate(self.add_live_points()):
(worst, ustar, vstar, loglstar, logvol, logwt,
logz, logzvar, h, nc, worst_it, boundidx, bounditer,
eff, delta_logz) = results
if delta_logz > 1e6:
delta_logz = np.inf
if logz <= -1e6:
logz = -np.inf
# Print progress.
if print_progress:
print_func(results, it, ncall, add_live_it=i+1,
dlogz=dlogz, logl_max=logl_max) | [
"def",
"run_nested",
"(",
"self",
",",
"maxiter",
"=",
"None",
",",
"maxcall",
"=",
"None",
",",
"dlogz",
"=",
"None",
",",
"logl_max",
"=",
"np",
".",
"inf",
",",
"add_live",
"=",
"True",
",",
"print_progress",
"=",
"True",
",",
"print_func",
"=",
"... | **A wrapper that executes the main nested sampling loop.**
Iteratively replace the worst live point with a sample drawn
uniformly from the prior until the provided stopping criteria
are reached.
Parameters
----------
maxiter : int, optional
Maximum number of iterations. Iteration may stop earlier if the
termination condition is reached. Default is `sys.maxsize`
(no limit).
maxcall : int, optional
Maximum number of likelihood evaluations. Iteration may stop
earlier if termination condition is reached. Default is
`sys.maxsize` (no limit).
dlogz : float, optional
Iteration will stop when the estimated contribution of the
remaining prior volume to the total evidence falls below
this threshold. Explicitly, the stopping criterion is
`ln(z + z_est) - ln(z) < dlogz`, where `z` is the current
evidence from all saved samples and `z_est` is the estimated
contribution from the remaining volume. If `add_live` is `True`,
the default is `1e-3 * (nlive - 1) + 0.01`. Otherwise, the
default is `0.01`.
logl_max : float, optional
Iteration will stop when the sampled ln(likelihood) exceeds the
threshold set by `logl_max`. Default is no bound (`np.inf`).
add_live : bool, optional
Whether or not to add the remaining set of live points to
the list of samples at the end of each run. Default is `True`.
print_progress : bool, optional
Whether or not to output a simple summary of the current run that
updates with each iteration. Default is `True`.
print_func : function, optional
A function that prints out the current state of the sampler.
If not provided, the default :meth:`results.print_fn` is used.
save_bounds : bool, optional
Whether or not to save past bounding distributions used to bound
the live points internally. Default is *True*. | [
"**",
"A",
"wrapper",
"that",
"executes",
"the",
"main",
"nested",
"sampling",
"loop",
".",
"**",
"Iteratively",
"replace",
"the",
"worst",
"live",
"point",
"with",
"a",
"sample",
"drawn",
"uniformly",
"from",
"the",
"prior",
"until",
"the",
"provided",
"sto... | python | train |
fhamborg/news-please | newsplease/crawler/spiders/recursive_sitemap_crawler.py | https://github.com/fhamborg/news-please/blob/731837c2a6c223cfb3e1d7f5fdc4f4eced2310f9/newsplease/crawler/spiders/recursive_sitemap_crawler.py#L41-L57 | def parse(self, response):
"""
Checks any given response on being an article and if positiv,
passes the response to the pipeline.
:param obj response: The scrapy response
"""
if not self.helper.parse_crawler.content_type(response):
return
for request in self.helper.parse_crawler \
.recursive_requests(response, self, self.ignore_regex,
self.ignore_file_extensions):
yield request
yield self.helper.parse_crawler.pass_to_pipeline_if_article(
response, self.allowed_domains[0], self.original_url) | [
"def",
"parse",
"(",
"self",
",",
"response",
")",
":",
"if",
"not",
"self",
".",
"helper",
".",
"parse_crawler",
".",
"content_type",
"(",
"response",
")",
":",
"return",
"for",
"request",
"in",
"self",
".",
"helper",
".",
"parse_crawler",
".",
"recursi... | Checks any given response on being an article and if positiv,
passes the response to the pipeline.
:param obj response: The scrapy response | [
"Checks",
"any",
"given",
"response",
"on",
"being",
"an",
"article",
"and",
"if",
"positiv",
"passes",
"the",
"response",
"to",
"the",
"pipeline",
"."
] | python | train |
tensorflow/tensor2tensor | tensor2tensor/utils/decoding.py | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/decoding.py#L394-L559 | def decode_from_file(estimator,
filename,
hparams,
decode_hp,
decode_to_file=None,
checkpoint_path=None):
"""Compute predictions on entries in filename and write them out."""
if not decode_hp.batch_size:
decode_hp.batch_size = 32
tf.logging.info(
"decode_hp.batch_size not specified; default=%d" % decode_hp.batch_size)
# Inputs vocabulary is set to targets if there are no inputs in the problem,
# e.g., for language models where the inputs are just a prefix of targets.
p_hp = hparams.problem_hparams
has_input = "inputs" in p_hp.vocabulary
inputs_vocab_key = "inputs" if has_input else "targets"
inputs_vocab = p_hp.vocabulary[inputs_vocab_key]
targets_vocab = p_hp.vocabulary["targets"]
problem_name = FLAGS.problem
filename = _add_shard_to_filename(filename, decode_hp)
tf.logging.info("Performing decoding from file (%s)." % filename)
if has_input:
sorted_inputs, sorted_keys = _get_sorted_inputs(
filename, decode_hp.delimiter)
else:
sorted_inputs = _get_language_modeling_inputs(
filename, decode_hp.delimiter, repeat=decode_hp.num_decodes)
sorted_keys = range(len(sorted_inputs))
num_sentences = len(sorted_inputs)
num_decode_batches = (num_sentences - 1) // decode_hp.batch_size + 1
if estimator.config.use_tpu:
length = getattr(hparams, "length", 0) or hparams.max_length
batch_ids = []
for line in sorted_inputs:
if has_input:
ids = inputs_vocab.encode(line.strip()) + [1]
else:
ids = targets_vocab.encode(line)
if len(ids) < length:
ids.extend([0] * (length - len(ids)))
else:
ids = ids[:length]
batch_ids.append(ids)
np_ids = np.array(batch_ids, dtype=np.int32)
def input_fn(params):
batch_size = params["batch_size"]
dataset = tf.data.Dataset.from_tensor_slices({"inputs": np_ids})
dataset = dataset.map(
lambda ex: {"inputs": tf.reshape(ex["inputs"], (length, 1, 1))})
dataset = dataset.batch(batch_size)
return dataset
else:
def input_fn():
input_gen = _decode_batch_input_fn(
num_decode_batches, sorted_inputs,
inputs_vocab, decode_hp.batch_size,
decode_hp.max_input_size,
task_id=decode_hp.multiproblem_task_id, has_input=has_input)
gen_fn = make_input_fn_from_generator(input_gen)
example = gen_fn()
return _decode_input_tensor_to_features_dict(example, hparams)
decodes = []
result_iter = estimator.predict(input_fn, checkpoint_path=checkpoint_path)
start_time = time.time()
total_time_per_step = 0
total_cnt = 0
def timer(gen):
while True:
try:
start_time = time.time()
item = next(gen)
elapsed_time = time.time() - start_time
yield elapsed_time, item
except StopIteration:
break
for elapsed_time, result in timer(result_iter):
if decode_hp.return_beams:
beam_decodes = []
beam_scores = []
output_beams = np.split(result["outputs"], decode_hp.beam_size, axis=0)
scores = None
if "scores" in result:
if np.isscalar(result["scores"]):
result["scores"] = result["scores"].reshape(1)
scores = np.split(result["scores"], decode_hp.beam_size, axis=0)
for k, beam in enumerate(output_beams):
tf.logging.info("BEAM %d:" % k)
score = scores and scores[k]
_, decoded_outputs, _ = log_decode_results(
result["inputs"],
beam,
problem_name,
None,
inputs_vocab,
targets_vocab,
log_results=decode_hp.log_results,
skip_eos_postprocess=decode_hp.skip_eos_postprocess)
beam_decodes.append(decoded_outputs)
if decode_hp.write_beam_scores:
beam_scores.append(score)
if decode_hp.write_beam_scores:
decodes.append("\t".join([
"\t".join([d, "%.2f" % s])
for d, s in zip(beam_decodes, beam_scores)
]))
else:
decodes.append("\t".join(beam_decodes))
else:
_, decoded_outputs, _ = log_decode_results(
result["inputs"],
result["outputs"],
problem_name,
None,
inputs_vocab,
targets_vocab,
log_results=decode_hp.log_results,
skip_eos_postprocess=decode_hp.skip_eos_postprocess)
decodes.append(decoded_outputs)
total_time_per_step += elapsed_time
total_cnt += result["outputs"].shape[-1]
duration = time.time() - start_time
tf.logging.info("Elapsed Time: %5.5f" % duration)
tf.logging.info("Averaged Single Token Generation Time: %5.7f "
"(time %5.7f count %d)" %
(total_time_per_step / total_cnt,
total_time_per_step, total_cnt))
if decode_hp.batch_size == 1:
tf.logging.info("Inference time %.4f seconds "
"(Latency = %.4f ms/setences)" %
(duration, 1000.0*duration/num_sentences))
else:
tf.logging.info("Inference time %.4f seconds "
"(Throughput = %.4f sentences/second)" %
(duration, num_sentences/duration))
# If decode_to_file was provided use it as the output filename without change
# (except for adding shard_id if using more shards for decoding).
# Otherwise, use the input filename plus model, hp, problem, beam, alpha.
decode_filename = decode_to_file if decode_to_file else filename
if not decode_to_file:
decode_filename = _decode_filename(decode_filename, problem_name, decode_hp)
else:
decode_filename = _add_shard_to_filename(decode_filename, decode_hp)
tf.logging.info("Writing decodes into %s" % decode_filename)
outfile = tf.gfile.Open(decode_filename, "w")
for index in range(len(sorted_inputs)):
outfile.write("%s%s" % (decodes[sorted_keys[index]], decode_hp.delimiter))
outfile.flush()
outfile.close()
output_dir = os.path.join(estimator.model_dir, "decode")
tf.gfile.MakeDirs(output_dir)
run_postdecode_hooks(DecodeHookArgs(
estimator=estimator,
problem=hparams.problem,
output_dirs=[output_dir],
hparams=hparams,
decode_hparams=decode_hp,
predictions=list(result_iter)
), None) | [
"def",
"decode_from_file",
"(",
"estimator",
",",
"filename",
",",
"hparams",
",",
"decode_hp",
",",
"decode_to_file",
"=",
"None",
",",
"checkpoint_path",
"=",
"None",
")",
":",
"if",
"not",
"decode_hp",
".",
"batch_size",
":",
"decode_hp",
".",
"batch_size",... | Compute predictions on entries in filename and write them out. | [
"Compute",
"predictions",
"on",
"entries",
"in",
"filename",
"and",
"write",
"them",
"out",
"."
] | python | train |
jhuapl-boss/intern | intern/remote/boss/remote.py | https://github.com/jhuapl-boss/intern/blob/d8fc6df011d8f212c87e6a1fd4cc21cfb5d103ed/intern/remote/boss/remote.py#L384-L398 | def delete_group_maintainer(self, grp_name, user):
"""
Delete the given user to the named group.
Both group and user must already exist for this to succeed.
Args:
name (string): Name of group.
user (string): User to add to group.
Raises:
requests.HTTPError on failure.
"""
self.project_service.set_auth(self._token_project)
self.project_service.delete_group_maintainer(grp_name, user) | [
"def",
"delete_group_maintainer",
"(",
"self",
",",
"grp_name",
",",
"user",
")",
":",
"self",
".",
"project_service",
".",
"set_auth",
"(",
"self",
".",
"_token_project",
")",
"self",
".",
"project_service",
".",
"delete_group_maintainer",
"(",
"grp_name",
",",... | Delete the given user to the named group.
Both group and user must already exist for this to succeed.
Args:
name (string): Name of group.
user (string): User to add to group.
Raises:
requests.HTTPError on failure. | [
"Delete",
"the",
"given",
"user",
"to",
"the",
"named",
"group",
"."
] | python | train |
ethereum/eth-abi | eth_abi/registry.py | https://github.com/ethereum/eth-abi/blob/0a5cab0bdeae30b77efa667379427581784f1707/eth_abi/registry.py#L270-L279 | def is_base_tuple(type_str):
"""
A predicate that matches a tuple type with no array dimension list.
"""
try:
abi_type = grammar.parse(type_str)
except exceptions.ParseError:
return False
return isinstance(abi_type, grammar.TupleType) and abi_type.arrlist is None | [
"def",
"is_base_tuple",
"(",
"type_str",
")",
":",
"try",
":",
"abi_type",
"=",
"grammar",
".",
"parse",
"(",
"type_str",
")",
"except",
"exceptions",
".",
"ParseError",
":",
"return",
"False",
"return",
"isinstance",
"(",
"abi_type",
",",
"grammar",
".",
... | A predicate that matches a tuple type with no array dimension list. | [
"A",
"predicate",
"that",
"matches",
"a",
"tuple",
"type",
"with",
"no",
"array",
"dimension",
"list",
"."
] | python | train |
BD2KGenomics/toil-lib | src/toil_lib/tools/aligners.py | https://github.com/BD2KGenomics/toil-lib/blob/022a615fc3dc98fc1aaa7bfd232409962ca44fbd/src/toil_lib/tools/aligners.py#L9-L82 | def run_star(job, r1_id, r2_id, star_index_url, wiggle=False, sort=True):
"""
Performs alignment of fastqs to bam via STAR
--limitBAMsortRAM step added to deal with memory explosion when sorting certain samples.
The value was chosen to complement the recommended amount of memory to have when running STAR (60G)
:param JobFunctionWrappingJob job: passed automatically by Toil
:param str r1_id: FileStoreID of fastq (pair 1)
:param str r2_id: FileStoreID of fastq (pair 2 if applicable, else pass None)
:param str star_index_url: STAR index tarball
:param bool wiggle: If True, will output a wiggle file and return it
:return: FileStoreID from RSEM
:rtype: str
"""
work_dir = job.fileStore.getLocalTempDir()
download_url(job, url=star_index_url, name='starIndex.tar.gz', work_dir=work_dir)
subprocess.check_call(['tar', '-xvf', os.path.join(work_dir, 'starIndex.tar.gz'), '-C', work_dir])
os.remove(os.path.join(work_dir, 'starIndex.tar.gz'))
# Determine tarball structure - star index contains are either in a subdir or in the tarball itself
star_index = os.path.join('/data', os.listdir(work_dir)[0]) if len(os.listdir(work_dir)) == 1 else '/data'
# Parameter handling for paired / single-end data
parameters = ['--runThreadN', str(job.cores),
'--genomeDir', star_index,
'--outFileNamePrefix', 'rna',
'--outSAMunmapped', 'Within',
'--quantMode', 'TranscriptomeSAM',
'--outSAMattributes', 'NH', 'HI', 'AS', 'NM', 'MD',
'--outFilterType', 'BySJout',
'--outFilterMultimapNmax', '20',
'--outFilterMismatchNmax', '999',
'--outFilterMismatchNoverReadLmax', '0.04',
'--alignIntronMin', '20',
'--alignIntronMax', '1000000',
'--alignMatesGapMax', '1000000',
'--alignSJoverhangMin', '8',
'--alignSJDBoverhangMin', '1',
'--sjdbScore', '1',
'--limitBAMsortRAM', '49268954168']
# Modify paramaters based on function arguments
if sort:
parameters.extend(['--outSAMtype', 'BAM', 'SortedByCoordinate'])
aligned_bam = 'rnaAligned.sortedByCoord.out.bam'
else:
parameters.extend(['--outSAMtype', 'BAM', 'Unsorted'])
aligned_bam = 'rnaAligned.out.bam'
if wiggle:
parameters.extend(['--outWigType', 'bedGraph',
'--outWigStrand', 'Unstranded',
'--outWigReferencesPrefix', 'chr'])
if r1_id and r2_id:
job.fileStore.readGlobalFile(r1_id, os.path.join(work_dir, 'R1.fastq'))
job.fileStore.readGlobalFile(r2_id, os.path.join(work_dir, 'R2.fastq'))
parameters.extend(['--readFilesIn', '/data/R1.fastq', '/data/R2.fastq'])
else:
job.fileStore.readGlobalFile(r1_id, os.path.join(work_dir, 'R1.fastq'))
parameters.extend(['--readFilesIn', '/data/R1.fastq'])
# Call: STAR Mapping
dockerCall(job=job, tool='quay.io/ucsc_cgl/star:2.4.2a--bcbd5122b69ff6ac4ef61958e47bde94001cfe80',
workDir=work_dir, parameters=parameters)
# Check output bam isnt size zero if sorted
aligned_bam_path = os.path.join(work_dir, aligned_bam)
if sort:
assert(os.stat(aligned_bam_path).st_size > 0, 'Aligned bam failed to sort. Ensure sufficient memory is free.')
# Write to fileStore
aligned_id = job.fileStore.writeGlobalFile(aligned_bam_path)
transcriptome_id = job.fileStore.writeGlobalFile(os.path.join(work_dir, 'rnaAligned.toTranscriptome.out.bam'))
log_id = job.fileStore.writeGlobalFile(os.path.join(work_dir, 'rnaLog.final.out'))
sj_id = job.fileStore.writeGlobalFile(os.path.join(work_dir, 'rnaSJ.out.tab'))
if wiggle:
wiggle_id = job.fileStore.writeGlobalFile(os.path.join(work_dir, 'rnaSignal.UniqueMultiple.str1.out.bg'))
return transcriptome_id, aligned_id, wiggle_id, log_id, sj_id
else:
return transcriptome_id, aligned_id, log_id, sj_id | [
"def",
"run_star",
"(",
"job",
",",
"r1_id",
",",
"r2_id",
",",
"star_index_url",
",",
"wiggle",
"=",
"False",
",",
"sort",
"=",
"True",
")",
":",
"work_dir",
"=",
"job",
".",
"fileStore",
".",
"getLocalTempDir",
"(",
")",
"download_url",
"(",
"job",
"... | Performs alignment of fastqs to bam via STAR
--limitBAMsortRAM step added to deal with memory explosion when sorting certain samples.
The value was chosen to complement the recommended amount of memory to have when running STAR (60G)
:param JobFunctionWrappingJob job: passed automatically by Toil
:param str r1_id: FileStoreID of fastq (pair 1)
:param str r2_id: FileStoreID of fastq (pair 2 if applicable, else pass None)
:param str star_index_url: STAR index tarball
:param bool wiggle: If True, will output a wiggle file and return it
:return: FileStoreID from RSEM
:rtype: str | [
"Performs",
"alignment",
"of",
"fastqs",
"to",
"bam",
"via",
"STAR"
] | python | test |
pschmitt/python-opsview | opsview/opsview.py | https://github.com/pschmitt/python-opsview/blob/720acc06c491db32d18c79d20f04cae16e57a7fb/opsview/opsview.py#L142-L148 | def user_info(self, verbose=False):
'''
Get information about the currently authenticated user
http://docs.opsview.com/doku.php?id=opsview4.6:restapi#user_information
'''
url = '{}/{}'.format(self.rest_url, 'user')
return self.__auth_req_get(url, verbose=verbose) | [
"def",
"user_info",
"(",
"self",
",",
"verbose",
"=",
"False",
")",
":",
"url",
"=",
"'{}/{}'",
".",
"format",
"(",
"self",
".",
"rest_url",
",",
"'user'",
")",
"return",
"self",
".",
"__auth_req_get",
"(",
"url",
",",
"verbose",
"=",
"verbose",
")"
] | Get information about the currently authenticated user
http://docs.opsview.com/doku.php?id=opsview4.6:restapi#user_information | [
"Get",
"information",
"about",
"the",
"currently",
"authenticated",
"user",
"http",
":",
"//",
"docs",
".",
"opsview",
".",
"com",
"/",
"doku",
".",
"php?id",
"=",
"opsview4",
".",
"6",
":",
"restapi#user_information"
] | python | train |
jonathf/chaospy | chaospy/distributions/evaluation/bound.py | https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/distributions/evaluation/bound.py#L32-L75 | def evaluate_bound(
distribution,
x_data,
parameters=None,
cache=None,
):
"""
Evaluate lower and upper bounds.
Args:
distribution (Dist):
Distribution to evaluate.
x_data (numpy.ndarray):
Locations for where evaluate bounds at. Relevant in the case of
multivariate distributions where the bounds are affected by the
output of other distributions.
parameters (:py:data:typing.Any):
Collection of parameters to override the default ones in the
distribution.
cache (:py:data:typing.Any):
A collection of previous calculations in case the same distribution
turns up on more than one occasion.
Returns:
The lower and upper bounds of ``distribution`` at location
``x_data`` using parameters ``parameters``.
"""
assert len(x_data) == len(distribution)
assert len(x_data.shape) == 2
cache = cache if cache is not None else {}
parameters = load_parameters(
distribution, "_bnd", parameters=parameters, cache=cache)
out = numpy.zeros((2,) + x_data.shape)
lower, upper = distribution._bnd(x_data.copy(), **parameters)
out.T[:, :, 0] = numpy.asfarray(lower).T
out.T[:, :, 1] = numpy.asfarray(upper).T
cache[distribution] = out
return out | [
"def",
"evaluate_bound",
"(",
"distribution",
",",
"x_data",
",",
"parameters",
"=",
"None",
",",
"cache",
"=",
"None",
",",
")",
":",
"assert",
"len",
"(",
"x_data",
")",
"==",
"len",
"(",
"distribution",
")",
"assert",
"len",
"(",
"x_data",
".",
"sha... | Evaluate lower and upper bounds.
Args:
distribution (Dist):
Distribution to evaluate.
x_data (numpy.ndarray):
Locations for where evaluate bounds at. Relevant in the case of
multivariate distributions where the bounds are affected by the
output of other distributions.
parameters (:py:data:typing.Any):
Collection of parameters to override the default ones in the
distribution.
cache (:py:data:typing.Any):
A collection of previous calculations in case the same distribution
turns up on more than one occasion.
Returns:
The lower and upper bounds of ``distribution`` at location
``x_data`` using parameters ``parameters``. | [
"Evaluate",
"lower",
"and",
"upper",
"bounds",
"."
] | python | train |
SALib/SALib | src/SALib/sample/morris/__init__.py | https://github.com/SALib/SALib/blob/9744d73bb17cfcffc8282c7dc4a727efdc4bea3f/src/SALib/sample/morris/__init__.py#L129-L166 | def _sample_groups(problem, N, num_levels=4):
"""Generate trajectories for groups
Returns an :math:`N(g+1)`-by-:math:`k` array of `N` trajectories,
where :math:`g` is the number of groups and :math:`k` is the number
of factors
Arguments
---------
problem : dict
The problem definition
N : int
The number of trajectories to generate
num_levels : int, default=4
The number of grid levels
Returns
-------
numpy.ndarray
"""
if len(problem['groups']) != problem['num_vars']:
raise ValueError("Groups do not match to number of variables")
group_membership, _ = compute_groups_matrix(problem['groups'])
if group_membership is None:
raise ValueError("Please define the 'group_membership' matrix")
if not isinstance(group_membership, np.ndarray):
raise TypeError("Argument 'group_membership' should be formatted \
as a numpy ndarray")
num_params = group_membership.shape[0]
num_groups = group_membership.shape[1]
sample = np.zeros((N * (num_groups + 1), num_params))
sample = np.array([generate_trajectory(group_membership,
num_levels)
for n in range(N)])
return sample.reshape((N * (num_groups + 1), num_params)) | [
"def",
"_sample_groups",
"(",
"problem",
",",
"N",
",",
"num_levels",
"=",
"4",
")",
":",
"if",
"len",
"(",
"problem",
"[",
"'groups'",
"]",
")",
"!=",
"problem",
"[",
"'num_vars'",
"]",
":",
"raise",
"ValueError",
"(",
"\"Groups do not match to number of va... | Generate trajectories for groups
Returns an :math:`N(g+1)`-by-:math:`k` array of `N` trajectories,
where :math:`g` is the number of groups and :math:`k` is the number
of factors
Arguments
---------
problem : dict
The problem definition
N : int
The number of trajectories to generate
num_levels : int, default=4
The number of grid levels
Returns
-------
numpy.ndarray | [
"Generate",
"trajectories",
"for",
"groups"
] | python | train |
square/pylink | pylink/jlink.py | https://github.com/square/pylink/blob/81dda0a191d923a8b2627c52cb778aba24d279d7/pylink/jlink.py#L3510-L3542 | def breakpoint_set(self, addr, thumb=False, arm=False):
"""Sets a breakpoint at the specified address.
If ``thumb`` is ``True``, the breakpoint is set in THUMB-mode, while if
``arm`` is ``True``, the breakpoint is set in ARM-mode, otherwise a
normal breakpoint is set.
Args:
self (JLink): the ``JLink`` instance
addr (int): the address where the breakpoint will be set
thumb (bool): boolean indicating to set the breakpoint in THUMB mode
arm (bool): boolean indicating to set the breakpoint in ARM mode
Returns:
An integer specifying the breakpoint handle. This handle should be
retained for future breakpoint operations.
Raises:
TypeError: if the given address is not an integer.
JLinkException: if the breakpoint could not be set.
"""
flags = enums.JLinkBreakpoint.ANY
if thumb:
flags = flags | enums.JLinkBreakpoint.THUMB
elif arm:
flags = flags | enums.JLinkBreakpoint.ARM
handle = self._dll.JLINKARM_SetBPEx(int(addr), flags)
if handle <= 0:
raise errors.JLinkException('Breakpoint could not be set.')
return handle | [
"def",
"breakpoint_set",
"(",
"self",
",",
"addr",
",",
"thumb",
"=",
"False",
",",
"arm",
"=",
"False",
")",
":",
"flags",
"=",
"enums",
".",
"JLinkBreakpoint",
".",
"ANY",
"if",
"thumb",
":",
"flags",
"=",
"flags",
"|",
"enums",
".",
"JLinkBreakpoint... | Sets a breakpoint at the specified address.
If ``thumb`` is ``True``, the breakpoint is set in THUMB-mode, while if
``arm`` is ``True``, the breakpoint is set in ARM-mode, otherwise a
normal breakpoint is set.
Args:
self (JLink): the ``JLink`` instance
addr (int): the address where the breakpoint will be set
thumb (bool): boolean indicating to set the breakpoint in THUMB mode
arm (bool): boolean indicating to set the breakpoint in ARM mode
Returns:
An integer specifying the breakpoint handle. This handle should be
retained for future breakpoint operations.
Raises:
TypeError: if the given address is not an integer.
JLinkException: if the breakpoint could not be set. | [
"Sets",
"a",
"breakpoint",
"at",
"the",
"specified",
"address",
"."
] | python | train |
lrq3000/pyFileFixity | pyFileFixity/lib/reedsolomon/reedsolo.py | https://github.com/lrq3000/pyFileFixity/blob/fd5ef23bb13835faf1e3baa773619b86a1cc9bdf/pyFileFixity/lib/reedsolomon/reedsolo.py#L316-L330 | def gf_poly_mul(p, q):
'''Multiply two polynomials, inside Galois Field (but the procedure is generic). Optimized function by precomputation of log.'''
# Pre-allocate the result array
r = bytearray(len(p) + len(q) - 1)
# Precompute the logarithm of p
lp = [gf_log[p[i]] for i in xrange(len(p))]
# Compute the polynomial multiplication (just like the outer product of two vectors, we multiply each coefficients of p with all coefficients of q)
for j in xrange(len(q)):
qj = q[j] # optimization: load the coefficient once
if qj != 0: # log(0) is undefined, we need to check that
lq = gf_log[qj] # Optimization: precache the logarithm of the current coefficient of q
for i in xrange(len(p)):
if p[i] != 0: # log(0) is undefined, need to check that...
r[i + j] ^= gf_exp[lp[i] + lq] # equivalent to: r[i + j] = gf_add(r[i+j], gf_mul(p[i], q[j]))
return r | [
"def",
"gf_poly_mul",
"(",
"p",
",",
"q",
")",
":",
"# Pre-allocate the result array",
"r",
"=",
"bytearray",
"(",
"len",
"(",
"p",
")",
"+",
"len",
"(",
"q",
")",
"-",
"1",
")",
"# Precompute the logarithm of p",
"lp",
"=",
"[",
"gf_log",
"[",
"p",
"[... | Multiply two polynomials, inside Galois Field (but the procedure is generic). Optimized function by precomputation of log. | [
"Multiply",
"two",
"polynomials",
"inside",
"Galois",
"Field",
"(",
"but",
"the",
"procedure",
"is",
"generic",
")",
".",
"Optimized",
"function",
"by",
"precomputation",
"of",
"log",
"."
] | python | train |
fumitoh/modelx | modelx/core/spacecontainer.py | https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/core/spacecontainer.py#L94-L121 | def import_module(self, module=None, recursive=False, **params):
"""Create a child space from an module.
Args:
module: a module object or name of the module object.
recursive: Not yet implemented.
**params: arguments to pass to ``new_space``
Returns:
The new child space created from the module.
"""
if module is None:
if "module_" in params:
warnings.warn(
"Parameter 'module_' is deprecated. Use 'module' instead.")
module = params.pop("module_")
else:
raise ValueError("no module specified")
if "bases" in params:
params["bases"] = get_impls(params["bases"])
space = (
self._impl.model.currentspace
) = self._impl.new_space_from_module(
module, recursive=recursive, **params
)
return get_interfaces(space) | [
"def",
"import_module",
"(",
"self",
",",
"module",
"=",
"None",
",",
"recursive",
"=",
"False",
",",
"*",
"*",
"params",
")",
":",
"if",
"module",
"is",
"None",
":",
"if",
"\"module_\"",
"in",
"params",
":",
"warnings",
".",
"warn",
"(",
"\"Parameter ... | Create a child space from an module.
Args:
module: a module object or name of the module object.
recursive: Not yet implemented.
**params: arguments to pass to ``new_space``
Returns:
The new child space created from the module. | [
"Create",
"a",
"child",
"space",
"from",
"an",
"module",
"."
] | python | valid |
googleapis/google-cloud-python | bigquery/google/cloud/bigquery/table.py | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery/google/cloud/bigquery/table.py#L1907-L1922 | def _rows_page_start(iterator, page, response):
"""Grab total rows when :class:`~google.cloud.iterator.Page` starts.
:type iterator: :class:`~google.api_core.page_iterator.Iterator`
:param iterator: The iterator that is currently in use.
:type page: :class:`~google.api_core.page_iterator.Page`
:param page: The page that was just created.
:type response: dict
:param response: The JSON API response for a page of rows in a table.
"""
total_rows = response.get("totalRows")
if total_rows is not None:
total_rows = int(total_rows)
iterator._total_rows = total_rows | [
"def",
"_rows_page_start",
"(",
"iterator",
",",
"page",
",",
"response",
")",
":",
"total_rows",
"=",
"response",
".",
"get",
"(",
"\"totalRows\"",
")",
"if",
"total_rows",
"is",
"not",
"None",
":",
"total_rows",
"=",
"int",
"(",
"total_rows",
")",
"itera... | Grab total rows when :class:`~google.cloud.iterator.Page` starts.
:type iterator: :class:`~google.api_core.page_iterator.Iterator`
:param iterator: The iterator that is currently in use.
:type page: :class:`~google.api_core.page_iterator.Page`
:param page: The page that was just created.
:type response: dict
:param response: The JSON API response for a page of rows in a table. | [
"Grab",
"total",
"rows",
"when",
":",
"class",
":",
"~google",
".",
"cloud",
".",
"iterator",
".",
"Page",
"starts",
"."
] | python | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.