seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
import re
def findReadPosition(fullAssembly, read, label=''):
"""Finds the index of a given target (read) inside the context (fullAssembly)
========================================= context
-------------- target
^ ^
startIndex ... | bigcode/self-oss-instruct-sc2-concepts |
def quantize_float(f, q):
"""Converts a float to closest non-zero int divisible by q."""
return int(round(f / q) * q) | bigcode/self-oss-instruct-sc2-concepts |
def generate_avatar_path(obj, filename):
""" Generates an unique path to user's avatar dir according to user's id. """
return 'images/avatars/' + str(obj.id) + '/' + filename | bigcode/self-oss-instruct-sc2-concepts |
def merge_two_dicts(starting_dict: dict, updater_dict: dict) -> dict:
"""
Starts from base starting dict and then adds the remaining key values from updater replacing the values from
the first starting dict with the second updater dict.
Thus, the update_dict has precedence as it updates and replaces the... | bigcode/self-oss-instruct-sc2-concepts |
import re
from typing import Tuple
from typing import Optional
def get_year_data(match: re.Match, mixed: bool = False) -> Tuple[int, Optional[int]]:
"""Get year data from match."""
if mixed:
year_string, *_ = match.groups()
else:
_, year_string, *_ = match.groups()
if "-" in year_str... | bigcode/self-oss-instruct-sc2-concepts |
def dot(p1, p2):
"""Dot product 4-momenta"""
e = p1[0] * p2[0]
px = p1[1] * p2[1]
py = p1[2] * p2[2]
pz = p1[3] * p2[3]
return e - px - py - pz | bigcode/self-oss-instruct-sc2-concepts |
import shlex
def string_to_tokens(s):
"""
Converts string to list of tokens, with support for quotes.
Defined here for convenience.
See shlex documentation for more information on parsing rules:
https://docs.python.org/2/library/shlex.html#parsing-rules
:param s: string "a b 'c d' e"
:re... | bigcode/self-oss-instruct-sc2-concepts |
def in_list(collection_list):
"""Return true if test is in collection"""
if "test" in str(collection_list): return True
else: return False | bigcode/self-oss-instruct-sc2-concepts |
def library_dilution_calculator_fixed_volume(concentration, size, ul):
"""Calculate ng per sample (based on given ul_sample) needed for multiplexing."""
nM_DNA = (float(concentration)*(10.0**6.0))/(660*float(size))
ng_sample = (660*float(size)*nM_DNA*ul)/(10.0**6.0)
return ng_sample | bigcode/self-oss-instruct-sc2-concepts |
def _format_timedelta(timedelta):
"""Convert timedelta to string, lopping off microseconds."""
# This approach probably looks awful to all you time nerds, but it will work
# in all the locales we use in-house.
return str(timedelta).split('.')[0] | bigcode/self-oss-instruct-sc2-concepts |
def genPPG(prices, weights):
"""
Generates low and high price per gram amounts for an item
returns an array, with first element being low, and second element being high
if there is only one variant of an item, a single element array will be returned
"""
try:
assert(prices... | bigcode/self-oss-instruct-sc2-concepts |
def add_carry_bits(res, carry, MASK=0xFFFFFFFF):
"""Adds bits at each position
1 + 1 = 0
1 + 0 = 1
Examples:
>>> res, carry = int("0101", 2), int("0011", 2)
>>> bin(add_carry_bits(res, carry))
'0b110'
"""
return (res ^ carry) & MASK | bigcode/self-oss-instruct-sc2-concepts |
import json
def is_string_json_loadable(string: str):
"""
Determine if the serialized dictionary is a JSON object.
Rather than constructing a complicated regex pattern, a simple try/except of the json.load should suffice.
"""
try:
json.loads(string)
return True
except json.JSO... | bigcode/self-oss-instruct-sc2-concepts |
import struct
def byte2py_int(data):
"""
Converts byte to Python int value.
"""
return struct.unpack('B', data)[0] | bigcode/self-oss-instruct-sc2-concepts |
def _get_interval_domain_min(dom):
""" Get the lower bound of an interval domain
Args:
dom: Domain
Returns:
Domain min value
"""
return dom[0] if isinstance(dom, tuple) else dom | bigcode/self-oss-instruct-sc2-concepts |
def create_decompose_file_name(hw_details, decompose_param_obj):
"""
Creates file name for output of decompose process using hw_details_class obj and schedule_param obj
"""
fname = ""
fname += str(hw_details.tree_depth)
fname += str(hw_details.n_tree)
fname += decompose_param_obj.str_fname()
return... | bigcode/self-oss-instruct-sc2-concepts |
import re
def to_snake(string):
"""
Converts to snake case.
:param string: A target string.
:return: Converted string.
"""
return re.sub(r'(?<!^)(?=[A-Z])', '_', string).lower() | bigcode/self-oss-instruct-sc2-concepts |
def with_metaclass(mcls):
"""
For metaclass compatibility between Python 2 and 3.
cf. http://stackoverflow.com/questions/22409430/portable-meta-class-between-python2-and-python3
"""
def decorator(cls):
body = vars(cls).copy()
# clean out class body
body.pop('__dict__', None)... | bigcode/self-oss-instruct-sc2-concepts |
import inspect
def get_keyword_names(obj):
"""Returns a list of method names for the given object
This excludes methods that begin with an underscore, and
also excludes the special method `get_keyword_names`.
"""
names = [
member[0]
for member in inspect.getmembers(obj, inspect.is... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Optional
def parse_key(headers) -> Optional[str]:
"""
Parses the header for an API key, and returns it if found.
The authorization header must be in the following format: ``Token <api key>``.
:param headers: A dictionary of request headers
:return: If present, the key pa... | bigcode/self-oss-instruct-sc2-concepts |
def _receptor_standard_config(config):
"""Set standard config for network with receptor layer."""
config.data_dir = './datasets/proto/relabel_200_100'
config.receptor_layer = True
config.ORN_NOISE_STD = 0.1
config.kc_dropout_rate = 0.
config.lr = 1e-4 # For receptor, this is the default LR
... | bigcode/self-oss-instruct-sc2-concepts |
def validate_both(first_validator, second_validator):
"""Make sure both validators pass"""
def validate(cursor_trail, tree):
return (first_validator(cursor_trail, tree)
and second_validator(cursor_trail, tree))
return validate | bigcode/self-oss-instruct-sc2-concepts |
def repeat_flaky_test(test, n_repeats=2, n_allowed_failures=0, *args, **kwargs):
"""
Run the given test `n_repeats` times, raising the `n_allowed_failures+1`^th assertion error.
Parameters
----------
test : Callable[Any, V]
test to wrap
n_repeats : int, optional
number of times ... | bigcode/self-oss-instruct-sc2-concepts |
def maximum_border_length(w):
"""Maximum string borders by Knuth-Morris-Pratt
:param w: string
:returns: table f such that f[i] is the longest border length of w[:i + 1]
:complexity: linear
"""
n = len(w)
f = [0] * n # init f[0] = 0
k = 0 # current lo... | bigcode/self-oss-instruct-sc2-concepts |
def hash_object(object_):
"""
Returns the hash value of the given object even if it not defines `__hash__`.
Parameters
----------
object_ : `Any`
The object to get it's hash value of.
Returns
-------
hash_value : `int`
"""
try:
hash_value = hash(object_)... | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
def read_ta_list(fname: str)->List[str]:
""" Read total list of TAs from a file with one TA roll number per line"""
tfile = open(fname,"r")
tas = []
for l in tfile:
s=l.strip()
if (len(s)==0):
continue
tas.append(s.lower())
return tas | bigcode/self-oss-instruct-sc2-concepts |
import math
def sum_of_divisors_v2(n):
"""Find the sum of all divisors of a given integer.
NOTE: If we look carefully, all the divisors are present in pairs. For
example if n = 100, then the various pairs of divisors are: (1,100),
(2,50), (4,25), (5,20), (10,10).
resource: https://www.geeksforgeek... | bigcode/self-oss-instruct-sc2-concepts |
def replace_vol(img, vol, center, vol_as_mask=None):
"""Replace a volume within an image, centering on the given coordinates
and cropping the input volume to fit.
Args:
img: Image as a Numpy array into which ``vol`` will be placed.
``img`` will be updated in-place.
vol: Volume... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def max_loss(predict,target):
"""return max value of predict - target"""
return torch.max(torch.abs(predict-target)) | bigcode/self-oss-instruct-sc2-concepts |
import re
import string
from typing import Counter
def get_words(text):
"""Retrieve the words present in a given string of text.
The return value is a list of tuples where the first member is a lowercase word,
and the second member the number of time it is present in the text. Example:
IN: "Did th... | bigcode/self-oss-instruct-sc2-concepts |
def create_put_request(item):
"""Create a PutRequest object."""
return {'PutRequest': {'Item': item}} | bigcode/self-oss-instruct-sc2-concepts |
def filter_invalid_unicode(text):
"""Return an empty string and True if 'text' is in invalid unicode."""
return ("", True) if isinstance(text, bytes) else (text, False) | bigcode/self-oss-instruct-sc2-concepts |
import json
def get_city_from_string(ctx: str):
"""
Parses the city out of the JSON contained in the given string.
:param ctx: a string containing JSON.
:return: (city id, city name) tuple or (None, None) if not found.
"""
js = json.loads(ctx)
for j in js["data"]:
if "iglu:com.dbi... | bigcode/self-oss-instruct-sc2-concepts |
def toBytes(b):
"""
Converts a string to a bytes object by encoding it as utf-8.
"""
if type(b) == str:
return b.encode("utf-8")
else:
return b | bigcode/self-oss-instruct-sc2-concepts |
def read_file_to_string(path):
"""
Returns the contents of a file at ``path`` as a string.
:param path: A path string
:return: Contents of the file as a string
:raises FileNotFoundError: If ``path`` does not exist
:raises UnicodeDecodeError: If file does not contain UTF-8/ASCII text
"""
... | bigcode/self-oss-instruct-sc2-concepts |
def _pos_trace_func(state):
"""Trace function which records the state position (pos) component."""
return {'pos': state.pos} | bigcode/self-oss-instruct-sc2-concepts |
def strip_wikilink_to_article(wikilink):
"""Strip wikilink to article.
Parameters
----------
wikilink : str
Wikilink
Returns
-------
stripped_wikilink : str
String with stripped wikilink.
Examples
--------
>>> strip_wikilink_to_article('[[dansk (sprog)|dansk]]'... | bigcode/self-oss-instruct-sc2-concepts |
def is_empty(module, container_name, facts):
"""
Check if container can be removed safely.
To be removed, a container shall not have any container or
device attached to it. Current function parses facts to see if a device or
a container is attached. If not, we can remove container
Parameters
... | bigcode/self-oss-instruct-sc2-concepts |
def convert_to_dict(data):
"""Returns a dictionary of US state and the total number of COVID-19 cases as key-value pairs.
Parameters:
data (list): a list of lists that contain states and total number of cases
Returns:
dict: a dictionary that contains state and the total number of cases as ... | bigcode/self-oss-instruct-sc2-concepts |
def SUBTRACT(x, y):
"""
Subtracts two numbers to return the difference,
or two dates to return the difference in milliseconds,
or a date and a number in milliseconds to return the resulting date.
See https://docs.mongodb.com/manual/reference/operator/aggregation/subtract/
for more details
:p... | bigcode/self-oss-instruct-sc2-concepts |
def cc(key):
"""
Changes python key into Camel case equivalent. For example, 'compute_environment_name' becomes
'computeEnvironmentName'.
:param key:
:return:
"""
components = key.split('_')
return components[0] + "".join([token.capitalize() for token in components[1:]]) | bigcode/self-oss-instruct-sc2-concepts |
def clamp(n, smallest, largest):
"""Ensure 'n' is no smaller or larger then a certain range.
If the number is smaller than the range it will be returned as
the smallest.
If the number is larger than largest it will be returned as the
largest.
Args:
n (int): integer to inspect
... | bigcode/self-oss-instruct-sc2-concepts |
def run_verbose(message, fn, args=[]):
"""
Calls the function provided by 'fn' with the parameters provided in 'args'.
Prints '[message] ... done', with '[message] ...' printed at the start of
the function call and 'done' printed at the end of the function call.
"""
print('{} ...'.format(message... | bigcode/self-oss-instruct-sc2-concepts |
def xtick_formatter(x, pos):
"""
A formatter used in main_paper function to divide
ticks by specific amount.
From Stackoverflow #27575257
"""
s = '%d' % int(x / 1000)
return s | bigcode/self-oss-instruct-sc2-concepts |
def sum_htcl_branches(nested_dict, adj_frac, sum_val):
"""Sum all leaf node values under a given nested dict level.
Args:
nested_dict (dict): The nested dict with values to sum.
adj_frac (dict): Adjustment fraction to apply to values.
sum_val (dict): Summed values.
Returns:
... | bigcode/self-oss-instruct-sc2-concepts |
def remove_undefined(payload: dict) -> dict:
"""Takes a dictionary and removes keys without value"""
return {name: value for name, value in payload.items() if value is not None} | bigcode/self-oss-instruct-sc2-concepts |
import socket
def send_all(s, text, stutdown_after_sending=True):
"""send_all(socket, text, stutdown_after_sending=True)
Send all text to the socket. Used during handshaking and in
the clientserver module.
If stutdown_after_sending, the socket is shut down. Some protocols
rely on this.
It i... | bigcode/self-oss-instruct-sc2-concepts |
def adjust_repeat_data(li, suffix='+'):
""" 分析序列li里的值,对出现重复的值进行特殊标记去重
:param li: list,每个元素值一般是str
:param suffix: 通过增加什么后缀来去重
:return: 新的无重复数值的li
>>> adjust_repeat_data(['a', 'b', 'a', 'c'])
['a', 'b', 'a+', 'c']
"""
res = []
values = set()
for x in li:
while x in values:... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Any
def update(
dct: dict[str, Any],
dct_merge: dict[str, Any],
) -> dict[str, Any]:
"""Recursively merge dicts."""
if not isinstance(dct, dict):
return dct
for key, value in dct_merge.items():
if key in dct and isinstance(dct[key], dict):
dct[key] = ... | bigcode/self-oss-instruct-sc2-concepts |
import json
def to_json(response):
"""Convert raw response into json output."""
return json.dumps(response, indent=2) | bigcode/self-oss-instruct-sc2-concepts |
def mock_pack_data(name='SomePack'):
""" Creates mock data to create a pack. """
data = {
'name': name,
'submit': ''
}
return data | bigcode/self-oss-instruct-sc2-concepts |
import calendar
def millis(input_dt):
"""Convert datetime to milliseconds since epoch"""
# Python 3 (or 2 with future module)
return 1000 * int(calendar.timegm(input_dt.timetuple()))
# Python 2
# return 1000 * long(calendar.timegm(input_dt.timetuple()))
# return 1000 * long(time.mktime(input_d... | bigcode/self-oss-instruct-sc2-concepts |
import pickle
def load_data(filename):
"""Return a Data object loaded from the given pickle file."""
with open(filename, "rb") as f:
return pickle.load(f) | bigcode/self-oss-instruct-sc2-concepts |
def get_fields(db, fields_sql):
"""
Calls the database and gets fields information.
Input: database connection object, SQL query
Returns: dictionary of student information, key=field name
"""
fields = {}
with db.cursor() as cursor:
cursor.execute(fields_sql)
for id, name, fu... | bigcode/self-oss-instruct-sc2-concepts |
def first(predicate, iterable):
"""return first element in iterable that satisfies given predicate.
Args:
predicate: a function that takes one parameter and return a truth value.
iterable: any iterable, the items to check.
Return:
first element in iterable that satisfies predicate,... | bigcode/self-oss-instruct-sc2-concepts |
import string
import random
def random_string(count=10):
"""
Return a random string with the length of given count.
Args:
count: the count of random charactors to return. (default: 10)
Returns:
string, with random charactors, with the length of count.
"""
charactors = string.... | bigcode/self-oss-instruct-sc2-concepts |
def unflatten(data, dims):
""" Given a batch of flattened 1-D tensors, reshapes them into specified N-Dims. """
B = data.size(0)
return data.view(B, *dims) | bigcode/self-oss-instruct-sc2-concepts |
from typing import Tuple
def complete_index(index: Tuple, n_dims: int) -> Tuple:
""" Complete the index with empty slices.
This will expand ellipses if present, or pad at the end if not.
Args:
index:
The index in which to replace ellipses
n_dims:
The number of dim... | bigcode/self-oss-instruct-sc2-concepts |
def calc_PV_power(absorbed_radiation_Wperm2, T_cell_C, eff_nom, tot_module_area_m2, Bref_perC, misc_losses):
"""
To calculate the power production of PV panels.
:param absorbed_radiation_Wperm2: absorbed radiation [W/m2]
:type absorbed_radiation_Wperm2: float
:param T_cell_C: cell temperature [degr... | bigcode/self-oss-instruct-sc2-concepts |
def power_law_vband_norm(x, slope):
"""Power law normalised at 0.55 microns (V band)."""
return (x / 0.55) ** slope | bigcode/self-oss-instruct-sc2-concepts |
def get_chrom_sizes(fai_file, exclude_scaffolds=True):
"""
Get the names and sizes of all the chromosomes in a reference by iterating over the index.
"""
chroms = {}
with fai_file.open('r') as fin:
for line in fin:
# get the chrom name and size
contig, size, _, _, _ ... | bigcode/self-oss-instruct-sc2-concepts |
import pprint
def pformat_truncate(o, width=50):
"""Convert the object to printable representation and truncate it if too long
Note: If the object is a multiline string or pformat returns a multiline
string, only the first line of the string will be returned
Args:
o (object): Object to... | bigcode/self-oss-instruct-sc2-concepts |
def create_schema_name(account):
"""Create a database schema name."""
return f"acct{account}" | bigcode/self-oss-instruct-sc2-concepts |
def specific_match(versions, position=0):
"""Matches a specific position in a trie dict ordered by its keys
Recurse on the trie until it finds an end node (i.e. a non dict node)
Position = 0 indicates it will follow the first element
Position = -1 indicates it will follow the last element
"""
if... | bigcode/self-oss-instruct-sc2-concepts |
def divide_by_four(a):
"""Return a / 4.
"""
return a / 4.0 | bigcode/self-oss-instruct-sc2-concepts |
def int_tuple(arg):
"""Convert a string of comma separated numbers to a tuple of integers"""
args = arg.split(',')
try:
return tuple([int(e) for e in args])
except ValueError:
raise ValueError('Expected a comma separated list of integers, ' +
'found %s' % arg) | bigcode/self-oss-instruct-sc2-concepts |
def format_perc(x, dec_places=1):
"""
format_perc
x: a number to format as a percentage
dec_places: an integer for the number of digits past the decimal
"""
format_str = '{{:,.{}f}}%'.format(dec_places)
return format_str.format(float(100*x)) | bigcode/self-oss-instruct-sc2-concepts |
def find_service_roles(roles, type):
"""
Look for roles like spark_worker, spark_master, namenode, ... We will have duplicate roles depending on how many
host are running the same role
:param roles: list of service roles
:param type: the type of role we are looking for, ie "SPARK_MASTER"
:retur... | bigcode/self-oss-instruct-sc2-concepts |
def check_puppet_class(rec):
"""
Checks if the given file is a puppet class
:param rec: file path
:return: check result
"""
return rec.lower().endswith(".pp") | bigcode/self-oss-instruct-sc2-concepts |
import math
def surface_disque(rayon):
"""
fonction qui calcule et renvoie la surface du disque
:param rayon: le rayon du disque
:type rayon: int ou float
:return: la surface du disque (unité (au carré) de celle du rayon)
:rtype: float
"""
return math.pi*rayon**2 | bigcode/self-oss-instruct-sc2-concepts |
def get_datetime_str(record):
"""
Get the datetime string for a record.
Args:
record: the record to get data for.
Returns:
datetime string.
"""
return str(record.getDataTime())[0:19].replace(" ", "_") + ".0" | bigcode/self-oss-instruct-sc2-concepts |
def find_average_score(generation):
"""
Generation is a dictionary with the subjects and score.
Returns the average score of that generation
"""
sum = 0
for score in generation.values():
sum += score
return sum/len(generation.values()) | bigcode/self-oss-instruct-sc2-concepts |
import inspect
def method_name(caller_depth=0):
"""
Returns the name of the caller method.
"""
# Note: inspect.stack()[0][3] would return the name of this method.
return inspect.stack()[caller_depth+1][3] | bigcode/self-oss-instruct-sc2-concepts |
def _is_earlier(t1, t2):
"""Compares two timestamps."""
if t1['secs'] > t2['secs']:
return False
elif t1['secs'] < t2['secs']:
return True
elif t1['nsecs'] < t2['nsecs']:
return True
return False | bigcode/self-oss-instruct-sc2-concepts |
def eq_tokens(token_sequence1: str, token_sequence2: str) -> bool:
"""Returns True if bothe token sequences contain the same tokens,
no matter in what order::
>>> eq_tokens('red thin stroked', 'stroked red thin')
True
>>> eq_tokens('red thin', 'thin blue')
False
"""
retu... | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
from typing import Tuple
from typing import Any
def simple_producer(key, value) -> List[Tuple[Any, Any]]:
"""simple_producer A function that returns the key,value passed in for production via "KafkaProducerOperator"
:param key: the key for the message
:type key: Any
:param val... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def process_data(file_name, tokenizer, max_size=None):
"""Reads the line of a file and segments the lines using the tokenizer
Args:
file_name (str): Full file path
tokenizer (:obj:`WMT16Tokenizer`): The tokenizer to use
max_size (Optional[int]): The maximum size of result... | bigcode/self-oss-instruct-sc2-concepts |
def get_out_dir(request):
"""
Get the temporary output directory for writing files to
"""
return request.fspath.join("..") + "/tmp" | bigcode/self-oss-instruct-sc2-concepts |
def string_to_bytes(string):
"""
Convert a string to NULL-terminated ASCII string.
"""
return bytearray(string, encoding='ascii') + b'\x00' | bigcode/self-oss-instruct-sc2-concepts |
def isheader(string):
"""
Check if a string looks like a star header line.
Args:
string (str): line of a star file
Returns:
true if the line looks like a star file header lines
false if the line is expected to be a star file data line.
"""
try:
string = string.de... | bigcode/self-oss-instruct-sc2-concepts |
def tuple_setter(tensor, idx_tuple, val):
""" Sets a tensor element while indexing by a tuple"""
tensor_ = tensor
for el in idx_tuple[:-1]:
tensor_ = tensor_[el]
tensor_[idx_tuple[-1]] = val
return tensor | bigcode/self-oss-instruct-sc2-concepts |
def is_ask_help(text: str) -> bool:
"""
A utility method to tell if the input text is asking for help.
"""
sample_phrases = [
"help", "help me", "i need help", "i'm lost", "i am lost"
]
text = text.strip()
return any(text == phrase for phrase in sample_phrases) | bigcode/self-oss-instruct-sc2-concepts |
def minus(first, second):
"""The difference of two numbers"""
return first - second | bigcode/self-oss-instruct-sc2-concepts |
import math
def _find_poles(damping, freq):
"""Find roots of equation s^2+2hws+w^2=0
Parameters
----------
damping: float
Damping constant.
freq: float
Angular frequency.
"""
real = -damping*freq
imaginary = freq * math.sqrt(1 - damping*damping)
return real, imag... | bigcode/self-oss-instruct-sc2-concepts |
def pot_harmonic(x, x0, k):
"""
pot_harmonic(x, x0, k)
Returns harmonic potential from displacememt of x away from x0
"""
return k * (x - x0)**2 | bigcode/self-oss-instruct-sc2-concepts |
def int_to_mac(integer):
"""
Converts a an integer into a mac address, with `:` notation.
Arguments
---------
integer: int
Returns
-------
str
"""
first = "{:012x}".format(integer)[::2]
second = "{:012x}".format(integer)[1::2]
return ':'.join(a + b for a, b in ... | bigcode/self-oss-instruct-sc2-concepts |
def coord_2_id(x, y):
"""Give the pinID from the x,y coordinate."""
return (34 - y) * 34 + x | bigcode/self-oss-instruct-sc2-concepts |
from typing import Dict
from typing import Any
from typing import Mapping
import itertools
def is_cleanly_mergable(*dicts: Dict[Any, Any]) -> bool:
"""Check that nothing will be overwritten when dictionaries are merged using `deep_merge`.
Examples:
>>> is_cleanly_mergable({"a": 1}, {"b": 2}, {"c": 3... | bigcode/self-oss-instruct-sc2-concepts |
def emission_probability(symbol, word, emission_probabilities, symbol_counts):
"""
Takes a symbol, a word, a nested dictionary of emission probabilities,
and a dictionary of symbol counts
and returns the emission probability for that symbol and word
If the word has not been encountered in the traini... | bigcode/self-oss-instruct-sc2-concepts |
def _make_qa_class(type_class, mode_class, p_name, p_description, p_software):
"""Create and return a new class to represent a QA metric"""
class QA(type_class, mode_class):
name = p_name
__doc__ = p_description
software = p_software
QA.__name__ = p_name
return QA | bigcode/self-oss-instruct-sc2-concepts |
import re
def __highlight_fuzzy_string(target: str, search_value: str) -> str:
"""
Highlight every existence of target in the search_value with the <em> tag.
This <em> tag can be replaces with any other tag.
:param target: the haystack to search in
:param search_value: the needle to search for ta... | bigcode/self-oss-instruct-sc2-concepts |
def url_file_name(url: str) -> str:
"""
Extract file name from url (last part of the url).
:param url: URL to extract file name from.
:return: File name.
"""
return url.split('/')[-1] if len(url) > 0 else '' | bigcode/self-oss-instruct-sc2-concepts |
def _add_box_and_whiskers(canvas, quantiles, limits):
"""Add a box and whiskers to the canvas"""
for jj in range(5):
canvas[quantiles[jj], limits[0] + 1 : limits[2]] = 20
canvas[quantiles[0] + 1 : quantiles[1], limits[1]] = 22
canvas[quantiles[3] + 1 : quantiles[4], limits[1]] = 22
canvas[... | bigcode/self-oss-instruct-sc2-concepts |
def convert_kicad_coor(edif_pt):
""" KiCAD schematic coordinates are 10 times EDIF
Y axis is flipped
"""
scale = 10
return [edif_pt[0] * scale, -edif_pt[1] * scale] | bigcode/self-oss-instruct-sc2-concepts |
def fake_request(*responses):
"""
Creates a request function that returns the supplied responses, one at a time.
Making a new request after the last response has been returned results in a StopIteration error.
"""
iterator = (response for response in responses)
def request(method, url, **kwargs... | bigcode/self-oss-instruct-sc2-concepts |
def rovarspraket(english):
"""Translates input to rovarspraket"""
for low, upper in zip("bcdfghjklmnpqrstvwxyz", "BCDFGHJKLMNPQRSTVWXYZ"):
english = f"{upper}o{low}".join(f"{low}o{low}".join(english.split(low)).split(upper))
return english | bigcode/self-oss-instruct-sc2-concepts |
import re
def iscrcard(value):
"""
Return whether or not given value is a credit card.
If the value is a credit card, this function returns ``True``, otherwise ``False``.
Examples::
>>> iscrcard('375556917985515')
True
>>> iscrcard('5398228707871528')
False
:par... | bigcode/self-oss-instruct-sc2-concepts |
def compute_scale_factor(height, size):
"""
Compute gallery conversion scale factor as a percentage.
"""
landscape = True
source_width = size[0]
source_height = size[1]
if source_width < source_height:
landscape = False
if landscape:
return height/source_height * 100
... | bigcode/self-oss-instruct-sc2-concepts |
def utc_time(source):
"""Convert source bytes to UTC time as (H, M, S) triple
HHMMSS.000
>>> utc_time(b'123456.000')
(12, 34, 56.0)
"""
if source:
return int(source[:2]), int(source[2:4]), float(source[4:])
return None, None, None | bigcode/self-oss-instruct-sc2-concepts |
import re
def quoted_split(string_to_split, preserve_quotations=False):
"""
Function to split string into list of words but preserves quoted
sub strings.
found here: https://stackoverflow.com/a/51560564
Parameters
----------
string_to_split : string
the string to split
preser... | 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.