seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
def get_longest_repeating_substring(input_string: str) -> str:
"""
Algorithm for getting the longest repeating substring from a string
Complexity --> O(N)
:param input_string: str
:return longest_substring: str
"""
longest_substring = ""
local_longest_substring = input_string[0]
... | bigcode/self-oss-instruct-sc2-concepts |
def count_mol_weights(mol_weights):
"""
Count the number of weights in each bin, and
return a list of counts.
"""
counts = [0 for _ in range(9)]
for mol_weight in mol_weights:
if mol_weight < 250:
counts[0] += 1
elif 250 <= mol_weight < 300:
counts[1... | bigcode/self-oss-instruct-sc2-concepts |
import bisect
def bottom_values(values, period=None, num=1):
"""Returns list of bottom num items.
:param values: list of values to iterate and compute stat.
:param period: (optional) # of values included in computation.
* None - includes all values in computation.
:param num: the num in the b... | bigcode/self-oss-instruct-sc2-concepts |
def safemax(data, default=0):
""" Return maximum of array with default value for empty array
Args:
data (array or list ): data to return the maximum
default (obj): default value
Returns:
object: maximum value in the array or the default value
"""
if isinstance(data, list):
... | bigcode/self-oss-instruct-sc2-concepts |
import tqdm
def _pbar(x):
"""Create a tqdm progress bar"""
return tqdm.tqdm(x, ascii=True, unit=" scans") | bigcode/self-oss-instruct-sc2-concepts |
def is_yaml(file_path: str) -> bool:
"""Returns True if file_path is YAML, else False
Args:
file_path: Path to YAML file.
Returns:
True if is yaml, else False.
"""
if file_path.endswith("yaml") or file_path.endswith("yml"):
return True
return False | bigcode/self-oss-instruct-sc2-concepts |
import hashlib
def sha256_file(filename):
"""Calculate sha256 hash of file
"""
buf_size = 65536 # lets read stuff in 64kb chunks!
sha256 = hashlib.sha256()
with open(filename, 'rb') as f:
while True:
data = f.read(buf_size)
if not data:
break
... | bigcode/self-oss-instruct-sc2-concepts |
import re
def extract_thread_list(trace_data):
"""Removes the thread list from the given trace data.
Args:
trace_data: The raw trace data (before decompression).
Returns:
A tuple containing the trace data and a map of thread ids to thread names.
"""
threads = {}
parts = re.split('USER +PID +PPID ... | bigcode/self-oss-instruct-sc2-concepts |
def getDuration(timesarr):
"""
gets the duration of the input time array
:param timesarr: array of times as returned by readCSV
:returns: Duration for which there are times
"""
dur = max(timesarr)-min(timesarr)
return dur | bigcode/self-oss-instruct-sc2-concepts |
def landsat_ts_norm_diff(collection, bands=['Green', 'SWIR1'], threshold=0):
"""Computes a normalized difference index based on a Landsat timeseries.
Args:
collection (ee.ImageCollection): A Landsat timeseries.
bands (list, optional): The bands to use for computing normalized difference. Defaul... | bigcode/self-oss-instruct-sc2-concepts |
import json
def fromJSON(json_file):
"""load json with utf8 encoding"""
with open(str(json_file),"r", encoding='utf8') as fp:
return json.load(fp) | bigcode/self-oss-instruct-sc2-concepts |
def get_node_attributes(G, name):
"""Get node attributes from graph
Parameters
----------
G : NetworkX Graph
name : string
Attribute name
Returns
-------
Dictionary of attributes keyed by node.
Examples
--------
>>> G=nx.Graph()
>>> G.add_nodes_from([1,2,3],col... | bigcode/self-oss-instruct-sc2-concepts |
def calc_downsample(w, h, target=400):
"""Calculate downsampling value."""
if w > h:
return h / target
elif h >= w:
return w / target | bigcode/self-oss-instruct-sc2-concepts |
import re
def camel_case_split(text: str) -> list:
"""camel_case_split splits strings if they're in CamelCase and need to be not Camel Case.
Args:
str (str): The target string to be split.
Returns:
list: A list of the words split up on account of being Camel Cased.
"""
return re.... | bigcode/self-oss-instruct-sc2-concepts |
def hex_to_bytes(data):
"""Convert an hex string to bytes"""
return bytes.fromhex(data) | bigcode/self-oss-instruct-sc2-concepts |
import textwrap
def multiline_fix(s):
"""Remove indentation from a multi-line string."""
return textwrap.dedent(s).lstrip() | bigcode/self-oss-instruct-sc2-concepts |
def oc2_pair(actuator_nsid, action_name, target_name):
"""Decorator for your Consumer/Actuator functions.
Use on functions you implement when inheriting
from OpenC2CmdDispatchBase.
Example:
class MyDispatch(OOpenC2CmdDispatchBase):
...
@oc2_pair('slpf', 'deny', 'ipv4_connection')
... | bigcode/self-oss-instruct-sc2-concepts |
def round_next (x,step):
"""Rounds x up or down to the next multiple of step."""
if step == 0: return x
return round(x/step)*step | bigcode/self-oss-instruct-sc2-concepts |
def trim_seq(seq):
"""
Remove 'N's and non-ATCG from beginning and ends
"""
good = ['A','T','C','G']
seq = seq.upper()
n = len(seq)
i = 0
while i < n and seq[i] not in good: i += 1
j = len(seq)-1
while j >= 0 and seq[j] not in good: j -= 1
return seq[i:j+1] | bigcode/self-oss-instruct-sc2-concepts |
def _extract_patch(img_b, coord, patch_size):
""" Extract a single patch """
x_start = int(coord[0])
x_end = x_start + int(patch_size[0])
y_start = int(coord[1])
y_end = y_start + int(patch_size[1])
patch = img_b[:, x_start:x_end, y_start:y_end]
return patch | bigcode/self-oss-instruct-sc2-concepts |
def do_sql(conn, sql, *vals):
"""
issue an sql query on conn
"""
# print(sql, vals)
return conn.execute(sql, vals) | bigcode/self-oss-instruct-sc2-concepts |
from typing import Iterable
def sigma(a: Iterable[int]) -> int:
"""Returns sum of the list of int"""
return sum(a) | bigcode/self-oss-instruct-sc2-concepts |
def merge(d1, d2):
"""
Merge two dictionaries. In case of duplicate keys, this function will return values from the 2nd dictionary
:return dict: the merged dictionary
"""
d3 = {}
if d1:
d3.update(d1)
if d2:
d3.update(d2)
return d3 | bigcode/self-oss-instruct-sc2-concepts |
def obs_to_dict(obs):
"""
Convert an observation into a dict.
"""
if isinstance(obs, dict):
return obs
return {None: obs} | bigcode/self-oss-instruct-sc2-concepts |
import math
def convert_state_to_hex(state: str) -> str:
"""
This assumes that state only has "x"s and Us or Ls or Fs or Rs or Bs or Ds
>>> convert_state_to_hex("xxxU")
'1'
>>> convert_state_to_hex("UxUx")
'a'
>>> convert_state_to_hex("UUxUx")
'1a'
"""
state = (
stat... | bigcode/self-oss-instruct-sc2-concepts |
def _lat_hemisphere(latitude):
"""Return the hemisphere (N, S or '' for 0) for the given latitude."""
if latitude > 0:
hemisphere = 'N'
elif latitude < 0:
hemisphere = 'S'
else:
hemisphere = ''
return hemisphere | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
from typing import Tuple
import operator
def _get_longest_palindrome_boundaries(lps_table: List[int]) -> Tuple[int, int]:
"""Returns real text longest palindrome boundaries based from its lps table.
"""
center_index, radius = max(enumerate(lps_table), key=operator.itemgetter(1))
... | bigcode/self-oss-instruct-sc2-concepts |
def parse_word(word):
"""
Split given attribute word to key, value pair.
Values are casted to python equivalents.
:param word: API word.
:returns: Key, value pair.
"""
mapping = {'yes': True, 'true': True, 'no': False, 'false': False}
_, key, value = word.split('=', 2)
try:
... | bigcode/self-oss-instruct-sc2-concepts |
def merge_sort(nsl: list) -> list:
"""
function sorts an array by a merge method.
:param nsl: type list: non sorted list
:return: type list: list after merge sort
"""
sl = nsl[:]
n = len(nsl)
if n < 2:
return sl
else:
left_arr = merge_sort(nsl=nsl[:n//2])
rig... | bigcode/self-oss-instruct-sc2-concepts |
import json
def read_json(filename):
"""
Deserializes json formatted string from filename (text file) as a dictionary.
:param filename: string
"""
with open(filename) as f:
return json.load(f) | bigcode/self-oss-instruct-sc2-concepts |
def redshift2dist(z, cosmology):
""" Convert redshift to comoving distance in units Mpc/h.
Parameters
----------
z : float array like
cosmology : astropy.cosmology instance
Returns
-------
float array like of comoving distances
"""
return cosmology.comoving_distance(z).to('Mpc'... | bigcode/self-oss-instruct-sc2-concepts |
def first_half(dayinput):
"""
first half solver:
Starting with a frequency of zero, what is the resulting
frequency after all of the changes in frequency have been applied?
"""
lines = dayinput.split('\n')
result = 0
for freq in lines:
result += int(freq)
return result | bigcode/self-oss-instruct-sc2-concepts |
def reorder(x, indexList=[], indexDict={}):
"""
Reorder a list based upon a list of positional indices and/or a dictionary of fromIndex:toIndex.
>>> l = ['zero', 'one', 'two', 'three', 'four', 'five', 'six']
>>> reorder( l, [1, 4] ) # based on positional indices: 0-->1, 1-->4
['one', 'f... | bigcode/self-oss-instruct-sc2-concepts |
def textarea_to_list(text: str):
"""Converts a textarea into a list of strings, assuming each line is an
item. This is meant to be the inverse of `list_to_textarea`.
"""
res = [x.strip() for x in text.split("\n")]
res = [x for x in res if len(x) > 0]
return res | bigcode/self-oss-instruct-sc2-concepts |
from pathlib import Path
def iterdir(path):
"""Return directory listing as generator"""
return Path(path).iterdir() | bigcode/self-oss-instruct-sc2-concepts |
import re
def count_ops_in_hlo_proto(hlo_proto,
ops_regex):
"""Counts specific ops in hlo proto, whose names match the provided pattern.
Args:
hlo_proto: an HloModuleProto object.
ops_regex: a string regex to filter ops with matching names.
Returns:
Count of matching ops... | bigcode/self-oss-instruct-sc2-concepts |
def list_diff(l1: list, l2: list):
""" Return a list of elements that are present in l1
or in l2 but not in both l1 & l2.
IE: list_diff([1, 2, 3, 4], [2,4]) => [1, 3]
"""
return [i for i in l1 + l2 if i not in l1 or i not in l2] | bigcode/self-oss-instruct-sc2-concepts |
def get_list_sig_variants(file_name):
"""
Parses through the significant variants file
and creates a dictionary of variants and their
information for later parsing
: Param file_name: Name of file being parsed
: Return sig_variants_dict: A dictionary of significant results
"""
... | bigcode/self-oss-instruct-sc2-concepts |
def attack_successful(prediction, target, targeted):
"""
See whether the underlying attack is successful.
"""
if targeted:
return prediction == target
else:
return prediction != target | bigcode/self-oss-instruct-sc2-concepts |
def merge(elements):
"""Merge Sort algorithm
Uses merge sort recursively to sort a list of elements
Parameters
elements: List of elements to be sorted
Returns
list of sorted elements
"""
def list_merge(a, b):
"""Actual "merge" of two lists
Compares every member of a l... | bigcode/self-oss-instruct-sc2-concepts |
def map_structure(func, structure, args=(), kwargs={}):
"""apply func to each element in structure
Args:
func (callable): The function
structure (dict, tuple, list): the structure to be mapped.
Kwargs:
args (tuple,list): The args to the function.
kwargs (dict): The kwargs t... | bigcode/self-oss-instruct-sc2-concepts |
def is_a_monitoring_request(request):
"""Returns True it the input request is for monitoring or health check
purposes
"""
# does the request begin with /health?
return request.get_full_path()[:7] == '/health' | bigcode/self-oss-instruct-sc2-concepts |
def num2songrandom(num: str) -> int:
"""
将用户输入的随机歌曲范围参数转为发送给 API 的数字
Algorithm: (ratingNumber * 2) + (ratingPlus ? 1 : 0)
Example: '9+' -> 19
"""
return int(num.rstrip('+')) * 2 + (1 if num.endswith('+') else 0) | bigcode/self-oss-instruct-sc2-concepts |
def pad(size, padding):
"""Apply padding to width and height.
:param size: two-tuple of width and height
:param padding: padding to apply to width and height
:returns: two-tuple of width and height with padding applied
"""
width = size[0] + padding.left + padding.right
height = size[1] + p... | bigcode/self-oss-instruct-sc2-concepts |
def _parse_input_list(input_list: str) -> list[str]:
"""
Converts a CSV list of assets IDs into a list of parsed IDs (but not Asset objects)
"""
return [fqn_id for fqn_id in input_list.split(",") if fqn_id != "" and fqn_id != ":"] | bigcode/self-oss-instruct-sc2-concepts |
def count_where(predicate, iterable):
"""
Count the number of items in iterable that satisfy
the predicate
"""
return sum(1 for x in iterable if predicate(x)) | bigcode/self-oss-instruct-sc2-concepts |
def add_default_value_to(description, default_value):
"""Adds the given default value to the given option description."""
# All descriptions end with a period, so do not add another period.
return '{} Default: {}.'.format(description,
default_value if default_value else '... | bigcode/self-oss-instruct-sc2-concepts |
def derive_order_id(user_uid: str, cl_order_id: str, ts: int, order_src='a') -> str:
"""
Server order generator based on user info and input.
:param user_uid: user uid
:param cl_order_id: user random digital and number id
:param ts: order timestamp in milliseconds
:param order_src: 'a' for rest ... | bigcode/self-oss-instruct-sc2-concepts |
def get_edge(source, target, interaction):
"""
Get the edge information in JSON format.
:param source: the id or name of source node.
:param target: the id or name of target node.
:param interaction: the interaction of edge.
:return : the JSON value about edge.
"""
if interaction is No... | bigcode/self-oss-instruct-sc2-concepts |
def is_invocation(event):
"""Return whether the event is an invocation."""
attachments = event.get("attachments")
if attachments is None or len(attachments) < 1:
return False
footer = attachments[0].get("footer", "")
if footer.startswith("Posted using /giphy"):
return True
retu... | bigcode/self-oss-instruct-sc2-concepts |
def calc_prof(ability, profs, prof_bonus):
"""
Determine if proficiency modifier needs to be applied.
If character has expertise in selected skill, double the proficiency bonus.
If character has proficiency in selected skill/ability/save,
prof_mod = prof_bonus (multiply by 1).
If character h... | bigcode/self-oss-instruct-sc2-concepts |
def inexact(pa, pb, pc, pd):
"""Tests whether pd is in circle defined by the 3 points pa, pb and pc
"""
adx = pa[0] - pd[0]
bdx = pb[0] - pd[0]
cdx = pc[0] - pd[0]
ady = pa[1] - pd[1]
bdy = pb[1] - pd[1]
cdy = pc[1] - pd[1]
bdxcdy = bdx * cdy
cdxbdy = cdx * bdy
alift = adx * ... | bigcode/self-oss-instruct-sc2-concepts |
def oef_port() -> int:
"""Port of the connection to the OEF Node to use during the tests."""
return 10000 | bigcode/self-oss-instruct-sc2-concepts |
def get_input(filename):
"""returns list of inputs from data file. File should have integer values,
one per line.
Args:
filename: the name of the file with the input data.
Returns:
a list of integers read from the file
"""
text_file = open(filename, "r")
input_strs = text_... | bigcode/self-oss-instruct-sc2-concepts |
def tuple_for_testing(model, val, replace_i):
"""this function creates a tuple by changing only one parameter from a list
Positionnal arguments :
model -- a list of valid arguments to pass to the object to test
val -- the value you want to put in the list
replace_i -- the index of t... | bigcode/self-oss-instruct-sc2-concepts |
def all_entities_on_same_layout(entities):
""" Check if all entities are on the same layout (model space or any paper layout but not block).
"""
owners = set(entity.dxf.owner for entity in entities)
return len(owners) < 2 | bigcode/self-oss-instruct-sc2-concepts |
def merge_dicts(dicts_a, dicts_b):
"""Merges two lists of dictionaries by key attribute.
Example:
da = [{'key': 'a', 'value': 1}, {'key': 'b', 'value': 2}]
db = [{'key': 'b', 'value': 3, 'color':'pink'}, {'key': 'c', 'value': 4}]
merge_dicts(da, db) = [{'key': 'a', 'value': 1}, {'key': ... | bigcode/self-oss-instruct-sc2-concepts |
def parenthesize(s):
"""
>>> parenthesize('1')
'1'
>>> parenthesize('1 + 2')
'(1 + 2)'
"""
if ' ' in s:
return '(%s)' % s
else:
return s | bigcode/self-oss-instruct-sc2-concepts |
def _PiecewiseConcat(*args):
"""Concatenates strings inside lists, elementwise.
Given ['a', 's'] and ['d', 'f'], returns ['ad', 'sf']
"""
return map(''.join, zip(*args)) | bigcode/self-oss-instruct-sc2-concepts |
def brute_force(s: str) -> int:
"""
Finds the length of the longest substring in s without repeating characters.
Parameters
----------
s : str
Given string.
Returns:
int
Length of the longest substring in s without repeating characters.
Speed Analysis: O(n), no ma... | bigcode/self-oss-instruct-sc2-concepts |
def get_box(mol, padding=1.0):
"""
Given a molecule, find a minimum orthorhombic box containing it.
Size is calculated using min and max x, y, and z values.
For best results, call oriented_molecule first.
Args:
mol: a pymatgen Molecule object
padding: the extra space to be added... | bigcode/self-oss-instruct-sc2-concepts |
def is_maximum_local(index, relative_angles, radius):
"""
Determine if a point at index is a maximum local in radius range of relative_angles function
:param index: index of the point to check in relative_angles list
:param relative_angles: list of angles
:param radius: radius used ... | bigcode/self-oss-instruct-sc2-concepts |
def get_clean_name(name, char='-'):
"""
Return a string that is lowercase and all whitespaces are replaced
by a specified character.
Args:
name: The string to be cleaned up.
char: The character to replace all whitespaces. The default
character is "-" (hyphen).
Returns:
... | bigcode/self-oss-instruct-sc2-concepts |
def decrement(field):
"""
Decrement a given field in the element.
"""
def transform(element):
element[field] -= 1
return transform | bigcode/self-oss-instruct-sc2-concepts |
def read_list_of_filepaths(list_filepath):
"""
Reads a .txt file of line seperated filepaths and returns them as a list.
"""
return [line.rstrip() for line in open(list_filepath, 'r')] | bigcode/self-oss-instruct-sc2-concepts |
def gatherKeys(data):
"""Gather all the possible keys in a list of dicts.
(Note that voids in a particular row aren't too bad.)
>>> from shared.tools.examples import complexListDict
>>> gatherKeys(complexListDict)
['date', 'double', 'int', 'string']
"""
keys = set()
for row in data:
keys.update(row)
return... | bigcode/self-oss-instruct-sc2-concepts |
def read_file(path):
"""Reads file"""
with open(path) as file:
return file.readlines() | bigcode/self-oss-instruct-sc2-concepts |
import torch
def sigmoid(z):
"""Applies sigmoid to z."""
return 1/(1 + torch.exp(-z)) | bigcode/self-oss-instruct-sc2-concepts |
import base64
def decode64(string):
""" Decode a string from base64 """
return base64.b64decode(string) | bigcode/self-oss-instruct-sc2-concepts |
import threading
import time
def rate_limited(num_calls=1, every=1.0):
"""Rate limit a function on how often it can be called
Source: https://github.com/tomasbasham/ratelimit/tree/0ca5a616fa6d184fa180b9ad0b6fd0cf54c46936 # noqa E501
Args:
num_calls (float, optional): Maximum method invocations w... | bigcode/self-oss-instruct-sc2-concepts |
def throttling_mod_func(d, e):
"""Perform the modular function from the throttling array functions.
In the javascript, the modular operation is as follows:
e = (e % d.length + d.length) % d.length
We simply translate this to python here.
"""
return (e % len(d) + len(d)) % len(d) | bigcode/self-oss-instruct-sc2-concepts |
import math
def dimension_of_bounding_square(number):
"""Find the smallest binding square, e.g.
1x1, 3x3, 5x5
Approach is to assume that the number is the largest
that the bounding square can contain.
Hence taking the square root will find the length of the
side of the bounding square.
The... | bigcode/self-oss-instruct-sc2-concepts |
def key_has_granted_prefix(key, prefixes):
"""
Check that the requested s3 key starts with
one of the granted file prefixes
"""
granted = False
for prefix in prefixes:
if key.startswith(prefix):
granted = True
return granted | bigcode/self-oss-instruct-sc2-concepts |
def add_key(rec, idx):
"""Add a key value to the character records."""
rec["_key"] = idx
return rec | bigcode/self-oss-instruct-sc2-concepts |
def unpack_twist_msg(msg, stamped=False):
""" Get linear and angular velocity from a Twist(Stamped) message. """
if stamped:
v = msg.twist.linear
w = msg.twist.angular
else:
v = msg.linear
w = msg.angular
return (v.x, v.y, v.z), (w.x, w.y, w.z) | bigcode/self-oss-instruct-sc2-concepts |
import requests
from bs4 import BeautifulSoup
def get_soup(url):
"""Gets soup object for given URL."""
r = requests.get(url)
soup = BeautifulSoup(r.content, 'html.parser')
return soup | bigcode/self-oss-instruct-sc2-concepts |
def generate_fake_ping_data(random_state, size):
"""
Generate random ping values (in milliseconds) between 5 and 20,
some of them will be assigned randomly to a low latency between 100 and 200
with direct close values between 40 and 80
"""
values = random_state.random_integers(low=5, high=20, si... | bigcode/self-oss-instruct-sc2-concepts |
def split_cols_with_dot(column: str) -> str:
"""Split column name in data frame columns whenever there is a dot between 2 words.
E.g. price.availableSupply -> priceAvailableSupply.
Parameters
----------
column: str
Pandas dataframe column value
Returns
-------
str:
Valu... | bigcode/self-oss-instruct-sc2-concepts |
def parse_stat(stat):
"""Parses the stat html text to get rank, code, and count"""
stat_clean = stat.replace('\n', ' ').replace('.', '').strip()
stat_list = stat_clean.split(' ')
rank = stat_list[0]
code = code_orig = ' '.join(stat_list[1:-1])
# remove xx and dd from the end of the code so we c... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Dict
import torch
from typing import List
def collect_flow_outputs_by_suffix(
output_dict: Dict[str, torch.Tensor], suffix: str
) -> List[torch.Tensor]:
"""Return output_dict outputs specified by suffix, ordered by sorted flow_name."""
return [
output_dict[flow_name]
for... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Counter
def _counterSubset(list1, list2):
"""
Check if all the elements of list1 are contained in list2.
It counts the quantity of each element (i.e. 3-letter amino acid code)
in the list1 (e.g. two 'HIS' and one 'ASP') and checks if the list2 contains
at least that quant... | bigcode/self-oss-instruct-sc2-concepts |
def clean_url(address):
"""Remove unwanted data and provide a default value (127.0.0.1)"""
if address == "":
return '127.0.0.1'
address = address.replace("http://", "")
address = address.replace("https://", "")
address = address.split(":")[0]
return address | bigcode/self-oss-instruct-sc2-concepts |
def string_encode(key):
"""Encodes ``key`` with UTF-8 encoding."""
if isinstance(key, str):
return key.encode("UTF-8")
else:
return key | bigcode/self-oss-instruct-sc2-concepts |
def hasanno(node, key, field_name='__anno'):
"""Returns whether AST node has an annotation."""
return hasattr(node, field_name) and key in getattr(node, field_name) | bigcode/self-oss-instruct-sc2-concepts |
def scale_reader_decrease(provision_decrease_scale, current_value):
"""
:type provision_decrease_scale: dict
:param provision_decrease_scale: dictionary with key being the
scaling threshold and value being scaling amount
:type current_value: float
:param current_value: the current consumed ... | bigcode/self-oss-instruct-sc2-concepts |
import logging
def compareFuzzies(known_fuzz, comparison_fuzz):
"""
The compareFuzzies function compares Fuzzy Hashes
:param known_fuzz: list of hashes from the known file
:param comparison_fuzz: list of hashes from the comparison file
:return: dictionary of formatted results for output
"""
... | bigcode/self-oss-instruct-sc2-concepts |
import typing
def _rounded(d: typing.SupportsFloat) -> float:
"""Rounds argument to 2 decimal places"""
return round(float(d), 2) | bigcode/self-oss-instruct-sc2-concepts |
def ping_parser(line):
"""When Twitch pings, the server ,ust pong back or be dropped."""
if line == 'PING :tmi.twitch.tv':
return 'PONG :tmi.twitch.tv'
return None | bigcode/self-oss-instruct-sc2-concepts |
def _in_matched_range(start_idx, end_idx, matched_ranges):
"""Return True if provided indices overlap any spans in matched_ranges."""
for range_start_idx, range_end_idx in matched_ranges:
if not (end_idx <= range_start_idx or start_idx >= range_end_idx):
return True
return False | bigcode/self-oss-instruct-sc2-concepts |
def isSubList(largerList, smallerList):
"""returns 1 if smallerList is a sub list of largerList
>>> isSubList([1,2,4,3,2,3], [2,3])
1
>>> isSubList([1,2,3,2,2,2,2], [2])
1
>>> isSubList([1,2,3,2], [2,4])
"""
if not smallerList:
raise ValueError("isSubList: smallerList is empty: %s"% smallerList)
... | bigcode/self-oss-instruct-sc2-concepts |
def merge_sort(arr):
"""
Merge sort repeatedly divides the arr then
recombines the parts in sorted order
"""
l = len(arr)
if l > 1:
mid = l//2
L = arr[:mid]
R = arr[mid:]
merge_sort(L)
merge_sort(R)
i = j = k = 0
while i < len(L) and j < le... | bigcode/self-oss-instruct-sc2-concepts |
import re
def is_file_pattern(text):
"""
>>> is_file_pattern('file.java')
True
>>> is_file_pattern('.gitignore')
True
>>> is_file_pattern('file')
False
>>> is_file_pattern('java')
False
>>> is_file_pattern('*.java')
True
>>> is_file_pattern('docs/Makefile')
True
... | bigcode/self-oss-instruct-sc2-concepts |
def gc_percent(seq):
"""
Calculate fraction of GC bases within sequence.
Args:
seq (str): Nucleotide sequence
Examples:
>>> sequtils.gc_percent('AGGATAAG')
0.375
"""
counts = [seq.upper().count(i) for i in 'ACGTN']
total = sum(counts)
if total == 0:
retu... | bigcode/self-oss-instruct-sc2-concepts |
def build_superblock(chanjo_db, block_group):
"""Create a new superblock and add it to the current session.
Args:
chanjo_db (Store): Chanjo store connected to an existing database
block_group (list): group of related database blocks
Returns:
object: new database block
"""
superblock_id, some_blo... | bigcode/self-oss-instruct-sc2-concepts |
def prune_small_terms(hpo_counts, min_samples):
"""
Drop HPO terms with too few samples
"""
filtered_counts = {}
for term, count in hpo_counts.items():
if count >= min_samples:
filtered_counts[term] = count
return filtered_counts | bigcode/self-oss-instruct-sc2-concepts |
import jinja2
def get_jinja_parser(path):
""" Create the jinja2 parser """
return jinja2.Environment(loader=jinja2.FileSystemLoader(path)) | bigcode/self-oss-instruct-sc2-concepts |
def debian_number(major='0', minor='0', patch='0', build='0'):
"""Generate a Debian package version number from components."""
return "{}.{}.{}-{}".format(major, minor, patch, build) | bigcode/self-oss-instruct-sc2-concepts |
import logging
def get_request_data(request):
""" Retrieve request data from the request object.
Parameters
----------
request: object
the request object instance
Returns
-------
Dictionary
the request data from the request object.
Raises
------
Exception:
... | bigcode/self-oss-instruct-sc2-concepts |
def get_prospective_location(location, velocity, time):
"""Calculate the final location and velocity based on the one at time 0"""
return [l + v * time for l, v in zip(location, velocity)] | bigcode/self-oss-instruct-sc2-concepts |
import json
def pretty_jsonify(data):
"""Returns a prettier JSON output for an object than Flask's default
tojson filter"""
return json.dumps(data, indent=2) | 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.