content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from typing import Optional
async def line_notify_redirect(uid: Optional[str] = "") -> RedirectResponse:
"""轉址至 LINE Notify 綁定頁面
Args:
uid (Optional[str], optional): 使用者 LINE ID. Defaults to "".
Returns:
RedirectResponse: LINE Notify 綁定頁面
"""
link = config.lotify_client.get_auth_... | 091f991075109ce9ec16e1c4e47061be615887dd | 55,300 |
def get_version():
"""
get a comprehensive git version and report it in
the package at build-time.
:param :
:return str:
"""
return (
get_tag()
+ "+"
+ get_commit_count_after_tag()
+ "."
+ get_commit()
+ (".dirty" if dirty() else "")
) | 926133e4a4c4992601bcd848538a14ab3db83b9b | 55,301 |
def add_x_to_plotting_options(plotting_options: dict, option_cat: str, x: str, defaultvalue):
"""
don't override given plotting_options, meaning it only add the default value
if value not already defined in plotting_options
"""
if plotting_options is None:
plotting_options = {}
if option... | 48ff564e58b35b8dc38d529fb27188556401c81c | 55,302 |
def pair_features_heatmap(feat_names, feat_diff, plot_filename, separator=' - ',
num_drop_char=0, sort_by_pos=None, numerical_sort=False,
vmin=None, vmax=None, symmetric=True, cbar_label=None):
"""
Visualizes data per feature pair in a heatmap.
Param... | e3e035527e8784654635309822214276525e6abb | 55,303 |
def get_tendency_name_with_incompatible_units(input_properties, tendency_properties):
"""
Returns False if there are any keys shared by the two properties
dictionaries which indicate units that are incompatible with one another,
and True otherwise (if there are no conflicting unit specifications).
"... | 44dd8dc43a6d89ef897172cf6b0c7894edd98a44 | 55,304 |
def register(request):
"""
return signin.html
:param request: None
:return: signin.html
"""
return render(request, "signup.html") | 046e0af87604e21547573e49b2e1fcfcbe0c4c61 | 55,305 |
def calc_repairs(scenario, years):
"""RISK: Repairs of equipment on the farm
Args:
scenario (object): The farm scenario
years (int): No. of years for analysis
Returns:
repair (list): Repair costs taken as a percentage of capital costs for facilities and lighting... | 1a56b5154e228ec2c78debc50d1c94f24a595b5c | 55,306 |
def explain_pair(grid,digs,locs):
"""Concoct explanation for application of pair rule."""
d1,d2 = digs
g1 = [g for g in groups if
grid.locations[d1] & g.mask == grid.locations[d1] & locs]
g2 = [g for g in groups if
grid.locations[d2] & g.mask == grid.locations[d2] & locs]
for g i... | 20edeb5af1af0ce8a3fa6d654894328e77cb59b6 | 55,307 |
def decimal_function(number):
"""
It converts a binary number into a decimal number by using
a re and a recursion function.
"""
decimal_sum = 0
#regular expression substitution
transform = re.sub("(]?\w+)(\w{1})", '\g<1>.\g<2>',str(number))
for arg in str(number):
if ... | 699594a298c75d23594e3c6e7c298df1b76ce4db | 55,308 |
import os
def lambda_handler(event, context):
""" Route the incoming request based on type (LaunchRequest, IntentRequest,
etc.) The JSON body of the request is provided in the event parameter.
"""
print("event.session.application.applicationId=" +
event['session']['application']['application... | d5c60fbb22e783458408b960e1ce19bc0415709f | 55,309 |
def normalize(x, points):
"""Min-Max normalization"""
x = np.array(x)
xmax = get_max(points)
xmin = x.min(axis=0)
return (x-xmin)/(xmax-xmin) | 65fcf471cc161feccfb05cc04d1caa07fbf2d6a6 | 55,310 |
def read_data(filepath, channel):
"""
Read the data file at a specific data channel.
Parameters
----------
filepath : path
Path to the .mat file.
channel : str
Name of the channel in the .mat file.
Returns
-------
dataobject : DataObject
The DataObject containing the data from
the specific channel.
... | fdd4dbeb442c4c99bddeb146f9113f55d2a84367 | 55,311 |
def drivecount(pool_name, count=None, p5_connection=None):
"""
Syntax: Pool <name> drivecount <count>
Description: Sets the drives per stream the pool is allowed to use
Return Values:
-On Success: the drivecount as string
"""
method_name = "drivecount"
return exec_nsdchat([module_name... | 94c4eea8c63790fc76afc2530981677a255b0218 | 55,312 |
def divide(a, b):
"""
Calculates the division of a by b.
If the denominator equals 0, then the result is plus infinity.
--------------------
args:
a (float): the numerator
b (float): the denominator
--------------------
return:
(float): the division of a by b
--... | 2e7f42ed3c92c6ea95798295030262b746e48653 | 55,313 |
def fake_ml_model_data(n_models: int = 1) -> pd.DataFrame:
"""Generate mock data for raw ML model info from the Augury app."""
return pd.DataFrame(
[
{
"name": FAKE.company(),
"prediction_type": np.random.choice(["margin", "win_probability"]),
... | a8d5485e3869463279ffedcc4b00b31823abd3f7 | 55,314 |
def add_plot(df, num_subplots, axes, field="bg", subplot=2):
"""
Parameters
----------
df: dataframe
the dataframe adding data from for the plot
num_subplots: int
number of subplots (1-indexed)
axes: axes object
the axes of the matplotlib figure
field: basestring
... | 86f256afea9b2c0b45b2e248e6cd545055fea30b | 55,315 |
def multi_call(*methods, **kwargs):
"""
Invoke multiple Netmiko methods at once, and return their output, as list.
methods
A list of dictionaries with the following keys:
- ``name``: the name of the Netmiko method to be executed.
- ``args``: list of arguments to be sent to the Netm... | 2a82bcffc796a8f137ee3c87126b57d3976b6623 | 55,316 |
def color_category(category):
"""
adds color to a category and puts it in brackets
"""
if Opts.Print.no_color:
return '['+category+']'
color = {
'progress':'\033[32m',
'get':'\033[1;33m',
'download':'\033[1;36m',
'convert':'\033[36m',
'parse':'\03... | c8f2aa15b3d4b3c841b6f25d8a66924d89da586b | 55,317 |
from typing import Counter
def uniquify(strings):
"""
Return a list of unique strings.
The string at i'th position will have the same prefix as strings[i]
with an appended suffix to make the item unique (if necessary).
>>> uniquify(["cat", "dog", "cat"])
["cat 1", "dog", "cat 2"]
"""
... | 658d0bb16fdca3876be85c2bfbc4da956e35e9b7 | 55,318 |
def nominal_values(arr):
"""
Return the nominal values of the numbers in NumPy array arr.
Elements that are not numbers with uncertainties (derived from a
class from this module) are passed through untouched (because a
numpy.array can contain numbers with uncertainties and pure floats
simultane... | f779be5e71db40b35e1a96c2af21adaa66d03e93 | 55,319 |
import torch
def point_to_cell(pts, feat, W, H, D, expand=1):
""" perform maxpool on points in every cell
set zero vector if cell is empty
if expand=1 then return (N+1)x(N+1)x(N+1), for dmc
expand=0 then return NxNxN, for occupancy/sdf baselines
"""
batchsize = feat.size()[0]
C = feat.s... | 0c805f5dbeb1adf06cf0ad11f4104a5b933de75b | 55,320 |
def init_transitions_simplified(tag_dict):
"""
This function initializes a tag transition table containing only
the boundaries IOBES.
"""
tags = sorted(tag_dict, key=tag_dict.get)
transitions = []
for tag in tags:
if tag in 'OES':
trans = lambda x: 0 if x in 'BOS' el... | f3b9525f24bcd1b6e4c7f50d4ff36be42f363ef4 | 55,321 |
def get_password_hash(password):
"""return password hash"""
pass_secret = password + secret_key
return sha224(pass_secret.encode()).hexdigest() | 8c779000562e83d43fdacfae29a0411fe78d3e05 | 55,322 |
def classify(classifier, im, im2, scaleFactor, minNeigbours, imNum):
"""
Take the V channel image and apply the classifier to it, if the
square to be drawn is larger than 15x15 it is not added to the image
as this is just some over detection occurring.
"""
v = vChannel(im)
cells = classifier... | 3986976dd02fd6f37a6b02fc021dd679da7cbdd1 | 55,323 |
async def get_vpc_peering_connection(cidr_block=None,filters=None,id=None,owner_id=None,peer_cidr_block=None,peer_owner_id=None,peer_region=None,peer_vpc_id=None,region=None,status=None,tags=None,vpc_id=None,opts=None):
"""
The VPC Peering Connection data source provides details about
a specific VPC peering... | e0c79cd5cbbf42e9315b7fa7833fba93fe07c983 | 55,324 |
def color_splash(image, mask):
"""Apply color splash effect.
image: RGB image [height, width, 3]
mask: instance segmentation mask [height, width, instance count]
Returns result image.
"""
# for show
# # Make a grayscale copy of the image. The grayscale copy still
# # has 3 RGB channels, ... | b4fe72fea3fb40c87cc0f093c875f0060a492311 | 55,325 |
def fcode(expr, **settings):
"""Converts an expr to a string of Fortran 77 code
Arguments:
expr -- a sympy expression to be converted
Optional arguments:
assign_to -- When given, the argument is used as the name of the
variable to which the Fortran expre... | bc6015d056046d347bd16591c79abd64fd35a612 | 55,326 |
import types
def task_shell_ui() -> types.TaskDict:
"""Build the Shell UI."""
return {
"actions": None,
"task_dep": [
"_shell_ui_mkdir_build_root",
"_shell_ui_build",
],
} | 3dccd634dfda2e7e623369e0f893432054e64d50 | 55,327 |
def RandomUniform(shape, low=-1.0, high=1.0, **kwargs):
"""Return a Tensor randomly initialized with *Uniform* distribution.
**Type Constraints**: *float32*
Parameters
----------
shape : sequence of (int, Tensor)
The shape of the new tensor.
low : number, optional
The lower bou... | 2260d1bf101287acce9be774aa199f06cf4b8441 | 55,328 |
def get_colors_for_class_ids(class_ids):
"""Set color for class."""
colors = []
for class_id in class_ids:
if class_id == 1:
colors.append((.941, .204, .204))
return colors | a856d804b893bd9ba440833f178ef8b6c9743c1f | 55,329 |
import os
def which_program(program):
"""
Checks that a program exists and is executable
:param program: the program name
:type program: str
:return: The program name if the program is in the system and is executable
"""
def is_exe(fpath):
return fpath is not None and os.path.exis... | 6b14197b1b674a50da3bf94c22c643e6c6eebf3c | 55,330 |
def diag(a):
""" Diagonal of a TT-matrix OR diagonal matrix from a TT-tensor """
if hasattr(a,'__diag__'):
return a.__diag__()
else:
raise ValueError('Can be called only on TT-tensor or a TT-matrix') | bb77b18d627ade342a0638290b12f9523d492d82 | 55,331 |
import torch
def compute_dihedrals(
conformer: torch.Tensor,
atom_indices: torch.Tensor,
) -> torch.Tensor:
"""Computes the dihedral angles [rad] between each atom quartet specified by the
``atom_indices``.
Returns:
A tensor of the dihedral angles.
"""
if len(atom_indices) == 0:
... | e2cc3aa05655c00290ea2b2cc39acd72bff51e5c | 55,332 |
def conflict_resolution_on_insert(old, new, mode='i'):
"""conflict resolution with two entries
"""
if mode == 'i':
print(entry_diff(old, new))
print(bcolors.OKBLUE + 'what to do? ')
print('''
(u)pdate missing (discard conflicting fields in new entry)
(U)pdate other (overwrite conflic... | 2cd80e31599573af38bf3fc1a1ea6045c8b2b379 | 55,333 |
def find_url_by_short(conn, short_url):
"""Возвращает url-адрес по короткому url-у"""
short_url = short_url.rsplit('/', 1).pop() # rsplit('/', 1) режем с правого края по / и режем один раз
pk = inverse(short_url) # запрос по первичному ключу намного быстрее чем обычный запрос
return find_url_by_pk(conn,... | d9d01b10e8f15a7399c6866a12c294930e1637c2 | 55,334 |
import tempfile
import os
import subprocess
def extract_audio(filename, channels=1, rate=44100):
"""
Extract audio from an input file to a temporary WAV file.
"""
temp = tempfile.NamedTemporaryFile(suffix='.wav', delete=False)
if not os.path.isfile(filename):
print("The given file does not... | 3db2db4b70f86c6a7561166b02756e5b29cd403a | 55,335 |
def sticker_set(session, admin):
"""Create a user."""
stickers = []
for file_id in range(0, 10):
sticker = Sticker(str(file_id), str(file_id) + "unique")
stickers.append(sticker)
return sticker_set_factory(session, "test_set", stickers) | 8d611768fd4054865776aa9baa3f71b95ae454c4 | 55,336 |
def merge_data(
data1, data2, how="left", portfolio_suffix=None, **kwargs
):
"""Merge the data
According to whether the data is same, the data is merged by itself, or not.
The data is the transript data and the portfolio data
Self merge parameters example:
merge_data(data1, data1, condition="c... | cf836af1ed968ed758b1c7d04e47534834311d4b | 55,337 |
def compose_complex_features(data, interaction=False, log=False,
sqrt=False, intercept=True, pca=False,
standardize_first=True, power=False,
**kwargs):
"""
Feature engineering:
further improvement of the data varietie... | c1981d9c6eb04426b3b051e86463782d7a52c534 | 55,338 |
import html
import warnings
def cite_me(
doi: str = None, manual_ref: str = None, cite_text: str = "Cite me"
) -> html.Div:
"""
Create a button to show users how to cite a particular resource.
:param doi: DOI
:param manual_ref: If DOI not available
:param cite_text: Text to show as button labe... | d0deb1b98046845a475ba456e445214ddfef1ab2 | 55,339 |
def get_r2plus1d_stem(use_pool1=False):
"""R(2+1)D stem is different than the default one as it uses separated 3D convolution
Args:
use_pool1 (bool, optional): Should the stem contain pool1 layer. Defaults to False.
Returns:
nn.Sequential: the stem of the conv-separated network.
"""
... | ae387d509fe73fc99a71b0de802477412d6a6cbd | 55,340 |
from typing import Tuple
from typing import Optional
def load_dataset(
dataset, data_dir, results_dir
) -> Tuple[SupportedDataset, Optional[SupportedDataset], SupportedDataset, int]:
"""Loads the given classification dataset.
:returns: (train dataset, val dataset (or None if not available), test dataset,... | 48c4e5ae6ba700bd816390ad2ea991132d0d07cb | 55,341 |
import os
import torch
import tqdm
import zipfile
import array
import six
def load_word_vectors(root, wv_type, dim):
"""
From https://github.com/pytorch/text/
BSD 3-Clause License
Copyright (c) James Bradbury and Soumith Chintala 2016,
All rights reserved.
Redistribution and use in source ... | 587bc099f1446cbdd20dc98985124d9242a4fa92 | 55,342 |
def get_api_button():
""" basic api button
get a dropdown populated by an api
"""
return ApiButton(
"Api Button",
"/api/api_button/",
"api_button",
"selection",
None
) | 51c1dd25baade07ed751061559490790831aee87 | 55,343 |
import os
import re
import operator
def Find(name, path):
"""Find executable file with the given name
and maximum API level under specific path."""
result = {}
for root, _, files in os.walk(path):
if name in files:
key = os.path.join(root, name)
sdk_version = os.path.basename(os.path.dirname(k... | c34ae704e8f5b564367c2ff2efd0d72559ecc1e9 | 55,344 |
import pickle
import os
def try_read_cache(dbd_file, dbd_cache_path):
"""
Try to read a cached dbd file from the given path,
return the dbd contents or None if failed or out of date.
"""
try:
with open(dbd_cache_path, "rb") as f:
size,mtime = pickle.load(f)
stat = o... | 207e7568ee2c5eefc90e9d1f7100a636c0c33e42 | 55,345 |
def _map_args(repo, args):
"""
Maps a set of arguments to a predefined set of values. Currently only
__REPO__ is support and will be replaced with the repository name.
:param repo: The repo name used for mapping.
:type repo: str
:param args: An array of arguments to map.
:type args: list
... | 0e31510a764c3f6dca4726daa4e8716bdc7328db | 55,346 |
def plot_population_on_the_surface(
function,
boundaries=(-100, 100),
points=30,
ax=None,
population_coordinates=None,
filename=None,
display=False,
):
"""Plot population and the surface.
Arguments:
function: function that will be used to generate surface
It shou... | 09cde61346fa08463c61b8f064971efbbb8af58d | 55,347 |
def R_curv(deltaT_sub, r_min, radius, Q_drop):
""" thermal resistance due drop curvature
Parameters
----------
deltaT_sub: float
temperature difference to the cooled wall in K
r_min: float
minimum droplet radius in m
radius: float
... | 176520b43184e879bb25bcecc50e64e6dabaa6cc | 55,348 |
def _load_data_012_2015(
subject,
path=None,
force_update=False,
update_path=None,
base_url=BBCI_URL,
verbose=None,
):
"""Load data for 012-2015 dataset."""
if (subject < 1) or (subject > 12):
raise ValueError("Subject must be between 1 and 12. Got %d." % subject)
subjects =... | d51d04de3405c82ac2350c1474967773fc135f3b | 55,349 |
def problem057():
"""
It is possible to show that the square root of two can be expressed as an
infinite continued fraction.
√ 2 = 1 + 1/(2 + 1/(2 + 1/(2 + ... ))) = 1.414213...
By expanding this for the first four iterations, we get:
1 + 1/2 = 3/2 = 1.5
1 + 1/... | 48e0d14be2893dd23e4b13238b56d9939541b526 | 55,350 |
def _logical_1d_to_physical_subspace_auto(sizes_and_strides, physical_shape):
"""Maps logical 1d mesh to subspace of physical nd mesh.
We are mapping a 1d logical mesh to a subspace (a strided slice containing the
origin) of a n-dimensional physical mesh.
output[i] contains the coordinate-tuple in the physica... | bd2b95885183db99cb4fe190554da92defb1d9c9 | 55,351 |
def contributor(request, email, template='user.html'):
"""Contirbutor profile."""
log.debug("Contirbutor profile.")
# Validate user
try:
user = User.objects.get(email=email)
except User.DoesNotExist:
raise Http404
translations = Translation.objects.filter(user=user)
current... | 0465c769cd955afd41769ca105db38a9d3aef3db | 55,352 |
import sys
def print_structure(self, max_rows=20, output=sys.stdout):
"""
Print the keys and row counts of each table in the tableset.
:param max_rows:
The maximum number of rows to display before truncating the data.
Defaults to 20.
:param output:
The output used to print the... | 29e8e7b7f23b5a27387b503e5873d9f10bb70e07 | 55,353 |
import subprocess
def srun(cmd, check=False):
""" run a commmand in a shell """
return subprocess.run(cmd, shell=True, check=check) | b84827f50b5dec3f17e0d0396b9bdd684e16556f | 55,354 |
def map_grouping(fn, grouping):
"""
Map a function over all of the scalar values of a grouping, maintaining the
grouping structure
:param fn: Single-argument function that accepts and returns scalar grouping values
:param grouping: The grouping to map the function over
:return: A new grouping w... | 3307100aa4824e63aa6f466da20064fe9a1fdecb | 55,355 |
import re
import os
import click
def intent_to_dataset_format(path: str, name: str, dataset: str, common: str) -> None:
"""
:param path: location of the intent folder and location of dataset folder
are take from the single arguments.
:type: path
:param name: name of the NLU's readable/tr... | 10f1241097f238c7fb86df9017601a4e2b3ec4d8 | 55,356 |
def non_rec_admix(founders,founders_weight,gen,breakpoint_probability):
"""
create an admixed haploid from the paternal and maternal sequences
in a non-recursive way.
Returns:
haploid_returns: dict with same keys as self.maternal and self.paternal
"""
# assert all founders have all ke... | 852a11a740e4462f1dfb68c6077659917886e664 | 55,357 |
from pathlib import Path
from typing import Any
def update_subscription(
*,
scsAsId: str = Path(..., title="The ID of the Netapp that creates a subscription", example="myNetapp"),
subscriptionId: str = Path(..., title="Identifier of the subscription resource"),
item_in: schemas.AsSessionWithQoSSubscri... | 7ad41a633759f6e4a21d0df7b2478805047377aa | 55,358 |
def double_ema(data, period):
"""Double EMA"""
try:
logger.info(
"Calculating Double Exponential Moving Average for period = {}".
format(period))
check_period_type(period)
ema1 = data.ewm(span=period, min_periods=period).mean()
ema2 = ema1.ewm(span=period,... | 27c71683df05b04ef5a0fe0e9a6e2e4e6669bed6 | 55,359 |
def converter_qrcode_em_json(files: UploadFile = File(...)):
""" Recebe um QRCODE e Retorna um Json com as informações do QRCODE"""
img = Image.open(files.file)
decoded = pyzbar.decode(img)
if decoded:
return jsonFromBrcode(decoded[0].data.decode())
raise ValueError | 2648cc0370bbfac823765ceabc284096d91a76e7 | 55,360 |
def extension_to_format(extension):
"""
Extension to image format
Attempts to convert file extension to image format that Pillow
library understands.
:param extension: string - file extension
:return: string - image format name
"""
formats = dict()
formats['jpg'] = 'JPEG'
formats... | 5b0f22d51cfd8f3076e0ff4b78da2869865c03ed | 55,361 |
from typing import Concatenate
def uxnet(input_shape,
n_depth=2,
n_filter_base=16,
kernel_size=(3, 3),
n_conv_per_depth=2,
activation="relu",
last_activation='linear',
batch_norm=False,
dropout=0.0,
pool_size=(2, 2),
r... | 004fca5859d0ea76372fd981f8c65d68e74bba9d | 55,362 |
def _decode_list(vals):
""" List decoder
"""
return [val.decode() if hasattr(val, 'decode') else val for val in vals] | 852629abaa25e5bc4f2388b273a0676d3afb8337 | 55,363 |
def convert_to_grayscale(cv2im):
"""
Converts 3d image to grayscale
Args:
cv2im (numpy arr): RGB image with shape (D,W,H)
returns:
grayscale_im (numpy_arr): Grayscale image with shape (1,W,D)
"""
grayscale_im = np.sum(np.abs(cv2im), axis=0)
im_max = np.percentile(grayscal... | a645a5350c3da7be01ec3e9b705e3badc010b5a4 | 55,364 |
def visualize_one_hot_segmentation(segmap_one_hot, num_seg_classes=30,
dtype='float32'):
"""TBD."""
assert dtype in ['uint8', 'float32']
seg_label_map = tf.argmax(segmap_one_hot, axis=-1)
return visualize_label_map(seg_label_map, num_seg_classes=num_seg_classes,
... | ce550a8d95e68c7db9a57fca00563913fca10600 | 55,365 |
def ecliptic_horizon(local_sidereal_time, geo_latitude, obliquity):
"""This function returns the longitudes of the two points of the ecliptic
which are on the horizon, as well as the angle between the ecliptic and the
horizon.
:param local_sidereal_time: Local sidereal time, as an Angle object
:typ... | 6be06048d54ad208fa8a0a43f932258ad8a6838b | 55,366 |
def loadWeights (args) :
"""
Load weights to off chip device memory. The weights are first quantized.
:param args: Collection of arguments. Most importanly args["datadir"] which is the path to a folder containing weights & biases.
:type args: dict.
:returns: tuple -- (weightsBlob, fcWeight, fcBias)... | b80d5f6645a9c9d405b33c20afaf2d22cf9e2d9c | 55,367 |
def butter_highpass_coefficients(freqmin, sampling_rate, order=4.):
"""
:param freqmin:
:param freqmax:
:param sampling_rate:
:param order:
:return:
"""
nyq = 0.5 * sampling_rate
b, a = butter(order, [freqmin / nyq], btype='high')
return b, a | ae55dfa2a1f36cdaaf7aa15b80364fbe59793928 | 55,368 |
def find_possible_plates(input_img) -> t.Optional[t.List[Plate]]:
"""
Finding all possible contours that can be plates
"""
plates = []
img_preprocessed = preprocess_color(input_img)
possible_plate_contours = get_contours(img_preprocessed)
for plate_contour in possible_plate_contours:
... | 84bdc121ed874d2efdbfca0fa3203ae3a87bfd3e | 55,369 |
def is_empty(elem):
"""This function is just a helper function for
check whether the passed elements (i.e. list)
is empty or not
Args:
elem (:obj:): Any structured data object (i.e. list).
Returns:
bool: True if element is empty or false if not.
"""
if not elem:
ret... | e449e1f765744bbc21880881550c9e87c8e83bcd | 55,370 |
from pathlib import Path
def get_toplevel_dirpath(path):
"""
Provide the top level directory for the given path.
The top level directory contains the ``controls.json`` file.
This function returns ``None`` if a top level path can not be found.
:param path: absolute or relative path to a file or d... | 324df1ceda2bf5813d65f86f6319dde8819f8fa3 | 55,371 |
def list_pad(l, pad_tok, max_length):
"""
Args:
sequences: a generator of list or tuple
pad_tok: the char to pad with
max_seq_len: max len for padding
Returns:
a list of list where each sublist has same length
"""
result = [l[x] if x < len(l) else pad_tok for x in ran... | b4d3c4875d7a1a411c0e6527ed9f7550e1a01cdb | 55,372 |
def w_cucm_file_main(current_window=None):
"""Window for CUCM export file selection"""
if current_window is not None:
current_window.close()
layout = [
gui_print('Select CUCM export CSV file'),
cucm_file_browse_botton('Browse'),
button('Next')
]
return Sg.Window(windo... | d784446f48d6db1ace51cb341394e45c21c5c2a7 | 55,373 |
def get_IQUV(filename):
"""Get IQUV from a CASA im file exported to fits."""
f = pyfits.open(filename)
data = f[0].data
f.close()
stokes = {}
stokes['I'] = data[0, 0, :, :]
stokes['Q'] = data[1, 0, :, :]
stokes['U'] = data[2, 0, :, :]
stokes['V'] = data[3, 0, :, :]
return stokes | 0eae5d5a52f84ebc01b7985baaf92245829432cd | 55,374 |
import os
def check_ad_id(path: str):
"""A simple checker."""
pdf_text = []
for file in os.listdir(path):
with open(f"{path}/{file}", "rb") as pdf:
data = pdftotext.PDF(pdf)[0]
pdf_text.append(data)
ad_id = []
for datapoint in pdf_text:
idx = datapoint.find("Ad... | cb96cda16de5cc096ac889a6f44707694f782382 | 55,375 |
import json
def load_json_from_disk(filename):
"""Loads a json file from disk"""
with open(filename, "r") as handle:
return json.load(handle) | ea81de7186963b260ed66e7d5e9083b9f0afc881 | 55,376 |
import signal
def bandpassfilter(x: object, fs: object) -> object:
"""
:rtype: object
:param x: a list of samples
:param fs: sampling frequency
:return: filtered list
"""
x = signal.detrend(x)
b = signal.firls(129, [0, 0.6 * 2 / fs, 0.7 * 2 / fs, 3 * 2 / fs, 3.5 * 2 / fs, 1], [0, ... | fd1bd1b4d6c555e0e162b9091230c91d8825da9e | 55,377 |
def str_(s):
"""
In python 3 turns bytes to string. In python 2 just passes string.
:param s:
:return:
"""
try:
return s.decode()
except:
return s | ee9c65334a201ad37db058c0e3c51a41f0650298 | 55,378 |
def format_drugs(br):
"""
Format drug rows in merged clinical file from Firehose.
The data consists of one or more drug entries for each patient.
Here we use a MultiIndex with Patient Barcode on level 0 and
the drug administration on level 1.
Input
br: clinical DataFrame with pati... | 1cf1167f9898b049ed4b836b4463f80435681769 | 55,379 |
from datetime import datetime
import pickle
def produce_statements(output_list, enrich=True, no_upload=False,
pickle_file=None, n_proc=1, db=None):
"""Convert the reader output into a list of StatementData instances."""
if db is None:
db = get_primary_db()
if enrich:
... | 071f5b5c02be29d2a9131b91aaa44f45bde40ce4 | 55,380 |
def read_corpus(file):
"""
fxn to pars the database : corpus of thematic documents
"""
long_list = []
with jsonlines.open(file) as f:
for line in f.iter():
long_list.append(line)
my_corpus = pd.DataFrame(long_list,copy =True)
corpus = select_useful_cols(my_corpus)
ret... | d658959509ab14c9a1f5eeb28d71a137516dba4a | 55,381 |
from typing import List
def write_on_image(img: np.ndarray, text: str, color: List) -> np.ndarray:
"""Write text at the top of the image."""
# Add a white border to top of image for writing text
for i, line in enumerate(text.split('\n')):
y = 30 + i * 30
cv2.putText(img=img,
... | 20c9dbc3f51bdf723d583279b9956ab808bcdf9c | 55,382 |
from datetime import datetime
def _move_relevant_activities_to_hospital(human, mobility_planner, current_activity, rng, conf, hospital, critical=False):
"""
Changes the schedule so that `human`s future activities are at a hospital.
Note 1: [IMPORTANT]: human.recovery_days and mobility_planner.location_of_... | ffa2a6dd8afd43d7e2737218beedf8d64391d6f5 | 55,383 |
def f1(cosmo, a):
""" Linear order growth rate
Parameters
----------
cosmo: dict
Cosmology dictionary.
a : tf.TensorArray
Scale factor.
Returns
-------
Scalar float Tensor
Linear order growth rate.
Notes
-----
The expression for :math:`f_{1}(a)` is:
... | 58eb6e4c8f4ebd44445a902442fe867a26d3376f | 55,384 |
def expand_sentences(encoded_sentences, max_word_len):
"""
Expand every given sentence to the same length (pad it with 0) and
put them all into one tensor.
"""
# Get word counts of all sentences.
lens = np.array([sentence.shape[0] for sentence in encoded_sentences])
# Create mask of shape [n... | 93bb4c3d34ea0292c3c08cd998f693475af66216 | 55,385 |
def order_by_num_props(assets: list) -> dict:
"""Order unsigs by number of properties"""
ordered = defaultdict(list)
for asset in assets:
num_props = asset.get("num_props")
ordered[num_props].append(asset)
return ordered | 28f0408dd654b9263fb1ab51a21a27ae43406c9a | 55,386 |
def suppress_registration(cache_path):
"""Build a package to suppress Setup Assistant, returns path to it."""
pkg_output_file = os.path.join(cache_path, 'suppress_registration.pkg')
if not os.path.isfile(pkg_output_file):
print "Building registration suppression package..."
temp_dir = tempfile.mkdtemp(pre... | 52d887820aa6b26eedb1c48fb609af5dc098ab7f | 55,387 |
def expandAbreviations(inputColumn,expansionList):
"""iteratively delete regex query matches from input list
Keyword arguments:
inputColumn -- a column from a pandas dataframe, this will be the set of
target words/entries that deletions will be made from
eraseList -- a column containing strings ... | 89748fad8a77a846787927e58706a8c3c96d5486 | 55,388 |
import click
import glob
import os
import copy
import traceback
def main(command, argument, argument2, paths_to_mutate, backup, runner, tests_dir,
test_time_multiplier, test_time_base,
swallow_output, use_coverage, dict_synonyms, cache_only, version,
suspicious_policy, untested_policy, pre_... | 99d4ab3ad456a58fb1401b510937078d8ed73fa6 | 55,389 |
from datetime import datetime
async def raw_stations_observations(station, websession, userid, limit=0, start=None):
"""Get observation response from station"""
params = {}
if limit > 0:
params["limit"] = limit
if start:
if not isinstance(start, datetime):
raise ValueError... | 45beb0a2d085408677fc2fb23f5dc1f1040e8fe1 | 55,390 |
def get_youtube_data(user_id: int) -> {str: any}:
"""
This function helps to render a specific preferences-submenu
:param user_id: int (user_id should be stored in the session with key=identifier)
:return: all variable values that are required in the jinja2-template of the preferences menu
"""
... | e7d1f565fd422db49212ba5ae384e977963204ea | 55,391 |
from typing import Union
from typing import Optional
from typing import Literal
def three_d_plot(
mesh: Union[PolyData, UnstructuredGrid, MultiBlock],
key: str = None,
filename: Optional[str] = None,
jupyter: bool = False,
off_screen: bool = False,
window_size: tuple = (1024, 768),
backgro... | c1ad27c4012b84ca4521ac6eb1ec2f327b8cb271 | 55,392 |
from typing import Union
from typing import List
def runs_test(arr: Union[ndarray, List]) -> float:
"""
runs_test
Run tests are a very simple method of sanity checking a set of random numbers. A run is defined
as a series of increasing values or a series of decreasing values. The number of increasing... | 932a29754979b4687a0f57fa186ca8d182d65742 | 55,393 |
import pathlib
def _detect_home_location() -> pathlib.Path:
"""Detects the location of the root directory"""
# path/to/home/backend/core/config_loader.py
path_to_self = pathlib.Path(__file__).absolute()
# path/to/home/backend/core/
path_to_core_module = path_to_self.parent
# path/to/home/ba... | c309656d5a56261fd96c86c179947981dc65dc58 | 55,394 |
from typing import Optional
from typing import Callable
def get_app(ini_settings: dict, extra_init: Optional[Callable] = None) -> Router:
"""Construct a WSGI application from INI settings.
You can pass extra callable which is called back when Initializer is about to finish. This allows you to poke app config... | 4fdb74406a3dcc86888c7ad46b1370d0b147ea3a | 55,395 |
from typing import List
def get_conv2D_Wmats(tensor: np.ndarray) -> List[np.ndarray]:
"""
Extract W slices from a 4 index conv2D tensor of shape: (N,M,i,j) or (M,N,i,j).
Return ij (N x M) matrices
"""
mats = []
N, M, imax, jmax = tensor.shape
assert N + M >= imax + jmax, 'invalid tensor shape detected: ... | 982ec7b689cbfba60979e2445538f89d87197a19 | 55,396 |
def verify_synonym(input_file, output_file, synonym_file,
usagekeycol='gbifapi_usageKey',
acceptedkeycol='gbifapi_acceptedKey',
taxonomicstatuscol='gbifapi_status',
outputcol='nameMatchValidation'):
"""verify if more information on the sy... | 45686244186601ff67ba885a2af25775e2baa994 | 55,397 |
import re
def normalize(sresult, force_id_mask=False):
"""Replace time, updateSequence and version specific values with generic
values"""
# XML responses
version = re.search(b'<!-- (.*) -->', sresult)
updatesequence = re.search(b'updateSequence="(\S+)"', sresult)
timestamp = re.search(b'times... | 18dda2b8881feb01cc98f4e3b2b9d940f0f0abca | 55,398 |
def _to_int(hex_digit):
"""turn an hexadecimal digit into a proper integer"""
return int(hex_digit, 16) | 2d9f0a3f5e754fc0fc932349a9a0bcb5f0066cce | 55,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.