seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
import base64
def BinaryEncode(value):
"""If None, returns empty string. Otherwise, encode to a string."""
if value is None:
return ""
return base64.b64encode(value) | bigcode/self-oss-instruct-sc2-concepts |
import functools
def mobile_template(template):
"""
Mark a function as mobile-ready and pass a mobile template if MOBILE.
@mobile_template('a/{mobile/}/b.html')
def view(request, template=None):
...
if request.MOBILE=True the template will be 'a/mobile/b.html'.
if request.MOBILE=Fals... | bigcode/self-oss-instruct-sc2-concepts |
def build_indices(stream):
""" Parses the stream of logs and indexes it.
Args:
stream, list of string, format <metric_name>|<value>|<coma_separated_tags>
Returns:
pair of hashes,
first hash has the format {tag -> set([line_indices])}
second hash has the format {line_i... | bigcode/self-oss-instruct-sc2-concepts |
def get_crowd_selection(selection_count, selection_map):
"""
Figure out what the crowd actually selected
:param selection_count: number of responses per selection
:type selection_count: dict
:param selection_map: maps selections to output fields
:type selection_map: dict
:return: the respo... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Iterable
def has_intersection(left: Iterable[str], right: Iterable[str]) -> float:
"""Returns 1.0 if there is any overlap between the iterables, else 0.0."""
if len(set(left).intersection(right)) > 0:
return 1.0
return 0.0 | bigcode/self-oss-instruct-sc2-concepts |
def extract_HBS_learning_curves(runs):
"""
function to get the hyperband learning curves
This is an example function showing the interface to use the
HB_result.get_learning_curves method.
Parameters
----------
runs: list of HB_result.run objects
the performed runs for an unspecifi... | bigcode/self-oss-instruct-sc2-concepts |
def pick_and_pop(keys, d: dict) -> dict:
"""
pick all (key, val) pair from dictionary 'd' for all keys in 'keys'
Then, return a new dict with those picked (key, val) pair
"""
values = list(map(lambda key: d.pop(key), keys))
return dict(zip(keys, values)) | bigcode/self-oss-instruct-sc2-concepts |
def find_double_day(older_birthday, younger_birthday):
"""Takes 2 datetime.date objects representing different days, returns the date when one is
twice as old as the other
Precondition: older_birthday < younger_birthday"""
assert older_birthday < younger_birthday
difference = younger_birthday - olde... | bigcode/self-oss-instruct-sc2-concepts |
def fit_to_block_size(sequence, block_size, pad_token_id):
""" Adapt the source and target sequences' lengths to the block size.
If the sequence is shorter we append padding token to the right of the sequence.
Args:
sequence (list): sequence to be truncated to padded
block_size (int): lengt... | bigcode/self-oss-instruct-sc2-concepts |
import re
def get_integer(number: str) -> int:
"""
Fetches all numbers and returns an integer
Args:
number: A string of the identified number
Returns:
An integer value of number
"""
return int("".join(re.findall(r"\d+", number))) | bigcode/self-oss-instruct-sc2-concepts |
def proposed_cut_off_value(cut_off_value, length):
"""Proposes a cutoff-value if cut_off_value < 0 (=default)
Reynolds and Gutman (1988) recommend using a cut-off level of 3-5 for 50-60 paricipants
--> 4/55: relation cut-off/ladders
Args:
cut_off_value ([int]): [cutoff-value ]
length (... | bigcode/self-oss-instruct-sc2-concepts |
def get_query_statistics(tweets, sentiment_aggregate_list):
"""
Generates basic statistics for a given query set of Tweets.
:param tweets: A query set of Tweets
:param sentiment_aggregate_list: A list with number of positive, negative and neutral Tweets in the query set
:return: Dictionary with tot... | bigcode/self-oss-instruct-sc2-concepts |
def lines_that_start_with(string, fp):
"""Helper function to lines in a FORC data file that start with a given string
Inputs:
string: string to compare lines to
fp: file identifier
Outputs:
line: string corresponding to data line that meets the above conditions
"""
return [line fo... | bigcode/self-oss-instruct-sc2-concepts |
def ignore_ctrlc(method):
"""Decorator to make a ProjectKey command ignore Ctrl-C.
- For a commands that runs programs that want to handle
Ctrl-C themselves - ipython for instance."""
method.ignore_ctrlc = True
return method | bigcode/self-oss-instruct-sc2-concepts |
def naive_matrix_multiplication_lists(a, b):
"""
Uses nested loops to calculate AB
:param a: An MxN matrix of numbers.
:param b: An NxP matrix of numbers.
:return: An MxP matrix of numbers which is the product: AB.
"""
M = len(a)
N = len(a[0])
if len(b) != N:
raise ValueError... | bigcode/self-oss-instruct-sc2-concepts |
def overrides_method(method_name, obj, base):
"""
Return True if the named base class method is overridden by obj.
Parameters
----------
method_name : str
Name of the method to search for.
obj : object
An object that is assumed to inherit from base.
base : class
The ... | bigcode/self-oss-instruct-sc2-concepts |
import requests
def create_account(base_url: str, email: str, password: str, username: str,
firstname: str, lastname: str, secure: bool):
"""
Create an account with the server
:param base_url: base URL of server
:param email: email
:param password: password
:param username: ... | bigcode/self-oss-instruct-sc2-concepts |
def split(path: str):
"""Split path into (head, tail) tuple. Tail is the last path component. Head is all the rest."""
if path == "":
return "", ""
r = path.rsplit("/", 1)
if len(r) == 1:
return "", path
head = "/" if not r[0] else r[0]
return head, r[1] | bigcode/self-oss-instruct-sc2-concepts |
import io
import hashlib
def get_file_hash(filepath, algorithm):
"""
Get hash of a file.
:param filepath: the path to the file
:type filepath: str
:param algorithm: the desired hashing algorithm
:type algorithm: str
:return: Hash of the file in hex form.
:rtype: str
"""
file =... | bigcode/self-oss-instruct-sc2-concepts |
def GetAlleleString(allele):
"""Get string representation of allele
If it is a sequence, return upper case sequence
If _SV type, return string representation
Parameters
----------
allele : ALT allele from vcf.Record
Returns
-------
str_allele : str
String representa... | bigcode/self-oss-instruct-sc2-concepts |
def enum_metaclass(enum_param, return_name=False, start=0):
"""
Returns a ``type`` subclass that may be used as a metaclass for
an enum.
Paremeters:
:enum_param: the name of class attribute that defines enum values.
The metaclass will add a class attribute for each value i... | bigcode/self-oss-instruct-sc2-concepts |
def readfile(file_dir):
""" readfile(file_dir:str)
Returns the content of a file in an array.
"""
f = open(file_dir)
content = [line.rstrip('\n') for line in f]
return content | bigcode/self-oss-instruct-sc2-concepts |
def isAbundant(x):
"""Returns whether or not the given number x is abundant.
A number is considered to be abundant if the sum of its factors
(aside from the number) is greater than the number itself.
Example: 12 is abundant since 1+2+3+4+6 = 16 > 12.
However, a number like 15, where the sum of the... | bigcode/self-oss-instruct-sc2-concepts |
def strip_and_get(val, fallback=""):
"""
Return the enclosing text or provided fallback value
:param val: item to get text and strip whitespace
:param fallback: fallback when val is None
:return: stripped text value
"""
if val:
return val.text.strip(' \t\n\r')
else:
retur... | bigcode/self-oss-instruct-sc2-concepts |
import binascii
def hexlify(x):
"""Return the hexadecimal representation of the binary data. Decode from ASCII to UTF-8."""
return binascii.hexlify(x).decode('ascii') | bigcode/self-oss-instruct-sc2-concepts |
def solve_for_scale(a_scale, a_n_bits, b_scale, b_n_bits, y_n_bits):
""" Finds the scale factor for the following case:
y = a * b
We know the scale factor and the number of bits of a, as well as b. We also know the number of
bits for y. This function computes the resulting scale factor for y
... | bigcode/self-oss-instruct-sc2-concepts |
def isbit(integer, nth_bit):
"""Tests if nth bit (0,1,2..) is on for the input number.
Args:
integer (int): A number.
nth_bit (int): Investigated bit.
Returns:
bool: True if set, otherwise False.
Raises:
ValueError: negative bit as input.
Examples:
>>> isb... | bigcode/self-oss-instruct-sc2-concepts |
import string
import re
def remove_punctuation(text):
"""
Remove punctiation from piece of text
"""
text = [t for t in text if t not in string.punctuation]
text = [t for t in text if t not in ['...']]
text = [re.sub(r'(?:\@|https?\://)\S+', '', (t)) for t in text]
# text = [re.sub(r'[^\w\s... | bigcode/self-oss-instruct-sc2-concepts |
def clusters_from_blast_uc_file(uc_lines, otu_id_field=1):
""" Parses out hit/miss sequences from usearch blast uc file
All lines should be 'H'it or 'N'o hit. Returns a dict of OTU ids: sequence
labels of the hits, and a list of all sequence labels that miss.
uc_lines = open file object of uc file
... | bigcode/self-oss-instruct-sc2-concepts |
def get_tablename(model):
"""return the model's table name"""
return model._m.table_name | bigcode/self-oss-instruct-sc2-concepts |
def print_attrs(attr, celebA_dataset):
"""
human-readable format for CelebA attributes vector
"""
legible = ''
for i, a in enumerate(list(attr)):
if a == 1:
legible += celebA_dataset.attr_names[i] + ", "
return legible | bigcode/self-oss-instruct-sc2-concepts |
def calc_t_int(n_group, t_frame, n_frame, n_skip):
"""Calculates the integration time.
Parameters
----------
n_group : int
Groups per integration.
t_frame : float
Frame time (in seconds).
n_frame : int
Frames per group -- always 1 except maybe brown dwarves.
n_sk... | bigcode/self-oss-instruct-sc2-concepts |
def filter_blast_result(alignment, record):
"""
The binding pocket of the target structure should be covered by identical residues in the test sequence. We
don't know where the target-sequence binding pocket is located. To increase the chances that the test sequence
and target sequence have identical bi... | bigcode/self-oss-instruct-sc2-concepts |
def calculate_integration_error(
max_forth_derivative: float, low: float, high: float, length: int) -> float:
"""Find integration error if Simpson method is used.
Args:
max_forth_derivative: precalculated value.
low: left range boundary.
high: right range boundary.
lengt... | bigcode/self-oss-instruct-sc2-concepts |
def defined_submodule(arr):
"""
Check if model uses submodules
"""
return any([el.endswith('_module]') for el in arr]) | bigcode/self-oss-instruct-sc2-concepts |
import math
def calc_triangle_area(a,b,c):
"""
使用海伦公式计算三角形面积
a、b、c为三角形边长
:return: 三角形面积
"""
p=(a+b+c)/2
return math.sqrt(p*(p-a)*(p-b)*(p-c)) | bigcode/self-oss-instruct-sc2-concepts |
def im2mat(img):
"""Converts and image to matrix (one pixel per line)"""
return img.reshape((img.shape[0] * img.shape[1], img.shape[2])) | bigcode/self-oss-instruct-sc2-concepts |
import functools
import time
def simple_timer(func):
"""Simple decorator to give a rough estimate of calculation time. Thank you to RealPython for
the help -- https://realpython.com/primer-on-python-decorators/"""
@functools.wraps(func)
def wrapper(*args, **kwargs):
start = time.perf_counter()... | bigcode/self-oss-instruct-sc2-concepts |
import sqlite3
def build_type_dict_from_row(row: sqlite3.Row):
"""This function takes a row from a sqlite3 query, and returns a dict of damage modifers by type."""
type_dict = {'type': row[0], "effectiveness": {}}
for i in range(len(row.keys())):
if i == 0:
continue
else:
... | bigcode/self-oss-instruct-sc2-concepts |
def _iso_datetime(value):
"""
If value appears to be something datetime-like, return it in ISO format.
Otherwise, return None.
"""
if hasattr(value, 'strftime'):
if hasattr(value, 'hour'):
return value.isoformat()
else:
return '%sT00:00:00' % value.isoformat(... | bigcode/self-oss-instruct-sc2-concepts |
import click
def prompt_password(ctx, param, use_password): # pylint: disable=W0613
"""Prompt for password."""
if use_password:
mysql_password = ctx.params.get("mysql_password")
if not mysql_password:
mysql_password = click.prompt("MySQL password", hide_input=True)
return... | bigcode/self-oss-instruct-sc2-concepts |
def parse_and_validate_longitude(request):
"""Extract and Check the validity of longitude.
Args:
request: HTTP request.
Returns:
longitude(float) if valid.
Raises:
ValueError: if longitude is not float, or outside range [-180, 180].
"""
lon = float(request.rel_url.quer... | bigcode/self-oss-instruct-sc2-concepts |
def calculate_outlier_bounds(df, column_name):
"""
Calculates outlier bounds based on interquartile range of distribution of values in column 'column_name'
from data set in data frame 'df'.
:param df: data frame containing data to be analyzed
:param column_name: column name to analyze
:return: d... | bigcode/self-oss-instruct-sc2-concepts |
import types
def get_function(callable_):
"""If given a method, returns its function object; otherwise a no-op."""
if isinstance(callable_, types.MethodType):
return callable_.__func__
return callable_ | bigcode/self-oss-instruct-sc2-concepts |
import re
def normalize_underscore_case(name):
"""Normalize an underscore-separated descriptor to something more readable.
i.e. 'NAGIOS_SERVER' becomes 'Nagios Server', and 'host_components' becomes
'Host Components'
"""
normalized = name.lower()
normalized = re.sub(r'_(\w)',
... | bigcode/self-oss-instruct-sc2-concepts |
import math
def int_log(x: float, base: float = math.e) -> int:
"""Finds the nearest integer to ``log(x, base)``.
Args:
x: The number whose logarithm will be found.
base: The numeric base of the logarithm.
Returns:
The result of rounding ``log(x, base)`` to the nearest integer.
... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Dict
from typing import Optional
def get_new_name(attrs: Dict[str, str],
mark_name: str = '',
name_map: Optional[Dict[str, str]] = None) -> str:
"""Get new name for a node.
Args:
attrs (Dict[str, str]): A dict contains attributes of an ONNX node.
... | bigcode/self-oss-instruct-sc2-concepts |
import getpass
def get_password(args):
"""Set the password or getpass it in a secure way"""
if not args.password:
password = getpass.getpass(prompt="Password for {} @ {}: ".format(args.username, args.server))
else:
password = args.password
return args, password | bigcode/self-oss-instruct-sc2-concepts |
def join(*args):
"""Forms join instruction."""
inputs = [arg[0] for arg in args]
return {
'cmd': 'join',
'inputs': inputs,
'args': args,
} | bigcode/self-oss-instruct-sc2-concepts |
def in_right_closed_range(s, min_val, max_val):
"""
Check if a value lies in the right-closed interval (min_val, max_val].
:param s: Value to check.
:param min_val: Lower boundary of the interval.
:param max_val: Upper boundary of the interval.
:return: True/False whether or not the value lies ... | bigcode/self-oss-instruct-sc2-concepts |
def find_cheapest_fuel_use(positions: list[int]) -> int:
"""
Returns the amount of fuel used for the cheapest
alignment position.
Args:
positions (list[int]): The list of starting positions.
Returns:
int: Fuel usage.
"""
positions = sorted(positions)
median = positions[... | bigcode/self-oss-instruct-sc2-concepts |
def display_body_parts(image, image_draw, coordinates, image_height=1024, image_width=1024, marker_radius=5):
"""
Draw markers on predicted body part locations.
Args:
image: PIL Image
The loaded image the coordinate predictions are inferred for
image_draw: PIL ImageDraw m... | bigcode/self-oss-instruct-sc2-concepts |
def end_text_with_single_terminating_newline_character(text: str) -> str:
"""Ensure the text ends with a single terminating newline character."""
return text.rstrip() + '\n' | bigcode/self-oss-instruct-sc2-concepts |
import math
def truncate(number, digits) -> float:
""" Truncates number to a specified number of digits
Args:
number (float): Number to truncate
digits (int): No. of digits to truncate to
Returns:
Truncated number (float)
"""
stepper = 10.0 ** digits
return math.trunc... | bigcode/self-oss-instruct-sc2-concepts |
def _asciizToStr(s):
"""Transform a null-terminated string of any length into a Python str.
Returns a normal Python str that has been terminated.
"""
i = s.find('\0')
if i > -1:
s = s[0:i]
return s | bigcode/self-oss-instruct-sc2-concepts |
from typing import Any
import pickle
def load_file_from_disk(loc_folder: str, filename: str) -> Any:
"""Loads a file that was previously saved to the disk.
:param loc_folder: The location of the containing folder.
:param filename: The name of the file to be loaded.
:return: The contents of the loaded... | bigcode/self-oss-instruct-sc2-concepts |
def scientific_notation(value: float | str, precision: int = 2) -> str:
"""Return number in string scientific notation z.wq x 10ⁿ.
Examples:
>>> scientific_notation(float(0.3))
'3.00 x 10⁻¹'
>>> scientific_notation(int(500))
'5.00 x 10²'
>>> scientific_notation(-1000)
... | bigcode/self-oss-instruct-sc2-concepts |
def fpr(fp: int, tn: int) -> float:
"""False Positive Rate computed from false positives and true negatives."""
return fp / (fp + tn) if fp + tn else 0.0 | bigcode/self-oss-instruct-sc2-concepts |
def make_row(table, row, model_name):
"""
Parameters:
-----------
table : `collections.defaultdict`
The dictionary to fill.
row : `pandas.DataFrame`
The dataframe to get the data from.
model_name : `str`
The model name.
Returns:
--------
table : `collecti... | bigcode/self-oss-instruct-sc2-concepts |
def ascii64_paths(tnum):
"""
Return components of the path to the data for trigger `tnum`, both at
the COSSC FTP site and locally: (group, fname, remote).
group name of the group directory containing the trigger directory
rfname name of the remote ASCII data file, "cat64ms.<tnum>"
r... | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
import itertools
def generate_partitions(num_elements: int, num_parts: int) -> List[List[int]]:
"""Generates partitions of num_elements into num_parts nonnegative parts.
Args:
num_elements: The number of things to permute (a nonnegative integer).
num_parts: The number of groups to... | bigcode/self-oss-instruct-sc2-concepts |
def is_state_error(state_meta):
"""
Determines if the state resulted in an error.
"""
return not state_meta['result'] | bigcode/self-oss-instruct-sc2-concepts |
def contact_sequence(data, pIDs):
"""
Given a pd.DataFrame with variables ['gID', 'pID', 'begin', 'end'], generate a contact sequence of events (j, i, t) where j is the group member being interrupted, i is the group member doing the interrupting, and t is the start time of the interruptive speech. Ignores non-i... | bigcode/self-oss-instruct-sc2-concepts |
import time
import copy
import torch
def train_model(nb_epoch, dataloaders, model, opt, criterion, device,
scheduler=None):
"""
Function to train a model.
Args:
nb_epoch: number of epoch to train
train_dsld: dataset loader for training
model: model to optimize
... | bigcode/self-oss-instruct-sc2-concepts |
def split_param_filter_index1(s):
"""
Split a parameter name into the <string><number> components
where <string> is the parameter name and <number> is the filter
index (1-based). If there is no number at the end for a filter
index, then return None for the second argument.
Returns
---------... | bigcode/self-oss-instruct-sc2-concepts |
def get_diffs(pulse_times, pulses):
"""
Returns a list of time differences between the pulse times given,
corresponding 1 - for - 1
*** PARAMS ***
pulse_time (list of strings): list of strings containing the exact time of the pulse.
pulses (list of floats): list of floats of the exact time (... | bigcode/self-oss-instruct-sc2-concepts |
def get_maxdepth(input_table_A,input_table_B):
"""Get maximum depth between tables"""
#gaps and overlaps
maxlist=[]
a= input_table_A['todepth'].unique().tolist()
maxlist.append(a[-1])
b= input_table_B['todepth'].unique().tolist()
maxlist.append(b[-1])
maxl=float(max(maxlist))
return ... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def concat_without_padding(text_idx, cand_idx, use_cuda, null_idx=0):
"""
Concatenate two right padded tensors and move padding to the right.
For example,
if text_idx = [[1, 2, 3, 4, 0, 0 ]]
and cand_idx = [[5, 6, 7, 8, 0, 0 ]]:
Then result = (tokens, segments) where
... | bigcode/self-oss-instruct-sc2-concepts |
def get_hps(data):
"""
Get the name of all columns corresponding to hyperparameters
"""
return [c for c in data.columns if c.startswith("hp.")] | bigcode/self-oss-instruct-sc2-concepts |
def compareDicts(dict1, dict2):
""" Compare two dictionaries, returning sets containing keys from
dict1 difference dict2, dict2 difference dict1, and shared keys with
non-equivalent values, respectively.
Parameters
----------
dict1 : dict
dict2 : dict
Returns
-------
set, set, ... | bigcode/self-oss-instruct-sc2-concepts |
def API_fatal(description):
"""Create an API fatal error message."""
return {"status": "fatal", "error": description} | bigcode/self-oss-instruct-sc2-concepts |
def power(a, n: int):
"""Return `a` to the n-th power, uses exponentiation by squaring i.e square and multiply
"""
# Shortcuts are evaluated here to avoid code duplication
if a == 0:
if n > 0:
return 0 # 0^n = 0 for n > 0
if n == 0:
return 1 # a^0 = 1 (0^0 = 1 is a co... | bigcode/self-oss-instruct-sc2-concepts |
import unicodedata
async def _get_all_intents(skills):
"""Get all skill intents and concatenate into a single markdown string."""
intents = [skill["intents"] for skill in skills if skill["intents"] is not None]
if not intents:
return None
intents = "\n\n".join(intents)
return unicodedata.n... | bigcode/self-oss-instruct-sc2-concepts |
def total_gross_income(responses, derived):
""" Return the total gross income of both claimants """
try:
claimant_1 = float(responses.get('annual_gross_income', 0))
except ValueError:
claimant_1 = 0
try:
claimant_2 = float(responses.get('spouse_annual_gross_income', 0))
exc... | bigcode/self-oss-instruct-sc2-concepts |
def gross_count(spec, c1, c2):
"""Returns total number of counts in a spectrum between two channels"""
if c1 > c2:
raise ValueError("c1 must be less than c2")
if c1 < 0:
raise ValueError("c1 must be positive number above 0")
if c2 > max(spec.channels):
raise ValueError("c2 must ... | bigcode/self-oss-instruct-sc2-concepts |
def asbool(value, true=(b'true', u'true'), false=(b'false', u'false')):
"""Return string as bool if possible, else raise TypeError.
>>> asbool(b' False ')
False
"""
value = value.strip().lower()
if value in true: # might raise UnicodeWarning/BytesWarning
return True
if value in fa... | bigcode/self-oss-instruct-sc2-concepts |
import re
import copy
def _getZoneData(line):
""" Extract TecPlot formatted zone data from a line, return as two lists of
keys and matching values.
Attributes
----------
* ``line`` (`string`): string representation of a line in a TecPlot file
Returns
----------
* `list` with all the names of zone properti... | bigcode/self-oss-instruct-sc2-concepts |
import hashlib
def get_hash_string_of_numpy_array(array):
"""
Returns a 32 character long string that is a deterministic hash of a numpy array's data.
"""
return hashlib.md5(array.data.tobytes()).hexdigest() | bigcode/self-oss-instruct-sc2-concepts |
def maskAngLT452(image):
"""
mask out angles >= 45.23993
Parameters
----------
image : ee.Image
image to apply the border noise masking
Returns
-------
ee.Image
Masked image
"""
ang = image.select(['angle'])
return image.updateMask(ang.lt(45.23993)).set('sy... | bigcode/self-oss-instruct-sc2-concepts |
def prettyPrintResults(evaluationResults):
"""prettyPrintResults returns a string formatting the results of a simulation evaluation result"""
output = ""
for er in evaluationResults:
message = (
f"Evaluated Action Name: {er['EvalActionName']}\n"
f"\tEvaluated Resource name: {... | bigcode/self-oss-instruct-sc2-concepts |
def plot_wrapper(self, func, *args, cmap=None, values=None, **kwargs):
"""
Calls `~proplot.axes.Axes.parametric` if the `cmap` argument was supplied,
otherwise calls `~matplotlib.axes.Axes.plot`. Wraps %(methods)s.
Parameters
----------
*args : (y,), (x, y), or (x, y, fmt)
Passed to `~m... | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
def max_profit(prices: List[int]) -> int:
"""
Find the maximum profit that can be made from buying and selling a stock once
"""
if prices is None or len(prices) < 2:
return 0
min_price = prices[0]
current_max_profit = 0
for price in prices:
if pric... | bigcode/self-oss-instruct-sc2-concepts |
def element_to_apparent(element):
"""Create an apparent element from an element.
Parameters
----------
element
The element.
Returns
-------
A tuple (ElementType, Direction).
"""
return (element.element_type, element.direction) | bigcode/self-oss-instruct-sc2-concepts |
def _fmt_string(array, float_format="{}"):
"""
makes a formatting string for a rec-array;
given a desired float_format.
Parameters
----------
array : np.recarray
float_format : str
formatter for floating point variable
Returns
-------
fmt_string : str
formatting... | bigcode/self-oss-instruct-sc2-concepts |
def merge(left, right):
"""Merges two sorted sublists into a single sorted list."""
ret = []
li = ri =0
while li < len(left) and ri < len(right):
if left[li] <= right[ri]:
ret.append(left[li])
li += 1
else:
ret.append(right[ri])
ri += 1
... | bigcode/self-oss-instruct-sc2-concepts |
def matrix_max(matrix): # SYFPEITHI NORMALIZATION
"""Returns the maximum attainable score for a pssm"""
return sum([ max(value.values()) for _, value in matrix.items() ]) | bigcode/self-oss-instruct-sc2-concepts |
def padding(corpus, logger=None):
"""
Performs padding on the already tokenized documents
Args:
corpus (list): A list of strings where elements are the tokens from your document.
logger (Logger):
Returns:
A list of strings where elements are all at equal length
"""
ne... | bigcode/self-oss-instruct-sc2-concepts |
import pickle
def top_n_bigrams(pkl_file_name, N, shift=0):
"""
Returns a dictionary of form {bigram:rank} of top N bigrams from a pickle
file which has a Counter object generated by stats.py
Args:
pkl_file_name (str): Name of pickle file
N (int): The number of bigrams to get
... | bigcode/self-oss-instruct-sc2-concepts |
def list_is_nested(input_list: list) -> bool:
"""This function checks whether the input_list is nested (i.e. it is a list of lists).
Args:
input_list (list): the input list
Returns:
is_nested (bool): True if list is nested, False if it isn’t
"""
is_nested = any(isinstance(i, list) fo... | bigcode/self-oss-instruct-sc2-concepts |
def recursive_fold(left, right):
"""
Recursively folds (reduces) two records.
Parameters
----------
left : dict
The "left-hand", or current, record.
right : dict
The "right-hand", or next, record.
Returns
-------
left : dict
The folded (reduced) record.
"... | bigcode/self-oss-instruct-sc2-concepts |
def load_labels_file(file_path):
"""
Reads the 'classes.txt' file and returns a class dictionary.
Args:
file_path: Full path to the 'classes.txt' file.
Returns:
classes: Dict in the format: 'classes[class_name] = class_id'.
"""
classes = {}
with open(file_path, 'r') as file:
... | bigcode/self-oss-instruct-sc2-concepts |
def epsilon_schedule(eps: float, n_frames: int) -> float:
"""
Epsilon is annealed linearly from 1 to 0.1 over the n_frames
"""
change = (1 - 0.05) / n_frames
eps -= change
eps = max(eps, 0.05)
return eps | bigcode/self-oss-instruct-sc2-concepts |
def gcdr(a, b):
"""Recursive Greatest Common Divisor algorithm."""
if b == 0:
return a
if a<b:
a,b = b,a
print(a,b)
return gcdr(b, a%b) | bigcode/self-oss-instruct-sc2-concepts |
def get_empty_marker_error(marker_type):
"""
Generate error message for empty marker.
"""
msg = (
"no configuration file is specified in "
"``@pytest.mark.gdeploy_config_{0}`` decorator "
"of this test case, please add at least one "
"configuration file file name as a par... | bigcode/self-oss-instruct-sc2-concepts |
def find_value(keys, d, create=False):
"""Return a possibly deeply buried {key, value} with all parent keys.
Given:
keys = ['a', 'b']
d = {'a': {'b': 1, 'c': 3}, 'b': 4}
returns: 1
"""
default = {} if create else None
value = d.get(keys[0], default)
if len(keys) > 1 and ty... | bigcode/self-oss-instruct-sc2-concepts |
def convertir(hora: str) -> str:
"""Convierte una hora en notación de 24 horas a 12 horas.
:param hora: Hora a convertir
:hora type: str
:return: Hora en notación de 12 horas
:rtype: str
"""
hora_24 = int(hora[:2])
hora_12 = 12 if hora_24 % 12 == 0 else hora_24 % 12
return f"{hora_1... | bigcode/self-oss-instruct-sc2-concepts |
def path_concordance_jspecies(path_fixtures_base):
"""Path to JSpecies analysis output."""
return path_fixtures_base / "concordance/jspecies_output.tab" | bigcode/self-oss-instruct-sc2-concepts |
def normal_from_ineq(s_ineq):
"""
Get the normal stored in the phase surface inequalitie vector
:param s_ineq: A phase data surface vector (see SL1M output doc)
:return: The surface normal, as an array of size 3
"""
return s_ineq[2] | bigcode/self-oss-instruct-sc2-concepts |
def _get_from_onclick(node, index):
"""Private function to grab a value in the "`onclick`" attribute.
Grabs the value in the specified index of the "`onclick`" attribute
of a selectolax `Node`.
Args:
node (:class:`Node`): A `Node` containing the "`onclick`" attribute.
index (:obj:`int`... | bigcode/self-oss-instruct-sc2-concepts |
import typing
def is_basic_iterable(obj: typing.Any) -> bool:
"""Checks if an object is a basic iterable.
By basic iterable we want to mean objects that are iterable and from a
basic type.
:param obj: Object to be analysed.
:return: True if obj is a basic iterable (see list below). False otherwi... | 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.