content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def arrstrip(arr):
""" Strip beginning and end blanklines of an array """
if not arr[0]: arr.pop(0)
if not arr[-1]: arr.pop()
return arr | cd79ce4fe12c864e0b57f1513962e3123e291b8d | 36,460 |
def evaluate_part_two(expression: str) -> int:
"""Solve the expression giving preference to additions over multiplications"""
while "+" in expression:
expression_list = expression.split()
i = expression_list.index("+")
new_expression = str()
for j, char in enumerate(expression_li... | 5e9a28a0ca079abcfc364ce3085dbfd3ef3a695e | 36,463 |
def markdown_image(url):
"""Markdown image markup for `url`."""
return ''.format(url) | df17ec7e51b8b5ad10e1e489dd499aa840dbc45b | 36,467 |
def task_exists(twarrior, task_name: str) -> bool:
"""
Check if task exists before inserting it
in Task Warrior.
"""
tasks = twarrior.load_tasks()
for key in tasks.keys():
for task in tasks[key]:
if task['description'] == task_name:
return True
return Fals... | 1a5dbd790b11492c7417b7611c7f62af544a7862 | 36,471 |
def select_coefs(model_coefs, idx):
"""
Auxiliary function for compute_couplings().
Used to select the desired subvector/submatrix from the vector/matrix
of model coefficients.
"""
if len(model_coefs.shape) == 1: # Binomial case
sel_coefs = model_coefs[range(idx, idx + 20)]
else: #... | b8a90fa20c5dc4ff9630291466eeaaea2f44046b | 36,479 |
def _normalize_site_motif(motif):
"""Normalize the PSP site motif to all caps with no underscores and return
the preprocessed motif sequence and the position of the target residue
in the motif (zero-indexed)."""
no_underscores = motif.replace('_', '')
offset = motif.find(no_underscores)
respos =... | 6758ff876b123eba86ec623753c49007baa07431 | 36,482 |
from typing import Dict
from typing import Any
import json
def _serialize_content_with_header(content: Dict[str, Any]) -> bytes:
"""Writes serialized LSP message that includes a header and content."""
serialized_content = json.dumps(content).encode("utf-8")
# Each header parameter is terminated by \r\n, and the... | 5058de8a604cf626616011220b6c20dd17a61c9c | 36,484 |
import random
def normalDistrib(a, b, gauss=random.gauss):
"""
NOTE: assumes a < b
Returns random number between a and b, using gaussian distribution, with
mean=avg(a, b), and a standard deviation that fits ~99.7% of the curve
between a and b.
For ease of use, outlying results are re-compute... | cbb6d6e10998a46c7686956820987fb5e125a598 | 36,489 |
def read_object(self, obj):
"""
Read an object file, enabling injection in libs/programs. Will trigger a rebuild if the file changes.
:param obj: object file path, as string or Node
"""
if not isinstance(obj, self.path.__class__):
obj = self.path.find_resource(obj)
return self(features='fake_obj', source=obj, ... | 973e4bce06d28243a3ebf07a9f945509730af7c1 | 36,490 |
def convert_to_bool(b_str:str):
"""Converts a string to a boolean.
b_str (str): A string that spells out True or False, regardless of
capitilisation.
Return bool
"""
if not isinstance(b_str, str):
raise TypeError("Input must be a string.")
if b_str.u... | 52dddf84d1bdd0e72774104c2b736989d941a196 | 36,492 |
def _as256String(rgb):
"""
Encode the given color as a 256-colors string
Parameters:
rgb (tuple): a tuple containing Red, Green and Blue information
Returns:
The encoded string
"""
redRatio = (0 if rgb[0] < 75 else (rgb[0] - 35) / 40) * 6 * 6
greenRatio = (0 if rgb[1] < 75 ... | cbefff1dcb11be3e74f5b12bb02fbc897f1e5d07 | 36,495 |
def new(name, num_servings):
""" Create and return a new recipe.
"""
return {'name' : name,
'num_servings' : num_servings,
'instructions' : [],
'ingredients' : []} | d8d864308a962307514a4966eb226a95d7c0fb05 | 36,496 |
def label_rs_or_ps(player_data_list, label):
"""Adds label of either RS or PS.
Args:
player_data_list: player data list
label: RS or PS
Returns:
Labels data RS or PS
"""
return [[*year, label] for year in player_data_list] | 1fd4d87df1b656bb3a90c6fe8d2ce4ba2f62b508 | 36,497 |
import itertools
def get_grid(args):
""" Make a dict that contains every combination of hyperparameters to explore"""
# Make a list of every value in the dict if its not
for k, v in args.items():
if type(v) is not list:
args[k] = [v]
# Get every pairwise combination
hyperparam... | ef29106e3bc27359f5e27ae2acd4984e85e8489d | 36,500 |
def get_5_cards(deck):
"""Return a list of 5 cards dealt from a given deck."""
l =[]
for i in range(5):
l.append(deck.deal_card())
return l | c7b6cf751a144e7d4b0dccb40a92dbb3cc3022c9 | 36,504 |
def GetBuildersWithNoneMessages(statuses, failing):
"""Returns a list of failed builders with NoneType failure message.
Args:
statuses: A dict mapping build config names to their BuilderStatus.
failing: Names of the builders that failed.
Returns:
A list of builder names.
"""
return [x for x in f... | 207a71f5a3965609b41da424492a316d03df0d7d | 36,505 |
def str_name_value(name, value, tab=4, ljust=25):
"""
This will return a str of name and value with uniform spacing
:param name: str of the name
:param value: str of the value
:param tab: int of the number of spaces before the name
:param ljust: int of the name ljust to apply to name
... | fdcbba230e6045c3f84bc050cf3774fe0e4c6036 | 36,509 |
def verbose_name(instance, field_name=None):
"""
Returns verbose_name for a model instance or a field.
"""
if field_name:
return instance._meta.get_field(field_name).verbose_name
return instance._meta.verbose_name | 50e3c9c341e5cd8e259b00807daf068edc2a1772 | 36,511 |
def findClosestValueInBST(bst , target):
"""
You are given a BST data structure consisting of BST nodes.
Each BST node has an integer value stored in a property
called "value" and two children nodes stored in properties called
"left" and "right," respectively. A node is said to be a
BST node if ... | 8b91b6cea5350babfafb43698eac4d9aef79662d | 36,513 |
import re
from typing import OrderedDict
def _make_str_data_list(filename):
"""
read pickle_list file to make group of list of pickle files.
group id is denoted in front of the line (optional).
if group id is not denoted, group id of -1 is assigned.
example:
0:file1.pickle
0:file2.pickle
... | cf69c678c8cf0b544d6d811034c1efe94370e08e | 36,515 |
def get_description_data(description):
"""If description is set will try to open the file (at given path), and read the contents.
To use as the description for the MR.
Args:
description (str): Path to description for MR.
Returns
str: The description to use for the MR.
Raises:
... | e1594ef02f9f33443e24fac76f186846912a45fa | 36,517 |
def order(request):
"""
A possible bond order.
"""
return request.param | 7d5d9bc55d1b839c5df19caa560889901e6dd009 | 36,519 |
import grp
def gid_to_name(gid):
"""
Find the group name associated with a group ID.
:param gid: The group ID (an integer).
:returns: The group name (a string) or :data:`None` if :func:`grp.getgrgid()`
fails to locate a group for the given ID.
"""
try:
return grp.getgrgi... | abde4a17fccd88add0392a4185f2db40753ccae0 | 36,522 |
def have_binaries(packages):
"""Check if there are any binaries (executables) in the packages.
Return: (bool) True if packages have any binaries, False otherwise
"""
for pkg in packages:
for filepath in pkg.files:
if filepath.startswith(('/usr/bin', '/usr/sbin')):
ret... | f270defa5f9ab141692bf17fc91d1580989437de | 36,523 |
def get_param_names(df):
"""Get the parameter names from df.
Since the parameters are dynamically retrieved from the df,
this function ensures that we have a consistent and correct mapping
between their names and values across the callbacks.
"""
return sorted(col for col in df.columns if col.st... | 8def5a18c717dffb3d07da006cc0a04efbf1cf8d | 36,527 |
def div_roundup(a, b):
""" Return a/b rounded up to nearest integer,
equivalent result to int(math.ceil(float(int(a)) / float(int(b))), only
without possible floating point accuracy errors.
"""
return (int(a) + int(b) - 1) // int(b) | cb44ec46b1867e56906edeb99f64f7aedd088482 | 36,529 |
def _point_cloud_error_balltree(src_pts, tgt_tree):
"""Find the distance from each source point to its closest target point
Uses sklearn.neighbors.BallTree for greater efficiency
Parameters
----------
src_pts : array, shape = (n, 3)
Source points.
tgt_tree : sklearn.neighbors.BallTree
... | 6a5c37b639bbb4f0bc971c482834a47d560fd8e4 | 36,530 |
def __get_default_resource_group() -> str:
"""Get the resource group name for player account"""
return 'CloudGemPlayerAccount' | c77a4f29292f3c761b2bd687456bb1e60114173c | 36,534 |
def matrixAsList( matrix, value = True ):
"""
Turns a matrix into a list of coordinates matching the specified value
"""
rows, cols = len( matrix ), len( matrix[0] )
cells = []
for row in range( rows ):
for col in range( cols ):
if matrix[row][col] == value:
c... | 837944d212635cff0b01549b4397624a4e4bbfd9 | 36,537 |
def is_next_month(first_date, second_date):
""" Return True if second_date is in following month to first_date """
return (second_date.month - first_date.month) + \
(second_date.year - first_date.year) * first_date.month == 1 | bd22ffd4ffd7dba142090130015de50f9a079945 | 36,538 |
def convert_title(x) -> str:
"""Trim trailing characters on the title"""
return x.strip() | a63ccc9886fc16f936ce38fba37e3b6c6b7d0fba | 36,539 |
def GetFileExt(path, add_dot=False):
""" Returns the filetype extension from the given file path.
:param str path: file path
:param boolean add_dot: whether to append a period/dot to the returned extension
:returns str: filetype extension (e.g: png)
"""
ext = path.split(".")
ext.reverse()
... | 149b5df42b0f37b2414e6c1ef46b9a35a8308fdf | 36,541 |
def unit_conversion(array, unit_prefix, current_prefix=""):
"""
Converts an array or value to of a certain
unit scale to another unit scale.
Accepted units are:
E - exa - 1e18
P - peta - 1e15
T - tera - 1e12
G - giga - 1e9
M - mega - 1e6
k - kilo - 1e3
m - milli - 1e-3
u... | 202725b01912532a6e899e6dbaff1e5edfbef7e0 | 36,542 |
def second(x, y):
"""Second argument"""
return y | 2a66d4dc0ea831537af565cd8ad03f16ad54b554 | 36,549 |
def epiweek_to_month(ew):
"""
Convert an epiweek to a month.
"""
return (((ew - 40) + 52) % 52) // 4 + 1 | 95403f0ef57d4dece759cc7922e3bf295d08c459 | 36,550 |
import torch
def masked_function(function, *inputs, mask=None, restore_shape=True):
"""
Apply a function to the masked part of an input tensor.
:param function: The function to apply.
:param inputs: Input tensor, shape (N* x hidden)
:param mask: Mask, shape (N*) or broadcastable, optional
:ret... | 35fbacad265a94b409131ec74d84b87c824f0c8a | 36,552 |
def _determine_dimensions(ideal_dimensions, current_dimensions):
"""
ideal_dimensions: dimensions we want an image to fit into (width, height)
current_dimensions: the dimensions the image currently has (width, height)
returns the dimensions the image should be resized to
"""
current_width = cur... | 5954ca209b6d8aa12480944d53346035379cd4c7 | 36,558 |
import requests
def genderize(first_name):
""" Use genderize.io to return a dictionary with the result of the
probability of a first name being of a man or a woman.
Example: {'count': 5856,
'gender': 'male',
'name': 'Alex',
'probability': '0.87'}
Parameters
... | dd6d107ce28bec3a5149f815ae15865cf34205be | 36,569 |
def import_sensors_from_device(client, device):
"""
Imports sensor data of specified devices from the Rayleigh Connect API
:param client: An instance of the RayleighClient class
:param device: A list of Node objects describing the Rayleigh devices
:return: A JSON object containing the sensors for e... | 275f818cb56aa244e79aa5b9b3ad077472026e0e | 36,578 |
def get_years(start_time, stop_time):
"""Get years contained in a time period.
Returns the list of years contained in between the provided
start time and the stop time.
:param start_time: Start time to determine list of years
:type start_time: str
:param stop_time: Stop time to determine list ... | 9d8073933f7dfe4c2917b1eb95e38700e30b3243 | 36,579 |
def and_join(items: list[str], sep: str = ", ") -> str:
"""Joins a list by a separator with an 'and' at the very end for readability."""
return f"{sep.join(str(x) for x in items[:-1])}{sep}and {items[-1]}" | 4ba8be63f7add4a124dce05c139a1521d83ab12e | 36,581 |
def test_same_type(iterable_obj):
"""
Utility function to test whether all elements of an iterable_obj are of the
same type. If not it raises a TypeError.
"""
# by set definition, the set of types of the elements in iterable_obj
# includes all and only the different types of the elements in ite... | 25b48d11eef503f8a0fd78b648f5b6b273f0a8a9 | 36,582 |
def schur_representative_from_index(i0, i1):
"""
Simultaneously reorder a pair of tuples to obtain the equivalent
element of the distinguished basis of the Schur algebra.
.. SEEALSO::
:func:`schur_representative_indices`
INPUT:
- A pair of tuples of length `r` with elements in `\{1,\... | b747f247c77b108e86564eb30b6f06376551c7bc | 36,583 |
import requests
def import_web_intraday(ticker):
"""
Queries the website of the stock market data provider AlphaVantage (AV). AV provides stock,
forex, and cryptocurrency data. AV limits access for free users as such:
1. maximum of : 5 unique queries per minute, and 500 unique queries per 24h period
2. Intra... | 8d38a950923f32c805d15e8f29d83b113e4e3b5b | 36,584 |
def command_handler(option_value):
"""Dynamically load a Python object from a module and return an instance"""
module, klass = option_value.rsplit('.',1)
mod = __import__(module, fromlist=[klass])
return getattr(mod, klass)() | d199b8f031c08f4e559aa66edb5a3979a295079c | 36,586 |
def to_list(collection):
""":yaql:toList
Returns collection converted to list.
:signature: collection.toList()
:receiverArg collection: collection to be converted
:argType collection: iterable
:returnType: list
.. code::
yaql> range(0, 3).toList()
[0, 1, 2]
"""
re... | 730c2d1b939b24f501461362e585212a353cf1b8 | 36,587 |
def safe_dict_set_value(tree_node, key, value):
"""Safely set a value to a node in a tree read from JSON or YAML.
The JSON and YAML parsers returns nodes that can be container or non-container
types. This method internally checks the node to make sure it's a dictionary
before setting for the specified key. I... | 5a6e527a2e0bde659086c75f9cca06824069cd9a | 36,588 |
def get_next_cursor(res):
"""Extract the next_cursor field from a message object. This is
used by all Web API calls which get paginated results.
"""
metadata = res.get('response_metadata')
if not metadata:
return None
return metadata.get('next_cursor', None) | e5ef1daaf228a4c556387e913297998810c82511 | 36,594 |
def resource_to_type_name(resource):
"""Creates a type/name format from a resource dbo."""
return resource.type_name | 444ce157cdef0cb54c842c2636801ec075e1db15 | 36,599 |
def get_kmers(start,end,input_alignment):
"""
Accepts as start and end position within a MSA and returns a dict of all of the kmers
:param start: int
:param end: int
:param input_alignment: dict of sequences
:return: dict of sequence kmers corresponding to the positions
"""
kmers = {}
... | d4fa3a98cb4a9bdbba4aff423df94f7898430d3c | 36,600 |
from typing import List
from typing import Any
def stable_sort(deck: List[Any]) -> List[Any]:
"""Sort of list of object, assuming that <, ==, and > are implement for the
objects in the list.
This function implements a merge sort, which has an average performance of
O(nlog(n)) and a worst case perform... | d35ab897160c0f483b924ed4527edf718e3e21d2 | 36,601 |
def get_device_model(device):
"""
Get the model of a given device
Args:
device: The device instance.
Returns:
The device model.
"""
logFile = device.adb("shell", "getprop", "ro.product.model")
return logFile.strip() | acea6f64f2aa6aefe6963f660d08a8bb7421cf94 | 36,610 |
import shutil
from pathlib import Path
def get_program_path(program):
"""Get full path to a program on system PATH."""
path = shutil.which(program)
if not program:
raise OSError(f"{program} not found on system $PATH")
return Path(path).resolve() | 5422a0577527149110a77bf07a67a4ea83ed5add | 36,613 |
def split_jaspar_id(id):
"""
Utility function to split a JASPAR matrix ID into its component base ID
and version number, e.g. 'MA0047.2' is returned as ('MA0047', 2).
"""
id_split = id.split('.')
base_id = None
version = None
if len(id_split) == 2:
base_id = id_split[0]
... | d1a0646abf2650b87421b656d5abc7fb4bfa4c31 | 36,615 |
def iota(n):
"""
Return a list of integers.
"""
return list(range(n)) | 6fda33ce7e367cdf46330a6aa089571397b38535 | 36,617 |
def get_limelines_by_name(resolve_project, timeline_names):
"""
For a given list of timeline names, will output a list of timeline objects
"""
all_timelines = []
output = []
for index in range(int(resolve_project.GetTimelineCount())):
all_timelines.append(resolve_project.GetTimelineByInd... | 4038dfa5efd995c938ef12fd636ffd289b8977dc | 36,624 |
def capital_recovery_factor(interest_rate, years):
"""Compute the capital recovery factor
Computes the ratio of a constant loan payment to the present value
of paying that loan for a given length of time. In other words,
this works out the fraction of the overnight capital cost you need
to pay back... | 4a92ca527557087537973e2adfedd48279a7c59e | 36,625 |
def ellipsis_eqiv(key):
"""
Returns whether *key* is a *tuple* of *Ellipsis* or equivalent *slice*s.
"""
return isinstance(key, tuple) and all(
k is Ellipsis or
isinstance(k, slice) and (
k.start in (None, 0) and
k.stop in (None, -1) and
k.step in (Non... | 5c0de46415afd936b9828685229f848fbf099e18 | 36,629 |
def prepare_tenant_name(ts, tenant_name, product_name):
"""
Prepares a tenant name by prefixing it with the organization shortname and returns the
product and organization record associated with it. The value of 'tenant_name' may
already contain the prefix.
Returns a dict of 'tenant_name', 'product'... | e5afa36eb866e182c0ca674cb0a578a66fad242a | 36,638 |
def linear_search(L, e):
"""
Function of linear searching a list to look for specific element
Complexity: O(n)
:param L: List-object
:param e: Element to look for
:return: Boolean value if element has been found
"""
found = False
for i in range(len(L)):
if e == L[i]:
... | 56d690d13ced909868943baa7ef5bc75d2f4de6a | 36,640 |
def parse_hal_spikes(hal_spikes):
"""Parses the tag information from the output of HAL
Parameters
----------
hal_spikes: output of HAL.get_spikes() (list of tuples)
Returns a nested dictionary:
[pool][neuron] = list of (times, 1) tuples
The 1 is for consistency with the return of p... | fb1faba1c10845331bc2e526bbd5553289be2be7 | 36,641 |
from typing import List
from typing import Optional
def brute_force(arr: List[int], value: int) -> Optional[int]:
"""
A brute force method that runs in O(n) and thus does not satisfy the question's requirements.
We use it for comparison.
:param arr: the rotated array
:param value: the value to fin... | b374a81843dc827984382830b9f89d14b24a1c74 | 36,643 |
import random
def hsk_grabber(
target_hsk: float, search_str: str = "", deviation: float = 0.2, limit: int = 10
):
"""
Finds HSK sentences at `target_hsk` level, with a ± deviation of `deviation`.
Search for sentences that contain words (space-separated) with `search_str` and set a sentence output li... | c5f5b4c6f015c309588dcbf791fded250428ab6e | 36,646 |
from typing import List
def bip32_path_from_string(path: str) -> List[bytes]:
"""Convert BIP32 path string to list of bytes."""
splitted_path: List[str] = path.split("/")
if "m" in splitted_path and splitted_path[0] == "m":
splitted_path = splitted_path[1:]
return [int(p).to_bytes(4, byteord... | 8a79d738669724ebacf6afd241f08b7773fcacba | 36,648 |
def _get_centering_constraint_from_dmatrix(design_matrix):
""" Computes the centering constraint from the given design matrix.
We want to ensure that if ``b`` is the array of parameters, our
model is centered, ie ``np.mean(np.dot(design_matrix, b))`` is zero.
We can rewrite this as ``np.dot(c, b)`` bei... | 47aff43f5e6658309e7c11ed2328b279a44e2243 | 36,649 |
def float_callback(input_):
"""Accepts only a float or '' as entry.
Args:
input_ (str): input to check
Returns:
bool: True if input is a float or an empty string, False otherwise
"""
if input_ != "":
try:
float(input_)
except (ValueError, TypeError):
... | 979443f9f6efcec65a09fbc7e7b8b5281763ce7b | 36,650 |
def __checkCanLink(context, source, source_type, message_libname, real_libs=[]):
"""
Check that source can be successfully compiled and linked against real_libs.
Keyword arguments:
source -- source to try to compile
source_type -- type of source file, (probably should be ".c")
message_libname -- library name to ... | 66cc4819d684501462465308eb9f8fdeca9f3e6e | 36,656 |
def figsize(rows=1, cols=1):
"""Default figsize for a plot with given subplot rows and columns."""
return (7 * rows, 5 * cols) | 1269f7e6400f903249b3de5857f355aad9a53d46 | 36,664 |
def compare_lists(lst, other_lst):
""" compare two lists
:param lst: list for compare
:param other_lst: list for compare
:return: result compare
"""
return frozenset(lst) == frozenset(other_lst) | 764ecc0974e863395407f81c435cd1eb4631d649 | 36,669 |
def bool2option(b):
"""
Get config-file-usable string representation of boolean value.
:param bool b: value to convert.
:rtype: string
:returns: ``yes`` if input is ``True``, ``no`` otherwise.
"""
return 'yes' if b else 'no' | 0a0eec4b27cd3c062c7dbe6b1fd7625648c2f0ba | 36,671 |
def gotoHostGnx(c, target):
"""Change host node selection to target gnx.
This will not change the node displayed by the
invoking window.
ARGUMENTS
c -- the Leo commander of the outline hosting our window.
target -- the gnx to be selected in the host, as a string.
RETURNS
True if targe... | 22eeb26137b2f082abb32ab9fd1daedf44c08033 | 36,675 |
import click
def check(fn, error_message=None):
"""
Creates callback function which raises click.BadParameter when `fn` returns `False` on given input.
>>> @click.command()
>>> @click.option('--probability', callback=check(lambda x: 0 <= x <= 1, "--probability must be between 0 and 1 (inclusive)"))
... | 8519e6c29a1cb2843260570a8888b551d8c4987c | 36,676 |
def surround_double_quotes(string: str) -> str:
"""Surrounds the input string with double quotes and returns the modified string.
Args:
string: String to be modified.
Returns:
str: String with double quotes.
"""
return '"' + str(string) + '"' | 63526107bc13772e23a4d1eb198bc703cb6824b0 | 36,683 |
import itertools
def sort_and_group(iterable, key):
"""Sort an iterable and group the items by the given key func"""
groups = [
(k, list(g)) for k, g in
itertools.groupby(sorted(iterable, key=key), key=key)
]
return groups | e0bddcad90cc4c4e6652a6a9a8faa043dcb69ebd | 36,685 |
def whitespace_tokenize(text):
"""Splits an input into tokens by whitespace."""
return text.strip().split() | 266f6bb537f82e599c85c96f70675a571bf5dafd | 36,688 |
def interpret(instruction: str) -> tuple:
"""
Split and interpret a piloting instruction and return a tuple of action and
units.
Paramaters:
instruction (str): Instruction to interpret
Returns
tuple: Tuple of action and units
"""
action, units = instruction.split(" ", 1)
units ... | 5d52bbefea69aaab66a3f34cfa0f8185c9abadff | 36,692 |
def main(args=None):
""" Main entry point of hello-world """
print('Hello World')
return 0 | 7c2032c045d7ce96e5a32a20483176c362689ab3 | 36,693 |
import hashlib
import json
def check_hash(hash: str, content: dict) -> bool:
"""Check that the stored hash from the metadata file matches the pyproject.toml file."""
# OG source: https://github.com/python-poetry/poetry/blob/fe59f689f255ea7f3290daf635aefb0060add056/poetry/packages/locker.py#L44 # noqa: E501
... | 5b4d9407c95eb2239c42dd13c5052ce011f4fa5a | 36,694 |
def _percent_str(percentages):
"""Convert percentages values into string representations"""
pstr = []
for percent in percentages:
if percent >= 0.1:
pstr.append('%.1f' %round(percent, 1)+' %')
elif percent >= 0.01:
pstr.append('%.2f' %round(percent, 2)+' %')
... | 0e6acc22eb14e0e5dfb1f44a52dc64e076e15b33 | 36,695 |
import typing
def isunion(T) -> bool:
"""Returns whether the given type is a generic union"""
return typing.get_origin(T) == typing.Union | 23e8095ad8e131abf079e384c850038c25b57aab | 36,696 |
def get_non_job_argslist(details_form):
"""
Gets a list of all fields returned with the Job options forms that
shouldn't be included in the job args list put in the database.
Args:
details_form (WTForm): the JobDetails form (a form that is
used as a base for most ... | f236bfdfd3edab88406845dda893cc4b35f9378d | 36,703 |
def temp_dir_simulated_files(tmp_path_factory):
"""Temporal common directory for processing simulated data."""
return tmp_path_factory.mktemp("simulated_files") | 0f1cf4b8501463b9e2dd484d68e9c74978f9b5b8 | 36,706 |
def _indent(msg, tab=' '):
"""Add indentation to a message line per line"""
res = ''
for line in msg.split('\n'):
res += tab+line+'\n'
return res | af871f6b9478ed4a21a0d8c8437b23942002c781 | 36,709 |
def create_payment_msg(identifier, status):
"""Create a payment payload for the paymentToken."""
payment_msg = {'paymentToken': {'id': identifier, 'statusCode': status}}
return payment_msg | 265401c5b8c9bbc0f71cfb718157101e3b48e8de | 36,713 |
def addElements(record,recordInfo,featureList):
"""
Input: record - node from XML File,
recordInfo - dict of info about record,
featureList - list of features to parse
Output: Updated recordInfo with text of features in featureList
"""
for entry in featureLi... | 351d06e23c6d21ee3c4da980e077dcd09b163a61 | 36,714 |
def path_to_str(pathP: list) -> str:
"""Use to get a string representing a path from a list"""
if len(pathP) < 1:
return ""
if len(pathP) < 2:
return pathP[0]
res = f"{pathP[0]} -> "
for i in range(1, len(pathP) - 1):
res += f"{pathP[i]} -> "
return res + f"{pathP[-1]}" | db4a2c054455e2de6a6b4c7844b3104b4706c7f4 | 36,716 |
def truncate_int(tval, time_int):
"""Truncate tval to nearest time interval."""
return((int(tval)/time_int) * time_int) | 3c366f417ab9e84b5337814f78d7888fca4d0265 | 36,717 |
def get_cid_from_cert_lot_result(result):
"""
Get CID from a certificate-by-location query result.
The query looks like:
'[hardware_api]/201404-14986/'
This function is a parser to get 201404-14986.
:param result: elements of results queried from C3 certificate API
:return: string, CI... | 724d9371411e378e1e143d9d09d6d3686e7133c7 | 36,719 |
def _create_expr(symbols, prefix='B', suffix='NK'):
"""Create einsum expr with prefix and suffix."""
return prefix + ''.join(symbols) + suffix | d5e0aff866f375d611b4a4fa82665a0a5447bf02 | 36,720 |
def raw_to_regular(exitcode):
"""
This function decodes the raw exitcode into a plain format:
For a regular exitcode, it returns a value between 0 and 127;
For signals, it returns the negative signal number (-1 through -127)
For failures (when exitcode < 0), it returns the special value -128
"""... | 1146bc0303886489f10864c9511280dff8047710 | 36,727 |
def get_trigger_severity(code):
"""Get trigger severity from code."""
trigger_severity = {0: "Not classified", 1: "Information", 2: "Warning", 3: "Average", 4: "High", 5: "Disaster"}
if code in trigger_severity:
return trigger_severity[code]
return "Unknown ({})".format(str(code)) | 234c58a04f374a2f227f11b519a82b6272b7aa18 | 36,728 |
def get_attributevalue_from_directchildnode (parentnode, childname, attribute):
""" Takes a parent node element as input
Searches for the first child with the provided name under the parent node
If child is present returns the value for the requested child attribute (the returns None if
the child does n... | cee739b8c0f79f4361f2bee4faf47465ecf06212 | 36,751 |
def get_H_O_index_list(atoms):
"""Returns two lists with the indices of hydrogen and oxygen atoms.
"""
H_list = O_list = []
for index, atom in enumerate(atoms):
if atom[0] == 'H':
H_list.append(index)
if atom[0] == 'O':
O_list.append(index)
return H_list, O_li... | 337d6809e3953172601b7a698b7fb28b96bc3720 | 36,754 |
def _one_or_both(a, b):
"""Returns f"{a}\n{b}" if a is truthy, else returns str(b).
"""
if not a:
return str(b)
return f"{a}\n{b}" | c206b64654817b91962a3583d08204cc02b8c003 | 36,756 |
def update_figure_data_dropdowns(_df1, _df2):
"""
:param _df1: regular season DataFrame values
:param _df2: play-off DataFrame values
:return: return lists with dictionaries for drop down menus
"""
if len(_df1) > 0:
drop_values = [{'label': 'Regular season', 'value': 'Regular season'}]
... | f50fdd29946cd639b42d8883fc4c08b65d87293a | 36,757 |
def to_bdc(number: int) -> bytes:
"""
4 bit bcd (Binary Coded Decimal)
Example: Decimal 30 would be encoded with b"\x30" or 0b0011 0000
"""
chars = str(number)
if (len(chars) % 2) != 0:
# pad string to make it a hexadecimal one.
chars = "0" + chars
bcd = bytes.fromhex(str(cha... | 948da3d4e50e6348a3174826c8bd9ec5c78b559c | 36,760 |
def get_counters(cursor):
""" Fetches counters for the different database categories and returns
them in a dictionary """
counter = {}
cursor.execute('SELECT "count" FROM "counters" WHERE "category" = "genes"')
counter["genes"] = int(cursor.fetchone()[0])
cursor.execute('SELECT "count" FROM... | 761337a42b13f1e65bc21f0bf9f815a72fd9bef5 | 36,762 |
def is_arn_filter_match(arn: str, filter_arn: str) -> bool:
"""
Returns True if the given arn matches the filter pattern. In order
for an arn to be a match, it must match each field separated by a
colon(:). If the filter pattern contains an empty field, then it is
treated as wildcard for that field.... | e94cf5852f4993386b1cbe8d6ada25c6100fb348 | 36,765 |
def calc_delay2(freq, freqref, dm, scale=None):
""" Calculates the delay in seconds due to dispersion delay.
freq is array of frequencies. delay is relative to freqref.
default scale is 4.1488e-3 as linear prefactor (reproducing for rtpipe<=1.54 requires 4.2e-3).
"""
scale = 4.1488e-3 if not scale ... | 7475f140f593692ece4976795a0fd34eba93cffd | 36,766 |
def c_terminal_proline(amino_acids):
"""
Is the right-most (C-terminal) amino acid a proline?
"""
return amino_acids[-1] == "P" | f54563ff59973d398e787186a1c390da03ff8999 | 36,768 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.