text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def _update_nonce_explicit(self):
"""
Increment the explicit nonce while avoiding any overflow.
"""
ne = self.nonce_explicit + 1
self.nonce_explicit = ne % 2**(self.nonce_explicit_len * 8) | [
"def",
"_update_nonce_explicit",
"(",
"self",
")",
":",
"ne",
"=",
"self",
".",
"nonce_explicit",
"+",
"1",
"self",
".",
"nonce_explicit",
"=",
"ne",
"%",
"2",
"**",
"(",
"self",
".",
"nonce_explicit_len",
"*",
"8",
")"
] | 37.166667 | 10.5 |
def registerErrorHandler(f, ctx):
"""Register a Python written function to for error reporting.
The function is called back as f(ctx, error). """
import sys
if 'libxslt' not in sys.modules:
# normal behaviour when libxslt is not imported
ret = libxml2mod.xmlRegisterErrorHandler(f,ctx)... | [
"def",
"registerErrorHandler",
"(",
"f",
",",
"ctx",
")",
":",
"import",
"sys",
"if",
"'libxslt'",
"not",
"in",
"sys",
".",
"modules",
":",
"# normal behaviour when libxslt is not imported",
"ret",
"=",
"libxml2mod",
".",
"xmlRegisterErrorHandler",
"(",
"f",
",",
... | 38.769231 | 12.846154 |
def to_mapquest_str(self):
"""
Convert Viewbox object to a string that can be used by
`MapQuest <http://www.mapquestapi.com/geocoding/#options>`_
as a query parameter.
"""
vb = self.convert_srs(4326)
return '%s,%s,%s,%s' % (vb.left, vb.top, vb.right, vb.bottom) | [
"def",
"to_mapquest_str",
"(",
"self",
")",
":",
"vb",
"=",
"self",
".",
"convert_srs",
"(",
"4326",
")",
"return",
"'%s,%s,%s,%s'",
"%",
"(",
"vb",
".",
"left",
",",
"vb",
".",
"top",
",",
"vb",
".",
"right",
",",
"vb",
".",
"bottom",
")"
] | 38.75 | 13.5 |
def polygons_to_geom_dicts(polygons, skip_invalid=True):
"""
Converts a Polygons element into a list of geometry dictionaries,
preserving all value dimensions.
For array conversion the following conventions are applied:
* Any nan separated array are converted into a MultiPolygon
* Any array wi... | [
"def",
"polygons_to_geom_dicts",
"(",
"polygons",
",",
"skip_invalid",
"=",
"True",
")",
":",
"interface",
"=",
"polygons",
".",
"interface",
".",
"datatype",
"if",
"interface",
"==",
"'geodataframe'",
":",
"return",
"[",
"row",
".",
"to_dict",
"(",
")",
"fo... | 36.30137 | 17.150685 |
def initialize_users(self) -> None:
"""Load device user data and initialize user management."""
users = self.request('get', pwdgrp_url)
self.users = Users(users, self.request) | [
"def",
"initialize_users",
"(",
"self",
")",
"->",
"None",
":",
"users",
"=",
"self",
".",
"request",
"(",
"'get'",
",",
"pwdgrp_url",
")",
"self",
".",
"users",
"=",
"Users",
"(",
"users",
",",
"self",
".",
"request",
")"
] | 49 | 4.75 |
def usage(self):
"""Instance depends on the API version:
* 2015-06-15: :class:`UsageOperations<azure.mgmt.storage.v2015_06_15.operations.UsageOperations>`
* 2016-01-01: :class:`UsageOperations<azure.mgmt.storage.v2016_01_01.operations.UsageOperations>`
* 2016-12-01: :class:`Usa... | [
"def",
"usage",
"(",
"self",
")",
":",
"api_version",
"=",
"self",
".",
"_get_api_version",
"(",
"'usage'",
")",
"if",
"api_version",
"==",
"'2015-06-15'",
":",
"from",
".",
"v2015_06_15",
".",
"operations",
"import",
"UsageOperations",
"as",
"OperationClass",
... | 67.461538 | 35.384615 |
def _fetch(self):
"""forces update of a local cached copy of the real object
(regardless of the preference setting self.cache)"""
if not self.is_local and not self._obcache_current:
#print('fetching data from %s' % self._ref.id)
def _remote_fetch(id):
retu... | [
"def",
"_fetch",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"is_local",
"and",
"not",
"self",
".",
"_obcache_current",
":",
"#print('fetching data from %s' % self._ref.id)",
"def",
"_remote_fetch",
"(",
"id",
")",
":",
"return",
"distob",
".",
"engine",
... | 52.090909 | 13.181818 |
def footprint(self):
"""Return product footprint."""
product_footprint = self._product_metadata.iter("Product_Footprint")
# I don't know why two "Product_Footprint" items are found.
for element in product_footprint:
global_footprint = None
for global_footprint in ... | [
"def",
"footprint",
"(",
"self",
")",
":",
"product_footprint",
"=",
"self",
".",
"_product_metadata",
".",
"iter",
"(",
"\"Product_Footprint\"",
")",
"# I don't know why two \"Product_Footprint\" items are found.",
"for",
"element",
"in",
"product_footprint",
":",
"globa... | 52.444444 | 18.111111 |
def _has_match(self, assembled_summary):
'''assembled_summary should be output of _to_cluster_summary_assembled'''
if assembled_summary.startswith('yes'):
if self.data[0]['var_only'] == '0' or self._to_cluster_summary_has_known_nonsynonymous(assembled_summary) == 'yes':
retur... | [
"def",
"_has_match",
"(",
"self",
",",
"assembled_summary",
")",
":",
"if",
"assembled_summary",
".",
"startswith",
"(",
"'yes'",
")",
":",
"if",
"self",
".",
"data",
"[",
"0",
"]",
"[",
"'var_only'",
"]",
"==",
"'0'",
"or",
"self",
".",
"_to_cluster_sum... | 44.777778 | 25.222222 |
def _request(self, uri, method='GET', params=None, files=None, headers=None, auth=None):
"""Override the parent _request method.
We have to do this here because FireEye requires some extra
authentication steps.
"""
if params:
params['environment_id'] = self.env_id
... | [
"def",
"_request",
"(",
"self",
",",
"uri",
",",
"method",
"=",
"'GET'",
",",
"params",
"=",
"None",
",",
"files",
"=",
"None",
",",
"headers",
"=",
"None",
",",
"auth",
"=",
"None",
")",
":",
"if",
"params",
":",
"params",
"[",
"'environment_id'",
... | 33.24 | 19.8 |
def render(self, template: str, **vars) -> str:
"""
Render the named template.
The current context will be available to the template as the ``ctx`` variable.
:param template: name of the template file
:param vars: extra template variables
:return: the rendered results
... | [
"def",
"render",
"(",
"self",
",",
"template",
":",
"str",
",",
"*",
"*",
"vars",
")",
"->",
"str",
":",
"vars",
".",
"setdefault",
"(",
"'ctx'",
",",
"self",
".",
"_ctx",
")",
"return",
"self",
".",
"_renderer",
".",
"render",
"(",
"template",
","... | 32 | 16.307692 |
def updateMappingsOnDeviceType(self, thingTypeId, logicalInterfaceId, mappingsObject, notificationStrategy = "never"):
"""
Add mappings for a thing type.
Parameters:
- thingTypeId (string) - the thing type
- logicalInterfaceId (string) - the id of the application interfac... | [
"def",
"updateMappingsOnDeviceType",
"(",
"self",
",",
"thingTypeId",
",",
"logicalInterfaceId",
",",
"mappingsObject",
",",
"notificationStrategy",
"=",
"\"never\"",
")",
":",
"req",
"=",
"ApiClient",
".",
"oneThingTypeMappingUrl",
"%",
"(",
"self",
".",
"host",
... | 50.818182 | 30.878788 |
def _make_schema_patterns(self) -> None:
"""Build schema pattern for the receiver and its data descendants."""
self.schema_pattern = self._schema_pattern()
for dc in self.data_children():
if isinstance(dc, InternalNode):
dc._make_schema_patterns() | [
"def",
"_make_schema_patterns",
"(",
"self",
")",
"->",
"None",
":",
"self",
".",
"schema_pattern",
"=",
"self",
".",
"_schema_pattern",
"(",
")",
"for",
"dc",
"in",
"self",
".",
"data_children",
"(",
")",
":",
"if",
"isinstance",
"(",
"dc",
",",
"Intern... | 49 | 3.166667 |
def _get_structure(self):
"""
Get the structure we are going to work with.
:return: The structure we have to work with.
:rtype: dict
"""
# We initiate an empty variable which is going to save the location of
# file we are going to download.
structure_fil... | [
"def",
"_get_structure",
"(",
"self",
")",
":",
"# We initiate an empty variable which is going to save the location of",
"# file we are going to download.",
"structure_file",
"=",
"\"\"",
"# We initiate the variable which will save the request instance.",
"req",
"=",
"\"\"",
"if",
"... | 37.555556 | 23.583333 |
def _set_init_params(self, qrs_amp_recent, noise_amp_recent, rr_recent,
last_qrs_ind):
"""
Set initial online parameters
"""
self.qrs_amp_recent = qrs_amp_recent
self.noise_amp_recent = noise_amp_recent
# What happens if qrs_thr is calculated to b... | [
"def",
"_set_init_params",
"(",
"self",
",",
"qrs_amp_recent",
",",
"noise_amp_recent",
",",
"rr_recent",
",",
"last_qrs_ind",
")",
":",
"self",
".",
"qrs_amp_recent",
"=",
"qrs_amp_recent",
"self",
".",
"noise_amp_recent",
"=",
"noise_amp_recent",
"# What happens if ... | 41.294118 | 11.529412 |
def _schedule_processing_blocks(self):
"""Schedule Processing Blocks for execution."""
LOG.info('Starting to Schedule Processing Blocks.')
while True:
time.sleep(0.5)
if not self._queue:
continue
if self._num_pbcs >= self._max_pbcs:
... | [
"def",
"_schedule_processing_blocks",
"(",
"self",
")",
":",
"LOG",
".",
"info",
"(",
"'Starting to Schedule Processing Blocks.'",
")",
"while",
"True",
":",
"time",
".",
"sleep",
"(",
"0.5",
")",
"if",
"not",
"self",
".",
"_queue",
":",
"continue",
"if",
"s... | 47.538462 | 14.5 |
def containsPoint(self, point, Zorder=False):
'''
:param: point - Point subclass
:param: Zorder - optional Boolean
Is true if the point is contain in the rectangle or
along the rectangle's edges.
If Zorder is True, the method will check point.z for
equality wit... | [
"def",
"containsPoint",
"(",
"self",
",",
"point",
",",
"Zorder",
"=",
"False",
")",
":",
"if",
"not",
"point",
".",
"isBetweenX",
"(",
"self",
".",
"A",
",",
"self",
".",
"B",
")",
":",
"return",
"False",
"if",
"not",
"point",
".",
"isBetweenY",
"... | 27.809524 | 20 |
def _updated(self, url, payload, template=None):
"""
Generic call to see if a template request returns 304
accepts:
- a string to combine with the API endpoint
- a dict of format values, in case they're required by 'url'
- a template name to check for
As per the A... | [
"def",
"_updated",
"(",
"self",
",",
"url",
",",
"payload",
",",
"template",
"=",
"None",
")",
":",
"# If the template is more than an hour old, try a 304",
"if",
"(",
"abs",
"(",
"datetime",
".",
"datetime",
".",
"utcnow",
"(",
")",
".",
"replace",
"(",
"tz... | 39.333333 | 17.333333 |
def p_let_arr_substr_in_args2(p):
""" statement : LET ARRAY_ID LP arguments COMMA TO expr RP EQ expr
| ARRAY_ID LP arguments COMMA TO expr RP EQ expr
"""
i = 2 if p[1].upper() == 'LET' else 1
id_ = p[i]
arg_list = p[i + 2]
top_ = p[i + 5]
substr = (make_number(0, lineno=p.... | [
"def",
"p_let_arr_substr_in_args2",
"(",
"p",
")",
":",
"i",
"=",
"2",
"if",
"p",
"[",
"1",
"]",
".",
"upper",
"(",
")",
"==",
"'LET'",
"else",
"1",
"id_",
"=",
"p",
"[",
"i",
"]",
"arg_list",
"=",
"p",
"[",
"i",
"+",
"2",
"]",
"top_",
"=",
... | 35.833333 | 17.916667 |
def imagetransformer_base_10l_16h_big_dr01_imgnet():
"""big 1d model for conditional image generation."""
hparams = imagetransformer_base_14l_8h_big_dr01()
# num_hidden_layers
hparams.num_decoder_layers = 10
hparams.num_heads = 16
hparams.hidden_size = 1024
hparams.filter_size = 4096
hparams.batch_size ... | [
"def",
"imagetransformer_base_10l_16h_big_dr01_imgnet",
"(",
")",
":",
"hparams",
"=",
"imagetransformer_base_14l_8h_big_dr01",
"(",
")",
"# num_hidden_layers",
"hparams",
".",
"num_decoder_layers",
"=",
"10",
"hparams",
".",
"num_heads",
"=",
"16",
"hparams",
".",
"hid... | 33.833333 | 11.833333 |
def heightmap_add_hill(
hm: np.ndarray, x: float, y: float, radius: float, height: float
) -> None:
"""Add a hill (a half spheroid) at given position.
If height == radius or -radius, the hill is a half-sphere.
Args:
hm (numpy.ndarray): A numpy.ndarray formatted for heightmap functions.
... | [
"def",
"heightmap_add_hill",
"(",
"hm",
":",
"np",
".",
"ndarray",
",",
"x",
":",
"float",
",",
"y",
":",
"float",
",",
"radius",
":",
"float",
",",
"height",
":",
"float",
")",
"->",
"None",
":",
"lib",
".",
"TCOD_heightmap_add_hill",
"(",
"_heightmap... | 41.533333 | 23.866667 |
def trajectory_SgConst(Sg=0.1, delta_logt_dex=-0.01):
'''
setup trajectories for constant radiation entropy.
S_gamma/R where the radiation constant R = N_A*k
(Dave Arnett, Supernova book, p. 212)
This relates rho and T but the time scale for this
is independent.
Parameters
----------
... | [
"def",
"trajectory_SgConst",
"(",
"Sg",
"=",
"0.1",
",",
"delta_logt_dex",
"=",
"-",
"0.01",
")",
":",
"# reverse logarithmic time",
"logtimerev",
"=",
"np",
".",
"arange",
"(",
"5.",
",",
"-",
"6.",
",",
"delta_logt_dex",
")",
"logrho",
"=",
"np",
".",
... | 31.478261 | 24 |
def xmlresponse(py_data):
"""
Generates an XML formatted method response for the given python
data.
:param py_data | <variant>
"""
xroot = ElementTree.Element('methodResponse')
xparams = ElementTree.SubElement(xroot, 'params')
xparam = ElementTree.SubElement(xparams, 'param')
... | [
"def",
"xmlresponse",
"(",
"py_data",
")",
":",
"xroot",
"=",
"ElementTree",
".",
"Element",
"(",
"'methodResponse'",
")",
"xparams",
"=",
"ElementTree",
".",
"SubElement",
"(",
"xroot",
",",
"'params'",
")",
"xparam",
"=",
"ElementTree",
".",
"SubElement",
... | 34.148649 | 15.337838 |
def lookup(self, iterable, gather=False):
"""Call the lookup on the root node with the given parameters.
Args
iterable(index or key): Used to retrive nodes from tree
gather(bool): this is passed down to the root node lookup
Notes:
max_edit_distance and match... | [
"def",
"lookup",
"(",
"self",
",",
"iterable",
",",
"gather",
"=",
"False",
")",
":",
"for",
"result",
"in",
"self",
".",
"root",
".",
"lookup",
"(",
"iterable",
",",
"gather",
"=",
"gather",
",",
"edit_distance",
"=",
"0",
",",
"max_edit_distance",
"=... | 43.0625 | 21.75 |
def _resolve_assignment_parts(parts, assign_path, context):
"""recursive function to resolve multiple assignments"""
assign_path = assign_path[:]
index = assign_path.pop(0)
for part in parts:
assigned = None
if isinstance(part, nodes.Dict):
# A dictionary in an iterating cont... | [
"def",
"_resolve_assignment_parts",
"(",
"parts",
",",
"assign_path",
",",
"context",
")",
":",
"assign_path",
"=",
"assign_path",
"[",
":",
"]",
"index",
"=",
"assign_path",
".",
"pop",
"(",
"0",
")",
"for",
"part",
"in",
"parts",
":",
"assigned",
"=",
... | 33.710526 | 17.815789 |
def put_mouse_event_absolute(self, x, y, dz, dw, button_state):
"""Positions the mouse pointer using absolute x and y coordinates.
These coordinates are expressed in pixels and
start from [1,1] which corresponds to the top left
corner of the virtual display. The values [-1,-1] and
... | [
"def",
"put_mouse_event_absolute",
"(",
"self",
",",
"x",
",",
"y",
",",
"dz",
",",
"dw",
",",
"button_state",
")",
":",
"if",
"not",
"isinstance",
"(",
"x",
",",
"baseinteger",
")",
":",
"raise",
"TypeError",
"(",
"\"x can only be an instance of type baseinte... | 40.661538 | 20 |
def and_terms(*args):
""" Connect given term strings or list(s) of term strings with an AND operator for querying.
Args:
An arbitrary number of either strings or lists of strings representing query terms.
Returns
A query string consisting of argument terms and'ed together.
... | [
"def",
"and_terms",
"(",
"*",
"args",
")",
":",
"args",
"=",
"[",
"arg",
"if",
"not",
"isinstance",
"(",
"arg",
",",
"list",
")",
"else",
"' '",
".",
"join",
"(",
"arg",
")",
"for",
"arg",
"in",
"args",
"]",
"return",
"'({0})'",
".",
"format",
"(... | 40 | 25.363636 |
def handle(self):
"""
Executes the command.
"""
if not self.confirm_to_proceed(
"<question>Are you sure you want to seed the database?:</question> "
):
return
self.resolver.set_default_connection(self.option("database"))
self._get_seeder(... | [
"def",
"handle",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"confirm_to_proceed",
"(",
"\"<question>Are you sure you want to seed the database?:</question> \"",
")",
":",
"return",
"self",
".",
"resolver",
".",
"set_default_connection",
"(",
"self",
".",
"option... | 25.214286 | 20.5 |
def read_file(self, changeset_file):
"""Download the replication changeset file or read it directly from the
filesystem (to test purposes).
"""
if isfile(changeset_file):
self.filename = changeset_file
else:
self.path = mkdtemp()
self.filename ... | [
"def",
"read_file",
"(",
"self",
",",
"changeset_file",
")",
":",
"if",
"isfile",
"(",
"changeset_file",
")",
":",
"self",
".",
"filename",
"=",
"changeset_file",
"else",
":",
"self",
".",
"path",
"=",
"mkdtemp",
"(",
")",
"self",
".",
"filename",
"=",
... | 36.625 | 13.375 |
def rowCount(self, parentIndex=QtCore.QModelIndex()):
""" Returns the number of rows under the given parent. When the parent is valid it means
that rowCount is returning the number of children of parent.
Note: When implementing a table based model, rowCount() should return 0 when the pa... | [
"def",
"rowCount",
"(",
"self",
",",
"parentIndex",
"=",
"QtCore",
".",
"QModelIndex",
"(",
")",
")",
":",
"parentItem",
"=",
"self",
".",
"getItem",
"(",
"parentIndex",
",",
"altItem",
"=",
"self",
".",
"invisibleRootItem",
")",
"return",
"parentItem",
".... | 51.888889 | 22.666667 |
def astensor(array: TensorLike) -> BKTensor:
"""Convert to product tensor"""
tensor = tf.convert_to_tensor(array, dtype=CTYPE)
if DEVICE == 'gpu':
tensor = tensor.gpu() # pragma: no cover
# size = np.prod(np.array(tensor.get_shape().as_list()))
N = int(math.log2(size(tensor)))
tensor =... | [
"def",
"astensor",
"(",
"array",
":",
"TensorLike",
")",
"->",
"BKTensor",
":",
"tensor",
"=",
"tf",
".",
"convert_to_tensor",
"(",
"array",
",",
"dtype",
"=",
"CTYPE",
")",
"if",
"DEVICE",
"==",
"'gpu'",
":",
"tensor",
"=",
"tensor",
".",
"gpu",
"(",
... | 32.454545 | 15.454545 |
def from_content_type(cls, content_type):
"""
Build a serializer object from a MIME Content-Type string.
:param str content_type: The Content-Type string to parse.
:return: A new serializer instance.
:rtype: :py:class:`.Serializer`
"""
name = content_type
options = {}
if ';' in content_type:
name,... | [
"def",
"from_content_type",
"(",
"cls",
",",
"content_type",
")",
":",
"name",
"=",
"content_type",
"options",
"=",
"{",
"}",
"if",
"';'",
"in",
"content_type",
":",
"name",
",",
"options_str",
"=",
"content_type",
".",
"split",
"(",
"';'",
",",
"1",
")"... | 30.541667 | 15.625 |
def is_valid_endpoint(url):
"""
Just ensures the url has a scheme (http/https), and a net location (IP or domain name).
Can make more advanced or do on-network tests if needed, but this is really just to catch obvious errors.
>>> is_valid_endpoint("https://34.216.72.29:6206")
True
>>> is_valid_e... | [
"def",
"is_valid_endpoint",
"(",
"url",
")",
":",
"try",
":",
"result",
"=",
"urlparse",
"(",
"url",
")",
"if",
"result",
".",
"port",
":",
"_port",
"=",
"int",
"(",
"result",
".",
"port",
")",
"return",
"(",
"all",
"(",
"[",
"result",
".",
"scheme... | 31.52 | 20.48 |
def _acl_changes(name, id=None, type=None, rules=None, consul_url=None, token=None):
'''
return True if the acl need to be update, False if it doesn't need to be update
'''
info = __salt__['consul.acl_info'](id=id, token=token, consul_url=consul_url)
if info['res'] and info['data'][0]['Name'] !=... | [
"def",
"_acl_changes",
"(",
"name",
",",
"id",
"=",
"None",
",",
"type",
"=",
"None",
",",
"rules",
"=",
"None",
",",
"consul_url",
"=",
"None",
",",
"token",
"=",
"None",
")",
":",
"info",
"=",
"__salt__",
"[",
"'consul.acl_info'",
"]",
"(",
"id",
... | 37.285714 | 28.714286 |
def setParams(self, inputCol=None, outputCol=None, stopWords=None, caseSensitive=False,
locale=None):
"""
setParams(self, inputCol=None, outputCol=None, stopWords=None, caseSensitive=false, \
locale=None)
Sets params for this StopWordRemover.
"""
kwargs ... | [
"def",
"setParams",
"(",
"self",
",",
"inputCol",
"=",
"None",
",",
"outputCol",
"=",
"None",
",",
"stopWords",
"=",
"None",
",",
"caseSensitive",
"=",
"False",
",",
"locale",
"=",
"None",
")",
":",
"kwargs",
"=",
"self",
".",
"_input_kwargs",
"return",
... | 40.777778 | 16.111111 |
def find_object(self, pattern):
"""Get a list of host corresponding to the pattern regarding the context
:param pattern: pattern to find
:type pattern: str
:return: Host list matching pattern (hostgroup name, template, all)
:rtype: list[alignak.objects.host.Host]
"""
... | [
"def",
"find_object",
"(",
"self",
",",
"pattern",
")",
":",
"obj",
"=",
"None",
"error",
"=",
"None",
"pattern",
"=",
"pattern",
".",
"strip",
"(",
")",
"if",
"pattern",
"==",
"'*'",
":",
"obj",
"=",
"[",
"h",
".",
"host_name",
"for",
"h",
"in",
... | 37.756098 | 20.414634 |
def _get_result_paths(self, data):
""" Build the dict of result filepaths
"""
# access data through self.Parameters so we know it's been cast
# to a FilePath
wd = self.WorkingDir
db_name = self.Parameters['-n'].Value
log_name = self.Parameters['-l'].Value
... | [
"def",
"_get_result_paths",
"(",
"self",
",",
"data",
")",
":",
"# access data through self.Parameters so we know it's been cast",
"# to a FilePath",
"wd",
"=",
"self",
".",
"WorkingDir",
"db_name",
"=",
"self",
".",
"Parameters",
"[",
"'-n'",
"]",
".",
"Value",
"lo... | 44 | 15.190476 |
def _get_more_compressed(collection_name, num_to_return, cursor_id, ctx):
"""Internal compressed getMore message helper."""
return _compress(
2005, _get_more(collection_name, num_to_return, cursor_id), ctx) | [
"def",
"_get_more_compressed",
"(",
"collection_name",
",",
"num_to_return",
",",
"cursor_id",
",",
"ctx",
")",
":",
"return",
"_compress",
"(",
"2005",
",",
"_get_more",
"(",
"collection_name",
",",
"num_to_return",
",",
"cursor_id",
")",
",",
"ctx",
")"
] | 54.75 | 21 |
def submit_row(context):
"""
Displays the row of buttons for delete and save.
"""
opts = context['opts']
change = context['change']
is_popup = context['is_popup']
save_as = context['save_as']
return {
'onclick_attrib': (opts.get_ordered_objects() and change
... | [
"def",
"submit_row",
"(",
"context",
")",
":",
"opts",
"=",
"context",
"[",
"'opts'",
"]",
"change",
"=",
"context",
"[",
"'change'",
"]",
"is_popup",
"=",
"context",
"[",
"'is_popup'",
"]",
"save_as",
"=",
"context",
"[",
"'save_as'",
"]",
"return",
"{"... | 43.15 | 20.65 |
def get(self, key, subcommand="config:get"):
"""Get a app config value by name"""
cmd = ["heroku", subcommand, key, "--app", self.name]
return self._result(cmd) | [
"def",
"get",
"(",
"self",
",",
"key",
",",
"subcommand",
"=",
"\"config:get\"",
")",
":",
"cmd",
"=",
"[",
"\"heroku\"",
",",
"subcommand",
",",
"key",
",",
"\"--app\"",
",",
"self",
".",
"name",
"]",
"return",
"self",
".",
"_result",
"(",
"cmd",
")... | 45.25 | 8.25 |
def scale_pixels(color, layer):
"""Scales the pixel to the virtual pixelmap."""
pixelmap = []
# Scaling the pixel offsets.
for pix_x in range(MAX_X + 1):
for pix_y in range(MAX_Y + 1):
# Horizontal pixels
y1 = pix_y * dotsize[0]
x1 = pix_x * dotsize[1]
... | [
"def",
"scale_pixels",
"(",
"color",
",",
"layer",
")",
":",
"pixelmap",
"=",
"[",
"]",
"# Scaling the pixel offsets.",
"for",
"pix_x",
"in",
"range",
"(",
"MAX_X",
"+",
"1",
")",
":",
"for",
"pix_y",
"in",
"range",
"(",
"MAX_Y",
"+",
"1",
")",
":",
... | 32.047619 | 16.190476 |
def total_edge_pixels_from_mask(mask):
"""Compute the total number of borders-pixels in a masks."""
border_pixel_total = 0
for y in range(mask.shape[0]):
for x in range(mask.shape[1]):
if not mask[y, x]:
if mask[y + 1, x] or mask[y - 1, x] or mask[y, x + 1] or mask[y, x... | [
"def",
"total_edge_pixels_from_mask",
"(",
"mask",
")",
":",
"border_pixel_total",
"=",
"0",
"for",
"y",
"in",
"range",
"(",
"mask",
".",
"shape",
"[",
"0",
"]",
")",
":",
"for",
"x",
"in",
"range",
"(",
"mask",
".",
"shape",
"[",
"1",
"]",
")",
":... | 38.692308 | 22.230769 |
def fallback(cache):
"""
Caches content retrieved by the client, thus allowing the cached
content to be used later if the live content cannot be retrieved.
"""
log_filter = ThrottlingFilter(cache=cache)
logger.filters = []
logger.addFilter(log_filter)
def get_cache_response(cache_key)... | [
"def",
"fallback",
"(",
"cache",
")",
":",
"log_filter",
"=",
"ThrottlingFilter",
"(",
"cache",
"=",
"cache",
")",
"logger",
".",
"filters",
"=",
"[",
"]",
"logger",
".",
"addFilter",
"(",
"log_filter",
")",
"def",
"get_cache_response",
"(",
"cache_key",
"... | 39.076923 | 18.384615 |
def rev_reg_id2cred_def_id(rr_id: str) -> str:
"""
Given a revocation registry identifier, return its corresponding credential definition identifier.
Raise BadIdentifier if input is not a revocation registry identifier.
:param rr_id: revocation registry identifier
:return: credential definition ide... | [
"def",
"rev_reg_id2cred_def_id",
"(",
"rr_id",
":",
"str",
")",
"->",
"str",
":",
"if",
"ok_rev_reg_id",
"(",
"rr_id",
")",
":",
"return",
"':'",
".",
"join",
"(",
"rr_id",
".",
"split",
"(",
"':'",
")",
"[",
"2",
":",
"-",
"2",
"]",
")",
"# rev re... | 45.083333 | 25.916667 |
def set(self, conn, key, value, exptime=0):
"""Sets a key to a value on the server
with an optional exptime (0 means don't auto-expire)
:param key: ``bytes``, is the key of the item.
:param value: ``bytes``, data to store.
:param exptime: ``int``, is expiration time. If it's 0, ... | [
"def",
"set",
"(",
"self",
",",
"conn",
",",
"key",
",",
"value",
",",
"exptime",
"=",
"0",
")",
":",
"flags",
"=",
"0",
"# TODO: fix when exception removed",
"resp",
"=",
"yield",
"from",
"self",
".",
"_storage_command",
"(",
"conn",
",",
"b'set'",
",",... | 41.357143 | 13.571429 |
def level_ipix_to_uniq(level, ipix):
"""
Convert a level and HEALPix index into a uniq number representing the cell.
This function is the inverse of `uniq_to_level_ipix`.
Parameters
----------
level : int
The level of the HEALPix cell
ipix : int
The index of the HEALPix cel... | [
"def",
"level_ipix_to_uniq",
"(",
"level",
",",
"ipix",
")",
":",
"level",
"=",
"np",
".",
"asarray",
"(",
"level",
",",
"dtype",
"=",
"np",
".",
"int64",
")",
"ipix",
"=",
"np",
".",
"asarray",
"(",
"ipix",
",",
"dtype",
"=",
"np",
".",
"int64",
... | 23.6 | 20 |
def call(cmd, shell=True, **kwargs):
" Run shell command. "
LOGGER.debug("Cmd: %s" % cmd)
check_call(cmd, shell=shell, stdout=LOGFILE_HANDLER.stream, **kwargs) | [
"def",
"call",
"(",
"cmd",
",",
"shell",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"LOGGER",
".",
"debug",
"(",
"\"Cmd: %s\"",
"%",
"cmd",
")",
"check_call",
"(",
"cmd",
",",
"shell",
"=",
"shell",
",",
"stdout",
"=",
"LOGFILE_HANDLER",
".",
... | 33.6 | 19.6 |
def make_cleansed_file(i_chunk, tmp_cleansed_path):
'''make a temp file of cleansed text'''
tmp_cleansed = open(tmp_cleansed_path, 'wb')
for idx, si in enumerate(i_chunk):
tmp_cleansed.write('<FILENAME docid="%s">\n' % si.stream_id)
tmp_cleansed.write(si.body.cleansed)
## how to deal... | [
"def",
"make_cleansed_file",
"(",
"i_chunk",
",",
"tmp_cleansed_path",
")",
":",
"tmp_cleansed",
"=",
"open",
"(",
"tmp_cleansed_path",
",",
"'wb'",
")",
"for",
"idx",
",",
"si",
"in",
"enumerate",
"(",
"i_chunk",
")",
":",
"tmp_cleansed",
".",
"write",
"(",... | 43.454545 | 7.636364 |
def context():
"""
Returns a new JobBackend instance which connects to AETROS Trainer
based on "model" in aetros.yml or (internal: env:AETROS_MODEL_NAME environment variable).
internal: If env:AETROS_JOB_ID is not defined, it creates a new job.
Job is ended either by calling JobBackend.done(), Job... | [
"def",
"context",
"(",
")",
":",
"job",
"=",
"JobBackend",
"(",
")",
"offline",
"=",
"False",
"if",
"'1'",
"==",
"os",
".",
"getenv",
"(",
"'AETROS_OFFLINE'",
",",
"''",
")",
":",
"offline",
"=",
"True",
"if",
"os",
".",
"getenv",
"(",
"'AETROS_JOB_I... | 28.83871 | 25.612903 |
def choose(self, choose_from):
"""given a mapping of implementations
choose one based on the current settings
returns a key value pair
"""
for choice in self.elements:
if choice in choose_from:
return ImplementationChoice(choice, choose_from[choice])
... | [
"def",
"choose",
"(",
"self",
",",
"choose_from",
")",
":",
"for",
"choice",
"in",
"self",
".",
"elements",
":",
"if",
"choice",
"in",
"choose_from",
":",
"return",
"ImplementationChoice",
"(",
"choice",
",",
"choose_from",
"[",
"choice",
"]",
")",
"raise"... | 37.1 | 12.5 |
def logpdf_link(self, link_f, y, Y_metadata=None):
"""
Log Likelihood Function given link(f)
.. math::
\\ln p(y_{i}|\lambda(f_{i})) = \\ln \\lambda(f_{i}) - y_{i}\\lambda(f_{i})
:param link_f: latent variables (link(f))
:type link_f: Nx1 array
:param y: data... | [
"def",
"logpdf_link",
"(",
"self",
",",
"link_f",
",",
"y",
",",
"Y_metadata",
"=",
"None",
")",
":",
"log_objective",
"=",
"np",
".",
"log",
"(",
"link_f",
")",
"-",
"y",
"*",
"link_f",
"return",
"log_objective"
] | 32.333333 | 19.444444 |
def equals(self, other):
"""
Equality of two SSAFiles.
Compares :attr:`SSAFile.info`, :attr:`SSAFile.styles` and :attr:`SSAFile.events`.
Order of entries in OrderedDicts does not matter. "ScriptType" key in info is
considered an implementation detail and thus ignored.
U... | [
"def",
"equals",
"(",
"self",
",",
"other",
")",
":",
"if",
"isinstance",
"(",
"other",
",",
"SSAFile",
")",
":",
"for",
"key",
"in",
"set",
"(",
"chain",
"(",
"self",
".",
"info",
".",
"keys",
"(",
")",
",",
"other",
".",
"info",
".",
"keys",
... | 44.433962 | 25.113208 |
def to_weld_type(weld_type, dim):
"""Summary
Args:
weld_type (TYPE): Description
dim (TYPE): Description
Returns:
TYPE: Description
"""
for i in xrange(dim):
weld_type = WeldVec(weld_type)
return weld_type | [
"def",
"to_weld_type",
"(",
"weld_type",
",",
"dim",
")",
":",
"for",
"i",
"in",
"xrange",
"(",
"dim",
")",
":",
"weld_type",
"=",
"WeldVec",
"(",
"weld_type",
")",
"return",
"weld_type"
] | 19.307692 | 16.153846 |
def END(self):
"""END state."""
logger.debug('In state: END')
self.current_state = STATE_END
if self.script is not None:
self.script.script_init(self.client.lease, self.current_state)
self.script.script_go()
else:
set_net(self.client.lease)
... | [
"def",
"END",
"(",
"self",
")",
":",
"logger",
".",
"debug",
"(",
"'In state: END'",
")",
"self",
".",
"current_state",
"=",
"STATE_END",
"if",
"self",
".",
"script",
"is",
"not",
"None",
":",
"self",
".",
"script",
".",
"script_init",
"(",
"self",
"."... | 32.2 | 13 |
def _handle_execute_reply(self, msg):
""" Reimplemented to support prompt requests.
"""
msg_id = msg['parent_header'].get('msg_id')
info = self._request_info['execute'].get(msg_id)
if info and info.kind == 'prompt':
number = msg['content']['execution_count'] + 1
... | [
"def",
"_handle_execute_reply",
"(",
"self",
",",
"msg",
")",
":",
"msg_id",
"=",
"msg",
"[",
"'parent_header'",
"]",
".",
"get",
"(",
"'msg_id'",
")",
"info",
"=",
"self",
".",
"_request_info",
"[",
"'execute'",
"]",
".",
"get",
"(",
"msg_id",
")",
"i... | 44 | 10.909091 |
def _convert_images(self):
"""
Convert any images into a more Screen-friendly format.
"""
self._plain_images = []
self._colour_map = []
for image in self._images:
colour_map = []
new_image = []
for line in image.split("\n"):
... | [
"def",
"_convert_images",
"(",
"self",
")",
":",
"self",
".",
"_plain_images",
"=",
"[",
"]",
"self",
".",
"_colour_map",
"=",
"[",
"]",
"for",
"image",
"in",
"self",
".",
"_images",
":",
"colour_map",
"=",
"[",
"]",
"new_image",
"=",
"[",
"]",
"for"... | 43.025641 | 10.923077 |
def get(self, url, headers=None, params=None, stream=False, timeout=None):
"""GET request.
:param str url: Request url
:param dict headers: (optional) Request headers
:param dict params: (optional) Request query parameter
:param bool stream: (optional) get content as stream
... | [
"def",
"get",
"(",
"self",
",",
"url",
",",
"headers",
"=",
"None",
",",
"params",
"=",
"None",
",",
"stream",
"=",
"False",
",",
"timeout",
"=",
"None",
")",
":",
"if",
"timeout",
"is",
"None",
":",
"timeout",
"=",
"self",
".",
"timeout",
"respons... | 39.913043 | 17.826087 |
def set_override(self, newchannels):
'''this is a public method for use by drone API or other scripting'''
self.override = newchannels
self.override_counter = 10
self.send_rc_override() | [
"def",
"set_override",
"(",
"self",
",",
"newchannels",
")",
":",
"self",
".",
"override",
"=",
"newchannels",
"self",
".",
"override_counter",
"=",
"10",
"self",
".",
"send_rc_override",
"(",
")"
] | 42.6 | 12.2 |
def get_action(action):
"""Get action."""
action_obj = Base.get_or_new_from_json_dict_with_types(
action, {
'postback': PostbackAction,
'message': MessageAction,
'uri': URIAction,
'datetimepicker': DatetimePickerAction,
'camera': CameraAction,
... | [
"def",
"get_action",
"(",
"action",
")",
":",
"action_obj",
"=",
"Base",
".",
"get_or_new_from_json_dict_with_types",
"(",
"action",
",",
"{",
"'postback'",
":",
"PostbackAction",
",",
"'message'",
":",
"MessageAction",
",",
"'uri'",
":",
"URIAction",
",",
"'dat... | 30.571429 | 12.785714 |
def extract_path(cloudpath):
"""cloudpath: e.g. gs://neuroglancer/DATASET/LAYER/info or s3://..."""
protocol_re = r'^(gs|file|s3|boss|matrix|https?)://'
bucket_re = r'^(/?[~\d\w_\.\-]+)/'
tail_re = r'([\d\w_\.\-]+)/([\d\w_\.\-]+)/?$'
error = UnsupportedProtocolError("""
Cloud path must conform to PROTOCO... | [
"def",
"extract_path",
"(",
"cloudpath",
")",
":",
"protocol_re",
"=",
"r'^(gs|file|s3|boss|matrix|https?)://'",
"bucket_re",
"=",
"r'^(/?[~\\d\\w_\\.\\-]+)/'",
"tail_re",
"=",
"r'([\\d\\w_\\.\\-]+)/([\\d\\w_\\.\\-]+)/?$'",
"error",
"=",
"UnsupportedProtocolError",
"(",
"\"\"\"... | 27.846154 | 20.461538 |
def retrieveVals(self):
"""Retrieve values for graphs."""
lighttpdInfo = LighttpdInfo(self._host, self._port,
self._user, self._password,
self._statuspath, self._ssl)
stats = lighttpdInfo.getServerStats()
if self.hasGraph('... | [
"def",
"retrieveVals",
"(",
"self",
")",
":",
"lighttpdInfo",
"=",
"LighttpdInfo",
"(",
"self",
".",
"_host",
",",
"self",
".",
"_port",
",",
"self",
".",
"_user",
",",
"self",
".",
"_password",
",",
"self",
".",
"_statuspath",
",",
"self",
".",
"_ssl"... | 56.4 | 18.6 |
async def _mogrify(conn, query, args):
"""Safely inline arguments to query text."""
# Introspect the target query for argument types and
# build a list of safely-quoted fully-qualified type names.
ps = await conn.prepare(query)
paramtypes = []
for t in ps.get_parameters():
if t.name.ends... | [
"async",
"def",
"_mogrify",
"(",
"conn",
",",
"query",
",",
"args",
")",
":",
"# Introspect the target query for argument types and",
"# build a list of safely-quoted fully-qualified type names.",
"ps",
"=",
"await",
"conn",
".",
"prepare",
"(",
"query",
")",
"paramtypes"... | 35.333333 | 17.777778 |
def _get_value(self, evt):
"""Internal usage only"""
if evt.err:
e = evt.errors[0]
return "[%s] %s" % (e.reason, e.desc)
if isinstance(evt, EventData):
return "[%s] %s" % (
evt.attr_value.quality, str(evt.attr_value.value))
elif isinst... | [
"def",
"_get_value",
"(",
"self",
",",
"evt",
")",
":",
"if",
"evt",
".",
"err",
":",
"e",
"=",
"evt",
".",
"errors",
"[",
"0",
"]",
"return",
"\"[%s] %s\"",
"%",
"(",
"e",
".",
"reason",
",",
"e",
".",
"desc",
")",
"if",
"isinstance",
"(",
"ev... | 36.578947 | 13.052632 |
def fetchText(cls, url, data, textSearch, optional):
"""Search text entry for given text XPath in a HTML page."""
if cls.css:
searchFun = data.cssselect
else:
searchFun = data.xpath
if textSearch:
text = ''
for match in searchFun(textSearch... | [
"def",
"fetchText",
"(",
"cls",
",",
"url",
",",
"data",
",",
"textSearch",
",",
"optional",
")",
":",
"if",
"cls",
".",
"css",
":",
"searchFun",
"=",
"data",
".",
"cssselect",
"else",
":",
"searchFun",
"=",
"data",
".",
"xpath",
"if",
"textSearch",
... | 38.318182 | 15.681818 |
def add(self, routeID, edges):
"""add(string, list(string)) -> None
Adds a new route with the given id consisting of the given list of edge IDs.
"""
self._connection._beginMessage(tc.CMD_SET_ROUTE_VARIABLE, tc.ADD, routeID,
1 + 4 + sum(map(len, edg... | [
"def",
"add",
"(",
"self",
",",
"routeID",
",",
"edges",
")",
":",
"self",
".",
"_connection",
".",
"_beginMessage",
"(",
"tc",
".",
"CMD_SET_ROUTE_VARIABLE",
",",
"tc",
".",
"ADD",
",",
"routeID",
",",
"1",
"+",
"4",
"+",
"sum",
"(",
"map",
"(",
"... | 46.666667 | 21.222222 |
def independent_freq_count(frequencies, times, conservative=True):
'''This estimates M: the number of independent frequencies in the periodogram.
This follows the terminology on page 3 of Zechmeister & Kurster (2009)::
M = DELTA_f / delta_f
where::
DELTA_f = freq.max() - freq.min()
... | [
"def",
"independent_freq_count",
"(",
"frequencies",
",",
"times",
",",
"conservative",
"=",
"True",
")",
":",
"M",
"=",
"frequencies",
".",
"ptp",
"(",
")",
"*",
"times",
".",
"ptp",
"(",
")",
"if",
"conservative",
":",
"M_eff",
"=",
"min",
"(",
"[",
... | 23.166667 | 28.541667 |
def feed(self, data, o: int = 0, l: int = -1):
"""Feed data to parser."""
if l == -1:
l = len(data) - o
if o < 0 or l < 0:
raise ValueError("negative input")
if o + l > len(data):
raise ValueError("input is larger than buffer size")
self._parse... | [
"def",
"feed",
"(",
"self",
",",
"data",
",",
"o",
":",
"int",
"=",
"0",
",",
"l",
":",
"int",
"=",
"-",
"1",
")",
":",
"if",
"l",
"==",
"-",
"1",
":",
"l",
"=",
"len",
"(",
"data",
")",
"-",
"o",
"if",
"o",
"<",
"0",
"or",
"l",
"<",
... | 37.444444 | 10.777778 |
def version_cmp(ver1, ver2, ignore_epoch=False, **kwargs):
'''
.. versionadded:: 2015.5.4
Do a cmp-style comparison on two packages. Return -1 if ver1 < ver2, 0 if
ver1 == ver2, and 1 if ver1 > ver2. Return None if there was a problem
making the comparison.
ignore_epoch : False
Set to ... | [
"def",
"version_cmp",
"(",
"ver1",
",",
"ver2",
",",
"ignore_epoch",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"__salt__",
"[",
"'lowpkg.version_cmp'",
"]",
"(",
"ver1",
",",
"ver2",
",",
"ignore_epoch",
"=",
"ignore_epoch",
")"
] | 29.5 | 28.1 |
def dumps(self):
"""
Returns contents of config file as string
OUT: out (type: str, hint: config content)
"""
out = ""
for option in self.options:
value = make_value(option.default_value)
out += "%s = %s%s\n" % (option.name, value,
(" # %s" % option.comment) if option.comment else "")
return ou... | [
"def",
"dumps",
"(",
"self",
")",
":",
"out",
"=",
"\"\"",
"for",
"option",
"in",
"self",
".",
"options",
":",
"value",
"=",
"make_value",
"(",
"option",
".",
"default_value",
")",
"out",
"+=",
"\"%s = %s%s\\n\"",
"%",
"(",
"option",
".",
"name",
",",
... | 29.454545 | 10.363636 |
def get_bounding_box(self):
"""Get the bounding box of this file."""
from pyproj import Geod
geod = Geod(ellps='WGS84')
dataset_group = DATASET_KEYS[self.datasets[0]]
idx = 0
lons_ring = None
lats_ring = None
while True:
path = 'Data_Products/{... | [
"def",
"get_bounding_box",
"(",
"self",
")",
":",
"from",
"pyproj",
"import",
"Geod",
"geod",
"=",
"Geod",
"(",
"ellps",
"=",
"'WGS84'",
")",
"dataset_group",
"=",
"DATASET_KEYS",
"[",
"self",
".",
"datasets",
"[",
"0",
"]",
"]",
"idx",
"=",
"0",
"lons... | 42.878788 | 21.484848 |
def unserialize(self, msg_list, content=True, copy=True):
"""Unserialize a msg_list to a nested message dict.
This is roughly the inverse of serialize. The serialize/unserialize
methods work with full message lists, whereas pack/unpack work with
the individual message parts in the messa... | [
"def",
"unserialize",
"(",
"self",
",",
"msg_list",
",",
"content",
"=",
"True",
",",
"copy",
"=",
"True",
")",
":",
"minlen",
"=",
"4",
"message",
"=",
"{",
"}",
"if",
"not",
"copy",
":",
"for",
"i",
"in",
"range",
"(",
"minlen",
")",
":",
"msg_... | 39.055556 | 17.537037 |
def pruned_affine(inp, n_outmaps,
base_axis=1,
w_init=None, b_init=None,
fix_parameters=False, rng=None, with_bias=True,
prune_w=True, rate_w=0.9, prune_b=True, rate_b=0.9):
"""Pruned Affine.
Pruned Affine is the affine function,
exce... | [
"def",
"pruned_affine",
"(",
"inp",
",",
"n_outmaps",
",",
"base_axis",
"=",
"1",
",",
"w_init",
"=",
"None",
",",
"b_init",
"=",
"None",
",",
"fix_parameters",
"=",
"False",
",",
"rng",
"=",
"None",
",",
"with_bias",
"=",
"True",
",",
"prune_w",
"=",
... | 41.159574 | 26.968085 |
def _read_schema(self):
"""return the local filename of the definition file for this schema
if not present or older than expiry, pull the latest version from
the web at self._ontology_file"""
cache_filename = os.path.join(
CACHE_ROOT, "%s.smt" % self._representation)
... | [
"def",
"_read_schema",
"(",
"self",
")",
":",
"cache_filename",
"=",
"os",
".",
"path",
".",
"join",
"(",
"CACHE_ROOT",
",",
"\"%s.smt\"",
"%",
"self",
".",
"_representation",
")",
"log",
".",
"info",
"(",
"\"Attempting to read local schema at %s\"",
"%",
"cac... | 44.722222 | 19.5 |
def _accumulate_random(count, found, oldthing, newthing):
"""This performs on-line random selection.
We have a stream of objects
o_1,c_1; o_2,c_2; ...
where there are c_i equivalent objects like o_1. We'd like to pick
a random object o uniformly at random from the list
[o_1]*c_1 + [... | [
"def",
"_accumulate_random",
"(",
"count",
",",
"found",
",",
"oldthing",
",",
"newthing",
")",
":",
"if",
"randint",
"(",
"1",
",",
"count",
"+",
"found",
")",
"<=",
"found",
":",
"return",
"count",
"+",
"found",
",",
"newthing",
"else",
":",
"return"... | 29.22449 | 21.081633 |
def get_reviews(obj):
"""Simply returns the reviews for an object."""
ctype = ContentType.objects.get_for_model(obj)
return models.Review.objects.filter(content_type=ctype, object_id=obj.id) | [
"def",
"get_reviews",
"(",
"obj",
")",
":",
"ctype",
"=",
"ContentType",
".",
"objects",
".",
"get_for_model",
"(",
"obj",
")",
"return",
"models",
".",
"Review",
".",
"objects",
".",
"filter",
"(",
"content_type",
"=",
"ctype",
",",
"object_id",
"=",
"o... | 49.75 | 16.5 |
def _list_crossmatch(
self,
dbRows):
"""*to a finer grain crossmatch of the input coordinates and the database results.*
**Key Arguments:**
- ``dbRows`` -- the rows return from the database on first crossmatch pass.
**Return:**
- ``matchIndices1`... | [
"def",
"_list_crossmatch",
"(",
"self",
",",
"dbRows",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"'starting the ``_list_crossmatch`` method'",
")",
"dbRas",
"=",
"[",
"]",
"dbRas",
"[",
":",
"]",
"=",
"[",
"d",
"[",
"self",
".",
"raCol",
"]",
"f... | 31.479167 | 22.4375 |
def exec_container(self,
asset_url,
algorithm_url,
resource_group_name,
account_name,
account_key,
location,
share_name_input='compute',
... | [
"def",
"exec_container",
"(",
"self",
",",
"asset_url",
",",
"algorithm_url",
",",
"resource_group_name",
",",
"account_name",
",",
"account_key",
",",
"location",
",",
"share_name_input",
"=",
"'compute'",
",",
"share_name_output",
"=",
"'output'",
",",
"docker_ima... | 54.88 | 22.64 |
def unpack(d):
"""Unpack and return a framed binary message.
"""
p = SBP._parser.parse(d)
assert p.preamble == SBP_PREAMBLE, "Invalid preamble 0x%x." % p.preamble
return SBP(p.msg_type, p.sender, p.length, p.payload, p.crc) | [
"def",
"unpack",
"(",
"d",
")",
":",
"p",
"=",
"SBP",
".",
"_parser",
".",
"parse",
"(",
"d",
")",
"assert",
"p",
".",
"preamble",
"==",
"SBP_PREAMBLE",
",",
"\"Invalid preamble 0x%x.\"",
"%",
"p",
".",
"preamble",
"return",
"SBP",
"(",
"p",
".",
"ms... | 34 | 19.714286 |
def remove(self, item):
"""Remove the first occurence of an item, the caseless way."""
for entry in self:
if item.lower() == entry.lower():
list.remove(self, entry)
return
raise ValueError(': list.remove(x): x not in list') | [
"def",
"remove",
"(",
"self",
",",
"item",
")",
":",
"for",
"entry",
"in",
"self",
":",
"if",
"item",
".",
"lower",
"(",
")",
"==",
"entry",
".",
"lower",
"(",
")",
":",
"list",
".",
"remove",
"(",
"self",
",",
"entry",
")",
"return",
"raise",
... | 40.714286 | 10.428571 |
def intersect(df, other, index=False, keep='first'):
"""
Returns rows that appear in both DataFrames.
Args:
df (pandas.DataFrame): data passed in through the pipe.
other (pandas.DataFrame): other DataFrame to use for set operation with
the first.
Kwargs:
index (bool... | [
"def",
"intersect",
"(",
"df",
",",
"other",
",",
"index",
"=",
"False",
",",
"keep",
"=",
"'first'",
")",
":",
"validate_set_ops",
"(",
"df",
",",
"other",
")",
"if",
"index",
":",
"df_reset_index",
"=",
"df",
".",
"reset_index",
"(",
")",
"other_rese... | 41.27027 | 20.027027 |
def child_link_record_exists(self):
# type: () -> bool
'''
Determine whether this Rock Ridge entry has a child link record (used
for relocating deep directory records).
Parameters:
None.
Returns:
True if this Rock Ridge entry has a child link record, Fa... | [
"def",
"child_link_record_exists",
"(",
"self",
")",
":",
"# type: () -> bool",
"if",
"not",
"self",
".",
"_initialized",
":",
"raise",
"pycdlibexception",
".",
"PyCdlibInternalError",
"(",
"'Rock Ridge extension not yet initialized'",
")",
"return",
"self",
".",
"dr_en... | 37.4 | 28.733333 |
def _add_property(object_type, # type: Type[T]
parameter, # type: Parameter
pycontract=None, # type: Any
validators=None # type: Any
):
"""
A method to dynamically add a property to a class with the optional given pycontract ... | [
"def",
"_add_property",
"(",
"object_type",
",",
"# type: Type[T]",
"parameter",
",",
"# type: Parameter",
"pycontract",
"=",
"None",
",",
"# type: Any",
"validators",
"=",
"None",
"# type: Any",
")",
":",
"property_name",
"=",
"parameter",
".",
"name",
"# 1. create... | 48 | 29.928571 |
def filter(self, field, operator, value):
""" Add a query filter to be applied to the next API list call for this resource.
:param field: Field name to filter by
:type field: str
:param operator: Operator value
:type operator: str
:param value: Value o... | [
"def",
"filter",
"(",
"self",
",",
"field",
",",
"operator",
",",
"value",
")",
":",
"instance",
"=",
"copy",
"(",
"self",
")",
"i",
"=",
"len",
"(",
"instance",
".",
"_filters",
")",
"instance",
".",
"_filters",
".",
"append",
"(",
"{",
"'filter[fie... | 49.392857 | 26.142857 |
def create_comment(self, body, line=github.GithubObject.NotSet, path=github.GithubObject.NotSet, position=github.GithubObject.NotSet):
"""
:calls: `POST /repos/:owner/:repo/commits/:sha/comments <http://developer.github.com/v3/repos/comments>`_
:param body: string
:param line: integer
... | [
"def",
"create_comment",
"(",
"self",
",",
"body",
",",
"line",
"=",
"github",
".",
"GithubObject",
".",
"NotSet",
",",
"path",
"=",
"github",
".",
"GithubObject",
".",
"NotSet",
",",
"position",
"=",
"github",
".",
"GithubObject",
".",
"NotSet",
")",
":... | 49.142857 | 23.285714 |
def _gcs_create(args, _):
""" Create one or more buckets. """
errs = []
for name in args['bucket']:
try:
bucket, key = google.datalab.storage._bucket.parse_name(name)
if bucket and not key:
google.datalab.storage.Bucket(bucket).create(_make_context(args['project']))
else:
rai... | [
"def",
"_gcs_create",
"(",
"args",
",",
"_",
")",
":",
"errs",
"=",
"[",
"]",
"for",
"name",
"in",
"args",
"[",
"'bucket'",
"]",
":",
"try",
":",
"bucket",
",",
"key",
"=",
"google",
".",
"datalab",
".",
"storage",
".",
"_bucket",
".",
"parse_name"... | 35.866667 | 19.533333 |
def drawClosedPath(self, pointList):
"""
Draws a closed series of lines on the current :py:class:`Layer` with the current :py:class:`Brush`.
No interpolation is applied to these point and :py:meth:`drawLine` will be used to connect all the points lineraly.
Coordinates are relative to the original layer size WIT... | [
"def",
"drawClosedPath",
"(",
"self",
",",
"pointList",
")",
":",
"self",
".",
"drawLine",
"(",
"pointList",
"[",
"0",
"]",
"[",
"0",
"]",
",",
"pointList",
"[",
"0",
"]",
"[",
"1",
"]",
",",
"pointList",
"[",
"1",
"]",
"[",
"0",
"]",
",",
"poi... | 49.733333 | 33.466667 |
def format_all(self):
"""
return a trace of parents and children of the obect
"""
res = '\n--- Format all : ' + str(self.name) + ' -------------\n'
res += ' parent = ' + str(self.parent) + '\n'
res += self._get_all_children()
res += self._get_links()
... | [
"def",
"format_all",
"(",
"self",
")",
":",
"res",
"=",
"'\\n--- Format all : '",
"+",
"str",
"(",
"self",
".",
"name",
")",
"+",
"' -------------\\n'",
"res",
"+=",
"' parent = '",
"+",
"str",
"(",
"self",
".",
"parent",
")",
"+",
"'\\n'",
"res",
"+=",
... | 33.3 | 14.5 |
def _reset_internal(self):
"""Resets simulation internal configurations."""
# instantiate simulation from MJCF model
self._load_model()
self.mjpy_model = self.model.get_model(mode="mujoco_py")
self.sim = MjSim(self.mjpy_model)
self.initialize_time(self.control_freq)
... | [
"def",
"_reset_internal",
"(",
"self",
")",
":",
"# instantiate simulation from MJCF model",
"self",
".",
"_load_model",
"(",
")",
"self",
".",
"mjpy_model",
"=",
"self",
".",
"model",
".",
"get_model",
"(",
"mode",
"=",
"\"mujoco_py\"",
")",
"self",
".",
"sim... | 40.722222 | 18.722222 |
def plot_boundaries(self, **kwargs):
""" Plots boundaries of a mesh """
edges = self.extract_edges()
plotter = vtki.Plotter(off_screen=kwargs.pop('off_screen', False),
notebook=kwargs.pop('notebook', None))
plotter.add_mesh(edges, 'r', style='wireframe', l... | [
"def",
"plot_boundaries",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"edges",
"=",
"self",
".",
"extract_edges",
"(",
")",
"plotter",
"=",
"vtki",
".",
"Plotter",
"(",
"off_screen",
"=",
"kwargs",
".",
"pop",
"(",
"'off_screen'",
",",
"False",
")"... | 45.777778 | 18.666667 |
def run(self, cmd, sudo=False, ignore_error=False, success_status=(0,),
error_callback=None, custom_log=None, retry=0):
"""Run a command on the remote host.
The command is run on the remote host, if there is a redirected host
then the command will be run on that redirected host. See... | [
"def",
"run",
"(",
"self",
",",
"cmd",
",",
"sudo",
"=",
"False",
",",
"ignore_error",
"=",
"False",
",",
"success_status",
"=",
"(",
"0",
",",
")",
",",
"error_callback",
"=",
"None",
",",
"custom_log",
"=",
"None",
",",
"retry",
"=",
"0",
")",
":... | 42.610169 | 19.067797 |
def list_downloadable_sources(target_dir):
"""Returns a list of python source files is target_dir
Parameters
----------
target_dir : str
path to the directory where python source file are
Returns
-------
list
list of paths to all Python source files in `target_dir`
"""
... | [
"def",
"list_downloadable_sources",
"(",
"target_dir",
")",
":",
"return",
"[",
"os",
".",
"path",
".",
"join",
"(",
"target_dir",
",",
"fname",
")",
"for",
"fname",
"in",
"os",
".",
"listdir",
"(",
"target_dir",
")",
"if",
"fname",
".",
"endswith",
"(",... | 28.933333 | 17.266667 |
def df(self, y, f, var):
r"""
Derivative of Gaussian log likelihood w.r.t.\ f.
Parameters
----------
y: ndarray
array of 0, 1 valued integers of targets
f: ndarray
latent function from the GLM prior (:math:`\mathbf{f} =
\boldsymbol\Ph... | [
"def",
"df",
"(",
"self",
",",
"y",
",",
"f",
",",
"var",
")",
":",
"var",
"=",
"self",
".",
"_check_param",
"(",
"var",
")",
"y",
",",
"f",
"=",
"np",
".",
"broadcast_arrays",
"(",
"y",
",",
"f",
")",
"return",
"(",
"y",
"-",
"f",
")",
"/"... | 30.521739 | 17.521739 |
def __cutRaw(self, oiraw, maxLength):
'''现将句子按句子完结符号切分,如果切分完后一个句子长度超过限定值
,再对该句子进行切分'''
vec = []
m = re.findall(u".*?[。?!;;!?]", oiraw)
num, l, last = 0, 0, 0
for i in range(len(m)):
if(num + len(m[i]) >= maxLength):
vec.append("".join(m[last:i]... | [
"def",
"__cutRaw",
"(",
"self",
",",
"oiraw",
",",
"maxLength",
")",
":",
"vec",
"=",
"[",
"]",
"m",
"=",
"re",
".",
"findall",
"(",
"u\".*?[。?!;;!?]\", oiraw)",
"",
"",
"",
"num",
",",
"l",
",",
"last",
"=",
"0",
",",
"0",
",",
"0",
"for",
"i"... | 31.8 | 11.2 |
def rows(array):
"""
Function to find the number of rows in an array.
Excel reference: https://support.office.com/en-ie/article/rows-function-b592593e-3fc2-47f2-bec1-bda493811597
:param array: the array of which the rows should be counted.
:return: the number of rows.
"""
if isinstance(arr... | [
"def",
"rows",
"(",
"array",
")",
":",
"if",
"isinstance",
"(",
"array",
",",
"(",
"float",
",",
"int",
")",
")",
":",
"rows",
"=",
"1",
"# special case for A1:A1 type ranges which for some reason only return an int/float",
"elif",
"array",
"is",
"None",
":",
"r... | 34.117647 | 25.529412 |
def roundvals(self, col: str, precision: int=2):
"""
Round floats in a column. Numbers are going to be
converted to floats if they are not already
:param col: column name
:type col: str
:param precision: float precision, defaults to 2
:param precision: int, optio... | [
"def",
"roundvals",
"(",
"self",
",",
"col",
":",
"str",
",",
"precision",
":",
"int",
"=",
"2",
")",
":",
"try",
":",
"self",
".",
"df",
"[",
"col",
"]",
"=",
"self",
".",
"df",
"[",
"col",
"]",
".",
"astype",
"(",
"\"float64\"",
")",
"self",
... | 35.052632 | 15.789474 |
def _set_management(self, v, load=False):
"""
Setter method for management, mapped from YANG variable /interface/management (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_management is considered as a private
method. Backends looking to populate this variable... | [
"def",
"_set_management",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",
"bas... | 124.44 | 60.72 |
def reduce_function(op_func, input_tensor, axis=None, keepdims=None,
name=None, reduction_indices=None):
"""
This function used to be needed to support tf 1.4 and early, but support for tf 1.4 and earlier is now dropped.
:param op_func: expects the function to handle eg: tf.reduce_sum.
:para... | [
"def",
"reduce_function",
"(",
"op_func",
",",
"input_tensor",
",",
"axis",
"=",
"None",
",",
"keepdims",
"=",
"None",
",",
"name",
"=",
"None",
",",
"reduction_indices",
"=",
"None",
")",
":",
"warnings",
".",
"warn",
"(",
"\"`reduce_function` is deprecated a... | 49.4 | 27.7 |
def update():
'''
Update the cache file for the bucket.
'''
metadata = _init()
if S3_SYNC_ON_UPDATE:
# sync the buckets to the local cache
log.info('Syncing local cache from S3...')
for saltenv, env_meta in six.iteritems(metadata):
for bucket_files in _find_file... | [
"def",
"update",
"(",
")",
":",
"metadata",
"=",
"_init",
"(",
")",
"if",
"S3_SYNC_ON_UPDATE",
":",
"# sync the buckets to the local cache",
"log",
".",
"info",
"(",
"'Syncing local cache from S3...'",
")",
"for",
"saltenv",
",",
"env_meta",
"in",
"six",
".",
"i... | 39.666667 | 26.904762 |
def decrypt(self, enctext, key_file=None, id_attr=''):
""" Decrypting an encrypted text by the use of a private key.
:param enctext: The encrypted text as a string
:return: The decrypted text
"""
if not id_attr:
id_attr = self.id_attr
if not isinstance(key_f... | [
"def",
"decrypt",
"(",
"self",
",",
"enctext",
",",
"key_file",
"=",
"None",
",",
"id_attr",
"=",
"''",
")",
":",
"if",
"not",
"id_attr",
":",
"id_attr",
"=",
"self",
".",
"id_attr",
"if",
"not",
"isinstance",
"(",
"key_file",
",",
"list",
")",
":",
... | 32.777778 | 18.185185 |
def _onIncomingMessageReceived(self, conn, message):
"""
Callback for initial messages on incoming connections. Handles encryption, utility messages, and association of the connection with a Node.
Once this initial setup is done, the relevant connected callback is executed, and further messages ... | [
"def",
"_onIncomingMessageReceived",
"(",
"self",
",",
"conn",
",",
"message",
")",
":",
"if",
"self",
".",
"_syncObj",
".",
"encryptor",
"and",
"not",
"conn",
".",
"sendRandKey",
":",
"conn",
".",
"sendRandKey",
"=",
"message",
"conn",
".",
"recvRandKey",
... | 43.65625 | 23.84375 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.