seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
def _check_pixel(tup):
"""Check if a pixel is black, supports RGBA"""
return tup[0] == 0 and tup[1] == 0 and tup[2] == 0 | bigcode/self-oss-instruct-sc2-concepts |
def deprecated_argument_lookup(new_name, new_value, old_name, old_value):
"""Looks up deprecated argument name and ensures both are not used.
Args:
new_name: new name of argument
new_value: value of new argument (or None if not used)
old_name: old name of argument
old_value: value of old argument (or None if not used)
Returns:
The effective argument that should be used.
Raises:
ValueError: if new_value and old_value are both non-null
"""
if old_value is not None:
if new_value is not None:
raise ValueError("Cannot specify both '%s' and '%s'" %
(old_name, new_name))
return old_value
return new_value | bigcode/self-oss-instruct-sc2-concepts |
import torch
def total_variation(x):
"""
Total Variation Loss.
"""
return torch.sum(torch.abs(x[:, :, :, :-1] - x[:, :, :, 1:])
) + torch.sum(torch.abs(x[:, :, :-1, :] - x[:, :, 1:, :])) | bigcode/self-oss-instruct-sc2-concepts |
def match_asset(asset_name, goos, goarch):
"""
Compate asset name with GOOS and GOARCH.
Return True if matched.
"""
asset_name = asset_name.lower()
goarch = {
"386": ["386"],
"amd64": ["amd64", "x86_64"]
}[goarch]
match_goos = goos in asset_name
match_goarch = any([word in asset_name for word in goarch])
return match_goos and match_goarch | bigcode/self-oss-instruct-sc2-concepts |
def create_fill_row_string(slot1: str, slot2: str, gap_space: int):
""" creates a gap with variable spaces according to the length of the slot string """
return '|' + slot1 + (' ' * (gap_space-(2 + len(slot1) + len(slot2)))) + slot2 + '|' | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
from typing import Any
def list_union(a: List[Any], b: List[Any]) -> List[Any]:
"""Return union of two lists maintaining order of the first list."""
return a + [x for x in b if x not in a] | bigcode/self-oss-instruct-sc2-concepts |
def sum_two(num_1, num_2):
"""
This function returns the sum of two numbers
"""
return num_1 + num_2 | bigcode/self-oss-instruct-sc2-concepts |
def fix_config_list(config_list):
"""
transforms a list of the form ['a, b'] to ['a', 'b']
"""
if not config_list:
return []
t = config_list
item = t[0]
list_items = item.split(',')
return [nr.strip() for nr in list_items] | bigcode/self-oss-instruct-sc2-concepts |
def collabel_2_index(label):
"""Convert a column label into a column index (based at 0), e.g., 'A'-> 1,
'B' -> 2, ..., 'AA' -> 27, etc.
Returns -1 if the given labe is not composed only of upper case letters A-Z.
Parameters
----------
label : string
Column label (expected to be composed of upper case letters A-Z)
Returns
-------
int
"""
# The following code is adopted from
# https://stackoverflow.com/questions/7261936/convert-an-excel-or-spreadsheet-column-letter-to-its-number-in-pythonic-fashion
num = 0
for c in label:
if ord('A') <= ord(c) <= ord('Z'):
num = num * 26 + (ord(c) - ord('A')) + 1
else:
return -1
return num | bigcode/self-oss-instruct-sc2-concepts |
def calculate_total_votes(poll):
"""Calculate the total number of votes of a poll."""
total = 0
for vote in poll.votes:
total += vote.vote_count
return total | bigcode/self-oss-instruct-sc2-concepts |
def __none_mult(x, y):
"""PRIVATE FUNCTION, If x or y is None return None, else return x * y"""
if x is not None and y is not None:
return x * y
return None | bigcode/self-oss-instruct-sc2-concepts |
def get_rescale_ratio(image, target):
"""Gets the required ratio to rescale an image to a target resolution
:param image: An image to resize.
:param target: The target resolution to resize to.
:type image: Image
:type target: int
:return: The min of the ratio between the target resolution and the image's smallest dimension, and 1.
:rtype: float
"""
width = image.width
height = image.height
if width <= target or height <= target:
return 1
ratio = target / min(width, height)
return ratio | bigcode/self-oss-instruct-sc2-concepts |
def option_name(path, delimiter="--"):
"""
Returns a cli option name from attribute path
**Arguments**
- path (`list`): attribute path
- delimiter (`str`): delimiter for nested attributes
**Returns**
cli option name (`str`)
"""
return "--{}".format(delimiter.join(path).replace("_", "-")) | bigcode/self-oss-instruct-sc2-concepts |
def ledaLines(lines):
"""Filter sequence of lines to keep only the relevant ones for LEDA.GRAPH"""
def relevant(line):
return line and not line.startswith('#')
return filter(relevant, lines) | bigcode/self-oss-instruct-sc2-concepts |
import colorsys
def rgb_to_hls(r, g ,b):
"""Convert R(0-255) G(0-255) B(0-255) to H(0-360) L(0-255) S(0-255).
"""
rgb = [x / 255.0 for x in (r, g, b)]
h, s, v = colorsys.rgb_to_hls(*rgb)
return (h * 360, s * 255, v * 255) | bigcode/self-oss-instruct-sc2-concepts |
def int_or_float(x):
"""Return `x` as `int` if possible, or as `float` otherwise."""
x = float(x)
if x.is_integer():
return int(x)
return x | bigcode/self-oss-instruct-sc2-concepts |
def aggregate_group(df, aggregate_me, name="aggregated_group"):
"""
Aggregates several rows into one row.
df: str
aggregate_me: list.
One or more values from the new_var column may be given as a list.
This function takes those values (rows), aggregates them, and
returns one row that is the sum.
Ex: commute mode table provides counts for various commute modes.
One might want to combine public transit and biking commute modes together.
name: str. This is the name of the new aggregated group.
Ex: The sum of public transit and biking commute modes
will be named "sustainable_transport".
"""
df = (
df.assign(
new_var2=df.apply(
lambda row: name
if any(x in row.new_var for x in aggregate_me)
else row.new_var,
axis=1,
)
)
.groupby(["GEOID", "new_var2"])
.agg({"num": "sum"})
.reset_index()
.rename(columns={"new_var2": "new_var"})
)
return df | bigcode/self-oss-instruct-sc2-concepts |
import re
def remove_relative_imports(source) -> str:
"""
Remove all the relative imports from the source code
:param source:
:return:
"""
return re.sub(r"^#include \"(.+)\"$", "", source, flags=re.MULTILINE) | bigcode/self-oss-instruct-sc2-concepts |
def get_table_names(connection):
"""
Gets all table names in the specified database file.
:param connection: Connection to the DB file.
:return: List of table names
"""
connection.execute("SELECT name FROM sqlite_master WHERE type='table';")
tables = []
for table in connection.fetchall():
tables.append(table[0])
return tables | bigcode/self-oss-instruct-sc2-concepts |
import itertools
def binary_cartesian_product(nb_bits: int):
"""
Compute binary possibilities of an nb_bits variable.
"""
ranges = [range(0, 2) for i in range(nb_bits)]
# In possibilities, we compute the nb_bits cartesian product of set([0, 1]}
possibilities = list()
for xs in itertools.product(*ranges):
possibilities.append(tuple([*xs]))
return possibilities | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
def brute_force(num_lst: List[int], pivot: int) -> List[int]:
"""
Given a list and a pivot, sort so that all elements to the left of the pivot(s) are less than the pivot
and all elements to the right of the pivot(s) are greater than the pivot. Runs in O(3n) but not constant storage.
:param num_lst: the list of numbers
:param pivot: the pivot element
:return: a list as described above
>>> brute_force([10, 5, 3, 11, 10, 2, 4, 12], 10)
[5, 3, 2, 4, 10, 10, 11, 12]
"""
return [x for x in num_lst if x < pivot] + [x for x in num_lst if x == pivot] + [x for x in num_lst if x > pivot] | bigcode/self-oss-instruct-sc2-concepts |
def degree(a):
""" returns the degree of the atom """
return a.GetDegree() | bigcode/self-oss-instruct-sc2-concepts |
import decimal
def format_value(value):
"""Returns the given value rounded to one decimal place if it is a
decimal, or integer if it is an integer.
"""
value = decimal.Decimal(str(value))
if int(value) == value:
return int(value)
# On Python 3, an explicit cast to float is required
return float(round(value, 1)) | bigcode/self-oss-instruct-sc2-concepts |
import copy
def exclude_meta(src_obj):
"""return copy of src_obj, without path, img, full_path, and objects keys"""
obj = copy.copy(src_obj)
for key in ['path', 'img', 'full_path', 'objects']:
if key in obj:
del obj[key]
return obj | bigcode/self-oss-instruct-sc2-concepts |
def part1(input_lines):
"""
The captcha requires you to review a sequence of digits (your puzzle input) and find
the sum of all digits that match the next digit in the list. The list is circular,
so the digit after the last digit is the first digit in the list.
For example:
- 1122 produces a sum of 3 (1 + 2) because the first digit (1) matches the second digit
and the third digit (2) matches the fourth digit.
- 1111 produces 4 because each digit (all 1) matches the next.
- 1234 produces 0 because no digit matches the next.
- 91212129 produces 9 because the only digit that matches the next one is the last digit, 9.
"""
captcha = input_lines[0]
captcha = captcha + captcha[0]
return sum([
int(captcha[i]) for i in range(1, len(captcha))
if captcha[i] == captcha[i - 1]
]) | bigcode/self-oss-instruct-sc2-concepts |
import importlib
def import_and_get_task(task_path):
"""
Given a modular path to a function, import that module
and return the function.
"""
module, function = task_path.rsplit(".", 1)
app_module = importlib.import_module(module)
app_function = getattr(app_module, function)
return app_function | bigcode/self-oss-instruct-sc2-concepts |
def MDD(series):
"""Maximum Drawdown (MDD) is an indicator of downside
risk over a specified time period.
MDD = (TroughValue – PeakValue) ÷ PeakValue
"""
trough = min(series)
peak = max(series)
mdd = (peak - trough) / peak
return round(mdd, 3) | bigcode/self-oss-instruct-sc2-concepts |
def named_value(dictionary):
"""
Gets the name and value of a dict with a single key (for example SenzaInfo
parameters or Senza Components)
"""
return next(iter(dictionary.items())) | bigcode/self-oss-instruct-sc2-concepts |
def _get_conjuncts(tok):
"""
Return conjunct dependents of the leftmost conjunct in a coordinated phrase,
e.g. "Burton, [Dan], and [Josh] ...".
"""
return [right for right in tok.rights
if right.dep_ == 'conj'] | bigcode/self-oss-instruct-sc2-concepts |
def last_common_item(xs, ys):
"""Search for index of last common item in two lists."""
max_i = min(len(xs), len(ys)) - 1
for i, (x, y) in enumerate(zip(xs, ys)):
if x == y and (i == max_i or xs[i+1] != ys[i+1]):
return i
return -1 | bigcode/self-oss-instruct-sc2-concepts |
def gen_anytext(*args):
"""
Convenience function to create bag of words for anytext property
"""
bag = []
for term in args:
if term is not None:
if isinstance(term, list):
for term2 in term:
if term2 is not None:
bag.append(term2)
else:
bag.append(term)
return ' '.join(bag) | bigcode/self-oss-instruct-sc2-concepts |
def bool_on_off(value):
"""Convert True/False to on/off correspondingly."""
return 'on' if value else 'off' | bigcode/self-oss-instruct-sc2-concepts |
def getStereoPair(pipeline, monoLeft, monoRight):
"""
Generates a stereo node. Takes left and right camera streams as inputs and generates outputs
"""
stereo = pipeline.createStereoDepth()
stereo.setLeftRightCheck(True)
monoLeft.out.link(stereo.left)
monoRight.out.link(stereo.right)
return stereo | bigcode/self-oss-instruct-sc2-concepts |
from fractions import Fraction
def compile_continued_fraction_representation(seq):
"""
Compile an integer sequence (continued fraction representation) into its corresponding fraction.
"""
# sanity check
assert seq
# initialize the value to be returned by working backwards from the last number
retval = Fraction(1, seq.pop())
# keep going backwords till the start of the sequence
while seq:
retval = 1 / (seq.pop() + retval)
return retval | bigcode/self-oss-instruct-sc2-concepts |
def get_skin_num(id, skin_id):
"""
Returns Skin Number from the Skin ID
"""
skin = str(id)
length = len(skin)
new_id = str(skin_id)[length:]
return int(new_id) | bigcode/self-oss-instruct-sc2-concepts |
def check_int(value: int) -> bool:
"""Check whether value can be written as 2^p * 5^q where p and q are
natural numbers."""
if value == 1:
return True
else:
if value % 2 == 0:
return check_int(value//2)
if value % 5 == 0:
return check_int(value//5)
return False | bigcode/self-oss-instruct-sc2-concepts |
def make_ngrams(tokens: list, n: int) -> list:
"""Creates n-grams for the given token sequence.
Args:
tokens (list): a list of tokens as strings
n (int): the length of n-grams to create
Returns:
list: list of tuples of strings, each tuple being one of the individual n-grams
"""
n_grams = []
for token in tokens:
word_list = token.split(" ") # split with whitespace
# initialize index
starting_index = 0
end_index = starting_index + n - 1
# use sliding window to append tuples of length n to n_grams
while end_index < len(word_list):
n_grams.append(tuple(word_list[starting_index: starting_index + n]))
starting_index += 1
end_index += 1
return n_grams | bigcode/self-oss-instruct-sc2-concepts |
import inspect
def get_channelmethods(obj):
"""
Returns a sorted list of the names of all channelmethods defined for an object.
"""
channelmethods = list()
# getmembers() returns a list of tuples already sorted by name
for name, method in inspect.getmembers(obj, inspect.ismethod):
# To be a channelmethod, the method must have an attribute called `is_channelmethod`,
# *and* it must be bound to the object, since it is common for channelmethods from one
# channel manager to be passed into the constructor of a subsequent channel manager!
if hasattr(method, 'is_channelmethod') and (method.__self__ == obj):
channelmethods.append(name)
return tuple(channelmethods) | bigcode/self-oss-instruct-sc2-concepts |
def map_range(value, from_lower, from_upper, to_lower, to_upper):
"""Map a value in one range to another."""
mapped = (value - from_lower) * (to_upper - to_lower) / (
from_upper - from_lower
) + to_lower
return round(min(max(mapped, to_lower), to_upper)) | bigcode/self-oss-instruct-sc2-concepts |
def default_logfile_names(script, suffix):
"""Method to return the names for output and error log files."""
suffix = script.split('.')[0] if suffix is None else suffix
output_logfile = '{}_out.txt'.format(suffix)
error_logfile = '{}_err.txt'.format(suffix)
return output_logfile, error_logfile | bigcode/self-oss-instruct-sc2-concepts |
import re
def str_split(string, split_length=1):
"""Method splits string to substrings
Args:
string (str): original string
split_length (int): substrin length
Returns:
list: list of strings
"""
return list(filter(None, re.split('(.{1,%d})' % split_length, string))) | bigcode/self-oss-instruct-sc2-concepts |
def flatten(l):
"""Flattens a list of lists to the first level.
Given a list containing a mix of scalars and lists,
flattens down to a list of the scalars within the original
list.
Args:
l (list): Input list
Returns:
list: Flattened list.
"""
if not isinstance(l, list):
return [l]
else:
return sum(map(flatten, l), []) | bigcode/self-oss-instruct-sc2-concepts |
def is_annotation_size_unusual(annotation, minimum_size, minimum_aspect_ratio, maximum_aspect_ratio):
"""
Checks if object described by annotation has unusual size - is too small or has unusual aspect ratio
:param annotation: net.utilities.Annotation instance
:param minimum_size: int, minimum size object must have to be considered normal
:param minimum_aspect_ratio: float, minimum aspect ratio object must have to be considered normal.
Both width to height and height to width ratios are tested against this criterion
:param maximum_aspect_ratio: float, maximum aspect ratio object must have to be considered normal.
Both width to height and height to width ratios are tested against this criterion
:return: bool, True if object size is unusual, False otherwise
"""
if annotation.width < minimum_size or annotation.height < minimum_size:
return True
if annotation.aspect_ratio < minimum_aspect_ratio or 1 / annotation.aspect_ratio < minimum_aspect_ratio:
return True
if annotation.aspect_ratio > maximum_aspect_ratio or 1 / annotation.aspect_ratio > maximum_aspect_ratio:
return True
return False | bigcode/self-oss-instruct-sc2-concepts |
def to_json_list(objs):
"""
Wrap strings in lists. Other iterables are converted to lists directly.
"""
if isinstance(objs, str):
return [objs]
if not isinstance(objs, list):
return list(objs)
return objs | bigcode/self-oss-instruct-sc2-concepts |
def make_list(item_or_items):
"""
Makes a list out of the given items.
Examples:
>>> make_list(1)
[1]
>>> make_list('str')
['str']
>>> make_list(('i', 'am', 'a', 'tuple'))
['i', 'am', 'a', 'tuple']
>>> print(make_list(None))
None
>>> # An instance of lists is unchanged
>>> l = ['i', 'am', 'a', 'list']
>>> l_res = make_list(l)
>>> l_res
['i', 'am', 'a', 'list']
>>> l_res is l
True
Args:
item_or_items: A single value or an iterable.
Returns:
Returns the given argument as an list.
"""
if item_or_items is None:
return None
if isinstance(item_or_items, list):
return item_or_items
if hasattr(item_or_items, '__iter__') and not isinstance(item_or_items, str):
return list(item_or_items)
return [item_or_items] | bigcode/self-oss-instruct-sc2-concepts |
def check(these_bytes):
"""Tests a file for presence of a valid header"""
test = str(these_bytes[8:12])
if test[2:6] != 'logo':
return 1
return 0 | bigcode/self-oss-instruct-sc2-concepts |
def safe_get(lst, index, default=None):
"""
An implementation of the similar :meth:`get` of the dictionary class.
:param lst: the list to perform the operation on
:param index: the index to query
:param default: the default value if not found
:return: the result if exists or the default value
"""
try:
return lst[index]
except IndexError:
return default | bigcode/self-oss-instruct-sc2-concepts |
def calculate(x: int, y: int = 1, *, subtract: bool = False) -> int:
"""Calculates the sum (or difference) of two numbers.
Parameters:
`x` : int
The first number
`y` : int, optional
The second number (default is 1)
`subtraction`: bool, optional
Whether to perform subtraction. (Default is `False`.)
Returns:
int
"""
if subtract:
return x - y
else:
return x + y | bigcode/self-oss-instruct-sc2-concepts |
def elevation_line(client, format_in, geometry,
format_out='geojson',
dataset='srtm',
validate=True,
dry_run=None):
"""
POSTs 2D point to be enriched with elevation.
:param format_in: Format of input geometry. One of ['geojson',
'polyline', 'encodedpolyline']
:type format_in: string
:param geometry: Point geometry
:type geometry: depending on format_in, either list of coordinates, LineString
geojson or string
:param format_out: Format of output geometry, one of ['geojson',
'polyline', 'encodedpolyline']
:type format_out: string
:param dataset: Elevation dataset to be used. Currently only SRTM v4.1 available.
:type dataset: string
:param dry_run: Print URL and parameters without sending the request.
:param dry_run: boolean
:returns: correctly formatted parameters
:rtype: Client.request()
"""
params = {
'format_in': format_in,
'geometry': geometry,
'format_out': format_out,
'dataset': dataset
}
return client.request('/elevation/line', {}, post_json=params, dry_run=dry_run) | bigcode/self-oss-instruct-sc2-concepts |
import sqlite3
def commit_data(conn):
"""Commit data to db"""
try:
conn.commit()
conn.close()
except sqlite3.Error as e:
print(e)
return None | bigcode/self-oss-instruct-sc2-concepts |
import re
def _strip_terminal_commas(data: str) -> str:
"""Remove all terminal commas.
Samples sheets have a large number of commas append to the end of the
various sections. I think this is an artifact of exporting to a CSV
forcing each row to have the same number of columns as the main Data
section. This strips all of these extra commas off.
Example:
>>> data = "key1,value1,,,,,,,,,,\nkey2,value2,,,,,,,,,,\n"
>>> _strip_terminal_commas(data)
"key1,value1\nkey2,value2\n
"""
return re.sub("\n+", "\n", re.sub(r",*\n", "\n", data)) | bigcode/self-oss-instruct-sc2-concepts |
def _get_runfile_path(ctx, f):
"""Return the runfiles relative path of f."""
if ctx.workspace_name:
return ctx.workspace_name + "/" + f.short_path
else:
return f.short_path | bigcode/self-oss-instruct-sc2-concepts |
def calculate_cn_values(m, sigma_veff):
"""
CN parameter from CPT, Eq 2.15a
"""
CN = (100 / sigma_veff) ** m
if CN > 1.7:
CN = 1.7
return CN | bigcode/self-oss-instruct-sc2-concepts |
import torch
def shuffle_data(inputs, outputs):
"""Shuffle the first dimension of a set of input/output data"""
n_examples = outputs.shape[0]
shuffled_indices = torch.randperm(n_examples)
inputs = inputs[shuffled_indices]
outputs = outputs[shuffled_indices]
return inputs, outputs | bigcode/self-oss-instruct-sc2-concepts |
import re
def is_valid_entity(line: str) -> bool:
"""Check if the line is a valid entity annotation."""
regex = r'^T\d+\t\w+ \d+ \d+(;\d+ \d+)*\t.+$'
return re.search(regex, line) is not None | bigcode/self-oss-instruct-sc2-concepts |
def _blob_and_weights(net, layer_name):
"""Get the activation blob and the weights blob for the named layer
in the Caffe network.
"""
# Get the activation blob for this layer and its parameters
# (weights).
blob = net.blobs[net.top_names[layer_name][0]]
weights = net.params[layer_name][0]
return blob, weights | bigcode/self-oss-instruct-sc2-concepts |
def null_val(val):
"""Return True if the value is a mmCIF NULL charactor: ? or .
"""
if val == "?" or val == ".":
return True
return False | bigcode/self-oss-instruct-sc2-concepts |
import torch
def radius_gaussian(sq_r, sig, eps=1e-9):
"""
Compute a radius gaussian (gaussian of distance)
:param sq_r: input radiuses [dn, ..., d1, d0]
:param sig: extents of gaussians [d1, d0] or [d0] or float
:return: gaussian of sq_r [dn, ..., d1, d0]
"""
return torch.exp(-sq_r / (2 * sig**2 + eps)) | bigcode/self-oss-instruct-sc2-concepts |
def human_to_mb(s):
"""Translates human-readable strings like '10G' to numeric
megabytes"""
if len(s) == 0:
raise Exception("unexpected empty string")
md = dict(M=1, G=1024, T=1024 * 1024, P=1024 * 1024 * 1024)
suffix = s[-1]
if suffix.isalpha():
return float(s[:-1]) * md[suffix]
else:
return float(s) | bigcode/self-oss-instruct-sc2-concepts |
import collections
def longest_substring_deque_rotations(s: str) -> int:
"""
find the longest substring without repeating characters
512 ms 14.5 MB
>>> longest_substring_deque_rotations("abac")
3
>>> longest_substring_deque_rotations("abcabcbb")
3
>>> longest_substring_deque_rotations("bbbbb")
1
>>> longest_substring_deque_rotations("pwwkew")
3
"""
words = collections.deque()
longest = 0
for char in s:
for _ in range(len(words)):
word = words.popleft()
if char not in word:
words.append(word + char)
else:
longest = max(longest, len(word))
words.append(char)
for word in words:
longest = max(longest, len(word))
return longest | bigcode/self-oss-instruct-sc2-concepts |
def CodepointsToUTF16CodeUnits( line_value, codepoint_offset ):
"""Return the 1-based UTF-16 code unit offset equivalent to the 1-based
unicode codepoint offset |codepoint_offset| in the Unicode string
|line_value|"""
# Language server protocol requires offsets to be in utf16 code _units_.
# Each code unit is 2 bytes.
# So we re-encode the line as utf-16 and divide the length in bytes by 2.
#
# Of course, this is a terrible API, but until all the servers support any
# change out of
# https://github.com/Microsoft/language-server-protocol/issues/376 then we
# have to jump through hoops.
if codepoint_offset > len( line_value ):
return ( len( line_value.encode( 'utf-16-le' ) ) + 2 ) // 2
value_as_utf16 = line_value[ : codepoint_offset ].encode( 'utf-16-le' )
return len( value_as_utf16 ) // 2 | bigcode/self-oss-instruct-sc2-concepts |
import importlib
def _import_name(generator):
"""Import a class from its module name."""
# A generator 'path'
try:
mod_name, func_name = generator.rsplit(".", 1)
except ValueError:
raise ValueError("Invalid generator class name %s" % generator)
try:
mod = importlib.import_module(mod_name)
except ImportError as e:
raise ValueError("Error importing generator module %s: '%s'" % (mod_name, e))
try:
return getattr(mod, func_name)
except AttributeError:
raise ValueError(
"Module '%s' does not define a '%s' class" % (mod_name, func_name)
) | bigcode/self-oss-instruct-sc2-concepts |
def sciNot(x):
"""Returns scientific notation of x value"""
return '%.2E' % x | bigcode/self-oss-instruct-sc2-concepts |
import ctypes
def struct_to_dict(struct: ctypes.Structure) -> dict:
"""Create a dict from a struct's fields and their values."""
return {name: getattr(struct, name) for name, _ in getattr(struct, "_fields_")} | bigcode/self-oss-instruct-sc2-concepts |
def parse_hkey(idx):
"""parse index and convert to str
Args:
idx (pd.DatetimeIndex): datetime index
Returns:
str: zero padded 24-clock hour(%H)
"""
return str(idx.hour).zfill(2) | bigcode/self-oss-instruct-sc2-concepts |
def apparent_latitude(t='now'): # pylint: disable=W0613
"""Returns the true latitude. Set to 0 here."""
return 0 | bigcode/self-oss-instruct-sc2-concepts |
def normalise_activity_by_sector_month(
topic_activity, sector_month_labels, sector_variable="sector"
):
"""Normalise s.t. each [sector, month] sums to 1."""
norm_factor = (
sector_month_labels.dropna()
.groupby(
[
"month",
sector_variable,
]
)
.size()
.sort_index()
)
# Each sector sums to 1
return topic_activity.reorder_levels(["month", sector_variable]).divide(
norm_factor.reorder_levels(["month", sector_variable]), axis="rows"
) | bigcode/self-oss-instruct-sc2-concepts |
def is_permutation(a: int, b: int) -> bool:
"""Returns boolean if a and b are permutations of each other."""
s_a, s_b = str(a), str(b)
if set(s_a) != set(s_b):
return False
if len(s_a) != len(s_b):
return False
return sorted(list(s_a)) == sorted(list(s_b)) | bigcode/self-oss-instruct-sc2-concepts |
from collections import Counter
def related_by_digit_permutation(num_a, num_b):
"""
Check if two numbers are related by digit permutation.
"""
return Counter(str(num_a)) == Counter(str(num_b)) | bigcode/self-oss-instruct-sc2-concepts |
from typing import Dict
from typing import Any
from typing import Optional
def get_name(hook: Dict[Any, Any]) -> Optional[str]:
"""
Creates a name based on the webhook call it recieved
Format: Timestamp_Devicename.mp4
Removes any characters that are not regular characters, numbers, '_' '.' or '-'
to ensure the filename is valid
:param hook: Dict with webhook response
:return: filename: str, None if invalid hook failed
"""
if 'extraInfo' not in hook:
return
timestamp = hook.get('createdOn', '').replace(':', '-')
device_name = hook['extraInfo'].get('Device name', '').replace(' ', '_')
if timestamp == '' or device_name == '':
return
name = f'{timestamp}_{device_name}.mp4'
# https://stackoverflow.com/questions/7406102/create-sane-safe-filename-from-any-unsafe-string
file_name = "".join([c for c in name if
c.isalpha()
or c.isdigit()
or c == '_'
or c == '.'
or c == '-']).rstrip()
return file_name | bigcode/self-oss-instruct-sc2-concepts |
def iterator(it):
"""
Convenience function to toggle whether to consume dataset and forecasts as iterators or iterables.
:param it:
:return: it (as iterator)
"""
return iter(it) | bigcode/self-oss-instruct-sc2-concepts |
def normalize_date(date):
"""Round datetime down to midnight."""
return date.replace(hour=0, minute=0, second=0, microsecond=0) | bigcode/self-oss-instruct-sc2-concepts |
import math
def hits_to_kill(damage, health):
"""
Returns the number of hits it takes to kill the target.
"""
if damage > 0:
hits = health / damage
else:
hits = math.inf
if hits < 1:
hits = 1
elif hits < math.inf:
hits = math.ceil(hits)
return hits | bigcode/self-oss-instruct-sc2-concepts |
import uuid
def generate_unique_id(text):
"""
Generate a unique UUID based on a string
Args:
text(str): The string to base the uuid on
Returns:
str: The UUID in hex string format
"""
return uuid.uuid3(uuid.NAMESPACE_URL, text).hex | bigcode/self-oss-instruct-sc2-concepts |
import random
import string
def generate_random_key() -> str:
"""
Creates and returns a randomly generated 10 character alphanumeric string.
:return:
"""
return "".join(
random.SystemRandom().choice(string.ascii_uppercase + string.digits)
for _ in range(10)
) | bigcode/self-oss-instruct-sc2-concepts |
def _df_meta_to_arr(df):
"""Check what kind of data exists in pandas columns or index. If string return as numpy array 'S' type, otherwise regular numpy array.
"""
if len(df.columns):
if isinstance(df.columns[0], str):
columns = df.columns.values.astype("S")
else:
columns = df.columns.values
else:
columns = []
if len(df.index):
if isinstance(df.index[0], str):
index = df.index.values.astype("S")
else:
index = df.index.values
else:
index = []
return columns, index | bigcode/self-oss-instruct-sc2-concepts |
from pathlib import Path
import yaml
def load_yaml(yamlpath: str):
"""
Loads a yaml file from a path.
:param yamlpath: Path to yaml settings file
:returns: dict settings object """
yamlpath_full = Path(yamlpath).absolute()
with open(yamlpath_full, 'r', encoding="utf-8") as stream:
try:
outdict = yaml.safe_load(stream)
return outdict
except yaml.YAMLError as exc:
print(exc)
raise RuntimeError(f"Could not load yaml file at {yamlpath}") | bigcode/self-oss-instruct-sc2-concepts |
def has_field(analysis, field):
"""Return true or false if given field exists in analysis"""
for f in field:
try:
analysis = analysis[f]
except:
return False
return True | bigcode/self-oss-instruct-sc2-concepts |
import multiprocessing
def queue_loader(q_list):
"""
Copy values from a List into a SimpleQueue.
"""
q = multiprocessing.SimpleQueue()
for item in q_list:
q.put(item)
return q | bigcode/self-oss-instruct-sc2-concepts |
def generate_method(method_name):
"""Generate a method for a given Thrift service.
Uses the provided TChannelSyncClient's threadloop in order
to convert RPC calls to concurrent.futures
:param method_name: Method being called.
:return: A method that invokes the RPC using TChannelSyncClient
"""
def call(self, *args, **kwargs):
"""Forward RPC call to TChannelSyncClient
:return concurrent.futures.Future:
"""
if not self.threadloop.is_ready():
self.threadloop.start()
return self.threadloop.submit(
getattr(self.async_thrift, method_name), *args, **kwargs
)
return call | bigcode/self-oss-instruct-sc2-concepts |
def color_to_int(rgb):
"""Converts a color from floating point range 0-1 to integer range 0-255."""
return tuple(int(round(c * 255)) for c in rgb) | bigcode/self-oss-instruct-sc2-concepts |
import re
def _get_before_pronounce_sentence(words, index):
"""Return before pronounce sentence
Args:
words (List[Words]): stanfordnlp word object list.
index (int): Pronounce index.
Return:
sentence (str): target word contains sentence to pronounce.
"""
roots = [(i, w) for i, w in enumerate(words) if int(w.index) == 1]
start_index = 0
for i, w in roots:
if i <= index:
start_index = i
else:
break
governor_index = index + (int(words[index].governor) - int(words[index].index))
if governor_index < index:
start_index = governor_index
sentence = " ".join([w.text for w in words[start_index:index]])
sentence = re.sub(r" (\W)", r"\1", sentence)
sentence = re.sub(r" n't", r"n't", sentence)
return sentence | bigcode/self-oss-instruct-sc2-concepts |
def _get_kaggle_type(competition_or_dataset: str) -> str:
"""Returns the kaggle type (competitions/datasets).
Args:
competition_or_dataset: Name of the kaggle competition/dataset.
Returns:
Kaggle type (competitions/datasets).
"""
# Dataset are `user/dataset_name`
return 'datasets' if '/' in competition_or_dataset else 'competitions' | bigcode/self-oss-instruct-sc2-concepts |
def token_response_json(token_response):
"""
Return the JSON from a successful token response.
"""
return token_response.json | bigcode/self-oss-instruct-sc2-concepts |
def get_subgraph(G, attribute, attribute_value):
"""
This function returns the subgraph of G with the attribute
attribute_value.
Input:
------
G: networkx graph
attribute: attribute of the nodes
attribute_value: value of the attribute
Output:
-------
subgraph: the subgraph of G with the attribute attribute_value
"""
node_list = []
for x, y in G.nodes(data=True):
if y[attribute] == attribute_value:
node_list.append(x)
return G.subgraph(node_list) | bigcode/self-oss-instruct-sc2-concepts |
import re
def verifyFormat(ATS_LIST):
"""
Matches a list of input ATS coordinates against the AltaLIS format in a regex.
Returns True if any of the coordinates match the regex,
False if none return.
"""
# Defines a list of expressions to check against the coordinates.
# Anything in square brackets represents a range (i.e. [0-9][0-9] represents anything from 00-99)
# Anything in curly brackets represents a required number of items (i.e. [0-9][0-9]{1} will not pass if a number from 00-99 is not inputted)
# Anything outside of the brackets (ex. 'SEC-') are checked literally, and will only pass if they are in the expression in that position.
# *** Regex are great.
#
reList = [ re.compile("^(TWP-[0-9][0-9][0-9]{1} RGE-[0-9][0-9]{1} MER-[4-7]{1})$"),
re.compile("^(SEC-[0-9][0-9]{1} TWP-[0-9][0-9][0-9]{1} RGE-[0-9][0-9]{1} MER-[4-7]{1})$"),
re.compile("^(QS-[neswNEWS]{2} SEC-[0-9][0-9]{1} TWP-[0-9][0-9][0-9]{1} RGE-[0-9][0-9]{1} MER-[4-7]{1})$"),
re.compile("^(LSD-[0-9][0-9]{1} SEC-[0-9][0-9]{1} TWP-[0-9][0-9][0-9]{1} RGE-[0-9][0-9]{1} MER-[4-7]{1})$")
]
# Uses a broad sweeping check for the coordinates. This is mostly to check whether the right column was inputted.
# Returns True if any coordinates match any of the expressions.
# Returns False if none of the coordinates match.
#
if any(r.match(x) for x in ATS_LIST for r in reList):
return True
else:
return False | bigcode/self-oss-instruct-sc2-concepts |
def SanityCheck(s):
"""
Class performs a simple text-based SanityCheck
to validate generated SMILES. Note, this method
does not check if the SMILES defines a valid molecule,
but just if the generated SMILES contains the
correct number of ring indices as well as opening/closing
brackets.
Input:
s -- Generated SMILES String.
Return:
True if the generated SMILES String is valid.
"""
# Check ring-pairing
for r in range(1,10):
if s.count("%s"%(r)) % 2 != 0:
return False
# Check branch-pairing
if s.count("(") != s.count(")"):
return False
# Check explicit info pairing
if s.count("[") != s.count("]"):
return False
# All rules pass
return True | bigcode/self-oss-instruct-sc2-concepts |
def priormonthToDay(freq, j_mth, k_mth):
"""
Consistent w/ Fama and French (2008, 2016), map the prior `(j-k)` monthly return strategy into a daily strategy
(see `Ken French's online documentation <https://mba.tuck.dartmouth.edu/pages/faculty/ken.french/data_library.html>`_).
Parameters
___________
freq : str
Frequency used to calculate prior `(j-k)` return strategy. Possible choices are:
* ``D`` : daily
* ``'M`` : monthly
j_mth : str
Lagged month (or day) we start measuring stock performance.
k_mth : str
How many months (or days) are used in measuring stock performance.
Returns
________
j_per, k_per : tuple, str
``j_per = j_mth`` and ``k_per = k_mth`` if ``freq = M``.
Otherwise, monthly figures mapped to daily periods using the description found on Ken French's online documentation:
* `Daily Momentum <https://mba.tuck.dartmouth.edu/pages/faculty/ken.french/Data_Library/det_mom_factor_daily.html>`_.
* `Daily Short-Term Reversal <https://mba.tuck.dartmouth.edu/pages/faculty/ken.french/Data_Library/det_st_rev_factor_daily.html>`_.
* `Daily Long-Term Reversal <https://mba.tuck.dartmouth.edu/pages/faculty/ken.french/Data_Library/det_lt_rev_factor_daily.html>`_.
Note
____
Monthly ``M`` (daily ``D``) strategies involve portfolios formed every month `t-1` (or day `t-1`)
for month `t` (or day `t`).
Note
____
The Fama and French (2008, 2016) momentum strategy definition differs from that of Jegadeesh and Titman (1993).
Jegadeesh and Titman (1993) consider **J/K** strategies, which include portfolios formed on stock performance over the previous
**J** months (excluding the last week or month prior to portfolio formation, to remove the
large short-horizon reversals associated with bid-ask bounce) and hold portfolios for **K** months, where **J**, **K** :math:`\in` {3,6,9,12}.
Future updates to this module will extend this package to include these additional momentum strategies.
References
___________
* Fama, Eugene F., and Kenneth R. French. (2008). `Dissecting Anomalies`,
Journal of Finance, 48(4), pp.1653-1678
* Fama, Eugene F., and Kenneth R. French. (2016). `Dissecting Anomalies with a Five-Factor Model`,
Journal of Finance, 48(4), pp.1653-1678
"""
# Per Fama and French, map prior (2-12), (1-1), and (13-60) returns
# at the monthly frequency to the daily frequency
if freq in ['D', 'W']:
if (j_mth == '2') and (k_mth == '12'):
j_per, k_per = '21', '250'
return j_per, k_per
elif (j_mth == '1') and (k_mth == '1'):
j_per, k_per = '1', '20'
return j_per, k_per
elif (j_mth == '13') and (k_mth == '60'):
j_per, k_per = '251', '1250'
return j_per, k_per
else:
raise ValueError('\'prior (j-k)\' return strategy not of the standard Fama and French type.')
elif freq in ['M', 'Q', 'A']:
j_per, k_per = j_mth, k_mth
return j_per, k_per
else:
raise ValueError('Please specify one of the following frequencies: \'D\' or \'M\'') | bigcode/self-oss-instruct-sc2-concepts |
import re
def _filter_zones(wanted_zones_prefix, zone_list):
"""Filter unwanted zones from a zone list using a prefix."""
target_zones = []
for zone in zone_list:
for prefix in wanted_zones_prefix:
pattern = re.compile(f'^{prefix}')
if pattern.match(zone):
target_zones.append(zone)
return target_zones | bigcode/self-oss-instruct-sc2-concepts |
def _cut_if_too_long(text: str, max_length: int) -> str:
"""Cut a string down to the maximum length.
Args:
text: Text to check.
max_length: The maximum length of the resulting string.
Returns:
Cut string with ... added at the end if it was too long.
"""
if len(text) <= max_length:
return text
return text[: max_length - 3] + "..." | bigcode/self-oss-instruct-sc2-concepts |
import ipaddress
def is_address(entry):
""" Check if entry is a valid IP address """
try:
_ = ipaddress.ip_address(entry)
except ValueError:
return False
return True | bigcode/self-oss-instruct-sc2-concepts |
def tuple_or_list(target):
"""Check is a string object contains a tuple or list
If a string likes '[a, b, c]' or '(a, b, c)', then return true,
otherwise false.
Arguments:
target {str} -- target string
Returns:
bool -- result
"""
# if the target is a tuple or list originally, then return directly
if isinstance(target, tuple) or isinstance(target, list):
return target
try:
target = eval(target)
if isinstance(target, tuple) or isinstance(target, list):
return target
except:
pass
return None | bigcode/self-oss-instruct-sc2-concepts |
def get_ext(file):
"""Return the extension of the given filename."""
return file.split('.')[-1] | bigcode/self-oss-instruct-sc2-concepts |
import inspect
def get_wrapped_sourcelines(f):
"""
Gets a list of source lines and starting line number for the given function
:param f: Input function
:return: Source lines
"""
if hasattr(f, "__wrapped__"):
# has __wrapped__, going deep
return get_wrapped_sourcelines(f.__wrapped__)
else:
# Returning getsourcelines
return inspect.getsourcelines(f) | bigcode/self-oss-instruct-sc2-concepts |
import inspect
import ast
import textwrap
def ast_object(obj):
"""Convert a Python object to its AST representation."""
src = inspect.getsource(obj)
# ast wraps always into a module
node = ast.parse(textwrap.dedent(src)).body[0]
return node | bigcode/self-oss-instruct-sc2-concepts |
def txt2str(filename):
"""Reads the plain text of a .txt file and returns a string"""
with open(filename, 'r') as myfile:
data=myfile.read().replace('\n', '')
myfile.close()
return data | bigcode/self-oss-instruct-sc2-concepts |
def _monitor_pvs(*pv_names, context, queue, data_type='time'):
"""
Monitor pv_names in the given threading context, putting events to `queue`.
Parameters
----------
*pv_names : str
PV names to monitor.
context : caproto.threading.client.Context
The threading context to use.
queue : ThreadsafeQueue
Thread-safe queue for the current server async library.
data_type : {'time', 'control', 'native'}
The subscription type.
Returns
-------
subscriptions : list
List of subscription tuples, with each being:
``(sub, subscription_token, *callback_references)``
"""
def add_to_queue(sub, event_add_response):
queue.put(('subscription', sub, event_add_response))
def connection_state_callback(pv, state):
queue.put(('connection', pv, state))
pvs = context.get_pvs(
*pv_names, timeout=None,
connection_state_callback=connection_state_callback
)
subscriptions = []
for pv in pvs:
sub = pv.subscribe(data_type=data_type)
token = sub.add_callback(add_to_queue)
subscriptions.append((sub, token, add_to_queue,
connection_state_callback))
return subscriptions | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
def column_widths(table: List[List[str]]) -> List[int]:
"""Get the maximum size for each column in table"""
return [max(map(len, col)) for col in zip(*table)] | bigcode/self-oss-instruct-sc2-concepts |
def commands(command):
""" Check if command is to get available Commands (c | commands). """
return (command.strip().lower() == 'c' or command.strip().lower() == 'commands') | bigcode/self-oss-instruct-sc2-concepts |
def build_concentartion(species_id, number):
"""
Builds the concentration component for each species
Parameters
----------
species_id : int
species id from the species_indices dictionary
number : float
stoichiometric co-eff of the species
for specific reactions
Returns
----------
concentration : string
the concentration component of that particular
species
"""
if abs(float(number)) == 1:
concentration = '* y[%s] ' % species_id
else:
concentration = '* y[%s] ** %s ' % (species_id, abs(float(number)))
return concentration | 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.