seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
def _label_group(key, pattern):
"""
Build the right pattern for matching with
named entities.
>>> _label_group('key', '[0-9]{4}')
'(?P<key>[0-9]{4})'
"""
return '(?P<%s>%s)' % (key, pattern) | bigcode/self-oss-instruct-sc2-concepts |
def _to_set(loc):
"""Convert an array of locations into a set of tuple locations."""
return set(map(tuple, loc)) | bigcode/self-oss-instruct-sc2-concepts |
def is_valid_port(entry, allow_zero = False):
"""
Checks if a string or int is a valid port number.
:param list,str,int entry: string, integer or list to be checked
:param bool allow_zero: accept port number of zero (reserved by definition)
:returns: **True** if input is an integer and within the valid port range, **False** otherwise
"""
try:
value = int(entry)
if str(value) != str(entry):
return False # invalid leading char, e.g. space or zero
elif allow_zero and value == 0:
return True
else:
return value > 0 and value < 65536
except TypeError:
if isinstance(entry, (tuple, list)):
for port in entry:
if not is_valid_port(port, allow_zero):
return False
return True
else:
return False
except ValueError:
return False | bigcode/self-oss-instruct-sc2-concepts |
from typing import Any
def hide_if_not_none(secret: Any):
""" Hide a secret unless it is None, which means that the user didn't set it.
:param secret: the secret.
:return: None or 'hidden'
"""
value = None
if secret is not None:
value = 'hidden'
return value | bigcode/self-oss-instruct-sc2-concepts |
def percentIncrease(old, new):
"""
Calculates the percent increase between two numbers.
Parameters
----------
old : numeric
The old number.
new : numeric
The new number.
Returns
-------
numeric
The percent increase (as a decimal).
"""
return (new - old)/old | bigcode/self-oss-instruct-sc2-concepts |
from typing import OrderedDict
def create_model(api, name, fields):
"""Helper for creating api models with ordered fields
:param flask_restx.Api api: Flask-RESTX Api object
:param str name: Model name
:param list fields: List of tuples containing ['field name', <type>]
"""
d = OrderedDict()
for field in fields:
d[field[0]] = field[1]
return api.model(name, d) | bigcode/self-oss-instruct-sc2-concepts |
import torch
def rgb_to_srgb(image):
"""Applies gamma correction to rgb to get sRGB. Assumes input is in range [0,1]
Works for batched images too.
:param image: A pytorch tensor of shape (3, n_pixels_x, n_pixels_y) in which the channels are linearized R, G, B
:return: A pytorch tensor of shape (3, n_pixels_x, n_pixels_y) in which the channels are gamma-corrected RGB
"""
# assert torch.max(image) <= 1
small_u = image*12.92
big_u = torch.pow(image,.416)*1.055-0.055
return torch.where(image<=0.0031308, small_u, big_u) | bigcode/self-oss-instruct-sc2-concepts |
def confirmed_password_valid(password, confirmation):
"""
Tell if a password was confirmed properly
Args:
password the password to check.
confirmation the confirmation of the password.
Returns:
True if the password and confirmation are the same (no typos)
"""
return password == confirmation | bigcode/self-oss-instruct-sc2-concepts |
def contains(element):
"""
Check to see if an argument contains a specified element.
:param element: The element to check against.
:return: A predicate to check if the argument is equal to the element.
"""
def predicate(argument):
try:
return element in argument
except:
return False
return predicate | bigcode/self-oss-instruct-sc2-concepts |
def split_bbox(bbox):
"""Split a bounding box into its parts.
:param bbox: String describing a bbox e.g. '106.78674459457397,
-6.141301491467023,106.80691480636597,-6.133834354201348'
:type bbox: str
:returns: A dict with keys: 'southwest_lng, southwest_lat, northeast_lng,
northeast_lat'
:rtype: dict
"""
values = bbox.split(',')
if not len(values) == 4:
raise ValueError('Invalid bbox')
# pylint: disable=W0141
# next line should probably use list comprehension rather
# http://pylint-messages.wikidot.com/messages:w0141
values = map(float, values)
# pylint: enable=W0141
names = ['SW_lng', 'SW_lat', 'NE_lng', 'NE_lat']
coordinates = dict(zip(names, values))
return coordinates | bigcode/self-oss-instruct-sc2-concepts |
def compare_rgb_colors_tolerance(first_rgb_color, second_rgb_color, tolerance):
"""
Compares to RGB colors taking into account the given tolerance (margin for error)
:param first_rgb_color: tuple(float, float, float), first color to compare
:param second_rgb_color: tuple(float, float, float), second color to compare
:param tolerance: float, range in which the colors can vary
:return: bool, True if two colors matches within the given tolerance; False otherwise
"""
for i, value in enumerate(first_rgb_color):
if not abs(value - second_rgb_color[i]) <= tolerance:
return False
return True | bigcode/self-oss-instruct-sc2-concepts |
from pathlib import Path
def GetRendererLabelFromFilename(file_path: str) -> str:
"""Gets the renderer label from the given file name by removing the '_renderer.py' suffix."""
file_name = Path(file_path).stem
return file_name.rstrip("_renderer.py") | bigcode/self-oss-instruct-sc2-concepts |
def _sample_generator(*data_buffers):
"""
Takes a list of many mono audio data buffers and makes a sample generator
of interleaved audio samples, one sample from each channel. The resulting
generator can be used to build a multichannel audio buffer.
>>> gen = _sample_generator("abcd", "ABCD")
>>> list(gen)
["a", "A", "b", "B", "c", "C", "d", "D"]
"""
frame_gen = zip(*data_buffers)
return (sample for frame in frame_gen for sample in frame) | bigcode/self-oss-instruct-sc2-concepts |
def get_novel_smiles(new_unique_smiles, reference_unique_smiles):
"""Get novel smiles which do not appear in the reference set.
Parameters
----------
new_unique_smiles : list of str
List of SMILES from which we want to identify novel ones
reference_unique_smiles : list of str
List of reference SMILES that we already have
"""
return set(new_unique_smiles).difference(set(reference_unique_smiles)) | bigcode/self-oss-instruct-sc2-concepts |
def error(message, code=400):
"""Generate an error message.
"""
return {"error": message}, code | bigcode/self-oss-instruct-sc2-concepts |
import warnings
def _validate_buckets(categorical, k, scheme):
"""
This method validates that the hue parameter is correctly specified. Valid inputs are:
1. Both k and scheme are specified. In that case the user wants us to handle binning the data into k buckets
ourselves, using the stated algorithm. We issue a warning if the specified k is greater than 10.
2. k is left unspecified and scheme is specified. In that case the user wants us to handle binning the data
into some default (k=5) number of buckets, using the stated algorithm.
3. Both k and scheme are left unspecified. In that case the user wants us bucket the data variable using some
default algorithm (Quantiles) into some default number of buckets (5).
4. k is specified, but scheme is not. We choose to interpret this as meaning that the user wants us to handle
bucketing the data into k buckets using the default (Quantiles) bucketing algorithm.
5. categorical is True, and both k and scheme are False or left unspecified. In that case we do categorical.
Invalid inputs are:
6. categorical is True, and one of k or scheme are also specified. In this case we raise a ValueError as this
input makes no sense.
Parameters
----------
categorical : boolean
Whether or not the data values given in ``hue`` are already a categorical variable.
k : int
The number of categories to use. This variable has no effect if ``categorical`` is True, and will be set to 5
by default if it is False and not already given.
scheme : str
The PySAL scheme that the variable will be categorized according to (or rather, a string representation
thereof).
Returns
-------
(categorical, k, scheme) : tuple
A possibly modified input tuple meant for reassignment in place.
"""
if categorical and (k != 5 or scheme):
raise ValueError("Invalid input: categorical cannot be specified as True simultaneously with scheme or k "
"parameters")
if k > 10:
warnings.warn("Generating a choropleth using a categorical column with over 10 individual categories. "
"This is not recommended!")
if not scheme:
scheme = 'Quantiles' # This trips it correctly later.
return categorical, k, scheme | bigcode/self-oss-instruct-sc2-concepts |
import json
def save_json(f, cfg):
""" Save JSON-formatted file """
try:
with open(f, 'w') as configfile:
json.dump(cfg, configfile)
except:
return False
return True | bigcode/self-oss-instruct-sc2-concepts |
import math
def parallelepiped_magnet(
length=0.01, width=0.006, thickness=0.001, density=7500
):
"""
Function to get the masse, volume and inertial moment of a parallelepiped
magnet. International system units.
The hole for the axis is ignored.
"""
V = length * width * thickness
m = V * density
mom_z = m * (math.pow(length, 2) + math.pow(width, 2)) / 12
return {"V": V, "m": m, "mom_z": mom_z} | bigcode/self-oss-instruct-sc2-concepts |
def max_cw(l):
"""Return max value of a list."""
a = sorted(l)
return a[-1] | bigcode/self-oss-instruct-sc2-concepts |
def eia_mer_url_helper(build_url, config, args):
"""Build URL's for EIA_MER dataset. Critical parameter is 'tbl', representing a table from the dataset."""
urls = []
for tbl in config['tbls']:
url = build_url.replace("__tbl__", tbl)
urls.append(url)
return urls | bigcode/self-oss-instruct-sc2-concepts |
def safe_index(l, e):
"""Gets the index of e in l, providing an index of len(l) if not found"""
try:
return l.index(e)
except:
return len(l) | bigcode/self-oss-instruct-sc2-concepts |
import codecs
import json
def load_json(path_to_json: str) -> dict:
"""Load json with information about train and test sets."""
with codecs.open(path_to_json, encoding='utf-8') as train_test_info:
return json.loads(train_test_info.read()) | bigcode/self-oss-instruct-sc2-concepts |
def _and(arg1, arg2):
"""Boolean and"""
return arg1 and arg2 | bigcode/self-oss-instruct-sc2-concepts |
def get_repositories(reviewboard):
"""Return list of registered mercurial repositories"""
repos = reviewboard.repositories()
return [r for r in repos if r.tool == 'Mercurial'] | bigcode/self-oss-instruct-sc2-concepts |
import grp
def check_gid(gid):
""" Get numerical GID of a group.
Raises:
KeyError: Unknown group name.
"""
try:
return 0 + gid # already numerical?
except TypeError:
if gid.isdigit():
return int(gid)
else:
return grp.getgrnam(gid).gr_gid | bigcode/self-oss-instruct-sc2-concepts |
def bin_to_str(val):
""" Converts binary integer to string of 1s and 0s """
return str(bin(val))[2:] | bigcode/self-oss-instruct-sc2-concepts |
import signal
def register_signal_handler(sig, handler):
"""Registers a signal handler."""
return signal.signal(sig, handler) | bigcode/self-oss-instruct-sc2-concepts |
def AfterTaxIncome(combined, expanded_income, aftertax_income,
Business_tax_expinc, corp_taxliab):
"""
Calculates after-tax expanded income.
Parameters
----------
combined: combined tax liability
expanded_income: expanded income
corp_taxliab: imputed corporate tax liability
Returns
-------
aftertax_income: expanded_income minus combined
"""
if Business_tax_expinc is True:
expanded_income = expanded_income + corp_taxliab
else:
expanded_income = expanded_income
aftertax_income = expanded_income - combined
return aftertax_income | bigcode/self-oss-instruct-sc2-concepts |
def _find_tbl_starts(section_index, lines):
"""
next three tables are the hill, channel, outlet
find the table header lines
:param section_index: integer starting index of section e.g.
"ANNUAL SUMMARY FOR WATERSHED IN YEAR"
:param lines: loss_pw0.txt as a list of strings
:return: hill0, chn0, out0
index to line starting the hill, channel, and outlet table
"""
header_indx = []
for i, L in enumerate(lines[section_index + 2:]):
if L.startswith('----'):
header_indx.append(i)
hill0 = header_indx[0] + 1 + section_index + 2
chn0 = header_indx[1] + 2 + section_index + 2 # channel and outlet summary
out0 = header_indx[2] + 2 + section_index + 2 # have a blank line before the data
return hill0, chn0, out0 | bigcode/self-oss-instruct-sc2-concepts |
def decode_list_index(list_index: bytes) -> int:
"""Decode an index for lists in a key path from bytes."""
return int.from_bytes(list_index, byteorder='big') | bigcode/self-oss-instruct-sc2-concepts |
def mode_decomposition(plant):
"""Returns a list of single mode transfer functions
Parameters
----------
plant : TransferFunction
The transfer function with at list one pair of complex poles.
Returns
-------
wn : array
Frequencies (rad/s).
q : array
Q factors.
k : array
Dcgains of the modes.
"""
poles = plant.pole()
complex_mask = poles.imag > 0 # Avoid duplication
wn = abs(poles[complex_mask]) # Frequencies
q = wn/(-2*poles[complex_mask].real) # Q factors of the modes
k = abs(plant(1j*wn)/q) # DC gain of the modes
return wn, q, k | bigcode/self-oss-instruct-sc2-concepts |
def assign_province_road_conditions(x):
"""Assign road conditions as paved or unpaved to Province roads
Parameters
x - Pandas DataFrame of values
- code - Numeric code for type of asset
- level - Numeric code for level of asset
Returns
String value as paved or unpaved
"""
asset_code = x.code
asset_level = x.level
# This is an expressway, national and provincial road
if asset_code in (17, 303) or asset_level in (0, 1):
return 'paved'
else:
# Anything else not included above
return 'unpaved' | bigcode/self-oss-instruct-sc2-concepts |
import ast
def guess_type(string):
"""
Guess the type of a value given as string and return it accordingly.
Parameters
----------
string : str
given string containing the value
"""
string = str(string)
try:
value = ast.literal_eval(string)
except Exception: # SyntaxError or ValueError
return string
else:
return value | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
def split_high_level(s: str,
c: str,
open_chars: List[str],
close_chars: List[str]
) -> List[str]:
"""Splits input string by delimiter c.
Splits input string by delimiter c excluding occurences
of character c that are between open_chars close_chars
:param s: string to split
:type s: str
:param c: delimiter character
:type c: str
:param open_chars: list of block opening characters
:type open_chars: List[str]
:param close_chars: list of block closing characters
:type close_chars: List[str]
:return: list of strings containing the splitted blocks
:rtype: List[str]
"""
splits = []
index = 0
depth = 0
start = 0
while index < len(s) - 1:
index += 1
if s[index] in open_chars:
depth += 1
elif s[index] in close_chars:
depth -= 1
if depth == 0 and s[index] == c:
splits.append(s[start:index:])
start = index + 1
else:
if start < len(s) - 1:
splits.append(s[start::])
return splits | bigcode/self-oss-instruct-sc2-concepts |
def tonumpy(img):
"""
Convert torch image map to numpy image map
Note the range is not change
:param img: tensor, shape (C, H, W), (H, W)
:return: numpy, shape (H, W, C), (H, W)
"""
if len(img.size()) == 2:
return img.cpu().detach().numpy()
return img.permute(1, 2, 0).cpu().detach().numpy() | bigcode/self-oss-instruct-sc2-concepts |
import re
def substitute_query_params(query, params):
"""
Substitutes the placeholders of the format ${n} (where n is a non-negative integer) in the query. Example, ${0}.
${n} is substituted with params[n] to generate the final query.
"""
placeholders = re.findall("((\${)(\d+)(}))", query)
for placeholder in placeholders:
placeholder_str, placeholder_index = placeholder[0], placeholder[2]
value = params[int(placeholder_index)]
query = query.replace(placeholder_str, value)
return query | bigcode/self-oss-instruct-sc2-concepts |
def group_text(text, n=5):
"""Groups the given text into n-letter groups separated by spaces."""
return ' '.join(''.join(text[i:i+n]) for i in range(0, len(text), n)) | bigcode/self-oss-instruct-sc2-concepts |
def p_length_unit(units):
"""Returns length units string as expected by pagoda weights and measures module."""
# NB: other length units are supported by resqml
if units.lower() in ['m', 'metre', 'metres']: return 'metres'
if units.lower() in ['ft', 'foot', 'feet', 'ft[us]']: return 'feet'
assert(False) | bigcode/self-oss-instruct-sc2-concepts |
from typing import Callable
def fname(func: Callable) -> str:
"""Return fully-qualified function name."""
return "{}.{}".format(func.__module__, func.__name__) | bigcode/self-oss-instruct-sc2-concepts |
def getNrOfDictElements(thisdict):
"""
Will get the total number of entries in a given dictionary
Argument: the source dictionary
Output : an integer
"""
total = 0
for dicttype in thisdict:
for dictval in thisdict[dicttype]:
total += 1
return total | bigcode/self-oss-instruct-sc2-concepts |
import random
def mutate_agent(agent_genome, max_mutations=3):
"""
Applies 1 - `max_mutations` point mutations to the given road trip.
A point mutation swaps the order of two waypoints in the road trip.
"""
agent_genome = list(agent_genome)
num_mutations = random.randint(1, max_mutations)
for mutation in range(num_mutations):
swap_index1 = random.randint(0, len(agent_genome) - 1)
swap_index2 = swap_index1
while swap_index1 == swap_index2:
swap_index2 = random.randint(0, len(agent_genome) - 1)
agent_genome[swap_index1], agent_genome[swap_index2] = agent_genome[swap_index2], agent_genome[swap_index1]
return tuple(agent_genome) | bigcode/self-oss-instruct-sc2-concepts |
from typing import Sequence
def strictly_increasing(s: Sequence):
"""Returns true if sequence s is monotonically increasing"""
return all(x < y for x, y in zip(s, s[1:])) | bigcode/self-oss-instruct-sc2-concepts |
import random
def generate_number(digits):
"""Generate an integer with the given number of digits."""
low = 10**(digits-1)
high = 10**digits - 1
return random.randint(low, high) | bigcode/self-oss-instruct-sc2-concepts |
def _applescriptify_str(text):
"""Replace double quotes in text for Applescript string"""
text = text.replace('"', '" & quote & "')
text = text.replace('\\', '\\\\')
return text | bigcode/self-oss-instruct-sc2-concepts |
def unpack_spectrum(HDU_list):
"""
Unpacks and extracts the relevant parts of an SDSS HDU list object.
Parameters
----------
HDU_list : astropy HDUlist object
Returns
-------
wavelengths : ndarray
Wavelength array
flux : ndarray
Flux array
z : float
Redshift of the galaxy
"""
table_data = HDU_list[0].header
z = HDU_list[2].data[0][63]
wavelengths = 10 ** HDU_list[1].data['loglam']
flux = HDU_list[1].data['flux']
return wavelengths, flux, z | bigcode/self-oss-instruct-sc2-concepts |
import re
def is_stable_version(version):
"""
Return true if version is stable, i.e. with letters in the final component.
Stable version examples: ``1.2``, ``1.3.4``, ``1.0.5``.
Non-stable version examples: ``1.3.4beta``, ``0.1.0rc1``, ``3.0.0dev0``.
"""
if not isinstance(version, tuple):
version = version.split('.')
last_part = version[-1]
if not re.search(r'[a-zA-Z]', last_part):
return True
else:
return False | bigcode/self-oss-instruct-sc2-concepts |
def read_symfile(path='baserom.sym'):
"""
Return a list of dicts of label data from an rgbds .sym file.
"""
symbols = []
for line in open(path):
line = line.strip().split(';')[0]
if line:
bank_address, label = line.split(' ')[:2]
bank, address = bank_address.split(':')
symbols += [{
'label': label,
'bank': int(bank, 16),
'address': int(address, 16),
}]
return symbols | bigcode/self-oss-instruct-sc2-concepts |
def cert_bytes(cert_file_name):
"""
Parses a pem certificate file into raw bytes and appends null character.
"""
with open(cert_file_name, "rb") as pem:
chars = []
for c in pem.read():
if c:
chars.append(c)
else:
break
# null-terminated certs, for compatibility
return chars + [0] | bigcode/self-oss-instruct-sc2-concepts |
def cupy_cuda_MemoryPointer(cp_arr):
"""Return cupy.cuda.MemoryPointer view of cupy.ndarray.
"""
return cp_arr.data | bigcode/self-oss-instruct-sc2-concepts |
def extend(*dicts):
"""Create a new dictionary from multiple existing dictionaries
without overwriting."""
new_dict = {}
for each in dicts:
new_dict.update(each)
return new_dict | bigcode/self-oss-instruct-sc2-concepts |
def mult (x, y):
"""
multiply : 2 values
"""
return x * y | bigcode/self-oss-instruct-sc2-concepts |
def combine_on_sep(items, separator):
"""
Combine each item with each other item on a `separator`.
Args:
items (list): A list or iterable that remembers order.
separator (str): The SEPARATOR the items will be combined on.
Returns:
list: A list with all the combined items as strings.
"""
combined_items = []
# Combine items only if there is more than 1 items.
if len(items) > 1:
# Convert the empty string back to minus.
items = [i if i!='' else '-' for i in items]
for i, item in enumerate(items):
reduced_items = items[:i] + items[i+1:]
combined_with_item = [separator.join((item, r)) for r in reduced_items]
combined_items += combined_with_item
# Else simply return the given list.
else:
combined_items = items
return combined_items | bigcode/self-oss-instruct-sc2-concepts |
def swapPos(list:list, pos1:int, pos2:int):
"""
Swap two elements in list. Return modified list
"""
list[pos1], list[pos2] = list[pos2], list[pos1]
return list | bigcode/self-oss-instruct-sc2-concepts |
import csv
def team2machine(cur_round):
"""Compute the map from teams to machines."""
# Get the config with the teamname-source mappings.
config_name = f"configs/config_round_{cur_round}.csv"
team_machine = {}
with open(config_name, 'r') as infile:
reader = csv.reader(infile)
for row in reader:
team_machine[row[0]] = row[1]
return team_machine | bigcode/self-oss-instruct-sc2-concepts |
import torch
def systematic_sampling(weights: torch.Tensor) -> torch.Tensor:
"""Sample ancestral index using systematic resampling.
Get from https://docs.pyro.ai/en/stable/_modules/pyro/infer/smcfilter.html#SMCFilter
Args:
log_weight: log of unnormalized weights, tensor
[batch_shape, num_particles]
Returns:
zero-indexed ancestral index: LongTensor [batch_shape, num_particles]
"""
with torch.no_grad():
batch_shape, size = weights.shape[:-1], weights.size(-1)
n = weights.cumsum(-1).mul_(size).add_(torch.rand(batch_shape + (1,), device=weights.device))
n = n.floor_().long().clamp_(min=0, max=size)
diff = torch.zeros(batch_shape + (size + 1,), dtype=torch.long, device=weights.device)
diff.scatter_add_(-1, n, torch.tensor(1, device=weights.device, dtype=torch.long).expand_as(weights))
ancestors = diff[..., :-1].cumsum(-1).clamp_(min=0, max=size-1)
return ancestors | bigcode/self-oss-instruct-sc2-concepts |
def get_column_as_list(matrix, column_no):
"""
Retrieves a column from a matrix as a list
"""
column = []
num_rows = len(matrix)
for row in range(num_rows):
column.append(matrix[row][column_no])
return column | bigcode/self-oss-instruct-sc2-concepts |
def _GetDefault(t):
"""Returns a string containing the default value of the given type."""
if t.element_type or t.nullable:
return None # Arrays and optional<T> are default-initialized
type_map = {
'boolean': 'false',
'double': '0',
'DOMString': None, # std::string are default-initialized.
}
assert t.name in type_map, 'Type %s not found' % t.name
return type_map[t.name] | bigcode/self-oss-instruct-sc2-concepts |
import configparser
def get_downstream_distgit_branch(dlrn_projects_ini):
"""Get downstream distgit branch info from DLRN projects.ini"""
config = configparser.ConfigParser()
config.read(dlrn_projects_ini)
return config.get('downstream_driver', 'downstream_distro_branch') | bigcode/self-oss-instruct-sc2-concepts |
def get_defined_enums(conn, schema):
"""
Return a dict mapping PostgreSQL enumeration types to the set of their
defined values.
:param conn:
SQLAlchemy connection instance.
:param str schema:
Schema name (e.g. "public").
:returns dict:
{
"my_enum": frozenset(["a", "b", "c"]),
}
"""
sql = """
SELECT
pg_catalog.format_type(t.oid, NULL),
ARRAY(SELECT enumlabel
FROM pg_catalog.pg_enum
WHERE enumtypid = t.oid)
FROM pg_catalog.pg_type t
LEFT JOIN pg_catalog.pg_namespace n ON n.oid = t.typnamespace
WHERE
t.typtype = 'e'
AND n.nspname = %s
"""
return {r[0]: frozenset(r[1]) for r in conn.execute(sql, (schema,))} | bigcode/self-oss-instruct-sc2-concepts |
def find_valid_edges(components, valid_edges):
"""Find all edges between two components in a complete undirected graph.
Args:
components: A [V]-shaped array of boolean component ids. This assumes
there are exactly two nonemtpy components.
valid_edges: An uninitialized array where output is written. On return,
the subarray valid_edges[:end] will contain edge ids k for all
valid edges.
Returns:
The number of valid edges found.
"""
k = 0
end = 0
for v2, c2 in enumerate(components):
for v1 in range(v2):
if c2 ^ components[v1]:
valid_edges[end] = k
end += 1
k += 1
return end | bigcode/self-oss-instruct-sc2-concepts |
def find_column_by_utype(table, utype):
"""
Given an astropy table derived from a VOTABLE, this function returns
the first Column object that has the given utype.
The name field of the returned value contains the column name and can be used
for accessing the values in the column.
Parameters
----------
table : astropy.table.Table
Astropy Table which was created from a VOTABLE (as if by astropy_table_from_votable_response).
utype : str
The utype identifying the column to be found.
Returns
-------
astropy.table.Column
The first column found which had the given utype. None is no such column found.
Example
-------
col = find_column_by_utype(my_table, 'Access.Reference')
print ('1st row access_url value is:', my_table[col.name][0])
"""
# Loop through all the columns looking for the utype
for key in table.columns:
col = table.columns[key]
utypeval = col.meta.get('utype')
if utypeval is not None:
if utype == utypeval:
return col
return None | bigcode/self-oss-instruct-sc2-concepts |
def calc_node_attr(node, edge):
"""
Returns a tuple of (cltv_delta, min_htlc, fee_proportional) values of the node in the channel.
"""
policy = None
if node == edge['node1_pub']:
policy = edge['node1_policy']
elif node == edge['node2_pub']:
policy = edge['node2_policy']
else:
raise Exception('node ' + node + ' is not a peer to channel ' + edge['channel_id'])
return policy['time_lock_delta'], policy['min_htlc'], policy['fee_rate_milli_msat'] | bigcode/self-oss-instruct-sc2-concepts |
def format_mac(mac: str) -> str:
"""
Format the mac address string.
Helper function from homeassistant.helpers.device_registry.py
"""
to_test = mac
if len(to_test) == 17 and to_test.count("-") == 5:
return to_test.lower()
if len(to_test) == 17 and to_test.count(":") == 5:
to_test = to_test.replace(":", "")
elif len(to_test) == 14 and to_test.count(".") == 2:
to_test = to_test.replace(".", "")
if len(to_test) == 12:
# no - included
return "-".join(to_test.lower()[i : i + 2] for i in range(0, 12, 2))
# Not sure how formatted, return original
return mac | bigcode/self-oss-instruct-sc2-concepts |
def present(element, act):
"""Return True if act[element] is valid and not None"""
if not act:
return False
elif element not in act:
return False
return act[element] | bigcode/self-oss-instruct-sc2-concepts |
def format_output(tosave, formatter):
"""
Applies the formatting function, formatter, on tosave.
If the resulting string does not have a newline adds it.
Otherwise returns the formatted string
:param tosave: The item to be string serialized
:param formatter: The formatter function applied to item
:return: The formatted string after formatter has been applied to tosave
"""
formatted = formatter(tosave)
if not formatted.endswith('\n'):
formatted = formatted + '\n'
return formatted | bigcode/self-oss-instruct-sc2-concepts |
def _update_query(table: str, field: str, is_jsonb: bool, from_string: str,
to_string: str) -> str:
"""Generates a single query to update a field in a PostgresSQL table.
Args:
table (str): The table to update.
field (str): The field to update.
is_jsonb (bool): Whether the field is jsonb or not.
from_string (str): The string to replace.
to_string (str): The string to replace with.
Returns:
str: The query to update the field.
"""
const = f'UPDATE {table} SET "{field}" = replace({field}' # noqa
if is_jsonb:
query = f'{const}::TEXT, \'{from_string}\', \'{to_string}\')::jsonb;'
else:
query = f'{const}, \'{from_string}\', \'{to_string}\');'
return query | bigcode/self-oss-instruct-sc2-concepts |
def generateFilenameFromUrl(url):
"""
Transforms a card URL into a local filename in the format
imageCache/setname_cardnumber.jpg.
"""
return 'imageCache/' + '_'.join(url.split('/')[1:]) | bigcode/self-oss-instruct-sc2-concepts |
import shutil
def move(src_path, dest_path, raise_error=False):
"""
Moves a file or folder from ``src_path`` to ``dest_path``. If either the source or
the destination path no longer exist, this function does nothing. Any other
exceptions are either raised or returned if ``raise_error`` is False.
"""
err = None
try:
shutil.move(src_path, dest_path)
except FileNotFoundError:
# do nothing of source or dest path no longer exist
pass
except OSError as exc:
err = exc
if raise_error and err:
raise err
else:
return err | bigcode/self-oss-instruct-sc2-concepts |
def unblock_list(blocked_ips_list, to_block_list):
""" This function creates list of IPs that are present in the firewall block list, but not in
the list of new blockings which will be sent to the firewall.
:param blocked_ips_list: List of blocked IPs.
:param to_block_list: List of new blockings.
:return: List of IPs to be unblocked.
"""
to_be_unblocked_list = []
for blocked in blocked_ips_list:
found_ip = False
blocked_ip = blocked['ip']
for host in to_block_list:
if host['host']['ip_address'] == blocked_ip:
found_ip = True
# if the blocked_ip was not found in list of blockings, unblock it
if not found_ip:
to_be_unblocked_list.append(blocked_ip)
return to_be_unblocked_list | bigcode/self-oss-instruct-sc2-concepts |
import csv
import re
def get_keys_from_file(file):
"""
Reads a file and creates a list of dictionaries.
:param file: Filename relative to project root.
:return: lkeys - a list of dictionaries
[{
Key: '00484545-2000-4111-9000-611111111111',
Region: 'us-east-1'
},
{
Key: '00484545-2000-4111-9000-622222222222',
Region: 'us-east-1'
}]
"""
lkeys = []
regex = '[0-9A-Za-z]{8}-[0-9A-Za-z]{4}-4[0-9A-Za-z]{3}-[89ABab][0-9A-Za-z]{3}-[0-9A-Za-z]{12}'
with open(file, newline='') as csvfile:
reader = csv.reader(csvfile, delimiter=' ', quotechar='|')
for row in reader:
if len(row) > 3 and re.search(regex, row[2]):
lkeys.append({'Key': row[2], 'Region': row[0]})
return lkeys | bigcode/self-oss-instruct-sc2-concepts |
def file_list(redis, task_id):
"""Returns the list of files attached to a task"""
keyf = "files:" + task_id
return redis.hkeys(keyf) | bigcode/self-oss-instruct-sc2-concepts |
def _parse_quad_str(s):
"""Parse a string of the form xxx.x.xx.xxx to a 4-element tuple of integers"""
return tuple(int(q) for q in s.split('.')) | bigcode/self-oss-instruct-sc2-concepts |
def flatten_dict(dct, separator='-->', allowed_types=[int, float, bool]):
"""Returns a list of string identifiers for each element in dct.
Recursively scans through dct and finds every element whose type is in
allowed_types and adds a string indentifier for it.
eg:
dct = {
'a': 'a string',
'b': {
'c': 1.0,
'd': True
}
}
flatten_dict(dct) would return
['a', 'b-->c', 'b-->d']
"""
flat_list = []
for key in sorted(dct):
if key[:2] == '__':
continue
key_type = type(dct[key])
if key_type in allowed_types:
flat_list.append(str(key))
elif key_type is dict:
sub_list = flatten_dict(dct[key])
sub_list = [str(key) + separator + sl for sl in sub_list]
flat_list += sub_list
return flat_list | bigcode/self-oss-instruct-sc2-concepts |
def _parse_tersoff_line(line):
"""
Internal Function.
Parses the tag, parameter and final value of a function parameter
from an atomicrex output line looking like:
tersoff[Tersoff].lambda1[SiSiSi]: 2.4799 [0:]
Returns:
[(str, str, float): tag, param, value
"""
line = line.strip().split()
value = float(line[1])
info = line[0].split("].")[1]
info = info.split("[")
param = info[0]
tag = info[1].rstrip("]:")
return tag, param, value | bigcode/self-oss-instruct-sc2-concepts |
def find_IPG_hits(group, hit_dict):
"""Finds all hits to query sequences in an identical protein group.
Args:
group (list): Entry namedtuples from an IPG from parse_IP_groups().
hit_dict (dict): All Hit objects found during cblaster search.
Returns:
List of all Hit objects corresponding to any proteins in a IPG.
"""
seen = set()
hits = []
for entry in group:
try:
new = hit_dict.pop(entry.protein_id)
except KeyError:
continue
for h in new:
if h.query in seen:
continue
seen.add(h.query)
hits.append(h)
return hits | bigcode/self-oss-instruct-sc2-concepts |
def get_mc_filepath(asm_path):
"""
Get the filepath for the machine code.
This is the assembly filepath with .asm replaced with .mc
Args:
asm_path (str): Path to the assembly file.
Returns:
str: Path to the machine code file.
"""
return "{basepath}.mc".format(basepath=asm_path[:-4]) | bigcode/self-oss-instruct-sc2-concepts |
import re
def encode(name, system='NTFS'):
"""
Encode the name for a suitable name in the given filesystem
>>> encode('Test :1')
'Test _1'
"""
assert system == 'NTFS', 'unsupported filesystem'
special_characters = r'<>:"/\|?*' + ''.join(map(chr, range(32)))
pattern = '|'.join(map(re.escape, special_characters))
pattern = re.compile(pattern)
return pattern.sub('_', name) | bigcode/self-oss-instruct-sc2-concepts |
from itertools import tee
def pairs(iterable):
"""
Return a new iterable over sequential pairs in the given iterable.
i.e. (0,1), (1,2), ..., (n-2,n-1)
Args:
iterable: the iterable to iterate over the pairs of
Returns: a new iterator over the pairs of the given iterator
"""
# lazily import tee from `itertools`
# split the iterator into 2 identical iterators
a, b = tee(iterable)
# retrieve the next item from the b iterator
next(b, None)
# zip up the iterators of current and next items
return zip(a, b) | bigcode/self-oss-instruct-sc2-concepts |
import re
def convert_spaces_and_special_characters_to_underscore(name):
""" Converts spaces and special characters to underscore so 'Thi$ i# jun&' becomes 'thi__i__jun_'
:param name: A string
:return: An altered string
Example use case:
- A string might have special characters at the end when they are really the same field such as My_Field$ and My_Field#
- We use this to covert the names to "my_field" to combine the values so the events will be easily grouped together
Examples:
.. code-block:: python
# Example #1
input_string = '$Scr "get-rid^-of-the@" special #characters%&space'
output_string = convert_spaces_and_special_characters_to_underscore(input_string)
output_string = '_scr__get_rid__of_the___special__characters__space'
"""
clean_name = re.sub(r'[\W_]', '_', name)
return clean_name.lower() | bigcode/self-oss-instruct-sc2-concepts |
def uid_already_processed(db, notification_uid):
"""Check if the notification UID has already been processed."""
uid = db.document(notification_uid).get()
if uid.exists:
return True
else:
return False | bigcode/self-oss-instruct-sc2-concepts |
def count_matched_numbers(a:list, b:list):
"""
Write a function that takes two lists as parameters and returns a list
containing the number of elements that occur in the same index in both
lists. If there is not common elements in the same indices in both lists, return False
Example:
>>> count_matched_numbers([1, 2, 3], [1, 2, 3])
3
>>> count_matched_numbers([1, 2, 3], [1, 5, 3, 4, 5])
2
>>> count_matched_numbers([1, 2, 3], [4,5,6])
False
"""
matching = 0
length_of_b = len(b)
if len(b) == 0:
return 0
for key,value_1 in enumerate(a):
if key>= length_of_b:
break # len(a)>len(b) AND we reached the limit
the_type = type(value_1) # getting the type of the element in first list
try:
value_2 = the_type(b[key]) # casting types
except Exception as e:
continue # Sometime casting may fail
# Now we are sure that value_1 and value_2 have the ame type
if value_1 == value_2:
matching += 1
#print(matching)
if matching:
return matching
else:
return False | bigcode/self-oss-instruct-sc2-concepts |
import binascii
def from_bytes(bytes):
"""Reverse of to_bytes()."""
# binascii works on all versions of Python, the hex encoding does not
return int(binascii.hexlify(bytes), 16) | bigcode/self-oss-instruct-sc2-concepts |
def runningMean(oldMean, newValue, numValues):
# type: (float, float, int) -> float
"""
A running mean
Parameters
----------
oldMean : float
The old running average mean
newValue : float
The new value to be added to the mean
numValues : int
The number of values in the new running mean once this value is included
Returns
-------
newMean : float
The new running average mean
Notes
-----
Based on Donald Knuth’s Art of Computer Programming, Vol 2, page 232, 3rd edition and taken from
https://www.johndcook.com/blog/standard_deviation/
Examples
--------
>>> runningMean(1, 2, 2)
1.5
>>> runningMean(1.5, 3, 3)
2.0
"""
newMean = oldMean + (newValue - oldMean) / numValues
return newMean | bigcode/self-oss-instruct-sc2-concepts |
from typing import Tuple
from typing import Optional
def validate_parse_directions(verb: str, direction: str) -> Tuple[Optional[str], Optional[str]]:
"""Parse north, south, east, west to n, s, e, w and if the user types trash
insult them and return a tuple like, (None, some validation message)"""
if len(direction) >= 1:
# shorten [N]orth to N
direction = direction[0]
if direction in "nsew":
return verb, direction
else:
return None, "Bad direction, you idiot! Only n, s, e, w!"
else:
return None, "Missing direction" | bigcode/self-oss-instruct-sc2-concepts |
def read_file_lines(filename):
"""Reads the lines of a file as a list"""
with open(filename, mode="r") as f_in:
return f_in.readlines() | bigcode/self-oss-instruct-sc2-concepts |
def get_list_hashes(lst):
"""
For LZ to be more effective, than worst case 'fresh' raw dump,
you need to lz encode minimum 4 bytes length. Break into 4 bytes chunks and hash
Parameters
----------
lst : list
Input list to form hashes from (lz haystack).
Returns
-------
enumerated list: (n, hash)
list of enumerated hashes.
"""
assert len(lst) > 0, 'Empty list in list hashes'
return [(x, hash(tuple(lst[x:x + 4]))) for x in range(len(lst))] | bigcode/self-oss-instruct-sc2-concepts |
def remove_ext(filename: str, ext: str) -> str:
"""
Remove a file extension. No effect if provided extension is missing.
"""
if not ext.startswith('.'):
ext = f'.{ext}'
parts = filename.rsplit(ext, 1)
if len(parts) == 2 and parts[1] == '':
return parts[0]
else:
return filename | bigcode/self-oss-instruct-sc2-concepts |
def parse_to_dicts(lines, containers):
"""
Parses a list of lines into tuples places in the given containers.
The lists of lines has the following format
token1: tval1
key1: val11
key2: val12
token1: tval2
key1: val21
key2: val22
:param lines:
:param containers: a dictionary { token : array_instance}
:return:
"""
pairs = [(a, b.strip()) for a, b in (m.split(':', 1) for m in lines)]
item = {}
kind, name = None, None
for j in range(0, len(pairs)):
if pairs[j][0] in containers.keys():
if j != 0:
containers[kind].append((name, item))
item = {}
kind = pairs[j][0]
name = pairs[j][1]
else:
item[pairs[j][0]] = pairs[j][1]
if kind is not None:
containers[kind].append((name, item))
return containers | bigcode/self-oss-instruct-sc2-concepts |
def is_number(s):
"""
Test if a string is an int or float.
:param s: input string (word)
:type s: str
:return: bool
"""
try:
float(s) if "." in s else int(s)
return True
except ValueError:
return False | bigcode/self-oss-instruct-sc2-concepts |
def get_locale_identifier(tup, sep='_'):
"""The reverse of :func:`parse_locale`. It creates a locale identifier out
of a ``(language, territory, script, variant)`` tuple. Items can be set to
``None`` and trailing ``None``\s can also be left out of the tuple.
>>> get_locale_identifier(('de', 'DE', None, '1999'))
'de_DE_1999'
.. versionadded:: 1.0
:param tup: the tuple as returned by :func:`parse_locale`.
:param sep: the separator for the identifier.
"""
tup = tuple(tup[:4])
lang, territory, script, variant = tup + (None,) * (4 - len(tup))
return sep.join(filter(None, (lang, script, territory, variant))) | bigcode/self-oss-instruct-sc2-concepts |
def to_channel_last(tensor):
"""Move channel axis in last position."""
return tensor.permute(1, 2, 0) | bigcode/self-oss-instruct-sc2-concepts |
def _is_file_a_directory(f):
"""Returns True is the given file is a directory."""
# Starting Bazel 3.3.0, the File type as a is_directory attribute.
if getattr(f, "is_directory", None):
return f.is_directory
# If is_directory is not in the File type, fall back to the old method:
# As of Oct. 2016, Bazel disallows most files without extensions.
# As a temporary hack, Tulsi treats File instances pointing at extension-less
# paths as directories. This is extremely fragile and must be replaced with
# logic properly homed in Bazel.
return (f.basename.find(".") == -1) | bigcode/self-oss-instruct-sc2-concepts |
def correct_bounding_box(x1, y1, x2, y2):
""" Corrects the bounding box, so that the coordinates are small to big """
xmin = 0
ymin = 0
xmax = 0
ymax = 0
if x1 < x2:
xmin = x1
xmax = x2
else:
xmin = x2
xmax = x1
if y1 < y2:
ymin = y1
ymax = y2
else:
ymin = y2
ymax = y1
return [xmin, ymin, xmax, ymax] | bigcode/self-oss-instruct-sc2-concepts |
def train_test_split_features(data_train, data_test, zone, features):
"""Returns a pd.DataFrame with the explanatory variables and
a pd.Series with the target variable, for both train and test data.
Args:
data_train (pd.DataFrame): Train data set.
data_tes (pd.DataFrame): Test data set.
zone (int): The zone id (id of the wind farm).
features (list): A list of the column names to be used.
Returns:
(pd.DataFrame): Explanatory variables of train data set.
(pd.Series): Target variable fo train data set.
(pd.DataFrame): Explanatory variables of test data set.
(pd.Series): Target variable fo test data set.
"""
X_train = data_train[data_train.ZONEID == zone][features]
y_train = data_train[data_train.ZONEID == zone].TARGETVAR
X_test = data_test[data_test.ZONEID == zone][features]
y_test = data_test[data_test.ZONEID == zone].TARGETVAR
return X_train, X_test, y_train, y_test | bigcode/self-oss-instruct-sc2-concepts |
import torch
def create_random_binary_mask(features):
"""
Creates a random binary mask of a given dimension with half of its entries
randomly set to 1s.
:param features: Dimension of mask.
:return: Binary mask with half of its entries set to 1s, of type torch.Tensor.
"""
mask = torch.zeros(features).byte()
weights = torch.ones(features).float()
num_samples = features // 2 if features % 2 == 0 else features // 2 + 1
indices = torch.multinomial(
input=weights, num_samples=num_samples, replacement=False
)
mask[indices] += 1
return mask | bigcode/self-oss-instruct-sc2-concepts |
def pbar(val, maxval, empty='-', full='#', size=50):
"""
return a string that represents a nice progress bar
Parameters
----------
val : float
The fill value of the progress bar
maxval : float
The value at which the progress bar is full
empty : str
The character used to draw the empty part of the bar
full : str
The character used to draw the full part of the bar
size : integer
The lenght of the bar expressed in number of characters
Returns
-------
br : str
The string containing the progress bar
Examples
--------
>>> a = pbar(35.5, 100, size=5)
>>> print(a)
35.50% [##----]
"""
br = "{{1: 6.2f}}% [{{0:{}<{}s}}]".format(empty, size)
br = br.format(full*int(size*val/maxval), val*100/maxval)
return br | bigcode/self-oss-instruct-sc2-concepts |
def hasShapeType(items, sort):
"""
Detect whether the list has any items of type sort. Returns :attr:`True` or :attr:`False`.
:param shape: :class:`list`
:param sort: type of shape
"""
return any([getattr(item, sort) for item in items]) | bigcode/self-oss-instruct-sc2-concepts |
def reestructure_areas(config_dict):
"""Ensure that all [Area_0, Area_1, ...] are consecutive"""
area_names = [x for x in config_dict.keys() if x.startswith("Area_")]
area_names.sort()
for index, area_name in enumerate(area_names):
if f"Area_{index}" != area_name:
config_dict[f"Area_{index}"] = config_dict[area_name]
config_dict.pop(area_name)
return config_dict | bigcode/self-oss-instruct-sc2-concepts |
def get_section_markups(document, sectionLabel):
""" Given a ConTextDocument and sectionLabel, return an ordered list of the ConTextmarkup objects in that section"""
tmp = [(e[1],e[2]['sentenceNumber']) for e in document.getDocument().out_edges(sectionLabel, data=True) if
e[2].get('category') == 'markup']
tmp.sort(key=lambda x:x[1])
return [t[0] for t in tmp] | bigcode/self-oss-instruct-sc2-concepts |
def absolute_min(array):
"""
Returns absolute min value of a array.
:param array: the array.
:return: absolute min value
>>> absolute_min([1, -2, 5, -8, 7])
1
>>> absolute_min([1, -2, 3, -4, 5])
1
"""
return min(array, key=abs) | 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.