content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def get_glyph_horizontal_advance(font, glyph_id):
"""Returns the horiz advance of the glyph id."""
hmtx_table = font['hmtx'].metrics
adv, lsb = hmtx_table[glyph_id]
return adv | 75af73d3dd824391c9058d501fa0883ebdce8bcf | 24,177 |
def _is_array(data):
"""Return True if object implements all necessary attributes to be used
as a numpy array.
:param object data: Array-like object (numpy array, h5py dataset...)
:return: boolean
"""
# add more required attribute if necessary
for attr in ("shape", "dtype"):
if not ... | 72e8225d9fa74ac31f264d99764d94c62013cb06 | 24,185 |
from typing import Iterator
def deepmap(func, *seqs):
""" Apply function inside nested lists
>>> inc = lambda x: x + 1
>>> deepmap(inc, [[1, 2], [3, 4]])
[[2, 3], [4, 5]]
>>> add = lambda x, y: x + y
>>> deepmap(add, [[1, 2], [3, 4]], [[10, 20], [30, 40]])
[[11, 22], [33, 44]]
"""
... | 4a3ee7d15b150cc3cbf1ee22b254c224783ecece | 24,187 |
import logging
def get(name=""):
"""
Get the specified logger
:param name: the name of the logger
:return: the logger
"""
return logging.getLogger(f"wafflebot{'.' + name if name else ''}") | 8102a2f55d4b9badf290fec68d63e11434bcd45d | 24,191 |
def success_response(data):
""" When an API call is successful, the function is used as a simple envelope for the results,
using the data key, as in the following:
{
status : "success",
data : {
"posts" : [
{ "id" : 1, "title" : "A blog post", "body" : "Some useful content"... | 26ca231fcb9e0204c80307b7eebf03b434faca70 | 24,201 |
def solve(n, ar):
"""
Given an integer array ar of size n, return the decimal fraction of the
number of positive numbers, negative numbers and zeroes. Test cases are
scaled to 6 decimal places.
"""
num_pos = 0
num_neg = 0
num_zero = 0
for i in ar:
if i > 0:
num_... | b61b179c357dcf70ac887af20588324624a84ea3 | 24,202 |
def create_phone_number_v2(n):
"""
Turns an array of integers into phone number form.
:param n: an array of integers.
:return: numbers in phone number form.
"""
return "({}{}{}) {}{}{}-{}{}{}{}".format(*n) | 659daecdbb8a0e8a1f02826c35fc26eadef14598 | 24,205 |
def isInSequence(word):
"""
Checks if the string passed is a sequence of digits logically connected ("e.g. 369")
"""
if len(word)<3:
return False
else:
increment = int(word[0]) - int(word[1])
for i in range(len(word) - 2):
if int(word[i+1]) - int(word[i+2]) != inc... | d4749bc5cd656ec2fd2886743ad1848062d3e1db | 24,206 |
def get_file_id(string):
"""
Returns file_id from a information string like Ferrybox CMEMS: <file_id>
:param string:
:return:
"""
return string.split(':')[-1].strip() | a5e58147e4a6e08298ecb6cd34614cff99e7bdac | 24,209 |
from datetime import datetime
import calendar
def month_bounds(date=None):
"""
Return month start and end datetimes
"""
if date is None:
date=datetime.now()
firstday,lastday=calendar.monthrange(date.year,date.month)
start=datetime(date.year,date.month,firstday,0,0,0)
end=datetime(d... | f007bbea414f4ea5756c22ba9228ff74e93a5a09 | 24,212 |
import re
def enum_calculate_value_string(enum_value):
"""
Calculate the value of the enum, even if it does not have one explicitly
defined.
This looks back for the first enum value that has a predefined value and then
applies addition until we get the right value, using C-enum semantics.
Args:
enum... | b6df34ea221cd485f1ca730192bc1fda3fa34a98 | 24,221 |
def _is_gs_offloader(proc):
"""Return whether proc is a gs_offloader process."""
cmdline = proc.cmdline()
return (len(cmdline) >= 2
and cmdline[0].endswith('python')
and cmdline[1].endswith('gs_offloader.py')) | d8a8bd1ec03bcdef05b683e2e7cb88b4521de0ab | 24,225 |
def drop_features(df, to_drop):
"""Drop unwanted features
Parameters
----------
df : panda dataframe
to_drop : array with name of features to be dropped
Returns
-------
Original dataframe with all original features but those in to_drop
"""
return df.drop(to_drop, axis... | 30d6c270a7c4ac2c63a9472362b844a11eb5c119 | 24,232 |
def first(collection, callback):
"""
Find the first item in collection that, when passed to callback, returns
True. Returns None if no such item is found.
"""
return next((item for item in collection if callback(item)), None) | ebecfb1b4264a17dc24c4aeedb8c987e9ddde680 | 24,235 |
import re
def _MakeXMLSafe(s):
"""Escapes <, >, and & from s, and removes XML 1.0-illegal chars."""
# Note that we cannot use cgi.escape() here since it is not supported by
# Python 3.
s = s.replace('&', '&').replace('<', '<').replace('>', '>')
# Remove characters that cannot appear in an XML 1.0... | d64a0c51d79f2384fd14dae8c46ef26fc49c888c | 24,240 |
def deg_to_arcmin(angle: float) -> float:
"""
Convert degrees to arcminutes.
Args:
angle: Angle in units of degrees.
Returns:
Angle in units of arcminutes.
"""
return float(angle) * 60. | 2c075362f4163cb70587eb9fac69ef669c337e2d | 24,241 |
def _get_datetime_beginning_of_day(dt):
"""
Truncates hours, minutes, seconds, and microseconds to zero on given datetime.
"""
return dt.replace(hour=0, minute=0, second=0, microsecond=0) | 12ddcaed68db08740e4edc851a299aa08c23f91c | 24,243 |
def ordinal(n):
"""Translate a 0-based index into a 1-based ordinal, e.g. 0 -> 1st, 1 -> 2nd, etc.
:param int n: the index to be translated.
:return: (*str*) -- Ordinal.
"""
ord_dict = {1: "st", 2: "nd", 3: "rd"}
return str(n + 1) + ord_dict.get((n + 1) if (n + 1) < 20 else (n + 1) % 10, "th") | e6b8583bfb9fbb8a2b2443bc5fad233b1f7a9038 | 24,247 |
def bresenham(p0, p1):
"""
Bresenham's line algorithm is a line drawing algorithm that determines the
points of an n-dimensional raster that should be selected in order to form
a close approximation to a straight line between two points. It is commonly
used to draw line primitives in a bitmap image (e... | 8948059454213c35b11917ac02a846d1d22e26e3 | 24,248 |
def c_git_commit_handler(value, **kwargs):
"""
Return a git VCS URL from a package commit.
"""
return {f'vcs_url': f'git+http://git.alpinelinux.org/aports/commit/?id={value}'} | e9036241be3816a0296caf895a9b323cb297f35a | 24,251 |
def psi_ising(x_1,x_2,alpha):
""" Ising potential function
:param float x_1: first argument of the potential, eventually ndarray.
:param float x_2: second argument, eventually ndarray of the same size that x_1.
:param float alpha: granularity parameter
:returns: **res** *(ndarray)* - outpu... | 071d6256f400b836c392eef739e60a9e1eb4cbbe | 24,253 |
def map_obj_to_string(obj):
"""
Function to create a string version from an object.
Parameters
----------
obj
Some python object
Returns
-------
str_version
Examples
--------
>>> map_obj_to_string(1)
"1"
>>> map_obj_to_string("1")
"1"
>>> map_obj_to... | 913e2c99021976a745fcf5ede5c224060defabc1 | 24,256 |
def clear_grid(ax, pos=["x","y"]):
"""Clear a grid
Args:
ax (Axes) : The ``Axes`` instance.
pos (list) : Positions to clean a grid
Examples:
>>> from pyutils.matplotlib import clear_grid, FigAxes_create
>>> fig,ax = FigAxes_create(nplots=1)[0]
>>> ax = clear_grid(a... | 1f5a148f2e8c885735aaef0c676355299f1a21a4 | 24,261 |
def queenCanTattack(board, size, row, column):
"""Check if the new queen will not be able to attack an other one.
Args:
board (array): board on which the queen will be
size (int): size of the board
row (int): row position on the board
column (int): column position on the board
Retu... | b06c60b797c928caf1fed405f820e8b45a2a61f0 | 24,262 |
def xor(bytes_1: bytes, bytes_2: bytes) -> bytes:
"""
Return the exclusive-or of two 32-byte strings.
"""
return bytes(a ^ b for a, b in zip(bytes_1, bytes_2)) | 1f9eb00848ab963536c01d0c0321321f0c3be887 | 24,265 |
def residual_variance(y_true, y_pred):
"""
Manual calculation of residual variance. It is obtained calculating the square error for every entry of every point,
summarizing all of them and then dividing the sum for n-2, where n is the length of the array.
Please refer to this specification: https://www.c... | 013f2b0d220ce3bd4e26c506302d4a843f8fdd95 | 24,266 |
from typing import Callable
from typing import Any
from typing import Sequence
from typing import Tuple
from typing import Optional
def _find_last(condition: Callable[[Any], bool], sequence: Sequence) -> Tuple[Optional[int], Any]:
"""条件に合う要素をシーケンスの末尾から順に探す。
複数存在する場合、もっとも index が大きいものが返される。
Args:
... | 362575e13e1f0a64560b4c29cf4e97fbff8a248b | 24,267 |
def _defaultHeaders(token):
"""Default headers for GET or POST requests.
:param token: token string."""
return {'Accept': '*/*',
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + token} | 33125604bcb3c7af3d71ae2c7c21f0dd82d141ac | 24,270 |
def load_pizza_data(source):
"""
This function loads a text file as dataset
from a source path. The data structure is
supposed to be like:
<15 4
2 3 5 6>
Parameters
----------
source : String
Global path to text file to be loaded.
Returns
-------
participants : ... | e032619dc01e021f06a9c4eafe2e9f9353bbb66b | 24,277 |
def russian(a, b):
"""
The Russian Peasant Algorithm:
Multiply one integer by the other integer.
Input: a, b: integers
Returns: a*b
"""
c = 0
while a > 0:
if a % 2 == 1:
c = c + b
b = b << 1
a = a >> 1
return c | 1ef601dbeced430ca7d09093ad7338319bb128d4 | 24,278 |
def service(app):
"""Vocabularies service object."""
return app.extensions['invenio-vocabularies'].service | d440e300581fdf71a2f36c8f00c6f0e163f646f0 | 24,284 |
import time
def _get_event_file_active_filter(flags):
"""Returns a predicate for whether an event file load timestamp is active.
Returns:
A predicate function accepting a single UNIX timestamp float argument, or
None if multi-file loading is not enabled.
"""
if not flags.reload_multifile:... | 6d8faeac218293643f0df9d9ffe198d24323ba52 | 24,285 |
def rightRow(r, c):
"""
>>> rightRow(5, 4)
[(5, 4), (5, 5), (5, 6), (5, 7), (5, 8)]
"""
x = [r, ] * (9-c)
y = range(c, 9)
return zip(x, y) | 476ad7f757162c0bd70c41f33564ee8ddf307547 | 24,288 |
def get_uuids(things):
"""
Return an iterable of the 'uuid' attribute values of the things.
The things can be anything with a 'uuid' attribute.
"""
return [thing.uuid for thing in things] | c71a659c96ea0bd7dbb22a92ccca46e29fa072b8 | 24,295 |
def all_black_colors(N):
"""
Generate all black colors
"""
black = [(0, 0, 0) for i in range(N)]
return black | 191a6211caa58b88c62fb327b18d8eef023b74c4 | 24,301 |
def growTracked(mesh, growSet, allSet):
""" Grow a set of verts along edges and faces
This function takes a set of vertices and returns two
dicts. One that is vert:(edgeAdjVerts..), and another
that is vert:(faceAdjVerts..)
While I'm growing a vert, if all vertices adjacent to
that vert are matched, then I no l... | 8930e0b5579ce9a009d71340aeed7366184189dc | 24,302 |
import hashlib
def generate_aes_key(token, secret):
""" Generates and returns a 256 bit AES key, based on sha256 hash. """
return hashlib.sha256(token + secret).digest() | f058402ad893c614c9cde8e9c96a2fdb2ff9ea95 | 24,312 |
def is_identical_typedateowner(ev1, ev2):
"""Check if two events are identical in type, date, and owner.
Args:
ev1: roxar event
ev2: roxar event
Returns:
True if the two events are identical in type, date, and owner; otherwise False.
"""
ident = False
if ev1.type == ev2.type:... | 13490e918abd38161324836dbe002cee552b86b2 | 24,327 |
def get_ele_list_from_struct(struct):
"""
Get elements list from pymatgen structure objective
Parameters
----------
struct : pymatgen objective
The structure
Returns
-------
ele_list : [str]
The list of elements
"""
ele_list = []
for ele in st... | 4a6fa05518ff0725d85b270b8d8b0003eb139e5e | 24,328 |
from typing import Dict
from typing import List
def convert_by_vocab(vocab: Dict, items: List) -> List:
"""Converts a sequence of [tokens|ids] using the vocab."""
output = []
for item in items:
output.append(vocab[item])
return output | 440f1936baafae06a4a38c205e877e71a7ed37e9 | 24,337 |
def get_iou_th_min_th_dila_from_name(folder, mode='str'):
"""
This function gets the iou_th, min_th and dila values from the folder name
:param: folder: The folder name of interest for extraction
:param: mode: The format of extraction, currently support either 'str' or 'num'
"""
iou_th = folder[... | 8dfa3b3b58dc15f72ccb51cd7076c4bc9bd9cf9f | 24,338 |
from typing import OrderedDict
def extractKeyIndexTimeValue(dic={0 : 0}, frameRange=(0, 30), **kwargs):
"""this is extract animCurve's time and value in any frame range.
Parameters
----------
dic : dict(in int or float)
key = time, value = value.
frameRange : tupple(in... | 27cca6ffe38026a4d4b9b5fc732e7c2aa9347e6d | 24,340 |
def print_matrix(m, rownames, colnames):
"""Pretty-print a 2d numpy array with row and column names."""
# Max column width:
col_width = max([len(x) for x in rownames + colnames]) + 4
# Row-formatter:
def fmt_row(a):
return "".join(map((lambda x : str(x).rjust(col_width)), a))
# Printing:... | 83b9f6ca8a2683398344c57c0bbd509a776cffa3 | 24,355 |
def settingsLink(translator, settings, tag):
"""
Render the URL of the settings page.
"""
return tag[translator.linkTo(settings.storeID)] | 413e2ec27a27e77b1850f47f20af45ddbb8d4f6f | 24,356 |
import tarfile
from typing import Optional
def _cache_filter(tar_info: tarfile.TarInfo) -> Optional[tarfile.TarInfo]:
"""
Filter for ``tarfile.TarFile.add`` which removes Python and pytest cache
files.
"""
if '__pycache__' in tar_info.name:
return None
if tar_info.name.endswith('.pyc')... | 5dd54cc8c2532cc89bcf2e357803e9036ce18322 | 24,357 |
import base64
def b64_decode(s):
"""
Decode input string with base64url safe without padding scheme.
"""
mod = len(s) % 4
if mod >= 2:
s += (4 - mod) * "="
return base64.urlsafe_b64decode(s) | e82a6cbffe30b9a27bdd0a58c7f7bf11cc4066f4 | 24,359 |
def _cast_types(args):
"""
This method performs casting to all types of inputs passed via cmd.
:param args: argparse.ArgumentParser object.
:return: argparse.ArgumentParser object.
"""
args.x_val = None if args.x_val == 'None' else int(args.x_val)
args.test_size = float(args.test_size)
args.max_depth = int(args... | 5db5f9569849a868bc180e38bd9bcec618b7cb5d | 24,360 |
def rgb_to_hsv(rgb):
"""
Convert an RGB color representation to an HSV color representation.
(r, g, b) :: r -> [0, 255]
g -> [0, 255]
b -> [0, 255]
:param rgb: A tuple of three numeric values corresponding to the
red, green, and blue value.
:return: HSV represent... | aa2c75b92c9830c7e798b0ca6ee9feac20793de4 | 24,361 |
import logging
import re
def get_landsat_angles(productdir):
"""
Get Landsat angle bands file path.
Parameters:
productdir (str): path to directory containing angle bands.
Returns:
sz_path, sa_path, vz_path, va_path: file paths to solar zenith, solar azimuth, view... | 8b22cb6fc1ea8ae3f3869664aff2f165c418f20c | 24,364 |
import time
def roundtime(seconds, rounding=None):
"""
Round the provided time and return it.
`seconds`: time in seconds.
`rounding`: None, 'floor' or 'ceil'.
"""
Y, M, D, h, m, s, wd, jd, dst = time.localtime(seconds)
hms = {None: (h, m, s), 'floor': (0, 0, 0), 'ceil': (23, 59, 59)}
... | 8cbbc0c8e684e8ea6d1f58e8f9ffc2a40e185b06 | 24,368 |
def envelope_to_geom(env):
"""convert envelope array to geojson
"""
geom = {
"type": "Polygon",
"coordinates": [ [
env[0],
env[1],
env[2],
env[3],
env[0]
] ]
}
return geom | 550765136207b898bac9202847fe8b239a91a20d | 24,372 |
def is_json_object(json_data):
"""Check if the JSON data are an object."""
return isinstance(json_data, dict) | 7b72fc51752f9cfd00ba4815230401f1d40e888f | 24,373 |
import typing
def naive_ctz2(x: int) -> typing.Tuple[int, int]:
"""Count trailing zeros, naively.
Args:
x: An int.
Returns:
A tuple (zeros, x >> zeros) where zeros is the number of trailing
zeros in x. I.e. (x >> zeros) & 1 == 1 or x == zeros == 0.
This is a slow reference i... | 863998c3c7a8b8bd812910d07a911843f43bc549 | 24,374 |
def safe_tile(tile) -> bool:
"""Determines if the given tile is safe to move onto."""
if tile["type"] == "Blank":
return True
if tile["type"] == "Doodah":
return True
if tile["type"] == "SnakeTail" and tile["seg"] == 0:
return True
return False | ffdd3ace46dfe094b49c28e56bebe10e82311158 | 24,378 |
def _field_column_enum(field, model):
"""Returns the column enum value for the provided field"""
return '{}_{}_COL'.format(model.get_table_name().upper(), field.name.upper()) | f0653eb6ccf4c0864a05715643021759cf99e191 | 24,379 |
def get_reply_message(message):
"""Message the `message` is replying to, or `None`."""
# This function is made for better compatibility
# with other versions.
return message.reply_to_message | b2d253047eb1bdcb037b979f1819089ae88fb771 | 24,380 |
from typing import Callable
from typing import List
import inspect
def _get_fn_argnames(fn: Callable) -> List[str]:
"""Get argument names of a function.
:param fn: get argument names for this function.
:returns: list of argument names.
"""
arg_spec_args = inspect.getfullargspec(fn).args
if i... | a464f1fb21a454f4e6a854a64810ba48cdb6f9f8 | 24,381 |
def get_primary_key(s3_index_row):
"""
returns the primary key of the s3Index dynamo table.
Args:
s3_index_row(dict): dynamo table row for the s3Index
Returns:
(dict): primary key
"""
primary = {"object-key": s3_index_row["object-key"],
"version-node": s3_index_ro... | b5ca8ccb82dd1410626f205f0a8ea5486a2bcb8a | 24,390 |
import csv
def read_student_names(file):
"""If file ends in .csv, read the CSV file where each username should
reside in the second column and the first column contains "student".
If not, the file should contain several lines, one username per line.
Return a list of students thus extracted."""
wit... | d52716648bba85e776ef431ce879b8ea37068e8d | 24,392 |
def project_list(d, ks):
"""Return a list of the values of `d` at `ks`."""
return [d[k] for k in ks] | 62b82429e4c8e18f3fb6b1f73de72b1163f460bf | 24,393 |
def list_users(iam_client):
""" List all IAM users """
return iam_client.list_users()['Users'] | da3509377968d642469e384bd6143783528e7f76 | 24,394 |
def snip(content):
"""
This is a special modifier, that will look for a marker in
``content`` and if found, it will truncate the content at that
point.
This way the editor can decide where he wants content to be truncated,
for use in the various list views.
The marker we will look for in t... | 6d836f610dfe1b49d4f1971cc3c6a471b789f475 | 24,397 |
def build_search_query(query, page, per_page) -> dict:
"""
Build the multi-search query for Elasticsearch.
:param str query:
:param int page:
:param int per_page:
"""
search_query = {
"query": {"multi_match": {"query": query, "fields": ["*"]}},
"from": (page - 1) * per_page,
... | f82dfdd11b0ad9bf2e3dfce9d723b46944ed2e53 | 24,399 |
def white_dwarfs(ds, data):
"""
Returns slicing array to determine white dwarf particles
"""
pcut = data['particle_type'] == 12
pcut = pcut * (data['particle_mass'] > 0.0)
return pcut | 83217024591af0e6f6918227be68251c452a0a08 | 24,400 |
import json
def key_dumps(obj):
"""Return serialized JSON keys and values without wrapping object."""
s = json.dumps(obj, sort_keys=True, indent=4, separators=(',', ': '))
# first and last lines will be "{" and "}" (resp.), strip these
return '\n'.join(s.split('\n')[1:-1]) | c1b303de6ed34d5308aa2486f2e04a1f6d932bb8 | 24,401 |
def getUnique(df):
"""Calcualtes percentage of unique reads"""
return (
df.loc[df[0] == "total_nodups", 1].values[0]
/ df.loc[df[0] == "total_mapped", 1].values[0]
) | d5922fe59b95ec56c7310dce955ff85d97d6d9f1 | 24,411 |
def no_none_get(dictionary, key, alternative):
"""Gets the value for a key in a dictionary if it exists and is not None.
dictionary is where the value is taken from.
key is the key that is attempted to be retrieved from the dictionary.
alternative is what returns if the key doesn't exist."""
if key... | 68b6f1d3cdd736f5f373093058e630db039be781 | 24,413 |
def similar(real, predicted):
"""
Compare if the captcha code predicted is close to the real one
:param real string: Real captcha string
:param predicted string: Predicted captcha string
:return
wrong_letter_count float: Percentage of wrong letter
wrong_letter_dict dict: Dict of all wron... | e5595e34b81e770604b383dbd48906efc5a91173 | 24,414 |
from typing import List
import requests
def get_github_ips() -> List[str]:
"""Gets GitHub's Hooks IP Ranges
Returns:
List of IP Ranges
"""
resp = requests.get(
'https://api.github.com/meta',
headers={
'User-Agent': 'hreeder/security-group-synchronizer'
}
... | 74a5c4fb62b94dc9bf8cba41cf75da4dbb11f15c | 24,417 |
def _num_matured(card_reviews):
"""Count the number of times the card matured over the length of time.
This can be greater than one because the card may be forgotten and mature again."""
tot = 0
for review in card_reviews.reviews:
if review.lastIvl < 21 and review.ivl >= 21:
tot += ... | fe955d7a1322b995b12d030337008b99da9f8c1f | 24,422 |
import re
import fnmatch
def build_pattern(pattern_algorithm: str, pattern: str, case_insensitive: bool) -> re.Pattern[str]:
"""
Build a matching object from the pattern given.
:param pattern_algorithm: A pattern matching algorithm.
:param pattern: A pattern text.
:param case_insensitive: True if... | 9935285e3590d285aa97a3eaa6cd9bc17cc3fc32 | 24,423 |
def search(metadata, keyword, include_readme):
"""Search for the keyword in the repo metadata.
Args:
metadata (dict) : The dict on which to run search.
keyword (str) : The keyword to search for.
include_readme (bool) : Flag variable indicating whether
to search keyword inside th... | a7ff3900547518fbf3e774df8954d383ba1227b5 | 24,428 |
def format_moz_error(query, exception):
"""
Format syntax error when parsing the original query.
"""
line = exception.lineno
column = exception.col
detailed_message = str(exception)
msg = query.split('\n')[:line]
msg.append('{indent}^'.format(indent=' ' * (column - 1)))
msg.append(... | fb558e1c3149aa9191db76c153e24a9435f6bec3 | 24,430 |
def bitarray_to_bytes(b):
"""Convert a bitarray to bytes."""
return b.tobytes() | d4851f60a056953c3862968e24af5db5597e7259 | 24,431 |
def get_field_value(instance, field_name, use_get):
"""Get a field value given an instance."""
if use_get:
field_value = instance.get(field_name)
else:
field_value = getattr(instance, field_name, '')
return field_value | 71e89e9c0f52a71d78bc882d45ae2dda8100a1f7 | 24,435 |
def removesuffix(s, suffix):
"""
Removes suffix a string
:param s: string to remove suffix from
:param suffix: suffix to remove
:type s: str
:type suffix: str
:return: a copy of the string with the suffix removed
:rtype: str
"""
return s if not s.endswith(suffix) else s[:-len(su... | 7503e7ca390434936cdda8f706f5ca1eb7b80b98 | 24,437 |
def chomp(text):
""" Removes the trailing newline character, if there is one. """
if not text:
return text
if text[-2:] == '\n\r':
return text[:-2]
if text[-1] == '\n':
return text[:-1]
return text | 8813631dd201a281dd4d879b7ec8d87e9425b9c7 | 24,438 |
def to_list(inp):
""" Convert to list """
if not isinstance(inp, (list, tuple)):
return [inp]
return list(inp) | 55350d48bd578252213710fd4c5e672db8ba1f8e | 24,439 |
def get_ra(b, d):
"""
Converts birth and death to turnover and relative extinction rates.
Args:
b (float): birth rate
d (float): extinction rate
Returns:
(float, float): turnover, relative extinction
"""
return (b - d, d / b) | 64e6e9752c623b17745de92ecfe2ce96c43bc381 | 24,441 |
def all_angles_generator(board: list):
"""
This function is a generator for all angles of a board
>>> board = [\
"**** ****",\
"***1 ****",\
"** 3****",\
"* 4 1****",\
" 9 5 ",\
" 6 83 *",\
"3 1 **",\
" 8 2***",\
" 2 ****"]
>>> [a for a in all_angles_ge... | 3ea04a9b1aea2236e6bbc1595982cc8d50f9dbb3 | 24,446 |
def GetBraviasNum(center,system):
"""Determine the Bravais lattice number, as used in GenHBravais
:param center: one of: 'P', 'C', 'I', 'F', 'R' (see SGLatt from GSASIIspc.SpcGroup)
:param system: one of 'cubic', 'hexagonal', 'tetragonal', 'orthorhombic', 'trigonal' (for R)
'monoclinic', 'triclin... | 06c4c4f4ac2a0b915fb544df2f99a305e143cea2 | 24,453 |
def format_attribute(attribute):
"""Format a tuple describing an attribute.
:param attribute: attribute tuple, which may be either ``(key, value)`` or
``(value,)``.
:return: the formatted string
If given, `key` is either formatted as itself, if it's a `str`, or else as
``repr(key)``, and is ... | e5926e13da947240bf0efb215f2f75aad308c251 | 24,454 |
from typing import Iterator
from typing import Any
from typing import List
def take(it: Iterator[Any], n: int) -> List[Any]:
"""Take n elements of the iterator."""
return [next(it) for _ in range(n)] | d12b7a26e0bc7712174f75e99fd9a9103df1b86e | 24,455 |
def _text_choose_characters(player):
"""Display the menu to choose a character."""
text = "Enter a valid number to log into that character.\n"
characters = player.db._playable_characters
if len(characters):
for i, character in enumerate(characters):
text += "\n |y{}|n - Log into {}.... | 1a94934f838f3fcae85a62ac867191b630b39f3d | 24,456 |
def create_charm_name_from_importable(charm_name):
"""Convert a charm name from the importable form to the real form."""
# _ is invalid in charm names, so we know it's intended to be '-'
return charm_name.replace("_", "-") | 983c7b9796e8987c66d22aa01b9f3d273969f18a | 24,459 |
def find_null_net_stations(db, collection="arrival"):
"""
Return a set container of sta fields for documents with a null net
code (key=net). Scans collection defined by collection argument.
"""
dbcol = db[collection]
net_not_defined = set()
curs = dbcol.find()
for doc in curs:
i... | 582dc0a0b14e091e3b54fb3c2040669216ec4bf5 | 24,460 |
def FindApprovalValueByID(approval_id, approval_values):
"""Find the specified approval_value in the given list or return None."""
for av in approval_values:
if av.approval_id == approval_id:
return av
return None | d4e14ad235dae859559376a99d14bf1fe8156054 | 24,461 |
def get_nice_address(address):
"""
Take address returned by Location Service and make it nice for speaking.
Args:
address: Address as returned by Location Service Place Index.
Returns:
str: Spoken address.
"""
spoken_street = address['Street']
if spoken_street.endswith('St')... | bc18427d5453646e766185e1e347839fa4e1b168 | 24,462 |
def is_pure_word(text: str) -> bool:
"""
Words containing parentheses, whitespaces, hyphens and w characters are not considered as proper words
:param text:
:return:
"""
return "-" not in text and "(" not in text and ")" not in text and " " not in text and "w" not in text | af364ebaab38c17543db238169f3a26587c69eae | 24,463 |
def apply_substitution(subst_dict, cleaned_string):
""" Apply a substitution dictionary to a string.
"""
encoded_string = ''
# Slightly confusing, the get function will get the value of the
# key named letter or will return letter.
for letter in cleaned_string:
letter = letter.lower()
... | b823139dff91e02e5765670c645b1977f21340c8 | 24,466 |
def _merge_config(entry, conf):
"""Merge configuration.yaml config with config entry."""
return {**conf, **entry.data} | b29404005bfd7578999bb982da27a7291f186228 | 24,467 |
from typing import Set
import csv
def get_all_ids(filename: str) -> Set:
"""Function that returns the set of all ids of all items saved in the file.
Args:
filename (str): File where items are saved.
Returns:
Set: Set of ids.
"""
ids = set()
with open(filename, mode="... | 4d4ff1374d273dbdc0fc499e1b634ea2bf604b3d | 24,469 |
def and_list(items):
""" Create a comma-separated list of strings.
"""
assert isinstance(items, list)
match len(items):
case 0: return ''
case 1: return items[0]
case 2: return f'{items[0]} and {items[1]}'
case _: return ', '.join(items[0:-1]) + f', and {items[-1]}' | b0cea95bfe95d613986b6130fd7acabaef6a1d7c | 24,477 |
def set_optional_attr(in_args, classifier):
"""
This function applies all the optional commandline arguments. This is designed to
call after the instantiation of classifier object
Parameters:
in_args - This is parsed command line arguments
classifier - This is an object of type Flower_C... | b850ee150143d4727430f9d2077844fa687f26ee | 24,482 |
def modify_column(func, rows):
"""Apply 'func' to the first column in all of the supplied rows."""
delta = []
for columns in rows:
delta.append([func(columns[0])] + columns[1:])
return delta | 1362fd3a54df44a132e47563d8ffe2d472ceb934 | 24,491 |
def bool_from_native(value):
"""Convert value to bool."""
if value in ('false', 'f', 'False', '0'):
return False
return bool(value) | 5f9cbcef5c862b5a507d376ffca8d814acfee87b | 24,494 |
from typing import Counter
import math
def shannon_entropy(data):
"""Calculates shannon entropy value
Arguments:
data {string} -- the string whose entropy must be calculated
Returns:
[float] -- value that represents the entropy value on the data {string}
"""
p, lns = Counter(data... | d383054f33639136182751a6d884839595ec4efd | 24,500 |
def note_to_f(note: int, tuning: int=440) -> float:
"""Convert a MIDI note to frequency.
Args:
note: A MIDI note
tuning: The tuning as defined by the frequency for A4.
Returns:
The frequency in Hertz of the note.
"""
return (2**((note-69)/12)) * tuning | 55201b54e525966ee7f8133c217111b22a26d827 | 24,501 |
def _get_iso_name(node, label):
"""Returns the ISO file name for a given node.
:param node: the node for which ISO file name is to be provided.
:param label: a string used as a base name for the ISO file.
"""
return "%s-%s.iso" % (label, node.uuid) | 3d73236bfa2b8fab8af39b9a3083b540e93eb30d | 24,510 |
def open_file(file):
"""Open a file and read the content
"""
if not file:
return ''
content = ''
try:
with open(file, 'r+', encoding="utf-8") as f:
content = f.read()
except Exception as err:
print('Something wrong happened while trying to open the file ' + fi... | 0b0308256b2a68cdc5a84fad850cdaa086d3541d | 24,513 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.