content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import unittest
import os
def needs_cvxpy(fn):
"""Shortcut decorator for skipping tests that require CVXPY"""
return unittest.skipIf('SKIP_CVXPY' in os.environ, "skipping cvxpy tests")(fn) | 3e2bec230f7263c37ea100ed2401598adb780def | 685,096 |
async def hello():
"""
Returns "hello from service1"
"""
return 'hello from service1' | 95801d51a4a4cbdf2a5535f009be54b271f29091 | 685,097 |
def parsePoint(storedPt):
"""
Translates a string of the form "{1, 0}" into a float tuple (1.0, 0.0)
"""
return tuple(float(c) for c in storedPt.strip("{}").split(",")) | e9d7f88c866fe0f504119258488df90b9e56024f | 685,098 |
def center_path(x: float, diameter: float) -> float:
"""
Describes the y values of a a straight path across the center of a
detector given a position x and detector diameter d0.
"""
return 0.0 | 674e139eef6a2a98e1420d9abe5bdd4277933de9 | 685,099 |
def spatial_overlap_conv_3x3_stride_2(p):
"""
This method computes the spatial overlap of 3x3 convolutional layer with stride 2 in terms of its input feature map's
spatial overal value (p).
"""
return (1 + 2 * (1-p)) / (1 + 4 * (1 - p) * (2 - p)) | 5874bc24f0fefc771021268bcd83425c3298b822 | 685,100 |
def join(*args):
"""
Return a string composed of the result of applying str() to each one of
the given args, separated by spaced, but only if the item exists.
Example:
>>> join('Hello', False, 1, True, 0, 'world')
'Hello 1 True world'
"""
strings = [str(arg) for arg in args if a... | ec9236d51d68717b5de26fad9c5a74871e106270 | 685,101 |
from typing import List
from typing import Dict
def reduce_raw_dict(data: List[Dict[str, str]]) -> List[Dict[str, str]]:
"""
Initial data cleanup. Filter all logs that deal with accessing a
"BernsteinConference" page and that contain "Completed" to remove
"Started" duplicates. Further remove "/plugin... | 7595977c3d5edbd70059c916eb631daad031a866 | 685,102 |
def build(name, builder):
"""Wrapper to turn (name, vm) -> val method signatures into (vm) -> val."""
return lambda vm: builder(name, vm) | 61a87daca6702c84e3f790c6042f82059ceead17 | 685,103 |
def all_pairs(s1, s2):
"""
:param s1: = list/string
:param s2: = list/string
:return: = a list with all pairs of elements from list s1 and s2 respectively, with the second element varying more
rapidly than the first
"""
combo = []
i = 0
j = 0
while i < len(s1):
while ... | e7b55326a01292a534f7853dcc64357ec16e473e | 685,104 |
def PrepareCorrResults(df):
"""
Pass it a dataframe, and it returns Pairwise Pearson correlation coefficient values
for the entire variables of the datadframe.
The first columns of the returned dfCORR contains correlation values of the classvariable
versus all other variables.
"""
dfCORR ... | fb9a8969e95f614e2c7e5603abfbbe3a87bf2b9f | 685,105 |
import os
def get_input_txt_files(input_data_folder):
"""Create a list of files in a directory and put them into a list."""
list_data_files = []
os.chdir(input_data_folder)
directory_path = os.getcwd()
for filename in os.listdir(input_data_folder):
if filename.endswith(".txt... | 84589f058940f009f4c8d0d9cceefaab127ad00d | 685,106 |
def full_to_type_name(full_resource_name):
"""Creates a type/name format from full resource name."""
return '/'.join(full_resource_name.split('/')[-2:]) | 9bcb3985be683060e0b4028183c9da750f4c619c | 685,108 |
def is_shuffle(stage: str) -> bool:
"""Whether shuffle input.
Args:
stage: Train, val, test.
Returns:
Bool value.
"""
is_sh = {'train': True, 'val': False, 'test': False}
return is_sh[stage] | 7529c23cc1170cb36af57e9cc7473005cda78366 | 685,109 |
def wr0(self) -> int:
"""
Name: Write accumulator into RAM status character 0.
Function: The content of the accumulator is written into the
RAM status character 0 of the previously selected
RAM register.
The accumulator and the car... | 7de9a7d54d462ae3766b771a847aab15d7590fe3 | 685,110 |
def cluster_info(clustering_result):
"""return cluster number: clust_num and cluster name dictionary: cluster_dict in a tuple (clust_num,cluster_dict)
"""
cluster_set=list(set(clustering_result));
cluster_num=len(cluster_set);
cluster_dict=dict(zip(cluster_set,range(cluster_num)));
return (cluster_num,cluster_dic... | b74210c1fc28e391d9a54525ccd0dde244e5a9f5 | 685,112 |
def _get_item_by_name(cls, name):
"""
Gets the item from the corresponding class with the indicated name.
:param cls: Class / Entity of the item.
:param name: Case-insensitive name of the item.
:return: The item if there is a match, None otherwise.
"""
if name:
try:
retur... | 9e8f3b32f774ded572d1b49aee8f73de82f03e9c | 685,113 |
def datetimeindex_to_human(datetimeindex):
"""Convert pandas DatatimeIndex to an ISO string with the T and Z removed (yyyy-mm-dd hh:mm:ss).
Inputs:
DatetimeIndex [pd.DatetimeIndex]: A pandas DatetimeIndex to be converted.
Optional Inputs:
None.
Outputs:
times_human [np.array]:... | 2459bfe260d68bba0f98fb2dfe3549efbd6dcdda | 685,114 |
import six
def intersect(*masks):
"""Return new masks that are the per-layer intersection of the provided masks.
Args:
*masks: The set of masks to intersect.
Returns:
The intersection of the provided masks.
"""
result = {}
for mask in masks:
for layer, values in six.iteritems(mask):
if ... | db883859a72299a9dea2188dd27b7b62c3d229ec | 685,115 |
import os
import click
import json
def load_github_token() -> str:
"""Loads and returns the github access token."""
file = os.path.join(
click.get_app_dir("githubber", roaming=True), "config", "account.json"
)
try:
with open(file, "r") as jsonfile:
token = json.load(jsonfil... | a28849442749ea15585e5c65e7f61eef9d34d0bc | 685,116 |
def get_label_dummy_goal(vertex_input):
"""Get the index of the fictitious dummy goal (last vertex + 1)"""
if isinstance(vertex_input, int):
v_g = vertex_input + 1
return v_g
elif isinstance(vertex_input, list):
v_g = vertex_input[-1] + 1
return v_g
else:
print('... | 5a9a9cf8283580d50f7cf2f5a2d5e3ed1667da7f | 685,117 |
from typing import Any
def is_not(a: Any, b: Any, /) -> bool:
"""Check if the arguments are different objects."""
return id(a) != id(b) | 11927ceac6ef3e2885b2825223257cf6c40da8c3 | 685,118 |
import torch
def clip_gradient(model, clip_norm=10):
""" clip gradients of each parameter by norm """
for param in model.parameters():
torch.nn.utils.clip_grad_norm(param, clip_norm)
return model | d7b4ad07acb9625910782481cbaebb8a4d81954a | 685,119 |
def fetch_all_items(client, method, response_key, **kwargs):
"""
client: The boto3 client
method: The boto3 method to be fetched (e.g. ecs_client.list_clusters)
kwargs: The parameter name and value for a given boto3 method (e.g. ecs_client.list_services(cluster=clusterArn))
"""
if kwargs:
... | b4038fd6265fe11d82f489a1f9b6e967266377f3 | 685,120 |
def get_last_modified(repo):
"""Returns the paths to the last modified files in the provided Git repo
Arguments:
repo {git.Repo} -- The repository object
"""
changed_files = repo.git.diff('HEAD~1..HEAD', name_only=True).split()
changed_files.sort(key=lambda x: x.count('/') or 0)
return... | 7a0f6cbc842c7b03da36c3def7d87c5ff6dff8b3 | 685,121 |
import random
def split_partition(annotations):
"""Randomly split annotations into train (80%), dev (10%), and test (10%) sets"""
train_annotations = dict()
dev_annotations = dict()
test_annotations = dict()
doc_names = list(annotations.keys())
random.seed(100) #To ensure the shu... | 752078e8fd4121db702f0a79d8995f7c27446568 | 685,122 |
def standardize_folder(folder: str) -> str:
"""Returns for the given folder path is returned in a more standardized way.
I.e., folder paths with potential \\ are replaced with /. In addition, if
a path does not end with / will get an added /.
Argument
----------
* folder: str ~ The folder path... | cb71ca68e787d69e11a0d23ebfa4d6abe3efe4a7 | 685,123 |
import math
def conttogrowth(contrate):
"""
Convert continuous compounding rate to annual growth
"""
return math.exp(contrate) | b3b3c9a7a7ee7d16a19bb0b17294a4dab0012297 | 685,124 |
def Backtracking_linesearch(f, x, lambda_newton, Delta_x,options):
"""
The goal of this function is to perform a backtracking linesearch to adapt
the stepsize t of the Newton step, i.e. prepare a damped Newton step.
For this, do the following:
1. Imports and definitions
2. Loop till con... | be0761ed8ee59e635ce17db2b952aa2faa4e64ba | 685,126 |
import warnings
def _check_write_names(names):
"""
Ensure valid names
"""
outnames = []
for i, name in enumerate(names):
if not name.isidentifier():
oldname, name = name, f"m{i}"
warnings.warn(
f"Matrix for output4 write has name: {oldname!r}. "
... | 7a5246516e9c41fbda74b3207e35735483e03cdc | 685,127 |
def cal_rmse(actual_readings, predicted_readings):
"""Calculating the root mean square error"""
square_error_total = 0.0
total_readings = len(actual_readings)
for i in range(0, total_readings):
error = predicted_readings[i] - actual_readings[i]
square_error_total += pow(error, 2)
rms... | 86e124284907c0044d829c5870f5540fbed41a90 | 685,128 |
def GetArcsOut(source):
"""All outgoing arc types for this specified node."""
arcs = {}
for triple in source.arcsOut:
arcs[triple.arc] = 1
return arcs.keys() | ac05b4051ce69d90d716cd04b85210bee1f97138 | 685,131 |
def ajoute_virgule(valeur1):
"""Ajoute une virgule, s'il n'y en a pas déjà."""
if valeur1.find(".") == -1:
return valeur1 + "."
else:
return valeur1 | f4533c8d59c535c8c4a1fa9f69b3891f0412725e | 685,133 |
import socket
def _port_not_in_use():
"""Use the port 0 trick to find a port not in use."""
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
port = 0
s.bind(('', port))
_, port = s.getsockname()
return port | 8223a4c89d4623a7a80917e7ef8892e188e6f42c | 685,134 |
def get_video_url(array):
"""
get video url from list
:param array:
:return:
"""
if isinstance(array, list) and len(array) >= 1:
return array[-1]
return None | 3e3829b22d9199862a9e5fe1b9c02f2b4c42fdf0 | 685,135 |
import json
import requests
def update_protection(token, repo_owner, repo_name, branches, teams):
"""
:param token: str
:param repo_owner: str
:param repo_name: str
:param branches: array of strings
:param teams: array of strings
:return: True
"""
settings = json.dumps({
"... | 3b7b396546abcef94f3073d3840eba6ec8680a0e | 685,136 |
def make_profile_mask(ref_2d_profile, threshold=1e-3):
"""Build a mask of the trace based on the 2D profile reference file.
:param ref_2d_profile: the 2d trace profile reference.
:param threshold: threshold value for excluding pixels based on
ref_2d_profile.
:type ref_2d_profile: array[flo... | 61d8dc14a2f5bf8c7fdeccc101aacca18b90e09e | 685,137 |
import random
def initialize_hetero_vector(class_, limits):
"""Initializes a heterogeneous vector of type `class_` based on the values
in `limits`.
:param class_: the class into which the final list will be
typecasted into.
:param limits: a list that determines whether an element o... | 5cbdb42852b68b6b22c5fd12493c526d68372c65 | 685,138 |
import os
def database_get_config_path(project_path):
"""
Get configuration path from project path.
:param project_path: Project path
:rtype: Configuration path
"""
return os.path.join(project_path, ".docknv") | f11e964cfac5769fdee4a0c0786d8a8313a298ae | 685,140 |
def kpt_flip(kpts, img_shape, flip_pairs, direction):
"""Flip keypoints horizontally or vertically.
Args:
kpts (Tensor): Shape (..., 2)
img_shape (tuple): Image shape.
flip_pairs (list): Flip pair index.
direction (str): Flip direction, only "horizontal" is supported now.
... | 33159bb7d2fda04bfb29d7a7deef335fef2bd0e2 | 685,142 |
def default_exclude(left, right, options):
"""A custom function should return True to exclude
the record pair and short circuit further comparison.
"""
return False | 535df3b9137c4b71c28eb96047fc0f3a270b9af5 | 685,143 |
import struct
def _StToNum(S):
"""
Convert S to a number.
:param S: The (big-endian) bytestring to convert to an integer
:type S: bytes
:return: An integer representation of the bytestring (rightmost chr == LSB)
:rtype: int
"""
return struct.unpack('>L', S)[0] | 34fa90e7ef9cef9c46d9a423f85e517f5436fb58 | 685,144 |
def cleanp(stx):
"""
Simple string cleaner
"""
return stx.replace("(", "").replace(")", "").replace(",", "") | 2b5407d9c03371d031410df74136c3783ee3babe | 685,145 |
def mergeRegions(regions):
"""
Given a list of [(chrom, start, end), ...], merge all overlapping regions
This returns a dict, where values are sorted lists of [start, end].
"""
bar = sorted(regions)
out = dict()
last = [None, None, None]
for reg in bar:
if reg[0] == last[0] and ... | 2515881e7f4755e763a9befc8d9c8e1222ce18c5 | 685,146 |
def parse_notifier_name(name):
"""Convert the name argument to a list of names.
Examples
--------
>>> parse_notifier_name('a')
['a']
>>> parse_notifier_name(['a','b'])
['a', 'b']
>>> parse_notifier_name(None)
['anytrait']
"""
if isinstance(name, str):
return [name]
... | 487e2a35fdf3777d2719bfdb09664e85668ab673 | 685,147 |
import re
def email_to_rname(email):
""" Normalize email value into SOA's RNAME style.
This method will convert "@" to "." and "." in user-parts to "\\.".
"""
match = re.match(r'^(?P<user>[0-9A-Za-z.-]+)@(?P<domain>[0-9A-Za-z.-]+?)\.?$', email)
if match:
email_user = match.group('user').re... | 85d7a0db0f258e187f9a945a49f192f1ec834ef4 | 685,148 |
import re
def get_size(size):
"""
Get the size from WWWxHHH format
It also check if the format is correct
"""
if re.match(r"^\d+x\d+$", size) is not None:
sizes = [int(value) for value in re.findall(r"\d+", size)]
return sizes
else:
print("Size should be in WWWxHHH form... | eb3ac369062e4de83128db2fe7cbed0bf7213ab6 | 685,149 |
def crop_size(img, height_to_width):
"""Crop the image to have the appropriate ratio for a flexagon."""
width, height = img.size
# could use fit, with the assumption that the height will be sufficient
# return ImageOps.fit(img, (width, int(width * sqrt3_2)))
# better make a case distinction
if... | d06aa97a07f041677ebcdf46c15d1f7917786d66 | 685,150 |
def sqrt_expansion(ceil):
"""
Returns the number of fractions (of the expansion of sqrt(2)) where the
numerator has more digits than the denominator in the first ceil
iterations.
"""
counter = 0
frac = [1, 1]
for _ in range(ceil):
frac = [frac[0] + 2 * frac[1], frac[0] + frac[1]]... | 74895c988fedce8de3160e3d4219f27668ff9ac7 | 685,151 |
import uuid
def create_csrf_token():
"""Create and return a canonical CSRF token; a un-segmented UUID4."""
return uuid.uuid4().hex | 7a2f991c459a07f7ca3e681679688c25ab83f811 | 685,152 |
def _prune_arg(l, key, extra=0):
"""Removes list entry "key" and "extra" additional entries, if present.
Args:
l (list): The list to prune.
key (object): The list entry to identify and remove.
extra (int): Additional entries after key to prune, if found.
"""
try:
idx = l.index(key)
args = l... | 2a8f6826e12607e4f5192b8b3129fbb4512ad684 | 685,153 |
from typing import Set
def get_genes_in_overlap(genes, overlap_list) -> Set[str]:
"""Select members from a gene list which are also in a given overlap(second list of genes)
Parameters
----------
genes : list
ordered list of genes from which to select from
overlap_list ... | f3d34d39798d1f538f4b3e19ddee0eaf011b5603 | 685,154 |
def get_transfer_dict_cmd(server_from_str, server_to_str, folders_str):
"""
Convert command line options to transfer dictionary
Args:
server_from_str (str): counter to iterate over environment variables
server_to_str (str): Environment variables from os.environ
folders_str (str)
... | 7602a7b85d4dda0db0aac676b0ee583a4b9fb6d3 | 685,155 |
def mult_mat_vec(a, b):
"""Multiply matrix times vector for any indexable types."""
return [sum(ae*be for ae, be in zip(a_row, b)) for a_row in a] | b6c82095171acf82488d95b54884421a346b8429 | 685,156 |
def _get_y_coord(tile):
"""
Return y coordinate of square
"""
return tile[1] | d5d6af47095c076f826ca982d59506e5d96c0eb7 | 685,157 |
def list2dict(
l=['A', 'B', 'C'],
keylist=['a', 'b', 'c']
):
"""
task 0.5.31 && task 0.6.3
implement one line procedure taking a list of letters and a keylist
output should be a dict. that maps them together
e.g. input l=['A', 'B', 'C'] keylist=['a', 'b', 'c'] output={'a':'A', '... | 002fdf595629f79928d36615de7ea7bc32231148 | 685,158 |
import ast
def get_genre(dataframe):
"""
This function is to get information about genres
Input: dataframe
Output: list of genres
"""
genres = []
for row_number in range(len(dataframe)):
genre = []
for id_name in ast.literal_eval(dataframe.genres.to_list()[row_number]):
... | 373e8a34c553ea330dfa5982e28dca1bd679d4d5 | 685,159 |
def get_ptype(proxy):
"""
:param proxy: https://124.0.0.1
:return: https
"""
return proxy.split(':')[0] | d726856ecf11bcedcfe2123a51b19a8e9bf1feff | 685,160 |
def find_selfloop_nodes(G):
"""
Finds all nodes that have self-loops in the graph G.
"""
nodes_in_selfloops = []
# Iterate over all the edges of G
for u, v in G.edges():
# Check if node u and node v are the same
if u == v:
# Append node u to nodes_i... | 7c181e38067f0334649874b4bcc0a7e75c501a0b | 685,161 |
def rerun_probability(n_runs):
"""
Calculates a probability for running another episode with the same
genome.
"""
if n_runs <= 0:
return 1
return 1 / n_runs**2 | 163e6431b0a8b80893bd3771b32fc217c0598969 | 685,162 |
def get_fasta_stats(fasta_file):
"""file_path => dict
Return lenght and base counts of each seuqence found in the fasta file.
"""
d = {}
_id = False
seq = ""
with open(fasta_file, "r") as f:
for line in f:
if line.startswith("\n"):
continue
if ... | bce628aa35a3e86ff5615bef55e1af8168008398 | 685,163 |
import random
import decimal
def randdecimal(precision, scale):
"""Generate a random decimal value with specified precision and scale.
Parameters
----------
precision : int
The maximum number of digits to generate. Must be an integer between 1
and 38 inclusive.
scale : int
... | 40f1747d735e6de7f9c42dc999d888783abb64e4 | 685,164 |
def get_constant_pi(df):
"""
Parameters
----------
df Input DataFrame
Returns The name of columns that are constant (always same value)
-------
"""
constants = []
for col in df.columns:
items = list(df[col])
prev = items[0]
is_constant = True
for ite... | 7a847e4d0b6f4155b5eca41541e58578f39244b4 | 685,165 |
def max_transmit_rule(mod, l, tmp):
"""
**Constraint Name**: TxSimple_Max_Transmit_Constraint
**Enforced Over**: TX_SIMPLE_OPR_TMPS
Transmitted power cannot exceed the maximum transmission flow capacity in
each operational timepoint.
"""
return (
mod.TxSimple_Transmit_Power_MW[l, tm... | c586b466e13e695484381a59b11fb3e286e6e914 | 685,166 |
def sum(intA, intB):
"""Add two integers, both with value between 0-100
:param intA: First integer to add
:type intA: int
:param intB: Second integer to add
:type intB: int
:return: The sum of the parameters
:rtype: int
"""
return intA + intB | de50a2098e7c83e7ec2de9dec726cb55525e6680 | 685,167 |
def mix(col1, col2, p=0.5):
"""Mix two colors according to percentage p where
- p=0 returns col1
- p=1 returns col2
- p=0.5 returns an equal mix of col1 and col2
- p=0.25 returns a color containing 75% of col1 and 25% of col2
etc.
Args:
col1: First colour to be mixed.
col2: ... | 343a12ef258ed9d37fab773baf569d593d190a82 | 685,168 |
def get_lam_list(self, is_int_to_ext=True):
"""Returns the ordered list of lamination of the machine
Parameters
----------
self : MachineSRM
MachineSRM object
is_int_to_ext : bool
true to order the list from the inner lamination to the extrenal one
Returns
-------
lam_l... | cd798c936a7fe6f11e3f5b0ebcb621339adf7d3e | 685,169 |
def create_tree(input_list):
"""Create a tree given an input list."""
tree_order = []
next_lists = [input_list]
while next_lists:
current_list = next_lists.pop(0)
middle_index = len(current_list) // 2
if middle_index < len(current_list):
tree_order.append(current_list... | a1e4a1d544db7dbcc147dd014a3c3fc40609fc8f | 685,171 |
def column(matrix, i):
"""
Gets column of matrix.
INPUTS:
Matrix, Int of column to look at
RETURNS:
Array of the column
"""
return [row[i] for row in matrix] | ab7fba90b5f87486a7f52ba3f8aad5c0047ecad9 | 685,172 |
import os
def get_all_scripts_from_disk(test_dir, non_scripts):
"""
Return all available test script from script directory (excluding NON_SCRIPTS)
"""
python_files = set([t for t in os.listdir(test_dir) if t[-3:] == ".py"])
return list(python_files - set(non_scripts)) | 8d90483ff5980ba6361e7d0a0b3e6c6e7d3526dd | 685,173 |
import os
def define_subset():
"""
Use the study structure to identify the names of each field
# https://clinicaltrials.gov/api/info/study_structure
"""
subset = []
subset.append('study_type')
fileName = os.path.join( 'data', 'ref', 'studyFields.txt')
with open(fileName, 'r') as f:
... | 4dbbd0fd6fa461dc6513988f20b934bd9b7e1e11 | 685,174 |
import torch
def get_dict_info_batch(input_id, features_dict):
"""
batched dict info
"""
# input_id = [1, batch size]
features = []
for rid in input_id.squeeze(1):
features.append(features_dict[rid.cpu().tolist()])
features = torch.tensor(features).float()
# features = [1, bat... | 7af5b43ef5a5af864bc17a3372433afbe8eb908b | 685,175 |
def _ensure_extension(filename: str, extension: str):
"""Add the extension if needed."""
if filename.endswith(extension):
return filename
return filename + extension | 11846b555c6663b9a0916f6a6981baf365fcdf9a | 685,176 |
import socket
def have_connectivity(host="8.8.8.8", port=53, timeout=3):
""" Attempt to make a DNS connection to see if we're on the Internet.
From https://stackoverflow.com/questions/3764291/checking-network-connection
@param host: the host IP to connect to (default 8.8.8.8, google-public-dns-a.google.co... | 4234cae9d361e1a42de3fa17ab6becfdf2ab20d3 | 685,177 |
def str2list(data):
"""
Create a list of values from a whitespace and newline delimited text (keys are ignored).
For example, this:
ip 1.2.3.4
ip 1.2.3.5
ip 1.2.3.6
becomes:
['1.2.3.4', '1.2.3.5', '1.2.3.6']
"""
list_data = []
for line in data.split('\n'):
line = l... | 496a704a081ba8a0fc1d94a2959470bc4697ca48 | 685,178 |
from datetime import datetime
def read_mne_raw_edf_header(edf_obj, **kwargs):
"""
Header extraction function for RawEDF and Raw objects.
Reads the number of channels, channel names and sample rate properties
If existing, reads the date information as well.
Returns:
Header information as d... | 1e9c13757e5c4221e137a38e57ab18833c0d1eb0 | 685,179 |
from typing import Dict
import binascii
import json
def format_data_for_comment(data: Dict) -> str:
"""
Format a data dictionary for appending to a comment.
"""
b64 = binascii.b2a_base64(json.dumps(data).encode("utf8")).strip().decode("ascii")
return f"\n<!-- data: {b64} -->\n" | 8dfadcaaddeee884ca89f9b294edc1d2281b3962 | 685,180 |
def generateRedirectURL(host, params):
"""
Computes the redirect url in the specified format.
:return: (string)
"""
return "{}?{}".format(host, params) | 3a8f5649492222339d0e10d87094743cd2e5eba5 | 685,181 |
import os
def get_allpaths(dir_name, extension):
"""
Loads all the files in the dir_name with the provided extension
Args:
dir_name: The name of the directory
extension: The extension to be loaded
Returns: list of all files with the extension in the directory
"""
return_list =... | a70522037d6829908955581f8fdf4be1b6d31be1 | 685,182 |
def formatter(msg, values):
"""Functional form of format on strings"""
return msg.format(**values) | fc7cb8329528df07536b5a1e3d24bbbf0cd19225 | 685,183 |
def get_dz(zmax, zmin, Nz):
"""Longitudinal resolution (meters)."""
return (zmax - zmin) / Nz | 0d9cc4e0a880af366ad496c8c33fc7c9e82c177d | 685,184 |
from typing import Optional
def optional_type(name: Optional[str] = None) -> str:
"""`Optional` type to also accept a `None`."""
# Optional[str] means the same thing as Union[str, None]
if name is None:
name = "stranger"
return "Hello, " + name | 404f11e5b683c602e0ef9b76711aeb377f3f13a0 | 685,185 |
def thaw(snowflake):
"""
Tiny function to return the unix timestamp of a snowflake
:param snowflake: a discord snowflake (It's unique, just like you! ha.)
:type snowflake: int
:return: unix timestamp of the message
:rtype: int
"""
return ((snowflake >> 22)+1420070400000)/1000 | 2bdce93f717685c354543731867d106f49d85c82 | 685,186 |
import torch
def displacement_error(pred_traj, pred_traj_gt, consider_ped=None, mode="sum"):
"""
Input:
- pred_traj: Tensor of shape (seq_len, batch, 2). Predicted trajectory. [12, person_num, 2]
- pred_traj_gt: Tensor of shape (seq_len, batch, 2). Ground truth
predictions.
- consider_ped: Ten... | b6b50d9c7b25fc908785a7b86389416b52b153bb | 685,187 |
from typing import Union
import base64
def read_file_as_b64(path: Union[str, bytes, int]) -> str:
"""Reads a file's contents as binary bytes and encodes it in a base64-string.
Args:
path (Union[str, bytes, int]): binary file path
Returns:
str: file's bytes in base64-encoded string
""... | c14e24628d1ca9b0742fb2776922467dc6183feb | 685,188 |
def isstr(s):
"""True if 's' is an instance of basestring in py2, or of str in py3"""
bs = getattr(__builtins__, 'basestring', str)
return isinstance(s, bs) | 336570eb1b5e4be92788ec4cb6f1c7f7d02b47a5 | 685,189 |
import os
def low_mesh_options(filename, **kwargs):
""" Generates an options dictionary for a low mesh """
kwargs["path"] = os.path.abspath(filename)
"""
List of possible low mesh options in the form:
(keyword_argument, xml_name, default_value)
"""
low_opts = [
("vis... | e5efb7847681e5d20963f44ecd1fdf7223e17cb6 | 685,190 |
from typing import OrderedDict
def iterable_to_ordered_dict(iterable):
"""
Change from an iterable data structure (list, tuple, string) to an
ordered dictionary data structure.
"""
ordered_dict = OrderedDict()
for letter in iterable:
if letter in ordered_dict and ordered_dict[letter] =... | e1a26c8e18ed67b6fd3134f1309841e163ca38a5 | 685,191 |
import re
def is_dpkg_locked(exit_code, output):
"""
If dpkg is locked, the output will contain a message similar to 'dpkg
status database is locked by another process'
"""
if exit_code is not 0:
dpkg_locked_search = r'^.*dpkg.+lock.*$'
dpkg_locked_re = re.compile(dpkg_locked_searc... | 5b240a0a83d21f50a3db25385f15988096ae30bd | 685,192 |
from typing import List
import copy
def insertion_sort(x: List) -> List:
"""Insertion sort compares elements and moves them to their correct position by repeatedly comparing an element
with previous elements in the list until its correct position is located, then moving the element to its correct
position... | e821aea2a8718ca446c7ad5db0391a5c2dc96b2a | 685,193 |
from typing import Union
import logging
def get_level(level:Union[str,int]) -> str:
"""Return the logging level as a string"""
if isinstance(level, str):
return level.upper()
return logging.getLevelName(level) | c545f15a3d06a6d558ecae5c98f5f965fdb4d8e0 | 685,194 |
def set_cur_model(client, model, drawing=None):
"""Set the active model on a drawing.
Args:
client (obj):
creopyson Client
model (str):
Model name.
drawing (str, optional):
Drawing name. Defaults: current active drawing.
Returns:
None
... | 5cfade6f22bbc076c97f49b24436b8bfa9b5c0f6 | 685,195 |
def limit(vmin, vmax, npeaks):
"""
Fixed limits, vmin to vmax for all peaks.
"""
return [(vmin, vmax)] * npeaks | 118d9fb2fbf4efc2b3bde4eee7e36f4b4338f54c | 685,196 |
def G(poisson, young):
"""
Shear Modulus in MPa.
"""
result = young/(2*(1+poisson))
return result | 9eb216d08c2c8baa3d9d15fff0ba3322fd344e06 | 685,197 |
from typing import Union
def operacion_basica(a: float, b: float, multiplicar: bool) -> Union[float, str]:
"""Toma dos números (a, b) y un booleano (multiplicar):
- Si multiplicar es True: devuelve la multiplicación entre a y b.
- Si multiplicar es False: devuelve la division entre a y b.
... | 24bce4394d3daf0b1817ff533bf11884f635f74c | 685,198 |
import math
def is_pentagonal(p: int) -> int:
"""
P = n * (3n - 1) / 2
If P is pentagonal, the above equation will have a positive integer solution
for n. We use the quadratic formula to check if either solution for n is a
positive integer
"""
root = math.sqrt(24 * p + 1)
return root.... | 0561f7453eeda33c780917c708eaa8fa88ac0df4 | 685,199 |
def canForm(p):
"""
Canonical form of a partition set.
"""
p[:]=[x for x in p if x!=0]
p.sort()
p.reverse()
return p | 48eb79f62368e2e7cb8e055140d0fc8939310174 | 685,200 |
def hello_world():
"""
Greetings users with 'Hello, World!'
---
tags:
- greeting
responses:
200:
schema:
type: string
"""
return 'Hello, World!' | d8778e390fe903b1c0c98872c56dadb15e097536 | 685,201 |
import locale
def getSystemLang():
"""
Get the default language in the current system
"""
sys_language = locale.getdefaultlocale()[0]
if not sys_language:
sys_language = 'en'
else:
sys_language = sys_language.lower()
return sys_language[:2] | 5f3f21b43408b3230a24d5e3829316684a32a5ad | 685,202 |
def int2uint32(value):
"""
Convert a signed 32 bits integer into an unsigned 32 bits integer.
>>> print(int2uint32(1))
1
>>> print(int2uint32(2**32 + 1)) # ignore bits larger than 32 bits
1
>>> print(int2uint32(-1))
4294967295
"""
return value & 0xffffffff | fe13d66f069796caf668f35b300e52a5eda40723 | 685,203 |
def to_camel_case(snake_case_string):
"""
Convert a string from snake case to camel case.
:param snake_case_string: Snake-cased string to convert to camel case.
:returns: Camel-cased version of snake_case_string.
"""
parts = snake_case_string.lstrip('_').split('_')
return parts[0] + ''.join... | 3dfc887461febb756a69eaefe3bbf245972e7ce4 | 685,204 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.