seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
def change(seq, start, end, change):
"""Return the sequence with ``seq[start:end]`` replaced by ``change``"""
return seq[:start] + change + seq[end:] | bigcode/self-oss-instruct-sc2-concepts |
def beta_word(beta: float) -> str:
"""Describe a beta
Parameters
----------
beta : float
The beta for a portfolio
Returns
----------
str
The description of the beta
"""
if abs(1 - beta) > 3:
part = "extremely "
elif abs(1 - beta) > 2:
part = "ver... | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
import importlib
def instanciate_classes(modules: dict, module_root) -> List:
"""
Creates sources based on the config file where each key is a module and each subkey is a class
Each class can also have custom configurations when creating an instance
:param modules: dictionary w... | bigcode/self-oss-instruct-sc2-concepts |
def exp_points(df):
"""
Calculates expected points for home and away team
"""
df["H_Pts_Exp"] = 3 * df["H_prob_odds"] + 1 * df["D_prob_odds"]
df["A_Pts_Exp"] = 3 * df["A_prob_odds"] + 1 * df["D_prob_odds"]
return df | bigcode/self-oss-instruct-sc2-concepts |
import requests
from bs4 import BeautifulSoup
def get_soup_web(path):
""" Return the soup object of the url passed as argument."""
url = path
r = requests.get(url)
r_html = r.text
soup = BeautifulSoup(r_html, "html.parser")
return soup | bigcode/self-oss-instruct-sc2-concepts |
def split_sections(record):
"""Split record to LOCUS, VERSION, FEATURES and ORIGIN sections"""
ret = {'LOCUS': [], 'VERSION': [], 'FEATURES': [], 'ORIGIN': []}
keywords = ['LOCUS', 'DEFINITION', 'ACCESSION', 'VERSION', 'KEYWORDS', 'SOURCE', 'REFERENCE', 'FEATURES', 'ORIGIN']
key = ''
for line in re... | bigcode/self-oss-instruct-sc2-concepts |
def find_ultimate_dependency(cache, deps):
"""Find any one manually-installed package that ultimately caused at
least one of the given deps to be installed. Returns "" if none found.
"""
depchain = {dep: dep for dep in deps}
while depchain:
newchain = {}
for dep, path in depchain.items():
for parent in cach... | bigcode/self-oss-instruct-sc2-concepts |
def get_conv_fname(fname: str, dest_ext: str, output_dir=None) -> str:
"""Returns the filename and path of the file after conversion
Arguments:
fname -- the original filename
dest_ext -- the extension of the destination file
output_dir -- the output directory of the operation
"""
if output... | bigcode/self-oss-instruct-sc2-concepts |
def keffLineParse(keffLine):
"""
Parses through the anaKeff line in .res file.
@ In, keffLine, string, string from .res file listing IMPKEFF
@ Out, keffTuple, list, (mean IMPKEFF, sd of IMPKEFF)
"""
newKeffLine = keffLine[keffLine.find('='):]
start = newKeffLine.find('[')
end = newKeffLine.find(']... | bigcode/self-oss-instruct-sc2-concepts |
def from_dataframe(df):
"""Turn a dataframe into a dictionary of columns, suitable writing."""
index = {}
for column in df.columns:
values = df[column].values
if(values.dtype == "object"):
index[column] = values.tolist()
else:
index[column] = values
retu... | bigcode/self-oss-instruct-sc2-concepts |
def index_sites(structure, species=None, labels=None):
"""
Return a list of the site indices in a structure that are occupied by specie or label (or both)
Args:
- structure (Structure): pymatgen structure object
- species ({str}): site species to count
- label ({str}): sit... | bigcode/self-oss-instruct-sc2-concepts |
def getHttpStatusCode(v):
"""Return HTTP response code as integer, e.g. 204."""
if hasattr(v, "value"):
return int(v.value) # v is a DAVError
else:
return int(v) | bigcode/self-oss-instruct-sc2-concepts |
import json
def get_sns_msg(event):
"""Returns a message object extracted from AWS SNS event.
:param event: AWS event object
:type event: dict
:returns: JSON serialized SNS message object
:rtype: dict
"""
return json.loads(event['Records'][0]['Sns']['Message']) | bigcode/self-oss-instruct-sc2-concepts |
def dfs_visited_re(node, graph, visited=[]):
"""DFS: Return visited nodes via recursion"""
for child in graph[node]:
if child not in visited:
visited.append(child)
dfs_visited_re(child, graph, visited)
return visited | bigcode/self-oss-instruct-sc2-concepts |
import json
def convert_json_to_dict(filename):
""" Convert json file to python dictionary
"""
with open(filename, 'r') as JSON:
json_dict = json.load(JSON)
return json_dict | bigcode/self-oss-instruct-sc2-concepts |
import math
def distance(x1: float, y1: float, x2: float, y2: float):
"""
Return distance between two 2D points.
"""
dx = x2 - x1
dy = y2 - y1
return math.sqrt(dx * dx + dy * dy) | bigcode/self-oss-instruct-sc2-concepts |
def get_last(s):
"""Get the last item in a Pandas Series"""
return s.iloc[-1] | bigcode/self-oss-instruct-sc2-concepts |
def excel_column_number(name):
"""Excel-style column name to number, e.g., A = 1, Z = 26, AA = 27, AAA = 703."""
n = 0
for c in name:
n = n * 26 + 1 + ord(c) - ord('A')
return n | bigcode/self-oss-instruct-sc2-concepts |
def set_val_or_default(in_dict, key, val):
"""Helper functions to either get and item from or add an item to a dictionary and return that item
Parameters
----------
in_dict : `dict`
input dictionary
key : `str`
key to search for
val : `dict` or `function`
item to add to ... | bigcode/self-oss-instruct-sc2-concepts |
from warnings import warn
def read_and_check(file_handle, byte_sizes):
"""
Return data read from input file stream in segments of specified byte sizes
and check for complete reads.
Inputs:
file_handle - Handle to file to read from.
byte_sizes - List of byte sizes to read.
Outputs:
... | bigcode/self-oss-instruct-sc2-concepts |
import textwrap
def mutations( seqID='A' ): # pragma: no cover
"""RosettaScript to execute a
`RESFILE <https://www.rosettacommons.org/docs/latest/rosetta_basics/file_types/resfiles>`_.
:param str seqID: |seqID_param|
:return: :class:`str`
.. seealso::
:func:`.DesignFrame.apply_resfile`... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Dict
from typing import List
import re
def get_typos_in_string(s: str, known_typos: Dict[str, str]) -> List:
"""
>>> get_typos_in_string('foo buzz', {'foo': 'bar', 'bazz': 'buzz'})
['foo']
>>> get_typos_in_string('foo bazz', {'foo': 'bar', 'bazz': 'buzz'})
['bazz', 'foo']
"... | bigcode/self-oss-instruct-sc2-concepts |
def valid_chunk_size(chunk_size):
# type: (int) -> bool
"""Checks whether chunk size is multiple of 256 KiB.
Args:
chunk_size (int): Input chunk_size to be validated.
Returns:
bool: True if chunk_size is multiple of 256 KiB, False otherwise.
"""
return not bool(chunk_size % 262... | bigcode/self-oss-instruct-sc2-concepts |
def calculate_range(histogram, words, index):
"""Return the difference between the high and low ends of a range for a
value in the modified histogram.
Param: histogram(dict): modified so each value is a tuple
words(list): a list of the keys in histogram
index(int): a way fo... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Any
import gzip
import pickle
def load_object(path: str, compressed: bool = True) -> Any:
"""Reads a python object into memory that's been saved to disk.
Args:
path: the file path of the object to load
compressed: flag to specify whether the file was compressed prior to sav... | bigcode/self-oss-instruct-sc2-concepts |
from datetime import datetime
def datetime_to_epoch(datetime: datetime, ms: bool = True) -> int:
"""
Convert a python datetime to number of (milli-) seconds since epoch.
"""
if ms:
return int(datetime.timestamp() * 1000)
return int(datetime.timestamp()) | bigcode/self-oss-instruct-sc2-concepts |
def colorize(text, color):
"""
Wrap `text` with ANSI `color` code. See
https://stackoverflow.com/questions/4842424/list-of-ansi-color-escape-sequences
"""
code = f"\033[{color}m"
restore = "\033[0m"
return "".join([code, text, restore]) | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
def ligands_from_conformers(conformers: List[str]) -> List[str]:
"""
Extract the ligands from a list of conformers.
"""
return [conformer.split('_')[0] for conformer in conformers] | bigcode/self-oss-instruct-sc2-concepts |
def bit_on(num, bit):
"""Return the value of a number's bit position.
>>> [bit_on(42, i) for i in range(clog2(42))]
[0, 1, 0, 1, 0, 1]
"""
return (num >> bit) & 1 | bigcode/self-oss-instruct-sc2-concepts |
def load_filepaths(filename):
"""Read in a list of file paths.
Args:
filename: A text file containing a list of file paths. Assume that
each line has one file path.
Returns:
filepaths: A list of strings where each is a file path.
"""
with open(filename) as f:
filepa... | bigcode/self-oss-instruct-sc2-concepts |
import requests
def _http_get(url, session=None, stream=True, **kwargs):
"""Make a GET request with the URL.
Any errors from the HTTP request (non 200 codes) will raise an HTTPError.
:param url: The URL to GET.
:type url: str
:param session: Optional :class:`~requests.Session` object to use to m... | bigcode/self-oss-instruct-sc2-concepts |
def SignToBool(inp):
"""Converts signed bits into boolean bits
-1 -> 0
1 -> 1"""
return (inp + 1) / 2 | bigcode/self-oss-instruct-sc2-concepts |
import re
def trim_after(string, regex, include_pattern=False):
"""Trim a string after the first match of regex.
If fail to match any pattern, the original string is returned
The matched pattern is trimed as well.
Args:
string (str): the string to trim
regex (regex): the regex to ma... | bigcode/self-oss-instruct-sc2-concepts |
def crowdsale(uncapped_flatprice, uncapped_flatprice_finalizer, team_multisig):
"""Set up a crowdsale with customer id require policy."""
uncapped_flatprice.transact({"from": team_multisig}).setRequireCustomerId(True)
return uncapped_flatprice | bigcode/self-oss-instruct-sc2-concepts |
def _return_arg(__arg: ..., /) -> ...:
"""Return the singular positional argument unchanged."""
return __arg | bigcode/self-oss-instruct-sc2-concepts |
def display_iscsi_device(iqn, sess):
"""
Print the data for iscsi device identified by iqn.
Parameters
----------
iqn: str
The iSCSI qualified name.
sess: OCISession
An oci sdk session.
Returns
-------
bool: True on success, False otherwise.
"""
this_compa... | bigcode/self-oss-instruct-sc2-concepts |
def get_fitness(traceIsFit, traceFitnessValue):
"""
Gets a dictionary expressing fitness in a synthetic way from the list of boolean values
saying if a trace in the log is fit, and the float values of fitness associated to each trace
Parameters
------------
traceIsFit
Boolean value that... | bigcode/self-oss-instruct-sc2-concepts |
import re
def make_key(word: str, sense: str) -> str:
"""Create a key from a word and sense, e.g. "usage_example|NOUN".
word (unicode): The word.
sense (unicode): The sense.
RETURNS (unicode): The key.
"""
text = re.sub(r"\s", "_", word)
return text + "|" + sense | bigcode/self-oss-instruct-sc2-concepts |
def discard_unknown_labels(labels):
"""Function for discarding medial wall (unknown) labels from a list
of labels.
Input arguments:
================
labels : list
List of labels. Each label must be an instance of the MNE-Python
Label class.
Output arguments:
===============... | bigcode/self-oss-instruct-sc2-concepts |
def org_default_payload(login: str, uid: int):
"""Provide the basic structure for an organization payload."""
return {
'action': 'member_added',
'membership': {
'url': '',
'state': 'pending',
'role': 'member',
'organization_url': '',
'u... | bigcode/self-oss-instruct-sc2-concepts |
def generate_brightness_string_from_brightness_barcode(brightness_barcode, num_interval=15):
"""
Helper function
Generate the string where each character represents the brightness interval of the brightness in the input
brightness barcode.
:param brightness_barcode: Input 1 dimensional brightness b... | bigcode/self-oss-instruct-sc2-concepts |
def rfcspace(string):
"""
If the string is an RFC designation, and doesn't have
a space between 'RFC' and the rfc-number, a space is
added
"""
string = str(string)
if string[:3].lower() == "rfc" and string[3] != " ":
return string[:3].upper() + " " + string[3:]
else:
retu... | bigcode/self-oss-instruct-sc2-concepts |
def extract_header(filename: str):
""" Extract the header of a Deltamed .eeg file.
Args:
filename: path to the .eeg file.
Returns:
A list of bytes
"""
header = []
with open(filename, 'rb') as file_:
header = [
char if isinstance(char, bytes) else bytes([char... | bigcode/self-oss-instruct-sc2-concepts |
def named(values, names):
"""Creates a dict with `names` as fields, and `values` as values."""
return dict(zip(names.split(), values)) | bigcode/self-oss-instruct-sc2-concepts |
def get_majority_vote(a):
"""
Returns the majority vote element of a list
"""
return max(map(lambda val: (a.count(val), val), set(a)))[1] | bigcode/self-oss-instruct-sc2-concepts |
def hasQueryMatch(qList, tweetJSON):
"""Returns true if a tweet containing any keyword in QUERY_KEYWORDS is found"""
return any(keyword in tweetJSON['text'] for keyword in qList) | bigcode/self-oss-instruct-sc2-concepts |
import torch
def get_window(name, window_length, squared=False):
"""
Returns a windowing function.
Arguments:
window (str): name of the window, currently only 'hann' is available
window_length (int): length of the window
squared (bool): if true, square the window
Returns:
... | bigcode/self-oss-instruct-sc2-concepts |
import math
def binom(n, k):
"""
Compute a binomial coefficient (n choose k).
Parameters
----------
n, k : int
Positive integers.
Returns
-------
int
"""
# could be replace by math.comb(n, k) in Python >= 3.8
try:
return math.factorial(n) // ma... | bigcode/self-oss-instruct-sc2-concepts |
def get_kinds_section(structure, protocol_settings):
""" Write the &KIND sections given the structure and the settings_dict"""
kinds = []
all_atoms = set(structure.get_ase().get_chemical_symbols())
for atom in all_atoms:
kinds.append({
'_': atom,
'BASIS_SET': protocol_set... | bigcode/self-oss-instruct-sc2-concepts |
def sanitizeContents(contents:str) -> str:
"""
Sanitizes the input `contents` string to be a well-behaved config file.
"""
out = []
for line in contents.splitlines():
tmp=(" ".join(line.split())).strip() #squeezes spaces and trims leading and trailing spaces
tmp=tmp.replace("&", '&') #decodes HTML-encoded ... | bigcode/self-oss-instruct-sc2-concepts |
def add_metadata_defaults(md):
"""Central location for defaults for algorithm inputs.
"""
defaults = {"batch": None,
"phenotype": ""}
for k, v in defaults.items():
if k not in md:
md[k] = v
return md | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
def parse_reqs(requirements_file: str) -> List[str]:
"""Get requirements as a list of strings from the file."""
with open(requirements_file) as reqs:
return [r for r in reqs if r] | bigcode/self-oss-instruct-sc2-concepts |
def _mean_int(*args):
"""Return the mean of the supplied values."""
return int(sum(args) / len(args)) | bigcode/self-oss-instruct-sc2-concepts |
def payload_2(kernels, time_2, output_time_format, output_time_custom_format):
"""Payload from WGC API example 2."""
return {
"kernels": [{
"type": "KERNEL_SET",
"id": kernels,
}],
"times": [
time_2,
],
"calculationType": "TIME_CONVERSI... | bigcode/self-oss-instruct-sc2-concepts |
def nodeKey(search, node, goal, heuristicFunc):
"""
Give sort key that prioritizes node based on search, where min key is higher priority.
This prioritization is essentially the difference between the various search algorithms.
"""
if search == 'A*':
g = node.cost;
h = heu... | bigcode/self-oss-instruct-sc2-concepts |
def _has_surrogates(s):
"""Return True if s contains surrogate-escaped binary data."""
try:
s.encode()
return False
except UnicodeEncodeError:
return True | bigcode/self-oss-instruct-sc2-concepts |
def format_indent_line(items, spaces, indent, backslash, is_last):
"""Returns elements separated by commas. The line can be indented. This function is for
internal use and is not available in templates.
:param list items: a list of items.
:param int spaces: indentation spaces
:param bool indent: in... | bigcode/self-oss-instruct-sc2-concepts |
def tower_of_hanoi(
n: int = 1,
from_rod: str = 'A',
to_rod: str = 'B',
through_road: str = 'C'
) -> str:
"""
Solving the Hanoi Towers puzzle.
Returns a string with the sequence of disc changes from rod to rod in the format 'disk_number from_rod->to_rod'
If n < 0 it raise... | bigcode/self-oss-instruct-sc2-concepts |
def parse_exts(extstr):
""" Parse a comma or space-separated list of file extensions. """
if not extstr:
return None
exts = []
for word in extstr.split():
exts.extend((s for s in word.split(',') if s))
return set((
s if s.startswith('.') else '.{}'.format(s)
for s in ... | bigcode/self-oss-instruct-sc2-concepts |
import re
def get_prefixes_from_labels(labels):
"""Extracts a unique list of trigger prefixes from a dict of labels.
"""
regex = r'^SCALING_TRIGGER_[0-9]+_'
trigger_prefixes = set()
for k in labels:
match = re.match(regex, k)
if match is not None:
trigger_prefixes.add(m... | bigcode/self-oss-instruct-sc2-concepts |
def get_form_details(form):
"""
This function extracts all possible useful information about an HTML `form`
"""
details = {}
# get the form action (target url)
action = form.attrs.get("action").lower()
# get the form method (POST, GET, etc.)
method = form.attrs.get("method", "get").lower... | bigcode/self-oss-instruct-sc2-concepts |
def num_of_books_complete_message(tracker):
"""Return the number of books complete in a message string format."""
num_of_books_complete = tracker.shelf.num_complete_books
message = f"You have completed {num_of_books_complete} book"
message += "s" if num_of_books_complete != 1 else "" # Add plural
m... | bigcode/self-oss-instruct-sc2-concepts |
def extract_all_wiki_links(entry):
"""
Extract all wikipedia links associated to an entry
:param entry: entry data
:return:
"""
if "sitelinks" in entry:
return entry['sitelinks'] | bigcode/self-oss-instruct-sc2-concepts |
def escape_attribute(value, encoding):
"""Escape an attribute value using the given encoding."""
if "&" in value:
value = value.replace("&", "&")
if "<" in value:
value = value.replace("<", "<")
if '"' in value:
value = value.replace('"', """)
return value.encode(... | bigcode/self-oss-instruct-sc2-concepts |
def is_uc_alpha(astring):
"""
(str) -> Boolean
return True if any char in astring is an
uppercase letter.
else return False
>>> is_uc_alpha('CIS122')
True
>>> is_uc_alpha('Ducks')
True
>>> is_uc_alpha('testing')
False
"""
for c in astring:
if c.isupper():
... | bigcode/self-oss-instruct-sc2-concepts |
def get_window_in_sec(s):
"""Returns number of seconds in a given duration or zero if it fails.
Supported durations are seconds (s), minutes (m), hours (h), and days(d)."""
seconds_per_unit = {"s": 1, "m": 60, "h": 3600, "d": 86400}
try:
return int(float(s[:-1])) * seconds_per_unit[s[-1]]
ex... | bigcode/self-oss-instruct-sc2-concepts |
def echo(event):
"""Echoes back the message it recieves."""
return ' '.join(event.args) | bigcode/self-oss-instruct-sc2-concepts |
import random
def random_int(*, k_min: int = 1, k_max: int = 100000) -> int:
"""Generate a random integer."""
return random.randint(k_min, k_max) | bigcode/self-oss-instruct-sc2-concepts |
def permutations(lst):
"""Lists all permutations of the given list.
>>> permutations(['angie', 'cat'])
[['angie', 'cat'], ['cat', 'angie']]
>>> permutations([1, 2, 3])
[[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]
"""
if len(lst) <= 1:
return [lst]
total = [... | bigcode/self-oss-instruct-sc2-concepts |
def set_walls(rooms, walls):
"""
Sets the number of walls between every room
:param rooms: Dictionary of room objects
:param walls: nested list containing number of walls between each room
:return: the updated rooms dictionary
"""
# loop through all walls except the first row, since does not... | bigcode/self-oss-instruct-sc2-concepts |
def coverage(g, c):
"""Evaluates the coverage of the clustering solution c on a given graph g."""
n = len(g.vs)
A_delta = 0
A = 0
for i in range(n):
for j in g.neighbors(i):
A += 1
if c[i] == c[j]:
A_delta += 1
return A_delta/A | bigcode/self-oss-instruct-sc2-concepts |
def bytesToMac(addr_bytes):
"""Convert byte sequence into MAC address
Byte sequence can comprise of both single character string elements, as
well as byte-encoded string elements, which is extracted as an int. So we
need to convert the character to its ordinal Unicode datapoint.
b'\\xac\\x84\\xc6\... | bigcode/self-oss-instruct-sc2-concepts |
def mni2tal(xin):
"""
mni2tal for converting from ch2/mni space to tal - very approximate.
This is a standard approach but it's not very accurate.
ANTsR function: `mni2tal`
Arguments
---------
xin : tuple
point in mni152 space.
Returns
-------
tuple
Example
-... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Set
def is_sum_of_numbers(number: int, numbers: Set[int]) -> bool:
"""Check if a given number `number` is the sum of any two numbers from `numbers`."""
for i in range(1, number):
if i in numbers and (number - i) in numbers:
return True
return False | bigcode/self-oss-instruct-sc2-concepts |
def safe_int(to_int: str) -> int:
"""Return int from str safely."""
try:
return int(to_int)
except ValueError:
return -1 | bigcode/self-oss-instruct-sc2-concepts |
def parse_events(props):
"""
Pull out the dashEvents from the Component props
Parameters
----------
props: dict
Dictionary with {propName: propMetadata} structure
Returns
-------
list
List of Dash event strings
"""
if 'dashEvents' in props and props['dashEvents'... | bigcode/self-oss-instruct-sc2-concepts |
def make_successive(xs):
"""
Return a list of successive combinations
Parameters
----------
xs : list
List of elements, e.g. [X, Y, Z]
Returns
-------
list
List of combinations where each combination include all the preceding elements
Examples
--------
>>> ... | bigcode/self-oss-instruct-sc2-concepts |
def y2label(y_pred, int2tag, mask=0):
"""
Transforms numbers to the corresponding label
:param y_pred: list of lists of tag predictions as integers for each word in a sentence
:param int2tag: (dict) dictionary of integers to their corresponding tag
:param mask: (int) integer corresponding to '-PAD-'... | bigcode/self-oss-instruct-sc2-concepts |
def set_custom_certs_enabled(
self,
enabled: bool,
) -> dict:
"""Enable or disable custom CA certificate trust store
.. list-table::
:header-rows: 1
* - Swagger Section
- Method
- Endpoint
* - customCerts
- POST
- /customCert/enable
... | bigcode/self-oss-instruct-sc2-concepts |
def location_modifier(fields):
"""
Modify the parsed location variable.
Subtract 1 from all the start positions in order to be able to use pd.read_fwf()
Parameters:
field (list): The list of tuples created by location_parser()
Returns:
fields: A list of tuples
"""
for i, i... | bigcode/self-oss-instruct-sc2-concepts |
def format_output(dets, w, h):
"""
:param dets: detection result input: x1, y1, x2, y2, score, cls_id
:param w: image's original width
:param h: image's original height
:return: list of items: cls_id, conf_score, center_x, center_y, bbox_w, bbox_h, [0, 1]
"""
if dets is None:
return... | bigcode/self-oss-instruct-sc2-concepts |
def snake_to_camel(name):
"""Converts Python Snake Case to Zscaler's lower camelCase."""
# Edge-cases where camelCase is breaking
edge_cases = {
"routable_ip": "routableIP",
"is_name_l10n_tag": "isNameL10nTag",
"name_l10n_tag": "nameL10nTag",
"surrogate_ip": "surrogateIP",
... | bigcode/self-oss-instruct-sc2-concepts |
def has_keys(data, keys):
"""
Checks whether a dictionary has all the given keys.
@type data: dict
@param data: Parameter name
@type keys: list
@param keys: list containing the expected keys to be found in the dict.
@rtype: bool
@return: True if all the keys are found in the dict, ... | bigcode/self-oss-instruct-sc2-concepts |
import string
def simple(s):
"""Break str `s` into a list of str.
1. `s` has all of its peripheral whitespace removed.
1. `s` is downcased with `lower`.
2. `s` is split on whitespace.
3. For each token, any peripheral punctuation on it is stripped
off. Punctuation is here defined by `strin... | bigcode/self-oss-instruct-sc2-concepts |
def _normalize_depth_vars(depth_k, depth_v, filters):
"""
Accepts depth_k and depth_v as either floats or integers
and normalizes them to integers.
Args:
depth_k: float or int.
depth_v: float or int.
filters: number of output filters.
Returns:
depth_k, depth_v as inte... | bigcode/self-oss-instruct-sc2-concepts |
def add_comma_rs(_index, _value, _row_separator):
"""Adds a comma and row separator if index > 0, used in loops when making lists of references."""
if _index > 0:
return ',' + _row_separator + _value
else:
return _value
# Some database functions | bigcode/self-oss-instruct-sc2-concepts |
def group_values_nearest(values, closest=2):
"""Group given values together under multiple buckets.
:param values: values to group
:type values: list
:param closest: closest is the maximun value difference between two values
in order to be considering in the same bucket, defaults to 2
:type clo... | bigcode/self-oss-instruct-sc2-concepts |
def combinations(seqs):
"""
Recipe 496807 from ActiveState Python CookBook
Non recursive technique for getting all possible combinations of a sequence
of sequences.
"""
r=[[]]
for x in seqs:
r = [ i + [y] for y in x for i in r ]
return r | bigcode/self-oss-instruct-sc2-concepts |
def collect_content(parent_tag):
"""Collects all text from children p tags of parent_tag"""
content = ''
for tag in parent_tag:
p_tags = tag.find_all('p')
for tag in p_tags:
content += tag.text + '\n'
return content | bigcode/self-oss-instruct-sc2-concepts |
def build_gameboard(term):
"""Build the gameboard layout."""
column, row = 0, 0
board = dict()
spacing = 2
for keycode in sorted(term._keycodes.values()):
if (keycode.startswith('KEY_F')
and keycode[-1].isdigit()
and int(keycode[len('KEY_F'):]) > 24):
... | bigcode/self-oss-instruct-sc2-concepts |
def create_error_text(error_response: dict) -> str:
"""
Creates error text for Telegram Bot error response.
See https://core.telegram.org/bots/api/#making-requests
"""
description = error_response.get("description", "?")
error_code = error_response.get("error_code", "?")
return f"{error_cod... | bigcode/self-oss-instruct-sc2-concepts |
def extract_file_names(videos_path: str) -> list:
""" Extract filenames from .lst file.
Args:
videos_path (str): Path to .lst file.
Returns:
list: List of filenames.
"""
with open(videos_path, "r") as f:
file_names = [line.strip() for line in f.readlines()]
return file... | bigcode/self-oss-instruct-sc2-concepts |
def byte_length(n):
"""Finds the byte length of an `int` object."""
return (n.bit_length() + 7) // 8 | bigcode/self-oss-instruct-sc2-concepts |
def changePlayer(player):
"""Returns the opposite player given any player"""
if player == "X":
return "O"
else:
return "X" | bigcode/self-oss-instruct-sc2-concepts |
def exp_to_int(s):
"""
Converts numbers like 1.01e+2 or 1.007783151912803607421e+21 to integers.
By default, these are parsed by the float function and lose precision
"""
if 'e' in s: #if it is exponential
exp = int(s.split('+')[1])
(whole, tmp) = s.split('.')
frac = tmp.split('e')[0]
assert(len(frac) <= e... | bigcode/self-oss-instruct-sc2-concepts |
def reduce_diff(diff):
"""remove the lines added for context and just keep the lines that show the actual differences """
new_diff = ""
for line in diff.splitlines():
if line[:2] in [" ", "? "]:
continue
new_diff += line + "\n"
return new_diff | bigcode/self-oss-instruct-sc2-concepts |
def create_time_periods(connector, future_years):
"""
This function writes the time_periods table to an sqlite
database. Only "future" time periods will be written.
Parameters
----------
connector : sqlite3 connection object
An object for connecting to a specific SQLite
database... | bigcode/self-oss-instruct-sc2-concepts |
def merge_list(list1, list2, remove_duplicate=False):
"""
merge two lists
when remove_duplicate is false, duplicate item will be kept.
when remove_dupliate is true, no duplicate item is allowed
"""
merged_list = []
if not list1 and list2:
merged_list.extend(list2)
elif list1 and ... | bigcode/self-oss-instruct-sc2-concepts |
def get_date_filter(report_config):
"""
Returns the first date filter, or None.
Assumes the first date filter is the one to use.
.. NOTE: The user might not want to filter by date for DHIS2
integration. They can use a "period" column to return
rows for multiple periods, or se... | bigcode/self-oss-instruct-sc2-concepts |
import pathlib
def join(*pthslist):
""" Returns the join of all paths"""
return str(pathlib.PurePath(*pthslist)) | 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.