text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def roundClosestValid(val, res, decimals=None):
""" round to closest resolution """
if decimals is None and "." in str(res):
decimals = len(str(res).split('.')[1])
return round(round(val / res) * res, decimals) | [
"def",
"roundClosestValid",
"(",
"val",
",",
"res",
",",
"decimals",
"=",
"None",
")",
":",
"if",
"decimals",
"is",
"None",
"and",
"\".\"",
"in",
"str",
"(",
"res",
")",
":",
"decimals",
"=",
"len",
"(",
"str",
"(",
"res",
")",
".",
"split",
"(",
... | 40.333333 | 0.008097 |
def get_locales(prefix=None, normalize=True,
locale_getter=_default_locale_getter):
"""
Get all the locales that are available on the system.
Parameters
----------
prefix : str
If not ``None`` then return only those locales with the prefix
provided. For example to ge... | [
"def",
"get_locales",
"(",
"prefix",
"=",
"None",
",",
"normalize",
"=",
"True",
",",
"locale_getter",
"=",
"_default_locale_getter",
")",
":",
"try",
":",
"raw_locales",
"=",
"locale_getter",
"(",
")",
"except",
"Exception",
":",
"return",
"None",
"try",
":... | 32.518519 | 0.000553 |
def object_to_markdownpage(obj_name, obj, s=''):
"""Generate the markdown documentation of a Python object.
Parameters
----------
obj_name : str
Name of the Python object.
obj : object
Python object (class, method, function, ...)
s : str (default: '')
A string to which t... | [
"def",
"object_to_markdownpage",
"(",
"obj_name",
",",
"obj",
",",
"s",
"=",
"''",
")",
":",
"# header",
"s",
"+=",
"'## %s\\n'",
"%",
"obj_name",
"# function/class/method signature",
"sig",
"=",
"str",
"(",
"inspect",
".",
"signature",
"(",
"obj",
")",
")",... | 32.86 | 0.000591 |
def extractPrintSaveIntermittens():
"""
This function will print out the intermittents onto the screen for casual viewing. It will also print out
where the giant summary dictionary is going to be stored.
:return: None
"""
# extract intermittents from collected failed tests
global g_summary... | [
"def",
"extractPrintSaveIntermittens",
"(",
")",
":",
"# extract intermittents from collected failed tests",
"global",
"g_summary_dict_intermittents",
"localtz",
"=",
"time",
".",
"tzname",
"[",
"0",
"]",
"for",
"ind",
"in",
"range",
"(",
"len",
"(",
"g_summary_dict_all... | 55.333333 | 0.008387 |
def load_features(paths: List[str],
expected_shape: Optional[tuple] = None) -> List[np.ndarray]:
"""
Load features specified with absolute paths.
:param paths: List of files specified with paths.
:param expected_shape: Optional expected shape.
:return: A list of loaded images (num... | [
"def",
"load_features",
"(",
"paths",
":",
"List",
"[",
"str",
"]",
",",
"expected_shape",
":",
"Optional",
"[",
"tuple",
"]",
"=",
"None",
")",
"->",
"List",
"[",
"np",
".",
"ndarray",
"]",
":",
"data",
"=",
"[",
"]",
"# type: List[np.ndarray]",
"for"... | 35.538462 | 0.00211 |
def make_scrape_request(session, url, mode='get', data=None):
"""Make a request to URL."""
try:
html = session.request(mode, url, data=data)
except RequestException:
raise VooblyError('failed to connect')
if SCRAPE_FETCH_ERROR in html.text:
raise VooblyError('not logged in')
... | [
"def",
"make_scrape_request",
"(",
"session",
",",
"url",
",",
"mode",
"=",
"'get'",
",",
"data",
"=",
"None",
")",
":",
"try",
":",
"html",
"=",
"session",
".",
"request",
"(",
"mode",
",",
"url",
",",
"data",
"=",
"data",
")",
"except",
"RequestExc... | 43.272727 | 0.002058 |
def copy(self):
"""Make a deep copy of this object.
Example::
>>> c2 = c.copy()
"""
vec1 = np.copy(self.scoef1._vec)
vec2 = np.copy(self.scoef2._vec)
return VectorCoefs(vec1, vec2, self.nmax, self.mmax) | [
"def",
"copy",
"(",
"self",
")",
":",
"vec1",
"=",
"np",
".",
"copy",
"(",
"self",
".",
"scoef1",
".",
"_vec",
")",
"vec2",
"=",
"np",
".",
"copy",
"(",
"self",
".",
"scoef2",
".",
"_vec",
")",
"return",
"VectorCoefs",
"(",
"vec1",
",",
"vec2",
... | 25.545455 | 0.013746 |
def __create_list_bidir_connections(self):
"""!
@brief Creates network as bidirectional list.
@details Each oscillator may be conneted with two neighbors in line with classical list structure: right, left.
"""
if (self._conn_represent == conn_represent.MA... | [
"def",
"__create_list_bidir_connections",
"(",
"self",
")",
":",
"if",
"(",
"self",
".",
"_conn_represent",
"==",
"conn_represent",
".",
"MATRIX",
")",
":",
"for",
"index",
"in",
"range",
"(",
"0",
",",
"self",
".",
"_num_osc",
",",
"1",
")",
":",
"self"... | 43.64 | 0.013453 |
def evaluate_net(net, path_imgrec, num_classes, num_batch, mean_pixels, data_shape,
model_prefix, epoch, ctx=mx.cpu(), batch_size=32,
path_imglist="", nms_thresh=0.45, force_nms=False,
ovp_thresh=0.5, use_difficult=False, class_names=None,
voc07_metric... | [
"def",
"evaluate_net",
"(",
"net",
",",
"path_imgrec",
",",
"num_classes",
",",
"num_batch",
",",
"mean_pixels",
",",
"data_shape",
",",
"model_prefix",
",",
"epoch",
",",
"ctx",
"=",
"mx",
".",
"cpu",
"(",
")",
",",
"batch_size",
"=",
"32",
",",
"path_i... | 36.36 | 0.00241 |
def clean(outputdir, drivers=None):
"""Remove driver executables from the specified outputdir.
drivers can be a list of drivers to filter which executables
to remove. Specify a version using an equal sign i.e.: 'chrome=2.2'
"""
if drivers:
# Generate a list of tuples: [(driver_name, request... | [
"def",
"clean",
"(",
"outputdir",
",",
"drivers",
"=",
"None",
")",
":",
"if",
"drivers",
":",
"# Generate a list of tuples: [(driver_name, requested_version)]",
"# If driver string does not contain a version, the second element",
"# of the tuple is None.",
"# Example:",
"# [('driv... | 40.365854 | 0.00059 |
def template_inheritance(obj):
'''
Generator that iterates the template and its ancestors.
The order is from most specialized (furthest descendant) to
most general (furthest ancestor).
obj can be either:
1. Mako Template object
2. Mako `self` object (available within a rendering tem... | [
"def",
"template_inheritance",
"(",
"obj",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"MakoTemplate",
")",
":",
"obj",
"=",
"create_mako_context",
"(",
"obj",
")",
"[",
"'self'",
"]",
"elif",
"isinstance",
"(",
"obj",
",",
"MakoContext",
")",
":",
"o... | 32.294118 | 0.00177 |
def sim(self, src, tar):
"""Return the length similarity of two strings.
Length similarity is the ratio of the length of the shorter string to
the longer.
Parameters
----------
src : str
Source string for comparison
tar : str
Target strin... | [
"def",
"sim",
"(",
"self",
",",
"src",
",",
"tar",
")",
":",
"if",
"src",
"==",
"tar",
":",
"return",
"1.0",
"if",
"not",
"src",
"or",
"not",
"tar",
":",
"return",
"0.0",
"return",
"(",
"len",
"(",
"src",
")",
"/",
"len",
"(",
"tar",
")",
"if... | 22.578947 | 0.002235 |
def check_signature(signature, key, data):
"""Compute the HMAC signature and test against a given hash."""
if isinstance(key, type(u'')):
key = key.encode()
digest = 'sha1=' + hmac.new(key, data, hashlib.sha1).hexdigest()
# Covert everything to byte sequences
if isinstance(digest, type(u''... | [
"def",
"check_signature",
"(",
"signature",
",",
"key",
",",
"data",
")",
":",
"if",
"isinstance",
"(",
"key",
",",
"type",
"(",
"u''",
")",
")",
":",
"key",
"=",
"key",
".",
"encode",
"(",
")",
"digest",
"=",
"'sha1='",
"+",
"hmac",
".",
"new",
... | 34.642857 | 0.002008 |
def get_map_location(target_device, fallback_device='cpu'):
"""Determine the location to map loaded data (e.g., weights)
for a given target device (e.g. 'cuda').
"""
map_location = torch.device(target_device)
# The user wants to use CUDA but there is no CUDA device
# available, thus fall back t... | [
"def",
"get_map_location",
"(",
"target_device",
",",
"fallback_device",
"=",
"'cpu'",
")",
":",
"map_location",
"=",
"torch",
".",
"device",
"(",
"target_device",
")",
"# The user wants to use CUDA but there is no CUDA device",
"# available, thus fall back to CPU.",
"if",
... | 42.4375 | 0.001441 |
def split_args(args):
"""
Split a list of argument strings into a dictionary where each key is an
argument name.
An argument looks like ``force_ssl=True``.
"""
if not args:
return {}
# Handle the old comma separated argument format.
if len(args) == 1 and not REGEXP_ARGS.search(... | [
"def",
"split_args",
"(",
"args",
")",
":",
"if",
"not",
"args",
":",
"return",
"{",
"}",
"# Handle the old comma separated argument format.",
"if",
"len",
"(",
"args",
")",
"==",
"1",
"and",
"not",
"REGEXP_ARGS",
".",
"search",
"(",
"args",
"[",
"0",
"]",... | 27.227273 | 0.001613 |
def queryWorkitems(self, query_str, projectarea_id=None,
projectarea_name=None, returned_properties=None,
archived=False):
"""Query workitems with the query string in a certain
:class:`rtcclient.project_area.ProjectArea`
At least either of `projecta... | [
"def",
"queryWorkitems",
"(",
"self",
",",
"query_str",
",",
"projectarea_id",
"=",
"None",
",",
"projectarea_name",
"=",
"None",
",",
"returned_properties",
"=",
"None",
",",
"archived",
"=",
"False",
")",
":",
"pa_id",
"=",
"(",
"self",
".",
"rtc_obj",
"... | 45.789474 | 0.002251 |
def start(self, wait_for_completion=True, operation_timeout=None):
"""
Start this CPC, using the HMC operation "Start CPC".
Authorization requirements:
* Object-access permission to this CPC.
* Task permission for the "Start (start a single DPM system)" task.
Parameter... | [
"def",
"start",
"(",
"self",
",",
"wait_for_completion",
"=",
"True",
",",
"operation_timeout",
"=",
"None",
")",
":",
"result",
"=",
"self",
".",
"manager",
".",
"session",
".",
"post",
"(",
"self",
".",
"uri",
"+",
"'/operations/start'",
",",
"wait_for_c... | 37.90566 | 0.00097 |
def save_figures(image_path, fig_count, gallery_conf):
"""Save all open matplotlib figures of the example code-block
Parameters
----------
image_path : str
Path where plots are saved (format string which accepts figure number)
fig_count : int
Previous figure number count. Figure num... | [
"def",
"save_figures",
"(",
"image_path",
",",
"fig_count",
",",
"gallery_conf",
")",
":",
"figure_list",
"=",
"[",
"]",
"fig_managers",
"=",
"matplotlib",
".",
"_pylab_helpers",
".",
"Gcf",
".",
"get_all_fig_managers",
"(",
")",
"for",
"fig_mngr",
"in",
"fig_... | 38.102041 | 0.000522 |
def render_debug_img(
file_name,
page_num,
elems,
nodes=[],
scaler=1,
print_segments=False,
print_curves=True,
print_table_bbox=True,
print_text_as_rect=True,
):
"""
Shows an image rendering of the pdf page along with debugging
info printed
"""
# For debugging sho... | [
"def",
"render_debug_img",
"(",
"file_name",
",",
"page_num",
",",
"elems",
",",
"nodes",
"=",
"[",
"]",
",",
"scaler",
"=",
"1",
",",
"print_segments",
"=",
"False",
",",
"print_curves",
"=",
"True",
",",
"print_table_bbox",
"=",
"True",
",",
"print_text_... | 34.147059 | 0.001256 |
async def wait_for_group(self, container, networkid, timeout = 120):
"""
Wait for a VXLAN group to be created
"""
if networkid in self._current_groups:
return self._current_groups[networkid]
else:
if not self._connection.connected:
raise Co... | [
"async",
"def",
"wait_for_group",
"(",
"self",
",",
"container",
",",
"networkid",
",",
"timeout",
"=",
"120",
")",
":",
"if",
"networkid",
"in",
"self",
".",
"_current_groups",
":",
"return",
"self",
".",
"_current_groups",
"[",
"networkid",
"]",
"else",
... | 48.333333 | 0.009019 |
def fields(depth, Rp, Rm, Gam, lrec, lsrc, zsrc, TM):
r"""Calculate Pu+, Pu-, Pd+, Pd-.
This is a modified version of empymod.kernel.fields(). See the original
version for more information.
"""
# Booleans if src in first or last layer; swapped if up=True
first_layer = lsrc == 0
last_layer ... | [
"def",
"fields",
"(",
"depth",
",",
"Rp",
",",
"Rm",
",",
"Gam",
",",
"lrec",
",",
"lsrc",
",",
"zsrc",
",",
"TM",
")",
":",
"# Booleans if src in first or last layer; swapped if up=True",
"first_layer",
"=",
"lsrc",
"==",
"0",
"last_layer",
"=",
"lsrc",
"==... | 30.152778 | 0.000446 |
def _conflict_bail(VC_err, version):
"""
Setuptools was imported prior to invocation, so it is
unsafe to unload it. Bail out.
"""
conflict_tmpl = textwrap.dedent("""
The required version of setuptools (>={version}) is not available,
and can't be installed while this script is running... | [
"def",
"_conflict_bail",
"(",
"VC_err",
",",
"version",
")",
":",
"conflict_tmpl",
"=",
"textwrap",
".",
"dedent",
"(",
"\"\"\"\n The required version of setuptools (>={version}) is not available,\n and can't be installed while this script is running. Please\n instal... | 34.125 | 0.001783 |
def circular(cls, shape, pixel_scale, radius_arcsec, centre=(0., 0.), invert=False):
"""Setup a mask where unmasked pixels are within a circle of an input arc second radius and centre.
Parameters
----------
shape: (int, int)
The (y,x) shape of the mask in units of pixels.
... | [
"def",
"circular",
"(",
"cls",
",",
"shape",
",",
"pixel_scale",
",",
"radius_arcsec",
",",
"centre",
"=",
"(",
"0.",
",",
"0.",
")",
",",
"invert",
"=",
"False",
")",
":",
"mask",
"=",
"mask_util",
".",
"mask_circular_from_shape_pixel_scale_and_radius",
"("... | 50.722222 | 0.008602 |
def distance_correlation_sqr(x, y, **kwargs):
"""
distance_correlation_sqr(x, y, *, exponent=1)
Computes the usual (biased) estimator for the squared distance correlation
between two random vectors.
Parameters
----------
x: array_like
First random vector. The columns correspond wit... | [
"def",
"distance_correlation_sqr",
"(",
"x",
",",
"y",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"_can_use_fast_algorithm",
"(",
"x",
",",
"y",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_distance_correlation_sqr_fast",
"(",
"x",
",",
"y",
")",
"else",... | 31.258621 | 0.000535 |
def create_key_file(path):
"""
Creates a new encryption key in the path provided and sets the file
permissions. Setting the file permissions currently does not work
on Windows platforms because of the differences in how file
permissions are read and modified.
"""
iv = "{}{}".format(os.urand... | [
"def",
"create_key_file",
"(",
"path",
")",
":",
"iv",
"=",
"\"{}{}\"",
".",
"format",
"(",
"os",
".",
"urandom",
"(",
"32",
")",
",",
"time",
".",
"time",
"(",
")",
")",
"new_key",
"=",
"generate_key",
"(",
"ensure_bytes",
"(",
"iv",
")",
")",
"wi... | 39.583333 | 0.002058 |
def simplify_specifiers(spec):
"""Try to simplify a SpecifierSet by combining redundant specifiers."""
def key(s):
return (s.version, 1 if s.operator in ['>=', '<'] else 2)
def in_bounds(v, lo, hi):
if lo and v not in lo:
return False
if hi and v not in hi:
... | [
"def",
"simplify_specifiers",
"(",
"spec",
")",
":",
"def",
"key",
"(",
"s",
")",
":",
"return",
"(",
"s",
".",
"version",
",",
"1",
"if",
"s",
".",
"operator",
"in",
"[",
"'>='",
",",
"'<'",
"]",
"else",
"2",
")",
"def",
"in_bounds",
"(",
"v",
... | 29.403846 | 0.001899 |
def addItem(self, child, href):
"""Add a new item (a catalogue or resource) as a child of this catalogue."""
assert isinstance(child, Base), "child must be a hypercat Catalogue or Resource"
child.setHref(href)
for item in self.items:
assert item.href != href, "All items in a ... | [
"def",
"addItem",
"(",
"self",
",",
"child",
",",
"href",
")",
":",
"assert",
"isinstance",
"(",
"child",
",",
"Base",
")",
",",
"\"child must be a hypercat Catalogue or Resource\"",
"child",
".",
"setHref",
"(",
"href",
")",
"for",
"item",
"in",
"self",
"."... | 52.375 | 0.011737 |
async def aiter(*args):
"""Return an iterator object.
Args:
obj: An object that implements the __iter__ or __aiter__ method.
sentinel: An optional sentinel value to look for while iterator.
Return:
iterable: Some iterable that provides a __anext__ method.
Raises:
TypeE... | [
"async",
"def",
"aiter",
"(",
"*",
"args",
")",
":",
"if",
"not",
"args",
":",
"raise",
"TypeError",
"(",
"'aiter() expected at least 1 arguments, got 0'",
")",
"if",
"len",
"(",
"args",
")",
">",
"2",
":",
"raise",
"TypeError",
"(",
"'aiter() expected at most... | 34.253968 | 0.00045 |
def delete_vpcid_for_switch(vpc_id, switch_ip):
"""Removes unused vpcid for a switch.
:param vpc_id: vpc id to remove
:param switch_ip: ip address of the switch
"""
LOG.debug("delete_vpcid_for_switch called")
session = bc.get_writer_session()
vpc = _lookup_one_vpc_allocs(vpc_id=vpc_id,
... | [
"def",
"delete_vpcid_for_switch",
"(",
"vpc_id",
",",
"switch_ip",
")",
":",
"LOG",
".",
"debug",
"(",
"\"delete_vpcid_for_switch called\"",
")",
"session",
"=",
"bc",
".",
"get_writer_session",
"(",
")",
"vpc",
"=",
"_lookup_one_vpc_allocs",
"(",
"vpc_id",
"=",
... | 29.866667 | 0.002165 |
def _setup(self):
"""Prepare for code generation by setting up root clock nodes.
These nodes are subsequently used as the basis for all clock operations.
"""
# Create a root system ticks and user configurable ticks
systick = self.allocator.allocate_stream(DataStream.CounterType... | [
"def",
"_setup",
"(",
"self",
")",
":",
"# Create a root system ticks and user configurable ticks",
"systick",
"=",
"self",
".",
"allocator",
".",
"allocate_stream",
"(",
"DataStream",
".",
"CounterType",
",",
"attach",
"=",
"True",
")",
"fasttick",
"=",
"self",
"... | 56.181818 | 0.009547 |
def sample_with_temperature(x, dim, temperature=1.0, dtype=tf.int32, name=None):
"""Either argmax or random sampling.
Args:
x: a Tensor.
dim: a Dimension in x.shape.dims
temperature: a float 0.0=argmax 1.0=random
dtype: a tf.dtype (for the output)
name: an optional string
Returns:
a Ten... | [
"def",
"sample_with_temperature",
"(",
"x",
",",
"dim",
",",
"temperature",
"=",
"1.0",
",",
"dtype",
"=",
"tf",
".",
"int32",
",",
"name",
"=",
"None",
")",
":",
"dim",
"=",
"convert_to_dimension",
"(",
"dim",
")",
"with",
"tf",
".",
"name_scope",
"("... | 30.193548 | 0.013458 |
def train(model, X_train=None, Y_train=None, save=False,
predictions_adv=None, evaluate=None,
args=None, rng=None, var_list=None,
attack=None, attack_args=None):
"""
Train a TF Eager model
:param model: cleverhans.model.Model
:param X_train: numpy array with training inputs
:para... | [
"def",
"train",
"(",
"model",
",",
"X_train",
"=",
"None",
",",
"Y_train",
"=",
"None",
",",
"save",
"=",
"False",
",",
"predictions_adv",
"=",
"None",
",",
"evaluate",
"=",
"None",
",",
"args",
"=",
"None",
",",
"rng",
"=",
"None",
",",
"var_list",
... | 39.104762 | 0.009026 |
def __update(self):
"""
This is called each time an attribute is asked, to be sure every params are updated, beceause of callbacks.
"""
# I can not set the size attr because it is my property, so I set the width and height separately
width, height = self.size
super(BaseW... | [
"def",
"__update",
"(",
"self",
")",
":",
"# I can not set the size attr because it is my property, so I set the width and height separately",
"width",
",",
"height",
"=",
"self",
".",
"size",
"super",
"(",
"BaseWidget",
",",
"self",
")",
".",
"__setattr__",
"(",
"\"wid... | 48 | 0.00818 |
def process_record_dataset(dataset, is_training, batch_size, shuffle_buffer,
parse_record_fn, num_epochs=1, num_gpus=None,
examples_per_epoch=None, dtype=tf.float32):
"""Given a Dataset with raw records, return an iterator over the records.
Args:
dataset: A... | [
"def",
"process_record_dataset",
"(",
"dataset",
",",
"is_training",
",",
"batch_size",
",",
"shuffle_buffer",
",",
"parse_record_fn",
",",
"num_epochs",
"=",
"1",
",",
"num_gpus",
"=",
"None",
",",
"examples_per_epoch",
"=",
"None",
",",
"dtype",
"=",
"tf",
"... | 47.444444 | 0.008413 |
def configure_nodes(self, info):
""" Handles display of the nodes editor.
"""
if info.initialized:
self.model.edit_traits(parent=info.ui.control,
kind="live", view=nodes_view) | [
"def",
"configure_nodes",
"(",
"self",
",",
"info",
")",
":",
"if",
"info",
".",
"initialized",
":",
"self",
".",
"model",
".",
"edit_traits",
"(",
"parent",
"=",
"info",
".",
"ui",
".",
"control",
",",
"kind",
"=",
"\"live\"",
",",
"view",
"=",
"nod... | 37 | 0.013216 |
def setup(app):
''' Required Sphinx extension setup function. '''
app.add_node(bokeh_palette_group, html=(html_visit_bokeh_palette_group, None))
app.add_directive('bokeh-palette-group', BokehPaletteGroupDirective) | [
"def",
"setup",
"(",
"app",
")",
":",
"app",
".",
"add_node",
"(",
"bokeh_palette_group",
",",
"html",
"=",
"(",
"html_visit_bokeh_palette_group",
",",
"None",
")",
")",
"app",
".",
"add_directive",
"(",
"'bokeh-palette-group'",
",",
"BokehPaletteGroupDirective",
... | 55.5 | 0.008889 |
def MessageSetItemSizer(field_number):
"""Returns a sizer for extensions of MessageSet.
The message set message looks like this:
message MessageSet {
repeated group Item = 1 {
required int32 type_id = 2;
required string message = 3;
}
}
"""
static_size = (_TagSize(1) * 2 + _... | [
"def",
"MessageSetItemSizer",
"(",
"field_number",
")",
":",
"static_size",
"=",
"(",
"_TagSize",
"(",
"1",
")",
"*",
"2",
"+",
"_TagSize",
"(",
"2",
")",
"+",
"_VarintSize",
"(",
"field_number",
")",
"+",
"_TagSize",
"(",
"3",
")",
")",
"local_VarintSiz... | 26.15 | 0.012915 |
def build_overviews(source_file, factors=None, minsize=256, external=False,
blocksize=256, interleave='pixel', compress='lzw',
resampling=Resampling.gauss, **kwargs):
"""Build overviews at one or more decimation factors for all
bands of the dataset.
Parameters
--... | [
"def",
"build_overviews",
"(",
"source_file",
",",
"factors",
"=",
"None",
",",
"minsize",
"=",
"256",
",",
"external",
"=",
"False",
",",
"blocksize",
"=",
"256",
",",
"interleave",
"=",
"'pixel'",
",",
"compress",
"=",
"'lzw'",
",",
"resampling",
"=",
... | 38.244898 | 0.001561 |
def validate(self, value, messages=None, prefix=None):
"""validate(value[, messages[, prefix]]) -> True | False
Validates the given value according to this PrimitiveType
definition. Validation error messages are appended to an optional
messages array, each with the optional message pre... | [
"def",
"validate",
"(",
"self",
",",
"value",
",",
"messages",
"=",
"None",
",",
"prefix",
"=",
"None",
")",
":",
"valid",
"=",
"False",
"def",
"log",
"(",
"msg",
")",
":",
"if",
"messages",
"is",
"not",
"None",
":",
"if",
"prefix",
"is",
"not",
... | 39.939394 | 0.002222 |
def set_icon_file(self, filename, rel="icon"):
""" Allows to define an icon for the App
Args:
filename (str): the resource file name (ie. "/res:myicon.png")
rel (str): leave it unchanged (standard "icon")
"""
mimetype, encoding = mimetypes.guess_type(... | [
"def",
"set_icon_file",
"(",
"self",
",",
"filename",
",",
"rel",
"=",
"\"icon\"",
")",
":",
"mimetype",
",",
"encoding",
"=",
"mimetypes",
".",
"guess_type",
"(",
"filename",
")",
"self",
".",
"add_child",
"(",
"\"favicon\"",
",",
"'<link rel=\"%s\" href=\"%s... | 46.888889 | 0.009302 |
def bitonic_sort(arr, reverse=False):
"""
bitonic sort is sorting algorithm to use multiple process, but this code not containing parallel process
It can sort only array that sizes power of 2
It can sort array in both increasing order and decreasing order by giving argument true(increasing) and false(de... | [
"def",
"bitonic_sort",
"(",
"arr",
",",
"reverse",
"=",
"False",
")",
":",
"def",
"compare",
"(",
"arr",
",",
"reverse",
")",
":",
"n",
"=",
"len",
"(",
"arr",
")",
"//",
"2",
"for",
"i",
"in",
"range",
"(",
"n",
")",
":",
"if",
"reverse",
"!="... | 31.72093 | 0.008535 |
def _run_markdownlint(matched_filenames, show_lint_files):
"""Run markdownlint on matched_filenames."""
from prospector.message import Message, Location
for filename in matched_filenames:
_debug_linter_status("mdl", filename, show_lint_files)
try:
proc = subprocess.Popen(["mdl"] + matc... | [
"def",
"_run_markdownlint",
"(",
"matched_filenames",
",",
"show_lint_files",
")",
":",
"from",
"prospector",
".",
"message",
"import",
"Message",
",",
"Location",
"for",
"filename",
"in",
"matched_filenames",
":",
"_debug_linter_status",
"(",
"\"mdl\"",
",",
"filen... | 35.518519 | 0.00203 |
def get_url_shortener():
"""
Return the selected URL shortener backend.
"""
try:
backend_module = import_module(URL_SHORTENER_BACKEND)
backend = getattr(backend_module, 'backend')
except (ImportError, AttributeError):
warnings.warn('%s backend cannot be imported' % URL_SHORTE... | [
"def",
"get_url_shortener",
"(",
")",
":",
"try",
":",
"backend_module",
"=",
"import_module",
"(",
"URL_SHORTENER_BACKEND",
")",
"backend",
"=",
"getattr",
"(",
"backend_module",
",",
"'backend'",
")",
"except",
"(",
"ImportError",
",",
"AttributeError",
")",
"... | 32.9375 | 0.001845 |
def compute_average_oxidation_state(site):
"""
Calculates the average oxidation state of a site
Args:
site: Site to compute average oxidation state
Returns:
Average oxidation state of site.
"""
try:
avg_oxi = sum([sp.oxi_state * occu
for sp, occu ... | [
"def",
"compute_average_oxidation_state",
"(",
"site",
")",
":",
"try",
":",
"avg_oxi",
"=",
"sum",
"(",
"[",
"sp",
".",
"oxi_state",
"*",
"occu",
"for",
"sp",
",",
"occu",
"in",
"site",
".",
"species",
".",
"items",
"(",
")",
"if",
"sp",
"is",
"not"... | 30 | 0.001404 |
def build_db_tables(db):
"""Build Seshet's basic database schema. Requires one parameter,
`db` as `pydal.DAL` instance.
"""
if not isinstance(db, DAL) or not db._uri:
raise Exception("Need valid DAL object to define tables")
# event log - self-explanatory, logs all events
db.define... | [
"def",
"build_db_tables",
"(",
"db",
")",
":",
"if",
"not",
"isinstance",
"(",
"db",
",",
"DAL",
")",
"or",
"not",
"db",
".",
"_uri",
":",
"raise",
"Exception",
"(",
"\"Need valid DAL object to define tables\"",
")",
"# event log - self-explanatory, logs all events"... | 42.606061 | 0.001391 |
def wait_for_prepare_to_finish(
self,
prepare_id,
sec_to_sleep=5.0,
max_retries=100000):
"""wait_for_prepare_to_finish
:param prepare_id: MLPrepare.id to wait on
:param sec_to_sleep: seconds to sleep during polling
:param max_retries: max ... | [
"def",
"wait_for_prepare_to_finish",
"(",
"self",
",",
"prepare_id",
",",
"sec_to_sleep",
"=",
"5.0",
",",
"max_retries",
"=",
"100000",
")",
":",
"not_done",
"=",
"True",
"retry_attempt",
"=",
"1",
"while",
"not_done",
":",
"if",
"self",
".",
"debug",
":",
... | 34.975309 | 0.000687 |
def split_url(self, url):
"""Parse an IIIF API URL path into components.
Will parse a URL or URL path that accords with either the
parametrized or info API forms. Will raise an IIIFRequestError on
failure.
If self.identifier is set then url is assumed not to include the
... | [
"def",
"split_url",
"(",
"self",
",",
"url",
")",
":",
"# clear data first",
"identifier",
"=",
"self",
".",
"identifier",
"self",
".",
"clear",
"(",
")",
"# url must start with baseurl if set (including slash)",
"if",
"(",
"self",
".",
"baseurl",
"is",
"not",
"... | 42.448276 | 0.001588 |
def _linearEOM(y,t,pot):
"""
NAME:
linearEOM
PURPOSE:
the one-dimensional equation-of-motion
INPUT:
y - current phase-space position
t - current time
pot - (list of) linearPotential instance(s)
OUTPUT:
dy/dt
HISTORY:
2010-07-13 - Bovy (NYU)
""... | [
"def",
"_linearEOM",
"(",
"y",
",",
"t",
",",
"pot",
")",
":",
"return",
"[",
"y",
"[",
"1",
"]",
",",
"_evaluatelinearForces",
"(",
"pot",
",",
"y",
"[",
"0",
"]",
",",
"t",
"=",
"t",
")",
"]"
] | 22.5 | 0.016 |
def EncryptPassword(password, key):
""" Encrypts the password using the given key. """
from time import time
from array import array
import hmac
import sha
import os
import base64
H = UcsUtils.GetShaHash
uhash = H(','.join(str(x) for x in [`time()`, `os.getpid()`, `len(password)`, password, key]))[:... | [
"def",
"EncryptPassword",
"(",
"password",
",",
"key",
")",
":",
"from",
"time",
"import",
"time",
"from",
"array",
"import",
"array",
"import",
"hmac",
"import",
"sha",
"import",
"os",
"import",
"base64",
"H",
"=",
"UcsUtils",
".",
"GetShaHash",
"uhash",
... | 29.071429 | 0.029727 |
def table_output(data):
'''Get a table representation of a dictionary.'''
if type(data) == DictType:
data = data.items()
headings = [ item[0] for item in data ]
rows = [ item[1] for item in data ]
columns = zip(*rows)
if len(columns):
widths = [ max([ len(str(y)) for y in row ]) ... | [
"def",
"table_output",
"(",
"data",
")",
":",
"if",
"type",
"(",
"data",
")",
"==",
"DictType",
":",
"data",
"=",
"data",
".",
"items",
"(",
")",
"headings",
"=",
"[",
"item",
"[",
"0",
"]",
"for",
"item",
"in",
"data",
"]",
"rows",
"=",
"[",
"... | 41.789474 | 0.025862 |
def addDelta(self, location, aMathObject, deltaName = None, punch=False, axisOnly=True):
""" Add a delta at this location.
* location: a Location object
* mathObject: a math-sensitive object
* deltaName: optional string/token
* punch:
* ... | [
"def",
"addDelta",
"(",
"self",
",",
"location",
",",
"aMathObject",
",",
"deltaName",
"=",
"None",
",",
"punch",
"=",
"False",
",",
"axisOnly",
"=",
"True",
")",
":",
"#location = self._bender(location)",
"if",
"punch",
":",
"r",
"=",
"self",
".",
"getIns... | 45.555556 | 0.008363 |
def qubit_adjacent_lifted_gate(i, matrix, n_qubits):
"""
Lifts input k-qubit gate on adjacent qubits starting from qubit i
to complete Hilbert space of dimension 2 ** num_qubits.
Ex: 1-qubit gate, lifts from qubit i
Ex: 2-qubit gate, lifts from qubits (i+1, i)
Ex: 3-qubit gate, lifts from qubit... | [
"def",
"qubit_adjacent_lifted_gate",
"(",
"i",
",",
"matrix",
",",
"n_qubits",
")",
":",
"n_rows",
",",
"n_cols",
"=",
"matrix",
".",
"shape",
"assert",
"n_rows",
"==",
"n_cols",
",",
"'Matrix must be square'",
"gate_size",
"=",
"np",
".",
"log2",
"(",
"n_ro... | 45.044444 | 0.001931 |
def fft_frequencies(sr=22050, n_fft=2048):
'''Alternative implementation of `np.fft.fftfreq`
Parameters
----------
sr : number > 0 [scalar]
Audio sampling rate
n_fft : int > 0 [scalar]
FFT window size
Returns
-------
freqs : np.ndarray [shape=(1 + n_fft/2,)]
F... | [
"def",
"fft_frequencies",
"(",
"sr",
"=",
"22050",
",",
"n_fft",
"=",
"2048",
")",
":",
"return",
"np",
".",
"linspace",
"(",
"0",
",",
"float",
"(",
"sr",
")",
"/",
"2",
",",
"int",
"(",
"1",
"+",
"n_fft",
"//",
"2",
")",
",",
"endpoint",
"=",... | 23.5 | 0.001362 |
def read_mutating_webhook_configuration(self, name, **kwargs): # noqa: E501
"""read_mutating_webhook_configuration # noqa: E501
read the specified MutatingWebhookConfiguration # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, ... | [
"def",
"read_mutating_webhook_configuration",
"(",
"self",
",",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async_req'",
")",
":",
"return",
"self",
... | 56.375 | 0.001453 |
def generate_sql_markdown(jvm, path):
"""
Generates a markdown file after listing the function information. The output file
is created in `path`.
Expected output:
### NAME
USAGE
**Arguments:**
ARGUMENTS
**Examples:**
```
EXAMPLES
```
**Note:**
NOTE
**... | [
"def",
"generate_sql_markdown",
"(",
"jvm",
",",
"path",
")",
":",
"with",
"open",
"(",
"path",
",",
"'w'",
")",
"as",
"mdfile",
":",
"for",
"info",
"in",
"_list_function_infos",
"(",
"jvm",
")",
":",
"name",
"=",
"info",
".",
"name",
"usage",
"=",
"... | 23.413793 | 0.001413 |
def visit(self, node, abort=abort_visit):
"""Visit a node."""
method = 'visit_' + node.__class__.__name__
visitor = getattr(self, method, abort)
return visitor(node) | [
"def",
"visit",
"(",
"self",
",",
"node",
",",
"abort",
"=",
"abort_visit",
")",
":",
"method",
"=",
"'visit_'",
"+",
"node",
".",
"__class__",
".",
"__name__",
"visitor",
"=",
"getattr",
"(",
"self",
",",
"method",
",",
"abort",
")",
"return",
"visito... | 38.6 | 0.010152 |
def v1_fc_put(request, response, visid_to_dbid, store, cid):
'''Store a single feature collection.
The route for this endpoint is:
``PUT /dossier/v1/feature-collections/<content_id>``.
``content_id`` is the id to associate with the given feature
collection. The feature collection should be in the ... | [
"def",
"v1_fc_put",
"(",
"request",
",",
"response",
",",
"visid_to_dbid",
",",
"store",
",",
"cid",
")",
":",
"fc",
"=",
"FeatureCollection",
".",
"from_dict",
"(",
"json",
".",
"load",
"(",
"request",
".",
"body",
")",
")",
"store",
".",
"put",
"(",
... | 36.647059 | 0.001565 |
def items_get(self, **kwargs):
'''taobao.increment.items.get 获取商品变更通知信息
开通主动通知业务的APP可以通过该接口获取商品变更通知信息 建议获取增量消息的时间间隔是:半个小时'''
request = TOPRequest('taobao.increment.items.get')
for k, v in kwargs.iteritems():
if k not in ('status', 'nick', 'start_modified', 'end_modif... | [
"def",
"items_get",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"request",
"=",
"TOPRequest",
"(",
"'taobao.increment.items.get'",
")",
"for",
"k",
",",
"v",
"in",
"kwargs",
".",
"iteritems",
"(",
")",
":",
"if",
"k",
"not",
"in",
"(",
"'status'",
... | 54.3 | 0.016304 |
def parse_type_reference(lexer: Lexer) -> TypeNode:
"""Type: NamedType or ListType or NonNullType"""
start = lexer.token
if expect_optional_token(lexer, TokenKind.BRACKET_L):
type_ = parse_type_reference(lexer)
expect_token(lexer, TokenKind.BRACKET_R)
type_ = ListTypeNode(type=type_,... | [
"def",
"parse_type_reference",
"(",
"lexer",
":",
"Lexer",
")",
"->",
"TypeNode",
":",
"start",
"=",
"lexer",
".",
"token",
"if",
"expect_optional_token",
"(",
"lexer",
",",
"TokenKind",
".",
"BRACKET_L",
")",
":",
"type_",
"=",
"parse_type_reference",
"(",
... | 43.166667 | 0.00189 |
def _new_stream(self, idx):
'''Randomly select and create a stream.
Parameters
----------
idx : int, [0:n_streams - 1]
The stream index to replace
'''
# instantiate
if self.rate is not None:
n_stream = 1 + self.rng.poisson(lam=self.rate)
... | [
"def",
"_new_stream",
"(",
"self",
",",
"idx",
")",
":",
"# instantiate",
"if",
"self",
".",
"rate",
"is",
"not",
"None",
":",
"n_stream",
"=",
"1",
"+",
"self",
".",
"rng",
".",
"poisson",
"(",
"lam",
"=",
"self",
".",
"rate",
")",
"else",
":",
... | 33.923077 | 0.002205 |
def load_entry_point_group(self, entry_point_group):
"""Load actions from an entry point group."""
for ep in pkg_resources.iter_entry_points(group=entry_point_group):
self.register(ep.name, ep.load()) | [
"def",
"load_entry_point_group",
"(",
"self",
",",
"entry_point_group",
")",
":",
"for",
"ep",
"in",
"pkg_resources",
".",
"iter_entry_points",
"(",
"group",
"=",
"entry_point_group",
")",
":",
"self",
".",
"register",
"(",
"ep",
".",
"name",
",",
"ep",
".",... | 56.25 | 0.008772 |
def parse(bin_payload, recipient, update_hash ):
"""
# NOTE: first three bytes were stripped
"""
fqn = bin_payload
if not is_name_valid( fqn ):
log.warning("Name '%s' is invalid" % fqn)
return None
return {
'opcode': 'NAME_IMPORT',
'name': fqn,
're... | [
"def",
"parse",
"(",
"bin_payload",
",",
"recipient",
",",
"update_hash",
")",
":",
"fqn",
"=",
"bin_payload",
"if",
"not",
"is_name_valid",
"(",
"fqn",
")",
":",
"log",
".",
"warning",
"(",
"\"Name '%s' is invalid\"",
"%",
"fqn",
")",
"return",
"None",
"r... | 22.8125 | 0.018421 |
def _makeHttpRequest(self, method, route, payload):
""" Make an HTTP Request for the API endpoint. This method wraps
the logic about doing failure retry and passes off the actual work
of doing an HTTP request to another method."""
url = self._constructUrl(route)
log.debug('Full... | [
"def",
"_makeHttpRequest",
"(",
"self",
",",
"method",
",",
"route",
",",
"payload",
")",
":",
"url",
"=",
"self",
".",
"_constructUrl",
"(",
"route",
")",
"log",
".",
"debug",
"(",
"'Full URL used is: %s'",
",",
"url",
")",
"hawkExt",
"=",
"self",
".",
... | 39.090909 | 0.000907 |
def _init_stub(self, stub_init, **stub_kwargs):
"""Initializes all other stubs for consistency's sake"""
getattr(self.testbed, stub_init, lambda **kwargs: None)(**stub_kwargs) | [
"def",
"_init_stub",
"(",
"self",
",",
"stub_init",
",",
"*",
"*",
"stub_kwargs",
")",
":",
"getattr",
"(",
"self",
".",
"testbed",
",",
"stub_init",
",",
"lambda",
"*",
"*",
"kwargs",
":",
"None",
")",
"(",
"*",
"*",
"stub_kwargs",
")"
] | 63 | 0.010471 |
def stmts_from_path(path, model, stmts):
"""Return source Statements corresponding to a path in a model.
Parameters
----------
path : list[tuple[str, int]]
A list of tuples where the first element of the tuple is the
name of a rule, and the second is the associated polarity along
... | [
"def",
"stmts_from_path",
"(",
"path",
",",
"model",
",",
"stmts",
")",
":",
"path_stmts",
"=",
"[",
"]",
"for",
"path_rule",
",",
"sign",
"in",
"path",
":",
"for",
"rule",
"in",
"model",
".",
"rules",
":",
"if",
"rule",
".",
"name",
"==",
"path_rule... | 35.407407 | 0.001018 |
def initialise(self):
"""
Initialise this data repository, creating any necessary directories
and file paths.
"""
self._checkWriteMode()
self._createSystemTable()
self._createNetworkTables()
self._createOntologyTable()
self._createReferenceSetTable... | [
"def",
"initialise",
"(",
"self",
")",
":",
"self",
".",
"_checkWriteMode",
"(",
")",
"self",
".",
"_createSystemTable",
"(",
")",
"self",
".",
"_createNetworkTables",
"(",
")",
"self",
".",
"_createOntologyTable",
"(",
")",
"self",
".",
"_createReferenceSetTa... | 35.782609 | 0.002367 |
def transform(self, sequences, mode='clip'):
"""Transform a list of sequences to internal indexing
Recall that `sequences` can be arbitrary labels, whereas ``transmat_``
and ``countsmat_`` are indexed with integers between 0 and
``n_states - 1``. This methods maps a set of sequences fro... | [
"def",
"transform",
"(",
"self",
",",
"sequences",
",",
"mode",
"=",
"'clip'",
")",
":",
"if",
"mode",
"not",
"in",
"[",
"'clip'",
",",
"'fill'",
"]",
":",
"raise",
"ValueError",
"(",
"'mode must be one of [\"clip\", \"fill\"]: %s'",
"%",
"mode",
")",
"seque... | 40.96 | 0.000954 |
def export_icon(self, icon, size, color='black', scale='auto',
filename=None, export_dir='exported'):
"""
Exports given icon with provided parameters.
If the desired icon size is less than 150x150 pixels, we will first
create a 150x150 pixels image and then scale it ... | [
"def",
"export_icon",
"(",
"self",
",",
"icon",
",",
"size",
",",
"color",
"=",
"'black'",
",",
"scale",
"=",
"'auto'",
",",
"filename",
"=",
"None",
",",
"export_dir",
"=",
"'exported'",
")",
":",
"org_size",
"=",
"size",
"size",
"=",
"max",
"(",
"1... | 35.908163 | 0.00083 |
def terminate(self):
"""Override of PantsService.terminate() that cleans up when the Pailgun server is terminated."""
# Tear down the Pailgun TCPServer.
if self.pailgun:
self.pailgun.server_close()
super(PailgunService, self).terminate() | [
"def",
"terminate",
"(",
"self",
")",
":",
"# Tear down the Pailgun TCPServer.",
"if",
"self",
".",
"pailgun",
":",
"self",
".",
"pailgun",
".",
"server_close",
"(",
")",
"super",
"(",
"PailgunService",
",",
"self",
")",
".",
"terminate",
"(",
")"
] | 36.285714 | 0.011538 |
def get(self, type: Type[T], query: Mapping[str, Any], context: PipelineContext = None) -> T:
"""Gets a query from the data source.
Args:
query: The query being requested.
context: The context for the extraction (mutable).
Returns:
The requested object.
... | [
"def",
"get",
"(",
"self",
",",
"type",
":",
"Type",
"[",
"T",
"]",
",",
"query",
":",
"Mapping",
"[",
"str",
",",
"Any",
"]",
",",
"context",
":",
"PipelineContext",
"=",
"None",
")",
"->",
"T",
":",
"pass"
] | 30 | 0.008824 |
def _pull_out_unaffected_blocks_lhs(lhs, rest, out_port, in_port):
"""In a self-Feedback of a series product, where the left-most operand is
reducible, pull all non-trivial blocks outside of the feedback.
Args:
lhs (Circuit): The reducible circuit
rest (tuple): The other SeriesProduct operands... | [
"def",
"_pull_out_unaffected_blocks_lhs",
"(",
"lhs",
",",
"rest",
",",
"out_port",
",",
"in_port",
")",
":",
"_",
",",
"block_index",
"=",
"lhs",
".",
"index_in_block",
"(",
"out_port",
")",
"bs",
"=",
"lhs",
".",
"block_structure",
"nbefore",
",",
"nblock"... | 38.057143 | 0.000732 |
def assign_from_ast(node, expr):
"""
Creates code to assign name (or tuple of names) node from expr
This is useful for recreating destructuring assignment behavior, like
a, *b = [1,2,3].
"""
if isinstance(expr, str):
expr = ast.Name(id=expr, ctx=ast.Load())
mod = ast.Module([ast.Ass... | [
"def",
"assign_from_ast",
"(",
"node",
",",
"expr",
")",
":",
"if",
"isinstance",
"(",
"expr",
",",
"str",
")",
":",
"expr",
"=",
"ast",
".",
"Name",
"(",
"id",
"=",
"expr",
",",
"ctx",
"=",
"ast",
".",
"Load",
"(",
")",
")",
"mod",
"=",
"ast",... | 36 | 0.002257 |
def createFinalTPEDandTFAM(tped, toReadPrefix, prefix, snpToRemove):
"""Creates the final TPED and TFAM.
:param tped: a representation of the ``tped`` of duplicated markers.
:param toReadPrefix: the prefix of the unique files.
:param prefix: the prefix of the output files.
:param snpToRemove: the m... | [
"def",
"createFinalTPEDandTFAM",
"(",
"tped",
",",
"toReadPrefix",
",",
"prefix",
",",
"snpToRemove",
")",
":",
"# First, copying the tfam",
"try",
":",
"shutil",
".",
"copy",
"(",
"toReadPrefix",
"+",
"\".tfam\"",
",",
"prefix",
"+",
"\".final.tfam\"",
")",
"ex... | 36.583333 | 0.000555 |
def mend(self, length):
"""Cut all branches from this node to its children and adopt
all nodes at certain level."""
if length == 0: raise Exception("Can't mend the root !")
if length == 1: return
self.children = OrderedDict((node.name, node) for node in self.get_level(length))
... | [
"def",
"mend",
"(",
"self",
",",
"length",
")",
":",
"if",
"length",
"==",
"0",
":",
"raise",
"Exception",
"(",
"\"Can't mend the root !\"",
")",
"if",
"length",
"==",
"1",
":",
"return",
"self",
".",
"children",
"=",
"OrderedDict",
"(",
"(",
"node",
"... | 53.714286 | 0.015707 |
def create_ui(self):
'''
.. versionchanged:: 0.21.2
Load the builder configuration file using :func:`pkgutil.getdata`,
which supports loading from `.zip` archives (e.g., in an app
packaged with Py2Exe).
'''
builder = gtk.Builder()
# Read glade ... | [
"def",
"create_ui",
"(",
"self",
")",
":",
"builder",
"=",
"gtk",
".",
"Builder",
"(",
")",
"# Read glade file using `pkgutil` to also support loading from `.zip`",
"# files (e.g., in app packaged with Py2Exe).",
"glade_str",
"=",
"pkgutil",
".",
"get_data",
"(",
"__name__"... | 45.025641 | 0.001115 |
def in_string(objet, pattern):
""" abstractSearch dans une chaine, sans tenir compte de la casse. """
return bool(re.search(pattern, str(objet), flags=re.I)) if objet else False | [
"def",
"in_string",
"(",
"objet",
",",
"pattern",
")",
":",
"return",
"bool",
"(",
"re",
".",
"search",
"(",
"pattern",
",",
"str",
"(",
"objet",
")",
",",
"flags",
"=",
"re",
".",
"I",
")",
")",
"if",
"objet",
"else",
"False"
] | 63.666667 | 0.015544 |
def conditional(self, condition, name):
"""Defines a 'condition' when conditional element of 'name' exists if `condition` is true.
`condition` can contain multiple conditions combined together using Logical Expressions(&&,||).
Example:
| Conditional | mycondition == 1 | foo |
|... | [
"def",
"conditional",
"(",
"self",
",",
"condition",
",",
"name",
")",
":",
"self",
".",
"_message_stack",
".",
"append",
"(",
"ConditionalTemplate",
"(",
"condition",
",",
"name",
",",
"self",
".",
"_current_container",
")",
")"
] | 39.733333 | 0.008197 |
def _check_next(self):
"""Checks if a next message is possible.
:returns: True if a next message is possible, otherwise False
:rtype: bool
"""
if self.is_initial:
return True
if self.before:
if self.before_cursor:
return True
else:
return False
else:
... | [
"def",
"_check_next",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_initial",
":",
"return",
"True",
"if",
"self",
".",
"before",
":",
"if",
"self",
".",
"before_cursor",
":",
"return",
"True",
"else",
":",
"return",
"False",
"else",
":",
"if",
"self",... | 19.842105 | 0.01519 |
def _find_secondary_anchors(self, residue, heavy_atom, anchor):
"""
Searches through the bond network for atoms bound to the anchor.
Returns a secondary and tertiary anchors.
Example, for CA, returns C and O.
"""
for secondary in self.bonds[residue][anchor.n... | [
"def",
"_find_secondary_anchors",
"(",
"self",
",",
"residue",
",",
"heavy_atom",
",",
"anchor",
")",
":",
"for",
"secondary",
"in",
"self",
".",
"bonds",
"[",
"residue",
"]",
"[",
"anchor",
".",
"name",
"]",
"[",
"1",
"]",
":",
"for",
"tertiary",
"in"... | 39.4 | 0.01157 |
def fetch_all_objects_from_db(self,
cls: Type[T],
table: str,
fieldlist: Sequence[str],
construct_with_pk: bool,
*args) -> List[T]:
"""Fetches... | [
"def",
"fetch_all_objects_from_db",
"(",
"self",
",",
"cls",
":",
"Type",
"[",
"T",
"]",
",",
"table",
":",
"str",
",",
"fieldlist",
":",
"Sequence",
"[",
"str",
"]",
",",
"construct_with_pk",
":",
"bool",
",",
"*",
"args",
")",
"->",
"List",
"[",
"T... | 51.2 | 0.013436 |
def add_idle(self, callback, *args, **kwds):
"""Add an idle callback.
An idle callback can return True, False or None. These mean:
- None: remove the callback (don't reschedule)
- False: the callback did no work; reschedule later
- True: the callback did some work; reschedule soon
If the cal... | [
"def",
"add_idle",
"(",
"self",
",",
"callback",
",",
"*",
"args",
",",
"*",
"*",
"kwds",
")",
":",
"self",
".",
"idlers",
".",
"append",
"(",
"(",
"callback",
",",
"args",
",",
"kwds",
")",
")"
] | 34.307692 | 0.002183 |
def query(database,
query,
time_precision='s',
chunked=False,
user=None,
password=None,
host=None,
port=None):
'''
Querying data
database
The database to query
query
Query to be executed
time_precision
T... | [
"def",
"query",
"(",
"database",
",",
"query",
",",
"time_precision",
"=",
"'s'",
",",
"chunked",
"=",
"False",
",",
"user",
"=",
"None",
",",
"password",
"=",
"None",
",",
"host",
"=",
"None",
",",
"port",
"=",
"None",
")",
":",
"client",
"=",
"_c... | 20.866667 | 0.002035 |
def assign(self, experiment):
"""Assign an experiment."""
self.experiments.append(experiment)
self.farms.append(empty_farm) | [
"def",
"assign",
"(",
"self",
",",
"experiment",
")",
":",
"self",
".",
"experiments",
".",
"append",
"(",
"experiment",
")",
"self",
".",
"farms",
".",
"append",
"(",
"empty_farm",
")"
] | 28.8 | 0.013514 |
def date_time_between(self, start_date='-30y', end_date='now', tzinfo=None):
"""
Get a DateTime object based on a random date between two given dates.
Accepts date strings that can be recognized by strtotime().
:param start_date Defaults to 30 years ago
:param end_date Defaults ... | [
"def",
"date_time_between",
"(",
"self",
",",
"start_date",
"=",
"'-30y'",
",",
"end_date",
"=",
"'now'",
",",
"tzinfo",
"=",
"None",
")",
":",
"start_date",
"=",
"self",
".",
"_parse_date_time",
"(",
"start_date",
",",
"tzinfo",
"=",
"tzinfo",
")",
"end_d... | 44.869565 | 0.001898 |
def has_option(self, option_name=None):
""" Check whether configuration selection has the specified option.
:param option_name: option name to check. If no option is specified, then check is made for this option
:return: bool
"""
if option_name is None:
option_name = ''
return self.config().has_option(... | [
"def",
"has_option",
"(",
"self",
",",
"option_name",
"=",
"None",
")",
":",
"if",
"option_name",
"is",
"None",
":",
"option_name",
"=",
"''",
"return",
"self",
".",
"config",
"(",
")",
".",
"has_option",
"(",
"self",
".",
"section",
"(",
")",
",",
"... | 36.2 | 0.02965 |
def render_file(context, path, absolute=False):
"""
Like :py:func:`read_file`, except that the file is rendered as a Jinja template
using the current context. If `absolute` is True, use absolute path, otherwise
path is assumed to be relative to Tarbell template root dir.
For example:
... | [
"def",
"render_file",
"(",
"context",
",",
"path",
",",
"absolute",
"=",
"False",
")",
":",
"site",
"=",
"g",
".",
"current_site",
"if",
"not",
"absolute",
":",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"site",
".",
"path",
",",
"path",
")"... | 30.263158 | 0.011804 |
def strahler_order(section):
'''Branching order of a tree section
The strahler order is the inverse of the branch order,
since this is computed from the tips of the tree
towards the root.
This implementation is a translation of the three steps described in
Wikipedia (https://en.wikipedia.org/w... | [
"def",
"strahler_order",
"(",
"section",
")",
":",
"if",
"section",
".",
"children",
":",
"child_orders",
"=",
"[",
"strahler_order",
"(",
"child",
")",
"for",
"child",
"in",
"section",
".",
"children",
"]",
"max_so_children",
"=",
"max",
"(",
"child_orders"... | 42.516129 | 0.002226 |
def execute(self, query, args=None):
"""Execute a query.
query -- string, query to execute on server
args -- optional sequence or mapping, parameters to use with query.
Note: If args is a sequence, then %s must be used as the
parameter placeholder in the query. If a mapping is ... | [
"def",
"execute",
"(",
"self",
",",
"query",
",",
"args",
"=",
"None",
")",
":",
"while",
"self",
".",
"nextset",
"(",
")",
":",
"pass",
"db",
"=",
"self",
".",
"_get_db",
"(",
")",
"if",
"isinstance",
"(",
"query",
",",
"unicode",
")",
":",
"que... | 32.594595 | 0.00161 |
def get_parts(self):
"""
Searches for all DictCells (with nested structure)
"""
return self.find_path(lambda x: isinstance(x[1], DictCell), on_targets=True) | [
"def",
"get_parts",
"(",
"self",
")",
":",
"return",
"self",
".",
"find_path",
"(",
"lambda",
"x",
":",
"isinstance",
"(",
"x",
"[",
"1",
"]",
",",
"DictCell",
")",
",",
"on_targets",
"=",
"True",
")"
] | 36.8 | 0.015957 |
def _default_auth_location(filename):
"""
Determine auth location for filename, like 'bugzillacookies'. If
old style ~/.bugzillacookies exists, we use that, otherwise we
use ~/.cache/python-bugzilla/bugzillacookies. Same for bugzillatoken
"""
homepath = os.path.expanduser("~/.%s" % filename)
... | [
"def",
"_default_auth_location",
"(",
"filename",
")",
":",
"homepath",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"\"~/.%s\"",
"%",
"filename",
")",
"xdgpath",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"\"~/.cache/python-bugzilla/%s\"",
"%",
"filen... | 38.375 | 0.00159 |
def close(self, wait=False):
"""Close session, shutdown pool."""
self.session.close()
self.pool.shutdown(wait=wait) | [
"def",
"close",
"(",
"self",
",",
"wait",
"=",
"False",
")",
":",
"self",
".",
"session",
".",
"close",
"(",
")",
"self",
".",
"pool",
".",
"shutdown",
"(",
"wait",
"=",
"wait",
")"
] | 34 | 0.014388 |
def variable_name(value,
allow_empty = False,
**kwargs):
"""Validate that the value is a valid Python variable name.
.. caution::
This function does **NOT** check whether the variable exists. It only
checks that the ``value`` would work as a Python variable (or ... | [
"def",
"variable_name",
"(",
"value",
",",
"allow_empty",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"value",
"and",
"not",
"allow_empty",
":",
"raise",
"errors",
".",
"EmptyValueError",
"(",
"'value (%s) was empty'",
"%",
"value",
")",
... | 33.236842 | 0.002308 |
def fromdicts(dicts, header=None, sample=1000, missing=None):
"""
View a sequence of Python :class:`dict` as a table. E.g.::
>>> import petl as etl
>>> dicts = [{"foo": "a", "bar": 1},
... {"foo": "b", "bar": 2},
... {"foo": "c", "bar": 2}]
>>> table1 =... | [
"def",
"fromdicts",
"(",
"dicts",
",",
"header",
"=",
"None",
",",
"sample",
"=",
"1000",
",",
"missing",
"=",
"None",
")",
":",
"return",
"DictsView",
"(",
"dicts",
",",
"header",
"=",
"header",
",",
"sample",
"=",
"sample",
",",
"missing",
"=",
"mi... | 34.564103 | 0.000722 |
def source_call(method_name, *args, **kwargs):
"""
Creates an effect that will drop the current effect value,
call the source's method with specified name
with the specified arguments and keywords.
@param method_name: the name of method belonging to the source reference.
@type method_name: str
... | [
"def",
"source_call",
"(",
"method_name",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"source_call",
"(",
"_value",
",",
"context",
",",
"*",
"*",
"_params",
")",
":",
"method",
"=",
"getattr",
"(",
"context",
"[",
"\"model\"",
"]",
"... | 35.214286 | 0.001976 |
def as_chord(chord):
""" convert from str to Chord instance if input is str
:type chord: str|pychord.Chord
:param chord: Chord name or Chord instance
:rtype: pychord.Chord
:return: Chord instance
"""
if isinstance(chord, Chord):
return chord
elif isinstance(chord, str):
... | [
"def",
"as_chord",
"(",
"chord",
")",
":",
"if",
"isinstance",
"(",
"chord",
",",
"Chord",
")",
":",
"return",
"chord",
"elif",
"isinstance",
"(",
"chord",
",",
"str",
")",
":",
"return",
"Chord",
"(",
"chord",
")",
"else",
":",
"raise",
"TypeError",
... | 29.071429 | 0.002381 |
def which(cmd, mode=os.F_OK | os.X_OK, path=None):
"""Given a command, mode, and a PATH string, return the path which
conforms to the given mode on the PATH, or None if there is no such
file.
`mode` defaults to os.F_OK | os.X_OK. `path` defaults to the result
of os.environ.get("PATH"), or can be ove... | [
"def",
"which",
"(",
"cmd",
",",
"mode",
"=",
"os",
".",
"F_OK",
"|",
"os",
".",
"X_OK",
",",
"path",
"=",
"None",
")",
":",
"# Check that a given file can be accessed with the correct mode.",
"# Additionally check that `file` is not a directory, as on Windows",
"# direct... | 35.785714 | 0.000648 |
def layout_json_outputs(self):
"""Return layout.json outputs in a flattened dict with name param as key."""
if self._layout_json_outputs is None:
self._layout_json_outputs = {}
for o in self.layout_json.get('outputs', []):
self._layout_json_outputs.setdefault(o.ge... | [
"def",
"layout_json_outputs",
"(",
"self",
")",
":",
"if",
"self",
".",
"_layout_json_outputs",
"is",
"None",
":",
"self",
".",
"_layout_json_outputs",
"=",
"{",
"}",
"for",
"o",
"in",
"self",
".",
"layout_json",
".",
"get",
"(",
"'outputs'",
",",
"[",
"... | 52.571429 | 0.008021 |
def read_namespaced_replication_controller_scale(self, name, namespace, **kwargs): # noqa: E501
"""read_namespaced_replication_controller_scale # noqa: E501
read scale of the specified ReplicationController # noqa: E501
This method makes a synchronous HTTP request by default. To make an
... | [
"def",
"read_namespaced_replication_controller_scale",
"(",
"self",
",",
"name",
",",
"namespace",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async_req'",
")"... | 54.913043 | 0.001556 |
def payzen_form(payment_request, auto_submit=False):
"""TODO docstring."""
if auto_submit:
template_used = "django_payzen/auto_submit_form.html"
else:
template_used = "django_payzen/form.html"
payment_request.update()
t = template.loader.get_template(template_used)
return t.rende... | [
"def",
"payzen_form",
"(",
"payment_request",
",",
"auto_submit",
"=",
"False",
")",
":",
"if",
"auto_submit",
":",
"template_used",
"=",
"\"django_payzen/auto_submit_form.html\"",
"else",
":",
"template_used",
"=",
"\"django_payzen/form.html\"",
"payment_request",
".",
... | 37.333333 | 0.002179 |
def adjust_text(texts, x=None, y=None, add_objects=None, ax=None,
expand_text=(1.05, 1.2), expand_points=(1.05, 1.2),
expand_objects=(1.05, 1.2), expand_align=(1.05, 1.2),
autoalign='xy', va='center', ha='center',
force_text=(0.1, 0.25), force_points=(0.2... | [
"def",
"adjust_text",
"(",
"texts",
",",
"x",
"=",
"None",
",",
"y",
"=",
"None",
",",
"add_objects",
"=",
"None",
",",
"ax",
"=",
"None",
",",
"expand_text",
"=",
"(",
"1.05",
",",
"1.2",
")",
",",
"expand_points",
"=",
"(",
"1.05",
",",
"1.2",
... | 42.531469 | 0.002008 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.