content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def get_supply_growth(ohm_stakers, ohm_bonders, ohm_dao, ohm_pexercise):
"""
OHM supply does not have a hard cap. Its supply increases when:
- OHM is minted and distributed to the stakers.
- OHM is minted for the bonder. This happens whenever someone purchases a
bond.
- OHM is minted for t... | 9b4cfd45ab69093093ef18cee6353179167772dd | 585,158 |
def difflist(list1: list, list2: list) -> list:
"""Showing difference between two lists
Args:
list1 (list): First list to check difference
list2 (list): Second list to check difference
Returns:
list: Difference between list1 and list2
"""
return list(set(list1).symmetric_di... | 9f247e3324c8b76e184928ef97248ab0f35232d3 | 585,159 |
def clear_state(dict_in):
"""Clear the state information for a given dictionary.
Parameters
----------
dict_in : obj
Input dictionary to be cleared.
"""
if not isinstance(dict_in,dict):
return dict_in
for k,v in dict_in.items():
if isinstance(v,dict):
d... | 9917e758375095486698cab4386cc24c42b6f2b1 | 585,160 |
def is_identifier_match(identifier: str, project: dict) -> bool:
"""
Determines whether or not the specified identifier matches
any of the criteria of the given project context data values
and returns the result as a boolean.
"""
matches = (
'{:.0f}'.format(project.get('index', -1) + 1),... | e6df341270fac1832ac1bc7703777bd8670e9a72 | 585,161 |
import click
def confirm(string):
"""
Outputs a confirmation-flavored string.
"""
return click.confirm(click.style(string, fg='magenta'), abort=True) | 462bef7b97df0b4374beb453bcef9656f27ddc2f | 585,162 |
def extractor(data, cell_type, conditions, cell_type_key="cell_type", condition_key="condition"):
"""
Returns a list of `data` files while filtering for a specific `cell_type`.
Parameters
----------
data: `~anndata.AnnData`
Annotated data matrix
cell_type: basestring
specific ce... | caf177811524b4585aebde12c9c764623af0b2ed | 585,165 |
def read_targets(tarfile):
"""
Return a tuple of targets
Arguments:
- `tarfile`: A tab-del file with EcoCyc names of sRNA and target
"""
if not tarfile:
return None
tars = []
try:
for line in open(tarfile):
tars.append(tuple(line.strip().split()[:2]))
exce... | 541794c34c713e20626ec5691af0a256ceaf4f39 | 585,166 |
def escape_like(value):
"""Escapes a string to be used as a plain string in LIKE"""
escape_char = '\\'
return (value
.replace(escape_char, escape_char * 2) # literal escape char needs to be escaped
.replace('%', escape_char + '%') # we don't want % wildcards inside the value
... | 8a63963f2539e658d4419504e33740c0039384d3 | 585,167 |
def _resource_type_lookup(assigned, root):
"""
Returns ``ResourceType`` object
:param str assigned: The string name of the assigned resource type
:param root: RAML root object
"""
res_types = root.resource_types
if res_types:
res_type_obj = [r for r in res_types if r.name == assigne... | ea73811ad4e958d925113f9a25c5c72dc30c1a03 | 585,168 |
def ParseVariableDefinitions(var_defs):
"""Parses variable definitions.
Args:
var_defs: A list of strings which define variables in the form of
"[prefix_]var_name[=value]".
Returns:
A list in the form of [(prefix, var_name, value), ...].
"""
prefixes = ('enable_', 'disable_', 'squoted_', 'dq... | 3644d6c8c434779c4da55d8b0b42c402b6261206 | 585,171 |
def create_codes_and_names_of_A_matrix(db):
"""
Create a dictionary a tuple (activity name, reference product,
unit, location) as key, and its code as value.
:return: a dictionary to map indices to activities
:rtype: dict
"""
return {
(i["name"], i["reference product"], i["unit"], i[... | 1f803ef2a9a8b1978defb12b8a9224547acbaf05 | 585,173 |
from typing import List
def max_triangle_path(triangle: List[List[int]]) -> int:
"""Alters triangle and returns the maximum path sum from top to bottom.
A path is valid iff it consists of a number from each row of the triangle
such that each number is adjacent to those in the rows above and below it.
... | e7e0e67331e3afd349937b6c703de883a6f66819 | 585,175 |
def upsert_resource(apiroot, settings):
"""
Convenience function to create or update a resource
Args:
apiroot (obj): API endpoint root eg `api.cnxn.pipes`
settings (dict): resource settings
Returns:
response (obj): server response
data (dict): json returned by server
... | 949326354ab41b2cc291dc7536d27755926856b2 | 585,179 |
def to_value(card):
"""
Returns the value of the card.
Args:
card(str): A two character string with value then suit.
Returns:
str: The first character of the string.
"""
return card[0] | 5bd2c49f3ad425dbacc83f207f46925637c2590a | 585,180 |
import torch
def scale_and_translation_transform_batch_torch(P, T):
"""
First Normalises batch of input 3D meshes P such that each mesh has mean (0, 0, 0) and
RMS distance from mean = 1.
Then transforms P such that it has the same mean and RMSD as T.
:param P: (batch_size, N, 3) batch of N 3D mesh... | cd3b1da9111233376d1056217ae2c14ffdd8ea38 | 585,182 |
def hotKey(s):
"""
Return the hotkey from a '~T~ilde' formatted string
:param s: String
:return: The escaped character or None
"""
head, _, tail = s.partition('~')
if tail:
return tail[0].upper()
return None | 2afb7d132c325e76c08e5c3052a02c08eced64f5 | 585,185 |
def extract_request(mock_method):
"""Pull out the request object from the last call to the mocked method
req = extract_request(session.search_items)
"""
args, kwargs = mock_method.call_args
*_, request = args
return request | d71ca14b6ee1f3ee25d51f7ed548f4acf96f23b6 | 585,196 |
def deg_to_qt(deg):
"""
Converts from degrees to QT degrees.
16 deg = 1 QTdeg
Parameters
----------
deg : float
The value to convert.
Returns
-------
float
The value converted.
"""
# Angles for Qt are in units of 1/16 of a degree
return deg * 16 | 96eecbc9d9f45fc9ae2192c7f05ae8b1d4b93694 | 585,204 |
def get_nchans(chanrange):
"""Determine the number of channels from a channel range
Parameters:
chanrange (str): Channel range
"""
i, f = map(int, chanrange.split('~'))
return abs(f-i) + 1 | 8e44541480c2b516c12d53ecf104ad7aafb595f8 | 585,208 |
import time
def to_hhmmss(x: int) -> str:
"""Convert time from secs (int) to hh:mm:ss (str).
"""
if not x >= 0: raise Exception(f'seconds cannot be negative, got {x}')
return time.strftime("%H:%M:%S", time.gmtime(x)) | 34baa20a15f14051318ddcbc19cd323b1fd7f29a | 585,209 |
def get_parent_id(node):
"""Return the node's parent id or 0 if node is a root node."""
if node.is_root():
return 0
return node.get_parent().pk | 0c77863f48dcd8a8c833474e062903b4e1031971 | 585,211 |
from typing import List
from typing import Collection
def all_same_size(collections: List[Collection]) -> bool:
"""Return True if all collections have the same size/length and False otherwise.
Args:
collections: A list of collections.
Returns:
Indication if all collections are the same s... | c5f7d2baa163bf24d06c40112d822b54a370fc12 | 585,217 |
def _splitRecordAndRemoveComments(line, delimiter=None):
"""
Method to split a record (relap5 input line) removing the comments if present
@ In, line, str, the line to be splitted
@ In, delimiter, str, optional, the delimiter to split by (default None -> white spaces)
@ Out, splitted, list, the list c... | 54e28405fec2301351ba1c8a8bcf367026c4b6bc | 585,218 |
def user_email_in_whitelist(email, domains):
"""
Check to see if a user's email address is within one of
the whitelisted domains. Only returns True if an explicit
match has been found. This matching is case-insensitive.
NOTE: This routine is a critical security function.
"""
allowed = False... | 7e5984e16dc75880ea2f13150589bc5b624aba5d | 585,222 |
import csv
def readcsv(filename, delimiter=',', quotechar='"'):
"""Read CSV file data into a list.
Args:
filename (str): Full path of file.
delimiter (str, optional): Delimiter
quotechar (str, optional): Quote character
Returns:
list: List of lines from CSV file
"""
... | e80b09d27339561b4d3bdb12979ece8fd2bd83dc | 585,223 |
def _GetSliceWindow(array, start, duration, sampling_freq):
"""Extracts a slice from an array.
Args:
array: numpy array of shape (n_channels, n_samples).
start: start seconds to perform the slice.
duration: duration in seconds of the slice.
sampling_freq: sampling frequency of the array (Hz).
Re... | e80c63a0547e95a7093aa29b29f66387f6c15c40 | 585,230 |
def get_picard_max_records_string(max_records: str) -> str:
"""Get the max records string for Picard.
Create the 'MAX_RECORDS_IN_RAM' parameter using `max_records`. If
`max_records` is empty, an empty string is returned.
"""
if max_records is None or max_records == "":
return ""
else:
... | f337511815b9f2d4381f868e1937393374932a3a | 585,231 |
def valid_filename(filename:str) -> bool:
"""
Fungsi yang melakukan validasi filename, di mana filename harus berekstensi .ps atau .eps dan filename tidak boleh mengandung illegal characters.
"""
ILLEGAL_CHARACTERS = '<>:"/\\|?*'
# Menyimpan filename dalam bentuk upper sementara (hanya untuk pengece... | bdfd4e75fb87728c255a21068bf9fe7ca387a524 | 585,232 |
def prediction(reg, pred_df):
"""Generate and return a prediction for the observations in the pred_df.
Args:
reg: LinearRegression class from four_factors_regression.py
pred_df: A dataframe of observations, with home and away statistics, from which to generate a prediction
Returns:
... | 76133f49e09d9e1ddaf404101677ff87fdac4f88 | 585,239 |
def count_above(obj, n):
"""
Return tally of numbers in obj, and sublists of obj, that are over n, if
obj is a list. Otherwise, if obj is a number over n, return 1. Otherwise
return 0.
>>> count_above(17, 19)
0
>>> count_above(19, 17)
1
>>> count_above([17, 18, 19, 20], 18)
2
... | d4eb048aec73fda31ebd694ec219c73dbb247f48 | 585,248 |
def Summation(xs, mu, cache={}):
"""Computes the sum of (x-mu)**2 for x in t.
Caches previous results.
xs: tuple of values
mu: hypothetical mean
cache: cache of previous results
"""
try:
return cache[xs, mu]
except KeyError:
ds = [(x-mu)**2 for x in xs]
total = ... | 5d6b7af207dc34a57236ddfa313e4409e15ec473 | 585,252 |
import random
import string
def random_string_lower_numeric(size):
"""
Generate a random string consisting of lowercase letters and numbers of the
specified size.
:param int size: The size of the string to make.
:return: The string containing the random characters.
:rtype: str
"""
return ''.join(random.choic... | 744fb3dc93657db842ab8d56a9b77e8753d9212e | 585,255 |
def step_dfa(D, q, c):
"""In : D (consistent DFA)
q (state in D)
c (symbol in D's sigma)
Out: next state of q via c (state in D)
"""
assert(c in D["Sigma"]), "step_dfa given c not in Sigma."
assert(q in D["Q"]), "step_dfa given q not in Q."
return D["Delta"][(q,c)] | b6efa70ca672afdcc7f9405c6a2df0ba8c41bc54 | 585,257 |
def write_csdata_to_file(data_dict, filename: str, start_csdata_id):
"""Given a dictionary of electron energies and corresponding cross sections,
write the data to a file in the correct format for a NEPC database.
Parameters
----------
data_dict: dict
A dictionary where 'e' is a numpy array... | e89159371b281a172906ddc887d9eff60ad4301b | 585,261 |
def CastMutator(current, value):
"""Cast value."""
return value(current) | ec42c2f0c6fd9f271d1fb4b9562fe3ddaeca1a66 | 585,264 |
import struct
def _encode_msg_size(size: int) -> bytes:
""" Return a bytes object encoding the size of message.
"""
return struct.pack("<I", size) | af459bf3092f9c900184f1b208b1f0fec5bf5d86 | 585,265 |
import math
def halstead_metrics(n1: int, n2: int, N1: int, N2: int):
"""
Compute Halstead metrics for a given program.
Parameters:
n1 (int): Number of unique operators in the query.
n2 (int): Number of unique operands in the query.
N1 (int): Number of operators in the query.
... | 34dee8dd6dd4143506f1523e77dcd316a3b71a9d | 585,266 |
def parse_tuple(line):
"""Parses a string containing a tuple to an actual tuple."""
tup = line.split(',', 1)
x = tup[0].lstrip(' (')
y = tup[1].rstrip(' )')
return (int(x), int(y)) | bf13063be56de9c7735902917945c6c755dafc5a | 585,268 |
def genomeToBlock(chrom, start, end, L=1000000000, blockSize=5000000, delimiter='.'):
"""Transform genomic to block coordinates.
@param chrom: Chromosome
@param start: Start coordinate
@param end: End coorinate
@param L: Chromosome length
@param blockSize: Block size (Default: 5000000)
... | 99ac9c640d4ad1b45f9b2622d9d835a3b7ed7354 | 585,269 |
def filter_float(value):
"""Change a floating point value that represents an integer into an
integer."""
if isinstance(value, float) and float(value) == int(value):
return int(value)
return value | 2940f43db4fb0c4c09d1bd16eac3ccea23eeb8f5 | 585,271 |
import torch
def compute_batch_accuracy(o: torch.Tensor, y: torch.Tensor) -> float:
"""
Computes the accuracy of the predictions over the items in a single batch
:param o: the logit output of datum in the batch
:param y: the correct class index of each datum
:return the percentage of correct predi... | 522a1fe9e04f1b6dfb8a09be52d121935a860e75 | 585,272 |
def upper(word: str) -> str:
"""Upper given word and replace 'ß' to 'ẞ' if exist.
:param word: The word to upper.
:return: The uppered word.
:rtype: str
"""
return word.replace("ß", "ẞ").upper() | bfe1b5c64d2b587250d8e69e704abcf793b6c619 | 585,284 |
def validate_nip(nip):
"""Validate NIP.
:param nip: nip to validate
:return: True if nip is valid, False otherwise
"""
nip_digits = list(map(int, nip))
args = (6, 5, 7, 2, 3, 4, 5, 6, 7)
sum_v = sum(map(lambda x: x[0] * x[1], zip(args, nip_digits)))
checksum_digit = sum_v % 11
retur... | 324017a77c3c8416676a435c15de596eb82cba3f | 585,286 |
def get_as_int(store, key, default):
""" Return the value for key as integer from a dictionary, else default """
try:
value = store.get(key, default)
return int(value)
except (ValueError, TypeError):
return default | 67514515bc4f6a30f64fed16f9adb0abd1ea438b | 585,294 |
import inspect
def _get_alphabetical_members(obj, predicate):
"""Get members of an object, sorted alphabetically.
Parameters
----------
obj
An object.
predicate : callable
Callable that takes an attribute and returns a bool of whether the
attribute should be returned or no... | 704e95b5c47c4d3fca05a6e137ecdd9f8ae40138 | 585,297 |
def _insert_single_package_eups_version(c, eups_version):
"""Insert version information into the configuration namespace.
Parameters
----------
eups_version
The EUPS version string (as opposed to tag). This comes from the
``__version__`` attribute of individual modules and is only set f... | 5fb78d55952466d454f911cead259948407c6e92 | 585,300 |
def list_reshape_bywindow(longlist, windowlen, step=1):
"""
A function to use window cut longlist into several pieces
A list could be like below,
[a, b, c, d, e]
when windowlen as 2, step as 2,
output as
[[a,b], [c,d]]
when window len as 2, step as 1,
output as
[[a,b], [b,c], ... | 9dc9036576901eccaf0f5b8e79bb780501bc0184 | 585,303 |
def is_editable(request, attribute):
"""Returns true if the special hidden 'editable.name' field is set in
the request, indicating that the given field was editable by the user
at the time the edit page was rendered."""
return 'editable.%s' % attribute.key().name() in request.arguments() | 7c3e40f0a2f4e105706821e11513a0b0c820c076 | 585,305 |
def manhattan_distance(i, j):
"""
Returns the Manhattan distance between two nodes i and j
:param i: Node
:param j: Node
:return: Manhattan distance
"""
(ix, iy, iz), (jx, jy, jz) = i, j
return abs(ix - jx) + abs(iy - jy) + abs(iz - jz) | d4aefb50aefdec3b81eb114b421aa891f1b9bfe8 | 585,309 |
def get_hw_dicts(image_id=None):
"""
image_id: list[int], if given image_id, the returned dict_list only contain corresponding dict.
:return: a list[dict], dict : {'file_name': str :'the/path/to/image/2345.jpg',
'height': int,
'width': ... | 8a2aa95b4b0569867dbcbf6a2bf7fb89ce49f15e | 585,310 |
import math
def pretty(values, classes=5, start=None, end=None):
"""
R's pretty algorithm implemented in Python
Code based on R implementation from 'labeling' R package.
Compute a sequence of about 'n+1' equally spaced 'round' values
which cover the range of the values in 'values'. The value... | 474ddd227bd3fc86c71e5028a4c0cb0e94b8d2d1 | 585,311 |
from bs4 import BeautifulSoup
def get_text_from_json(json_file):
"""
Grabs the text of an opinion file from the json file
"""
# get html from json file
# check each of these keys for the case text
html = ''
keys_to_try = ['html', 'plain_text', 'html_with_citations',
'htm... | 46f32c304f970c0fd7d55df233f907235c40ac76 | 585,315 |
def tadd(tup1, tup2):
""" Adds the elements of tup1 and tup2. """
return (tup1[0]+tup2[0], tup1[1]+tup2[1]) | 2ea61f975395e36947697d49f2c8a131defd9bb3 | 585,316 |
from typing import Sequence
import math
def prime_factorization(n: int) -> Sequence[Sequence[int]]:
"""Computes the prime factorization of the natural number n.
Returns a list of base-exponent pairs containing each prime factor and
its power in the prime factorization of n.
"""
d = 2
fac... | 5f36afc75086a2968894a0965fb1d1fb848d72df | 585,319 |
def eq141d13(fy):
"""Shear in webs of rolled beams and plate girders, gross section
AREMA 2018 Table 15-1-11 Row 13 Equations
fa = 0.35*fy
Args:
fy (float): yield stress
Returns:
fa (tuple(float, str)): Allowable shear stress in webs
"""
... | 4e937888c59a822a1d533d109b421ac6dc0ef6eb | 585,320 |
import sqlite3
def get_db(test=False):
""" Get/create a database connection.
If a local ergal.db file exists, a connection
is established and returned, otherwise a new
database is created and the connection is returned.
:param test: (optional) determines whether or not a test database
... | 5ae1be5b6c74f788b89b260a2597ac543968a392 | 585,322 |
def parse_id_lat_lon(row):
""" Returns dictionary of station_id, lat, lon from metadata row. """
return {"station_id": row[:11],
"lat": float(row[12:20]),
"lon": float(row[21:30])} | 2427e1fcb71d5fdfa27682ba7421948ddc8eb0ab | 585,323 |
def related_domain_annotation(sample, domain, relatedness):
"""Create a string for the summary annotation of related samples"""
if sample in relatedness:
if relatedness[sample] == domain:
rv = ":Y"
else:
rv = ":Y:%s" % relatedness[sample]
else:
rv = ""
ret... | 69e05bb157164a0d976575039fa1e96092d8cfe7 | 585,333 |
def split_data(dir, train_size):
"""Splits data into train and validation sets.
Arguments:
----------
dir (pathlib.Path):
Path to images dir.
train_size (float):
Percentage of files in train set.
Returns:
--------
train_images, val_images (tuple):
... | 91e8b5b16054d46e14d3c6a5a908bc5515fe19b2 | 585,335 |
def jaccards_index(set1, set2):
"""
Calculates Jaccard's index between two sets, used to compute overlap
between a word context and a definition's signature.
@param set1 - First set
@param set2 - Second set
@return Jaccard's index
"""
set1 = set(set1)
set2 = set(set2)
return float(len(set1 & set2)) / len(se... | 7193b4d4cd4eea9ebdf32f197e48984110d3dcee | 585,336 |
from typing import List
def shift(steps_number: int, values: List[int]) -> List[int]:
"""Shift values for steps_number steps."""
return [v + steps_number for v in values] | af159a917fba1d2f490a954192c9068f6108316e | 585,343 |
def utm_to_ll(easting, northing, projection):
"""
Convert easting, northing to longitude, latitude
:param easting:
:param northing:
:param projection:
:return: tuple result, (longitude, latitude)
"""
return projection(easting, northing, inverse=True) | 5175eff1cfda3042c535946e59b4525ea7320d16 | 585,344 |
def _prepare_cfg_export_curve(obj):
""" Prepares curve object for libconfig-type export.
:param obj: curve object
:return: curve data as a string
"""
line = ""
# Start exporting object
line += "\ttype = \"curve\";\n"
line += "\tdegree = " + str(obj.degree) + ";\n"
line += "\tknotve... | 3ac4006c6515ef92ad4644f00294ac71c90fd551 | 585,345 |
def get_spelling_suggestions(spelling_suggestions):
"""Returns spelling suggestions from JSON if any """
res = []
if spelling_suggestions and spelling_suggestions[0] and spelling_suggestions[0]['s']:
res = spelling_suggestions[0]['s']
return res | d4eb29fdcb26ac27000aff7888f872e26417b6ad | 585,347 |
import logging
def lookup_release(repo, tag_name):
"""The release corresponding to a tag name."""
for release in repo.get_releases():
if release.tag_name == tag_name:
logging.info('Found release for tag %s: %s', tag_name, release)
return release
logging.info('Failed to fin... | 490567462a458f0dbde86ad3b956e31280443aa0 | 585,348 |
import pathlib
def _get_csv_file_path(data_dir: str, three_sec_song: bool) -> pathlib.Path:
"""Gets CSV file path from data directory.
Parameters
----------
data_dir : str
directory where datafiles are stored
three_sec_song : bool
if should use the three second song csv (as oppose... | 8ce28b1fe367f329a1629dc04cb930715baec765 | 585,349 |
def noop_app(environ, start_response):
""" Dummy app that always returns 404 """
_ = environ
#
start_response("404 Not Found", [
("Content-type", "text/plain")
])
#
return [b"Not Found\n"] | cc810a337dd44a004aa455ff8c8abd83793eb41f | 585,351 |
import math
def orbital_speed(planet, planatary_radius, altitude):
"""
Calculate the orbital speed of an object.
v = R*sqrt(g/(R+h))
>>> from math import *
>>> round(orbital_speed(Constants.Earth, 600000, 70), 3)
2425.552
"""
total_altitude = planatary_radius + altitude
speed = p... | b961271494a1cc6ae513b0144fb627904c1b0b6d | 585,352 |
def serialize_statistics(statistics):
"""
Returns an string with the representation of the statistics in XML format.
:param statistics: statistics to serialize
:return: an string with the representation in the desired format
"""
result = '<statistics>\n'
for question_id, correct_answers in... | 1bed3ba4ba24a8c056036fd20e6971977177e8c9 | 585,355 |
def fetch_item(x, k):
"""Fetch an item from a given subscript
Given a subscript, which may be a slice, a string, or an index, fetch the required items.
This function assumes that the data-subscript pairs have already been checked using is_valid_index.
Args:
x (any): Data either in LOD or DOL f... | d131a8818ce20516bd58fbacf071774bf651db26 | 585,357 |
import hashlib
def get_sha1(file_obj, block_size=65536):
"""Get SHA1 for a file"""
sha = hashlib.sha1()
with open(file_obj, 'rb') as f:
while True:
buf = f.read(block_size)
if not buf:
break
sha.update(buf)
return sha.hexdigest() | 3e65a2e611856cbd1bb7b951ca606ca592ff715c | 585,359 |
import math
def calculate_worker_assignments(host_configs, client_count):
"""
Assigns clients to workers on the provided hosts.
:param host_configs: A list of dicts where each dict contains the host name (key: ``host``) and the number of
available CPU cores (key: ``cores``).
... | d5150cfcfef0b9d35c1ae1d4e6d46f3a28f4f093 | 585,366 |
def _split_tag(tag):
"""Split a tag into its components.
Return a tuple containing task, variant, distro. The values are None if absent from the tag.
If the tag is invalid, the return value is (None, None, None).
"""
elements = tag.split("|")
length = len(elements)
if elements[0] != "unreli... | 608c636b5df99b8ec366f404473a78afa8da65bf | 585,367 |
def max_distant_color(color):
"""
Returns the maximally distant uint8 color for a given uint8 color.
"""
return tuple(255 if item <= 127 else 0 for item in color) | b82fe35368f93abf187a277e5e384759bb191cac | 585,370 |
from pathlib import Path
from typing import Dict
import glob
def get_yml_paths(yml_dir: Path) -> Dict[str, Path]:
"""Uses glob() to find all of the yml workflow definition files within any subdirectory of yml_dir
NOTE: This function assumes all yml files found are workflow definition files,
so do not mix ... | defc998b4efab747ba5918c5ec751f81f836e315 | 585,372 |
def append_child(parent_el, name, content=None):
"""Returns a new xml element with the given name and optional text content appended to the given parent element."""
doc = parent_el.ownerDocument
el = doc.createElement(name)
parent_el.appendChild(el)
if content:
el.appendChild(doc.createTextN... | 59706d784ffe5d43ed49b64ac9c591694958f6df | 585,375 |
import itertools
def previous_current_next(items):
"""
From http://www.wordaligned.org/articles/zippy-triples-served-with-python
Creates an iterator which returns (previous, current, next) triples,
with ``None`` filling in when there is no previous or next
available.
"""
extend = itertool... | a94dc2e58c3246a22c1d19ee221dd3ee297de633 | 585,379 |
import torch
def compute_volume(batch_lattice):
"""Compute volume from batched lattice matrix
batch_lattice: (N, 3, 3)
"""
vector_a, vector_b, vector_c = torch.unbind(batch_lattice, dim=1)
return torch.abs(torch.einsum('bi,bi->b', vector_a,
torch.cross(vector_b, ... | ee3c8c805300f5f5dc8e38834389b5c6f0475eec | 585,387 |
import base64
def base64url_decode(data: bytes) -> bytes:
"""
Decodes a URL Safe Base64 encoded bytes string into its original contents.
:param data: Data to be decoded.
:type data: bytes
:return: Original contents of the provided encoded data.
:rtype: bytes
"""
data += b"=" * (len(... | b5b98aa01005ce0594d52ebaf3adeab46759ba71 | 585,390 |
import hashlib
def rfc6962_hash_leaf(leaf):
"""RFC6962 hashing function for hashing leaves of a Merkle tree.
Arguments:
leaf: A bytearray containing the Merkle tree leaf to be hashed.
Returns:
A bytearray containing the RFC6962 SHA256 hash of the leaf.
"""
hasher = hashlib.sha256()
# RFC6962 sta... | 19589a6f96def8a9a000c932b38a97515383da5b | 585,391 |
import time
def total_time(func):
"""
Calculate the running time of the function
:param func: the function need to been calculated
:return: func's result
"""
def call_fun(*args, **kwargs):
start_time = time.time()
f = func(*args, **kwargs)
end_time = time.time()
... | 30879a8364106eb759922b63ae81319ed38dda34 | 585,392 |
def linear_roots(a=1.0, b=0.0):
"""Returns the roots of a linear equation: ax+ b = 0.
INPUTS
=======
a: float, optional, default value is 1
Coefficient of linear term
b: float, optional, default value is 0
Coefficient of constant term
RETURNS
========
roots: 1-tup... | 00fcd9a0d6f96a6de93cbc7e4ef53e23a6c3d056 | 585,394 |
def ReadFile(filename):
"""Utility function reads a file and returns its content.
Args:
filename: the file to read.
Returns:
The file content.
"""
with open(filename, "r") as data_file:
return data_file.read() | 7487e5c2e238f8890cdb1582ace984278346434e | 585,396 |
from typing import Dict
from typing import Any
def merge_dicts(*dicts: Dict[Any, Any]) -> Dict[Any, Any]:
"""
Merges two or more dicts. If there are duplicate keys, later dict arguments take precedence.
Null, empty, or non-dict arguments are qiuetly skipped.
:param dicts:
:return:
"""
res... | fdbc1435382f74caf360b743c55b98784d92b981 | 585,399 |
def replace_umlauts(text):
"""
Replaces german umlauts and sharp s in given text.
:param text: text as str
:return: manipulated text as str
"""
res = text
res = res.replace(u'ä', u'ae')
res = res.replace(u'ö', u'oe')
res = res.replace(u'ü', u'ue')
res = res.replace(u'Ä', u'Ae')
... | 39ff2c71a78cdf74f5195dcf65320cc078436d77 | 585,402 |
def getFieldNames(in_layer):
"""
in_layer: This must be a OGRLayer.
Returns an array of field names from the given table.
"""
field_names = []
layerDefinition = in_layer.GetLayerDefn()
for i in range(layerDefinition.GetFieldCount()):
field_names.append(layerDefinition.GetFieldDef... | fadfc7a5defcf73dbf22be6b3e66b2b893872200 | 585,403 |
def _el_orb_tuple(string):
"""Parse the element and orbital argument strings.
The presence of an element without any orbitals means that we want to plot
all of its orbitals.
Args:
string (`str`): The selected elements and orbitals in in the form:
`"Sn.s.p,O"`.
Returns:
... | b56932ce95afb54e3f5d9f01530d50851edab311 | 585,406 |
from typing import Union
def subtract(first: Union[int, float], second: Union[int, float]) -> Union[int, float]:
"""Subtract two numbers.
Arguments:
first {Union[int, float]} -- First number.
second {Union[int, float]} -- second number.
Raises:
TypeError: first has to be a number... | 2f34bd488eb6beab81037702164f47bfcd2da4aa | 585,407 |
def filter_sites_by_distance_to_rupture(rupture, integration_distance, sites):
"""
Filter out sites from the collection that are further from the rupture
than some arbitrary threshold.
:param rupture:
Instance of :class:`~openquake.hazardlib.source.rupture.Rupture`
that was generated by... | d1205cd9f5a3ea8992b8369d4cc3777de99ed021 | 585,408 |
import random
def randhex(n):
"""generate a string of random hex digits"""
return "".join([random.choice("abcdef0123456789") for _ in range(n)]) | 76994a77d6e87b47a91c1e676a48159189112165 | 585,409 |
def verify_numeric_inputs(input_num):
"""Verifies that the user input can be converted to a float.
Args:
input_num (str): string which may contain a float
Returns:
bool: boolean value indicating if input_num can be converted to float
"""
try:
float(input_num)
retur... | 8af43fd192f764bbf33cbd708bf517c3ca0e5491 | 585,411 |
def create_email_remediation_key(message_id, recipient):
"""Returns the value to be used for the key column of the remediation table for email remediations."""
return f'{message_id}:{recipient}' | 501d32a8d03a79670eda892db2d57456dce6261a | 585,412 |
def deepreload(module):
"""
Convenience package for reloading diskpy modules when working.
Parameters
----------
module : str
Module to reload
Returns
-------
command : str
Command to exec which will reload the module and its parents
Examp... | 4e747f34c01edeedbfed9d1637ac86310b715628 | 585,414 |
def shpBBoxMerge(a, b):
"""
Given two shapely bounding boxes, return smallest bounding box where both
can fit.
"""
return (
min(a[0], b[0]),
min(a[1], b[1]),
max(a[2], b[2]),
max(a[3], b[3])
) | 804ba82bde352065df084c5bd2a681ee8d62f65c | 585,417 |
def find_empty(board):
"""Function to find empty cells in game board.
Args:
board (list): the current game board.
Returns:
(i, j) (tuple): empty position (row, column) if found, otherwise None.
"""
for i in range(len(board)):
for j in range(len(board[0])):
if bo... | 7ac6d976fea3af469dc94107f4441e00d015f46e | 585,418 |
def vari(n, k):
"""Variations.
n = total number of elements
k = number of elements chosen
k
Notation: V
n
All elements included: no
Can elements repeat: no
Order matters: yes
See: Number of ways there are to rearrange k elements
... | c4be3aea12e75c0b976b4bf2dbb532db5fc668fa | 585,420 |
def get_volume_average(tickers) -> float:
"""Get volume average from tickers data.
:param dict tickers: tickers data.
:return: calculated volume average from tickers data.
"""
all_volumes = [v['quoteVolume'] for v in tickers.values()]
avg = sum(all_volumes) / len(all_volumes)
return avg | f31fe2943b342b7f113c8584aeac61db07b72353 | 585,422 |
def palindrome(word: str) -> bool:
"""
Check if a string is palindrome
:param word: the word to analyze
:return: True if the statement is verified, False otherwise
"""
i=0
while i < int((len(word)+1)/2):
if word[i] != word[-(i+1)]: return False
i+=1
return True | 98da35f89c6c245c66aa5b0c2d65305b9090b1da | 585,424 |
def create_dummy_func(func, dependency):
"""
When a dependency of a function is not available, create a dummy function which throws ImportError when used.
Args:
func (str): name of the function.
dependency (str or list[str]): name(s) of the dependency.
Returns:
function: a func... | 4f6f0f7f647e9bf379b13798fc6d895c89ddd918 | 585,427 |
def adjustNumberInRange(x: float) -> float:
"""Adjust number into range (0,100)"""
if x <= 0:
return 1e-12
if x >= 100:
return 100 - 1e-12
return x | 3cb16d47a3b69972764473d05dd4963f47eb4090 | 585,429 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.