seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
from functools import reduce
def fuseDotAl(dotAl):
"""Given input [ (2, "3"), (4, "5"), (2,"6") ],
d will be a dict { 2: {"3","6"}, 4: {"5"} }
and return value { 2: {"3 \n 6"}, 4: {"5"} }
"""
d = dict([(x, {y for (z,y) in dotAl if z==x}) for (x,w) in dotAl]) # sets of y for the same x
... | bigcode/self-oss-instruct-sc2-concepts |
def outline_az_sub(sub_index, sub, tenant):
"""Return a summary of an Azure subscription for logging purpose.
Arguments:
sub_index (int): Subscription index.
sub (Subscription): Azure subscription model object.
tenant (str): Azure Tenant ID.
Returns:
str: Return a string th... | bigcode/self-oss-instruct-sc2-concepts |
def lowercase_set(sequence):
""" Create a set from sequence, with all entries converted to lower case.
"""
return set((x.lower() for x in sequence)) | bigcode/self-oss-instruct-sc2-concepts |
import requests
def _get_token(ZC, username, password):
"""Gets the client's token using a username and password."""
url = '{}/oauth/token/'.format(ZC.HOME)
data = {'username': username, 'password': password, 'noexpire': True}
r = requests.post(url, json=data)
if r.status_code != 200:
r... | bigcode/self-oss-instruct-sc2-concepts |
def error_general_details(traceback_str: str) -> str:
"""
Error message DM'ed to the user after a general error with the traceback associated
with it.
:param traceback_str: The formatted traceback.
:returns: the formatted message.
"""
return f"Here is some more info on the error I encounte... | bigcode/self-oss-instruct-sc2-concepts |
import csv
def get_genes(path):
"""Returns a list of genes from common results tables. Assumes the genes are in the first column."""
with open(path) as full_gene_list:
full_gene_list = csv.reader(full_gene_list)
gene_list = [row[0] for row in full_gene_list]
del gene_list[0] # Remove ... | bigcode/self-oss-instruct-sc2-concepts |
def pretty_bytes(b):
"""
Format a value of bytes to something sensible.
"""
if b >= 10 * (1024**3): # 10 GiB
return '%0.0f GiB' % (float(b) / (1024**3))
elif b >= (1024**3): # 1 GiB
return '%0.1f GiB' % (float(b) / (1024**3))
elif b >= 10 * (1024**2): # 10 MiB
return '%0.0f MiB' % (float(b) / (1024**2))
e... | bigcode/self-oss-instruct-sc2-concepts |
import logging
def mask_sanity_fail(mask, shape, description):
"""
Sanity check on training masks; shape needs to match.
description affects the logging, on failure.
"""
if mask is None:
logging.warn("{} : mask is None".format(description))
return True
if mask.shape != shape:
... | bigcode/self-oss-instruct-sc2-concepts |
def get_error_score(y_true, y_predicted):
""" Error score calculation for classification.
Checks if the labels correspond and gives a score.
An error score of 1 means that everything is falsly predicted.
An error score of 0 means that everything is correctly predicted.
Inputs:
y... | bigcode/self-oss-instruct-sc2-concepts |
import hashlib
def get_consts(method):
"""
Create hash object and its integer upper bound.
"""
hasher = getattr(hashlib, method)
max_plus_one = 2 ** (hasher().digest_size * 8)
return hasher, max_plus_one | bigcode/self-oss-instruct-sc2-concepts |
def remove_by_index(l, index):
"""removes element at index position from indexed sequence l and returns the result as new object"""
return l[:index] + l[index + 1:] | bigcode/self-oss-instruct-sc2-concepts |
def resdiv_r2(Vin, Vout, R1):
"""
Calculate the exact value of R1 with R2 given.
"""
return R1 / (Vin/Vout - 1) | bigcode/self-oss-instruct-sc2-concepts |
def get_file_changes(commit, prev_commit):
"""
Perform a diff between two commit objects and extract the changed
files from it.
Args:
commit(:class:`~git.objects.commit.Commit`): Commit object for commit
with file changes
prev_commit(:class:`~git.objects.commit.Commit`): Com... | bigcode/self-oss-instruct-sc2-concepts |
import random
import string
def random_string(length=25):
"""Generate a random string."""
return ''.join(random.choice(string.ascii_letters) for i in range(length)) | bigcode/self-oss-instruct-sc2-concepts |
def find_response_end_token(data):
"""Find token that indicates the response is over."""
for line in data.splitlines(True):
if line.startswith(('OK', 'ACK')) and line.endswith('\n'):
return True
return False | bigcode/self-oss-instruct-sc2-concepts |
def perc95(chromosomes):
"""
Returns the 95th percentile value of the given chromosomes.
"""
values = []
for peaks in chromosomes.values():
for peak in peaks:
values.append(peak[3])
values.sort()
# Get 95% value
return values[int(len(values) * 0.95)] | bigcode/self-oss-instruct-sc2-concepts |
def is_square(arr):
"""
Determines whether an array is square or not.
:param ndarray arr: numpy array
:return: condition
:rtype: bool
"""
shape = arr.shape
if len(shape) == 2 and (shape[0] == shape[1]):
return True
return False | bigcode/self-oss-instruct-sc2-concepts |
import hashlib
def string_hash(data: str) -> str:
"""Given a string, return a hash."""
md5 = hashlib.md5()
md5.update(data.encode())
# Note: returning plain integers instead of hex so linters
# don't see words and give spelling errors.
return str(int.from_bytes(md5.digest(), byteorder='big')) | bigcode/self-oss-instruct-sc2-concepts |
def _escape_filename(filename):
"""Escapes spaces in the given filename, Unix-style."""
return filename.replace(" ", "\\ ") | bigcode/self-oss-instruct-sc2-concepts |
def _parse_languages(value):
"""
Utility function to parse languages.
>>> _parse_languages(None) is None
True
>>> _parse_languages("en") == frozenset(('en',))
True
>>> _parse_languages('')
''
>>> _parse_languages("en,es") == frozenset(('en', 'es'))
... | bigcode/self-oss-instruct-sc2-concepts |
import csv
def read_csv(filename):
"""
Read values from csv filename and returns a list of OrderedDict for each row.
"""
csv_data = []
with open(filename, 'r') as f:
csv_file = csv.DictReader(f)
for row in csv_file:
csv_data.append(row)
return csv_data | bigcode/self-oss-instruct-sc2-concepts |
def str_to_dpid (s):
"""
Convert a DPID in the canonical string form into a long int.
"""
if s.lower().startswith("0x"):
s = s[2:]
s = s.replace("-", "").split("|", 2)
a = int(s[0], 16)
if a > 0xffFFffFFffFF:
b = a >> 48
a &= 0xffFFffFFffFF
else:
b = 0
if len(s) == 2:
b = int(s[1])... | bigcode/self-oss-instruct-sc2-concepts |
import requests
import click
def _update_resource(url, token, data):
"""
Update a resource using a PATCH request.
This function is generic and was designed to unify all the PATCH requests to the Backend.
:param url: url to update the resource
:param token: user token
:param data: dict with t... | bigcode/self-oss-instruct-sc2-concepts |
def extended_euclidean(a, b, test=False):
"""
Extended Euclidean algorithm
Given a, b, solve:
ax + by = gcd(a, b)
Returns x, y, gcd(a, b)
Other form, for a prime b:
ax mod b = gcd(a, b) = 1
>>> extended_euclidean(3, 5, test=True)
3 * 2 + 5 * -1 = 1 True
>>> extended_euclidean(2... | bigcode/self-oss-instruct-sc2-concepts |
def get_sample_name(sample, delimiter='_', index=0):
"""
Return the sample name
"""
return sample.split(delimiter)[index] | bigcode/self-oss-instruct-sc2-concepts |
def negate_condition(condition):
"""Negates condition.
"""
return "not ({0})".format(condition) | bigcode/self-oss-instruct-sc2-concepts |
from typing import Callable
from typing import Dict
def add_features(transform: Callable[[Dict], Dict], x: Dict) -> Dict:
"""
Takes the input, passes it to a transformation and merge the original
input with the result of the transformation, can be used to
augment data in the batch.
.. note::
... | bigcode/self-oss-instruct-sc2-concepts |
def insertGame(gtitle: str, release_date: str="0000-00-00") -> str:
"""Return a query to insert a game into the database."""
return (f"INSERT IGNORE INTO game (title, release_date) "
f"VALUES ('{gtitle}', '{release_date}');"
) | bigcode/self-oss-instruct-sc2-concepts |
import pathlib
from typing import Tuple
import ast
def find_import_region(file: pathlib.Path) -> Tuple[int, int]:
"""Return the index of the first last import line that precedes any other code.
Note: will not handle try/except imports
file: pathlib.Path path to file to evaluate
Return: Tuple[int, in... | bigcode/self-oss-instruct-sc2-concepts |
def most_common_dict(a_dict: dict):
"""Returns the most common value from a dict. Used by consensus"""
val_list = list(a_dict.values())
return max(set(val_list), key=val_list.count) | bigcode/self-oss-instruct-sc2-concepts |
def count_characters(array: list):
"""given a list:array of strings return the character count"""
if len(array) == 1: # base case
return len(array[0])
elif len(array) == 0: # edge case of empty array
return 0
else:
return len(array[0]) + count_characters(array[1:]) | bigcode/self-oss-instruct-sc2-concepts |
def filter_type(data, titletype: str):
"""
Filters the data so that it only returns rows with the
defined value 'titletype' in the field titleType.
Parameters:
data = IMDb dataframe that contains the column 'titleType'.
titletype = String value used to filter the data.
Returns: A dat... | bigcode/self-oss-instruct-sc2-concepts |
def concatenate_matrices(matrices):
"""
This function creates a concatenated matrix from a list of matrices
Arguments:
matrices: A list of tranformation matrices
Returns:
_transform: Concatenated matrix
"""
_transform = matrices[0]
for i in range(1,len(matrices)):
... | bigcode/self-oss-instruct-sc2-concepts |
def is_overlapping(node2comm):
"""Determine whether a graph partition contains overlapping communities.
Parameters
----------
node2comm : list of set of nonnegative integers **or** ndarray
Community structure. A mapping from node IDs [0..NN-1] to community
IDs [0..NC-1].
Examples
... | bigcode/self-oss-instruct-sc2-concepts |
def find_io_by_name(input_list: list, name: str):
"""Retrieve an item from a list by its name attribute
Arguments:
input_list {list} -- A list of IO Items
name {str} -- The name to filter for
Raises:
ValueError: No item with this name was found
Returns:
IOItem -- An IO... | bigcode/self-oss-instruct-sc2-concepts |
def get_tasks_args(parser):
"""Provide extra arguments required for tasks."""
group = parser.add_argument_group(title='tasks')
group.add_argument('--task', type=str, required=True,
help='Task name.')
group.add_argument('--epochs', type=int, default=None,
he... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def compute_fg_mask(gt_boxes2d, shape, downsample_factor=1, device=torch.device("cpu")):
"""
Compute foreground mask for images
Args:
gt_boxes2d: (B, N, 4), 2D box labels
shape: torch.Size or tuple, Foreground mask desired shape
downsample_factor: int, Downsample facto... | bigcode/self-oss-instruct-sc2-concepts |
def dict_to_tuple(dict):
"""Return RSA PyCrypto tuple from parsed rsa private dict.
Args:
dict: dict of {str: value} returned from `parse`
Returns:
tuple of (int) of RSA private key integers for PyCrypto key construction
"""
tuple = (
dict['modulus'],
dict['publicExponent'],
... | bigcode/self-oss-instruct-sc2-concepts |
def get_word_freq(word_list, normalize=True):
"""Returns a sorted list of (word,word count) tuples in descending order.
The frequency is normalized to values between 0 and 1 by default."""
word_freq_dict = {}
for w in word_list:
if w in word_freq_dict:
word_freq_dict[w] += 1
... | bigcode/self-oss-instruct-sc2-concepts |
from operator import concat
def concat_list(wire_list):
"""
Concatenates a list of WireVectors into a single WireVector
:param wire_list: list of WireVectors to concat
:return: WireVector with length equal to the sum of the args' lengths
The concatenation order is LSB (UNLIKE Concat)
"""
... | bigcode/self-oss-instruct-sc2-concepts |
def split_doc_num(doc_num, effective_date):
""" If we have a split notice, we construct a document number
based on the original document number and the effective date. """
effective_date = ''.join(effective_date.split('-'))
return '{0}_{1}'.format(doc_num, effective_date) | bigcode/self-oss-instruct-sc2-concepts |
import re
from typing import Tuple
def parse_version_string(name: str) -> Tuple[str, str]:
"""Parse a version string (name ID 5) and return (major, minor) strings.
Example of the expected format: 'Version 01.003; Comments'. Version
strings like "Version 1.3" will be post-processed into ("1", "300").
The pars... | bigcode/self-oss-instruct-sc2-concepts |
def autocrop_array_shapes(input_shapes, cropping):
"""Computes the shapes of the given arrays after auto-cropping is applied.
For more information on cropping, see the :func:`autocrop` function
documentation.
# Arguments
input_shapes: the shapes of input arrays prior to cropping in
... | bigcode/self-oss-instruct-sc2-concepts |
def degc_to_kelvin(x):
"""Degree Celsius to Kelvin
Parameters
----------
x : float or array of floats
Air temperature in deg C
Returns
-------
output : float or array of floats
Air temperature in Kelvin
"""
return x + 273.15 | bigcode/self-oss-instruct-sc2-concepts |
def letter_count(word, letter):
"""
Returns the number of instances of "letter" in "word"
"""
return word.count(letter) | bigcode/self-oss-instruct-sc2-concepts |
def make_reducer(delimiter):
"""Create a reducer with a custom delimiter.
Parameters
----------
delimiter : str
Delimiter to use to join keys.
Returns
-------
f : Callable
Callable that can be passed to `flatten()`'s `reducer` argument.
"""
def f(k1, k2):
if ... | bigcode/self-oss-instruct-sc2-concepts |
def resource_is_object(resource):
"""Check if the resource is a simple object."""
if resource:
return (
"metadata" in resource
and "kind" in resource
and "name" in resource["metadata"]
)
return False | bigcode/self-oss-instruct-sc2-concepts |
import warnings
def div(a, b):
"""Divides a number 'a' by another number 'b'
Parameters
----------
a: int or float
Number to be divided
b: int or float
Number to divide by
Returns
-------
d: int or float
Result of the division
""... | bigcode/self-oss-instruct-sc2-concepts |
def get_param_value(param_name, args, config):
"""Get value of a named command parameter either from args or from config.
"""
param_val = None
# If param_name is available in config use it
if config and config.get('default', None) and config['default'].get(param_name, None):
param_val = conf... | bigcode/self-oss-instruct-sc2-concepts |
def CO2_to_fCO2(CO2, Ks):
"""
Calculate fCO2 from CO2
"""
return CO2 / Ks.K0 | bigcode/self-oss-instruct-sc2-concepts |
def chr_start_stop_to_sj_ind(chr_start_stop, sj):
"""Transform a 'chr1:100-200' string into index range of sj dataframe
Parameters
----------
chr_start_stop : str
Genome location string of the format chr:start-stop
sj : pandas.DataFrame
Dataframe of splice junctions as created by re... | bigcode/self-oss-instruct-sc2-concepts |
import time
def to_timestamp(dtime):
"""Converts datetime to unix timestamp"""
return int(time.mktime(dtime.timetuple())) | bigcode/self-oss-instruct-sc2-concepts |
def nmc_LGM50_thermal_conductivity_ORegan2021(T):
"""
Wet positive electrode thermal conductivity as a function of the temperature from
[1].
References
----------
.. [1] Kieran O’Regan, Ferran Brosa Planella, W. Dhammika Widanage, and Emma
Kendrick. "Thermal-electrochemical parametrisation ... | bigcode/self-oss-instruct-sc2-concepts |
def check_order(order: int) -> int:
"""Confirms the input is a valid parity order."""
if not isinstance(order, int):
raise TypeError("`order` must be an integer.")
if order <= 0:
raise ValueError("`order` must be greater than zero.")
return order | bigcode/self-oss-instruct-sc2-concepts |
def get_h5_dataset_shape_from_descriptor_shape(
descriptor_shape, ep_data_key, ep_data_list
):
"""
Return the initial shape of the h5 dataset corresponding to the specified data_key.
Initially the dataset will have length 0. It will be resized when data is appended.
The descriptor shape will be eit... | bigcode/self-oss-instruct-sc2-concepts |
def uri_leaf(uri):
"""
Get the "leaf" - fragment id or last segment - of a URI. Useful e.g. for
getting a term from a "namespace like" URI. Examples:
>>> uri_leaf('http://example.org/ns/things#item')
'item'
>>> uri_leaf('http://example.org/ns/stuff/item')
'item'
>>> ... | bigcode/self-oss-instruct-sc2-concepts |
import asyncio
async def wait_for_event(evt, timeout): # pylint: disable=invalid-name
"""Wait for an event with a timeout"""
try:
await asyncio.wait_for(evt.wait(), timeout)
except asyncio.TimeoutError:
pass
return evt.is_set() | bigcode/self-oss-instruct-sc2-concepts |
def _GenerateJsDoc(args, return_val=False):
"""Generate JSDoc for a function.
Args:
args: A list of names of the argument.
return_val: Whether the function has a return value.
Returns:
The JSDoc as a string.
"""
lines = []
lines.append('/**')
lines += [' * @param {} %s' % arg for arg in ar... | bigcode/self-oss-instruct-sc2-concepts |
def metric_count_active(result, base_key, count):
"""Counts the number of chain active ("o") for the specified keys."""
active = 0
base_keys = base_key.split(",")
for base_key in base_keys:
for i in range(1, count):
key = base_key.replace("[i]", str(i))
if key in result:
... | bigcode/self-oss-instruct-sc2-concepts |
def _testLengthBoundaryValidity(dataLength, tableDirectory):
"""
>>> test = [
... dict(tag="test", offset=44, length=1)
... ]
>>> bool(_testLengthBoundaryValidity(45, test))
False
>>> test = [
... dict(tag="test", offset=44, length=2)
... ]
>>> bool(_testLengthBoundaryVal... | bigcode/self-oss-instruct-sc2-concepts |
def get_neighbor(rows, ele):
"""
:param rows: lst, letters get from user
:param ele: lst, current letter position
:return neighbor: lst, the location tuple next to ele
"""
neighbor = []
# find valid location tuples that in 3x3 grid centered by ele
for x in range(-1, 2):
for y in range(-1, 2):
test_x = ele[... | bigcode/self-oss-instruct-sc2-concepts |
def get_unset_keys(dictionary, keys):
"""
This is a utility that takes a dictionary and a list of keys
and returns any keys with no value or missing from the dict.
"""
return [k for k in keys if k not in dictionary or not dictionary[k]] | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
from typing import Any
def get_search_result_path(search_response: List[Any]) -> str:
"""Extracts a search result path from a search job creation response
:type search_response: ``List[Any]``
:param search_response: A search job creation response
:return: A path to the search... | bigcode/self-oss-instruct-sc2-concepts |
def fichier2str(nom_fichier):
"""
Renvoie le contenu du fichier sous forme de chaîne de caractères.
"""
with open(nom_fichier, 'r') as f:
chaine = f.read()
return chaine | bigcode/self-oss-instruct-sc2-concepts |
def remove_optgroups(choices):
"""
Remove optgroups from a choice tuple.
Args:
choices (tuple): The choice tuple given in the model.
Returns:
The n by 2 choice tuple without optgroups.
"""
# Check whether the tuple contains extra optgroup
if isinstance(cho... | bigcode/self-oss-instruct-sc2-concepts |
def is_valid_username(username):
"""Ensure username meets requirements. Returns True if successful."""
return bool(username and username.isalnum() and len(username) <= 30) | bigcode/self-oss-instruct-sc2-concepts |
def remove_all(alist,k):
"""Removes all occurrences of k from alist."""
retval = []
for x in alist:
if x != k:
retval.append(x)
return retval | bigcode/self-oss-instruct-sc2-concepts |
def intensity(c, i):
"""Return color c changed by intensity i
For 0 <= i <= 127 the color is a shade, with 0 being black, 127 being the
unaltered color.
For 128 <= i <= 255 the color is a tint, with 255 being white, 128 the
unaltered color.
"""
r, g, b = c[0:3]
if 0 <= i <= 127:
... | bigcode/self-oss-instruct-sc2-concepts |
def pixelfit(obs, i, times, series, timeslice=slice(None,None,None)) :
"""Fits a series object to the time series of data contained within
a single pixel, optionally extracting the specified time period.
Coefficients of the fit have been stored in the
series. The rsquared of the fit is returned."""
... | bigcode/self-oss-instruct-sc2-concepts |
def is_dict(obj):
"""
Check if an object is a dict.
"""
return isinstance(obj, dict) | bigcode/self-oss-instruct-sc2-concepts |
def get_iteration(nb, batch_size):
"""
Given total sample size and batch size, return
number of batch.
"""
basic = nb//batch_size
total = basic + (0 if nb%batch_size==0 else 1)
return total | bigcode/self-oss-instruct-sc2-concepts |
def test_is_true(v):
"""
Helper function tests for a value that evaluates to Boolean True
"""
return bool(v) | bigcode/self-oss-instruct-sc2-concepts |
def generate_plus_grid_isls(output_filename_isls, n_orbits, n_sats_per_orbit, isl_shift, idx_offset=0):
"""
Generate plus grid ISL file.
:param output_filename_isls Output filename
:param n_orbits: Number of orbits
:param n_sats_per_orbit: Number of satellites per orbit
... | bigcode/self-oss-instruct-sc2-concepts |
def unique_list(list):
"""
Returns a unique version of a list
:param list: Input list
:return: Unique list
"""
new_list = []
for i in list:
if i not in new_list:
new_list.append(i)
return new_list | bigcode/self-oss-instruct-sc2-concepts |
def calculate_comment_to_code_ratio(production_code_metrics, test_code_metrics):
"""Calculate the ratio between the comments and the lines of code."""
lines_of_code = production_code_metrics["SUM"]["code"] + test_code_metrics["SUM"]["code"]
comment_lines = production_code_metrics["SUM"]["comment"] + test_c... | bigcode/self-oss-instruct-sc2-concepts |
def lowercase_first_letter(s: str) -> str:
"""
Given a string, returns that string with a lowercase first letter
"""
if s:
return s[0].lower() + s[1:]
return s | bigcode/self-oss-instruct-sc2-concepts |
def _h_n_linear_geometry(bond_distance: float, n_hydrogens: int):
# coverage: ignore
"""Create a geometry of evenly-spaced hydrogen atoms along the Z-axis
appropriate for consumption by MolecularData."""
return [('H', (0, 0, i * bond_distance)) for i in range(n_hydrogens)] | bigcode/self-oss-instruct-sc2-concepts |
def split_alignments_by_chrom(alignments_file, get_temp_path):
"""Split an alignments file into several files, one per chromosome.
get_temp_path is a function that returns a new temporary file path.
Returns a dictionary, {chrom_name: alignmentfile_path}."""
paths = {}
cur_chrom = None
output_p... | bigcode/self-oss-instruct-sc2-concepts |
def generate_occluder_pole_position_x(
wall_x_position: float,
wall_x_scale: float,
sideways_left: bool
) -> float:
"""Generate and return the X position for a sideways occluder's pole object
using the given properties."""
if sideways_left:
return -3 + wall_x_position - wall_x_scale / 2
... | bigcode/self-oss-instruct-sc2-concepts |
def merge(ll, rl):
"""Merge given two lists while sorting the items in them together
:param ll: List one (left list)
:param rl: List two (right list)
:returns: Sorted, merged list
"""
res = []
while len(ll) != 0 and len(rl) != 0:
if ll[0] < rl[0]:
res.append(ll.pop(0))
... | bigcode/self-oss-instruct-sc2-concepts |
def prep_reply_text(screen_name, text):
"""Replies have to contain the original tweeter's screen_name"""
if screen_name in text:
return text
else:
if "@" in screen_name:
return screen_name + " " + text
else:
return "@{} {}".format(screen_name, text) | bigcode/self-oss-instruct-sc2-concepts |
def evaluate_probabilities(data):
"""Calculate accuracy of logistic regression model
Args:
data (pandas.DataFrame): dataframe with nudge success and probability
Returns:
int: accuracy in percentage
"""
check = round(data['probability']) == data['outcome']
correct = sum(check)
... | bigcode/self-oss-instruct-sc2-concepts |
def community_kwargs_from_role(role):
"""Parses community id and role from role name."""
args = role.name.split(':')
if args[0] != 'community' or len(args) != 3:
return None
return dict(
id_=args[1],
role=args[2]
) | bigcode/self-oss-instruct-sc2-concepts |
import torch
def get_lengths_from_binary_sequence_mask(mask: torch.Tensor):
"""
Compute sequence lengths for each batch element in a tensor using a
binary mask.
Parameters
----------
mask : torch.Tensor, required.
A 2D binary mask of shape (batch_size, sequence_length) to
calcu... | bigcode/self-oss-instruct-sc2-concepts |
def _f_p_r_lcs(llcs, m, n):
"""
Computes the LCS-based F-measure score
Source: http://research.microsoft.com/en-us/um/people/cyl/download/papers/
rouge-working-note-v1.3.1.pdf
Args:
llcs: Length of LCS
m: number of words in reference summary
n: number of words in candidate summary... | bigcode/self-oss-instruct-sc2-concepts |
def flatten_frames(array):
"""
Flattens array of shape [frames, height, width] into array of shape [frames, height*width]
Parameters
----------
array : np.array
(frames, height, width)
Returns
-------
np.array
flattened array (frames, height, width)
"""
_, heig... | bigcode/self-oss-instruct-sc2-concepts |
def check_valid_coors(coords):
"""Check if the given coords of the polygon are valid
Parameters
----------
coords : numpy array
a list of coordinates, shape = (8,)
Returns
------
bool
whether all coordinates are valid or not
"""
for i in coords:
if i < 0:
... | bigcode/self-oss-instruct-sc2-concepts |
import configparser
def _get_api_key() -> str:
"""
Retrieves the ADSBexchange API key from secrets.conf
"""
config = configparser.ConfigParser()
config.read("secrets.conf")
return config.get("adsbexchange", "key") | bigcode/self-oss-instruct-sc2-concepts |
def removeNoneValues(dict):
""" If value = None in key/value pair, the pair is removed.
Python >3
Args:
dict: dictionary
Returns:
dictionary
"""
return {k:v for k,v in dict.items() if v is not None} | bigcode/self-oss-instruct-sc2-concepts |
def subsampling(sequence, sampling_factor=5):
"""
Args:
sequence: data sequence [n_samples, n_features]
sampling_factor: sub-sampling factor
Returns:
sequence: sub-sampled data sequence [n_samples/sampling_factor, n_features]
"""
sequence = sequence[::sampling_factor]
... | bigcode/self-oss-instruct-sc2-concepts |
def _get_local_explanation_row(explainer, evaluation_examples, i, batch_size):
"""Return the local explanation for the sliced evaluation_examples.
:param explainer: The explainer used to create local explanations.
:type explainer: BaseExplainer
:param evaluation_examples: The evaluation examples.
:... | bigcode/self-oss-instruct-sc2-concepts |
def get_addons(objects):
"""Return tuple of required addons for a given sequence of objects."""
required = {}
def _required_addons(objs):
for addon in objs:
if addon not in required:
if addon.required_addons:
_required_addons(addon.required_addons)
... | bigcode/self-oss-instruct-sc2-concepts |
def big_letters(sequence_of_sequences):
"""
Returns a new STRING that contains all the upper-case letters
in the subsequences of the given sequence that are strings,
in the order that they appear in the subsequences.
For example, if the argument is:
[(3, 1, 4), # not... | bigcode/self-oss-instruct-sc2-concepts |
import secrets
import string
def random_name(length: int) -> str:
"""Get a random string suitable for a processes/consumer name"""
return "".join(secrets.choice(string.ascii_lowercase) for _ in range(length)) | bigcode/self-oss-instruct-sc2-concepts |
def pressure_at_model_level(ps, ak, bk):
"""computes pressure at a certain model level.
Uses surface pressure and vertical hybrid coordinates.
**Arguments:**
*ps:*
surface pressure
*ak, bk:*
hybrid coordinates at a certain level
"""
return ak + bk * ps | bigcode/self-oss-instruct-sc2-concepts |
def is_valid_matrix(mtx):
"""
>>> is_valid_matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
True
>>> is_valid_matrix([[1, 2, 3], [4, 5], [7, 8, 9]])
False
"""
if mtx == []:
return False
cols = len(mtx[0])
for col in mtx:
if len(col) != cols:
return False
r... | bigcode/self-oss-instruct-sc2-concepts |
import re
def handle_star(github_star):
"""
Get github repository star
:param github_star: 1.1k or 100
:return: 1100 or 100
"""
pattern = r'[^k]+'
star = re.findall(pattern, github_star)
if github_star[-1] == 'k':
return int(float(star[0]) * 1000)
else:
return int(s... | bigcode/self-oss-instruct-sc2-concepts |
def binary_to_hex(binary_data, byte_offset, length):
"""Converts binary data chunk to hex"""
hex_data = binary_data[byte_offset:byte_offset + length].hex()
return ' '.join(a+b for a,b in zip(hex_data[::2], hex_data[1::2])) | bigcode/self-oss-instruct-sc2-concepts |
def generate_degradation_matrix(p, h_max):
"""
Generate an upper triangular degradation transition matrix.
Parameters
----------
p : float
The probability of degrading by one unit at each time step.
h_max : int
The index of the failed state.
Returns
-------
list o... | bigcode/self-oss-instruct-sc2-concepts |
def ncities(cost):
"""
Return the number of cities
"""
nc, _ = cost.shape
return nc | 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.