text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def select_down(self):
"""move cursor down"""
r, c = self._index
self._select_index(r+1, c) | [
"def",
"select_down",
"(",
"self",
")",
":",
"r",
",",
"c",
"=",
"self",
".",
"_index",
"self",
".",
"_select_index",
"(",
"r",
"+",
"1",
",",
"c",
")"
] | 28 | 9.5 |
def create(self, language, query, tasks=values.unset, model_build=values.unset,
field=values.unset):
"""
Create a new QueryInstance
:param unicode language: An ISO language-country string of the sample.
:param unicode query: A user-provided string that uniquely identifies... | [
"def",
"create",
"(",
"self",
",",
"language",
",",
"query",
",",
"tasks",
"=",
"values",
".",
"unset",
",",
"model_build",
"=",
"values",
".",
"unset",
",",
"field",
"=",
"values",
".",
"unset",
")",
":",
"data",
"=",
"values",
".",
"of",
"(",
"{"... | 49.655172 | 35.931034 |
def get_frames(self):
"Define an iterator that will return frames at the given blocksize"
nb_frames = self.input_totalframes // self.output_blocksize
if self.input_totalframes % self.output_blocksize == 0:
nb_frames -= 1 # Last frame must send eod=True
for index in xrange(... | [
"def",
"get_frames",
"(",
"self",
")",
":",
"nb_frames",
"=",
"self",
".",
"input_totalframes",
"//",
"self",
".",
"output_blocksize",
"if",
"self",
".",
"input_totalframes",
"%",
"self",
".",
"output_blocksize",
"==",
"0",
":",
"nb_frames",
"-=",
"1",
"# La... | 44.153846 | 27.076923 |
def stop(self):
"""
Stop the reader
"""
# print('stopping NonBlockingStreamReader..')
# print('acquire..')
NonBlockingStreamReader._stream_mtx.acquire()
# print('acquire..ok')
NonBlockingStreamReader._streams.remove(self._descriptor)
if not NonBloc... | [
"def",
"stop",
"(",
"self",
")",
":",
"# print('stopping NonBlockingStreamReader..')",
"# print('acquire..')",
"NonBlockingStreamReader",
".",
"_stream_mtx",
".",
"acquire",
"(",
")",
"# print('acquire..ok')",
"NonBlockingStreamReader",
".",
"_streams",
".",
"remove",
"(",
... | 37.5 | 11 |
def do_speak(self, args):
"""Repeats what you tell me to."""
words = []
for word in args.words:
if args.piglatin:
word = '%s%say' % (word[1:], word[0])
if args.shout:
word = word.upper()
words.append(word)
repetitions =... | [
"def",
"do_speak",
"(",
"self",
",",
"args",
")",
":",
"words",
"=",
"[",
"]",
"for",
"word",
"in",
"args",
".",
"words",
":",
"if",
"args",
".",
"piglatin",
":",
"word",
"=",
"'%s%say'",
"%",
"(",
"word",
"[",
"1",
":",
"]",
",",
"word",
"[",
... | 32.5 | 16.863636 |
def network_expansion(network, method = 'rel', ext_min=0.1,
ext_width=False, filename=None, boundaries=[]):
"""Plot relative or absolute network extension of AC- and DC-lines.
Parameters
----------
network: PyPSA network container
Holds topology of grid including resul... | [
"def",
"network_expansion",
"(",
"network",
",",
"method",
"=",
"'rel'",
",",
"ext_min",
"=",
"0.1",
",",
"ext_width",
"=",
"False",
",",
"filename",
"=",
"None",
",",
"boundaries",
"=",
"[",
"]",
")",
":",
"cmap",
"=",
"plt",
".",
"cm",
".",
"jet",
... | 38.780303 | 21.25 |
def get_subarray_sbi_ids(sub_array_id):
"""Return list of scheduling block Id's associated with the given
sub_array_id
"""
ids = []
for key in sorted(DB.keys(pattern='scheduling_block/*')):
config = json.loads(DB.get(key))
if config['sub_array_id'] == sub_array_id:
ids.ap... | [
"def",
"get_subarray_sbi_ids",
"(",
"sub_array_id",
")",
":",
"ids",
"=",
"[",
"]",
"for",
"key",
"in",
"sorted",
"(",
"DB",
".",
"keys",
"(",
"pattern",
"=",
"'scheduling_block/*'",
")",
")",
":",
"config",
"=",
"json",
".",
"loads",
"(",
"DB",
".",
... | 34.4 | 11.4 |
def get_time(filename):
"""
Get the modified time for a file as a datetime instance
"""
ts = os.stat(filename).st_mtime
return datetime.datetime.utcfromtimestamp(ts) | [
"def",
"get_time",
"(",
"filename",
")",
":",
"ts",
"=",
"os",
".",
"stat",
"(",
"filename",
")",
".",
"st_mtime",
"return",
"datetime",
".",
"datetime",
".",
"utcfromtimestamp",
"(",
"ts",
")"
] | 28.333333 | 7.666667 |
def get_vmware_inventory_path():
"""
Returns VMware inventory file path.
:returns: path to the inventory file
"""
if sys.platform.startswith("win"):
return os.path.expandvars(r"%APPDATA%\Vmware\Inventory.vmls")
elif sys.platform.startswith("darwin"):
... | [
"def",
"get_vmware_inventory_path",
"(",
")",
":",
"if",
"sys",
".",
"platform",
".",
"startswith",
"(",
"\"win\"",
")",
":",
"return",
"os",
".",
"path",
".",
"expandvars",
"(",
"r\"%APPDATA%\\Vmware\\Inventory.vmls\"",
")",
"elif",
"sys",
".",
"platform",
".... | 36.692308 | 18.846154 |
def fit(self, data, debug=False):
"""
Fit each segment. Segments that have not already been explicitly
added will be automatically added with default model and ytransform.
Parameters
----------
data : pandas.DataFrame
Must have a column with the same name as ... | [
"def",
"fit",
"(",
"self",
",",
"data",
",",
"debug",
"=",
"False",
")",
":",
"data",
"=",
"util",
".",
"apply_filter_query",
"(",
"data",
",",
"self",
".",
"fit_filters",
")",
"unique",
"=",
"data",
"[",
"self",
".",
"segmentation_col",
"]",
".",
"u... | 37.125 | 22.525 |
def _get_dbal_column_type(self, type_):
"""
Get the dbal column type.
:param type_: The fluent type
:type type_: str
:rtype: str
"""
type_ = type_.lower()
if type_ == "enum":
return "string"
return super(PostgresSchemaGrammar, self)... | [
"def",
"_get_dbal_column_type",
"(",
"self",
",",
"type_",
")",
":",
"type_",
"=",
"type_",
".",
"lower",
"(",
")",
"if",
"type_",
"==",
"\"enum\"",
":",
"return",
"\"string\"",
"return",
"super",
"(",
"PostgresSchemaGrammar",
",",
"self",
")",
".",
"_get_... | 22.333333 | 18.866667 |
def plot_brillouin_zone(bz_lattice, lines=None, labels=None, kpoints=None,
fold=False, coords_are_cartesian=False,
ax=None, **kwargs):
"""
Plots a 3D representation of the Brillouin zone of the structure.
Can add to the plot paths, labels and kpoints
Args... | [
"def",
"plot_brillouin_zone",
"(",
"bz_lattice",
",",
"lines",
"=",
"None",
",",
"labels",
"=",
"None",
",",
"kpoints",
"=",
"None",
",",
"fold",
"=",
"False",
",",
"coords_are_cartesian",
"=",
"False",
",",
"ax",
"=",
"None",
",",
"*",
"*",
"kwargs",
... | 36.84 | 21 |
def file_path(self, request, response=None, info=None):
"""
抓取到的资源存放到七牛的时候, 应该采用什么样的key? 返回的path是一个JSON字符串, 其中有bucket和key的信息
"""
return json.dumps(self._extract_key_info(request)) | [
"def",
"file_path",
"(",
"self",
",",
"request",
",",
"response",
"=",
"None",
",",
"info",
"=",
"None",
")",
":",
"return",
"json",
".",
"dumps",
"(",
"self",
".",
"_extract_key_info",
"(",
"request",
")",
")"
] | 41.4 | 13 |
def qvalues(pv, m = None, verbose = False, lowmem = False, pi0 = None):
"""
Copyright (c) 2012, Nicolo Fusi, University of Sheffield
All rights reserved.
Estimates q-values from p-values
Args
=====
m: number of tests. If not specified m = pv.size
verbose: print verbose messages? (defa... | [
"def",
"qvalues",
"(",
"pv",
",",
"m",
"=",
"None",
",",
"verbose",
"=",
"False",
",",
"lowmem",
"=",
"False",
",",
"pi0",
"=",
"None",
")",
":",
"assert",
"(",
"pv",
".",
"min",
"(",
")",
">=",
"0",
"and",
"pv",
".",
"max",
"(",
")",
"<=",
... | 27.642857 | 21.561224 |
def phi(v):
"""Neutrino direction in polar coordinates.
``phi``, ``theta`` is the opposite of ``zenith``, ``azimuth``.
Angles in radians.
"""
v = np.atleast_2d(v)
dir_x = v[:, 0]
dir_y = v[:, 1]
return phi_separg(dir_x, dir_y) | [
"def",
"phi",
"(",
"v",
")",
":",
"v",
"=",
"np",
".",
"atleast_2d",
"(",
"v",
")",
"dir_x",
"=",
"v",
"[",
":",
",",
"0",
"]",
"dir_y",
"=",
"v",
"[",
":",
",",
"1",
"]",
"return",
"phi_separg",
"(",
"dir_x",
",",
"dir_y",
")"
] | 22.727273 | 19.636364 |
def _write_str(self, data):
"""
Converts the given data then writes it
:param data: Data to be written
:return: The result of ``self.output.write()``
"""
with self.__lock:
self.output.write(
to_str(data, self.encoding)
.encode(... | [
"def",
"_write_str",
"(",
"self",
",",
"data",
")",
":",
"with",
"self",
".",
"__lock",
":",
"self",
".",
"output",
".",
"write",
"(",
"to_str",
"(",
"data",
",",
"self",
".",
"encoding",
")",
".",
"encode",
"(",
")",
".",
"decode",
"(",
"self",
... | 29.538462 | 12.615385 |
def assign_site_properties(self, slab, height=0.9):
"""
Assigns site properties.
"""
if 'surface_properties' in slab.site_properties.keys():
return slab
else:
surf_sites = self.find_surface_sites_by_height(slab, height)
surf_props = ['surface' if s... | [
"def",
"assign_site_properties",
"(",
"self",
",",
"slab",
",",
"height",
"=",
"0.9",
")",
":",
"if",
"'surface_properties'",
"in",
"slab",
".",
"site_properties",
".",
"keys",
"(",
")",
":",
"return",
"slab",
"else",
":",
"surf_sites",
"=",
"self",
".",
... | 40 | 16 |
def findElementsWithId(node, elems=None):
"""
Returns all elements with id attributes
"""
if elems is None:
elems = {}
id = node.getAttribute('id')
if id != '':
elems[id] = node
if node.hasChildNodes():
for child in node.childNodes:
# from http://www.w3.or... | [
"def",
"findElementsWithId",
"(",
"node",
",",
"elems",
"=",
"None",
")",
":",
"if",
"elems",
"is",
"None",
":",
"elems",
"=",
"{",
"}",
"id",
"=",
"node",
".",
"getAttribute",
"(",
"'id'",
")",
"if",
"id",
"!=",
"''",
":",
"elems",
"[",
"id",
"]... | 33.625 | 13.75 |
def quic_graph_lasso_cv(X, metric):
"""Run QuicGraphicalLassoCV on data with metric of choice.
Compare results with GridSearchCV + quic_graph_lasso. The number of
lambdas tested should be much lower with similar final lam_ selected.
"""
print("QuicGraphicalLassoCV with:")
print(" metric: {}"... | [
"def",
"quic_graph_lasso_cv",
"(",
"X",
",",
"metric",
")",
":",
"print",
"(",
"\"QuicGraphicalLassoCV with:\"",
")",
"print",
"(",
"\" metric: {}\"",
".",
"format",
"(",
"metric",
")",
")",
"model",
"=",
"QuicGraphicalLassoCV",
"(",
"cv",
"=",
"2",
",",
"... | 37.35 | 15.6 |
def route(route_str): # decorator param
"""
Provides play2 likes routes, with python formatter
All string fileds should be named parameters
:param route_str: a route "GET /parent/{parentID}/child/{childId}{ctype}"
:return: the response of requests.request
"""
def ilog(elapsed):
# s... | [
"def",
"route",
"(",
"route_str",
")",
":",
"# decorator param",
"def",
"ilog",
"(",
"elapsed",
")",
":",
"# statistic",
"last_stat",
"=",
"_routes_stat",
".",
"get",
"(",
"route_str",
",",
"{",
"\"count\"",
":",
"0",
",",
"\"min\"",
":",
"sys",
".",
"ma... | 45.049505 | 24.673267 |
def parse(self, line, **options):
"""\
Parse a line and return (cmd, args, kwargs) - cmd may be False
if it wasn't parseable.
Relatively simple in the Regex parser - anything can be "parsed",
but is not guaranteed to match.
"""
line = line.strip()
if not ... | [
"def",
"parse",
"(",
"self",
",",
"line",
",",
"*",
"*",
"options",
")",
":",
"line",
"=",
"line",
".",
"strip",
"(",
")",
"if",
"not",
"line",
":",
"return",
"(",
"False",
",",
"(",
")",
",",
"{",
"}",
")",
"split",
"=",
"line",
".",
"split"... | 31.928571 | 13 |
def histogram(a, bins=10, range=None, **kwargs):
"""Compute the histogram of the input data.
Parameters
----------
a : NDArray
Input data. The histogram is computed over the flattened array.
bins : int or sequence of scalars
If bins is an int, it defines the number of equal-width bi... | [
"def",
"histogram",
"(",
"a",
",",
"bins",
"=",
"10",
",",
"range",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"isinstance",
"(",
"bins",
",",
"Symbol",
")",
":",
"return",
"_internal",
".",
"_histogram",
"(",
"data",
"=",
"a",
",",
"b... | 46.413793 | 26.551724 |
def publish(idx=None):
"""Publish packaged distributions to pypi index"""
if idx is None:
idx = ''
else:
idx = '-r ' + idx
run('python setup.py register {}'.format(idx))
run('twine upload {} dist/*.whl dist/*.egg dist/*.tar.gz'.format(idx)) | [
"def",
"publish",
"(",
"idx",
"=",
"None",
")",
":",
"if",
"idx",
"is",
"None",
":",
"idx",
"=",
"''",
"else",
":",
"idx",
"=",
"'-r '",
"+",
"idx",
"run",
"(",
"'python setup.py register {}'",
".",
"format",
"(",
"idx",
")",
")",
"run",
"(",
"'twi... | 33.625 | 19.125 |
def cli():
"""Parse options from the command line"""
parser = argparse.ArgumentParser(prog="sphinx-serve",
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
conflict_handler="resolve",
descriptio... | [
"def",
"cli",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"prog",
"=",
"\"sphinx-serve\"",
",",
"formatter_class",
"=",
"argparse",
".",
"ArgumentDefaultsHelpFormatter",
",",
"conflict_handler",
"=",
"\"resolve\"",
",",
"description",
"="... | 38.53125 | 20.6875 |
def encode_pin(self, pin, matrix=None):
"""Transform correct PIN according to the displayed matrix."""
if matrix is None:
_, matrix = self.read_pin()
return "".join([str(matrix.index(p) + 1) for p in pin]) | [
"def",
"encode_pin",
"(",
"self",
",",
"pin",
",",
"matrix",
"=",
"None",
")",
":",
"if",
"matrix",
"is",
"None",
":",
"_",
",",
"matrix",
"=",
"self",
".",
"read_pin",
"(",
")",
"return",
"\"\"",
".",
"join",
"(",
"[",
"str",
"(",
"matrix",
".",... | 47.4 | 7.8 |
def dynamicmap_memoization(callable_obj, streams):
"""
Determine whether the Callable should have memoization enabled
based on the supplied streams (typically by a
DynamicMap). Memoization is disabled if any of the streams require
it it and are currently in a triggered state.
"""
memoization... | [
"def",
"dynamicmap_memoization",
"(",
"callable_obj",
",",
"streams",
")",
":",
"memoization_state",
"=",
"bool",
"(",
"callable_obj",
".",
"_stream_memoization",
")",
"callable_obj",
".",
"_stream_memoization",
"&=",
"not",
"any",
"(",
"s",
".",
"transient",
"and... | 38.133333 | 21.6 |
def _parse_module(self, uri):
''' Parse module defined in *uri* '''
filename = self._uri2path(uri)
if filename is None:
# nothing that we could handle here.
return ([],[])
f = open(filename, 'rt')
functions, classes = self._parse_lines(f)
f.close()... | [
"def",
"_parse_module",
"(",
"self",
",",
"uri",
")",
":",
"filename",
"=",
"self",
".",
"_uri2path",
"(",
"uri",
")",
"if",
"filename",
"is",
"None",
":",
"# nothing that we could handle here.",
"return",
"(",
"[",
"]",
",",
"[",
"]",
")",
"f",
"=",
"... | 34.5 | 9.9 |
def pdf(self, x, e=0., w=1., a=0.):
"""
probability density function
see: https://en.wikipedia.org/wiki/Skew_normal_distribution
:param x: input value
:param e:
:param w:
:param a:
:return:
"""
t = (x-e) / w
return 2. / w * stats.no... | [
"def",
"pdf",
"(",
"self",
",",
"x",
",",
"e",
"=",
"0.",
",",
"w",
"=",
"1.",
",",
"a",
"=",
"0.",
")",
":",
"t",
"=",
"(",
"x",
"-",
"e",
")",
"/",
"w",
"return",
"2.",
"/",
"w",
"*",
"stats",
".",
"norm",
".",
"pdf",
"(",
"t",
")",... | 28.333333 | 15.166667 |
def minimize_algorithm_1dim_golden(function, a, b, c, tolerance=DOUBLE_TOL):
'''
Given a function f, and given a bracketing triplet of abscissas ax, bx, cx
(such that bx is between ax and cx, and f(bx) is less than both f(ax) and f(cx)),
this routine performs a golden section search for the minimum, iso... | [
"def",
"minimize_algorithm_1dim_golden",
"(",
"function",
",",
"a",
",",
"b",
",",
"c",
",",
"tolerance",
"=",
"DOUBLE_TOL",
")",
":",
"x0",
"=",
"a",
"x3",
"=",
"c",
"if",
"abs",
"(",
"c",
"-",
"b",
")",
">",
"abs",
"(",
"b",
"-",
"a",
")",
":... | 32.647059 | 22.392157 |
def _make_all_matchers(cls, parameters):
'''
For every parameter, create a matcher if the parameter has an
annotation.
'''
for name, param in parameters:
annotation = param.annotation
if annotation is not Parameter.empty:
yield name, cls._m... | [
"def",
"_make_all_matchers",
"(",
"cls",
",",
"parameters",
")",
":",
"for",
"name",
",",
"param",
"in",
"parameters",
":",
"annotation",
"=",
"param",
".",
"annotation",
"if",
"annotation",
"is",
"not",
"Parameter",
".",
"empty",
":",
"yield",
"name",
","... | 39.222222 | 17.222222 |
def lines(self) -> str:
"""Return the source code lines for this error."""
if self.definition is None:
return ''
source = ''
lines = self.definition.source
offset = self.definition.start # type: ignore
lines_stripped = list(reversed(list(dropwhile(is_blank,
... | [
"def",
"lines",
"(",
"self",
")",
"->",
"str",
":",
"if",
"self",
".",
"definition",
"is",
"None",
":",
"return",
"''",
"source",
"=",
"''",
"lines",
"=",
"self",
".",
"definition",
".",
"source",
"offset",
"=",
"self",
".",
"definition",
".",
"start... | 40.421053 | 15.052632 |
def set_if_unset(self, key, value):
"""Set a particular spark property by the string key name if it hasn't already been set.
This method allows chaining so that i can provide a similar feel to the standard Scala way of setting
multiple configurations
Parameters
----------
... | [
"def",
"set_if_unset",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"if",
"key",
"not",
"in",
"self",
".",
"_conf_dict",
":",
"self",
".",
"set",
"(",
"key",
",",
"value",
")",
"return",
"self"
] | 27.277778 | 21.888889 |
def robust_single_linkage(X, cut, k=5, alpha=1.4142135623730951,
gamma=5, metric='euclidean', algorithm='best',
memory=Memory(cachedir=None, verbose=0), leaf_size=40,
core_dist_n_jobs=4, **kwargs):
"""Perform robust single linkage cluster... | [
"def",
"robust_single_linkage",
"(",
"X",
",",
"cut",
",",
"k",
"=",
"5",
",",
"alpha",
"=",
"1.4142135623730951",
",",
"gamma",
"=",
"5",
",",
"metric",
"=",
"'euclidean'",
",",
"algorithm",
"=",
"'best'",
",",
"memory",
"=",
"Memory",
"(",
"cachedir",
... | 43.223602 | 22.10559 |
def parse(self, data):
"""Parse a 17 bytes packet in the Wind format and return a
dictionary containing the data extracted. An example of a return value
would be:
.. code-block:: python
{
'id': "0x2EB2",
'packet_length': 16,
'... | [
"def",
"parse",
"(",
"self",
",",
"data",
")",
":",
"self",
".",
"validate_packet",
"(",
"data",
")",
"results",
"=",
"self",
".",
"parse_header_part",
"(",
"data",
")",
"sub_type",
"=",
"results",
"[",
"'packet_subtype'",
"]",
"id_",
"=",
"self",
".",
... | 30.626667 | 15.76 |
def template_chooser_clicked(self):
"""Slot activated when report file tool button is clicked.
.. versionadded: 4.3.0
"""
path = self.template_path.text()
if not path:
path = setting('lastCustomTemplate', '', str)
if path:
directory = dirname(path... | [
"def",
"template_chooser_clicked",
"(",
"self",
")",
":",
"path",
"=",
"self",
".",
"template_path",
".",
"text",
"(",
")",
"if",
"not",
"path",
":",
"path",
"=",
"setting",
"(",
"'lastCustomTemplate'",
",",
"''",
",",
"str",
")",
"if",
"path",
":",
"d... | 32.684211 | 13.052632 |
def open_submission(self, url=None):
"""
Select the current submission to view posts.
"""
if url is None:
data = self.get_selected_item()
url = data['permalink']
if data.get('url_type') == 'selfpost':
self.config.history.add(data['url_f... | [
"def",
"open_submission",
"(",
"self",
",",
"url",
"=",
"None",
")",
":",
"if",
"url",
"is",
"None",
":",
"data",
"=",
"self",
".",
"get_selected_item",
"(",
")",
"url",
"=",
"data",
"[",
"'permalink'",
"]",
"if",
"data",
".",
"get",
"(",
"'url_type'... | 34.272727 | 11.545455 |
def get_google_links(limit, params, headers):
"""
function to fetch links equal to limit
every Google search result page has a start index.
every page contains 10 search results.
"""
links = []
for start_index in range(0, limit, 10):
params['start'] = start_index
resp = s.get("https://www.google.com/search"... | [
"def",
"get_google_links",
"(",
"limit",
",",
"params",
",",
"headers",
")",
":",
"links",
"=",
"[",
"]",
"for",
"start_index",
"in",
"range",
"(",
"0",
",",
"limit",
",",
"10",
")",
":",
"params",
"[",
"'start'",
"]",
"=",
"start_index",
"resp",
"="... | 32.071429 | 13.357143 |
def get_resource_agent_session(self):
"""Gets the session for retrieving resource agent mappings.
return: (osid.resource.ResourceAgentSession) - a
``ResourceAgentSession``
raise: OperationFailed - unable to complete request
raise: Unimplemented - ``supports_resource_ag... | [
"def",
"get_resource_agent_session",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"supports_resource_agent",
"(",
")",
":",
"raise",
"errors",
".",
"Unimplemented",
"(",
")",
"# pylint: disable=no-member",
"return",
"sessions",
".",
"ResourceAgentSession",
"(",
... | 41.625 | 14.625 |
def starts_variation(self) -> bool:
"""
Checks if this node starts a variation (and can thus have a starting
comment). The root node does not start a variation and can have no
starting comment.
For example, in ``1. e4 e5 (1... c5 2. Nf3) 2. Nf3``, the node holding
1... c... | [
"def",
"starts_variation",
"(",
"self",
")",
"->",
"bool",
":",
"if",
"not",
"self",
".",
"parent",
"or",
"not",
"self",
".",
"parent",
".",
"variations",
":",
"return",
"False",
"return",
"self",
".",
"parent",
".",
"variations",
"[",
"0",
"]",
"!=",
... | 36.461538 | 19.538462 |
def on_canvas_slave__route_electrode_added(self, slave, electrode_id):
'''
.. versionchanged:: 0.11
Draw temporary route currently being formed.
.. versionchanged:: 0.11.3
Update routes table by setting ``df_routes`` property of
:attr:`canvas_slave`.
... | [
"def",
"on_canvas_slave__route_electrode_added",
"(",
"self",
",",
"slave",
",",
"electrode_id",
")",
":",
"logger",
".",
"debug",
"(",
"'Route electrode added: %s'",
",",
"electrode_id",
")",
"if",
"slave",
".",
"_route",
".",
"electrode_ids",
"is",
"None",
":",
... | 47.52381 | 23.238095 |
def buffer_typechecks_and_display(self, call_id, payload):
"""Adds typecheck events to the buffer, and displays them right away.
This is a workaround for this issue:
https://github.com/ensime/ensime-server/issues/1616
"""
self.buffer_typechecks(call_id, payload)
self.edi... | [
"def",
"buffer_typechecks_and_display",
"(",
"self",
",",
"call_id",
",",
"payload",
")",
":",
"self",
".",
"buffer_typechecks",
"(",
"call_id",
",",
"payload",
")",
"self",
".",
"editor",
".",
"display_notes",
"(",
"self",
".",
"buffered_notes",
")"
] | 43.875 | 12.875 |
def fseq(self, client, message):
"""
fseq messages associate a unique frame id with a set of set
and alive messages
"""
client.last_frame = client.current_frame
client.current_frame = message[3] | [
"def",
"fseq",
"(",
"self",
",",
"client",
",",
"message",
")",
":",
"client",
".",
"last_frame",
"=",
"client",
".",
"current_frame",
"client",
".",
"current_frame",
"=",
"message",
"[",
"3",
"]"
] | 33.714286 | 8.285714 |
def money_receipts(pronac, dt):
"""
Checks how many items are in a same receipt when payment type is
withdraw/money
- is_outlier: True if there are any receipts that have more than one
- itens_que_compartilham_comprovantes: List of items that share receipt
"""
df = verified_repeated_... | [
"def",
"money_receipts",
"(",
"pronac",
",",
"dt",
")",
":",
"df",
"=",
"verified_repeated_receipts_for_pronac",
"(",
"pronac",
")",
"comprovantes_saque",
"=",
"df",
"[",
"df",
"[",
"'tpFormaDePagamento'",
"]",
"==",
"3.0",
"]",
"return",
"metric_return",
"(",
... | 40.363636 | 19.272727 |
def fgp_dual(p, data, alpha, niter, grad, proj_C, proj_P, tol=None, **kwargs):
"""Computes a solution to the ROF problem with the fast gradient
projection algorithm.
Parameters
----------
p : np.array
dual initial variable
data : np.array
noisy data / proximal point
alpha : ... | [
"def",
"fgp_dual",
"(",
"p",
",",
"data",
",",
"alpha",
",",
"niter",
",",
"grad",
",",
"proj_C",
",",
"proj_P",
",",
"tol",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"# Callback object",
"callback",
"=",
"kwargs",
".",
"pop",
"(",
"'callback'"... | 25.306818 | 21.681818 |
def id_to_object(self, line):
"""
Resolves an ip adres to a range object, creating it if it doesn't exists.
"""
result = Range.get(line, ignore=404)
if not result:
result = Range(range=line)
result.save()
return result | [
"def",
"id_to_object",
"(",
"self",
",",
"line",
")",
":",
"result",
"=",
"Range",
".",
"get",
"(",
"line",
",",
"ignore",
"=",
"404",
")",
"if",
"not",
"result",
":",
"result",
"=",
"Range",
"(",
"range",
"=",
"line",
")",
"result",
".",
"save",
... | 31.777778 | 12.666667 |
def _mpda(self, re_grammar, splitstring=0):
"""
Args:
re_grammar (list): A list of grammar rules
splitstring (bool): A boolean for enabling or disabling
the splitting of symbols using a space
Returns:
PDA: The generated PDA
... | [
"def",
"_mpda",
"(",
"self",
",",
"re_grammar",
",",
"splitstring",
"=",
"0",
")",
":",
"cnfgrammar",
"=",
"CNFGenerator",
"(",
"re_grammar",
")",
"if",
"not",
"self",
".",
"alphabet",
":",
"self",
".",
"_extract_alphabet",
"(",
"cnfgrammar",
")",
"cnftopd... | 39.5 | 13.5 |
def useNonce(self, server_url, timestamp, salt):
"""Return whether this nonce is valid.
str -> bool
"""
if abs(timestamp - time.time()) > nonce.SKEW:
return False
if server_url:
proto, rest = server_url.split('://', 1)
else:
# Create ... | [
"def",
"useNonce",
"(",
"self",
",",
"server_url",
",",
"timestamp",
",",
"salt",
")",
":",
"if",
"abs",
"(",
"timestamp",
"-",
"time",
".",
"time",
"(",
")",
")",
">",
"nonce",
".",
"SKEW",
":",
"return",
"False",
"if",
"server_url",
":",
"proto",
... | 31.363636 | 19.818182 |
def hkdf(self, chaining_key, input_key_material, dhlen=64):
"""Hash-based key derivation function
Takes a ``chaining_key'' byte sequence of len HASHLEN, and an
``input_key_material'' byte sequence with length either zero
bytes, 32 bytes or dhlen bytes.
Returns two byte sequence... | [
"def",
"hkdf",
"(",
"self",
",",
"chaining_key",
",",
"input_key_material",
",",
"dhlen",
"=",
"64",
")",
":",
"if",
"len",
"(",
"chaining_key",
")",
"!=",
"self",
".",
"HASHLEN",
":",
"raise",
"HashError",
"(",
"\"Incorrect chaining key length\"",
")",
"if"... | 45.470588 | 19.588235 |
def nl_skipped_handler_debug(msg, arg):
"""https://github.com/thom311/libnl/blob/libnl3_2_25/lib/handlers.c#L134."""
ofd = arg or _LOGGER.debug
ofd('-- Debug: Skipped message: ' + print_header_content(nlmsg_hdr(msg)))
return NL_SKIP | [
"def",
"nl_skipped_handler_debug",
"(",
"msg",
",",
"arg",
")",
":",
"ofd",
"=",
"arg",
"or",
"_LOGGER",
".",
"debug",
"ofd",
"(",
"'-- Debug: Skipped message: '",
"+",
"print_header_content",
"(",
"nlmsg_hdr",
"(",
"msg",
")",
")",
")",
"return",
"NL_SKIP"
] | 48.8 | 14 |
def _calculate_scores(self):
"""Calculate the 'value' of each node in the graph based on how many
blocking descendants it has. We use this score for the internal
priority queue's ordering, so the quality of this metric is important.
The score is stored as a negative number because the i... | [
"def",
"_calculate_scores",
"(",
"self",
")",
":",
"scores",
"=",
"{",
"}",
"for",
"node",
"in",
"self",
".",
"graph",
".",
"nodes",
"(",
")",
":",
"score",
"=",
"-",
"1",
"*",
"len",
"(",
"[",
"d",
"for",
"d",
"in",
"nx",
".",
"descendants",
"... | 40.96 | 22.44 |
def instructions(self):
"""
Return an iterator over this block's instructions.
The iterator will yield a ValueRef for each instruction.
"""
if not self.is_block:
raise ValueError('expected block value, got %s' % (self._kind,))
it = ffi.lib.LLVMPY_BlockInstruct... | [
"def",
"instructions",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"is_block",
":",
"raise",
"ValueError",
"(",
"'expected block value, got %s'",
"%",
"(",
"self",
".",
"_kind",
",",
")",
")",
"it",
"=",
"ffi",
".",
"lib",
".",
"LLVMPY_BlockInstructio... | 40.727273 | 12.545455 |
def to_dict(self, into=dict):
"""
Convert Series to {label -> value} dict or dict-like object.
Parameters
----------
into : class, default dict
The collections.abc.Mapping subclass to use as the return
object. Can be the actual class or an empty
... | [
"def",
"to_dict",
"(",
"self",
",",
"into",
"=",
"dict",
")",
":",
"# GH16122",
"into_c",
"=",
"com",
".",
"standardize_mapping",
"(",
"into",
")",
"return",
"into_c",
"(",
"self",
".",
"items",
"(",
")",
")"
] | 31.735294 | 17.735294 |
def setrange(self, key, offset, value):
"""Overwrites part of the string stored at key, starting at the
specified offset, for the entire length of value. If the offset is
larger than the current length of the string at key, the string is
padded with zero-bytes to make offset fit. Non-exi... | [
"def",
"setrange",
"(",
"self",
",",
"key",
",",
"offset",
",",
"value",
")",
":",
"return",
"self",
".",
"_execute",
"(",
"[",
"b'SETRANGE'",
",",
"key",
",",
"ascii",
"(",
"offset",
")",
",",
"value",
"]",
")"
] | 54.02439 | 27.536585 |
def _grow(list_of_lists, num_new):
""" Given a list of lists, and a number of new lists to add, copy the
content of the first list into the new ones, and add them to the list
of lists.
"""
first = list_of_lists[0]
for i in range(num_new):
list_of_lists.append(copy.deepcopy(first))
re... | [
"def",
"_grow",
"(",
"list_of_lists",
",",
"num_new",
")",
":",
"first",
"=",
"list_of_lists",
"[",
"0",
"]",
"for",
"i",
"in",
"range",
"(",
"num_new",
")",
":",
"list_of_lists",
".",
"append",
"(",
"copy",
".",
"deepcopy",
"(",
"first",
")",
")",
"... | 36.666667 | 12.888889 |
def calculate_vss(self, method=None):
"""
Calculate the vertical swimming speed of this behavior.
Takes into account the vertical swimming speed and the
variance.
Parameters:
method: "gaussian" (default) or "random"
"random" (vss - variance) < X... | [
"def",
"calculate_vss",
"(",
"self",
",",
"method",
"=",
"None",
")",
":",
"if",
"self",
".",
"variance",
"==",
"float",
"(",
"0",
")",
":",
"return",
"self",
".",
"vss",
"else",
":",
"# Calculate gausian distribution and return",
"if",
"method",
"==",
"\"... | 41.35 | 19.95 |
def gcm_send_message(registration_id, data, encoding='utf-8', **kwargs):
"""
Standalone method to send a single gcm notification
"""
messenger = GCMMessenger(registration_id, data, encoding=encoding, **kwargs)
return messenger.send_plain() | [
"def",
"gcm_send_message",
"(",
"registration_id",
",",
"data",
",",
"encoding",
"=",
"'utf-8'",
",",
"*",
"*",
"kwargs",
")",
":",
"messenger",
"=",
"GCMMessenger",
"(",
"registration_id",
",",
"data",
",",
"encoding",
"=",
"encoding",
",",
"*",
"*",
"kwa... | 36.285714 | 19.142857 |
def get_platform_node_selector(self, platform):
"""
search the configuration for entries of the form node_selector.platform
:param platform: str, platform to search for, can be null
:return dict
"""
nodeselector = {}
if platform:
nodeselector_str = sel... | [
"def",
"get_platform_node_selector",
"(",
"self",
",",
"platform",
")",
":",
"nodeselector",
"=",
"{",
"}",
"if",
"platform",
":",
"nodeselector_str",
"=",
"self",
".",
"_get_value",
"(",
"\"node_selector.\"",
"+",
"platform",
",",
"self",
".",
"conf_section",
... | 42.307692 | 23.384615 |
def allow_address_pairs(session, network, subnet):
"""Allow several interfaces to be added and accessed from the other machines.
This is particularly useful when working with virtual ips.
"""
nclient = neutron.Client('2', session=session,
region_name=os.environ['OS_REGION_N... | [
"def",
"allow_address_pairs",
"(",
"session",
",",
"network",
",",
"subnet",
")",
":",
"nclient",
"=",
"neutron",
".",
"Client",
"(",
"'2'",
",",
"session",
"=",
"session",
",",
"region_name",
"=",
"os",
".",
"environ",
"[",
"'OS_REGION_NAME'",
"]",
")",
... | 40.821429 | 15.678571 |
def pairwise(X):
M = X.shape[0]
N = X.shape[1]
D = numpy.zeros((M,N))
"omp parallel for private(i,j,d,k,tmp)"
for i in xrange(M):
for j in xrange(M):
d = 0.0
for k in xrange(N):
tmp = X[i,k] - X[j,k]
d += tmp * tmp
D[i,j] = ... | [
"def",
"pairwise",
"(",
"X",
")",
":",
"M",
"=",
"X",
".",
"shape",
"[",
"0",
"]",
"N",
"=",
"X",
".",
"shape",
"[",
"1",
"]",
"D",
"=",
"numpy",
".",
"zeros",
"(",
"(",
"M",
",",
"N",
")",
")",
"for",
"i",
"in",
"xrange",
"(",
"M",
")"... | 25.615385 | 14.846154 |
def download_from(self, buff, remote_path):
"""Downloads file from WebDAV and writes it in buffer.
:param buff: buffer object for writing of downloaded file content.
:param remote_path: path to file on WebDAV server.
"""
urn = Urn(remote_path)
if self.is_dir(urn.path()):... | [
"def",
"download_from",
"(",
"self",
",",
"buff",
",",
"remote_path",
")",
":",
"urn",
"=",
"Urn",
"(",
"remote_path",
")",
"if",
"self",
".",
"is_dir",
"(",
"urn",
".",
"path",
"(",
")",
")",
":",
"raise",
"OptionNotValid",
"(",
"name",
"=",
"'remot... | 39.066667 | 18.333333 |
def compose(*funcs):
'''
Compose an ordered list of functions. Args of a,b,c,d evaluates as a(b(c(d(ctx))))
'''
def _compose(ctx):
# last func gets context, rest get result of previous func
_result = funcs[-1](ctx)
for f in reversed(funcs[:-1]):
_result = f(_result)
... | [
"def",
"compose",
"(",
"*",
"funcs",
")",
":",
"def",
"_compose",
"(",
"ctx",
")",
":",
"# last func gets context, rest get result of previous func",
"_result",
"=",
"funcs",
"[",
"-",
"1",
"]",
"(",
"ctx",
")",
"for",
"f",
"in",
"reversed",
"(",
"funcs",
... | 29.25 | 22.75 |
def data_iter(batch_size, num_embed, pre_trained_word2vec=False):
"""Construct data iter
Parameters
----------
batch_size: int
num_embed: int
pre_trained_word2vec: boolean
identify the pre-trained layers or not
Returns
----------
train_set: DataIter
... | [
"def",
"data_iter",
"(",
"batch_size",
",",
"num_embed",
",",
"pre_trained_word2vec",
"=",
"False",
")",
":",
"print",
"(",
"'Loading data...'",
")",
"if",
"pre_trained_word2vec",
":",
"word2vec",
"=",
"data_helpers",
".",
"load_pretrained_word2vec",
"(",
"'data/rt.... | 32.677966 | 16.118644 |
def CRRAutility_invP(u, gam):
'''
Evaluates the derivative of the inverse of the CRRA utility function (with
risk aversion parameter gam) at a given utility level u.
Parameters
----------
u : float
Utility value
gam : float
Risk aversion
Returns
-------
(unnamed... | [
"def",
"CRRAutility_invP",
"(",
"u",
",",
"gam",
")",
":",
"if",
"gam",
"==",
"1",
":",
"return",
"np",
".",
"exp",
"(",
"u",
")",
"else",
":",
"return",
"(",
"(",
"(",
"1.0",
"-",
"gam",
")",
"*",
"u",
")",
"**",
"(",
"gam",
"/",
"(",
"1.0... | 23.047619 | 25.619048 |
def expect_element(__funcname=_qualified_name, **named):
"""
Preprocessing decorator that verifies inputs are elements of some
expected collection.
Examples
--------
>>> @expect_element(x=('a', 'b'))
... def foo(x):
... return x.upper()
...
>>> foo('a')
'A'
>>> foo('b... | [
"def",
"expect_element",
"(",
"__funcname",
"=",
"_qualified_name",
",",
"*",
"*",
"named",
")",
":",
"def",
"_expect_element",
"(",
"collection",
")",
":",
"if",
"isinstance",
"(",
"collection",
",",
"(",
"set",
",",
"frozenset",
")",
")",
":",
"# Special... | 33.557692 | 23.173077 |
def variance_inflation_factors(df):
'''
Computes the variance inflation factor (VIF) for each column in the df.
Returns a pandas Series of VIFs
Args:
df: pandas DataFrame with columns to run diagnostics on
'''
corr = np.corrcoef(df, rowvar=0)
corr_inv = np.linalg.inv(corr)
vifs ... | [
"def",
"variance_inflation_factors",
"(",
"df",
")",
":",
"corr",
"=",
"np",
".",
"corrcoef",
"(",
"df",
",",
"rowvar",
"=",
"0",
")",
"corr_inv",
"=",
"np",
".",
"linalg",
".",
"inv",
"(",
"corr",
")",
"vifs",
"=",
"np",
".",
"diagonal",
"(",
"cor... | 31.916667 | 19.416667 |
def Update(self, env, args=None):
"""
Update an environment with the option variables.
env - the environment to update.
"""
values = {}
# first set the defaults:
for option in self.options:
if not option.default is None:
values[optio... | [
"def",
"Update",
"(",
"self",
",",
"env",
",",
"args",
"=",
"None",
")",
":",
"values",
"=",
"{",
"}",
"# first set the defaults:",
"for",
"option",
"in",
"self",
".",
"options",
":",
"if",
"not",
"option",
".",
"default",
"is",
"None",
":",
"values",
... | 34.794118 | 16.117647 |
def unregister(name, delete=False):
'''
Unregister a VM
CLI Example:
.. code-block:: bash
salt '*' vboxmanage.unregister my_vm_filename
'''
nodes = list_nodes_min()
if name not in nodes:
raise CommandExecutionError(
'The specified VM ({0}) is not registered.'.f... | [
"def",
"unregister",
"(",
"name",
",",
"delete",
"=",
"False",
")",
":",
"nodes",
"=",
"list_nodes_min",
"(",
")",
"if",
"name",
"not",
"in",
"nodes",
":",
"raise",
"CommandExecutionError",
"(",
"'The specified VM ({0}) is not registered.'",
".",
"format",
"(",
... | 23.608696 | 21.521739 |
def utrecht(mag_file, dir_path=".", input_dir_path="", meas_file="measurements.txt",
spec_file="specimens.txt", samp_file="samples.txt", site_file="sites.txt",
loc_file="locations.txt", location="unknown", lat="", lon="", dmy_flag=False,
noave=False, meas_n_orient=8, meth_code="LP-N... | [
"def",
"utrecht",
"(",
"mag_file",
",",
"dir_path",
"=",
"\".\"",
",",
"input_dir_path",
"=",
"\"\"",
",",
"meas_file",
"=",
"\"measurements.txt\"",
",",
"spec_file",
"=",
"\"specimens.txt\"",
",",
"samp_file",
"=",
"\"samples.txt\"",
",",
"site_file",
"=",
"\"s... | 40.343558 | 17.815951 |
def beacon(config):
'''
The journald beacon allows for the systemd journal to be parsed and linked
objects to be turned into events.
This beacons config will return all sshd jornal entries
.. code-block:: yaml
beacons:
journald:
- services:
sshd:
... | [
"def",
"beacon",
"(",
"config",
")",
":",
"ret",
"=",
"[",
"]",
"journal",
"=",
"_get_journal",
"(",
")",
"_config",
"=",
"{",
"}",
"list",
"(",
"map",
"(",
"_config",
".",
"update",
",",
"config",
")",
")",
"while",
"True",
":",
"cur",
"=",
"jou... | 28.02439 | 20.512195 |
def l2_distance_sq(t1, t2, name=None):
"""Square of l2 distance between t1 and t2.
Args:
t1: A tensor.
t2: A tensor that is the same size as t1.
name: Optional name for this op.
Returns:
The l2 distance between t1 and t2.
"""
with tf.name_scope(name, 'l2_distance_sq', [t1, t2]) as scope:
... | [
"def",
"l2_distance_sq",
"(",
"t1",
",",
"t2",
",",
"name",
"=",
"None",
")",
":",
"with",
"tf",
".",
"name_scope",
"(",
"name",
",",
"'l2_distance_sq'",
",",
"[",
"t1",
",",
"t2",
"]",
")",
"as",
"scope",
":",
"t1",
"=",
"tf",
".",
"convert_to_ten... | 32.214286 | 13.5 |
def trimUTR(args):
"""
%prog trimUTR gffile
Remove UTRs in the annotation set.
If reference GFF3 is provided, reinstate UTRs from reference
transcripts after trimming.
Note: After running trimUTR, it is advised to also run
`python -m jcvi.formats.gff fixboundaries` on the resultant GFF3
... | [
"def",
"trimUTR",
"(",
"args",
")",
":",
"import",
"gffutils",
"from",
"jcvi",
".",
"formats",
".",
"base",
"import",
"SetFile",
"p",
"=",
"OptionParser",
"(",
"trimUTR",
".",
"__doc__",
")",
"p",
".",
"add_option",
"(",
"\"--trim5\"",
",",
"default",
"=... | 44.160714 | 19.5 |
def do_terminateInstance(self,args):
"""Terminate an EC2 instance"""
parser = CommandArgumentParser("terminateInstance")
parser.add_argument(dest='instance',help='instance index or name');
args = vars(parser.parse_args(args))
instanceId = args['instance']
try:
... | [
"def",
"do_terminateInstance",
"(",
"self",
",",
"args",
")",
":",
"parser",
"=",
"CommandArgumentParser",
"(",
"\"terminateInstance\"",
")",
"parser",
".",
"add_argument",
"(",
"dest",
"=",
"'instance'",
",",
"help",
"=",
"'instance index or name'",
")",
"args",
... | 39.470588 | 18.588235 |
def loadTableData(df, df_key='index',table="node", \
table_key_column = "name",
network="current",\
namespace="default",\
host=cytoscape_host,port=cytoscape_port,verbose=False):
"""
Loads tables into cytoscape
:param df: a pan... | [
"def",
"loadTableData",
"(",
"df",
",",
"df_key",
"=",
"'index'",
",",
"table",
"=",
"\"node\"",
",",
"table_key_column",
"=",
"\"name\"",
",",
"network",
"=",
"\"current\"",
",",
"namespace",
"=",
"\"default\"",
",",
"host",
"=",
"cytoscape_host",
",",
"por... | 30.265823 | 17.987342 |
def get_samples_live_last(self, sensor_id):
"""Get the last sample recorded by the sensor.
Args:
sensor_id (string): hexadecimal id of the sensor to query, e.g.
``0x0013A20040B65FAD``
Returns:
list: dictionary objects containing sample data
"""
url = "https://api.neur.io/v1/sam... | [
"def",
"get_samples_live_last",
"(",
"self",
",",
"sensor_id",
")",
":",
"url",
"=",
"\"https://api.neur.io/v1/samples/live/last\"",
"headers",
"=",
"self",
".",
"__gen_headers",
"(",
")",
"headers",
"[",
"\"Content-Type\"",
"]",
"=",
"\"application/json\"",
"params",... | 27.65 | 18.6 |
def check_value_error_for_parity(value_error: ValueError, call_type: ParityCallType) -> bool:
"""
For parity failing calls and functions do not return None if the transaction
will fail but instead throw a ValueError exception.
This function checks the thrown exception to see if it's the correct one and... | [
"def",
"check_value_error_for_parity",
"(",
"value_error",
":",
"ValueError",
",",
"call_type",
":",
"ParityCallType",
")",
"->",
"bool",
":",
"try",
":",
"error_data",
"=",
"json",
".",
"loads",
"(",
"str",
"(",
"value_error",
")",
".",
"replace",
"(",
"\"'... | 40 | 25.307692 |
def GetFlagSuggestions(attempt, longopt_list):
"""Get helpful similar matches for an invalid flag."""
# Don't suggest on very short strings, or if no longopts are specified.
if len(attempt) <= 2 or not longopt_list:
return []
option_names = [v.split('=')[0] for v in longopt_list]
# Find close approximat... | [
"def",
"GetFlagSuggestions",
"(",
"attempt",
",",
"longopt_list",
")",
":",
"# Don't suggest on very short strings, or if no longopts are specified.",
"if",
"len",
"(",
"attempt",
")",
"<=",
"2",
"or",
"not",
"longopt_list",
":",
"return",
"[",
"]",
"option_names",
"=... | 33.538462 | 20.307692 |
def build_api(packages, input, output, sanitizer, excluded_modules=None):
"""
Builds the Sphinx documentation API.
:param packages: Packages to include in the API.
:type packages: list
:param input: Input modules directory.
:type input: unicode
:param output: Output reStructuredText files d... | [
"def",
"build_api",
"(",
"packages",
",",
"input",
",",
"output",
",",
"sanitizer",
",",
"excluded_modules",
"=",
"None",
")",
":",
"LOGGER",
".",
"info",
"(",
"\"{0} | Building Sphinx documentation API!\"",
".",
"format",
"(",
"build_api",
".",
"__name__",
")",... | 45.991667 | 24.558333 |
def decorate(func, caller):
"""
decorate(func, caller) decorates a function using a caller.
"""
evaldict = func.__globals__.copy()
evaldict['_call_'] = caller
evaldict['_func_'] = func
fun = FunctionMaker.create(
func, "return _call_(_func_, %(shortsignature)s)",
evaldict, __... | [
"def",
"decorate",
"(",
"func",
",",
"caller",
")",
":",
"evaldict",
"=",
"func",
".",
"__globals__",
".",
"copy",
"(",
")",
"evaldict",
"[",
"'_call_'",
"]",
"=",
"caller",
"evaldict",
"[",
"'_func_'",
"]",
"=",
"func",
"fun",
"=",
"FunctionMaker",
".... | 32.384615 | 9.461538 |
def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types):
"""
Implements equation 3.5.1-1 page 148 for mean value and equation
3.5.5-1 page 151 for total standard deviation.
See :meth:`superclass method
<.base.GroundShakingIntensityModel.get_mean_and_stddevs>`
... | [
"def",
"get_mean_and_stddevs",
"(",
"self",
",",
"sites",
",",
"rup",
",",
"dists",
",",
"imt",
",",
"stddev_types",
")",
":",
"mean",
",",
"stddevs",
"=",
"super",
"(",
")",
".",
"get_mean_and_stddevs",
"(",
"sites",
",",
"rup",
",",
"dists",
",",
"im... | 46 | 18.142857 |
def add_mavlink_packet(self, msg):
'''add data to the graph'''
mtype = msg.get_type()
if mtype not in self.msg_types:
return
for i in range(len(self.fields)):
if mtype not in self.field_types[i]:
continue
f = self.fields[i]
... | [
"def",
"add_mavlink_packet",
"(",
"self",
",",
"msg",
")",
":",
"mtype",
"=",
"msg",
".",
"get_type",
"(",
")",
"if",
"mtype",
"not",
"in",
"self",
".",
"msg_types",
":",
"return",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"fields",
... | 39.5 | 11.5 |
def list_comments(self, topic_id, start=0):
"""
回复列表
:param topic_id: 话题ID
:param start: 翻页
:return: 带下一页的列表
"""
xml = self.api.xml(API_GROUP_GET_TOPIC % topic_id, params={'start': start})
xml_results = xml.xpath('//ul[@id="comments"]/li')
... | [
"def",
"list_comments",
"(",
"self",
",",
"topic_id",
",",
"start",
"=",
"0",
")",
":",
"xml",
"=",
"self",
".",
"api",
".",
"xml",
"(",
"API_GROUP_GET_TOPIC",
"%",
"topic_id",
",",
"params",
"=",
"{",
"'start'",
":",
"start",
"}",
")",
"xml_results",
... | 44.764706 | 18.529412 |
def _handle_delete(self, transaction):
"""
Handle DELETE requests
:type transaction: Transaction
:param transaction: the transaction that owns the request
:rtype : Transaction
:return: the edited transaction with the response to the request
"""
path = str... | [
"def",
"_handle_delete",
"(",
"self",
",",
"transaction",
")",
":",
"path",
"=",
"str",
"(",
"\"/\"",
"+",
"transaction",
".",
"request",
".",
"uri_path",
")",
"transaction",
".",
"response",
"=",
"Response",
"(",
")",
"transaction",
".",
"response",
".",
... | 36.6 | 17.8 |
def stdout_avail(self):
"""Data is available in stdout, let's empty the queue and write it!"""
data = self.interpreter.stdout_write.empty_queue()
if data:
self.write(data) | [
"def",
"stdout_avail",
"(",
"self",
")",
":",
"data",
"=",
"self",
".",
"interpreter",
".",
"stdout_write",
".",
"empty_queue",
"(",
")",
"if",
"data",
":",
"self",
".",
"write",
"(",
"data",
")"
] | 41.4 | 14 |
def features_check_singular(X, tol=1e-8):
"""Checks if a set of features/variables X result in a
ill-conditioned matrix dot(X.T,T)
Parameters:
-----------
X : ndarray
An NxM array with N observations (rows)
and M features/variables (columns).
Note: Make sure that X variable... | [
"def",
"features_check_singular",
"(",
"X",
",",
"tol",
"=",
"1e-8",
")",
":",
"import",
"numpy",
"as",
"np",
"_",
",",
"s",
",",
"_",
"=",
"np",
".",
"linalg",
".",
"svd",
"(",
"np",
".",
"dot",
"(",
"X",
".",
"T",
",",
"X",
")",
")",
"faile... | 30.452381 | 21.238095 |
def load_hdf(cls, filename, path='', name=None):
"""
A class method to load a saved StarModel from an HDF5 file.
File must have been created by a call to :func:`StarModel.save_hdf`.
:param filename:
H5 file to load.
:param path: (optional)
Path within H... | [
"def",
"load_hdf",
"(",
"cls",
",",
"filename",
",",
"path",
"=",
"''",
",",
"name",
"=",
"None",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"filename",
")",
":",
"raise",
"IOError",
"(",
"'{} does not exist.'",
".",
"format",
"(",... | 26.464286 | 18.821429 |
def add_network(self, network, netmask, area=0):
"""Adds a network to be advertised by OSPF
Args:
network (str): The network to be advertised in dotted decimal
notation
netmask (str): The netmask to configure
area (str): ... | [
"def",
"add_network",
"(",
"self",
",",
"network",
",",
"netmask",
",",
"area",
"=",
"0",
")",
":",
"if",
"network",
"==",
"''",
"or",
"netmask",
"==",
"''",
":",
"raise",
"ValueError",
"(",
"'network and mask values '",
"'may not be empty'",
")",
"cmd",
"... | 44.45 | 16 |
def get_token_from_env():
"""Get the token from env var, VAULT_TOKEN. If not set, attempt to get the token from, ~/.vault-token
:return: The vault token if set, else None
:rtype: str | None
"""
token = os.getenv('VAULT_TOKEN')
if not token:
token_file_path = os.path.expanduser('~/.vault... | [
"def",
"get_token_from_env",
"(",
")",
":",
"token",
"=",
"os",
".",
"getenv",
"(",
"'VAULT_TOKEN'",
")",
"if",
"not",
"token",
":",
"token_file_path",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"'~/.vault-token'",
")",
"if",
"os",
".",
"path",
".",... | 30 | 17.294118 |
def convert_to_layout_rules(x):
"""Converts input to a LayoutRules.
Args:
x: LayoutRules, str, or set-like of string pairs.
Returns:
LayoutRules.
"""
if isinstance(x, LayoutRules):
return x
if isinstance(x, str):
x = _parse_string_to_list_of_pairs(x)
return LayoutRules(x) | [
"def",
"convert_to_layout_rules",
"(",
"x",
")",
":",
"if",
"isinstance",
"(",
"x",
",",
"LayoutRules",
")",
":",
"return",
"x",
"if",
"isinstance",
"(",
"x",
",",
"str",
")",
":",
"x",
"=",
"_parse_string_to_list_of_pairs",
"(",
"x",
")",
"return",
"Lay... | 20.785714 | 18.5 |
def _call_apt(args, scope=True, **kwargs):
'''
Call apt* utilities.
'''
cmd = []
if scope and salt.utils.systemd.has_scope(__context__) and __salt__['config.get']('systemd.scope', True):
cmd.extend(['systemd-run', '--scope'])
cmd.extend(args)
params = {'output_loglevel': 'trace',
... | [
"def",
"_call_apt",
"(",
"args",
",",
"scope",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"cmd",
"=",
"[",
"]",
"if",
"scope",
"and",
"salt",
".",
"utils",
".",
"systemd",
".",
"has_scope",
"(",
"__context__",
")",
"and",
"__salt__",
"[",
"'co... | 33.066667 | 23.6 |
def _get_redis_cache_opts():
'''
Return the Redis server connection details from the __opts__.
'''
return {
'host': __opts__.get('cache.redis.host', 'localhost'),
'port': __opts__.get('cache.redis.port', 6379),
'unix_socket_path': __opts__.get('cache.redis.unix_socket_path', None... | [
"def",
"_get_redis_cache_opts",
"(",
")",
":",
"return",
"{",
"'host'",
":",
"__opts__",
".",
"get",
"(",
"'cache.redis.host'",
",",
"'localhost'",
")",
",",
"'port'",
":",
"__opts__",
".",
"get",
"(",
"'cache.redis.port'",
",",
"6379",
")",
",",
"'unix_sock... | 49 | 29.142857 |
def get_config(self):
"""
Currently only contains the "config" member, which is a string
containing the config file as loaded by i3 most recently.
:rtype: ConfigReply
"""
data = self.message(MessageType.GET_CONFIG, '')
return json.loads(data, object_hook=ConfigRe... | [
"def",
"get_config",
"(",
"self",
")",
":",
"data",
"=",
"self",
".",
"message",
"(",
"MessageType",
".",
"GET_CONFIG",
",",
"''",
")",
"return",
"json",
".",
"loads",
"(",
"data",
",",
"object_hook",
"=",
"ConfigReply",
")"
] | 35.111111 | 17.555556 |
def get_eids(self, num_rlzs):
"""
:param num_rlzs: the number of realizations for the given group
:returns: an array of event IDs
"""
num_events = self.n_occ if self.samples > 1 else self.n_occ * num_rlzs
return TWO32 * U64(self.serial) + numpy.arange(num_events, dtype=U6... | [
"def",
"get_eids",
"(",
"self",
",",
"num_rlzs",
")",
":",
"num_events",
"=",
"self",
".",
"n_occ",
"if",
"self",
".",
"samples",
">",
"1",
"else",
"self",
".",
"n_occ",
"*",
"num_rlzs",
"return",
"TWO32",
"*",
"U64",
"(",
"self",
".",
"serial",
")",... | 45.142857 | 16.857143 |
def _author_line(self):
"""
Helper method to concatenate author and institution values, if necessary
:return: string
"""
if self.author and self.institution:
return self.author + ";" + self.institution
elif self.author:
return self.author
e... | [
"def",
"_author_line",
"(",
"self",
")",
":",
"if",
"self",
".",
"author",
"and",
"self",
".",
"institution",
":",
"return",
"self",
".",
"author",
"+",
"\";\"",
"+",
"self",
".",
"institution",
"elif",
"self",
".",
"author",
":",
"return",
"self",
"."... | 31.818182 | 13.636364 |
def assertDutTraceDoesNotContain(dut, message, bench):
"""
Raise TestStepFail if bench.verify_trace does not find message from dut traces.
:param dut: Dut object.
:param message: Message to look for.
:param: Bench, must contain verify_trace method.
:raises: AttributeError if bench does not cont... | [
"def",
"assertDutTraceDoesNotContain",
"(",
"dut",
",",
"message",
",",
"bench",
")",
":",
"if",
"not",
"hasattr",
"(",
"bench",
",",
"\"verify_trace\"",
")",
":",
"raise",
"AttributeError",
"(",
"\"Bench object does not contain verify_trace method!\"",
")",
"if",
"... | 45.428571 | 17.714286 |
def qr(X, ip_B=None, reorthos=1):
"""QR factorization with customizable inner product.
:param X: array with ``shape==(N,k)``
:param ip_B: (optional) inner product, see :py:meth:`inner`.
:param reorthos: (optional) numer of reorthogonalizations. Defaults to
1 (i.e. 2 runs of modified Gram-Schmidt)... | [
"def",
"qr",
"(",
"X",
",",
"ip_B",
"=",
"None",
",",
"reorthos",
"=",
"1",
")",
":",
"if",
"ip_B",
"is",
"None",
"and",
"X",
".",
"shape",
"[",
"1",
"]",
">",
"0",
":",
"return",
"scipy",
".",
"linalg",
".",
"qr",
"(",
"X",
",",
"mode",
"=... | 38.428571 | 15.678571 |
def deal(self, num=1, end=TOP):
"""
Returns a list of cards, which are removed from the Stack.
:arg int num:
The number of cards to deal.
:arg str end:
Which end to deal from. Can be ``0`` (top) or ``1`` (bottom).
:returns:
The given number o... | [
"def",
"deal",
"(",
"self",
",",
"num",
"=",
"1",
",",
"end",
"=",
"TOP",
")",
":",
"ends",
"=",
"{",
"TOP",
":",
"self",
".",
"cards",
".",
"pop",
",",
"BOTTOM",
":",
"self",
".",
"cards",
".",
"popleft",
"}",
"self_size",
"=",
"self",
".",
... | 25.588235 | 18.823529 |
def create_version(self,
name,
project,
description=None,
releaseDate=None,
startDate=None,
archived=False,
released=False,
):
"... | [
"def",
"create_version",
"(",
"self",
",",
"name",
",",
"project",
",",
"description",
"=",
"None",
",",
"releaseDate",
"=",
"None",
",",
"startDate",
"=",
"None",
",",
"archived",
"=",
"False",
",",
"released",
"=",
"False",
",",
")",
":",
"data",
"="... | 35.744681 | 14.021277 |
def _ModifyInterface(
self, interface_config, config_key, config_value, replace=False):
"""Write a value to a config file if not already present.
Args:
interface_config: string, the path to a config file.
config_key: string, the configuration key to set.
config_value: string, the value ... | [
"def",
"_ModifyInterface",
"(",
"self",
",",
"interface_config",
",",
"config_key",
",",
"config_value",
",",
"replace",
"=",
"False",
")",
":",
"config_entry",
"=",
"'%s=%s'",
"%",
"(",
"config_key",
",",
"config_value",
")",
"if",
"not",
"open",
"(",
"inte... | 46.352941 | 20.352941 |
def get_ip_mac_arp_list(auth, url, devid=None, devip=None):
"""
function takes devid of specific device and issues a RESTFUL call to get the IP/MAC/ARP list
from the target device.
:param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class
:param url: base url of IMC RS in... | [
"def",
"get_ip_mac_arp_list",
"(",
"auth",
",",
"url",
",",
"devid",
"=",
"None",
",",
"devip",
"=",
"None",
")",
":",
"if",
"devip",
"is",
"not",
"None",
":",
"dev_details",
"=",
"get_dev_details",
"(",
"devip",
",",
"auth",
",",
"url",
")",
"if",
"... | 35.36 | 25.52 |
def add_debug(parser):
"""Add a `debug` flag to the _parser_."""
parser.add_argument(
'-d', '--debug', action='store_const', const=logging.DEBUG, default=logging.INFO, help='Set DEBUG output') | [
"def",
"add_debug",
"(",
"parser",
")",
":",
"parser",
".",
"add_argument",
"(",
"'-d'",
",",
"'--debug'",
",",
"action",
"=",
"'store_const'",
",",
"const",
"=",
"logging",
".",
"DEBUG",
",",
"default",
"=",
"logging",
".",
"INFO",
",",
"help",
"=",
"... | 51.25 | 27 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.