seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
def _scale_size(size, scale):
"""Rescale a size by a ratio.
Args:
size (tuple[int]): (w, h).
scale (float): Scaling factor.
Returns:
tuple[int]: scaled size.
"""
w, h = size
return int(w * float(scale) + 0.5), int(h * float(scale) + 0.5) | bigcode/self-oss-instruct-sc2-concepts |
def remove_digits(s):
"""
Returns a string with all digits removed.
"""
return ''.join(filter(lambda x: not x.isdigit(), s)) | bigcode/self-oss-instruct-sc2-concepts |
def _ParseGnArgs(args_path):
"""Returns a list of normalized "key=value" strings."""
args = {}
with open(args_path) as f:
for l in f:
# Strips #s even if within string literal. Not a problem in practice.
parts = l.split('#')[0].split('=')
if len(parts) != 2:
continue
args[parts... | bigcode/self-oss-instruct-sc2-concepts |
import copy
def merge_qedges(qedges1: dict, qedges2: dict) -> dict:
"""Merge qedges: the keys must be the same and the values must be the same.
If a key is unique to one edges dict, then the edge will be concatenated to
the new edges dictionary. If a particular key exists in both messages but
the valu... | bigcode/self-oss-instruct-sc2-concepts |
def rekey_map(mapping, replacements):
"""Given an iterable of destination/source pairs in replacements,
create a new dict that is the same as the original except for the
new key names."""
result = dict(mapping)
for dst, src in replacements:
value = result[src]
result[dst] = value
... | bigcode/self-oss-instruct-sc2-concepts |
def parseOperator(value):
"""
Returns a search operator based on the type of the value to match on.
:param value: to match in the search.
:return: operator to use for the type of value.
"""
if type(value) == str:
return " LIKE "
else:
return "=" | bigcode/self-oss-instruct-sc2-concepts |
def unique_list(lst):
"""Make a list unique, retaining order of initial appearance."""
uniq = []
for item in lst:
if item not in uniq:
uniq.append(item)
return uniq | bigcode/self-oss-instruct-sc2-concepts |
def get_filenames_add_username(files, username):
"""
Adds the username to the end of a file name
:param files: List of file names
:param username: Username to append
:return: filename with appended username
"""
filenames = []
for file in files:
filenames.append(file + username... | bigcode/self-oss-instruct-sc2-concepts |
def sortedby(item_list, key_list, reverse=False):
""" sorts ``item_list`` using key_list
Args:
list_ (list): list to sort
key_list (list): list to sort by
reverse (bool): sort order is descending (largest first)
if reverse is True else acscending (smallest first)... | bigcode/self-oss-instruct-sc2-concepts |
def FWHMgeom2FWHMeff(FWHMgeom):
"""
Convert FWHMgeom to FWHMeff.
This conversion was calculated by Bo Xin and Zeljko Ivezic
(and will be in an update on the LSE-40 and overview papers).
Parameters
----------
FWHMgeom: float
The geometric FWHM value, as measured from a typical PSF pr... | bigcode/self-oss-instruct-sc2-concepts |
def selector(selection_string: str, options: "list[str]", default = None) -> str:
"""
Asks the user for an option within a list of provided options and an optional default and returns their response
"""
while True:
if default:
input_string = f"{selection_string} ({', '.join(options)}... | bigcode/self-oss-instruct-sc2-concepts |
def first(x):
"""Returns the first time step of all sequences in x."""
return x.dimshuffle((1,0,2))[0] | bigcode/self-oss-instruct-sc2-concepts |
import torch
def exact_gaussian_kernel(x1, x2):
"""Computes exact Gaussian kernel value(s) for tensors x1 and x2."""
x1 = torch.tensor(x1, dtype=torch.float32)
x2 = torch.tensor(x2, dtype=torch.float32)
x1_squared = torch.sum(x1 ** 2, list(range(1, len(x1.shape))))
x2_squared = torch.sum(x2 ** 2, ... | bigcode/self-oss-instruct-sc2-concepts |
def get_depth(node):
"""
Helper function to get depth of node
from root
"""
depth = 0
while node.parent:
node = node.parent
depth += 1
return depth | bigcode/self-oss-instruct-sc2-concepts |
def parametrization_name_func(func_name, kwargs):
"""
Method name generator for parametrized testcases.
>>> import collections
>>> parametrization_name_func('test_method',
collections.OrderedDict(('foo', 5), ('bar', 10)))
'test_method__foo_5__bar_10'
:param func_... | bigcode/self-oss-instruct-sc2-concepts |
def union(root1, root2):
"""Perform a weighted union between root1 and root2.
Args:
root1 (Root): root of the first cluster in the union
root2 (Root): root of the second cluster in the union
Returns:
NoneType or (Root, Root): If root1 and root2 are same, returns None;
e... | bigcode/self-oss-instruct-sc2-concepts |
def dispatch(result):
"""DB query result parser"""
return [row for row in result] | bigcode/self-oss-instruct-sc2-concepts |
def is_vcs_link(ireq):
"""
Returns whether an InstallRequirement is a version control link.
"""
return ireq.link is not None and not ireq.link.is_artifact | bigcode/self-oss-instruct-sc2-concepts |
def option7(current_person):
"""The children of a person can printed using this function.
Parameters:
current_person:
The current Person object.
Returns:
The current Person object.
"""
ch_lst = current_person.get_children()
if len(ch_lst) == 0:
print(f"No children f... | bigcode/self-oss-instruct-sc2-concepts |
def disp(c, domain=True):
"""
Create a string formatted list of the curve's x-values if domain is True, otherwise y-values.
>>> c = pydvif.span(1, 10)
>>> yvalues = pydvif.disp(c, False)
:param c: The given curve
:type curvelist: Curve
:param domain: if True, display the x-values of the c... | bigcode/self-oss-instruct-sc2-concepts |
def is_model_class(val) -> bool:
"""Return whether the parameter is a SQLAlchemy model class."""
return hasattr(val, '__base__') and hasattr(val, '__table__') | bigcode/self-oss-instruct-sc2-concepts |
def get_range(value):
""" Return the range for under or over limit message """
if (value & 4) == 4:
return '80 - 130'
elif (value & 3) == 3:
return '60 - 110'
elif (value & 2) == 2:
return '50 - 100'
elif (value & 1) == 1:
return '30 - 80'
else :
return '... | bigcode/self-oss-instruct-sc2-concepts |
import re
def _escape(line):
"""
Escape the syntax-breaking characters.
"""
line = line.replace('[', r'\[').replace(']', r'\]')
line = re.sub('\'', '', line) # ' is unescapable afaik
return line | bigcode/self-oss-instruct-sc2-concepts |
def build_message(attr_name, val1, val2, details=""):
""" Build error message for is_has_traits_almost_equal and
is_val_almost_equal to return.
"""
type1 = type(val1)
type2 = type(val2)
msg = "Different {} {}. Types: {} vs {}. Values: \n{} \nvs \n{}"
msg = msg.format(attr_name, details, type... | bigcode/self-oss-instruct-sc2-concepts |
def string_to_number(byte_repr_str):
"""
Args:
byte_repr_str (str): e.g. 100MB, 10Kb; float is not allowed
Returns:
num (int): bytes
"""
is_parsing_unit = False
num = 0
for ch in byte_repr_str:
if ch.isdigit():
assert is_parsing_unit is False
n... | bigcode/self-oss-instruct-sc2-concepts |
def read_article(file_name):
"""
Reads the Text file, and coverts them into sentences.
:param file_name: Path of text file (line 12)
:return: sentences
"""
file = open(file_name, 'r', encoding="utf-8")
filedata = file.readlines()
article = filedata[0].split(". ")
sentences = []
... | bigcode/self-oss-instruct-sc2-concepts |
def subset_sum_squeeze(data, subset={}, sum_dims=None, squeeze=False):
"""
Take an xarray DataArray and apply indexing, summing and squeezing,
to prepare it for analysis.
Parameters
----------
data : xarray DataArray
A Calliope model data variable, either input or output, which has been... | bigcode/self-oss-instruct-sc2-concepts |
def find_root_node(program_tree):
"""Find root program."""
return [program for program in program_tree if not program_tree[program]][0] | bigcode/self-oss-instruct-sc2-concepts |
def create_stream_size_map(stream_indices):
"""
Creates a map from stream name to stream size from the indices table.
:param stream_indices: The stream indices table.
:return: The map.
"""
return {pair[0]: len(pair[1]) for pair in stream_indices} | bigcode/self-oss-instruct-sc2-concepts |
import string
import random
def generate_key(key_length: int = 16, key_pattern: str = "x#x#"):
"""
generates a unique activation key with a length and a pattern
key_length: length of the key (default 16)
key_pattern: set of x's and #'s in a string (default "x#x#")
"x": random letter
"#": rando... | bigcode/self-oss-instruct-sc2-concepts |
def _is_name_start(css, pos):
"""Return true if the given character is a name-start code point."""
# https://www.w3.org/TR/css-syntax-3/#name-start-code-point
c = css[pos]
return (
c in 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_' or
ord(c) > 0x7F) | bigcode/self-oss-instruct-sc2-concepts |
import torch
def nearest_neighbor_grad(
averaged_grad,
embedding_matrix,
trigger_token_ids,
tree,
step_size,
increase_loss=False,
num_candidates=1,
):
"""
Takes a small step in the direction of the averaged_grad and finds the nearest
vector in the embedding matrix using a kd-tr... | bigcode/self-oss-instruct-sc2-concepts |
def validate_timestamp(val):
"""
Returns a boolean indication that a field is a valid timestamp - a
floating point number representing the time in seconds since the Epoch (so
called POSIX time, see https://en.wikipedia.org/wiki/Unix_time).
"""
return (isinstance(val, float) and val >= 0.0) | bigcode/self-oss-instruct-sc2-concepts |
def TDict(val):
"""Checks if the given value is a dictionary.
"""
return isinstance(val, dict) | bigcode/self-oss-instruct-sc2-concepts |
from typing import OrderedDict
def invert(mapper):
"""Invert a dict of lists preserving the order."""
inverse = OrderedDict()
for k, v in mapper.items():
for i in v:
inverse[i] = k
return inverse | bigcode/self-oss-instruct-sc2-concepts |
import socket
import struct
def inet_aton(addr):
"""Convert an IP addr in IPv4 dot notation into an int.
addr IP address as a string
returns integer
"""
b = socket.inet_aton(addr)
return struct.unpack('!I', b)[0] | bigcode/self-oss-instruct-sc2-concepts |
def validate_nodes_number(nodes_number: int) -> int:
"""
Check whether a number of nodes is sufficient to detrend the data.
Parameters
----------
nodes_number : int
The number of nodes.
Returns
-------
int
The number of nodes.
Raises
------
ValueError
... | bigcode/self-oss-instruct-sc2-concepts |
def sum_of_all(list_of_nums: list):
"""adds all numbers in a list together and returns the sum"""
sum_of_nums = 0
for num in list_of_nums:
sum_of_nums += num
print(sum_of_nums)
return sum_of_nums | bigcode/self-oss-instruct-sc2-concepts |
def link_topics_and_weightings(topic_words, topic_words_weighting):
"""
Pair every words with their weightings for topics into tuples of (), for each topic.
:param topic_words: a 2D array of shape [topics, top_words]
:param topic_words_weighting: a 2D array of shape [topics, top_words_weightings]
:... | bigcode/self-oss-instruct-sc2-concepts |
def clean_caption(caption):
"""Removes unnecessary parts of an Instagram post caption
It removes all the hashtags and converts tags in plain text (@marco97pa --> marco97pa)
Args:
caption: a text
Returns:
the same caption without hashtags and tags
"""
clean = ""
words = capti... | bigcode/self-oss-instruct-sc2-concepts |
import pickle
def load_goal_set(goal_file_path):
"""
Utility method to load the user goals
# Arguments:
- goal_file_path: the path to the user goals file
"""
# Read all goals
all_goal_set = pickle.load(open(goal_file_path, 'rb'))
# Initialize and create the list of all... | bigcode/self-oss-instruct-sc2-concepts |
def rec_mergeSort(array):
""" Perform merge sort by recursively splitting array into
halves until all the values are separated
then do a piece wise comparason to fill the array in order
"""
# check if array is none
if len(array) > 1:
# find mid index of list
mid = len(array) // 2... | bigcode/self-oss-instruct-sc2-concepts |
def is_line_continuation(line):
"""Determine whether L{line} has a line continuation marker.
.properties files can be terminated with a backslash (\\) indicating
that the 'value' continues on the next line. Continuation is only
valid if there are an odd number of backslashses (an even number
woul... | bigcode/self-oss-instruct-sc2-concepts |
def get_skip_initial_samples_min(post_proc_args):
""" Function iterates over a list of arguments of the form
["plot_all_individual_cdfs", "visualise_traceworkload", "skipmins_3"]
searches for "skipmins_3" and returns 3 in this case.
This parameter indicates how many minutes to skip from the ycsb results... | bigcode/self-oss-instruct-sc2-concepts |
def duration_to_string(value):
"""Converts the given timedelta into an appropriate ISO-8601 duration format for JSON. Only handles positive
durations correctly. Fractional seconds are rounded.
:param value: The timedelta to convert
:type value: :class:`datetime.timedelta`
:returns: The ISO-8601 dur... | bigcode/self-oss-instruct-sc2-concepts |
def lookup_prev_stage_start(stage_boundaries, t):
"""
Returns the previous stage start timestamp from a list/set of stage
boundaries and current time.
"""
return max([0] + [x for x in stage_boundaries if x <= t]) | bigcode/self-oss-instruct-sc2-concepts |
import logging
def get_repo_path(ont_obj):
"""
Extract the repository path for the given object
"""
repo_path = None
if 'repository' in ont_obj:
repo_path = ont_obj['repository']
elif 'tracker' in ont_obj:
tracker = ont_obj['tracker']
if tracker is not None and 'github' in tracker:
repo_... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def sentence_emb(inp_token_embeddings, n=4):
"""
Adds the last n layers of each token and stacks all the input token representations except the first and last ones.
It considers that the first and last tokens are special BERT tokens ([CLS] and [SEP]) and it drops them within the
function
... | bigcode/self-oss-instruct-sc2-concepts |
import struct
def unpack_int(string):
"""Read an n-byte big-endian integer from a byte string."""
(ret,) = struct.unpack_from('>I', b'\x00' * (4 - len(string)) + string)
return ret | bigcode/self-oss-instruct-sc2-concepts |
def lookup(stmt, embeddings, dictionary):
"""
Look up a statement's embedded vector in the embedding matrix
:param stmt: statement to be looked up (string)
:param embeddings: embedding matrix
:param dictionary: [keys=statement, values==statement index]
:return: embedded vector
"""
return... | bigcode/self-oss-instruct-sc2-concepts |
def search_entities(raw_text_string, search):
"""Searches for known entities in a string.
Helper function for construct_entity_conet(). Iterates over a list
of entities and looks to see if they are present in a given text
string. If they are, then it will append the entity to a list for
each te... | bigcode/self-oss-instruct-sc2-concepts |
def int_list_to_string(intli, sep=''):
"""整数列表转字符串
:param intli:
:param sep:
:return:
>>> int_list_to_string([1,2])
'\\x01\\x02'
"""
return sep.join([chr(n) for n in intli]) | bigcode/self-oss-instruct-sc2-concepts |
def sources_and_sinks(
data,
enforce_earliest_start=False
):
"""
Calculates all sources and sinks in a given dataset.
:param list data: a list of :obj:`decitala.search.Extraction` objects.
:param bool enforce_earliest_start: whether to require that all sources begin at the earliest
detected onset.
... | bigcode/self-oss-instruct-sc2-concepts |
def underscore_to_camelcase(s):
"""
Convert lowercase_with_underscore names to CamelCase.
"""
return ''.join(x.capitalize() or '_' for x in s.split('_')) | bigcode/self-oss-instruct-sc2-concepts |
def pixel_wise_boundary_precision_recall(pred, gt):
"""Evaluate voxel prediction accuracy against a ground truth.
Parameters
----------
pred : np.ndarray of int or bool, arbitrary shape
The voxel-wise discrete prediction. 1 for boundary, 0 for non-boundary.
gt : np.ndarray of int or bool, s... | bigcode/self-oss-instruct-sc2-concepts |
import itertools
def flatten(list_, gen=False):
""" Flatten a list. """
if gen:
return itertools.chain(*list_)
else:
return list(flatten(list_=list_, gen=True)) | bigcode/self-oss-instruct-sc2-concepts |
def JsBoolString(bool_value):
"""Write boolean value as javascript boolean."""
if bool_value:
return "true"
else:
return "false" | bigcode/self-oss-instruct-sc2-concepts |
def split_tracks(midfile):
"""Break file into different tracks and store them separately
:param midfile: MidiFile object
:return: meta messages, instrument messages
"""
meta_messages = []
instrument_messages = []
for i, track in enumerate(midfile.tracks):
temp_meta_messages = []
... | bigcode/self-oss-instruct-sc2-concepts |
import requests
def get_node(name, api_url, headers, validate_certs=True):
"""Returns a dict containing API results for the node if found.
Returns None if not just one node is found
"""
url = "{}/v3/nodes?name={}".format(api_url, name)
node_search = requests.get(url, headers=headers, verify=valid... | bigcode/self-oss-instruct-sc2-concepts |
def get_max_operand_size(operands):
"""
Given the list of named tuples containing the operand value and bit width, determine the largest bit width.
:param operands: list of Operand objects
:return: largest operand width
"""
return max(operand.width for operand in operands) | bigcode/self-oss-instruct-sc2-concepts |
def _read_file_data(filepath):
"""Read file data.
:param filepath: The file path.
:return: The file contents.
"""
data = open(filepath, 'rb').read()
return data | bigcode/self-oss-instruct-sc2-concepts |
from typing import Optional
from typing import Dict
import json
def load_result_file(eval_file) -> Optional[Dict]:
"""Loads the results data from a submitted file.
If the file cannot be read, returns None.
"""
try:
with open(eval_file, 'r') as f:
result = json.load(f)
... | bigcode/self-oss-instruct-sc2-concepts |
def NSE(y_pred, y_true):
"""
Calculate the Nash-Sutcliffe efficiency coefficient.
"""
return 1 - sum((y_pred - y_true) ** 2) / sum((y_true - y_true.mean()) ** 2) | bigcode/self-oss-instruct-sc2-concepts |
def sort_params(model, params):
"""Sort parameters to be consistent with the model's parameter order"""
return [p for p in model.parameters if p in params] | bigcode/self-oss-instruct-sc2-concepts |
def check_args(args):
"""See if we got our minimal set of valid arguments."""
ok = True
message = ""
if not args.output_root :
ok = False
message += "Didn't get directory for output (--output-root) "
return([ok,message]) | bigcode/self-oss-instruct-sc2-concepts |
def unflatten1(flat_list, reverse_list):
"""Rebuilds unflat list from invertible_flatten1
Args:
flat_list (list): the flattened list
reverse_list (list): the list which undoes flattenting
Returns:
unflat_list2: original nested list
SeeAlso:
invertible_flatten1
... | bigcode/self-oss-instruct-sc2-concepts |
import zipfile
def zipFileIsGood(filePath):
"""
Function to test if a ZIP file is good or bad
@param filePath the zip file to be tested
@return True if the ZIP file is good. False otherwise.
"""
ret = True
try:
the_zip_file = zipfile.ZipFile(filePath)
badFile ... | bigcode/self-oss-instruct-sc2-concepts |
def qt4_to_mpl_color(color):
"""
Convert a QColor object into a string that matplotlib understands
Note: This ignores opacity
:param color: QColor instance
*Returns*
A hex string describing that color
"""
hexid = color.name()
return str(hexid) | bigcode/self-oss-instruct-sc2-concepts |
def public(fun, scope=None):
"""
Functions that allow any client access, including those that haven't logged
in should be wrapped in this decorator.
:param fun: A REST endpoint.
:type fun: callable
:param scope: The scope or list of scopes required for this token.
:type scope: str or list o... | bigcode/self-oss-instruct-sc2-concepts |
def check_key(request):
"""
Check to see if we already have an access_key stored,
if we do then we have already gone through
OAuth. If not then we haven't and we probably need to.
"""
try:
access_key = request.session.get('oauth_token', None)
if not access_key:
return... | bigcode/self-oss-instruct-sc2-concepts |
def divide_separate_words(X):
"""
As part of processing, some words obviously need to be separated.
:param X: a data matrix: a list wrapping a list of strings, with each sublist being a sentence.
:return:
>>> divide_separate_words([['ita vero'], ['quid', 'est', 'veritas']])
[['ita', 'vero'], ['q... | bigcode/self-oss-instruct-sc2-concepts |
def resize(image, size, resize_image_pl, resize_shape_pl, resize_op, session):
"""
Performs resizing of image.
:param image: Image to resize.
:param size: Size of resized image.
:param resize_image_pl: Resize operation input tensor.
:param resize_shape_pl: Resize operation shape input t... | bigcode/self-oss-instruct-sc2-concepts |
def ilcode(msg: str):
"""Format to inline markdown code"""
return f'`{msg}`' | bigcode/self-oss-instruct-sc2-concepts |
def opaque_legend(ax, fontsize=None, handler_map=None):
"""
Calls legend, and sets all the legend colors opacity to 100%.
Returns the legend handle.
"""
leg = ax.legend(fontsize=fontsize, handler_map=handler_map)
for lh in leg.legendHandles:
fc_arr = lh.get_fc().copy()
fc_arr[:, ... | bigcode/self-oss-instruct-sc2-concepts |
def _requirement_to_str_lowercase_name(requirement):
"""
Formats a packaging.requirements.Requirement with a lowercase name.
This is simply a copy of
https://github.com/pypa/packaging/blob/16.8/packaging/requirements.py#L109-L124
modified to lowercase the dependency name.
Previously, we were i... | bigcode/self-oss-instruct-sc2-concepts |
import re
def to_snake_case(value: str) -> str:
"""
Convert camel case string to snake case
:param value: string
:return: string
"""
first_underscore = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', value)
return re.sub('([a-z0-9])([A-Z])', r'\1_\2', first_underscore).lower() | bigcode/self-oss-instruct-sc2-concepts |
def alnum(string, alt='_', trim=False, single=False):
"""Replace non alpha numeric characters with *alt*. If *trim* is **True**
remove preceding and trailing *arg* characters. If *single* is **True**,
contain only a single joining *alt* character. """
result = ''
multi = not bool(single)
prev... | bigcode/self-oss-instruct-sc2-concepts |
def is_singleline_comment_start(code, idx=0):
"""Position in string starts a one-line comment."""
return idx >= 0 and idx+2 <= len(code) and code[idx:idx+2] == '//' | bigcode/self-oss-instruct-sc2-concepts |
def unique(elements):
"""
Removes duplicate elements from a list of elements.
"""
return list(set(elements)) | bigcode/self-oss-instruct-sc2-concepts |
def get_route_policy(
self,
ne_id: str,
cached: bool,
) -> dict:
"""Get route policy configurations from Edge Connect appliance
.. list-table::
:header-rows: 1
* - Swagger Section
- Method
- Endpoint
* - routePolicy
- GET
- GET /route... | bigcode/self-oss-instruct-sc2-concepts |
def change_categorical_value(df, new_name, old_values, col):
"""
replace categorical values in `old_values` with `new_name`
in given `col` of `df`
Parameters
----------
df: pandas.DataFrame
new_name: STR
old_values: LIST
col: STR
Returns
-------
DataFrame
... | bigcode/self-oss-instruct-sc2-concepts |
def insert(s, c, pos):
"""
Returns the string s with character c inserted into position pos.
c can also be a string. If the position given is 0, c will be placed
at the beginning of the string. If the position given is len(s), c
will be placed at the end of the string. If pos is anything beyond thes... | bigcode/self-oss-instruct-sc2-concepts |
import torch
from typing import Union
def first_element(x: torch.Tensor, element: Union[int, float], dim: int = 1) -> torch.Tensor:
"""
Return indices of first occurence of element in x. If not found, return length of x along dim.
Based on https://discuss.pytorch.org/t/first-nonzero-index/24769/9
Ex... | bigcode/self-oss-instruct-sc2-concepts |
import re
def check_legitimate_ver(version):
"""
This function check if the version is legitimate, only digits and dot.
:param version: str
:return: boolean
"""
return re.match("^[0-9.]+$", version) | bigcode/self-oss-instruct-sc2-concepts |
def insertion_sort(array):
"""
Insertion Sort
Complexity: O(N^2)
"""
array_len = len(array)
for k in range(array_len):
temp = array[k]
i = k
while i > 0 and temp < array[i-1]:
array[i] = array[i-1]
i -= 1
array[i] = temp
return array | bigcode/self-oss-instruct-sc2-concepts |
from typing import Tuple
def find_padding_for_stride(
image_height: int, image_width: int, max_stride: int
) -> Tuple[int, int]:
"""Compute padding required to ensure image is divisible by a stride.
This function is useful for determining how to pad images such that they will not
have issues with div... | bigcode/self-oss-instruct-sc2-concepts |
def calcBounds(array):
"""Calculate the bounding rectangle of a 2D points array.
Args:
array: A sequence of 2D tuples.
Returns:
A four-item tuple representing the bounding rectangle ``(xMin, yMin, xMax, yMax)``.
"""
if len(array) == 0:
return 0, 0, 0, 0
xs = [x for x, y... | bigcode/self-oss-instruct-sc2-concepts |
def set_title(title):
""" print title in a square box
To enhance the readability of the tests, this function prints in the
terminal teh string title in a square box.
Args:
title (str): the string
"""
space = " "
title = space + title + space
h_line = '+'
for character in... | bigcode/self-oss-instruct-sc2-concepts |
def _get_enz_states(er_mech: str) -> list:
"""
Given a string with the enzyme mechanism written as a sequence of elementary reactions produces a list with the
enzyme state numbers and metabolites that bind/unbind to the respective enzyme states.
Args:
er_mech: string with elementary reactions t... | bigcode/self-oss-instruct-sc2-concepts |
def parse_stage_config(stage_cfg):
"""Parse config of STPP for three stages.
Args:
stage_cfg (int | tuple[int]):
Config of structured temporal pyramid pooling.
Returns:
tuple[tuple[int], int]:
Config of structured temporal pyramid pooling and
total numbe... | bigcode/self-oss-instruct-sc2-concepts |
def redis_update_load_data_button(n):
"""
Let the user load the DRF data once they have chosen an input directory
"""
if n < 1: return True
return False | bigcode/self-oss-instruct-sc2-concepts |
import pathlib
def get_config_directory() -> pathlib.Path:
"""
Get the path to the config directory based off its location to this file. Up two directories, then into config
:return: Path pointing to the config directory
"""
return pathlib.Path(__file__).absolute().parent.parent.joinpath("config... | bigcode/self-oss-instruct-sc2-concepts |
def egcd(a, b):
"""extended GCD
returns: (s, t, gcd) as a*s + b*t == gcd
>>> s, t, gcd = egcd(a, b)
>>> assert a % gcd == 0 and b % gcd == 0
>>> assert a * s + b * t == gcd
"""
s0, s1, t0, t1 = 1, 0, 0, 1
while b > 0:
q, r = divmod(a, b)
a, b = b, r
s0, s1, t0, t1... | bigcode/self-oss-instruct-sc2-concepts |
def english_to_persian_number(number):
"""
converts a number from English alphabet to Persian alphabet. It is used because some students use Persian alphabet
in their student number and for each student number, we must check both English and Persian alphabet.
:param number: int or str
Number in... | bigcode/self-oss-instruct-sc2-concepts |
def _GetPackageName(module_name):
"""Returns package name for given module name."""
last_dot_idx = module_name.rfind('.')
if last_dot_idx > 0:
return module_name[:last_dot_idx]
return '' | bigcode/self-oss-instruct-sc2-concepts |
def nldpost(self, label="", key="", fileid="", prefix="", **kwargs):
"""Gets element component information from nonlinear diagnostic files.
APDL Command: NLDPOST
Parameters
----------
label
Specifies the type of command operation:
EFLG - Element flag for nonlinear diagnostics.
... | bigcode/self-oss-instruct-sc2-concepts |
def recursive_min(nxs):
"""
Find the maximum in a recursive structure of lists
within other lists.
Precondition: No lists or sublists are empty.
"""
smallest = None
first_time = True
for e in nxs:
if type(e) == type([]):
val = recursive_min(e)
else:
... | bigcode/self-oss-instruct-sc2-concepts |
import textwrap
def public_doc(name: str, url: str) -> str:
"""Generate public module gallery docs from template."""
summary = f'This example was generated from `{name} source <{url}>`_'
summary = '\n'.join(textwrap.wrap(summary, width=79))
return f""".. _gallery-{name}:
{name}
{'=' * len(name)}
{sum... | bigcode/self-oss-instruct-sc2-concepts |
def _format_list(param_name, list1, datadict, **kwargs):
"""Concatenate and format list items.
This is used to prepare substitutions in user-supplied args to the
various test invocations (ie: the location of flash).
Args:
@param param_name: The name of the item in `datadict`.
@param lis... | bigcode/self-oss-instruct-sc2-concepts |
import requests
from bs4 import BeautifulSoup
def make_request(url):
"""
Make the request and return a soup obj
:param url: the subito.it url
:return: a bs4 obj
"""
http_response = requests.get(url).text
return BeautifulSoup(http_response, 'html.parser') | 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.