content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def _threshold_binary(image, thresholds):
"""
Apply binary thresholding to an image
Inputs
----------
image: numpy.ndarray
A single image, grayscale or RGB
thresholds: numpy.ndarray
A list containing a min and max value for thresholding
Outputs
-------
binary_ou... | dac47dbbdcfcbc9a5c55bfc4447ecf2a0bceb803 | 3,616,706 |
def is_field_remote(model, field_name):
"""Check whether a given model field is a remote field.
"""
if not hasattr(model, '_meta'):
# ephemeral model with no metaclass
return False
model_field = get_model_field(model, field_name)
return isinstance(model_field, (ManyToManyField, Rela... | f000422278aa934a9400f1b31ddde9d5b7a5728d | 3,616,707 |
def dist_bool_output(dist, dist1, dist2=0, mode='lim'):
"""
This function takes an input distance and the upper and lower limits or the central value and the tolerance and outputs
if it satisfies or not the given criteria.
modes:
lim -> limit mode, it requires a max and a min value
tol ... | bf3df055331ddfc608ad0c97fe9602c65082c582 | 3,616,708 |
def rollaxis(a, axis, start=0):
"""
Roll the specified axis backwards, until it lies in a given position.
Parameters
----------
a : ndarray
Input array.
axis : int
The axis to roll backwards. The positions of the other axes do not
change relative to one another.
sta... | 0a386ae86096be232b7ed83f4f7497ddf51ddb64 | 3,616,709 |
def consistency_check(args, alphabet, key):
"""Checks the alphabet and the key for consistency and normalizes both to lower case
:param object args: object containing the converted arguments
:param str alphabet: the untrusted alphabet to check
:param str key: the untrusted key to check
:return: a t... | 44c650d5a6db285b6d2df9bb25699860dd24ca8e | 3,616,710 |
def func(arg1, arg2):
"""magic function
"""
return arg2, arg1 | eb5841ce5765d44ede5162aa8bf51ec370c35b00 | 3,616,711 |
def network_exists(network: str):
"""True if a network exists in docker, else False"""
try:
get_client().networks.get(network)
return True
except NotFound:
return False | 78b0ddae2deeeac2150c7283ec294f25f68a2ade | 3,616,713 |
def calc_theta(t,p):
"""
Calculate potential temperature.
**Inputs/Outputs**
Variable I/O Description Units
-------- --- ----------- -----
t I Air pressure Pa
p I Air temperature K
theta O Potential temp. K
"""
re... | 597f56ddb0a48e8b10c7c4d155d9fc772966741e | 3,616,714 |
def louvain(adj_mat: np.ndarray,
verbose: bool = False,
shuffle_nodes: bool = False,
tol_optimization: float = 0.0001,
tol_aggregation: float = 0.001,
return_adj: bool = False,
**kwargs):
""" Performs louvain partiti... | 19241490e19a73ed8ed40aca963ad9a94aa03950 | 3,616,715 |
def _init_search_param(search_idx, x, y0):
"""Initialize search_param
"""
if len(search_idx[0]) != len(set(search_idx[0])):
raise ValueError('Duplicate param name.')
elif len(search_idx[1]) != len(set(search_idx[1])):
raise ValueError('Duplicate var name.')
else:
pass
se... | d1308614a4ddc65c73dc766d9864b1b833794200 | 3,616,716 |
def create_timelength(
seconds: spec.TimelengthSecondsRaw,
to_representation: spec.TimelengthRepresentation = None,
) -> spec.Timelength:
"""create Timelength
## Inputs
- seconds: int or float seconds
- to_reprsentation: str name of Timelength representation
## Returns
- Timelength wit... | f7143b484f19e360eb582ca93a11bc9be71b910a | 3,616,717 |
import collections
def _load_vocabulary(filename):
"""Loads a vocabulary file.
Args:
filename: Path to text file containing newline-separated words.
Returns:
vocab: A dictionary mapping word to word id.
"""
tf.logging.info("Reading vocabulary from %s", filename)
vocab = collections.OrderedDict()... | b13648d603c8876cc6acc74c36bc106b75d3f804 | 3,616,718 |
def get_instance_type_by_flavor_id(flavor_id):
"""Retrieve instance type by flavor_id."""
ctxt = context.get_admin_context()
try:
return db.instance_type_get_by_flavor_id(ctxt, flavor_id)
except ValueError:
raise exception.FlavorNotFound(flavor_id=flavor_id) | afa709da2bfa98d1396946b3733d2becb1ae5eb9 | 3,616,719 |
def create_job(system, args:Args) -> str:
""" Create a job file template """
return f"""#!/usr/bin/bash
# --------------------------------------------------
# Request resources here
# --------------------------------------------------
#{system} --job-name={args.name}
#{system} --output={args.name}.out
#{system... | 7a91030310ba8c9185ebc6e07de8a08b9f78dd6c | 3,616,720 |
def standardize_features(df_train, df_test, cols=[]):
"""Scale continuous features to unit variance and zero mean.
Parameters
----------
df_train : pandas.core.frame.DataFrame
A subset of data intended for training.
df_test : pandas.core.frame.DataFrame
A subset of data intended for... | c1ff27d1c339cb155e04d5322bf848bd7694451e | 3,616,721 |
def tile_ref_enc_to_elements(ref_enc, elements_mask):
"""Utility to tile the ref_enc to the same shape as the elements."""
with tf.variable_scope('tile_ref_enc_to_elements'):
orig_shape = tf.shape(ref_enc)
orig_shape_static = ref_enc.get_shape().as_list()
ref_enc = tf.tile(
tf.reshape(ref_enc, [... | 3af995b296228802128a759e113ba9a12579631e | 3,616,722 |
async def get_level(request: web.Request) -> web.Response:
"""GET /api/level/{id}
Description:
Fetch a level by given ID.
Example:
link: /api/level/30029017
Returns:
200: JSON with level info;
400: Invalid type;
404: Level was not found.
Return Type:
a... | 1684a89f3d3dae170b8e93ab5e58189af5487f66 | 3,616,723 |
def sanity_fit(model: nn.Module, train_loader, val_loader,
device: str, num_batches: int = None,
log_interval: int = 100, fp16: bool = False,):
"""
Performs Sanity fit over train loader and valid loader.
Use this to dummy check your fit function. It does not calculate metrics,... | 220d720573d4967dda9ccd77ea1304b53b7d6a55 | 3,616,724 |
from typing import Tuple
import ctypes
def spkezp(
targ: int, et: float, ref: str, abcorr: str, obs: int
) -> Tuple[ndarray, float]:
"""
Return the position of a target body relative to an observing
body, optionally corrected for light time (planetary aberration)
and stellar aberration.
https... | 07de45de30a7364375e5cdba4b7e927468da4b80 | 3,616,725 |
def make_birefringent(theta, eta=pi, phi=0):
"""
:param theta: Angle fast axis makes with horizontal
:param eta: retardance
:param phi: "circularity"?
:return: Jones matrix for the given parameters
"""
a = exp(1j * eta/2)*cos(theta)**2 + exp(-1j * eta/2)*sin(theta)**2
b = (exp(1j * eta... | bac26af439c7aaf670fe286a2f6729f90d50e37c | 3,616,726 |
import json
import logging
def news_API_request(covid_terms:str=json.loads(
open("config.json").read())["news_terms"]) -> list:
"""news_API_request function
This function takes in covid_terms and returns a list of dictionaries of news articles with those terms.
Args:
covid_terms (string)... | 51cfd0bcece47b6e99f64cc5b05311318f31ed65 | 3,616,727 |
def gt(value, other):
"""Greater than"""
return value > other | 943d50ded0dfcb248eefb060d28850154693956b | 3,616,728 |
def user_label(i):
""" Generate the user lable. Lables are 1 indexed.
"""
i = i - 1
if i < 0 or i > len(users):
return "User" + str(int(i))
return users[i] | 736ea251ada086ab1314d8d7b9f3320925bfbaeb | 3,616,729 |
import numpy
def doweight(theta, lam, p, v):
"""Re-weight visibilities
Note that as is usual, convolution kernels are not taken into account
"""
N = int(round(theta * lam))
assert N > 1
gw = numpy.zeros([N, N])
x, xf, y, yf = frac_coords(gw.shape, 1, p / lam)
for i in range(len(x)):
... | f8a397318c43326221e0b4c75d3281b021b27628 | 3,616,730 |
def ecg_rsa(rpeaks, rsp, sampling_rate=1000):
"""
Returns Respiratory Sinus Arrhythmia (RSA) features. Only the Peak-to-trough (P2T) algorithm is currently implemented (see details).
Parameters
----------
rpeaks : list or ndarray
List of R peaks indices.
rsp : list or ndarray
Fi... | 999a1a8f3208df113c61af08e4499e6e57ac5cf4 | 3,616,732 |
import inspect
from typing import OrderedDict
def data_io_decorator(func):
"""
Decorator to standardize docstrings for data I/O functions.
"""
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
# Parse the docstrings of the base df_to_time_series function & decorated function.
... | 177400dc57bb5a0fa571790a148cf2ebfb176074 | 3,616,734 |
def similar(amazonID, googleURL):
""" Return similarity value
Args:
amazonID: amazon ID
googleURL: google URL
Returns:
similar: cosine similarity value
"""
return (similarities
.filter(lambda record: (record[0] == googleURL and record[1] == amazonID))
... | 3edb4e3a07150fd1da2c09c95ba6d828fc73ba14 | 3,616,735 |
def atos(data, separator=' ', fmt='02X'):
""" Convert array of bytes to string
:param data: Data in bytes or bytearray type
:param separator: String separator
:param fmt: String format
:return string
"""
ret = ''
for x in data:
if fmt == 'c' and x not in printable.encode():
... | 362f2cac329abaa91ebba8b35f72fea27f908bc0 | 3,616,736 |
def get_fc_block(n_in: int, n_out: int):
"""
Fully connected block of SimpleCNN model
:param n_in: number of input channels
:param n_out: number of output channels
:return: fully connected block
"""
block = nn.Sequential(
nn.Linear(n_in, n_out),
nn.ReLU()
)
return bl... | d68a6fba3c1e5413b96e530217a603413ddaff60 | 3,616,737 |
def get_instance_from_str(matrix, format):
"""This function returns the string representation of the given matrix instance according to the indicated format."""
# Parsing format
format_list = format.split('.')
if len(format_list) == 1:
format_primary = format_list[0]
format_secondary = '... | 0bce3af9d6e988a125847a1e3ba29746824cb34f | 3,616,738 |
import stat
def find_duplicates( rootdir ):
"""Find duplicate files in directory tree."""
filesizes = {}
# Build up dict with key as filesize and value is list of filenames.
for path, dirs, files in walk( rootdir ):
for filename in files:
filepath = joinpath( path, filename )
... | a1ce6a15872d50a4447e5d03daae07cd78dfb34c | 3,616,739 |
def get_oiio_info_for_input(filepath, logger=None):
"""Call oiiotool to get information about input and return stdout.
Stdout should contain xml format string.
"""
args = [
get_oiio_tools_path(), "--info", "-v", "-i:infoformat=xml", filepath
]
output = run_subprocess(args, logger=logger... | 00e2bbb28e9e37a294510c54b1127a7ebf928faf | 3,616,740 |
def _tsnr(imgdata, t_axis):
"""Calculate median of temporal signal to noise ratio.
This is consistent with MRIQC
"""
meanimg = np.mean(imgdata, axis=t_axis)
stddevimg = np.std(imgdata, axis=t_axis)
tsnr = np.zeros_like(meanimg)
stddevimg_nonzero = stddevimg > 1.0e-3
tsnr[stddevimg_nonzer... | c31f11d08cc437c1227f5d4cc02d0a0401b5a10c | 3,616,741 |
def point_dist(a, b):
""" Distance between two points. """
return ((a[0]-b[0]) ** 2 + (a[1]-b[1]) ** 2) ** 0.5 | ad3490e25fb21a555ee2d12bead5fa476f682566 | 3,616,742 |
def checking(Y, V_map, S_map, I0_pq, n_buses, n_time, n_scale):
"""
:param Y: data file name
:param V_map: outer iterations
:param S_map: intermediate iterations
:param I0_pq: inner iterations
:param n_buses: number of buses
:param n_scale: number of discretized points, arbitrary
:param... | 69dee0de6b918eca3e4e69de30863b872458d5ea | 3,616,743 |
def parse_xml(path):
"""Return ([analysts], service number, document text, document title).
"""
with open(path) as f:
doc = etree.parse(f)
analysts = [x.text.encode('utf-8', 'ignore')
for x in doc.xpath('//authors/author/author-name')]
title = ''
els = doc.... | 424174d5e8c98503b4d05c7194ddfbce60f9f482 | 3,616,744 |
def task(*, name, waiter=None, exception_handler=None):
"""Returns a decorator that creates a `Task` with the given options."""
def decorator(func):
return Task(name, func, waiter, exception_handler, instance=None)
return decorator | db32e8c7b3013a32be47b58985fe932c4f849bc5 | 3,616,745 |
def quote(s: str) -> str:
"""
Quotes the identifier.
This ensures that the identifier is valid to use in SQL statements even if it
contains special characters or is a SQL keyword.
It DOES NOT protect against malicious input. DO NOT use this function with untrusted
input.
"""
if not (s.... | b4530f7570384beedbb7aafd02e642862a484bb8 | 3,616,746 |
def cluster_tweets_external(texts: PreprocessedText, top=3):
"""
Clusters Tweets, from preprocessed texts in db.
:param texts: PreprocessedText objects representing the texts.
:param top: The number of keywords to assign to each clusters.
:return: The ClusterResult representing the result.
"""
... | d76ae7d2b8c9dcfc8da3943e6c262141571cbe03 | 3,616,747 |
import warnings
def dicom2narray(path, voi_lut = False, fix_monochrome = True):
"""
Converts a DICOM into a NUMPY array and returns this array and
its corresponding dataset.
"""
dicom = pydicom.read_file(path)
# VOI LUT (if available by DICOM device) is used to transform raw DICOM data
#... | 0a02bcf7f4a2e48c7c4476a13d9cfba75bb7d525 | 3,616,748 |
def make_activity_context(context,
splits, strava_activity,
race,
stravaSessionExists,
isStrava,
trackFit,
laps, lap_index=-1
):
"""
... | e1d0319d7cf71cd2df6b7969e6ab87b740d043cc | 3,616,750 |
def extract_bigrams_as_list(text):
"""Extract bigrams from text and return as list
:param text: source text
:type text: str
:return: bigram tokens list
:rtype: list
"""
tokens = text.split(" ")
bigram_tokens = create_bigrams(tokens)
return bigram_tokens | 3d5dc0c406a084c129ac7edd931fa22a42674977 | 3,616,751 |
import time
import warnings
def find_best_polynomial(data_x, data_y, max_poly_order, rsq_threshold,
max_dim_n=32,
alpha_sweep=None,
max_iter=1000, cv=2):
"""Find minimal polynomial expansion that is sufficient to explain data using Lasso reg... | 6a1b9b9a034acf08710222541c2c1c630e401835 | 3,616,752 |
import decimal
def create_decimal128_context():
"""Returns an instance of :class:`decimal.Context` appropriate
for working with IEEE-754 128-bit decimal floating point values.
"""
opts = _CTX_OPTIONS.copy()
opts['traps'] = []
return decimal.Context(**opts) | 3d6832212e5af5a4eb41c63759ba6f599f0ff7d2 | 3,616,753 |
def decipher(ciphered_text: str, key: str, charset: str = DEFAULT_CHARSET) -> str:
""" Decipher given text using substitution method.
Note you should use the same charset that ciphering end did.
:param ciphered_text: Text to be deciphered.
:param key: Secret key. In substitution method it corresponds ... | 608606abff29bd0b81a96f8ddafbd8f13d389240 | 3,616,754 |
def manifold_polar(x,y,lamda,A,s,p,m,k,mu):
"""
Returns "Omega", the orthogonal basis for the manifold evaluated at x[-1]
and "gamma" the radial equation evaluated at x[-1].
Input "x" is the interval on which the manifold is solved, "y" is the
initializing vector, "lambda" is the point in the c... | fe60dfe0584e9ad6ca4f55ced3ffe504f6c3d40a | 3,616,755 |
def shrink(filename):
"""
:param filename: str, original image.
:return img: SimpleImage, 0.5x size of original image.
"""
original = SimpleImage("images/poppy.png")
blank_img = SimpleImage.blank(original.width//2, original.height//2)
for x in range(0, original.width, 2):
for y in r... | 36f1f1b9942d08206f9706bd282e2b4c7cb21743 | 3,616,756 |
def sendBind(to):
"""绑定手机"""
code = str(randint(1000, 999999))
param = "%s,3" % (code)
return _sendSms(to, config.SMS_BIND, param) and code | 4443d481836673ac52743ae4bd8f03a6e67a89b7 | 3,616,757 |
def WMTNewsCrawl(tokenizer=None, root='.data', vocab=None, split=('train'), year=2010, language='en'):
""" Defines WMTNewsCrawl datasets.
Create language modeling dataset: WMTNewsCrawl
returns the train set
Args:
tokenizer: the tokenizer used to preprocess raw text data.
The defaul... | c4d3ef56ad3373b0663ae4952d3a66518b5b021a | 3,616,758 |
def c2s_stereographic(z):
"""
Stereographic projection from the plane to the sphere.
"""
x = z.real
y = z.imag
u = 2*x
v = 2*y
w = 1 - x**2 - y**2
return np.stack([u,v,w], axis=-1)/(1+x**2+y**2)[..., np.newaxis] | 706f7dc5fb91a3b162a6e3d5def55077c723304a | 3,616,759 |
def get_dtype(nbits):
"""For a given number of bits per sample return
a numpy-recognized dtype.
Input:
nbits: Number of bits per sample, as recorded in the filterbank
file's header.
Output:
dtype: A numpy-recognized dtype string.
"""
check_nb... | d3aa6f32c517d7ebf4fa4a8b2e226f65972a7d0f | 3,616,760 |
def feature_exposed_pop(df):
"""
Adds the total population of the countries to which an individual can travel
from the initial country. Is the population most exposed to the disease
apart from the initial country.
Parameters
----------
df : pandas.DataFrame
Returns
-------
df ... | 47d533b2fa52338d2a2c6414387b744ddf916eac | 3,616,761 |
import select
def add_new_location(project):
"""
Add a new location object to the database
POST data MUST be in JSON format.
POST data MUST contain:
name: location name
POST data SHOULD also contain:
description: location description
POST data CAN also contain:
legacy_id: legac... | d9e44aa11583644970300dfe159f3f6ff67589a0 | 3,616,762 |
def red_highlight(val) -> str:
"""Red highlight
Parameters
----------
val
dataframe values to color
Returns
----------
str
colored dataframes values
"""
return f"{Fore.RED}{val}{Style.RESET_ALL}" | 023c4ca8ee9cec8661cb8a3c1549a71734c51c74 | 3,616,763 |
import math
def animal_ears(image, ear_image, face_landmarks):
"""attach animal_ears like nekomimi
args:
image: base image
ear_image: one animal ear image
face_landmarks: face_landmarks list
"""
for landmark in face_landmarks:
# position of ear_image center
left... | 77f3a629d3d9fa733a2596db6352876befa3067c | 3,616,764 |
def covariance_matrix(data, fb=False, spsmooth=0, method='scm'):
"""
Parameters
----------
data : np.ndarray
The data used to create the covariance matrix. Is of shape (n_samples, n_snapshots)
fb : bool
If true, uses forward-backward averaging
spsmooth : int
Number of ... | 47ec9e531938e6310738737df9a8139c9549e86d | 3,616,765 |
import torch
def replicate_layers(layer: torch.nn.Module, num_copies: int):
"""
# Parameters
layer (torch.nn.Module) - The torch layer that needs to be replicated.
num_copies (int) - Number of copies to create.
# Returns
A ModuleList that contains `num_copies` of the `... | a6e88d2d9d37f2f0cc4acdbdc3da21c19ace1eba | 3,616,766 |
def get_stocks_urls(db_name) -> list:
"""
# This function gets the basic url for each stock. It reads the stocks and url from the database
:return: list for the stocks name and urls [(stock1, stock1_url), (stock1, stock1_url), ...]
"""
con = connect_to_mysql(db_name)
cursor = con.cursor()
cu... | cf7c5309034b34f5e9fa07d079551b7c65065304 | 3,616,767 |
def substBuiltInVarsInParam(val, svars, splitListOfStrs = True, notHandled = None):
"""
Return value with handled substitutions from a param of 'str',
'list-of-strs' types or from a param of 'dict' with params of such types.
"""
if not val:
return val
if isinstance(val, stringtype):
... | 59162fefb02f9f80d167cd1078d409a5ca672688 | 3,616,768 |
def _mangle_dimension_name(name):
"""Return a dimension name from a mixpanel property name."""
fixed_name = name.replace("$", "_")
fixed_name = fixed_name.replace(" ", "_")
return fixed_name | b18738f4c27fcebe7a93f724bfd45414e075f0a6 | 3,616,769 |
def all_variants(protein_id, sequence, position=None):
"""Position is 0-based"""
positions = [(position, sequence[position])] \
if position else enumerate(sequence)
return pd.DataFrame([
[protein_id, sequence, i+1, wt, mt]
for i, wt in positions
for mt in AMINO_A... | 008a31ffbb701d745f39c7d1a9ae18b45b69bf80 | 3,616,770 |
def strftime(time, include_date=True, include_tz=False):
"""
This function converts a time value to a string.
Parameters
----------
time : numeric, pandas.Timestamp with tz
The time value to convert.
include_date : bool (Default: True)
If time is a pandas.Timestamp, include the ... | 41207b31cdc4fa1c87a16d89ca9b8e9ebefe5241 | 3,616,771 |
def update_dict(old_data, new_data):
"""
Overwrites old usa_ids, descriptions, and abbreviation with data from
the USA contacts API
"""
old_data['usa_id'] = new_data.get('usa_id')
if new_data.get('description') and not old_data.get('description'):
old_data['description'] = new_data.get(... | bec860144de28f5e3097e92216d94e6025223d2e | 3,616,772 |
def read(f, normalized=False):
"""MP3 to numpy array"""
a = pydub.AudioSegment.from_mp3(f)
y = np.array(a.get_array_of_samples())
# if a.channels == 2:
# y = y.reshape((-1, 2))
if normalized:
return a.frame_rate, np.float32(y) / 2**15
else:
return a.frame_rate, y | 21c7ce0018f458b35828ca8e82f77ea6facaf608 | 3,616,773 |
from pathlib import Path
import json
def read_fgdb_fc(path, simplify=True, geom_attrs=True, strict=True):
"""Generates a networkx.DiGraph from an Esri File Geodatabase Feature
Class. Point geometries are translated into nodes, and lines into edges.
Coordinate tuples are used as keys. Attributes are pres... | d3215420c8436ad8a930698d5fcc9b61676d9382 | 3,616,774 |
def min_box(box1, box2):
"""
return the minimum of two bounding boxes
"""
ext = lambda values: max(values) if sum(values) <= 0 else min(values)
return tuple(tuple(ext(offs) for offs in zip(dim[0], dim[1])) for dim in zip(box1, box2)) | 58c8a0fa75c66f1327df13a4e7b5a0f7385c805e | 3,616,775 |
def trapezoid(t, params):
"""Trapezoidal pulse. Width of linear slope.
Parameters
----------
params : dict
t_final : float
Total length of pulse.
risefall : float
Length of the slope
"""
risefall = tf.cast(params["risefall"].get_value(), tf.float64)
t... | 107de257dd6072503e5e7cb175e2dd0f2a3e7730 | 3,616,776 |
import math
def exempt_milliwatts_sar(cm: float, ghz: float) -> float:
"""Calculate power threshold for exemption from routine radio frequency exposure evaluation. Note: narrow range
of applicable frequencies. FCC formula is "based on localized specific absorption rate (SAR) limits." Source: FCC
19-126 p.... | d705c3fd2388204d188e95d9013fe0c574f9e82a | 3,616,779 |
def estimate_fdr_stats(res_real, res_perm, delta):
"""
Helper function for get_fdr_stats_across_deltas.
It computes the FDR and tval_s0 thresholds for a specified delta.
The function returns a list of the following values:
t_cut, n_pos, n_false_pos, pi0, n_false_pos_corr, fdr
"""
perm_avg = ... | 1bfc1b506907ce5b1d42a30916ffe5161b845e21 | 3,616,780 |
def generate_base_anchors(cfg):
"""
Generating top left anchors for given anchor_ratios, anchor_scales and image size values.
:param cfg: dictionary with configuration parameters
:returns: base_anchors = (anchor_count, [y1, x1, y2, x2])
"""
img_size = cfg.IMG_SIZE_WIDTH
anchor_ratios = c... | 474dbdd34a1994dd6de9b24c17991525791f0953 | 3,616,781 |
def spaghetti_annual_hydrograph(file):
"""
spaghetti_annual_hydrograph
INPUTS:
file -- Raven output file containing simulated streamflows of one model
Create a spaghetti plot of the mean hydrological cycle for one model
simulations. The mean simulation is also displayed.
"""
# Tim... | f92637a6794dde26142f1afdddddc0e37c981884 | 3,616,782 |
import logging
def fill_categories(array,fill,coord=None):
"""
Replace categorical labels and interpolate missing categories depending on a custom dictionary
:param array: array of a categorical variable
:param fill: dictionary with category replacements and missing categories
:param coord: o... | cb5ad614b85357b2b288b83474410fc9ebc6f2ad | 3,616,784 |
def get_u(r_div_R, z_div_L, k, Ap, Am, lam1):
""" Using Eq. (31) (the second expression) in [1]
"""
# uR_HP = (1. - r_div_R**2.0)*lam1/2.
uR_HP = (1. - r_div_R**2.0)
uZ_PS = -k*(exp( k*z_div_L)*Ap - exp(-k*z_div_L)*Am)
return uZ_PS*uR_HP | cc0a959291186abed0a429fd3933b5d79ddce567 | 3,616,785 |
def is_zero(pauli_string):
"""
Checks if a PauliString is zero.
Parameters
----------
pauli_string : (PauliString object) a PauliString object which is to be checked
Returns
-------
True if PauliString is zero, False otherwise
"""
if isinstance(pauli_string, PauliString):
... | aa0a8c0565fd61cf2a767ab081cbfee5f9d2dbd4 | 3,616,787 |
def evalAllocater(task, metrics, reshapeDims, n_classes):
"""Returns an evaluator based on the specified task.
# Arguments
task: integer value denoting the task
metrics: evaluation metrics related to that task
reshapeDims: reshape dimensions of the image
n_classes: integer value denoting the number of classe... | 2a2b15493168c14196d6035e2b3b10a2260c07fe | 3,616,788 |
def checkCrash(player, upperPipes, lowerPipes):
"""returns True if player collders with base or pipes."""
pi = player['index']
player['w'] = IMAGES['player'][0].get_width()
player['h'] = IMAGES['player'][0].get_height()
# if player crashes into ground or above screen
if (player['y'] + player['h... | 85e093c0455e85cae838a0ddce9d5df37a3783ba | 3,616,789 |
def login_required(func):
"""Decorator for enforcing a logged in user.
Also pulls the token out of the request and passes a user instance into the decorated function.
"""
@wraps(func)
def check_log_in(*args, **kwargs):
current_user.ping()
database_session.commit()
return f... | 40a44b5022d3a71f2428b961e81cf493cac4f75d | 3,616,790 |
def gdx(request, year=None, gdx_path=None, array_results=False):
"""
Look up the request in a gdx file.
A request uses Gekko syntax, e.g. "qBNP", "qY[tje]", or "qY[#s]".
If no year is specified, an array is returned with values for all available years.
If no gdx_path is specified, use the global path set usin... | 527e475f42e26efa8810fa6249f8f1b6539a71c6 | 3,616,791 |
def KernelDisorderSC(kx, ky, px, py, params):
"""
This subroutine defines the kernel between self energy and free Feynman propagator.
In case of phase-disordered superconductivity,
this corresponds to the fourier transformation of space correlation of Cooper gap.
E.g. In two dimens... | 4dbc85bb1800d066e1e86edf7f2cbe1840f7d4c0 | 3,616,792 |
def DOV(ATcur, A, Gcur, a):
"""
| LAT | ----------+---------- Astr.
| LON | | Azimuth
| H |AT | (A)
|
|
+-----------------> Deflection of , Geoid
... | b18b26f2985fec536dfda029a1f3803e076d0f5c | 3,616,793 |
import typing
import re
def replace_cif_reference(refs: typing.Iterable[str], new_sub_str: str) -> typing.List:
"""Replace the "cif-reference-0" to bec new names with increasing index."""
ans = []
source = r"@article{.*,"
for i, ref in enumerate(refs):
ref2 = re.sub(source, "@article{{{}{},".f... | 014f633c8eef43093944ec8f63690b59c446c2c1 | 3,616,794 |
import uuid
def random_string() -> str:
"""
Create a 36-character random string.
Returns
-------
str
"""
return str(uuid.uuid4()) | f01e291f6d36a8468a256af0fad83e2d468b471d | 3,616,795 |
def get_points_raytracing(count, side, other_side, building_data, road_part, points_classified):
"""
Get all the point created by the raytracing for the given road segment.
Returns a dictionary with the distances and heights on the left and right side.
"""
bld_dist_heights = {}
i = count
fo... | 30902b1c43d36c37bc13fbb0b88da1465c38012b | 3,616,796 |
import torch
def forward(sample, G, imgs_size, indices, device):
"""
This function takes the whole input, prepares it for the forward pass,
creates the patches of given size and with two loops pass these adiacent
patches through the generator. Then, the simulated patches are concatenaed
together t... | 7fa360e56f27f94090b0f88c42659fdcbb5040f3 | 3,616,797 |
def _extent(x, y):
"""Get data extent for pyplot imshow.
Parameters
----------
x: list
Data array on X-axis.
y: list
Data array on Y-axis.
Returns
-------
[float, float, float, float]
X and Y extent.
"""
dx, dy = .5 * (x[1] - x[0]), .5 * (y[1] - y[0])
... | 1b8a062e2060dc99d3fcdc32fe6fd1952f468a6a | 3,616,798 |
import random
def get_random_string(length=12,
allowed_chars='abcdefghijklmnopqrstuvwxyz'
'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'):
"""
Returns a securely generated random string.
The default length of 12 with the a-z, A-Z, 0-9 character set return... | 7e113513331a94170948763e15d2de4415eeb0a0 | 3,616,800 |
def chunk_average(epochs):
"""
Because the number of trials is hugee, ~ 5000, I don't have the patience to
wait for the process and the cluster does not have the memory to process
such a huge dataset, so I will average every 10 trials to boost the
signal-to-noise ratio and decrease the number of t... | 377da889f56902cd8db00cd4e610c4936511ad3f | 3,616,802 |
def getField(statefile, fieldname):
""" Get field from MITgcm netCDF output
statefile : string with /path/to/state.0000000000.t001.nc
fieldname : string with the variable name as written on the netCDF file ('Temp', 'S','Eta', etc.)"""
StateOut = Dataset(statefile)
Fld = StateOut.variables[fieldname][:... | 808c302ac0a2daae3d5c11009391bb8bee4fab0c | 3,616,803 |
from typing import List
def get_stations_with_n_docks(num: int, stations: List['Station']) -> List[int]:
"""Return a list containing the station ids for the stations in
stations that have at least num docks available, in the same order
as they appear in stations.
Precondition: num >= 0
>>> get_s... | 9e9f1b265dc7721a031369bc996363a5e71629ac | 3,616,804 |
def apply_corrections(fluxes, filters, pd_corrections):
"""Apply pd correctionst to the fluxes by fitler."""
return np.array([flux*pd_corrections.get(filt, 1)
for flux, filt in zip(fluxes, filters)]) | 1d049fe5187e6c38b1b65ea0e9898e68a97a6178 | 3,616,805 |
import feedparser # type: ignore
def get_posts_details(rss=None):
"""
Take link of mrss feed as argument
"""
if rss is not None:
# import the library only when url for feed is passed
# parsing partner feed
partner_feed = partner_feed = feedparser.parse(rss)
# getting lists of partner entries vi... | eee63b49ab4cf7c1746b752cb0a436b18fb7201e | 3,616,807 |
def XYZ2Shp(filecsv, t_srs="EPSG:4326", fileout=None):
"""
XYZ2Shp
"""
driver = ogr.GetDriverByName('ESRI Shapefile')
fileout = forceext(filecsv, "shp") if not fileout else fileout
remove(fileout)
layername = juststem(fileout)
print layername
dataset = driver.CreateDataSource(fileout... | 5b4c03c34863d1d5ee82bf2f7fbcca8fce4221ad | 3,616,810 |
import copy
def __transform_dataframe_to_event_stream_new(dataframe, stream_post_processing=False, compress=False):
"""
Transforms a dataframe to an event stream
Parameters
------------------
dataframe
Pandas dataframe
stream_post_processing
Boolean value that enables the post... | 98ca6190434cb68732ee2b554279722b252b1abb | 3,616,811 |
def backward_selection(g, n_, k_=None):
"""For details, see here.
Parameters
----------
g : function
n_ : int
k_ : int, optional
Returns
-------
s_star_bwd : list, shape(k_, 1:k_)
"""
if k_ is None:
k_ = n_
# Step 0: Initialize
s_star_backw... | cc384b6c6fca68b51d0806c498b0a7328edd2ebd | 3,616,812 |
def auc_score(y_true, y_pred):
"""Gets the auc score of labels and predictions.
Parameters
----------
y_true : torch.tensor
The true labels.
y_pred : torch.tensor
The prediction.
Returns
-------
numpy.ndarray
The auc score.
"""
y_true, y_pred = prepare... | 8e37e1ad60b1593f61d80c88b1fb6f65e5148e9f | 3,616,813 |
def _get_node_names():
"""
returns the list of nodes in the cluster
:return: the list of nodes in the cluster
:rtype: list[str]
"""
nodes = _get_nodes()
node_list = []
for n in nodes:
node_list.append(n['name'])
return node_list | 96a323e6da30c6247d7e53d7306a7d7003f25fb1 | 3,616,814 |
import collections
def defaultdict():
"""defaultdict(...): Dictionary with a value for missing keys."""
kart = collections.defaultdict(lambda: 'unknown')
kart['speed'] = 66
return "kart specs are {}".format(''.join(
'{} -> {}'.format(key, kart[key]) for key in ('speed', 'sound'))) | 71f00871b2280ce09581aa90e4645aa0424bf2de | 3,616,815 |
def execute_cast_datetime_to_integer(op, data, type, **kwargs):
"""Cast datetimes to integers"""
return pd.Timestamp(data).value | 5448a341adaae6fe58769ef43c5d0da5322aabfd | 3,616,816 |
def ferret_result_limits(efid):
"""
Abstract axis limits for the shapefile_writeval PyEF
"""
return ( (1, 1), None, None, None, None, None, ) | 9e1ef0f1ee1a0126c47e4fa46cbb5c1ee6ed52fb | 3,616,817 |
import warnings
def containment(lower_forecast, upper_forecast, actual):
"""Expects two, 2-D numpy arrays of forecast_length * n series.
Returns a 1-D array of results in len n series
Args:
actual (numpy.array): known true values
forecast (numpy.array): predicted values
"""
with ... | 7692a31337705cf5fafc9f3efb664be41e7678b7 | 3,616,818 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.