seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
def all_nums(table):
"""Returns True if table contains only numbers
Precondition: table is a (non-ragged) 2d List"""
cnt = 0
number_cnt = 0
for row in table:
for item in row:
cnt += 1
if type(item) in [int, float]:
number_cnt += 1
if cnt != number_... | bigcode/self-oss-instruct-sc2-concepts |
def e(parameters, p, r_v):
"""
Returns an expression for the partial pressure of water vapour
from the total pressure and the water vapour mixing ratio.
:arg parameters: a CompressibleParameters object.
:arg p: the pressure in Pa.
:arg r_v: the mixing ratio of water vapour.
"""
epsilon... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Dict
from typing import Any
def check_is_legacy(sample: Dict[str, Any]) -> bool:
"""
Check if a sample has legacy read files.
:param sample: the sample document
:return: legacy boolean
"""
files = sample["files"]
return (
all(file.get("raw", False) is False for... | bigcode/self-oss-instruct-sc2-concepts |
def genotype_likelihood_index(allele_indices):
"""Returns the genotype likelihood index for the given allele indices.
Args:
allele_indices: list(int). The list of allele indices for a given genotype.
E.g. diploid homozygous reference is represented as [0, 0].
Returns:
The index into the associated... | bigcode/self-oss-instruct-sc2-concepts |
import re
def text_area_extractor(text):
"""
Textbox extractor function to preprocess and extract text
Args:
text: Raw Extracted Text from the News Article
Returns:
text: Preprocessed and clean text ready for analysis
"""
text = text.lower()
text = re.sub(r'[^a-zA-Z0-9\s]',... | bigcode/self-oss-instruct-sc2-concepts |
import calendar
import time
def time_string_to_unix(time_string, time_format):
"""Converts time from string to Unix format.
Unix format = seconds since 0000 UTC 1 Jan 1970.
:param time_string: Time string.
:param time_format: Format of time string (example: "%Y%m%d" or
"%Y-%m-%d-%H%M%S").
... | bigcode/self-oss-instruct-sc2-concepts |
import click
def read_user_variable(var_name, default_value):
"""Prompt the user for the given variable and return the entered value
or the given default.
:param str var_name: Variable of the context to query the user
:param default_value: Value that will be returned if no input happens
"""
#... | bigcode/self-oss-instruct-sc2-concepts |
def gvariant(lst):
"""Turn list of strings to gvariant list."""
assert isinstance(lst, list), "{} is not a list".format(lst)
content = ", ".join(
"'{}'".format(l) for l in lst
)
return '[{}]'.format(content) | bigcode/self-oss-instruct-sc2-concepts |
def compss_open(file_name, mode='r'):
# type: (str, str) -> object
""" Dummy compss_open.
Open the given file with the defined mode (see builtin open).
:param file_name: The file name to open.
:param mode: Open mode. Options = [w, r+ or a , r or empty]. Default=r.
:return: An object of 'file' ... | bigcode/self-oss-instruct-sc2-concepts |
def can_view_cohorts(user):
"""To access Cohort views user need to be
authenticated and either be an admin, or
in a group that has the 'view cohorts' permission."""
return user.is_authenticated and user.has_perm('release.view_releasecohort') | bigcode/self-oss-instruct-sc2-concepts |
from typing import Counter
import math
def conditional_entropy(x, y):
"""
Calculates the conditional entropy of x given y: S(x|y)
Wikipedia: https://en.wikipedia.org/wiki/Conditional_entropy
:param x: list / NumPy ndarray / Pandas Series
A sequence of measurements
:param y: list / NumPy ... | bigcode/self-oss-instruct-sc2-concepts |
def evaluate_error(model, test_gen, no_test_sam):
"""
DESCRIPTION: Evaluate the network performance
INPUT: The trained model, the test set generator,
number of testing images
OUTPUT: List of statistics about the performance of the model
"""
stats = model.evaluate_generator(test_gen, no_test_... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def get_valid_negative_mask(labels):
"""
To be a valid negative pair (a,n),
- a and n are different embeddings
- a and n have the different label
"""
indices_equal = torch.eye(labels.size(0)).byte()
indices_not_equal = ~indices_equal
label_not_equal = torch.ne(labels.unsqueeze(1), labels.unsqu... | bigcode/self-oss-instruct-sc2-concepts |
def compoundInterestFutureValue(p, r, c, n):
"""Compound interest future value
Returns: future value
Input values:
p : principal
r : interest rate
c : number of compounding periods in a year
n : (c * t) , total number of compounding periods
"""
fv = (p * (1 + (r / c))) **... | bigcode/self-oss-instruct-sc2-concepts |
def signature(self):
"""
Returns the signature of the quadratic form, defined as:
number of positive eigenvalues - number of negative eigenvalues
of the matrix of the quadratic form.
INPUT:
None
OUTPUT:
an integer
EXAMPLES:
sage: Q = DiagonalQuadraticForm(Z... | bigcode/self-oss-instruct-sc2-concepts |
def rgb_to_hex(r, g, b):
"""
Convert RGB color to an Hexadecimal representation
"""
return "%02x%02x%02x" % (r, g, b) | bigcode/self-oss-instruct-sc2-concepts |
def binary_lookup(index, offsets):
"""
Given a character index, look up the index of it in the offsets. This will
be the number at which the next index is greater
"""
bottom = 0
top = len(offsets) - 1
if index > offsets[top]:
return top
while top - bottom > 1:
mid = ... | bigcode/self-oss-instruct-sc2-concepts |
import random
def snp(sequence):
"""
Function takes a sequence string and introduces a single nucleotide polymorphism (SNP)
Randomly finds an index in the string and replaces the value at the index with a new
letter from the given alphabet. If the value is the same as the previous value, the
funct... | bigcode/self-oss-instruct-sc2-concepts |
import csv
def load_training3(infile):
"""Load training data with normalized unigram count, hamming distance, and
query length.
Args:
infile: file name to load data from
"""
X = []
Y = []
with open(infile, 'r') as f:
reader = csv.reader(f)
for row in reader:
if reader.line_num == ... | bigcode/self-oss-instruct-sc2-concepts |
def compute_whitespace(d):
"""Calculates the percentage of empty strings in a
two-dimensional list.
Parameters
----------
d : list
Returns
-------
whitespace : float
Percentage of empty cells.
"""
whitespace = 0
r_nempty_cells, c_nempty_cells = [], []
for i in ... | bigcode/self-oss-instruct-sc2-concepts |
import time
import torch
from typing import OrderedDict
def load_model(model, model_file, is_restore=False):
"""Load model.
:param model: created model.
:param model_file: pretrained model file.
:param is_restore: set true to load from model_file.
"""
t_start = time.time()
if isinstance(m... | bigcode/self-oss-instruct-sc2-concepts |
import re
def camel_case(words):
"""Convert a noun phrase to a CamelCase identifier."""
result = ''
for word in re.split(r'(?:\W|_)+', words):
if word:
if word[:1].islower():
word = word.capitalize()
result += word
return result | bigcode/self-oss-instruct-sc2-concepts |
def key(profile):
"""Get a sorting key based on the lower case last name, then firstname"""
components = profile["name"].lower().split(" ")
return " ".join([components[-1]] + components[:-1]) | bigcode/self-oss-instruct-sc2-concepts |
def insertion_sort(A, reverse = False):
"""Assumes A is a list of integers, by default reverse = False
Returns the sorted A in non-decreasing order if reverse = False,
and in non-increasing order if reverse = True.
****************************************
The complexity of the algorithm... | bigcode/self-oss-instruct-sc2-concepts |
import random
import json
def _retrieve_quote(json_filename):
"""
Retrieve a random quote entry from json_filename, very quickly,
without loading the entire file into memory
:param str json_filename: Name of .json file to open
:return: Tuple of the form: (str(quote_text), str(quote_author))
... | bigcode/self-oss-instruct-sc2-concepts |
def compute_overdose_deaths(run, start_year, end_year, config, intervention):
"""Compute number of opioid overdose deaths from start_year to end_year.
Parameters
----------
run: whynot.dynamics.Run
Run object produced by running simulate for the opioid simulator
start_year: int
... | bigcode/self-oss-instruct-sc2-concepts |
def sequential_search(target, lyst):
"""
in()
顺序搜索
Returns the position of the target item if found, or -1 otherwise.
:param target:
:param lyst:
:return:
"""
position = 0
while position < len(lyst):
if target == lyst[position]:
return position
positio... | bigcode/self-oss-instruct-sc2-concepts |
def check_obs(idx, obs):
"""Check every term in every sequence of obs and see if any term is >= idx
or < 0. If true, return false. Otherwise return true.
"""
for o in obs:
for term in o:
if (term >= idx) or (term < 0):
return False
return True | bigcode/self-oss-instruct-sc2-concepts |
from dateutil.tz import tzlocal, gettz
def to_system_time(dt):
"""
Converts a timezone aware datetime object to an object to be used in the messagebus scheduler
:param dt: datetime object to convert
:return: timezone aware datetime object that can be scheduled
"""
tz = tzlocal()
if dt.tzi... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def to_gpu(x):
"""Move `x` to cuda device.
Args:
x (tensor)
Returns:
torch.Variable
"""
x = x.contiguous()
if torch.cuda.is_available():
x = x.cuda(non_blocking=True)
return torch.autograd.Variable(x) | bigcode/self-oss-instruct-sc2-concepts |
import math
def floor_with_place(value, keep_decimal_place):
"""
無條件捨去小數點後 N 位
Args:
value(float): 數值
keep_decimal_place(2): 要保留到小數點第幾位, e.g 2,表示保留到第二位,後面的位數則無條件捨去
"""
scale_value = math.floor(value * pow(10, keep_decimal_place))
result = scale_value / pow(10, keep_decimal_place)
return result | bigcode/self-oss-instruct-sc2-concepts |
def ci_equals(left, right):
"""Check is @left string is case-insensative equal to @right string.
:returns: left.lower() == right.lower() if @left and @right is str. Or
left == right in other case.
"""
if isinstance(left, str) and isinstance(right, str):
return left.lower() == right.lower()
... | bigcode/self-oss-instruct-sc2-concepts |
def get_trig_val(abs_val: int, max_unit: int, abs_limit: int) -> int:
"""Get the corresponding trigger value to a specific limit. This evenly
devides the value so that the more you press the trigger, the higher the
output value.
abs_val - The current trigger value
max_unit - The maximum value to re... | bigcode/self-oss-instruct-sc2-concepts |
def transpose(g):
"""Fonction qui, à l'aide d'une grille sous forme de liste contenant des listes, retourne une nouvelle grille
pour laquelle on a inversé les colonnes et les lignes de la grille d'origine.
Paramètre(s):
- g list: Grille à transposer sous la forme de liste de liste. La liste parente... | bigcode/self-oss-instruct-sc2-concepts |
import random
def complete(subjects, seed=None):
""" Create a randomization list using complete randomization.
Complete randomization randomly shuffles a list of group labels. This
ensures that the resultant list is retains the exact balance desired.
This randomization is done in place.
Args:
... | bigcode/self-oss-instruct-sc2-concepts |
def str_to_int(num_str):
"""
Converts string into number.
Parameters:
num_str: a string to be converted into number
Returns:
numeric value of the string representing the number
"""
if num_str.lower().startswith('0x'):
return int(num_str[2:], 16)
return int(num_str... | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
def scale_prev_up_to_1(prev_vals: List[float], fraction: float):
"""
Apply a percentage to the previous value, saturating at one or zero
"""
val = prev_vals[-1] * fraction
if val > 1:
return 1
elif val < 0:
return 0
else:
return val | bigcode/self-oss-instruct-sc2-concepts |
def manhattan_distance(start, end):
"""Calculate the Manhattan distance from a start point to an end point"""
return abs(end.x - start.x) + abs(end.y - start.y) | bigcode/self-oss-instruct-sc2-concepts |
def parse_alignment(alignment):
"""
Parses an alignment string.
Alignment strings are composed of space separated graphemes, with
optional parentheses for suppressed or non-mandatory material. The
material between parentheses is kept.
Parameters
----------
alignment : str
The a... | bigcode/self-oss-instruct-sc2-concepts |
def highlight_single_token(token):
"""Highlight a single token with ^."""
return {token.start_row: " " * token.start_col + "^" * len(token.string)} | bigcode/self-oss-instruct-sc2-concepts |
def voter_notification_settings_update_doc_template_values(url_root):
"""
Show documentation about voterNotificationSettingsUpdate
"""
required_query_parameter_list = [
{
'name': 'api_key',
'value': 'string (from post, cookie, or get (in that order))', # b... | bigcode/self-oss-instruct-sc2-concepts |
import re
def parse_gitmodules(input_text):
"""Parse a .gitmodules file and return a list of all the git submodules
defined inside of it. Each list item is 2-tuple with:
- submodule name (string)
- submodule variables (dictionary with variables as keys and their values)
The input should be a ... | bigcode/self-oss-instruct-sc2-concepts |
def is_clockwise(vertices):
"""
Returns whether a list of points describing a polygon are clockwise or counterclockwise.
is_clockwise(Point list) -> bool
Parameters
----------
vertices : a list of points that form a single ring
Examples
--------
>>> is_clockwise([Point((0, 0)), Point... | bigcode/self-oss-instruct-sc2-concepts |
import yaml
def yaml_from_dict(dictionary):
"""convert a Python dictionary to YAML"""
return yaml.dump(dictionary) | bigcode/self-oss-instruct-sc2-concepts |
def _GetOrAddArgGroup(parser, help_text):
"""Create a new arg group or return existing group with given help text."""
for arg in parser.arguments:
if arg.is_group and arg.help == help_text:
return arg
return parser.add_argument_group(help_text) | bigcode/self-oss-instruct-sc2-concepts |
import re
def parse_show_arp(raw_result):
"""
Parse the 'show arp' command raw output.
:param str raw_result: vtysh raw result string.
:rtype: dict
:return: The parsed result of the show arp command in a \
dictionary of the form. Returns None if no arp found or \
empty dictionary:
... | bigcode/self-oss-instruct-sc2-concepts |
def quote(s: str) -> str:
"""
Quotes the '"' and '\' characters in a string and surrounds with "..."
"""
return '"' + s.replace('\\', '\\\\').replace('"', '\\"') + '"' | bigcode/self-oss-instruct-sc2-concepts |
import re
def remove_structure_definitions(data):
"""
Remove lines of code that aren't representative of LLVM-IR "language"
and shouldn't be used for training the embeddings
:param data: input data as a list of files where each file is a list of strings
:return: input data with non-representative ... | bigcode/self-oss-instruct-sc2-concepts |
def normalise_list(
l: list,
d: int,
f: int = 1,
) -> list:
"""Normalise a list according to a given displacement
Parameters
----------
l : list
The list of values
n : int, optional
The displacement, by default 0
Returns
-------
list
The normalis... | bigcode/self-oss-instruct-sc2-concepts |
def assert_time_of_flight_is_positive(tof):
"""
Checks if time of flight is positive.
Parameters
----------
tof: float
Time of flight.
"""
if tof <= 0:
raise ValueError("Time of flight must be positive!")
else:
return True | bigcode/self-oss-instruct-sc2-concepts |
def int2mac(integer, upper=False):
"""
Convert a integer value into a mac address
:param integer: Integer value of potential mac address
:param upper: True if you want get address with uppercase
:return: String mac address in format AA:BB:CC:DD:EE:FF
"""
def format_int():
return zip... | bigcode/self-oss-instruct-sc2-concepts |
def filter_phrases(input_str, filter_list):
"""
Filters out phrases/words from the input string
:param input_str: String to be processed.
:return: string with phrases from filter_list removed.
"""
for phrase in filter_list:
input_str = input_str.replace(phrase,'')
return input_str | bigcode/self-oss-instruct-sc2-concepts |
def build_mpi_call_str(task_specs,common_options,format_opts=None,runner='mpiexec'):
"""Summary
Args:
task_specs (list): List of strings, each containing an MPI task description, eg
e.g: ['-n {nrunners} python3 awrams.module.example {pickle_file}']
common_options ... | bigcode/self-oss-instruct-sc2-concepts |
def get_channel_dim(input_tensor, data_format='INVALID'):
"""Returns the number of channels in the input tensor."""
shape = input_tensor.get_shape().as_list()
assert data_format != 'INVALID'
assert len(shape) == 4
if data_format == 'NHWC':
return int(shape[3])
elif data_format == 'NCHW':
return int(... | bigcode/self-oss-instruct-sc2-concepts |
def index_of_square(square):
"""
Index of square
Args:
square (String): Square in chess notation e.g. f7
Returns:
Int: Index of square in bitboard
"""
line = ord(square[0].lower()) - ord('a')
row = int(square[1])
idx = 8 * (row - 1) + line
return idx | bigcode/self-oss-instruct-sc2-concepts |
def _check_attribute(obj, attr, typ, allow_none=False):
"""Check that a given attribute attr exists in the object obj and
is of type typ. Optionally, allow the attribute to be None.
"""
if not hasattr(obj, attr):
return False
val = getattr(obj, attr)
return isinstance(val, typ) or (allo... | bigcode/self-oss-instruct-sc2-concepts |
def join(func):
"""Decorator that joins characters of a returned sequence into a string."""
return lambda *args: ''.join(func(*args)) | bigcode/self-oss-instruct-sc2-concepts |
def divide(value, divisor):
"""
Divide value by divisor
"""
v = float(value)
d = float(divisor)
return v / d | bigcode/self-oss-instruct-sc2-concepts |
import warnings
def datastream_does_not_exist_warning(sensor_type, operation):
"""Warn about not existing datastreams."""
message = 'The datastream "{}" does not exist for the current session.\
The performed operation "{}" will have not effect'.format(
sensor_type, operation
)
return warn... | bigcode/self-oss-instruct-sc2-concepts |
def getWAMP(rawEMGSignal, threshold):
""" Wilson or Willison amplitude is a measure of frequency information.
It is a number of time resulting from difference between the EMG signal of two adjoining segments, that exceed a threshold.::
WAMP = sum( f(|x[i] - x[i+1]|)) for n = 1 --> n-1
... | bigcode/self-oss-instruct-sc2-concepts |
def fileGroupName(filePath):
"""
Get the group file name. foo.0080 would return foo
"""
return filePath.split('.')[0] | bigcode/self-oss-instruct-sc2-concepts |
def _min_filter(path_data, min_genes, min_transcripts):
"""
Return `True` is path_data has more than min_genes and min_transcripts.
"""
if min_genes > 1:
if len(path_data.Genes) < min_genes:
return False
if min_transcripts > 1:
if len(path_data.Transcripts) < min_transcri... | bigcode/self-oss-instruct-sc2-concepts |
def InvertDictionary(origin_dict):
"""Invert the key value mapping in the origin_dict.
Given an origin_dict {'key1': {'val1', 'val2'}, 'key2': {'val1', 'val3'},
'key3': {'val3'}}, the returned inverted dict will be
{'val1': {'key1', 'key2'}, 'val2': {'key1'}, 'val3': {'key2', 'key3'}}
Args:
origin_dict:... | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
import re
def split(sentence: str) -> List[str]:
"""
Split a string by groups of letters, groups of digits,
and groups of punctuation. Spaces are not returned.
"""
return re.findall(r"[\d]+|[^\W\d_]+|[^\w\s]+", sentence) | bigcode/self-oss-instruct-sc2-concepts |
def get_user_name(email: str) -> str:
"""Returns username part of email, if valid email is provided."""
if "@" in email:
return email.split("@")[0]
return email | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
def rotate_right(sequence: List[int]) -> List[int]:
"""
Shifts the elements in the sequence to the right, so that the last element of the sequence becomes the first.
>>> rotate_right([1,2,3,4,5])
[5, 1, 2, 3, 4]
>>> rotate_right([1])
[1]
>>> rotate_right([])
[]... | bigcode/self-oss-instruct-sc2-concepts |
import itertools
def get_all_combinations(elements):
""" get all combinations for a venn diagram from a list of elements"""
result = []
n = len(elements)
for i in range(n):
idx = n - i
result.append(list(set(itertools.combinations(elements, idx))))
return result | bigcode/self-oss-instruct-sc2-concepts |
def calc_theta_int_inc(theta_int_ini, delta_theta_int_inc):
"""
Eq. (1) in [prEN 15316-2:2014]
:param theta_int_ini: temperature [C]
:type theta_int_ini: double
:param delta_theta_int_inc: temperature [C]
:type delta_theta_int_inc: double
:return: sum of temperatures [C]
:rtyp... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Sequence
def evaluate_poly(poly: Sequence[float], x: float) -> float:
"""Evaluate a polynomial f(x) at specified point x and return the value.
Arguments:
poly -- the coeffiecients of a polynomial as an iterable in order of
ascending degree
x -- the point at which to eva... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Optional
import html
def unescape_string(value: Optional[str]) -> Optional[str]:
"""Perform HTML unescape on value."""
if value is None:
return value
return html.unescape(str(value)) | bigcode/self-oss-instruct-sc2-concepts |
def split(target_name):
"""Split a target name. Returns a tuple "(build_module, name)".
The split is on the first `:`.
Extra `:` are considered part of the name.
"""
return target_name.split(':', 1) | bigcode/self-oss-instruct-sc2-concepts |
def validate(config):
"""
Validate the beacon configuration
"""
# Configuration for aix_account beacon should be a dictionary
if not isinstance(config, dict):
return False, "Configuration for aix_account beacon must be a dict."
if "user" not in config:
return (
False,... | bigcode/self-oss-instruct-sc2-concepts |
def calc_closest_point_w_linestr(point, linestr):
"""
Calculate closest point between shapely LineString and Point.
Parameters
----------
point : object
Shapely point object
linestr : object
Shapely LineString object
Returns
-------
closest_point : object
Sh... | bigcode/self-oss-instruct-sc2-concepts |
def _compute_time(index, align_type, timings):
"""Compute start and end time of utterance.
Adapted from https://github.com/lumaku/ctc-segmentation
Args:
index: frame index value
align_type: one of ["begin", "end"]
Return:
start/end time of utterance in seconds
"""
mid... | bigcode/self-oss-instruct-sc2-concepts |
import math
def lcc_simp(seq):
"""Local Composition Complexity (LCC) for a sequence.
seq - an unambiguous DNA sequence (a string or Seq object)
Returns the Local Composition Complexity (LCC) value for the entire
sequence (as a float).
Reference:
Andrzej K Konopka (2005) Sequence Complexity ... | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
def right(lst: List[int], idx: int) -> int:
"""Return right heap child."""
right_idx = idx * 2 + 2
if right_idx < len(lst):
return right_idx
else:
return -1 | bigcode/self-oss-instruct-sc2-concepts |
def get_temp_dir(app_name):
"""Get the temporary directory for storing fab deploy artifacts.
Args:
app_name: a string representing the app name
Returns:
a string representing path to tmp dir
"""
return '/tmp/.fab-deploy-{}'.format(app_name) | bigcode/self-oss-instruct-sc2-concepts |
def command( *args ):
"""
Returns the command as a string joining the given arguments. Arguments
with embedded spaces are double quoted, as are empty arguments.
"""
cmd = ''
for s in args:
if cmd: cmd += ' '
if not s or ' ' in s:
cmd += '"'+s+'"'
else:
... | bigcode/self-oss-instruct-sc2-concepts |
def find_nearest(dataframes, x, npoints=5):
"""
Function that will take a list of dataframes, and
return slices of the dataframes containing a specified
number of closest points.
"""
nearest = [
df.loc[(df["Frequency"] - x).abs().argsort()[:npoints]] for df in dataframes
... | bigcode/self-oss-instruct-sc2-concepts |
def threept_center(x1, x2, x3, y1, y2, y3):
"""
Calculates center coordinate of a circle circumscribing three points
Parameters
--------------
x1: `double`
First x-coordinate
x2: `double`
Second x-coordinate
x3: `double`
Third y-coordinate
y1: `double`
... | bigcode/self-oss-instruct-sc2-concepts |
def _clean_name(name):
"""Strip surrounding whitespace."""
return name.strip() | bigcode/self-oss-instruct-sc2-concepts |
import calendar
def short_month(i, zero_based=False):
""" Looks up the short name of a month with an index.
:param i: Index of the month to lookup.
:param zero_based: Indicates whether the index starts from 0.
:returns: The short name of the month for example Jan.
>>> from dautils import ts
... | bigcode/self-oss-instruct-sc2-concepts |
def delete_double_undervotes(tally):
"""
Delete all double undervotes from a ballot dictionary tally
If a double undervote occurs, delete it and all
subsequent positions from ballot.
Args:
dictionary {tally}: dictionary mapping ballots to nonnegative reals
Returns:
dictionary ... | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
def parse_timeseries(
timeseries_str, time_input_unit="minute", time_output_unit="second"
) -> List[List[float]]:
"""Create a list of 2-list [timestep (seconds), value (mm/hour)]."""
if not timeseries_str:
return [[]]
output = []
for line in timeseries_str.split():
... | bigcode/self-oss-instruct-sc2-concepts |
def authz_query(authz, field='collection_id'):
"""Generate a search query filter from an authz object."""
# Hot-wire authorization entirely for admins.
if authz.is_admin:
return {'match_all': {}}
collections = authz.collections(authz.READ)
if not len(collections):
return {'match_none... | bigcode/self-oss-instruct-sc2-concepts |
def mul(a, b):
"""return the multiply of a and b"""
return a * b | bigcode/self-oss-instruct-sc2-concepts |
def _solve_expx_x_logx(tau, tol, kernel, ln, max_steps=10):
"""Solves the equation
log(pi/tau) = pi/2 * exp(x) - x - log(x)
approximately using Newton's method. The approximate solution is guaranteed
to overestimate.
"""
# Initial guess
x = kernel.log(2 / kernel.pi * ln(kernel.pi / tau))
... | bigcode/self-oss-instruct-sc2-concepts |
import json
def json_from_text(text_file):
"""JSON to dictionary from text file."""
tmp = open(text_file, "r")
data = json.load(tmp)
return data | bigcode/self-oss-instruct-sc2-concepts |
def student_ranking (student_scores, student_names):
"""Organize the student's rank, name, and grade information in ascending order.
:param student_scores: list of scores in descending order.
:param student_names: list of names in descending order by exam score.
:return: list of strings in format ["... | bigcode/self-oss-instruct-sc2-concepts |
def find_heuristic_position(child_partition):
"""
This function finds the starting position of different heuristics in a combined game payoff matrix.
:param child_partition:
:return:
"""
position = {}
i = 0
for method in child_partition:
position[method] = (i, i+child_partition[m... | bigcode/self-oss-instruct-sc2-concepts |
import time
import random
def _custom_libname(filetype, salt_len=2):
"""
Choose a custom name for library file
Format:
filetype: file extensiion
cur_time: current time
salt: salt_len number of digits
<cur_time>_<salt>.<filetype>
Args:
filety... | bigcode/self-oss-instruct-sc2-concepts |
def to_bytes(obj):
"""Convert object to bytes"""
if isinstance(obj, bytes):
return obj
if isinstance(obj, str):
return obj.encode('utf-8')
return str(obj).encode('utf-8') | bigcode/self-oss-instruct-sc2-concepts |
def IsPureVirtual(fname):
"""
Returns true if a header file is a pure virtual (no implementation)
Pure virtual header files are designated as such by the phrase "Pure virtual"
at the first line
Input:
fname - File name
"""
f = open(fname)
fl = f.readline()
f.close()
return f... | bigcode/self-oss-instruct-sc2-concepts |
def _compose2(f, g):
"""Compose 2 callables"""
return lambda *args, **kwargs: f(g(*args, **kwargs)) | bigcode/self-oss-instruct-sc2-concepts |
import hashlib
def get_md5_hash(value):
"""Returns the md5 hash object for the given value"""
return hashlib.md5(value.lower().encode("utf-8")) | bigcode/self-oss-instruct-sc2-concepts |
def cap(value: float, minimum: float, maximum: float) -> float:
"""Caps the value at given minumum and maximum.
Arguments:
value {float} -- The value being capped.
minimum {float} -- Smallest value.
maximum {float} -- Largest value.
Returns:
float -- The capped value or the... | bigcode/self-oss-instruct-sc2-concepts |
import re
def partial_path_match(path1, path2, kwarg_re=r'\{.*\}'):
"""Validates if path1 and path2 matches, ignoring any kwargs in the string.
We need this to ensure we can match Swagger patterns like:
/foo/{id}
against the observed pyramid path
/foo/1
:param path1: path of a url
... | bigcode/self-oss-instruct-sc2-concepts |
def compute_checksum(datafile):
"""Checksum is the sum of the differences between the
minimum and maximum value on each line of a tab delimited
data file.
"""
checksum = 0
with open(datafile, 'rb') as f:
for line in f:
# Remove trailing newline, split on tabs
nums... | bigcode/self-oss-instruct-sc2-concepts |
def comp_length(self):
"""Compute the length of the line
Parameters
----------
self : Segment
A Segment object
Returns
-------
length: float
lenght of the line [m]
Raises
------
PointSegmentError
Call Segment.check()
"""
self.check()
z1 =... | bigcode/self-oss-instruct-sc2-concepts |
def is_filtered(variant):
"""Returns True if variant has a non-PASS filter field, or False otherwise."""
return bool(variant.filter) and any(
f not in {'PASS', '.'} for f in variant.filter) | 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.