content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def mean_IoU(Y_true, Y_pred):
"""
Calculate the mean IoU score between two lists of labeled masks.
:param Y_true: a list of labeled masks (numpy arrays) - the ground truth
:param Y_pred: a list labeled predicted masks (numpy arrays) for images with the original dimensions
:return: mean IoU score for... | 79581b1015512653f428a93c0e61cd5d451f031e | 32,829 |
def get_matrix_header(filename):
"""
Returns the entries, rows, and cols of a matrix market file.
"""
with open(filename) as f:
entries = 0
rows = 0
cols = 0
for line in f.readlines():
if line.startswith('%'):
continue
line = line.s... | 66200661715cb9a67522ced7b13d4140a3905c28 | 32,830 |
def get_slot_names(slotted_instance):
"""Get all slot names in a class with slots."""
# thanks: https://stackoverflow.com/a/6720815/782170
return slotted_instance.__slots__ | bd0f5b58964444396ceae7facb916012a4fb7c8a | 32,831 |
def make_standard_fisher_regularizer(make_logits, scope, should_regularize,
perturbation, differentiate_probability):
"""Creates per-example logits and the per-example standard Fisher-Rao norm.
This function assumes the model of a categorical distribution generated by a
softm... | b8edc41ccce39511e147fdfeb919c30ad65e8a85 | 32,832 |
def objective(y_objective, sim_param, curve_param):
"""
Calculates the objective function (RMS-VIF) given the control point y-values of a given particle
:param y_objective: control point y-values of the particle
:param sim_param: Instance of sim_param
:param curve_param: Instance of curve_param
... | 8191aa0cc346ea596c88d3cdff86c3a3abc3ccca | 32,833 |
def shortest_first_name(names):
"""Returns the shortest first name (str)"""
names = dedup_and_title_case_names(names)
name_dict = []
for i in names:
i = i.split()
name_dict.append({'name':i[0], 'surname': i[1]})
short_name_sort = sorted(name_dict, key=lambda k: len(k['name']))
re... | 868d5d977d4ef3aa4264fa1644ca5f142920bbe4 | 32,835 |
def timezone_validator(self, response):
"""Match timezone code in libraries/timezone.
Arguments
---------
response: "String containing current answer"
Raises
------
ValidationError: "Display a short description with available formats"
Returns
-------
boolean: True
... | 080e56256a72a254e1c5940d16a5a89b693a3ad6 | 32,836 |
def reset_clb_srv(req):
"""
Service when reset of state planner
:param req:
:return:
"""
global reset_pose, pose_msgs , goal_sub, global_offset
rospy.loginfo_once("reset pose")
resp = TriggerResponse()
resp.success = True
resp.message = "Reset pose: True"
reset_pose = pose... | 14deae77fd35fa256760164978eacf7cee1421ad | 32,837 |
import tkinter
def Calcola():
"""Calcolate point of task!"""
esci=False
while esci is False:
try:
check=False
while check is False:
DeadLine=input("inserisci la deadline in giorni ")
try:
DeadLine = int(DeadLine)
... | 7f9d03a2c45a3dd06172368213000c38ffa6532d | 32,838 |
import six
def disabled(name):
"""
Ensure an Apache module is disabled.
.. versionadded:: 2016.3.0
name
Name of the Apache module
"""
ret = {"name": name, "result": True, "comment": "", "changes": {}}
is_enabled = __salt__["apache.check_mod_enabled"](name)
if is_enabled:
... | edc69d3ad8b03c739a01e28d50aacbf00db54d9c | 32,839 |
def get_stops_in_polygon(feed, polygon, geo_stops=None):
"""
Return the slice of ``feed.stops`` that contains all stops that lie
within the given Shapely Polygon object that is specified in
WGS84 coordinates.
Parameters
----------
feed : Feed
polygon : Shapely Polygon
Specified ... | cf42652a1a00f9f70f51d5bc9597733ca9d89cf6 | 32,840 |
def define_stkvar(*args):
"""
define_stkvar(pfn, name, off, flags, ti, nbytes) -> bool
Define/redefine a stack variable.
@param pfn: pointer to function (C++: func_t *)
@param name: variable name, NULL means autogenerate a name (C++: const
char *)
@param off: offset of the stack variabl... | bbd52e35a92dcd84afe990e0519a2a5e26abe5b8 | 32,841 |
def spherical_polar_area(r, lon, lat):
"""Calculates the area bounding an array of latitude and longitude points.
Parameters
----------
r : float
Radius of sphere.
lon : 1d array
Longitude points. [Degrees]
lat : 1d array
Longitude points. [Degrees]
Returns
----... | a07b73f6e04ee64b06d1e663dfff7ff971d00bf5 | 32,842 |
def row_plays(hand, row):
"""Return the set of legal plays in the specified row.
A row play is a (start, 'WORD') pair,
"""
results = set()
# for each anchor and for each legal prefix, add all legal suffixes and save any valid words in results
for (i, square) in enumerate(row[1: -1], start=1):
... | 5b98f30fb8a932f31bc9bc0b22f21480880c3302 | 32,843 |
def nearest_pillar(grid, xy, ref_k0 = 0, kp = 0):
"""Returns the (j0, i0) indices of the primary pillar with point closest in x,y plane to point xy."""
# note: currently works with unmasked data and using primary pillars only
pe_i = grid.extent_kji[2] + 1
sum_dxy2 = grid.pillar_distances_sqr(xy, ref_k0... | 2338698963cb6bddca8d9702e000e5be125e6e86 | 32,844 |
def read_state(file, statename):
""" read and select state from file
Args:
file (str): path to state shapefile
statename (str): name of state (i.e. California)
"""
all = gpd.read_file("../data/states.shp")
state = all[all['STATE_NAME'] == statename]
return state | 0732d01dfb466ac00622964dfd3a9d0655367fbf | 32,845 |
def get_random_state(seed):
"""
Get a random number from the whole range of large integer values.
"""
np.random.seed(seed)
return np.random.randint(MAX_INT) | abf99c5547d146bfc9e6e1d33e7970d7090ba6d2 | 32,846 |
def get_start_and_end_time(file_or_file_object):
"""
Returns the start and end time of a MiniSEED file or file-like object.
:type file_or_file_object: str or file
:param file_or_file_object: MiniSEED file name or open file-like object
containing a MiniSEED record.
:return: tuple (start time... | 4c094a8fb1d9e186a0bbcbff25b7af8ac5461131 | 32,847 |
from typing import Optional
import json
import asyncio
async def send_message(msg: str) -> Optional[str]:
"""
Send a message to the websocket and return the response
Args:
msg: The message to be sent
Returns:
The response message or None if it was not defined
"""
if not (WS a... | d6395c3f74baf1900d99f605a08b77990637be8e | 32,848 |
def _getname(storefile):
"""returns the filename"""
if storefile is None:
raise ValueError("This method cannot magically produce a filename when given None as input.")
if not isinstance(storefile, basestring):
if not hasattr(storefile, "name"):
storefilename = _getdummyname(store... | fa423102a3ff8355af4784eaa39b2a065da80ec4 | 32,849 |
def flow_lines(sol, nlines, time_length, scale=0.5):
"""
compute the flow lines of the solution
Parameters
----------
sol : :py:class:`Simulation<pylbm.simulation.Simulation>`
the solution given by pylbm
nlines : int (number of flow lines)
time_length : double (time during which we ... | fea6667aa8b3012918a66ae3f6e94b9b0a4439ad | 32,850 |
def minOperations(n):
""" finds min. operations to reach and string """
if type(n) != int or n <= 1:
return 0
res = 0
i = 2
while(i <= n + 1):
if (n % i == 0):
res += i
n /= i
else:
i += 1
return res | c26cbd71c6e675adea79938b6e7248a4c093e63f | 32,851 |
def matrix2dictionary(matrix):
"""
convert matrix to dictionary of comparisons
"""
pw = {}
for line in matrix:
line = line.strip().split('\t')
if line[0].startswith('#'):
names = line[1:]
continue
a = line[0]
for i, pident in enumerate(line[1:]... | fd53dc4f80ff45d4eb41939af54be1d712ee2fa4 | 32,852 |
def combine_fastq_output_files(files_to_combine, out_prefix, remove_temp_output):
""" Combines fastq output created by BMTagger/bowtie2 on multiple databases and
returns a list of output files. Also updates the log file with read counts for the
input and output files.
"""
# print out the read... | 1421878edf7e44b46b386d7d4465090cc22acfa4 | 32,853 |
import json
def deliver_dap():
"""
Endpoint for submissions only intended for DAP. POST request requires the submission JSON to be uploaded
as "submission" and the filename passed in the query parameters.
"""
logger.info('Processing DAP submission')
filename = request.args.get("filename")
... | e7c2753319f512eaa1328fcb3cc808a17a5933b8 | 32,854 |
def api_run_delete(run_id):
"""Delete the given run and corresponding entities."""
data = current_app.config["data"] # type: DataStorage
RunFacade(data).delete_run(run_id)
return "DELETED run %s" % run_id | c2a07caa95d9177eb8fe4b6f27caf368d1a9fbdd | 32,855 |
import numpy
def gfalternate_createdataandstatsdict(ldt_tower,data_tower,attr_tower,alternate_info):
"""
Purpose:
Creates the data_dict and stat_dict to hold data and statistics during gap filling from
alternate data sources.
Usage:
Side effects:
Called by:
Calls:
Author: PRI
... | a1690fb9e53abcd6b23e33046d82c10a2ca7abc0 | 32,856 |
import re
def doGeneMapping(model):
"""
Function that maps enzymes and genes to reactions
This function works only if the GPR associations are defined
as follows: (g1 and g2 and g6) or ((g3 or g10) and g12)
- *model* Pysces model
- *GPRdict* dictionary with ... | d2e12f7161aca69afa28f7bb0d528d9b922b25b4 | 32,857 |
def delay_to_midnight():
"""Calculates the delay between the current time and midnight"""
current_time = get_current_time()
delay = time_conversions.hhmm_to_seconds("24:00") - time_conversions.hhmm_to_seconds(current_time)
return delay | 14b33591e58975cd5a4f95d3602e6a1494131267 | 32,858 |
def predict(model, imgs):
"""
Predict the labels of a set of images using the VGG16 model.
Args:
imgs (ndarray) : An array of N images (size: N x width x height x channels).
Returns:
preds (np.array) : Highest confidence value of the predictio... | 0f992412a9067608e99a6976c6ef65b466ef7572 | 32,859 |
def _endmsg(rd) -> str:
"""
Returns an end message with elapsed time
"""
msg = ""
s = ""
if rd.hours > 0:
if rd.hours > 1:
s = "s"
msg += colors.bold(str(rd.hours)) + " hour" + s + " "
s = ""
if rd.minutes > 0:
if rd.minutes > 1:
s = "s"
... | 635792c4ebf772926f492e5976ee4ac7caf92cca | 32,861 |
import bz2
import zlib
import lzma
def decompress(fcn):
"""Decorator that decompresses returned data.
libmagic is used to identify the MIME type of the data and the function
will keep decompressing until no supported compression format is identified.
"""
def wrapper(cls, raw=False, *args, **kw):
... | ba5d1540da70c4f92604888f5fd10b879bd62371 | 32,862 |
def get_satellite_params(platform=None):
"""
Helper function to generate Landsat or Sentinel query information
for quick use during NRT cube creation or sync only.
Parameters
----------
platform: str
Name of a satellite platform, Landsat or Sentinel only.
params
"""
... | 2298c100eed431a48a9531bc3038c5ab8565025d | 32,863 |
import random
def generate_random_token(length = 64):
""" Generates a random token of specified length.
"""
lrange = 16 ** length
hexval = "%0{}x".format(length)
return hexval % (random.randrange(lrange)) | 5140dc2a07cb336387fd3e71b3b1edc746cccb44 | 32,864 |
from typing import Optional
from typing import Union
from typing import Tuple
def permute_sse_metric(
name: str,
ref: np.ndarray,
est: np.ndarray,
compute_permutation: bool = False,
fs: Optional[int] = None) -> Union[float, Tuple[float, list]]:
"""
Computation of SiSNR/... | 4e6398852231fa74b8999158dc5f20833f53643b | 32,866 |
from typing import Literal
def test_if() -> None:
"""if-elif-else."""
PositiveOrNegative = Literal[-1, 0, 1]
def positive_negative(number: int) -> PositiveOrNegative:
"""Return -1 for negative numbers, 1 for positive numbers, and 0 for 0."""
result: PositiveOrNegative
if number < ... | 771c5e5375b161d5eed0efc00db1094a7996169a | 32,870 |
def ba2str(ba):
"""Convert Bluetooth address to string"""
string = []
for b in ba.b:
string.append('{:02X}'.format(b))
string.reverse()
return ':'.join(string).upper() | 765fc9dbbea5afdd32c6d09c18f428e3693e20bf | 32,871 |
import requests
def delete_user(client: Client, user_id: str) -> bool:
"""Deletes disabled user account via the `/users/{user_id}` endpoint.
:param client: Client object
:param user_id: The ID of the user account
:return: `True` if succeeded, `False` otherwise
"""
params = {'version': get_use... | f385ca6e1108f95c00e28dbd99ffa640fefed761 | 32,873 |
import requests
def get_token(corp_id: str, corp_secret: str):
"""获取access_token
https://open.work.weixin.qq.com/api/doc/90000/90135/91039
"""
req = requests.get(
f'https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={corp_id}&corpsecret={corp_secret}'
)
return req.json().get('access_t... | 9a9c3fcdb74312b5d2d7c62588aea3cf78796ec9 | 32,874 |
def _update_run_op(beta1, beta2, eps, global_step, lr, weight_decay, param, m, v, gradient, decay_flag, optim_filter):
"""
Update parameters.
Args:
beta1 (Tensor): The exponential decay rate for the 1st moment estimations. Should be in range (0.0, 1.0).
beta2 (Tensor): The exponential decay... | 292f493ff83aba5e95a7b4ddce6b454ce4600e2c | 32,875 |
def make_initial_ledger(toodir=None):
"""Set up the initial ToO ledger with one ersatz observation.
Parameters
----------
toodir : :class:`str`, optional, defaults to ``None``
The directory to treat as the Targets of Opportunity I/O directory.
If ``None`` then look up from the $TOO_DIR ... | 9f377c54b65973bd26b868a3a7ca11dd96a7e1e6 | 32,876 |
def trace_sqrt_product_tf(cov1, cov2):
""" This function calculates trace(sqrt(cov1 * cov2))
This code is inspired from:
https://github.com/tensorflow/tensorflow/blob/r1.10/tensorflow/contrib/gan/python/eval/python/classifier_metrics_impl.py
:param cov1:
:param cov2:
:return:
"""
sqrt_... | f685080ce644a889aff633fb44cccf452746c5e9 | 32,877 |
from typing import Any
from typing import Optional
import json
def opennem_serialize(obj: Any, indent: Optional[int] = None) -> str:
"""Use custom OpenNEM serializer which supports custom types and GeoJSON"""
obj_deserialized = None
if not obj_deserialized:
obj_deserialized = json.dumps(obj, cls=... | 77bcb41130b5d8d95f5460cc45f4e78b9ef8bdf5 | 32,878 |
def min_vector(first_atom, second_atom, cell=None):
"""Helper to find mimimum image criterion distance."""
if cell is None:
cell = first_atom._parent.cell.cell
return min_vect(first_atom.pos,
first_atom.fractional,
second_atom.pos,
second_a... | aa159ff5379b8087f05c8b4c88e3ee71a5d2765f | 32,879 |
def dice_coeff_2label(pred, target):
"""This definition generalize to real valued pred and target vector.
This should be differentiable.
pred: tensor with first dimension as batch
target: tensor with first dimension as batch
"""
target = target.data.cpu()
# pred = torch.sigmoid(pred)
# ... | 553f3cdc76f4061512dea27a482f177948f87063 | 32,880 |
def cost_arrhenius(p, T, rate):
"""
Sum of absolute deviations of obs and arrhenius function.
Parameters
----------
p : iterable of floats
`p[0]` is activation energy [J]
x : float or array_like of floats
independent variable
y : float or array_like of floats
depende... | f69a98e06e79774e2fa7eef2709f0bdd6adbe3e1 | 32,881 |
def get_ou_accounts_by_ou_name(ou_name, accounts_list=None, parent=None):
"""
Returns the account of an OU by itsname
Args:
ou_name: name of the OU
accounts_list: list of accounts from a previous call due to the recursive
next_token: the token for the call in case a recursive occurs
... | 6a8d638b18de08937208de45665fd3586dff8c76 | 32,882 |
def split_result_of_axis_func_pandas(axis, num_splits, result, length_list=None):
"""Split the Pandas result evenly based on the provided number of splits.
Args:
axis: The axis to split across.
num_splits: The number of even splits to create.
result: The result of the computation. This ... | bd136350147db12ed165129310fd5ee22f55b40e | 32,883 |
def is_icypaw_scalar_type_annotation(obj):
"""Return if the object is usable as an icypaw scalar type annotation."""
if isinstance(obj, type) and issubclass(obj, IcypawScalarType):
return True
return False | 7c3095ff03183a1dce33062b18dac94ee2528170 | 32,884 |
def pair_is_inward(read, regionlength):
"""Determine if pair is pointing inward"""
return read_is_inward(read, regionlength) and mate_is_inward(read, regionlength) | 4d67b7824093df1cd5d2e020d88894a0877d5d71 | 32,886 |
def sort_by_game(game_walker, from_locale, pack):
"""Sort a pack by the order in which strings appears in the game files.
This is one of the slowest sorting method. If the pack contains strings
that are not present in the game, they are sorted alphabetically at the
end and a message is logged."""
... | 97cebe8db744aef876c7dd0018c49593e7c22888 | 32,889 |
from ..base.util.worker_thread import stop_all_threads
from typing import Sequence
import threading
def main(args: Sequence[str]) -> int:
"""
Entry for the program.
"""
try:
user_args = parse_args(args)
bus = bootstrap_petronia(user_args)
return run_petronia(bus, user_args)
... | 099c0ab97569028a6ca8af3bc97103c1490c54ff | 32,890 |
def to_query_str(params):
"""Converts a dict of params to a query string.
Args:
params (dict): A dictionary of parameters, where each key is a
parameter name, and each value is either a string or
something that can be converted into a string. If `params`
is a list, i... | 11b27e17525cf05dabf0d36e1709be749e829264 | 32,891 |
def histogram(backend, qureg):
"""
Make a measurement outcome probability histogram for the given qubits.
Args:
backend (BasicEngine): A ProjectQ backend
qureg (list of qubits and/or quregs): The qubits,
for which to make the histogram
Returns:
A tuple (fig, axes, p... | 77227d1db0f90420134c18737248989481d384c1 | 32,892 |
import bisect
def crop(sequence, minimum, maximum, key=None, extend=False):
"""
Calculates crop indices for given sequence and range. Optionally the range
can be extended by adding additional adjacent points to each side. Such
extension might be useful to display zoomed lines etc. Note that this metho... | af761dbdbcb40270a4aaf7c55921497e1872f8c1 | 32,893 |
def reverse_dict(dict_obj):
"""Reverse a dict, so each value in it maps to a sorted list of its keys.
Parameters
----------
dict_obj : dict
A key-value dict.
Returns
-------
dict
A dict where each value maps to a sorted list of all the unique keys
that mapped to it.... | 94ff638e67de94a37754cfae7fd9d2605835b946 | 32,894 |
def remote_error_known():
"""Return a remote "error" code."""
return {"errorType": 1} | bd848143531a9f8e997af8ef64f2d1ee4ad3670b | 32,895 |
import re
def get_throttling_plan(js: str):
"""Extract the "throttling plan".
The "throttling plan" is a list of tuples used for calling functions
in the c array. The first element of the tuple is the index of the
function to call, and any remaining elements of the tuple are arguments
to pass to ... | c53eba9d018a6e3308f07031c4c8f26101f853dd | 32,896 |
def list_agg(object_list, func):
"""Aggregation function for a list of objects."""
ret = []
for elm in object_list:
ret.append(func(elm))
return ret | b2d8eef9c795e4700d111a3949922df940435809 | 32,897 |
from typing import Callable
def job_metadata_api(**kwargs: dict) -> Callable[[dict], str]:
"""
Job Metadata API route.
Arguments:
kwargs: required keyword arguments
Returns:
JSON response
"""
return job_resource.job_metadata_api(**kwargs) | 4641930a6c18066eac3dbaaaed99bfbd59560722 | 32,898 |
def parse_word(word: str) -> str:
"""Compile a word of uppercase letters as numeric digits. Non-uppercase letter words are returned unchanged."""
if not word.isupper():
return word
compiled_word = " + ".join([letter + "*" + str(10**index) for index, letter in enumerate(word[:: -1])])
return "(" ... | aa246c7d5e92035f14476327f5b2b694b383f7e1 | 32,899 |
def rayleigh(gamma, M0, TtR):
"""
Function that takes in a input (output) Mach number and a stagnation
temperature ratio and yields an output (input) Mach number, according
to the Rayleigh flow equation. The function also outputs the stagnation
pressure ratio
Inputs:
M [dimension... | f1432158136bee529ec592f7ef539f2aac19e5f5 | 32,900 |
def attack(N, e, c, oracle):
"""
Recovers the plaintext from the ciphertext using the LSB oracle attack.
:param N: the modulus
:param e: the public exponent
:param c: the encrypted message
:param oracle: a function which returns the last bit of a plaintext for a given ciphertext
:return: the... | 3fe99894909c07da0dc42fc1101bb45853e3366f | 32,901 |
from typing import Optional
from typing import Union
from typing import Dict
from typing import Any
def setup_wandb_logging(
trainer: Engine,
optimizers: Optional[Union[Optimizer, Dict[str, Optimizer]]] = None,
evaluators: Optional[Union[Engine, Dict[str, Engine]]] = None,
log_every_iters: int = 100,
... | caf67149d8aa8d2b85f07f96b4d55677183c594b | 32,902 |
def _norm(X, y):
"""Scales data to [0..1] interval"""
X = X.astype(np.float32) / (X.max() - X.min())
return X, y | 87189d4c885d77654793373416c0d5c4be498fba | 32,903 |
async def delete_layer(location_id, layer_id):
"""
Delete layer
---
delete:
summary: Delete layer
tags:
- layers
parameters:
- name: id
in: path
required: true
description: ID of the object to be deleted
responses:
... | 537ea3907fef2998ca8ae960a05a2e5204b4ab7e | 32,906 |
def fit_and_save_model(params, data, targets):
"""Fit xgb classifier pipeline with params parameters and
save it to disk"""
pipe = make_pipeline(StandardScaler(),
XGBClassifier(learning_rate=params['learning_rate'],
max_depth=int(params['max_de... | 589dd94f0a258f8eabcbd47b2341a71303c5d6b7 | 32,907 |
def relu_backward(dout, cache):
"""
Backward pass for the ReLU function layer.
Arguments:
dout: numpy array of gradient of output passed from next layer with any shape
cache: tuple (x)
Output:
x: numpy array of gradient for input with same shape of dout
... | 3384ddf789ed2a31e25a4343456340a60e5a6e11 | 32,908 |
def run_decopath(request):
"""Process file submission page."""
# Get current user
current_user = request.user
user_email = current_user.email
# Check if user submits pathway analysis results
if 'submit_results' in request.POST:
# Populate form with data from the request
results... | d86d21a31004f971e2f77b11040e88dcd2a26ee4 | 32,909 |
import tqdm
def load_abs_pos_sighan_plus(dataset=None, path_head=""):
"""
Temporary deprecation !
for abs pos bert
"""
print("Loading Expanded Abs_Pos Bert SigHan Dataset ...")
train_pkg, valid_pkg, test_pkg = load_raw_lattice(path_head=path_head)
tokenizer_model_name_path="hfl/chinese... | 8da548c4586f42c8a7421482395895b56aa31a10 | 32,910 |
def _train_on_tpu_system(model_fn_wrapper, dequeue_fn):
"""Executes `model_fn_wrapper` multiple times on all TPU shards."""
config = model_fn_wrapper.config.tpu_config
iterations_per_loop = config.iterations_per_loop
num_shards = config.num_shards
single_tpu_train_step = model_fn_wrapper.convert_to_single_tp... | faad0d857b2741b5177f348a6f2b7a54f9470135 | 32,911 |
def get_docs_url(model):
"""
Return the documentation URL for the specified model.
"""
return f'{settings.STATIC_URL}docs/models/{model._meta.app_label}/{model._meta.model_name}/' | 613cb815ff01fa13c6c957f47c0b5f3f7edcff8f | 32,912 |
import random
def _fetch_random_words(n=1000):
"""Generate a random list of words"""
# Ensure the same words each run
random.seed(42)
# Download the corpus if not present
nltk.download('words')
word_list = nltk.corpus.words.words()
random.shuffle(word_list)
random_words = word_lis... | aaf257e3b6202555b29bdf34fd9342794a5acf6f | 32,913 |
import json
def cache_pdf(pdf, document_number, metadata_url):
"""Update submission metadata and cache comment PDF."""
url = SignedUrl.generate()
content_disposition = generate_content_disposition(document_number,
draft=False)
s3_client.put_object... | 44ffd6841380b9454143f4ac8c71ef6ea560030a | 32,914 |
def get_tile_list(geom,
zoom=17):
"""Generate the Tile List for The Tasking List
Parameters
----------
geom: shapely geometry of area.
zoom : int Zoom Level for Tiles
One or more zoom levels.
Yields
------
list of tiles that intersect with
"""
west,... | dcceb93b13ce2bbd9e95f664c12929dee10a1e63 | 32,915 |
def findTolerableError(log, file='data/psf4x.fits', oversample=4.0, psfs=10000, iterations=7, sigma=0.75):
"""
Calculate ellipticity and size for PSFs of different scaling when there is a residual
pixel-to-pixel variations.
"""
#read in PSF and renormalize it
data = pf.getdata(file)
data /= ... | 02b1771e4a363a74a202dd8d5b559efd68064f4d | 32,916 |
def squeeze_labels(labels):
"""Set labels to range(0, objects+1)"""
label_ids = np.unique([r.label for r in measure.regionprops(labels)])
for new_label, label_id in zip(range(1, label_ids.size), label_ids[1:]):
labels[labels == label_id] == new_label
return labels | 9c78f5e103fa83f891c11477d4cea6fdac6e416d | 32,917 |
import itertools
def orient_edges_gs2(edge_dict, Mb, data, alpha):
"""
Similar algorithm as above, but slightly modified for speed?
Need to test.
"""
d_edge_dict = dict([(rv,[]) for rv in edge_dict])
for X in edge_dict.keys():
for Y in edge_dict[X]:
nxy = set(edge_dict[X]) - set(edge_dict[Y]) - {Y}
for ... | 272bdd74ed5503851bd4eb5519c505d8583e3141 | 32,918 |
def _divide_evenly(start, end, max_width):
""" Evenly divides the interval between ``start`` and ``end`` into
intervals that are at most ``max_width`` wide.
Arguments
---------
start : float
Start of the interval
end : float
End of the interval
max_width : float
... | 08647cc55eca35447a08fd4ad3959db56dffc565 | 32,919 |
def uncompress_pubkey(pubkey):
""" Convert compressed public key to uncompressed public key.
Args:
pubkey (str): Hex encoded 33Byte compressed public key
Return:
str: Hex encoded uncompressed 65byte public key (4 + x + y).
"""
public_pair = encoding.sec_to_public_pair(h2b(pubkey))
... | 672f89482e5338f1e23cbe21823b9ee6625c792f | 32,920 |
def make_celery(main_flask_app):
"""Generates the celery object and ties it to the main Flask app object"""
celery = Celery(main_flask_app.import_name, include=["feed.celery_periodic.tasks"])
celery.config_from_object(envs.get(main_flask_app.config.get("ENV"), "config.DevConfig"))
task_base = celery.T... | 57fc0d7917b409cb36b4f50442dd357d384b3852 | 32,921 |
def adjustForWeekdays(dateIn):
""" Returns a date based on whether or not the input date
is on a weekend. If the input date falls on a Saturday or
Sunday, the return is the date on the following Monday. If
not, it returns the original date. """
#If Saturday, return the following Monday.
if dat... | 9db5c3fadbcb8aeb77bfc1498333d6b0f44fd716 | 32,922 |
from datetime import datetime
def get_user_or_add_user(spotify_id, display_name, display_image=None, token=None):
"""Fetch an existing user or create a user"""
user = User.query.filter(User.spotify_id == spotify_id).first()
if user is None:
spotify_id = spotify_id
spotify_display_name =... | 27f0fffcaf10e4060860c39f1df54afe21814250 | 32,925 |
from bs4 import BeautifulSoup
def get_daily_data(y, m, d, icao):
"""
grab daily weather data for an airport from wunderground.com
parameter
---------
y: year
m: month
d: day
ICAO: ICAO identification number for an airport
return
------
a di... | 35abfda3ed6f80c213099149d5a3009c03be1d48 | 32,926 |
def image_tag_create(context, image_id, value, session=None):
"""Create an image tag."""
session = session or get_session()
tag_ref = models.ImageTag(image_id=image_id, value=value)
tag_ref.save(session=session)
return tag_ref['value'] | 5aaa684912ae18fe98beb1d62d1c219239c013c6 | 32,928 |
def test_branch_same_shape():
"""
Feature: control flow function.
Description: Two branch must return the same shape.
Expectation: Null.
"""
class Net(Cell):
def __init__(self):
super().__init__()
self.a = 1
def construct(self, x, y):
for k i... | 57326097cb0da2c3982aea2cfeee5be19923b4cf | 32,929 |
def potential(__func__=None, **kwds):
"""
Decorator function instantiating potentials. Usage:
@potential
def B(parent_name = ., ...)
return baz(parent_name, ...)
where baz returns the deterministic B's value conditional
on its parents.
:SeeAlso:
Deterministic, deterministic,... | 5023755aee2d887eb0077cb202c01013dda456e8 | 32,930 |
def numBytes(qimage):
"""Compatibility function btw. PyQt4 and PyQt5"""
try:
return qimage.numBytes()
except AttributeError:
return qimage.byteCount() | a2e5bfb28ef679858f0cdb2fb8065ad09b87c037 | 32,931 |
def _dt_to_decimal_time(datetime):
"""Convert a datetime.datetime object into a fraction of a day float.
Take the decimal part of the date converted to number of days from 01/01/0001
and return it. It gives fraction of way through day: the time."""
datetime_decimal = date2num(datetime)
time_d... | febcaa0779cbd24340cc1da297e338f1c4d63385 | 32,932 |
def poll_create(event, context):
"""
Return true if the resource has been created and false otherwise so
CloudFormation polls again.
"""
endpoint_name = get_endpoint_name(event)
logger.info("Polling for update of endpoint: %s", endpoint_name)
return is_endpoint_ready(endpoint_name) | 3ac7dd8a4142912035c48ff41c343e5d56caeba3 | 32,933 |
def outsatstats_all(percent, Reads_per_CB, counts, inputbcs):
"""Take input from downsampled bam stats and returns df of genes, UMIs and reads for each bc.
Args:
percent (int): The percent the bamfile was downsampled.
Reads_per_CB (file path): Space delimited file of the barcodes and # of reads... | f6d320e10c3171c543afdc6bdf70d83f5bcfb030 | 32,934 |
from typing import Optional
from typing import List
import random
import itertools
def generate_sums(
n: int, min_terms: int, max_terms: int, *, seed=12345, fold=False, choose_from=None
) -> Optional[List[ExprWithEnv]]:
""" Generate the specified number of example expressions (with no duplicates).
The... | 26dbd81ec62fe15ff6279356bb5f41f894d033d2 | 32,937 |
def arr2pil(frame: npt.NDArray[np.uint8]) -> Image.Image:
"""Convert from ``frame`` (BGR ``npt.NDArray``) to ``image`` (RGB ``Image.Image``)
Args:
frame (npt.NDArray[np.uint8]) : A BGR ``npt.NDArray``.
Returns:
Image.Image: A RGB ``Image.Image``
"""
return Image.fromarray(cv2.cvtCo... | 5878d983055d75653a54d2912473eacac3b7501d | 32,939 |
def sophos_firewall_app_category_update_command(client: Client, params: dict) -> CommandResults:
"""Update an existing object
Args:
client (Client): Sophos XG Firewall Client
params (dict): params to update the object with
Returns:
CommandResults: Command results object
"""
... | 1ba77c9b2ad172e2d9c508c833a7d4b08fb5b876 | 32,940 |
import collections
def find_identities(l):
"""
Takes in a list and returns a dictionary with seqs as keys and positions of identical elements in list as values.
argvs: l = list, e.g. mat[:,x]
"""
# the number of items in the list will be the number of unique types
uniq = [item for item, coun... | db7b64cc430ab149de7d14e4f4a88abafbadbe34 | 32,941 |
def decode_event_to_internal2(event):
""" Enforce the binary encoding of address for internal usage. """
data = event.event_data
# Note: All addresses inside the event_data must be decoded.
if data['event'] == EVENT_TOKEN_ADDED2:
data['token_network_address'] = to_canonical_address(data['args']... | fdacba3f496f5aa3715b8f9c4f26c54a21ca3472 | 32,942 |
def _repeated_features(n, n_informative, X):
"""Randomly select and copy n features from X, from the col
range [0 ... n_informative].
"""
Xrep = np.zeros((X.shape[0], n))
for jj in range(n):
rand_info_col = np.random.random_integers(0, n_informative - 1)
Xrep[:, jj] = X[:, rand_info... | f15811a34bcc94fff77812a57a2f68178f7a8802 | 32,943 |
def create_auto_edge_set(graph, transport_guid):
"""Set up an automatic MultiEdgeSet for the intersite graph
From within MS-ADTS 6.2.2.3.4.4
:param graph: the intersite graph object
:param transport_guid: a transport type GUID
:return: a MultiEdgeSet
"""
e_set = MultiEdgeSet()
# use a ... | 5f6832506d0f31795dd82f92416bb532cc7237fe | 32,944 |
def jaccard(box_a, box_b):
"""Compute the jaccard overlap of two sets of boxes. The jaccard overlap
is simply the intersection over union of two boxes. Here we operate on
ground truth boxes and default boxes.
E.g.:
A ∩ B / A ∪ B = A ∩ B / (area(A) + area(B) - A ∩ B)
Args:
box_a: (t... | fc72ebcaa47b7f0f1f27a0618cbe7592ada5ad70 | 32,945 |
def concat(input, axis, main_program=None, startup_program=None):
"""
This function concats the input along the axis mentioned
and returns that as the output.
"""
helper = LayerHelper('concat', **locals())
out = helper.create_tmp_variable(dtype=helper.input_dtype())
helper.append_op(
... | 55a6e8704141a45a135402dac10d6793f2ae6a28 | 32,946 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.