text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def bschoi(value, ndim, array, order):
"""
Do a binary search for a given value within an integer array,
accompanied by an order vector. Return the index of the
matching array entry, or -1 if the key value is not found.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/bschoi_c.html
:pa... | [
"def",
"bschoi",
"(",
"value",
",",
"ndim",
",",
"array",
",",
"order",
")",
":",
"value",
"=",
"ctypes",
".",
"c_int",
"(",
"value",
")",
"ndim",
"=",
"ctypes",
".",
"c_int",
"(",
"ndim",
")",
"array",
"=",
"stypes",
".",
"toIntVector",
"(",
"arra... | 32.958333 | 0.001229 |
def dvdot(s1, s2):
"""
Compute the derivative of the dot product of two double
precision position vectors.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dvdot_c.html
:param s1: First state vector in the dot product.
:type s1: 6-Element Array of floats
:param s2: Second state vect... | [
"def",
"dvdot",
"(",
"s1",
",",
"s2",
")",
":",
"assert",
"len",
"(",
"s1",
")",
"is",
"6",
"and",
"len",
"(",
"s2",
")",
"is",
"6",
"s1",
"=",
"stypes",
".",
"toDoubleVector",
"(",
"s1",
")",
"s2",
"=",
"stypes",
".",
"toDoubleVector",
"(",
"s... | 32.555556 | 0.001658 |
def FromPublicKey(cls, public_key):
"""An alternate constructor which generates a new client id."""
# Our CN will be the first 64 bits of the hash of the public key
# in MPI format - the length of the key in 4 bytes + the key
# prefixed with a 0. This weird format is an artifact from the way
# M2Cry... | [
"def",
"FromPublicKey",
"(",
"cls",
",",
"public_key",
")",
":",
"# Our CN will be the first 64 bits of the hash of the public key",
"# in MPI format - the length of the key in 4 bytes + the key",
"# prefixed with a 0. This weird format is an artifact from the way",
"# M2Crypto handled this, w... | 47.769231 | 0.00158 |
def _delete_subtree(self, nodes):
"""
Delete subtree private method.
No argument validation and usage of getter/setter private methods is
used for speed
"""
nodes = nodes if isinstance(nodes, list) else [nodes]
iobj = [
(self._db[node]["parent"], node... | [
"def",
"_delete_subtree",
"(",
"self",
",",
"nodes",
")",
":",
"nodes",
"=",
"nodes",
"if",
"isinstance",
"(",
"nodes",
",",
"list",
")",
"else",
"[",
"nodes",
"]",
"iobj",
"=",
"[",
"(",
"self",
".",
"_db",
"[",
"node",
"]",
"[",
"\"parent\"",
"]"... | 34.666667 | 0.002339 |
def finalize(self):
""" Called at clean up, when the editor is closed. Can be used to disconnect signals.
This is often called after the client (e.g. the inspector) is updated. If you want to
take action before the update, override prepareCommit instead.
Be sure to call the f... | [
"def",
"finalize",
"(",
"self",
")",
":",
"for",
"subEditor",
"in",
"self",
".",
"_subEditors",
":",
"self",
".",
"removeSubEditor",
"(",
"subEditor",
")",
"self",
".",
"cti",
".",
"model",
".",
"sigItemChanged",
".",
"disconnect",
"(",
"self",
".",
"mod... | 53.692308 | 0.008451 |
def send(self, content):
"""Sends a JavaScript command to PS
:param content: Script content
:type content: str
:yields: :class:`.Message`
"""
LOGGER.debug('Sending: %s', content)
all_bytes = struct.pack('>i', Connection.PROTOCOL_VERSION)
all_bytes += stru... | [
"def",
"send",
"(",
"self",
",",
"content",
")",
":",
"LOGGER",
".",
"debug",
"(",
"'Sending: %s'",
",",
"content",
")",
"all_bytes",
"=",
"struct",
".",
"pack",
"(",
"'>i'",
",",
"Connection",
".",
"PROTOCOL_VERSION",
")",
"all_bytes",
"+=",
"struct",
"... | 31.7 | 0.002041 |
def get_version():
"Returns a PEP 386-compliant version number from VERSION."
assert len(VERSION) == 5
assert VERSION[3] in ('alpha', 'beta', 'rc', 'final')
# Now build the two parts of the version number:
# main = X.Y[.Z]
# sub = .devN - for pre-alpha releases
# | {a|b|c}N - for alpha,... | [
"def",
"get_version",
"(",
")",
":",
"assert",
"len",
"(",
"VERSION",
")",
"==",
"5",
"assert",
"VERSION",
"[",
"3",
"]",
"in",
"(",
"'alpha'",
",",
"'beta'",
",",
"'rc'",
",",
"'final'",
")",
"# Now build the two parts of the version number:",
"# main = X.Y[.... | 31.473684 | 0.001623 |
def replace(obj, **changes):
"""Return a new object replacing specified fields with new values.
This is especially useful for frozen classes. Example usage:
@dataclass(frozen=True)
class C:
x: int
y: int
c = C(1, 2)
c1 = replace(c, x=3)
assert c1.x == 3 and ... | [
"def",
"replace",
"(",
"obj",
",",
"*",
"*",
"changes",
")",
":",
"# We're going to mutate 'changes', but that's okay because it's a",
"# new dict, even if called with 'replace(obj, **my_changes)'.",
"if",
"not",
"_is_dataclass_instance",
"(",
"obj",
")",
":",
"raise",
"TypeE... | 34.857143 | 0.000664 |
def cyclone(
adata,
marker_pairs,
gene_names,
sample_names,
iterations=1000,
min_iter=100,
min_pairs=50):
"""Assigns scores and predicted class to observations [Scialdone15]_ [Fechtner18]_.
Calculates scores for each observation and each phase and assigns... | [
"def",
"cyclone",
"(",
"adata",
",",
"marker_pairs",
",",
"gene_names",
",",
"sample_names",
",",
"iterations",
"=",
"1000",
",",
"min_iter",
"=",
"100",
",",
"min_pairs",
"=",
"50",
")",
":",
"try",
":",
"from",
"pypairs",
"import",
"__version__",
"as",
... | 34.662162 | 0.00834 |
def _onPrevBookmark(self):
"""Previous Bookmark action triggered. Move cursor
"""
for block in qutepart.iterateBlocksBackFrom(self._qpart.textCursor().block().previous()):
if self.isBlockMarked(block):
self._qpart.setTextCursor(QTextCursor(block))
retu... | [
"def",
"_onPrevBookmark",
"(",
"self",
")",
":",
"for",
"block",
"in",
"qutepart",
".",
"iterateBlocksBackFrom",
"(",
"self",
".",
"_qpart",
".",
"textCursor",
"(",
")",
".",
"block",
"(",
")",
".",
"previous",
"(",
")",
")",
":",
"if",
"self",
".",
... | 45.142857 | 0.009317 |
def _search_url(search_term:str, size:str='>400*300', format:str='jpg') -> str:
"Return a Google Images Search URL for a given search term."
return ('https://www.google.com/search?q=' + quote(search_term) +
'&espv=2&biw=1366&bih=667&site=webhp&source=lnms&tbm=isch' +
_url_params(size, fo... | [
"def",
"_search_url",
"(",
"search_term",
":",
"str",
",",
"size",
":",
"str",
"=",
"'>400*300'",
",",
"format",
":",
"str",
"=",
"'jpg'",
")",
"->",
"str",
":",
"return",
"(",
"'https://www.google.com/search?q='",
"+",
"quote",
"(",
"search_term",
")",
"+... | 74.2 | 0.024 |
def get_from_relations(self, query,aliases):
'''
Returns list of the names of all positive relations in the query
'''
return [aliases[rel.get_name()] for rel in query.get_relations() if not rel.is_negated()] | [
"def",
"get_from_relations",
"(",
"self",
",",
"query",
",",
"aliases",
")",
":",
"return",
"[",
"aliases",
"[",
"rel",
".",
"get_name",
"(",
")",
"]",
"for",
"rel",
"in",
"query",
".",
"get_relations",
"(",
")",
"if",
"not",
"rel",
".",
"is_negated",
... | 47 | 0.016736 |
def best_item_from_list(item,options,fuzzy=90,fname_match=True,fuzzy_fragment=None,guess=False):
'''Returns just the best item, or ``None``'''
match = best_match_from_list(item,options,fuzzy,fname_match,fuzzy_fragment,guess)
if match:
return match[0]
return None | [
"def",
"best_item_from_list",
"(",
"item",
",",
"options",
",",
"fuzzy",
"=",
"90",
",",
"fname_match",
"=",
"True",
",",
"fuzzy_fragment",
"=",
"None",
",",
"guess",
"=",
"False",
")",
":",
"match",
"=",
"best_match_from_list",
"(",
"item",
",",
"options"... | 46.833333 | 0.045455 |
def getModelData(self,name):
"""
Gets the model data associated with the given name.
If it was loaded, a cached copy will be returned.
It it was not loaded, it will be loaded and cached.
"""
if name in self.modelcache:
return self.modelcache[name]
... | [
"def",
"getModelData",
"(",
"self",
",",
"name",
")",
":",
"if",
"name",
"in",
"self",
".",
"modelcache",
":",
"return",
"self",
".",
"modelcache",
"[",
"name",
"]",
"return",
"self",
".",
"loadModelData",
"(",
"name",
")"
] | 34.7 | 0.011236 |
def add(self, pattern, method=None, call=None, name=None):
"""Add a url pattern.
Args:
pattern (:obj:`str`): URL pattern to add. This is usually '/'
separated path. Parts of the URL can be parameterised using
curly braces.
Examples: "/", "/pat... | [
"def",
"add",
"(",
"self",
",",
"pattern",
",",
"method",
"=",
"None",
",",
"call",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"if",
"not",
"pattern",
".",
"endswith",
"(",
"'/'",
")",
":",
"pattern",
"+=",
"'/'",
"parts",
"=",
"tuple",
"("... | 39.666667 | 0.001367 |
def default_table(self, layout, table_content, cols_width):
"""format a table"""
cols_width = [size + 1 for size in cols_width]
format_strings = " ".join(["%%-%ss"] * len(cols_width))
format_strings = format_strings % tuple(cols_width)
format_strings = format_strings.split(" ")
... | [
"def",
"default_table",
"(",
"self",
",",
"layout",
",",
"table_content",
",",
"cols_width",
")",
":",
"cols_width",
"=",
"[",
"size",
"+",
"1",
"for",
"size",
"in",
"cols_width",
"]",
"format_strings",
"=",
"\" \"",
".",
"join",
"(",
"[",
"\"%%-%ss\"",
... | 47.368421 | 0.002179 |
def find_goodness_of_fit_csv(observed_simulated_file, out_file=None):
"""
Finds the goodness of fit comparing observed and simulated flows
In the file, the first column is the observed flows and the
second column is the simulated flows.
Example::
33.5, 77.2
34.7, 73.0
Paramete... | [
"def",
"find_goodness_of_fit_csv",
"(",
"observed_simulated_file",
",",
"out_file",
"=",
"None",
")",
":",
"observed_simulated_table",
"=",
"np",
".",
"loadtxt",
"(",
"observed_simulated_file",
",",
"ndmin",
"=",
"2",
",",
"delimiter",
"=",
"\",\"",
",",
"usecols"... | 34.426471 | 0.000415 |
def remapScipy(im, coords):
"""
Remap an image using SciPy. See :func:`remap` for parameters.
"""
height, width = im.shape[0], im.shape[1]
# switch to y,x order
coords = coords[:,:,::-1]
# make it (h, w, 3, 3)
coords_channels = np.empty((height, width, 3, 3))
coords_channel = n... | [
"def",
"remapScipy",
"(",
"im",
",",
"coords",
")",
":",
"height",
",",
"width",
"=",
"im",
".",
"shape",
"[",
"0",
"]",
",",
"im",
".",
"shape",
"[",
"1",
"]",
"# switch to y,x order",
"coords",
"=",
"coords",
"[",
":",
",",
":",
",",
":",
":",
... | 29.333333 | 0.02751 |
def clustered_sortind(x, k=10, scorefunc=None):
"""
Uses MiniBatch k-means clustering to cluster matrix into groups.
Each cluster of rows is then sorted by `scorefunc` -- by default, the max
peak height when all rows in a cluster are averaged, or
cluster.mean(axis=0).max().
Returns the index t... | [
"def",
"clustered_sortind",
"(",
"x",
",",
"k",
"=",
"10",
",",
"scorefunc",
"=",
"None",
")",
":",
"try",
":",
"from",
"sklearn",
".",
"cluster",
"import",
"MiniBatchKMeans",
"except",
"ImportError",
":",
"raise",
"ImportError",
"(",
"'please install scikits.... | 32.825397 | 0.000469 |
def scaled_dimensions(self, width=None, height=None):
"""
Return a (cx, cy) 2-tuple representing the native dimensions of this
image scaled by applying the following rules to *width* and *height*.
If both *width* and *height* are specified, the return value is
(*width*, *height*)... | [
"def",
"scaled_dimensions",
"(",
"self",
",",
"width",
"=",
"None",
",",
"height",
"=",
"None",
")",
":",
"if",
"width",
"is",
"None",
"and",
"height",
"is",
"None",
":",
"return",
"self",
".",
"width",
",",
"self",
".",
"height",
"if",
"width",
"is"... | 48.346154 | 0.00156 |
def get_events(self):
"""Get event list from satellite
:return: A copy of the events list
:rtype: list
"""
res = copy.copy(self.events)
del self.events[:]
return res | [
"def",
"get_events",
"(",
"self",
")",
":",
"res",
"=",
"copy",
".",
"copy",
"(",
"self",
".",
"events",
")",
"del",
"self",
".",
"events",
"[",
":",
"]",
"return",
"res"
] | 23.777778 | 0.009009 |
def _bounds_from_array(arr, dim_name, bounds_name):
"""Get the bounds of an array given its center values.
E.g. if lat-lon grid center lat/lon values are known, but not the
bounds of each grid box. The algorithm assumes that the bounds
are simply halfway between each pair of center values.
"""
... | [
"def",
"_bounds_from_array",
"(",
"arr",
",",
"dim_name",
",",
"bounds_name",
")",
":",
"# TODO: don't assume needed dimension is in axis=0",
"# TODO: refactor to get rid of repetitive code",
"spacing",
"=",
"arr",
".",
"diff",
"(",
"dim_name",
")",
".",
"values",
"lower"... | 47.2 | 0.001038 |
def _query(queue_name=None, build_id=None, release_id=None, run_id=None,
count=None):
"""Queries for work items based on their criteria.
Args:
queue_name: Optional queue name to restrict to.
build_id: Optional build ID to restrict to.
release_id: Optional release ID to restri... | [
"def",
"_query",
"(",
"queue_name",
"=",
"None",
",",
"build_id",
"=",
"None",
",",
"release_id",
"=",
"None",
",",
"run_id",
"=",
"None",
",",
"count",
"=",
"None",
")",
":",
"assert",
"queue_name",
"or",
"build_id",
"or",
"release_id",
"or",
"run_id",
... | 29.393939 | 0.000998 |
def get_bounds(self, R):
"""Calculate lower and upper bounds for centers and widths
Parameters
----------
R : 2D array, with shape [n_voxel, n_dim]
The coordinate matrix of fMRI data from one subject
Returns
-------
bounds : 2-tuple of array_like,... | [
"def",
"get_bounds",
"(",
"self",
",",
"R",
")",
":",
"max_sigma",
"=",
"self",
".",
"_get_max_sigma",
"(",
"R",
")",
"final_lower",
"=",
"np",
".",
"zeros",
"(",
"self",
".",
"K",
"*",
"(",
"self",
".",
"n_dim",
"+",
"1",
")",
")",
"final_lower",
... | 32.774194 | 0.001912 |
def postprocess(x, n_bits_x=8):
"""Converts x from [-0.5, 0.5], to [0, 255].
Args:
x: 3-D or 4-D Tensor normalized between [-0.5, 0.5]
n_bits_x: Number of bits representing each pixel of the output.
Defaults to 8, to default to 256 possible values.
Returns:
x: 3-D or 4-D Tensor represen... | [
"def",
"postprocess",
"(",
"x",
",",
"n_bits_x",
"=",
"8",
")",
":",
"x",
"=",
"tf",
".",
"where",
"(",
"tf",
".",
"is_finite",
"(",
"x",
")",
",",
"x",
",",
"tf",
".",
"ones_like",
"(",
"x",
")",
")",
"x",
"=",
"tf",
".",
"clip_by_value",
"(... | 34.533333 | 0.013158 |
def fetch_cluster_se(data, samfile, chrom, rstart, rend):
"""
Builds a single end cluster from the refmapped data.
"""
## If SE then we enforce the minimum overlap distance to avoid the
## staircase syndrome of multiple reads overlapping just a little.
overlap_buffer = data._hackersonly["min_SE... | [
"def",
"fetch_cluster_se",
"(",
"data",
",",
"samfile",
",",
"chrom",
",",
"rstart",
",",
"rend",
")",
":",
"## If SE then we enforce the minimum overlap distance to avoid the",
"## staircase syndrome of multiple reads overlapping just a little.",
"overlap_buffer",
"=",
"data",
... | 35.979798 | 0.009016 |
def set_properties(obj, values):
"""
Recursively sets values of some (all) object and its subobjects properties.
The object can be a user defined object, map or array.
Property values correspondently are object properties, map key-pairs or array elements with their indexes.
If ... | [
"def",
"set_properties",
"(",
"obj",
",",
"values",
")",
":",
"if",
"values",
"==",
"None",
"or",
"len",
"(",
"values",
")",
"==",
"0",
":",
"return",
"for",
"(",
"key",
",",
"value",
")",
"in",
"values",
".",
"items",
"(",
")",
":",
"RecursiveObje... | 40.666667 | 0.009346 |
def discover(app, module_name=None):
"""
Automatically apply the permission logics written in the specified
module.
Examples
--------
Assume if you have a ``perms.py`` in ``your_app`` as::
from permission.logics import AuthorPermissionLogic
PERMISSION_LOGICS = (
('y... | [
"def",
"discover",
"(",
"app",
",",
"module_name",
"=",
"None",
")",
":",
"from",
"permission",
".",
"compat",
"import",
"import_module",
"from",
"permission",
".",
"compat",
"import",
"get_model",
"from",
"permission",
".",
"conf",
"import",
"settings",
"from... | 35.487179 | 0.000703 |
def namedb_delete_prepare( cur, primary_key, primary_key_value, table_name ):
"""
Prepare to delete a record, but make sure the fields in record
correspond to actual columns.
Return a DELETE FROM ... WHERE statement on success.
Raise an Exception if not.
DO NOT CALL THIS METHOD DIRETLY
... | [
"def",
"namedb_delete_prepare",
"(",
"cur",
",",
"primary_key",
",",
"primary_key_value",
",",
"table_name",
")",
":",
"# primary key corresponds to a real column ",
"namedb_assert_fields_match",
"(",
"cur",
",",
"{",
"primary_key",
":",
"primary_key_value",
"}",
",",
"... | 37.625 | 0.012966 |
def fmt_datetime(d, fmt='', local=True):
"""
format date with local support
``d``: datetime to format
``fmt``: format, default is '%Y-%m-%d %H-%M'
``local``: format as local time
"""
if not d:
return ''
if local:
from django.templatetags.tz import localtime
d = lo... | [
"def",
"fmt_datetime",
"(",
"d",
",",
"fmt",
"=",
"''",
",",
"local",
"=",
"True",
")",
":",
"if",
"not",
"d",
":",
"return",
"''",
"if",
"local",
":",
"from",
"django",
".",
"templatetags",
".",
"tz",
"import",
"localtime",
"d",
"=",
"localtime",
... | 26 | 0.002475 |
def plot_world_with_plotly(world, species_list=None, max_count=1000):
"""
Plot a World on IPython Notebook
"""
if isinstance(world, str):
from .simulation import load_world
world = load_world(world)
if species_list is None:
species_list = [sp.serial() for sp in world.list_sp... | [
"def",
"plot_world_with_plotly",
"(",
"world",
",",
"species_list",
"=",
"None",
",",
"max_count",
"=",
"1000",
")",
":",
"if",
"isinstance",
"(",
"world",
",",
"str",
")",
":",
"from",
".",
"simulation",
"import",
"load_world",
"world",
"=",
"load_world",
... | 29.446809 | 0.000699 |
def get_open_func(fn, return_fmt=False):
"""Get the opening function.
Args:
fn (str): the name of the file.
return_fmt (bool): if the file format needs to be returned.
Returns:
tuple: either a tuple containing two elements: a boolean telling if the
format is bgzip, and the ... | [
"def",
"get_open_func",
"(",
"fn",
",",
"return_fmt",
"=",
"False",
")",
":",
"# The file might be compressed using bgzip",
"bgzip",
"=",
"None",
"with",
"open",
"(",
"fn",
",",
"\"rb\"",
")",
"as",
"i_file",
":",
"bgzip",
"=",
"i_file",
".",
"read",
"(",
... | 25.358974 | 0.000974 |
def create_asymmetric_key_pair(self, algorithm, length):
"""
Create an asymmetric key pair.
Args:
algorithm(CryptographicAlgorithm): An enumeration specifying the
algorithm for which the created keys will be compliant.
length(int): The length of the keys ... | [
"def",
"create_asymmetric_key_pair",
"(",
"self",
",",
"algorithm",
",",
"length",
")",
":",
"if",
"algorithm",
"not",
"in",
"self",
".",
"_asymmetric_key_algorithms",
".",
"keys",
"(",
")",
":",
"raise",
"exceptions",
".",
"InvalidField",
"(",
"\"The cryptograp... | 42.540541 | 0.001242 |
def split_writable_text(encoder, text, encoding):
"""Splits off as many characters from the begnning of text as
are writable with "encoding". Returns a 2-tuple (writable, rest).
"""
if not encoding:
return None, text
for idx, char in enumerate(text):
if encoder.can_encode(encoding, ... | [
"def",
"split_writable_text",
"(",
"encoder",
",",
"text",
",",
"encoding",
")",
":",
"if",
"not",
"encoding",
":",
"return",
"None",
",",
"text",
"for",
"idx",
",",
"char",
"in",
"enumerate",
"(",
"text",
")",
":",
"if",
"encoder",
".",
"can_encode",
... | 30.461538 | 0.002451 |
def create_data_file_attachment(self, identifier, resource_id, filename, mime_type=None):
"""Attach a given data file with a model run. The attached file is
identified by the resource identifier. If a resource with the given
identifier already exists it will be overwritten.
This operati... | [
"def",
"create_data_file_attachment",
"(",
"self",
",",
"identifier",
",",
"resource_id",
",",
"filename",
",",
"mime_type",
"=",
"None",
")",
":",
"# Get model run to ensure that it exists",
"model_run",
"=",
"self",
".",
"get_object",
"(",
"identifier",
")",
"if",... | 43.945946 | 0.001203 |
def parse_method_configs(interface_config):
"""Creates default retry and timeout objects for each method in a gapic
interface config.
Args:
interface_config (Mapping): The interface config section of the full
gapic library config. For example, If the full configuration has
a... | [
"def",
"parse_method_configs",
"(",
"interface_config",
")",
":",
"# Grab all the retry codes",
"retry_codes_map",
"=",
"{",
"name",
":",
"retry_codes",
"for",
"name",
",",
"retry_codes",
"in",
"six",
".",
"iteritems",
"(",
"interface_config",
".",
"get",
"(",
"\"... | 35.272727 | 0.002006 |
def _get_gecos(name):
'''
Retrieve GECOS field info and return it in dictionary form
'''
gecos_field = pwd.getpwnam(name).pw_gecos.split(',', 3)
if not gecos_field:
return {}
else:
# Assign empty strings for any unspecified trailing GECOS fields
while len(gecos_field) < 4... | [
"def",
"_get_gecos",
"(",
"name",
")",
":",
"gecos_field",
"=",
"pwd",
".",
"getpwnam",
"(",
"name",
")",
".",
"pw_gecos",
".",
"split",
"(",
"','",
",",
"3",
")",
"if",
"not",
"gecos_field",
":",
"return",
"{",
"}",
"else",
":",
"# Assign empty string... | 38.8 | 0.001678 |
def _determine_outliers_index(hist: Hist,
moving_average_threshold: float = 1.0,
number_of_values_to_search_ahead: int = 5,
limit_of_number_of_values_below_threshold: int = None) -> int:
""" Determine the location of where out... | [
"def",
"_determine_outliers_index",
"(",
"hist",
":",
"Hist",
",",
"moving_average_threshold",
":",
"float",
"=",
"1.0",
",",
"number_of_values_to_search_ahead",
":",
"int",
"=",
"5",
",",
"limit_of_number_of_values_below_threshold",
":",
"int",
"=",
"None",
")",
"-... | 49.728571 | 0.009014 |
def ecef2geodetic(x: float, y: float, z: float,
ell: Ellipsoid = None, deg: bool = True) -> Tuple[float, float, float]:
"""
convert ECEF (meters) to geodetic coordinates
Parameters
----------
x : float or numpy.ndarray of float
target x ECEF coordinate (meters)
y : flo... | [
"def",
"ecef2geodetic",
"(",
"x",
":",
"float",
",",
"y",
":",
"float",
",",
"z",
":",
"float",
",",
"ell",
":",
"Ellipsoid",
"=",
"None",
",",
"deg",
":",
"bool",
"=",
"True",
")",
"->",
"Tuple",
"[",
"float",
",",
"float",
",",
"float",
"]",
... | 26.468354 | 0.002305 |
def _write_move_counts(self, sess, h):
"""Add move counts from the given histogram to the table.
Used to update the move counts in an existing table. Should
not be needed except for backfill or repair.
Args:
sess: TF session to use for doing a Bigtable write.
tf_t... | [
"def",
"_write_move_counts",
"(",
"self",
",",
"sess",
",",
"h",
")",
":",
"def",
"gen",
"(",
")",
":",
"for",
"k",
",",
"v",
"in",
"h",
".",
"items",
"(",
")",
":",
"# The keys in the histogram may be of type 'bytes'",
"k",
"=",
"str",
"(",
"k",
",",
... | 42.833333 | 0.001903 |
def update_sg(self, context, sg, rule_id, action):
"""Begins the async update process."""
db_sg = db_api.security_group_find(context, id=sg, scope=db_api.ONE)
if not db_sg:
return None
with context.session.begin():
job_body = dict(action="%s sg rule %s" % (action,... | [
"def",
"update_sg",
"(",
"self",
",",
"context",
",",
"sg",
",",
"rule_id",
",",
"action",
")",
":",
"db_sg",
"=",
"db_api",
".",
"security_group_find",
"(",
"context",
",",
"id",
"=",
"sg",
",",
"scope",
"=",
"db_api",
".",
"ONE",
")",
"if",
"not",
... | 47.222222 | 0.002307 |
def get_raw(self):
"""
Get the reconstructed code as bytearray
:rtype: bytearray
"""
code_raw = self.code.get_raw()
self.insns_size = (len(code_raw) // 2) + (len(code_raw) % 2)
buff = bytearray()
buff += pack("<H", self.registers_size) + \
... | [
"def",
"get_raw",
"(",
"self",
")",
":",
"code_raw",
"=",
"self",
".",
"code",
".",
"get_raw",
"(",
")",
"self",
".",
"insns_size",
"=",
"(",
"len",
"(",
"code_raw",
")",
"//",
"2",
")",
"+",
"(",
"len",
"(",
"code_raw",
")",
"%",
"2",
")",
"bu... | 29.814815 | 0.009627 |
def _get_collection(self, collection_uri, request_headers=None):
"""Generator function that returns collection members."""
# get the collection
status, headers, thecollection = self._rest_get(collection_uri)
if status != 200:
msg = self._get_extended_error(thecollection)
... | [
"def",
"_get_collection",
"(",
"self",
",",
"collection_uri",
",",
"request_headers",
"=",
"None",
")",
":",
"# get the collection",
"status",
",",
"headers",
",",
"thecollection",
"=",
"self",
".",
"_rest_get",
"(",
"collection_uri",
")",
"if",
"status",
"!=",
... | 47.465517 | 0.000712 |
def cli(env, identifier, enabled, port, weight, healthcheck_type, ip_address):
"""Edit the properties of a service group."""
mgr = SoftLayer.LoadBalancerManager(env.client)
loadbal_id, service_id = loadbal.parse_id(identifier)
# check if any input is provided
if ((not any([ip_address, weight, por... | [
"def",
"cli",
"(",
"env",
",",
"identifier",
",",
"enabled",
",",
"port",
",",
"weight",
",",
"healthcheck_type",
",",
"ip_address",
")",
":",
"mgr",
"=",
"SoftLayer",
".",
"LoadBalancerManager",
"(",
"env",
".",
"client",
")",
"loadbal_id",
",",
"service_... | 36.607143 | 0.000951 |
def next(self, Class=True, scope=True, reverse=False):
"""Returns the next element, if it is of the specified type and if it does not cross the boundary of the defined scope. Returns None if no next element is found. Non-authoritative elements are never returned.
Arguments:
* ``Class``: The... | [
"def",
"next",
"(",
"self",
",",
"Class",
"=",
"True",
",",
"scope",
"=",
"True",
",",
"reverse",
"=",
"False",
")",
":",
"if",
"Class",
"is",
"True",
":",
"Class",
"=",
"self",
".",
"__class__",
"if",
"scope",
"is",
"True",
":",
"scope",
"=",
"S... | 56.551724 | 0.012886 |
def get_html(self,
url,
params=None,
cache_cb=None,
decoder_encoding=None,
decoder_errors=url_specified_decoder.ErrorsHandle.strict,
**kwargs):
"""
Get html of an url.
"""
response = sel... | [
"def",
"get_html",
"(",
"self",
",",
"url",
",",
"params",
"=",
"None",
",",
"cache_cb",
"=",
"None",
",",
"decoder_encoding",
"=",
"None",
",",
"decoder_errors",
"=",
"url_specified_decoder",
".",
"ErrorsHandle",
".",
"strict",
",",
"*",
"*",
"kwargs",
")... | 27.772727 | 0.012658 |
def write(self, output_buffer, kmip_version=enums.KMIPVersion.KMIP_1_0):
"""
Write the data encoding the Create response payload to a buffer.
Args:
output_buffer (stream): A data buffer in which to encode object
data, supporting a write method.
kmip_versi... | [
"def",
"write",
"(",
"self",
",",
"output_buffer",
",",
"kmip_version",
"=",
"enums",
".",
"KMIPVersion",
".",
"KMIP_1_0",
")",
":",
"local_buffer",
"=",
"utils",
".",
"BytearrayStream",
"(",
")",
"if",
"self",
".",
"_object_type",
":",
"self",
".",
"_obje... | 35.145833 | 0.001153 |
def init_c_overturn(step):
"""Initial concentration.
This compute the resulting composition profile if fractional
crystallization of a SMO is assumed.
Args:
step (:class:`~stagpy.stagyydata._Step`): a step of a StagyyData
instance.
Returns:
tuple of :class:`numpy.array`... | [
"def",
"init_c_overturn",
"(",
"step",
")",
":",
"rbot",
",",
"rtop",
"=",
"misc",
".",
"get_rbounds",
"(",
"step",
")",
"xieut",
"=",
"step",
".",
"sdat",
".",
"par",
"[",
"'tracersin'",
"]",
"[",
"'fe_eut'",
"]",
"k_fe",
"=",
"step",
".",
"sdat",
... | 32 | 0.000948 |
def download_url_to_path(self, url, path, force=False):
"""
Download a file from url via http, and put it at path
Parameters
----------
url : str
URL of file to download
path : str
local path to put file in
"""
path_exists = isf... | [
"def",
"download_url_to_path",
"(",
"self",
",",
"url",
",",
"path",
",",
"force",
"=",
"False",
")",
":",
"path_exists",
"=",
"isfile",
"(",
"path",
")",
"if",
"not",
"path_exists",
"or",
"force",
":",
"dir",
"=",
"dirname",
"(",
"path",
")",
"if",
... | 31.931034 | 0.002095 |
def bytes_from_readable_size(C, size, suffix='B'):
"""given a readable_size (as produced by File.readable_size()), return the number of bytes."""
s = re.split("^([0-9\.]+)\s*([%s]?)%s?" % (''.join(C.SIZE_UNITS), suffix), size, flags=re.I)
bytes, unit = round(float(s[1])), s[2].upper()
wh... | [
"def",
"bytes_from_readable_size",
"(",
"C",
",",
"size",
",",
"suffix",
"=",
"'B'",
")",
":",
"s",
"=",
"re",
".",
"split",
"(",
"\"^([0-9\\.]+)\\s*([%s]?)%s?\"",
"%",
"(",
"''",
".",
"join",
"(",
"C",
".",
"SIZE_UNITS",
")",
",",
"suffix",
")",
",",
... | 60 | 0.01232 |
def delete(self):
" Delete the address."
response = self.dyn.delete(self.delete_url)
return response.content['job_id'] | [
"def",
"delete",
"(",
"self",
")",
":",
"response",
"=",
"self",
".",
"dyn",
".",
"delete",
"(",
"self",
".",
"delete_url",
")",
"return",
"response",
".",
"content",
"[",
"'job_id'",
"]"
] | 34.75 | 0.014085 |
def multiifo_noise_coinc_rate(rates, slop):
"""
Calculate the expected rate of noise coincidences for multiple detectors
Parameters
----------
rates: dict
Dictionary keyed on ifo string
Value is a sequence of single-detector trigger rates, units assumed
to be Hz
slop: fl... | [
"def",
"multiifo_noise_coinc_rate",
"(",
"rates",
",",
"slop",
")",
":",
"ifos",
"=",
"numpy",
".",
"array",
"(",
"sorted",
"(",
"rates",
".",
"keys",
"(",
")",
")",
")",
"rates_raw",
"=",
"list",
"(",
"rates",
"[",
"ifo",
"]",
"for",
"ifo",
"in",
... | 37.804348 | 0.000561 |
def load(self):
"""
Load the stream definition from the database
:return: None
"""
with switch_db(StreamDefinitionModel, 'hyperstream'):
self.mongo_model = StreamDefinitionModel.objects.get(__raw__=self.stream_id.as_raw())
self._calculated_intervals = sel... | [
"def",
"load",
"(",
"self",
")",
":",
"with",
"switch_db",
"(",
"StreamDefinitionModel",
",",
"'hyperstream'",
")",
":",
"self",
".",
"mongo_model",
"=",
"StreamDefinitionModel",
".",
"objects",
".",
"get",
"(",
"__raw__",
"=",
"self",
".",
"stream_id",
".",... | 39.111111 | 0.011111 |
def export_chat_invite_link(self, *args, **kwargs):
"""See :func:`export_chat_invite_link`"""
return export_chat_invite_link(*args, **self._merge_overrides(**kwargs)).run() | [
"def",
"export_chat_invite_link",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"export_chat_invite_link",
"(",
"*",
"args",
",",
"*",
"*",
"self",
".",
"_merge_overrides",
"(",
"*",
"*",
"kwargs",
")",
")",
".",
"run",
"(... | 62 | 0.015957 |
def map(self, fn, *iterables, **kwargs):
"""Returns an iterator equivalent to map(fn, iter).
Args:
fn: A callable that will take as many arguments as there are
passed iterables.
timeout: The maximum number of seconds to wait. If None, then there
i... | [
"def",
"map",
"(",
"self",
",",
"fn",
",",
"*",
"iterables",
",",
"*",
"*",
"kwargs",
")",
":",
"timeout",
"=",
"kwargs",
".",
"get",
"(",
"'timeout'",
",",
"None",
")",
"chunksize",
"=",
"kwargs",
".",
"get",
"(",
"'chunksize'",
",",
"1",
")",
"... | 42.16129 | 0.001496 |
def get_words(data):
"""
Extracts the words from given string.
Usage::
>>> get_words("Users are: John Doe, Jane Doe, Z6PO.")
[u'Users', u'are', u'John', u'Doe', u'Jane', u'Doe', u'Z6PO']
:param data: Data to extract words from.
:type data: unicode
:return: Words.
:rtype: l... | [
"def",
"get_words",
"(",
"data",
")",
":",
"words",
"=",
"re",
".",
"findall",
"(",
"r\"\\w+\"",
",",
"data",
")",
"LOGGER",
".",
"debug",
"(",
"\"> Words: '{0}'\"",
".",
"format",
"(",
"\", \"",
".",
"join",
"(",
"words",
")",
")",
")",
"return",
"w... | 23.833333 | 0.002242 |
def invert(image):
"""Return an inverted image of the same dtype.
Assumes the full range of the input dtype is in use and
that no negative values are present in the input image.
:param image: :class:`jicbioimage.core.image.Image`
:returns: inverted image of the same dtype as the input
"""
... | [
"def",
"invert",
"(",
"image",
")",
":",
"if",
"image",
".",
"dtype",
"==",
"bool",
":",
"return",
"np",
".",
"logical_not",
"(",
"image",
")",
"maximum",
"=",
"np",
".",
"iinfo",
"(",
"image",
".",
"dtype",
")",
".",
"max",
"maximum_array",
"=",
"... | 36.428571 | 0.001912 |
def parser(description=None, usage=None):
"""Parse out command line arguments"""
class ArgNamespace(object):
def __init__(self, result):
self._result = result
def __getattr__(self, name):
try:
super(ArgNamespace, self).__getattr__(name)
excep... | [
"def",
"parser",
"(",
"description",
"=",
"None",
",",
"usage",
"=",
"None",
")",
":",
"class",
"ArgNamespace",
"(",
"object",
")",
":",
"def",
"__init__",
"(",
"self",
",",
"result",
")",
":",
"self",
".",
"_result",
"=",
"result",
"def",
"__getattr__... | 31.857143 | 0.000544 |
def filter_service_by_host_tag_name(tpl):
"""Filter for service
Filter on tag
:param tpl: tag to filter
:type tpl: str
:return: Filter
:rtype: bool
"""
def inner_filter(items):
"""Inner filter for service. Accept if tpl in service.host.tags"""
service = items["service"]... | [
"def",
"filter_service_by_host_tag_name",
"(",
"tpl",
")",
":",
"def",
"inner_filter",
"(",
"items",
")",
":",
"\"\"\"Inner filter for service. Accept if tpl in service.host.tags\"\"\"",
"service",
"=",
"items",
"[",
"\"service\"",
"]",
"host",
"=",
"items",
"[",
"\"hos... | 25.947368 | 0.001957 |
def job_data(job_id):
'''Get the raw data that the job returned. The mimetype
will be the value provided in the metdata for the key ``mimetype``.
**Results:**
:rtype: string
:statuscode 200: no error
:statuscode 403: not authorized to view the job's data
:statuscode 404: job id not found
... | [
"def",
"job_data",
"(",
"job_id",
")",
":",
"job_dict",
"=",
"db",
".",
"get_job",
"(",
"job_id",
")",
"if",
"not",
"job_dict",
":",
"return",
"json",
".",
"dumps",
"(",
"{",
"'error'",
":",
"'job_id not found'",
"}",
")",
",",
"404",
",",
"headers",
... | 36.136364 | 0.001225 |
def seasons(ephemeris):
"""Build a function of time that returns the quarter of the year.
The function that this returns will expect a single argument that is
a :class:`~skyfield.timelib.Time` and will return 0 through 3 for
the seasons Spring, Summer, Autumn, and Winter.
"""
earth = ephemeris... | [
"def",
"seasons",
"(",
"ephemeris",
")",
":",
"earth",
"=",
"ephemeris",
"[",
"'earth'",
"]",
"sun",
"=",
"ephemeris",
"[",
"'sun'",
"]",
"def",
"season_at",
"(",
"t",
")",
":",
"\"\"\"Return season 0 (Spring) through 3 (Winter) at time `t`.\"\"\"",
"t",
".",
"_... | 34.25 | 0.00142 |
def create(self, key, *args, **kwargs):
"""
Creates and inserts an identified object with the passed params
using the specified class.
"""
instance = self._class(key, *args, **kwargs)
self._events.create.trigger(list=self, instance=instance, key=key, args=args, kwargs... | [
"def",
"create",
"(",
"self",
",",
"key",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"instance",
"=",
"self",
".",
"_class",
"(",
"key",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"self",
".",
"_events",
".",
"create",
".",
"trig... | 44.75 | 0.008219 |
def update(self, params, path, **kwargs):
"""
Test Update
:param params:
:param path:
:param random:
"""
self.client.request('POST', params, path, **kwargs) | [
"def",
"update",
"(",
"self",
",",
"params",
",",
"path",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"client",
".",
"request",
"(",
"'POST'",
",",
"params",
",",
"path",
",",
"*",
"*",
"kwargs",
")"
] | 25.625 | 0.009434 |
def check_for_old_config(ipython_dir=None):
"""Check for old config files, and present a warning if they exist.
A link to the docs of the new config is included in the message.
This should mitigate confusion with the transition to the new
config system in 0.11.
"""
if ipython_dir is None:
... | [
"def",
"check_for_old_config",
"(",
"ipython_dir",
"=",
"None",
")",
":",
"if",
"ipython_dir",
"is",
"None",
":",
"ipython_dir",
"=",
"get_ipython_dir",
"(",
")",
"old_configs",
"=",
"[",
"'ipy_user_conf.py'",
",",
"'ipythonrc'",
",",
"'ipython_config.py'",
"]",
... | 40.6875 | 0.002251 |
def setup_installed_apps(cls):
"""
To import 3rd party applications along with associated properties
It is a list of dict or string.
When a dict, it contains the `app` key and the configuration,
if it's a string, it is just the app name
If you require dependencies from... | [
"def",
"setup_installed_apps",
"(",
"cls",
")",
":",
"cls",
".",
"_installed_apps",
"=",
"cls",
".",
"_app",
".",
"config",
".",
"get",
"(",
"\"INSTALLED_APPS\"",
",",
"[",
"]",
")",
"if",
"cls",
".",
"_installed_apps",
":",
"def",
"import_app",
"(",
"mo... | 36.166667 | 0.001923 |
def qplane(qplane_tile_dict, fseries, return_complex=False):
"""Performs q-transform on each tile for each q-plane and selects
tile with the maximum energy. Q-transform can then
be interpolated to a desired frequency and time resolution.
Parameters
----------
qplane_tile_dict:
Dic... | [
"def",
"qplane",
"(",
"qplane_tile_dict",
",",
"fseries",
",",
"return_complex",
"=",
"False",
")",
":",
"# store q-transforms for each q in a dict",
"qplanes",
"=",
"{",
"}",
"max_energy",
",",
"max_key",
"=",
"None",
",",
"None",
"for",
"i",
",",
"q",
"in",
... | 34.617021 | 0.000598 |
def get_data(name, train_batch_size, test_batch_size):
"""Gets training and testing dataset iterators.
Args:
name: String. Name of dataset, either 'mnist' or 'cifar10'.
train_batch_size: Integer. Batch size for training.
test_batch_size: Integer. Batch size for testing.
Returns:
Dict containing:... | [
"def",
"get_data",
"(",
"name",
",",
"train_batch_size",
",",
"test_batch_size",
")",
":",
"if",
"name",
"not",
"in",
"[",
"'mnist'",
",",
"'cifar10'",
"]",
":",
"raise",
"ValueError",
"(",
"'Expected dataset \\'mnist\\' or \\'cifar10\\', but got %s'",
"%",
"name",
... | 36.185185 | 0.011958 |
def check_exists(self):
'''
Check if resource exists, update self.exists, returns
Returns:
None: sets self.exists
'''
response = self.repo.api.http_request('HEAD', self.uri)
self.status_code = response.status_code
# resource exists
if self.status_code == 200:
self.exists = True
# resource no ... | [
"def",
"check_exists",
"(",
"self",
")",
":",
"response",
"=",
"self",
".",
"repo",
".",
"api",
".",
"http_request",
"(",
"'HEAD'",
",",
"self",
".",
"uri",
")",
"self",
".",
"status_code",
"=",
"response",
".",
"status_code",
"# resource exists",
"if",
... | 22.142857 | 0.039175 |
def with_pivot(self, *columns):
"""
Set the columns on the pivot table to retrieve.
"""
columns = list(columns)
self._pivot_columns += columns
return self | [
"def",
"with_pivot",
"(",
"self",
",",
"*",
"columns",
")",
":",
"columns",
"=",
"list",
"(",
"columns",
")",
"self",
".",
"_pivot_columns",
"+=",
"columns",
"return",
"self"
] | 21.777778 | 0.009804 |
def readSAM(SAMfile,header=False):
"""
Reads and parses a sam file.
:param SAMfile: /path/to/file.sam
:param header: logical, if True, reads the header information
:returns: a pandas dataframe with the respective SAM columns: 'QNAME','FLAG','RNAME','POS','MAPQ','CIGAR','RNEXT','PNEXT','TLEN','SEQ'... | [
"def",
"readSAM",
"(",
"SAMfile",
",",
"header",
"=",
"False",
")",
":",
"if",
"header",
"==",
"True",
":",
"f",
"=",
"open",
"(",
"SAMfile",
",",
"\"r+\"",
")",
"head",
"=",
"[",
"]",
"for",
"line",
"in",
"f",
".",
"readlines",
"(",
")",
":",
... | 31.179487 | 0.038278 |
def timestamp_YmdHMS(value):
"""Convert timestamp string to time in seconds since epoch.
Timestamps strings like '20130618120000' are able to be converted by this
function.
Args:
value: A timestamp string in the format '%Y%m%d%H%M%S'.
Returns:
The time in seconds since epoch as an... | [
"def",
"timestamp_YmdHMS",
"(",
"value",
")",
":",
"i",
"=",
"int",
"(",
"value",
")",
"S",
"=",
"i",
"M",
"=",
"S",
"//",
"100",
"H",
"=",
"M",
"//",
"100",
"d",
"=",
"H",
"//",
"100",
"m",
"=",
"d",
"//",
"100",
"Y",
"=",
"m",
"//",
"10... | 23.555556 | 0.001511 |
def setattr(self, key, value):
""" This method sets attribute of a Managed Object. """
if (UcsUtils.FindClassIdInMoMetaIgnoreCase(self.classId) != None):
if (key in _ManagedObjectMeta[self.classId]):
propMeta = UcsUtils.GetUcsPropertyMeta(self.classId, key)
if (propMeta.ValidatePropertyValue(value) == F... | [
"def",
"setattr",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"if",
"(",
"UcsUtils",
".",
"FindClassIdInMoMetaIgnoreCase",
"(",
"self",
".",
"classId",
")",
"!=",
"None",
")",
":",
"if",
"(",
"key",
"in",
"_ManagedObjectMeta",
"[",
"self",
".",
"c... | 32.421053 | 0.031546 |
def mimf_ferrario(mi):
''' Curvature MiMf from Ferrario etal. 2005MNRAS.361.1131.'''
mf=-0.00012336*mi**6+0.003160*mi**5-0.02960*mi**4+\
0.12350*mi**3-0.21550*mi**2+0.19022*mi+0.46575
return mf | [
"def",
"mimf_ferrario",
"(",
"mi",
")",
":",
"mf",
"=",
"-",
"0.00012336",
"*",
"mi",
"**",
"6",
"+",
"0.003160",
"*",
"mi",
"**",
"5",
"-",
"0.02960",
"*",
"mi",
"**",
"4",
"+",
"0.12350",
"*",
"mi",
"**",
"3",
"-",
"0.21550",
"*",
"mi",
"**",... | 35.166667 | 0.023148 |
def _get_result_constructor(self):
""" Returns a function that will be used to instantiate query results """
if not self._values_list: # we want models
return lambda rows: self.model._construct_instance(rows)
elif self._flat_values_list: # the user has requested flattened list (1 val... | [
"def",
"_get_result_constructor",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_values_list",
":",
"# we want models",
"return",
"lambda",
"rows",
":",
"self",
".",
"model",
".",
"_construct_instance",
"(",
"rows",
")",
"elif",
"self",
".",
"_flat_values_... | 58.25 | 0.012685 |
def request(self, method, url, access_token=None, **kwargs):
"""
向微信服务器发送请求
:param method: 请求方法
:param url: 请求地址
:param access_token: access token 值, 如果初始化时传入 conf 会自动获取, 如果没有传入则请提供此值
:param kwargs: 附加数据
:return: 微信服务器响应的 JSON 数据
"""
access_token =... | [
"def",
"request",
"(",
"self",
",",
"method",
",",
"url",
",",
"access_token",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"access_token",
"=",
"self",
".",
"__conf",
".",
"access_token",
"if",
"self",
".",
"__conf",
"is",
"not",
"None",
"else",
... | 32.692308 | 0.002285 |
def Freqs(self,jr,jphi,jz,**kwargs):
"""
NAME:
Freqs
PURPOSE:
return the frequencies corresponding to a torus
INPUT:
jr - radial action (scalar)
jphi - azimuthal action (scalar)
jz - vertical action (scalar)
tol= (... | [
"def",
"Freqs",
"(",
"self",
",",
"jr",
",",
"jphi",
",",
"jz",
",",
"*",
"*",
"kwargs",
")",
":",
"out",
"=",
"actionAngleTorus_c",
".",
"actionAngleTorus_Freqs_c",
"(",
"self",
".",
"_pot",
",",
"jr",
",",
"jphi",
",",
"jz",
",",
"tol",
"=",
"kwa... | 22.567568 | 0.014925 |
def put_group_policy(group_name, policy_name, policy_json, region=None, key=None,
keyid=None, profile=None):
'''
Adds or updates the specified policy document for the specified group.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion boto_iam... | [
"def",
"put_group_policy",
"(",
"group_name",
",",
"policy_name",
",",
"policy_json",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"group",
"=",
"get_group",
"(",
"group_name",
","... | 38.09375 | 0.0016 |
def min_weighted_vertex_cover(G, weight=None, sampler=None, **sampler_args):
"""Returns an approximate minimum weighted vertex cover.
Defines a QUBO with ground states corresponding to a minimum weighted
vertex cover and uses the sampler to sample from it.
A vertex cover is a set of vertices such that... | [
"def",
"min_weighted_vertex_cover",
"(",
"G",
",",
"weight",
"=",
"None",
",",
"sampler",
"=",
"None",
",",
"*",
"*",
"sampler_args",
")",
":",
"indep_nodes",
"=",
"set",
"(",
"maximum_weighted_independent_set",
"(",
"G",
",",
"weight",
",",
"sampler",
",",
... | 36.527273 | 0.000969 |
def _to_json_type(obj, classkey=None):
""" Recursively convert the object instance into a valid JSON type.
"""
if isinstance(obj, dict):
data = {}
for (k, v) in obj.items():
data[k] = _to_json_type(v, classkey)
return data
elif hasattr(obj, "_ast"):
return _to... | [
"def",
"_to_json_type",
"(",
"obj",
",",
"classkey",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"dict",
")",
":",
"data",
"=",
"{",
"}",
"for",
"(",
"k",
",",
"v",
")",
"in",
"obj",
".",
"items",
"(",
")",
":",
"data",
"[",
"... | 35.304348 | 0.001199 |
def validateOneElement(self, ctxt, elem):
"""Try to validate a single element and it's attributes,
basically it does the following checks as described by the
XML-1.0 recommendation: - [ VC: Element Valid ] - [ VC:
Required Attribute ] Then call xmlValidateOneAttribute()
f... | [
"def",
"validateOneElement",
"(",
"self",
",",
"ctxt",
",",
"elem",
")",
":",
"if",
"ctxt",
"is",
"None",
":",
"ctxt__o",
"=",
"None",
"else",
":",
"ctxt__o",
"=",
"ctxt",
".",
"_o",
"if",
"elem",
"is",
"None",
":",
"elem__o",
"=",
"None",
"else",
... | 48.461538 | 0.009346 |
def run(self, stdout_func = None, stdin_func = None, stderr_func = None):
"""Runs the process, using the provided functions for I/O.
The function stdin_func should return strings whenever a
character or characters become available.
The functions stdout_func and stderr_func are called wh... | [
"def",
"run",
"(",
"self",
",",
"stdout_func",
"=",
"None",
",",
"stdin_func",
"=",
"None",
",",
"stderr_func",
"=",
"None",
")",
":",
"if",
"stdout_func",
"==",
"None",
"and",
"stdin_func",
"==",
"None",
"and",
"stderr_func",
"==",
"None",
":",
"return"... | 44.68 | 0.00876 |
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 | 0.002268 |
def read_crn(filename):
"""
Read NOAA USCRN [1]_ [2]_ fixed-width file into pandas dataframe.
Parameters
----------
filename: str
filepath or url to read for the fixed-width file.
Returns
-------
data: Dataframe
A dataframe with DatetimeIndex and all of the variables in... | [
"def",
"read_crn",
"(",
"filename",
")",
":",
"# read in data",
"data",
"=",
"pd",
".",
"read_fwf",
"(",
"filename",
",",
"header",
"=",
"None",
",",
"names",
"=",
"HEADERS",
".",
"split",
"(",
"' '",
")",
",",
"widths",
"=",
"WIDTHS",
")",
"# loop her... | 33.203125 | 0.000457 |
def independent_data(self):
"""
Read-only Property
:return: Data belonging to each independent variable as a dict with
variable names as key, data as value.
:rtype: collections.OrderedDict
"""
return OrderedDict((var, self.data[var]) for var in self.mode... | [
"def",
"independent_data",
"(",
"self",
")",
":",
"return",
"OrderedDict",
"(",
"(",
"var",
",",
"self",
".",
"data",
"[",
"var",
"]",
")",
"for",
"var",
"in",
"self",
".",
"model",
".",
"independent_vars",
")"
] | 36.777778 | 0.00885 |
def imagej_metadata_tag(metadata, byteorder):
"""Return IJMetadata and IJMetadataByteCounts tags from metadata dict.
The tags can be passed to the TiffWriter.save function as extratags.
The metadata dict may contain the following keys and values:
Info : str
Human-readable information ... | [
"def",
"imagej_metadata_tag",
"(",
"metadata",
",",
"byteorder",
")",
":",
"header",
"=",
"[",
"{",
"'>'",
":",
"b'IJIJ'",
",",
"'<'",
":",
"b'JIJI'",
"}",
"[",
"byteorder",
"]",
"]",
"bytecounts",
"=",
"[",
"0",
"]",
"body",
"=",
"[",
"]",
"def",
... | 32.12 | 0.000403 |
def add(self, field, val):
"Add a sample"
if engine.FieldDefinition.FIELDS[field]._matcher is matching.TimeFilter:
val = self._basetime - val
try:
self.total[field] += val
self.min[field] = min(self.min[field], val) if field in self.min else val
s... | [
"def",
"add",
"(",
"self",
",",
"field",
",",
"val",
")",
":",
"if",
"engine",
".",
"FieldDefinition",
".",
"FIELDS",
"[",
"field",
"]",
".",
"_matcher",
"is",
"matching",
".",
"TimeFilter",
":",
"val",
"=",
"self",
".",
"_basetime",
"-",
"val",
"try... | 38.909091 | 0.009132 |
def check_archs(copied_libs, require_archs=(), stop_fast=False):
""" Check compatibility of archs in `copied_libs` dict
Parameters
----------
copied_libs : dict
dict containing the (key, value) pairs of (``copied_lib_path``,
``dependings_dict``), where ``copied_lib_path`` is a library r... | [
"def",
"check_archs",
"(",
"copied_libs",
",",
"require_archs",
"=",
"(",
")",
",",
"stop_fast",
"=",
"False",
")",
":",
"if",
"isinstance",
"(",
"require_archs",
",",
"string_types",
")",
":",
"require_archs",
"=",
"(",
"[",
"'i386'",
",",
"'x86_64'",
"]"... | 50.05 | 0.000327 |
def _place_order(self,
side,
product_id='BTC-USD',
client_oid=None,
type=None,
stp=None,
price=None,
size=None,
funds=None,
time_in_force=None,
... | [
"def",
"_place_order",
"(",
"self",
",",
"side",
",",
"product_id",
"=",
"'BTC-USD'",
",",
"client_oid",
"=",
"None",
",",
"type",
"=",
"None",
",",
"stp",
"=",
"None",
",",
"price",
"=",
"None",
",",
"size",
"=",
"None",
",",
"funds",
"=",
"None",
... | 28.148148 | 0.029262 |
def fast_comp(seq1, seq2, transpositions=False):
"""Compute the distance between the two sequences `seq1` and `seq2` up to a
maximum of 2 included, and return it. If the edit distance between the two
sequences is higher than that, -1 is returned.
If `transpositions` is `True`, transpositions will be taken into ac... | [
"def",
"fast_comp",
"(",
"seq1",
",",
"seq2",
",",
"transpositions",
"=",
"False",
")",
":",
"replace",
",",
"insert",
",",
"delete",
"=",
"\"r\"",
",",
"\"i\"",
",",
"\"d\"",
"L1",
",",
"L2",
"=",
"len",
"(",
"seq1",
")",
",",
"len",
"(",
"seq2",
... | 22.775 | 0.044187 |
def _format_envvar(param):
"""Format the envvars of a `click.Option` or `click.Argument`."""
yield '.. envvar:: {}'.format(param.envvar)
yield ' :noindex:'
yield ''
if isinstance(param, click.Argument):
param_ref = param.human_readable_name
else:
# if a user has defined an opt ... | [
"def",
"_format_envvar",
"(",
"param",
")",
":",
"yield",
"'.. envvar:: {}'",
".",
"format",
"(",
"param",
".",
"envvar",
")",
"yield",
"' :noindex:'",
"yield",
"''",
"if",
"isinstance",
"(",
"param",
",",
"click",
".",
"Argument",
")",
":",
"param_ref",
... | 40.923077 | 0.001838 |
def uid(self, p_todo):
"""
Returns the unique text-based ID for a todo item.
"""
try:
return self._todo_id_map[p_todo]
except KeyError as ex:
raise InvalidTodoException from ex | [
"def",
"uid",
"(",
"self",
",",
"p_todo",
")",
":",
"try",
":",
"return",
"self",
".",
"_todo_id_map",
"[",
"p_todo",
"]",
"except",
"KeyError",
"as",
"ex",
":",
"raise",
"InvalidTodoException",
"from",
"ex"
] | 29.125 | 0.008333 |
def _make_zipfile(base_name, base_dir, verbose=0, dry_run=0, logger=None):
"""Create a zip file from all the files under 'base_dir'.
The output zip file will be named 'base_name' + ".zip". Uses either the
"zipfile" Python module (if available) or the InfoZIP "zip" utility
(if installed and found on th... | [
"def",
"_make_zipfile",
"(",
"base_name",
",",
"base_dir",
",",
"verbose",
"=",
"0",
",",
"dry_run",
"=",
"0",
",",
"logger",
"=",
"None",
")",
":",
"zip_filename",
"=",
"base_name",
"+",
"\".zip\"",
"archive_dir",
"=",
"os",
".",
"path",
".",
"dirname",... | 36.108696 | 0.000586 |
def _parse_pet_record(self, root):
"""
Given a <pet> Element from a pet.get or pet.getRandom response, pluck
out the pet record.
:param lxml.etree._Element root: A <pet> tag Element.
:rtype: dict
:returns: An assembled pet record.
"""
record = {
... | [
"def",
"_parse_pet_record",
"(",
"self",
",",
"root",
")",
":",
"record",
"=",
"{",
"\"breeds\"",
":",
"[",
"]",
",",
"\"photos\"",
":",
"[",
"]",
",",
"\"options\"",
":",
"[",
"]",
",",
"\"contact\"",
":",
"{",
"}",
",",
"}",
"# These fields can just ... | 35.901639 | 0.000889 |
def get(self, obj, cls):
"""
Using the lowercase name of the class as node_type, returns `obj.visit_{node_type}`,
or `obj.visit_default` if the type-specific method is not found.
"""
method = self._cache.get(cls)
if not method:
name = "visit_" + cls.__name__.lower()
method = getattr(... | [
"def",
"get",
"(",
"self",
",",
"obj",
",",
"cls",
")",
":",
"method",
"=",
"self",
".",
"_cache",
".",
"get",
"(",
"cls",
")",
"if",
"not",
"method",
":",
"name",
"=",
"\"visit_\"",
"+",
"cls",
".",
"__name__",
".",
"lower",
"(",
")",
"method",
... | 35.363636 | 0.012531 |
def _get_raw_objects(self):
"""
Helper function to populate the first page of raw objects for this tag.
This has the side effect of creating the ``_raw_objects`` attribute of
this object.
"""
if not hasattr(self, '_raw_objects'):
result = self._client.get(type... | [
"def",
"_get_raw_objects",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'_raw_objects'",
")",
":",
"result",
"=",
"self",
".",
"_client",
".",
"get",
"(",
"type",
"(",
"self",
")",
".",
"api_endpoint",
",",
"model",
"=",
"self",
... | 41.642857 | 0.008389 |
def account_block(self, id):
"""
Block a user.
Returns a `relationship dict`_ containing the updated relationship to the user.
"""
id = self.__unpack_id(id)
url = '/api/v1/accounts/{0}/block'.format(str(id))
return self.__api_request('POST', url) | [
"def",
"account_block",
"(",
"self",
",",
"id",
")",
":",
"id",
"=",
"self",
".",
"__unpack_id",
"(",
"id",
")",
"url",
"=",
"'/api/v1/accounts/{0}/block'",
".",
"format",
"(",
"str",
"(",
"id",
")",
")",
"return",
"self",
".",
"__api_request",
"(",
"'... | 32.777778 | 0.009901 |
def fingerprints(self, keyhalf='any', keytype='any'):
"""
List loaded fingerprints with some optional filtering.
:param str keyhalf: Can be 'any', 'public', or 'private'. If 'public', or 'private', the fingerprints of keys of the
the other type will not be included i... | [
"def",
"fingerprints",
"(",
"self",
",",
"keyhalf",
"=",
"'any'",
",",
"keytype",
"=",
"'any'",
")",
":",
"return",
"{",
"pk",
".",
"fingerprint",
"for",
"pk",
"in",
"self",
".",
"_keys",
".",
"values",
"(",
")",
"if",
"pk",
".",
"is_primary",
"in",
... | 67.666667 | 0.008746 |
def deleteAttachment(self, oid, attachment_id):
""" removes an attachment from a feature service feature
Input:
oid - integer or string - id of feature
attachment_id - integer - id of attachment to erase
Output:
JSON response
"""
... | [
"def",
"deleteAttachment",
"(",
"self",
",",
"oid",
",",
"attachment_id",
")",
":",
"url",
"=",
"self",
".",
"_url",
"+",
"\"/%s/deleteAttachments\"",
"%",
"oid",
"params",
"=",
"{",
"\"f\"",
":",
"\"json\"",
",",
"\"attachmentIds\"",
":",
"\"%s\"",
"%",
"... | 39.823529 | 0.010101 |
def _parse_line_entry(self, line, type):
"""
Parse a section entry line into its components. In case of a 'vars'
section, the first field will be None. Otherwise, the first field will
be the unexpanded host or group name the variables apply to.
For example:
[producti... | [
"def",
"_parse_line_entry",
"(",
"self",
",",
"line",
",",
"type",
")",
":",
"name",
"=",
"None",
"key_values",
"=",
"{",
"}",
"if",
"type",
"==",
"'vars'",
":",
"key_values",
"=",
"self",
".",
"_parse_line_vars",
"(",
"line",
")",
"else",
":",
"tokens... | 32.153846 | 0.002322 |
def append_transformation(self, transformation, extend_collection=False,
clear_redo=True):
"""
Appends a transformation to all TransformedStructures.
Args:
transformation: Transformation to append
extend_collection: Whether to use more than ... | [
"def",
"append_transformation",
"(",
"self",
",",
"transformation",
",",
"extend_collection",
"=",
"False",
",",
"clear_redo",
"=",
"True",
")",
":",
"if",
"self",
".",
"ncores",
"and",
"transformation",
".",
"use_multiprocessing",
":",
"p",
"=",
"Pool",
"(",
... | 47.609756 | 0.001506 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.