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)
... | 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 int... | 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... | 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 ... | 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.ge... | 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... | 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_gr... | 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:] ... | 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
>>> har... | 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,}
... | 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,... | 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.su... | 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 : voc... | 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 pa... | 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... | 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 str... | 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:
... | 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 ... | 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... | 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 = he... | 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 t... | 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: ... | 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 escribi... | 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... | 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... | 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] > pea... | 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... | 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:
samp... | 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]
... | 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... | 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 sche... | 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:
ret... | 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]
>>> ... | 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 oper... | 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.
... | 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 fr... | 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 ... | 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.no... | 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... | 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 dic... | 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__,
... | 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 ide... | 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_... | 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:
... | 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
... | 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
re... | 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 isinsta... | 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:
tit... | 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 =... | 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(... | 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', 'tx... | 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 va... | 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[" ... | 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
... | 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 : boo... | 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 == 'yx... | 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.