seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
def output_dir(tmpdir):
"""Fixture. Create and return custom temp directory for test."""
return str(tmpdir.mkdir('templates')) | bigcode/self-oss-instruct-sc2-concepts |
def det(a: list) -> int:
"""
Calculates the determinant of a 2x2 Matrix, via the shortcut
(a*d) - (b*c)
:param a: The matrix A.
:return: The determinant.
"""
d= (a[0][0] * a[1][1]) - (a[0][1] * a[1][0])
return d | bigcode/self-oss-instruct-sc2-concepts |
def _intify_keys(d):
"""Make sure all integer strings in a dictionary are converted into integers."""
assert isinstance(d, dict)
out = {}
for k, v in d.items():
if isinstance(k, str) and k.isdigit():
k = int(k)
out[k] = v
return out | bigcode/self-oss-instruct-sc2-concepts |
def get_job_state_str(job):
"""Get string representation of a job."""
if not hasattr(job, 'next_run_time'):
# based on apscheduler sources
return 'pending'
elif job.next_run_time is None:
return 'paused'
else:
return 'active' | bigcode/self-oss-instruct-sc2-concepts |
import torch
def normalize_pointcloud_transform(x):
"""
Compute an affine transformation that normalizes the point cloud x to lie in [-0.5, 0.5]^2
:param x: A point cloud represented as a tensor of shape [N, 3]
:return: An affine transformation represented as a tuple (t, s) where t is a translation an... | bigcode/self-oss-instruct-sc2-concepts |
def is_json(_path) -> bool:
"""Return True if file ends with .json, otherwise False."""
if _path.endswith(".json"):
return True
else:
return False | bigcode/self-oss-instruct-sc2-concepts |
def get_next_tile(thisTile, neighboringTile):
""" Look 1 tile over in the direction specified by the value passed in neighboringTile (north, south, ..., etc.) """
row, column = thisTile # thisTile[i, j]
row_neighboringTile, column_neighboringTile = neighboringTile # neighborTile[k, l], where [k, l] is the dir... | bigcode/self-oss-instruct-sc2-concepts |
def grouped(sequence, key=None, transform=None):
"""
Parse the sequence into groups, according to key:
>>> ret = grouped(range(10), lambda n: n % 3)
>>> ret[0]
[0, 3, 6, 9]
>>> ret[1]
[1, 4, 7]
>>> ret[2]
[2, 5, 8]
"""
groups = {}
if not key:
... | bigcode/self-oss-instruct-sc2-concepts |
def _is_typing_object(type_object):
"""Checks to see if a type belong to the typing module.
Parameters
----------
type_object: type or typing._GenericAlias
The type to check
Returns
-------
bool
True if `type_object` is a member of `typing`.
"""
return type_object._... | bigcode/self-oss-instruct-sc2-concepts |
def merge_dicts(*dictionaries):
"""Return a new dictionary by merging all the keys from given dictionaries"""
merged_dict = dict()
for dictionary in dictionaries:
if not dictionary:
continue
merged_dict.update(dictionary)
return merged_dict | bigcode/self-oss-instruct-sc2-concepts |
import torch
def get_optimizer(opts, model):
"""
Create optimizer and scheduler according to the opts
"""
opt_name = opts.optimizer.name.lower()
if opt_name == "adam":
opt_class = torch.optim.Adam
else:
raise NotImplementedError("Unknown optimizer " + opts.optimizer.name)
o... | bigcode/self-oss-instruct-sc2-concepts |
import math
def define_joint_angle_list(shoulder_pan_joint, shoulder_lift_joint, elbow_joint, wrist_1_joint, wrist_2_joint, wrist_3_joint):
"""
This function takes float values for each joint and returns a list.
:param shoulder_pan_joint: shoulder pan joint angle
:param shoulder_lift_joint: shoulder l... | bigcode/self-oss-instruct-sc2-concepts |
def NestedMultiplication(x, xValues, coeff):
"""Evaluates Newton Polynomial at x in nested form
given the interpolating points and its coefficents"""
n = coeff.size
y = coeff[n-1]
for i in reversed(range(n - 1)):
y = coeff[i] + (x - xValues[i]) * y
return y | bigcode/self-oss-instruct-sc2-concepts |
def default_if_empty(value, arg):
"""
Set default one if the value is empty.
String: None, ''
Integer: None, 0
"""
if not value:
return arg
return value | bigcode/self-oss-instruct-sc2-concepts |
def exitCodeToOutcome(exit_code):
"""convert pytest ExitCode to outcome"""
if exit_code == 0:
return "passed"
elif exit_code == 1:
return "failed"
elif exit_code == 2:
return "interrupted"
elif exit_code == 3:
return "internal_error"
elif exit_code == 4:
r... | bigcode/self-oss-instruct-sc2-concepts |
def update_set(current_value, new_value):
"""Set Updater
Returns:
The value provided in ``new_value``.
"""
return new_value | bigcode/self-oss-instruct-sc2-concepts |
from typing import Any
def is_false(x: Any) -> bool:
"""
Positively false? Evaluates: ``not x and x is not None``.
"""
# beware: "0 is False" evaluates to False -- AVOID "is False"!
# ... but "0 == False" evaluates to True
# https://stackoverflow.com/questions/3647692/
# ... but comparison... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Iterable
import click
def _get_options_flags(options: Iterable[click.Option]):
"""
Given a list of options, produce a list of formatted option flags, like
"--verbose/-v".
"""
return ", ".join(["/".join(opt.opts) for opt in options]) | bigcode/self-oss-instruct-sc2-concepts |
import ast
from typing import Callable
def bin_op(op: ast.operator) -> Callable[[ast.expr, ast.expr], ast.BinOp]:
"""Generate an ast binary operation"""
def _bin_op(left: ast.expr, right: ast.expr) -> ast.BinOp:
return ast.BinOp(left=left, op=op, right=right)
return _bin_op | bigcode/self-oss-instruct-sc2-concepts |
import math
def norme_vecteur(vect):
"""Calcul de la norme d'un vecteur en dimension 2"""
return math.sqrt(math.pow(vect[0],2)+math.pow(vect[1],2)) | bigcode/self-oss-instruct-sc2-concepts |
def gradient_descent(wb, dwdb, optimizer_args):
"""
The simple gradient descent update.
Parameters
----------
wb : dict
A dictionary of the weights/biases for each layer.
dwdb : dict
A dictionary of the gradients with respect to the weights and
biases.
optimizer_args... | bigcode/self-oss-instruct-sc2-concepts |
from datetime import datetime
def now(request):
"""
Add current datetime to template context.
"""
return {'now': datetime.now()} | bigcode/self-oss-instruct-sc2-concepts |
import random
def roll_dice(sides=6) -> int:
"""Simulate Rolling a die.
Uses random.randrange to calculate the roll.
sides defaults to 6 sides.
:param sides: number of sides the die has.
:return: the int value of the roll.
"""
sides += 1 # Include the last number for randrange.
roll... | bigcode/self-oss-instruct-sc2-concepts |
def get_tw_refs(tw_refs_by_verse, book, chapter, verse):
""" Retrurns a list of refs for the given book, chapter, verse, or
empty list if no matches. """
if book not in tw_refs_by_verse:
return []
if chapter not in tw_refs_by_verse[book]:
return []
if verse not in tw_refs_by_vers... | bigcode/self-oss-instruct-sc2-concepts |
def diff_list(first, second):
"""Computes the difference between two input sets,
with the elements in the first set that are not in the second.
"""
second = set(second)
return [item for item in first if item not in second] | bigcode/self-oss-instruct-sc2-concepts |
def pure_list(comma_list):
"""
Transform a list with items that can be comma-separated strings, into
a pure list where the comma-separated strings become multiple items.
"""
pure_items = []
for comma_item in comma_list:
for item in comma_item.split(','):
pure_items.append(ite... | bigcode/self-oss-instruct-sc2-concepts |
def wmo_correction(R_raw):
"""Apply WMO calibration factor to raw rain rate
parameters
----------
R_raw : array like
Rain rate in mm/h
return
------
R_calib : pandas.DataFrame
Corrected rain rate in mm/h
"""
R_calib = (R_raw / 1.16) ** (1 / 0.92)
return R_ca... | bigcode/self-oss-instruct-sc2-concepts |
def decode_pair(left: str, right: str, rep: int, s: str) -> str:
"""Decodes a left/right pair using temporary characters."""
return (
s.replace("", "")
.replace("\ufffe" * rep, left)
.replace("\uffff" * rep, right)
) | bigcode/self-oss-instruct-sc2-concepts |
def calor_vaporizacion(T, Tc, C1, C2, C3, C4):
"""Calor de vaporización de liquidos organicos e inorganicos [J/(mol.K)]"""
Tr = T / Tc
return C1*(1 - Tr)**(C2 + C3*Tr + C4*Tr**2) / 1000 | bigcode/self-oss-instruct-sc2-concepts |
def get_requires_for_build_wheel(config_settings=None):
"""Returns a list of requirements for building, as strings"""
return [] | bigcode/self-oss-instruct-sc2-concepts |
def isproperty(obj):
"""
Is this a property?
>>> class Foo:
... def got(self):
... return 2
... def get(self):
... return 1
... get = property(get)
>>> isproperty(Foo.got)
False
>>> isproperty(Foo.get)
True
"""
return type(obj) == pro... | bigcode/self-oss-instruct-sc2-concepts |
def target_schema() -> str:
"""Get target schema name."""
return "dv" | bigcode/self-oss-instruct-sc2-concepts |
def calculate_change_label(last_close, close):
""" Calculate the label for a given input. The label is the change of the closing price from the last closing price.
:param last_close: closing price of last candle
:param close: closing price of current candle
:return: float
"""
return (close - la... | bigcode/self-oss-instruct-sc2-concepts |
def check_role_requirement(requirement, roles):
"""
Check user roles meets requirement
A requirement looks like:
{
"type": "all|any"
"roles: ["role_A", "role_B"]
}
"""
allow = False
if requirement["type"] == "all":
# require user has all the roles specified
... | bigcode/self-oss-instruct-sc2-concepts |
def has_tag_requirements(tags, required_tags, qtype):
"""
Returns True if `tags` meets the requirements based on
the values of `required_tags` and `qtype`. False otherwise.
"""
has_tag_requirements = False
tag_intersection = set(required_tags).intersection(set(tags))
if qtype == "or":
... | bigcode/self-oss-instruct-sc2-concepts |
def getSelectColumns(columns):
"""
Prepare the columns to be selected by the SELECT statement.
"""
if columns == '*':
return columns
else:
return ', '.join(columns) | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
def annotation_name(attributes: List[dict],
category_name: str,
with_attributes: bool = False) -> str:
"""
Returns the "name" of an annotation, optionally including the attributes.
:param attributes: The attribute dictionary.
:param categ... | bigcode/self-oss-instruct-sc2-concepts |
import unicodedata
def strip_accents_unicode(s: str) -> str:
"""Transform accentuated unicode symbols into their ASCII counterpart."""
try:
# If `s` is ASCII-compatible, then it does not contain any accented
# characters and we can avoid an expensive list comprehension
s.encode('ASCII'... | bigcode/self-oss-instruct-sc2-concepts |
def get_param_value_by_name(parameters, name):
"""
Return the value from the conditions parameters given the param name.
:return: Object
"""
for p in parameters:
if p['name'] == name:
return p['value'] | bigcode/self-oss-instruct-sc2-concepts |
def _get_db_subnet_group_arn(region, current_aws_account_id, db_subnet_group_name):
"""
Return an ARN for the DB subnet group name by concatenating the account name and region.
This is done to avoid another AWS API call since the describe_db_instances boto call does not return the DB subnet
group ARN.
... | bigcode/self-oss-instruct-sc2-concepts |
def count_words(text):
"""Count the words of text passed as argument."""
total_words = 0
for word in text.split("\n"):
if word.strip():
total_words += 1
return total_words | bigcode/self-oss-instruct-sc2-concepts |
import pickle
def load_from_pickle(load_path):
"""Deserialize data from pickle file.
:param load_path: (str) Path of file to load
:return: (Python obj) Deserialised data
"""
with open(load_path, "rb") as file:
data = pickle.load(file)
return data | bigcode/self-oss-instruct-sc2-concepts |
def _get_monthly_values(df):
"""Accepts a Panda's DataFrame with columns ['month', 'average', and 'count'].
Returns a list of dicts ensuring all possible months have values. Months
not listed in DataFrame assigned average and count of 0."""
months = ['April', 'May', 'June', 'July', 'August', 'September',
'Octo... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def get_xG_and_goals(preds, labels):
"""
Calculate expected goals and goals.
Args:
preds (tensor or lists of tensors): predictions. Each tensor is in
in the shape of (n_batch, num_classes). Tensor(s) must be on CPU.
labels (tensor or lists of tensors): correspondin... | bigcode/self-oss-instruct-sc2-concepts |
def _list_comprehensions(obj, item=None, return_tuple=False, make_none=False):
"""
Generates a new list/tuple by list comprehension.
Args:
obj (Union[int, list, tuple]):
If integer, it will be the length of the returned tuple/list.
item: The value to be filled. Default: None.
... | bigcode/self-oss-instruct-sc2-concepts |
def is_basetype(value):
"""
Returns:
(bool): True if value is a base type
"""
return isinstance(value, (int, float, str)) | bigcode/self-oss-instruct-sc2-concepts |
import math
def interleave(left_size, right_size):
""" Finds the number of possible ways to interleave the left and right sub tree
We are interested only in the combinations with fixed ordering, giving the formula:
(left_size + Right_size)! / (left_size! * right_size)
"""
return math.factorial(l... | bigcode/self-oss-instruct-sc2-concepts |
def poly_to_integer(coeffs, order):
"""
Converts polynomial to decimal representation.
Parameters
----------
coeffs : array_like
List of polynomial coefficients in descending order.
order : int
The coefficient's field order.
Returns
-------
int
The decimal r... | bigcode/self-oss-instruct-sc2-concepts |
import ntpath
def get_file_name(file_key):
"""
Returns the name of an email file based on the full s3 file path
:param file_key: the file path
:return: string
"""
return ntpath.basename(file_key) | bigcode/self-oss-instruct-sc2-concepts |
def GenZeroStr(n):
"""Generate a bunch of zeroes.
Arguments:
n -- Number of zeroes
Returns: string
"""
return "".join(["0"] * n) | bigcode/self-oss-instruct-sc2-concepts |
def patch_response(response):
"""
returns Http response in the format of
{
'status code': 200,
'body': body,
'headers': {}
}
"""
return {
'statusCode': response.status_code,
'headers': dict(response.headers),
'body': response.content.decode(),
'isBa... | bigcode/self-oss-instruct-sc2-concepts |
def format_seconds(ticks):
"""
Given ticks (int) returns a string of format hour:minutes:seconds
"""
seconds = ticks / 20
hours = int(seconds / 3600)
seconds = seconds - hours * 3600
minutes = int(seconds / 60)
seconds = seconds - minutes * 60
seconds = round(seconds, 3)
return s... | bigcode/self-oss-instruct-sc2-concepts |
def f(r: int, t: int, Cf: float) -> float:
"""Calcula el monto de depósito anual teniendo en cuenta la tasa de
interés, el tiempo y el monto a retirar.
:param r: tasa de interes anual
:r type: int
:param t: tiempo
:r type: int
:param Cf: monto a retirar
:r type: float
:return: monto... | bigcode/self-oss-instruct-sc2-concepts |
def rescale_layout(Y, scale=1):
"""Return scaled position array to (-scale, scale) in all axes.
The function acts on NumPy arrays which hold position information.
Each position is one row of the array. The dimension of the space
equals the number of columns. Each coordinate in one column.
To resca... | bigcode/self-oss-instruct-sc2-concepts |
import json
def gen_send_data(data:str):
"""This function converts the given data to a JSON
string that can be passed to WhatsApp to send a message.
Args:
data (string): The message to be sent.
"""
message_data = {
"data": [
{
"message": data,
... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def _get_seg_ids(ids, sep_id):
""" Dynamically build the segment IDs for a concatenated pair of sentences
Searches for index SEP_ID in the tensor
args:
ids (torch.LongTensor): batch of token IDs
returns:
seg_ids (torch.LongTensor): batch of segment IDs
example:
... | bigcode/self-oss-instruct-sc2-concepts |
def heun_step(f, x0, t0, t1):
"""
One time step of Heun's method
f : function dx_dt(t0, x0)
x0 : initial condition
t0 : this step time
t1 : next step time
"""
# time step
delta_t = t1 - t0
# slope
s1 = f(t0, x0)
# next step by Euler
x1_euler = x0 + s1 * delta_t
... | bigcode/self-oss-instruct-sc2-concepts |
import requests
def download_insee_excel(url, output_file, verbose=False, check=True):
"""Downloads data from url to an Excel file.
Args:
url (str): An url to request for the excel data.
output_file (str): The output excel filepath.
verbose (boolean): A verbose indicat... | bigcode/self-oss-instruct-sc2-concepts |
def J2kWh(x):
"""J -> kWh"""
return x/1000./3600. | bigcode/self-oss-instruct-sc2-concepts |
def product_sum(record: list) -> list:
"""Return a list that contains the sum of each prodcut sales."""
return [sum(i) for i in record] | bigcode/self-oss-instruct-sc2-concepts |
def calc_check_digit(number):
"""Calculate the check digit. The number passed should not have the
check digit included."""
digits = [int(c) for c in number]
checksum = (
7 * (digits[0] + digits[3] + digits[6]) +
3 * (digits[1] + digits[4] + digits[7]) +
9 * (digits[2] + digits[5]... | bigcode/self-oss-instruct-sc2-concepts |
def sensor_error(raw_sensor_value):
"""Actual sensor error derived from field tests."""
return (raw_sensor_value + 2.5) / 1.32 | bigcode/self-oss-instruct-sc2-concepts |
def is_color(s):
"""Test if parameter is one of Black or Red"""
return s in "BR" | bigcode/self-oss-instruct-sc2-concepts |
from datetime import datetime
import pytz
def utc_offset(time_zone: str) -> int:
"""Convert time zone string to utc offset integer for hour diff."""
now = datetime.now(pytz.timezone(time_zone))
offset = now.utcoffset()
if offset:
return int(offset.total_seconds() / 3600)
return 0 | bigcode/self-oss-instruct-sc2-concepts |
def not_rpython(func):
""" mark a function as not rpython. the translation process will raise an
error if it encounters the function. """
# test is in annotator/test/test_annrpython.py
func._not_rpython_ = True
return func | bigcode/self-oss-instruct-sc2-concepts |
import re
def collapse_spaces(value):
"""
First replace multiple newlines with a single newline,
then collapse multiple non-newline whitespace characters
"""
return re.sub(r'(?![\r\n])\s+', ' ', re.sub(r'[\r\n]+', '\n', value)) | bigcode/self-oss-instruct-sc2-concepts |
def calc_life(trajs, ub=5, lb=-5):
"""
Identifies transition paths and returns lifetimes of states.
Parameters
----------
trajs : list of lists
Set of trajectories.
ub, lb : float
Cutoff value for upper and lower states.
"""
try:
assert ub > lb
e... | bigcode/self-oss-instruct-sc2-concepts |
def nx(request):
"""Number of model states."""
return request.param | bigcode/self-oss-instruct-sc2-concepts |
def get_ns_from_rel(full_ns:str, rel_from:str, comp:str, sep: str = '.') -> str:
"""
Converts a relative import into a full namespace
Args:
full_ns (str): The namespace that import is relative to
rel_from (str): from part of import such as ``..uno.x_interface``
comp (str): Component... | bigcode/self-oss-instruct-sc2-concepts |
def _empty_filter(arg):
"""Place holder for a filter which always returns True.
This is the default ``image_filter`` and ``collection_filter``
argument for ``fetch_neurovault``.
"""
return True | bigcode/self-oss-instruct-sc2-concepts |
def prepare_embedding_config(args):
"""Specify configuration of embeddings.
"""
# Device
args.ent_emb_on_cpu = args.mix_cpu_gpu
# As the number of relations in KGs is relatively small, we put relation
# emebddings on GPUs by default to speed up training.
args.rel_emb_on_cpu = False
prin... | bigcode/self-oss-instruct-sc2-concepts |
def estimatePiSquared(n):
"""
Estimates that value of Pi^2 through a formula involving partial sums.
n is the number of terms to be summed; the larger the more accurate the
estimation of Pi^2 tends to be (but not always).
"""
partialSum = 0 # Initializing
# Implementation of the mathema... | bigcode/self-oss-instruct-sc2-concepts |
def get_volume_fn_from_mask_fn(mask_filename):
"""Extract volume path from mask path"""
return mask_filename.replace("S-label", "") | bigcode/self-oss-instruct-sc2-concepts |
def get_colour(series_options, series_name):
"""Return the graph colour for the series specified."""
if series_options is None:
return None
if series_name in series_options:
if "colour" in series_options[series_name]:
return series_options[series_name]["colour"]
return None | bigcode/self-oss-instruct-sc2-concepts |
def text_to_paras(text, aux=""):
"""
:in: str text
list of str: paras = text_to_paras(text, aux='')
aux = '.' for use in baidutr batch translate
seg text to paras
newline delimiters a para
empty lines ignored
"""
# lines = text.split('\n')
lines = text.splitlines()
lines = ... | bigcode/self-oss-instruct-sc2-concepts |
def pay_excess(principal, minimum, remainder):
"""Pay any excess remaining after making minimum payments."""
excess = remainder
if principal - excess <= 0:
excess = principal
remainder = remainder - principal
else:
remainder = 0
return principal - excess, minimum + excess, ... | bigcode/self-oss-instruct-sc2-concepts |
def sanitize_column_list(input_column_list):
"""Remove empty elements (Nones, '') from input columns list"""
sanitized_column_list = [input for input in input_column_list if input]
return sanitized_column_list | bigcode/self-oss-instruct-sc2-concepts |
from functools import reduce
def compose(*args):
"""Composes all the given function in one."""
return reduce(lambda fun, tion: lambda arg: fun(tion(arg)),
args,
lambda arg: arg) | bigcode/self-oss-instruct-sc2-concepts |
def amp_img(html_code):
"""Convert <img> to <amp-img>"""
return html_code.replace("<img", "<amp-img") | bigcode/self-oss-instruct-sc2-concepts |
def _multiplicative_inverse(num, modulo):
"""
Return the multiplicative inverse of the given number in given modulo or raises a ValueError if no inverse exists.
:param num: Number to be inverted
:type num: int
:param modulo:
:type modulo: int
:raises ValueError if num has no inverse
:ret... | bigcode/self-oss-instruct-sc2-concepts |
def _split_var_path(path):
"""
Split the given OpenMDAO variable path into a system path and a variable name.
Parameters
----------
path : str
The variable path to be split
Returns
-------
sys_path : str
The path to the system containing the given variable.
var_name... | bigcode/self-oss-instruct-sc2-concepts |
import logging
def logger_has_filter(logger, filter_class):
"""
Will `logger` execute a filter of `filter_class`?
:param logging.Logger logger: the logger to examine
:param class filter_class: the filter class to search for
:return: :data:`True` if the `logger` contains a `filter_class`
f... | bigcode/self-oss-instruct-sc2-concepts |
def rescale(X, x_min, x_max):
"""
Rescaled the array of input to the range [x_min, x_max] linearly.
This method is often used in the context of making maps with matplotlib.pyplot.inshow.
The matrix to be accepted must contain arrays in the [0,1] range.
:param X: numpy.ndarray
This is the in... | bigcode/self-oss-instruct-sc2-concepts |
def kelvin2celcius(K):
"""
Convert Kelvin to Celcius
:param K: Temperature in Kelvin
:return: Temperature in Celcius
"""
return K - 273.15 | bigcode/self-oss-instruct-sc2-concepts |
from typing import Collection
from typing import Any
def has_duplicates(itera: Collection[Any]) -> bool:
"""Determine if ``itera`` contains duplicates.
Args:
itera (Collection): a sized iterable
Returns:
bool
"""
seen = set()
for i in itera:
if i in seen:
... | bigcode/self-oss-instruct-sc2-concepts |
def parse_docs(hunter, docs):
"""returns tuple of (name, docs)"""
if not docs:
return hunter.__name__, "<no documentation>"
docs = docs.strip().split('\n')
for i, line in enumerate(docs):
docs[i] = line.strip()
return docs[0], ' '.join(docs[1:]) if len(docs[1:]) else "<no documentat... | bigcode/self-oss-instruct-sc2-concepts |
def gmas(ipe, gmpe, sx, rx, dx, oqimt, stddev_types):
"""
This is a helper function to call get_mean_and_stddevs for the
appropriate object given the IMT.
Args:
ipe: An IPE instance.
gmpe: A GMPE instance.
sx: Sites context.
rx: Rupture context.
dx: Distance cont... | bigcode/self-oss-instruct-sc2-concepts |
def get_default_dims(dims):
"""Get default dims on which to perfom an operation.
Whenever a function from :mod:`xarray_einstats.stats` is called with
``dims=None`` (the default) this function is called to choose the
default dims on which to operate out of the list with all the dims present.
This f... | bigcode/self-oss-instruct-sc2-concepts |
def _invert_indices(arr, range_max):
"""return all indices from range(range_max) that are not in arr as a list"""
inv = []
for j in range(range_max):
if j not in arr:
inv.append(j)
return inv | bigcode/self-oss-instruct-sc2-concepts |
import torch
def lincomb(rp: torch.Tensor, coeff: torch.Tensor) -> torch.Tensor:
"""Returns the normal distributions for w linear combinations of p
portfolios
Args:
rp (torch.Tensor): p-by-n matrix where the (i, j) entry corresponds to
the j-th return of the i-th portfolio
coeff... | bigcode/self-oss-instruct-sc2-concepts |
def rindex_str(text, sub, start=None, end=None):
"""
Finds the highest index of the substring ``sub`` within ``text`` in the range [``start``, ``end``].
Optional arguments ``start`` and ``end`` are interpreted as in slice notation. However,
the index returned is relative to the original string ``te... | bigcode/self-oss-instruct-sc2-concepts |
def int_to_sequence(integer):
"""Return a list of each digit in integer
For example:
1111 -> [1, 1, 1, 1]
451 -> [4, 5, 1]
"""
return [int(n) for n in str(integer)] | bigcode/self-oss-instruct-sc2-concepts |
def moeda(valor=0.0, moeda='R$'):
"""
Funçao que formata um valor ao formato de moeda
:param valor: Valor a ser formatado
:param moeda: Moeda ao qual deve ser formatado
:return: Valor formatado na moeda desejada
"""
return f'{moeda} {valor:.2f}'.replace('.', ',') | bigcode/self-oss-instruct-sc2-concepts |
from typing import Any
def is_fixture(obj: Any) -> bool:
"""
Returns True if and only if the object is a fixture function
(it would be False for a Fixture instance,
but True for the underlying function inside it).
"""
return hasattr(obj, "ward_meta") and obj.ward_meta.is_fixture | bigcode/self-oss-instruct-sc2-concepts |
def normal_round(num: float, ndigits: int = 0) -> float:
"""Rounds a float to the specified number of decimal places.
Args:
num: the value to round
ndigits: the number of digits to round to
"""
if ndigits == 0:
return int(num + 0.5)
else:
digit_value = 10 ** ndigits
... | bigcode/self-oss-instruct-sc2-concepts |
def make_pairs_for_model(model_num=0):
""" Create a list of pairs of model nums; play every model nearby, then
every other model after that, then every fifth, etc.
Returns a list like [[N, N-1], [N, N-2], ... , [N, N-12], ... , [N, N-50]]
"""
if model_num == 0:
return
pairs = []
pai... | bigcode/self-oss-instruct-sc2-concepts |
from functools import reduce
def compose(*functions):
"""
Returns a function which acts as a composition of several `functions`. If
one function is given it is returned if no function is given a
:exc:`TypeError` is raised.
>>> from brownie.functional import compose
>>> compose(lambda x: x + 1... | bigcode/self-oss-instruct-sc2-concepts |
def _formatwarning(message, category, filename, lineno, line=None):
# pylint: disable=unused-argument
"""
Replacement for warnings.formatwarning() that is monkey patched in.
"""
return "{}: {}\n".format(category.__name__, message) | bigcode/self-oss-instruct-sc2-concepts |
import re
def is_text(email_message):
"""Whether a message is text"""
return re.match(r"^text/.*", email_message.get_content_type(), re.IGNORECASE) | bigcode/self-oss-instruct-sc2-concepts |
import json
def parse_sthv2_splits(level):
"""Parse Something-Something dataset V2 into "train", "val" splits.
Args:
level (int): Directory level of data. 1 for the single-level directory,
2 for the two-level directory.
Returns:
list: "train", "val", "test" splits of Somethin... | 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.