content
stringlengths 39
9.28k
| sha1
stringlengths 40
40
| id
int64 8
710k
|
---|---|---|
def no_highlight(nick: str) -> str:
"""
Inserts a Unicode Zero Width Space into nick to prevent highlights
"""
return nick[0:1] + "\u200b" + nick[1:] | 53b365eb5dc6e762ca3091cb4566ef7de1fef226 | 252,507 |
def _set_to_None_if_empty(x):
"""
Helper function to clean up arguments: Returns None if x==None or
x is an empty container.
EXAMPLES::
sage: import sage.geometry.polyhedron.misc as P
sage: None == P._set_to_None_if_empty([])
True
sage: P._set_to_None_if_empty([1])
[1]
"""
if x is None: return x
x = list(x)
if len(x)==0: return None
return x | 39c2c6ec625baa2ca498a6283e7b18263c8f872e | 245,317 |
import re
def substitute(string, substitutions):
"""
Take each key in the substitutions dict. See if this key exists
between double curly braces in string. If so replace with value.
Example:
substitute("my name is {{name}}.",{version:1,name=John})
> "my name is John"
"""
for key, value in substitutions:
string = re.sub(re.escape("{{" + key + "}}"), value, string)
return string | 8afc8fafcc34bf138598f8f5cb24a7da6a9b79cf | 676,547 |
def noop(arg):
"""Do nothing, return arg"""
return arg | 0c79f4bb6fbfc440807d293daea14639d27d65d0 | 121,362 |
def shape_list_decompose(polyList):
"""Decompose a list of tuples containing the LON/LAT pairs defining a polygon
The result is the bounding box components of the polygon"""
# Pull Longitudes and Latitudes individually
lons = [i[0] for i in polyList]
lats = [i[1] for i in polyList]
return min(lons), min(lats), max(lons), max(lats) | af47f362e866ae7a327387f51068964c96218272 | 153,606 |
def search_linear(xs, target):
""" Find and return the index of target in sequence xs """
for (i, v) in enumerate(xs):
if v == target:
return i
return -1 | 91b719857decfe4818f2843ac1df6e423ea966ef | 670,236 |
def non_modal_dynamic_melt(Co, Do, F, P, phi):
"""
non_modal_dynamic_melt calculates the concentration of a liquid extracted via
dynamic melting as described in McKenzie (1985) and Zou (2007) Eq. 3.18. This is
applicable for a sitiuation in which melt is in equilibrium when the fraction
is below a critical value and then fractional when it is above that value.
Parameters
----------
Co : array-like
Concentration of trace element in original solid
Do : array-like
Bulk distribution coefficient for element when F = 0
F : array-like
fraction of original solid melted (fraction of melt)
P : array-like
Bulk distribution coefficient of melting mineral assemblage
phi : array-like
critical mass porosity of residue
Returns
-------
Cl : array-like
Concentration of trace element in the liquid
"""
X = (F - phi) / (1 - phi)
Cl = (Co / X) * (
1
- (1 - ((X * (P + phi * (1 - P))) / (Do + phi * (1 - P))))
** (1 / (phi + (1 - phi) * P))
)
return Cl | fa6b84a276001a3816300cc94f56a80de6599acd | 308,535 |
def remove_item(thislist, item):
"""
Remove item from list without complaining if absent
@param thislist : list of items
@param item : item which may or may not be in the list
@return: reduced list
"""
try:
thislist.remove(item)
except ValueError:
pass
return thislist | e26b5292ac54f993cfe3e892e6416342fedc23f0 | 540,244 |
def find_vout_for_address_from_txobj(tx_obj, addr):
"""
Locate the vout index of the given transaction sending to the
given address. Raises runtime error exception if not found.
"""
for i in range(len(tx_obj["vout"])):
if any([addr == a for a in tx_obj["vout"][i]["scriptPubKey"]["addresses"]]):
return i
raise RuntimeError("Vout not found for address: txid={}, addr={}".format(tx_obj['txid'], addr)) | 62d5499337ee31294bc0da1adfdf6d2b5ceb2d3a | 445,673 |
def to_snake_case(input_string):
"""
Converts a string into a snake case.
:param input_string: Input string
:return: Snake case string
:rtype: str
"""
final = ''
for item in input_string:
if item.isupper():
final += "_"+item.lower()
else:
final += item
if final[0] == "_":
final = final[1:]
return final | e32e16da10c157c3eb2d34df19aab2052db53ec2 | 336,872 |
def drop_counts(df, threshold):
"""Removes rows from an ngram table with counts fewer than threshold.
Arguments:
df {Pandas dataframe} -- ngram table with columns "word" and "count"
threshold {Integer} -- minimum count to keep rows
"""
dropped_df = df[df['count'] >= threshold]
return dropped_df | 1b8f87b28043d7ad76e0e04e6672906eb1159dec | 351,130 |
def midpoint(a, b):
"""Calculate midpoint between two points."""
middle = []
for i in range(len(a)):
middle.append(round((a[i]+b[i])/2))
return tuple(middle) | 29174e31d00e9a30cfed8c5737c155be8b66aba3 | 329,715 |
def UnclippedObjective(probs_ratio, advantages):
"""Unclipped Objective from the PPO algorithm."""
unclipped_objective = probs_ratio * advantages
return unclipped_objective | d04775c34c86e64e32a6d5e29d5ad1648e618577 | 477,229 |
def get_windows_version(windows_version: str = 'win7') -> str:
"""
valid windows versions : 'nt40', 'vista', 'win10', 'win2k', 'win2k3', 'win2k8', 'win31', 'win7', 'win8', 'win81', 'win95', 'win98', 'winxp'
>>> import unittest
>>> assert get_windows_version() == 'win7'
>>> assert get_windows_version('nt40') == 'nt40'
>>> unittest.TestCase().assertRaises(RuntimeError, get_windows_version, windows_version='invalid')
"""
valid_windows_versions = ['nt40', 'vista', 'win10', 'win2k', 'win2k3', 'win2k8', 'win31', 'win7', 'win8', 'win81', 'win95', 'win98', 'winxp']
if not windows_version:
windows_version = 'win7'
windows_version = windows_version.lower().strip()
if windows_version not in valid_windows_versions:
raise RuntimeError('Invalid windows_version: "{windows_version}"'.format(windows_version=windows_version))
return windows_version | 1fbc01c011f2eff93187503247ae769d3aa3b5ad | 448,566 |
def create_new_features(clean_df):
"""
Function to create new features using the cleansed data
clean_df (DataFrame) : DataFrame which is used to create new features
return (DataFrame) : DataFrame with the derived features
"""
# Convert gender feature to numbers
genders = {"male": 0, "female": 1}
clean_df['Sex'] = clean_df['Sex'].map(genders)
# Keep only these columns for modeling
X_cols = ['Passenger_Class', 'Sex', 'SibSp', 'Parch', 'Fare']
Y_col = ["Survived"]
# Subsetting and keeping only those columns
req_df = clean_df[X_cols+Y_col].copy()
return req_df | 42fcee1968b99fd9e10bfde28ce87f20824328e1 | 583,724 |
from typing import Mapping
from typing import Any
from typing import Tuple
from typing import List
from typing import Union
def flatten_dict(
d: Mapping[str, Any], prefix: Tuple[str, ...] = ()
) -> List[Tuple[str, Union[int, float, str]]]:
"""Returns a sequence of flattened (k, v) pairs for tfsummary.hparams().
Args:
d: A dict-like object that has an `.item()` method.
prefix: Prefix to add to keys in `d`.
Returns:
Sequence of (k, v) pairs where k is the flattened key with individual
subkeys separated by dots. `None` values are replaced by the empty string.
"""
ret = []
for k, v in d.items():
# Note `ml_collections.ConfigDict` is not (yet) a `Mapping`.
if isinstance(v, Mapping) or hasattr(v, "items"):
ret += flatten_dict(v, prefix + (k,))
elif isinstance(v, (list, tuple)):
ret += flatten_dict({str(idx): value for idx, value in enumerate(v)},
prefix + (k,))
else:
ret.append((".".join(prefix + (k,)), v if v is not None else ""))
return ret | 311c703342e78f7b9d94783f02df2e6b500a6d89 | 473,287 |
def knotvector_normalize(knotvector=()):
""" Normalizes the input knot vector between 0 and 1.
:param knotvector: input knot vector
:type knotvector: tuple
:return: normalized knot vector
:rtype: list
"""
if len(knotvector) == 0:
return knotvector
first_knot = float(knotvector[0])
last_knot = float(knotvector[-1])
knotvector_out = []
for kv in knotvector:
knotvector_out.append((float(kv) - first_knot) / (last_knot - first_knot))
return knotvector_out | 5e3b5ff584a57214bef570697f534a9a62aad324 | 351,506 |
def db_to_ls_classification_labels(db_label: dict) -> dict:
"""Function to convert database classification labels to labelstudio labels.
Args:
db_label (dict): Dictionary contains labels as keys with associated bool values.
Returns:
dict: Returns dictionary with key "choices" and a list of all labels which were evaluated as true.
"""
ls_label = []
for target, value in db_label.items():
if value == 1:
ls_label.append(target)
return {"choices": ls_label} | 4c58f2cff63da337273f1f31c419719e90b712fe | 242,425 |
import mpmath
def sf(x, xi, mu=0, sigma=1):
"""
Generalized extreme value distribution survival function.
"""
xi = mpmath.mpf(xi)
mu = mpmath.mpf(mu)
sigma = mpmath.mpf(sigma)
# Formula from wikipedia, which has a sign convention for xi that
# is the opposite of scipy's shape parameter.
if xi != 0:
t = mpmath.power(1 + ((x - mu)/sigma)*xi, -1/xi)
else:
t = mpmath.exp(-(x - mu)/sigma)
return -mpmath.expm1(-t) | cdf2b32c37e3b953115f7870d65ec0a882e2252c | 344,701 |
def to_float(value: str) -> float:
"""Convert value to a floating point number"""
return float(value) | b6143a9211cd385bfd4ff6f171e01ce1a584b781 | 656,197 |
from typing import Counter
def total_useful_clusters(model):
"""A useful cluster here is defined as being a cluster with > 1 member."""
clusters = Counter(model.labels_)
useful_clusters = 0
for cluster_num, total_members in clusters.items():
if total_members > 1:
useful_clusters += 1
return useful_clusters | 93df3354c37f5f252f2071b50b7937c61ce81946 | 31,333 |
def atomic_min(ary, i, v):
"""
Atomically, perform `ary[i] = min(ary[i], v)` and return the previous value of `ary[i]`.
This operation does not support floating-point values.
i must be a simple index for a single element of ary. Broadcasting and vector operations are not supported.
This should be used from numba compiled code.
"""
orig = ary[i]
ary[i] = min(ary[i], v)
return orig | e8fbd4c193d9526a386e431aea41415fe3975a22 | 566,653 |
def list_of_langs(data):
"""Construct list of language codes from data."""
lang_codes = []
for lang_data in data:
lang_codes.append(lang_data.get('value'))
return lang_codes | e65504175c59ec10dd55b1f932b1ece263253266 | 448,256 |
def build_url(base, endpoint, params):
"""Build URL using base, endpoint and params.
Args
:endpoint: text format string
:params: dict
"""
url = base + endpoint.format(params)
return url | e061e1a1b1ae4eac436988f932331c9e9f337aaf | 216,400 |
def train_test_split(windows, labels, size=.2):
"""
Splits windows and labels into train and test splits.
"""
split_size = int(len(windows) * (1-size))
window_train = windows[:split_size]
window_test = windows[split_size:]
label_train = windows[:split_size]
label_test = windows[split_size:]
return window_train, window_test, label_train, label_test | 0ec24566e09db53860afd1e628ec66385e7ce4a3 | 47,408 |
def contains_any(a, bs):
"""Returns true if any of the strings in list bs are found
in the string a"""
for b in bs:
if b in a: return True
return False | 0c768d46e0c3fc0b9776ba3131c6161cbaf4618a | 527,641 |
def get_layer_inbound_count(layer):
"""Returns the number inbound nodes of a layer."""
return len(layer._inbound_nodes) | d7739bc8c9dd7ed3c2c712a8869a84646eac2b43 | 430,879 |
def game_moves(board):
"""
Returns the list of all legal moves available from the current position.
Moves are represented directly as the resulting game positions.
If the game is over, it returns an empty list.
"""
LINES = ((0,1,2),(1,2,3),(4,5,6),(5,6,7),(8,9,10),(9,10,11),(0,4,8),
(1,5,9),(2,6,10),(3,7,11),(0,5,10),(1,6,11),(2,5,8),(3,6,9))
# If the game is over: return an empty list
if any(0 < board[x] == board[y] == board[z] for x,y,z in LINES): return []
# Otherwise: compute and return a list with all the legal moves
moves = []
for i in range(12):
if board[i] < 3:
moves.append(tuple(b+1 if i==j else b for j,b in enumerate(board)))
return moves | 68639f482aba48468588b41862c5623f60b0bcde | 324,538 |
import requests
def get_remote_file_content(file_url, **kwargs):
"""Gets the contents of a remote file.
Will throw an error if the remote file can't be downloaded,
or if the file content can't be decoded by bytes.decode()"""
return requests.get(file_url).content.decode() | 40338b94344a192860d5d6e7442098424b54fb58 | 474,046 |
import hashlib
def compute_md5(file_name, chunk_size=65536):
"""
Compute MD5 of the file.
Parameters:
file_name (str): file name
chunk_size (int, optional): chunk size for reading large files
"""
md5 = hashlib.md5()
with open(file_name, "rb") as fin:
chunk = fin.read(chunk_size)
while chunk:
md5.update(chunk)
chunk = fin.read(chunk_size)
return md5.hexdigest() | b9d1718bf9f83eb3568a2dc5d913e318298ddf91 | 451,380 |
def remove_duplicates(my_list):
"""
Creates a new list with just the first occurrence of any repeated item
"""
result = []
for item in my_list:
if item not in result:
result.append(item)
return result | 8f60847fbc922d94fd2f01348cf371010e18dd89 | 182,481 |
def equal_dicts(d1: dict, d2: dict, ignore_keys: list):
"""Check two dictionaries for equality with the ability to ignore
specific keys.
Source: https://stackoverflow.com/a/10480904/6942666
Args:
d1 (dict): the first dictionary
d2 (dict): the second dictionary
ignore_keys (list): a list of strings with keys to ignore
Returns:
bool: whether the dicts are equal
"""
d1_filtered = {k: v for k, v in d1.items() if k not in ignore_keys}
d2_filtered = {k: v for k, v in d2.items() if k not in ignore_keys}
return d1_filtered == d2_filtered | 12e61cc13952543669aef6d9524aaf76d65451b3 | 530,731 |
import getpass
def get_mysql_pwd(config):
"""Get the MySQL password from the config file or an interactive prompt."""
# Two ways to get the password are supported.
#
# 1. Read clear-text password from config file. (least secure)
# 2. Read password as entered manually from a console prompt. (most secure)
# First try the config file. This is the least secure method. Protect the file.
#mysql_pwd = config.get('mysql', 'mysql_pwd', 0)
mysql_pwd = config['mysql'].get('mysql_pwd')
# Try other method if config file password is blank or missing.
if mysql_pwd == '':
# Prompt for the password. More secure, but won't work unattended.
mysql_pwd = getpass.getpass()
return(mysql_pwd) | 3077fca733739d1d0648e555fa2a485a31cc3d8a | 676,026 |
def verify_ico(bin: str) -> bool:
"""Check whether IČO number is valid
https://phpfashion.com/jak-overit-platne-ic-a-rodne-cislo
:param bin: string of the BIN number
:retun: bool
"""
if isinstance(bin, str):
if not bin.isnumeric() or len(bin) > 8:
return False
# pad with zeros from left to length 8 (123456 -> 00123456)
bin.rjust(8, "0")
else:
raise ValueError(f"'BIN' must be an instance of 'str', not '{type(bin)}'")
a = 0
for i in range(7):
a += int(bin[i]) * (8 - i)
a %= 11
if a == 0:
c = 1
elif a == 1:
c = 0
else:
c = 11 - a
return int(bin[7]) == c | 5810c8f65fbbf541faf2d811f808ad44652b6693 | 84,404 |
def disabled(fun):
""" A decorator to disable a test. """
def decorator(*args, **kwargs):
pass
return decorator | eef7dbdb0797a78691b0b0aa59c7244477e6f8f3 | 200,475 |
def is_prebuffer() -> bool:
"""
Return whether audio is in pre-buffer (threadsafe).
Returns
-------
is_prebuffer : bool
Whether audio is in pre-buffer.
"""
is_prebuffer = bool(RPR.Audio_IsPreBuffer()) # type:ignore
return is_prebuffer | 8afa4979578be310fd71b22907c99bb747780454 | 705,308 |
def create_brake_enable_soul(packer, apply_brake):
"""Creates a CAN message for the Honda DBC BRAKE_COMMAND."""
brake_rq = apply_brake > 0
if brake_rq == True:
x = 0xCC05
else:
x = 0x0000
values = {
"BRAKE_ENABLE_magic": x,
}
print("kiacan.py soul_brake_enable")
print(values)
return packer.make_can_msg("SOUL_BRAKE_ENABLE", 0, values) | 233e50ba0669c0b9358d8ee810179d74a4b32f54 | 414,507 |
def has_permission(user, proposal, speaker=False, reviewer=False):
"""
Returns whether or not ther user has permission to review this proposal,
with the specified requirements.
If ``speaker`` is ``True`` then the user can be one of the speakers for the
proposal. If ``reviewer`` is ``True`` the speaker can be a part of the
reviewer group.
"""
if user.is_superuser:
return True
if speaker:
if (user == proposal.speaker.user or
proposal.additional_speakers.filter(user=user).exists()):
return True
if reviewer:
if user.groups.filter(name="reviewers").exists():
return True
return False | b62a06036415e374e29afbd9cd78a4ec46ec1454 | 418,028 |
from typing import Any
def is_view_object(input_object: Any) -> bool:
"""Returns a boolean whether an object is a view object or not.
Args:
input_object (object): an object that is to be tested whether or
not it is a View object.
Returns:
True if it is a View object, False otherwise.
"""
if not hasattr(input_object, 'lazyload_data'):
return False
if not hasattr(input_object, 'query_dsl'):
return False
if not hasattr(input_object, 'name'):
return False
if not hasattr(input_object, 'query_filter'):
return False
return True | 34405b882be8dc6b82cfc19ebef427a3943d73a0 | 70,611 |
def get_presets(ctx):
"""
Get the valid setup string presets in the current context.
"""
presets = {}
if ctx.guild:
presets.update(ctx.client.config.guilds.get(ctx.guild.id, "timer_presets") or {}) # Guild presets
presets.update(ctx.client.config.users.get(ctx.author.id, "timer_presets") or {}) # Personal presets
return presets | 594e4724413d18db030f04b65eb48bc7f67520b5 | 602,685 |
def unpack(n, x):
"""Unpacks the integer x into an array of n bits, LSB-first, truncating on overflow."""
bits = []
for _ in range(n):
bits.append((x & 1) != 0)
x >>= 1
return bits | 04c6566da527f9c362fbffa64a1d77d49a24f411 | 231,205 |
import struct
def short_to_bytes(short_data):
"""
For a 16 bit signed short in little endian
:param short_data:
:return: bytes(); len == 2
"""
result = struct.pack('<h', short_data)
return result | 26eeb2de936fa6b434c724ef80c008d93aec0446 | 698,806 |
from pathlib import Path
def make_wrapper_name(path: Path) -> str:
"""Return an escaped filename to be used in source wrappers.
Reverses the order of parts from the original filepath for
easier readability
"""
escaped = '_'.join(reversed(path.parts))
for char in '. /':
escaped = escaped.replace(char, '_')
return escaped + '.sh' | 0b82b5b22071a700103c07cf2d0d9cbfdf582de4 | 575,694 |
def maybe_coeff_key(grid, expr):
"""
True if `expr` could be the coefficient of an FD derivative, False otherwise.
"""
if expr.is_Number:
return True
indexeds = [i for i in expr.free_symbols if i.is_Indexed]
return any(not set(grid.dimensions) <= set(i.function.dimensions) for i in indexeds) | acc21eb144ea24a6a96b56ceed12f81696430976 | 674,985 |
from typing import Dict
from typing import Type
def filter_classes_from_module(
classes: Dict[str, Type], module_name: str
) -> Dict[str, Type]:
"""Restrict the given classes to the one found in the given module.
Parameters
----------
classes : Dict[str, Type]
A dict of classes from which to extract the ones to return. Full python path as keys, and
the classes as values.
module_name : str
The python path of the module for which we want the classes
Returns
-------
Dict[str, Type]
The filtered `classes` (same format as the given `classes` argument)
"""
prefix = f"{module_name}."
return {
class_name: klass
for class_name, klass in classes.items()
if class_name.startswith(prefix)
} | 47cf45d476b91e98932ad9c5c7f6bbd16b9042db | 543,022 |
def invert(array):
"""return a dictionary mapping array values to arrays of indices
containing those values
"""
inverted_array = {}
for i, val in enumerate(array):
inverted_array.setdefault(val, []).append(i)
return inverted_array | ed04b2cf90d0ec07d96f4153f6a793c780397eb9 | 40,075 |
import torch
def split_heads(x: torch.Tensor, num_heads: int) -> torch.Tensor:
"""Split input tensor into multiple attention heads
(Batch size, Length, Attention size) => (Batch size, Heads, Lengths, Attention size / Heads)
Args:
x (torch.Tensor): [B, L, A] input tensor
num_heads (int): number of heads
Returns:
torch.Tensor: [B, H, L, A/H] Splitted / reshaped tensor
"""
batch_size, max_length, attention_size = x.size()
head_size = int(attention_size / num_heads)
return x.view(batch_size, max_length, num_heads, head_size).permute(0, 2, 1, 3) | f2061462edded740f0a17901380b231a4257909f | 537,256 |
def string_to_list(s, append=""):
"""
This function is used to store lists of strings in SQLDB because it cannot store a list, it is stored as a single string
Args:
str: takes the list of responses as a whole string
append: text that you want to add to the list of strings
Returns: a list of strings
"""
str_list = s.split(":.:.:")
if str_list[-1] == "":
str_list.pop()
if append != "":
str_list.append(append)
return str_list | 01d2e82fca7c83c6cdb90ecf799b395a112ddb81 | 474,265 |
def to_vartype(input, default=None, vartype=str):
"""
Returns input converted to vartype or default if the conversion fails.
Parameters
----------
input : *
Input value (of any type).
default : *
Default value to return if conversion fails.
vartype : data type
Desired data type. (default: string)
Returns
-------
output : vartype or type(default)
Input converted to vartype data type or default.
"""
if vartype == bool and input == 'False': return False # special custom case
try:
try:
return vartype(input)
except ValueError: return vartype(eval(input))
except: return default | 66dcf57e7af7d4e63e776cf5f88583250b729090 | 476,587 |
from typing import Set
def parse_git_diff(diff_str: str) -> Set[str]:
"""
Return parsed output of `git-diff --name-only`.
Arguments
---------
diff_str : str
Output of `git-diff --name-only`.
Returns
-------
set of str
Unique set of files changed, according to git-diff
"""
return set(map(str.strip, diff_str.strip().split("\n"))) | e40ce32bb53e2d29d4f6d62f8bc2c0159504c4ac | 528,113 |
def _get_item2_names(nstrm, reachinput, isfropt, structured=False):
"""
Determine which variables should be in item 2, based on model grid type,
reachinput specification, and isfropt.
Returns
-------
names : list of str
List of names (same as variables in SFR Package input instructions) of
columns to assign (upon load) or retain (upon write) in reach_data
array.
Notes
-----
Lowercase is used for all variable names.
"""
names = []
if structured:
names += ["k", "i", "j"]
else:
names += ["node"]
names += ["iseg", "ireach", "rchlen"]
if nstrm < 0 or reachinput:
if isfropt in [1, 2, 3]:
names += ["strtop", "slope", "strthick", "strhc1"]
if isfropt in [2, 3]:
names += ["thts", "thti", "eps"]
if isfropt == 3:
names += ["uhc"]
return names | 515907f182c00800bc26ef898e445212b8be4563 | 288,971 |
import re
def format_wsl_path(path: str) -> str:
"""Format windows path to the WSL equivalent
Args:
path (str): Windows path to convert
Returns:
str: WSL path, i.e. /mnt/c/my/path.sh
"""
out_path = path.replace("\\", "/", -1)
if re.search("^[a-z]:/", out_path, re.IGNORECASE):
drive, _, rest = out_path.partition(":")
out_path = f"/mnt/{drive.lower()}{rest}"
return out_path | 71f37009404c2875b9694b2ef8f98085a5c13542 | 478,693 |
def format_repository_listing(repositories):
"""Returns a formatted list of repositories.
Args:
repositories (list): A list of repositories.
Returns:
The formated list as string
"""
out = ""
i = 1
for r in repositories:
out += (f"{i:>4} {r.get('name', '??')}\n"
f" {r.get('description', '-')}\n"
f" {r.get('url', '??')}\n\n")
i += 1
return out | f046889948889d5a5aaa7e99bce805f1f10f32a3 | 660,769 |
def dummy_token_file(tmpdir):
"""
Simulate a token file.
"""
# Refer to https://docs.pytest.org/en/6.2.x/tmpdir.html#the-tmpdir-fixture for tmpdir usage
token_file = tmpdir.join("dummy_token_file.txt")
token_file.write("top_secret_auth_token")
return token_file | c910038c976a247b8fb6f7e3ef90c6282f9ab3a7 | 432,081 |
def line_filter_and_transform(filter_re, transform_re, repl, lines):
"""
Transform and filter lines.
Filter out lines that match filter_re.
Transform remaining lines by transform_re and repl as a regular
expression replace. If the regular expression is not matched, then
the line is output as is.
"""
output = []
for line in lines:
match = filter_re.match(line)
if match:
# Drop line matching filter_re
continue
output.append(transform_re.sub(repl, line))
return output | 3b9febdc4b7e7772042e136db04f6d164827dc21 | 181,148 |
def _stanza_handler(element_name, stanza_type, payload_class, payload_key,
usage_restriction):
"""Method decorator generator for decorating <message/> or <presence/>
stanza handler methods in `XMPPFeatureHandler` subclasses.
:Parameters:
- `element_name`: "message" or "presence"
- `stanza_type`: expected value of the 'type' attribute of the stanza
- `payload_class`: payload class expected
- `payload_key`: payload class specific filtering key
- `usage_restriction`: optional usage restriction: "pre-auth" or
"post-auth"
:Types:
- `element_name`: `unicode`
- `stanza_type`: `unicode`
- `payload_class`: subclass of `StanzaPayload`
- `usage_restriction`: `unicode`
"""
def decorator(func):
"""The decorator"""
func._pyxmpp_stanza_handled = (element_name, stanza_type)
func._pyxmpp_payload_class_handled = payload_class
func._pyxmpp_payload_key = payload_key
func._pyxmpp_usage_restriction = usage_restriction
return func
return decorator | 8614952f9101f3613a2f8a0e6de6b2fe58c22c44 | 636,322 |
import hashlib
def hash_text(text, algo='sha1'):
"""Return the hash value for the text."""
h = hashlib.new(algo)
h.update(text)
return h.hexdigest() | 330ea67d3291ddfc1d227697a62efcc848a5c447 | 596,247 |
from pathlib import Path
from typing import Dict
from typing import Any
import toml
def load_toml(path: Path) -> Dict[str, Any]:
"""Load a TOML file to create a dictionary."""
return toml.load(path) | b41e2cdb93d6e195b2050e168e430477299aa45b | 283,910 |
def may_view_cronjobs_not_logged_in(app, identity, model, permission):
""" Cronjobs are run anonymously from a thread and need to be excluded
from the permission rules as a result.
"""
return True | 21d6e7f999e94c5aa8b88af6378906e632144e49 | 40,132 |
def compute_etan(sch1, sch2, cos2phi, sin2phi):
"""Compute tangential ellipticity."""
return - (sch1 * cos2phi + sch2 * sin2phi) | 87c3a2831847604b88110b6c4c58aac2c73cce4d | 622,753 |
def _filter_repeating_nonalnum(phrase, length):
"""
Check if a given phrase has non repeating alphanumeric chars
of given length.
Example: 'phrase $$$' with length=3 will return False
"""
if len(phrase) > 0:
alnum_len = length
for t in phrase:
if not t.is_alpha:
alnum_len -= 1
else:
alnum_len = length
if alnum_len == 0:
return None
return phrase | 723507022fd66fba3df8d708df4740e9aee08920 | 86,661 |
def lerp_color(cold, hot, t):
"""
Linearly interpolates between two colors
Arguments:
color1 - RGB tuple representing a color
color2 - RGB tuple representing a color
t - float between 0 and 1
"""
r1, g1, b1 = cold
r2, g2, b2 = hot
r = int(r1 + (r2 - r1) * t)
g = int(g1 + (g2 - g1) * t)
b = int(b1 + (b2 - b1) * t)
return (r, g, b) | 91ab55ef58adad0278c0666d7b48ad5969d0025f | 486,926 |
import re
def section_exists(filename, version, print_message=True):
"""
Check given file for existing section with specified version.
"""
for i, line in enumerate(open(filename)):
if re.search(r'^## ' + version, line):
if print_message:
print(" Existing section for v{0} found,"
.format(version), end=" ")
return True
return False | 6b26a719c549f6ad2e94f16e2b47d48f23498e74 | 187,384 |
from typing import List
def tokenize_sentence(sentence: str) -> List[str]:
"""
Split sentence into tokens by spaces.
:param sentence: Sentence string.
:return: List of tokens.
"""
tokens = sentence.split()
return ["###LEFT-WALL###"] + tokens if tokens[0] != r"###LEFT-WALL###" else tokens | 52dbcf3fc455c25b2b6ab63e69dec350f5f84b8e | 610,731 |
from typing import Dict
from typing import Any
from typing import List
def invert_dict_of_lists(dict_of_lists: Dict[Any, List[Any]]) -> Dict[Any, Any]:
"""
Given a dictionary mapping x -> [a, b, c], invert such that it now maps all a, b, c -> x.
If same value in multiple keys, then inverted dictionary overwrites arbitrarily.
Parameters
----------
dict_of_lists:
Input dictionary of lists.
Returns
-------
Inverted:
Output inverted dictionary.
"""
inverted = {}
for key, val in dict_of_lists.items():
for item in val:
inverted[item] = key
return inverted | 084f88863945cb13d2690c5713885171eca17008 | 165,079 |
import re
def get_eq_and_vals(filtered_sentence, variables, unclean_eq):
"""Parses and separates the equation part from the values in the string
INPUTS
=======
filtered_sentence: a list of tokenized strings from the original equation
variables: list of the user defined variables
unclean_eq: essentially the version of the first input without stop the words
RETURNS
========
string: the equation part
list: the variables and the values in the list
EXAMPLES
=========
>>> filtered_sentence = parse_sentence('x^2 + 2x when x is 1')
>>> get_eq_and_vals(filtered_sentence, ['x', 'y'], 'x^2+2xx1')
>>> ('x^2 + 2x', ['x', '1'])
"""
regex_vars = ''
for var in variables:
regex_vars += var + '\d+\.*\d*'
var_val_str = re.findall(regex_vars,unclean_eq)[0]
print('vvs', var_val_str)
values = [i for i in re.findall('\d*\.*\d*', var_val_str) if i !='']
print('vars_vals', values)
equation = ''
final_eq = ''.join(filtered_sentence)
for i in final_eq.split(var_val_str):
if i != '':
equation = i
return equation, values | 411e587f7ae36f09c5f69d0580f48a628610a487 | 246,323 |
def bytesToWord(high, low):
"""Convert two byte buffers into a single word value
shift the first byte into the work high position
then add the low byte
Args:
high: byte to move to high position of word
low: byte to place in low position of word
Returns:
word: the final value
Raises:
None
"""
word = (high << 8) + low
return word | 762b6c1fedb36e18b23adc3023a4334b4ad268df | 205,855 |
import json
def json_format(text: str) -> str:
"""Simple utility to parse json text and format it for printing.
"""
obj = json.loads(text)
return json.dumps(obj, indent=4, sort_keys=True) | bc7e613287d23f1c51ec8c6c825b5422316d71a0 | 665,501 |
def PyDict_Items(space, w_obj):
"""Return a PyListObject containing all the items from the
dictionary, as in the dictionary method dict.items()."""
return space.call_method(space.w_dict, "items", w_obj) | 1ed26f4bb9f9631b85356473f351196ad54d06af | 326,053 |
def set_md_table_font_size(row, size):
"""Wrap each row element with HTML tags and specify font size"""
for k, elem in enumerate(row):
row[k] = '<p style="font-size:' + str(size) + '">' + elem + '</p>'
return row | f6607aa3e882b6a698ae4609262293fc05f5e3a9 | 474,105 |
def separate_content_and_variables(text, boundary='{# /variables #}'):
"""Separate variables and content from a Markdown file"""
# Find boundary
pos = text.find(boundary)
# Text contains variables
if pos > 0:
return(text[:pos].strip(), text[(pos + len(boundary)):].strip())
# Text does not contain variables
return ('', text) | 795579dcdb397d10fbf8abdf3a83d81136bea82f | 354,119 |
def rescale(low_res, high_res):
"""
Function that rescales the pixel values of high_res to the -1 to 1 range.
For use with the generator output tanh function.
Args:
low_res: The tf tensor of the low res image.
high_res: The tf tensor of the high res image.
Returns:
low_res: The tf tensor of the low res image, rescaled.
high_res: The tf tensor of the high res image, rescaled.
"""
high_res = high_res * 2.0 - 1.0
return low_res, high_res | d829ecc48e20fa5bde2c0829a131c733c13cae1d | 548,847 |
def acmg_classification2(entry):
"""Return ACMG classification from entry, if any"""
if entry.class_override:
return entry.class_override
elif entry.class_auto:
return entry.class_auto
else:
return None | 1ec575031b724714eea12973b454a2cee593639a | 469,877 |
def convert_string2bytes(string: str):
"""Converts a "str" type object into a "bytes" type object
Examples:
>>> convert_string2bytes('nice string')\n
b'nice string'
"""
return string.encode() | 679592dd0894cf91e76456b63e0325c9aa17270b | 469,775 |
def add(x, y):
"""An addition endpoint."""
return {"result": x + y} | df8ac1c6977bc24d5f6204f464c77c4bd7c82983 | 427,848 |
def concat(str1: str, str2: str) -> str:
"""
Returns the concatenation of 2 strings. A string
with null value is considered as an empty string.
"""
if str1 and str2:
return "{} ~ {}".format(str1, str2)
if not str1 and str2:
return str2
if str1 and not str2:
return str1
return "" | 2ef5123c5adb1a38c341c4545b7a48d2bb87ae60 | 515,552 |
def dict_contains(keys: tuple, check_dict: dict) -> bool:
"""
Check if a dictionary contains all of the desired keys.
"""
for key in keys:
if not key in check_dict:
return False
return True | 3a8548256aef09fc6e24f714207734f2093a30a3 | 129,011 |
def _clean_key(root_key, filekey):
"""Return the cleaned key 'filekey', using 'root_key' as the root
Args:
root_key (str): root_key for accessing object store
filekey (str): filename to access in object store
Returns:
str: Location to access the file
"""
if root_key:
return "%s/%s" % (str(root_key), str(filekey))
else:
return str(filekey) | bf39e95a182506900b0cdb110f1fea2566e85520 | 686,068 |
def proxy_result_as_dict(obj):
"""
Convert SQLAlchemy proxy result object to list of dictionary.
"""
return [{key: value for key, value in row.items()} for row in obj] | 6e7244fa47553d234fba4568d41110d095330704 | 689,897 |
def topic_ref_transform(ref_string, topic):
"""
Converts a topic string with forward-slashes into a JSON reference-friendly format
("/" becomes "~1"), then places the new string into the provided base reference path.
:param ref_string: The base reference path
:param topic: The DXL topic string to convert
"""
return str(ref_string.format(topic.replace("/", "~1"))) | b80071faed0e9bc3a4c8b06453e84c385012b532 | 636,901 |
from typing import Union
import hashlib
def hashsum_str(x: Union[str, bytes], algo=None) -> str:
"""Compute the hash sum of the given string / bytes ; default algorithm is Sha1"""
if algo is None:
algo = hashlib.sha1
elif isinstance(algo, str):
algo = getattr(hashlib, algo)
else:
assert callable(algo), f'`algo` must be a hashlib algorithm name or a callable'
if isinstance(x, str):
x = x.encode('utf-8')
return algo(x).hexdigest() | 348d5b5a5f299f0a40129ef2ccd329b59224e1b8 | 378,480 |
async def is_nsfw_or_private_predicate(ctx):
"""A predicate to test if a channel is NSFW or private
:param ctx: The context of the predicate
"""
return not ctx.guild or ctx.channel.is_nsfw() | 71ea83e063cfe744ea384fb5e298b112d61c69de | 567,348 |
def force_list(value):
"""
Coerce the input value to a list.
If `value` is `None`, return an empty list. If it is a single value, create
a new list with that element on index 0.
:param value: Input value to coerce.
:return: Value as list.
:rtype: list
"""
if value is None:
return []
elif type(value) == list:
return value
else:
return [value] | 24e4876ad650447a1860efbfefcf0881f856aa21 | 405,147 |
def count_pairs(char_list):
"""Generate pair counts for all pairs of codes in char_list.
Parameters
----------
char_list: list of arrays of int64
A list of encoded arrays for which pairs will be counted
Returns
-------
pair_counts: dict of pairs to int
A dictionary mapping pairs of codes to the count of the total
number of occurrences of the pair in encoded arrays.
"""
result = {}
for array in char_list:
for i in range(array.shape[0] - 1):
pair = (array[i], array[i + 1])
if pair in result:
result[pair] += 1
else:
result[pair] = 1
return result | 430a5be813f3c647ad6b40c95816215b855e21af | 459,210 |
import re
import string
def validate_word(word, text):
"""Check if something is a valid "word" submission with previous existing text.
Return (valid, formatted_word, message), where valid is a boolean, formatted_word is
the word ready to be added to existing text (adding a space if applicable for example), and
message is an error message if the word was not valid.
It can be a word, or ?, !, . for now. Can make it a little more complicated later."""
if not text:
if re.fullmatch("[a-zA-Z']+", word):
return (True, string.capwords(word), "")
else:
return (False, "", "Story must begin with a word")
if word == "":
return (False, "", "You have to write something!")
if re.fullmatch("[a-zA-Z']+", word):
if text[-1] in ["?", ".", "!", "\n"]:
return (True, (' ' + string.capwords(word)), "")
else:
return (True, (' ' + word), "")
if re.fullmatch("\-[a-zA-Z']+", word):
if not text[-1].isalpha():
return (False, "", "You can only hyphenate after a word.")
if re.search("\-'", word):
return(False, "", "An apostrophe cannot directly follow a hyphen.")
else:
return (True, word, "")
if re.search(",", word):
if re.fullmatch(", [a-zA-Z']+", word):
if text[-1].isalpha():
return (True, word, "")
else:
return (False, "", "A comma can only come after a word.")
else:
return (False, "", "Invalid comma use.")
if word in ["?", ".", "!"]:
if text[-1].isalpha():
return (True, word, "")
else:
return (False, "", "Sentence-ending punctuation can only go after a word.")
if " " in word:
return (False, "", "Word cannot contain spaces except after a comma.")
else:
return (False, "", "Not a valid word for some reason (disallowed characters?)") | 658873c8cbf446cbe53ec5f806db668ceecaa2cf | 704,158 |
def remove_prefix(string, prefix):
"""
Removes a prefix from the string, if it exists.
"""
if string.startswith(prefix):
return string[len(prefix):]
else:
return string[:] | a3f5647140c0bfe95be7869b5ea42694b43dbd8e | 341,627 |
from typing import List
from typing import Any
import collections
def _create_ngrams(tokens: List[Any], n: int) -> collections.Counter:
"""Creates ngrams from the given list of tokens.
Args:
tokens: A list of tokens from which ngrams are created.
n: Number of tokens to use, e.g. 2 for bigrams.
Returns:
A dictionary mapping each ngram to the number of occurrences.
"""
ngrams = collections.Counter()
for i in range(len(tokens) - n + 1):
ngrams[tuple(tokens[i:i + n])] += 1
return ngrams | 759da5a3179a3805ff84437aff7d52f620bb3bfc | 673,154 |
def seq_is_equal(a, b):
"""
Helper function that checks if two sequences are equal (assuming they have
the same length).
"""
for i in range(len(a)):
if a[i] != b[i]:
return False
return True | 32660427c8e883f09ef0f9098dd81bbf44211b2a | 338,388 |
def get_height(img):
"""
Returns the number of rows in the image
"""
return len(img) | 765babc9fbc1468ef5045fa925843934462a3d32 | 709,893 |
def parse_list_amount(amount_str: str) -> int:
"""
Convert str to absolute integer.
If amount is "all", then it will be 0.
Args:
amount_str (str): amount from the message
Returns:
int: amount to be used
"""
if amount_str.lower() == "all":
return 0
else:
return abs(int(amount_str)) | bc7cf90cee085709318738122464509d3135c50c | 465,031 |
from typing import Mapping
def create_tag(tag_type: str, tag_value: str, tag_color: str) -> Mapping[str, str]:
"""Create a tag."""
return {"tag_type": tag_type, "value": tag_value, "color": tag_color} | 4af3c2cb41b7d4ede03aa40767ef2c9971ee43dd | 218,977 |
def add_two(x: int) -> int:
"""Add two to the number."""
return x + 2 | 82684f3513f8619f73cf6decea5cedeb68b52c4a | 228,514 |
def is_iterable(var):
""" Return True if the given is list or tuple.
"""
return (isinstance(var, (list, tuple)) or
issubclass(var.__class__, (list, tuple))) | f4c1d60d2e62688aedb776fb90d90049d93ad5e2 | 696,498 |
def point_on_line(point, seg_p1, seg_p2, tol=1e-6):
"""Determines whether a point lies on a line segment
Allows for a small tolerance
Args:
point ([float, float]): the point to test
seg_p1 ([float, float]): the beginning of the line segment
seg_p2 ([float, float]): the end of the line segment
tol (float): the maximum distance of the point from the 1d line
Returns:
bool indicating whether the point lies within tol of the line
"""
# Special case: vertical lines:
if seg_p1[0] == seg_p2[0]:
if point[0] != seg_p1[0]:
return False
else:
miny = min(seg_p1[1], seg_p2[1])
maxy = max(seg_p1[1], seg_p2[1])
return miny <= point[1] <= maxy
prop_along = (point[0] - seg_p1[0]) / (seg_p2[0] - seg_p1[0])
if prop_along < 0 or prop_along > 1:
return False
guess_y = seg_p1[1] + prop_along * (seg_p2[1] - seg_p1[1])
return abs(guess_y - point[1]) < tol | 1aa4ada909c8781eb2dd51b4d02af7f8a700ff24 | 526,664 |
def rewrite(n, axiom, productions):
"""Produce the final list of commands after all replacements.
Start by setting the axiom as the final string. With every iteration,
replace each symbol with the string that is mapped to them in the
productions dictionary.
If the symbol is a constant that cannot be replaced, add it to the string
as it is (this is the case for '+' and '-').
For example: given an axiom F-F-F-F and a production F->FF-F, the first
iteration would replace each 'F' in the axiom with the string 'FF-F',
resulting in this new string: F->FF-F-F->FF-F-F->FF-F-F->FF-F. The second
iteration would replace each 'F' in that new string with the string 'FF-F',
and so on...
"""
final_string = axiom
for _ in range(n):
s = "" # String to be built
for symbol in final_string:
if symbol in productions: # Replace
s += productions[symbol]
else: # Constant
s += symbol
final_string = s
return final_string | c142bbc8043f2619a7e3dbd70bfe6a59043dd73d | 356,442 |
def split_df(df):
"""
This function splits the DataFrame in the 3 Parts that we use for all the calculations.
Args:
df (DataFrame): This is the filtered DataFrame that we will split into the 3 qual parts
Returns:
df_first_25 (DataFrame) : DataFrame containing the first 25% of the Original DataFrame
df_middle_50 (DataFrame) : DataFrame containing the middle 50% of the Original DataFrame
df_last_25 (DataFrame) : DataFrame containing the last 25% of the Original DataFrame
"""
df_25_len = round(len(df) / 4)
df_first_25 = df[:-(df_25_len*3)]
df_middle_50 = df[-(df_25_len*3):-df_25_len]
df_last_25 = df[-df_25_len:]
return df_first_25, df_middle_50, df_last_25 | d27ea3f27f8bb3a7207f9ebc5c229bc6abe62c99 | 467,186 |
def decode_completion(text: str) -> str:
"""Reverse the encoding process for completion text.
Args:
text (str): The text to decode for use in action parameters and displaying
Returns:
str: The properly decoded text
"""
return text.replace("\\ ", " ") | 4d8e10cf9b662c5e17eb64e6b2c6a3fe54de795a | 379,997 |
def get_lc_cwt_params(mode: str) -> dict:
"""
Return sane default values for performing CWT based peak picking on LC data.
Parameters
----------
mode : {"hplc", "uplc"}
HPLC assumes typical experimental conditions for HPLC experiments:
longer columns with particle size greater than 3 micron. UPLC is for
data acquired with short columns with particle size lower than 3 micron.
Returns
-------
cwt_params : dict
parameters to pass to .peak.pick_cwt function.
"""
cwt_params = {"snr": 10, "min_length": 5, "max_distance": 1,
"gap_threshold": 1, "estimators": "default"}
if mode == "hplc":
cwt_params["min_width"] = 10
cwt_params["max_width"] = 90
elif mode == "uplc":
cwt_params["min_width"] = 5
cwt_params["max_width"] = 60
else:
msg = "`mode` must be `hplc` or `uplc`"
raise ValueError(msg)
return cwt_params | 9bbca4f7bcb89251e224a42c868aa4cda65fe086 | 402,365 |
def convert_simple_sub_commands_to_position(arr: list) -> tuple[int, int, int]:
"""
Args:
arr: list of strings including a simple command and magnitude separated by one space
Returns:
depth, horizontal, and depth * horizontal positions after parsing all simple sub commands
"""
d = 0
h = 0
for elem in arr:
command, magnitude = elem.split(' ', 1)
if command == 'forward':
h += int(magnitude)
elif command == 'up':
d -= int(magnitude)
elif command == 'down':
d += int(magnitude)
return d, h, d * h | a31068aaa5920bb311fb60b4dae4fd58a9554def | 322,686 |
def is_odd(num):
"""
Check whether its argument is odd.
>>> is_odd(2)
False
>>> is_odd(3)
True
:param num: int
:return: bool
"""
return num % 2 == 1 | 0fc535ce7260924fb2c2edf3c690378800ca916f | 270,349 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.