text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def mean(name, add, match):
'''
Accept a numeric value from the matched events and store a running average
of the values in the given register. If the specified value is not numeric
it will be skipped
USAGE:
.. code-block:: yaml
foo:
reg.mean:
- add: data_field
... | [
"def",
"mean",
"(",
"name",
",",
"add",
",",
"match",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'changes'",
":",
"{",
"}",
",",
"'comment'",
":",
"''",
",",
"'result'",
":",
"True",
"}",
"if",
"name",
"not",
"in",
"__reg__",
":",
... | 29.487179 | 0.001684 |
def quantize_factor(factor_data,
quantiles=5,
bins=None,
by_group=False,
no_raise=False,
zero_aware=False):
"""
Computes period wise factor quantiles.
Parameters
----------
factor_data : pd.DataFrame... | [
"def",
"quantize_factor",
"(",
"factor_data",
",",
"quantiles",
"=",
"5",
",",
"bins",
"=",
"None",
",",
"by_group",
"=",
"False",
",",
"no_raise",
"=",
"False",
",",
"zero_aware",
"=",
"False",
")",
":",
"if",
"not",
"(",
"(",
"quantiles",
"is",
"not"... | 44.848837 | 0.000254 |
def get_default_terminal(environ=None, fallback=_UNSPECIFIED):
"""Get the user's default terminal program."""
if environ is None:
environ = os.environ
# If the option is specified in the environment, respect it.
if "PIAS_OPT_TERMINAL" in environ:
return environ["PIAS_OPT_TERMINAL"]
#... | [
"def",
"get_default_terminal",
"(",
"environ",
"=",
"None",
",",
"fallback",
"=",
"_UNSPECIFIED",
")",
":",
"if",
"environ",
"is",
"None",
":",
"environ",
"=",
"os",
".",
"environ",
"# If the option is specified in the environment, respect it.",
"if",
"\"PIAS_OPT_TERM... | 40.576923 | 0.000926 |
def bundle_changed(self, event):
# type: (BundleEvent) -> None
"""
A bundle event has been triggered
:param event: The bundle event
"""
kind = event.get_kind()
bundle = event.get_bundle()
if kind == BundleEvent.STOPPING_PRECLEAN:
# A bundle i... | [
"def",
"bundle_changed",
"(",
"self",
",",
"event",
")",
":",
"# type: (BundleEvent) -> None",
"kind",
"=",
"event",
".",
"get_kind",
"(",
")",
"bundle",
"=",
"event",
".",
"get_bundle",
"(",
")",
"if",
"kind",
"==",
"BundleEvent",
".",
"STOPPING_PRECLEAN",
... | 38.705882 | 0.002224 |
def start(self, *args, **kwargs):
"""
Set the arguments for the callback function and start the
thread
"""
self.runArgs = args
self.runKwargs = kwargs
Thread.start(self) | [
"def",
"start",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"runArgs",
"=",
"args",
"self",
".",
"runKwargs",
"=",
"kwargs",
"Thread",
".",
"start",
"(",
"self",
")"
] | 19.4 | 0.009852 |
def WriteFlowRequests(self, requests, cursor=None):
"""Writes a list of flow requests to the database."""
args = []
templates = []
flow_keys = []
needs_processing = {}
for r in requests:
if r.needs_processing:
needs_processing.setdefault((r.client_id, r.flow_id), []).append(r)
... | [
"def",
"WriteFlowRequests",
"(",
"self",
",",
"requests",
",",
"cursor",
"=",
"None",
")",
":",
"args",
"=",
"[",
"]",
"templates",
"=",
"[",
"]",
"flow_keys",
"=",
"[",
"]",
"needs_processing",
"=",
"{",
"}",
"for",
"r",
"in",
"requests",
":",
"if",... | 36.448276 | 0.008291 |
def URL(base, path, segments=None, defaults=None):
"""
URL segment handler capable of getting and setting segments by name. The
URL is constructed by joining base, path and segments.
For each segment a property capable of getting and setting that segment is
created dynamically.
"""
# Make a... | [
"def",
"URL",
"(",
"base",
",",
"path",
",",
"segments",
"=",
"None",
",",
"defaults",
"=",
"None",
")",
":",
"# Make a copy of the Segments class",
"url_class",
"=",
"type",
"(",
"Segments",
".",
"__name__",
",",
"Segments",
".",
"__bases__",
",",
"dict",
... | 45.388889 | 0.001199 |
def main():
""" Called by PyBridge.start()
"""
#: If we set the TMP env variable the dev reloader will save file
#: and load changes in this directory instead of overwriting the
#: ones installed with the app.
os.environ['TMP'] = os.path.join(sys.path[0], '../tmp')
from enamlnative.android... | [
"def",
"main",
"(",
")",
":",
"#: If we set the TMP env variable the dev reloader will save file",
"#: and load changes in this directory instead of overwriting the",
"#: ones installed with the app.",
"os",
".",
"environ",
"[",
"'TMP'",
"]",
"=",
"os",
".",
"path",
".",
"join"... | 28.352941 | 0.002008 |
def returner(ret):
'''
Return data to a Cassandra ColumnFamily
'''
consistency_level = getattr(pycassa.ConsistencyLevel,
__opts__['cassandra.consistency_level'])
pool = pycassa.ConnectionPool(__opts__['cassandra.keyspace'],
__opts__... | [
"def",
"returner",
"(",
"ret",
")",
":",
"consistency_level",
"=",
"getattr",
"(",
"pycassa",
".",
"ConsistencyLevel",
",",
"__opts__",
"[",
"'cassandra.consistency_level'",
"]",
")",
"pool",
"=",
"pycassa",
".",
"ConnectionPool",
"(",
"__opts__",
"[",
"'cassand... | 35.956522 | 0.001178 |
def docinfo2dict(doctree):
"""
Return the docinfo field list from a doctree as a dictionary
Note: there can be multiple instances of a single field in the docinfo.
Since a dictionary is returned, the last instance's value will win.
Example:
pub = rst2pub(rst_string)
print docinfo2... | [
"def",
"docinfo2dict",
"(",
"doctree",
")",
":",
"nodes",
"=",
"doctree",
".",
"traverse",
"(",
"docutils",
".",
"nodes",
".",
"docinfo",
")",
"md",
"=",
"{",
"}",
"if",
"not",
"nodes",
":",
"return",
"md",
"for",
"node",
"in",
"nodes",
"[",
"0",
"... | 33.777778 | 0.001066 |
def _pull_status(data, item):
'''
Process a status update from a docker pull, updating the data structure.
For containers created with older versions of Docker, there is no
distinction in the status updates between layers that were already present
(and thus not necessary to download), and those whi... | [
"def",
"_pull_status",
"(",
"data",
",",
"item",
")",
":",
"def",
"_already_exists",
"(",
"id_",
")",
":",
"'''\n Layer already exists\n '''",
"already_pulled",
"=",
"data",
".",
"setdefault",
"(",
"'Layers'",
",",
"{",
"}",
")",
".",
"setdefault",... | 39.275862 | 0.000428 |
def _lazy_child(self, index):
"""
Builds a child object if the child has only been parsed into a tuple so far
"""
child = self.children[index]
if child.__class__ == tuple:
child = self.children[index] = _build(*child)
return child | [
"def",
"_lazy_child",
"(",
"self",
",",
"index",
")",
":",
"child",
"=",
"self",
".",
"children",
"[",
"index",
"]",
"if",
"child",
".",
"__class__",
"==",
"tuple",
":",
"child",
"=",
"self",
".",
"children",
"[",
"index",
"]",
"=",
"_build",
"(",
... | 31.444444 | 0.010309 |
def plot_main(pid, return_fig_ax=False):
"""Main function for creating these plots.
Reads in plot info dict from json file or dictionary in script.
Args:
return_fig_ax (bool, optional): Return figure and axes objects.
Returns:
2-element tuple containing
- **fig** (*obj*): ... | [
"def",
"plot_main",
"(",
"pid",
",",
"return_fig_ax",
"=",
"False",
")",
":",
"global",
"WORKING_DIRECTORY",
",",
"SNR_CUT",
"if",
"isinstance",
"(",
"pid",
",",
"PlotInput",
")",
":",
"pid",
"=",
"pid",
".",
"return_dict",
"(",
")",
"WORKING_DIRECTORY",
"... | 30.943396 | 0.002364 |
def errdp(marker, number):
"""
Substitute a double precision number for the first occurrence of
a marker found in the current long error message.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/errdp_c.html
:param marker: A substring of the error message to be replaced.
:type marker: s... | [
"def",
"errdp",
"(",
"marker",
",",
"number",
")",
":",
"marker",
"=",
"stypes",
".",
"stringToCharP",
"(",
"marker",
")",
"number",
"=",
"ctypes",
".",
"c_double",
"(",
"number",
")",
"libspice",
".",
"errdp_c",
"(",
"marker",
",",
"number",
")"
] | 34.466667 | 0.001883 |
def stage_http_request(self, conn_id, version, url, target, method, headers,
payload):
"""Log request HTTP information including url, headers, etc."""
if self.enabled and self.http_detail_level is not None and \
self.httplogger.isEnabledFor(logging.DEBUG):
... | [
"def",
"stage_http_request",
"(",
"self",
",",
"conn_id",
",",
"version",
",",
"url",
",",
"target",
",",
"method",
",",
"headers",
",",
"payload",
")",
":",
"if",
"self",
".",
"enabled",
"and",
"self",
".",
"http_detail_level",
"is",
"not",
"None",
"and... | 50.461538 | 0.002244 |
def __runTimer(self):
"""运行在计时器线程中的循环函数"""
while self.__timerActive:
# 创建计时器事件
event = Event(type_=EVENT_TIMER)
# 向队列中存入计时器事件
self.put(event)
# 等待
sleep(self.__timerSleep) | [
"def",
"__runTimer",
"(",
"self",
")",
":",
"while",
"self",
".",
"__timerActive",
":",
"# 创建计时器事件",
"event",
"=",
"Event",
"(",
"type_",
"=",
"EVENT_TIMER",
")",
"# 向队列中存入计时器事件",
"self",
".",
"put",
"(",
"event",
")",
"# 等待",
"sleep",
"(",
"self",
".",
... | 25 | 0.017544 |
def fit_2dgaussian(data, error=None, mask=None):
"""
Fit a 2D Gaussian plus a constant to a 2D image.
Invalid values (e.g. NaNs or infs) in the ``data`` or ``error``
arrays are automatically masked. The mask for invalid values
represents the combination of the invalid-value masks for the
``dat... | [
"def",
"fit_2dgaussian",
"(",
"data",
",",
"error",
"=",
"None",
",",
"mask",
"=",
"None",
")",
":",
"from",
".",
".",
"morphology",
"import",
"data_properties",
"# prevent circular imports",
"data",
"=",
"np",
".",
"ma",
".",
"asanyarray",
"(",
"data",
")... | 36.317073 | 0.000327 |
def clone(self, name=None):
"""
:param name: new env name
:rtype: Environment
"""
resp = self._router.post_env_clone(env_id=self.environmentId, json=dict(name=name) if name else {}).json()
return Environment(self.organization, id=resp['id']).init_router(self._router) | [
"def",
"clone",
"(",
"self",
",",
"name",
"=",
"None",
")",
":",
"resp",
"=",
"self",
".",
"_router",
".",
"post_env_clone",
"(",
"env_id",
"=",
"self",
".",
"environmentId",
",",
"json",
"=",
"dict",
"(",
"name",
"=",
"name",
")",
"if",
"name",
"e... | 44.142857 | 0.012698 |
def refunds_get(self, **kwargs):
'''taobao.increment.refunds.get 获取退款变更通知信息
开通主动通知业务的APP可以通过该接口获取用户的退款变更通知信息 建议在获取增量消息的时间间隔是:半个小时'''
request = TOPRequest('taobao.increment.refunds.get')
for k, v in kwargs.iteritems():
if k not in ('status', 'nick', 'start_modified', ... | [
"def",
"refunds_get",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"request",
"=",
"TOPRequest",
"(",
"'taobao.increment.refunds.get'",
")",
"for",
"k",
",",
"v",
"in",
"kwargs",
".",
"iteritems",
"(",
")",
":",
"if",
"k",
"not",
"in",
"(",
"'status... | 56.1 | 0.015789 |
def do_disable_commands(self, _):
"""Disable the Application Management commands"""
message_to_print = "{} is not available while {} commands are disabled".format(COMMAND_NAME,
self.CMD_CAT_APP_MGMT)
self.disa... | [
"def",
"do_disable_commands",
"(",
"self",
",",
"_",
")",
":",
"message_to_print",
"=",
"\"{} is not available while {} commands are disabled\"",
".",
"format",
"(",
"COMMAND_NAME",
",",
"self",
".",
"CMD_CAT_APP_MGMT",
")",
"self",
".",
"disable_category",
"(",
"self... | 74.5 | 0.00885 |
def _convert_bundle(bundle):
""" Converts ambry bundle to dict ready to send to CKAN API.
Args:
bundle (ambry.bundle.Bundle): bundle to convert.
Returns:
dict: dict to send to CKAN to create dataset.
See http://docs.ckan.org/en/latest/api/#ckan.logic.action.create.package_creat... | [
"def",
"_convert_bundle",
"(",
"bundle",
")",
":",
"# shortcut for metadata",
"meta",
"=",
"bundle",
".",
"dataset",
".",
"config",
".",
"metadata",
"notes",
"=",
"''",
"for",
"f",
"in",
"bundle",
".",
"dataset",
".",
"files",
":",
"if",
"f",
".",
"path"... | 30.871795 | 0.00161 |
def fromstring(text):
"""Create a SVG figure from a string.
Parameters
----------
text : str
string representing the SVG content. Must be valid SVG.
Returns
-------
SVGFigure
newly created :py:class:`SVGFigure` initialised with the string
content.
"""
fig = ... | [
"def",
"fromstring",
"(",
"text",
")",
":",
"fig",
"=",
"SVGFigure",
"(",
")",
"svg",
"=",
"etree",
".",
"fromstring",
"(",
"text",
".",
"encode",
"(",
")",
")",
"fig",
".",
"root",
"=",
"svg",
"return",
"fig"
] | 19.5 | 0.002445 |
def format_atomic(value):
"""Format atomic value
This function also takes care of escaping the value in case one of the
reserved characters occurs in the value.
"""
# Perform escaping
if isinstance(value, str):
if any(r in value for r in record.RESERVED_CHARS):
for k, v in r... | [
"def",
"format_atomic",
"(",
"value",
")",
":",
"# Perform escaping",
"if",
"isinstance",
"(",
"value",
",",
"str",
")",
":",
"if",
"any",
"(",
"r",
"in",
"value",
"for",
"r",
"in",
"record",
".",
"RESERVED_CHARS",
")",
":",
"for",
"k",
",",
"v",
"in... | 30.1875 | 0.002008 |
def list(self, *args, **kwargs):
"""
List networks. Similar to the ``docker networks ls`` command.
Args:
names (:py:class:`list`): List of names to filter by.
ids (:py:class:`list`): List of ids to filter by.
filters (dict): Filters to be processed on the net... | [
"def",
"list",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"greedy",
"=",
"kwargs",
".",
"pop",
"(",
"'greedy'",
",",
"False",
")",
"resp",
"=",
"self",
".",
"client",
".",
"api",
".",
"networks",
"(",
"*",
"args",
",",
"*... | 42.586207 | 0.001584 |
def fourier2dpad(data, zero_pad=True):
"""Compute the 2D Fourier transform with zero padding
Parameters
----------
data: 2d fload ndarray
real-valued image data
zero_pad: bool
perform zero-padding to next order of 2
"""
if zero_pad:
# zero padding size is next order ... | [
"def",
"fourier2dpad",
"(",
"data",
",",
"zero_pad",
"=",
"True",
")",
":",
"if",
"zero_pad",
":",
"# zero padding size is next order of 2",
"(",
"N",
",",
"M",
")",
"=",
"data",
".",
"shape",
"order",
"=",
"np",
".",
"int",
"(",
"max",
"(",
"64.",
","... | 28.291667 | 0.001425 |
def WriteBlobToFile(self, request):
"""Writes the blob to a file and returns its path."""
# First chunk truncates the file, later chunks append.
if request.offset == 0:
mode = "w+b"
else:
mode = "r+b"
temp_file = tempfiles.CreateGRRTempFile(
filename=request.write_path, mode=mod... | [
"def",
"WriteBlobToFile",
"(",
"self",
",",
"request",
")",
":",
"# First chunk truncates the file, later chunks append.",
"if",
"request",
".",
"offset",
"==",
"0",
":",
"mode",
"=",
"\"w+b\"",
"else",
":",
"mode",
"=",
"\"r+b\"",
"temp_file",
"=",
"tempfiles",
... | 28.45 | 0.013605 |
def OnUpView(self, event):
"""Request to move up the hierarchy to highest-weight parent"""
node = self.activated_node
parents = []
selected_parent = None
if node:
if hasattr( self.adapter, 'best_parent' ):
selected_parent = self.adapter.best_p... | [
"def",
"OnUpView",
"(",
"self",
",",
"event",
")",
":",
"node",
"=",
"self",
".",
"activated_node",
"parents",
"=",
"[",
"]",
"selected_parent",
"=",
"None",
"if",
"node",
":",
"if",
"hasattr",
"(",
"self",
".",
"adapter",
",",
"'best_parent'",
")",
":... | 41.956522 | 0.013171 |
def _make_version(major, minor, micro, level, serial):
"""Generate version string from tuple (almost entirely from coveragepy)."""
level_dict = {"alpha": "a", "beta": "b", "candidate": "rc", "final": ""}
if level not in level_dict:
raise RuntimeError("Invalid release level")
version = "{0:d}.{1:... | [
"def",
"_make_version",
"(",
"major",
",",
"minor",
",",
"micro",
",",
"level",
",",
"serial",
")",
":",
"level_dict",
"=",
"{",
"\"alpha\"",
":",
"\"a\"",
",",
"\"beta\"",
":",
"\"b\"",
",",
"\"candidate\"",
":",
"\"rc\"",
",",
"\"final\"",
":",
"\"\"",... | 45.272727 | 0.001969 |
def _loadFolders(self,
start=1,
num=100):
"""
Returns the items for the current location of the user's content
Inputs:
start - The number of the first entry in the result set
response. The index number is 1-based.
... | [
"def",
"_loadFolders",
"(",
"self",
",",
"start",
"=",
"1",
",",
"num",
"=",
"100",
")",
":",
"url",
"=",
"self",
".",
"root",
"params",
"=",
"{",
"\"f\"",
":",
"\"json\"",
",",
"\"num\"",
":",
"num",
",",
"\"start\"",
":",
"start",
"}",
"res",
"... | 35.444444 | 0.008643 |
def coordinates(self, x0, y0, distance, angle):
""" Calculates the coordinates of a point from the origin.
"""
x = x0 + cos(radians(angle)) * distance
y = y0 + sin(radians(angle)) * distance
return Point(x, y) | [
"def",
"coordinates",
"(",
"self",
",",
"x0",
",",
"y0",
",",
"distance",
",",
"angle",
")",
":",
"x",
"=",
"x0",
"+",
"cos",
"(",
"radians",
"(",
"angle",
")",
")",
"*",
"distance",
"y",
"=",
"y0",
"+",
"sin",
"(",
"radians",
"(",
"angle",
")"... | 32.5 | 0.014981 |
def _locate_element(dom, el_content, transformer=None):
"""
Find element containing `el_content` in `dom`. Use `transformer` function
to content of all elements in `dom` in order to correctly transforming them
to match them with `el_content`.
Args:
dom (obj): HTMLElement tree.
el_co... | [
"def",
"_locate_element",
"(",
"dom",
",",
"el_content",
",",
"transformer",
"=",
"None",
")",
":",
"return",
"dom",
".",
"find",
"(",
"None",
",",
"fn",
"=",
"utils",
".",
"content_matchs",
"(",
"el_content",
",",
"transformer",
")",
")"
] | 29.869565 | 0.00141 |
def fill(self, **kwargs):
''' Loads the relationships into this model. They are not loaded by
default '''
setattr(self.obj, self.name, self.get(**kwargs)) | [
"def",
"fill",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"setattr",
"(",
"self",
".",
"obj",
",",
"self",
".",
"name",
",",
"self",
".",
"get",
"(",
"*",
"*",
"kwargs",
")",
")"
] | 43.75 | 0.011236 |
def recarray_view(qimage):
"""Returns recarray_ view of a given 32-bit color QImage_'s
memory.
The result is a 2D array with a complex record dtype, offering the
named fields 'r','g','b', and 'a' and corresponding long names.
Thus, each color components can be accessed either via string
indexin... | [
"def",
"recarray_view",
"(",
"qimage",
")",
":",
"raw",
"=",
"_qimage_or_filename_view",
"(",
"qimage",
")",
"if",
"raw",
".",
"itemsize",
"!=",
"4",
":",
"raise",
"ValueError",
"(",
"\"For rgb_view, the image must have 32 bit pixel size (use RGB32, ARGB32, or ARGB32_Prem... | 35.162162 | 0.002244 |
def create_version(self, project_id, model_name, version_spec):
"""
Creates the Version on Google Cloud ML Engine.
Returns the operation if the version was created successfully and
raises an error otherwise.
"""
parent_name = 'projects/{}/models/{}'.format(project_id, mo... | [
"def",
"create_version",
"(",
"self",
",",
"project_id",
",",
"model_name",
",",
"version_spec",
")",
":",
"parent_name",
"=",
"'projects/{}/models/{}'",
".",
"format",
"(",
"project_id",
",",
"model_name",
")",
"create_request",
"=",
"self",
".",
"_mlengine",
"... | 43.421053 | 0.002372 |
def flatten(self, lst=None):
"""syntax.flatten(token_stream) - compile period tokens
This turns a stream of tokens into p-code for the trivial
stack machine that evaluates period expressions in in_period.
"""
tree = []
uops = [] # accumulated unary ... | [
"def",
"flatten",
"(",
"self",
",",
"lst",
"=",
"None",
")",
":",
"tree",
"=",
"[",
"]",
"uops",
"=",
"[",
"]",
"# accumulated unary operations",
"s",
"=",
"Stack",
"(",
")",
"group_len",
"=",
"0",
"# in current precendence group",
"for",
"item",
"in",
"... | 36.690909 | 0.001448 |
def queries(table):
"""Given dictionaries of tables and view-queries, return a dictionary
of all the rest of the queries I need.
"""
def update_where(updcols, wherecols):
"""Return an ``UPDATE`` statement that updates the columns ``updcols``
when the ``wherecols`` match. Every column ha... | [
"def",
"queries",
"(",
"table",
")",
":",
"def",
"update_where",
"(",
"updcols",
",",
"wherecols",
")",
":",
"\"\"\"Return an ``UPDATE`` statement that updates the columns ``updcols``\n when the ``wherecols`` match. Every column has a bound parameter of\n the same name.\n\n... | 34.651163 | 0.001305 |
def _Scroll(self, lines=None):
"""Set attributes to scroll the buffer correctly.
Args:
lines: An int, number of lines to scroll. If None, scrolls
by the terminal length.
"""
if lines is None:
lines = self._cli_lines
if lines < 0:
self._displayed -= self._cli_lines
s... | [
"def",
"_Scroll",
"(",
"self",
",",
"lines",
"=",
"None",
")",
":",
"if",
"lines",
"is",
"None",
":",
"lines",
"=",
"self",
".",
"_cli_lines",
"if",
"lines",
"<",
"0",
":",
"self",
".",
"_displayed",
"-=",
"self",
".",
"_cli_lines",
"self",
".",
"_... | 25 | 0.013487 |
def _Supercooled(T, P):
"""Guideline on thermodynamic properties of supercooled water
Parameters
----------
T : float
Temperature, [K]
P : float
Pressure, [MPa]
Returns
-------
prop : dict
Dict with calculated properties of water. The available properties are:
... | [
"def",
"_Supercooled",
"(",
"T",
",",
"P",
")",
":",
"# Check input in range of validity",
"if",
"P",
"<",
"198.9",
":",
"Tita",
"=",
"T",
"/",
"235.15",
"Ph",
"=",
"0.1",
"+",
"228.27",
"*",
"(",
"1",
"-",
"Tita",
"**",
"6.243",
")",
"+",
"15.724",
... | 31.023121 | 0.000181 |
def groupby_with_null(data, *args, **kwargs):
"""
Groupby on columns with NaN/None/Null values
Pandas currently does have proper support for
groupby on columns with null values. The nulls
are discarded and so not grouped on.
"""
by = kwargs.get('by', args[0])
altered_columns = {}
i... | [
"def",
"groupby_with_null",
"(",
"data",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"by",
"=",
"kwargs",
".",
"get",
"(",
"'by'",
",",
"args",
"[",
"0",
"]",
")",
"altered_columns",
"=",
"{",
"}",
"if",
"not",
"isinstance",
"(",
"by",
"... | 35.291667 | 0.000574 |
def __cancel(self, preapproval_id, **kwargs):
"""Call documentation: `/preapproval/cancel
<https://www.wepay.com/developer/reference/preapproval#cancel>`_, plus
extra keyword parameters:
:keyword str access_token: will be used instead of instance's
``access_token``, with ``ba... | [
"def",
"__cancel",
"(",
"self",
",",
"preapproval_id",
",",
"*",
"*",
"kwargs",
")",
":",
"params",
"=",
"{",
"'preapproval_id'",
":",
"preapproval_id",
"}",
"return",
"self",
".",
"make_call",
"(",
"self",
".",
"__cancel",
",",
"params",
",",
"kwargs",
... | 36.26087 | 0.002336 |
def __sort_stats(self, sortedby=None):
"""Return the stats (dict) sorted by (sortedby)."""
return sort_stats(self.stats, sortedby,
reverse=glances_processes.sort_reverse) | [
"def",
"__sort_stats",
"(",
"self",
",",
"sortedby",
"=",
"None",
")",
":",
"return",
"sort_stats",
"(",
"self",
".",
"stats",
",",
"sortedby",
",",
"reverse",
"=",
"glances_processes",
".",
"sort_reverse",
")"
] | 52.25 | 0.009434 |
def process_docopts(test=None): # type: (Optional[Dict[str,Any]])->None
"""
Just process the command line options and commands
:return:
"""
if test:
arguments = test
else:
arguments = docopt(__doc__, version="Jiggle Version {0}".format(__version__))
logger.debug(arguments)
... | [
"def",
"process_docopts",
"(",
"test",
"=",
"None",
")",
":",
"# type: (Optional[Dict[str,Any]])->None",
"if",
"test",
":",
"arguments",
"=",
"test",
"else",
":",
"arguments",
"=",
"docopt",
"(",
"__doc__",
",",
"version",
"=",
"\"Jiggle Version {0}\"",
".",
"fo... | 30.784615 | 0.000969 |
def release(self, shortname):
"""
Get a specific release by its shortname.
:param shortname: str, eg. "ceph-3-0"
:returns: deferred that when fired returns a Release (Munch, dict-like)
object representing this release.
:raises: ReleaseNotFoundException if this ... | [
"def",
"release",
"(",
"self",
",",
"shortname",
")",
":",
"url",
"=",
"'api/v6/releases/?shortname=%s'",
"%",
"shortname",
"releases",
"=",
"yield",
"self",
".",
"_get",
"(",
"url",
")",
"# Note, even if this shortname does not exist, _get() will not errback",
"# for t... | 44.777778 | 0.00243 |
def load_merge_candidate(self, filename=None, config=None):
"""Open the candidate config and replace."""
self.config_replace = False
self._load_candidate(filename, config, False) | [
"def",
"load_merge_candidate",
"(",
"self",
",",
"filename",
"=",
"None",
",",
"config",
"=",
"None",
")",
":",
"self",
".",
"config_replace",
"=",
"False",
"self",
".",
"_load_candidate",
"(",
"filename",
",",
"config",
",",
"False",
")"
] | 49.75 | 0.009901 |
def extract_index(index_data, global_index=False):
'''
Instantiates and returns an AllIndex object given a valid index
configuration
CLI Example:
salt myminion boto_dynamodb.extract_index index
'''
parsed_data = {}
keys = []
for key, value in six.iteritems(index_data):
... | [
"def",
"extract_index",
"(",
"index_data",
",",
"global_index",
"=",
"False",
")",
":",
"parsed_data",
"=",
"{",
"}",
"keys",
"=",
"[",
"]",
"for",
"key",
",",
"value",
"in",
"six",
".",
"iteritems",
"(",
"index_data",
")",
":",
"for",
"item",
"in",
... | 36.011905 | 0.000644 |
def version(user=None, host=None, port=None, maintenance_db=None,
password=None, runas=None):
'''
Return the version of a Postgres server.
CLI Example:
.. code-block:: bash
salt '*' postgres.version
'''
query = 'SELECT setting FROM pg_catalog.pg_settings ' \
'W... | [
"def",
"version",
"(",
"user",
"=",
"None",
",",
"host",
"=",
"None",
",",
"port",
"=",
"None",
",",
"maintenance_db",
"=",
"None",
",",
"password",
"=",
"None",
",",
"runas",
"=",
"None",
")",
":",
"query",
"=",
"'SELECT setting FROM pg_catalog.pg_setting... | 30.384615 | 0.001227 |
def filter_from_import(line, unused_module):
"""Parse and filter ``from something import a, b, c``.
Return line without unused import modules, or `pass` if all of the
module in import is unused.
"""
(indentation, imports) = re.split(pattern=r'\bimport\b',
strin... | [
"def",
"filter_from_import",
"(",
"line",
",",
"unused_module",
")",
":",
"(",
"indentation",
",",
"imports",
")",
"=",
"re",
".",
"split",
"(",
"pattern",
"=",
"r'\\bimport\\b'",
",",
"string",
"=",
"line",
",",
"maxsplit",
"=",
"1",
")",
"base_module",
... | 39.419355 | 0.000799 |
def changeSize(self, newsize):
"""
Changes the size of the layer. Should only be called through
Network.changeLayerSize().
"""
# overwrites current data
if newsize <= 0:
raise LayerError('Layer size changed to zero.', newsize)
minSize = min(self.size, ... | [
"def",
"changeSize",
"(",
"self",
",",
"newsize",
")",
":",
"# overwrites current data",
"if",
"newsize",
"<=",
"0",
":",
"raise",
"LayerError",
"(",
"'Layer size changed to zero.'",
",",
"newsize",
")",
"minSize",
"=",
"min",
"(",
"self",
".",
"size",
",",
... | 41.25 | 0.001974 |
def get(self,str_name):
"""
return a column of data with the name str_name.
Parameters
----------
str_name : string
Is the name of the column as printed in the
profilennn.data or lognnn.data file; get the available
columns from self.cols (wher... | [
"def",
"get",
"(",
"self",
",",
"str_name",
")",
":",
"column_array",
"=",
"self",
".",
"data",
"[",
":",
",",
"self",
".",
"cols",
"[",
"str_name",
"]",
"-",
"1",
"]",
".",
"astype",
"(",
"'float'",
")",
"return",
"column_array"
] | 30.1875 | 0.008032 |
def hasCamera(self, nDeviceIndex):
"""For convenience, same as tracked property request Prop_HasCamera_Bool"""
fn = self.function_table.hasCamera
pHasCamera = openvr_bool()
result = fn(nDeviceIndex, byref(pHasCamera))
return result, pHasCamera | [
"def",
"hasCamera",
"(",
"self",
",",
"nDeviceIndex",
")",
":",
"fn",
"=",
"self",
".",
"function_table",
".",
"hasCamera",
"pHasCamera",
"=",
"openvr_bool",
"(",
")",
"result",
"=",
"fn",
"(",
"nDeviceIndex",
",",
"byref",
"(",
"pHasCamera",
")",
")",
"... | 39.714286 | 0.010563 |
def replace_entities(entities, pattern):
"""
Replaces all entity names in a given pattern with the corresponding
values provided by entities.
Args:
entities (dict): A dictionary mapping entity names to entity values.
pattern (str): A path pattern that contains entity names denoted
... | [
"def",
"replace_entities",
"(",
"entities",
",",
"pattern",
")",
":",
"ents",
"=",
"re",
".",
"findall",
"(",
"r'\\{(.*?)\\}'",
",",
"pattern",
")",
"new_path",
"=",
"pattern",
"for",
"ent",
"in",
"ents",
":",
"match",
"=",
"re",
".",
"search",
"(",
"r... | 36.475 | 0.000668 |
def run(self, dag):
"""collect blocks of adjacent gates acting on a pair of "cx" qubits.
The blocks contain "op" nodes in topological sort order
such that all gates in a block act on the same pair of
qubits and are adjacent in the circuit. the blocks are built
by examining prede... | [
"def",
"run",
"(",
"self",
",",
"dag",
")",
":",
"# Initiate the commutation set",
"self",
".",
"property_set",
"[",
"'commutation_set'",
"]",
"=",
"defaultdict",
"(",
"list",
")",
"good_names",
"=",
"[",
"\"cx\"",
",",
"\"u1\"",
",",
"\"u2\"",
",",
"\"u3\""... | 53.88125 | 0.001708 |
def to_frame(self, data, state):
"""
Extract a single frame from the data buffer. The consumed
data should be removed from the buffer. If no complete frame
can be read, must raise a ``NoFrames`` exception.
:param data: A ``bytearray`` instance containing the data so
... | [
"def",
"to_frame",
"(",
"self",
",",
"data",
",",
"state",
")",
":",
"# Find the next packet start",
"if",
"not",
"state",
".",
"frame_start",
":",
"# Find the begin sequence",
"idx",
"=",
"data",
".",
"find",
"(",
"self",
".",
"begin",
")",
"if",
"idx",
"... | 34.75 | 0.001272 |
def random_model(ctx, model_class_name):
"""
Get a random model identifier by class name. For example::
# db/fixtures/Category.yml
{% for i in range(0, 10) %}
category{{ i }}:
name: {{ faker.name() }}
{% endfor %}
# db/fixtures/Post.yml
a_blog_post:
... | [
"def",
"random_model",
"(",
"ctx",
",",
"model_class_name",
")",
":",
"model_identifiers",
"=",
"ctx",
"[",
"'model_identifiers'",
"]",
"[",
"model_class_name",
"]",
"if",
"not",
"model_identifiers",
":",
"return",
"'None'",
"idx",
"=",
"random",
".",
"randrange... | 32.25 | 0.002151 |
def generate_phase_2(phase_1, dim = 40):
"""
The second step in creating datapoints in the Poirazi & Mel model.
This takes a phase 1 vector, and creates a phase 2 vector where each point
is the product of four elements of the phase 1 vector, randomly drawn with
replacement.
"""
phase_2 = []
for i in ran... | [
"def",
"generate_phase_2",
"(",
"phase_1",
",",
"dim",
"=",
"40",
")",
":",
"phase_2",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"dim",
")",
":",
"indices",
"=",
"[",
"numpy",
".",
"random",
".",
"randint",
"(",
"0",
",",
"dim",
")",
"for",
... | 38.25 | 0.014894 |
def serialize(self, msg, ident=None):
"""Serialize the message components to bytes.
This is roughly the inverse of unserialize. The serialize/unserialize
methods work with full message lists, whereas pack/unpack work with
the individual message parts in the message list.
Parame... | [
"def",
"serialize",
"(",
"self",
",",
"msg",
",",
"ident",
"=",
"None",
")",
":",
"content",
"=",
"msg",
".",
"get",
"(",
"'content'",
",",
"{",
"}",
")",
"if",
"content",
"is",
"None",
":",
"content",
"=",
"self",
".",
"none",
"elif",
"isinstance"... | 33.490909 | 0.00211 |
def nmin(wave, indep_min=None, indep_max=None):
r"""
Return the minimum of a waveform's dependent variable vector.
:param wave: Waveform
:type wave: :py:class:`peng.eng.Waveform`
:param indep_min: Independent vector start point of computation
:type indep_min: integer or float
:param ind... | [
"def",
"nmin",
"(",
"wave",
",",
"indep_min",
"=",
"None",
",",
"indep_max",
"=",
"None",
")",
":",
"ret",
"=",
"copy",
".",
"copy",
"(",
"wave",
")",
"_bound_waveform",
"(",
"ret",
",",
"indep_min",
",",
"indep_max",
")",
"return",
"np",
".",
"min",... | 28.029412 | 0.001014 |
def _determine_branch_locations(self, other_services):
"""Determine the branch locations for the other services.
Determine if the local branch being tested is derived from its
stable or next (dev) branch, and based on this, use the corresonding
stable or next branches for the o... | [
"def",
"_determine_branch_locations",
"(",
"self",
",",
"other_services",
")",
":",
"self",
".",
"log",
".",
"info",
"(",
"'OpenStackAmuletDeployment: determine branch locations'",
")",
"# Charms outside the ~openstack-charmers",
"base_charms",
"=",
"{",
"'mysql'",
":",
... | 42.205128 | 0.001188 |
def set_subject(self, value: Union[Literal, Identifier, str], lang: str= None):
""" Set the DC Subject literal value
:param value: Value of the subject node
:param lang: Language in which the value is
"""
return self.metadata.add(key=DC.subject, value=value, lang=lang) | [
"def",
"set_subject",
"(",
"self",
",",
"value",
":",
"Union",
"[",
"Literal",
",",
"Identifier",
",",
"str",
"]",
",",
"lang",
":",
"str",
"=",
"None",
")",
":",
"return",
"self",
".",
"metadata",
".",
"add",
"(",
"key",
"=",
"DC",
".",
"subject",... | 43.428571 | 0.009677 |
def _get_date_pagination(self, base, oldest_neighbor, newest_neighbor):
""" Compute the pagination for date-based views """
_, span, date_format = utils.parse_date(self.spec['date'])
if newest_neighbor:
newer_date = newest_neighbor.date.span(span)[0]
newer_view = View({*... | [
"def",
"_get_date_pagination",
"(",
"self",
",",
"base",
",",
"oldest_neighbor",
",",
"newest_neighbor",
")",
":",
"_",
",",
"span",
",",
"date_format",
"=",
"utils",
".",
"parse_date",
"(",
"self",
".",
"spec",
"[",
"'date'",
"]",
")",
"if",
"newest_neigh... | 38.904762 | 0.002389 |
def _fetchAllChildren(self):
""" Fetches the index if the showIndex member is True
Descendants can override this function to add the subdevicions.
"""
assert self.isSliceable, "No underlying pandas object: self._ndFrame is None"
childItems = []
if self._standAlone:
... | [
"def",
"_fetchAllChildren",
"(",
"self",
")",
":",
"assert",
"self",
".",
"isSliceable",
",",
"\"No underlying pandas object: self._ndFrame is None\"",
"childItems",
"=",
"[",
"]",
"if",
"self",
".",
"_standAlone",
":",
"childItems",
".",
"append",
"(",
"self",
".... | 41.7 | 0.00939 |
def create(ctx, opts, owner_repo, show_tokens, name, token):
"""
Create a new entitlement in a repository.
- OWNER/REPO: Specify the OWNER namespace (i.e. user or org), and the REPO
name where you want to create an entitlement. All separated by a slash.
Example: 'your-org/your-repo'
Ful... | [
"def",
"create",
"(",
"ctx",
",",
"opts",
",",
"owner_repo",
",",
"show_tokens",
",",
"name",
",",
"token",
")",
":",
"owner",
",",
"repo",
"=",
"owner_repo",
"# Use stderr for messages if the output is something else (e.g. # JSON)",
"use_stderr",
"=",
"opts",
".",... | 31.948718 | 0.001558 |
def datafeed(self):
"""
Return a new raw REST interface to feed resources
:rtype: :py:class:`ns1.rest.data.Feed`
"""
import ns1.rest.data
return ns1.rest.data.Feed(self.config) | [
"def",
"datafeed",
"(",
"self",
")",
":",
"import",
"ns1",
".",
"rest",
".",
"data",
"return",
"ns1",
".",
"rest",
".",
"data",
".",
"Feed",
"(",
"self",
".",
"config",
")"
] | 27.25 | 0.008889 |
def from_string(species_string: str):
"""
Returns a Dummy from a string representation.
Args:
species_string (str): A string representation of a dummy
species, e.g., "X2+", "X3+".
Returns:
A DummySpecie object.
Raises:
ValueE... | [
"def",
"from_string",
"(",
"species_string",
":",
"str",
")",
":",
"m",
"=",
"re",
".",
"search",
"(",
"r\"([A-Z][a-z]*)([0-9.]*)([+\\-]*)(.*)\"",
",",
"species_string",
")",
"if",
"m",
":",
"sym",
"=",
"m",
".",
"group",
"(",
"1",
")",
"if",
"m",
".",
... | 34.107143 | 0.002037 |
def _get_deltas(self, rake):
"""
Return the value of deltas (delta_R, delta_S, delta_V, delta_I),
as defined in "Table 5: Model 1" pag 198
"""
# delta_R = 1 for reverse focal mechanism (45<rake<135)
# and for interface events, 0 for all other events
# delta_S = 1 ... | [
"def",
"_get_deltas",
"(",
"self",
",",
"rake",
")",
":",
"# delta_R = 1 for reverse focal mechanism (45<rake<135)",
"# and for interface events, 0 for all other events",
"# delta_S = 1 for Strike-slip focal mechanisms (0<=rake<=45) or",
"# (135<=rake<=180) or (-45<=rake<=0), 0 for all other e... | 36.925926 | 0.001955 |
def ds2n(self):
"""Calculates the derivative of the neutron separation energies:
ds2n(Z,A) = s2n(Z,A) - s2n(Z,A+2)
"""
idx = [(x[0] + 0, x[1] + 2) for x in self.df.index]
values = self.s2n.values - self.s2n.loc[idx].values
return Table(df=pd.Series(values, index=self.df.... | [
"def",
"ds2n",
"(",
"self",
")",
":",
"idx",
"=",
"[",
"(",
"x",
"[",
"0",
"]",
"+",
"0",
",",
"x",
"[",
"1",
"]",
"+",
"2",
")",
"for",
"x",
"in",
"self",
".",
"df",
".",
"index",
"]",
"values",
"=",
"self",
".",
"s2n",
".",
"values",
... | 44.625 | 0.008242 |
def wrap_parser_error(self, data, renderer_context):
"""
Convert parser errors to the JSON API Error format
Parser errors have a status code of 400, like field errors, but have
the same native format as generic errors. Also, the detail message is
often specific to the input, so... | [
"def",
"wrap_parser_error",
"(",
"self",
",",
"data",
",",
"renderer_context",
")",
":",
"response",
"=",
"renderer_context",
".",
"get",
"(",
"\"response\"",
",",
"None",
")",
"status_code",
"=",
"response",
"and",
"response",
".",
"status_code",
"if",
"statu... | 37.62069 | 0.001787 |
def _set_bang_to_py_ast(ctx: GeneratorContext, node: SetBang) -> GeneratedPyAST:
"""Return a Python AST Node for a `set!` expression."""
assert node.op == NodeOp.SET_BANG
val_temp_name = genname("set_bang_val")
val_ast = gen_py_ast(ctx, node.val)
target = node.target
assert isinstance(
... | [
"def",
"_set_bang_to_py_ast",
"(",
"ctx",
":",
"GeneratorContext",
",",
"node",
":",
"SetBang",
")",
"->",
"GeneratedPyAST",
":",
"assert",
"node",
".",
"op",
"==",
"NodeOp",
".",
"SET_BANG",
"val_temp_name",
"=",
"genname",
"(",
"\"set_bang_val\"",
")",
"val_... | 35.384615 | 0.00141 |
def _bg_combine(self, bgs):
"""Combine several background amplitude images"""
out = np.ones(self.h5["raw"].shape, dtype=float)
# bg is an h5py.DataSet
for bg in bgs:
out *= bg[:]
return out | [
"def",
"_bg_combine",
"(",
"self",
",",
"bgs",
")",
":",
"out",
"=",
"np",
".",
"ones",
"(",
"self",
".",
"h5",
"[",
"\"raw\"",
"]",
".",
"shape",
",",
"dtype",
"=",
"float",
")",
"# bg is an h5py.DataSet",
"for",
"bg",
"in",
"bgs",
":",
"out",
"*=... | 33.571429 | 0.008299 |
def generate_epochs_info(epoch_list):
""" use epoch_list to generate epoch_info defined below
Parameters
----------
epoch_list: list of 3D (binary) array in shape [condition, nEpochs, nTRs]
Contains specification of epochs and conditions, assuming
1. all subjects have the same number of... | [
"def",
"generate_epochs_info",
"(",
"epoch_list",
")",
":",
"time1",
"=",
"time",
".",
"time",
"(",
")",
"epoch_info",
"=",
"[",
"]",
"for",
"sid",
",",
"epoch",
"in",
"enumerate",
"(",
"epoch_list",
")",
":",
"for",
"cond",
"in",
"range",
"(",
"epoch"... | 39.486486 | 0.000668 |
def verify_enroll(self, response):
"""Verifies and saves U2F enroll"""
seed = session.pop('_u2f_enroll_')
try:
new_device, cert = complete_register(seed, response, self.__facets_list)
except Exception as e:
if self.__call_fail_enroll:
self.__call_... | [
"def",
"verify_enroll",
"(",
"self",
",",
"response",
")",
":",
"seed",
"=",
"session",
".",
"pop",
"(",
"'_u2f_enroll_'",
")",
"try",
":",
"new_device",
",",
"cert",
"=",
"complete_register",
"(",
"seed",
",",
"response",
",",
"self",
".",
"__facets_list"... | 26.351351 | 0.01088 |
def _get_enterprise_customer_users_batch(self, start, end):
"""
Returns a batched queryset of EnterpriseCustomerUser objects.
"""
LOGGER.info('Fetching new batch of enterprise customer users from indexes: %s to %s', start, end)
return User.objects.filter(pk__in=self._get_enterpri... | [
"def",
"_get_enterprise_customer_users_batch",
"(",
"self",
",",
"start",
",",
"end",
")",
":",
"LOGGER",
".",
"info",
"(",
"'Fetching new batch of enterprise customer users from indexes: %s to %s'",
",",
"start",
",",
"end",
")",
"return",
"User",
".",
"objects",
"."... | 58.166667 | 0.011299 |
def stitch_macro(path, output_folder=None):
"""Create fiji-macros for stitching all channels and z-stacks for a well.
Parameters
----------
path : string
Well path.
output_folder : string
Folder to store images. If not given well path is used.
Returns
-------
output_fil... | [
"def",
"stitch_macro",
"(",
"path",
",",
"output_folder",
"=",
"None",
")",
":",
"output_folder",
"=",
"output_folder",
"or",
"path",
"debug",
"(",
"'stitching '",
"+",
"path",
"+",
"' to '",
"+",
"output_folder",
")",
"fields",
"=",
"glob",
"(",
"_pattern",... | 31.494624 | 0.001324 |
def ctcp_unpack_message(info):
"""Given a an input message (privmsg/pubmsg/notice), return events."""
verb = info['verb']
message = info['params'][1]
# NOTE: full CTCP dequoting and unpacking is not done here, only a subset
# this is because doing the full thing breaks legitimate messages
# ... | [
"def",
"ctcp_unpack_message",
"(",
"info",
")",
":",
"verb",
"=",
"info",
"[",
"'verb'",
"]",
"message",
"=",
"info",
"[",
"'params'",
"]",
"[",
"1",
"]",
"# NOTE: full CTCP dequoting and unpacking is not done here, only a subset",
"# this is because doing the full thin... | 31 | 0.000753 |
def __write_json_file(path, values):
"""Writes a JSON file at the path with the values provided."""
# Sort the keys to ensure ordering
sort_order = ['name', 'switch', 'comment', 'value', 'flags']
sorted_values = [
OrderedDict(
sorted(
value.items(), key=lambda value: ... | [
"def",
"__write_json_file",
"(",
"path",
",",
"values",
")",
":",
"# Sort the keys to ensure ordering",
"sort_order",
"=",
"[",
"'name'",
",",
"'switch'",
",",
"'comment'",
",",
"'value'",
",",
"'flags'",
"]",
"sorted_values",
"=",
"[",
"OrderedDict",
"(",
"sort... | 36.307692 | 0.002066 |
def check_for_period_error(data, period):
"""
Check for Period Error.
This method checks if the developer is trying to enter a period that is
larger than the data set being entered. If that is the case an exception is
raised with a custom message that informs the developer that their period
is ... | [
"def",
"check_for_period_error",
"(",
"data",
",",
"period",
")",
":",
"period",
"=",
"int",
"(",
"period",
")",
"data_len",
"=",
"len",
"(",
"data",
")",
"if",
"data_len",
"<",
"period",
":",
"raise",
"Exception",
"(",
"\"Error: data_len < period\"",
")"
] | 36.153846 | 0.002075 |
def _gcs_list(args, _):
""" List the buckets or the contents of a bucket.
This command is a bit different in that we allow wildchars in the bucket name and will list
the buckets that match.
"""
target = args['objects']
project = args['project']
if target is None:
return _gcs_list_buckets(project, '*'... | [
"def",
"_gcs_list",
"(",
"args",
",",
"_",
")",
":",
"target",
"=",
"args",
"[",
"'objects'",
"]",
"project",
"=",
"args",
"[",
"'project'",
"]",
"if",
"target",
"is",
"None",
":",
"return",
"_gcs_list_buckets",
"(",
"project",
",",
"'*'",
")",
"# List... | 36.325 | 0.016756 |
def ensure_dir_exists(func):
"wrap a function that returns a dir, making sure it exists"
@functools.wraps(func)
def make_if_not_present():
dir = func()
if not os.path.isdir(dir):
os.makedirs(dir)
return dir
return make_if_not_present | [
"def",
"ensure_dir_exists",
"(",
"func",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"make_if_not_present",
"(",
")",
":",
"dir",
"=",
"func",
"(",
")",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"dir",
")",
":",
"os"... | 27.333333 | 0.035433 |
def set(self, section, key, value, comment=None):
"""
Set config value with data type transformation (to str)
:param str section: Section to set config for
:param str key: Key to set config for
:param value: Value for key. It can be any primitive type.
:param str comment... | [
"def",
"set",
"(",
"self",
",",
"section",
",",
"key",
",",
"value",
",",
"comment",
"=",
"None",
")",
":",
"self",
".",
"_read_sources",
"(",
")",
"if",
"(",
"section",
",",
"key",
")",
"in",
"self",
".",
"_dot_keys",
":",
"section",
",",
"key",
... | 31.24 | 0.002484 |
def flat(self):
"""Return a tuple of alternating kind and id values."""
flat = []
for kind, id in self.__pairs:
flat.append(kind)
flat.append(id)
return tuple(flat) | [
"def",
"flat",
"(",
"self",
")",
":",
"flat",
"=",
"[",
"]",
"for",
"kind",
",",
"id",
"in",
"self",
".",
"__pairs",
":",
"flat",
".",
"append",
"(",
"kind",
")",
"flat",
".",
"append",
"(",
"id",
")",
"return",
"tuple",
"(",
"flat",
")"
] | 26.571429 | 0.015625 |
def hybrid_forward(self, F, samples, valid_length, outputs, scores, beam_alive_mask, states):
"""
Parameters
----------
F
samples : NDArray or Symbol
The current samples generated by beam search. Shape (batch_size, beam_size, L)
valid_length : NDArray or Symbo... | [
"def",
"hybrid_forward",
"(",
"self",
",",
"F",
",",
"samples",
",",
"valid_length",
",",
"outputs",
",",
"scores",
",",
"beam_alive_mask",
",",
"states",
")",
":",
"beam_size",
"=",
"self",
".",
"_beam_size",
"# outputs: (batch_size, beam_size, vocab_size)",
"out... | 45.090909 | 0.002302 |
def _to_jd_schematic(year, month, day, method):
'''Calculate JD using various leap-year calculation methods'''
y0, y1, y2, y3, y4, y5 = 0, 0, 0, 0, 0, 0
intercal_cycle_yrs, over_cycle_yrs, leap_suppression_yrs = None, None, None
# Use the every-four-years method below year 16 (madler) or below 15 (ro... | [
"def",
"_to_jd_schematic",
"(",
"year",
",",
"month",
",",
"day",
",",
"method",
")",
":",
"y0",
",",
"y1",
",",
"y2",
",",
"y3",
",",
"y4",
",",
"y5",
"=",
"0",
",",
"0",
",",
"0",
",",
"0",
",",
"0",
",",
"0",
"intercal_cycle_yrs",
",",
"ov... | 31.359375 | 0.001449 |
def encode_command(*args, buf=None):
"""Encodes arguments into redis bulk-strings array.
Raises TypeError if any of args not of bytearray, bytes, float, int, or str
type.
"""
if buf is None:
buf = bytearray()
buf.extend(b'*%d\r\n' % len(args))
try:
for arg in args:
... | [
"def",
"encode_command",
"(",
"*",
"args",
",",
"buf",
"=",
"None",
")",
":",
"if",
"buf",
"is",
"None",
":",
"buf",
"=",
"bytearray",
"(",
")",
"buf",
".",
"extend",
"(",
"b'*%d\\r\\n'",
"%",
"len",
"(",
"args",
")",
")",
"try",
":",
"for",
"arg... | 32.111111 | 0.001681 |
def save_inst(self, obj):
"""Inner logic to save instance. Based off pickle.save_inst"""
cls = obj.__class__
# Try the dispatch table (pickle module doesn't do it)
f = self.dispatch.get(cls)
if f:
f(self, obj) # Call unbound method with explicit self
ret... | [
"def",
"save_inst",
"(",
"self",
",",
"obj",
")",
":",
"cls",
"=",
"obj",
".",
"__class__",
"# Try the dispatch table (pickle module doesn't do it)",
"f",
"=",
"self",
".",
"dispatch",
".",
"get",
"(",
"cls",
")",
"if",
"f",
":",
"f",
"(",
"self",
",",
"... | 26.363636 | 0.001663 |
def get_access_token(self, request, callback=None):
"""Fetch access token from callback request."""
callback = request.build_absolute_uri(callback or request.path)
if not self.check_application_state(request):
logger.error('Application state check failed.')
return None
... | [
"def",
"get_access_token",
"(",
"self",
",",
"request",
",",
"callback",
"=",
"None",
")",
":",
"callback",
"=",
"request",
".",
"build_absolute_uri",
"(",
"callback",
"or",
"request",
".",
"path",
")",
"if",
"not",
"self",
".",
"check_application_state",
"(... | 40.6 | 0.001925 |
def setFilterData(self, key, value):
"""
Sets the filtering information for the given key to the inputed value.
:param key | <str>
value | <str>
"""
self._filterData[nativestring(key)] = nativestring(value) | [
"def",
"setFilterData",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"self",
".",
"_filterData",
"[",
"nativestring",
"(",
"key",
")",
"]",
"=",
"nativestring",
"(",
"value",
")"
] | 34.125 | 0.010714 |
def save_indent(token_class, start=False):
"""Save a possible indentation level."""
def callback(lexer, match, context):
text = match.group()
extra = ''
if start:
context.next_indent = len(text)
if context.next_indent < context.indent:
... | [
"def",
"save_indent",
"(",
"token_class",
",",
"start",
"=",
"False",
")",
":",
"def",
"callback",
"(",
"lexer",
",",
"match",
",",
"context",
")",
":",
"text",
"=",
"match",
".",
"group",
"(",
")",
"extra",
"=",
"''",
"if",
"start",
":",
"context",
... | 42.761905 | 0.002179 |
def close(self):
"""Close the queue, signalling that no more data can be put into the queue."""
self.read_queue.put(QueueClosed)
self.write_queue.put(QueueClosed) | [
"def",
"close",
"(",
"self",
")",
":",
"self",
".",
"read_queue",
".",
"put",
"(",
"QueueClosed",
")",
"self",
".",
"write_queue",
".",
"put",
"(",
"QueueClosed",
")"
] | 45.75 | 0.016129 |
def valueAt( self, pos ):
"""
Returns the value for the slider at the inputed position.
:param pos | <int>
:return <int>
"""
if ( self.orientation() == Qt.Horizontal ):
perc = (self.width() - 4 - pos) / float(self.width())
... | [
"def",
"valueAt",
"(",
"self",
",",
"pos",
")",
":",
"if",
"(",
"self",
".",
"orientation",
"(",
")",
"==",
"Qt",
".",
"Horizontal",
")",
":",
"perc",
"=",
"(",
"self",
".",
"width",
"(",
")",
"-",
"4",
"-",
"pos",
")",
"/",
"float",
"(",
"se... | 30.588235 | 0.020522 |
def clone(self, config, **kwargs):
"""Make a clone of this analysis instance."""
gta = GTAnalysis(config, **kwargs)
gta._roi = copy.deepcopy(self.roi)
return gta | [
"def",
"clone",
"(",
"self",
",",
"config",
",",
"*",
"*",
"kwargs",
")",
":",
"gta",
"=",
"GTAnalysis",
"(",
"config",
",",
"*",
"*",
"kwargs",
")",
"gta",
".",
"_roi",
"=",
"copy",
".",
"deepcopy",
"(",
"self",
".",
"roi",
")",
"return",
"gta"
... | 37.8 | 0.010363 |
def tag_evidence_subtype(evidence):
"""Returns the type and subtype of an evidence object as a string,
typically the extraction rule or database from which the statement
was generated.
For biopax, this is just the database name.
Parameters
----------
statement: indra.statements.Evidence
... | [
"def",
"tag_evidence_subtype",
"(",
"evidence",
")",
":",
"source_api",
"=",
"evidence",
".",
"source_api",
"annotations",
"=",
"evidence",
".",
"annotations",
"if",
"source_api",
"==",
"'biopax'",
":",
"subtype",
"=",
"annotations",
".",
"get",
"(",
"'source_su... | 32.534884 | 0.000694 |
def route_filter_rule_create_or_update(name, access, communities, route_filter, resource_group, **kwargs):
'''
.. versionadded:: 2019.2.0
Create or update a rule within a specified route filter.
:param name: The name of the rule to create.
:param access: The access type of the rule. Valid values ... | [
"def",
"route_filter_rule_create_or_update",
"(",
"name",
",",
"access",
",",
"communities",
",",
"route_filter",
",",
"resource_group",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"isinstance",
"(",
"communities",
",",
"list",
")",
":",
"log",
".",
"err... | 32.012987 | 0.001968 |
def shutdown(self, prompt=False):
"""
Shut down the server.
This method checks if the H2O cluster is still running, and if it does shuts it down (via a REST API call).
:param prompt: A logical value indicating whether to prompt the user before shutting down the H2O server.
"""
... | [
"def",
"shutdown",
"(",
"self",
",",
"prompt",
"=",
"False",
")",
":",
"if",
"not",
"self",
".",
"is_running",
"(",
")",
":",
"return",
"assert_is_type",
"(",
"prompt",
",",
"bool",
")",
"if",
"prompt",
":",
"question",
"=",
"\"Are you sure you want to shu... | 43.421053 | 0.008304 |
def check_case_sensitivity (self):
"""
Check if url and windows path name match cases
else there might be problems when copying such
files on web servers that are case sensitive.
"""
if os.name != 'nt':
return
path = self.get_os_filename()
real... | [
"def",
"check_case_sensitivity",
"(",
"self",
")",
":",
"if",
"os",
".",
"name",
"!=",
"'nt'",
":",
"return",
"path",
"=",
"self",
".",
"get_os_filename",
"(",
")",
"realpath",
"=",
"get_nt_filename",
"(",
"path",
")",
"if",
"path",
"!=",
"realpath",
":"... | 44 | 0.011127 |
def get_playcount(self):
"""Returns the user's playcount so far."""
doc = self._request(self.ws_prefix + ".getInfo", True)
return _number(_extract(doc, "playcount")) | [
"def",
"get_playcount",
"(",
"self",
")",
":",
"doc",
"=",
"self",
".",
"_request",
"(",
"self",
".",
"ws_prefix",
"+",
"\".getInfo\"",
",",
"True",
")",
"return",
"_number",
"(",
"_extract",
"(",
"doc",
",",
"\"playcount\"",
")",
")"
] | 31 | 0.010471 |
def gain(self, db):
"""gain takes one paramter: gain in dB."""
self.command.append('gain')
self.command.append(db)
return self | [
"def",
"gain",
"(",
"self",
",",
"db",
")",
":",
"self",
".",
"command",
".",
"append",
"(",
"'gain'",
")",
"self",
".",
"command",
".",
"append",
"(",
"db",
")",
"return",
"self"
] | 30.8 | 0.012658 |
def update(self):
""" Fetch and parse stats """
self.frontends = []
self.backends = []
self.listeners = []
csv = [ l for l in self._fetch().strip(' #').split('\n') if l ]
if self.failed:
return
#read fields header to create keys
self.fields =... | [
"def",
"update",
"(",
"self",
")",
":",
"self",
".",
"frontends",
"=",
"[",
"]",
"self",
".",
"backends",
"=",
"[",
"]",
"self",
".",
"listeners",
"=",
"[",
"]",
"csv",
"=",
"[",
"l",
"for",
"l",
"in",
"self",
".",
"_fetch",
"(",
")",
".",
"s... | 33.28125 | 0.010949 |
def _compute_term2(self, C, mag, r):
"""
This computes the term f2 equation 8 Drouet & Cotton (2015)
"""
return (C['c4'] + C['c5'] * mag) * \
np.log(np.sqrt(r**2 + C['c6']**2)) + C['c7'] * r | [
"def",
"_compute_term2",
"(",
"self",
",",
"C",
",",
"mag",
",",
"r",
")",
":",
"return",
"(",
"C",
"[",
"'c4'",
"]",
"+",
"C",
"[",
"'c5'",
"]",
"*",
"mag",
")",
"*",
"np",
".",
"log",
"(",
"np",
".",
"sqrt",
"(",
"r",
"**",
"2",
"+",
"C... | 38.166667 | 0.008547 |
def encode(g, top=None, cls=PENMANCodec, **kwargs):
"""
Serialize the graph *g* from *top* to PENMAN notation.
Args:
g: the Graph object
top: the node identifier for the top of the serialized graph; if
unset, the original top of *g* is used
cls: serialization codec class... | [
"def",
"encode",
"(",
"g",
",",
"top",
"=",
"None",
",",
"cls",
"=",
"PENMANCodec",
",",
"*",
"*",
"kwargs",
")",
":",
"codec",
"=",
"cls",
"(",
"*",
"*",
"kwargs",
")",
"return",
"codec",
".",
"encode",
"(",
"g",
",",
"top",
"=",
"top",
")"
] | 31.157895 | 0.001639 |
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 No... | [
"def",
"getScreen",
"(",
"self",
",",
"screen_data",
"=",
"None",
")",
":",
"if",
"(",
"screen_data",
"is",
"None",
")",
":",
"width",
"=",
"ale_lib",
".",
"getScreenWidth",
"(",
"self",
".",
"obj",
")",
"height",
"=",
"ale_lib",
".",
"getScreenWidth",
... | 54.214286 | 0.009067 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.