content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def memoize_with_hashable_args(func):
"""Decorator for fast caching of functions which have hashable args.
Note that it will convert np.NaN to None for caching to avoid this common
case causing a cache miss.
"""
_cached_results_ = {}
hash_override = getattr(func, "__hash_override__", None)
i... | b5e55b35042688d9131e05e36a56bf0f6515f336 | 19,064 |
def orthogonalize(vec1, vec2):
"""Given two vectors vec1 and vec2, project out the component of vec1
that is along the vec2-direction.
@param[in] vec1 The projectee (i.e. output is some modified version of vec1)
@param[in] vec2 The projector (component subtracted out from vec1 is parallel to this)
... | aceca85edfc6ed4a6c3b21cb169f993b0b30c889 | 19,065 |
import re
def tokenize(text):
"""
Function to process text data taking following steps:
1) normalization and punctuation removal: convert to lower case and remove punctuations
2) tokenization: splitting each sentence into sequence of words
3) stop words removal: removal of words which ... | 769949bc2d4a23d4064b8addcaa7dbfc29346549 | 19,066 |
def extract_text(bucketname, filepath):
"""Return OCR data associated with filepaths"""
textract = boto3.client('textract')
response = textract.detect_document_text(
Document={
'S3Object': {
'Bucket': bucketname,
'Name': filepath
}
})
... | fde7c1bc99003bf8f094538d402a66b6d0c8bcb4 | 19,067 |
def box1_input(input):
"""uses above to return input to player 1"""
return get_input(1, input) | c619be2f73fc124eb3198c27542af014eeffd3f8 | 19,068 |
def _get_xy_from_geometry(df):
"""
Return a numpy array with two columns, where the
first holds the `x` geometry coordinate and the second
column holds the `y` geometry coordinate
"""
# NEW: use the centroid.x and centroid.y to support Polygon() and Point() geometries
x = df.geometry.centroi... | 6a1345607d3c75190dd9fd22ea45aad82901282a | 19,069 |
def create_styled_figure(
title,
name=None,
tooltips=None,
plot_width=PLOT_WIDTH,
):
"""Return a styled, empty figure of predetermined height and width.
Args:
title (str): Title of the figure.
name (str): Name of the plot for later retrieval by bokeh. If not given the
... | caeb7eb887d84c5e1ebaf83b01a71ce15917a27f | 19,070 |
def render_text(string, padding=5, width=None, height=None,
size=12, font="Arial", fgcolor=(0, 0, 0), bgcolor=None):
"""
Render text to an image and return it
Not specifying bgcolor will give a transparent image, but that will take a *lot* more work to build.
Specifying a bgcolor, width... | 9402aa9cbcbb920b73723d74b944f5940db9e0e0 | 19,071 |
def pretty_spectrogram(d,log = True, thresh= 5, fft_size = 512, step_size = 64):
"""
creates a spectrogram
log: take the log of the spectrgram
thresh: threshold minimum power for log spectrogram
"""
specgram = np.abs(stft(d, fftsize=fft_size, step=step_size, real=False,
compute_onesided=... | eaae2893944df28dcefb607bac3e8648db265acf | 19,072 |
def check_for_win(position, board, player):
"""
check for wins on 3x3 board on rows,cols,diag,anti-diag
args: position (int 1-9, user input)
board (np.array 2d)
player ("X" or "O")
"""
#initialize win to False
win = False
#check win on rows
for row in board:
... | fad580912f3a281ce605fd743732481915c352ea | 19,073 |
def wrap_http_exception(app: FastAPI):
"""
https://doc.acrobits.net/api/client/intro.html#web-service-responses
"""
@app.exception_handler(StarletteHTTPException)
async def http_exception_handler(request, exc):
return JSONResponse({'message': exc.detail}, exc.status_code) | b43eea9b59eb50eaefd3d52a5569d6952518f61b | 19,074 |
import random
def perm_2sample(group1, group2, nrand=10000, tail=0, paired=True):
# Take from JW's functions
"""
non-parametric permutation test (Efron & Tibshirani, 1998)
tail = 0 (test A~=B), 1 (test A>B), -1 (test A<B)
"""
a = group1
b = group2
ntra = len(a)
ntrb = len(b)
... | afb3c56d277c583eeb34089bcd808e7e6e662ec7 | 19,075 |
def softmax_op(node):
""" This function computes its softmax along an axis.
Parameters:
----
node : Node
Input variable.
Returns:
----
A new Node instance created by Op.
"""
return SoftmaxOp()(node) | 42004658214b7b7c083d40fe43393f1cf450175b | 19,076 |
def full_chain():
"""
:return: Returns entire blockchain in memory (current_chain.blockchain)
"""
response = {
'chain': current_chain.blockchain,
'length': len(current_chain.blockchain),
}
return response, 200 | 0161195e3dc28b9157ee824f8d3103029f058498 | 19,077 |
def normalizer(x, mi, ma, eps=1e-20, dtype=np.float32):
"""
Number expression evaluation for normalization
Parameters
----------
x : np array of Image patch
mi : minimum input percentile value
ma : maximum input percentile value
eps: avoid dividing by zero
dtype: type of numpy array... | 0f39a4d02bc3f3897d0b2070567a45eb68ade2d4 | 19,078 |
def do(args):
""" Main Entry Point. """
build_worktree = qibuild.parsers.get_build_worktree(args)
sourceme = build_worktree.generate_sourceme()
print(sourceme)
return sourceme | d706fe7f8a277f58dd8f184212851d087b7890d1 | 19,079 |
import json
import traceback
def policy_action(module,
state=None,
policy_name=None,
policy_arn=None,
policy_document=None,
path=None,
description=None):
"""
Execute the actions needed to bring the poli... | 5da4c4649170e81569cc3e77fa102fd0043cebd9 | 19,080 |
def GET_v1_metrics_location(days=1):
"""Return some data about the locations users have reported from.
"""
if days > 7:
days = 7
from_time = f'-{days}d'
locations = fetch_graphite_sum('*.geoip.*', from_time=from_time)
return jsonify(locations=locations) | e9765f338c1adbbb46e203024b7637af45e2f217 | 19,081 |
def add_default_to_usage_help(
usage_help: str, default: str or int or float or bool
) -> str:
"""Adds default value to usage help string.
Args:
usage_help (str):
usage help for click option.
default (str or int or float):
default value as string for click option.
... | a40cf9a68f18beeafcb965c51e0329b4e8216fb4 | 19,082 |
def describe_deformation(el_disps, bfg):
"""
Describe deformation of a thin incompressible 2D membrane in 3D
space, composed of flat finite element faces.
The coordinate system of each element (face), i.e. the membrane
mid-surface, should coincide with the `x`, `y` axes of the `x-y`
plane.
... | e748a8ecf3cc369fb03ba835b6f0c762eeafbf07 | 19,083 |
import re
def remove_emails(text):
"""Returns A String with the emails removed """
result = re.sub(EMAIL_REGEX, "", text)
return result | 08d30119f5e32a92c3df3a7b5612ba99390e7df9 | 19,084 |
def _fit_model_residual_with_radial(lmparams, star, self, interpfunc):
"""Residual function for fitting individual profile parameters
:param lmparams: lmfit Parameters object
:param star: A Star instance.
:param self: PSF instance
:param interpfunc: The interpolation function
... | 77f4031dbf7522236c36a8e096c965766df16ccb | 19,085 |
def _whoami():
# type: () -> Tuple[str,str]
"""
Return the current operating system account as (username, fullname)
"""
username = getuser()
fullname = username
if GET_PW_NAM:
pwnam = getpwnam(username)
if pwnam:
fullname = pwnam.pw_gecos.split(",", 1)[0]
retu... | 508189e4798e83425b754ad6cde617a3b0d1ec9f | 19,086 |
from typing import Sequence
def text_set_class(
set_class: Sequence,
) -> str:
"""Converts a set class into a string representing its interval vector.
"""
id_dict = {0: "one",
1: "two",
2: "three",
3: "four",
4: "five",
5: "six"}
... | f430ddf4b32f64f37df5fb9ec984ce5a809b09a1 | 19,087 |
def Span_read(stream):
"""Read a span from an 88.1 protocol stream."""
start = Address_read(stream)
width = Offset_read(stream)
return Span(start, width) | 0bbd5d62a1111dd056a939ee272ea200e1f7abd9 | 19,088 |
def temp_database(tmpdir_factory):
""" Initalize the Database """
tmpdb = str(tmpdir_factory.mktemp('temp'))+"/testdb.sqlite"
return tmpdb | 5cfcb27e6ac76766e21a1612691dbe79d1713abd | 19,089 |
import ast
def get_classes(pyfile_path):
"""
Obtiene las clases que están dentro de un fichero python
:param str pyfile_path: nombre del fichero a inspeccionar
:return: devuelve una lista con todas las clases dentro de un fichero python
:rtype: list
.. code-block:: python
>> get_cla... | 72f376d10fd02574085a0236e10ea8901033ebd0 | 19,090 |
from typing import List
def transpose_outer_dimensions(outer_dimensions: ST_Type, diff_dimensions: ST_Type, ports_to_transpose: List) -> Kind:
"""
Transpose the outer dimensions of a set of ports, move them inside the diff dimensions. The outer dimensions
that are sseqs are the same for all elements, so t... | ca51943223bbca58f871a9cb4c6b296ae941e87d | 19,091 |
def pad_or_clip_nd(tensor, output_shape):
"""Pad or Clip given tensor to the output shape.
Args:
tensor: Input tensor to pad or clip.
output_shape: A list of integers / scalar tensors (or None for dynamic dim)
representing the size to pad or clip each dimension of the input tensor.
Ret... | a22b6872b4af4424411d26232af0c21fda7c55df | 19,092 |
def dynamic_lstm(x, n_neuron, act_fn=tanh, seq_len=None):
""" assert x is batch_major, aka [batch, time, ...] """
cell_class = lstm
with tf.variable_scope("fw"):
cell_fw = cell_class(n_neuron, activation=act_fn, cell_clip=15.0)
o, s = tf.nn.dynamic_rnn(
cell_fw, x, seq_len, ... | 4f2df8155281e3664d5d8521918af5c84a211a34 | 19,093 |
def ho2ax_single(ho):
"""Conversion from a single set of homochoric coordinates to an
un-normalized axis-angle pair :cite:`rowenhorst2015consistent`.
Parameters
----------
ho : numpy.ndarray
1D array of (x, y, z) as 64-bit floats.
Returns
-------
ax : numpy.ndarray
1D a... | 50ec25eb488ea894f6a5c6a00feab27b93954200 | 19,094 |
import json
def task_export_commit(request):
"""提交导出任务"""
try:
datas = json.loads(request.body.decode())
taskSetting = PlTaskSetting.objects.get(id=datas["params"]["id"])
try:
exportJob = PlExportJob.objects.get(task_setting_id=taskSetting.id)
except ObjectDoesNotEx... | 4ec543af62e9abab9194b22cf54e22de2551ce24 | 19,095 |
def getExceptionMessage(exceptionDetails: dict) -> str:
"""Get exception message from `exceptionDetails` object."""
exception = exceptionDetails.get('exception')
if exception:
return exception.get('description')
message = exceptionDetails.get('text', '')
stackTrace = exceptionDetails.get('st... | ba3d15aa383de9f55600a72ba113c37fd042d3a4 | 19,096 |
def evaluate_by_net(net, input_fn, **kwargs):
"""encapsulate evaluate
"""
ret = evaluate(
graph=net.graph, sess=net.session,
fea_ph=net.features_ph, label_ph=net.labels_ph, outputs=net.outputs,
input_fn=input_fn, **kwargs
)
return ret | a58b80b5e93dbb4251eb71393f8a9f70ddff813b | 19,097 |
import array
def ordinate(values,maxrange,levels):
"""Ordinate values given a maximum data range and number of levels
Parameters:
1. values: an array of continuous values to ordinate
2. maxrange: the maximum data range. Values larger than this will be saturated.
3. levels: the number of level... | 4db4a26579d9208cd90ec630cf82e54a4a7ec3fe | 19,098 |
def is_start_state(state):
"""
Checks if the given state is a start state.
"""
return (state.g_pos.value == 0) and (state.theta.value == 'N') | 0f58e7a193533ba3d5db15c4e79ed98e190fa1be | 19,099 |
def days_in_month(year, month):
""" return number of days in that month in that year """
if not 1 <= month <= 12:
return 'Invalid Month'
if month == 2 and is_leap(year):
return 29
return month_days[month] | 8e9e5878fcfb595518d33a38baaf5bdc1b45c8ed | 19,100 |
def tmm_normal(fPath, bFilter=True):
"""
Function to obtain the Voom normal Count
Args:
fPath string Path with the raw counts
outPath string File output
bFilter Bool Bool to FIlter low expression genes
Returns:
tmm dataframe DataFrame with the log2(TMM) counts
... | 4741a6af490e24485bd4ad28e7289dd320abf77d | 19,101 |
import base64
def np_to_base64(img_np):
"""
Convert numpy image (RGB) to base64 string
"""
img = Image.fromarray(img_np.astype("uint8"), "RGB")
buffered = BytesIO()
img.save(buffered, format="PNG")
return "data:image/png;base64," + base64.b64encode(
buffered.getvalue()).decode("asc... | 2856e8ccf5402b5f6615bc8b66a364cef3e3a01c | 19,103 |
def sample_unknown_parameters(_params, _n=None):
"""
AW - sample_unknown_parameters - Sample the parameters we do not fix and hence wish to marginalize over.
:param _params: SimpNameSp: dot accessible simple name space of simulation parameters.
:return: SimpNameSp: dot accessible simple name spac... | 700d4ab80cd3e798fa87f9249194015377d19cc7 | 19,104 |
import logging
def vector2Table (hdu, xlabel='wavelength',ylabel='flux') :
"""
Reads a 1-D vector from a FITS HDU into a Table.
If present, the wavelength scale is hopefully in a simple, linear WCS!
"""
hdr = hdu.header
if hdr['NAXIS'] != 1 :
logging.error ('vector2Table can only construct 1-D tables!')
ret... | b0ff458f8cf6de660ae5c314f3e9db1f50aeaf3c | 19,105 |
def get_zarr_size(fn):
"""Get size of zarr file excluding metadata"""
# Open file
grp = zarr.open_group(fn)
# Collect size
total = 0
for var in list(grp.keys()):
total += grp[var].nbytes_stored
return total | e2fe053bf239156e74038672a435144cf7bc5216 | 19,106 |
def rotation_matrix(a, b):
""" Calculate rotation matrix M, such that Ma is aligned to b
Args:
a: Initial vector direction
b: Target direction
"""
# np.allclose might be safer here
if np.array_equal(a, b):
return np.eye(3)
# Allow cases where a,b are not unit vectors, s... | 948eb08758b81a6b9f2cc0f518dbb74f04970a1c | 19,107 |
def saveuserprefs():
""" Fetch the preferences of the current user in JSON form """
user = current_user()
j = request.get_json(silent=True)
# Return the user preferences in JSON form
uf = UserForm()
uf.init_from_dict(j)
err = uf.validate()
if err:
return jsonify(ok=False, err=e... | 0b2e893623432f0337014df3f0a67a4d2174a082 | 19,109 |
import torch
def make_features(batch, side, data_type='text'):
"""
Args:
batch (Tensor): a batch of source or target data.
side (str): for source or for target.
data_type (str): type of the source input.
Options are [text|img|audio].
Returns:
A sequence of src/t... | 6ffed5546ea35a7be559f58521aa119d576ed465 | 19,111 |
def page_dirs_to_file_name(page_dirs):
"""
[カテゴリ1,カテゴリ2,ページ]というディレクトリの配列状態になっているページパスを
「カテゴリ1_._カテゴリ2_._ページ」というファイル名形式に変換する。
:param page_dirs:
:return:
"""
file_name = ""
for page_dir in page_dirs:
if page_dir:
file_name = file_name + page_dir.strip() + '_._'
fil... | 1e7bb5f04900440824e7a223fbb88599add86c07 | 19,112 |
def has_field(feature_class, field_name):
"""Returns true if the feature class has a field named field_name."""
for field in arcpy.ListFields(feature_class):
if field.name.lower() == field_name.lower():
return True
return False | afe2352a1a17b9c0c48e68b68ab41595230343f9 | 19,113 |
from re import T
def process_settings(settings: AttrDict, params: T.Optional[T.Set[str]] = None, ignore: T.Iterable[str]=()) -> AttrDict:
"""
Process an dict-like input parameters, according to the rules specified in the
`Input parameter documentation <https://sqsgenerator.readthedocs.io/en/latest/input_... | 0cd49f857fe2923d71fb4be46cac4eefa1fa11bf | 19,114 |
def serialize_block(block: dict) -> Block:
"""Serialize raw block from dict to structured and filtered custom Block object
Parameters
----------
block : dict
Raw KV block data from gRPC response
Returns
-------
Block
Structured, custom defined Block object for more controll... | 05931685b970a562b108df134e26c6857bd9bb6a | 19,115 |
from pandas import get_option
def repr_pandas_Series(series, _):
"""
This function can be configured by setting the `max_rows` attributes.
"""
return series.to_string(
max_rows=repr_pandas_Series.max_rows,
name=series.name,
dtype=series.dtype,
length=get_option("displa... | 86009d8fc1559dd97361a8c5e113c5477ff73de2 | 19,116 |
def convert_fmt(fmt):
"""rs.format to pyglet format string"""
return {
rs.format.rgb8: 'RGB',
rs.format.bgr8: 'BGR',
rs.format.rgba8: 'RGBA',
rs.format.bgra8: 'BGRA',
rs.format.y8: 'L',
}[fmt] | b2f34498969d2e29d8c21367788ddcaebe205acf | 19,117 |
import math
def train_ALS(train_data, validation_data, num_iters, reg_param, ranks):
"""
Grid Search Function to select the best model based on RMSE of hold-out data
"""
# initial
min_error = float('inf')
best_rank = -1
best_regularization = 0
best_model = None
for rank in ranks:
... | 99d0584e9374a529632024caeadb88d85c681b81 | 19,118 |
import copy
def response_ack(**kwargs):
""" Policy-based provisioning of ACK value. """
try:
tlv, code, policy, post_c2c = kwargs["tlv"], kwargs["code"], kwargs["policy"], kwargs["post_c2c"]
new_tlv = copy.deepcopy(tlv)
if post_c2c is not True:
ret = policy.get_ava... | ff34cf196e0d565ebac7700f5b412f615685ca37 | 19,121 |
def is_file(path, use_sudo=False):
"""
Check if a path exists, and is a file.
"""
func = use_sudo and sudo or run
with settings(hide('running', 'warnings'), warn_only=True):
return func('[ -f "%(path)s" ]' % locals()).succeeded | 9b3402205fe972dbedfa582117b6d03bdb949122 | 19,122 |
def bounded_random_walk(minval, maxval, delta_min, delta_max, T,
dtype=tf.float32, dim=1):
"""
Simulates a random walk with boundary conditions. Used for data augmentation
along entire tube.
Based on: https://stackoverflow.com/questions/48777345/vectorized-random-
... | 18bba29b9f0c320da04eb2419a49483ee301e178 | 19,123 |
def validate_photo_url(photo_url, required=False):
"""Parses and validates the given URL string."""
if photo_url is None and not required:
return None
if not isinstance(photo_url, str) or not photo_url:
raise ValueError(
'Invalid photo URL: "{0}". Photo URL must be a non-empty '
... | 9c6d617d4b618f626c29977b0a7c4c9dc9b3f9ab | 19,124 |
def to_flp(stipples, dpi=300, x_mm=0, y_mm=0, laser_pwr=35000,
ticks=500, base=100):
"""" Converts a set of stipples into a list of FLP packets
dpi is the image's DPI
x_mm and y_mm are the corner location of the image (default 0,0)
(where 0,0 is the center of the b... | 9d826b6174478cbfb3d2033e05b9ccafb5dca79c | 19,125 |
def GetSchema(component):
"""convience function for finding the parent XMLSchema instance.
"""
parent = component
while not isinstance(parent, XMLSchema):
parent = parent._parent()
return parent | 3445acb7bade3cca15d4eeeb3da4d548ea44a206 | 19,126 |
def ranked_bots_query(alias="ranked_bots"):
"""
Builds a query that ranks all bots.
This is a function in case you need this as a subquery multiple times.
"""
return sqlalchemy.sql.select([
bots.c.user_id,
bots.c.id.label("bot_id"),
bots.c.mu,
bots.c.sigma,
b... | f6641efa611884721e33453f4fcc4af0503b4aaf | 19,127 |
def marathon_deployments_check(service):
"""Checks for consistency between deploy.yaml and the marathon yamls"""
the_return = True
pipeline_deployments = get_pipeline_config(service)
pipeline_steps = [step['instancename'] for step in pipeline_deployments]
pipeline_steps = [step for step in pipeline_... | 3f2df53652efad4b731a05b3ecc17929d65982ac | 19,128 |
def get_book_info(book_id, books):
"""Obtain meta data of certain books.
:param book_id: Books to look up
:type: int or list of ints
:param books: Dataframe containing the meta data
:type: pandas dataframe
:return: Meta data for the book ids
:rtype: List[str], List[str], List[str]
"... | 64a91a498f9bf9df918d256a7ce705e98dadbbd9 | 19,129 |
import functools
import six
def save_error_message(func):
"""
This function will work only if transition_entity is defined in kwargs and
transition_entity is instance of ErrorMessageMixin
"""
@functools.wraps(func)
def wrapped(*args, **kwargs):
try:
return func(*args, **kwa... | 9ac592100445a0232efc4afaa3807b050c8eddff | 19,130 |
def EMV(data,n=20,m=23):
"""
"""
def emv(high,low,vol,n=14):
MID = np.zeros(len(high))
MID[1:] = (np.array(high[1:])+np.array(low[1:])-np.array(high[:-1])-np.array(low[:-1]))/2.
BRO = np.array(vol)/(100000000.*(np.array(high)-np.array(low)))
EM = MID/BRO
return ta.S... | a3555738c2f0c047ad4c21ae32dcfed460a9ec5b | 19,131 |
from typing import Tuple
def desired_directions(state: np.ndarray) -> Tuple[np.ndarray, np.ndarray]:
"""Given the current state and destination, compute desired direction."""
destination_vectors = state[:, 4:6] - state[:, 0:2]
directions, dist = normalize(destination_vectors)
return directions, dist | 02088734bd3ef6ec2e1b009d5c43e6ea9f008aab | 19,132 |
import operator
def binary_repr(number, max_length = 1025):
"""
Return the binary representation of the input *number* as a
string.
This is more efficient than using :func:`base_repr` with base 2.
Increase the value of max_length for very large numbers. Note that
on 32-bit machines, 2**1023 ... | 40d0198067722d8d4c1ef1e1a195ce6817ab0935 | 19,133 |
def df_fc_overlap_9():
"""Scenario case with 3 sets of 2 overlapping fragments, bound to a common combination of 2 redundant fragments."""
mol = Chem.MolFromSmiles('NC1C(O)C(CCCC2CC2CCC2CC2)C1CCC1CC(C(N)C1O)C1CCC(O)C(N)C1')
return DataFrame([
['mol_fc_overlap_9', 'XXX', 'O1', 0, 'O1:0', ... | 5a86bce8741b76ac265b5a1865f7d3d1ad8970ea | 19,134 |
import requests
import json
def check_cal(es_url, es_index, id):
"""Query for calibration file with specified input ID."""
query = {
"query":{
"bool":{
"must": [
{ "term": { "_id": id } },
]
}
},
"fields": [],... | 10aab4dd6587b901cda543298c13662e6edeb0e1 | 19,135 |
def mountpoint_create(name, size):
"""Service Layer to create mountpoint"""
mountpoint = MountPoint(name, size)
return mountpoint | d52be1773b3cfad62423d2695b42d56ca83f7eaf | 19,136 |
import requests
import json
def GetTSAWaitTimes(airportCode):
"""
Returns data from the TSA Wait Times API for a particular airport shortcode.
:param airportCode: 3-letter shortcode of airport
:return: Returns the full parsed json data from TSA Wait Times API
"""
base_url = "http://apps.tsa.dh... | bd03be14c95a3892ac75a0396da12ca04b52a59b | 19,137 |
def False(context):
"""Function: <boolean> false()"""
return boolean.false | 93d1f1c9fbe9cf7bb02d5caac2c01ed7d0d9a2dc | 19,138 |
def namedtuple_to_dict(model_params):
"""Transfers model specification from a
named tuple class object to dictionary."""
init_dict = {}
init_dict["GENERAL"] = {}
init_dict["GENERAL"]["num_periods"] = model_params.num_periods
init_dict["GENERAL"]["num_choices"] = model_params.num_choices
... | 9ac2f23aff3b9c57599eb2c2c6cacd455ac711a5 | 19,139 |
def roberts(stream: Stream, *args, **kwargs) -> FilterableStream:
"""https://ffmpeg.org/ffmpeg-filters.html#roberts"""
return filter(stream, roberts.__name__, *args, **kwargs) | ff58eaea65d536b47614050600c91136dc2d6f7e | 19,140 |
import json
def run_code():
"""
codec api response
{
"error": {
"decode:": "error message"
},
"output": {
"status_code": 0,
"result": {
"data_type": "event",
"data": {
"humidity": {
"time": 1547... | 96118a1c74b027716a68d7c1f25eb3585e1a255c | 19,141 |
def build_dense_conf_block(x, filter_size=32, dropout_rate=None):
"""
builds a dense block according to https://arxiv.org/pdf/1608.06993.pdf
:param x:
:param dropout_rate:
:param filter_size
:return:
"""
x = BatchNormalization(axis=-1, epsilon=1.1e-5)(x)
x = Activation('relu')(x)
... | 2cb9639ed620d32c513ecbccf2c311360cc3cb9d | 19,143 |
def _viz_flow(u, v, logscale=True, scaledown=6):
"""
Copied from @jswulff:
https://github.com/jswulff/pcaflow/blob/master/pcaflow/utils/viz_flow.py
top_left is zero, u is horizon, v is vertical
red is 3 o'clock, yellow is 6, light blue is 9, blue/purple is 12
"""
color_wheel = _color_wheel()
n_cols =... | 43901f227bc30367910bc41f9ba324bcc217bdbf | 19,144 |
def submission_history(request, course_id, learner_identifier, location):
"""Render an HTML fragment (meant for inclusion elsewhere) that renders a
history of all state changes made by this user for this problem location.
Right now this only works for problems because that's all
StudentModuleHistory rec... | dd0459844b4f30e653dacf474cdb5ddf186ed0dc | 19,145 |
def tou(month, weekday, hour):
""" Calculate TOU pricing
"""
if weekday in [0, 6]:
return OFFPEAK
else:
if month in [5, 6, 7, 8, 9, 10]:
if hour in [11, 12, 13, 14, 15, 16]:
return ONPEAK
elif hour in [7, 8, 9, 10, 17, 18, 19, 20]:
... | 31708916be97d52d229499053b0b3d29603fdfb9 | 19,146 |
import json
def get_job(request):
""" Retrieve a specific Job
URL: /admin/Jobs/GetOne
:param request:
:return:
"""
id = request.GET.dict().get("id")
response = {
'status': 1,
'status_message': 'Success',
'job': job.objects.filter(id=id)
}
return HttpRe... | 82d4c981b48fb0274ae4f2f888149b11ed731b88 | 19,147 |
def cpt_lvq_merid_deriv(temp, sphum):
"""Meridional derivative of c_p*T + L_v*q on pressure coordinates."""
deriv_obj = LatCenDeriv(cpt_lvq(temp, sphum), LAT_STR)
return deriv_obj.deriv() | 629a630bb0663b16f20fb0f7d68ca54ebebc7e21 | 19,148 |
def hubert_pretrain_large(
encoder_projection_dropout: float = 0.0,
encoder_attention_dropout: float = 0.0,
encoder_ff_interm_dropout: float = 0.0,
encoder_dropout: float = 0.0,
encoder_layer_drop: float = 0.0,
) -> HuBERTPretrainModel:
# Overriding the signature so that the return type is corre... | dd57cfcb803424ed46fcb597a71aa8e88de3ad32 | 19,150 |
def random_scaled_rotation(ralpha=(-0.2, 0.2), rscale=((0.8, 1.2), (0.8, 1.2))):
"""Compute a random transformation matrix for a scaled rotation.
:param ralpha: range of rotation angles
:param rscale: range of scales for x and y
:returns: random transformation
"""
affine = np.eye(2)
if rsc... | f6216486e94fa7eac0be75b2a420fc1f251987c2 | 19,151 |
import time
def time_as_int() -> int:
"""
Syntactic sugar for
>>> from time import time
>>> int(time())
"""
return int(time.time()) | f7f6d037d156c09a01c0ff13f8b43418133ab1b0 | 19,152 |
from unittest.mock import Mock
from unittest.mock import patch
def test_end_response_is_one_send():
"""Test that ``HAPServerHandler`` sends the whole response at once."""
class ConnectionMock:
sent_bytes = []
def sendall(self, bytesdata):
self.sent_bytes.append([bytesdata])
... | 7c28c6b6fb8f123daa75f9710c26d5345810160b | 19,153 |
def compute_norm_cond_entropy_corr(data_df, attrs_from, attrs_to):
"""
Computes the correlations between attributes by calculating
the normalized conditional entropy between them. The conditional
entropy is asymmetric, therefore we need pairwise computation.
The computed correlations are stored in ... | 12dafa7ecb941c008ab2bb7c93ed6e0c8b1302ad | 19,154 |
def should_retry_http_code(status_code):
"""
:param status_code: (int) http status code to check for retry eligibility
:return: (bool) whether or not responses with the status_code should be retried
"""
return status_code not in range(200, 500) | 69acb5bd34b06e1ff1e29630ac93e60a3ccc835c | 19,155 |
def softmax(x):
"""Calculates the softmax for each row of the input x.
Your code should work for a row vector and also for matrices of shape (n, m).
Argument:
x -- A numpy matrix of shape (n,m)
Returns:
s -- A numpy matrix equal to the softmax of x, of shape (n,m)
"""
# Apply exp() el... | d4905ec1a145aae47532b43a66a00a29180a37e4 | 19,156 |
def inertia_tensor_eigvals(image, mu=None, T=None):
"""Compute the eigenvalues of the inertia tensor of the image.
The inertia tensor measures covariance of the image intensity along
the image axes. (See `inertia_tensor`.) The relative magnitude of the
eigenvalues of the tensor is thus a measure of the... | af48827b709b48cdae7b2a8fe7ad3723845ee6cd | 19,157 |
def extract_values(inst):
"""
:param inst: the instance
:return: python values extracted from the instance
"""
# inst should already be python
return inst | 087bb00ee6e3666b4a9e682ca420623982a12102 | 19,158 |
def voc_ap(rec, prec, use_07_metric=False):
""" ap = voc_ap(rec, prec, [use_07_metric])
Compute VOC AP given precision and recall.
If use_07_metric is true, uses the
VOC 07 11 point method (default:False).
"""
if use_07_metric:
# 11 point metric
ap = 0.
for t in np.arange(0., 1.1, 0.1):
if np.sum(rec ... | e9a4ebec8908e306bcf12e2e9538a8de8b74e84b | 19,159 |
def is_on_path(prog):
"""Checks if a given executable is on the current PATH."""
r = runcmd("which %s" % prog)
if r.failed:
return False
else:
return r | 1019ab3b08ef97c307588f8902a7884a89039998 | 19,160 |
def validate_entry(new_text) -> bool:
"""Função callback para validação de entrada dos campos na janela
ExperimentPCR.
É chamada toda vez que o usuário tenta inserir um valor no campo de
entrada.
Uma entrada válida deve atender os seguintes requisitos:
-Ser composto apenas de números intei... | 8e0f5f126d0688279fc28a8be287fda00d346a59 | 19,161 |
import io
def eia_cbecs_land_call(*, resp, url, **_):
"""
Convert response for calling url to pandas dataframe, begin
parsing df into FBA format
:param resp: df, response from url call
:param url: string, url
:return: pandas dataframe of original source data
"""
# Convert response to d... | 396079863ecc2faa6420e90f3d608ff997a3fb39 | 19,162 |
def add_l2_interface(interface_name, interface_desc=None, interface_admin_state="up", **kwargs):
"""
Perform a POST call to create an Interface table entry for physical L2 interface.
:param interface_name: Alphanumeric Interface name
:param interface_desc: Optional description for the interface. Defaul... | d27b4b5ec738a5a508a3fc9d8852ecf5df56debe | 19,163 |
import pkg_resources
def language_descriptions():
"""
Return a dict of `LanguageDesc` instances keyed by language name.
"""
global languages
if languages is None:
languages = {}
for language in pkg_resources.WorkingSet().iter_entry_points(
group='textx_languages'):
... | 236b8fd595f1b4754eeca2b8b17a88fa36090ca5 | 19,164 |
import six
def load_fixtures(fixtures_dict=None):
"""
Loads fixtures specified in fixtures_dict. This method must be
used for fixtures that don't have associated data models. We
simply want to load the meta into dict objects.
fixtures_dict should be of the form:
{
'actionchains': ['act... | b43c1303a7c54a571a0e3ddf7881d7113371e293 | 19,165 |
def generate_sbm(sizes, probs, maxweight=1):
"""Generate a Stochastic Block Model graph.
Assign random values drawn from U({1, ..., maxw}) to the edges.
sizes : list of sizes (int) of the blocks
probs : matrix of probabilities (in [0, 1]) of edge creation
between nodes dependi... | c6b0a106d88016afc99bf45abeb7c60af2981d77 | 19,166 |
import re
def eq_portions(actual: str, expected: str):
"""
Compare whether actual matches portions of expected. The portions to ignore are of two types:
- ***: ignore anything in between the left and right portions, including empty
- +++: ignore anything in between left and right, but non-empty
:p... | 704b2a83575347c5143c2dc0aca5227a8fc5bd4b | 19,167 |
def _get_encoder(
in_features: int,
embed_dim: int,
dropout_input: float,
pos_conv_kernel: int,
pos_conv_groups: int,
num_layers: int,
num_heads: int,
attention_dropout: float,
ff_interm_features: int,
ff_interm_dropout: float,
drop... | 72ff9887575905172db0b095b3d6822ee6b51411 | 19,168 |
def _soft_threshold(a, b):
"""Soft-threshold operator for the LASSO and elastic net."""
return np.sign(a) * np.clip(np.abs(a) - b, a_min=0, a_max=None) | 34f28c1154cf9eefecc19e1ece8dfa3ca82e677e | 19,169 |
def predict(input_tokens):
"""register predict method in pangu-alpha"""
token_ids, valid_length = register.call_preprocess(preprocess, input_tokens)
############# two output ###################
# p, p_args = register.call_servable(token_ids)
# add_token = register.call_postprocess(postprocess, p, p_... | f2de6ff2ba78c3cac47a823bfe7a201a9a6b93ad | 19,170 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.