seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
def comment_command(mwdb, file_or_hash, comment):
"""
Add comment to object
"""
obj = mwdb.query(file_or_hash)
obj.add_comment(comment)
return dict(message="Added comment {object_id}", object_id=obj.id) | bigcode/self-oss-instruct-sc2-concepts |
from typing import Tuple
def _get_brackets(range_: str) -> Tuple[bool, bool]:
"""Extract the bracket types from the provided range."""
if range_[0] not in {"[", "("}:
raise ValueError(f"Invalid range bracket {range_[0]}" f", should be [ or (.")
if range_[-1] not in {"]", ")"}:
raise ValueE... | bigcode/self-oss-instruct-sc2-concepts |
def conductivity_to_imaginary_permittivity(freq: float,
conductivity: float) -> float:
"""Converts between conductivity and imaginary permittivity
This is a simple and straightforward conversion between the value
of conductivity, in S/m, and the imaginary part of ... | bigcode/self-oss-instruct-sc2-concepts |
import click
import functools
def common_args(func):
"""
Decorator to contain CLI args that will be common to both CLI and GUI: title and engine args.
"""
@click.option("--title", "-t", help="Title to display (if omitted will use file name).")
@click.option(
"--layout",
"-l",
... | bigcode/self-oss-instruct-sc2-concepts |
import itertools
def _split_doctest(code):
"""Split a single doctest string into multiple code block strings"""
def is_code(x):
return x.startswith(">>>") or x.startswith("...")
groups = itertools.groupby(code.splitlines(), is_code)
raw_code_blocks = (lines for is_code, lines in groups if is... | bigcode/self-oss-instruct-sc2-concepts |
def add_cp(results, nodes, probabilities):
"""
Add the F-N cumulative frequency.
See equation (1) from Oughton et al. 2019.
Parameters
----------
results : list of dicts
All iterations generated in the simulation function.
nodes : int
Number of substations for the scenario.... | bigcode/self-oss-instruct-sc2-concepts |
import re
def process_history(post_hist : list) -> dict:
"""Parses history metadata for title, date, student uid, and creation date.
:param post_hist: post history
:returns: dictionary with relevant history data pulled.
"""
hist_result = {}
init_post = post_hist[-1]
hist_result["student u... | bigcode/self-oss-instruct-sc2-concepts |
def bool_2_uint8(bool_arr):
"""
Converts a boolean array to a black-and-white
uint8 array (0 and 255).
PARAMETERS:
im : (M x N) numpy array of bools
boolean array to convert
RETURNS:
(result) : (M x N) numpy array of uint8s
uint8 array of 0s (False) and 255s (... | bigcode/self-oss-instruct-sc2-concepts |
def input_new(s=""):
"""
Wrapper for the data entry function.
:param s: Description of the input value(Default value = "")
"""
return input(s) | bigcode/self-oss-instruct-sc2-concepts |
def step_learning_rate(base_lr, epoch, step_epoch, multiplier=0.1):
"""Sets the learning rate to the base LR decayed by 10 every step epochs"""
lr = base_lr * (multiplier ** (epoch // step_epoch))
return lr | bigcode/self-oss-instruct-sc2-concepts |
def get_multi_async(keys, **ctx_options):
"""Fetches a sequence of keys.
Args:
keys: A sequence of keys.
**ctx_options: Context options.
Returns:
A list of futures.
"""
return [key.get_async(**ctx_options) for key in keys] | bigcode/self-oss-instruct-sc2-concepts |
def get_permission_names(perm_int):
"""Takes an integer representing a set of permissions and returns a list
of corresponding permission names."""
pms = {'God': 16, 'Admin': 8, 'Builder': 2, 'Player': 1, 'DM': 4}
perm_list = []
for key, value in pms.items():
if perm_int & value:
... | bigcode/self-oss-instruct-sc2-concepts |
def edgelist_from_synapse_df(syn_df,
pre_column='pre_pt_root_id',
post_column='post_pt_root_id',
weight_column='size',
agg='count'):
"""Compute a list of pre to post edges from a synapse-query-style d... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Dict
def remove_margin_lines(obj: Dict) -> bool:
"""Remove the lines that are inside the margins
Useful for 106 D and E/F - mostly for split pages
:param obj: PDF character
:return: True or False
"""
if obj["width"] < 10:
return False
if 70 < obj["x0"] < 75:
... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Dict
from typing import Optional
from typing import Tuple
from typing import Any
def get_best_attribute(item: Dict[str, Optional[str]], keys: Tuple, fallback: Any = None) -> Optional[str]:
"""
Due to the weird nature of data exported from Last.fm, we need to check multiple keys to find the ... | bigcode/self-oss-instruct-sc2-concepts |
def calc_accu(a, b):
"""
Returns the accuracy (in %) between arrays <a> and <b>. The two arrays must
be column/row vectors.
"""
a = a.flatten()
b = b.flatten()
accu = 100.0 * (a == b).sum() / len(a)
return accu | bigcode/self-oss-instruct-sc2-concepts |
import hashlib
def message_to_hash(message_string):
"""Generate a hash deterministically from an arbitrary string."""
message = hashlib.sha256()
message.update(message_string.encode()) # Encode as UTF-8.
return int(message.digest().hex(), 16) >> 5 | bigcode/self-oss-instruct-sc2-concepts |
def frequencies(colorings):
"""
Procedure for computing the frequency of each colour in a given coloring.
:param colorings: The given coloring.
:return: An array of colour frequencies.
"""
maxvalue = -1
frequency = [0] * (len(colorings))
for i in colorings:
maxvalue = max(maxvalu... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def pairwise_l2_sq(
x1,
x2,
):
"""Compute pairwise squared Euclidean distances."""
return torch.cdist(x1, x2).pow(2) | bigcode/self-oss-instruct-sc2-concepts |
def update_function(func, invars, energized):
"""Return the output of the a Function's update method."""
return func.update(*invars, energized=energized) | bigcode/self-oss-instruct-sc2-concepts |
import torch
def boxes3d_to_bev_torch_lidar(boxes3d):
"""
:param boxes3d: (N, 7) [x, y, z, w, l, h, ry] in LiDAR coords
:return:
boxes_bev: (N, 5) [x1, y1, x2, y2, ry]
"""
boxes_bev = boxes3d.new(torch.Size((boxes3d.shape[0], 5)))
cu, cv = boxes3d[:, 0], boxes3d[:, 1]
half_l, half... | bigcode/self-oss-instruct-sc2-concepts |
def unpack(value):
"""Return a three tuple of data, code, and headers"""
if not isinstance(value, tuple):
return value, 200, {}
value_len = len(value)
if value_len == 2:
return value[0], value[1], {}
elif value_len == 3:
return value[0], value[1], value[2]
else:
r... | bigcode/self-oss-instruct-sc2-concepts |
def is_condition_key_match(document_key, some_str):
""" Given a documented condition key and one from a policy, determine if they match
Examples:
- s3:prefix and s3:prefix obviously match
- s3:ExistingObjectTag/<key> and s3:ExistingObjectTag/backup match
"""
# Normalize both
document_key = ... | bigcode/self-oss-instruct-sc2-concepts |
def read_best_fit(path):
"""
Return a 2-tuple consisting of the name and the best-fit objective function value,
given the path to sorted_params.txt
"""
with open(path) as f:
f.readline() # header
line = f.readline() # first pset (best)
parts = line.split()
n... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def ssm_vr_loss(energy_model, x, n_slices=1):
"""SSM-VR (variance reduction) loss from
Sliced Score Matching: A Scalable Approach to Density and Score Estimation
The loss is computed as
s = -dE(x)/dx
loss = vT*(ds/dx)*v + 1/2*||s||^2
Args:
x (torch.Tensor): input samples... | bigcode/self-oss-instruct-sc2-concepts |
def get_z_sample(xbar, mu, SE):
"""
Return the z-score of a sample, from a sampling distribution.
Parameters
----------
* xbar: mean of the current sample.
* mu: mean of the population from where the sample is drawn.
* SE: standard error of the sampling distribution (population SD / root(po... | bigcode/self-oss-instruct-sc2-concepts |
def round_filters(channels, global_params, skip=False):
"""
Calculate and round number of channels based on depth multiplier.
Args:
channels (int): base number of channels.
global_params (EasyDict): global args, see: class: `EfficientNet`.
skip (bool): if True, do nothing and return... | bigcode/self-oss-instruct-sc2-concepts |
def ConstructNameFilterExpression(requested_name_regexes):
"""Construct a name filter expression.
Args:
requested_name_regexes: A list of name regular expressions that can
be used to filter the resources by name on the server side.
Returns:
A string expression suitable for the requested names, or ... | bigcode/self-oss-instruct-sc2-concepts |
def for_text_write(fpath):
""" For Python3 we often should open as a text file (like for json, csv.reader, etc) """
return open(fpath, "w") | bigcode/self-oss-instruct-sc2-concepts |
def split_heads(x, num_heads):
""" Split heads
:param x: A tensor with shape [batch, length, channels]
:param num_heads: An integer
:returns: A tensor with shape [batch, heads, length, channels / heads]
"""
assert x.shape[-1] % num_heads == 0, str(x.shape)
return x.reshape(x.shape[:-1] + (... | bigcode/self-oss-instruct-sc2-concepts |
def right_child(node, new_node=None):
""" Set right child: right_child(node, new_right_child); Get right node: right_child(node). """
if new_node is not None:
node[2] = new_node
return node[2] | bigcode/self-oss-instruct-sc2-concepts |
def square(number: int):
"""Calculate square of a given number."""
return number ** 2 | bigcode/self-oss-instruct-sc2-concepts |
def calculatePostIapAggregateInterference(q_p, num_sas, iap_interfs):
"""Computes post IAP allowed aggregate interference.
Routine to calculate aggregate interference from all the CBSDs managed by the
SAS at protected entity.
Args:
q_p: Pre IAP threshold value for protection type (mW)
num_sas: Number ... | bigcode/self-oss-instruct-sc2-concepts |
def get_plain_texts(input_dict):
"""
Widget transforms Annotated Document Corpus to string.
:param adc: Annotated Document Corpus.
:param feature_annotation: Select a feature annotation.
:param delimiter: Delimiter for token concatenation.
:param include_doc_id: Include Document Identifier.
... | bigcode/self-oss-instruct-sc2-concepts |
import string
def is_starting(token, alphabet=string.ascii_lowercase):
"""
Determines if the token starts a new word
"""
return len(token) > 1 and token.startswith(' ') and token[1].lower() in alphabet | bigcode/self-oss-instruct-sc2-concepts |
def create_term_query(key, values, query_type):
"""Return an all or any term query for es"""
if query_type == "or":
return [{"terms": {key: values}}]
else:
return [{"term": {key: value}} for value in values] | bigcode/self-oss-instruct-sc2-concepts |
def get_version(nb):
"""Get the version of a notebook.
Parameters
----------
nb : dict
NotebookNode or dict containing notebook data.
Returns
-------
Tuple containing major (int) and minor (int) version numbers
"""
major = nb.get('nbformat', 1)
minor = nb.get('nbformat_... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Counter
def check_duplicate_fields(field_names):
"""
Check that there are no duplicate in the `field_names` list of field name
strings, ignoring case. Return a list of unique duplicated field names.
"""
counted = Counter(c.lower() for c in field_names)
return [field for fiel... | bigcode/self-oss-instruct-sc2-concepts |
def get_access_token(request):
"""
Find access token in request in next order:
- acc_token query param
- X-Access-Token header
- access.token body value (for POST, PUT, PATCH and application/json content type)
Raise ValueError if no token provided
"""
token = request.params.get(... | bigcode/self-oss-instruct-sc2-concepts |
def tree_to_s2t(tree_str):
"""
linearized the phrase tree to token sequences.
Args:
tree_str:(TOP (NP (NNP EDUCATION) (NNPS ADS) (: :)))
Return:
s2t format:
words: EDUCATION ADS :
tokens: NP NNP NNPS : /NP
"""
stack, tokens, words = [], [], []
for tok... | bigcode/self-oss-instruct-sc2-concepts |
def get_client_class_name_from_module(module):
"""Being a module that is an Autorest generation, get the client name."""
# Using the fact that Client is always the first element in __all__
# I externalize that code in a class in case we need to be smarter later
return module.__all__[0] | bigcode/self-oss-instruct-sc2-concepts |
def build_train_and_test_features(
df_columns,
features_to_process,
predict_feature,
ignore_features):
"""build_train_and_test_features
Order matters when slicing up datasets using scalers...
if not, then something that is an int/bool can get into a float
column and tha... | bigcode/self-oss-instruct-sc2-concepts |
import time
def logarithmic_progress(iterable, verbose=True):
"""A funny type of progress bar I use a lot.
This does two things:
* Return a true/false flag if the iteration is a power of two, or
the last iteration. Usually I want to save results at this point, or
print an update to screen.
* ... | bigcode/self-oss-instruct-sc2-concepts |
def nullish_coalescing(value, default):
"""
nullish coalescing utility call
Provides a return of the provided value unless the value is a ``None``,
which instead the provided default value is returned instead.
Args:
value: the value
default: the default value
Returns:
... | bigcode/self-oss-instruct-sc2-concepts |
def convert_ft_to_psi(fthead, sg = None, W = None):
"""
Conversion formula for calculating head in psi if head in ft is known, as well
as either the specific gravity or Specific weight (ex. W for water = 62.32 lb/ft^3 @ 68 deg C)
ex:
>>> x = tdh.convert_ft_to_psi(15.0, sg = 1.0)
or
>>> ... | bigcode/self-oss-instruct-sc2-concepts |
import math
def nextpow2(n):
"""
Return the smallest power of two greater than or equal to n.
"""
return int(math.ceil(math.log(n) / math.log(2))) | bigcode/self-oss-instruct-sc2-concepts |
def extract_http_req_body(contents):
"""
Splits the HTTP request by new lines and gets the
last line which is the HTTP payload body
"""
return contents.split(b"\n")[-1] | bigcode/self-oss-instruct-sc2-concepts |
def serialize_value(value):
"""
Serialize a value in an DeepImageJ XML compatible manner.
:param value:
:return:
"""
if isinstance(value, bool):
return str(value).lower()
else:
return str(value) | bigcode/self-oss-instruct-sc2-concepts |
from typing import Iterable
from typing import Counter
def number_of_clusters(_, labels: Iterable) -> float:
"""Number of total clusters.
Args:
_: Dummy, pass anything or None
labels (Iterable): Vector of sample labels.
Returns (int):
Number of clusters.
"""
ret... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Union
def device_id_from_mac_address(mac_address: Union[str, bytearray]) -> str:
"""
Convert device's physical address to a device ID
:param mac_address: MAC-address in dash/colon/spaced/concatenated format
:type mac_address: str, bytes, bytearray
:return: Device ID
:rtype: ... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def hinge_loss_rec(positive: torch.Tensor, negative: torch.Tensor, margin=1) -> torch.Tensor:
"""Hinge loss for recommendations"""
dist = positive - negative
return torch.sum(torch.maximum(margin - dist, torch.Tensor([0]))) | bigcode/self-oss-instruct-sc2-concepts |
def set_recomputation_options(opts,
allow_recompute=True,
allow_stateful_recompute=None): # pylint: disable=unused-argument
"""Set re-computation options.
Args:
allow_recompute: Whether or not to re-compute instructions during training.
If this... | bigcode/self-oss-instruct-sc2-concepts |
def passthrough_scorer(estimator, *args, **kwargs):
"""Function that wraps estimator.score"""
return estimator.score(*args, **kwargs) | bigcode/self-oss-instruct-sc2-concepts |
def convert_to_bundleClass_format(samcc_selection):
"""converts samcc selection from this library to original format used by bundleClass
input: samcc-ready selection, list of helices, each helix a list of format [ chain_id(string), start_residue(int), stop_residue(int) ]
output: BundleClass-ready selection, list of ... | bigcode/self-oss-instruct-sc2-concepts |
def create_ca_file(anchor_list, filename):
"""
Concatenate all the certificates (PEM format for the export) in
'anchor_list' and write the result to file 'filename'. On success
'filename' is returned, None otherwise.
If you are used to OpenSSL tools, this function builds a CAfile
that can be us... | bigcode/self-oss-instruct-sc2-concepts |
def uppercase_range(code1, code2):
"""
If the range of characters from code1 to code2-1 includes any
lower case letters, return the corresponding upper case range.
"""
code3 = max(code1, ord('a'))
code4 = min(code2, ord('z') + 1)
if code3 < code4:
d = ord('A') - ord('a')
retu... | bigcode/self-oss-instruct-sc2-concepts |
def int_to_bin_string(x, bits_for_element):
"""
Convert an integer to a binary string and put initial padding
to make it long bits_for_element
x: integer
bit_for_element: bit length of machine words
Returns:
string
"""
encoded_text = "{0:b}".format(x)
len_bin = len(... | bigcode/self-oss-instruct-sc2-concepts |
def get_record_meta(record_list):
"""Get meta data of FASTA record.
"""
acc_code = record_list[0]
organism = record_list[1]
EC_code = record_list[2].replace("__", " ")
species = record_list[3].replace("__", " ")
note = record_list[4]
return acc_code, organism, EC_code, species, note | bigcode/self-oss-instruct-sc2-concepts |
def str_to_list(string, key_name=""):
"""Evaluates a string as a list. Checks if border characters are
'[' and ']', to avoid bad typing.
key_name : string (optional)
Name of the parameter. Useful for error message.
"""
if string[0] == '[' and string[-1] == ']':
return list(eval(stri... | bigcode/self-oss-instruct-sc2-concepts |
def clip_grad_by_norm_(grad, max_norm):
"""
in-place gradient clipping.
:param grad: list of gradients
:param max_norm: maximum norm allowable
:return: average norm
"""
total_norm = 0
counter = 0
for g in grad:
param_norm = g.data.norm(2)
total_norm += param_norm.ite... | bigcode/self-oss-instruct-sc2-concepts |
import re
def idsub(tag):
"""In aSc, "id" fields may only contain ASCII alphanumeric characters,
'-' and '_'. Substitute anything else by '_'.
"""
return re.sub('[^-_A-Za-z0-9]', '_', tag) | bigcode/self-oss-instruct-sc2-concepts |
def reverse_geometric_key(gkey):
"""Reverse a geometric key string into xyz coordinates.
Parameters
----------
gkey : str
A geometric key.
Returns
-------
list of float
A list of XYZ coordinates.
Examples
--------
>>> from math import pi
>>> xyz = [pi, pi, ... | bigcode/self-oss-instruct-sc2-concepts |
import json
def to_json_string(obj):
"""Convert object as a JSON string."""
return json.JSONEncoder(indent=2).encode(obj) | bigcode/self-oss-instruct-sc2-concepts |
import json
def make_base_config(config_file, kwargs, par):
"""
Make a config file for `fps_single.py`.
Args:
config_file (str): path to general config file
kwargs (dict): extra dictionary items to put in it
par (bool): whether we're going to be using
this to make finge... | bigcode/self-oss-instruct-sc2-concepts |
def sim_file_to_run(file):
"""Extracts run number from a simulation file path
Parameters
----------
file : str
Simulation file path.
Returns
-------
run : int
Run number for simulation file
Examples
--------
>>> file = '/data/ana/CosmicRay/IceTop_level3/sim/IC7... | bigcode/self-oss-instruct-sc2-concepts |
def calculate_number_of_pay_periods(period_payment, frequency, max_tax):
"""
Calculate the number of pay periods that it will take to pay off a tax burden
Param: period_payment: (float)
How much is being taken off per pay
Param: frequency: (int)
How many payments per year
Param: ma... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Tuple
from typing import List
import re
def parse_mate_info_from_id(
seq_id: str
) -> Tuple[int, str]:
"""Extracts mate information from sequence identifier.
Args:
seq_id: Sequence identifier.
Returns:
An integer representing the mate information and the sequence
... | bigcode/self-oss-instruct-sc2-concepts |
def coord2act(board, coords):
"""Convert coordinate to action."""
return coords[0] * board.shape[-1] + coords[1] | bigcode/self-oss-instruct-sc2-concepts |
from functools import reduce
def multiply_ints_list(tokens):
"""
parse action to multiply integers in a VBA expression with operator '*'
"""
# extract argument from the tokens:
# expected to be a tuple containing a list of integers such as [a,'&',b,'&',c,...]
integers = tokens[0][::2]
retu... | bigcode/self-oss-instruct-sc2-concepts |
def stringify(grid: dict, n: int) -> str:
"""Stringify with (0, 0) in the lower-left corner."""
rows = []
for y in reversed(range(n)):
row = []
for x in range(n):
value = grid.get((x, y), "-")
row.append(value)
rows.append(row)
return "\n".join("".join(r... | bigcode/self-oss-instruct-sc2-concepts |
def get_winner(game):
"""
Returns the winner player if any, or None otherwise.
"""
return game["winner"] | bigcode/self-oss-instruct-sc2-concepts |
def results_config(current_page):
"""Returns a config for each source's search results page."""
return {
"coindesk": {
"page_url": "https://www.coindesk.com/page/" + str(current_page) + "/?s=Bitcoin",
"item_XPATH": '//div[@class="post-info"]', # XPATH for the search result item ... | bigcode/self-oss-instruct-sc2-concepts |
def find_google_fileid_tree(service, fileId):
"""Find the folder tree of a file
Arguments:
service: in order to use any of this library, the user needs to first build the service class using google ServiceAccountCredentials. see https://pypi.org/project/google-api-v3-helper/ or https://github.com/sbi-rviot/goo... | bigcode/self-oss-instruct-sc2-concepts |
def curve(t, acc_t, fast_t, dec_t, slow_t, fast, slow):
"""Returns a speed value between 0 and fast for a given t
t is the time (a float in seconds), from zero at which point acceleration starts
typically t would be incrementing in real time as the door is opening/closing
acc_t is the accelerat... | bigcode/self-oss-instruct-sc2-concepts |
def word_preprocessing(word, ignore_non_alnumspc=True, ignore_space=True, ignore_numeric=True, ignore_case=True):
"""
Function for word preprocessing
|
| Argument
| | word: a string to be processed
|
| Parameter
| | ignore_non_alnumspc: whether to remove all non alpha/numeric/space characters
| | ignore_space... | bigcode/self-oss-instruct-sc2-concepts |
def floyd_warshall(weight):
"""All pairs shortest paths by Floyd-Warshall
:param weight: edge weight matrix
:modifies: weight matrix to contain distances in graph
:returns: True if there are negative cycles
:complexity: :math:`O(|V|^3)`
"""
V = range(len(weight))
for k in V:
for... | bigcode/self-oss-instruct-sc2-concepts |
def test_api_key(client, BinanceAPIException):
"""Checks to see if API keys supplied returns errors
Args:
client (class): binance client class
BinanceAPIException (clas): binance exeptions class
Returns:
bool | msg: true/false depending on success, and message
"""
try:
... | bigcode/self-oss-instruct-sc2-concepts |
def find_primary_and_secondaries(users):
"""Given a list of users with the same username, find the user who should be the primary
user into which the other users will be merged. Return a tuple (primary_user, list_of_secondary_users)
"""
actives = [each for each in users if each.is_active]
# If there... | bigcode/self-oss-instruct-sc2-concepts |
def _extract_open_mpi(version_buffer_str):
"""
Parses the typical OpenMPI library version message, eg:
Open MPI v4.0.1, package: Open MPI Distribution, ident: 4.0.1, repo rev: v4.0.1, Mar 26, 2019
"""
return version_buffer_str.split("v", 1)[1].split(",", 1)[0] | bigcode/self-oss-instruct-sc2-concepts |
import torch
def make_valid_from_train(dataset, cut=0.9):
"""
Split training data to get validation set
:param dataset: Training dataset
:param cut: Percentage of dataset to be kept for training purpose
"""
tr_ds, val_ds = [], []
for task_ds in dataset:
x_t, y_t = task_ds
# shuffle before spli... | bigcode/self-oss-instruct-sc2-concepts |
def find_history_active_at(obj, time):
"""Assumes obj has a corresponding history model (e.g. obj could
be Person with a corresponding PersonHistory model), then either
returns the object itself if it was active at time, or the history
object active at time, or None if time predates the object and its
... | bigcode/self-oss-instruct-sc2-concepts |
def make_tile_type_name(cells):
"""
Generate the tile type name from cell types
"""
cell_types = sorted([c.type for c in cells])
cell_counts = {t: 0 for t in cell_types}
for cell in cells:
cell_counts[cell.type] += 1
parts = []
for t, c in cell_counts.items():
if c == 1... | bigcode/self-oss-instruct-sc2-concepts |
def put_number(line_number, line):
"""
Return a string. The `line_number` is formatted as 3 digits
number with a dot and a space preceding the `line`. The empty
space before line number will be replaced by '0's.
Example:
>>> put_number(1, "Hello World!")
'001. Hello World'
"""
retur... | bigcode/self-oss-instruct-sc2-concepts |
def flip_bit(bit: str) -> str:
"""returns the input bit flipped"""
assert bit == "0" or bit =="1"
return "0" if bit =="1" else "1" | bigcode/self-oss-instruct-sc2-concepts |
import json
def read_json(file_path: str) -> dict:
"""Reads a json file and returns the dict
"""
with open(file_path) as f:
return json.load(f) | bigcode/self-oss-instruct-sc2-concepts |
def username(user: dict):
"""
Returns the user's first and last name if they've seen set, else
returns the user's email
"""
if user["first_name"]:
return user["first_name"] + " " + user["last_name"]
return user["email"] | bigcode/self-oss-instruct-sc2-concepts |
import torch
def get_masks(slen, lengths, causal):
"""
Generate hidden states mask, and optionally an attention mask.
"""
assert lengths.max().item() <= slen
bs = lengths.size(0)
alen = torch.arange(slen, dtype=torch.long, device=lengths.device)
mask = alen < lengths[:, None]
# attent... | bigcode/self-oss-instruct-sc2-concepts |
import functools
def middleware(f):
"""Function decorator for making WSGI middlewares."""
return functools.update_wrapper(
lambda app: lambda wsgi_env, start_resp: f(app, wsgi_env, start_resp),
f) | bigcode/self-oss-instruct-sc2-concepts |
def conflateable(seg1, seg2, segment_pairs):
"""
Return True iff seg1 and seg2 are exactly one of the segment pairs
in segment_pairs (ignoring ordering of either).
seg1 and seg2 will never be identical in the input.
Parameters
----------
seg1, seg2: Segment
Two segments on which m... | bigcode/self-oss-instruct-sc2-concepts |
def norm3d(x, y, z):
"""Calculate norm of vector [x, y, z]."""
return (x * x + y * y + z * z) ** 0.5 | bigcode/self-oss-instruct-sc2-concepts |
def with_metaclass(metaclass, *bases):
"""
Construct a base class with metaclass compatible with python2 and python3.
Usage:
```
class(with_metaclass(metaclass, base1, base2...)):
....
```
"""
class InterposedMetaClass(metaclass):
def __new__(mcls, name, new_bases, attr... | bigcode/self-oss-instruct-sc2-concepts |
import pickle
def _read_results(pickle_file_name):
"""Reads results from Pickle file.
:param pickle_file_name: Path to input file.
:return: monte_carlo_dict: Dictionary in format created by
`monte_carlo.run_monte_carlo_test`.
"""
pickle_file_handle = open(pickle_file_name, 'rb')
mont... | bigcode/self-oss-instruct-sc2-concepts |
def _no_stop_codon(aa_seq):
""" Returns True if a sequence does not contain a stop codon,
otherwise returns False
"""
if '*' not in aa_seq:
return True
else:
return False | bigcode/self-oss-instruct-sc2-concepts |
def get_categories_used_ordered(ordered_categories, used_categories) -> list:
"""Returns an ordered list of categories that appear in used_categories.
* ordered_categories: manually defined ordered list
* used_categories: a list or set of categories actually used in the data frame
"""
used_set = set... | bigcode/self-oss-instruct-sc2-concepts |
def RK4n(diffeq, y0, t, h): # non-vectorized with lists
""" RK4 method for n ODEs:
Given y0 at t, returns y1 at t+h """
n, y1 = len(y0), [0.0]*len(y0)
k1 = diffeq(y0, t) # dy/dt at t
for i in range(n): # loop thru n ODEs
y1[i] = y0[i] + 0.... | bigcode/self-oss-instruct-sc2-concepts |
import re
def get_new_version(version):
"""
Get new version by bumping only the last digit group in the string.
Args:
version (): Version: like 2.7.epic14859_9
Returns: New version: like 2.7.epic14859_10
Original credit: https://stackoverflow.com/questions/23820883/incrementing-the-last-d... | bigcode/self-oss-instruct-sc2-concepts |
def motif_factors(m, M):
"""
Generates the set of non redundant motif sizes to be checked for division
rule.
Parameters
----------
m : <int> minimum motif size
M : <int> maximum motif size
Returns
-------
factors : <list> sorted(descending) list of non-redundant motifs.
""... | bigcode/self-oss-instruct-sc2-concepts |
def parse_id(arg):
"""
Parses an ID from a discord @
:param arg: @ or ID passed
:return: ID
"""
if "<" in arg:
for i, c in enumerate(arg):
if c.isdigit():
return int(arg[i:-1])
# Using ID
else:
return int(arg) | bigcode/self-oss-instruct-sc2-concepts |
def dict_merge(base, override):
"""Recursively merge two dictionaries
Parameters
----------
base : dict
Base dictionary for merge
override : dict
dictionary to override values from base with
Returns
-------
dict
Merged dictionary of base and overrides
"""
... | bigcode/self-oss-instruct-sc2-concepts |
def get_eids_from_op2_vector(vector):
"""Obtain the element ids for a given op2 vector
Parameters
----------
vector : op2 vector
An op2 vector obtained, for example, doing::
vector = op2.cquad4_force[1]
vector = op2.cquad8_stress[1]
vector = op2.ctriar_force... | 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.