content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def reproject_to_template(input_raster, template_raster, output_raster, resolution=None,
resampling=gdal.GRA_Bilinear, nodata_val=0):
"""
Reprojects a raster to match the extent, cell size, projection and dimensions of a template
raster using GDAL. Optionally, can set custom resolu... | 76788873377331f95d3e886ed2d7c0b0c50a2a4d | 3,600,799 |
def create_ssviz_spreadsheet_and_feature_data(user_id, file_id,\
is_file_samples_as_rows, sample_names, feature_names, feature_types,\
feature_nan_counts, sample_nan_counts, ss_df):
"""Creates a record in ssviz_spreadsheet and records in ssviz_feature_data
for a spreadsheet used in SSV.
... | 05496ebcda13532675fcf223ad85da49ee4d083c | 3,600,800 |
def create_empty(val=0x00):
"""Create an empty Userdata object.
val: value to fill the empty user data fields with (default is 0x00)
"""
user_data_dict = {}
for index in range(1, 15):
key = "d{}".format(index)
user_data_dict.update({key: val})
return user_data_dict | 55e614059940b7eda5a0684dd105a60dbc7f1549 | 3,600,801 |
def make_dataloader(dataset, wandb_config, eval=False):
"""
The DataLoader needs to know our batch size for training, so we specify it here.
For fine-tuning BERT on a specific task, the authors recommend a batch size of 16 or 32.
:param dataset: Torch TensorDataset (see make_tensor_dataset)
:param ... | abcf3bc2e0bf237f72fa51852a82adc4830c4c0d | 3,600,802 |
def getDistanceByPoint(data, model):
""" Function that calculates the distance between a point and centroid of a cluster,
returns the distances in pandas series"""
distance = []
for i in range(0,len(data)):
Xa = np.array(data.loc[i])
Xb = model.cluster_centers_[model.labels_[i]-... | 03f4dbd21a5e8d4c7347c600985ff11c8f9eb27c | 3,600,804 |
import re
def remove_tags(text):
"""
remove html style tags from some text
"""
cleaned = re.sub('<[^>]+>', '', text)
return re.sub('\s+',' ', cleaned).strip() | 5bbce34ca179f871eca6306f7fbe50b5cc1ee893 | 3,600,805 |
def AccelWalk_quad(pos, tree, softening=0, no=-1, theta=0.7): #,include_self_potential=False):
"""Returns the gravitational acceleration field at position x by performing the Barnes-Hut treewalk using the provided octree instance. Uses the quadrupole expansion.
Arguments:
pos - (3,) array containing positi... | f2c3281b7df589f09bb61585626cd570ca5c3cc1 | 3,600,806 |
def obsTime_onAxis_integrated(RRs, Gams, Betas):
"""
Very crude numerical integration to obtain the on-axis observer time
"""
TTs = zeros(len(Betas))
integrand = 1./(cc*Gams**2.*Betas*(1.+Betas))
TTs[0] = RRs[0]/(cc*Gams[0]**2.*Betas[0]*(1.+Betas[0]))
for ii in range(1,len(Betas)):
... | 97a8815c90cbbbe2a7c01895c6f30bb4d6c86a5b | 3,600,807 |
def decorator_blank_line_and_sleep(function):
""" This decorator just waits one second and prints a blank line after executing function"""
def inner_wrapper(*args, **kwargs):
input("")
value = function(*args, **kwargs)
print()
return value
return inner_wrapper | 1f544c87990c24b0cd82eeefe524cdf0649de69b | 3,600,808 |
def get_note_type(syllables, song_db) -> list:
"""
Function to determine the category of the syllable
Parameters
----------
syllables : str
song_db : db
Returns
-------
type_str : list
"""
type_str = []
for syllable in syllables:
if syllable in song_db.motif:
... | 621448603581a56af22ec9c559f9854c62073318 | 3,600,809 |
import json
import time
def run_job(queue_id,
wes_id,
wf_jsonyaml,
opts=None,
add_attachments=None,
submission=False):
"""
Put a workflow in the queue and immmediately run it.
:param str queue_id: String identifying the workflow queue.
:para... | 6f4ceba015859c0b4d1d44d9d54ea934fa9311f7 | 3,600,810 |
import asyncio
def _get_selector_noop(loop) -> asyncio.AbstractEventLoop:
"""no-op on non-Windows"""
return loop | b2b53006c66a2900642858a9bc975c54225d8034 | 3,600,811 |
def get_plain_text(values, strip=True):
"""Get the first value in a list of values that we expect to be plain-text.
If it is a dict, then return the value of "value".
:param list values: a list of values
:param boolean strip: true if we should strip the plaintext value
:return: a string or None
... | 3c0937d1faefda4ba8649005e29c9961afbadc0a | 3,600,812 |
def user_management_url(context):
"""Construct url for user Management."""
return urljoin(context.core_v2_api_url,
'/user') | c4b7b02e2e8c665ad3e56e9e7b4917ad4181d02a | 3,600,813 |
def get_reverse_complement(dna):
""" Computes the reverse complementary sequence of DNA for the specfied DNA
sequence
dna: a DNA sequence represented as a string
returns: the reverse complementary DNA sequence represented as a string
>>> get_reverse_complement("ATGCCCGCTTT")
'AAAGCGG... | 8d9e517c60ba961efb27409f692dbec3017c9976 | 3,600,814 |
def load_image(image_file, mode=None):
"""Load filename into a numpy array, filling in transparency with 0's.
Parameters
----------
image_file : str
File to load. Usually works with .jpg and .png.
Returns
-------
numpy.ndarray of resulting image. Has shape (w, h), (w, h, 3), or (w,... | 82d08e45b65abfe85c6c739109c51d5dcf1d6cd9 | 3,600,816 |
def A_matrix_complex(mesh):
"""
Area matrix for complex parametrization
See this course:
https://www.cs.cmu.edu/~kmcrane/Projects/DDG/
section 7.4.
CURRENTLY ONLY FOR A MESH WITH A SINGLE BOUNDARY (no holes)
Parameters
----------
mesh : trimesh
Returns
-------
A : area... | c5fdc197884b06f98dd1c2b7119acae2389bd742 | 3,600,817 |
def _convert_string_to_device_name(name: str) -> str:
"""Convert string device name to hexadecimal before sending.
Args:
name: the desired name for conerting.
Return:
Hexadecimal represntation of the name argument.
Raises:
aioswitcher.erros.EncodingError: when failed hexlify.
N... | 4354569556add20a38100cdb0490959ced743663 | 3,600,818 |
from pathlib import Path
from typing import List
def read_relations(file_path: Path) -> List[RelationTarget]:
"""Read config file containing relational information."""
with open(file_path) as file:
relations: List[RelationTarget] = load(file)
return relations | 70b438b45d36d6714a376651be4f89c14d560239 | 3,600,819 |
def move_polygon(polygon_coords=None, move_coords=None, limit_x=None, limit_y=None):
"""
update coordinate pairs in a list by the specified coordinate pair that represents distance
:param polygon_coords: a list of coordinate pairs
:param move_coords: a coordinate pair that holds offset values for the x... | 4f21f5e6e561697edde7e1e3c6baefada16fe7e9 | 3,600,821 |
def temporary_json_directory(tmpdir_factory) -> local:
"""Create a temporary directory for a JSON file"""
return tmpdir_factory.mktemp("json") | 116852613e231a23262ec5fa517d176b4753bb10 | 3,600,822 |
def _check_status_for_restype(restype, json_data):
"""
Depending on the resource type, check that it is "ready" or "complete"
Uses the status json from an 'oc get'
Returns True if ready, False if not.
"""
restype = parse_restype(restype)
if restype != "pod" and restype not in _CHECKABLE_RES... | 3084af31ce482a2d6811917f9704b0fc307a81af | 3,600,823 |
def bearer_oauth(r):
"""
Method required by bearer token authentication.
"""
r.headers["Authorization"] = f"Bearer {bearer_token}"
r.headers["User-Agent"] = "v2RecentSearchPython"
return r | f460648783f99f0543ef2d0e44d4aa36e40b2598 | 3,600,824 |
def create_dataset(data_file=None, do_shuffle=True, device_num=1, rank=0, batch_size=1,
num=None, num_parallel_workers=1):
"""Read train data"""
dataset = ds.MindDataset(data_file,
columns_list=["word_ids", 'word_segment_ids', "word_attention_mask",
... | 61f6ba5ff350bdb41be3faa74ade8aca6d556b9c | 3,600,825 |
from typing import Any
from typing import Optional
def password(
message: str,
default: str = "",
validate: Any = None,
qmark: str = DEFAULT_QUESTION_PREFIX,
style: Optional[Style] = None,
**kwargs: Any,
) -> Question:
"""Question the user to enter a secret text not displayed in the prompt... | b76388ad0f1d9d07fd75210b4e209047c95bc7c4 | 3,600,826 |
def validate_request(request):
"""
Make sure the request is from Twilio and is valid.
Ref: https://www.twilio.com/docs/security#validating-requests
"""
# Forgot where this token if from. Different from above.
# From: https://www.twilio.com/user/account/developer-tools/test-credentials
# Sho... | a83f3065fcebcb8231be4ed5558743fa6d837754 | 3,600,827 |
def powerstat_ucsm(sg, wanted_servers):
"""
Get the power stat of the UCS Manager servers.
"""
try:
handle = UCSUtil.ucs_login(sg)
except KubamError as e:
return jsonify({"error": str(e)}), Const.HTTP_UNAUTHORIZED
try:
powerstat = UCSServer.list_servers(handle)
i... | df04c8ff5f9c2c197bd429fc8712f915b9611d22 | 3,600,828 |
import requests
def upgradeFirmware(host, api_key):
"""
Method that upgrades firmware on an ExtraHop system
Parameters:
host (str): The IP address or hostname of the ExtraHop system
api_key (str): An API key on the ExtraHop system
Returns:
str: The relativ... | 7f8479d7becfd7f8c99f6d6acff0a225a27b7889 | 3,600,829 |
def compute_ap(recall, precision):
"""
Computes the average precision, given the recall and precision curves.
Code originally from https://github.com/rbgirshick/py-faster-rcnn.
Args:
recall (list): The recall curve.
precision (list): The precision curve.
Returns:
The av... | 086d6fe9187849e0716e48fc1710e47e1b6a19cf | 3,600,830 |
def prepare_extraction(features, in_folder, out_folder):
"""
Create the necessary folders for the extraction.
Args:
features: list of features to get names of image_extractor from.
in_folder: path to input files to get labels from.
out_folder: path to the output folder where to stor... | 00068f8f98768cd19f45854732f1bc2add7380d1 | 3,600,831 |
def fodo_lattice(mux, muy, L, fill_fac=0.5, angle=0, start='drift', fringe=False,
reverse=False):
"""Create a FODO lattice.
Parameters
----------
mux{y}: float
The x{y} lattice phase advance [deg]. These are the phase advances
when the lattice is uncoupled (`angle` ... | 99f95647e8754d00d6af0920474787ea730d9276 | 3,600,832 |
def create_normal_distribution_connection(name, from_group_amount, to_group_amount, stddev=0.02):
"""
Normal distribution initializer of a connection.
Parameters
----------
name : str
Name of the Tensor.
from_group_amount : int
Number of cells in the 'from_group'.
to_group_amount : int
... | 8903fd6c18a9aa14e44969c325f1986a6a2ac54e | 3,600,833 |
def has_internet_connection(url=INTERNET_CONNECTION_URL):
"""Returns a boolean indicating if an internet connection if present.
:param url: the url used to check if a connection can be made
"""
try:
urlopen(url=url)
return True
except URLError:
return False | 715b4817448634c5c97d64db7f463ee7243790ca | 3,600,834 |
def delete_stack(token, stack_name, stack_id):
"""
Asks OpenStack Heat to delete a stack
"""
url = token.get_service_url(OPENSTACK_SERVICE.HEAT)
if url is None:
raise ValueError("OpenStack Heat URL is invalid")
api_cmd = url + "/stacks/%s/%s" % (stack_name, stack_id)
response = res... | fe9f7ca37c7eefec79047e455800348d201465af | 3,600,835 |
def _to_struct_of_array(array_of_struct):
"""
utility function that convert array of struct (AoS) to struct of array (SoA),
which is more suitable for ML application down the road (ex: PyTorch).
"""
if not array_of_struct:
return {}
keys = array_of_struct[0].__dict__.keys()
return {
... | 86b76546083f5fc869ddfc3b2b19a2e92f8fa727 | 3,600,836 |
from datetime import datetime
import copy
def create_available_block(begin_datetime, end_datetime):
"""
Create a time table for each day.
:param begin_datetime: str
:param end_datetime: str
:return: list, list
"""
# initialize variables
block_bounds = []
time_blocks = []
# con... | 0b21ef1ffcb4e8cff62512a15eb0267681206b86 | 3,600,837 |
def subset_sum2(x_table, r_target):
"""Subsetsum by splitting
:param x_table: table of values
:param r_target: target value
:returns bool: if there is a subsequence of x_table with total sum r_target
:complexity: :math:`O(n^{\\lceil n/2 \\rceil})`
"""
k = len(x_table) // 2 # di... | eda7a6238c31c8cb8157ee2ec34c7db5352d13fc | 3,600,839 |
import PIL
def text_image(text_path, font_path=None):
"""Convert text file to a grayscale image with black characters on a white background.
arguments:
text_path - the content of this file will be converted to an image
font_path - path to a font file (for example impact.ttf)
"""
grayscale = '... | b2af56362e50885c3fa341f32bddaebf60a60996 | 3,600,840 |
def mathprod(seq): # math.prod function is available at python 3.8
"""
returns product of sequence elements
"""
v = seq[0]
for s in seq[1:]:
v *= s
return v | b75ff229e4cfaabe42e542367dd27e257f1d33ec | 3,600,841 |
import functools
def require_aggregate_exists(f):
"""Decorator to require the specified aggregate to exist.
Requires the wrapped function to use context and aggregate_id as
their first two arguments.
"""
@functools.wraps(f)
def wrapper(context, aggregate_id, *args, **kwargs):
aggrega... | dc302fac1b563c17077c1c7a074c4b2502c299a7 | 3,600,843 |
def DWD(input_shape=(500, 500, 1), n_classes=124, n_energybins=10):
"""
Create a deepwatershed model. The model takes an image of size input_shape
(default to (500,500,1)). The model predicts 3 types of outputs:
- energy_output: quantized energy on every pixel
- class_output: class prediction o... | 2ab6e0836728627d87c08ff807ddbaa1a44ea7ad | 3,600,844 |
def build_forward_rates(rateconstantlist, temp, convert='cal'):
"""
This function builds the forward rate values for all
the reactions. The Arrhenius rate parameters are found
in the rateconstantlist file.
Parameters
----------
rateconstantlist : str
path o... | e8f311c031a5a136d41aadae8577239bdc4f94d3 | 3,600,845 |
def control_2_8_ensure_kms_cmk_rotation(regions):
"""Summary
Returns:
TYPE: Description
"""
result = True
failReason = ""
offenders = []
offenders_links = []
control = "2.8"
description = "Ensure rotation for customer created CMKs is enabled"
scored = True
for n in r... | 67dd52101141db76498c04e8f67d4c8f5418e965 | 3,600,846 |
def ReadDrMemorySuppressions(lines, supp_descriptor):
"""Given a list of lines, returns a list of DrMemory suppressions.
Args:
lines: a list of lines containing suppressions.
supp_descriptor: should typically be a filename.
Used only when parsing errors happen.
"""
lines = StripAndSkipCommentsIte... | 738b311d2f47fc932bf6b9304747f7935803ebb2 | 3,600,847 |
from typing import List
from typing import Any
def _split_list_into_chunks(x: List[Any], chunk_size: int = 50) -> List[List[Any]]:
"""Helper function that splits a list into chunks."""
chunks = [x[i:i + chunk_size] for i in range(0, len(x), chunk_size)]
return chunks | b9972b57a18a97fceec78ec1d55156c83d255f9f | 3,600,848 |
def uniform_dist(x):
"""Returns a uniform distribution with same shape as the given numpy array.
Args:
x: numpy array
Returns:
constant numpy array of same shape as input x, sums to 1
"""
return np.ones_like(x) / float(x.size) | 4fd3533f3d0573a03677ee6a906a29da20b77f83 | 3,600,850 |
from typing import List
from datetime import datetime
import calendar
import warnings
def get_shfe_inv_1(date: str = None, vars_list: List = cons.contract_symbols):
"""
抓取上海期货交易所注册仓单数据, 适用20081006至20140518(包括) 20100126、20101029日期交易所格式混乱,直接回复脚本中DataFrame, 20100416、20130821日期交易所数据丢失
:param date: 开始日期 format... | e638f8acb45a5743241119f6f21373c0f9e157f3 | 3,600,851 |
def compare_messages_lock_status(self, messages):
""" compare messages """
# set counter
message_counter = 0
# compare - messages
self.assertEqual(messages[message_counter].message, '1 system was created.')
self.assertEqual(messages[message_counter].level_tag, 'success')
message_counter +=... | d0972a5eb114d27942c81f12098cb6b2be7b66c3 | 3,600,852 |
import re
def define_id (s):
"""Return a conventional macro identifier from a pseudo-file name.
(ast/FooBar.hh -> AST_FOO_BAR_HH)."""
return re.sub ("[^A-Z]", "_", file_id(s).upper()) | fe7f14e433f4e32aa370e0ba36cf55dfb339f3b4 | 3,600,853 |
def recalc_muscle_ouptut(VLMN, VRMN, Time, dt, nMN, nMuscle, R, C, weight_MN_Muscle):
"""
This function takes the VLMN and VRMN output and calculates the muscle output based upon R, C and weight of MN to Muscle connection
:param VLMN: list or 1-D numpy array
:param VRMN: list or 1-D numpy array
:pa... | 8c3b4f4c43bdd7fcf28f0735c2d07ee09acdf290 | 3,600,855 |
def conv3x3(in_planes, out_planes, stride=1):
"""3x3 convolution with padding"""
return Conv2D(in_planes, out_planes, filter_size=3, stride=stride,
padding=1, bias_attr=False) | 5c98ade4eb7d955f20b050c24c53828f956674dd | 3,600,856 |
def to_unit_cell(dimensions, angles):
"""
Returns a transform from cartesian to unit cell coordinates.
"""
a, b, c = _basis_vectors(dimensions, angles)
det = np.linalg.det(np.array([a, b, c]))
rows = []
for pos in range(3):
unit = [0.0] * 3
unit[pos] = 1.0
unit = np.a... | 18e035d5da8ce05fa30366e13ca081e22615c937 | 3,600,857 |
def _calculate_number_trajectories(model_inputs: np.ndarray,
trajectory_size: int) -> int:
"""Calculate the number of trajectories.
Parameters
----------
model_inputs: np.ndarray
Matrix of model inputs
trajectory_size: int
Number of input points in... | 7ccc0bed0aead914167075fefe172b08400c573b | 3,600,858 |
import math
def fix(x):
"""
From http://www.mathworks.com/help/matlab/ref/fix.html
fix
Round toward zero
Syntax:
B = fix(A)
Description:
B = fix(A) rounds the elements of A toward zero,
resulting in an array of integers.
For complex A, the im... | d57d4dd7088b2191e63fff16d0000508275f8a09 | 3,600,859 |
import platform
def is_linux():
"""是否Linux操作系统"""
return 'Linux' in platform.system() | f88693b702396c1ccb1220c0ea0c7edae78d03e6 | 3,600,861 |
def unpack2Dforces(file, D=1, U=1):
"""
Unpacks ASCII files coontaining the following columns: non-dimensional time, time step, fx, fy, vx, vy.
fx, fy are the pressure forces and vx, vy the viscous forces (not returned with this function).
:param file: File to read from.
:param D: Characteristic len... | b21f260250b45259e70000b369a923c7666cef05 | 3,600,862 |
def label_accuracy_score(label_trues, label_preds, n_class):
"""Returns accuracy score evaluation result.
- overall accuracy
- mean accuracy
- mean IU
- fwavacc
"""
hist = np.zeros((n_class, n_class))
for lt, lp in zip(label_trues, label_preds):
hist += _fast_hist(lt.flat... | fc814db24a3046f2bf5c35da441397f1e0ed527e | 3,600,863 |
def _event_handler(event_type, slack_event):
"""
A helper function that routes events from Slack to our Bot
by event type and subtype.
Parameters
----------
event_type : str
type of event received from Slack
slack_event : dict
JSON response from a Slack reaction event
R... | 43562bb8ae265941824e19bdbfed650b0716e8e7 | 3,600,864 |
def text_cluster(docs, features_method='tfidf', method="dbscan",
k=3, max_iter=100, eps=0.5, min_pts=2, tokenizer=list):
"""文本聚类,目前支持 K-Means 和 DBSCAN 两种方法
:param features_method: str
提取文本特征的方法,目前支持 tfidf 和 count 两种。
:param docs: list of str
输入的文本列表,如 ['k-means', 'dbscan']
:param me... | 8bb7604f7fa97438d269b5355710f96a9b9bf15d | 3,600,866 |
import requests
from bs4 import BeautifulSoup
import re
def us_president_infobox_processing_function(term):
"""The US Presidents infobox processing function, returns a dictionary containing
semi-processed information about a President (from the Wikipedia person infobox)."""
# Construct webpage.
page = req... | 458d93adc473da6fd67df0dccf3a12437ba35c30 | 3,600,867 |
import scipy
def log2_normal(mu, sigma, **kwargs):
"""Log 2-scaled continuous normal distribution.
Gaussian distribution parameterized with expected value ``mu`` and standard
deviation ``sigma``. Sampled values ``x`` are scaled by ``2**x`` before
being returned.
Parameters
----------
mu ... | a56ea7099d4365f4da1a0e9c04c9d5a8e9a083b3 | 3,600,868 |
def reversed_dict(choices):
"""Create a reverse lookup dictionary"""
return dict([(b, a) for a, b in choices]) | 85355bac403e8a49e55710eeef979120b1a34788 | 3,600,869 |
def powPDF(f, exp, ut=None):
"""
Return the powering 'exp' of the given quadratic form 'f'.
"""
if ut is None:
D = disc(f)
ut = unit_form(D)
if exp == 0:
return ut
elif exp == 1:
return f
elif f == ut:
return ut
if exp < 0:
lexp = -exp
... | cc6ac97fac5297fed0cbcd31a9da8f435f5ae10a | 3,600,870 |
def kube_spec():
"""Generate a random kubernetes spec."""
return fixed_dictionaries({
"name": text()
}) | de2c7160ff56047eab80b76c09fc0caaef8f0097 | 3,600,871 |
from typing import Optional
from typing import Sequence
def get_cpes(compartment_id: Optional[str] = None,
filters: Optional[Sequence[pulumi.InputType['GetCpesFilterArgs']]] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetCpesResult:
"""
This data source provides ... | e118381473c127f10ba8c194b23c4390de74bbb6 | 3,600,872 |
def plot_bijections(flow):
"""
Returns a figure that visualizes the bijections
in the provided flow.
"""
n_bij = len(flow.bij.bijectors)
fig,ax_arr = plt.subplots(
3,n_bij,
figsize=(1+3*n_bij,10),
subplot_kw=dict(aspect='equal')
)
fig.subplots_adjust(
wspa... | c0805912a8be0c7b3ba1baa2a8030fa0e4b2ab2c | 3,600,873 |
def workspace_traffic(_id):
"""
工作空间内的流量明细
:return:
"""
banner = ""
nor_banner = ""
al = None
suspect = None
if request.method == 'POST':
banner = request.form.get('banner')
nor_banner = request.form.get('nor_banner')
al = request.form.get('al')
suspec... | 737efe7a3b6fd312e25d52f0986b76e41c6b6b88 | 3,600,874 |
def project_detail(list_of_active_project, user_roles):
"""
To give project details for a particular project id
Args:
list_of_active_project(list):List of project id's.
user_roles(object):UserOrgRole object.
Returns:
Returns project details with org id.
"""
# dict o... | 6bdf9bdd74e33c0553ac2b804b58c54c351b69f0 | 3,600,875 |
def create_demand_callback(data):
"""Creates callback to get demands at each location."""
def demand_callback(from_node, to_node):
return data["demands"][from_node]
return demand_callback | ceff0d3caaa1e1269fee18e8aa4684afaa7a5e81 | 3,600,876 |
import requests
def get_bot_id(group_id: str) -> int:
"""Retrives the bot_id in the form of int via
the specified group_id that the bot is a member of.
If no such bot exists, then -1 is returned.
Args:
group_id (int): the id of the group that the
message is sent in
... | af8431388fcd5167850890ef148b74136d68664a | 3,600,878 |
import copy
def smooth(arr, window=9, poly=1, iterations=2):
""" Smooth an array with some number of Savitzky-Golay filters
Args:
arr (arr): Array to be be smoothed
window (int): Filter window length
poly (int): Order of polynomail
iterations (int): The number of times to smoo... | ff9bfc85650004d4d2e26a7604be5f2049225348 | 3,600,879 |
def compose_update_register(register, table, fields):
"""Compose update query string for registration table.
Arguments
---------
register : str
Real name of a registration table.
table : str
Real name of a migrated table.
fields : str
List of table fields.
Returns
... | 5051a1794b320e5a0fd17d7d0918e7741a2fb317 | 3,600,880 |
import re
def is_pages(value: str) -> float:
"""Asserts that a value looks like page number(s)."""
pages = re.compile(r'(\d+)(?:\s+)?[\s\-._/\:]+(?:\s+)?(\d+)')
match = pages.match(value)
if match:
start, end = [int(i) for i in match.groups()]
if start < end:
return 1.0
... | e816007698f902a4812446bd4270224fbb7ae6fc | 3,600,881 |
def dataframe_export_chunks(df, filepath, max_size=None, overwrite=True, **kwargs):
"""
Exports a dataframe into chunks and returns the filepaths.
:param df: (pd.DataFrame)
The DataFrame to export in chunks.
:param filepath: (str)
The base filepath (will be incremented by 1 for each exp... | 0d0056efa2976d0f312c0115fb7a4fd5761f3924 | 3,600,882 |
def get_parameter(client, name, type="String"):
"""Return value from Parameter Store"""
try:
if type == "SecureString":
return client.get_parameter(Name=name, WithDecryption=True)["Parameter"][
"Value"
]
else:
return client.get_parameter(Name=... | c025cabfc17ecbff16fad939afbf5806ab8abfc7 | 3,600,883 |
def require_admin_context(f):
"""Decorator to require admin request context.
The first argument to the wrapped function must be the context.
"""
@wraps(f)
def wrapper(*args, **kwargs):
if not is_admin_context(args[0]):
raise exception.AdminRequired()
return f(*args, **k... | c9b6a9ebb96e8349f6bd114d851afac90a993ee3 | 3,600,884 |
def write_text(obj: object, file: str, encoding: str = None):
"""
Write an object as string to a text file.
:param obj: The data object.
:param file: The text file path.
:param encoding: Optional encoding, e.g. "utc-8".
"""
if isinstance(file, str):
with open(file, 'w', encoding=enc... | caf3d4c2459860f85b9bc95482003fa1f2567608 | 3,600,885 |
def calc_fueltype_share_yh_all_h(fueltypes_yh_p_cy):
"""Calculate fuel share for every hour
Parameters
----------
fueltypes_yh_p_cy : array
Fuel share per fueltype for every day and hour (7, 365, 24)
Returns
-------
fueltype_share_yh_all_h : array (7)
Sum of fuel share for ... | e0c601cd4c4ae4f93ef8b6c891e225de7b9aef38 | 3,600,888 |
import torch
def __coalesce(
edge_index: torch.Tensor,
edge_attr: _typing.Union[
torch.Tensor, _typing.Iterable[torch.Tensor], None
] = None,
num_nodes: _typing.Optional[int] = ...,
is_sorted: bool = False,
sort_by_row: bool = True
) -> _typing.Union[
to... | d0ffff39a5ddf97834094862659442561dba5422 | 3,600,889 |
def keymetrics_rows(samples_ids, genes=None):
"""Generate key metrics rows."""
query = (
api.query(
TranscriptStat,
func.avg(TranscriptStat.mean_coverage).label('mean_coverage'),
func.avg(TranscriptStat.completeness_10).label('completeness_10'),
func.avg(T... | aec3347ca8d9a145deb4b973e23b156ecc741143 | 3,600,890 |
def _get_unique_index_values(idf, index_col, assert_all_same=True):
"""
Get unique values in index column from a dataframe
Parameters
----------
idf : :obj:`pd.DataFrame`
Dataframe to get index values from
index_col : str
Column in index to get the values for
assert_all_sa... | 306a919a547a6d0056a4547daa50e6149d840910 | 3,600,891 |
def random_rps_pick():
"""Returns a random value of rock, paper, or scissors."""
rps_set = ("rock", "paper", "scissors")
i = randint(0, 2)
return rps_set[i] | 30081acbdca6cb0e345a1fd4ff0a0117d81defe3 | 3,600,892 |
def make_list_of_ranges_from_nums(nums, prefix=None):
"""Parse a list of numbers into a list of ranges.
This is a helper function for get_str_from_nums(), and does all of the
hard work of creating a list of ranges from a list of nums.
Args:
nums: A collection of numbers
Returns:
l... | ba32adef2b3fd6b39d5e4118ea2b9d448c9bf910 | 3,600,893 |
def verify_password(admin: AdminAccount, provided_password: str) -> bool:
"""
Checks to see if the password provided for the given user name is valid
admin (AdminAccount): The admin that is attempting to login
provided_password (str): The plain text password provided by the user
"""
correct_pas... | f382beb858936f3414584e28d79cce51bc93ad68 | 3,600,895 |
from typing import Counter
def occurences_counter(filepath, writepath='counts.txt'):
"""Counts occurences of words in a dataset
Input:
filepath: file to open
writepath: file where is written the result of the count, format is: key | count
Output:
Counter dictionary object filled w... | cb72b7b9bdcbbbe5dfdf5c86e3c43b5fe98ac3ea | 3,600,896 |
def format_data_sample(stream):
"""Return a table representation of a sample of the streamed data."""
keyed_rows = []
for row in stream.sample:
keyed_rows.append(dict(zip(stream.headers, row)))
petl_table = fromdicts(keyed_rows)
return repr(look(petl_table, limit=None)) | f92666ee8c462938297d5adea3bbbf68760c9fd4 | 3,600,897 |
def with_sharding(builder, sharding: SpatialSharding, op_fn, *args, **kwargs):
"""Builds op_fn(*args, **kwargs) with sharding annotation."""
builder.set_sharding(_sharding_to_proto(sharding))
try:
return op_fn(*args, **kwargs)
finally:
builder.clear_sharding() | 11c1cdbf853af51bcec26adca4947db7fd38e80f | 3,600,898 |
import copy
def symmetrize_edges(dataset: lit_dataset.Dataset) -> lit_dataset.Dataset:
"""Symmetrize edges by adding copies with span1 and span2 interchanged."""
def _swap(edge):
return lit_dtypes.EdgeLabel(edge.span2, edge.span1, edge.label)
edge_fields = utils.find_spec_keys(dataset.spec(), lit_types.Ed... | 3113722e1f353ded1f97c96e807a38d492640307 | 3,600,899 |
def detect_inner_pix(half_binary, outer_pix, side):
"""Relative (r, c) coordinates of the inner pixel (between wing and body)
Arguments
---------
half_binary : 2D array
binary image of left/right wing
outer_pix : 1D array
(r, c) coordinates (relative) of the outer pixel
side : s... | 2ec6d52d1464a606165af93e655e47a2badea6f3 | 3,600,900 |
def decode_list(in_str: str):
"""
Decode a list of strings from 2-digit decimal encoding
separated by 00's
(Decoding function provided in Scratch Library)
"""
return [decode_str(i) for i in in_str.split('00')] | ba8a7cbb05d8b7cd6ea4e142f4dfb3e8e51b1f59 | 3,600,901 |
import math
def hargreaves_equation(lat, doy, t_min, t_max):
"""
Calculate the reference evapotranspiration using the Hargreaves equation
(Allen et al. 1998).
This equation should be used when solar radiation data, relative humidity
data, and/or wind speed data are missing.
NOTE: This equati... | 25ae68458e4a5fb1783e47f38615a662ced7aa2d | 3,600,902 |
def justify_bytes(b: bytes, length: int) -> bytes:
"""
Same function than
text_formatter.justify.justify(), but taking
bytes instead of standard strings.
"""
checkBytes(b)
# Just like justify(), this
# function is not completed yet.
return b | e56aa1ca6ef0786fb55463dd6bea622b0ad78557 | 3,600,903 |
def on_epoch_start(func):
"""A function decorator that wraps a Callable inside the NeMoCallback object and runs the function with the
on_epoch_start callback event.
"""
class NeMoCallbackWrapper(NeMoCallback):
def __init__(self, my_func):
self._func = my_func
def on_epoch_s... | ee7bbd81799dac57355a5946f025919a187bf64c | 3,600,904 |
def get_columns(invoice_list):
"""return columns based on filters"""
columns = [
_("Item") + ":Data:350",
_("Invoice") + ":Link/Purchase Invoice:120",
_("Posting Date") + ":Date:80",
_("Vendor") + ":Link/Supplier:120",
_("Bill No") + "::120",
_("Bill Date") + ":Date:80",
_("Grand Total") + ":Currency/cu... | 12675f8c8e5ae87333b962c05cb17662807c3f4d | 3,600,907 |
def leaderboard_delete(request, pk=None):
"""Special view for deleting leaderboards from across the site
kwargs:
pk -- a leaderboard id (primary key)
"""
template = "pages/deleteLeaderboard.html"
if pk is not None and request.user.is_authenticated:
leaderboard = get_object_or_404(Le... | 410e86a570fac52e7b5b4cbf74d5cfcc82b616c8 | 3,600,908 |
def bboxes_crop_or_pad(bboxes, xs, ys,
height, width,
offset_y, offset_x,
target_height, target_width):
"""Adapt bounding boxes to crop or pad operations.
Coordinates are always supposed to be relative to the image.
Arguments:
bboxe... | 17e72d2c4c03065bafad918044163c63505de02b | 3,600,909 |
def create_Adam_op(loss, alpha, beta1, beta2, epsilon):
"""
adam
"""
return tf.train.AdamOptimizer(alpha, beta1, beta2, epsilon).minimize(loss) | 3299f4b931b505d501a77fd207d9e7f655ef462c | 3,600,910 |
def run_operate(model_data, timings, backend, build_only):
"""
For use when mode is 'operate', to allow the model to be built, edited, and
iteratively run within Pyomo.
"""
log_time(logger, timings, 'run_start',
comment='Backend: starting model run in operational mode')
defaults =... | 60d25fbb9214d7498881ab55bdfdcaa8c7deaaa9 | 3,600,911 |
def count_query(query):
"""
The Google Cloud Datastore API doesn't expose a way to count a query
the traditional method of doing a keys-only query is apparently actually
slower than this method
"""
# Largest 32 bit number, fairly arbitrary but I've seen Java Cloud Datastore
# co... | 6ad65b75838048cac0a0360098972427034e6cca | 3,600,912 |
import torch
def log_importance_weight_matrix(batch_size, dataset_size):
"""
Calculates a log importance weight matrix
Parameters
----------
batch_size: int
number of training images in the batch
dataset_size: int
number of training images in the dataset
"""
N = dataset_s... | 78555bd2e35bae8587602e43698c98bb0f463b21 | 3,600,917 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.