seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
def get_nonce_bytes(n):
"""BOLT 8 requires the nonce to be 12 bytes, 4 bytes leading
zeroes and 8 bytes little endian encoded 64 bit integer.
"""
return b"\x00"*4 + n.to_bytes(8, 'little') | bigcode/self-oss-instruct-sc2-concepts |
def humanize_bytes(num_bytes):
"""
Convert a number of bytes to human version
:param num_bytes: int: bytes to be converted to
:return: str
"""
val = num_bytes
suffix = "B"
factor = 1000
if val >= factor:
val = val / factor
suffix = "KB"
if val >= factor:
v... | bigcode/self-oss-instruct-sc2-concepts |
def categorical_fillna(data, col, value="N"):
"""
Fills a categorical features Nan Values with the provided value, returns a new column.
The pandas function sometimes does not work
"""
def helper(x):
if isinstance(x, float):
return value
return x
return data[col].app... | bigcode/self-oss-instruct-sc2-concepts |
def _is_max_limit_reached(current: int, maximum: int = -1) -> bool:
"""Check if the limit has been reached (if enabled).
Args:
current: the current value
maximum: the maximum value (or -1 to disable limit)
Returns:
bool: whether the limit has been reached
"""
return maximum... | bigcode/self-oss-instruct-sc2-concepts |
def oo_selector_to_string_list(user_dict):
"""Convert a dict of selectors to a key=value list of strings
Given input of {'region': 'infra', 'zone': 'primary'} returns a list
of items as ['region=infra', 'zone=primary']
"""
selectors = []
for key in user_dict:
selectors.append("{}={}".format(key... | bigcode/self-oss-instruct-sc2-concepts |
import random
def randomseq(length, letters):
"""
Returns a sequence of a certain length with a composition of letters given as input.
Args:
length (int): Length of the sequence
letters (string): A string containing all the possible letters
Returns:
Sequence (string): A seque... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Dict
def split_entry(entry: str) -> Dict[str, str]:
"""
Splits a given entry into a dictionary of parameters
:param entry: An entry as a formatted string
:return: A dictionary of key value pairs
"""
entries = entry.split(" ")
return {key: value for key, value in [entry.... | bigcode/self-oss-instruct-sc2-concepts |
def free_slots(slots):
"""With planned slots as 18 return available slots"""
return 18 - slots | bigcode/self-oss-instruct-sc2-concepts |
import math
def lonlat_to_mercator_tile_indices(
longitude: float, latitude: float, zoom: int,
tile_size: int = 512, flip_y: bool = False
):
"""
Conversion of lon-lat coordinates to (web)Mercator tile indices
:param longitude:
:param latitude:
:param zoom: zoom level (0, 1, ...)
... | bigcode/self-oss-instruct-sc2-concepts |
def within_tolerance(value, expected):
"""
Verify that all values of the color tuple are within a range of tolerance.
"""
t = 0.01
return ((expected[0] - t) <= value[0] <= (expected[0] + t)
and (expected[1] - t) <= value[1] <= (expected[1] + t)
and (expected[2] - t) <= value[... | bigcode/self-oss-instruct-sc2-concepts |
def node2geoff(node_name, properties, encoder):
"""converts a NetworkX node into a Geoff string.
Parameters
----------
node_name : str or int
the ID of a NetworkX node
properties : dict
a dictionary of node attributes
encoder : json.JSONEncoder
an instance of a JSON enco... | bigcode/self-oss-instruct-sc2-concepts |
def fix_filename(filename):
"""Latex has problems if there are one or more points in the filename,
thus 'abc.def.jpg' will be changed to '{abc.def}.jpg
:param filename:
:type filename: str
:return:
:rtype: str
"""
parts = filename.split('.')
... | bigcode/self-oss-instruct-sc2-concepts |
import re
def compare_no_whitespace(a, b):
"""Compare two base strings, disregarding whitespace."""
return re.sub('\s*"*', '', a) == re.sub('\s*"*', '', b) | bigcode/self-oss-instruct-sc2-concepts |
import logging
def make_log_record_output(category, level, message,
format=None, datefmt=None, **kwargs):
"""
Create the output for a log record, like performed by :mod:`logging` module.
:param category: Name of the logger (as string or None).
:param level: Log lev... | bigcode/self-oss-instruct-sc2-concepts |
import base64
def _decode_endpoints(crypt: str) -> str:
"""Decode a GE endpoint."""
return base64.b64decode(crypt).decode('ascii') | bigcode/self-oss-instruct-sc2-concepts |
def get_center(im):
""" Given image, returns the location of center pixel
Returns
-------
(int, int): center of the image
"""
center_x = float(im.size[0]) / 2
center_y = float(im.size[1]) / 2
return int(center_x), int(center_y) | bigcode/self-oss-instruct-sc2-concepts |
import json
def captureCardTransactionPayload(amount, capture_reference):
"""
Create JSON payload for capture transaction API call
:param amount: Integer - Amount of currency's smallest denomination to be moved
:param capture_reference: String - A reference specified by the merchant to identify the tr... | bigcode/self-oss-instruct-sc2-concepts |
def get_team_player_links(league_soup):
"""NPBのsoupを解いてリンク集を取り出す関数
Args:
league_soup(BeautifulSoup): NPB leagueの一覧表
Return:
Dict:
{
2019:{
chunichi dragons: URL,
yokohama ba... | bigcode/self-oss-instruct-sc2-concepts |
def get_chunks(t_start, t_stop, n_chunks):
"""Group frame indices into given number of 'chunks'.
Args:
t_start (int): Frame index to start at (inclusive)
t_stop (int): Frame index to stop at (exclusive)
n_chunks (int): Number of chunks
Returns:
List of 2-tuples containing (... | bigcode/self-oss-instruct-sc2-concepts |
from datetime import datetime
def dt(txt, fmt='%Y-%m-%d'):
"""
Parse a text in YYYY-mm-dd format and returns a datetime.date.
"""
return datetime.strptime(txt, fmt).date() | bigcode/self-oss-instruct-sc2-concepts |
import re
def _at_notification(username, _sub=re.compile(r"[^\w'.-]*").sub):
"""Produce the @DisplayName notification normazilation form"""
return "@" + _sub("", username) | bigcode/self-oss-instruct-sc2-concepts |
def update_particle(position_update, velocity_update, state, nbest_topology,
idx_particle):
""" Update function for a particle.
Calculates and updates the velocity and position of a particle for a
single iteration of the PSO algorithm. Social best particle is determined
by the state... | bigcode/self-oss-instruct-sc2-concepts |
import re
def parse_graphicspath(fname):
"""Parse "\grapchicspath" and return the result as a list object."""
with open(fname) as f:
s = f.read()
l = re.findall('.*graphicspath.*', s)
graphicspath = ['./']
if l:
for i in re.sub('(^.*?{)|(\s*}$)', '', l[-1]).split(','):
... | bigcode/self-oss-instruct-sc2-concepts |
import math
def hard_negative_mining(loss, labels, neg_pos_ratio):
"""
It used to suppress the presence of a large number of negative prediction.
It works on image level not batch level.
For any example/image, it keeps all the positive predictions and
cut the number of negative predictions to mak... | bigcode/self-oss-instruct-sc2-concepts |
import pathlib
def list_dirs(directory):
"""Returns all directories in a train directory
"""
return [folder for folder in pathlib.Path(directory).iterdir()
if folder.is_dir()] | bigcode/self-oss-instruct-sc2-concepts |
def nofirst(l):
"""
Returns a collection without its first element.
Examples
--------
>>> nofirst([0, 1, 2])
[1, 2]
>>> nofirst([])
[]
"""
return l[1:] | bigcode/self-oss-instruct-sc2-concepts |
def clean_code(code):
"""Escape newlines."""
return code.replace('\n', '\\n') | bigcode/self-oss-instruct-sc2-concepts |
def find_first1(l, pred):
"""
Find first occurrence in list satisfying predicate.
:param l: list.
:param pred: predicate on the list elements.
:return: index of first occurrence in list satisfying predicate; length of the list if not found.
"""
length = len(l)
index = length
for i in... | bigcode/self-oss-instruct-sc2-concepts |
def pack(x: int, y: int, z: int) -> int:
"""
Pack x, y, and z into fields of an 8-bit unsigned integer.
x: bits 4..7 (4 bits)
y: bits 2..3 (2 bits)
z: bits 0..1 (2 bits)
"""
word = (x << 4) | (y << 2) | z
return word | bigcode/self-oss-instruct-sc2-concepts |
def no_replace(f):
"""
Method decorator to indicate that a method definition shall
silently be ignored if it already exists in the target class.
"""
f.__no_replace = True
return f | bigcode/self-oss-instruct-sc2-concepts |
def read_centers(file='year_centers.txt'):
"""
Read text file of array centers. three numbers per
line: year of coverage, longitude, latitude.
Returns dict of lon,lat pairs (list) indexed by integer
year.
"""
centers={}
# More elegant method is to use with, but not necessary
# for ... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Tuple
def interval_overlap(a: Tuple[int, int], b: Tuple[int, int]) -> int:
"""
Calculate the overlap between two intervals
Example: a=(10, 30) and b=(20, 40) gives an overlap of 10
"""
return max(0, min(a[1], b[1]) - max(a[0], b[0])) | bigcode/self-oss-instruct-sc2-concepts |
def update_config(original, update, override=True):
"""
Recursively update a dict.
Subdict's won't be overwritten but also updated.
"""
for key, value in update.items():
if key not in original or (not isinstance(value, dict) and override):
original[key] = value
else:
... | bigcode/self-oss-instruct-sc2-concepts |
from datetime import datetime
def timestamp2str(t, fmt='%Y-%m-%d %H:%M:%S.000'):
"""Converts a unix timestamp into a formatted string."""
return datetime.fromtimestamp(t).strftime(fmt) | bigcode/self-oss-instruct-sc2-concepts |
from typing import Iterable
import math
from functools import reduce
def least_common_multiple(seq: Iterable[int]) -> int:
"""
Least common multiple of positive integers.
:param seq: sequence of numbers
:return: LCM
"""
def lcm(num1: int, num2: int) -> int:
return num1 * num2 // math.... | bigcode/self-oss-instruct-sc2-concepts |
def generate_flake8_command(file: str) -> str:
"""
Generate the flake8 command for a file.
Parameters
----------
file : str
The file to fix.
Returns
-------
str
The flake8 command.
"""
cmd = f"flake8 {file}"
return cmd | bigcode/self-oss-instruct-sc2-concepts |
def decomp(val):
""" Returns the absolute value of a one's complement negative number """
c = 1
while val * 2 > c:
val = val ^ c
c = c << 1
return val | bigcode/self-oss-instruct-sc2-concepts |
def extract_id(object_or_id):
"""Return an id given either an object with an id or an id."""
try:
id = object_or_id.id
except AttributeError:
id = object_or_id
return id | bigcode/self-oss-instruct-sc2-concepts |
def validate_header(fields, required):
""" Validate the header line in a source file.
Parameters
----------
fields : list of str
Each element is the name of a field from a header line
required : set of str
Each element is the name of a required field
Returns
--... | bigcode/self-oss-instruct-sc2-concepts |
def fill_with_neg_inf(t):
"""FP16-compatible function that fills a tensor with -inf."""
return t.float().fill_(float('-inf')).type_as(t) | bigcode/self-oss-instruct-sc2-concepts |
import jinja2
def make_jinja_env(templates_dir):
"""
Create the default Jinja environment given the template folder.
Parameters
----------
templates_dir : str or pathlib.Path
The path to the templates.
Returns
-------
env : jinja2.Environment
The environment used to r... | bigcode/self-oss-instruct-sc2-concepts |
def p_test_loc_uty(α_spt, p_lt, p_li, p_e):
"""Local test pressure unity check.
Reference:
DNVGL-ST-F101 (2017-12)
sec:5.4.2.1 eq:5.6 p:93
(local_test_press_unity)
"""
p_lt_uty = (p_li - p_e) * α_spt / p_lt
return p_lt_uty | bigcode/self-oss-instruct-sc2-concepts |
def _generator_transfer(m, t):
"""
Constraint rule for electricity generation in generator
@ In, m, pyo.ConcreteModel, model containing problem
@ In, t, int, time indexer
@ Out, constraint, bool, constraining evaluation
"""
return - m.elec_generator_production[0, t] == 2.0 * m.elec_generator_produ... | bigcode/self-oss-instruct-sc2-concepts |
def getSparkFrameFromCSV(sparkSession, localFileSystemPath, selectionColumns=None):
"""
This function returns a sparkSession dataframe from the provided csv file path
Syntax:
status, message, df = getSparkFrameFromCSV(sparkSession, "/path/to/data/dataset.csv")
Args:
sparkSessio... | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
import pathlib
from typing import Dict
from typing import Any
import pickle
def _open_hydra_pickles(paths: List[pathlib.Path]) -> Dict[str, Any]:
"""Open pickles in directory of Hydra log and return dict of data.
Parameters
----------
paths : List[pathlib.Path]
Paths t... | bigcode/self-oss-instruct-sc2-concepts |
def jaccard_distance(context_tokens: list[str], category_tokens: list[str]):
"""Simple function for calculating Jaccard Distance
Args:
context_tokens (list[str]): List of context words (i.e. target words)
category_tokens (list[str]): List of words in category
Returns:
[float]: Valu... | bigcode/self-oss-instruct-sc2-concepts |
def get_vars(varstr):
"""Gets 2d variable labels from a single string"""
variables = ['x', 'y', 'z', 'px', 'py', 'pz', 't']
#all_2d_vars = {}
for var1 in variables:
for var2 in variables:
if(varstr == f'{var1}{var2}'):
return [var1,var2] | bigcode/self-oss-instruct-sc2-concepts |
def query(port, prop, repo=False):
"""Query q property of a package."""
args = ("pkg", "rquery" if repo else "query", port.attr["pkgname"])
if prop == "config":
args += ("%Ok %Ov",)
else:
assert not "unknown package property '%s'" % prop
return args | bigcode/self-oss-instruct-sc2-concepts |
def next_event_name(trace: list, prefix_length: int):
"""Return the event event_name at prefix length or 0 if out of range.
"""
if prefix_length < len(trace):
next_event = trace[prefix_length]
name = next_event['concept:name']
return name
else:
return 0 | bigcode/self-oss-instruct-sc2-concepts |
def is_xlsx(filename: str) -> bool:
"""Checks if a filename suggests a file is an .xlsx file"""
return filename.endswith(".xlsx") | bigcode/self-oss-instruct-sc2-concepts |
def update_mean(mean, n, x, remove=False):
"""Calculates the updated mean of a collection on adding or removing an element. Returns 0 mean if updated number of elements become 0.
Args:
mean (float): current mean of the collection
n (int): current number of elements in the collection
x (... | bigcode/self-oss-instruct-sc2-concepts |
def rule_nr_to_rule_arr(number, digits, base=2):
"""Given a rule `number`, the number of cells the neighbourhood has
(as `digits`) and the `base` of the cells, this function calculates the
lookup array for computing that rule.
>>> rule_nr_to_rule_arr(110, 3)
[0, 1, 1, 1, 0, 1, 1, 0]
>>> rule_nr... | bigcode/self-oss-instruct-sc2-concepts |
def int_enum(cls, val):
"""Get int enum value.
Parameters
----------
cls : `type`
Int enum class.
val : `int` or `str`
Name or value.
Returns
-------
`IntEnum`
Raises
------
ValueError
"""
if isinstance(val, str):
val = val.upper()
t... | bigcode/self-oss-instruct-sc2-concepts |
def cummulative_sum(x):
"""Returns the cummulative sum of elements of a list."""
# Create a copy of list x.
output = x[:]
for i in range(len(output) - 1):
output[i + 1] += output[i]
return output | bigcode/self-oss-instruct-sc2-concepts |
def rivers_with_station(stations):
"""Returns a set with the names of rivers
that have a monitoring station
"""
rivers = set()
for station in stations:
if station.river != None:
rivers.add(station.river)
return rivers | bigcode/self-oss-instruct-sc2-concepts |
def author_media_location(instance, filename):
"""Return the location of a stored media file for an Author."""
author_id = instance.id
image_type = filename.rpartition(".")[2]
return f"workflow_system/authors/{author_id}/profileImage.{image_type}" | bigcode/self-oss-instruct-sc2-concepts |
def get_sub_image_coords(coords, region_size, x_parts, y_parts):
"""
If an image is divided into sub_images, return a list of coordinates
for all the sub-images.
Parameters
==========
coords: list of floats, [long,lat]
region_size: float, size of square image in degrees long,loat
x_part... | bigcode/self-oss-instruct-sc2-concepts |
def p() -> float:
"""``p`` in the top-."""
return 0.9 | bigcode/self-oss-instruct-sc2-concepts |
def validate_attr(attr, table_cols, attr_label, table_label):
"""Check if the attribute exists in the table."""
if attr not in table_cols:
raise AssertionError(attr_label + ' \'' + attr + '\' not found in ' + \
table_label)
return True | bigcode/self-oss-instruct-sc2-concepts |
def updated_dict(d, only_existing=True, **updates):
"""
Update dictionary `d` with `updates`, optionally changing `only_existing` keys.
* d: dict
* only_existing: do not add new keys, update existing ones only
* updates: dict
:return: updated dictionary
"""
d = d.copy()
if only_exis... | bigcode/self-oss-instruct-sc2-concepts |
def filter_irr(df, irr_col, low, high, ref_val=None):
"""
Top level filter on irradiance values.
Parameters
----------
df : DataFrame
Dataframe to be filtered.
irr_col : str
String that is the name of the column with the irradiance data.
low : float or int
Minimum va... | bigcode/self-oss-instruct-sc2-concepts |
def break_camelcase_pythonic(string: str) -> str:
"""Breaks camelcase string (pythonic).
Args:
string (str): as string
Examples:
>>> assert break_camelcase_pythonic("helloWorld") == "hello World"
"""
return "".join(f" {item}" if item.isupper() else item for item in string) | bigcode/self-oss-instruct-sc2-concepts |
import pickle
def load_results_dict(pickle_filename):
"""
Load results in a dict that have been pickled.
Parameters
----------
pickle_filename : str
DESCRIPTION. String with the filename we are loading results from
Returns
-------
results_dict : dict
DESCRIPTION. Dict... | bigcode/self-oss-instruct-sc2-concepts |
def get_clean_block(block):
"""Clean up unicode characters and common OCR errors in blocks"""
replacements = {'fi': 'fi',
'fl': 'fi',
'—': '-',
"’": "'",
"‘": "'",
'”': '"',
'“': '"',
... | bigcode/self-oss-instruct-sc2-concepts |
def read_diff_file(filename):
"""Read the diff file in its entirety."""
with open(filename) as fd:
content = fd.read()
return content | bigcode/self-oss-instruct-sc2-concepts |
def remove_multicollinearity_by_coefficient_threshold(df, method = 'spearman', coefficient_threshold = 0.7):
"""
Uses the correlation between features and a specified threshold to
identify and remove collinear/multicollinear features.
Args:
df ([pandas.DataFrame]):
A dataframe tha... | bigcode/self-oss-instruct-sc2-concepts |
def get_dir_edges_from_c_to_tars(c_to_tars):
"""
Returns tuple of all allowed directed edges (c, t) where c control
and t target.
Parameters
----------
c_to_tars : dict[int, list[int]]
a dictionary mapping j in range(num_qbits) to a list, possibly
empty, of the physically allowe... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def initial_state(hparams):
""" Samples a random initial state. """
B = hparams.batch_size
L = hparams.lattice_size
num_particles = round(hparams.concentration * L**2)
# choose sites that get a particle. Bose-Hubbard allows multiple particles per site.
if hparams.potential.starts... | bigcode/self-oss-instruct-sc2-concepts |
def seconds_to_str(s: int) -> str:
"""
Returns a string describing the given number of seconds in a human-readable form.
"""
s = abs(s)
result = []
days = s // 86400
if days:
result.append('{} day{}'.format(days, '' if days == 1 else 's'))
hours = s // 3600 % 24
if hours:
... | bigcode/self-oss-instruct-sc2-concepts |
import collections
import re
def key_assignments_from_file(file_path):
"""
Return the key assignments found in the given file, as a
collections.OrderedDict mapping each key to its text meaning.
The file syntax and semantics are detailed in
AnnotateShell.do_load_keys().
This function is meant... | bigcode/self-oss-instruct-sc2-concepts |
def _dec_out_formatter(out):
"""Converts PyTorch int sequences (word ids) to Python integers."""
res = []
for seq in out:
tmp = []
for elem in seq:
elem = elem.to('cpu').numpy()
if len(elem.shape) == 0:
elem = elem.item()
tmp.append(elem)
... | bigcode/self-oss-instruct-sc2-concepts |
import json
def load_map(map_path):
"""Load map in json format and return a dic
Args:
map_path (str): Path to json file
Returns:
map_dict: Map as dictionary.
"""
with open(map_path) as map_handle:
map_dict = json.load(map_handle)
return map_dict | bigcode/self-oss-instruct-sc2-concepts |
import re
def __capitalize_hexadecimals(source):
""" Capitalize all hexadecimal strings
:param source: The source CSS string
:return: The CSS string with all hexadecimal values capitalized
"""
def found(match):
return match[0].replace(match[1], match[1].lower())
return re.sub(r'... | bigcode/self-oss-instruct-sc2-concepts |
def squash_to_unit_interval(x: float, constant: float) -> float:
"""Scales non-negative x to be in range [0, 1], with a squash."""
if constant <= 0:
raise ValueError('Squash constant must be greater than zero.')
if x < 0:
raise ValueError('Squash can only be performed on a positive value.')
return x / (... | bigcode/self-oss-instruct-sc2-concepts |
import random
def uniformFloat(lo, hi):
"""
Return a number chosen uniformly from the range [lo, hi).
"""
return random.uniform(lo, hi) | bigcode/self-oss-instruct-sc2-concepts |
def levenshtein(s, t):
"""
Computes the levenschtein distance between two strings of text
This is borrowed code and has been checked, but stay careful
:param s: first string of text
:param t: second string of text
:return: a distance measure, not normalized
"""
if s == "":
return... | bigcode/self-oss-instruct-sc2-concepts |
import random
import time
def get_pick(pick_status):
"""
This function takes one argument of variable type and returns an intger.
It checks to see if it's the first round and randomly chooses a starting player
if it is the first round. Otherwise, it simply returns the argument passed (an integer determining
whose... | bigcode/self-oss-instruct-sc2-concepts |
def func_name(func):
"""
Return the name of the function, or None if `func` is None.
"""
return None if func is None else func.__name__ | bigcode/self-oss-instruct-sc2-concepts |
def find_short(s):
""" Given a string of words, return the length of the shortest word(s)."""
return min(len(x) for x in s.split()) | bigcode/self-oss-instruct-sc2-concepts |
def arraytize(v):
"""
convenience function that "transforms" its arguments
into a list. If the argument is already a list, returns
it. If the argument is None, returns an empty list.
Otherwise returns [argument].
"""
if v is None:
return []
try :
return list(v)
excep... | bigcode/self-oss-instruct-sc2-concepts |
def sort_freqs(freqs):
"""Sort a word frequency histogram represented as a dictionary.
Parameters
----------
freqs : dict
A dict with string keys and integer values.
Return
------
items : list
A list of (count, word) pairs.
"""
items = freqs.items()
items.sort(key =... | bigcode/self-oss-instruct-sc2-concepts |
def get_precision(n):
"""
Get precision.
Parameters
----------
n : dict
Confusion matrix which has integer keys 0, ..., nb_classes - 1;
an entry n[i][j] is the count how often class i was classified as
class j.
Returns
-------
float
precision (in [0, 1])... | bigcode/self-oss-instruct-sc2-concepts |
def get_clean_name(name):
"""
A convenience function for naming the output files.
:param name: A name of the target file.
:returns: The name suffixed with "_clean" and the file extension.
"""
name = name.split(".")
name = name[0] + "_clean." + name[1]
return name | bigcode/self-oss-instruct-sc2-concepts |
def add_unary_magic_methods(np_funcs, translate_func):
"""Class decorator to add unary magic methods using NumPy to the class."""
def wrapper(cls):
for fname, np_func in np_funcs:
def magic_func(self, np_func=np_func):
return translate_func(self, np_func)
setatt... | bigcode/self-oss-instruct-sc2-concepts |
def reformat_trademarks(data):
"""
Reformats the trademarks data to global standard.
:param data: unformatted data
:return: Formatted data
"""
for key,val in data.items():
if val == ["-"]:
new_val = []
else:
new_val = [{
"Name": ele[0],
... | bigcode/self-oss-instruct-sc2-concepts |
def quality_score_to_string(score: int) -> str:
"""Returns the string representation for the given quality score.
We add 33 to the score because this is how the quality score encoding is
defined. Source:
https://support.illumina.com/help/BaseSpace_OLH_009008/Content/Source/Informatics/BS/QualityScoreEncoding_s... | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
def octet_list_to_int(octet_list: List[int]) -> int:
"""
Convert octet list to integer.
:param octet_list: Octet list to convert.
:returns: Converted integer.
"""
result = 0
for octet in octet_list:
result <<= 8
result += octet
return result | bigcode/self-oss-instruct-sc2-concepts |
def get_host_replica(volume, host_id):
"""
Get the replica of the volume that is running on the test host. Trigger a
failed assertion if it can't be found.
:param volume: The volume to get the replica from.
:param host_id: The ID of the test host.
:return: The replica hosted on the test host.
... | bigcode/self-oss-instruct-sc2-concepts |
def delete_border_detections(chip_detections, chip_w, border_delete_amount):
"""Deletes detections near borders. This is to make merging of several slided inference patches easier.
The function is implemented vectorized and is therefore lightning fast.
Args:
chip_detections (list): List of np.array... | bigcode/self-oss-instruct-sc2-concepts |
def mosaic_name(pairs_param):
"""
Generates a filename for the mosaic. Concatenating the pair names would be very long so instead we combine the last
four numbers of the product_id's.
"""
return ''.join(
[
f'{pair["left"][-5:-1]}-{pair["right"][-5:-1]}_'
for pair in p... | bigcode/self-oss-instruct-sc2-concepts |
def add(x, y):
"""
Returns x+y
Parameter x: The first number to add
Precondition: x is an int or float
Parameter y: The second number to add
Precondition: y is an int or float
"""
return x+y | bigcode/self-oss-instruct-sc2-concepts |
def strip_uri_host_and_path(concept_uri):
"""remotes the host and path from a URI, returning only the final resource name
"""
if concept_uri is None:
return None
rightmost_slash_position = concept_uri.rfind('/')
rightmost_colon_position = concept_uri.rfind(':')
simplified_start = max(0, ... | bigcode/self-oss-instruct-sc2-concepts |
def extra(request):
""" Add information to the json response """
return {'one': 123} | bigcode/self-oss-instruct-sc2-concepts |
def parseDockerAppliance(appliance):
"""
Takes string describing a docker image and returns the parsed
registry, image reference, and tag for that image.
Example: "quay.io/ucsc_cgl/toil:latest"
Should return: "quay.io", "ucsc_cgl/toil", "latest"
If a registry is not defined, the default is: "d... | bigcode/self-oss-instruct-sc2-concepts |
def getFilename(f):
"""Get the filename from an open file handle or filename string."""
if isinstance(f, str):
return f
return f.name | bigcode/self-oss-instruct-sc2-concepts |
def coordinates(location):
"""Return a (lat, lng) tuple from an OpenCage location result
location: a dict (from opencage.geocoder.OpenCageGeocode.geocode)
"""
geometry = location['geometry']
return geometry['lat'], geometry['lng'] | bigcode/self-oss-instruct-sc2-concepts |
def m_seq_inx0_sort_in_list(seq, args=False):
"""
对列表中单个列表按第一个元素排序,返回新的列表
:param seq: 列表形成的列表
:param args: 是否倒序 True or False
:return: 排序后的列表
example:
:seq [['20160708', 'gyf'], ['20180505', 'zme'], ['20170101', 'zkp']]
:args True
... | bigcode/self-oss-instruct-sc2-concepts |
def cubes(l=[1, 2, 3]):
"""
task 0.5.29
implement one line procedure taking list of integers 'l'
output should be a list of numbers whose 'i'th element is the cube of the 'i'th element of 'l'
e.g. input[1, 2, 3] output[1, 8, 27]
def cubes(l=[1, 2, 3]): return [i ** 3 for i in l]
"""
... | bigcode/self-oss-instruct-sc2-concepts |
import re
def validate_date(date: str) -> dict:
"""
Validate provided date data.
Desired format: YYYY or YYYY-MM (2021 or 2021-12).
"""
# regex patters
rp_year_month = re.compile('^(20[0-9]{2})-((0[1-9])|(1[0-2]))$')
rp_year = re.compile('^(20[0-9]{2})$')
# Match year-month object
... | bigcode/self-oss-instruct-sc2-concepts |
def has_material(obj, name):
"""check if obj has a material with name"""
return name in obj.data.materials.keys() | bigcode/self-oss-instruct-sc2-concepts |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.