seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
import time
def get_range_query_args_from_duration(duration_secs=240):
"""Get start and end time for a duration of the last duration_secs."""
return (int(time.time()) - duration_secs, int(time.time())) | bigcode/self-oss-instruct-sc2-concepts |
def search_non_residue(p):
"""Find a non residue of p between 2 and p
Args:
p: a prime number
Returns:
a integer that is not a quadratic residue of p
or -1 if no such number exists
"""
for z in range(2, p):
if pow(z, (p - 1) // 2, p) == p - 1:
... | bigcode/self-oss-instruct-sc2-concepts |
def unique_list(obj, key=None):
"""
Remove same element from list
:param obj: list
:param key: key function
:return: list
"""
checked = []
seen = set()
for e in obj:
_e = key(e) if key else e
if _e not in seen:
checked.append(e)
seen.add(_e)
... | bigcode/self-oss-instruct-sc2-concepts |
def get_function_input(function):
"""
Return a with the single input that is documented using
api.decoratos.input
"""
parameters = []
if hasattr(function, 'doc_input'):
(description, return_type, required) = function.doc_input
parameters.append({
'name': 'body',
... | bigcode/self-oss-instruct-sc2-concepts |
def same_orientation(lineA, lineB):
"""Return whether two paired end reads are of the same orientation."""
# SAM flags
reverse = 16
mate_reverse = 32
flagA = int(lineA.split()[11])
flagB = int(lineB.split()[11])
return ((flagA & reverse) == (flagB & reverse) and
(flagA & mate_... | bigcode/self-oss-instruct-sc2-concepts |
def latest_lines(lines, last):
"""Return lines after last and not empty
>>> latest_lines(['a', 'b', '', 'c', '', 'd'], 1)
6, ['c', 'd']
"""
last_lnum = len(lines)
latest = [l for n, l in enumerate(lines, 1) if n > last and l.strip()]
return last_lnum, latest | bigcode/self-oss-instruct-sc2-concepts |
def gradient_t(prev_image, image):
"""Find gradient along time: time derivative using two images
Arguments:
prev_image {tensor} -- image at timestamp 1
image {tensor} -- image at timestamp 2
Returns:
tensor -- time derivative of image
"""
return prev_image-image | bigcode/self-oss-instruct-sc2-concepts |
def _indentation(line):
"""Returns the length of the line's leading whitespace, treating tab stops
as being spaced 8 characters apart."""
line = line.expandtabs()
return len(line) - len(line.lstrip()) | bigcode/self-oss-instruct-sc2-concepts |
def sum_fuel_across_sectors(fuels):
"""Sum fuel across sectors of an enduse if multiple sectors.
Otherwise return unchanged `fuels`
Arguments
---------
fuels : dict or np.array
Fuels of an enduse either for sectors or already aggregated
Returns
-------
sum_array : np.array
... | bigcode/self-oss-instruct-sc2-concepts |
import itertools
def element_ancestry(element):
"""Iterates element plus element.parents."""
return itertools.chain((element,), element.parents) | bigcode/self-oss-instruct-sc2-concepts |
def dasherize(word: str) -> str:
"""Replace underscores with dashes in the string.
Example::
>>> dasherize("foo_bar")
"foo-bar"
Args:
word (str): input word
Returns:
input word with underscores replaced by dashes
"""
return word.replace("_", "-") | bigcode/self-oss-instruct-sc2-concepts |
def log2floor(n):
"""
Returns the exact value of floor(log2(n)).
No floating point calculations are used.
Requires positive integer type.
"""
assert n > 0
return n.bit_length() - 1 | bigcode/self-oss-instruct-sc2-concepts |
def standardize(X):
""" Standardize data set by mean and standard deviation """
mu = X.mean(axis=0, keepdims=True)
s = X.std(axis=0, keepdims=True)
return (X-mu)/s | bigcode/self-oss-instruct-sc2-concepts |
def detection_center(detection):
"""Computes the center x, y coordinates of the object"""
#print(detection)
bbox = detection['bbox']
center_x = (bbox[0] + bbox[2]) / 2.0 - 0.5
center_y = (bbox[1] + bbox[3]) / 2.0 - 0.5
return (center_x, center_y) | bigcode/self-oss-instruct-sc2-concepts |
import requests
def get_countries_names() -> list:
"""
Function for getting list of all countries names procived by public
COVID-19 api on site "https://api.covid19api.com"
Returns
-------
List with all countries names.
Example
-------
>>> countries_names = get_countries_names()
... | bigcode/self-oss-instruct-sc2-concepts |
def overlaps(pattern_a, pattern_b):
"""Returns a boolean indicating if two patterns are overlapped.
Args:
pattern_a: SimilarPattern or TimeSpan.
pattern_b: SimilarPattern or TimeSpan.
Returns:
boolean indicating if the patterns are overlapped.
"""
start_a = pattern_a.start_time
start_b = patter... | bigcode/self-oss-instruct-sc2-concepts |
def distance_residues(r1, r2):
"""Return the distance between two residues."""
center_1 = r1.get_mass_center()
center_2 = r2.get_mass_center()
return (sum(map(lambda t: (t[0] - t[1])**2, zip(center_1, center_2))))**0.5 | bigcode/self-oss-instruct-sc2-concepts |
def max_weighted_independent_set_in_path_graph(weights):
""" Computes the independent set with maximum total weight for a path graph.
A path graph has all vertices are connected in a single path, without cycles.
An independent set of vertices is a subset of the graph vertices such that
no two vertices ... | bigcode/self-oss-instruct-sc2-concepts |
def select_with_processing(selector, cluster_sim):
"""A selection wrapper that uses the given operator to select from
the union of the population and the currently processing individuals.
"""
def select(population):
return selector(population + cluster_sim.processing)
return select | bigcode/self-oss-instruct-sc2-concepts |
def get_si(simpos):
"""
Get SI corresponding to the given SIM position.
"""
if ((simpos >= 82109) and (simpos <= 104839)):
si = 'ACIS-I'
elif ((simpos >= 70736) and (simpos <= 82108)):
si = 'ACIS-S'
elif ((simpos >= -86147) and (simpos <= -20000)):
si = ' HRC-I'
elif ... | bigcode/self-oss-instruct-sc2-concepts |
import json
def get_parameters(template):
"""
Builds a dict of parameters from a workflow manifest.
Parameters
----------
template : dict
Returns
-------
dict
Parameters.
"""
parameters = {}
prefix = "PARAMETER_"
for var in template["container"]["env"]:
... | bigcode/self-oss-instruct-sc2-concepts |
def create_index_of_A_matrix(db):
"""
Create a dictionary with row/column indices of the A matrix as key and a tuple (activity name, reference product,
unit, location) as value.
:return: a dictionary to map indices to activities
:rtype: dict
"""
return {
(
db[i]["name"],
... | bigcode/self-oss-instruct-sc2-concepts |
import io
def decode_int8(fh: io.BytesIO) -> int:
"""
Read a single byte as an unsigned integer.
This data type isn't given a special name like "ITF-8" or "int32" in the spec, and is only used twice in the
file descriptor as a special case, and as a convenience to construct other data types, like ITF... | bigcode/self-oss-instruct-sc2-concepts |
def full_qualified(pkg, symbols):
"""
パッケージ名と、文字列表記されたシンボルのリスト(このEus_pkgクラスと対応するEuslispのパッケージ以外のシンボルが含まれていても良い)を受け取る。
対応するパッケージ内のシンボルのみを取り出し、それぞれパッケージ接頭語(大文字)をつけ、リストにして返す。
>>> full_qualified("TEST", ['var1', 'OTHER-PACK::var2', 'LISP::var3'])
['TEST::var1', 'LISP::var3']
Args:
pkg (str... | bigcode/self-oss-instruct-sc2-concepts |
import pickle
def LoadModel(filname):
"""
Load a model using pickle
Parameters
----------
filname : str
model file name.
Returns
-------
model : dict
Output of BuildModel methode, a dict with:
-"model" an sklearn trained random forest classifier.
... | bigcode/self-oss-instruct-sc2-concepts |
import ctypes
def _malloc_char_array(n):
"""
Return a pointer to allocated UTF8 (C char) array of length `n'.
"""
t = ctypes.c_char * n
return t() | bigcode/self-oss-instruct-sc2-concepts |
def configure_camera_url(camera_address: str,
camera_username: str = 'admin',
camera_password: str = 'iamironman',
camera_port: int = 554,
camera_stream_address: str = 'H.264',
camera_protocol: s... | bigcode/self-oss-instruct-sc2-concepts |
def filer_elements(elements, element_filter):
"""Filter elements.
Ex.: If filtered on elements [' '], ['a', ' ', 'c']
becomes ['a', 'c']
"""
return [element for element in elements if element not in element_filter] | bigcode/self-oss-instruct-sc2-concepts |
def any_true_p (seq, pred) :
"""Returns first element of `seq` for which `pred` returns True,
otherwise returns False.
"""
for e in seq :
if pred (e) :
return e
else :
return False | bigcode/self-oss-instruct-sc2-concepts |
def _resize(im, width, height):
"""
Resizes the image to fit within the specified height and width; aspect ratio
is preserved. Images always preserve animation and might even result in a
better-optimized animated gif.
"""
# resize only if we need to; return None if we don't
if im.size.width ... | bigcode/self-oss-instruct-sc2-concepts |
def valid(x, y, n, m):
"""Check if the coordinates are in bounds.
:param x:
:param y:
:param n:
:param m:
:return:
"""
return 0 <= x < n and 0 <= y < m | bigcode/self-oss-instruct-sc2-concepts |
def _is_control_defined(node, point_id):
""" Checks if control should be created on specified point id
Args:
name (str): Name of a control
point_id (int): Skeleton point number
Returns:
(bool)
"""
node_pt = node.geometry().iterPoints()[point_id]
... | bigcode/self-oss-instruct-sc2-concepts |
def levelFromHtmid(htmid):
"""
Find the level of a trixel from its htmid. The level
indicates how refined the triangular mesh is.
There are 8*4**(d-1) triangles in a mesh of level=d
(equation 2.5 of
Szalay A. et al. (2007)
"Indexing the Sphere with the Hierarchical Triangular Mesh"
ar... | bigcode/self-oss-instruct-sc2-concepts |
import pprint
def fargs(*args, **kwargs):
"""
Format `*args` and `**kwargs` into one string resembling the original call.
>>> fargs(1, [2], x=3.0, y='four')
"1, [2], x=3.0, y='four'"
.. note:: The items of `**kwargs` are sorted by their key.
"""
items = []
for arg in args:
i... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Tuple
from pathlib import Path
def operating_system() -> Tuple[str, str]:
"""Return what operating system we are running.
Returns:
A tuple with two strings, the first with the operating system and the
second is the version. Examples: ``('ubuntu', '20.04')``,
``('cen... | bigcode/self-oss-instruct-sc2-concepts |
def get_max_key(d):
"""Return the key from the dict with the max value."""
return max(d, key=d.get) | bigcode/self-oss-instruct-sc2-concepts |
def generate_sample(id, name, controlled_metadata, user_metadata, source_meta):
"""
Create a sample record
"""
sample = {
'node_tree': [{
"id": id,
"type": "BioReplicate",
"meta_controlled": controlled_metadata,
"meta_user": user_metadata,
... | bigcode/self-oss-instruct-sc2-concepts |
def readline_comment(file, symbol='#'):
"""Reads line from a file object, but ignores everything after the
comment symbol (by default '#')"""
line = file.readline()
if not line:
return ''
result = line.partition(symbol)[0]
return result if result else readline_comment(file) | bigcode/self-oss-instruct-sc2-concepts |
import re
def collect_subroutine_calls(lines,ifbranch_lines):
"""
Collect a dictionary of all subroutine call instances. In the source code
on entry the "subroutine call" is given in the form of a function call, e.g.
t5 = nwxc_c_Mpbe(rhoa,0.0d+0,gammaaa,0.0d+0,0.0d+0)
we need to know the "nwxc_c_Mpbe(r... | bigcode/self-oss-instruct-sc2-concepts |
import xxhash
def get_hash(fname: str) -> str:
"""
Get xxHash3 of a file
Args:
fname (str): Path to file
Returns:
str: xxHash3 of file
"""
xxh = xxhash.xxh3_64()
with open(fname, "rb") as f:
for chunk in iter(lambda: f.read(4096), b""):
xxh.update(chun... | bigcode/self-oss-instruct-sc2-concepts |
def split_dataset_sizes(stream_list, split_sizes):
"""Splits with different sizes
Args:
stream_list (list): list of stream path
split_sizes (list): batch size per worker
"""
out = []
start = 0
total = sum(split_sizes)
for split_size in split_sizes[:-1]:
num = int(spl... | bigcode/self-oss-instruct-sc2-concepts |
def all_nums(table):
"""
Returns True if table contains only numbers (False
otherwise)
Example: all_nums([[1,2],[3,4]]) is True
all_nums([[1,2],[3,'a']]) is False
Parameter table: The candidate table to modify
Preconditions: table is a rectangular 2d List
"""
result = True... | bigcode/self-oss-instruct-sc2-concepts |
def _itemNames(comb):
""" Item names from result of knapsack01
Args:
comb tuple of tuples result of knapsack01
Returns:
tuple sorted item ids
"""
return tuple(sorted(item for item,_,_ in comb)) | bigcode/self-oss-instruct-sc2-concepts |
def split_def_command(command):
"""Split command in parts: variable name, specific command, definition.
Return None if command is invalid.
"""
# procedo per casi
# il che significa che dopo un '@' non posso usare un ':'
# perché verrebbe intercettato per primo!
valid_commands = [":", ... | bigcode/self-oss-instruct-sc2-concepts |
def get_ingredients(drink_dict):
""" Create a list of ingredients and measures
Form data is passed as a dictionary. The functions iterates through
the key/value pairs and appends the ingredients and measures to its
own list called ingredients.
Args:
drink_dict : The dictionary containing t... | bigcode/self-oss-instruct-sc2-concepts |
def linear (x, parameters):
"""Sigmoid function
POI = a + (b * x )
Parameters
----------
x: float or array of floats
variable
parameters: dict
dictionary containing 'linear_a', and 'linear_b'
Returns
-------
float or array of floats:
function re... | bigcode/self-oss-instruct-sc2-concepts |
def rax_clb_node_to_dict(obj):
"""Function to convert a CLB Node object to a dict"""
if not obj:
return {}
node = obj.to_dict()
node['id'] = obj.id
node['weight'] = obj.weight
return node | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
import random
def unique_floats_sum_to_one(num: int) -> List[float]:
"""return a list of unique floats summing up to 1"""
random_ints = random.sample(range(1, 100), k=num)
total = sum(random_ints)
return [(n / total) for n in random_ints] | bigcode/self-oss-instruct-sc2-concepts |
def get_timeouts(builder_cfg):
"""Some builders require longer than the default timeouts.
Returns tuple of (expiration, hard_timeout). If those values are None then
default timeouts should be used.
"""
expiration = None
hard_timeout = None
if 'Valgrind' in builder_cfg.get('extra_config', ''):
expirat... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def _skip(x, mask):
"""
Getting sliced (dim=0) tensor by mask. Supporting tensor and list/dict of tensors.
"""
if isinstance(x, int):
return x
if x is None:
return None
if isinstance(x, torch.Tensor):
if x.size(0) == mask.size(0):
return x[mas... | bigcode/self-oss-instruct-sc2-concepts |
def _get_zip_filename(xml_sps, output_filename=None):
"""
Obtém o nome canônico de um arquivo ZIP a partir de `xml_sps: packtools.sps.models.sps_package.SPS_Package`.
Parameters
----------
xml_sps : packtools.sps.models.sps_package.SPS_Package
output_filename: nome do arquivo zip
Returns
... | bigcode/self-oss-instruct-sc2-concepts |
def asic_cmd(asic, cmd, module_ignore_errors=False):
"""
Runs a command in the appropriate namespace for an ASIC.
Args:
asic: Instance of SonicAsic to run a command.
cmd: Command string to execute.
module_ignore_errors: Flag to pass along to ansible to ignore any execution errors.
... | bigcode/self-oss-instruct-sc2-concepts |
import configparser
def _config_ini(path):
"""
Parse an ini file
:param path: The path to a file to parse
:type file: str
:returns: Configuration contained in path
:rtype: Dict
"""
conf = configparser.ConfigParser()
conf.read(path)
return dict(conf) | bigcode/self-oss-instruct-sc2-concepts |
def read_messages_count(path, repeat_every):
"""
Count the predictions given so far
(may be used in case of retraining)
"""
file_list=list(path.iterdir())
nfiles = len(file_list)
if nfiles==0:
return 0
else:
return ((nfiles-1)*repeat_every) + len(file_list[-1].open().readlines()) | bigcode/self-oss-instruct-sc2-concepts |
import math
def percent(n, precision=0):
"""
Converts `n` to an appropriately-precise percentage.
"""
# 'or 1' prevents a domain error if n == 0 (i.e., 0%)
places = precision - math.floor(math.log10(abs(n) or 1))
return '{0:.{1}%}'.format(n, places) | bigcode/self-oss-instruct-sc2-concepts |
def Focal_length_eff(info_dict):
"""
Computes the effective focal length give the plate scale and
the pixel size.
Parameters
----------
info_dict: dictionary
Returns
---------
F_eff: float
effective focal length in m
"""
# F_eff = 1./ (info_dict['pixelScale'] *
#... | bigcode/self-oss-instruct-sc2-concepts |
def irb_decay_to_gate_infidelity(irb_decay, rb_decay, dim):
"""
Eq. 4 of [IRB], which provides an estimate of the infidelity of the interleaved gate,
given both the observed interleaved and standard decay parameters.
:param irb_decay: Observed decay parameter in irb experiment with desired gate interle... | bigcode/self-oss-instruct-sc2-concepts |
def jaccard(words_1, words_2):
"""words_1 และ words_2 เป็นลิสต์ของคำต่าง ๆ (ไม่มีคำซ้ำใน words_1 และ ไม่มีคำซ้ำใน words_2)
ต้องทำ: ตั้งตัวแปร jaccard_coef ให้มีค่าเท่ากับ Jaccard similarity coefficient ที่คำนวณจากค่าใน
words_1 และ words_2 ตามสูตรที่แสดงไว้ก่อนนี้
Doctest :
>>> words_1 = ['x', '... | bigcode/self-oss-instruct-sc2-concepts |
import json
def get_rev_list_kwargs(opt_list):
"""
Converts the list of 'key=value' options to dict.
Options without value gets True as a value.
"""
result = {}
for opt in opt_list:
opt_split = opt.split(sep="=", maxsplit=1)
if len(opt_split) == 1:
result[opt] = Tru... | bigcode/self-oss-instruct-sc2-concepts |
def collectReviewTeams(reviewers):
"""collectReviewTeams(reviewers) -> dictionary
Takes a dictionary as returned by getReviewersAndWatchers() or
getPendingReviewers() and transform into a dictionary mapping sets of users to
sets of files that those groups of users share review responsibilities for. The
same user ... | bigcode/self-oss-instruct-sc2-concepts |
def int_to_lower_mask(mask):
"""
Convert an integer into a lower mask in IPv4 string format where the first mask bits are 0
and all remaining bits are 1 (e.g. 8 -> 0.255.255.255)
:param mask: mask as integer, 0 <= mask <= 32
:return: IPv4 string representing a lower mask corresponding to mask
""... | bigcode/self-oss-instruct-sc2-concepts |
def zero_fill(value: bytearray) -> bytearray:
"""
Zeroing byte objects.
Args:
value: The byte object that you want to reset.
Returns:
Reset value.
"""
result = b''
if isinstance(value, (bytes, bytearray)):
result = b'/x00' * len(value)
result = bytearray(res... | bigcode/self-oss-instruct-sc2-concepts |
def get_user_choice(choices):
"""
ask the user to choose from the given choices
"""
# print choices
for index, choice in enumerate(choices):
print("[" + str(index) + "] " + choice)
# get user input
while True:
user_input = input("\n" + "input: ")
if (user_input.isdig... | bigcode/self-oss-instruct-sc2-concepts |
def get_size_from_block_count(block_count_str, size_step=1000, sizes = ["K", "M", "G", "T"], format_spec=":2.2f"):
"""Transforms block count (as returned by /proc/partitions and similar files) to a human-readable size string, with size multiplier ("K", "M", "G" etc.) appended.
Kwargs:
* ``size_step``:... | bigcode/self-oss-instruct-sc2-concepts |
import functools
def memoize(f):
""" Minimalistic memoization decorator (*args / **kwargs)
Based on: http://code.activestate.com/recipes/577219/ """
cache = {}
@functools.wraps(f)
def memf(*args, **kwargs):
fkwargs = frozenset(kwargs.items())
if (args, fkwargs) not in cache:
... | bigcode/self-oss-instruct-sc2-concepts |
import cgi
def check_api_v3_error(response, status_code):
"""
Make sure that ``response`` is a valid error response from
API v3.
- check http status code to match ``status_code``
:param response: a ``requests`` response
:param status_code: http status code to be checked
"""
assert n... | bigcode/self-oss-instruct-sc2-concepts |
def fail(s):
"""
A function that should fail out of the execution with a RuntimeError and the
provided message.
Args:
s: The message to put into the error.
Returns:
A function object that throws an error when run.
"""
def func():
raise RuntimeError(s)
return fu... | bigcode/self-oss-instruct-sc2-concepts |
def is_simple_locale_with_region(locale):
"""Check if a locale is only an ISO and region code."""
# Some locale are unicode names, which are not valid
try:
lang, sep, qualifier = locale.partition('_')
except UnicodeDecodeError:
return False
if '-' in lang:
return False
# ... | bigcode/self-oss-instruct-sc2-concepts |
def format_output_mesmer(output_list):
"""Takes list of model outputs and formats into a dictionary for better readability
Args:
output_list (list): predictions from semantic heads
Returns:
dict: Dict of predictions for whole cell and nuclear.
Raises:
ValueError: if model outp... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def extract_torchmeta_task(cs, class_ids):
""" Extracts a single "episode" (ie, task) from a ClassSplitter object, in the
form of a dataset, and appends variables needed by DatasetDistance computation.
Arguments:
cs (torchmeta.transforms.ClassSplitter): the ClassSplitter ... | bigcode/self-oss-instruct-sc2-concepts |
import unicodedata
def full2half(uc):
"""Convert full-width characters to half-width characters.
"""
return unicodedata.normalize('NFKC', uc) | bigcode/self-oss-instruct-sc2-concepts |
def simple_function(arg1, arg2=1):
"""
Just a simple function.
Args:
arg1 (str): first argument
arg2 (int): second argument
Returns:
List[str]: first argument repeated second argument types.
"""
return [arg1] * arg2 | bigcode/self-oss-instruct-sc2-concepts |
def _object_type(pobj):
###############################################################################
"""Return an XML-acceptable string for the type of <pobj>."""
return pobj.__class__.__name__.lower() | bigcode/self-oss-instruct-sc2-concepts |
import re
def smi_tokenizer(smi):
"""
Tokenize a SMILES
"""
pattern = "(\[|\]|Xe|Ba|Rb|Ra|Sr|Dy|Li|Kr|Bi|Mn|He|Am|Pu|Cm|Pm|Ne|Th|Ni|Pr|Fe|Lu|Pa|Fm|Tm|Tb|Er|Be|Al|Gd|Eu|te|As|Pt|Lr|Sm|Ca|La|Ti|Te|Ac|Si|Cf|Rf|Na|Cu|Au|Nd|Ag|Se|se|Zn|Mg|Br|Cl|U|V|K|C|B|H|N|O|S|P|F|I|b|c|n|o|s|p|\(|\)|\.|=|#|-|\+|\\\\|\/... | bigcode/self-oss-instruct-sc2-concepts |
def b2s(binary):
"""
Binary to string helper which ignores all data which can't be decoded
:param binary: Binary bytes string
:return: String
"""
return binary.decode(encoding='ascii', errors='ignore') | bigcode/self-oss-instruct-sc2-concepts |
def get_intersection_difference(runs):
"""
Get the intersection and difference of a list of lists.
Parameters
----------
runs
set of TestSets
Returns
-------
dict
Key "intersection" : list of Results present in all given TestSets,
Key "difference" : list of Resu... | bigcode/self-oss-instruct-sc2-concepts |
def Nxxyy2yolo(xmin, xmax, ymin, ymax):
"""convert normalised xxyy OID format to yolo format"""
ratio_cx = (xmin + xmax)/2
ratio_cy = (ymin + ymax)/2
ratio_bw = xmax - xmin
ratio_bh = ymax - ymin
return (ratio_cx, ratio_cy, ratio_bw, ratio_bh) | bigcode/self-oss-instruct-sc2-concepts |
def all_children(mod):
"""Return a list of all child modules of the model, and their children, and their children's children, ..."""
children = []
for idx, child in enumerate(mod.named_modules()):
children.append(child)
return children | bigcode/self-oss-instruct-sc2-concepts |
def normalize_filename(filename):
"""Normalizes the name of a file. Used to avoid characters errors and/or to
get the name of the dataset from a url.
Args:
filename (str): The name of the file.
Returns:
f_name (str): The normalized filename.
"""
if not isinstance(filename, str... | bigcode/self-oss-instruct-sc2-concepts |
def find_double_newline(s):
"""Returns the position just after a double newline in the given string."""
pos1 = s.find(b'\n\r\n') # One kind of double newline
if pos1 >= 0:
pos1 += 3
pos2 = s.find(b'\n\n') # Another kind of double newline
if pos2 >= 0:
pos2 += 2
if pos1 >= 0:... | bigcode/self-oss-instruct-sc2-concepts |
import re
def promote_trigger(source: list, trigger: str) -> list:
"""Move items matching the trigger regex to the start of the returned list"""
result = []
r = re.compile(trigger)
for item in source:
if isinstance(item, str) and r.match(item):
result = [item] + result
else... | bigcode/self-oss-instruct-sc2-concepts |
def oscar_calculator(wins: int) -> float:
""" Helper function to modify rating based on the number of Oscars won. """
if 1 <= wins <= 2:
return 0.3
if 3 <= wins <= 5:
return 0.5
if 6 <= wins <= 10:
return 1.0
if wins > 10:
return 1.5
return 0 | bigcode/self-oss-instruct-sc2-concepts |
import math
def initial_compass_bearing(lat1, lng1, lat2, lng2):
"""
Calculates the initial bearing (forward azimuth) of a great-circle arc.
Note that over long distances the bearing may change.
The bearing is represented as the compass bearing (North is 0 degrees)
Args:
lat1 (str): The l... | bigcode/self-oss-instruct-sc2-concepts |
def clean_meta_args(args):
"""Process metadata arguments.
Parameters
----------
args : iterable of str
Formatted metadata arguments for 'git-annex metadata --set'.
Returns
-------
A dict mapping field names to values.
"""
results = {}
for arg in args:
parts = [x... | bigcode/self-oss-instruct-sc2-concepts |
def _default_filter(meta_data):
"""The default meta data filter which accepts all files. """
return True | bigcode/self-oss-instruct-sc2-concepts |
import uuid
def generate_fwan_process_id() -> str:
""" Generates a new Firmware Analysis Process ID """
return str(uuid.uuid4()) | bigcode/self-oss-instruct-sc2-concepts |
import keyword
def pykeyword(operation='list', keywordtotest=None):
"""
Check if a keyword exists in the Python keyword dictionary
operation:
Whether to list or check the keywords. Possible options are list and check. The default is 'list'.
keywordtotest:
The keyword to test for if the oper... | bigcode/self-oss-instruct-sc2-concepts |
def validate(contacts, number):
"""
The validate() function accepts the contacts array and number as arguments and checks to see if the number inputted is in the range of the contacts array. It returns a number inputted by the user within that range.
"""
while number<1 or number>len(contacts):
p... | bigcode/self-oss-instruct-sc2-concepts |
def thresh_hold_binarization(feature_vector, thresh_hold):
"""
Turn each value above or equal to the thresh hold 1 and values below the thresh hold 0.
:param feature_vector: List of integer/float/double..
:param thresh_hold: Thresh hold value for binarization
:return: Process and binarized list ... | bigcode/self-oss-instruct-sc2-concepts |
def transform_okta_user(okta_user):
"""
Transform okta user data
:param okta_user: okta user object
:return: Dictionary container user properties for ingestion
"""
# https://github.com/okta/okta-sdk-python/blob/master/okta/models/user/User.py
user_props = {}
user_props["first_name"] = o... | bigcode/self-oss-instruct-sc2-concepts |
def _compare_fq_names(this_fq_name, that_fq_name):
"""Compare FQ names.
:param this_fq_name: list<string>
:param that_fq_name: list<string>
:return: True if the two fq_names are the same
"""
if not this_fq_name or not that_fq_name:
return False
elif len(this_fq_name) != len(that_fq_... | bigcode/self-oss-instruct-sc2-concepts |
def remove_element_from_list(x, element):
"""
Remove an element from a list
:param x: a list
:param element: an element to be removed
:return: a list without 'element'
Example:
>>>x = [1, 2, 3]
>>>print(arg_find_list(x, 3))
[1, 2]
"""
return list(filter(lambda a: a... | bigcode/self-oss-instruct-sc2-concepts |
def equal(param1, param2, ignore_case=False):
"""
Compare two parameters and return if they are equal.
This parameter doesn't run equal operation if first parameter is None.
With this approach we don't run equal operation in case user don't
specify parameter in their task.
:param param1: user i... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def BCEFlat(x: torch.Tensor, y: torch.Tensor) -> torch.Tensor:
"""Same as F.binary_cross_entropy but flattens the input and target.
Args:
x : logits
y: The corresponding targets.
Returns:
The computed Loss
"""
x = torch.sigmoid(x)
y = y.view(x.shape).type... | bigcode/self-oss-instruct-sc2-concepts |
def _parse_message(exc):
"""Return a message for a notification from the given exception."""
return '%s: %s' % (exc.__class__.__name__, str(exc)) | bigcode/self-oss-instruct-sc2-concepts |
import string
def printable_substring(the_str):
"""Returns the printable subset of the_str
:param str the_str: a putative string
:return str the_pr_str: the portion of the_str from index 0 that is printable
"""
i = 0
the_pr_str = ''
while i < len(the_str):
if the_str[i] in string.... | bigcode/self-oss-instruct-sc2-concepts |
def make_read_only(tkWdg):
"""Makes a Tk widget (typically an Entry or Text) read-only,
in the sense that the user cannot modify the text (but it can
still be set programmatically). The user can still select and copy
text
and key bindings for <<Copy>> and <<Select-All>> still work properly.
Inp... | bigcode/self-oss-instruct-sc2-concepts |
def is_array(value):
"""Check if value is an array."""
return isinstance(value, list) | bigcode/self-oss-instruct-sc2-concepts |
import random
def expand_model_parameters(model_params, expansion_limit):
"""Expand a model template into random combinations of hyperparameters.
For example, if model_params is:
{name: regression, l2_strength: [0, 1], train_steps: [100, 50] }
Then the returned new_model_params will be the following:
[
... | bigcode/self-oss-instruct-sc2-concepts |
import json
def mock_hue_put_response(request, context):
"""Callback for mocking a Philips Hue API response using the requests-mock library,
specifically for a put request.
This mock response assumes that the system has a single light with light_id of '1',
and the expected request is to set the 'on' ... | 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.