content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def get_mat_2d(sequence, rnn=False):
"""Uses aa_to_map to turn a sequence into a 3D array representation of the
protein.
"""
if rnn:
mat = np.zeros((len(sequence), 36))
for i, aa in enumerate(sequence):
mat[i] = aa_to_map(aa)[:,:6,:].flatten()
else... | 122eb7f890995eb4d95226251bb5f2c9a4ba38df | 27,000 |
from datetime import datetime
def TimeSec():
"""[Takes current time in and convert into seconds.]
Returns:
[float]: [Time in seconds]
"""
now = datetime.now()
return now.second+(now.minute*60)+(now.hour*60*60) | 58892b89feb05a56c27d4fd62ba174f9d1c09591 | 27,001 |
def partition_variable(variable, partition_dict):
"""
As partition_shape() but takes a mapping of dimension-name to number
of partitions as it's second argument. <variable> is a VariableWrapper
instance.
"""
partitions = []
for dim in variable.dimensions:
if dim.name in partition_d... | 7ffd4075bbb6bbd156f76c9271101003c5db8c1e | 27,002 |
def _get_object_properties(agent,
properties,
obj_type,
obj_property_name,
obj_property_value,
include_mors=False):
"""
Helper method to simplify retrieving of properties
T... | d2e43bcc1700e76a7ca117eaf419d1c5ef941975 | 27,003 |
def get_crypto_currency_pairs(info=None):
"""Gets a list of all the cypto currencies that you can trade
:param info: Will filter the results to have a list of the values that correspond to key that matches info.
:type info: Optional[str]
:returns: If info parameter is left as None then the list will co... | b44a013d6bbf348321c4f00006262e1ab02e0459 | 27,004 |
def sparse_graph_convolution_layers(name, inputs, units, reuse=True):
"""
This one is used by the Joint_SMRGCN model;
A crude prototypical operation
"""
with tf.variable_scope(name, reuse=tf.AUTO_REUSE if reuse else False):
# adj_tensor: list (size nb_bonds) of [length, length] matrices
... | c5c16242fb175e851a78a34249c2f902bd2e9cb4 | 27,005 |
import click
import sys
import logging
import os
def main(argv):
"""
The main function to invoke the powerfulseal cli
"""
args = parse_args(args=argv)
if args.mode is None:
return parse_args(['--help'])
##########################################################################
... | 76e38fb72b4ea96c8d4e62ed0359045e770df03f | 27,006 |
def update_or_create_tags(observer, repo, tag=None, type_to_update=None):
"""Create or update tags."""
observer.update_state(
state='PROGRESS',
meta='Retrieving data and media from Github'
)
git = GithubAPI(repo)
if tag:
data, media = git.get_data(tag)
if type_to_up... | 3f478c66cda9648cb72325e9668ea08b52147fbf | 27,007 |
def confirm_api_access_changes(request):
"""Renders the confirmation page to confirm the successful changes made to
the API access settings for the superuser's group.
Parameters:
request - The request object sent with the call to the confirm page if
the requested changes were su... | b31ce15ec72607200edd66e72df99b5ad9cb4afc | 27,008 |
def mpl_hill_shade(data, terrain=None,
cmap=DEF_CMAP, vmin=None, vmax=None, norm=None, blend_function=rgb_blending,
azimuth=DEF_AZIMUTH, elevation=DEF_ELEVATION):
""" Hill shading that uses the matplotlib intensities. Is only for making comparison between
blending me... | 6a881794b486e581f817bf073c7cbef465d8d504 | 27,009 |
def img_docs(filename='paths.ini', section='PATHS'):
"""
Serve the PATH to the img docs directory
"""
parser = ConfigParser()
parser.read(filename)
docs = {}
if parser.has_section(section):
params = parser.items(section)
for param in params:
docs[param[0]] = par... | c76cc9ae17fb5dd8cfc6387349b6f47545fe01ad | 27,010 |
def KGPhenio(
directed = False, preprocess = "auto", load_nodes = True, load_node_types = True,
load_edge_weights = True, auto_enable_tradeoffs = True,
sort_tmp_dir = None, verbose = 2, cache = True, cache_path = None,
cache_sys_var = "GRAPH_CACHE_DIR", version = "current", **kwargs
) -> Graph:
"""R... | e4a3647013c0b250e29007c0db08a6d6813c8976 | 27,011 |
def _x_mul(a, b, digit=0):
"""
Grade school multiplication, ignoring the signs.
Returns the absolute value of the product, or None if error.
"""
size_a = a.numdigits()
size_b = b.numdigits()
if a is b:
# Efficient squaring per HAC, Algorithm 14.16:
# http://www.cacr.math.uw... | 84dc948c03106ce26d9b4abf67c57b5d13438ef1 | 27,012 |
import re
def server_version(headers):
"""Extract the firmware version from HTTP headers."""
version_re = re.compile(r"ServerTech-AWS/v(?P<version>\d+\.\d+\w+)")
if headers.get("Server"):
match = version_re.match(headers["Server"])
if match:
return match.group("version") | 24151f3898430f5395e69b4dd7c42bd678626381 | 27,013 |
import os
def init_test_env(setting_path, output_path, file_list,fname_list):
"""
create test environment, the file list would be saved into output_path/reg/test/file_path_list.txt,
a corresponding auto-parsed filename list would also be saved in output/path/reg/test/file_name_list.txt
:param settin... | 132dfec46799c1395fefd0992c473cd52c8bc8ef | 27,014 |
def slice_constant(data, batch_size=32, name='constant_data', global_step=None):
"""Provide a slice based on the global_step.
This is useful when the entire data array can be stored in memory because it
allows you to feed the data very efficiently.
Args:
data: A numpy array or tensor.
batch_size: The ... | 53ebf9a6216841a4a4db8c2d77bd9545328454ac | 27,015 |
def es_subcadena(adn1, adn2):
"""
(str, str) -> bool
>>> es_subcadena('gatc', 'tta')
False
>>> es_subcadena('gtattt', 'atcgta')
False
:param:adn1:str:primera cadena a comparar
:param:adn2:str:segunda cadena a comparar
:return:bool:verificacion si una es subcadena de la otra
"""... | 9c3605e74e1c9dbf227695a4f0f6431cc845a5f1 | 27,016 |
def get_labels_and_features(nested_embeddings):
""" returns labels and embeddings
"""
x = nested_embeddings[:,:-1]
y = nested_embeddings[:,-1]
return x,y | 302505bd3aa769570fa602760f7da1ddd017e940 | 27,017 |
def all_(f : a >> bool, t : r(a)) -> bool:
"""
all :: Foldable r => (a -> bool) -> r a -> bool
Determines whether all elements of the structure satisfy the predicate.
"""
return DL.all_(toList(t)) | ec19ae23b282affd99580b9614edaec8a8a2fd44 | 27,018 |
def log_binom_sum(lower, upper, obs_vote, n0_curr, n1_curr, b_1_curr, b_2_curr, prev):
"""
Helper function for computing log prob of convolution of binomial
"""
# votes_within_group_count is y_0i in Wakefield's notation, the count of votes from
# given group for given candidate within precinct i (u... | 2a2d80671b594d2c56d6db5dc770833d5d8aa129 | 27,019 |
def parse_locator(src):
""" (src:str) -> [pathfile:str, label:either(str, None)]
"""
pathfile_label = src.split('#')
if len(pathfile_label)==1:
pathfile_label.append(None)
if len(pathfile_label)!=2:
raise ValueError('Malformed src: %s' % (src))
return pathfile_label | 970bc1e2e60eec4a54cd00fc5984d22ebc2b8c7a | 27,020 |
def detect_seperator(path, encoding):
"""
:param path: pathlib.Path objects
:param encoding: file encoding.
:return: 1 character.
"""
# After reviewing the logic in the CSV sniffer, I concluded that all it
# really does is to look for a non-text character. As the separator is
# determine... | 8436359a602d2b8caf72a6dbdac4870c502d1bad | 27,021 |
def pr_at_k(df, k):
"""
Returns p/r for a specific result at a specific k
df: pandas df with columns 'space', 'time', 'y_true', and 'y_pred'
k: the number of obs you'd like to label 1 at each time
"""
#static traits of df
universe = df['time'].nunique()
p = df['y_true'].... | 79997405f360fa66c4e0cbe35d54a15976cc6e3b | 27,022 |
def draw_segm(im, np_segms, np_label, np_score, labels, threshold=0.5, alpha=0.7):
"""
Draw segmentation on image.
"""
mask_color_id = 0
w_ratio = .4
color_list = get_color_map_list(len(labels))
im = np.array(im).astype('float32')
clsid2color = {}
np_segms = np_segms.astype(np.uint8)... | f2248256a0be01efb1e9402d1e51e04a5fde365d | 27,023 |
def solve(board):
"""
solve a sudoku board using backtracking
param board: 2d list of integers
return: solution
"""
space_found = find_empty_space(board)
if not space_found:
return True
else:
row, col = space_found
for i in range(1, 10):
if valid_number(board,... | 5b94db3ba4873c0fc5e91355dab6c59ed0603fa0 | 27,024 |
from typing import List
from typing import Optional
def check(s: str) -> None:
"""
Checks if the given input string of brackets are balanced or not
Args:
s (str): The input string
"""
stack: List[str] = []
def get_opening(char: str) -> Optional[str]:
"""
Gets the... | 720018e5b39e070f48e18c502e8a842feef32840 | 27,025 |
def format_address(msisdn):
"""
Format a normalized MSISDN as a URI that ParlayX will accept.
"""
if not msisdn.startswith('+'):
raise ValueError('Only international format addresses are supported')
return 'tel:' + msisdn[1:] | f5a5cc9f8bcf77f1185003cfd523d7d6f1212bd8 | 27,026 |
def get_nag_statistics(nag):
"""Return a report containing all NAG statistics"""
report = """Constants: {0}
Inputs: {1}
NANDs: {2}
Outputs: {3}
Min. I/O distance: {4}
Max. I/O distance: {5}""".format(
nag.constant_number,
nag.input_number,
nag.nand_number,
nag... | 44d3f32bc0b05d8b1d81c3b32dc140af4fd20aa0 | 27,027 |
def svm_loss_naive(w, x, y, reg):
"""
Structured SVM loss function, naive implementation (with loops).
Inputs have dimension D, there are C classes, and we operate on mini-batches of N examples.
:param w: A numpy array of shape (D, C) containing weights.
:param x: A numpy array of shape (N, D) con... | c115c61d1f384b187a031a13fbb96bf9dce69cfc | 27,028 |
def create_backup(storage, remote, parent=None):
""" Create a new backup of provided remote and return its backup object.
.. warning:: Do not forget to add a label on returned backup to avoid its
removal by the garbage collector.
"""
if parent:
parent_ref = storage.resolve(parent)
... | 7c4f5b424d6c48474fce74396eb6e47d0935f559 | 27,029 |
def get_pairwise_correlation(population_df, method="pearson"):
"""Given a population dataframe, calculate all pairwise correlations.
Parameters
----------
population_df : pandas.core.frame.DataFrame
Includes metadata and observation features.
method : str, default "pearson"
Which co... | 85f1df4357f9996492bac6053a2f0852b2318f14 | 27,030 |
import os
def get_game_raw_pbp_filename(season, game):
"""
Returns the filename of the raw pbp folder
:param season: int, current season
:param game: int, game
:return: str, /scrape/data/raw/pbp/[season]/[game].zlib
"""
return os.path.join(organization.get_season_raw_pbp_folder(season), ... | 111008b9e845b7e05960edcaf57ee3c155d7e2e9 | 27,031 |
def plot_route(cities, route, name='diagram.png', ax=None):
"""Plot a graphical representation of the route obtained"""
mpl.rcParams['agg.path.chunksize'] = 10000
if not ax:
fig = plt.figure(figsize=(5, 5), frameon = False)
axis = fig.add_axes([0,0,1,1])
axis.set_aspect('equal', ad... | b8ceadb0a26e6f8c2eacea66ede9db948d73ca65 | 27,032 |
import math
def bertScore(string):
"""
Function to generate the output list consisting top K replacements for each word in the sentence using BERT.
"""
corrector = SpellCorrector()
temp1 = []
temp2 = []
temp3 = []
con = list(string.split(" "))
tf.reset_default_graph()
sess = t... | 9edf75111a0df95532a1332f6b0f4b5dbe495ac2 | 27,033 |
import dataclasses
def configuration_stub(configuration_test: Configuration) -> Configuration:
"""
Configuration for tests.
"""
return dataclasses.replace(
configuration_test,
distance_between_wheels=DISTANCE_BETWEEN_WHEELS,
) | ea2fe84c19f86062fd728bd10814303026776c03 | 27,034 |
def join_smiles(df, df_smiles=None, how="left"):
"""Join Smiles from Compound_Id."""
if df_smiles is None:
load_resource("SMILES")
df_smiles = SMILES
result = df.merge(df_smiles, on="Compound_Id", how=how)
result = result.apply(pd.to_numeric, errors='ignore')
result = result.fillna("... | e36bc5d31764e5eb8fdcf006b05e4fe75eeff36a | 27,035 |
def signature(*types, **kwtypes):
"""Type annotations and conversions for methods.
Ignores first parameter.
"""
conversions = [(t if isinstance(t, tuple) else (t, t)) for t in types]
kwconversions = {k: (t if isinstance(t, tuple) else (t, t))
for k, t in kwtypes.items()}
d... | 414ecfd4738b431e8e059319c347a6e7bedabc80 | 27,036 |
def mean(image):
"""The mean pixel value"""
return image.mean() | 176dd8d483008fa1071f0f0be20c4b53ad0e2a5f | 27,037 |
import yaml
def read_event_file(file_name):
"""Read a file and return the corresponding objects.
:param file_name: Name of file to read.
:type file_name: str
:returns: ServiceEvent from file.
:rtype: ServiceEvent
"""
with open(file_name, 'r') as f:
contents = yaml.safe_load(f)
... | 66da0a76f064dd99c9b2eff5594aa58f5d1d8cca | 27,038 |
def create_basic_cnn_model(num_classes: int):
"""
Function to create a basic CNN.
:param num_classes: The number of classes (labels).
:return: A basic CNN model.
"""
model = Sequential()
# Convolutional + spooling layers
model.add(Conv2D(64, (5, 5), input_shape=(config.ROI_IMG_SIZE['HEI... | 42af48bfa673c5473fa2255b34a3155ee4e88dc0 | 27,039 |
def get_layer_information(cloudsat_filenames, get_quality=True, verbose=0):
""" Returns
CloudLayerType: -9: error, 0: non determined, 1-8 cloud types
"""
all_info = []
for cloudsat_path in cloudsat_filenames:
sd = SD(cloudsat_path, SDC.READ)
if verbose:
#... | e3c52cd9284730c35da3ddbc1879d0e083fa63bd | 27,040 |
import torch
def from_magphase(mag_spec, phase, dim: int = -2):
"""Return a complex-like torch tensor from magnitude and phase components.
Args:
mag_spec (torch.tensor): magnitude of the tensor.
phase (torch.tensor): angle of the tensor
dim(int, optional): the frequency (or equivalent... | 2f33de266fa295d0c21cf5002f6420c60eb07071 | 27,041 |
def remove_suboptimal_parses(parses: Parses, just_one: bool) -> Parses:
""" Return all parses that have same optimal cost. """
minimum = min(parse_cost(parse) for parse in parses)
minimal_parses = [parse for parse in parses if parse_cost(parse) == minimum]
if just_one:
return Parses([minimal_par... | c223229e73a5319bdb40ac58695aa6f5a8c0bb4b | 27,042 |
def local_ranking(results):
"""
Parameters
----------
results : list
Dataset with initial hand ranking and the global hand ranking.
Returns
-------
results : list
Dataset with the initial hand ranking and the game-local hand ranking
(from 0 - nplayers).
""... | 2be1ff269ad18ba9439d183f5899f5034927b5d7 | 27,043 |
def is_monotonic_increasing(bounds: np.ndarray) -> bool:
"""Check if int64 values are monotonically increasing."""
n = len(bounds)
if n < 2:
return True
prev = bounds[0]
for i in range(1, n):
cur = bounds[i]
if cur < prev:
return False
prev = cur
retur... | e745ce3825f4e052b2f62c7fdc23e66b5ee5d4d1 | 27,044 |
def parse(data):
"""
Takes binary data, detects the TLS message type, parses the info into a nice
Python object, which is what is returned.
"""
if data[0] == TLS_TYPE_HANDSHAKE:
obj = TlsHandshake()
obj.version = data[1:3]
obj.length = unpack(">H", data[3:5])[0]
if data[5] == TLS_TYPE_CLIENT_HELLO:
obj.... | 64698fde904d702181f4d8bacda648d9fbea68a7 | 27,045 |
def recoverSecretRanks_GPT(mod_rec, tok_rec, startingText, outInd, finishSentence=True):
"""
Function to calculate the secret ranks of GPT2 LM of a cover text given the cover text
"""
startingInd=tok_rec.encode(startingText)
endingInd=outInd[len(startingInd):]
secretTokensRec=[]
for i in ran... | be08520901b5c010d89a248814f96681265bb467 | 27,046 |
def threshold_strategies(random_state=None):
"""Plan (threshold):
- [x] aggregated features: (abs(mean - median) < 3dBm) || (2*stdev(x) < 8dBm)
- [x] histogram: x < 85dBm
- [ ] timeseries batch: p < 10**-3
"""
dummy = lambda: dummy_anomaly_injector(scaler=None, random_state=random_s... | d127a36d36360f6733e26538c37d3cbb47f199a4 | 27,047 |
import math
def ellipse_properties(x, y, w):
"""
Given a the (x,y) locations of the foci of the ellipse and the width return
the center of the ellipse, width, height, and angle relative to the x-axis.
:param double x: x-coordinates of the foci
:param double y: y-coordinates of the foci
:param... | 95864eac0feb9c34546eefed5ca158f330f88e3d | 27,048 |
def build_func(f, build_type):
"""
Custom decorator that is similar to the @conf decorator except that it is intended to mark
build functions specifically. All build functions must be decorated with this decorator
:param f: build method to bind
:type f: function
:parm build_type: The WAF build t... | e880b7d5a3c4ac79a3caff48f1a3f991ed321262 | 27,049 |
def getnumoflinesinblob(ext_blob):
"""
Get number of lines in blob
"""
ext, blob_id = ext_blob
return (ext, blob_id, int(getpipeoutput(['git cat-file blob %s' % blob_id, 'wc -l']).split()[0])) | ccc492cc66e046d73389f6822ad04cd943376f7b | 27,050 |
import os
def dir_exists(dir):
"""Test if dir exists"""
return os.path.exists(dir) and os.path.isdir(dir) | f787457f3a03c3e9c605a1753de0ab7c648e4a2c | 27,051 |
import requests
def fetch_data(full_query):
"""
Fetches data from the given url
"""
url = requests.get(full_query)
# Parse the json dat so it can be used as a normal dict
raw_data = url.json()
# It's a good practice to always close opened urls!
url.close()
return raw_data | 576b2548c1b89827e7586542e4d7e3f0cc89051d | 27,052 |
import http
def post(*args, **kwargs): # pragma: no cover
"""Make a post request. This method is needed for mocking."""
return http.post(*args, **kwargs) | d5c91da5f39ece36183a8265f74378a35f11c4c7 | 27,053 |
def shear_x(image: tf.Tensor, level: float, replace: int) -> tf.Tensor:
"""Equivalent of PIL Shearing in X dimension."""
# Shear parallel to x axis is a projective transform
# with a matrix form of:
# [1 level
# 0 1].
image = transform(
image=wrap(image), transforms=[1., level, 0., 0., 1., 0., 0., ... | 230fb5d346a966c4945b0bb39f336c1fddeb94fd | 27,054 |
import os
import logging
import sys
def sequence_data(project_dir, config):
"""
opens word sequence HDF5 file
:param project_dir:
:param config:
:return: pointer to word sequence array
"""
try:
h5_seq = h5py.File(os.path.join(project_dir, config['files'][config['word_sequence']['fi... | 4f6afa11e2e9f3473b5e9343c9ebba940964c1bb | 27,055 |
def extract_const_string(data):
"""Extract const string information from a string
Warning: strings array seems to be practically indistinguishable from strings with ", ".
e.g.
The following is an array of two elements
const/4 v0, 0x1
new-array v0, v0, [Ljava/lang/String;
const/4 v1, 0x0
... | 70229ea1a6183218577244f185a5e37d170fe4be | 27,056 |
def choose_action(q, sx, so, epsilon):
"""
Choose action index for given state.
"""
# Get valid action indices
a_vindices = np.where((sx+so)==False)
a_tvindices = np.transpose(a_vindices)
q_max_index = tuple(a_tvindices[np.argmax(q[a_vindices])])
# Choose next action based on epsilon-g... | 626ccda15c24d983a060bdd6dd90a836c461b1ba | 27,057 |
from typing import Union
import sys
def _meta_commands(sql: str, context: Context, client: Client) -> Union[bool, Client]:
"""
parses metacommands and prints their result
returns True if meta commands detected
"""
cmd, schema_name = _parse_meta_command(sql)
available_commands = [
["\... | faf456a4a0b448a7e2ea50a052dd100b0166e056 | 27,058 |
def soliswets(function, sol, fitness, lower, upper, maxevals, delta):
""""
Implements the solis wets algorithm
"""
bias = zeros(delta.shape)
evals = 0
num_success = 0
num_failed = 0
dim = len(sol)
while evals < maxevals:
dif = uniform(0, delta, dim)
newsol = clip(so... | 19104e717af6701ce3d838d526059575306018cf | 27,059 |
def _get_precision_type(network_el):
"""Given a network element from a VRP-REP instance, returns its precision type:
floor, ceil, or decimals. If no such precision type is present, returns None.
"""
if 'decimals' in network_el:
return 'decimals'
if 'floor' in network_el:
return 'flo... | b3b451a26ec50ce5f2424ea7a3652123ae96321d | 27,060 |
import textwrap
import argparse
def vtr_command_argparser(prog=None):
""" Argument parse for run_vtr_task """
description = textwrap.dedent(
"""
Runs one or more VTR tasks.
"""
)
epilog = textwrap.dedent(
"""
Examples
--------
Run the t... | 3f1c167f98a11123a194683df061e435b2d181c7 | 27,061 |
import json
def user_list():
"""Retrieves a list of the users currently in the db.
Returns:
A json object with 'items' set to the list of users in the db.
"""
users_json = json.dumps(({'items': models.User.get_items_as_list_of_dict()}))
return flask.Response(ufo.XSSI_PREFIX + users_json, headers=ufo.JS... | b216b41b35b4b25c23ea2cc987ff4fe2b6464775 | 27,062 |
import hashlib
def md5_str(content):
"""
计算字符串的MD5值
:param content:输入字符串
:return:
"""
m = hashlib.md5(content.encode('utf-8'))
return m.hexdigest() | affe4742c2b44a60ef6dafa52d7a330594a70ed9 | 27,063 |
import requests
def hurun_rank(indicator: str = "百富榜", year: str = "2020") -> pd.DataFrame:
"""
胡润排行榜
http://www.hurun.net/CN/HuList/Index?num=3YwKs889SRIm
:param indicator: choice of {"百富榜", "富豪榜", "至尚优品"}
:type indicator: str
:param year: 指定年份; {"百富榜": "2015至今", "富豪榜": "2015至今", "至尚优品": "201... | d8540f3b7482f8f56f0ec40ac2592ef0cfae4035 | 27,064 |
def yamartino_method(a, axis=None):
"""This function calclates the standard devation along the
chosen axis of the array. This function has been writen to
calculate the mean of complex numbers correctly by taking
the standard devation of the argument & the
angle (exp(1j*theta) ). This uses the Yamart... | 1a313ac97495a0822de1f071191be08ec5b65269 | 27,065 |
def calc_half_fs_axis(total_points, fs):
""" Геренирует ось до половины частоты дискр. с числом
точек равным заданному
"""
freq_axis = arange(total_points)*fs/2/total_points # Hz до половины fs
return freq_axis | 35ef0482e3062d0af6f0e03e03e58e1c3cd33406 | 27,066 |
def fetch_weather():
""" select flight records for display """
sql = "select station, latitude,longitude,visibility,coalesce(nullif(windspeed,''),cast(0.0 as varchar)) as windspeed, coalesce(nullif(precipitation,''),cast(0.00 as varchar)) as precipitation from (select station_id AS station, info ->> 'Latitude' ... | 8ab9f20255a64cfdaa5bfd6ed9aa675ed76f2f5d | 27,067 |
def update_params(old_param, new_param, errors="raise"):
""" Update 'old_param' with 'new_param'
"""
# Copy old param
updated_param = old_param.copy()
for k,v in new_param.items():
if k in old_param:
updated_param[k] = v
else:
if errors=="raise":
... | 95de4e8e1278b07d2bd8ccc61af4e2dc43f87ca2 | 27,068 |
from enum import Enum
def UppercaseEnum(*args):
"""
Provides an :class:`~stem.util.enum.Enum` instance where the values are
identical to the keys. Since the keys are uppercase by convention this means
the values are too. For instance...
::
>>> from stem.util import enum
>>> runlevels = enum.Upperc... | a765ff333cb274e3d15bc9d3e29f83f89d384842 | 27,069 |
from datetime import datetime
def rng_name():
"""Generate random string for a username."""
name = "b{dt.second}{dt.microsecond}"
return name.format(dt=datetime.datetime.utcnow()) | 81be1b40770b08ec6b9adce0c3c9970ff1f3d442 | 27,070 |
def collections(id=None):
"""
Return Collections
Parameters
----------
id : STR, optional
The default is None, which returns all know collections.
You can provide a ICOS URI or DOI to filter for a specifict collection
Returns
-------
query : STR
A query, which can... | 0cd1704d2ac43f34d6e83a3f9e9ead39db390c2e | 27,071 |
import os
def ajax_upload():
""" handle ajax file upload """
# dropzone sends one ajax request per file, so this invocation is for
# one file even if multiple files have been dropped on the web page.
page = request.page
print_debug(' ajax_upload ')
print_debug(' request.form.keys() ... | 543101acc0bf5e04ffc24fe3220f30b21c4d0979 | 27,072 |
def zmat_to_coords(zmat, keep_dummy=False, skip_undefined=False):
"""
Generate the cartesian coordinates from a zmat dict.
Considers the zmat atomic map so the returned coordinates is ordered correctly.
Most common isotopes assumed, if this is not the case, then isotopes should be reassigned to the xyz.... | 0859a549b611347b4e3d94e4f0965a8a550e198e | 27,073 |
def get_module_version(module_name: str) -> str:
"""Check module version. Raise exception when not found."""
version = None
if module_name == "onnxrt":
module_name = "onnx"
command = [
"python",
"-c",
f"import {module_name} as module; print(module.__version__)",
]
... | caadba47f46d96b0318cd90b0f85f8a2ca2275b0 | 27,074 |
def pd_images(foc_offsets=[0,0], xt_offsets = [0,0], yt_offsets = [0,0],
phase_zernikes=[0,0,0,0], amp_zernikes = [0], outer_diam=200, inner_diam=0, \
stage_pos=[0,-10,10], radians_per_um=None, NA=0.58, wavelength=0.633, sz=512, \
fresnel_focal_length=None, um_per_pix=6.0):
"""
Create a set of simu... | 71a7dd7206936541cc55d8909be7795261aeaefa | 27,075 |
def add_tickets(create_user, add_flights):
"""Fixture to add tickets"""
user = create_user(USER)
tickets = [{
"ticket_ref": "LOS29203SLC",
"paid": False,
"flight": add_flights[0],
"type": "ECO",
"seat_number": "E001",
"made_by": user,
}, {
"ticket... | 27f9ed9a5231c71e98a79632a97137b73831a0e0 | 27,076 |
def compute_depth_errors(gt, pred):
"""Computation of error metrics between predicted and ground truth depths
Args:
gt (N): ground truth depth
pred (N): predicted depth
"""
thresh = np.maximum((gt / pred), (pred / gt))
a1 = (thresh < 1.25).mean()
a2 = (thresh < 1.25 ** 2).mean()
... | a781d5a8c1e61b5562870d75124de64e05fe2789 | 27,077 |
def sanitize_bvals(bvals, target_bvals=[0, 1000, 2000, 3000]):
"""
Remove small variation in bvals and bring them to their closest target bvals
"""
for idx, bval in enumerate(bvals):
bvals[idx] = min(target_bvals, key=lambda x: abs(x - bval))
return bvals | a92b170748b5dbc64c4e62703a3c63103675b702 | 27,078 |
def fetch_engines():
"""
fetch_engines() : Fetches documents from Firestore collection as JSON
all_engines : Return all documents
"""
all_engines = []
for doc in engine_ref.stream():
engine = doc.to_dict()
engine["id"] = doc.id
all_engines.append(engine)
ret... | a79a623140209ed4e9e7cbea2d8944b3434f720a | 27,079 |
def isone(a: float) -> bool:
"""Work around with float precision issues"""
return np.isclose(a, 1.0, atol=1.0e-8, rtol=0.0) | ee44d5d7a9b00457e51501d8ce5680cd95726e3f | 27,080 |
import argparse
def get_arguments():
"""Get needed options for the cli parser interface"""
usage = """DSStoreParser CLI tool. v{}""".format(__VERSION__)
usage = usage + """\n\nSearch for .DS_Store files in the path provided and parse them."""
argument_parser = argparse.ArgumentParser(
formatte... | 8a306b13216149366564b6401c03ef869ca1cf66 | 27,081 |
def kerr(E=0, U=0, gs=None):
"""
Setup the Kerr nonlinear element
"""
model = scattering.Model(
omegas=[E]*1,
links=[],
U=[U])
if gs is None:
gs = (0.1, 0.1)
channels = []
channels.append(scattering.Channel(site=0, strength=gs[0]))
channels.append(scatte... | a94ecb4618405a2817267609008bc56ef97033b9 | 27,082 |
from typing import Dict
import requests
import logging
def get_estate_urls(last_estate_id: str) -> Dict:
"""Fetch urls of newly added estates
Args:
last_estate_id (str): estate_id of the most recent estate added (from last scrape)
Returns:
Dict: result dict in format {estate_id_1: {estat... | d93299002204edc9d26b3c77e2dff1f56f4b93d8 | 27,083 |
from datetime import datetime
def revert_transaction():
"""Revert a transaction."""
if not (current_user.is_admin or current_user.is_bartender):
flash("You don't have the rights to access this page.", 'danger')
return redirect(url_for('main.dashboard'))
transaction_id = request.args.get('... | 39f4fc0c6af9c58197c514d5d648e07da20558aa | 27,084 |
def is_number(s):
"""returns true if input can be converted to a float"""
try:
float(s)
return True
except ValueError:
return False | d9fc4411bbc5e5fd8d02b3c105a770e8859048e0 | 27,085 |
def bib_to_string(bibliography):
""" dict of dict -> str
Take a biblatex bibliography represented as a dictionary
and return a string representing it as a biblatex file.
"""
string = ''
for entry in bibliography:
string += '\n@{}{{{},\n'.format(
bibliography[entry]['type'],
... | c8fc4247210f74309929fdf9b210cd6f1e2ece3f | 27,086 |
import io
def make_plot(z, figsize=(20, 20), scale=255 * 257,
wavelength=800, terrain=None,
nir_min=0.2, offset=3.5):
"""
Make a 3-D plot of image intensity as z-axis and RGB image as an underlay on the z=0 plane.
:param z: NIR intensities
:param figsize: size of the figure... | 1a4dde23a11b320e6564b6657a871a33ecb65eea | 27,087 |
def check_prio_and_sorted(node):
"""Check that a treap object fulfills the priority requirement and that its sorted correctly."""
if node is None:
return None # The root is empty
else:
if (node.left_node is None) and (node.right_node is None): # No children to compare with
... | 64100fd4ba9af699ab362d16f5bbf216effa2da5 | 27,088 |
import os
def download100():
"""download cifar100 dataset"""
if not os.path.exists(IMG_DIR):
os.mkdir(IMG_DIR)
cifar = CIFAR100(root=IMG_DIR, download=True)
return cifar | 9d722ecad0758885489ce7f5ba01b99f14227ec4 | 27,089 |
import pickle
async def wait_for_msg(channel):
"""Wait for a message on the specified Redis channel"""
while await channel.wait_message():
pickled_msg = await channel.get()
return pickle.loads(pickled_msg) | dca398cb3adeb778458dd6be173a53cdd204bcb9 | 27,090 |
def abandoned_baby_bull(high, low, open_, close, periods = 10):
"""
Abandoned Baby Bull
Parameters
----------
high : `ndarray`
An array containing high prices.
low : `ndarray`
An array containing low prices.
open_ : `ndarray`
An array containing open prices.
clos... | 5fb0f2e3063e7b7aa03663d1e2d04d565ec8e885 | 27,091 |
def split_line_num(line):
"""Split each line into line number and remaining line text
Args:
line (str): Text of each line to split
Returns:
tuple consisting of:
line number (int): Line number split from the beginning of line
remaining text (str): Text for remainder ... | d232fd046ee60ac804fff032494c8c821456c294 | 27,092 |
def rad_to_arcmin(angle: float) -> float:
"""Convert radians to arcmins"""
return np.rad2deg(angle)*60 | c342286befd79a311edda18e8a7a2e978d8312ad | 27,093 |
def get_tile_prefix(rasterFileName):
"""
Returns 'rump' of raster file name, to be used as prefix for tile files.
rasterFileName is <date>_<time>_<sat. ID>_<product type>_<asset type>.tif(f)
where asset type can be any of ["AnalyticMS","AnalyticMS_SR","Visual","newVisual"]
The rump is defined as <da... | 15b517e5ba83b2cfb5f3b0014d800402c9683815 | 27,094 |
def get_indices_by_groups(dataset):
"""
Only use this to see F1-scores for how well we can recover the subgroups
"""
indices = []
for g in range(len(dataset.group_labels)):
indices.append(
np.where(dataset.targets_all['group_idx'] == g)[0]
)
return indices | 864aad8eef0339afd04cce34bee65f46c9fb030b | 27,095 |
def ranksumtest(x, y):
"""Calculates the rank sum statistics for the two input data sets
``x`` and ``y`` and returns z and p.
This method returns a slight difference compared to scipy.stats.ranksumtest
in the two-tailed p-value. Should be test drived...
Returns: z-value for first data set ``... | d01d0a56cf888983fa1b8358f2f6f0819ca824d9 | 27,096 |
from urls import routes
import jinja2
async def create_app():
""" Prepare application """
redis_pool = await aioredis.create_pool(settings.REDIS_CON)
middlewares = [session_middleware(RedisStorage(redis_pool)), request_user_middleware]
if settings.DEBUG:
middlewares.append(aiohttp_debugtoolbar... | 2dc90c99aa03383e418ae4c2637a5ef635dbec8e | 27,097 |
def inchi_to_can(inchi, engine="openbabel"):
"""Convert InChI to canonical SMILES.
Parameters
----------
inchi : str
InChI string.
engine : str (default: "openbabel")
Molecular conversion engine ("openbabel" or "rdkit").
Returns
-------
str
Canonical SMILES.
... | 040d091f1cdbc1556fd60b9ee001953e1a382356 | 27,098 |
from typing import List
from re import T
def swap(arr: List[T],
i: int,
j: int) -> List[T]:
"""Swap two array elements.
:param arr:
:param i:
:param j:
:return:
"""
arr[i], arr[j] = arr[j], arr[i]
return arr | e34c983b816f255a8f0fb438c14b6c81468b38c6 | 27,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.