seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
import typing
import functools
import asyncio
def executor_function(sync_function: typing.Callable):
"""A decorator that wraps a sync function in an executor, changing it into an async function.
This allows processing functions to be wrapped and used immediately as an async function.
Examples
------... | bigcode/self-oss-instruct-sc2-concepts |
def almost_flatten(A):
"""Flatten array in all except last dimension"""
return A.reshape((-1,A.shape[-1])) | bigcode/self-oss-instruct-sc2-concepts |
def delete(db_object):
""" Generates a query that deletes the given `db_object` from the DB.
Args:
db_object (DbObject): The DB object being deleted.
"""
id_param = "%sId" % db_object.type_name()
query_str = """mutation delete%sPyApi%s{update%s(
where: {id: $%s} data: {deleted: true... | bigcode/self-oss-instruct-sc2-concepts |
def clock_to_float(s):
"""given '7:30' return 7.5"""
if ":" in s:
M,S=[int(x) for x in s.split(":")]
return round(float(M+S/60.0),2)
else:
return float(s) | bigcode/self-oss-instruct-sc2-concepts |
import torch
from typing import Set
def get_entities(triples: torch.LongTensor) -> Set[int]:
"""Get all entities from the triples."""
return set(triples[:, [0, 2]].flatten().tolist()) | bigcode/self-oss-instruct-sc2-concepts |
import re
def normalize_version(version):
"""
Normalize a version string by removing extra zeroes and periods.
"""
return [int(x) for x in re.sub(r'(\.0+)*$', '', version).split('.')] | bigcode/self-oss-instruct-sc2-concepts |
def dict_merge(*dicts):
"""
Merge one or more dicts into one.
>>> d = dict_merge({'a': 'A'}, {'b': 'B'}, {'c': 'C'})
>>> sorted(d.keys()), sorted(d.values())
(['a', 'b', 'c'], ['A', 'B', 'C'])
"""
final = {}
for d in dicts:
final.update(d)
return final | bigcode/self-oss-instruct-sc2-concepts |
def address_area_or_none(address_area):
"""
Get Formatted Address Area Result
:param address_area: Address object returned on Company
:return: Address as an id name object or None
"""
if address_area:
return {
'id': str(address_area.id),
'name': address_area.name,... | bigcode/self-oss-instruct-sc2-concepts |
def modify_cum_probs(cum_probs):
"""
Insersion prolongs read length.
Therefore, insersion, deletion, and mutation rate must be modified based on expected genarated read length.
E(generated_readlength) = original_readlength * (1 + ci + ci^2 + ci^3 + ... + ci^inf) = original_readlength / (1 - ci)
E(ge... | bigcode/self-oss-instruct-sc2-concepts |
def decompose_list(input_):
"""Recusively decompose any list structure into a flat list"""
def dec(input_, output_):
if type(input_) is list:
for subitem in input_:
dec(subitem, output_)
else:
output_.append(input_)
output_ = []
dec(input_, output_... | bigcode/self-oss-instruct-sc2-concepts |
def ssl_scan(url):
"""
Method which change url to ssl url (https).
:param url: Main url of scanned Website.
:return: Link with changed Url (http to https)
"""
if url.startswith('http://'):
return url.replace('http://', 'https://')
return 'https://' + url | bigcode/self-oss-instruct-sc2-concepts |
def SliceMutator(current, value):
"""Returns a slice of the current value. Value must be a tuple (start, stop) or (start, stop, step)"""
return current[slice(value[0], value[1], value[2] if len(value) > 2 else None)] | bigcode/self-oss-instruct-sc2-concepts |
def parse_range(range_str):
""" Parse the chrom, start and end from the range string
Args:
range_str (str): In format chrom:start-end
Returns:
chrom (str), start (int), end (int)
"""
chrom, start_end = range_str.split(":")
start, end = start_end.split("-")
return str(chrom), ... | bigcode/self-oss-instruct-sc2-concepts |
def get_highest_action(life):
"""Returns highest action in the queue."""
if life['actions'] and life['actions'][0]:
return life['actions'][0]
else:
return None | bigcode/self-oss-instruct-sc2-concepts |
def default_matrix_multiplication(a: list, b: list) -> list:
"""
Multiplication only for 2x2 matrices
"""
if len(a) != 2 or len(a[0]) != 2 or len(b) != 2 or len(b[0]) != 2:
raise Exception("Matrices are not 2x2")
new_matrix = [
[a[0][0] * b[0][0] + a[0][1] * b[1][0], a[0][0] * b[0][1... | bigcode/self-oss-instruct-sc2-concepts |
import itertools
def tag_text(text, tag_info_list):
"""Apply start/end tags to spans of the given text.
Parameters
----------
text : str
Text to be tagged
tag_info_list : list of tuples
Each tuple refers to a span of the given text. Fields are `(start_ix,
end_ix, substrin... | bigcode/self-oss-instruct-sc2-concepts |
def format_release(release: dict) -> dict:
"""
Format a raw release record from GitHub into a release usable by Virtool.
:param release: the GitHub release record
:return: a release for use within Virtool
"""
asset = release["assets"][0]
return {
"id": release["id"],
"name... | bigcode/self-oss-instruct-sc2-concepts |
from unittest.mock import call
def test(args=None):
"""
Runs the tests.
"""
module = getattr(args, 'module', '')
if module == '':
module = 'tests'
else:
module = 'tests.{}'.format(module)
return call("DJANGO_SETTINGS_MODULE='tests.settings' coverage run "
".... | bigcode/self-oss-instruct-sc2-concepts |
def const(xx, a):
"""
Returns the constant a for any xx.
"""
return a | bigcode/self-oss-instruct-sc2-concepts |
import re
def version_normalize(v):
"""Normalize version string numbers like 3.10.1 so they can be compared."""
return [int(x) for x in re.sub(r'(\.0+)*$', '', v).split(".")] | bigcode/self-oss-instruct-sc2-concepts |
def duplicated_varnames(df):
"""Return a dict of all variable names that
are duplicated in a given dataframe."""
repeat_dict = {}
var_list = list(df) # list of varnames as strings
for varname in var_list:
# make a list of all instances of that varname
test_list = [v for v in var_lis... | bigcode/self-oss-instruct-sc2-concepts |
def convert_color(color):
"""Converts a color object (be it touple-like, or string to an SVG-readable color string)."""
if type(color) == str:
return color
else:
return '#' + ''.join(('0' + hex(int(c))[2:])[-2:] for c in color) | bigcode/self-oss-instruct-sc2-concepts |
def get_shortest_path(path_list):
"""
Return the shortest path (the uppest path)
(Used for find the uppest path for the files with the same filename)
Parameter
path_list: list[path-like str], e.g. ["./db.json", "./test/db.json", "./config/db.json"]
Return
return the shortest path, e... | bigcode/self-oss-instruct-sc2-concepts |
def getType(v):
"""
Returns a tuple with True if a vsip type is found, plus a string indicating the type.
For instance for
a = vsip_vcreate_f(10,VSIP_MEM_NONE)
will return for the call getType(a) (True,'vview_f')
also returns types of scalars derived from structure. for insta... | bigcode/self-oss-instruct-sc2-concepts |
def paths_are_not_structured(paths):
"""
returns true if the list of paths are not yet file system structured.
i.e. if not all paths start with the root path (contribution label)
"""
if not paths:
return False
root = paths[0][: paths[0].find('/', 1)]
for path in reversed(paths):
... | bigcode/self-oss-instruct-sc2-concepts |
def _evaluate(comp):
"""
Evaluates the value of a given expression component.
Parameters
----------
comp : dict
Dictionary of references, coefficient and operator
Returns
-------
v : float
Current value of the expression.
"""
ref = comp['ref']
val = comp['v... | bigcode/self-oss-instruct-sc2-concepts |
def compute_n_trials(trials):
"""
Compute number of trials in trials object
:param trials: trials object
:type trials: dict
returns: int containing number of trials in session
"""
return trials['choice'].shape[0] | bigcode/self-oss-instruct-sc2-concepts |
def correction_byte_table_l() -> dict[int, int]:
"""Table of the number of correction bytes per block for the correction
level L.
Returns:
dict[int, int]: Dictionary of the form {version: number of correction
bytes}
"""
table = {
1: 7, 2: 10, 3: 15, 4: 20, 5: 26, 6: 18, 7: 2... | bigcode/self-oss-instruct-sc2-concepts |
import gzip
def smart_open(filename: str, mode="rt", ftype="auto", errors='replace'):
"""
Returns a file descriptor for filename with UTF-8 encoding.
If mode is "rt", file is opened read-only.
If ftype is "auto", uses gzip iff filename endswith .gz.
If ftype is {"gzip","gz"}, uses gzip.
Note:... | bigcode/self-oss-instruct-sc2-concepts |
def get_tweet_object_from_tweet_js(seq, num_of_tweet_block):
"""
Helper method to get each smaller tweet blocks.
Tested May 2020 on tweet.js (subject to change as Twitter rolls out new data layout)
Parameters:
seq: (file object) opens a file in read mode.
num_of_tweet_block: (int) ... | bigcode/self-oss-instruct-sc2-concepts |
def flatten_list(obj):
"""
Given a set of embedded lists, return a single, "flattened" list.
:param obj:
:return:
"""
if not isinstance(obj, list):
return [obj]
else:
ret_list = []
for elt in obj:
ret_list.extend(flatten_list(elt))
return ret_list | bigcode/self-oss-instruct-sc2-concepts |
def verify_brother(brother, user):
""" Verify user is the same as brother """
if user.brother.id == brother.id:
return True
else:
return False | bigcode/self-oss-instruct-sc2-concepts |
def _combine_sup_unsup_datasets(sup_data, unsup_data):
"""Combines supervised and usupervised samples into single dictionary.
Args:
sup_data: dictionary with examples from supervised dataset.
unsup_data: dictionary with examples from unsupervised dataset.
Returns:
Dictionary with combined suvervised... | bigcode/self-oss-instruct-sc2-concepts |
def my_isclose(a, b, rel_tol=1e-09, abs_tol=0.0):
"""
Test if a and b are close enough to consider equal.
This function is essentially the same as the math.isclose function which
was added in Python 3.5 but is created here to increase compatibility across
all Python 3 versions.
"""
retu... | bigcode/self-oss-instruct-sc2-concepts |
def keyExists(thisDict, key):
"""Returns true if dictionary contains the key"""
return key in thisDict | bigcode/self-oss-instruct-sc2-concepts |
from typing import Optional
from typing import Union
from typing import Sequence
from typing import Tuple
def _verify_encodings(
encodings: Optional[Union[str, Sequence[str]]]
) -> Optional[Tuple[str, ...]]:
"""Checks the encoding to ensure proper format"""
if encodings is None:
return None
i... | bigcode/self-oss-instruct-sc2-concepts |
def user_confirm(prompt, default=False):
"""Yes/No question dialog with user.
:param prompt: question/statement to present to user (string)
:param default: boolean value to return if empty string
is received as response to prompt
"""
if default:
prompt_default = "[Y/n]"... | bigcode/self-oss-instruct-sc2-concepts |
import math
def calculate_vr_from_vm_va(vm, va):
"""
Compute the value of vr from vm and va
Parameters
----------
vm : float
The value of voltage magnitude (per)
va : float
The value of voltage angle (degrees)
Returns
-------
float : the value of vr or None if... | bigcode/self-oss-instruct-sc2-concepts |
def get_op_tensor_name(name):
"""
Will automatically determine if ``name`` is a tensor name (ends with ':x')
or a op name.
If it is an op name, the corresponding tensor name is assumed to be ``op_name + ':0'``.
Args:
name(str): name of an op or a tensor
Returns:
tuple: (op_name, tensor_name)
"""
if len(nam... | bigcode/self-oss-instruct-sc2-concepts |
import heapq
def dijkstra(graph, source, target):
"""
Finds the shortest path and shortest distance from source to target
:param graph: Dictionary linking the vertices using list of tuples
:param source: The vertex to start the path.
:param target: The vertex to end the path.
:return: shortes... | bigcode/self-oss-instruct-sc2-concepts |
def parse_line(line):
"""Parse line to (instruction, value) tuple."""
return [int(part) if part.isdigit() else part for part in line.split()] | bigcode/self-oss-instruct-sc2-concepts |
from typing import Dict
from typing import Any
def has_key(dictionary: Dict[str, Any], key: str) -> bool:
"""
Check whether dictionary has given key is present or not
:param dictionary: Dictionary that need to check if key present or not
:param key: Key value that need to check
:return: Boolean v... | bigcode/self-oss-instruct-sc2-concepts |
import time
def retry(func, max_tries = 16, timeout = 0.1):
"""Helper to retry functions and preserve exceptions, handy for network calls."""
acm = 0
while True:
try:
return func()
except Exception as exception:
if acm > max_tries:
raise exce... | bigcode/self-oss-instruct-sc2-concepts |
def scale(val, old_scale, new_scale=100):
""" Change scale of a value
:param val: value
:param old_scale: current scale max value
:param new_scale: new scale max value
:return: value converted to new scale """
return float(val * new_scale) / old_scale | bigcode/self-oss-instruct-sc2-concepts |
def decide_flow_name(desc):
"""
Based on the provided description, determine the FlowName.
:param desc: str, row description
:return: str, flowname for row
"""
if 'Production' in desc:
return 'Production'
if 'Consumed' in desc:
return 'Consumed'
if 'Sales' in desc:
... | bigcode/self-oss-instruct-sc2-concepts |
def omit_keys(*args):
"""Remove keys from a dictionary"""
*keys, dict_obj = args
return {
field: value
for field, value in dict_obj.items()
if field not in keys
} | bigcode/self-oss-instruct-sc2-concepts |
def register_extensions(db, app):
"""Register Flask extensions."""
db.init_app(app)
with app.app_context():
db.create_all()
return None | bigcode/self-oss-instruct-sc2-concepts |
def tuning_score_distribution(performance_space, nbins=10):
"""
Computes TS_d, the tuning score based on the distribution of configurations in the performance space.
"""
histogram = performance_space.histogram(nbins)
if (histogram[9] / performance_space.size()) >= 0.1:
return ((0.5 / 0.9) *... | bigcode/self-oss-instruct-sc2-concepts |
def sliding_window(array, window, step=1, axis=0):
"""Generate chunks for encoding and labels.
Args:
array: Numpy array with the pileup counts
window: Length of output chunks
step: window minus chunk overlap
axis: defaults to 0
Returns:
Iterator with chunks
"""
... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def accuracy(output, target):
"""
Accuracy metric for deterministic model for classification.
Args:
output: Output Tensor with shape (examples, classes)
target: Target Tensor with shape (examples)
Returns: float accuracy
"""
with torch.no_grad():
pred = t... | bigcode/self-oss-instruct-sc2-concepts |
def vert_init_commodities(vertex_df, commodities, sources=None, inplace=True):
"""Add commodity columns to the vertex DataFrame
with zeros to vertices without commodity source and
source capacity at the vertices provided by `sources`.
Parameters
----------
vertex_df : (Geo)DataFrame
ver... | bigcode/self-oss-instruct-sc2-concepts |
def select_metadata(metadata, **attributes):
"""Select specific metadata describing preprocessed data.
Parameters
----------
metadata : :obj:`list` of :obj:`dict`
A list of metadata describing preprocessed data.
**attributes :
Keyword arguments specifying the required variable attri... | bigcode/self-oss-instruct-sc2-concepts |
def set_same_eff_all_tech(technologies, f_eff_achieved=1):
"""Helper function to assing same achieved efficiency
Arguments
----------
technologies : dict
Technologies
f_eff_achieved : float,default=1
Factor showing the fraction of how much an efficiency is achieved
Returns
... | bigcode/self-oss-instruct-sc2-concepts |
def smoothstep(a, b, x):
""" Returns the Hermite interpolation (cubic spline) for x between a and b.
The return value between 0.0-1.0 eases (slows down) as x nears a or b.
"""
if x < a:
return 0.0
if x >= b:
return 1.0
x = float(x - a) / (b - a)
return x * x * (3 - 2 * x) | bigcode/self-oss-instruct-sc2-concepts |
def CalculateNumBonds(mol):
"""
Calculation the number of bonds where between heavy atoms
--->nBond
:param mol: molecule
:type mol: rdkit.Chem.rdchem.Mol
:return: the number of bonds where between heavy atoms
:rtype: int
"""
nBond = mol.GetNumBonds()
retu... | bigcode/self-oss-instruct-sc2-concepts |
from pathlib import Path
from typing import List
def read_fasta(path: Path) -> List[tuple]:
"""Parse the FASTA file at `path` and return its content as a `list` of tuples containing the header and sequence.
:param path: the path to the FASTA file
:return: the FASTA content
"""
data = list()
... | bigcode/self-oss-instruct-sc2-concepts |
def quote_str(value):
"""
Return a string in double quotes.
Parameters
----------
value : str
Some string
Returns
-------
quoted_value : str
The original value in quote marks
Example
-------
>>> quote_str('some value')
'"some value"'
"""
return ... | bigcode/self-oss-instruct-sc2-concepts |
def ends_with(suffix):
"""
Returns a function calling endswith using the given prefix on a given value.
>>> ends_with('123')('abc123')
True
>>> ends_with('abc')('abc123')
False
:param suffix: Suffix to check
:return: Function
"""
def _ends_with(s):
return s.endswith(su... | bigcode/self-oss-instruct-sc2-concepts |
import pickle
def load_pickle(filename):
"""
Load formatted skeleton data from pickle file
"""
with open(filename, 'rb') as fp:
data = pickle.load(fp)
return data | bigcode/self-oss-instruct-sc2-concepts |
def limit(value, v_min, v_max):
"""
limit a float or int python var
:param value: value to limit
:param v_min: minimum value
:param v_max: maximum value
:return: limited value
"""
try:
return min(max(value, v_min), v_max)
except TypeError:
return None | bigcode/self-oss-instruct-sc2-concepts |
async def twochars_async(arg):
"""
Formats a string of two characters into the format of (0X), useful for date formatting.
:param arg: The string
:return: String
"""
if len(arg) == 1:
return f"0{arg}"
return arg | bigcode/self-oss-instruct-sc2-concepts |
from typing import Union
from typing import Literal
import requests
def __ping_wayback_machine(url: str) -> Union[Literal[False], str]:
"""Check the Web Archive for an archived URL."""
r = requests.get(f"https://archive.org/wayback/available?url={url}").json()
if not r["archived_snapshots"]:
retur... | bigcode/self-oss-instruct-sc2-concepts |
from datetime import datetime
def str_to_datetime(s):
"""
Parse ISO datetime string and return a datetime object
:param str s: date/time string
:return: datetime object, None if not a valid date/time string
:rtype: datetime.datetime | None
"""
t = None
for fmt in ('%Y-%m-%dT%H:%M:%S.... | bigcode/self-oss-instruct-sc2-concepts |
def get_lsb (string, n):
"""
Get LSB with lenght=n of string
:param string: string
:param n: integer
:returns: string
"""
return str(string[-n:]) | bigcode/self-oss-instruct-sc2-concepts |
def singleChoiceWithSubParams(parameters, name, type_converter = str):
""" single choice with sub parameters value and chosen subparameters. Returns -1 and None if no value was chosen.
:param parameters: the parameters tree.
:param name: the name of the parameter.
:param type_converter: function to conv... | bigcode/self-oss-instruct-sc2-concepts |
def _LowercaseDict(d):
"""Returns a copy of `d` with both key and values lowercased.
Args:
d: dict to lowercase (e.g. {'A': 'BcD'}).
Returns:
A dict with both keys and values lowercased (e.g.: {'a': 'bcd'}).
"""
return {k.lower(): d[k].lower() for k in d} | bigcode/self-oss-instruct-sc2-concepts |
def load_vocab(filename):
"""Loads vocab from a file
Args:
filename: (string) the format of the file must be one word per line.
Returns:
d: dict[word] = index
"""
# try:
d = dict()
with open(filename) as f:
for idx, word in enumerate(f):
word = word.str... | bigcode/self-oss-instruct-sc2-concepts |
def HasValue(entity, property_name):
"""Returns whether `entity` has a property value with the provided name."""
return property_name in entity._values # pylint: disable=protected-access | bigcode/self-oss-instruct-sc2-concepts |
def default_layout(fig, n):
"""Setup a default layout for given number of axes.
Args:
fig: matplotlib figure
n: Number of axes required
Returns:
List of Axes
Raises:
ValueError: When no ax axes or > 9*9 are required. When no figure is given.
"""
if fig is None:
... | bigcode/self-oss-instruct-sc2-concepts |
import sqlite3
def check_priv(dbName, uid):
"""
checks the database to see if the user has the title of privileged.
Parameters:
dbName: String. Name of the database, derived from terminal.py
uid: 4 character string. Unique ID of the user, used for loads the things in the program.
Returns:
check: Boole... | bigcode/self-oss-instruct-sc2-concepts |
def captureStandardization(df, columns=None):
"""A function factory that creates a function for standardizing all columns
in df with each columns mean and standard deviation."""
if columns is None:
columns = df.columns
stdParams = {}
for c in columns:
mu = df[c].mean()
sigma2... | bigcode/self-oss-instruct-sc2-concepts |
def _token_str(token):
"""Shorten token so we do not leak sensitive info into the logs"""
if len(token) < 10:
# for some reason too short to reveal even a part of it
return "???TOOSHORT"
return token[:3] + '...' | bigcode/self-oss-instruct-sc2-concepts |
def get_requested_grants(settings):
"""Retrieve any valid requested_grants from dict settings
:param settings: dictionary which may contain key, requested_grants,
with comma delimited list of roles to grant.
:returns: list of roles to grant
"""
if ('requested_grants' in setting... | bigcode/self-oss-instruct-sc2-concepts |
def parse_input(input_data):
"""
Returns an array of unique cities and a dictionary of the distances between them
Each line of the input data must be in the format: City1 to City2 = 123
"""
lines = input_data.splitlines()
cities_arr = []
cities_dict = {}
distances = {}
for line in li... | bigcode/self-oss-instruct-sc2-concepts |
import math
def Log_Nash_Sutcliffe(SimulatedStreamFlow, ObservedStreamFlow):
"""
(SimulatedStreamFlow, ObservedStreamFlow)
Logarithmic Nash-Sutcliffe model efficiency coefficient
"""
x = SimulatedStreamFlow
y = ObservedStreamFlow
A = 0.0 # dominator
B = 0.0 # deminator
tot = 0.0
... | bigcode/self-oss-instruct-sc2-concepts |
def get_shared_vocab(vocab1, vocab2):
"""Return intersection of two vocabs."""
shared_words = set(word for word in vocab1 if word in vocab2)
return {word: idx for idx, word in enumerate(shared_words)} | bigcode/self-oss-instruct-sc2-concepts |
def CommaCode(inputList):
"""Takes a list value as an argument and returns \
a string with all the items separated by a comma \
and a space, with and inserted before the last item."""
inputList[-1] = 'and ' + str(inputList[-1])
return ", ".join(inputList) | bigcode/self-oss-instruct-sc2-concepts |
def normalize_url(url):
"""Make sure the url is in correct form."""
result = url
if not result.endswith("/"):
result = result + "/"
return result | bigcode/self-oss-instruct-sc2-concepts |
def get_dot_indices(face_index_from_1):
"""Get indices (from 0 through 20) corresponding to dots on the given face (from 1 through 6)."""
if face_index_from_1 == 1:
return [0]
elif face_index_from_1 == 2:
return [1,2]
elif face_index_from_1 == 3:
return [3,4,5]
elif face_inde... | bigcode/self-oss-instruct-sc2-concepts |
def dict_factory(cursor, row):
"""
Replace the row_factory result constructor with a dictionary constructor.
Args:
cursor: (object) the sqlite3 database cursor object.
row: (list) a result list.
Returns:
d: (dictionary) sqlite3 results dictionary.
Raises:
"""
d ... | bigcode/self-oss-instruct-sc2-concepts |
def _str2h5attr(data: str) -> str:
"""Add a str prefix to distinguish an actual string from the other types saved as strings"""
return f"str {data}" | bigcode/self-oss-instruct-sc2-concepts |
def program_entry(program):
"""
Template tag {% program_entry program %} is used to display a single
program.
Arguments
---------
program: Program object
Returns
-------
A context which maps the program object to program.
"""
return {'program': program} | bigcode/self-oss-instruct-sc2-concepts |
def parametrized(dec):
"""This decorator can be used to create other decorators that accept arguments"""
def layer(*args, **kwargs):
def repl(f):
return dec(f, *args, **kwargs)
return repl
return layer | bigcode/self-oss-instruct-sc2-concepts |
def changeset_revision_reviewed_by_user( user, repository, changeset_revision ):
"""Determine if the current changeset revision has been reviewed by the current user."""
for review in repository.reviews:
if review.changeset_revision == changeset_revision and review.user == user:
return True
... | bigcode/self-oss-instruct-sc2-concepts |
def startswith_in_list(src, items):
"""
Comparaison de type "startswith" avec une liste de 'match' possibles
"""
for k in items:
if src.startswith(k):
return k
return False | bigcode/self-oss-instruct-sc2-concepts |
def get_first_non_none_value(*configs, key, default=None, callback=None):
"""Get the first non-None value for a key from a list of dictionaries.
This function allows to prioritize information from many configurations by changing
the order of the inputs while also providing a default.
Examples
----... | bigcode/self-oss-instruct-sc2-concepts |
def get_item(dictionary, key_id):
"""Returns value in dictionary from the key_id.
Used when you want to get a value from a dictionary key using a variable
:param dictionary: dict
:param key_id: string
:return: value in the dictionary[key_id]
How to use:
{{ mydict|get_item:i... | bigcode/self-oss-instruct-sc2-concepts |
import logging
def create_logger(logger_name: str) -> logging.Logger:
"""Set up logging using the `logger_name`"""
logger = logging.getLogger(logger_name)
# Create console handler if not already present
if not logger.handlers:
ch = logging.StreamHandler()
formatter = logging.Formatte... | bigcode/self-oss-instruct-sc2-concepts |
def select_type(pathways, stype):
"""Selects all pathways of a given type
Parameters
----------
pathways : list
List of pathways to be analyzed
stype : str
Type of the pathways to be selected.
Possible values are "REPH", "NONR".
"""
di = d... | bigcode/self-oss-instruct-sc2-concepts |
def has_field(block, field_name):
""" Return whether the block has a field with the given name. """
return field_name in block.fields | bigcode/self-oss-instruct-sc2-concepts |
def get_scores(classProbabilities, trueLabels):
"""
Get scores of correct class
:param classProbabilities: list: list of arrays of prediction probabilities for each class
:param trueLabels: list: correct class labels
:return: list: scores for correct class
"""
return [p[l] for p, l in zip(cl... | bigcode/self-oss-instruct-sc2-concepts |
def get_generic_field_dict(cve, field):
"""
Attempts to extract the dictionary associated to the field
from the provided cve.
If none is found, returns an empty dictionary.
Parameters
----------
cve : dict
The dictionary generated from the CVE json.
Returns
-------
dict... | bigcode/self-oss-instruct-sc2-concepts |
def fake_frames(seq_name, field_name, value_seq):
""" Make fake frames for multiframe testing
Parameters
----------
seq_name : str
name of sequence
field_name : str
name of field within sequence
value_seq : length N sequence
sequence of values
Returns
-------
... | bigcode/self-oss-instruct-sc2-concepts |
def _dms2dd(d, m, s, dir):
"""
convert lat/lon degrees/minutes/seconds into decimal degrees
"""
degrees = float(d) + (float(m) / 60) + (float(s) / 3600)
if dir in ['S', 'W']:
degrees = degrees * -1
return degrees | bigcode/self-oss-instruct-sc2-concepts |
def flatten_dict(d: dict):
"""Flattens dictionary with subdictionaries.
Arguments:
d {dict} -- Dict to flatten
Returns:
flattened {dict} -- Flattened dict
"""
def items():
for key, value in d.items():
if isinstance(value, dict):
for subkey, sub... | bigcode/self-oss-instruct-sc2-concepts |
def parse_content_type(content_type):
"""Cleans up content_type."""
if content_type:
return content_type.split(';')[0].strip().lower()
else:
return '' | bigcode/self-oss-instruct-sc2-concepts |
def getSpan(array):
"""Return the span of `array`
span(array) = max array(s) - min array(s)
"""
return array.max() - array.min() | bigcode/self-oss-instruct-sc2-concepts |
def cropToAspectRatio(frame, size):
"""
Crop the frame to desired aspect ratio and then scales it down to desired size
Args:
frame (numpy.ndarray): Source frame that will be cropped
size (tuple): Desired frame size (width, height)
Returns:
numpy.ndarray: Cropped frame
"""
... | bigcode/self-oss-instruct-sc2-concepts |
def get_env_variable_str(d: dict):
"""
Creates a list of all the environment variables, that are relevant for the message generator.
:param d: dict, usually the the environment variables of the OS (as provided by os.locals())
:return: [str], of the format "<variable name>: <variable value>"
"""
... | bigcode/self-oss-instruct-sc2-concepts |
def GetContainerArgs(name: str):
"""Returns the command/arguments to start a process in a container.
Args:
name: The container name.
Returns:
The list with the command and arguments.
"""
return [
"container.py",
"run",
"--cpurate",
"100",
"--ram",
"60000",
"... | 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.