text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def get_replication_group_imbalance_stats(rgs, partitions):
"""Calculate extra replica count replica count over each replication-group
and net extra-same-replica count.
"""
tot_rgs = len(rgs)
extra_replica_cnt_per_rg = defaultdict(int)
for partition in partitions:
# Get optimal replica-c... | [
"def",
"get_replication_group_imbalance_stats",
"(",
"rgs",
",",
"partitions",
")",
":",
"tot_rgs",
"=",
"len",
"(",
"rgs",
")",
"extra_replica_cnt_per_rg",
"=",
"defaultdict",
"(",
"int",
")",
"for",
"partition",
"in",
"partitions",
":",
"# Get optimal replica-coun... | 41.2 | 13.72 |
def getLogger(name):
"""Return a logger from a given name.
If the name does not have a log handler, this will create one for it based
on the module name which will log everything to a log file in a location
the executing user will have access to.
:param name: ``str``
:return: ``object``
""... | [
"def",
"getLogger",
"(",
"name",
")",
":",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"name",
"=",
"name",
")",
"for",
"handler",
"in",
"log",
".",
"handlers",
":",
"if",
"name",
"==",
"handler",
".",
"name",
":",
"return",
"log",
"else",
":",
"... | 31.875 | 18.875 |
def get_array(array, **kw):
"""
Extract a subarray by filtering on the given keyword arguments
"""
for name, value in kw.items():
array = array[array[name] == value]
return array | [
"def",
"get_array",
"(",
"array",
",",
"*",
"*",
"kw",
")",
":",
"for",
"name",
",",
"value",
"in",
"kw",
".",
"items",
"(",
")",
":",
"array",
"=",
"array",
"[",
"array",
"[",
"name",
"]",
"==",
"value",
"]",
"return",
"array"
] | 28.571429 | 10.285714 |
def populate(self, metamodel):
'''
Populate a *metamodel* with entities previously encountered from input.
'''
self.populate_classes(metamodel)
self.populate_unique_identifiers(metamodel)
self.populate_associations(metamodel)
self.populate_instances(metamodel)
... | [
"def",
"populate",
"(",
"self",
",",
"metamodel",
")",
":",
"self",
".",
"populate_classes",
"(",
"metamodel",
")",
"self",
".",
"populate_unique_identifiers",
"(",
"metamodel",
")",
"self",
".",
"populate_associations",
"(",
"metamodel",
")",
"self",
".",
"po... | 39.222222 | 14.333333 |
def faces_sparse(self):
"""
A sparse matrix representation of the faces.
Returns
----------
sparse : scipy.sparse.coo_matrix
Has properties:
dtype : bool
shape : (len(self.vertices), len(self.faces))
"""
sparse = geometry.index_spars... | [
"def",
"faces_sparse",
"(",
"self",
")",
":",
"sparse",
"=",
"geometry",
".",
"index_sparse",
"(",
"column_count",
"=",
"len",
"(",
"self",
".",
"vertices",
")",
",",
"indices",
"=",
"self",
".",
"faces",
")",
"return",
"sparse"
] | 27.133333 | 13.133333 |
def delete_rrset(self, zone_name, rtype, owner_name):
"""Deletes an RRSet.
Arguments:
zone_name -- The zone containing the RRSet to be deleted. The trailing dot is optional.
rtype -- The type of the RRSet. This can be numeric (1) or
if a well-known name is defined for... | [
"def",
"delete_rrset",
"(",
"self",
",",
"zone_name",
",",
"rtype",
",",
"owner_name",
")",
":",
"return",
"self",
".",
"rest_api_connection",
".",
"delete",
"(",
"\"/v1/zones/\"",
"+",
"zone_name",
"+",
"\"/rrsets/\"",
"+",
"rtype",
"+",
"\"/\"",
"+",
"owne... | 56.923077 | 35.769231 |
def add_route(self, template, controller, **kwargs):
""" Add a route definition
`controller` can be either a controller instance,
or the name of a callable that will be imported.
"""
if isinstance(controller, basestring):
controller = pymagic.import_name(cont... | [
"def",
"add_route",
"(",
"self",
",",
"template",
",",
"controller",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"isinstance",
"(",
"controller",
",",
"basestring",
")",
":",
"controller",
"=",
"pymagic",
".",
"import_name",
"(",
"controller",
")",
"self",
... | 34.583333 | 21 |
def batch_predict(
self,
name,
input_config,
output_config,
params=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Perform a batch prediction. Unlike the online... | [
"def",
"batch_predict",
"(",
"self",
",",
"name",
",",
"input_config",
",",
"output_config",
",",
"params",
"=",
"None",
",",
"retry",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"DEFAULT",
",",
"timeout",
"=",
"google",
".",
"ap... | 49.133803 | 28.373239 |
def do_b(self, line):
"""Send the Master a BinaryInput (group 2) value. Command syntax is: 'b index true' or 'b index false'"""
index, value_string = self.index_and_value_from_line(line)
if index and value_string:
if value_string.lower() == 'true' or value_string.lower() == 'false':
... | [
"def",
"do_b",
"(",
"self",
",",
"line",
")",
":",
"index",
",",
"value_string",
"=",
"self",
".",
"index_and_value_from_line",
"(",
"line",
")",
"if",
"index",
"and",
"value_string",
":",
"if",
"value_string",
".",
"lower",
"(",
")",
"==",
"'true'",
"or... | 62.5 | 25.375 |
def native(self):
"""
The native Python datatype representation of this value
:return:
A datetime.datetime object in the UTC timezone or None
"""
if self.contents is None:
return None
if self._native is None:
string = str_cls(self)
... | [
"def",
"native",
"(",
"self",
")",
":",
"if",
"self",
".",
"contents",
"is",
"None",
":",
"return",
"None",
"if",
"self",
".",
"_native",
"is",
"None",
":",
"string",
"=",
"str_cls",
"(",
"self",
")",
"has_timezone",
"=",
"re",
".",
"search",
"(",
... | 32.368421 | 19.842105 |
def _build_conflict_target(self):
"""Builds the `conflict_target` for the ON CONFLICT
clause."""
conflict_target = []
if not isinstance(self.query.conflict_target, list):
raise SuspiciousOperation((
'%s is not a valid conflict target, specify '
... | [
"def",
"_build_conflict_target",
"(",
"self",
")",
":",
"conflict_target",
"=",
"[",
"]",
"if",
"not",
"isinstance",
"(",
"self",
".",
"query",
".",
"conflict_target",
",",
"list",
")",
":",
"raise",
"SuspiciousOperation",
"(",
"(",
"'%s is not a valid conflict ... | 35.55 | 15.675 |
def seconds_until_renew(self):
"""
Returns the number of seconds between the current time
and the set renew time. It can be negative if the
leader election is running late.
"""
delta = self.renew_time - datetime.now(self.renew_time.tzinfo)
return delta.total_secon... | [
"def",
"seconds_until_renew",
"(",
"self",
")",
":",
"delta",
"=",
"self",
".",
"renew_time",
"-",
"datetime",
".",
"now",
"(",
"self",
".",
"renew_time",
".",
"tzinfo",
")",
"return",
"delta",
".",
"total_seconds",
"(",
")"
] | 39.625 | 10.375 |
def _database_create(self, engine, database):
"""Create a new database and return a new url representing
a connection to the new database
"""
logger.info('Creating database "%s" in "%s"', database, engine)
database_operation(engine, 'create', database)
url = copy(engine.u... | [
"def",
"_database_create",
"(",
"self",
",",
"engine",
",",
"database",
")",
":",
"logger",
".",
"info",
"(",
"'Creating database \"%s\" in \"%s\"'",
",",
"database",
",",
"engine",
")",
"database_operation",
"(",
"engine",
",",
"'create'",
",",
"database",
")",... | 41.222222 | 9.555556 |
def create_user(self, user, table_privileges=['ALL PRIVILEGES'],
schema_privileges=['ALL PRIVILEGES'],
row_limit=50000):
con = self.connection or self._connect()
cur = con.cursor()
cur.execute('CREATE SCHEMA {0};'.format(user))
# self._initialize(... | [
"def",
"create_user",
"(",
"self",
",",
"user",
",",
"table_privileges",
"=",
"[",
"'ALL PRIVILEGES'",
"]",
",",
"schema_privileges",
"=",
"[",
"'ALL PRIVILEGES'",
"]",
",",
"row_limit",
"=",
"50000",
")",
":",
"con",
"=",
"self",
".",
"connection",
"or",
... | 38.442105 | 17.568421 |
def is_fifo(self):
"""
Whether this path is a FIFO.
"""
try:
return S_ISFIFO(self.stat().st_mode)
except OSError as e:
if e.errno not in (ENOENT, ENOTDIR):
raise
# Path doesn't exist or is a broken symlink
# (see htt... | [
"def",
"is_fifo",
"(",
"self",
")",
":",
"try",
":",
"return",
"S_ISFIFO",
"(",
"self",
".",
"stat",
"(",
")",
".",
"st_mode",
")",
"except",
"OSError",
"as",
"e",
":",
"if",
"e",
".",
"errno",
"not",
"in",
"(",
"ENOENT",
",",
"ENOTDIR",
")",
":"... | 31.5 | 13.166667 |
def unload(self):
'''unload module'''
self.mpstate.console.close()
self.mpstate.console = textconsole.SimpleConsole() | [
"def",
"unload",
"(",
"self",
")",
":",
"self",
".",
"mpstate",
".",
"console",
".",
"close",
"(",
")",
"self",
".",
"mpstate",
".",
"console",
"=",
"textconsole",
".",
"SimpleConsole",
"(",
")"
] | 34.5 | 14.5 |
def hash_codes(text, hashes):
"""Hashes inline code tags.
Code tags can begin with an arbitrary number of back-ticks, as long
as the close contains the same number of back-ticks. This allows
back-ticks to be used within the code tag.
HTML entities (&, <, >, ", ') are automatically escaped inside t... | [
"def",
"hash_codes",
"(",
"text",
",",
"hashes",
")",
":",
"def",
"sub",
"(",
"match",
")",
":",
"code",
"=",
"'<code>{}</code>'",
".",
"format",
"(",
"escape",
"(",
"match",
".",
"group",
"(",
"2",
")",
")",
")",
"hashed",
"=",
"hash_text",
"(",
"... | 33.75 | 18.375 |
def einsum_vecmul_index(gate_indices, number_of_qubits):
"""Return the index string for Numpy.eignsum matrix-vector multiplication.
The returned indices are to perform a matrix multiplication A.v where
the matrix A is an M-qubit matrix, vector v is an N-qubit vector, and
M <= N, and identity matrices a... | [
"def",
"einsum_vecmul_index",
"(",
"gate_indices",
",",
"number_of_qubits",
")",
":",
"mat_l",
",",
"mat_r",
",",
"tens_lin",
",",
"tens_lout",
"=",
"_einsum_matmul_index_helper",
"(",
"gate_indices",
",",
"number_of_qubits",
")",
"# Combine indices into matrix multiplica... | 45.52 | 28.6 |
def send_connection_request(self):
"""
Sends a ConnectionRequest to the iDigi server using the credentials
established with the id of the monitor as defined in the monitor
member.
"""
try:
self.log.info("Sending ConnectionRequest for Monitor %s."
... | [
"def",
"send_connection_request",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"log",
".",
"info",
"(",
"\"Sending ConnectionRequest for Monitor %s.\"",
"%",
"self",
".",
"monitor_id",
")",
"# Send connection request and perform a receive to ensure",
"# request is authen... | 42.059701 | 20.80597 |
def epanechnikovKernel(x,ref_x,h=1.0):
'''
The Epanechnikov kernel.
Parameters
----------
x : np.array
Values at which to evaluate the kernel
x_ref : float
The reference point
h : float
Kernel bandwidth
Returns
-------
out : np.array
Kernel value... | [
"def",
"epanechnikovKernel",
"(",
"x",
",",
"ref_x",
",",
"h",
"=",
"1.0",
")",
":",
"u",
"=",
"(",
"x",
"-",
"ref_x",
")",
"/",
"h",
"# Normalize distance by bandwidth",
"these",
"=",
"np",
".",
"abs",
"(",
"u",
")",
"<=",
"1.0",
"# Kernel = 0 outside... | 25.695652 | 22.304348 |
def list_notebooks(self):
"""List all notebooks in the notebook dir.
This returns a list of dicts of the form::
dict(notebook_id=notebook,name=name)
"""
names = glob.glob(os.path.join(self.notebook_dir,
'*' + self.filename_ext))
... | [
"def",
"list_notebooks",
"(",
"self",
")",
":",
"names",
"=",
"glob",
".",
"glob",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"notebook_dir",
",",
"'*'",
"+",
"self",
".",
"filename_ext",
")",
")",
"names",
"=",
"[",
"os",
".",
"path",
... | 35.857143 | 17.809524 |
def wavelengthToRGB(wavelength):
gamma = 0.80;
intensityMax = 255;
""" Taken from Earl F. Glynn's web page:
* <a href="http://www.efg2.com/Lab/ScienceAndEngineering/Spectra.htm">Spectra Lab Report</a>
"""
factor = None
r = None
g = None
b = None
if((wavelength >= 380) and (wavelength<440)):
r = -(wavelen... | [
"def",
"wavelengthToRGB",
"(",
"wavelength",
")",
":",
"gamma",
"=",
"0.80",
"intensityMax",
"=",
"255",
"factor",
"=",
"None",
"r",
"=",
"None",
"g",
"=",
"None",
"b",
"=",
"None",
"if",
"(",
"(",
"wavelength",
">=",
"380",
")",
"and",
"(",
"wavelen... | 24.728814 | 22.40678 |
def send(self, sender, **kwargs):
"""Internal. Call connected functions."""
if id(self) not in _alleged_receivers:
return
for func in _alleged_receivers[id(self)]:
func(sender, **kwargs) | [
"def",
"send",
"(",
"self",
",",
"sender",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"id",
"(",
"self",
")",
"not",
"in",
"_alleged_receivers",
":",
"return",
"for",
"func",
"in",
"_alleged_receivers",
"[",
"id",
"(",
"self",
")",
"]",
":",
"func",
... | 38.166667 | 8.333333 |
def bodvar(body, item, dim):
"""
Deprecated: This routine has been superseded by :func:`bodvcd` and
:func:`bodvrd`. This routine is supported for purposes of backward
compatibility only.
Return the values of some item for any body in the kernel pool.
http://naif.jpl.nasa.gov/pub/naif/toolkit_d... | [
"def",
"bodvar",
"(",
"body",
",",
"item",
",",
"dim",
")",
":",
"body",
"=",
"ctypes",
".",
"c_int",
"(",
"body",
")",
"dim",
"=",
"ctypes",
".",
"c_int",
"(",
"dim",
")",
"item",
"=",
"stypes",
".",
"stringToCharP",
"(",
"item",
")",
"values",
... | 32.592593 | 17.62963 |
def _annotate(reads, mirbase_ref, precursors):
"""
Using SAM/BAM coordinates, mismatches and realign to annotate isomiRs
"""
for r in reads:
for p in reads[r].precursors:
start = reads[r].precursors[p].start + 1 # convert to 1base
end = start + len(reads[r].sequence)
... | [
"def",
"_annotate",
"(",
"reads",
",",
"mirbase_ref",
",",
"precursors",
")",
":",
"for",
"r",
"in",
"reads",
":",
"for",
"p",
"in",
"reads",
"[",
"r",
"]",
".",
"precursors",
":",
"start",
"=",
"reads",
"[",
"r",
"]",
".",
"precursors",
"[",
"p",
... | 48.6875 | 22.4375 |
def countRandomBitFrequencies(numTerms = 100000, percentSparsity = 0.01):
"""Create a uniformly random counts matrix through sampling."""
# Accumulate counts by inplace-adding sparse matrices
counts = SparseMatrix()
size = 128*128
counts.resize(1, size)
# Pre-allocate buffer sparse matrix
sparseBitmap = ... | [
"def",
"countRandomBitFrequencies",
"(",
"numTerms",
"=",
"100000",
",",
"percentSparsity",
"=",
"0.01",
")",
":",
"# Accumulate counts by inplace-adding sparse matrices",
"counts",
"=",
"SparseMatrix",
"(",
")",
"size",
"=",
"128",
"*",
"128",
"counts",
".",
"resiz... | 31.684211 | 21.552632 |
def get_hoisted(dct, child_name):
"""Pulls all of a child's keys up to the parent, with the names unchanged."""
child = dct[child_name]
del dct[child_name]
dct.update(child)
return dct | [
"def",
"get_hoisted",
"(",
"dct",
",",
"child_name",
")",
":",
"child",
"=",
"dct",
"[",
"child_name",
"]",
"del",
"dct",
"[",
"child_name",
"]",
"dct",
".",
"update",
"(",
"child",
")",
"return",
"dct"
] | 31.5 | 15 |
def precompute_edge_matrices(adjacency, hparams):
"""Precompute the a_in and a_out tensors.
(we don't want to add to the graph everytime _fprop is called)
Args:
adjacency: placeholder of real valued vectors of shape [B, L, L, E]
hparams: HParams object
Returns:
edge_matrices: [batch, L * D, L * D] ... | [
"def",
"precompute_edge_matrices",
"(",
"adjacency",
",",
"hparams",
")",
":",
"batch_size",
",",
"num_nodes",
",",
"_",
",",
"edge_dim",
"=",
"common_layers",
".",
"shape_list",
"(",
"adjacency",
")",
"# build the edge_network for incoming edges",
"with",
"tf",
"."... | 39.288889 | 19.6 |
def absolute_error(y, y_pred):
"""Calculates the sum of the differences
between target and prediction.
Parameters:
-----------
y : vector, shape (n_samples,)
The target values.
y_pred : vector, shape (n_samples,)
The predicted values.
Returns:
--------
error : floa... | [
"def",
"absolute_error",
"(",
"y",
",",
"y_pred",
")",
":",
"y",
",",
"y_pred",
"=",
"convert_assert",
"(",
"y",
",",
"y_pred",
")",
"return",
"np",
".",
"sum",
"(",
"y",
"-",
"y_pred",
")"
] | 21.52381 | 17.952381 |
def brozzler_worker(argv=None):
'''
Main entry point for brozzler, gets sites and pages to brozzle from
rethinkdb, brozzles them.
'''
argv = argv or sys.argv
arg_parser = argparse.ArgumentParser(
prog=os.path.basename(argv[0]),
formatter_class=BetterArgumentDefaultsHelpFo... | [
"def",
"brozzler_worker",
"(",
"argv",
"=",
"None",
")",
":",
"argv",
"=",
"argv",
"or",
"sys",
".",
"argv",
"arg_parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"prog",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"argv",
"[",
"0",
"]",
")",
... | 42.556962 | 18.126582 |
def delimit(values, delimiter=', '):
"Returns a list of tokens interleaved with the delimiter."
toks = []
if not values:
return toks
if not isinstance(delimiter, (list, tuple)):
delimiter = [delimiter]
last = len(values) - 1
for i, value in enumerate(values):
toks.app... | [
"def",
"delimit",
"(",
"values",
",",
"delimiter",
"=",
"', '",
")",
":",
"toks",
"=",
"[",
"]",
"if",
"not",
"values",
":",
"return",
"toks",
"if",
"not",
"isinstance",
"(",
"delimiter",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"delimiter",
... | 20.315789 | 22.842105 |
def get(self, digest, chunk_size=1024 * 128):
"""
Return the contents of a blob
:param digest: the hex digest of the blob to return
:param chunk_size: the size of the chunks returned on each iteration
:return: generator returning chunks of data
"""
return self.co... | [
"def",
"get",
"(",
"self",
",",
"digest",
",",
"chunk_size",
"=",
"1024",
"*",
"128",
")",
":",
"return",
"self",
".",
"conn",
".",
"client",
".",
"blob_get",
"(",
"self",
".",
"container_name",
",",
"digest",
",",
"chunk_size",
")"
] | 41.1 | 15.5 |
def getRandomWithMods(inputSpace, maxChanges):
""" Returns a random selection from the inputSpace with randomly modified
up to maxChanges number of bits.
"""
size = len(inputSpace)
ind = np.random.random_integers(0, size-1, 1)[0]
value = copy.deepcopy(inputSpace[ind])
if maxChanges == 0:
return valu... | [
"def",
"getRandomWithMods",
"(",
"inputSpace",
",",
"maxChanges",
")",
":",
"size",
"=",
"len",
"(",
"inputSpace",
")",
"ind",
"=",
"np",
".",
"random",
".",
"random_integers",
"(",
"0",
",",
"size",
"-",
"1",
",",
"1",
")",
"[",
"0",
"]",
"value",
... | 26.846154 | 15.615385 |
def bibString(self, maxLength = 1000, WOSMode = False, restrictedOutput = False, niceID = True):
"""Makes a string giving the Record as a bibTex entry. If the Record is of a journal article (`PT J`) the bibtext type is set to `'article'`, otherwise it is set to `'misc'`. The ID of the entry is the WOS number an... | [
"def",
"bibString",
"(",
"self",
",",
"maxLength",
"=",
"1000",
",",
"WOSMode",
"=",
"False",
",",
"restrictedOutput",
"=",
"False",
",",
"niceID",
"=",
"True",
")",
":",
"keyEntries",
"=",
"[",
"]",
"if",
"self",
".",
"bad",
":",
"raise",
"BadRecord",... | 53.591549 | 35.492958 |
def predict(self, temp_type):
"""
Transpile the predict method.
Parameters
----------
:param temp_type : string
The kind of export type (embedded, separated, exported).
Returns
-------
:return : string
The transpiled predict metho... | [
"def",
"predict",
"(",
"self",
",",
"temp_type",
")",
":",
"# Exported:",
"if",
"temp_type",
"==",
"'exported'",
":",
"temp",
"=",
"self",
".",
"temp",
"(",
"'exported.class'",
")",
"return",
"temp",
".",
"format",
"(",
"class_name",
"=",
"self",
".",
"c... | 39.532258 | 16.532258 |
def stationary_distribution(self):
r""" Compute stationary distribution of hidden states if possible.
Raises
------
ValueError if the HMM is not stationary
"""
assert _tmatrix_disconnected.is_connected(self._Tij, strong=False), \
'No unique stationary distri... | [
"def",
"stationary_distribution",
"(",
"self",
")",
":",
"assert",
"_tmatrix_disconnected",
".",
"is_connected",
"(",
"self",
".",
"_Tij",
",",
"strong",
"=",
"False",
")",
",",
"'No unique stationary distribution because transition matrix is not connected'",
"import",
"m... | 38.25 | 20.833333 |
def fetch_captcha_store(self, name, value, attrs=None, generator=None):
"""
Fetches a new CaptchaStore
This has to be called inside render
"""
try:
reverse('captcha-image', args=('dummy',))
except NoReverseMatch:
raise ImproperlyConfigured('Make su... | [
"def",
"fetch_captcha_store",
"(",
"self",
",",
"name",
",",
"value",
",",
"attrs",
"=",
"None",
",",
"generator",
"=",
"None",
")",
":",
"try",
":",
"reverse",
"(",
"'captcha-image'",
",",
"args",
"=",
"(",
"'dummy'",
",",
")",
")",
"except",
"NoRever... | 41.578947 | 23.263158 |
def dump(self, fp=sys.stdout, **kwargs):
""" Serialize this keymap as a JSON formatted stream to the *fp*.
Arguments:
fp: A ``.write()``-supporting file-like object to write the
generated JSON to (default is ``sys.stdout``).
**kwargs: Options to be passed into :f... | [
"def",
"dump",
"(",
"self",
",",
"fp",
"=",
"sys",
".",
"stdout",
",",
"*",
"*",
"kwargs",
")",
":",
"fp",
".",
"write",
"(",
"FILE_HEADER",
")",
"fp",
".",
"write",
"(",
"self",
".",
"to_json",
"(",
"*",
"*",
"kwargs",
")",
")",
"fp",
".",
"... | 39.363636 | 15.545455 |
def _next_lowest_integer(group_keys):
"""
returns the lowest available integer in a set of dict keys
"""
try: #TODO Replace with max default value when dropping compatibility with Python < 3.4
largest_int= max([ int(val) for val in group_keys if _is_int(val)])
except:
largest_int= 0
... | [
"def",
"_next_lowest_integer",
"(",
"group_keys",
")",
":",
"try",
":",
"#TODO Replace with max default value when dropping compatibility with Python < 3.4",
"largest_int",
"=",
"max",
"(",
"[",
"int",
"(",
"val",
")",
"for",
"val",
"in",
"group_keys",
"if",
"_is_int",
... | 37.555556 | 19.111111 |
def create_source(srcdir, preload_image, datapusher=False):
"""
Copy ckan source, datapusher source (optional), who.ini and schema.xml
from preload image into srcdir
"""
try:
docker.web_command(
command='/bin/cp -a /project/ckan /project_target/ckan',
rw={srcdir: '/pr... | [
"def",
"create_source",
"(",
"srcdir",
",",
"preload_image",
",",
"datapusher",
"=",
"False",
")",
":",
"try",
":",
"docker",
".",
"web_command",
"(",
"command",
"=",
"'/bin/cp -a /project/ckan /project_target/ckan'",
",",
"rw",
"=",
"{",
"srcdir",
":",
"'/proje... | 35.148148 | 16.259259 |
def create_small_thumbnail(self, token, item_id):
"""
Create a 100x100 small thumbnail for the given item. It is used for
preview purpose and displayed in the 'preview' and 'thumbnails'
sidebar sections.
:param token: A valid token for the user in question.
:type token: ... | [
"def",
"create_small_thumbnail",
"(",
"self",
",",
"token",
",",
"item_id",
")",
":",
"parameters",
"=",
"dict",
"(",
")",
"parameters",
"[",
"'token'",
"]",
"=",
"token",
"parameters",
"[",
"'itemId'",
"]",
"=",
"item_id",
"response",
"=",
"self",
".",
... | 40.15 | 17.05 |
def create(cls, object_type=None, object_uuid=None, **kwargs):
"""Create a new deposit identifier.
:param object_type: The object type (Default: ``None``)
:param object_uuid: The object UUID (Default: ``None``)
:param kwargs: It contains the pid value.
"""
assert 'pid_va... | [
"def",
"create",
"(",
"cls",
",",
"object_type",
"=",
"None",
",",
"object_uuid",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"assert",
"'pid_value'",
"in",
"kwargs",
"kwargs",
".",
"setdefault",
"(",
"'status'",
",",
"cls",
".",
"default_status",
")... | 45.727273 | 16.090909 |
def bearing(self, format='numeric'):
"""Calculate bearing between locations in segments.
Args:
format (str): Format of the bearing string to return
Returns:
list of list of float: Groups of bearings between points in
segments
"""
bearings... | [
"def",
"bearing",
"(",
"self",
",",
"format",
"=",
"'numeric'",
")",
":",
"bearings",
"=",
"[",
"]",
"for",
"segment",
"in",
"self",
":",
"if",
"len",
"(",
"segment",
")",
"<",
"2",
":",
"bearings",
".",
"append",
"(",
"[",
"]",
")",
"else",
":",... | 29.764706 | 18 |
def rc2poly(kr, r0=None):
"""convert reflection coefficients to prediction filter polynomial
:param k: reflection coefficients
"""
# Initialize the recursion
from .levinson import levup
p = len(kr) #% p is the order of the prediction polynomial.
a = numpy.array([1, kr[0]]) ... | [
"def",
"rc2poly",
"(",
"kr",
",",
"r0",
"=",
"None",
")",
":",
"# Initialize the recursion",
"from",
".",
"levinson",
"import",
"levup",
"p",
"=",
"len",
"(",
"kr",
")",
"#% p is the order of the prediction polynomial.",
"a",
"=",
"numpy",
".",
"array",
"(",
... | 23.266667 | 24.833333 |
def _build_query(self, table, tree, visitor):
""" Build a scan/query from a statement """
kwargs = {}
index = None
if tree.using:
index_name = kwargs["index"] = tree.using[1]
index = table.get_index(index_name)
if tree.where:
constraints = Cons... | [
"def",
"_build_query",
"(",
"self",
",",
"table",
",",
"tree",
",",
"visitor",
")",
":",
"kwargs",
"=",
"{",
"}",
"index",
"=",
"None",
"if",
"tree",
".",
"using",
":",
"index_name",
"=",
"kwargs",
"[",
"\"index\"",
"]",
"=",
"tree",
".",
"using",
... | 46.431818 | 17.363636 |
def dnsrepr2names(x):
"""
Take as input a DNS encoded string (possibly compressed)
and returns a list of DNS names contained in it.
If provided string is already in printable format
(does not end with a null character, a one element list
is returned). Result is a list.
"""
res = []
... | [
"def",
"dnsrepr2names",
"(",
"x",
")",
":",
"res",
"=",
"[",
"]",
"cur",
"=",
"b\"\"",
"if",
"type",
"(",
"x",
")",
"is",
"str",
":",
"x",
"=",
"x",
".",
"encode",
"(",
"'ascii'",
")",
"while",
"x",
":",
"#l = ord(x[0])",
"l",
"=",
"x",
"[",
... | 30.193548 | 17.032258 |
def generate(data, dimOrder, maxWindowSize, overlapPercent, transforms = []):
"""
Generates a set of sliding windows for the specified dataset.
"""
# Determine the dimensions of the input data
width = data.shape[dimOrder.index('w')]
height = data.shape[dimOrder.index('h')]
# Generate the windows
return gene... | [
"def",
"generate",
"(",
"data",
",",
"dimOrder",
",",
"maxWindowSize",
",",
"overlapPercent",
",",
"transforms",
"=",
"[",
"]",
")",
":",
"# Determine the dimensions of the input data",
"width",
"=",
"data",
".",
"shape",
"[",
"dimOrder",
".",
"index",
"(",
"'... | 35.363636 | 19.181818 |
def write_bus_data(self, file):
""" Writes bus data to an Excel spreadsheet.
"""
bus_sheet = self.book.add_sheet("Buses")
for i, bus in enumerate(self.case.buses):
for j, attr in enumerate(BUS_ATTRS):
bus_sheet.write(i, j, getattr(bus, attr)) | [
"def",
"write_bus_data",
"(",
"self",
",",
"file",
")",
":",
"bus_sheet",
"=",
"self",
".",
"book",
".",
"add_sheet",
"(",
"\"Buses\"",
")",
"for",
"i",
",",
"bus",
"in",
"enumerate",
"(",
"self",
".",
"case",
".",
"buses",
")",
":",
"for",
"j",
",... | 37 | 11.375 |
def _get_view_result(view, raw_result, **kwargs):
""" Get view results helper. """
if raw_result:
return view(**kwargs)
if kwargs:
return Result(view, **kwargs)
return view.result | [
"def",
"_get_view_result",
"(",
"view",
",",
"raw_result",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"raw_result",
":",
"return",
"view",
"(",
"*",
"*",
"kwargs",
")",
"if",
"kwargs",
":",
"return",
"Result",
"(",
"view",
",",
"*",
"*",
"kwargs",
")",... | 28.625 | 13.875 |
def sentences(self, nb=3, ext_word_list=None):
"""
Generate an array of sentences
:example ['Lorem ipsum dolor sit amet.', 'Consectetur adipisicing eli.']
Keyword arguments:
:param nb: how many sentences to return
:param ext_word_list: a list of words you would like to h... | [
"def",
"sentences",
"(",
"self",
",",
"nb",
"=",
"3",
",",
"ext_word_list",
"=",
"None",
")",
":",
"return",
"[",
"self",
".",
"sentence",
"(",
"ext_word_list",
"=",
"ext_word_list",
")",
"for",
"_",
"in",
"range",
"(",
"0",
",",
"nb",
")",
"]"
] | 34.285714 | 17.285714 |
def readonce(self, size = None):
"""
Read from current buffer. If current buffer is empty, returns an empty string. You can use `prepareRead`
to read the next chunk of data.
This is not a coroutine method.
"""
if self.eof:
raise EOFError
if se... | [
"def",
"readonce",
"(",
"self",
",",
"size",
"=",
"None",
")",
":",
"if",
"self",
".",
"eof",
":",
"raise",
"EOFError",
"if",
"self",
".",
"errored",
":",
"raise",
"IOError",
"(",
"'Stream is broken before EOF'",
")",
"if",
"size",
"is",
"not",
"None",
... | 34.095238 | 15.238095 |
def advanced_search(self, terms, relation=None, index=0, limit=25, **kwargs):
"""
Advanced search of track, album or artist.
See `Search section of Deezer API
<https://developers.deezer.com/api/search>`_ for search terms.
:returns: a list of :class:`~deezer.resources.Resource` ... | [
"def",
"advanced_search",
"(",
"self",
",",
"terms",
",",
"relation",
"=",
"None",
",",
"index",
"=",
"0",
",",
"limit",
"=",
"25",
",",
"*",
"*",
"kwargs",
")",
":",
"assert",
"isinstance",
"(",
"terms",
",",
"dict",
")",
",",
"\"terms must be a dict\... | 47.210526 | 27.105263 |
def get_lines(self):
"""因为历史列表动态更新,需要刷新"""
self.lines = []
width = self.screen_width - 24
if self.state == 0:
# 播放列表
for index, i in enumerate(self.win.playlist):
line = i['title'] if len(i['title']) < width else i['title'][:width]
... | [
"def",
"get_lines",
"(",
"self",
")",
":",
"self",
".",
"lines",
"=",
"[",
"]",
"width",
"=",
"self",
".",
"screen_width",
"-",
"24",
"if",
"self",
".",
"state",
"==",
"0",
":",
"# 播放列表",
"for",
"index",
",",
"i",
"in",
"enumerate",
"(",
"self",
... | 42.377778 | 13.2 |
def search_lxc_bridges():
'''
Search which bridges are potentially available as LXC bridges
CLI Example:
.. code-block:: bash
salt '*' lxc.search_lxc_bridges
'''
bridges = __context__.get('lxc.bridges', None)
# either match not yet called or no bridges were found
# to handle ... | [
"def",
"search_lxc_bridges",
"(",
")",
":",
"bridges",
"=",
"__context__",
".",
"get",
"(",
"'lxc.bridges'",
",",
"None",
")",
"# either match not yet called or no bridges were found",
"# to handle the case where lxc was not installed on the first",
"# call",
"if",
"not",
"br... | 31.88 | 18.36 |
def execute_and_reset(
expr, params=None, scope=None, aggcontext=None, **kwargs
):
"""Execute an expression against data that are bound to it. If no data
are bound, raise an Exception.
Notes
-----
The difference between this function and :func:`~ibis.pandas.core.execute`
is that this functi... | [
"def",
"execute_and_reset",
"(",
"expr",
",",
"params",
"=",
"None",
",",
"scope",
"=",
"None",
",",
"aggcontext",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"result",
"=",
"execute",
"(",
"expr",
",",
"params",
"=",
"params",
",",
"scope",
"=",... | 32.44898 | 22.387755 |
def create(cls, name, enabled=True, superuser=True):
"""
Create a new API Client. Once client is created,
you can create a new password by::
>>> client = ApiClient.create('myclient')
>>> print(client)
ApiClient(name=myclient)
>>> client.change_pas... | [
"def",
"create",
"(",
"cls",
",",
"name",
",",
"enabled",
"=",
"True",
",",
"superuser",
"=",
"True",
")",
":",
"json",
"=",
"{",
"'enabled'",
":",
"enabled",
",",
"'name'",
":",
"name",
",",
"'superuser'",
":",
"superuser",
"}",
"return",
"ElementCrea... | 32.913043 | 13.608696 |
def int_to_date(date):
"""
Convert an int of form yyyymmdd to a python date object.
"""
year = date // 10**4
month = date % 10**4 // 10**2
day = date % 10**2
return datetime.date(year, month, day) | [
"def",
"int_to_date",
"(",
"date",
")",
":",
"year",
"=",
"date",
"//",
"10",
"**",
"4",
"month",
"=",
"date",
"%",
"10",
"**",
"4",
"//",
"10",
"**",
"2",
"day",
"=",
"date",
"%",
"10",
"**",
"2",
"return",
"datetime",
".",
"date",
"(",
"year"... | 21.7 | 16.1 |
def read(self):
"Connect to the feedback service and read all data."
log.msg('APNSService read (connecting)')
try:
server, port = ((FEEDBACK_SERVER_SANDBOX_HOSTNAME
if self.environment == 'sandbox'
else FEEDBACK_SERVER_HOSTNAME), FEEDBACK_SERVER_PORT)
... | [
"def",
"read",
"(",
"self",
")",
":",
"log",
".",
"msg",
"(",
"'APNSService read (connecting)'",
")",
"try",
":",
"server",
",",
"port",
"=",
"(",
"(",
"FEEDBACK_SERVER_SANDBOX_HOSTNAME",
"if",
"self",
".",
"environment",
"==",
"'sandbox'",
"else",
"FEEDBACK_S... | 39.8 | 19.8 |
def register_user(self, data):
""" Parses input and register user """
error = False
msg = ""
email_re = re.compile(
r"(^[-!#$%&'*+/=?^_`{}|~0-9A-Z]+(\.[-!#$%&'*+/=?^_`{}|~0-9A-Z]+)*" # dot-atom
r'|^"([\001-\010\013\014\016-\037!#-\[\]-\177]|\\[\001-011\013\014\0... | [
"def",
"register_user",
"(",
"self",
",",
"data",
")",
":",
"error",
"=",
"False",
"msg",
"=",
"\"\"",
"email_re",
"=",
"re",
".",
"compile",
"(",
"r\"(^[-!#$%&'*+/=?^_`{}|~0-9A-Z]+(\\.[-!#$%&'*+/=?^_`{}|~0-9A-Z]+)*\"",
"# dot-atom",
"r'|^\"([\\001-\\010\\013\\014\\016-\\... | 50.309091 | 27.763636 |
def generate_stack_policy_args(stack_policy=None):
""" Converts a stack policy object into keyword args.
Args:
stack_policy (:class:`stacker.providers.base.Template`): A template
object representing a stack policy.
Returns:
dict: A dictionary of keyword arguments to be used els... | [
"def",
"generate_stack_policy_args",
"(",
"stack_policy",
"=",
"None",
")",
":",
"args",
"=",
"{",
"}",
"if",
"stack_policy",
":",
"logger",
".",
"debug",
"(",
"\"Stack has a stack policy\"",
")",
"if",
"stack_policy",
".",
"url",
":",
"# stacker currently does no... | 35.92 | 22.16 |
def label_from_instance(self, obj):
"""
Create labels which represent the tree level of each node
when generating option labels.
"""
label = smart_text(obj)
prefix = self.level_indicator * getattr(obj, obj._mptt_meta.level_attr)
if prefix:
return '%s %... | [
"def",
"label_from_instance",
"(",
"self",
",",
"obj",
")",
":",
"label",
"=",
"smart_text",
"(",
"obj",
")",
"prefix",
"=",
"self",
".",
"level_indicator",
"*",
"getattr",
"(",
"obj",
",",
"obj",
".",
"_mptt_meta",
".",
"level_attr",
")",
"if",
"prefix"... | 35.2 | 12.6 |
def _get_closest_samp_num(self, ref_samp_num, start_test_samp_num):
"""
Return the closest testing sample number for the given reference
sample number. Limit the search from start_test_samp_num.
"""
if start_test_samp_num >= self.n_test:
raise ValueError('Invalid sta... | [
"def",
"_get_closest_samp_num",
"(",
"self",
",",
"ref_samp_num",
",",
"start_test_samp_num",
")",
":",
"if",
"start_test_samp_num",
">=",
"self",
".",
"n_test",
":",
"raise",
"ValueError",
"(",
"'Invalid starting test sample number.'",
")",
"ref_samp",
"=",
"self",
... | 37.181818 | 18.090909 |
def _remove_pre_formatting(self):
"""
Removes formatting tags added to pre elements.
"""
preformatted_wrappers = [
'pre',
'code'
]
for wrapper in preformatted_wrappers:
for formatter in FORMATTERS:
tag = FORMATTERS[form... | [
"def",
"_remove_pre_formatting",
"(",
"self",
")",
":",
"preformatted_wrappers",
"=",
"[",
"'pre'",
",",
"'code'",
"]",
"for",
"wrapper",
"in",
"preformatted_wrappers",
":",
"for",
"formatter",
"in",
"FORMATTERS",
":",
"tag",
"=",
"FORMATTERS",
"[",
"formatter",... | 31.7 | 16.6 |
def ip_v6(self) -> str:
"""Generate a random IPv6 address.
:return: Random IPv6 address.
:Example:
2001:c244:cf9d:1fb1:c56d:f52c:8a04:94f3
"""
ipv6 = IPv6Address(
self.random.randint(
0, 2 ** 128 - 1,
),
)
retu... | [
"def",
"ip_v6",
"(",
"self",
")",
"->",
"str",
":",
"ipv6",
"=",
"IPv6Address",
"(",
"self",
".",
"random",
".",
"randint",
"(",
"0",
",",
"2",
"**",
"128",
"-",
"1",
",",
")",
",",
")",
"return",
"str",
"(",
"ipv6",
")"
] | 22.785714 | 16.857143 |
def _processHandler(self, securityHandler, param_dict):
"""proceses the handler and returns the cookiejar"""
cj = None
handler = None
if securityHandler is None:
cj = cookiejar.CookieJar()
elif securityHandler.method.lower() == "token":
param_dict['token']... | [
"def",
"_processHandler",
"(",
"self",
",",
"securityHandler",
",",
"param_dict",
")",
":",
"cj",
"=",
"None",
"handler",
"=",
"None",
"if",
"securityHandler",
"is",
"None",
":",
"cj",
"=",
"cookiejar",
".",
"CookieJar",
"(",
")",
"elif",
"securityHandler",
... | 44.875 | 9.875 |
def setOpts(self, **opts):
"""
Changes the behavior of the SpinBox. Accepts most of the arguments
allowed in :func:`__init__ <pyqtgraph.SpinBox.__init__>`.
"""
#print opts
for k in opts:
if k == 'bounds':
#print opts[k]
... | [
"def",
"setOpts",
"(",
"self",
",",
"*",
"*",
"opts",
")",
":",
"#print opts",
"for",
"k",
"in",
"opts",
":",
"if",
"k",
"==",
"'bounds'",
":",
"#print opts[k]",
"self",
".",
"setMinimum",
"(",
"opts",
"[",
"k",
"]",
"[",
"0",
"]",
",",
"update",
... | 35.759259 | 15.277778 |
def rpc_get_account_at(self, address, block_height, **con_info):
"""
Get the account's statuses at a particular block height.
Returns the sequence of history states on success
"""
if not check_account_address(address):
return {'error': 'Invalid address', 'http_status'... | [
"def",
"rpc_get_account_at",
"(",
"self",
",",
"address",
",",
"block_height",
",",
"*",
"*",
"con_info",
")",
":",
"if",
"not",
"check_account_address",
"(",
"address",
")",
":",
"return",
"{",
"'error'",
":",
"'Invalid address'",
",",
"'http_status'",
":",
... | 42 | 22.173913 |
def ContainsAddressStr(self, address):
"""
Determine if the wallet contains the address.
Args:
address (str): a string representing the public key.
Returns:
bool: True, if the address is present in the wallet. False otherwise.
"""
for key, contra... | [
"def",
"ContainsAddressStr",
"(",
"self",
",",
"address",
")",
":",
"for",
"key",
",",
"contract",
"in",
"self",
".",
"_contracts",
".",
"items",
"(",
")",
":",
"if",
"contract",
".",
"Address",
"==",
"address",
":",
"return",
"True",
"return",
"False"
] | 30.714286 | 18.571429 |
def VectorLen(self, off):
"""VectorLen retrieves the length of the vector whose offset is stored
at "off" in this object."""
N.enforce_number(off, N.UOffsetTFlags)
off += self.Pos
off += encode.Get(N.UOffsetTFlags.packer_type, self.Bytes, off)
ret = encode.Get(N.UOffs... | [
"def",
"VectorLen",
"(",
"self",
",",
"off",
")",
":",
"N",
".",
"enforce_number",
"(",
"off",
",",
"N",
".",
"UOffsetTFlags",
")",
"off",
"+=",
"self",
".",
"Pos",
"off",
"+=",
"encode",
".",
"Get",
"(",
"N",
".",
"UOffsetTFlags",
".",
"packer_type"... | 41 | 17.888889 |
def compare_networks(self, other):
"""Compare two IP objects.
This is only concerned about the comparison of the integer
representation of the network addresses. This means that the
host bits aren't considered at all in this method. If you want
to compare host bits, you can ea... | [
"def",
"compare_networks",
"(",
"self",
",",
"other",
")",
":",
"if",
"self",
".",
"_version",
"<",
"other",
".",
"_version",
":",
"return",
"-",
"1",
"if",
"self",
".",
"_version",
">",
"other",
".",
"_version",
":",
"return",
"1",
"# self._version == o... | 36.58 | 18.28 |
def objective_bounds(self):
"""
Return objective bounds
Returns
-------
lower : list of floats
Lower boundaries for the objectives
Upper : list of floats
Upper boundaries for the objectives
"""
if self.ideal and self.nadir:
... | [
"def",
"objective_bounds",
"(",
"self",
")",
":",
"if",
"self",
".",
"ideal",
"and",
"self",
".",
"nadir",
":",
"return",
"self",
".",
"ideal",
",",
"self",
".",
"nadir",
"raise",
"NotImplementedError",
"(",
"\"Ideal and nadir value calculation is not yet implemen... | 23.947368 | 17.736842 |
def permissions(self, addr, permissions=None):
"""
Retrieve the permissions of the page at address `addr`.
:param addr: address to get the page permissions
:param permissions: Integer or BVV to optionally set page permissions to
:return: AST representing the pe... | [
"def",
"permissions",
"(",
"self",
",",
"addr",
",",
"permissions",
"=",
"None",
")",
":",
"out",
"=",
"self",
".",
"mem",
".",
"permissions",
"(",
"addr",
",",
"permissions",
")",
"# if unicorn is in play and we've marked a page writable, it must be uncached",
"if"... | 49.285714 | 22.285714 |
def until_synced(self, timeout=None):
"""Return a tornado Future; resolves when all subordinate clients are synced"""
futures = [r.until_synced(timeout) for r in dict.values(self.children)]
yield tornado.gen.multi(futures, quiet_exceptions=tornado.gen.TimeoutError) | [
"def",
"until_synced",
"(",
"self",
",",
"timeout",
"=",
"None",
")",
":",
"futures",
"=",
"[",
"r",
".",
"until_synced",
"(",
"timeout",
")",
"for",
"r",
"in",
"dict",
".",
"values",
"(",
"self",
".",
"children",
")",
"]",
"yield",
"tornado",
".",
... | 71.5 | 21.25 |
def groups_archive(self, room_id, **kwargs):
"""Archives a private group, only if you’re part of the group."""
return self.__call_api_post('groups.archive', roomId=room_id, kwargs=kwargs) | [
"def",
"groups_archive",
"(",
"self",
",",
"room_id",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"__call_api_post",
"(",
"'groups.archive'",
",",
"roomId",
"=",
"room_id",
",",
"kwargs",
"=",
"kwargs",
")"
] | 67 | 16 |
def quote_attrib(self, inStr):
"""
Transforms characters between xml notation and python notation.
"""
s1 = (isinstance(inStr, str) and inStr or
'%s' % inStr)
s1 = s1.replace('&', '&')
s1 = s1.replace('<', '<')
s1 = s1.replace('>', '>')
... | [
"def",
"quote_attrib",
"(",
"self",
",",
"inStr",
")",
":",
"s1",
"=",
"(",
"isinstance",
"(",
"inStr",
",",
"str",
")",
"and",
"inStr",
"or",
"'%s'",
"%",
"inStr",
")",
"s1",
"=",
"s1",
".",
"replace",
"(",
"'&'",
",",
"'&'",
")",
"s1",
"=",... | 30.294118 | 12.058824 |
def get_build_log_lines(self, project, build_id, log_id, start_line=None, end_line=None):
"""GetBuildLogLines.
Gets an individual log file for a build.
:param str project: Project ID or project name
:param int build_id: The ID of the build.
:param int log_id: The ID of the log fi... | [
"def",
"get_build_log_lines",
"(",
"self",
",",
"project",
",",
"build_id",
",",
"log_id",
",",
"start_line",
"=",
"None",
",",
"end_line",
"=",
"None",
")",
":",
"route_values",
"=",
"{",
"}",
"if",
"project",
"is",
"not",
"None",
":",
"route_values",
"... | 52.285714 | 19.892857 |
def set_sum_w2(self, w, ix, iy=0, iz=0):
"""
Sets the true number of entries in the bin weighted by w^2
"""
if self.GetSumw2N() == 0:
raise RuntimeError(
"Attempting to access Sumw2 in histogram "
"where weights were not stored")
xl = s... | [
"def",
"set_sum_w2",
"(",
"self",
",",
"w",
",",
"ix",
",",
"iy",
"=",
"0",
",",
"iz",
"=",
"0",
")",
":",
"if",
"self",
".",
"GetSumw2N",
"(",
")",
"==",
"0",
":",
"raise",
"RuntimeError",
"(",
"\"Attempting to access Sumw2 in histogram \"",
"\"where we... | 40.357143 | 7.214286 |
def create(self, username, password):
"""
Create Token by given username and password.
Authenticate user by given username and password.
Returning a :class:`Token` object contains username and token that you should pass to the all requests
(in X-TM-Username and X-TM-Key, respecti... | [
"def",
"create",
"(",
"self",
",",
"username",
",",
"password",
")",
":",
"data",
"=",
"dict",
"(",
"username",
"=",
"username",
",",
"password",
"=",
"password",
")",
"response",
",",
"instance",
"=",
"self",
".",
"request",
"(",
"\"POST\"",
",",
"sel... | 42.117647 | 22.705882 |
def ListDirectoryAbsolute(directory):
"""Yields all files in the given directory. The paths are absolute."""
return (os.path.join(directory, path)
for path in tf.io.gfile.listdir(directory)) | [
"def",
"ListDirectoryAbsolute",
"(",
"directory",
")",
":",
"return",
"(",
"os",
".",
"path",
".",
"join",
"(",
"directory",
",",
"path",
")",
"for",
"path",
"in",
"tf",
".",
"io",
".",
"gfile",
".",
"listdir",
"(",
"directory",
")",
")"
] | 50.25 | 4.25 |
def gzip_compress(data):
"""
Compress a string. Same as gzip.compress in Python3.
"""
buf = BytesIO()
with gzip.GzipFile(fileobj=buf, mode='wb') as fd:
fd.write(data)
return buf.getvalue() | [
"def",
"gzip_compress",
"(",
"data",
")",
":",
"buf",
"=",
"BytesIO",
"(",
")",
"with",
"gzip",
".",
"GzipFile",
"(",
"fileobj",
"=",
"buf",
",",
"mode",
"=",
"'wb'",
")",
"as",
"fd",
":",
"fd",
".",
"write",
"(",
"data",
")",
"return",
"buf",
".... | 26.625 | 12.375 |
def clean(self):
'''
Check if such an assignment configuration makes sense, and reject it otherwise.
This mainly relates to interdependencies between the different fields, since
single field constraints are already clatified by the Django model configuration.
'''
... | [
"def",
"clean",
"(",
"self",
")",
":",
"super",
"(",
"AssignmentAdminForm",
",",
"self",
")",
".",
"clean",
"(",
")",
"d",
"=",
"defaultdict",
"(",
"lambda",
":",
"False",
")",
"d",
".",
"update",
"(",
"self",
".",
"cleaned_data",
")",
"# Having valida... | 69.75 | 36.107143 |
def cortex_plot_colors(the_map,
color=None, cmap=None, vmin=None, vmax=None, alpha=None,
underlay='curvature', mask=None):
'''
cortex_plot_colors(mesh, opts...) yields the cortex colors as a matrix of RGBA rows for the
given mesh and options.
The followi... | [
"def",
"cortex_plot_colors",
"(",
"the_map",
",",
"color",
"=",
"None",
",",
"cmap",
"=",
"None",
",",
"vmin",
"=",
"None",
",",
"vmax",
"=",
"None",
",",
"alpha",
"=",
"None",
",",
"underlay",
"=",
"'curvature'",
",",
"mask",
"=",
"None",
")",
":",
... | 53 | 24.904762 |
def assoc(m, *args, **kw):
'''
assoc(m, k1, v1, k2, v2...) yields a map equivalent to m without the arguments k1, k2, etc.
associated with the values v1, v2, etc. If m is a mutable python dictionary, this is
equivalent to using m[k] = v for all the given key-value pairs then returning m itself. If m... | [
"def",
"assoc",
"(",
"m",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"if",
"len",
"(",
"args",
")",
"%",
"2",
"!=",
"0",
":",
"raise",
"ValueError",
"(",
"'assoc arguments must be given as key-value pairs'",
")",
"args",
"=",
"(",
"u",
"for",
"... | 48.673913 | 30.021739 |
def _set_information(self, v, load=False):
"""
Setter method for information, mapped from YANG variable /routing_system/ip/dhcp/relay/information (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_information is considered as a private
method. Backends looki... | [
"def",
"_set_information",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",
"ba... | 78.958333 | 38.208333 |
def _rfc822(date):
"""Parse RFC 822 dates and times
http://tools.ietf.org/html/rfc822#section-5
There are some formatting differences that are accounted for:
1. Years may be two or four digits.
2. The month and day can be swapped.
3. Additional timezone names are supported.
4. A default tim... | [
"def",
"_rfc822",
"(",
"date",
")",
":",
"daynames",
"=",
"set",
"(",
"[",
"'mon'",
",",
"'tue'",
",",
"'wed'",
",",
"'thu'",
",",
"'fri'",
",",
"'sat'",
",",
"'sun'",
"]",
")",
"months",
"=",
"{",
"'jan'",
":",
"1",
",",
"'feb'",
":",
"2",
","... | 31.892157 | 15.823529 |
def __updateJobResultsPeriodic(self):
"""
Periodic check to see if this is the best model. This should only have an
effect if this is the *first* model to report its progress
"""
if self._isBestModelStored and not self._isBestModel:
return
while True:
jobResultsStr = self._jobsDAO.j... | [
"def",
"__updateJobResultsPeriodic",
"(",
"self",
")",
":",
"if",
"self",
".",
"_isBestModelStored",
"and",
"not",
"self",
".",
"_isBestModel",
":",
"return",
"while",
"True",
":",
"jobResultsStr",
"=",
"self",
".",
"_jobsDAO",
".",
"jobGetFields",
"(",
"self"... | 37.288462 | 21.788462 |
def cartesian_product(parameter_dict, combined_parameters=()):
""" Generates a Cartesian product of the input parameter dictionary.
For example:
>>> print cartesian_product({'param1':[1,2,3], 'param2':[42.0, 52.5]})
{'param1':[1,1,2,2,3,3],'param2': [42.0,52.5,42.0,52.5,42.0,52.5]}
:param paramet... | [
"def",
"cartesian_product",
"(",
"parameter_dict",
",",
"combined_parameters",
"=",
"(",
")",
")",
":",
"if",
"not",
"combined_parameters",
":",
"combined_parameters",
"=",
"list",
"(",
"parameter_dict",
")",
"else",
":",
"combined_parameters",
"=",
"list",
"(",
... | 34.054545 | 26.727273 |
def getMd5Checksum(self):
"""
Returns the MD5 checksum for this reference set. This checksum is
calculated by making a list of `Reference.md5checksum` for all
`Reference`s in this set. We then sort this list, and take the
MD5 hash of all the strings concatenated together.
... | [
"def",
"getMd5Checksum",
"(",
"self",
")",
":",
"references",
"=",
"sorted",
"(",
"self",
".",
"getReferences",
"(",
")",
",",
"key",
"=",
"lambda",
"ref",
":",
"ref",
".",
"getMd5Checksum",
"(",
")",
")",
"checksums",
"=",
"''",
".",
"join",
"(",
"[... | 44.846154 | 16.692308 |
def save_model(self, path, output_format=None):
"""Save the :class:`pybel.BELGraph` using one of the outputs from
:py:mod:`pybel`
Parameters
----------
path : str
The path to output to
output_format : Optional[str]
Output format as ``cx``, ``pickl... | [
"def",
"save_model",
"(",
"self",
",",
"path",
",",
"output_format",
"=",
"None",
")",
":",
"if",
"output_format",
"==",
"'pickle'",
":",
"pybel",
".",
"to_pickle",
"(",
"self",
".",
"model",
",",
"path",
")",
"else",
":",
"with",
"open",
"(",
"path",
... | 37.095238 | 12.52381 |
def consistent_shuffle(*lists):
"""
Shuffle lists consistently.
Parameters
----------
*lists
Variable length number of lists
Returns
-------
shuffled_lists : tuple of lists
All of the lists are shuffled consistently
Examples
--------
>>> import mpu, random;... | [
"def",
"consistent_shuffle",
"(",
"*",
"lists",
")",
":",
"perm",
"=",
"list",
"(",
"range",
"(",
"len",
"(",
"lists",
"[",
"0",
"]",
")",
")",
")",
"random",
".",
"shuffle",
"(",
"perm",
")",
"lists",
"=",
"tuple",
"(",
"[",
"sublist",
"[",
"ind... | 24.64 | 18 |
def rot1(angle, form='c'):
"""Euler rotation about first axis
This computes the rotation matrix associated with a rotation about the first
axis. It will output matrices assuming column or row format vectors.
For example, to transform a vector from reference frame b to reference frame a:
Column V... | [
"def",
"rot1",
"(",
"angle",
",",
"form",
"=",
"'c'",
")",
":",
"cos_a",
"=",
"np",
".",
"cos",
"(",
"angle",
")",
"sin_a",
"=",
"np",
".",
"sin",
"(",
"angle",
")",
"rot_mat",
"=",
"np",
".",
"identity",
"(",
"3",
")",
"if",
"form",
"==",
"'... | 26.931818 | 22.318182 |
def to_text(self, digest, blob, mime_type):
"""Convert a file to plain text.
Useful for full-text indexing. Returns a Unicode string.
"""
# Special case, for now (XXX).
if mime_type.startswith("image/"):
return ""
cache_key = "txt:" + digest
text = ... | [
"def",
"to_text",
"(",
"self",
",",
"digest",
",",
"blob",
",",
"mime_type",
")",
":",
"# Special case, for now (XXX).",
"if",
"mime_type",
".",
"startswith",
"(",
"\"image/\"",
")",
":",
"return",
"\"\"",
"cache_key",
"=",
"\"txt:\"",
"+",
"digest",
"text",
... | 32.290323 | 15.677419 |
def cmd_as_file(cmd, *args, **kwargs):
"""Launch `cmd` and treat its stdout as a file object"""
kwargs['stdout'] = subprocess.PIPE
stdin = kwargs.pop('stdin', None)
if isinstance(stdin, basestring):
with tempfile.TemporaryFile() as stdin_file:
stdin_file.write(stdin)
stdi... | [
"def",
"cmd_as_file",
"(",
"cmd",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'stdout'",
"]",
"=",
"subprocess",
".",
"PIPE",
"stdin",
"=",
"kwargs",
".",
"pop",
"(",
"'stdin'",
",",
"None",
")",
"if",
"isinstance",
"(",
"s... | 35.111111 | 12.888889 |
def _advapi32_load_key(key_object, key_info, container):
"""
Loads a certificate, public key or private key into a Certificate,
PublicKey or PrivateKey object via CryptoAPI
:param key_object:
An asn1crypto.x509.Certificate, asn1crypto.keys.PublicKeyInfo or
asn1crypto.keys.PrivateKeyInfo... | [
"def",
"_advapi32_load_key",
"(",
"key_object",
",",
"key_info",
",",
"container",
")",
":",
"key_type",
"=",
"'public'",
"if",
"isinstance",
"(",
"key_info",
",",
"keys",
".",
"PublicKeyInfo",
")",
"else",
"'private'",
"algo",
"=",
"key_info",
".",
"algorithm... | 30.650602 | 23.39759 |
def geostatistical_prior_builder(pst, struct_dict,sigma_range=4,
par_knowledge_dict=None,verbose=False):
""" a helper function to construct a full prior covariance matrix using
a mixture of geostastical structures and parameter bounds information.
The covariance of parameter... | [
"def",
"geostatistical_prior_builder",
"(",
"pst",
",",
"struct_dict",
",",
"sigma_range",
"=",
"4",
",",
"par_knowledge_dict",
"=",
"None",
",",
"verbose",
"=",
"False",
")",
":",
"if",
"isinstance",
"(",
"pst",
",",
"str",
")",
":",
"pst",
"=",
"pyemu",
... | 43.804511 | 20.87218 |
def true_ces(subsystem, previous_state, next_state):
"""Set of all sets of elements that have true causes and true effects.
.. note::
Since the true |CauseEffectStructure| is always about the full system,
the background conditions don't matter and the subsystem should be
conditioned on ... | [
"def",
"true_ces",
"(",
"subsystem",
",",
"previous_state",
",",
"next_state",
")",
":",
"network",
"=",
"subsystem",
".",
"network",
"nodes",
"=",
"subsystem",
".",
"node_indices",
"state",
"=",
"subsystem",
".",
"state",
"_events",
"=",
"events",
"(",
"net... | 34.333333 | 21.208333 |
def _initialize_background(self):
"""Set up background state (zonal flow and PV gradients)."""
self.H = self.Hi.sum()
if np.asarray(self.U).ndim == 2:
self.Ubg = self.U * np.ones((self.ny))
else:
self.Ubg = np.expand_dims(self.U,axis=1) * np.ones((self.ny))
... | [
"def",
"_initialize_background",
"(",
"self",
")",
":",
"self",
".",
"H",
"=",
"self",
".",
"Hi",
".",
"sum",
"(",
")",
"if",
"np",
".",
"asarray",
"(",
"self",
".",
"U",
")",
".",
"ndim",
"==",
"2",
":",
"self",
".",
"Ubg",
"=",
"self",
".",
... | 39.688889 | 29.422222 |
def clmixhess(obj, exe, arg1, arg2, delta=DELTA):
"""
Returns numerical mixed Hessian function of given class method
with respect to two class attributes
Input: obj, general object
exe (str), name of object method
arg1(str), name of object attribute
arg2(str), name of ob... | [
"def",
"clmixhess",
"(",
"obj",
",",
"exe",
",",
"arg1",
",",
"arg2",
",",
"delta",
"=",
"DELTA",
")",
":",
"f",
",",
"x",
"=",
"get_method_and_copy_of_attribute",
"(",
"obj",
",",
"exe",
",",
"arg1",
")",
"_",
",",
"y",
"=",
"get_method_and_copy_of_at... | 38.628571 | 11.714286 |
def _check_value(self, ovsrec_row, column_value):
"""
:type column_value: tuple of column and value_json
"""
column, value_json = column_value
column_schema = ovsrec_row._table.columns[column]
value = ovs.db.data.Datum.from_json(
column_schema.type, value_json... | [
"def",
"_check_value",
"(",
"self",
",",
"ovsrec_row",
",",
"column_value",
")",
":",
"column",
",",
"value_json",
"=",
"column_value",
"column_schema",
"=",
"ovsrec_row",
".",
"_table",
".",
"columns",
"[",
"column",
"]",
"value",
"=",
"ovs",
".",
"db",
"... | 36.411765 | 11.705882 |
def delete_vault(self, vault_id):
"""Deletes a ``Vault``.
arg: vault_id (osid.id.Id): the ``Id`` of the ``Vault`` to
remove
raise: NotFound - ``vault_id`` not found
raise: NullArgument - ``vault_id`` is ``null``
raise: OperationFailed - unable to complete r... | [
"def",
"delete_vault",
"(",
"self",
",",
"vault_id",
")",
":",
"# Implemented from template for",
"# osid.resource.BinAdminSession.delete_bin_template",
"if",
"self",
".",
"_catalog_session",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_catalog_session",
".",
"del... | 53.678571 | 22.607143 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.