seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
def qualified_name(object_instance):
"""Return the fully qualified type name of an object.
:param object_instance: Object instance.
:return: Fully qualified name string.
"""
if hasattr(object_instance, '__module__'):
return object_instance.__module__ + '.' + type(object_instance).__na... | bigcode/self-oss-instruct-sc2-concepts |
import hashlib, base64
def get_hashing(string_repr, length=None):
"""Get the hashing of a string."""
hashing = base64.b64encode(hashlib.md5(string_repr.encode('utf-8')).digest()).decode().replace("/", "a")[:-2]
if length is not None:
hashing = hashing[:length]
return hashing | bigcode/self-oss-instruct-sc2-concepts |
def bce_loss(input, target):
"""
Numerically stable version of the binary cross-entropy loss function.
As per https://github.com/pytorch/pytorch/issues/751
See the TensorFlow docs for a derivation of this formula:
https://www.tensorflow.org/api_docs/python/tf/nn/sigmoid_cross_entropy_with_logits
... | bigcode/self-oss-instruct-sc2-concepts |
def best_fit(X, Y):
"""
Calculate linear line of best fit coefficients (y = kx + c)
"""
xbar = sum(X)/len(X)
ybar = sum(Y)/len(Y)
n = len(X) # or len(Y)
numer = sum([xi*yi for xi, yi in zip(X, Y)]) - n * xbar * ybar
denum = sum([xi**2 for xi in X]) - n * xbar**2
if denum != 0:
... | bigcode/self-oss-instruct-sc2-concepts |
import itertools
def augment_graph(graph, reads_dict, add_reads=False, min_mappings=0):
"""Add read nodes to graph according to read mapping file
Args:
graph (networkx Graph): contig assembly graph
reads_dict (str): Dict of read objects
add_reads: add read nodes if True, otherwise add... | bigcode/self-oss-instruct-sc2-concepts |
def select_device(on_gpu: bool) -> str:
"""Selects the appropriate device as requested.
Args:
on_gpu (bool): Selects gpu if True.
Returns:
str:
"gpu" if on_gpu is True otherwise returns "cpu"
"""
if on_gpu:
return "cuda"
return "cpu" | bigcode/self-oss-instruct-sc2-concepts |
def get_value(tixi, xpath):
""" Check first if the the xpath exist and that a value is stored
at this place. Returns this value. It returns a:
- float value if the value can be read as a float
- boolean if the value is 'True'/'False',
- otherwise a string
Source :
* TIXI functions: http... | bigcode/self-oss-instruct-sc2-concepts |
def _find_og_ent(ent, base_ents):
"""Find the original entity referenced by $ref entity."""
id = ent["$ref"]
return next(bent for bent in base_ents if ("$id" in bent) and bent["$id"] == id) | bigcode/self-oss-instruct-sc2-concepts |
import torch
def inner_product_normalized(x, y):
"""
Calculate the inner product between the given normalized vectors,
giving a result between -1 and 1.
"""
return torch.sum(x * y, dim=-1).clamp(min=-1, max=1) | bigcode/self-oss-instruct-sc2-concepts |
def create_queries_subset(eval_size):
"""
Create queries to extract a evaluation and training dataset from a preprocess BigQuery table.
Parameters
----------
eval_size : float
fraction of the data to the evaluation dataset
Returns
-------
eval_query: str
query for the e... | bigcode/self-oss-instruct-sc2-concepts |
def DecodePrivate(curve, bb):
"""
Decode a private key from bytes. Note that the length must match the
expected value (32 bytes for both do255e and do255s) and the value
is verified to be in the proper range (1 to r-1, with r being the
prime order of the do255* group).
"""
sk = curve.SF.Deco... | bigcode/self-oss-instruct-sc2-concepts |
import math
def float_zero(a):
"""Test if a equals zero, a more tolerant version than
:py:func:`float_equal(a, 0)`.
"""
return math.isclose(a, 0, abs_tol=1e-6) | bigcode/self-oss-instruct-sc2-concepts |
def example_distribution_config(ref):
"""Return a basic example distribution config for use in tests."""
return {
"CallerReference": ref,
"Origins": {
"Quantity": 1,
"Items": [
{
"Id": "origin1",
"DomainName": "asdf.... | bigcode/self-oss-instruct-sc2-concepts |
def parse_args(arg_list, keywords):
"""
parses a list of args, for either plain args or keyword args
args matching the keyword take the next argument as a value
missing values or duplicate keywords throw ValueError
returns a list and a dict
>>> args, kwargs = parse_args(arglist, ('keya', 'keyb')... | bigcode/self-oss-instruct-sc2-concepts |
def helper_parse_if(if_string : str):
"""
Parses the if_string manually to test for equality between its
members.
>>> helper_parse_if("this == this")
True
>>> helper_parse_if("2>3")
False
>>> helper_parse_if("40 >= 40")
True
"""
try:
i... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Union
import uuid
def str_to_uuid(in_uuid: Union[str, uuid.UUID]) -> uuid.UUID:
"""
Convert str uuid to uuid.UUID.
Provided as a convenience function if the identifier must be changed in the future.
Args:
in_uuid (str or uuid.UUID): The uuid to be converted.
Returns:
... | bigcode/self-oss-instruct-sc2-concepts |
def remove_duplicates_list(raw_list):
"""Return a list with just unique items.
Only works with a list of items, not with nested lists.
Args:
raw_list (list): List with duplicate items.
Returns:
unique_list (list):: List with only one instance of each item.
"""
... | bigcode/self-oss-instruct-sc2-concepts |
import six
import ast
def dict_or_none(val):
"""Attempt to dictify a value, or None."""
if val is None:
return {}
elif isinstance(val, six.string_types):
return dict(ast.literal_eval(val))
else:
try:
return dict(val)
except ValueError:
return {} | bigcode/self-oss-instruct-sc2-concepts |
def addMiddlePoints(p1, p2, n = 2):
""" Function to calculate the middle point between two points
Args:
p1: (Required) set of coordinates of first point
p2: (Required) set of coordinates of second point
n: (Required) number of divisions
"""
x_1 = p1[0]
y_1 = p1[1]
... | bigcode/self-oss-instruct-sc2-concepts |
def mrr(ground_truth, prediction):
"""
Compute Mean Reciprocal Rank metric. Reciprocal Rank is set 0 if no predicted item is in contained the ground truth.
:param ground_truth: the ground truth set or sequence
:param prediction: the predicted set or sequence
:return: the value of the metric
"""
... | bigcode/self-oss-instruct-sc2-concepts |
def get_cpe_version(cpe: str):
"""Return the version entry of the given CPE"""
split_cpe = cpe.split(":")
if len(split_cpe) > 4:
return split_cpe[4]
return "" | bigcode/self-oss-instruct-sc2-concepts |
import math
def round_to_significant(num, sig_figs):
"""Return (rounded_num, format_precision).
rounded_num is num rounded to sig_figs significant figures.
format_precision is the number of digits to format after the decimal.
"""
sig_digit = int(math.floor(math.log10(abs(num))))
sig_digit -= ... | bigcode/self-oss-instruct-sc2-concepts |
def select_span(cropped_length, original_length, center_point):
"""
Given a span of original_length pixels, choose a starting point for a new span
of cropped_length with center_point as close to the center as possible.
In this example we have an original span of 50 and want to crop that to 40:
... | bigcode/self-oss-instruct-sc2-concepts |
def shift_box(box: list,
x: float,
y: float) -> tuple:
"""
Shift original box by coordinates.
:param box: Original box.
:param x: X shift value.
:param y: Y shift value.
:return: Shifted box
"""
return box[0] - x, box[1] - y, box[2], box[3] | bigcode/self-oss-instruct-sc2-concepts |
import time
def datetime_to_timestamp_in_milliseconds(d):
"""convert a naive datetime object to milliseconds since Epoch.
"""
return int(time.mktime(d.timetuple()) * 1000) | bigcode/self-oss-instruct-sc2-concepts |
def cubic_farthest_fit_inside(p0, p1, p2, p3, tolerance):
"""Returns True if the cubic Bezier p entirely lies within a distance
tolerance of origin, False otherwise. Assumes that p0 and p3 do fit
within tolerance of origin, and just checks the inside of the curve."""
# First check p2 then p1, as p2 ha... | bigcode/self-oss-instruct-sc2-concepts |
def ncread_ts(ncvar, tidx_start=None, tidx_end=None):
"""Read in timeseries [ntime] from a netCDF variable.
:ncvar: (netCDF variable) input variable
:tidx_start: (int) starting index
:tidx_end: (int) ending index
:returns: (numpy array) timeseries data
"""
# read in profile
nsize = ncv... | bigcode/self-oss-instruct-sc2-concepts |
def _sort_dictionary(input: dict, reverse: bool = False) -> dict:
"""Rebuild a dictionary with the same keys and values but where the keys are inserted in sorted order. This can be useful for display purposes."""
sorted_keys = sorted(input, reverse=reverse)
return {k: input[k] for k in sorted_keys} | bigcode/self-oss-instruct-sc2-concepts |
import base64
def decode_authn_string(authn_string):
"""Decodes a hexadecimal authentication string into a MongoDB connnection URI"""
return base64.urlsafe_b64decode(authn_string.encode('utf-8')).decode('utf-8') | bigcode/self-oss-instruct-sc2-concepts |
def get_application_instance_name(application):
"""
Return the name of the application instance.
"""
return "{}-{}".format(application.image.project.name, application.name) | bigcode/self-oss-instruct-sc2-concepts |
def isiterable(target):
"""
Check if target object is iterable
:param target:
:return: true if target is iterable. Otherwise, return false
"""
try:
iter(target)
except:
return False
else:
return True | bigcode/self-oss-instruct-sc2-concepts |
def false_positive(y_true, y_pred):
"""
Function to calculate False Positives
:param y_true: list of true values
:param y_pred: list of predicted values
:return: number of false positives
"""
# initialize
fp = 0
for yt, yp in zip(y_true, y_pred):
if yt == 0 and yp == 1:
... | bigcode/self-oss-instruct-sc2-concepts |
def edits1(word):
"""
Return all strings that are one edit away
from the input word.
"""
alphabet = 'abcdefghijklmnopqrstuvwxyz'
def splits(word):
"""
Return a list of all possible (first, rest) pairs
that the input word is made of.
"""
return [(word[:i]... | bigcode/self-oss-instruct-sc2-concepts |
def CheckEnforcedChanges(input_api, output_api, committing, enforced):
"""Enforces changes based on the provided rules.
|enforced| is a list of 2-tuples, where each entry is a list of file
names relative to the repository root. If all of the files in
the first list have been changed, then all of the files in t... | bigcode/self-oss-instruct-sc2-concepts |
def list_concat(*lists):
"""
joins multiple lists into a single list. Always returns a copy.
"""
# base python: lists are concatenated with "+"
ret = list()
for l in lists:
ret.extend(l)
return ret | bigcode/self-oss-instruct-sc2-concepts |
def _accept_html(accept):
"""
Returns True if the request asked for HTML
"""
return hasattr(accept, 'accept_html') and accept.accept_html() | bigcode/self-oss-instruct-sc2-concepts |
def _calculate_interconnected_value(vij, vik, vil, vkj, vkk, vkl, vlj, vlk, vll):
"""Calculate an interconnected S-parameter value
Note:
The interconnect algorithm is based on equation 6 in the paper below::
Filipsson, Gunnar. "A new general computer algorithm for S-matrix calculation
... | bigcode/self-oss-instruct-sc2-concepts |
import cmath
def rotate_by(z: complex, angle: float) -> complex:
"""Rotate z around the origin by an angle"""
return z * cmath.rect(1,angle) | bigcode/self-oss-instruct-sc2-concepts |
def mapToDict(dictShape, x):
"""
Make a dict over two lists.
Parameters
----------
dictShape : list of any
The labels of the returned dict.
x : list of any
The values of the returned dict.
Returns
-------
dict
Each key in dictShape corresponds to the value i... | bigcode/self-oss-instruct-sc2-concepts |
def versiontuple(v):
"""Convert a string of package version in a tuple for future comparison.
:param v: string version, e.g "2.3.1".
:type v: str
:return: The return tuple, e.g. (2,3,1).
:rtype: tuple
:Example:
>>> versiontuple("2.3.1") > versiontuple("10.1.1")
>>> False
... | bigcode/self-oss-instruct-sc2-concepts |
def check_uniqueness_in_rows(board: list):
"""
Check buildings of unique height in each row.
Return True if buildings in a row have unique length,
False otherwise.
"""
for row in board:
row = row[1:][:-1].replace("*", "")
for num in row:
if row.count(num) > 1:
... | bigcode/self-oss-instruct-sc2-concepts |
import re
def _clean_word_name(word):
"""Cleans the text for a word name, returns None if no match
Prevents us from adding entries that are just prefixes of suffixes, e.g.
-phobia.
"""
p = re.compile('(^[\w]+[\w-]*[\w]+)')
match = p.search(word)
if match is None:
#Make sure we are... | bigcode/self-oss-instruct-sc2-concepts |
def _gen_package(overlay, pkg, distro, preserve_existing, collector):
"""This is just a stub. We just add to the collector"""
collector.append(pkg)
# return new installer, name it.
return True, pkg | bigcode/self-oss-instruct-sc2-concepts |
def expose(command=None, add_client=False):
"""
Decorator to expose a function. If add_client is True, the client
object will be added to the command list as first argument.
"""
def decorator(func):
func._toolkit_rpc = command or func.__name__
func._toolkit_rpc_param = (add_client,)
... | bigcode/self-oss-instruct-sc2-concepts |
def get_title(title_raw):
"""
Extracts title from raw string
"""
return title_raw.replace('\xa0', ' ').split('\n')[0].split('## ')[1] | bigcode/self-oss-instruct-sc2-concepts |
from typing import Optional
def _truncate_doc(
doc: str,
max_len: Optional[int] = None,
) -> str:
"""
Truncate a document to max_len by the rough number of tokens
"""
if not max_len:
return doc
if len(doc.split()) > max_len:
doc = " ".join(doc.split()[:max_len])
ret... | bigcode/self-oss-instruct-sc2-concepts |
def _maybe_get_and_apply(dictionary, key, apply_fn):
"""Returns the result of apply_fn on the value of the key if not None."""
if key not in dictionary:
return None
return apply_fn(dictionary[key]) | bigcode/self-oss-instruct-sc2-concepts |
import torch
from typing import List
import random
def get_indices(targets: torch.Tensor, per_class: bool = True,
count: int = 4, seed: int = 0) -> List[int]:
"""Samples indices to visualize
:param targets: ground truths
:type targets: torch.Tensor
:param per_class: whether count mean... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def NB_log_prob(x, mu, theta, eps=1e-8):
"""
Adapted from https://github.com/YosefLab/scVI/blob/master/scvi/models/log_likelihood.py
"""
log_theta_mu_eps = torch.log(theta + mu + eps)
res = (
theta * (torch.log(theta + eps) - log_theta_mu_eps)
+ x * (torch.log(mu + e... | bigcode/self-oss-instruct-sc2-concepts |
def validar_correo(usuario: str, dominio: str = '@calufa.com') -> bool:
"""Función que valida si un correo electrónico pertenece al dominio
calufa.com
:param usuario: correo electrónico a validar
:type usuario: str
:param dominio: dominio a validar
:type dominio: str
:return: True si perten... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def compute_dihedrals(xyz, particle_index):
""" Compute dihedral angles between sets of four particles.
Parameters:
-----------
xyz: torch.Tensor
input tensor of shape :math:`(\text{frames} , \text{particles} , 3)`
particle_index: torch.LongTensor
particle index tens... | bigcode/self-oss-instruct-sc2-concepts |
def degdiff(angle1, angle2):
"""
The difference of two angles given in degrees. The answer is an angle from
-180 to 180. Positive angles imply angle2 is clockwise from angle1 and -ve
angles imply counter-clockwise.
>>> int(degdiff(40, 30))
-10
>>> int(degdiff(30, 40))
10
>>> int(deg... | bigcode/self-oss-instruct-sc2-concepts |
def mul(a, b):
"""
>>> mul(2,3)
6
>>> mul('a',2)
'aa'
"""
return a*b | bigcode/self-oss-instruct-sc2-concepts |
def quote(string):
""" Surround a string with double quotes """
return f'"{string}"' | bigcode/self-oss-instruct-sc2-concepts |
def filter_top_exchange_addresses(exhanges_df, min_balance = 2000, min_txn_count = 400000):
"""
Filter exchanges with balance > min_balance and transaction count > min_txn_count
Args:
exchanges_df: (pd.Dataframe) Exchanges with atleast columns 'balance'(float), 'txn_count'(float) and 'address' (str... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Optional
from typing import List
def drop_duplicates(df, columns: Optional[List[str]]):
"""
Remove duplicate rows
---
### Parameters
*mandatory :*
- `columns` (*list*): columns to consider to identify duplicates (set to null to use all the columns)
### Example
*... | bigcode/self-oss-instruct-sc2-concepts |
def _entities_from_messages(messages):
"""Return all entities that occur in at least one of the messages."""
return list({e["entity"] for m in messages for e in m.data.get("entities", [])}) | bigcode/self-oss-instruct-sc2-concepts |
def remove_indent(s):
"""Remove indention of paragraph."""
s = "\n".join(i.lstrip() for i in s.splitlines())
return s | bigcode/self-oss-instruct-sc2-concepts |
import socket
def find_free_port() -> int:
"""
Find a free port
"""
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind(('', 0))
_host, port = s.getsockname()
return port | bigcode/self-oss-instruct-sc2-concepts |
def ngrams(sequence, n):
"""Create ngrams from sequence, e.g. ([1,2,3], 2) -> [(1,2), (2,3)]
Note that fewer sequence items than n results in an empty list being returned"""
# credit: http://stackoverflow.com/questions/2380394/simple-implementation-of-n-gram-tf-idf-and-cosine-similarity-in-python
seq... | bigcode/self-oss-instruct-sc2-concepts |
import six
def combine_logged_values(*logged_values_dicts):
"""Combine logged values dicts. Throws if there are any repeated keys."""
combined_dict = dict()
for logged_values in logged_values_dicts:
for k, v in six.iteritems(logged_values):
if k in combined_dict:
raise ValueError('Key "%s" is ... | bigcode/self-oss-instruct-sc2-concepts |
def _section_has_changes(section_data) -> bool:
"""
Looks for a section containing something other than "No changes."
:param section_data: list of lines
:return: boolean
"""
non_empty_lines = [line.strip() for line in section_data[1:] if line.strip()]
if len(non_empty_lines) == 0:
r... | bigcode/self-oss-instruct-sc2-concepts |
import re
def parse_phone(phone):
"""Parses the given phone, or returns `None` if it's invalid."""
if isinstance(phone, int):
return str(phone)
else:
phone = re.sub(r'[+()\s-]', '', str(phone))
if phone.isdigit():
return phone | bigcode/self-oss-instruct-sc2-concepts |
def list_sequence(lst, seq):
"""Return sequences of seq in lst"""
sequences = []
count = 0
len_seq = len(seq)
upper_bound = len(lst)-len_seq+1
for i in range(upper_bound):
if lst[i:i+len_seq] == seq:
count += 1
sequences.append([i,i+len_seq])
return sequences | bigcode/self-oss-instruct-sc2-concepts |
def moffat(x, amplitude=1, center=0., sigma=1, beta=1.):
""" 1 dimensional moffat function:
moffat(amplitude, center, sigma, beta) = amplitude / (((x - center)/sigma)**2 + 1)**beta
"""
return amplitude / (((x - center)/sigma)**2 + 1)**beta | bigcode/self-oss-instruct-sc2-concepts |
def round_filters(filters, mconfig, skip=False):
"""Round number of filters based on depth multiplier."""
multiplier = mconfig.width_coefficient
divisor = mconfig.depth_divisor
min_depth = mconfig.min_depth
if skip or not multiplier:
return filters
filters *= multiplier
min_depth = min_depth or divis... | bigcode/self-oss-instruct-sc2-concepts |
def get_spectral_w(w_pars,energy):
"""
Return spectral weight of an event
Parameters
----------
w_pars: parameters obtained with get_spectral_w_pars() function
energy: energy of the event in GeV
Returns
-------
float w
"""
E0 = w_pars[0]
index = w_pars[1]
index_w =... | bigcode/self-oss-instruct-sc2-concepts |
import hashlib
def sha1_hash_lst(byte_lst):
"""
Compute the SHA-1 hash of a list with byte streams.
"""
sha = hashlib.sha1()
for l in byte_lst:
sha.update(l)
return sha.digest() | bigcode/self-oss-instruct-sc2-concepts |
def bs3_cols(num_entries):
"""Return the appropriate bootstrap framework column width.
Args:
num_entries (int): The number of entries to determine column width for.
Returns:
int: The integer value for column width.
"""
if not isinstance(num_entries, int):
return 12
mapp... | bigcode/self-oss-instruct-sc2-concepts |
def one_of_k_encoding_unk(x, allowable_set):
"""
Maps inputs not in the allowable set to the last element.
Unlike `one_of_k_encoding`, if `x` is not in `allowable_set`, this method
pretends that `x` is the last element of `allowable_set`.
Parameters
----------
x: object
Must be present i... | bigcode/self-oss-instruct-sc2-concepts |
def all_children(model):
"""Return a list of all child modules of the model, and their children, and their children's children, ..."""
children = list(model.children())
for child in model.children():
children.extend(all_children(child))
return children | bigcode/self-oss-instruct-sc2-concepts |
def problem_48_self_powers(series_limit, digits):
""" Problem 48: Find the last digits of series n^n (n = 1 to series limit).
Args:
series_limit (int): The maximum base and power in the series.
digits (int): The number of last digits to take from sum.
"""
result = 0
for number in ra... | bigcode/self-oss-instruct-sc2-concepts |
def mapd(f, d):
"""Map function over dictionary values"""
return {k: f(v) for k, v in d.items()} | bigcode/self-oss-instruct-sc2-concepts |
def lt(y, x):
"""Returns true if the first argument is less than the second; false
otherwise"""
return x < y | bigcode/self-oss-instruct-sc2-concepts |
def find_key(dic, val):
"""Return the keys of dictionary dic with the value val."""
return [k for k, v in dic.iteritems() if v == val] | bigcode/self-oss-instruct-sc2-concepts |
def relu(x):
""" ReLU Activation Function
"""
return x.clamp_min(0.) | bigcode/self-oss-instruct-sc2-concepts |
import re
def translate_dict(cmd_list, label_map, dict_key='label'):
"""Create a translate dictionary of labels
Parameters
----------
cmd_list : list of dict
The Benchpress commands to translate
label_map : dict
Dictionary mapping old to new labels: {'old_label': 'new_label'}.... | bigcode/self-oss-instruct-sc2-concepts |
def choose_max_efficiency(efficiencies):
"""
Given a single or list of DOM efficiencies choose the highest
"""
if type(efficiencies) == list or type(efficiencies) == tuple:
return max(map(float,efficiencies))
else:
return float(efficiencies) | bigcode/self-oss-instruct-sc2-concepts |
import re
import fnmatch
def FilterTestNames(all_tests, gtest_filter):
"""Filter a list of test names based on the given gtest filter.
See https://github.com/google/googletest/blob/main/docs/advanced.md
for gtest_filter specification.
Args:
all_tests: List of test names.
gtest_filter: Filter to appl... | bigcode/self-oss-instruct-sc2-concepts |
def chartx(x, clen=70, c='#'):
"""generate a string of max length clen which is a bargraph of
floating point value 0. <= x <= 1 consisting of character c """
if x > 1.:
x = 1.
slen = int(x*clen)
cstr = [c for s in range(slen)]
return "".join(cstr) | bigcode/self-oss-instruct-sc2-concepts |
def get_pixel_dist(pixel, red, green, blue):
"""
Returns a value that refers to the "color distance" between a pixel and a mean RGB value.
Input:
pixel (Pixel): the pixel with RGB values to be compared
red (int): the average red value of the pixels to be compared
green (int): the av... | bigcode/self-oss-instruct-sc2-concepts |
def process_datafile(filename):
""" process_datafile -> (universities,enrollments,total_number_of_students)
universities: list of University
namesenrollments: corresponding list with enrollments
total_number_of_students: over all universities"""
universities=[]
enrollments=[]
with open(file... | bigcode/self-oss-instruct-sc2-concepts |
def _to_j2kt_native_name(name):
"""Convert a label name used in j2cl to be used in j2kt native"""
if name.endswith("-j2cl"):
name = name[:-5]
return "%s-j2kt-native" % name | bigcode/self-oss-instruct-sc2-concepts |
def validating_property(func, allow_del=False):
"""Factory that makes properties that perform some user-specified
validation when setting values. The returned function must be used as a
descriptor to create a class variable before setting the instance
attribute.
Parameters
----------
func: ... | bigcode/self-oss-instruct-sc2-concepts |
def _lockedSql(db, func, *args):
"""
Ensure write lock on database, otherwise concurrent access can result in
"schema has changed" errors.
"""
if not db.inTransaction():
db.cursor().execute('BEGIN IMMEDIATE')
return func(*args) | bigcode/self-oss-instruct-sc2-concepts |
def eval_agent(env, agent, num_episodes):
"""Evaluates `agent` for `num_episodes`."""
rewards = 0.0
for _ in range(num_episodes):
time_step = env.reset()
episode_reward = 0
while not time_step.last():
agent_output = agent.step(time_step, is_evaluation=True)
time_step = env.step([agent_outp... | bigcode/self-oss-instruct-sc2-concepts |
def _handle(request, handler, *rest): # pragma: no cover
"""invoke the next handler"""
return handler(request, *rest) | bigcode/self-oss-instruct-sc2-concepts |
def full_record(marc21_record, marc21_metadata):
"""Full record as is expected by the UI serializer."""
marc21_record
marc21_record["id"] = "9jkx5-hx115"
marc21_record["pid"] = {
"pk": 58,
"status": "R",
"obj_type": "rec",
"pid_type": "marcid",
}
marc21_record["f... | bigcode/self-oss-instruct-sc2-concepts |
def iter_in(value, seq, cmp):
"""
A function behaving like the "in" Python operator, but which works with a
a comparator function. This function checks whether the given value is
contained in the given iterable.
Args:
value: A value
seq: An iterable
cmp: A 2-arg comparator ... | bigcode/self-oss-instruct-sc2-concepts |
from typing import OrderedDict
def network_to_phenotype(net):
"""Converts a network instance to a phenotype representation,
i.e. a structure dictionary.
Arguments
----------
net: EvoNet instance
The network to convert.
Returns
----------
An ordered dictionary. Phenot... | bigcode/self-oss-instruct-sc2-concepts |
def join_neighs_OR_notrelpos(idxs0_ki, idxs1_ki):
"""Join neighs with OR.
Parameters
----------
idxs0_ki: list or np.ndarray
the indices of the neighs of neighbourhood0
idxs1_ki: list or np.ndarray
the indices of the neighs of neighbourhood1
Returns
-------
neighs: list... | bigcode/self-oss-instruct-sc2-concepts |
def power_digit_sum(base, power):
"""Return the sum of the digtis in base**power"""
return sum([int(x) for x in list(str(base**power))]) | bigcode/self-oss-instruct-sc2-concepts |
def upsert(manager, defaults=None, updates=None, **kwargs):
"""
Performs an update on an object or an insert if the object does not exist.
:type defaults: dict
:param defaults: These values are set when the object is inserted, but are irrelevant
when the object already exists. This field sh... | bigcode/self-oss-instruct-sc2-concepts |
def eval_callbacks(callbacks, record, logbook, estimator):
"""Evaluate list of callbacks on result.
Parameters
----------
callbacks : list of callables
Callbacks to evaluate.
record : logbook record
logbook:
Current stream logbook with the stats required
estimator: :class... | bigcode/self-oss-instruct-sc2-concepts |
def sizeStr(size):
"""Returns formatted string of a byte size
Args:
size (int): size in bytes
Returns:
string: Size with appropriate byte suffix
"""
prefixes = ["B", "KB", "MB", "GB", "TB"]
exponent = 0
while size > 1024:
size /= 1024
exponent += 1
pr... | bigcode/self-oss-instruct-sc2-concepts |
import re
def get_grammatical_function(attributes):
""" Compute the grammatical function of a mention in its sentence.
Args:
attributes (dict(str, object)): Attributes of the mention, must contain
a value for "parse_tree".
Returns:
str: The grammatical function of the mention... | bigcode/self-oss-instruct-sc2-concepts |
def blanks(i):
"""
Return i number of blank spaces
Used in places where reading number of blanks is tough
"""
return ''.join(' ' * i) | bigcode/self-oss-instruct-sc2-concepts |
def simplify_replacements(replacements):
"""
Simplify a list of replacement patterns to make sure there are no needless ones.
For instance in the sequence "Bert->BertNew, BertConfig->BertNewConfig, bert->bert_new", the replacement
"BertConfig->BertNewConfig" is implied by "Bert->BertNew" so not needed.... | bigcode/self-oss-instruct-sc2-concepts |
import re
def _transform_file_name_to_migration_name(name):
"""extracts from filename migration name
:param name: filename
:type name: string
:returns: Transformed filename
:rtype: string
"""
return re.sub(r'\.(up|down)\.sql$', '', name) | bigcode/self-oss-instruct-sc2-concepts |
import uuid
import random
def make_ds_id() -> str:
"""Generate a dataset ID like DataLad would.
This is intended for lightweight tests that don't create
full-fledged datasets.
"""
return str(uuid.UUID(int=random.getrandbits(128))) | 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.