content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def make_mlp(dim_list, activation_list, batch_norm=False, dropout=0):
"""
Generates MLP network:
Parameters
----------
dim_list : list, list of number for each layer
activation_list : list, list containing activation function for each layer
batch_norm : boolean, use batchnorm at each layer,... | dc2677ccd1291942f474eb6fe7719103731f4cfc | 3,646,900 |
import uuid
import os
def pddobj_video_file_path(instance, filename):
"""Generate file path for new video file"""
ext = filename.split('.')[-1]
filename = f'{uuid.uuid4()}.{ext}'
return os.path.join('uploads/videos/', filename) | 103f6f895983090100c245ce8845f744d4dce2aa | 3,646,901 |
def load_and_prep_image(filename):
"""
Reads an image from filename, turns it into a tensor
and reshapes it to (img_shape, img_shape, colour_channel).
"""
image = cv2.imread(filename)
# gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
face_cascade = cv2.CascadeClassifier(haarcascade)
fa... | cbf3b1a840ecc931adf0dd7f84cff68e83180efe | 3,646,902 |
def DoH(im, canvas, max_sigma=30, threshold=0.1, display=True):
""" Difference of Hessian blob detector
:param im: grayscale image
:param max_sigma: maximum sigma of Gaussian kernel
:param threshold: absolute lower bound Local maxima smaller than threshold ignore
"""
blobs = blob_doh... | 965ce92cdba24514fa9802a9e8891a96d97f1cf5 | 3,646,903 |
def _parse_class(s):
"""
Parse a key, value pair, separated by '='
On the command line (argparse) a declaration will typically look like:
foo=hello
or
foo="hello world"
"""
items = s.split('=')
key = items[0].strip() # we remove blanks around keys, as is logical
if len(... | db517a277e21448eb83ba25244a8bfa3892f18a4 | 3,646,904 |
import difflib
def getStringSimilarity(string1:str,string2:str):
"""
This function will return a similarity of two strings.
"""
return difflib.SequenceMatcher(None,string1,string2).quick_ratio() | 292f552449569206ee83ce862c2fb49f6063dc9e | 3,646,905 |
from typing import Optional
from datetime import datetime
import os
import shutil
import glob
def model_downloader(
handler_type: HandlerType,
bucket_name: str,
model_name: str,
model_version: str,
model_path: str,
temp_dir: str,
model_dir: str,
) -> Optional[datetime.datetime]:
"""
... | 4b7dea6f21278af92dd625f58bc5e28129f0da22 | 3,646,906 |
def calc_simcoef_distr(patfeats, labels, id_dict, simcoef):
"""
Calculates the score distributions
Inputs:
- simcoef: simcoef the values are calculated with (string)
- labels: list of strings with the scores to be calculated (e.g.: ['cited', 'random'])
- id_dict: dictionary containing the pa... | 897bcb2e30e0587173557772c17589fe43841e60 | 3,646,907 |
def fft(signal, sampling_rate, plot=False, show_grid=True, fig_size=(10, 5)):
"""
Perform FFT on signal.
Compute 1D Discrete Fourier Transform using Fast Fourier Transform.
Optionally, plot the power spectrum of the frequency domain.
Parameters
----------
signal : ndarray
Input arr... | 70296c900e8ad7342be3c6ee18ff8b34e481ac0e | 3,646,908 |
def pattern_count(data, **params):
"""
Count occurrences of a given pattern.
Args:
data (list): values.
params (kwargs):
pattern (str or list): the pattern to be sought in data (obligatory)
metric (str): 'identity' counts identical positions,
... | 0c943554b4c5b7739a6ca16aa739b3cd614ab79d | 3,646,909 |
import os
import logging
import sys
def read_directory(directory):
"""
Read file names from directory recursively
Parameters
----------
directory : string
directory/folder name where to read the file names from
Returns
---------
files : list of strings
list ... | a3e272b437c0bf4ea59cfe7afdc9ebab6718954c | 3,646,910 |
import requests
import signal
def do(hostname):
"""
Performs a GET request.
Parameters
----------
hostname : str
Target request
Return
------
The request results
"""
try:
return requests.get(hostname, timeout=10)
except TimeoutException:
print("\... | 7e300e4be98beecad29e28594b76230e6c19382d | 3,646,911 |
def getAssignmentReport(assignment):
"""
Produces an ABET assignment report (as a markdown-formatted string)
for the given assignment (which is expected to be a codepost API
object) by pulling all relevant data as well as source
code files (and grader comments) for randomly selected A, B and C samples
"""
... | fd2a49c8fa8e3a15a878e06d29ec9598912034c6 | 3,646,912 |
def start_game():
"""
Method to start
:return: Choice selection for new game or load game
"""
maximize_console()
print_title()
print('Do you want to start a new game (enter 1) or resume an ongoing game (enter 2)?')
choice = input('||> ')
print()
return choice | 5780468f4239a8a519538a18feb12a0956dd4170 | 3,646,913 |
import os
def modified_files():
"""
Gets a list of modified files in the repo.
:return: A list of absolute paths to all changed files in the repo
"""
repo_root_dir = repo_root()
return [os.path.join(repo_root_dir, d.b_path) for d in get().head.commit.diff() if not (d.new_file or d.deleted_fil... | 70e4aa10a754792782c3bdf76c11644730d7064d | 3,646,914 |
import os
def encode_data(dataset_path=DATASET_PATH):
"""Encodes the symbloc music in the dataset folder.
:param dataset_path (str): Path to the dataset
:return data, filenames (list): Encoded songs and their file names
"""
# encoded songs and their file names
data = []
filenames = []
... | bd454a1b85906077f484f51a496668c13acc85d7 | 3,646,915 |
def get_inception_score(images, batch_size, splits=10):
"""
the function is to calculate the inception score of the generated images
image is a numpy array with values should be in the range[0, 255]
images 299x299x3
"""
assert(type(images) == np.ndarray)
inception_model = inception_v3
... | 9e14691a5c885b6b95e6ff9ecff014db0cca119e | 3,646,916 |
def generate_audio_testing(raw_gain, raw_freq, raw_dampings, modal_fir, reverb, impulse_profile,
gains, frequencies, dampings, modal_response,
noise, acceleration_scale, revc, audio_sample_rate, example_secs, scratch='controls'):
"""Generate DiffImpact's estimat... | 1b7932c165c9615096b79b5d0c19859bc6dd113d | 3,646,917 |
def dice_coef_multilabel(y_true, y_pred, numLabels=4, channel='channel_first'):
"""
calculate channel-wise dice similarity coefficient
:param y_true: the ground truth
:param y_pred: the prediction
:param numLabels: the number of classes
:param channel: 'channel_first' or 'channel_last'
:retu... | 16af1961d900add04f0f277335524ba1568feb12 | 3,646,918 |
def gaussian(sigma, fs, t=None):
""" return a gaussian smoothing filter
Args:
sigma: standard deviation of a Gaussian envelope
fs: sampling frequency of input signals
t: time scale
Return:
a Gaussian filter and corresponding time scale
"""
if... | aba5d419bb22cd0bfe0a702346dd77735b7f0d4c | 3,646,919 |
def score_sent(sent):
"""Returns a score btw -1 and 1"""
sent = [e.lower() for e in sent if e.isalnum()]
total = len(sent)
pos = len([e for e in sent if e in positive_wds_with_negation])
neg = len([e for e in sent if e in negative_wds_with_negation])
if total > 0:
return (pos - neg) / to... | cc70d035e932513ae27743bbca66ae8d870fcc91 | 3,646,920 |
import torch
def flipud(tensor):
"""
Flips a given tensor along the first dimension (up to down)
Parameters
----------
tensor
a tensor at least two-dimensional
Returns
-------
Tensor
the flipped tensor
"""
return torch.flip(tensor, dims=[0]) | b0fd62172b0055d9539b554a8c967c058e46b397 | 3,646,921 |
def connect():
"""Function to connect to database on Amazon Web Services"""
try:
engine = create_engine('mysql+mysqlconnector://dublinbikesadmin:dublinbikes2018@dublinbikes.cglcinwmtg3w.eu-west-1.rds.amazonaws.com/dublinbikes')
port=3306
connection = engine.connect()
Sessio... | 81da870305a853b621f374b521bb680e435d852b | 3,646,922 |
def get_file_type(filepath):
"""Returns the extension of a given filepath or url."""
return filepath.split(".")[-1] | 070a1b22508eef7ff6e6778498ba764c1858cccb | 3,646,923 |
def calcB1grad(B2grad,W2,A2):
"""
Calculates the gradient of the cost with respect to B1 using the chain rule
INPUT: B2grad, [layer3Len,1] ; W2, [layer2Len, layer3Len] ;
A2, [layer2len, 1]
OUTPUT: B1grad, [layer2Len, 1]
"""
temp1 = np.dot(W2,B2grad) #layer2Len * 1 vector
sigmGra... | e214f79be1377b4fc0f36690accf6072fee27884 | 3,646,924 |
def plot_3d(x, y, z, title, labels):
"""
Returns a matplotlib figure containing the 3D T-SNE plot.
Args:
x, y, z: arrays
title: string with name of the plot
labels: list of strings with label names: [x, y, z]
"""
plt.rcParams.update({'font.size': 30, 'legend.fontsize': 2... | 624a62f9dc941d6b7cfed06e10250fae8c8defa9 | 3,646,925 |
def is_rating_col_name(col:str)->bool:
"""
Checks to see if the name matches the naming convention for a rating
column of data, i.e. A wrt B
:param col: The name of the column
:return: T/F
"""
if col is None:
return False
elif isinstance(col, (float, int)) and np.isnan(col):
... | 57802e888f5a75cdc521a08115ad3b74a56da43d | 3,646,926 |
def _make_buildifier_command():
"""Returns a list starting with the buildifier executable, followed by any
required default arguments."""
return [
find_data(_BUILDIFIER),
"-add_tables={}".format(find_data(_TABLES))] | ab480ff1bc7b21685a4dd95bbc12ae5ee223bdc0 | 3,646,927 |
from typing import Union
def infer_path_type(path: str) -> Union[XPath, JSONPath]:
"""
Infers the type of a path (XPath or JSONPath) based on its syntax.
It performs some basic sanity checks to differentiate a JSONPath from an XPath.
:param path: A valid XPath or JSONPath string.
:return: An insta... | abeed8003b05dd5b66ada1367d0a5acf39102d60 | 3,646,928 |
def get_proximity_angles():
"""Get the angles used for the proximity sensors."""
angles = []
# Left-side of the agent
angles.append(3 * pi / 4) # 135° (counter-clockwise)
for i in range(5): # 90° until 10° with hops of 20° (total of 5 sensors)
angles.append(pi / 2 - i * pi / 9)
... | 29c093d1aef0d10d24968af8bee06e6d050e9119 | 3,646,929 |
def delete(request, scenario_id):
"""
Delete the scenario
"""
# Retrieve the scenario
session = SessionMaker()
scenario = session.query(ManagementScenario).filter(ManagementScenario.id == scenario_id).one()
# Delete the current scenario
session.delete(scenario)
session.commit()
... | 4d9c7090d66f8cd3bd055c6f383870b4648a3828 | 3,646,930 |
import os
def get_python_list(file_path):
"""
Find all the .py files in the directory and append them to a raw_files list.
:params:
file_path = the path to the folder where the to-be read folders are.
:returns:
raw_files : list of all files ending with '.py' in the read folder.
"""
py... | b771814b86c5405d5810694ad58b7a8fe80b1885 | 3,646,931 |
def angle(p1, p2, p3):
"""Returns an angle from a series of 3 points (point #2 is centroid).
Angle is returned in degrees.
Parameters
----------
p1,p2,p3 : numpy arrays, shape = [n_points, n_dimensions]
Triplets of points in n-dimensional space, aligned in rows.
Returns
-------
... | 3e57121a20f18f2ee5728eeb1ea2ffb39500db40 | 3,646,932 |
def transformer_parsing_base():
"""HParams for parsing on WSJ only."""
hparams = transformer_base()
hparams.attention_dropout = 0.2
hparams.layer_prepostprocess_dropout = 0.2
hparams.max_length = 512
hparams.learning_rate_warmup_steps = 16000
hparams.hidden_size = 1024
hparams.learning_rate = 0.05
hpa... | f86b3fe446866ff3de51f02278c2d2c9d7f1b126 | 3,646,933 |
def split_protocol(urlpath):
"""Return protocol, path pair"""
urlpath = stringify_path(urlpath)
if "://" in urlpath:
protocol, path = urlpath.split("://", 1)
if len(protocol) > 1:
# excludes Windows paths
return protocol, path
return None, urlpath | e9b006d976847daa9a94eb46a9a1c2f53cd9800f | 3,646,934 |
import pprint
def createParPythonMapJob(info):
"""
Create map job json for IGRA matchup.
Example:
job = {
'type': 'test_map_parpython',
'params': {
'year': 2010,
'month': 7
},
'localize_urls': [
]
}... | 142afc4b4be0d77b4921e57c358494dbfc43c6ab | 3,646,935 |
def calc_lampam_from_delta_lp_matrix(stack, constraints, delta_lampams):
"""
returns the lamination parameters of a laminate
INPUTS
- ss: laminate stacking sequences
- constraints: design and manufacturing guidelines
- delta_lampams: ply partial lamination parameters
"""
lampam = np.ze... | a1d179f441368f2ebef8dc4be4e2a364d41cf84e | 3,646,936 |
def perp(i):
"""Calculates the perpetuity to present worth factor.
:param i: The interest rate.
:return: The calculated factor.
"""
return 1 / i | 2fe59a039ac5ecb295eb6c443143b15e41fdfddb | 3,646,937 |
def chebyshev(x, y):
"""chebyshev distance.
Args:
x: pd.Series, sample feature value.
y: pd.Series, sample feature value.
Returns:
chebyshev distance value.
"""
return np.max(x-y) | 876f0d441c48a7ab4a89b1826eb76459426ad9a3 | 3,646,938 |
def soda_url_helper(*, build_url, config, year, **_):
"""
This helper function uses the "build_url" input from flowbyactivity.py,
which is a base url for data imports that requires parts of the url text
string to be replaced with info specific to the data year. This function
does not parse the data,... | b4e0f8c781a966d0291dad7d897eba02dc7a4e09 | 3,646,939 |
import argparse
def generate_base_provider_parser():
"""Function that generates the base provider to be used by all dns providers."""
parser = argparse.ArgumentParser(add_help=False)
parser.add_argument('action', help='specify the action to take', default='list',
choices=['create',... | 9f677188835a8bddaefcdf2ab173d0392285e630 | 3,646,940 |
from typing import Optional
from datetime import datetime
from typing import List
def search(
submitted_before: Optional[datetime] = None,
submitted_after: Optional[datetime] = None,
awaiting_service: Optional[str] = None,
url:Optional[str] = None,
token:Optional[str] = None,
... | a2ce0d86fde2792365f27cf386e7c9ef0d4a0fa1 | 3,646,941 |
from typing import List
from typing import Pattern
import re
from typing import Optional
from typing import Match
def _target_js_variable_is_used(
*, var_name: str, exp_lines: List[str]) -> bool:
"""
Get a boolean value whether target variable is used in
js expression or not.
Parameters
-... | be07cb1628676717b2a02723ae7c01a7ba7364d6 | 3,646,942 |
def rnn_temporal(x, h0, Wx, Wh, b):
"""
Run a vanilla RNN forward on an entire sequence of data. We assume an input
sequence composed of T vectors, each of dimension D. The RNN uses a hidden
size of H, and we work over a minibatch containing N sequences. After running
the RNN forward, we return the ... | 794fed02ef96c97d9b4ccb6a7278fc72b81eea33 | 3,646,943 |
from typing import Union
def rejection_fixed_lag_stitch(fixed_particle: np.ndarray,
last_edge_fixed: np.ndarray,
last_edge_fixed_length: float,
new_particles: MMParticles,
adjusted_weights: np.n... | aeec4fc1956c7a63f15812988a38d54b63234de4 | 3,646,944 |
def zip_equalize_lists(a, b):
"""
A zip implementation which will not stop when reaching the end of the
smallest list, but will append None's to the smaller list to fill the gap
"""
a = list(a)
b = list(b)
a_len = len(a)
b_len = len(b)
diff = abs(a_len - b_len)
if a_len < b_len:... | 1cf5b9cadf4b75f6dab6c42578583585ea7abdfc | 3,646,945 |
def cover_line(line):
"""
This function takes a string containing a line that should
potentially have an execution count and returns a version
of that line that does have an execution count if deemed
appropriate by the rules in validate_line().
Basically, if there is currently no number where t... | 612cd295b78ce9a0d960b902027827c03733f609 | 3,646,946 |
def find_period(samples_second):
""" # Find Period
Args:
samples_second (int): number of samples per second
Returns:
float: samples per period divided by samples per second
"""
samples_period = 4
return samples_period / samples_second | c4a53e1d16be9e0724275034459639183d01eeb3 | 3,646,947 |
def sqrt(x: int) -> int:
"""
Babylonian Square root implementation
"""
z = (x + 1) // 2
y = x
while z < y:
y = z
z = ( (x // z) + z) // 2
return y | 1a91d35e5783a4984f2aca5a9b2a164296803317 | 3,646,948 |
def is_consecutive_list(list_of_integers):
"""
# ========================================================================
IS CONSECUTIVE LIST
PURPOSE
-------
Reports if elments in a list increase in a consecutive order.
INPUT
-----
[[List]] [list_of_integers]
- A list ... | 3b165eb8d50cc9e0f3a13b6e4d47b7a8155736b9 | 3,646,949 |
def circles(x, y, s, c='b', vmin=None, vmax=None, **kwargs):
"""
See https://gist.github.com/syrte/592a062c562cd2a98a83
Make a scatter plot of circles.
Similar to plt.scatter, but the size of circles are in data scale.
Parameters
----------
x, y : scalar or array_like, shape (n, )
... | cb3b2c4316ec573aa29cf5d500f50fbcd64f47b5 | 3,646,950 |
from datetime import datetime
def generate_agency_tracking_id():
""" Generate an agency tracking ID for the transaction that has some random
component. I include the date in here too, in case that's useful. (The
current non-random tracking id has the date in it.)
@todo - make this more random"""
... | d54e74c392bed6f4b3d8ec7409a6d7709a3bc8f2 | 3,646,951 |
import pathlib
def get_enabled_gems(cmake_file: pathlib.Path) -> set:
"""
Gets a list of enabled gems from the cmake file
:param cmake_file: path to the cmake file
:return: set of gem targets found
"""
cmake_file = pathlib.Path(cmake_file).resolve()
if not cmake_file.is_file():
lo... | 0b4c8c68230b075d2c27d72b1290217864fc6888 | 3,646,952 |
from operator import add
from operator import mul
def celeryAdd3(a,b):
"""This is for a specific Celery workflow
f = (a+b) * (a+b)
We'll use chord, group and chain"""
if request.method == 'GET':
# When a worker receives an expired task it will mark the task as REVOKED
res = (group(add.... | 84599389542663207ff57a07e3b58cecc9b6427b | 3,646,953 |
def create_unmerge_cells_request(sheet_id, start, end):
"""
Create v4 API request to unmerge rows and/or columns for a
given worksheet.
"""
start = get_cell_as_tuple(start)
end = get_cell_as_tuple(end)
return {
"unmergeCells": {
"range": {
"sheetId": shee... | 3fd560a82522738099bacd3f606bbea948de7226 | 3,646,954 |
def list_to_str(slist, seperator=None):
"""Convert list of any type to string seperated by seperator."""
if not seperator:
seperator = ','
if not slist:
return ""
slist = squash_int_range(slist)
return seperator.join([str(e) for e in slist]) | 64d20b744a7b465e58e50caf60e0e1aaf9b0c2e7 | 3,646,955 |
def log_web_error(msg):
"""Take a screenshot of a web browser based error
Use this function to capture a screen shot of the web browser
when using Python's `assert` keyword to perform assertions.
"""
screenshot = selene.helpers.take_screenshot(selene.browser.driver(),)
msg = '''{original_msg}
... | 8f5e9f6c586e6739d6581986c66689881d812316 | 3,646,956 |
def parent_id_name_and_quotes_for_table(sqltable):
""" Return tuple with 2 items (nameof_field_of_parent_id, Boolean)
True - if field data type id string and must be quoted), False if else """
id_name = None
quotes = False
for colname, sqlcol in sqltable.sql_columns.iteritems():
# root table... | 6f3319dc6ae0ea70af5d2c9eda90fb1a9fb9daac | 3,646,957 |
def client():
"""Returns a Flask client for the app."""
return app.test_client() | 40d3cf2c330d2f82b6ae7514e833ef5d1bcb9594 | 3,646,958 |
def _get_horizons_ephem(
id,
start: Time,
stop: Time,
step: str = "12H",
id_type: str = "smallbody",
location: str = "@TESS",
quantities: str = "2,3,9,19,20,43",
):
"""Returns JPL Horizons ephemeris.
This is simple cached wrapper around astroquery's Horizons.ephemerides.
"""
... | f57fae233cb16f365b1db2a78aa3de29df479aea | 3,646,959 |
from enthought.mayavi import version
from .maps_3d import plot_map_3d, m2screenshot
from enthought.tvtk.api import tvtk
from enthought.mayavi import mlab
from enthought.mayavi.core.registry import registry
def plot_map(map, affine, cut_coords=None, anat=None, anat_affine=None,
figure=None, axes=No... | d7ef70bb98849532e94d7b975303cbd370fe8bbe | 3,646,960 |
def get_mode(h5,songidx=0):
"""
Get mode from a HDF5 song file, by default the first song in it
"""
return h5.root.analysis.songs.cols.mode[songidx] | 9a9eb7cfed2bc525a3b5d3c8cb251c7e170a589c | 3,646,961 |
import json
def read_label_schema(path):
"""
Reads json file and returns deserialized LabelSchema.
"""
with open(path, encoding="UTF-8") as read_file:
serialized_label_schema = json.load(read_file)
return LabelSchemaMapper().backward(serialized_label_schema) | 8f15a6e63864c6f737f465abb3011193ce136db6 | 3,646,962 |
def Dump(root):
"""Return a string representing the contents of an object.
This function works only if root.ValidateExports() would pass.
Args:
root: the object to dump.
Returns:
A big string containing lines of the format:
Object.SubObject.
Object.SubObject.ParameterName = %r
"""
h = ... | 7f6a9229f6b0c250a56324570fae249c0bf1d246 | 3,646,963 |
def clean_profit_data(profit_data):
"""清理权益全为0的垃圾结算日"""
for i in list(range(len(profit_data)))[::-1]:
profit = profit_data[i][1] == 0
closed = profit_data[i][2] == 0
hold = profit_data[i][3] == 0
if profit and closed and hold:
profit_data.pop(i)
return profit_dat... | d1b7fe9d747a1149f04747b1b3b1e6eba363c639 | 3,646,964 |
def convert_single_example(ex_index, example, max_word_length,max_sen_length,
tokenizer):
"""Converts a single `InputExample` into a single `InputFeatures`."""
text_sen = example.text_sen.strip().split()
text_pos=example.text_pos.strip().split()
text_ps = example.text_ps.strip().spli... | faf13bd6db6a07a4546531cc968bad5443b95a12 | 3,646,965 |
def scrub_literal(value):
"""
Scrubs control characters from the incoming values to remove
things like form feeds (\f) and line breaks (\n) which might
cause problems with Jena.
Data with these characters was found in the Backstage data.
"""
if not value:
return None
if isinstanc... | e0e77bb0edecc810cc6fe051020936ca0ee9bf62 | 3,646,966 |
def mock_interface_settings_mismatch_protocol(mock_interface_settings, invalid_usb_device_protocol):
"""
Fixture that yields mock USB interface settings that is an unsupported device protocol.
"""
mock_interface_settings.getProtocol.return_value = invalid_usb_device_protocol
return mock_interface_se... | 61958439a2869d29532e50868efb39fe3da6c8b5 | 3,646,967 |
from typing import Mapping
from typing import Any
import shutil
def run_eval(exp_name: str) -> Mapping[str, Any]:
""" """
pred_log_dir = f"{_ROOT}/test_data/eval_tracking_dummy_logs_pred"
gt_log_dir = f"{_ROOT}/test_data/eval_tracking_dummy_logs_gt"
out_fpath = f"{_ROOT}/test_data/{exp_name}.txt"
... | 3eaead879a39a30d2524da037d82f4d9b68d17e7 | 3,646,968 |
import os
def check_dir(path):
"""
检查文件夹是否存在,存在返回True;不存在则创建,返回False
"""
if not os.path.exists(path):
os.makedirs(path)
return False
return True | 523cca18de4be3f2359151747a86ab5b5dfad633 | 3,646,969 |
def MakeLocalSsds(messages, ssd_configs):
"""Constructs the repeated local_ssd message objects."""
if ssd_configs is None:
return []
local_ssds = []
disk_msg = (
messages.
AllocationSpecificSKUAllocationAllocatedInstancePropertiesAllocatedDisk)
interface_msg = disk_msg.InterfaceValueValuesEnu... | 128e7a0358221fe3d93da4726924a7a783c65796 | 3,646,970 |
def valid_variant(s, is_coding=True):
"""
Returns True if s is a valid coding or noncoding variant, else False.
Parameters
----------
s : `str`
Variant string to validate.
is_coding : `bool`
Indicates if the variant string represents a coding variant.
"""
_validate_s... | 8cb6c37bed303a052a8655dfb0832bfba638f0d6 | 3,646,971 |
def is_icon_address_valid(address: str) -> bool:
"""Check whether address is in icon address format or not
:param address: (str) address string including prefix
:return: (bool)
"""
try:
if isinstance(address, str) and len(address) == 42:
prefix, body = split_icon_address(address... | 9666d22d04d568706356b7bafd0f202cb9178892 | 3,646,972 |
import base64
def _b64urldec(input: str) -> bytes:
"""
Deocde data from base64 urlsafe with stripped padding (as specified in the JWS RFC7515).
"""
# The input is stripped of padding '='. These are redundant when decoding (only relevant
# for concatenated sequences of base64 encoded data) but the ... | fb535072b560b8565916ae8ec3f32c61c41115d8 | 3,646,973 |
def get_sns_topic_arn(aws_creds, ec2_region):
"""
Retrieves the sns topic arn for the account
"""
rgt_client = ResourceGroupsTaggingClient(aws_creds, ec2_region, logger)
sns_topic_arn = rgt_client.get_sns_topic_arn(SNS_TOPIC_TAG_KEY, SNS_TOPIC_TAG_VALUE)
if not sns_topic_arn:
raise SnsTo... | 760caa77acf414eacf4bb177dd9252fe6578a505 | 3,646,974 |
import scipy
def create_bspline_basis(knots, spline_order, dt=0.02):
"""Create B-spline basis."""
# The repeated boundary knots are appended as it is required for Cox de Boor
# recursive algorithm. See https://math.stackexchange.com/questions/2817170/
# what-is-the-purpose-of-having-repeated-knots-in-a-b-spli... | 8256b282ffc5f19a9e00d59c689e57664600b2f4 | 3,646,975 |
def execute(
device,
commands,
creds=None,
incremental=None,
with_errors=False,
timeout=settings.DEFAULT_TIMEOUT,
command_interval=0,
force_cli=False
):
"""
Connect to a ``device`` and sequentially execute all the commands in the
iterab... | ead00377f7c50d8bfdb6da39a7a1fe1820d9bcc7 | 3,646,976 |
import hashlib
import sys
def _attempt_get_hash_function(hash_name, hashlib_used=hashlib, sys_used=sys):
"""Wrapper used to try to initialize a hash function given.
If successful, returns the name of the hash function back to the user.
Otherwise returns None.
"""
try:
_fetch_hash = getat... | 240d375ecf422c47be0366f34c5ccd9af44aa3e4 | 3,646,977 |
import requests
def get_proxy(usage: str):
"""
通过WEB API接口获取代理
:param usage: 目标站点,对应WEB_AVAILABLE_PROXIES的key
:return: 可用代理或None
"""
url = API_SERVER + "/proxy?usage={}".format(usage)
res = requests.get(url, timeout=5)
try:
if res.status_code == 200:
return res.jso... | 2c836f0a7a4dce2e5442080ee93a1b32d10dac3d | 3,646,978 |
def column_names_get(subject: str) -> tuple:
""" Returns column names. """
if subject == c.SUBJECT.PLANETS:
return c.HEADERS.PLANETS
elif subject == c.SUBJECT.STARSHIPS:
return c.HEADERS.STARSHIPS
elif subject == c.SUBJECT.VEHICLES:
return c.HEADERS.VEHICLES
elif subject == c... | a544574d5ac66e2ea7e045fa2bba37fe78df20f5 | 3,646,979 |
import os
def is_morepath_template_auto_reload():
""" Returns True if auto reloading should be enabled. """
auto_reload = os.environ.get("MOREPATH_TEMPLATE_AUTO_RELOAD", "")
return auto_reload.lower() in {"1", "yes", "true", "on"} | 72839bf2ab0a70cefe4627e294777533d8b0087f | 3,646,980 |
def relabel_prometheus(job_config):
"""Get some prometheus configuration labels."""
relabel = {
'path': '__metrics_path__',
'scheme': '__scheme__',
}
labels = {
relabel[key]: value
for key, value in job_config.items()
if key in relabel.keys()
}
# parse _... | eb08f617903fe66f462a5922f8149fd8861556ad | 3,646,981 |
import random
def q_geography_capital():
"""Ask what the capital of a given country is."""
question = QuestionGenerator()
question.set_type('geography')
# select country
all_countries = facts.get_geography_countries_list()
country = random.choice(all_countries)
# formulate question
q... | 63362aae1eb0e117da3ade0c9bff22edb5504689 | 3,646,982 |
from functools import reduce
def binary_stabilizer_to_pauli_stabilizer(stabilizer_tableau):
"""
Convert a stabilizer tableau to a list of PauliTerms
:param stabilizer_tableau: Stabilizer tableau to turn into pauli terms
:return: a list of PauliTerms representing the tableau
:rytpe: List of Pauli... | 78183d9ecd436267d7732ba50cb6591fea54984e | 3,646,983 |
def checkGroup(self, group, colls):
"""
Args:
group:
colls:
Returns:
"""
cut = []
for elem in group:
if elem in colls:
cut.append(elem)
if len(cut) == len(group):
return cut
else:
return [] | ca30648c536bcf26a1438d908f93a5d3dcc131c9 | 3,646,984 |
def get_node_shapes(input_graph_def, target_nodes):
"""Get shapes of target nodes from input_graph_def, shapes may be partial"""
node_shapes = []
for target in target_nodes:
for node in input_graph_def.node:
if node.name == target:
if not 'shape' in node.attr:
print("Warning: Fail to g... | 0a70a81f0be826697d47b52dc2a2e63c0c73b3b4 | 3,646,985 |
def calculate_cost(A3, Y):
"""
计算损失函数cost值
Args:
A3: 正向传播的输出,尺寸大小为(输出尺寸, 样本数量)
Y: 真实标签向量,尺寸大小和a3相同
Return:
cost: 损失函数cost值
"""
m = Y.shape[1]
logprobs = np.multiply(-np.log(A3), Y) + np.multiply(
-np.log(1 - A3), 1 - Y)
cost = 1. / m * np.nansum(logprobs)... | 0a85baae5acc6f9ceec417f2942727cd3d96a34e | 3,646,986 |
import sys
def _replace_sysarg(match):
"""Return the substitution for the $<n> syntax, .e.g. $1 for the
first command line parameter.
"""
return sys.argv[int(match.group(1))] | efd338c537ecf2ef9113bc71d7970563ac9e5553 | 3,646,987 |
def qsammobilenetv2(**kwargs):
"""Constructs a QSAMMobileNetv2 model.
"""
model = QSAMMobileNetV2(**kwargs)
return model | 4d0b9f23a3c40ab2386d30fe45ca70a401f41b1a | 3,646,988 |
def get_frame_labels_fields(
sample_collection,
frame_labels_field=None,
frame_labels_prefix=None,
frame_labels_dict=None,
dataset_exporter=None,
required=False,
force_dict=False,
):
"""Gets the frame label field(s) of the sample collection matching the
specified arguments.
Prov... | 0bdb1346f154f125b2f39f638929ae6e5d661db7 | 3,646,989 |
def _rpc_code_to_error_code(rpc_code):
"""Maps an RPC code to a platform error code."""
return _RPC_CODE_TO_ERROR_CODE.get(rpc_code, exceptions.UNKNOWN) | 7cb6ef3d7b751c915673f99a88800bdb53e81f72 | 3,646,990 |
def peak_values(dataframe_x, dataframe_y, param):
"""Outputs x (potentials) and y (currents) values from data indices
given by peak_detection function.
Parameters
----------
DataFrame_x : pd.DataFrame
should be in the form of a pandas DataFrame column.
For ex... | 3e0d656d80ef5806abcd2d71e80be544eca585cb | 3,646,991 |
def _infer_geometry(value):
"""Helper method that tries to infer the $geometry shape for a given value"""
if isinstance(value, dict):
if "$geometry" in value:
return value
elif 'coordinates' in value and 'type' in value:
return {"$geometry": value}
raise InvalidQu... | b381d647881bac5122f420cb9806e90ebf56b716 | 3,646,992 |
import typing
import scipy
def random_rotation_operator_tensor (operand_space_shape:typing.Tuple[int,...]) -> np.ndarray:
"""NOTE: Not a uniform distribution."""
if vorpy.tensor.dimension_of_shape(operand_space_shape) == 0:
raise Exception(f'invalid dimension for vector space having rotation')
A ... | fd4442bb6178824fe71c6050f44539f8af34c149 | 3,646,993 |
from . import highlevel
import platform
import sys
from typing import OrderedDict
def get_system_details(backends=True):
"""Return a dictionary with information about the system
"""
buildno, builddate = platform.python_build()
if sys.maxunicode == 65535:
# UCS2 build (standard)
unitype... | d33237bfe1d51c374e9e7e698cd27a9927ddf0df | 3,646,994 |
def get_early_stopping(callback_config:dict):
""" Get tf keras EarlyStopping callback.
Args:
callback_config: config info to build callback
"""
return keras.callbacks.EarlyStopping(**callback_config) | 6f9f5e26b69765ff817c89b6ebbb59a62bc76266 | 3,646,995 |
def decode(rdf, hint=[]):
"""Decode ReDIF document."""
def decode(encoding):
rslt = rdf.decode(encoding)
if rslt.lower().find("template-type") == -1:
raise RuntimeError("Decoding Error")
return rslt
encodings = hint + ["windows-1252", "utf-8", "utf-16", "latin-1"]
i... | f42eed2caaba90f4d22622643885b4d87b9df98b | 3,646,996 |
def pad_square(x):
""" Pad image to meet square dimensions """
r,c = x.shape
d = (c-r)/2
pl,pr,pt,pb = 0,0,0,0
if d>0: pt,pd = int(np.floor( d)),int(np.ceil( d))
else: pl,pr = int(np.floor(-d)),int(np.ceil(-d))
return np.pad(x, ((pt,pb),(pl,pr)), 'minimum') | 3a0b248f9403d0cb392e1aff306af435b5a43396 | 3,646,997 |
from typing import Union
from typing import Any
from typing import Tuple
def get_env_properties(
env: Union[gym.Env, VecEnv], network: Union[str, Any] = "mlp"
) -> (Tuple[int]):
"""
Finds important properties of environment
:param env: Environment that the agent is interacting with
:t... | 6a377830cb24bc215b7d1c6b09b08ed63ab383ef | 3,646,998 |
import os
import json
def gen_abc_json(abc_gt_dir, abc_json_path, image_dir):
"""
根据abcnet的gt标注生成coco格式的json标注
:param abc_gt_dir:
:param abc_json_path:
:param image_dir:
:return:
"""
# Desktop Latin_embed.
cV2 = [' ', '!', '"', '#', '$', '%', '&', '\'', '(', ')', '*', '+', ',', '-'... | 5b565fa632eeb69313035bc14ba35021de321142 | 3,646,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.