seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
from typing import List
def count_failed_students(student_scores: List[int]) -> int:
"""
:param student_scores: list of integer student scores.
:return: integer count of student scores at or below 40.
"""
return len(list(filter(lambda x: x <= 40, student_scores))) | bigcode/self-oss-instruct-sc2-concepts |
def add_bda(base_config):
"""Add BDA to config file with hard-coded parameter values."""
bda_config = """
bda:
max_decorr: 0
pre_fs_int_time: !dimensionful
value: 0.1
units: s
corr_FoV_angle: !dimensionful
value: 20
units: deg
max_time: !dimensionful
value... | bigcode/self-oss-instruct-sc2-concepts |
def getbitlen(bint):
"""
Returns the number of bits encoding an integer
"""
if bint == 0:
# Zero is encoded on one bit
return 1
else:
return int(bint).bit_length() | bigcode/self-oss-instruct-sc2-concepts |
from typing import Dict
import torch
def dictionary_to_device(dictionary: Dict, device: torch.device):
"""Move dictionary values to a torch device, if they support it.
:param dictionary: Dictionary, whose values are to be moved to the torch device.
:param device: torch device
:return: Dictionary, wit... | bigcode/self-oss-instruct-sc2-concepts |
import math
def determine_num_particles(pack_frac, num_vertices):
"""Return the number of model particles to be created
based on the packing fraction"""
num_particles = num_vertices * pack_frac
num_particles = int(math.ceil(num_particles))
return num_particles | bigcode/self-oss-instruct-sc2-concepts |
def functions_in(module):
"""
Create a dictionary of the functions in a module
Parameters
----------
module : Module
module to run on.
Returns
-------
dict
"""
return {name: f for name, f in module.__dict__.items() if callable(f)} | bigcode/self-oss-instruct-sc2-concepts |
def reverse_2nd(vec):
"""Do time-reversal on numpy array of form `B x T`
:param vec: vector to time-reverse
:return: Time-reversed vector
"""
return vec[:, ::-1] | bigcode/self-oss-instruct-sc2-concepts |
def GetPatchMetadata(patch_dict):
"""Gets the patch's metadata.
Args:
patch_dict: A dictionary that has the patch metadata.
Returns:
A tuple that contains the metadata values.
"""
# Get the metadata values of a patch if possible.
start_version = patch_dict.get('start_version', 0)
end_version = ... | bigcode/self-oss-instruct-sc2-concepts |
def get_suite_name(nodeid):
"""Return suitename from nodeid string.
Args:
nodeid(str): pytest.Item nodeid string
Returns:
str: test suite name
"""
names = nodeid.split("::")
names[0] = names[0].replace("/", '.')
names = [x.replace(".py", "") for x in names if x != "()"]
... | bigcode/self-oss-instruct-sc2-concepts |
def min_sec(secs):
"""
Takes an epoch timestamp and returns string of minutes:seconds.
:param secs:
Timestamp (in seconds)
>>> import time
>>> start = time.time() # Wait a few seconds
>>> finish = time.time()
>>> min_sec(finish - start)
'0:11'
"""
secs = int(secs)
... | bigcode/self-oss-instruct-sc2-concepts |
def get_number_of_images(body_response):
"""
Returns the number of images in the list.
:param body_response: Parsed response (Python dic). List of images
:return: Length of list
"""
return len(body_response['images']) | bigcode/self-oss-instruct-sc2-concepts |
def char_to_bin(char: str) -> str:
"""This creates a string representing the binary value of the character.
Parameters:
-----------
char:
string: A single character.
Returns:
--------
binary:
string: The 8-bit binary representation of the character.
"""
binary = bi... | bigcode/self-oss-instruct-sc2-concepts |
def is_indicator(item_type):
"""Return whether or not the given item_type is an indicator."""
indicator_types = [
'address',
'emailaddress',
'file',
'host',
'url',
'asn',
'cidr',
'mutex',
'registry key',
'user agent'
]
retur... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Tuple
def parse(args: Tuple[str, str, str, str, str]) -> Tuple[str, str, str]:
"""Parser for rd rs rt format instructions."""
return (args[2], args[3], args[4]) | bigcode/self-oss-instruct-sc2-concepts |
def list_daily_cases(list_of_cumulative_cases):
"""
Given a list of cumulative cases, this function makes and returns a list of
daily cases.
"""
daily_list = [0]
for i in range(1, len(list_of_cumulative_cases)):
N_daily_case = list_of_cumulative_cases[i] - list_of_cumulative_cases[i - 1... | bigcode/self-oss-instruct-sc2-concepts |
def is_user_inputs_populated(user_prefs):
"""
Takes a dictionary of user preferences and returns a Boolean whether all inputs are filled.
"""
return all(value != '' or value != 'No preference' for value in user_prefs.values()) | bigcode/self-oss-instruct-sc2-concepts |
from typing import Mapping
def get_keys_for_dict(d):
"""
Get all (possibly nested) keys in a dictionary
"""
out = []
for k, v in d.items():
out.append(k)
if isinstance(v, Mapping):
out += get_keys_for_dict(v)
return out | bigcode/self-oss-instruct-sc2-concepts |
def average(values):
"""calculates average from a list"""
try:
return float(sum(values) / len(values))
except ZeroDivisionError:
return 0 | bigcode/self-oss-instruct-sc2-concepts |
def _parse_action_removals(actions):
""" Separates the combined list of keys to remove into webhooks and emails. """
flattened = list({x for sublist in actions for x in sublist})
emails = []
webhooks = []
for item in flattened:
if item.startswith('http://') or item.startswith('https://'):
... | bigcode/self-oss-instruct-sc2-concepts |
import requests
from bs4 import BeautifulSoup
def get_soup(link):
"""Gets soup from a given website."""
res = requests.get(link)
soup = BeautifulSoup(res.text, "html.parser")
return soup | bigcode/self-oss-instruct-sc2-concepts |
def get_package_name_and_type(package, known_extensions):
"""Return package name and type.
Package type must exists in known_extensions list. Otherwise None is
returned.
>>> extensions = ['tar.gz', 'zip']
>>> get_package_name_and_type('underscored_name.zip', extensions)
('underscored_name', 'z... | bigcode/self-oss-instruct-sc2-concepts |
def merge(d1, d2, merge_fn):
"""
Merges two dictionaries, non-destructively, combining
values on duplicate keys as defined by the optional merge
function. The default behavior replaces the values in d1
with corresponding values in d2.
Examples:
>>> d1
{'a': 1, 'c': 3, 'b': 2}
>>> ... | bigcode/self-oss-instruct-sc2-concepts |
def _perp(t: tuple) -> tuple:
"""
Obtain the point whose corresponding vector is perpendicular to t.
Parameters
----------
t : tuple
Point (x, y)
Returns
-------
tuple:
(-y, x)
"""
return -t[1], t[0] | bigcode/self-oss-instruct-sc2-concepts |
def solve_me_first(num1: int, num2: int):
"""Calculate the sum of two numbers."""
return num1 + num2 | bigcode/self-oss-instruct-sc2-concepts |
import math
def cint(num):
"""
Returns ceiling of number as type integer
:param num: input number
:returns: integer ceil number
"""
return int(math.ceil(num)) | bigcode/self-oss-instruct-sc2-concepts |
import hashlib
def create_key(notification):
"""Create the key for status_keys from notification
in: notification
return: the key
"""
key = notification.host
key += '/'
key += notification.plugin
if notification.plugin_instance:
key += '-'
key += notification.plug... | bigcode/self-oss-instruct-sc2-concepts |
def zero_cross_down(values, start=0, end=-1):
"""
Returns the indexes of the values so that values[i] > 0 and values[i+1] < 0
params:
- values: list of values to consider
- start: index of the first value to consider
- end: index of the last value to consider (can be < 0)
"""
... | bigcode/self-oss-instruct-sc2-concepts |
def get_set_intersection(list_i, list_j):
""" Get the intersection set
Parameters
----------
list_i, list_j: list
two generic lists
Returns
-------
intersection_set: set
the intersection of list_i and list_j
"""
set_i = set(list_i)
set_j = set(list_j)
interse... | bigcode/self-oss-instruct-sc2-concepts |
def delete_user_defined_app_address_map(
self,
ip_start: int,
ip_end: int,
) -> bool:
"""Delete specific user defined application group based on
address map
.. list-table::
:header-rows: 1
* - Swagger Section
- Method
- Endpoint
* - applicationDefini... | bigcode/self-oss-instruct-sc2-concepts |
def getMutationIDs(data):
"""
Function to get uniques mutation IDs from COSMIC data
Arguments:
data = dataframe containing COSMIC data
Returns:
list of unique mutation IDs
"""
return list(set(data["Mutation ID"])) | bigcode/self-oss-instruct-sc2-concepts |
def AmOppCreditParts(exact, e87521, num, c00100, CR_AmOppRefundable_hc,
CR_AmOppNonRefundable_hc, c10960, c87668):
"""
Applies a phaseout to the Form 8863, line 1, American Opportunity Credit
amount, e87521, and then applies the 0.4 refundable rate.
Logic corresponds to Form 8863, P... | bigcode/self-oss-instruct-sc2-concepts |
def is_string_integer(string: str):
"""
This function takes in a character value and checks if it is a valid integer.
All entries must be strings of length 1
:param string: the string to be analyzed
:type string: str
:return: true or false, depending on if the character is a valid integer
... | bigcode/self-oss-instruct-sc2-concepts |
import torch
import math
def attention(query, key, value, atten_mask=None):
"""
Compute Scaled Dot Product Atten
should: d_q == d_k, len_v == len_q, atten_mask.shape equal to scores or can be broadcast
:param query: (batch_size, n_heads, len_q, d_q)
:param key: (batch_size, n_heads, len_k, d_q)
... | bigcode/self-oss-instruct-sc2-concepts |
def compute_pad(image_shape, kernel_size, enforce_odd=True):
"""Computes a padding length for a given image shape and kernel.
Args:
image_shape: A tuple or list of 2 integers.
kernel_size: A positive integer.
enforce_odd: A boolean indicating whether the padding should result in an
image with odd... | bigcode/self-oss-instruct-sc2-concepts |
def valid_field_in_tree(arch):
"""A `tree` must have `string` attribute and an immediate node of `tree` view must be `field` or `button`."""
if arch.xpath('//tree[not (@string)]'):
return False
for child in arch.xpath('/tree/child::*'):
if child.tag not in ('field', 'button'):
re... | bigcode/self-oss-instruct-sc2-concepts |
def one(iterable):
"""Return the single element in iterable.
Raise an error if there isn't exactly one element.
"""
item = None
iterator = iter(iterable)
try:
item = next(iterator)
except StopIteration:
raise ValueError('Iterable is empty, must contain one item')
try:
next(iterator)
except StopIteration... | bigcode/self-oss-instruct-sc2-concepts |
def GetDetailedHelpForAddIamPolicyBinding(collection,
example_id,
role='roles/editor',
use_an=False,
condition=False):
"""Returns a detailed_help for ... | bigcode/self-oss-instruct-sc2-concepts |
def flatten(image, char):
"""
Given a layered image (typically (y, x, RGB)), return a plain 2D image
(y, x) according to a spec.
Args:
image (np.ndarray): The image to flatten
char (char): One of (R, G, B, or V (=value))
Returns:
np.ndarray - The 2D image.
"""
if im... | bigcode/self-oss-instruct-sc2-concepts |
def get_translation_data(struct, key):
"""Returns translation data set by set_translation_data().
Args:
struct: type. A Struct class.
key: any object.
Raises:
KeyError: Translation data for the key is not defined.
"""
return struct._translation_data[key] | bigcode/self-oss-instruct-sc2-concepts |
def guess_multi_value(value):
"""
Make the best kind of list from `value`. If it's already a list, or tuple,
do nothing. If it's a value with new lines, split. If it's a single value
without new lines, wrap in a list
"""
if isinstance(value, (tuple, list)):
return value
if isinstanc... | bigcode/self-oss-instruct-sc2-concepts |
def calc_us_in_name(name):
"""
calculate how many underscore is in name.
:param name: a string.
:return: a number
"""
cnt = 0
for ch in name:
if ch == '_':
cnt += 1
return cnt | bigcode/self-oss-instruct-sc2-concepts |
import re
def process_text(text):
"""
This method is responsible for performing all pre-processing steps for the text.
It converts text to all lower case and performs some basic cleanup using regex.
"""
text = text.encode('ascii', errors='ignore').decode()
text = text.lower()
text = re.su... | bigcode/self-oss-instruct-sc2-concepts |
def read_gems(directory, file_name):
"""
Read a GEM file of the form "PlinePgem".
Args:
directory (str): directory of the file location (ex: '/Users/kimm/')
file_name (str): name of the file (ex: 'SHG0008H.Fragnum_PlinePgem')
Returns:
in_gems (list): tab-separated lists of lists
... | bigcode/self-oss-instruct-sc2-concepts |
def aggregate_count(items, col):
"""
Function to use on Group by Charts.
accepts a list and returns the count of the list's items
"""
return len(list(items)) | bigcode/self-oss-instruct-sc2-concepts |
def _replace_and_save(md, fns, replacing_fn):
"""
Replaces functions in `fns` list in `md` module with `replacing_fn`.
Returns the dictionary with functions that were replaced.
"""
saved = dict()
for check_f in fns:
try:
fn = getattr(md, check_f)
setattr(md, chec... | bigcode/self-oss-instruct-sc2-concepts |
def as_list(val):
"""
Helper function, always returns a list of the input value.
:param val: the input value.
:returns: the input value as a list.
:Example:
>>> as_list('test')
['test']
>>> as_list(['test1', 'test2'])
['test1', 'test2']
"""
treat_single_value = str
i... | bigcode/self-oss-instruct-sc2-concepts |
def quantize_dequantize(quantization, tensor):
"""Simple helper to quantize and dequantize."""
quantized_tensor, context = quantization.quantize(tensor)
dequantized_tensor = quantization.dequantize(quantized_tensor, context)
return quantized_tensor, dequantized_tensor, context | bigcode/self-oss-instruct-sc2-concepts |
import platform
def get_current_prefab_platform() -> str:
"""Get the name of the running platform.
Throws a RuntimeError on unsupported platforms.
"""
system = platform.system()
machine = platform.machine()
if system == 'Darwin':
# Currently there's just x86_64 on mac;
# will ... | bigcode/self-oss-instruct-sc2-concepts |
import pytz
def GetUtcTime(dt, tz):
"""Converts from a local time to UTC using timezone translation.
The returned time does not have any timezone information. This allows
comparison with times coming from the datastore (which do not have timezone
either).
Args:
dt: A datetime.datetime instance with no... | bigcode/self-oss-instruct-sc2-concepts |
def concat_path(path, child):
"""Concat path with subfolder or file."""
newpath = path + "/" + child
return newpath | bigcode/self-oss-instruct-sc2-concepts |
def velocity(vo2):
"""
A regression equation relating VO2 with running velocity. Used in conjuction with the "vO2" equation to create the Jack Daniel's VDOT tables. Initially retrieved from "Oxygen Power: Performance Tables for Distance Runners" by Jack Daniels.
J., Daniels, and J. Daniels. Conditioning fo... | bigcode/self-oss-instruct-sc2-concepts |
def GetTMIndex(iRes, posTM):# {{{
"""Get index of TM helix given a residue position
Return -1 if iRes is not within TM region
"""
for i in range(len(posTM)):
(b, e) = posTM[i]
if iRes >= b and iRes < e:
return i
return -1
# }}} | bigcode/self-oss-instruct-sc2-concepts |
import re
def get_valid_filename(s: str) -> str:
"""Return a filename-compatible version of the given string s
:param s: String to be used as the base of the filename. You may also pass
non-string objects that will however be able to convert to strings via the
str operator.
>... | bigcode/self-oss-instruct-sc2-concepts |
def cpu_processing_time(cycles: int, freq: float):
"""
:param cycles
:param freq: MHz
:return: seconds
"""
return (cycles / (freq * pow(10, 6))) * pow(10, 3) | bigcode/self-oss-instruct-sc2-concepts |
def subList(l, sl) :
"""return the index of sl in l or None"""
lLen = len(l)
slLen = len(sl)
for i in range(lLen - slLen + 1):
j = 0
while j < slLen and l[i + j] == sl[j]:
j += 1
if j == slLen:
return i
return None | bigcode/self-oss-instruct-sc2-concepts |
import torch
def jitter_soma_depth(feats, scale=10):
""""
Apply jitter to soma depth.
Args:
feats: features per node
scale: scale factor of jittering
"""
new_feats = feats.copy()
new_feats[:, 1] += torch.randn(1).numpy() * scale
return new_feats | bigcode/self-oss-instruct-sc2-concepts |
def translate_name(name):
"""
Convert names with underscores into camelcase.
For example:
"num_rows" => "numRows"
"very_long_json_name" => "veryLongJsonName"
"build_GBM_model" => "buildGbmModel"
"KEY" => "key"
"middle___underscores" => "middleUnderscores"
"_e... | bigcode/self-oss-instruct-sc2-concepts |
def calc_rank(someset, n):
"""
Calculates the rank of a subset `someset` of {1, 2, ..., `n`}
in the ordering given by grey sequenccce of characteristic vectors.
"""
assoc_seq = [k + 1 in someset for k in range(n)]
bit = False
rank = 0
for k, x in enumerate(assoc_seq):
bit ^= x
rank += bit * 2**... | bigcode/self-oss-instruct-sc2-concepts |
def BuildFileName(url):
"""Construct the file name from a given URL.
Args:
url: the given URL
Returns:
filename: the constructed file name
"""
filename = url.strip('\r\n\t \\/')
filename = filename.replace('http://', '')
filename = filename.replace(':', '_')
filename = filename.replace('/', '_... | bigcode/self-oss-instruct-sc2-concepts |
def _parse_suspected_cls(predator_result):
"""Parse raw suspected_cls into dict."""
if not predator_result:
return None
# The raw result contains some additional information that we don't need here.
# Everything we're concerned with is a part of the "result" object included
# with the response.
predato... | bigcode/self-oss-instruct-sc2-concepts |
import uuid
def get_uuid(key=None):
"""
生成UUID
:param key: 默认空 按照UUID-1方式生成,如果有值,者按照UUID-3规则生成。但是前提业务需保证key具有唯一性,如手机号
:return:
"""
'''
Python uuid 5种算法
1、uuid1()——基于时间戳
由MAC地址、当前时间戳、随机数生成。可以保证全球范围内的唯一性,
但MAC的使用同时带来安全性问题,局域网中可以使用IP来代替MAC。
2... | bigcode/self-oss-instruct-sc2-concepts |
import re
def is_string_valid_source_package_name(pkgname: str) -> bool:
"""
Check if a package name is debian compliant
The source package name should be all in lower case, and can contain letters, digits, and dashes.
Some other characters are also allowed.
:param pkgname: string to check
:... | bigcode/self-oss-instruct-sc2-concepts |
def _is_primitive(obj):
"""
Check if the given object is a primitive type
Args:
obj: the object to test
Returns:
True if the object is primitive i.e. hasn't a __dict__ attribute
"""
return not hasattr(obj, '__dict__') | bigcode/self-oss-instruct-sc2-concepts |
def real_basename(path):
"""Python's os.path.basename is not basename."""
if path.rsplit('/', 1)[1] is '': return None
return path.rsplit('/', 1)[1] | bigcode/self-oss-instruct-sc2-concepts |
import logging
def get_logger(name):
"""
Create new logger with the given name
:param name: Name of the logger
:return: Logger
"""
logger = logging.getLogger(name)
return logger | bigcode/self-oss-instruct-sc2-concepts |
import re
import random
def choose(phenny, input):
""".choose <red> <blue> - for when you just can't decide"""
origterm = input.groups()[1]
if not origterm:
return phenny.say(".choose <red> <blue> - for when you just can't decide")
c = re.findall(r'([^, ]+)', origterm)
fate = random.choice... | bigcode/self-oss-instruct-sc2-concepts |
import math
def complex_from_angle(phi, radius):
"""Return the complex number with argument 'phi' and absolute value 'radius'."""
return complex(math.cos(phi) * radius, math.sin(phi) * radius) | bigcode/self-oss-instruct-sc2-concepts |
async def get_all_entities(entities):
"""Get all entities on the same dict.
Watson API will return a list containing dictionaries for each,
entity found. On large numbers of entities it becomes hard to get
what we want, this function is meant to be an helper function to get
all the entities into a ... | bigcode/self-oss-instruct-sc2-concepts |
def let_user_choose(first, second, separator='|'):
"""
This function append both value (as string) inserting a separator inbetween.
:param first: First value.
:param second: Second value.
:param separator: Optional separator.
:return: first + separator + second.
>>> let_user_choose("first",... | bigcode/self-oss-instruct-sc2-concepts |
def duration(t):
"""
Give a nice short and readable string representation of a given time
duration in seconds, e.g. how long it took to render the whole project.
Usage
-----
>>> timetag = duration(t)
Parameters
----------
The time that has passed in seconds (int or float).
... | bigcode/self-oss-instruct-sc2-concepts |
def get_es_result(mode, current, best_so_far):
"""Returns true if monitored metric has been improved"""
if mode == 'max':
return current > best_so_far
elif mode == 'min':
return current < best_so_far | bigcode/self-oss-instruct-sc2-concepts |
import sympy
def is_multiplication_by_reciprocal(sympy_mul: sympy.Mul) -> bool:
"""Check if given sympy multiplication is of the form x * (1 / y)."""
args = sympy_mul.args
return len(args) == 2 and isinstance(args[1], sympy.Pow) and args[1].args[1] == -1 | bigcode/self-oss-instruct-sc2-concepts |
def get_param(gates, sweepgate):
""" Get qcodes parameter from scanjob argument """
if isinstance(sweepgate, str):
return getattr(gates, sweepgate)
else:
# assume the argument already is a parameter
return sweepgate | bigcode/self-oss-instruct-sc2-concepts |
def filter_selected(list_values, value):
"""
Check if a value exists in a list.
Parameters:
list_values = A non-empty list.
value = A value
Returns: True if the value exists in the list.
"""
return value in list_values | bigcode/self-oss-instruct-sc2-concepts |
def _filter(lst, func=None):
"""Filter a list according to a predicate.
Takes a sequence [o1,o2,..] and returns a list contains those which
are not `None` and satisfy the predicate `func(o)`
:param lst: Input iterable (not a dictionary)
:param func: Predicate function. If ``none``, this function a... | bigcode/self-oss-instruct-sc2-concepts |
def next_month_id(monthid):
"""
Return a month id that is one month ahead of the input.
Argument:
monthid - a valid month id in the format of YYYYMM
"""
month = monthid % 100
year = monthid // 100
if month == 12:
year += 1
month = 1
else:
month += 1
... | bigcode/self-oss-instruct-sc2-concepts |
def get_frame_index_int(image_file):
"""Returns an int-type index of the image file"""
return int(image_file.split('_')[-1].split('.')[0]) | bigcode/self-oss-instruct-sc2-concepts |
def find_free_game(games):
"""
finds the Free Game of the Day on MLB.TV
:param games: list of GameData() objects
:return: the free game's unique id: game_pk
"""
for game in games:
if game.free == 'ALL':
return game.game_pk | bigcode/self-oss-instruct-sc2-concepts |
def _base64_len(length):
"""Converts a length in 8 bit bytes to a length in 6 bits per byte base64 encoding"""
# Every 24 bits (3 bytes) becomes 32 bits (4 bytes, 6 bits encoded per byte)
# End is padded with '=' to make the result a multiple of 4
units, trailing = divmod(length, 3)
if trailing:
... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Union
from pathlib import Path
from typing import List
def get_files(path: Union[Path, str], extension='.wav') -> List[Path]:
""" Get all files from all subdirs with given extension. """
path = Path(path).expanduser().resolve()
return list(path.rglob(f'*{extension}')) | bigcode/self-oss-instruct-sc2-concepts |
def skipForLogfile(fragment, msg):
"""Return a decorator that skips the test for logfiles containing fragment."""
def testdecorator(testfunc):
def testwrapper(self, *args, **kwargs):
if fragment in self.logfile.filename:
self.skipTest(msg)
else:
te... | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
from typing import Any
def flatten_list_of_lists(list_of_lists: List[List[Any]]) -> List[Any]:
"""Flattens a list of lists."""
output = []
for one_list in list_of_lists:
output += one_list
return output | bigcode/self-oss-instruct-sc2-concepts |
import pathlib
def parse_requirements(filename):
"""Load requirements from a pip requirements file."""
with pathlib.Path(filename).open() as fp:
lines = (line.split('#')[0].strip() for line in fp)
return [line for line in lines if line and not line.startswith('--')] | bigcode/self-oss-instruct-sc2-concepts |
import typing
import itertools
def generate_permutations_with_replacement(width: int, seq_length: int) -> typing.List[typing.Tuple[int, ...]]:
"""
Generates a list containing all seq_length**width possible permutations
:param width: The length of each combination.
:param seq_length: The amount of eac... | bigcode/self-oss-instruct-sc2-concepts |
def coarse_pos_e(tags):
"""
Coarse POS tags of Treebank corpus: N: Noun, V: Verb, A: Adjective,
D: Adverb, Z: Pronoun, T: Determiner, E: Preposition, P: Postposition,
U: Number, J: Conjunction, O: Punctuation, R: Residual, L: Classifier,
I: Interjection
>>> coarse_pos_e(['Nasp---', 'pers', 'pro... | bigcode/self-oss-instruct-sc2-concepts |
import inspect
def get_calling_frame_variables( call_depth ):
"""
Uses the inspect module to get hold of the calling frames leading to this
function, picks the frame 'call_depth' back (up the call stack), then
gets the local and global variables as they exist in the scope of that
caller function. ... | bigcode/self-oss-instruct-sc2-concepts |
def error_response(error_message: str) -> dict:
"""
Form an error REST api response dict.
:param error_message: string error message
:return:
"""
return {
"success": False,
"error": error_message,
"data": None,
} | bigcode/self-oss-instruct-sc2-concepts |
def remaining_G9_12_cap(k12):
"""
Remaining enrollment capacity available at the school.
"""
return (k12['G9_12_cap'] - k12['G9_12']).clip(0) | bigcode/self-oss-instruct-sc2-concepts |
def _none_2_empty(text) -> str:
"""Translate None to empty string."""
if text is None:
return ""
return text | bigcode/self-oss-instruct-sc2-concepts |
def process_string(string: str) -> str:
"""Change escape sequences to the chars they match
ex: process_string("\\\\n") -> "\\n\""""
replacements = [
("\\\\", "\x00"),
("\\n", "\n"),
("\\t", "\t"),
("\\r", "\r"),
('\\"', '\"'),
("\\'", "'"),
("\x00", "\\"),
]
for search, replace in replacements:
str... | bigcode/self-oss-instruct-sc2-concepts |
def parse(query: str) -> str:
"""
Parse URL query into correct SQL syntax.
:param query: SQL query pulled from URL argument.
:return: Parsed query converted to valid SQL syntax.
"""
query_split = query.split("+")
return " ".join(query_split) | bigcode/self-oss-instruct-sc2-concepts |
def format_changes(changes):
"""
Format changes so it will look better.
ref on changeset:
https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-updating-stacks-changesets-view.html
"""
parts = []
for change in changes:
change_ = change["ResourceChange"]
l... | bigcode/self-oss-instruct-sc2-concepts |
def _make_style_str(styledict):
"""
Make an SVG style string from the dictionary. See also _parse_style_str also.
"""
s = ''
for key in styledict.keys():
s += "%s:%s;"%(key, styledict[key])
return s | bigcode/self-oss-instruct-sc2-concepts |
def chem_pot_cols(chems):
"""Return columns corresponding to the chemical potential
:chems: str
:returns: list str
"""
return ["param_chem_pot({})".format(c) for c in chems] | bigcode/self-oss-instruct-sc2-concepts |
def annotated_frames(scribbles_data):
""" Finds which frames have a scribble.
# Arguments
scribbles_data (dict): Scribble in the default format.
# Returns
list: Number of the frames that contain at least one scribble.
"""
scribbles = scribbles_data['scribbles']
frames_list = [i... | bigcode/self-oss-instruct-sc2-concepts |
def find_fusion_energy_per_reaction(reactants: str) -> float:
"""Finds the average fusion energy produced per fusion reaction in joules
from the fuel type.
Args:
reactants: the isotopes that are combined in the fusion even. Options
are "DD" or "DT"
Returns:
The average energy... | bigcode/self-oss-instruct-sc2-concepts |
def window_bounds(i, n, wn):
"""Start and stop indices for a moving window.
Parameters
----------
i : int
Current index
n : int
Total number of points
wn : int, odd
Total window size
Returns
-------
start : int
Start index
stop : int
Stop... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Optional
def linear_search(numbers: list[int], target: int) -> Optional[int]:
"""Search a target from the input using linear search algorithm
:param numbers: a collection with comparable items (not required to be sorted)
:param target: item value to search
:return: index of found i... | bigcode/self-oss-instruct-sc2-concepts |
def clipping(X, lo, hi):
"""
Helper function for clipping.
Args:
-- X: Pytorch tensor of shape (N, C, H, W)
-- lo: list, lower bound for each channel
-- hi: list, upper bound for each channel
Returns:
-- X: Pytorch tensor of shape (N, C, H, W)
"""
for c in range(3):
X.d... | bigcode/self-oss-instruct-sc2-concepts |
def percentage(value):
"""Converts a fraction to a percentage."""
return '{:.0f}'.format(value * 100) | 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.