content stringlengths 39 9.28k | sha1 stringlengths 40 40 | id int64 8 710k |
|---|---|---|
import random
import string
def gen_random_string(str_len):
""" generate random string with specified length
"""
return ''.join(
random.choice(string.ascii_letters + string.digits) for _ in range(str_len)) | f1e7256aace39e8fefdaaec12f1c0dd74d772e4d | 486,043 |
def string_to_list(t_str, t_char=" "):
"""
Returns a list of elements that are contains inside the string param.
:param str t_str: string with elements and delimiters
:param str t_char: delimiter of the elements
:return list t_list: list of elements that were inside t_str
"""
t_list = t_str... | 909d3a45bdac900812d9024b46d334b6c6d5c08c | 506,473 |
def locate_dominating_file(io, filename, directory=None):
"""
Find a file or directory with the given name, either in the given
(defaults to current) directory or a parent. Return the full path,
or None if the root of the filesystem is reached before finding a
matching file.
"""
if directory... | 37940616448be54df497ad528cbea20f52a953b7 | 196,634 |
import math
def _calc_KTB_rate(starting_rate, duration, roeotroe, rng):
"""
Returns a simulated rate for the head node of a tree when:
* the tail node has rate ``starting_rate``
* the time duration of the edge is ``duration``
* the rate of evolution of the rate of evolution is ``roeotr... | fa31faf91f0e26795ad136b327c116f3192e9913 | 281,524 |
def msg_color(msg_type):
"""Get the color to use for the msg type."""
return {
"sent": 0x4caf50,
"edited": 0xffc107,
"deleted": 0xff5252,
}.get(msg_type, 0x000000) | 5c1b6615531e9fe018a86d28a5a34122dbcd62e5 | 493,274 |
def _filename_dataset(dataset, market=None, variant=None, extension=None):
"""
Compose the filename for a dataset given its name, variant, market,
and filename extension.
:param dataset: String with dataset name e.g. 'income'.
:param market: Optional string with dataset market e.g. 'usa'.
:para... | 6b4cc7c1fed80088d391b481acc4c7c3fa0e6d85 | 218,265 |
def find_bad_building1099(X, y):
"""Returns indices of bad rows (with absurdly high readings) from building 1099."""
return X[(X.building_id == 1099) & (X.meter == 2) & (y > 3e4)].index | 96010fcd5d43fd231bdc688b482580ca4f56aba7 | 264,602 |
from typing import Tuple
def get_mode(mode: str, line: str) -> Tuple[str, bool]:
"""Get the mode of the map.
Args:
mode (str): the current mode
line (str): the line to check
Returns:
str, bool: the new mode, if the mode has changed
"""
if line == "" or line[0] == "#":
... | 721d335ea1eaefbfc3f8a3ab60fb351d1b940674 | 670,820 |
def star_formation_rate(z, z_inhom=0.):
"""Returns the star formation rate, per comoving volume, evaluated at the specified redshift.
Ref:
A.M. Hopkins and J.F. Beacom, Astrophys. J. 651, 142 (2006) [astro-ph/060146]
P. Baerwald, S. Huemmer, and W. Winter, Astropart. Phys. 35, 508 (2012) [1107.... | 83da0e6b776bfc35dac1c8e5e0df42c493da9d6b | 275,291 |
def get_taskResult(plRunitem, taskname, resultName):
"""タスク名、Result項目名を指定しタスクResult値を取得する
Args:
plRunitem (dict): TEKTON CLI pipelinerun listの結果明細(1 pipelinerun)
taskname (str): タスク名
resultName (str): Result項目名
Returns:
(str): タスクResult値
"""
# status.taskRuns[*]にtas... | 5f2b6d930f9b9497ecc1b6a1e6e8d6892ad7781e | 407,083 |
def bool2yn(b):
"""Converts a boolean to yes or no with the mapping: y = True, n = False."""
return 'y' if b else 'n' | d64c34fb720d547e6c9b557fa67fdca2fe3b1860 | 139,111 |
def get_numeric_name(name):
"""
Strips non-numeric characters from a string and returns a string with only numeric values in it.
:param name:
Name of a room
:type name:
`str`
:rtype:
`str`
"""
return ''.join([x for x in name if x.isnumeric()]) | 3bfcc63c92d5bac750420f9ec3c715326b57d8b6 | 336,576 |
def is_installed(settings):
"""
Check Django settings and verify that tinymce application is included
in INSTALLED_APPS to be sure that staticfiles will work properly and
serve required files.
"""
if not hasattr(settings, 'INSTALLED_APPS'):
raise RuntimeError('Django settings should con... | ababfb859f3b16921dadeaea7b7d4ffbabc751da | 172,935 |
def bilinear_interpolation(n1, n2, n3, n4, x, y):
"""
Bilinear interpolation of value for point of interest (P).
:param n1: value at node 1
:param n2: value at node 2
:param n3: value at node 3
:param n4: value at node 4
:param x: interpolation scale factor for x axis
:param y: interpol... | dda4474bbd7bbf744a265be7be79fff5f70ee7b8 | 579,780 |
import requests
def get_pypi_package_releases(package_name):
"""
calls PYPI json api as described here
https://wiki.python.org/moin/PyPIJSON
https://warehouse.readthedocs.io/api-reference/json.html
:param package_name: string, pypi project name
:return: json with pypi project response
"""
... | 14b8522e4c6c8087c72268abd9e627dbeff44eba | 170,271 |
def reject_hit(client, assignment_id, feedback):
"""Rejects a HIT assignment on MTurk
Parameters
----------
client : MTurk.Client
A boto3 client for MTurk
assignment_id : string
The ID of the assignment. The assignment must correspond to a HIT created by the Requester.
feed... | bc1f742e47baee29cfdf556aed31b32dd43b7da2 | 568,701 |
def virial_mass(FWHM, vel_disp):
"""
Calculates the Vyrial Theorem based Dynamical mass
FWHM is the deconvolved size of the source in pc
vel_disp is the velocity dispersion in km/s
http://adsabs.harvard.edu/abs/2018arXiv180402083L
Leroy et al 2018
"""
M = 892. * FWHM * (vel_disp**2.)
... | 0a2529b453edb4c0bc2cbd19d56ccf27fbf77005 | 249,424 |
def module_equals(model1, model2):
"""Check if 2 pytorch modules have the same weights
"""
for p1, p2 in zip(model1.parameters(), model2.parameters()):
if p1.data.ne(p2.data).sum() > 0:
return False
return True | cf23a7da62d95b80f6f878dc77f65e14db74dba6 | 659,918 |
def resolve(obj, attrspec):
"""
Resolve elements from an object.
Works with objects and dicts.
From: http://stackoverflow.com/a/9101577/1309774
"""
for attr in attrspec.split("."):
try:
obj = obj[attr]
except (TypeError, KeyError):
obj = getattr(obj, attr)... | 59280637c1cbc9ec8d402d6dbee020568c35a854 | 466,723 |
def listSnapshots(snapshots, tree=False):
"""Get VM snapshot information.
tree=True will return snapshot tree details required for snapshot removal
"""
snapshot_data = []
for snapshot in snapshots:
if tree is True:
snapshot_data.append(snapshot)
else:
snapsh... | bb375fc2eecbb6c395f5a89ba290b7b1d95eb7ee | 604,815 |
import itertools
def test_combination_combinator(container, pairs_):
"""
r-length tuples, in sorted order, no repeated elements
combinations('ABCD', 2)
AB AC AD BC BD CD
"""
return list(
itertools.combinations(container, pairs_)
) | 5bd1b6f2e2e6360c1db8b663445085d8b2ae3e99 | 588,490 |
def rotate(image):
"""Rotate the image based on it's exif tag.
If the exif tag is missing or the value
unknown the image is returned unchanged.
"""
try:
# Exif tag for orientation
orientation = image.getexif()[274]
if orientation == 3:
return image.rotate(180, ... | 51f6fc669263fbe715725de927fc220cf056b784 | 423,852 |
def get_requirements_from_file(requirements_file):
"""
Get requirements from file.
:param str req_file: Name of file to parse for requirements.
:return: List of requirements
:rtype: list(str)
"""
requirements = []
with open(requirements_file) as f:
for line in f:
lin... | 5ec6ad1f4c2b22aae1cfa7eb3888b3279ffeca31 | 8,846 |
def _has_numbers(text):
""" Checks if any characters in the input text contain numbers """
return any(char.isdigit() for char in text) | c8992cfe40c310f07d292aa376aad8d766a5242b | 657,440 |
def _get_last_page_offset(url_html):
"""Obtain last page offset.
Required to stop iterating over pages.
Parameters
----------
url_html : BeautifulSoup object
Returns
-------
int
"""
page_numbers = url_html.findAll("div", attrs={"class": "pageNumbers"})[0]
last_page_offset... | 3f3d01a095addb2c8ac577e33cc28129047df227 | 568,019 |
def build_form(Form, _request, *args, **kwargs):
"""
Build the ``Form`` instance.
If ``request.method`` is ``POST`` then build bound form else build unbound.
Usage example::
@login_required
@render_to('blog/post_create.html')
def post_create(request):
post = Post(i... | 7365ac3edd578503d25adda8f7f057a44637c123 | 250,765 |
import logging
def column_exists(df, column, log=True, stdout=True, log_msg=None):
"""Check whether a column exists in a given pandas DataFrame."""
if column in df.columns:
return True
if log:
if log_msg:
log_msg = str(log_msg)
else:
log_msg = (f'WARNING: `{... | 5e03223b6623f02bfec4a34494913d095f5d8f8b | 358,446 |
import json
def __force_mutable(plaintext):
"""Dumps mutable objects to string to make them hashable"""
if not isinstance(plaintext, str):
return json.dumps(plaintext)
return plaintext | 16d1afea71bc23c5f5319197789fec25cd38b916 | 345,316 |
def single(sequence, condition=None):
"""
Returns the single item in a sequence that satisfies specified condition or
raises error if none or more items found.
Args:
sequence: iterable
Sequence of items to go through.
condition: callable
Condition to... | 6849a5ea218f45b2ef163f3ca98b15311b779515 | 398,219 |
def try_int(string):
"""
Return an integer if possible, else string
"""
# Ignore octal & hexadecimal
if len(string) > 1 and string[0] == '0' and string.isdigit():
return string
try:
return int(string)
except ValueError:
return string | 26beb7162348dc2a3205d223578a52ef5d1abd23 | 412,340 |
import torch
def collate_samples(batch):
"""
Used by DatasetLoader to merge together multiple samples into one mini-batch.
"""
images = [d['image'] for d in batch]
targets = [d['target'] for d in batch]
collated_batch = dict(
image=torch.stack(images),
target=torch.stack(targe... | ae4cf311f75909bf57f5132e42806903df4c531a | 565,496 |
def qualitative_dates(df,
iterator_column='Animal_id',
date_column='relative_date',
label='qualitative_date',
fuzzy_matching={},
):
"""
Assign qualitative date labels.
Parameters
----------
df : pandas.DataFrame
A `pandas.DataFrame` object containing a date column.
iteraor_column : string, optional
The... | 370fa4b9e0ce81329094514882cd3686b7989ebb | 338,894 |
import re
def get_member(path):
"""Retrieve member_id from path ifpotentially wrong in database
Args:
path (str): data directory path
Returns:
string of member_id extracted from path
"""
mo = re.search(r'r\d*i\d*p\d*f\d*', path)
if mo:
return mo.group()
else:
... | caa171d3830763c5b73db3cd557a668c0067c58e | 463,476 |
def get_upstream_basin(catchment, totalBasinGeom):
"""Get upstream basin geometry by subtracting the local catchment from the totalBasinGeom"""
d = 0.00045
cf = 1.3 # cofactor
upstreamBasinGeom = totalBasinGeom.symmetric_difference(catchment).buffer(-d).buffer(d*cf).simplify(d)
return upstreamBas... | 53e665f9e3a4203b7374934f9ae6c1d38605aaeb | 160,522 |
def _strToBoundNumeral(v, interval, conversion):
"""Test (and convert) a generic numerical type, with a check against a lower and upper limit.
@param v: the literal string to be converted
@param interval: lower and upper bounds (non inclusive). If the value is None, no comparison should be done
@param c... | e1a473ba009462316e21b94613f3a8803c0954cd | 247,380 |
def lookup_in_namespace(name,namespace):
"""Resolve a dotted name into an object, using given namespace."""
bits = name.split(".")
obj = namespace[bits[0]]
for attr in bits[1:]:
obj = getattr(obj,attr)
return obj | ccb79410e6357fd3681da2d4afe3f25217e82720 | 588,067 |
def get_symlink_output(pull_number, job_name, build_number):
"""Return the location where the symlink should be created."""
# GCS layout is defined here:
# https://github.com/kubernetes/test-infra/tree/master/gubernator#job-artifact-gcs-layout
if not pull_number:
# Symlinks are only created for pull request... | 4320d124b12b3c4e0d88e85b27314e1c1c01db7c | 180,892 |
def assert_time_of_flight_is_positive(tof):
"""
Checks if time of flight is positive.
Parameters
----------
tof: float
Time of flight.
"""
if tof <= 0:
raise ValueError("Time of flight must be positive!")
else:
return True | 54f85189ca8b25f0447ccbca60179a2eff41b018 | 655,223 |
def a_send_line(text, ctx):
"""Send text line to the controller followed by `os.linesep`."""
ctx.ctrl.sendline(text)
return True | 79f40657fe2b346c695d808bb3cdc7650077b76e | 23,966 |
def get_full_name(given_name, family_name, config):
"""Return full name string obtained by concatenating given_name and
family_name in the order specified by config.family_name_first, or just
given_name if config.use_family_name is False."""
if config.use_family_name:
separator = (given_name and... | 51489dda714e678bbec36e6397c07bc228de060d | 143,577 |
def calculate_boundbox(list_coordinates):
"""
coordinates are inverted x: colums y :rows
list_coordinates: list of the form [ [x2,y1], [x2,y2], . . . ]
returns top left point (x,y) and width (w) and heigth (h) of rectangle
"""
x = int(min(list_coordinates[:,0]))
y = int(min(list... | bbabdd81e88dd4304293712aff389bfd568f4772 | 43,538 |
def split_sentences(inp_text, nlp_model):
"""
Splits an input string into sentence determined by spacy model
:param inp_text: string with input text
:param nlp_model: sciSpacy model
:return: list of sentences in string format
"""
doc = nlp_model(inp_text)
sentences_list = [sentence.text ... | b5617d9334509edf09bf4a0360d3030e67ddf800 | 700,537 |
import pathlib
import click
def validate_keep_media_path(ctx, param, value):
"""
Validate the path used to set the 'keep_media' option
"""
if value is None or pathlib.Path(value).exists():
return value
else:
path = pathlib.Path(value)
pathlib.Path(path).mkdir(parents=True, ... | 75c589e5fbc4c5cd26cac2c6f115de4f91c870b5 | 220,864 |
from typing import List
def is_empty(stack: List[str]) -> bool:
"""
Check if a stack is empty.
We add this custom method, as Python does not have a built-in is_empty() method.
:param stack: is the stack to inspect.
:return: a boolean value determining whether the stack is empty or not.
"""
... | 5a2ca546c08c5c417526869d272ae353469fc30f | 585,816 |
def evaluate_single_episode(environment, agent, render=False, epsilon=None):
"""
Evaluate a single episode of agent operating inside of an environment.
This method should be applicable to all reinforcement learning algorithms
so long as they implement the Agent interface.
"""
state = environmen... | 38473730d5c0a600408de8cacb3ec7b43168c7e8 | 144,678 |
import re
def parse_k(msg):
"""Parse create keypoint message and return keypoint number"""
if not re.search(r"KEYPOINT NUMBER", msg):
res = re.search(r"(KEYPOINT\s*)([0-9]+)", msg)
else:
res = re.search(r"(KEYPOINT NUMBER =\s*)([0-9]+)", msg)
if res:
result = int(res.group(2))... | 92f45ea09a7c9e1eecf48664c49218657687a217 | 35,729 |
def _get_feature_names_from_str_or_col_index(X, names_or_col_indices):
"""Helper function to map the user-input features param to column names."""
feature_list = []
for name_or_index in names_or_col_indices:
if isinstance(name_or_index, int):
feature_list.append(X.columns[name_or_index])... | e5d71f16b5a331425ff579e74df86cc78d60bb09 | 265,617 |
from collections import defaultdict
def problem_1_3(left: str, right: str) -> bool:
"""
Given two strings, write a method to decide if one is a permutation of the other.
So, I could iterate through a range of indicies and construct a single hashmap to store the counts of a character.
We can add from ... | 0f350bd19f0720fc41a30fa15930cf6d6f9c08d5 | 325,953 |
from pathlib import Path
def load_from_config(path: str, pattern: str) -> list:
"""
Loads all mris from a given path with a given pattern.
Args:
path (str): Path to the mris.
pattern (str): Pattern to search for.
Returns:
list: List of mris.
"""
p = Path(path).expandu... | be0a57fa3c1ae2793ea9bee02465f9fb4034cef7 | 529,781 |
def persistence_model(latest_ghi):
"""
Creates a persistence forecast when the software fails to receive a valid
GHI observation. Can also be used if one simply desires a persistence
forecast.
Parameters
----------
latest_ghi: 'Pandas Series object'
Current time. Usually contains a y... | 4a79dfe09d12b8b98cac9e542f20be48b5af1433 | 496,133 |
def get_history_slice(
frame_index: int, history_num_states: int, history_step_size: int, include_current_state: bool = False
) -> slice:
"""Given a frame index and history settings returns a slice that returns the given data in the right order.
Note that this history returned starts with the most "rece... | 185d472bd2b92e77a016473fb1afdc99c4534955 | 622,952 |
def IsBlankLine(line):
"""Returns true if the given line is blank.
We consider a line to be blank if the line is empty or consists of
only white spaces.
Args:
line: A line of a string.
Returns:
True, if the given line is blank.
"""
return not line or line.isspace() | 2353eebce8f33890d7e2a62a3d627365ac1cbea6 | 512,990 |
def flatten_get_parameters(request):
"""Return a dict with flattened GET parameters.
Otherwise a dict(ImmutableMultiDict) returns a list for each
parameter value and that is not what we want in most of the cases.
"""
if not hasattr(request, 'args'):
return {}
return {k: len(v) == 1 and ... | 7a29d7c7733db5a28b97e472431bbc36e3753e90 | 148,121 |
def fmt_d(num):
"""Decimal formatter"""
return f'${num:,.0f}' | 4d8e6b6c31de3150ed9530f9204e3d9d491acad6 | 400,157 |
def package_collection(distinct: bool):
"""Return the package collection, set or list."""
if distinct:
package = set()
else:
package = []
return package | 7dc1090fb526d2bf5c71037f3856f791bd0b8860 | 145,172 |
def renormalize_sv(elements):
"""
Accepts a vector or array and removes the integer part of all elements, reducing them floats in the interval (0,1).
Example:
x = [1.2, 4.5, 5, 3.1]
renormalize(x)
print(x)
[0.2, 0.5, 0, 0.1]
"""
D = len(elements)
elements_new = ... | 619d77a20511ccae60304e529519b268fd3c37ce | 303,813 |
import math
def cphase(c):
"""cphase(c): returns complex phase: (-pi, +pi]."""
return math.atan2(c.imag, c.real) | 6ff8207819d377bc8279d9f5efbf2123999650e3 | 123,592 |
def _package_root(name):
"""Convert treadmill.logging.xxx => treadmill
"""
return name.split('.', 1)[0] | 6ad3e2f89f8ce2fa708757ce772e020c1c216f6e | 243,007 |
def get_item(dictionary, key):
"""
Return a key value from a dictionary object.
**Parameters**
``dictonary``
Python dictionary object to parse
``key``
Key name tor etrieve from the dictionary
"""
# Use `get` to return `None` if not found
return dictionary.get(key) | 6a0a9bd78c8e7f68a329c39a3cf1b125b529bcd3 | 488,134 |
from typing import List
def load_list(filename: str) -> List[str]:
"""
Load list of strings from files.
Arguments:
filename - filename to be loaded
Returns:
List of lines
Raises:
PermissionError, FileNotFoundError
"""
with open(filename, encoding="UTF-8") as f: ... | 9c7b3f962f7167d04ecbcf3e4cc4e9b1a1ad2a04 | 158,320 |
def clamp(x, lo, up):
"""
clamp x to be lo <= x <= up
"""
assert lo <= up
return lo if x < lo else up if x > up else x | 1778a202559c7773cc3f0724d05235399ba96312 | 572,837 |
def load_phrase_dictionary(file, mode):
"""
Loads a phrase dictionary
:param file: The phrase dictionary to open
:param mode: Mode w, a, r - write, append, read
:return: The loaded phrase dictionary
"""
phrase_dict = open(file, mode)
return phrase_dict | b2403ef76880d9f67aa8464c2c41924ec8016227 | 219,573 |
def is_relative_url(url):
""" simple method to determine if a url is relative or absolute """
if url.startswith("#"):
return None
if url.find("://") > 0 or url.startswith("//"):
# either 'http(s)://...' or '//cdn...' and therefore absolute
return False
return True | b83d8fadf779fbd46835f5350b2329601a6fd46d | 130,844 |
def element(point, p, q, n):
"""Test, whether the given point is on the curve (p, q, n)"""
if point:
x, y = point
return (x * x * x - p * x - q) % n == (y * y) % n
else:
return True | 0433af33e5567597592d2b7fe07420317851b506 | 618,605 |
def get_tier_level(files: str) -> str:
"""
Retrieves the RHCS QE tier level based on the suite path or filename.
The argument contains "::" as a separate for multiple test suite execution. The
understanding in both the cases is that, the qe stage is provided at the starting
of the filename or direc... | b7030b110b99d93ee6eef79e69d0db7242060240 | 595,240 |
def get_figsize(df, x, hue):
"""Attempt to get a reasonable figure size."""
num_x = len(df[x].unique())
num_hue = len(df[hue].unique())
width_per_vplot = 0.3
width_per_tick = width_per_vplot * num_hue
width = num_x*width_per_tick + 2 # Extra space for axes/etc.
# Just using default value fo... | 3c4ac1d7b1d95de51d4765876216ed31bf2b6151 | 369,929 |
def datetime2DateOrNone(value):
"""
Function for converting datetime to date or None
"""
if value is None:
return None
else:
return value.date() | b548896d5b004258a482996a5b98adc965540d97 | 215,000 |
def reshape_to_images(x, im_h=None):
"""Reshape set of vectors to images, assuming square or given height."""
if im_h is None:
im_h = int(x.shape[1]**0.5)
im_w = x.shape[1] // im_h
return x.reshape(x.shape[0], im_h, im_w) | cf8fb93c32498622678329d2682783b33c4f7c18 | 316,677 |
def has_workflow_stage(artifact, workflow_step_name):
"""
Checks that the artifact's sample's root artifact has been through the given workflow.
:return True if it has False otherwise
"""
for w, status, name in artifact.samples[0].artifact.workflow_stages_and_statuses:
if name == workflow_st... | 13d9d4c2e79331bc5f8bec8ebadfca705439442e | 649,975 |
import torch
def rot_matrix_from_quaternion(q):
"""
Construct rotation matrix from quaternion
"""
# Shortcuts for individual elements (using wikipedia's convention)
qi, qj, qk, qr = q[..., 0], q[..., 1], q[..., 2], q[..., 3]
# Set individual elements
R00 = 1.0 - 2.0 * (qj ** 2 + qk ** 2)
... | 80a7a7110bde1377b7a1ed4c77ad67d5fbf6d688 | 121,714 |
def get_stack_id(x, y):
"""Get stack id.
Get the portainer stack id for a given
stack name.
Args:
x: Portainer stack name
y: Deployed portainer stacks
Return:
String portainer stack id
"""
return str(list(filter(lambda z: z['Name'] == x, y))[0]['Id']) | 71fe86e81683c749ea2fb7cecb73a022a0ae6df2 | 418,064 |
def use(*authenticator_classes):
""" A decorator to attach one or more :class:`Authenticator`'s to the decorated class.
Usage:
from thorium import auth
@auth.use(BasicAuth, CustomAuth)
class MyEngine(Endpoint):
...
OR
@auth.use(BasicAuth)
@auth.use... | 27aeb7711c842540a1ed77a76cebeb61e0342f1e | 2,905 |
import random
def generate_int_list(list=[], length=10, min_value=0, max_value=10):
"""Generate and return a list of random integers.
The random values will be between min_value and
max_value - 1. If list's length were less than length,
it'll be completed with random values until list's
... | f80ce3edd5cd1ca4189d1cda9c3d151ff4943d50 | 19,803 |
def tostr(s):
"""Stringify sequence s."""
return ''.join(s) | 8d27f8b331083c5b8ed9ae28a3fa22904ba55871 | 163,239 |
def to_netstring(buff):
"""
Converts a buffer into a netstring.
>>> to_netstring(b'hello')
b'5:hello,'
>>> to_netstring(b'with a nul\\x00')
b'11:with a nul\\x00,'
"""
bytes_length = str(len(buff)).encode('ascii')
return bytes_length + b':' + buff + b',' | eae0f8f3c06f14d9e8d281287386c31d1b5df33f | 553,570 |
def is_app_code(code: int) -> bool:
"""
Checks whether a code is part of the app range.
:param code: Code to check.
:return: Boolean indicating whether `code` is within the app range.
"""
return 0 < code < 0x10 | d0bd6485875500418b5ddd60ae5fb3c9b965b71f | 48,154 |
def gen_reg (class_names):
""" Generates registration calls for funtions with the given class names.
Args:
class_names (list of str): The class names.
Returns:
str: The registration calls.
"""
out = ""
for class_name in class_names:
if len(out) > 0:
out += '\n... | 8ae9adc319dd4a2923ab9cb3fd8cec2a2ae9301b | 115,545 |
def get_attribute_name(node_and_attribute):
"""
For a string node.attribute, return the attribute portion
"""
split = node_and_attribute.split('.')
attribute = ''
if split and len(split) > 1:
attribute = '.'.join(split[1:])
return attribute | a23e515c63e1c3e2d6843b8efe8088092bd783d0 | 587,877 |
from typing import Tuple
def get_current_coins(acc_details:dict) -> Tuple[list,list]:
"""
From account details get the non zero valued coins
Arguments:
acc_details - account details from Spot().account()
Returns:
list -> Non-zero free coins
list -> Non-zero locked coins
"""
b... | c420cb1bb9751b348305c888ff1c6449397134c0 | 323,552 |
def is_symspec(symspec):
"""
returns True if `symspec` can be used as a symbol specification.
"""
if not hasattr(symspec, 'name'):
return False
if not hasattr(symspec, 'prec'):
return False
return True | 5bee27e24f68009727ab5320bd577d73be4eb62c | 367,098 |
def prompt_chars(prompt: str, chars: str) -> str:
"""Prompt the user with a multiple-choice question."""
said = ""
while said not in list(chars):
said = input(f"{prompt} [{chars}]> ").lower()
return said | f01719f216b4dee16cedd00722731374aa65291c | 121,055 |
def extend(*dicts):
"""Create a new dictionary from multiple existing dictionaries
without overwriting."""
new_dict = {}
for each in dicts:
new_dict.update(each)
return new_dict | e5f6e4797eab6cc6c6b2c23f0766b6ff23f5f8e1 | 682,630 |
def get_bcg_coverage(database, country_iso_code):
"""
extract bcg coverage from inputs database
:param database: sql database
database containing the bcg data
:param country_iso_code: string
three letter ISO3 code for the country of interest
:return: dict
pandas data frame w... | 47c7c252af9e20dcbf96ef483fdff79b93bfea07 | 491,419 |
def convert_sorting(sortings):
"""Convert a V3 sort parameter into the V4 orderBys field.
Args:
sortings: A string representing the V3 sort parameter.
Returns:
A list of V4 orderBy objects.
"""
order_bys = []
for sorting in sortings.split(','):
order_by = {}
order_by['orderType'] = 'VALUE... | 3ad2bae0b7aa3d865fbd05d90f5f95169e4345e2 | 297,255 |
def filter_by_extension(ext):
"""
A higher-order function that returns a function
that given a filename filters by the extension
argument.
:param ext: the return function will return true if a filename ends with ext
:return: a one-arg function that takes a filename and returns true if filename e... | f4ec9e30bf867af29101226c23335c6328e6d032 | 107,071 |
def user(mocker):
"""Fake User instance."""
user = mocker.Mock()
user.id = "001"
user.email = "foo@bar.com" # /PS-IGNORE
return user | 21ff2c3c12f450a4e202a1ff75c427118fc56cd2 | 170,846 |
def chunk(mylist, chunksize):
"""
Args:
mylist: array
chunksize: int
Returns:
list of chunks of an array len chunksize (last chunk is less)
"""
N = len(mylist)
chunks = list(range(0, N, chunksize)) + [N]
return [mylist[i:j] for i, j in zip(chunks[:-1], chunks[1:])] | 69cc8aa812c989c63dae4c444ee132c54a861fa4 | 17,986 |
import _ast
def BinOpMap(operator):
"""Maps operator strings for binary operations to their _ast node."""
op_dict = {
'+': _ast.Add,
'-': _ast.Sub,
'*': _ast.Mult,
'**': _ast.Pow,
'/': _ast.Div,
'//': _ast.FloorDiv,
'%': _ast.Mod,
'<<': _ast.LShift,
'>>': _ast... | 0b332b1043b31b123daf8812e6f2ecb4e3974f19 | 9,128 |
def _basis_bitstring(i, num_qubits):
"""Create vector corresponding to i-th basis vector of num_qubits system."""
return [int(char) for char in bin(i)[2:].zfill(num_qubits)] | bbecb12400e1867274b3465cc37590ad37908c28 | 379,032 |
def _get_realm(response):
"""Return authentication realm requested by server for 'Basic' type or None
:param response: requests.response
:type response: requests.Response
:returns: realm
:rtype: str | None
"""
if 'www-authenticate' in response.headers:
auths = response.headers['www... | 346b3278eb52b565f747c952493c15820eece729 | 708,344 |
def TourType_idx_rule(M):
"""
Index is (start window, tour type)
:param M: Model
:return: Variable index (list of tuples)
"""
return [(i, t) for i in M.WINDOWS
for t in M.activeTT
if (i, t) in M.okTourType] | b017f2d1156b38133da43c5922293aa58d5a3de0 | 291,660 |
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 transform_schema(actions, schema):
"""Transform schema according to actions.
Args:
actions (list): actions to run
schema (pyarrow.Schema): original schema
Returns:
pyarrow.Schema: Transformed schema
"""
for action in actions:
schema = action.schema(schema)
r... | c37f9cf5c24ab49a1a10caed386c016bf123bc24 | 521,363 |
def bucket_by_length(words):
"""Bucket a list of words based on their lengths"""
num_buckets = list(set([len(x) for x in words]))
buckets = dict()
for x in num_buckets:
buckets[x] = list()
for word in words:
buckets[len(word)].append(word)
return buckets | d3a3fd6ff2cd580712fd5933e11918d5e3b2dd5f | 485,371 |
def task_config_to_dict(task_config):
""" Convert a task config to a dict and remove all empty keys """
dconf = dict(task_config)
for k in list(dconf.keys()):
if not dconf[k]:
del dconf[k]
return dconf | acc23d4881a0eb2ae9ea67733efae4127c077192 | 145,727 |
def first_non_empty(data_or_instance, field_or_fields, default=None):
"""
Return the first non-empty attribute of `instance` or `default`
:type data_or_instance: object or dict
:param data_or_instance: the instance or the resource
:type field_or_fields: str or tuple or list
:param field_or_fiel... | 9be9d7fddcfc3b71b92ca12fb8949d85ad4cb342 | 672,593 |
def _get_fields(events):
"""
Returns a list of all fields in the given event set.
@param events: The events as a list of dictionaries.
@type events: list(dict(str: str))
@return: All the fields.
@rtype: set(str)
"""
fields = set()
for event in events:
fields.update(list(even... | 1028e30ea761f4d8397a042863a243e71172539c | 62,279 |
def rightpad(x, c, w):
"""Rightpad string `x` with `c` using width `w`.
"""
return x + c * (w - len(x)) | cefcf48f3f60ad62b9d1b745bed8a1fe4086eca6 | 370,968 |
import logging
def logger(request):
"""Sets up a logger at loglevel 1 and attaches a LogHandler."""
logger_ = logging.getLogger(request.function.__name__)
logger_.setLevel(1)
return logger_ | 25e12b5222c17ff9bc2c421099c4042bc5465b6b | 325,018 |
def split_config_args(args):
"""Split -[-]name=value configuration command-line arguments."""
res = []
for arg in args:
if arg.startswith('-'):
for part in arg.split('=', 1):
res.append(part)
else:
res.append(arg)
return res | b08e16ac24edd694b793d1b2ea9c6db88b939083 | 90,078 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.