seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
def count(element, seq):
"""Counts and returns the number of times element occurs in the sequence"""
return seq.count(element) | bigcode/self-oss-instruct-sc2-concepts |
def break_links(x):
""" Break link to x by copying it"""
x = x.copy()
return x | bigcode/self-oss-instruct-sc2-concepts |
def clamp(value: float, n_min: float, n_max: float) -> float:
"""
returns a clamped value between min and max
:param value: the value to clamp
:param n_min: the minimum value
:param n_max: the maximum value
Example:
>>> clamp(12, 0, 10)
>>> 10
"""
return max(min(value, n... | bigcode/self-oss-instruct-sc2-concepts |
def load_config_auth(config_parser):
"""Convert an auth cfparser config into a dictionary
:param config_parser: configparser configuration
:type paths: class:`configparser.ConfigParser`
:return: configuration as a dictionary
:rtype: dict
"""
config = {'github': {'token': config_parser['gi... | bigcode/self-oss-instruct-sc2-concepts |
def diff(x):
"""Differences between subsequent values of a numpy.array"""
return x[1:] - x[:-1] | bigcode/self-oss-instruct-sc2-concepts |
def lonely_integer(a):
"""Hackerrank Problem: https://www.hackerrank.com/challenges/lonely-integer/problem
You will be given an array of integers. All of the integers except one occur twice. That one is unique in the array.
Given an array of integers, find and print the unique element.
For example, a... | bigcode/self-oss-instruct-sc2-concepts |
from pathlib import Path
def get_download_and_data_dirs(notebook="local"):
"""
Return DOWNLOAD_DIR and DATA_DIR depending on the type of notebook being
used.
Parameters
----------
notebook : str, optional {'local', 'colab'}
The type of notebook you are working in
Returns
----... | bigcode/self-oss-instruct-sc2-concepts |
def ignore_this_demo(args, reward, t, last_extras):
"""In some cases, we should filter out demonstrations.
Filter for if t == 0, which means the initial state was a success, and
also if we have exit_gracefully, which means for the bag-items tasks, it
may not have had visible item(s) at the start, for s... | bigcode/self-oss-instruct-sc2-concepts |
def encode_query(query, vocabulary):
"""Takes a textual query and a vocabulary (mapping from words to integers), returns the encoded query in a list.
If a word is not in the dictionary, the function returns False.
Args:
query (list): A textual query
vocabulary (dict): Mapping from all wo... | bigcode/self-oss-instruct-sc2-concepts |
import time
def wait_for_workload(client, workload_id, timeout=30):
"""Wait for a given workload to be active."""
def _get_result():
try:
return client.by_id_workload(workload_id)["state"]
except KeyError:
return ""
start = time.time()
while _get_result() != "ac... | bigcode/self-oss-instruct-sc2-concepts |
def newPipe(x, y, w, h):
"""
Create pipe object
"""
return {
"type": "rectangle",
"pos": [x,y],
"dim": [w, h]
} | bigcode/self-oss-instruct-sc2-concepts |
def collapsible_section(title: str, text: str) -> str:
"""Creates a collapsible section with the given title, and when expanded will show the given text.
:param title: The title for this collapsible section
:param text: The text to be displayed inside this collapsible section
"""
return f'<details>... | bigcode/self-oss-instruct-sc2-concepts |
def rotate90(tensor, times):
"""Rotate tensor clockwise by 90 degrees a number of times.
Assumes spatial dimensions are the last ones."""
if times == 1: # 90 deg
return tensor.transpose(-2, -1).flip(-1)
elif times == 2: # 180 deg
return tensor.flip(-2).flip(-1)
elif times == 3: # 270 deg
return... | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
import json
def load_train_data(train_data_files: str) -> List:
"""Load jsonl train data as a list, ready to be ingested by spacy model.
Args:
train_data_local_path (str): Path of files to load.
Returns:
List: Tuple of texts and dict of entities to be used for tra... | bigcode/self-oss-instruct-sc2-concepts |
import mpmath
def pdf(x, dfn, dfd):
"""
Probability density function of the F distribution.
`dfn` and `dfd` are the numerator and denominator degrees of freedom, resp.
"""
if x <= 0:
return mpmath.mp.zero
with mpmath.mp.extradps(5):
x = mpmath.mp.mpf(x)
dfn = mpmath.m... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Union
from pathlib import Path
def is_cwd(path: Union[Path, str]) -> bool:
"""Check whether a path is the current working directory.
path (Union[Path, str]): The directory path.
RETURNS (bool): Whether the path is the current working directory.
"""
return str(Path(path).resolve... | bigcode/self-oss-instruct-sc2-concepts |
def listing(items: list[str], separator: str, conjunction: str = "") -> str:
"""Return human readable list separated by separator.
Optional argument is conjuntion that substitutes the last separator.
Args:
items: list of items.
separator: separator of items.
conjunction: word/strin... | bigcode/self-oss-instruct-sc2-concepts |
def get_measurements(region, core_info, data, extra_offset=0):
"""
Get the complete measurement info from likwid's region info.
Args:
region: The region we took a measurement in.
core_info: The core information.
data: The raw data.
extra_offset (int): default = 0
Return... | bigcode/self-oss-instruct-sc2-concepts |
def is_value(s):
"""Test if parameter is a number or can be interpreted as a number"""
s = str(s)
return s.isdigit() or (len(s) == 1 and s[0] in "AJQK") | bigcode/self-oss-instruct-sc2-concepts |
import zipfile
import io
def open_zipfile(archive, filename, directory=None):
"""Retrieves a given file from a ZIP archive.
Args:
archive (:obj:`~zipfile.ZipFile`, str): The ZipFile object or path to
the ZIP archive containing the desired file.
filename (str): The name of the file... | bigcode/self-oss-instruct-sc2-concepts |
def aggregate_ravens(data, sub_num):
"""
Aggregate data from the Raven's Matrices task.
Calculates various summary statistics for the Raven's Matrices task for a
given subject.
Parameters
----------
data : dataframe
Pandas dataframe containing a single subjects trial data for the ... | bigcode/self-oss-instruct-sc2-concepts |
def calculate_total_user_pp(osu_scores: list, member_id: str, osu_tracking: dict):
""" Calculates the user's total PP. """
total_pp = 0
for i, osu_score in enumerate(osu_scores):
total_pp += osu_score["pp"] * (0.95 ** i)
total_pp_without_bonus_pp = 0
for osu_score in osu_tracking[member_id][... | bigcode/self-oss-instruct-sc2-concepts |
def _get_field_value(field_to_get, object_to_search):
"""
Gets the value of a nested object, for example, if we search
'address.city.neighborhood' in the object:
{'address':
{'city':
{'neighborhood': 'shapira'}
}
}
The returned value will be 'shapira'
:param fiel... | bigcode/self-oss-instruct-sc2-concepts |
import json
def chk_err_in_payload(json_payload, exc: bool = True):
"""
Check if there are error(s) indicated in response.
:param json_payload:
:param exc: Should raise exception if error found.
"""
err_fields = {'error', 'errors'}
for errf in err_fields:
if errf in json_payload a... | bigcode/self-oss-instruct-sc2-concepts |
import itertools
def gen_permutations(names, items, hack=False):
"""Takes a list of string names and a list of string items. Returns
len(name) sized permutations of items.
"""
if (not hack):
p = itertools.permutations(items, len(names))
else:
p = itertools.permutations(names, len(i... | bigcode/self-oss-instruct-sc2-concepts |
def _calculate_number_rows_plot(n_media_channels: int, n_columns: int):
"""Calculates the number of rows of plots needed to fit n + 1 plots in n_cols.
Args:
n_media_channels: Number of media channels. The total of plots needed is
n_media_channels + 1.
n_columns: Number of columns in the plot grid.
... | bigcode/self-oss-instruct-sc2-concepts |
def reporting_date(submission):
"""Format submission reporting date"""
if not (submission.reporting_start_date or submission.reporting_end_date):
return None
if submission.is_quarter_format:
return 'Q{}/{}'.format(submission.reporting_fiscal_period // 3,
submis... | bigcode/self-oss-instruct-sc2-concepts |
def add_parameter_group_to_list_of_dicts( Dlist, names, values ):
"""
Copies and returns the given list of dictionaries but with
names[0]=values[0] and names[1]=values[1] etc added to each.
"""
assert len(names) == len(values)
N = len(names)
new_Dlist = []
for D in Dlist:
newD ... | bigcode/self-oss-instruct-sc2-concepts |
def unset_bit(string: int, pos: int) -> int:
"""Return bitstring with the bit at the position unset
Args:
string (int): bit string
pos (int): position in the bit string
Returns:
int: string with the pos bit set to 0
"""
return int(string) & ~(1 << pos) | bigcode/self-oss-instruct-sc2-concepts |
def _get(item_id, items, id_key):
"""Get item from list with given ID."""
return next(item for item in items if item[id_key] == item_id) | bigcode/self-oss-instruct-sc2-concepts |
import string
import random
def flaskify_endpoint(identifier, randomize=None):
"""
Converts the provided identifier in a valid flask endpoint name
:type identifier: str
:param randomize: If specified, add this many random characters (upper case
and digits) to the endpoint name, separated by a... | bigcode/self-oss-instruct-sc2-concepts |
def extract_best_aligns(aligns_df):
"""Extracts alignments with highest score from the provided alignments
dataframe.
"""
mask = aligns_df.groupby('seq_index').agg({'score': 'idxmax'}) # get /!\ FIRST /!\ index of max align score for each sequence
aligns_df_best = aligns_df.loc[mask['score']].rese... | bigcode/self-oss-instruct-sc2-concepts |
import math
def haversine(p1, p2):
"""Calculate the distance between two (degree) longitude/latitude points in meters"""
lon1, lat1 = p1
lon2, lat2 = p2
# Earth radius in meters
R = 6371e3
# φ, λ in radians
φ1 = lat1 * math.pi / 180
φ2 = lat2 * math.pi / 180
Δφ = (lat2 - lat1) *... | bigcode/self-oss-instruct-sc2-concepts |
def ones(m,n):
"""Return an m-by-n arrayList consisting of all ones.
>>> ones(2,3)
[[1, 1, 1], [1, 1, 1]]
"""
return m * [n * [1]] | bigcode/self-oss-instruct-sc2-concepts |
def score_ap_from_ranks_1(ranks, nres):
""" Compute the average precision of one search.
ranks = ordered list of ranks of true positives
nres = total number of positives in dataset
"""
# accumulate trapezoids in PR-plot
ap = 0.0
# All have an x-size of:
recall_step = 1.0 / nres
f... | bigcode/self-oss-instruct-sc2-concepts |
import math
def calc_prob_prior(iterations, lam):
"""
Calculates the alpha prob for the mixture as
$$\alpha_i = \exp(-ki), \quad i = 0,1,\ldots,iterations$$
:param iterations: nbr of iterations for SPA
:param lam: decay rate
:return: list of length iterations with the prob. for prior in the... | bigcode/self-oss-instruct-sc2-concepts |
def are_relatively_prime(a, b):
"""Return ``True`` if ``a`` and ``b`` are two relatively prime numbers.
Two numbers are relatively prime if they share no common factors,
i.e. there is no integer (except 1) that divides both.
"""
for n in range(2, min(a, b) + 1):
if a % n == b % n == 0:
... | bigcode/self-oss-instruct-sc2-concepts |
import re
def find_and_replace(items, updates):
"""
aka find_and_replace
apply all updates in updates list
to all items in items list
updates consist of a list of lists
where the sub lists contain:
(search_string, replace_string)
"""
for u in updates:
search_string = u[0]... | bigcode/self-oss-instruct-sc2-concepts |
def filter_length(d, n):
"""Select only the words in d that have n letters.
d: map from word to list of anagrams
n: integer number of letters
returns: new map from word to list of anagrams
"""
res = {}
for word, anagrams in d.items():
if len(word) == n:
res[word] = anagra... | bigcode/self-oss-instruct-sc2-concepts |
def dict_to_sorted_pairs(d):
#===============================================================================
"""
Convert a dictionary to a list of key/value pairs sorted by key.
"""
keys = list(d.keys())
keys.sort()
results = []
for key in keys:
results.append((key, d[key]))
ret... | bigcode/self-oss-instruct-sc2-concepts |
def query_starts_with(formatted_sql, prefixes):
"""Check if the query starts with any item from *prefixes*."""
prefixes = [prefix.lower() for prefix in prefixes]
return bool(formatted_sql) and formatted_sql.split()[0] in prefixes | bigcode/self-oss-instruct-sc2-concepts |
def to_readable(src: int, unit: str = "bps") -> str:
"""
Convert number to human readable string.
For example: 1,000,000 bps to 1Mbps. 1,000 bytes to 1KB
:parameters:
src : int
the original data
unit : str
the unit ('bps', 'pps', or 'bytes')
:returns:
... | bigcode/self-oss-instruct-sc2-concepts |
def ask_multi_lines(prompt="Type :", escape_string="."):
"""Get input from user provided multilines
Keyword Arguments:
prompt {str} -- the question message (default: {"Type :"})
escape_string {str} -- escape character (default: {"."})
Returns:
str -- the text seperated by l... | bigcode/self-oss-instruct-sc2-concepts |
import string
def load_phrases(filename):
"""Load phrases from file and strip punctuation characters."""
f = open(filename, 'r')
punctuation_table = str.maketrans({key: None for key in string.punctuation})
phrases = [line.lower().rstrip("\r\n").translate(punctuation_table) for line in f]
f.close()
return phrase... | bigcode/self-oss-instruct-sc2-concepts |
def is_uvular(sound):
"""
Check if a sound is uvular or not.
"""
return sound.obj.place == "uvular" | bigcode/self-oss-instruct-sc2-concepts |
from datetime import datetime
def short_time(t=None):
""" Time used in printed messages """
if t is None:
t = datetime.now()
return str(t.strftime("%H:%M:%S")) | bigcode/self-oss-instruct-sc2-concepts |
def is_number(num):
"""
Determine whether a string s is a number (i.e., any floating point
representation of a number, including scientific notation)
"""
try:
float(num)
return True
except ValueError:
return False | bigcode/self-oss-instruct-sc2-concepts |
import torch
def swish(tensor):
"""
Swish activation is simply f(x)=x⋅sigmoid(x)
Paper: https://arxiv.org/abs/1710.05941
"""
return tensor * torch.sigmoid(tensor) | bigcode/self-oss-instruct-sc2-concepts |
def seqid_to_filename(seqid):
"""
Makes a sequence id filename friendly.
(eg, replaces '|' with '_')
"""
return seqid.replace("|", "_") | bigcode/self-oss-instruct-sc2-concepts |
def needs_update(source, target):
"""Return True if a file does not exist or is out of sync
:param pathlib.Path source: Source path
:param pathlib.Path target: Target path
"""
if target.exists() and target.lstat().st_mtime == source.lstat().st_mtime:
return False
else:
return Tr... | bigcode/self-oss-instruct-sc2-concepts |
def norm(value, start, stop):
"""
Interpolate using a value between 0 and 1
See also: https://processing.org/reference/norm_.html
"""
return start + (stop-start) * value | bigcode/self-oss-instruct-sc2-concepts |
def get_viewconf_status(files):
"""
Determine the Higlass viewconf's status based on the files used to compose it.
Args:
files(list) : A list of file objects that contain a status.
Returns:
A string.
"""
# The viewconf will be in "released to lab" status if any fil... | bigcode/self-oss-instruct-sc2-concepts |
def dict_to_json_keys(pydict: dict) -> dict:
"""this converts a dict using the python coding style to a dict
where the keys are in JSON format style
:pydict dict keys are strings in python style format
:returns dict
"""
d = {}
for key in pydict.keys():
new_key = key.title().replace('... | bigcode/self-oss-instruct-sc2-concepts |
import re
def tokenize(line):
"""Normalizes and tokenizes a line from a .tess file
Capital letters are changed to lowercase, line numbering and
extraneous whitespace is removed, and the result is given as
a list of tokens.
The tokenizer is intended to be applied to a line from a .tess
file a... | bigcode/self-oss-instruct-sc2-concepts |
def mag_to_flux(catalog, mag_col, zeropoint=27.0, update=True):
"""
Convert AB magnitude into HSC image flux unit.
"""
flux = 10.0 ** ((zeropoint - catalog[mag_col]) / 2.5)
if update:
flux_col = mag_col.replace('mag', 'flux')
if flux_col in catalog.colnames:
catalog.remov... | bigcode/self-oss-instruct-sc2-concepts |
import string
def _expand_wildcard(expr: str, num_wildcard_dims: int) -> str:
"""Replaces a wildcard with the correct number of axes.
Args:
expr: Shape expression containing '...'.
num_wildcard_dims: Number of dimensions captured by the wildcard.
Returns:
Copy of `expr` with the wildcard '...' rep... | bigcode/self-oss-instruct-sc2-concepts |
def calculate_chunks(dataset):
"""
For the given dataset, calculate if the size on any dimension is
worth chunking. Any dimension larger than 4000 will be chunked. This
is done to ensure that the variable can fit in memory.
Parameters
----------
dataset : xarray.Dataset
The dataset ... | bigcode/self-oss-instruct-sc2-concepts |
def recursive_sort(v):
"""Recursively sort a nested python objects of lists, dicts,
strings, ints, and floats
"""
def sort_key(v):
if isinstance(v, (list, dict, tuple)):
return str(type(v))
return f"{type(v)}-{v}"
if isinstance(v, dict):
sorted_keys = sorted(v.... | bigcode/self-oss-instruct-sc2-concepts |
def wordgen(iters, base_cases, rule, return_all=False):
"""generate arbitrary recursive words
Args:
iters (int): number of iterations to run on top of base cases
base_cases (list of strings): strings which your rule can refer to
rule (method): A function that takes in previous strings a... | bigcode/self-oss-instruct-sc2-concepts |
def get_headers(data):
"""Loop through the data and collect any headers.
:param data list[dict]:
:rtype: set[str]
:returns: set of headers
"""
return {k for row in data for k, _ in row.iteritems()} if data is not None else None | bigcode/self-oss-instruct-sc2-concepts |
def can_import_module(module_name):
"""
Check if the specified module can be imported.
Intended as a silent module availability check, as it does not print ModuleNotFoundError traceback to stderr when
the module is unavailable.
Parameters
----------
module_name : str
Fully-qualifie... | bigcode/self-oss-instruct-sc2-concepts |
def geo_db_path(type):
"""
Returns the full path of a specific GeoLite2 database
Args:
type (str): The type of database path to retrieve (ASN, City, Country)
Raises:
ValueError: An invalid database type has been provided
Returns:
str: The absolute path to the specified dat... | bigcode/self-oss-instruct-sc2-concepts |
def get_action_value(mdp, state_values, state, action, gamma):
""" Computes Q(s,a) as in formula above """
q_value = 0.0
for next_state in mdp.get_next_states(state,action):
q_value += (mdp.get_transition_prob(state, action, next_state)*
(mdp.get_reward(state, action,next_state) + gamma*stat... | bigcode/self-oss-instruct-sc2-concepts |
def channels_to_last_dim(X):
"""
Takes a signal with channels on the second dimension (for convolutions) and
returns it with channels on the last dimension (for most operations).
"""
return X.permute(*([0] + list(range(2, X.dim())) + [1])) | bigcode/self-oss-instruct-sc2-concepts |
def lzip(*args):
"""
zip(...) but returns list of lists instead of list of tuples
"""
return [list(el) for el in zip(*args)] | bigcode/self-oss-instruct-sc2-concepts |
import click
def _style(enabled, text, **kwargs):
""" Helper function to enable/disable styled output text.
Args:
enable (bool): Turn on or off styling.
text (string): The string that should be styled.
kwargs (dict): Parameters that are passed through to click.style
Returns:
... | bigcode/self-oss-instruct-sc2-concepts |
def RerouteTensor(t0, t1, can_modify=None):
"""Reroute the end of the tensor t0 to the ends of the tensor t1.
Args:
t0: a tf.Tensor.
t1: a tf.Tensor.
can_modify: iterable of operations which can be modified. Any operation
outside within_ops will be left untouched by this function.
Returns:
... | bigcode/self-oss-instruct-sc2-concepts |
def isiterable(o):
"""
Return True if the given object supports having iter() called on it BUT is not an
instance of string. Otherwise return False.
"""
if isinstance(o, (str, bytes)):
return False
try:
iter(o)
except TypeError:
return False
else:
return... | bigcode/self-oss-instruct-sc2-concepts |
def message_context_from_workflow_context(ctx):
"""Build a message context from a CloudifyWorkflowContext instance"""
return {
'blueprint_id': ctx.blueprint.id,
'deployment_id': ctx.deployment.id,
'execution_id': ctx.execution_id,
'workflow_id': ctx.workflow_id,
} | bigcode/self-oss-instruct-sc2-concepts |
def generate_relating_lines(input_field, output_field, function_name, field_prefix=""):
"""
Generates lua lines that checks other fields related to input_field for feature engineering
:param input_field: original censys field
:param output_field: flattened version of censys field
:param function_na... | bigcode/self-oss-instruct-sc2-concepts |
def _pbkdf1(hash_alg, passphrase, salt, count, key_size):
"""PKCS#5 v1.5 key derivation function for password-based encryption
This function implements the PKCS#5 v1.5 algorithm for deriving
an encryption key from a passphrase and salt.
The standard PBKDF1 function cannot generate more key by... | bigcode/self-oss-instruct-sc2-concepts |
import calendar
def _calculate_meeting_days_per_month(chosen_weekday, chosen_ordinals, year, month):
"""
Lots of city meeting websites describe their upcoming meetings by saying
things like: "this committee meets the 1st and 3rd Tuesday of every month".
This calculator is intended to help parse dates ... | bigcode/self-oss-instruct-sc2-concepts |
def strip_quotes(data):
"""
Strips whitespaces and then quotes (single or double) at both sides of data.
:param data: string
:return: dict: 'value': everything inside single or double quotes,
'error': empty string if no errors or 'syntax' if quote at the beginning has no matching
... | bigcode/self-oss-instruct-sc2-concepts |
def list_from_file(file):
""" Returns a list of tuples object based on a file of pipe-delimited key/value pairs """
l = []
with open(file) as f:
for line in f:
if not line.startswith('#') and line.strip():
line = line.strip()
(key, val) = line.split('|')[:... | bigcode/self-oss-instruct-sc2-concepts |
def normalize_title(title: str) -> str:
"""Normalize the wikitext article title by handling special characters."""
return title.replace(
'@-@', '-').replace('@,@', ',').replace('@.@', '.').replace(' ', '') | bigcode/self-oss-instruct-sc2-concepts |
import json
def json_dumps(value, **kwargs):
"""
Serializes an object as JSON. Optionally given keyword arguments
are passed to json.dumps(), ensure_ascii however defaults to False.
"""
kwargs.setdefault('ensure_ascii', False)
return json.dumps(value, **kwargs) | bigcode/self-oss-instruct-sc2-concepts |
import hashlib
def gen_gravatar(s, size=200):
"""Return URL for gravatar of md5 of string ``s``"""
h = hashlib.md5(s).hexdigest()
return ('http://www.gravatar.com/avatar/{0}.jpg'
'?d=identicon&f=y&s={1}'.format(h, size)) | bigcode/self-oss-instruct-sc2-concepts |
import re
def ref2equations(filestr):
"""
Replace references to equations. Unless "Equation(s)" already
precedes the reference, the following transformations are done:
(ref{my:label}) -> Equation (my:label)
(ref{my:label1})-(ref{my:label2}) -> Equations (my:label1)-(my:label2)
(ref{my:label1}... | bigcode/self-oss-instruct-sc2-concepts |
def make_columns(image, size):
"""
Processes an image and makes a list containing all one-pixel
wide columns of the image.
Parameters
----------
image : PIL Image File
The image to be processed.
size : (int, int)
The dimensions of the image.
Returns
-------
lis... | bigcode/self-oss-instruct-sc2-concepts |
def fib_table_for(n):
"""
Returns: fibonacci list [a0, a1, ..., an]
Parameter n: the position in the fibonacci sequence
Precondition: n >= 0 is an int
"""
if n == 0:
return [1]
# if for n==1 is unnecessary
fib = [1,1]
for k in range(2,n):
fib.append(fib[-1] ... | bigcode/self-oss-instruct-sc2-concepts |
def gasKgKgDryToMoist(q,qh2o):
"""
Take Kg/Kg dry air to Kg/Kg moist air.
"""
r = q/(1+qh2o)
return r | bigcode/self-oss-instruct-sc2-concepts |
def add_zero_to_age_breakpoints(breakpoints):
"""
append a zero on to a list if there isn't one already present, for the purposes of age stratification
:param breakpoints: list
integers for the age breakpoints requested
:return: list
age breakpoints with the zero value included
"""
... | bigcode/self-oss-instruct-sc2-concepts |
import requests
def has_backoff(response: requests.Response) -> bool:
"""Check if response sets the `backoff` field.
Args:
response: HTTP response.
Returns:
True if the response contains a rate limiting backoff amount.
"""
try:
return "backoff" in response.json()
exce... | bigcode/self-oss-instruct-sc2-concepts |
import re
def urlify(s):
"""
Replacing spaces, and other URL-hostile characters
like question marks, apostrophes, exclamation points, etc.
Example:
>>> s = 'iso met'
iso_met
>>> s = 'isomet?'
'isomet'
"""
# Remove all non-word characters (everything except numbers and letters)... | bigcode/self-oss-instruct-sc2-concepts |
def _prompt_username(prompt="Username: "):
"""Prompt the user for username."""
try:
while True:
username = input(prompt).strip()
if not username:
print("Username cannot be empty, please try again.")
elif "@" in username:
print("Please e... | bigcode/self-oss-instruct-sc2-concepts |
def _course_runs_from_container(container):
"""
Pluck nested course runs out of a ``container`` dictionary,
which is either the ``curriculum`` field of a program, or
a program itself (since either may contain a ``courses`` list).
"""
return [
course_run.get('key')
for course in c... | bigcode/self-oss-instruct-sc2-concepts |
def species_as_str(class_name, id, label, smiles, inchi, inchi_key):
"""
A helper function for generating a user-friendly string representation of a Species or NonPhysicalSpecies object.
"""
str_ = f"<{class_name}("
str_ += f"id={id}"
if label is not None and label:
str_ += f", label={la... | bigcode/self-oss-instruct-sc2-concepts |
def make_zipf(length):
"""Returns a list of counts that follows a Zipf distribution.
Args:
length: the number of counts to be generated
Returns:
A list of the provided length of floating point numbers corresponding
exactly the zipf distribution. For example, for length=5:
... | bigcode/self-oss-instruct-sc2-concepts |
def distance(puissance: int, reserve: str) -> str:
"""Calculation of the shooting distance
Args:
puissance (int): Power of the shot
reserve (str): Reserve of flakes
Returns:
str: Distance reached
"""
return str(puissance * len(reserve)//2 - 1) + 'm' | bigcode/self-oss-instruct-sc2-concepts |
def string_equal(name1, name2, case_sensitive=True, as_prefix=False):
"""
Determine if `name1` and `name2` are equal with taking special rules (`case_sensitive` and `as_prefix`) into account.
If ``as_prefix==True``, strings match even if `name1` is just a prefix of `name2`.
"""
if not case_sens... | bigcode/self-oss-instruct-sc2-concepts |
def cli(ctx, library_id, dataset_id, purged=False):
"""Delete a library dataset in a data library.
Output:
A dictionary containing the dataset id and whether the dataset
has been deleted.
For example::
{'deleted': True,
'id': '60e680a037f41974'}
"""
return... | bigcode/self-oss-instruct-sc2-concepts |
def extract_prefix(keys):
"""
Takes a list of strings and extracts a common prefix delimited by a dot,
for example::
extract_prefix(["entity.bang", "entity.bar", "entity.bat"])
entity.
"""
prefixes = set()
for key in keys:
parts = key.split(".")
if len(parts) > 1:
... | bigcode/self-oss-instruct-sc2-concepts |
def identity(u):
""" returns the field itself """
return u | bigcode/self-oss-instruct-sc2-concepts |
def camel_to_snake_case(s: str) -> str:
"""Convert a camel cased string into snake case.
Args:
s (str): A camel cased string.
Returns:
The snake case converted string.
"""
words = []
s_index = 0
for i in range(len(s)):
if s[i].isupper():
words.append(s[s_ind... | bigcode/self-oss-instruct-sc2-concepts |
def augment_class(string):
"""
Given a [string] representing the contents of a <main-classification> tag
(see USPTO XML Documentation 4.2 or later), realize the semantic meaning
of the string and return a string of form recognized by USPTO:
<main-class>/<sub-class>.<more-sub-class>
"""
mainc... | bigcode/self-oss-instruct-sc2-concepts |
def update_gms_group(
self,
group_pk: str,
group_name: str,
background_image_file: str = "",
) -> bool:
"""Update appliance group in Orchestrator
.. list-table::
:header-rows: 1
* - Swagger Section
- Method
- Endpoint
* - group
- POST
... | bigcode/self-oss-instruct-sc2-concepts |
import re
def extract_ints(raw: str):
"""
Extract integers from a string.
"""
return map(int, re.findall(r'(\d+)', raw)) | bigcode/self-oss-instruct-sc2-concepts |
def wheeled_network_2_robot_action_decoder(action, wheel_max, wheel_min, diff=0.25):
"""
Decode wheeled action from network to linear and angular speed for the robot
:param action: action for wheel spd
:param wheel_max: max wheel spd
:param wheel_min: min wheel spd
:param diff: diff of wheel for... | bigcode/self-oss-instruct-sc2-concepts |
def normalize_weights_dictionary(weights_dict):
"""
Normalizes weights provided as values in passed weight_dict so that
the sum of the weights equals 1.
Arguments
----------
weights_dict: a dictionary containing the columns to be included in the weighted sum
as keys, and the associate... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Iterable
def natural_prefix_len(values: Iterable[int]) -> int:
"""Counts the consecutive integers from 1 to n from the start of values."""
index = 0
for index, value in enumerate(values):
if value - 1 != index:
break
return index | 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.