content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def clean_up(lines):
"""
Get rid of all non-text lines and
try to combine text broken into multiple lines
"""
new_lines = []
for line in lines[1:]:
if has_no_text(line):
continue
elif len(new_lines) and is_lowercase_letter_or_comma(line[0]):
#combine with previous line
new_lines[-1... | 56704212dd18f440f4cce944ae6cf5f706a9a2a7 | 3,623,600 |
def create_spark():
""" Method to create Spark Context
Returns:
-----
sc : pyspark.SparkContext
"""
conf = SparkConf()\
.setAppName(APP_NAME)\
.setMaster("local[4]")\
.set("spark.executor.memory", "4g")\
.set("spark.executor.cores", "4")\
.set... | 26ea66b32074dac0b3cbab21a10ad459e86537ab | 3,623,601 |
def get_saved_posts_subreddits(in_dictofposts):
""" loop thru a given list or dict of posts, return a dict of those posts unique subreddits where key is subreddit name, value is subreddit object"""
subreddits = dict()
for post_id,post in in_dictofposts.items():
# post.subreddit_id will look somethin... | 4d6d727166368106fe1f29149fe9a17e70219ac4 | 3,623,602 |
def _is_not_blank(line):
"""Return true if `line` is not blank."""
return len(line.split())>0 | 835d991d71dcb59075b6ae2b317c8fb8c51abee9 | 3,623,603 |
def list_replicas_to_delete(pointers, host="metadata", port=6379):
"""
List the blocks that match the given threshold
Args:
pointers(int): The minimum number of documents pointing to a block for
the block to be considered for scrubbing
host(str, optional): The host met... | 863b8a5869d379d0631f3b7c73370bc820566162 | 3,623,604 |
import itertools
def tstRGB_HSV_RGB():
""" RGB to HSV back to RGB full range test """
report.write("\n*** RGB->HSV->RGB test ***")
nberr = nbt = 0
random_pick = unit_tests.RandPickInRange(100000, 500000)
for rtst, gtst, btst in itertools.product(range(256), range(256), range(256)):
nbt += ... | 4343e1b83a41555d89259db803a16015f3f2ccbc | 3,623,605 |
import socket
def _is_route_exists(dst):
"""Return True if destination (IP address/network prefix length,
e.g. "10.1.0.1/30") belongs to any network configured
on the OS interfaces."""
route_list = _ipr.get_routes(family=socket.AF_INET)
for route in route_list:
edst = "%s/%d" % (route.get... | fe975736010b02293497a0cd71f6f767023d042d | 3,623,606 |
from re import S
def residue_reduce(a, d, DE, z=None, invert=True):
"""
Lazard-Rioboo-Rothstein-Trager resultant reduction.
Given a derivation D on k(t) and f in k(t) simple, return g
elementary over k(t) and a Boolean b in {True, False} such that f -
Dg in k[t] if b == True or f + h and f + h - ... | 2c2a700139778056418fee77ba1ff9c5ff81adfe | 3,623,607 |
from typing import Optional
def apply_l2_weight_decay(
learning_rate_fn: optax.Schedule,
l2_regularizer_weight: Optional[float] = 0.
) -> ShardedGradientTransformation:
"""Applies L2 weight decay.
Args:
learning_rate_fn: An optax schedule that infers the lr given the step.
l2_regularizer_weight: ... | 97db7496201bfd263cbffe546dcb79a668049f61 | 3,623,608 |
def map_click(cube, index=2.03, figsize=(12, 6),
lon_min=0, lon_max=360,
lat_min=-90, lat_max=90,
bg='VIMS_ISS',
):
"""Interactive equirectangular projected map."""
pixels = []
fig, ax = plt.subplots(1, 1, figsize=figsize)
fig.subplots_adjust(righ... | 7ad7311c6c9c73a2f136d7a7256626d7e0df0a4d | 3,623,609 |
def overlaps(box1, box2):
"""
Checks whether two boxes have any overlap.
Args:
box1: (float, float, float, float)
Box coordinates as (x0, y0, x1, y1).
box2: (float, float, float, float)
Box coordinates as (x0, y0, x1, y1).
Returns:
bool
... | b8bf96e87f45f24d337b503184670d0f56d209e0 | 3,623,610 |
import binascii
def hashInt(bytebuffer):
"""
Map a long hash string to an int smaller than power(2, 31)-1
"""
hex_dig = binascii.hexlify(bytebuffer)
return int(hex_dig, 16) % 2147483647 | d89a20651175a023e844e5c14dd860fcd8f186ee | 3,623,611 |
def _ts_ema(x1, d: int):
"""exponential moving average (EMA)"""
alpha = 2 / (d + 1)
return __rolling(pd.Series(x1), d, function=__scalar_ema, alpha=alpha) | a730930a18bffb7102f46acb7905ea65cb49e9f7 | 3,623,612 |
import os
def write_files(directory, entries, organize):
"""Write a list of file entries to a directory."""
# (filename, data)
bad_entries = []
# Get absolute path, just in case working directory changes.
directory = os.path.abspath(directory)
# Make top-level.
os.makedirs(directory, exi... | 572832c4ea4efcbd1bcb1365a492716068e2a48d | 3,623,613 |
def vs_code():
"""报名表下载页面"""
if request.method == 'GET':
return render_template("vs_code.html")
elif request.method == 'POST':
form = request.form
valid_code = form.get("valid_code")
ad = Admin.query.filter_by(name="admin").first()
if ad.valid_code == valid_code:
... | 7126930fb1ce94f1be980e289a8e990eef2f3905 | 3,623,614 |
def nm_004448_coding_dna_delins(erbb2_context):
"""Create test fixture for NM_004448.4:c.2326_2327delinsCT."""
params = {
"id": "normalize.variation:NM_004448.4%3Ac.2326_2327delinsCT",
"type": "VariationDescriptor",
"variation_id": "ga4gh:VA.eMxxAEjNduAvg5U3eBZxf0nLtfcMNxqy",
"va... | 1a8ece5d5637f64487a21d51259d9fcb0db96dc4 | 3,623,615 |
def extend(dst, *args):
"""Recursively update a dictionary.
Parameters
----------
dst : `dict`
Dictionary to update.
*args : `dict`
Returns
-------
`dict`
Updated dictionary.
Examples
--------
>>> extend({'x': {'y': 0}}, {'x': {'z': 1}})
{'x': {'y': 0, ... | 1da944b9146f97e7e3d5b2947439b9146ab261fe | 3,623,616 |
import json
def list_saved_reply_ids(wrapped):
"""
Decorator for handling API calls that take as input a list of saved reply ids.
Calls the wrapped function with the parsed saved reply ids selected by the
API user.
"""
@wraps(wrapped)
def decorated(request, *args, **kwargs):
if 'sa... | 0797fb83437ab8922639ed731269743e3e457a36 | 3,623,617 |
import pickle
import multiprocessing
import os
import logging
def main(cifs, centres, **kwargs):
""" Process all supplied cif files using options supplied as kwargs (or defaults).
Returns
phases : Dict
Dictionary of Crystal objects (containing ellipsoid results), keyed by CIF name.
... | c4659eec11c5014eaa3cb6dd5369c5df3d1cefe6 | 3,623,618 |
import collections
import math
def _compute_bleu(reference_corpus, translation_corpus, max_order=4, smooth=False):
"""Computes BLEU score of translated segments against one or more references.
Args:
reference_corpus: list of lists of references for each translation. Each
reference should b... | 8861419fc6d1b11333e449f5294c466f4fcf8dde | 3,623,619 |
def poly_area(x,y):
""" vectorized implementation of shoelace formula.
inputs
x (ndarray) : x coordinates of polygon
y (ndarray) : y coordinates of polygon
type : 'green' or 'shoe' indicating either using greens theorem or the shoelace formula
returns
area (float) : area of... | 163101438f5419ca062788b9985533c911bd5eb9 | 3,623,620 |
import jinja2
def fixture_environment(template_loader: jinja2.BaseLoader) -> jinja2.Environment:
"""Setup an environment similar to what Salt does.
See https://github.com/saltstack/salt/blob/master/salt/utils/templates.py#L406-L476
"""
env = jinja2.Environment(
loader=template_loader,
... | 8a3703a1238710f88da88066fff3cd99379f2fe6 | 3,623,621 |
def try_import_tvm():
"""Try import tvm at runtime.
Returns
-------
tvm module if found. Raise ImportError otherwise
"""
msg = "tvm is required, for installation guide, please checkout:\n \
https://tvm.apache.org/docs/install/index.html"
return try_import('tvm', msg) | 6cfa770362e0c90ec0e5d3881e482d1a5bdfc7ae | 3,623,622 |
def make_combined_table(array_rows):
""" Build a table of tables
Args:
array_rows (list(list)): Array of tables rows to combine
Returns:
str: string representing table
"""
if IS_NOTEBOOK:
# compute the size for each col
col_size = str(int(100 / len(array_rows)) - 5)... | 1c49c2cb02c9db6773dcad739c5ff62595c5bbac | 3,623,623 |
def apply_precession(ra, dec, years) :
"""
see DESI-4957
Equator and zero longitude point glide westward at 0.0139 deg/year, so..
Star ecliptic longitudes increase +0.0139 deg/year from combined lunar and solar torques on the Earth.
To precess any sta'’s {RA,DEC}:
1. Convert to ecliptic coordina... | c73a12e65eb2a94e313862eeb282483ce60f716b | 3,623,624 |
import sympy
from re import T
def fourier_basis(freq):
""" sin and cos Formula for Fourier drift
The Fourier basis consists of sine and cosine waves of given
frequencies.
Parameters
----------
freq : sequence of float
Frequencies for the terms in the Fourier basis.
Returns
-... | af181d8d6ff2b19feba563652399776ed46cb4b5 | 3,623,625 |
def get_gene_sets(species, use_kegg_ids=False, use_name=True):
"""Gets mapping from gene ids to pathways as genesets.
Args:
species (str): Name of the species to query. Use or example 'hsa'
for human or 'mmu' for mouse.
use_kegg_ids (bool): Whether to return gene ids as entrez
... | f538168d24461f0854f7999eb31f930d24a18ba9 | 3,623,626 |
def registration(request):
"""Render the registration page"""
if request.user.is_authenticated:
# User is already registered, so no point to be on registration page.
return redirect(reverse('index'))
if request.method == "POST":
# Check of the method is post. If so instantiate the ... | 80a764abf086fe2b7767272e7c2ed3308805331c | 3,623,627 |
def likelihood(grid_pred, timed_points, minimum=1e-9):
"""Compute the normalised log likelihood,
:math:`\frac{1}{N} \sum_{i=1}^N \log f(x_i)`
where the prediction gives the probability density function :math:`f`.
:param grid_pred: An instance of :class:`GridPrediction` to give a
predict... | f495937be20a9989bef5160a5aed65eeb0827358 | 3,623,628 |
def get_data_iters(dataset, batch_size, opt):
"""get dataset iterators"""
if dataset == 'mnist':
train_data, val_data = get_mnist_iterator(batch_size, (1, 28, 28),
num_parts=kv.num_workers, part_index=kv.rank)
elif dataset == 'cifar10':
train... | c89bfa58aa019fe1ee26041fbd499190ed72e8c3 | 3,623,629 |
def to_sendeable_block_original_bus(array_of_msgs):
"""Given an array of msgs return it in the format
panda.can_send_many expects.
Input looks like: [(512, bytearray(b'>\x80\x1c'), 0), ...]
Output looks like: [(512, '>\x80\x1c', 0), ...]
"""
new_arr = []
for msg in array_of_msgs:
ne... | 24fd1cdf8c1bfed095d1685a8eaa246c89425958 | 3,623,630 |
from dateutil import tz
def _get_support(parts):
"""Retrieve supporting information for potentially multiple samples.
Convert speedseqs numbering scheme back into sample and support information.
sample_ids are generated like 20 or 21, where the first number is sample number
and the second is the type... | aba2f96fef3b94ed08b81c82bcbf59471652f342 | 3,623,631 |
def extractColorRamp(color_ramp):
"""Make a curve from color ramp data"""
# for uniformity looks like a glTF animation sampler
curve = {
'input' : [],
'output' : [],
'interpolation' : ('STEP' if color_ramp.interpolation == 'CONSTANT' else 'LINEAR')
}
for e in color_ramp.ele... | 7fb71e94c1d687065c5c015524b6739588fa047a | 3,623,632 |
def DNSServiceEnumerateDomains(
flags,
interfaceIndex = kDNSServiceInterfaceIndexAny,
callBack = None,
):
"""
Asynchronously enumerate domains available for browsing and
registration.
The enumeration MUST be cancelled by closing the returned
DNSServiceRef when no more domains are ... | 4b0c7624a927c1613c014fc1fe37d835f9c3a257 | 3,623,633 |
import copy
import itertools
def _ring_fgroup_union(mol, tagged_rings, tagged_fgroups, wbo_threshold=1.2):
"""
This function combines rings and fgroups that are conjugated (the bond between them has a Wiberg bond order > 1.2)
Parameters
----------
mol: OpenEye OEMolGraph
tagged_rings: dict
... | bead9e159ae0b276a197b9e326c69dcfbaa2ff0a | 3,623,634 |
from typing import List
import re
def tokenize(text: str) -> List[str]:
"""Токенизация текста, пустые строки отбрасываются"""
punctuation = "\\" + "\\".join(list("[](){}!?.,:;'\"\\/*&^%$_+-–—=<>@|~"))
words = "[a-zA-Zа-яА-ЯёЁ]+"
compounds = f"{words}-{words}"
scr = "\\.{3}"
tokenize_re = re.c... | cd835c3c3720ef39b540d4e83a50a2ee602dc622 | 3,623,635 |
def pca(data, n_components = None, copy = True, whiten = False, svd_solver = "auto", tol = 0.0, iterated_power = "auto", random_state = None):
"""
Performs a principle component analysis on the input data.
reference: https://scikit-learn.org/stable/modules/generated/sklearn.decomposition.PCA.html
parameters:
data... | ab41437955eed6c24c11a75560c55db76bfa6d94 | 3,623,636 |
def interpolate_cosine_single(start, end, coefficient):
""" Cosine interpolation """
cos_out = (np.cos(np.pi*coefficient) + 1) / 2.0
return end + (start - end) * cos_out | 57447d4b8e2a17dfb654ac616c4d6ff8df2d8d75 | 3,623,637 |
def get_taken_books():
"""
Get list of taken books
:return: All books
"""
result = []
try:
limit = int(request.args['pageSz'])
except StandardError, err:
app.logger.warning("get_books()->['pageSz' arg]: " + str(err))
limit = 0
try:
page_number = int(requ... | faca63b11691db7419e76872a5aad2b227502521 | 3,623,638 |
def solve(array):
""" For less than 3 elements, just return the lenght of the array
Else, solve the problem
"""
if len(array) < 3:
return len(array)
return longest_zigzag(array) | 12bb18e7c447d37f531a9c669d7a675a63402e14 | 3,623,639 |
from datetime import datetime
import pytz
def process(url):
"""
Fetches news items from the rss url and parses them.
Returns a list of NewsStory-s.
"""
feed = feedparser.parse(url)
entries = feed.entries
ret = []
for entry in entries:
guid = entry.guid
title = translate... | 4716c93ec5dfc16a1c491cc67c5e7d416def0bb3 | 3,623,640 |
import socket
import os
import time
def build_feed_index(feed_objects, directory, header=None, hostname=None,
port=70, sort=None, plug=True):
"""
Build a gophermap file in the specified directory, which presents an index
for all the feeds in feed_objects.
"""
if not hostname:
hostn... | 2ecd9444c5534a6e5478440fa1e1639cd3a19ab1 | 3,623,641 |
def _get_cfg():
"""Gets the configuration for the resnet101 yaml file.
Arguments:
None
Returns:
cfg (config object): a configuration for the resnet
"""
_, fstrrcnn_dir = _set_dirnames()
cfg_file = osp.join(fstrrcnn_dir, "cfgs", "res101.yml")
return cfg_from_file(cfg_file) | 006588decc17eeedb321d908f9170f672e5aa31b | 3,623,642 |
def create_distance_callback(data, manager):
"""Creates callback to return distance between points."""
distances_ = {}
index_manager_ = manager
# precompute distance between location to have distance callback in O(1)
for from_counter, from_node in enumerate(data['locations']):
distances_[fro... | eff81290aa396fa07a6f45ce137258a12695dfa1 | 3,623,643 |
def JSONDataset(filenames, columns=None):
"""Start with JSON parser in python to add tests."""
jsondataset = []
jsondataset = JSONParser(filenames, columns)
return tf.data.Dataset.from_tensor_slices(jsondataset) | 8fed40583da7146f3b292684725220693c42ea42 | 3,623,644 |
def max_sub_array(nums):
"""Given an integer array nums, find the contiguous subarray (containing at least one number)
which has the largest sum and return its sum."""
max_sum = float("-inf")# unbounded lower value
# https://stackoverflow.com/questions/34264710/what-is-the-point-of-floatinf-in-python
... | cb7ea6a3eda54d7566430e38acee7e5999618af8 | 3,623,645 |
import re
def validate_vm_name(vm_name) -> bool:
""" Checks that the vm name is valid.
Args:
vm_name: the name of the vm to check
Returns: True if valid, else false.
"""
# we minus 3 for max length because we generate the rg using: "{vm_name}-rg"
if len(vm_name) < 1 or len(vm_name) >... | 3ee3346f497718f7606b328c385014530ed5ed43 | 3,623,646 |
import os
def rst2rst_folder(rststring, folder, document_name="index", **options):
"""
Converts a :epkg:`RST` string into simplified :epkg:`RST`.
@param rststring :epkg:`rst` string
@param folder the builder needs to write the resuts in a
folde... | d838805399a59e9b8fca824dcbbc6ad80b2af004 | 3,623,647 |
import struct
def _parse_dictzip_field(subfield):
"""Returns a dict with:
chlen ... length of each uncompressed chunk,
zlengths ... lengths of compressed chunks.
The dictzip subfield consists of:
+---+---+---+---+---+---+==============================================+
| VER=1 | CHLEN ... | 0b3ce44425a3d3ee20e95b01f6fa5f1a341dce7f | 3,623,648 |
def BPmatch_slow_asym(c1, c2, G1, G2, dmax):
"""
New version which makes the differences between ascending
and descending links
- c1 and c2 are arrays of shape (n1,d) and (n2,d) that represent
features or coordinates,
where n1 and n2 are the number of things to be put in correpondence
and d ... | d341b9f2b2c219a782438cd854d085068870c204 | 3,623,649 |
def post_sample_ar_complete_multipart_upload_url(request, pk):
"""Reply with a sample group manifest."""
arf = authorize_sample_ar_upload_url(request, pk)
upload_id, parts = request.data['upload_id'], request.data['parts']
blob = arf.get_presigned_completion_url(upload_id, parts)
return Response(blo... | 60c53606cb5c1e01623250d097cbc4b98812969f | 3,623,650 |
import csv
def get_movies_by_director(data=movies_csv):
"""Extracts all the movies from csv and stores them in a dictionary
where keys are directors, and values is a list of movies (named tuples)"""
directors = defaultdict(list)
with open(data, encoding='utf-8') as f:
for line in csv.DictRead... | 9850749cc80556b45385facc4b4acf22b2494a69 | 3,623,651 |
import torch
def distance(F, shape_params=None, use_chamfer=False):
"""
Arguments:
----------
F: Tensor of size BxNxM, with the values of the inside-outside function
for the N points w.r.t. the M primitives
shape_params: Tensor with size BxMx3, containing the shape along each
... | 30e6776792eea1ea57e4af7a1e7150a96d29baf6 | 3,623,652 |
def extract_latest(obsv_data):
""" take the 'obsv' data dict and extract entries matching latest predictions.
We know the 'obsv' contains entries of observations and forecasts. Each entry
has the name of the dam as the last item three from the end of the line.
We want one observation of the latest level... | 4a3ba045e9a980418bfa2985d19e8e6120e32af9 | 3,623,653 |
from datetime import datetime
import pandas
import numpy
def get_cybex_dataframe(
db, start_date_utc, ticket_severity, group, tickets_closed_past_days
):
"""Stolen from https://github.com/jsf9k/ncats-webd/blob/develop/ncats_webd/cybex_queries.py."""
now = datetime.datetime.now(datetime.timezone.utc)
t... | c3b63d7de45207c1f02856b5871871214d53daf7 | 3,623,654 |
def html(i):
"""
Input: {
(skip_cid_predix) - if 'yes', skip "?cid=" prefix when creating URLs
}
Output: {
return - return code = 0, if successful
> 0, if error
(error) - error text if return > 0
... | bcd49ebb333ccbc7f0c472bd6d9bb70f49b5068c | 3,623,655 |
def history(name):
"""
History view for a wiki page.
"""
if isfile(
join(settings.CONFIG["wiki_root"], name + "." + settings.CONFIG["suffix"])
):
fname = join(
settings.CONFIG["wiki_root"], name + "." + settings.CONFIG["suffix"]
)
rel_fname = relpath(fnam... | 220e3724298858ef25aa8ca6ac8a77aede095708 | 3,623,656 |
def decompose_frame(frame:pd.DataFrame):
"""
Runs a full decomposure against a given DataFrame
:param: frame - a pandas dataframe
:return: a pandas Series that is the smallest unique label set
"""
_frame = frame.drop_duplicates()
_frame_size = len(_frame)
_weight_series = generate_weight... | e04e73d415e04bca0f02470a49bfedabc65d2abd | 3,623,657 |
def page_not_found_view(request, exception=None):
""" A view to render custom 404 not found page """
if exception:
messages.error(request, f"error encountered: {exception}")
return render(request, 'errors/404.html') | 77498ff64b57e761d68ff3c7070c6f10ed854fdc | 3,623,658 |
def mock_handlers() -> AsyncMock:
"""Get an asynchronous mock in the shape of CommandHandlers."""
# TODO(mc, 2021-01-04): Replace with mock_cmd_handlers
return CommandHandlers(
equipment=AsyncMock(spec=EquipmentHandler),
movement=AsyncMock(spec=MovementHandler),
pipetting=AsyncMock(s... | 889a18d7109f215536a377a69d4faf9da0422aba | 3,623,659 |
def logout(request):
""" Logs out the user from the system"""
permission_obj = PermissionValidation(request)
permission_obj.logout(request)
data = {
'success': True
}
return Response(data, status=status.HTTP_200_OK, content_type='application/json') | d66c5653fe6bf318778f5a899fad92b84d9609bf | 3,623,660 |
def filter_check_route_map_set_items(value):
"""
Function to check route-map set options in a template
:param value:
:return:
"""
error = f'{value} !!!! possible error check template for possible set items!!!!'
if not value: # pylint: disable=no-else-return
J2_FILTER_LOGGER.info('fi... | 865a59e0cc310d5d37fd956c794544a885054e7f | 3,623,661 |
import yaml
def _GetErrorDetailsSummary(error_info):
"""Returns a string summarizing `error_info`.
Attempts to interpret error_info as an error JSON returned by the Apigee
management API. If successful, the returned string will be an error message
from that data structure - either its top-level error message... | 276e8520bc5ca790fc61c71e0f43ebee0d78b597 | 3,623,662 |
def state_to_trip(trip_state, kp_state):
"""The function state_to_trip was added to have a uniform way of using the state between kinpy
and TriP in the tests
Args:
state (dict): dictionary with the state name of each joint as it occurs in TriP as the key
and a float as the val... | ca6e5e756fcb862c3c704f8d9fbdf39899cbe6bb | 3,623,663 |
import os
import glob
def get_recent_mask_dir(input_dir=None):
"""Grab the most recent sub-directory of masks in MASK_DIR.
Parameters
----------
input_dir : :class:`str`, optional, defaults to ``None``
If passed and not ``None``, then this is returned as the output.
Returns
-------
... | 98a788eaa0ed443e657e1353b7c11c8897056986 | 3,623,664 |
def format_duration_hhmm(d):
"""
Utility function to format durations in the widget as hh:mm
"""
if d is None:
return ''
elif isinstance(d, str):
return d
hours = d.days * 24 + d.seconds // 3600
minutes = int(round((d.seconds % 3600) / 60))
return '{}:{:02}'.format(hours... | 941670b1a16c87816589cfb05ff80b651857d337 | 3,623,665 |
from typing import List
def get_feed_list(opml_obj: OPML) -> List[str]:
"""Walk an OPML document to extract the list of feed it contains."""
rv = list()
def collect(obj):
for outline in obj.outlines:
if outline.type == 'rss' and outline.xml_url:
rv.append(outline.xml_u... | 5decba43dec70b17ea1e39eabb64443db6a73091 | 3,623,666 |
from typing import Optional
import uuid
def change_password(
session: Session,
new_password: str,
current_password: Optional[str] = None,
current_password_hash: Optional[str] = None,
username: Optional[str] = None,
email: Optional[str] = None,
user_id: Optional[uuid.UUID] = None,
) -> User... | 9b2b6474b86e0716ec9d9da683314e26708afc16 | 3,623,667 |
import argparse
def get_args():
"""
read parser and return args (as args namespace)
"""
parser = argparse.ArgumentParser(description='Modify/Update existing configuration file to v0.5')
parser.add_argument('-f', nargs=1, type=str, help='File to modify', required=True)
parser.add_argument('... | 412d33385f12c462d096f563841c63b2704e6de2 | 3,623,668 |
def pt_index(*args):
"""Access stored Pressure Transducer data from the sensor limits and collected data to index and build an integer numpy array for sensor values that have exceeded the set bounds.
Parameters
----------
pt_limits : int numpy array
Values for pressure transducer limits.
pt... | 2fe9ccbdf8f6e9661efd81276d4178edda81c891 | 3,623,669 |
from .alignment.align_with_amt import audio_to_score_alignment
from .vienna_transcription import transcribe
import copy
import torch
def transcribe(audio,
data,
score=None,
res=0.001,
sr=SR,
return_mini_specs=False):
"""
Takes an audio... | 7b8fee517519e6f2ce594b268dc6f6b38408c11f | 3,623,670 |
from typing import Tuple
def generate_housing_dataset(
num_rows=None, noise=None, distribution="poisson"
) -> Tuple[pd.DataFrame, np.ndarray, np.ndarray]:
"""Generate the openml house_sales housing dataset."""
df = _read_housing_data(num_rows, noise, distribution)
y, exposure = compute_y_exposure(df,... | dd55ef4ca4a0a1249e6ad12bf95fbedcaa12d70b | 3,623,671 |
def quaternion_to_yaw(quat: Quaternion, in_image_frame: bool = True) -> float:
"""Convert quaternion angle representation to yaw."""
if in_image_frame:
v = np.dot(quat.rotation_matrix, np.array([1, 0, 0]))
yaw = -np.arctan2(v[2], v[0])
else:
v = np.dot(quat.rotation_matrix, np.array(... | d404be7c3183d5d758c9897ec0fa5d2232aeb099 | 3,623,672 |
def try_int(obj):
"""return int(obj), or original obj if failed"""
try:
return int(obj)
except ValueError: # invalid literal for int()
return obj | 21613ce19e86f5c5545e9dc4b161f6ddc95fd0ce | 3,623,673 |
from datetime import datetime
def s3_datetime(name="date", **attr):
"""
Return a standard Datetime field
Additional options to normal S3ResuableField:
default = "now" (in addition to usual meanings)
represent = "date" (in addition to usual meanings)
widget = "d... | ef6634cf99561ddbcaf233278b8bd9203732a809 | 3,623,674 |
def gb_predict(X, model):
"""Apply a gradient boosting model using a standard function. It is a wrapper function."""
y = model.predict(X)
return y | 755844678e0478d3678856c35c6e5d94027fe30b | 3,623,675 |
def get_fft_features(npy_file='', m=84, keypoint=7):
"""
Parameters
----------
npy_file
m:
without trimmming: m = 84
with trimming: m = 51
keypoint
coordinate
Returns
-------
"""
raw_data = np.load(npy_file)
res = []
for coordinate in range(3):
data = raw_data[:, keypoint, coordinate]
data =... | 1080e84074574258b675042c9579cc0131dc8d03 | 3,623,676 |
def _anonymous_model_data(ops_data):
"""Returns a dict representing an anonymous model.
ops_data must be a dict representing the model operations. It will
be used unmodified for the model `operations` attribute.
"""
return {"model": "", "operations": ops_data} | 6b64f9098b30cf3e079311b75ca136cfc2f7038f | 3,623,677 |
def load_eazypy_templates(eazytemplatefilename,
format='ascii.commented_header',
verbose=True,
**kwargs):
"""Read in the galaxy SED templates (basis functions for the
eazypy SED fitting / simulation) and store as the 'eazytemplatedata... | a8c6aa81ef92f8c07058442329dd6ffaba25fc2b | 3,623,678 |
def encoding_string(string):
"""
Encoding URL per RFC 3986.
"""
return(quote(string,safe='')) | 9d0b7b4c61e3c178662a08a78121e3bfa6ad5647 | 3,623,679 |
def collect_files_from_dir(directory, prefix="", suffix="", recursive=True):
"""
Collects the files in the given directory that matches the given prefix
and suffix.
"""
files = []
_collect_files_from_dir(directory, prefix, suffix, recursive, files)
return files | 96d0a136204b7b7da3ac20f59c7e1ed5794c7bf4 | 3,623,680 |
def encode_to_dict(encoded_str):
""" 将encode后的数据拆成dict
>>> encode_to_dict('name=foo')
{'name': foo'}
>>> encode_to_dict('name=foo&val=bar')
{'name': 'foo', 'val': 'var'}
"""
pair_list = encoded_str.split('&')
d = {}
for pair in pair_list:
if pair:
key = pair.spli... | a3af4d93d13404f01511483621e166c50d9e489e | 3,623,681 |
def array_to_dataframe(x: np.ndarray) -> pd.DataFrame:
"""Convert Numpy array to Pandas DataFrame with default column names."""
return pd.DataFrame(x, columns=[f'x{i}' for i in range(x.shape[1])]) | 6eb8c09581f87ea3c1c454f7a98a4a306091ef80 | 3,623,682 |
def check_matrix(matrix, gold, pred):
"""Check matrix dimension."""
if matrix.size == 1:
tmp = matrix[0][0]
matrix = np.zeros((2, 2))
if (pred[1] == 0):
if gold[1] == 0: #true negative
matrix[0][0] = tmp
else: #falsi negativi
matrix[1][0] = tmp
else:
if gold[1] ==... | a5ee5d05c8756980142b5453b3d6d8c8624d9ef9 | 3,623,683 |
def create_inference_pipeline(sm_role,
workflow_execution_role,
inference_pipeline_name,
return_yaml=True,
dump_yaml_file='templates/sagemaker_inference_pipeline.yaml'):
"""
Return YAML definition... | e406cfd61f7ea6192ca7e946ee69bf766226b056 | 3,623,684 |
def send_job(fn, data, args, step):
"""decide if send jobs with ipython or run locally"""
res = []
logger.my_logger.debug("doing %s" % step)
if step not in resources:
raise ValueError("step not in resources %s" % step)
else:
args.memory_per_job = resources[step][0]
args.cores... | 6110931f3fed6ff2d45e3464a39f0ea4593a71e8 | 3,623,685 |
import os
def plot_sv_comparison(*, dates, noisy_sv, denoised_sv, model, obs, model_name,
fig_size=(8, 6), font_size=12, label_size=16,
plot_legend=False, plot_average=False,
window_length=12, min_samples=3, save_fig=False,
wr... | bec0e32d53e4af3af4d972fd79c7b11a150296dd | 3,623,686 |
def taxonomy_levels_below(taxa_level):
"""
E.g. 'Order' --> ['Family', 'Genus']
"""
p_levels = ['Kingdom', 'Phylum', 'Class', 'Order', 'Family', 'Genus']
position_of_taxa_level = p_levels.index(taxa_level)
return p_levels[position_of_taxa_level + 1:] | 57e41b0042daa14b8ed09469006c6c3bdac320ec | 3,623,687 |
def build_dict_from_role_object(plotly_dict: dict, is_dict: bool = True) -> dict:
"""
a recursive function that takes in a plotly api dict and transforms it to json schema format
"""
# blacklist if for keys that we are not going to put into our wizard
blacklist = [
"stream",
"transfo... | 30898cb561825a7c802f2b86acefb8f86bd20134 | 3,623,688 |
def higher_order_shelving_holters(Gd, N, wc=1, normalize=True):
"""Higher-order shelving filter design by Martin Holters."""
g = 10**(Gd / 20)
alpha = np.stack([np.pi * (0.5 - (2*m+1)/2/N) for m in range(N)])
p = -np.exp(1j * alpha)
z = g**(1 / N) * p
k = 1
if normalize:
z *= g**(-0.... | e8e58593a0a18a42f122a08dc1b140906d742134 | 3,623,689 |
import os
import subprocess
def paste():
"""Return a string from the OS clipboard."""
command = ["pbpaste"]
if os.uname().sysname == "Linux":
command = ["xclip", "-selection", "clipboard", "-o"]
return (
subprocess.Popen(command, shell=False, stdout=subprocess.PIPE)
.stdout.rea... | a1939f8c03f0fdad8dfdf5dc62bd594eca3e49e4 | 3,623,690 |
def bin_prd_clsf_info_pos(y_true, y_pred, threshold=0.5, N_MORE=True, epsilon=1e-7):
"""refer to this: https://stats.stackexchange.com/questions/49579/balanced-accuracy-vs-f-1-score
Both F1 and b_acc are metrics for classifier evaluation, that (to some extent) handle class imbalance. Depending
of whic... | 89fa13cb8829e3d78f8f9a1b224eea15046ef4fb | 3,623,691 |
def is_public(obj, attr):
"""Return True if input attribute is PUBLIC.
A public attribute has the name without '_' as a prefix.
Parameters
----------
obj : object
Any class instance.
attr : str
Name of the attribute to check.
"""
_check_is_attr_name(attr)
# Exclude... | 751008360eb288f595e2d052130d49c715a49dd9 | 3,623,692 |
def sort(nodes, total_order, dedup=False):
"""Sorts nodes according to order provided.
Args:
nodes: nodes to sort
total_order: list of nodes in correct order
dedup: if True, also discards duplicates in nodes
Returns:
Iterable of nodes in sorted order.
"""
total_order_idx = {}
for i, nod... | 4cfb53593b3c862ab918507ea3d4fe94ab4899df | 3,623,693 |
def cast_other(f):
"""Generic wrapper to be applied to binary operator type class methods and
whose purpose is to cast the second positional argument to the type self"""
@wraps(f)
def wrapper(self, *args, **kwargs):
cls = self.__class__
other = args[0]
if not isinstance(other, c... | 3a3b0ad33578e76411c2523af838cc3452272d13 | 3,623,694 |
def bet_wit_cv(b_d, w_d):
"""
引数:2つのディクショナリ
返値:double型のクラス間分散,クラス内分散の値のタプル
"""
bc_var = b_d['n'] * w_d['n'] * ((b_d['ave'] - w_d['ave']) ** 2) / ((b_d['n'] + w_d['n']) ** 2)
wc_var = (b_d['n'] * b_d['var'] + w_d['n'] * w_d['var'] ) / (b_d['n'] + w_d['n'])
return bc_var, wc_var | a4b34fd4a4a713ab1f3350201a8c47d35e75e6eb | 3,623,695 |
import os
import hashlib
def create_single_file_info(filen, piece_length):
"""
Return dictionary with the following keys:
- pieces: concatenated 20-byte-sha1-hashes
- name: basename of the file
- length: size of the file in bytes
- md5sum: md5sum of the file
@see: BitTorrent M... | 2fa052f60cc5a5d23796ec358def11682b6e7f94 | 3,623,696 |
import subprocess
def call(cmd, check=True, cwd=None):
"""Execute a command and return output and status code. If 'check' is True,
an exception will be raised if the command exists with an error code. If
'cwd' is set, the command will execute in that directory."""
p = subprocess.Popen(cmd, stdout=subp... | 5ee896062dd1dd5ca0618327a133d4d03c4cb57c | 3,623,697 |
import unittest
def suite():
"""Create test suite from TrickWorkflowTestCase unit test class and return"""
return unittest.TestLoader().loadTestsFromTestCase(TrickWorkflowTestCase) | 1dc9fb48c15875c744fd4952cf7490676878c0ed | 3,623,698 |
def only_if_element(func):
"""
Decorator which raises if element is None in class State.
Args:
func (callable): The function to be wrapped
Returns:
wrapper (callable): The decorated function
"""
@wraps(func)
def wrapper(self, *args, **kwargs):
if self.state.element... | b9278dc7c6acc883c8d590e3452e900d1c888898 | 3,623,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.