seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
import re
def parse_size(size):
"""Parse a size, kinda like 10MB, and return an amount of bytes."""
size_re = re.compile(r'^(\d+)([GMK]?B)$')
match = size_re.match(size.upper())
if not match:
raise ValueError("Invalid size %r" % size)
amount, unit = match.groups()
amount = int(amount)
if unit == 'GB':
return amount * 1024 * 1024 * 1024
elif unit == 'MB':
return amount * 1024 * 1024
elif unit == 'kB':
return amount * 1024
else:
return amount | bigcode/self-oss-instruct-sc2-concepts |
def convert_email(value: str) -> str:
"""Convert email domain from student to employee or vice versa"""
user, domain = value.split('@')
if domain.startswith('st.'):
return f"{user}@{domain[3:]}"
else:
return f"{user}@st.{domain}" | bigcode/self-oss-instruct-sc2-concepts |
def intersection(r1, r2):
"""Calculates the intersection rectangle of two regions.
Args:
r1, r2 (dict): A dictionary containing {x1, y1, x2, y2} arguments.
Returns:
dict or None: A dictionary in the same fashion of just the
intersection or None if the regions do not intersect.
"""
x1 = max(r1["x1"], r2["x1"])
y1 = max(r1["y1"], r2["y1"])
x2 = min(r1["x2"], r2["x2"])
y2 = min(r1["y2"], r2["y2"])
if y1 < y2 and x1 < x2:
return {
"x1": x1,
"y1": y1,
"x2": x2,
"y2": y2,
"accuracy": max(r1["accuracy"], r2["accuracy"])
}
else:
return None | bigcode/self-oss-instruct-sc2-concepts |
def get_label_name_from_dict(labels_dict_list):
"""
Parses the labels dict and returns just the names of the labels.
Args:
labels_dict_list (list): list of dictionaries
Returns:
str: name of each label separated by commas.
"""
label_names = [a_dict["name"] for a_dict in labels_dict_list]
return ",".join(label_names) | bigcode/self-oss-instruct-sc2-concepts |
def _FormatToken(token):
"""Converts a Pythonic token name into a Java-friendly constant name."""
assert str(token).startswith('Token.'), 'Expected token, found ' + token
return str(token)[len('Token.'):].replace('.', '_').upper() | bigcode/self-oss-instruct-sc2-concepts |
def is_fun_upd(t):
"""Whether t is fun_upd applied to three parameters, that
is, whether t is of the form f (a := b).
"""
return t.is_comb('fun_upd', 3) | bigcode/self-oss-instruct-sc2-concepts |
def select_field(features, field):
"""Select a field from the features
Arguments:
features {InputFeatures} -- List of features : Instances
of InputFeatures with attribute choice_features being a list
of dicts.
field {str} -- Field to consider.
Returns:
[list] -- List of corresponding features for field.
"""
return [
getattr(feature, field)
for feature in features
] | bigcode/self-oss-instruct-sc2-concepts |
import re
def purify_app_references(txt: str) -> str:
"""
Remove references to `/app`.
"""
txt = re.sub("/app/", "", txt, flags=re.MULTILINE)
return txt | bigcode/self-oss-instruct-sc2-concepts |
def paths_from_issues(issues):
"""Extract paths from list of BindConfigIssuesModel."""
return [issue.path for issue in issues] | bigcode/self-oss-instruct-sc2-concepts |
def get_hosts_descriptions(hosts_scans):
"""
Get the hosts descriptions
Args:
hosts_scans (list[dict]): hosts scans information.
Returns:
List[dict]: images descriptions.
"""
return [
{
"Hostname": scan.get("hostname"),
"OS Distribution": scan.get("distro"),
"Docker Version": scan.get("applications", [{}])[0].get("version"),
"Vulnerabilities Count": scan.get("vulnerabilitiesCount"),
"Compliance Issues Count": scan.get("complianceIssuesCount")
} for scan in hosts_scans
] | bigcode/self-oss-instruct-sc2-concepts |
def draw_rectangle(image=None, coordinates=None,
size=None, color=None):
"""
Generate a rectangle on a given image canvas at the given coordinates
:param image: Pillow/PIL Image Canvas
:param coordinates: coordinate pair that will be the center of the rectangle
:param size: tuple with the x and y sizes of the rectangle
:param color: color of the rectangle
:returns: image rectangle return or False
:raises TypeError: none
"""
if image \
and coordinates \
and size \
and color:
corner0 = (coordinates[0] - size[0] // 2, coordinates[1] - size[1] // 2)
corner1 = (coordinates[0] + size[0] // 2, coordinates[1] + size[1] // 2)
box_paint = [corner0, corner1]
# print('road box_coords: ', box_paint)
# pprint(box_paint)
drawn_rectangle = image.rectangle(box_paint, fill=color, outline=color)
return drawn_rectangle
else:
return False | bigcode/self-oss-instruct-sc2-concepts |
def _get_real_chan_name(chan):
""" Get the real channel name
Channels with a light group will have the light group
appended to the name
"""
ch_name = chan.channel_name
lgt_grp = chan.light_group.strip()
if lgt_grp != '' and lgt_grp not in ch_name:
ch_name = '%s_%s' % (ch_name, lgt_grp)
return ch_name | bigcode/self-oss-instruct-sc2-concepts |
def getOutputsNames(net):
"""Get the output names from the output layer
Arguments:
net {network} -- Yolo network
Returns:
list -- List of names
"""
layersNames = net.getLayerNames()
return [layersNames[i[0] - 1] for i in net.getUnconnectedOutLayers()] | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
def ds_make(n: int) -> List[int]:
"""
Make n subsets containing the numbers 0 to n - 1.
"""
# The value of element i is the parent of that set
# If parent is itself then it's the root
return [i for i in range(n)] | bigcode/self-oss-instruct-sc2-concepts |
import torch
def batched_concat_per_row(A, B):
"""Concat every row in A with every row in B where
the first dimension of A and B is the batch dimension"""
b, m1, n1 = A.shape
_, m2, n2 = B.shape
res = torch.zeros(b, m1, m2, n1 + n2)
res[:, :, :, :n1] = A[:, :, None, :]
res[:, :, :, n1:] = B[:, None, :, :]
return res.view(b, m1 * m2, -1) | bigcode/self-oss-instruct-sc2-concepts |
def process_dataset(dataset, labeler):
"""Labels all items of the dataset with the specified labeler."""
return {item: labeler.label_object(item, true_description) for item, true_description in dataset.items()} | bigcode/self-oss-instruct-sc2-concepts |
def user_info(
first_name,
last_name,
**profile):
"""Function that builds user information."""
profile['firstname'] = first_name
profile['lastname'] = last_name
return profile | bigcode/self-oss-instruct-sc2-concepts |
def harmonic_mean(frequencies1, frequencies2):
"""Finds the harmonic mean of the absolute differences between two frequency profiles,
expressed as dictionaries.
Assumes every key in frequencies1 is also in frequencies2
>>> harmonic_mean({'a':2, 'b':2, 'c':2}, {'a':1, 'b':1, 'c':1})
1.0
>>> harmonic_mean({'a':2, 'b':2, 'c':2}, {'a':1, 'b':1, 'c':1})
1.0
>>> harmonic_mean({'a':2, 'b':2, 'c':2}, {'a':1, 'b':5, 'c':1}) # doctest: +ELLIPSIS
1.285714285...
>>> harmonic_mean(normalise({'a':2, 'b':2, 'c':2}), \
normalise({'a':1, 'b':5, 'c':1})) # doctest: +ELLIPSIS
0.228571428571...
>>> harmonic_mean(normalise({'a':2, 'b':2, 'c':2}), \
normalise({'a':1, 'b':1, 'c':1})) # doctest: +ELLIPSIS
0.0
>>> harmonic_mean(normalise({'a':2, 'b':2, 'c':2}), \
normalise({'a':1, 'b':1, 'c':0})) # doctest: +ELLIPSIS
0.2
"""
total = 0.0
for k in frequencies1:
if abs(frequencies1[k] - frequencies2[k]) == 0:
return 0.0
total += 1.0 / abs(frequencies1[k] - frequencies2[k])
return len(frequencies1) / total | bigcode/self-oss-instruct-sc2-concepts |
def dnfcode_key(code):
"""Return a rank/dnf code sorting key."""
# rank [rel] '' dsq hd|otl dnf dns
dnfordmap = {
u'rel':8000,
u'':8500,
u'hd':8800,u'otl':8800,
u'dnf':9000,
u'dns':9500,
u'dsq':10000,}
ret = 0
if code is not None:
code = code.lower()
if code in dnfordmap:
ret = dnfordmap[code]
else:
code = code.strip(u'.')
if code.isdigit():
ret = int(code)
return ret | bigcode/self-oss-instruct-sc2-concepts |
import itertools
def countCombosSumEqual(sm: int, nums: list) -> int:
"""
Count all possible combos of elements in nums[] such that sum(combo) == sm
Args:
sm (int): the sum to match.
nums (list): list of positive integers.
Returns:
int: resulting count.
If nums[0] == sm, start with count=1, then pop nums[0]
For r from 2 to len(nums), iterate thru all combos C(len(nums), r),
then count all such that sum(combo) == sm
"""
count = 0
if nums[0] == sm:
count += 1
nums.pop(0)
return count + len([1 for r in range(2, len(nums) + 1)
for combo in itertools.combinations(nums, r)
if sum(combo) == sm]) | bigcode/self-oss-instruct-sc2-concepts |
import re
def titleize(name):
""" Titleize a course name or instructor, taking into account exceptions such as II. """
name = re.sub(r'I(x|v|i+)', lambda m: 'I' + m.group(1).upper(), name.strip().title())
name = re.sub(r'(\d)(St|Nd|Rd|Th)', lambda m: m.group(1) + m.group(2).lower(), name)
name = re.sub(r'Mc([a-z])', lambda m: 'Mc' + m.group(1).upper(), name)
name = name.replace("'S", "'s")
return name | bigcode/self-oss-instruct-sc2-concepts |
def get_prediction_results(data, labels, predict_prob, vocab_dict, label_dict):
"""
Get the prediction and the true labels with the words in conll format
@params : data - unpadded test data
@params : labels - unpadded test labels
@params : predict_prob - the predicted probabilities
@params : vocab_dict - vocabulary dict
@params : label_dict - label dict
@returns : result - Resulting textual predictions in conll format:
line_number(int) word(str) predict_label(str) true_label(str)
"""
result = []
for document, doc_labels, doc_preds in zip(data, labels, predict_prob):
document_result = []
for word, word_label, word_pred in zip(document, doc_labels, doc_preds):
# Get index of most probable label:
index = word_pred.tolist().index(max(word_pred))
# Conll format: line_number(int) word(str) predict_label(str) true_label(str)
document_result.append((vocab_dict[word],label_dict[index],label_dict[word_label]))
result.append(document_result)
return result | bigcode/self-oss-instruct-sc2-concepts |
def get_index_of_user_by_id(id_value, data):
"""Get index of user in list by id"""
for count, item in enumerate(data):
if item['id'] == id_value:
return count
return None | bigcode/self-oss-instruct-sc2-concepts |
def starts_new_warning(line) -> bool:
"""Return true if the line starts a new warning."""
return "warning:" in line | bigcode/self-oss-instruct-sc2-concepts |
def find_path(start, end, parents):
"""
Constructs a path between two vertices, given the parents of all vertices.
Parameters
----------
start : int
The first verex in the path
end : int
The last vertex in the path
parents : list[int]
The parent of a vertex in its path from start to end.
Returns
-------
path : list[int]
The path from start to end.
"""
path = []
parent = end
while parent != parents[start]:
path.append(parent)
parent = parents[parent]
return path[::-1] | bigcode/self-oss-instruct-sc2-concepts |
def get_class_image_ids(self, class_name=None, class_id=None):
""" Retrieves image_ids associated with class_name or class_id """
return self.get_class_info(class_id=class_id, class_name=class_name)['image_ids'] | bigcode/self-oss-instruct-sc2-concepts |
from typing import Union
def _get_vars(symbol: Union[str, int]) -> str:
"""Get the javascript variable declarations associated with a given symbol.
These are adapted from plotly.js -> src/components/drawing/symbol_defs.js
Args:
symbol: The symbol whose variables should be retrieved.
Returns:
A minified string representation of the variables to be declared in javascript.
"""
if isinstance(symbol, str):
return {'circle': 'var b1=n.round(t,2);',
'square': 'var b1=n.round(t,2);',
'diamond': 'var b1=n.round(t*1.3,2);',
'hexagram': 'var b1=n.round(t,2);var b2=n.round(t/2,2);var b3=n.round(t*Math.sqrt(3)/2,2);'}[symbol]
return {37: 'var d1=n.round(t*1.2,2);var d2=n.round(t*1.6,2);var d3=n.round(t*0.8,2);',
38: 'var d1=n.round(t*1.2,2);var d2=n.round(t*1.6,2);var d3=n.round(t*0.8,2);',
39: 'var d1=n.round(t*1.2,2);var d2=n.round(t*1.6,2);var d3=n.round(t*0.8,2);',
40: 'var d1=n.round(t*1.2,2);var d2=n.round(t*1.6,2);var d3=n.round(t*0.8,2);',
34: 'var d1=n.round(t,2);',
33: 'var d1=n.round(t*1.4,2);',
35: 'var d1=n.round(t*1.2,2);var d2=n.round(t*0.85,2);',
36: 'var d1=n.round(t/2,2);var d2=n.round(t,2);'}[symbol] | bigcode/self-oss-instruct-sc2-concepts |
import re
def make_consts_consecutive(s):
"""
The given phenotype will have zero or more occurrences of each const c[0],
c[1], etc. But eg it might have c[7], but no c[0]. We need to remap, eg:
7 -> 0
9 -> 1
so that we just have c[0], c[1], etc.
:param s: A given phenotype string.
:return: The phenotype string but with consecutive constants.
"""
p = r"c\[(\d+)\]"
# find the consts, extract idxs as ints, unique-ify and sort
const_idxs = sorted(map(int, set(re.findall(p, s))))
for i, j in enumerate(const_idxs):
ci = "c[%d]" % i
cj = "c[%d]" % j
s = s.replace(cj, ci)
return s, len(const_idxs) | bigcode/self-oss-instruct-sc2-concepts |
def normalized_value(xs):
""" normalizes a list of numbers
:param xs: a list of numbers
:return: a normalized list
"""
minval = min(xs)
maxval = max(xs)
minmax = (maxval-minval) * 1.0
return [(x - minval) / minmax for x in xs] | bigcode/self-oss-instruct-sc2-concepts |
import yaml
def _yaml_reader(yaml_file):
"""Import the YAML File for the YOLOv5 data as dict."""
with open(yaml_file) as file:
data = yaml.safe_load(file)
return data | bigcode/self-oss-instruct-sc2-concepts |
def valid_for_gettext(value):
"""Gettext acts weird when empty string is passes, and passing none would be even weirder"""
return value not in (None, "") | bigcode/self-oss-instruct-sc2-concepts |
def convert_indices(direction, x, y):
"""
Converts indices between Python and Fortran indexing, assuming that
Python indexing begins at 0 and Fortran (for x and y) begins at 1.
In Tracmass, the vertical indexing does begin at zero so this script
does nothing to vertical indexing.
Examples:
For before a call to tracmass:
>>> xstart,ystart = convert_indices('py2f',xstart,ystart)
For after a call to tracmass:
>>> xend,yend = convert_indices('f2py',xend,yend)
"""
if direction == 'py2f':
x = x+1
y = y+1
elif direction == 'f2py':
x = x-1
y = y-1
return x, y | bigcode/self-oss-instruct-sc2-concepts |
def get_or_none(model, **kwargs):
"""
Gets the model you specify or returns none if it doesn't exist.
"""
try:
return model.objects.get(**kwargs)
except model.DoesNotExist:
return None | bigcode/self-oss-instruct-sc2-concepts |
def armijo(fun, xk, xkp1, p, p_gradf, fun_xk, eta=0.5, nu=0.9):
""" Determine step size using backtracking
f(xk + alpha*p) <= f(xk) + alpha*nu*<p,Df>
Args:
fun : objective function `f`
xk : starting position
xkp1 : where new position `xk + alpha*p` is stored
p : search direction
p_gradf : local slope along the search direction `<p,Df>`
fun_xk : starting value `f(xk)`
eta : control parameter (shrinkage)
nu : control parameter (sufficient decrease)
Returns:
Set `xkp1[:] = xk + alpha*p` and return a tuple (f_xkp1, alpha)
f_xkp1 : new value `f(xk + alpha*p)`
alpha : determined step size
"""
if p_gradf >= 0:
raise Exception("Armijo: Not a descent direction!")
alpha = 1.0
while True:
xkp1[:] = xk + alpha*p
f_xkp1 = fun(xkp1)
if f_xkp1 <= fun_xk + alpha*nu*p_gradf:
break
else:
alpha *= eta
if alpha < 1e-10:
raise Exception("Armijo: Not a descent direction!")
return f_xkp1, alpha | bigcode/self-oss-instruct-sc2-concepts |
def processObjectListWildcards(objectList, suffixList, myId):
"""Replaces all * wildcards with n copies that each have appended one element from the provided suffixList and replaces %id wildcards with myId
ex: objectList = [a, b, c_3, d_*, e_%id], suffixList=['0', '1', '2'], myId=5 => objectList = [a, b, c_3, e_5, d_0, d_1, d_2]
:objectList: list of objects
:suffixList: list of strings that are going to be appended to each object that has the * wildcard
:myId: string used to replace '%id' wildcard
:returns: the new list"""
# we iterate over a copy of the object list (in order to modify it)
for item in objectList[:]:
if ('*' in item):
# append the new items
for suffix in suffixList:
objectList.append(item.replace("*", suffix))
# delete the item that contains the wildcards
objectList.remove(item)
if ('%id' in item):
# replace the id wildcard with the id parameter
objectList.append(item.replace("%id", myId))
# delete the item that contains the '%id' wildcard
objectList.remove(item)
return objectList | bigcode/self-oss-instruct-sc2-concepts |
def get_remote_file_name(url):
"""Create a file name from the url
Args:
url: file location
Returns:
String representing the filename
"""
array = url.split('/')
name = url
if len(array) > 0:
name = array[-1]
return name | bigcode/self-oss-instruct-sc2-concepts |
def has_nan(dataframe):
"""
Return true if dataframe has missing values (e.g. NaN) and counts how many missing value each feature has
"""
is_nan = dataframe.isnull().values.any()
no_nan = dataframe.isnull().sum()
# is_infinite = np.all(np.isfinite(dataframe))
return is_nan, no_nan | bigcode/self-oss-instruct-sc2-concepts |
def GnuHash(name):
"""Compute the GNU hash of a given input string."""
h = 5381
for c in name:
h = (h * 33 + ord(c)) & 0xffffffff
return h | bigcode/self-oss-instruct-sc2-concepts |
def dp_fib_ls(n: int):
"""A dynamic programming version of Fibonacci, linear space"""
res = [0, 1]
for i in range(2, n+1):
res.append(res[i-2] + res[i-1])
return res[n] | bigcode/self-oss-instruct-sc2-concepts |
def hex_to_rgb(hex_str: str, normalized=False):
"""
Returns a list of channel values of a hexadecimal string color
:param hex_str: color in hexadecimal string format (ex: '#abcdef')
:param normalized: if True, color will be float between 0 and 1
:return: list of all channels
"""
hex_str = hex_str.replace('#', '').replace('0x', '')
color = []
for idx in range(0, len(hex_str), 2):
color.append(int(hex_str[idx:idx + 2], 16))
if normalized:
color = [float(c) / 255 for c in color]
return color | bigcode/self-oss-instruct-sc2-concepts |
import math
def adam(opfunc, x, config, state=None):
""" An implementation of Adam http://arxiv.org/pdf/1412.6980.pdf
ARGS:
- 'opfunc' : a function that takes a single input (X), the point
of a evaluation, and returns f(X) and df/dX
- 'x' : the initial point
- 'config` : a table with configuration parameters for the optimizer
- 'config.learningRate' : learning rate
- 'config.beta1' : first moment coefficient
- 'config.beta2' : second moment coefficient
- 'config.epsilon' : for numerical stability
- 'config.weightDecay' : weight decay
- 'state' : a table describing the state of the optimizer; after each
call the state is modified
RETURN:
- `x` : the new x vector
- `f(x)` : the value of optimized function, evaluated before the update
"""
# (0) get/update state
if config is None and state is None:
raise ValueError("adam requires a dictionary to retain state between iterations")
state = state if state is not None else config
lr = config.get('learningRate', 0.001)
beta1 = config.get('beta1', 0.9)
beta2 = config.get('beta2', 0.999)
epsilon = config.get('epsilon', 1e-8)
wd = config.get('weightDecay', 0)
# (1) evaluate f(x) and df/dx
fx, dfdx = opfunc(x)
# (2) weight decay
if wd != 0:
dfdx.add_(wd, x)
# Initialization
if 't' not in state:
state['t'] = 0
# Exponential moving average of gradient values
state['m'] = x.new().resize_as_(dfdx).zero_()
# Exponential moving average of squared gradient values
state['v'] = x.new().resize_as_(dfdx).zero_()
# A tmp tensor to hold the sqrt(v) + epsilon
state['denom'] = x.new().resize_as_(dfdx).zero_()
state['t'] += 1
# Decay the first and second moment running average coefficient
state['m'].mul_(beta1).add_(1 - beta1, dfdx)
state['v'].mul_(beta2).addcmul_(1 - beta2, dfdx, dfdx)
state['denom'].copy_(state['v']).sqrt_().add_(epsilon)
biasCorrection1 = 1 - beta1 ** state['t']
biasCorrection2 = 1 - beta2 ** state['t']
stepSize = lr * math.sqrt(biasCorrection2) / biasCorrection1
# (3) update x
x.addcdiv_(-stepSize, state['m'], state['denom'])
# return x*, f(x) before optimization
return x, fx | bigcode/self-oss-instruct-sc2-concepts |
def _partition(nums, left, right):
"""Util method for quicksort_ip() to rearrange nums in place."""
# Use right number as pivot.
right_num = nums[right]
# Rearrange numbers w.r.t. pivot:
# - For left <= k <= i: nums[k] <= pivot,
# - For i+1 <= k <= j-1: nums[k] > pivot,
# - For k = right: nums[k] = pivot.
i = left - 1
for j in range(left, right):
if nums[j] <= right_num:
i += 1
nums[i], nums[j] = nums[j], nums[i]
# Swap num[i+1] and pivot, to rearrange to correct order.
nums[i + 1], nums[right] = nums[right], nums[i + 1]
return i + 1 | bigcode/self-oss-instruct-sc2-concepts |
def map_colnames(row, name_map):
"""Return table row with renamed column names according to `name_map`."""
return {
name_map.get(k, k): v
for k, v in row.items()} | bigcode/self-oss-instruct-sc2-concepts |
def is_ineq(tm):
"""check if tm is an ineq term."""
return tm.is_greater() or tm.is_greater_eq() or tm.is_less() or tm.is_less_eq() | bigcode/self-oss-instruct-sc2-concepts |
def show_resource_pool(client, private_cloud, resource_pool, location):
"""
Returns the details of a resource pool.
"""
return client.get(location, private_cloud, resource_pool) | bigcode/self-oss-instruct-sc2-concepts |
def limpiar(texto: str) -> str:
"""El texto que recibe se devuelve limpio, eliminando espacios dobles y los espacios que haya
tanto al principio como al final.
:param texto: Texto de entrada
:type texto: str
:return: Texto de entrada limpio (eliminando
:rtype: str
>>> limpiar("estoy escribiendo desde móvil y meto un espacio al final y algunos por enmedio ")
'estoy escribiendo desde móvil y meto un espacio al final y algunos por enmedio'
"""
texto = texto.strip()
return " ".join(texto.split()) | bigcode/self-oss-instruct-sc2-concepts |
from typing import Dict
from typing import Optional
def weighted_average(
distribution: Dict[str, float],
weights: Dict[str, float],
rounding: Optional[int] = None,
) -> float:
"""
Calculate a weighted average from dictionaries with the same keys, representing the values and the weights.
Args:
distribution: The values
weights: The weights
rounding: Whether to round off the result
Returns:
The weighted average
"""
msg = "Attempting to calculate weighted average over two dictionaries that do not share keys"
assert distribution.keys() == weights.keys(), msg
numerator = sum([distribution[i] * weights[i] for i in distribution.keys()])
denominator = sum(weights.values())
fraction = numerator / denominator
result = round(fraction, rounding) if rounding else fraction
return result | bigcode/self-oss-instruct-sc2-concepts |
def get_orientation(strategy, **kwargs):
"""
Determine a PV system's surface tilt and surface azimuth
using a named strategy.
Parameters
----------
strategy: str
The orientation strategy.
Allowed strategies include 'flat', 'south_at_latitude_tilt'.
**kwargs:
Strategy-dependent keyword arguments. See code for details.
Returns
-------
surface_tilt, surface_azimuth
"""
if strategy == 'south_at_latitude_tilt':
surface_azimuth = 180
surface_tilt = kwargs['latitude']
elif strategy == 'flat':
surface_azimuth = 180
surface_tilt = 0
else:
raise ValueError('invalid orientation strategy. strategy must ' +
'be one of south_at_latitude, flat,')
return surface_tilt, surface_azimuth | bigcode/self-oss-instruct-sc2-concepts |
def stockmax(prices_):
"""
Given an array of prices in a stock market
find the highest profit you can gain.
:param : int[] prices
:rtype : int
"""
if len(prices_) < 2:
return 0
profit, peak = 0, prices_[-1]
for i in range(len(prices_) - 1, -1, -1):
if prices_[i] > peak: # peak is current highest
peak = prices_[i]
elif prices_[i] < peak: # previous than peak gain all profits
profit += peak - prices_[i]
return profit | bigcode/self-oss-instruct-sc2-concepts |
import json
def load_categories(filename):
"""Load categories from a file containing json data
Parameters:
filename (string): the name of the file
Returns:
object:the categories object
"""
with open(filename, 'r') as f:
cat_to_name = json.load(f)
return cat_to_name | bigcode/self-oss-instruct-sc2-concepts |
def t_norm(a, b, norm=min):
"""
Equivalent to `a.t_norm(b, norm)`.
"""
return a.t_norm(b, norm) | bigcode/self-oss-instruct-sc2-concepts |
import random
import string
def get_random_string(length=6):
"""
Return a random string 'length' characters long
"""
return ''.join(random.SystemRandom().choice(string.ascii_uppercase + string.digits) for _ in range(length)) | bigcode/self-oss-instruct-sc2-concepts |
def mag_double_power_law(mag, phi_star, mag_star, alpha, beta):
"""Evaluate a broken double power law luminosity function as a function
of magnitude.
:param mag: Magnitude
:type mag: float or np.ndarray
:param phi_star: Normalization of the broken power law at a value of
mag_star
:type phi_star: float
:param mag_star: Break magnitude of the power law
:type mag_star: float
:param alpha: First slope of the broken power law
:type alpha: float
:param beta: Second slope of the broken power law
:type beta: float
:return: Value of the broken double power law at a magnitude of M
:rtype: float or np.ndarray
"""
A = pow(10, 0.4 * (alpha + 1) * (mag - mag_star))
B = pow(10, 0.4 * (beta + 1) * (mag - mag_star))
return phi_star / (A + B) | bigcode/self-oss-instruct-sc2-concepts |
def list_dict_to_list_list(players: list[dict]) -> list[list]:
"""Convert a list of dictionaries to a list of lists."""
new_list: list = []
for player in players:
stats: list = []
for stat in player.values():
stats.append(stat)
new_list.append(stats)
return new_list | bigcode/self-oss-instruct-sc2-concepts |
import csv
def samples(gnomAD_path: str):
"""Create dictionary of sample ID and haplogroup.
:param gnomAD_path: path to the gnomAD VCF
:return: matches_samples dictionary with the haplogroup of every sample
"""
with open(gnomAD_path + "t21/sample_annotations_gnomad.txt") as csv_file:
samples = csv.DictReader(csv_file, delimiter="\t")
matches_samples = {}
for row in samples:
matches_samples[row["s"]] = row["hap"]
return matches_samples | bigcode/self-oss-instruct-sc2-concepts |
def fix_var_name(var_name):
"""Clean up and apply standard formatting to variable names."""
name = var_name.strip()
for char in '(). /#,':
name = name.replace(char, '_')
name = name.replace('+', 'pos_')
name = name.replace('-', 'neg_')
if name.endswith('_'):
name = name[:-1]
return name | bigcode/self-oss-instruct-sc2-concepts |
from typing import Sequence
def variant_to_pair(variant: str) -> Sequence[str]:
"""Given a variant, splits it into an OS and ABI pair
Parameters
----------
variant : str
The variant received as input to the script (e.g. windows-win64)
Returns
-------
Sequence[str]
A 2 item sequence containing the OS at position 0 and, if applicable, the ABI at position 1 (otherwise empty string)
"""
if variant == "linux" or variant == "centos6":
return [variant, "x86_64"]
if variant == "macosx":
return ["macos", "x86_64"]
if variant == "ios":
return ["ios", ""]
first_dash = variant.index("-")
osname = variant[0:first_dash]
abi = variant[first_dash+1:]
if osname == "android":
return [osname, abi]
if abi.find("win64") != -1:
return ["windows", abi.replace("win64", "x86_64")]
elif abi.find("win32") != -1:
return ["windows", abi.replace("win32", "x86")]
else:
return [osname, abi] | bigcode/self-oss-instruct-sc2-concepts |
def extract_properties_by_schema(group_objects_list, group_gid_number_attr, group_name_attr):
"""
Safeguard Authentication Services is designed to support any Active Directory schema
configuration. If your Active Directory schema has built-in support for Unix attributes
(Windows 2003 R2 schema, SFU schema), Safeguard Authentication Services automatically
uses one of these schema configurations. Examples of group_object:
{
"DistinguishedName": "CN=AutoEnrollGroup,CN=Users,DC=QASDEV,DC=oi",
"Name": "AutoEnrollGroup",
"ObjectClass": "group",
"ObjectGUID": "fe8d95e1-d620-4661-bc14-a7ae5b172956",
"gidNumber": 641753664,
"sAMAccountName": "AutoEnrollGroup"
},
{
"DistinguishedName": "CN=TestGroup,CN=Users,DC=QASDEV,DC=oi",
"Name": "TestGroup",
"ObjectClass": "group",
"ObjectGUID": "619b9645-8a92-4584-bb82-b4818be77e54",
"gidNumber": 10001,
"sAMAccountName": "TestGroup"
},
"""
attrs = ['DistinguishedName', group_name_attr, group_gid_number_attr]
groups = []
for group_object in group_objects_list:
group = []
for attr in attrs:
if attr in group_object and group_object[attr]:
group.append(group_object[attr])
else:
group.append('')
# A Group object is considered to be 'Unix-enabled' if it has values for
# the Group GID Number and Group Name.
if group[1] and group[2]:
groups.append(group)
return groups | bigcode/self-oss-instruct-sc2-concepts |
def coupling_list2dict(couplinglist):
"""Convert coupling map list into dictionary.
Example list format: [[0, 1], [0, 2], [1, 2]]
Example dictionary format: {0: [1, 2], 1: [2]}
We do not do any checking of the input.
Return coupling map in dict format.
"""
if not couplinglist:
return None
couplingdict = {}
for pair in couplinglist:
if pair[0] in couplingdict:
couplingdict[pair[0]].append(pair[1])
else:
couplingdict[pair[0]] = [pair[1]]
return couplingdict | bigcode/self-oss-instruct-sc2-concepts |
def GetKnoteSummary(kn):
""" Summarizes a knote and related information
returns: str - summary of knote
"""
out_string = ""
format_string = "{o: <#020x}"
out_string += format_string.format(o=kn)
return out_string | bigcode/self-oss-instruct-sc2-concepts |
def scale(v,sc):
"""Scale a vector.
Parameters
----------
v : list
A 3D vector.
sc : int or float
A scaling factor.
Returns
-------
tuple
Returns `v` scaled by `sc`.
Examples
--------
>>> from .pycgmKinetics import scale
>>> v = [1,2,3]
>>> sc = 2
>>> scale(v, sc)
(2, 4, 6)
"""
x,y,z = v
return (x * sc, y * sc, z * sc) | bigcode/self-oss-instruct-sc2-concepts |
def infix_to_postfix(expression):
"""
Function turns infix expression into postfix expression by iterating over the expression
and moving operators after their operands whilst maintaining order of precedence.
:param expression: Space delimited parenthetical expression containing of letters and the operators * / + -
:return: PostFix version of expression
"""
'''
1)Fix a priority level for each operator. For example, from high to low:
3. - (unary negation)
2. * /
1. + - (subtraction)
2) If the token is an operand, do not stack it. Pass it to the output.
3) If token is an operator or parenthesis:
3.1) if it is '(', push
3.2) if it is ')', pop until '('
3.3) push the incoming operator if its priority > top operator; otherwise pop.
*The popped stack elements will be written to output.
4) Pop the remainder of the stack and write to the output (except left parenthesis)
'''
operators = {'(', ')', '*', '/', '+', '-'}
op_stack = []
precedence = {'*': 3, '/': 3, '+': 2, '-': 2}
result = ''
for exp in expression:
if exp not in operators:
result += exp
elif exp == '(':
op_stack.append(exp)
elif exp == ')':
while op_stack and op_stack[-1] != '(':
result += op_stack.pop()
op_stack.pop()
else:
while op_stack and op_stack[-1] != '(' and precedence[exp] <= precedence[op_stack[-1]]:
result += op_stack.pop()
op_stack.append(exp)
while op_stack:
result += op_stack.pop()
return result | bigcode/self-oss-instruct-sc2-concepts |
def q_max_ntu(c_min, temp_hot_in, temp_cold_in):
"""Computes the maximum q value for the NTU method
Args:
c_min (int, float): minimum C value for NTU calculations.
temp_hot_in (int, float): Hot side inlet temeprature.
temp_cold_in (int, float): Cold side inlet temeprature.
Returns:
int, float: The value of the maximum q value for the NTU method
"""
return c_min*(temp_hot_in-temp_cold_in) | bigcode/self-oss-instruct-sc2-concepts |
def get_year_version_from_schema(schema_string):
""" expects a schema string from xml like: 2015v2.1 """
[year, version] = schema_string.split('v')
return({'year':int(year), 'version':version}) | bigcode/self-oss-instruct-sc2-concepts |
def is_empty(value):
"""
Checks if a value is an empty string or None.
"""
if value is None or value == '':
return True
return False | bigcode/self-oss-instruct-sc2-concepts |
def theme(dark=False, lighten=0.3, lighten_edges=None, lighten_text=None,
lighten_grid=None, **kwargs):
"""
Create plotting parameters for different themes.
Parameters
----------
dark : bool
Dark or light theme.
lighten : float with range [0.0, 1.0]
Lighten lines by fration `lighten`.
See https://www.darkhorseanalytics.com/blog/data-looks-better-naked/
lighten_edges : float
Defaults to `lighten`.
lighten_text : float
Defaults to `lighten`.
lighten_grid : float
Defaults to `lighten`.
**kwargs : dict
Not used.
Returns
-------
dict
Matplotlib plotting parameters dictionary.
"""
if lighten_edges is None:
lighten_edges = lighten
if lighten_text is None:
lighten_text = lighten
if lighten_grid is None:
lighten_grid = lighten_edges
foreground_text = str(0.0 + lighten_text)
foreground_edges = str(0.0 + lighten_edges)
foreground_grid = str(0.0 + lighten_grid)
background = 'white'
if dark:
foreground_text = str(1.0 - lighten_text)
foreground_edges = str(1.0 - lighten_edges)
foreground_grid = str(1.0 - lighten_grid)
background = 'black'
params = {
# 'lines.color': foreground,
'patch.edgecolor': foreground_edges,
'text.color': foreground_text,
'axes.facecolor': background,
'axes.edgecolor': foreground_edges,
'axes.labelcolor': foreground_text,
'xtick.color': foreground_text,
'ytick.color': foreground_text,
'grid.color': foreground_grid,
'legend.edgecolor': foreground_edges,
'figure.facecolor': background,
'figure.edgecolor': background,
'savefig.facecolor': background,
'savefig.edgecolor': background
}
return params | bigcode/self-oss-instruct-sc2-concepts |
def fix_ra_dec(ra, dec):
"""
Wraps input RA and DEC values into range expected by the extensions.
Parameters
------------
RA: array-like, units must be degrees
Right Ascension values (astronomical longitude)
DEC: array-like, units must be degrees
Declination values (astronomical latitude)
Returns
--------
Tuple (RA, DEC): array-like
RA is wrapped into range [0.0, 360.0]
Declination is wrapped into range [-90.0, 90.0]
"""
try:
input_dtype = ra.dtype
except:
msg = "Input RA array must be a numpy array"
raise TypeError(msg)
if ra is None or dec is None:
msg = "RA or DEC must be valid arrays"
raise ValueError(msg)
if min(ra) < 0.0:
print("Warning: found negative RA values, wrapping into [0.0, 360.0] "
" range")
ra += 180.0
if max(dec) > 90.0:
print("Warning: found DEC values more than 90.0; wrapping into "
"[-90.0, 90.0] range")
dec += 90.0
return ra.astype(input_dtype), dec.astype(input_dtype) | bigcode/self-oss-instruct-sc2-concepts |
def complete_cases(_data):
"""Return a logical vector indicating values of rows are complete.
Args:
_data: The dataframe
Returns:
A logical vector specifying which observations/rows have no
missing values across the entire sequence.
"""
return _data.apply(lambda row: row.notna().all(), axis=1).values | bigcode/self-oss-instruct-sc2-concepts |
def non_writable_folder(fs):
"""
A filesystem with a /dir directory that is not writable
"""
fs.create_dir('/dir', perm_bits=000)
return fs | bigcode/self-oss-instruct-sc2-concepts |
def compose(*funcs):
""" Composes a series of functions, like the Haskell . operator.
Args:
*funcs: An arbitrary number of functions to be composed.
Returns:
A function that accepts whatever parameters funcs[-1] does, feeds those to funcs[-1],
feeds the result of that into funcs[-2], etc, all the way through funcs[0], and then
returns whatever funcs[0] returned.
>>> add1 = lambda n: n + 1
>>> times2 = lambda n: n * 2
>>> add3 = lambda n: n + 3
>>> f = compose(add1, times2, add3)
>>> f(4)
15
"""
def inner(*a, **kw):
acc = funcs[-1](*a, **kw)
for f in funcs[-2::-1]:
acc = f(acc)
return acc
return inner | bigcode/self-oss-instruct-sc2-concepts |
def match_barcode_rule(trello_db, barcode):
"""Finds a barcode rule matching the given barcode.
Returns the rule if it exists, otherwise returns None."""
rules = trello_db.get_all('barcode_rules')
for r in rules:
if r['barcode'] == barcode:
return r
return None | bigcode/self-oss-instruct-sc2-concepts |
def JoinDisjointDicts(dict_a, dict_b):
"""Joins dictionaries with no conflicting keys.
Enforces the constraint that the two key sets must be disjoint, and then
merges the two dictionaries in a new dictionary that is returned to the
caller.
@type dict_a: dict
@param dict_a: the first dictionary
@type dict_b: dict
@param dict_b: the second dictionary
@rtype: dict
@return: a new dictionary containing all the key/value pairs contained in the
two dictionaries.
"""
assert not (set(dict_a) & set(dict_b)), ("Duplicate keys found while joining"
" %s and %s" % (dict_a, dict_b))
result = dict_a.copy()
result.update(dict_b)
return result | bigcode/self-oss-instruct-sc2-concepts |
def diff_single(arr, val):
""" Return difference between array and scalar. """
return [i - val for i in arr] | bigcode/self-oss-instruct-sc2-concepts |
import time
def run_time_calc(func):
"""
Calculate the run time of a function.
"""
def wrapper(*args, **kwargs):
start = time.time()
ans = func(*args, **kwargs)
end = time.time()
print('\nRun time of function [%s] is %.2f.' % (func.__name__,
end - start))
return ans
return wrapper | bigcode/self-oss-instruct-sc2-concepts |
from typing import Union
from typing import List
def build_gcm_identifier(
gcm: str,
scenario: str,
train_period_start: str,
train_period_end: str,
predict_period_start: str,
predict_period_end: str,
variables: Union[str, List[str]],
**kwargs,
) -> str:
"""
Build the common identifier for GCM related data
Parameters
----------
gcm : str
From run hyperparameters
scenario : str
From run hyperparameters
train_period_start : str
From run hyperparameters
train_period_end : str
From run hyperparameters
predict_period_start : str
From run hyperparameters
predict_period_end : str
From run hyperparameters
variables : str
From run hyperparameters
Returns
-------
identifier : str
string to be used in gcm related paths as specified by the params
"""
if isinstance(variables, str):
variables = [variables]
var_string = '_'.join(variables)
return f'{gcm}_{scenario}_{train_period_start}_{train_period_end}_{predict_period_start}_{predict_period_end}_{var_string}' | bigcode/self-oss-instruct-sc2-concepts |
import re
def _apply_extractor(extractor, X, ch_names, return_as_df):
"""Utility function to apply features extractor to ndarray X.
Parameters
----------
extractor : Instance of :class:`~sklearn.pipeline.FeatureUnion` or
:class:`~sklearn.pipeline.Pipeline`.
X : ndarray, shape (n_channels, n_times)
ch_names : list of str or None
return_as_df : bool
Returns
-------
X : ndarray, shape (n_features,)
feature_names : list of str | None
Not None, only if ``return_as_df`` is True.
"""
X = extractor.fit_transform(X)
feature_names = None
if return_as_df:
feature_names = extractor.get_feature_names()
if ch_names is not None: # rename channels
mapping = {'ch%s' % i: ch_name
for i, ch_name in enumerate(ch_names)}
for pattern, translation in mapping.items():
r = re.compile(rf'{pattern}(?=_)|{pattern}\b')
feature_names = [
r.sub(string=feature_name, repl=translation)
for feature_name in feature_names]
return X, feature_names | bigcode/self-oss-instruct-sc2-concepts |
import importlib
def str_to_type(classpath):
"""
convert class path in str format to a type
:param classpath: class path
:return: type
"""
module_name, class_name = classpath.rsplit(".", 1)
cls = getattr(importlib.import_module(module_name), class_name)
return cls | bigcode/self-oss-instruct-sc2-concepts |
def read_file(path: str):
"""
Read a file from the filesystem.
"""
with open(path, "r") as file:
data = file.read()
return data | bigcode/self-oss-instruct-sc2-concepts |
def get_latest_reading(client, name):
"""Returns the value and timestamp of the latest reading."""
query = client.query(kind=name)
query.order = ["-timestamp"]
results = list(query.fetch(limit=1))
if not results:
return None, None
result = results[0]
if "value" not in result:
return None, None
value = result["value"]
if "timestamp" not in result:
return None, None
timestamp = result["timestamp"]
return value, timestamp | bigcode/self-oss-instruct-sc2-concepts |
def string_transformer(s: str) -> str:
"""
Given a string, return a new string that has
transformed based on the input:
1. Change case of every character, ie. lower
case to upper case, upper case to lower case.
2. Reverse the order of words from the input.
Note: You will have to handle multiple spaces, and
leading/trailing spaces.
You may assume the input only contain English
alphabet and spaces.
:param s:
:return:
"""
s_arr = s.split(' ')[::-1]
for i, word in enumerate(s_arr):
s_arr[i] = ''.join((char.upper() if char.islower() else char.lower()) for char in word)
return ' '.join(s_arr) | bigcode/self-oss-instruct-sc2-concepts |
def isSubDict(dict_super, dict_sub):
"""
Tests if the second dictonary is a subset of the first.
:param dict dict_super:
:param dict dict_sub:
:return bool:
"""
for key in dict_sub.keys():
if not key in dict_super:
return False
if not dict_sub[key] == dict_super[key]:
return False
return True | bigcode/self-oss-instruct-sc2-concepts |
import sympy
from typing import Iterable
def parameter_checker(parameters):
"""Checks if any items in an iterable are sympy objects."""
for item in parameters:
if isinstance(item, sympy.Expr):
return True
# This checks all the nested items if item is an iterable
if isinstance(item, Iterable) and not isinstance(item, str):
if parameter_checker(item):
return True
return False | bigcode/self-oss-instruct-sc2-concepts |
import re
def title_year(m_file):
"""
Regex searching returns the title and year from the filename
Currently optimized for: "Title (year).extension"
"""
name = re.compile(r'([\w+\W?]+)\s\(([0-9]{4})\)[\s\w]*[\d\.\d]*[\s\w]*\.\w{2,4}')
fsearch = name.search(m_file)
if fsearch:
title = fsearch.group(1)
year = fsearch.group(2)
else:
print('No match for {}'.format(m_file))
title = None
year = None
return title, year | bigcode/self-oss-instruct-sc2-concepts |
def offset_format(utc_offset):
"""Display + or - in front of UTC offset number"""
return str(utc_offset) if utc_offset < 0 else f"+{str(utc_offset)}" | bigcode/self-oss-instruct-sc2-concepts |
def odd_even(x):
"""
odd_even tells if a number is odd (return True) or even (return False)
Parameters
----------
x: the integer number to test
Returns
-------
bool : boolean
"""
if not isinstance(x, int):
raise TypeError(f'{x} should be an integer')
if int(x) % 2 == 0:
bool = False
else:
bool = True
return bool | bigcode/self-oss-instruct-sc2-concepts |
def sort(d):
"""sort dictionary by keys"""
if isinstance(d, dict):
return {k: d[k] for k in sorted(d)}
return d | bigcode/self-oss-instruct-sc2-concepts |
import pickle
def read_data(path, n_vaues=None):
"""
Given a path, read the file and return the contents.
Arguments:
path (string) : File path with .pkl extension
n_values (int) : Number of containers expected to be read.
"""
f = open(path, "rb")
d = pickle.load(f)
f.close()
return d | bigcode/self-oss-instruct-sc2-concepts |
from pathlib import Path
import json
def load_config(path_config, config_type='json'):
"""
加载配置文件。
如果不是绝对路径,则必须是在config目录下。
必须是json文件,可以不指定后缀。
:param path_config: Path变量或者是字符串。
:param config_type: 配置文件类型,值为'json'时,返回字典;为'txt'时,返回字符串列表
:return:
"""
assert config_type in ('json', 'txt')
# 转变类型
if isinstance(path_config, str):
path_config = Path(path_config)
# 文件是否存在
if not path_config.exists():
raise FileNotFoundError(f'找不到配置文件: {str(path_config)}')
# 读取配置文件
if config_type == 'json':
with open(path_config, 'rb') as f:
params = json.load(f)
else:
with open(path_config, 'r') as f:
params = [key.strip() for key in f.readlines()]
return params | bigcode/self-oss-instruct-sc2-concepts |
def _apply_linear_trend(data, elevs, trend, direction):
"""
Detrend or retrend a set of data points using a given trend value.
Parameters
----------
data : ndarray
Detrended values.
elevs : ndarray
Elevations corresponding to the data points.
trend : float
Trend value.
direction : str
Either "detrend" or "retrend".
Returns
-------
data_trend : ndarray
De-/retrended data points.
"""
if direction == 'detrend':
return data - trend * elevs
elif direction == 'retrend':
return data + trend * elevs
else:
raise NotImplementedError(f'Unsupported direction: {direction}') | bigcode/self-oss-instruct-sc2-concepts |
def _score_phrases(phrase_list, word_scores):
"""Score a phrase by tallying individual word scores"""
phrase_scores = {}
for phrase in phrase_list:
phrase_score = 0
# cumulative score of words
for word in phrase:
phrase_score += word_scores[word]
phrase_scores[" ".join(phrase)] = phrase_score
return phrase_scores | bigcode/self-oss-instruct-sc2-concepts |
def read_lines(filename):
"""Read all lines from a given file."""
with open(filename) as fp:
return fp.readlines() | bigcode/self-oss-instruct-sc2-concepts |
def prepToMatlab(detectorName, quantity):
"""Create a name of a variable for MATLAB"""
return detectorName + "_" + quantity | bigcode/self-oss-instruct-sc2-concepts |
from pathlib import Path
import re
def get_files(folder, name, indexes=None):
"""Get all files with given name in given folder (and in given order)
Parameters
----------
folder : str
path to files (folder name)
name : str
file name pattern
indexes : list
files order
Returns
-------
list
a list of file names
"""
nums = []
files = []
for path in Path(folder).glob(name):
numbers = [int(d) for d in re.findall(r'-?\d+', path.name)]
nums.append(numbers[-1] - 1 if len(numbers) > 0 else -1)
files.append(path.name)
if indexes is not None:
files = [x for _, x in sorted(zip(indexes, files))]
else:
files = [x for _, x in sorted(zip(nums, files))]
return files | bigcode/self-oss-instruct-sc2-concepts |
import click
def bool_option(name, short_name, desc, dflt=False, **kwargs):
"""Generic provider for boolean options
Parameters
----------
name : str
name of the option
short_name : str
short name for the option
desc : str
short description for the option
dflt : bool or None
Default value
**kwargs
All kwargs are passed to click.option.
Returns
-------
``callable``
A decorator to be used for adding this option.
"""
def custom_bool_option(func):
def callback(ctx, param, value):
ctx.meta[name.replace("-", "_")] = value
return value
return click.option(
"-%s/-n%s" % (short_name, short_name),
"--%s/--no-%s" % (name, name),
default=dflt,
help=desc,
show_default=True,
callback=callback,
is_eager=True,
**kwargs,
)(func)
return custom_bool_option | bigcode/self-oss-instruct-sc2-concepts |
def seqStartsWith(seq, startSeq):
"""
Returns True iff sequence startSeq is the beginning of sequence seq or
equal to seq.
"""
if len(seq) < len(startSeq):
return False
if len(seq) > len(startSeq):
return seq[:len(startSeq)] == startSeq
return seq == startSeq | bigcode/self-oss-instruct-sc2-concepts |
def calc_center(eye):
"""
Using for further cropping eyes from images with faces
:param eye:
:return: x, y, of center of eye
"""
center_x = (eye[0][0] + eye[3][0]) // 2
center_y = (eye[0][1] + eye[3][1]) // 2
return int(center_x), int(center_y) | bigcode/self-oss-instruct-sc2-concepts |
def xyz_datashape(al, xyz):
"""Get datashape from axislabels and bounds."""
x, X, y, Y, z, Z = xyz
if al == 'zyx':
datalayout = (Z - z, Y - y, X - x)
elif al == 'zxy':
datalayout = (Z - z, X - x, Y - y)
elif al == 'yzx':
datalayout = (Y - y, Z - z, X - x)
elif al == 'yxz':
datalayout = (Y - y, X - x, Z - z)
elif al == 'xzy':
datalayout = (X - x, Z - z, Y - y)
else:
datalayout = (X - x, Y - y, Z - z)
return datalayout | bigcode/self-oss-instruct-sc2-concepts |
def has_group(user, group_name):
"""
Verify the user has a group_name in groups
"""
groups = user.groups.all().values_list('name', flat=True)
return True if group_name in groups else False | bigcode/self-oss-instruct-sc2-concepts |
def output_dim(request) -> int:
"""Output dimension of the random process."""
return request.param | bigcode/self-oss-instruct-sc2-concepts |
def num_gt_0(column):
"""
Helper function to count number of elements > 0 in an array like object
Parameters
----------
column : pandas Series
Returns
-------
int, number of elements > 0 in ``column``
"""
return (column > 0).sum() | 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.