content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def deriv_MCP(w, alpha=1., g=3):
"""Derivative of the MCP, w > 0"""
return (w < alpha * g) * (alpha - w / g) | 0982f3354650d0cc5a9cbc14dbce9b007f56239b | 3,623,368 |
def bidirectional_rnn(cell_fw, cell_bw, inputs,
initial_state_fw=None, initial_state_bw=None,
dtype=None, sequence_length=None, scope=None):
"""Creates a bidirectional recurrent neural network.
Similar to the unidirectional case above (rnn) but takes input and builds
i... | 03c5901c6153863cbeab5331dbc2399dace443ca | 3,623,369 |
def get_colors():
"""
Returns a list of all the available color constants.
:rtype: list of :py:class:`Color`
"""
return GraphicsWindow.colors | 68b96a78c82b8fd2a2aafdecea5c7cc7427934d7 | 3,623,370 |
def area_circ(r_in):
"""Calculates the area of a circle with given radius.
:Input: The radius of the circle (float, >=0).
:Returns: The area of the circle (float)."""
if r_in < 0:
raise ValueError("The radius must be >= 0.")
area_out = np.pi * r_in**2
print("The area of a circle with ra... | 4748f2b161d80557243826e21ce8801c3a19f088 | 3,623,371 |
def _ve_pdg_format_ ( ve , latex = False ) :
"""Round value/error accoridng to PDG prescription and format it for print
@see http://pdg.lbl.gov/2010/reviews/rpp2010-rev-rpp-intro.pdf
@see section 5.3 of doi:10.1088/0954-3899/33/1/001
Quote:
The basic rule states that if the three highest orde... | 7ad0b158810aadcd34c39e5b9b5ee647e2fdabbd | 3,623,372 |
import re
def parse_stdout_data(stdout):
"""解析输出
Args:
stdout ([byte]): 标准输出
Returns:
[list]: 返回解析后的数据
"""
if stdout is None: #判断输出是否为None
return
pattern = r'[\r\n|\r|\n|=]' # 防止不同平台下回车不同,无法正确解析
res = re.split(pattern,stdout.decode('UTF-8').strip()) #依照回车分割字符串
... | 17f2c191c792ef473ff1c89829488ed1f119db29 | 3,623,373 |
def split(array, nrows, ncols):
"""Split a matrix into sub-matrices."""
return array.reshape(array.shape[1]//nrows, nrows, -1, ncols).swapaxes(1, 2) | a153ee015cd03b2cbc89d7e434a67bef3740237f | 3,623,374 |
async def push_status(req):
"""Push a status update to a job."""
data = req["data"]
if data["state"] == "error" and not data["error"]:
raise HTTPBadRequest(text="Missing error information")
try:
document = await get_data_from_req(req).jobs.push_status(
req.match_info["job_i... | 37ca34f64715405fc705ec71d11e9fa5996ff5e3 | 3,623,375 |
import dataclasses
def _remove_spans(node):
"""Return a new ``QASMNode`` with all spans recursively set to ``None`` to
reduce noise in test failure messages."""
if isinstance(node, list):
return [_remove_spans(item) for item in node]
if not isinstance(node, QASMNode):
return node
k... | 8dbc57c6a2440fac1b766f05adb2d59af3ec26ca | 3,623,376 |
def maskToOrignimalImg(img,mask):
"""add mask to color image"""
if img.shape != mask.shape:
#mask = expandImageTo3chan(mask)
img = expandImageTo3chan(img)
#print(img.shape,mask.shape)
return cv2.addWeighted(img, 1.0, mask, 0.8, 0) | 4afaadb0573a10fdcc60259f90fe3da15a480571 | 3,623,377 |
from typing import Iterable
def has_clockwise_orientation(vertices: Iterable['Vertex']) -> bool:
""" Returns True if 2D `vertices` have clockwise orientation. Ignores
z-axis of all vertices.
Args:
vertices: iterable of :class:`Vec2` compatible objects
Raises:
ValueError: less than 3 ... | 56b3f68f1362e05dfd34430a93eb09c625650fa2 | 3,623,378 |
import re
def parse_views(data):
"""parse view count to .views"""
m = re.search("videoPlayCount: \d+", data)
return int(m.group(0)[16:]) | ae297e0560826b5f036a25aeba98f4a894a58809 | 3,623,379 |
def row_to_dict():
"""Convert pyspark.Row to dict for easier unordered comparison"""
def func(row, recursive=True):
return row.asDict(recursive=recursive)
return func | ebc2395354d07a11895e7c85f0813279fea4630a | 3,623,380 |
def get_flask_celery_apps():
"""Call generate_context() and generate_config().
:return: First item is the Flask app instance, second is the Celery app instance.
:rtype: tuple
"""
config = generate_config()
flask_app = generate_context(config=config)
celery_app = flask_app.extensions['celery... | 960905c2f796cff8b54efa131a16469b615a9bef | 3,623,381 |
def is_type_bitfld(*args):
"""
is_type_bitfld(t) -> bool
See 'BT_BITFIELD' .
@param t (C++: type_t)
"""
return _ida_typeinf.is_type_bitfld(*args) | e85c9272ec85a81762f7c25daa59e46c9b1f9101 | 3,623,382 |
import re
from functools import reduce
import operator
import ast
def eval_function(dataset, function, functions):
"""Evaluate a given function on a dataset.
This function parses and evaluates a (possibly nested) function call,
returning its result.
"""
name, args = FUNCTION.match(function).grou... | 63f5faf34574e6d52b12930d98e728d6c519e8bb | 3,623,385 |
def RSI(data, period=14, price='close'):
"""
Relative Strength Index
RSI is a momentum oscillator that measures the speed and change of price movements.
RSI oscillates between zero and 100. Traditionally, and according to Wilder, RSI is considered overbought when
above 70 and oversold when below 3... | 061d925bc0ee62cfef9fabc7f1ccb5537d1248d9 | 3,623,386 |
def qrscaner():
"""Render template with QR scanner."""
title = 'Сканер'
return render_template(
'receipt/qrscaner.html',
page_title=title,
) | 3ce6ab1307c008383dace3a7549f3132e6c71b3b | 3,623,387 |
def ConvertVFSGRRClient(client):
"""Converts from `VFSGRRClient` to `rdfvalues.objects.ClientSnapshot`."""
snapshot = rdf_objects.ClientSnapshot(client_id=client.urn.Basename())
snapshot.filesystems = client.Get(client.Schema.FILESYSTEM)
snapshot.hostname = client.Get(client.Schema.HOSTNAME)
snapshot.fqdn = ... | 66172ec6d720f32cd1b26d17815564552a2e9936 | 3,623,389 |
from datetime import datetime
def validate_trigger(config: Config, trigger: client.models.v1_config_map.V1ConfigMap) -> bool:
"""Evaluate trigger ConfigMap age, returning True if valid."""
cm_ts = trigger.metadata.creation_timestamp.timestamp()
now = datetime.now().timestamp()
return cm_ts + config.tr... | 8a5c27faa33f723f5894b4ce9da07d669a53d5c2 | 3,623,390 |
def PrepareLocalPatches(manifest, patches):
"""Finish validation of parameters, and save patches to a temp folder.
Args:
manifest: The manifest object for the checkout in question.
patches: A list of user-specified patches, in project[:branch] form.
"""
patch_info = []
for patch in _CheckLocalPatches... | 181b0ace6b33c0c43914b5e0991b16d325e0bb4d | 3,623,391 |
def update_hsl_value(color, hue=None, sat=None, lum=None, inmodel=HSL, outmodel=HSL):
"""Change hue, saturation, or lumenosity of the color based on the
hue, sat, lum parameters provided.
Parameters:
color (Any):
The color
hue (int):
A number between 0 and 360.... | cf92fac981439ae9bcd96f71b506a4f2f1121426 | 3,623,392 |
def get_fits_image(fimage):
"""
reads fits image data and header
fimage: filename with or without extension
converts 32-bit floating values and 16-bit data to Python compatible values
reads also color images and transposes matrix to correct order
(normalizes images to +/- 1 range)
returns: i... | 83f59e30b69a3c483fb85e3dd7e129cae67f4dc6 | 3,623,393 |
def plot_histograms(ax, prng, nb_samples=10000):
"""Plot 4 histograms and a text annotation.
"""
params = ((10, 10), (4, 12), (50, 12), (6, 55))
for a, b in params:
values = prng.beta(a, b, size=nb_samples)
ax.hist(values, histtype="stepfilled", bins=30,
alpha=0.8)#, dens... | 887e4d1fafd6023767a7902b43b6356d807bd0ad | 3,623,395 |
def cleanup(wd, initdir, wrflag, rmwkdir):
""" cleanup function """
tolog("Overall cleanup function is called")
# collect any zombie processes
wd.collectZombieJob(tn=10)
tolog("Collected zombie processes")
# get the current work dir
wkdir = readStringFromFile(os.path.join(initdir, "CURRENT... | aa158af3939fae509f24b99c294c069e7b9dfe9b | 3,623,396 |
import tqdm
def generate_locations(
staypoints,
method="dbscan",
epsilon=100,
num_samples=1,
distance_metric="haversine",
agg_level="user",
print_progress=False,
):
"""
Generate locations from the staypoints.
Parameters
----------
staypoints : GeoDataFrame (as trackint... | 6ca7e5d31be1c8dda5edeedab4de7babe1a489bf | 3,623,398 |
def expand(im, filter_vec):
"""
Zero pads and blurs an image to expand it by 2
:param im: a grayscale image with double values in [0,1]
:param filter_vec: row vector of shape(1, filter_size) to blur with
:return: expanded image
"""
expanded_im = np.zeros((2 * im.shape[0], 2 * im.shape[1])) ... | 2252bc5a6f10fadd961008c62bcd3adf9256e512 | 3,623,399 |
def calc_f2_score(gt_bboxes_list, pred_bboxes_list, verbose=False):
"""
gt_bboxes_list: list of (N, 4) np.array in xywh format
pred_bboxes_list: list of (N, 5) np.array in conf+xywh format
"""
#f2s = []
f2_dict = {'f2':0, "P":0, "R": 0}
all_tps = [list([0] * 11) for _ in range(len(gt_bboxes... | fbc6e89bdd1555a3414c7ceb1d0653cb259256ee | 3,623,401 |
def decode(serialized_example):
"""
Parses an image and label from the given `serialized_example`
:param serialized_example:
:return:
"""
features = tf.parse_single_example(
serialized_example,
# Defaults are not specified since both keys are required.
features={
... | 8324094b768d849da16b82781b149ee827c9eae2 | 3,623,402 |
from datetime import datetime
def dateformated(x):
"""
===========================================================
dateformated(x)
===========================================================
this function converts the the date read from a list to a datetime format
input:
x is ... | ceee8998f5c381fcb4dc612e3f852f8c2a6862ab | 3,623,403 |
from Orange.widgets.utils.itemmodels import VariableListModel
def comboBox(
widget,
master,
value,
box=None,
label=None,
labelWidth=None,
orientation=Qt.Vertical,
items=(),
callback=None,
sendSelectedValue=False,
valueType=str,
emptyString=None,
editable=False,
... | 779a1f50e661fbf8ee5efe760bb34fec626658c2 | 3,623,404 |
def lowerbranch_subtract(X):
"""Function to subtract lower hysteresis branch from FORC magnetizations
Inputs:
H: Measurement applied field [float, SI units]
Hr: Reversal field [float, SI units]
M: Measured magnetization [float, SI units]
Fk: Index of measured FORC (int)
Fj: Index of giv... | 47f62298feec88cc4ab9424994016aa0b69f3cda | 3,623,405 |
def load_annotated_project(project_root_path):
"""
loads annotated symbols into a set of ModuleSymbols
:param project_root_path: symbols we will use to write out new source code
:return: set of ModuleSymbols objects
"""
return load_modules_into_module_symbol_objects(project_root_path,
... | 9d4dbd7c4bce81fb8364400faa998417109c359d | 3,623,406 |
def verify_annotation(ann_obj, projectconf):
"""
Verifies the correctness of a given AnnotationFile.
Returns a list of AnnotationIssues.
"""
issues = []
issues += verify_annotation_types(ann_obj, projectconf)
issues += verify_equivs(ann_obj, projectconf)
issues += verify_entity_overla... | 913658b75d64a161e17e256a72cb72458da9d8a6 | 3,623,407 |
def schedule_conv2d_nhwc_winograd_tensorcore_without_weight_transform(cfg, outs):
"""TOPI schedule callback"""
s = te.create_schedule([x.op for x in outs])
def _callback(op):
if "conv2d_nhwc_winograd" in op.tag:
schedule_nhwc_winograd_cuda(
cfg, s, op.output(0), use_tens... | 1ac825c61eee950bdba43c80c393519fd7234831 | 3,623,408 |
def encode_dataset(dataset, vocabulary):
"""Encode from strings to token ids.
Args:
dataset: a tf.data.Dataset with string values.
vocabulary: a mesh_tensorflow.transformer.Vocabulary
Returns:
a tf.data.Dataset with integer-vector values ending in EOS=1
"""
def encode(features):
return {k: vo... | 1631f760be39c786fe8d2f7eb5eba0a3b78b5079 | 3,623,409 |
from datetime import datetime
def now():
"""
Get current time.
:return: now as datetime with timezone
"""
return datetime.now(UTC) | 1653538681a2bcdadbab6d8ea9e909a47a98ba32 | 3,623,410 |
import typing
def CallGraphToFunctionCallCounts(g: nx.MultiDiGraph,) -> typing.Dict[str, int]:
"""Build a table of call counts for each function.
Args:
g: A call graph, such as produced by LLVM's -dot-callgraph pass.
See CallGraphFromDotSource().
Returns:
A dictionary where each function in the ... | 61a5080e48574c7f4d13d58f3d58b8220d0ee2a4 | 3,623,411 |
import logging
def decompose(args):
"""
Make a decomposition of the energy into some if its residue components.
"""
if args.resList is None:
msg = 'TERMINATED. List of residues not provided.'
logging.info(msg)
return None
gmx = search_commands(['gmx', 'gmx_mpi'], args.gmxE... | c384d760e215f07e0251f028908f4790c371fdf8 | 3,623,413 |
def define_generator(image_shape, n_resnet):
"""
Creates the generator
:param image_shape: shape of the input image
:param n_resnet: Number of resnet blocks
:return: generator model
"""
# Weight initialization
init = RandomNormal(stddev=0.02)
# Image input
in_image = Input(shape... | 2e24d70aff320cd282f3849e989f60adcc8ce950 | 3,623,414 |
def duplicates_allclose(dataframe, dcols, fcols):
"""Determine duplicates in dataframe based on tolerances
Args:
dataframe: the dataframe
dcols: the columns that are tested for exact duplicates
fcols: the columns that are checked for tolerance, dict with
tolerances
This is the si... | 53b70eb37d2c7ee61e8e66828b5e598915ddcc79 | 3,623,415 |
def get_topic_summary_by_id(topic_id, strict=True):
"""Returns a domain object representing a topic summary.
Args:
topic_id: str. ID of the topic summary.
strict: bool. Whether to fail noisily if no topic summary with the given
id exists in the datastore.
Returns:
Topic... | 34ed9e5e0cbdf8b2e06f2bcedb43c361ad56f063 | 3,623,417 |
def smoothing_Negative_rx0(MSK, Hobs, rx0max):
"""
This program use an opposite methode to the direct iterative method from
Martinho and Batteen (2006). This program optimizes the bathymetry for
a given rx0 factor by decreasing it.
Usage:
RetBathy = smoothing_Negative_rx0(MSK, Hobs, rx0max)
... | ac93c4b983780dc8eae524efc4d7b7b7d1ff650c | 3,623,418 |
def cgraphics_vec_to_RGBangle(source, w, h, cm, colorcorrect):
"""Pixelwise conversion of a 2D vectors to RGB angular image.
This is especially useful for optic-flow visualization.
Parameter
---------
source : numpy array [2 * dim_x * dim_y]
The 2D vector image of resolution dim_x x dim_y.... | ea4437a1355bcb254fabff4a85b9e0bdc5fc54fd | 3,623,419 |
def get_port():
"""Returns a port number."""
return 0 | 97259c825bbe41f47bd5bec81fedf24c5b19a547 | 3,623,420 |
def return_car_dict(car: Car):
"""
Returns a Car Object as dictionary
:param car: The car object being formatted
:return: Returns the car object formatted to return as dictionary
"""
riders = []
for rider in car.riders:
riders.append(rider.username)
return {
'id': car.id,... | 4bc9f15769db8564693b2396cef970c447a80729 | 3,623,421 |
def sort_unique(edges):
"""Make sure there are no duplicate edges and that for each
``coo_a < coo_b``.
"""
return tuple(sorted(
tuple(sorted(edge))
for edge in set(map(frozenset, edges))
)) | d4f4425b78baed6d822d5559787ced1653986761 | 3,623,422 |
def ext_subtable23(cxt: DecoderContext, fmt: Format):
""" EI | DI | SYSCALL | CLL | PUSHSP | POPSP | undef """
if fmt.lo5 == 0 and fmt.ext_hi5 == 0 and fmt.ext_lo5 == 0:
ff_hi = fmt[15:14]
ff_lo = fmt[13:11]
mnem = [[MNEM.DI] + [MNEM.UNDEF_CODE] * 3,
[MNEM.UNDEF_CODE] * 4... | 6b53cf2f29df6fb2f62d307ec72e3558afbc65dc | 3,623,423 |
def if_else(vector: np.ndarray) -> np.ndarray:
"""Copies vector but sets elements lower than 3 to 0
Parameters
----------
vector : np.ndarray
shape = (n, )
Returns
-------
np.ndarray
shape = (n, )
Examples
--------
>>> a = np.array([1, 2, 3, 4, 5, 6])
>>> i... | 039d2c6ead74af0d1d6536f1ec7c1969bb77d1ba | 3,623,424 |
def plot_roc_auc_f1(y_test, y_proba, title=None):
"""Plot ROC curve and random comparison, along with f1 and AUC metrics"""
std_f1 = f1_score(y_test, y_proba[:, 1] > 0.5)
fpr, tpr, _ = roc_curve(y_test, y_proba[:, 1])
auc_score = auc(fpr, tpr)
fig, axis = plt.subplots(figsize=(6, 6))
if title is... | 867a84a45eeeb0b2451b84252e313714d08b9ea4 | 3,623,426 |
def get_var_names(var_name):
"""Defines replacement dictionary for the bare variable name and
the names derived from it - the optimization flag and the identifier name.
"""
repl = dict()
repl['opt_var_name'] = "Opt_%s"%var_name
repl['id_var_name'] = "ID_%s"%var_name
repl['var_name'] = var_name
return... | 37999ffed0a0df1dbf736ada0cc355080dd9997f | 3,623,427 |
def hubble_parameter(z):
"""
It calculates the Hubble parameter at any redshift.
"""
part = np.sqrt(const.Omega0*(1.+z)**3+const.lam)
return const.H0 * part | a026648e2a14630e8121d27d7a3435bae55a4d5e | 3,623,429 |
import logging
def is_valid_snmp_v2_credential(credential):
"""check if credential is valid snmp v2 credential."""
if credential.keys() != SNMP_V2_CREDENTIALS.keys():
return False
if credential['version'] != '2c':
logging.error("The value of version in credential is not '2c'!")
ret... | 3adaf2eddc4c9afc9388e56f34c9d4d7afab171b | 3,623,431 |
from typing import Dict
from typing import Any
from typing import List
import json
def test_remove_existing_last_key(mocker):
"""
Given:
- a nonempty list with 1 value
- a key that exists in the list (the only one that exists)
When
- trying to remove the last key of the list
Th... | ccc1850aa17670d555308c0286dd8cdbdebb6a82 | 3,623,432 |
from emmaa.util import get_s3_client
from emmaa.model import save_config_to_s3
from emmaa.model_tests import ModelManager, save_model_manager_to_s3, \
def setup_bucket(
add_model=False, add_mm=False, add_tests=False,
add_results=False, add_model_stats=False, add_test_stats=False):
"""
This fun... | 3cf01e40dbcff44d1f91f324a4f81d7fe22f9427 | 3,623,433 |
def get_school_deadlines(college):
"""Get the admissions deadlines for the provided college."""
if college:
college = college.lower()
for deadline in DEADLINES:
if college in deadline.lower():
return statement(deadline)
return statement(
'Sorry, we are sti... | 8a1034f3e1275d6243feefeef9b058ed9c2d6f8b | 3,623,434 |
def function_grandkids_cell():
"""Returns string see usage"""
return "\n".join(["F1 is a function", "F1a is a function", "F1a1 is a function",
"F1 is composed of F1a", "F1a is composed of F1a1", "a is a data",
"F1a produces a", "b is a data", "F1a consumes b", "c is a... | 07b862cd5c5e02a90cba744d7182dab25994be1b | 3,623,435 |
def euclidean(matrix, vector, assure_consistency=False):
"""
Calculate inversed euclidean distance for all words in matrix against vector.
"""
if assure_consistency:
vector = _assure_consistency(matrix, vector)
inv_euc= 1/(1+matrix.subtract(vector).norm(axis=1))
return inv_euc.sort(ascen... | b31ec133957c555c8ce231f0ef0a99792ce0b502 | 3,623,436 |
def alfred_items_for_value(value):
"""
Given a Chinese language string, return a list of alfred items for each of the results
"""
index = 0
results = []
config_list = [
('t2s.json', u'繁體到簡體', 'SimplifiedChinese.png'),
('s2t.json', u'簡體到繁體', 'TraditionalChinese.png'),
('s... | 6f4437db0515e8464a235e59c5b4a3e26eaa5a44 | 3,623,437 |
import re
def preprocess_caption(row, mode):
"""Applies the selected preprocessing steps to the text.
Args:
row: A UTF-8 string.
mode: A string indicating the selected preprocessing strategy.
Valid values include: 'no_preprocessing' (no preprocessing),
'rm_all... | 68a3cad4e20ce5151cc7ed49b5de747b2a17cdcb | 3,623,438 |
def encode(val, base, minlen=0):
"""Returns the encoded string"""
code_string = get_code_string(base)
result = ""
while val > 0:
result = code_string[val % base] + result
val /= base
if len(result) < minlen:
result = code_string[0] * (minlen - len(result)) + result
return... | 772f787c915703cda7f7fb8f5942484ea6cbab6a | 3,623,439 |
from typing import List
from typing import Dict
import re
def parse_header_links(value: str) -> List[Dict[str, str]]:
"""
Returns a list of parsed link headers, for more info see:
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Link
The generic syntax of those is:
::
Link: < u... | 536d3f2b477666c076ac29312f3acfe63f40e324 | 3,623,440 |
import traceback
def main(testsuite_list, project_repository, data_repository,
auto_defects=False, ts_parallel=True):
"""Executes the list of testcases in parallel
Computes and returns the testsuite status"""
try:
project_status = execute_parallel_testsuites(testsuite_list, project_reposi... | 77542764fd46f57d420618fa747f3df8b09f0d4c | 3,623,441 |
import ast
from typing import List
def find_function_def_nodes(node: ast.Module) -> List[ast.FunctionDef]:
"""Finds ast.FunctionDef nodes in the source code. ast.FunctionDef
represents `def function_name(....):` statement in the code.
Args:
node: a root node of the AST tree, this node should be a... | 1bed6da5705da11d614210de453bee6edae11941 | 3,623,442 |
def parseFloat(value, ret=0.0):
"""
Parses a value as float.
This function works similar to its JavaScript-pendant, and performs
checks to parse most of a string value as float.
:param value: The value that should be parsed as float.
:param ret: The default return value if no integer could be pa... | 6828cc19882dcbfcf7b83781b1e79a6014034cad | 3,623,443 |
import requests
import json
def metadataview(request, container, objectname=None):
""" Return object/container/pseudofolder metadata. """
storage_url = get_endpoint(request, 'adminURL')
headers = {'X-Storage-Token': get_token_id(request)}
url = '{0}/{1}'.format(storage_url, container)
if objectn... | 82af25a85f89db5464bac5869dfa05480053c6b2 | 3,623,444 |
def count_call_alleles(ds: Dataset, merge: bool = True) -> Dataset:
"""Compute per sample allele counts from genotype calls.
Parameters
----------
ds : Dataset
Genotype call dataset such as from
`sgkit.create_genotype_call_dataset`.
merge : bool, optional
If True (the defaul... | 904235b56f0bc87c809e41c7f3fcaee85da5bf1f | 3,623,445 |
from typing import Concatenate
def dense_block(x, n_filters):
""" Construct a Densely Connected Residual Block
x : input to the block
n_filters: number of filters in convolution layer in residual block
"""
# Remember input tensor into residual block
shortcut = x
# BN-R... | 59d5d05b69756367f0ed4e24544ea58ff3afbae9 | 3,623,446 |
def get_fetcher(conf: MappingNode, build_dir: str, generator: ninja_syntax.Writer):
"""Construct and return RepoFetcher object"""
return RepoFetcher(conf, build_dir, generator) | afc4efeb39a03a63e25b7eba840bd532db59b05d | 3,623,447 |
def text_box_search_folder(path, tag, search_term):
"""applies the text_box_search() method to a full folder
Arguments: path [string]: absolute of relative path to folder
tag [string]: element type
search_term[string]: search term to find element
Returns: [named tuples]:
... | 58835459faf37ddc5ec85e8cd0ef29604ef6c235 | 3,623,448 |
def discard_inserted_documents(error_documents, original_documents):
"""Discard any documents that have already been inserted which are violating index constraints
such documents will have an error code of 11000 for a DuplicateKey error
from https://github.com/mongodb/mongo/blob/master/src/mongo/base/... | 9d7d47a0ade2300449a7f1a4a20c3a70f6dce583 | 3,623,449 |
def include_amp_css(path: str):
""" Inserts CSS content into a Django template, stripping illegal CSS rules and keywords. """
actual_path = finders.find(path)
with open(actual_path, 'r', encoding='UTF-8') as f:
content = f.read()
content = content.replace('!important', '')
return mar... | 45202a6dcfc894c72aabfa5c1b07ed9cd36a5c86 | 3,623,450 |
def get_target_no_match(mirna_sequence, length):
"""Given a miRNA sequence, return a random target sequence without 4 nt of contiguous pairing"""
rc = rev_comp(mirna_sequence[1:8]) + 'A'
off_limits = [rc[ix:ix + 4] for ix in range(5)]
while True:
target = generate_random_seq(length)
keep... | 2bd6e5fd226e21ff955f0f4f7ec30c8fbc54f887 | 3,623,451 |
def list_folder(drive, folder_id):
"""
Lists contents of a GoogleDriveFile that is a folder
:param drive: Drive object to use for getting folders
:param folder_id: The id of the GoogleDriveFile
:return: The GoogleDriveList of folders
"""
_q = {'q': "'{}' in parents and trashed=false".format(... | 1ea5837d6096f2f9c1f0485d5a02bd43a8b8c55e | 3,623,452 |
def media_100_fixture():
"""Load media payload for item 100 and return it."""
return load_fixture("plex/media_100.xml") | 8b9f7a76b9a16cb15cc5d8c7ee48f28de45d8f5d | 3,623,453 |
import re
def normalize_place_name(value):
"""Quick and dirty conversion of common verbiage around placenames"""
query_value = value
query_value = re.sub(r"^Place \w+:", "", query_value)
query_value = re.sub(r"^Cultural Place:", "", query_value)
query_value = query_value.strip()
return query_... | 790110ff9381cdce69caffc14362f61936c36cb4 | 3,623,456 |
def plot_calibration_curve(y_true, y_pred_prob, model_name, title, n_bins=5, normalize=False):
"""
Returns a matplotlib figure containing the plotted calibration plot.
Args:
y_true: array-like of shape (n_samples,) of true target
y_pred_prob: array-like of shape (n_samples,) probabiliti... | 3f1d5e20c61ea675e81372c1d3b9471c6e7d7979 | 3,623,457 |
from typing import List
from typing import Optional
from typing import Union
from typing import Tuple
from typing import Set
from typing import Dict
from typing import Callable
from typing import Any
def boxplot(
df: DataFrame,
groupby: List[str],
metrics: List[str],
whisker_type: PostProcessingBoxplo... | 7bead51525f95f59a31de626976e232c387c31dd | 3,623,458 |
def pow_mid(p, max_denom=1024):
""" Return (x,1,t) power tuple
t <= x^p 1^(1-p)
user wants the epigraph variable t
"""
assert 0 < p < 1
p = Fraction(p).limit_denominator(max_denom)
return p, (p, 1-p) | 0393aed017a8d7a41388ee2b185f8f708b8a880c | 3,623,459 |
def search_vulnerabilities_version(word_list, db_table):
"""
Search vulnerabilities for version number.
:param word_list: the list of words searched by the user.
:param db_table: the database table in which perform the search.
:return: the list containing the results of the performed search.
"""... | e6995b9fa01e20cdd250c1784ce17aaa29db1168 | 3,623,460 |
import struct
def htons(cpu_context, func_name, func_args):
"""
Convert the provided 16-bit number in host byte order (little-endian) to network byte order (big-endian)
"""
le_port = func_args[0]
port_data = struct.pack("<H", le_port)
return struct.unpack(">H", port_data)[0] | 095be37630fbe0dc86ea5e731180249c29ccac85 | 3,623,461 |
def _split_columns(df, columns, delimiter, converter=identity):
"""Split column string values into tuples with the given delimiter."""
return df.update_columns(
**{column: ignoring_exceptions(lambda s: tuple(converter(x) for x in s.split(delimiter)), (), (AttributeError)) for column in make_iterable(col... | fac76750bca4952c9ba8aff26b056c5554bbe076 | 3,623,463 |
def read_well_list(stream):
"""Read the well-list."""
retval = {}
for line in stream:
line = line.rstrip()
if line.startswith("Row"):
continue
tokens = line.split("\t")
wbc = tokens[5]
retval[wbc] = {
"row": tokens[0],
"column": tok... | 65b1782a76c5eddb88a6e6491a72fd2f93d56076 | 3,623,464 |
def bayes_compare_language(l1, l2, ngram_range=(1, 3), prior=.01, cv=None, counts_mat=None):
"""
Parameters
----------
l1, l2 : Iterable[str]
list of strings from each language sample
ngram_range : Tuple[int, int], default=(1,3)
an integer describing up to what n-gram you want to co... | d3f47e41e48618f634dd60bc9606d5a127cd370c | 3,623,465 |
import re
def find_asn(string: str):
"""
Returns a autonomous system number or None
:param str string: String
:return: int or None
"""
match = re.search(PATTERN_ASN, string)
if match:
return int(match.group(1))
return None | 1a5eade84a7960523197254160b2ce606ce4997d | 3,623,466 |
import imp
import uuid
def load_solvers(path):
"""Load a suite of solvers."""
logger.info("loading solver suite from %s", path)
return imp.load_source("borg.suite_{0}".format(uuid.uuid4().hex), path) | 4e7a7f804e31fe6ea3d907d8f47b0940cfa43f35 | 3,623,467 |
def cross_derivative(expr, dims, fd_order, deriv_order, **kwargs):
"""
Arbitrary-order cross derivative of a given expression.
Parameters
----------
expr : expr-like
Expression for which the cross derivative is produced.
dims : tuple of Dimension
Dimensions w.r.t. which to diffe... | 07574280f6ef0c8e1393db781506a008b90245db | 3,623,468 |
def starting_node_random_walk(bipartite,weights_x, min_weight=100, max_dim=10 ):
"""
Sample random node in X (from bipartite graph X-Y) with the restriction that it does not connect to more
than "max_dim" nodes in Y and that its weight is more than "min_weight"
Parameters
----------
bipartite :... | 7c8a54fa376823d6bb9b2d4c8c641f8e120fc247 | 3,623,469 |
def play_marbles(players, start_marble, limit_points):
"""Play marbles with number of players and limit_points."""
cur_marble = start_marble
cur_points = 1
cur_player = 0
while cur_points <= limit_points:
if cur_points % 23 == 0:
for _ in range(7):
cur_marble = cu... | 06bae200c7b1763c68304442e592f1ef44d8618f | 3,623,470 |
import json
import re
def get_extension_name(id: str, version: str) -> str:
"""Returns the 'name' of a Chrome extension by finding the correct source.
Args:
id: An extension identifier string.
version: The extension version that is used to search file paths.
Returns:
A string for... | d953c5bcd7150a2f9e41dfab7c79e3ae940c4ca2 | 3,623,471 |
import json
from datetime import datetime
def filter_data(data):
""" Setup the filter in use by the listen() function. It will take the rsvp event JSON string,
and return a JSON string subset of that data.
:param: json string
:return: json string
"""
try:
result = json.dumps({
... | f32c6f7907fd6dd64fac443c459864cd62bb737f | 3,623,473 |
from typing import OrderedDict
def _to_distiller_modulelist(model):
"""Replaces all instances of torch.nn.ModuleList in a model with DistillerModuleList instances
Args:
model (torch.nn.Module): Model to convert
"""
def convert_container(container):
# To maintain a similar order of reg... | 6a37737dae923c418d3931994f5dd0467abe0b75 | 3,623,474 |
from typing import Any
def noted_under(key: str) -> Any:
"""Gets a noted value from the director.
Examples::
the_actor.should(
See.the(
Text.of_the(WELCOME_MESSAGE), ContainsTheText(noted_under("first name"))
),
)
"""
try:
return Direct... | c598c33d8bd505a338d17ee90dbb8dd84fce35ab | 3,623,475 |
def department_page(school_name):
""" Renders the page where the user selects their department. """
school = School.query.filter(School.name == school_name).first()
if school is None:
return default_error, 400
return render_template('departments.html', departments=school.departments.all()) | 9871cf587f9310015be06305dd0cfd55d4ecb090 | 3,623,476 |
def add_feat_data_to_array(all_data, new_data, feat_pd_names, feat_name, params):
"""
Update all_data array by appending the new data. The new data contains the data from all freq bands
Syntax: all_data = add_feat_data_to_array(all_data, new_data, feat_pd_names, feat_name, params)
Inputs:
all_... | bb7e20ff0e0468442adc0e5600dc165bbf18bade | 3,623,478 |
def distance_matrix_dict_fixture():
"""The expected distances between the example cities defined in tests/conftest.py"""
return {
'euclidean': np.array([
[0, 1118, 2236],
[1118, 0, 1118],
[2236, 1118, 0]
]),
'manhattan': np.array([
[0, 1500... | 165c2cbd25f8e6659fc25a76489c37e72b3bd14e | 3,623,479 |
def get_global_config_definition(context, config, value):
"""Get config definitions included with Mycroft.
Arguments:
context: behave test context
config: config value to fetch from the file
value: predefined value to fetch
Returns:
Patch dictionary or None.
"""
con... | 883bbc2cca021ac3bbed6f923c8b948ea83f4800 | 3,623,480 |
import numpy as np
import xarray as xr
def interp_sw_levels_xr(sw_xr_var):
"""takes swoosh data xarray Dataarray (one var) and interpolate it
vertically to MERRA GCM pressure levels"""
# *levels is other optional pressure levels
MERRA_levels = np.array([3.00000000e+02, 2.50000000e+02, 2.00000000e... | 255a93e69965fb24a7039cad57d919766a8d5a1e | 3,623,481 |
def ordinal_number(n: int):
"""
Returns a string representation of the ordinal number for `n`
e.g.,
>>> ordinal_number(1)
'1st'
>>> ordinal_number(4)
'4th'
>>> ordinal_number(21)
'21st'
"""
# from https://codegolf.stackexchange.com/questions/4707/outputting-ordinal-numbers-1... | 9cb2b333cfe7d4e7b115d21d9d3c1bbaec02cdd9 | 3,623,482 |
def rgamma(alpha, beta, size=None):
"""
Random gamma variates.
"""
return np.random.gamma(shape=alpha, scale=1. / beta, size=size) | c7985db1be3e979d793f90ff4eea6845853c4684 | 3,623,483 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.