seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
def getCharacterFromGame(gtitle: str) -> str:
"""Return a query to get characters with lower Ryu Number to a game.
The query will retrieve the name and Ryu Number of a character whose Ryu
Number is exactly one less than the Ryu Number of the game whose title
is passed. This is used primarily for p... | bigcode/self-oss-instruct-sc2-concepts |
def is_if(t):
"""Whether t is of the form if P then x else y."""
return t.is_comb("IF", 3) | bigcode/self-oss-instruct-sc2-concepts |
def get_volume(module, system):
"""Return Volume or None"""
try:
try:
volume = system.volumes.get(name=module.params['name'])
except KeyError:
volume = system.volumes.get(name=module.params['volume'])
return volume
except Exception:
return None | bigcode/self-oss-instruct-sc2-concepts |
def mean_of_columns(mat):
"""Returns 1-row matrix representing means of
corresponding columns
"""
return mat.mean(axis=0) | bigcode/self-oss-instruct-sc2-concepts |
import logging
def collect_data(**kwargs):
"""
Ideally, a function that defines how data should be collected
for training and prediction.
In the real world, of course, there are often differences in data
sources between training (data warehouse) and prediction (production
application databas... | bigcode/self-oss-instruct-sc2-concepts |
def normalize_response(response):
""" Transform response so that 'off' == 'away' """
if response == 'away':
return 'off'
else:
return response | bigcode/self-oss-instruct-sc2-concepts |
def sec2ts(time_s):
""" Convert time in seconds to timestamp """
return int(time_s * 1e9) | bigcode/self-oss-instruct-sc2-concepts |
import re
def find_cites(f):
"""Return keys to cited papers.
"""
with open(f) as fp:
lst = re.findall(r"{{(.+?)}}", fp.read())
refs = []
for l in lst:
if "site.data.refs" in l:
refs.append(l.split(".")[3])
return sorted(set(refs)) | bigcode/self-oss-instruct-sc2-concepts |
def mag(*args):
""" Magnitude of any number of axes """
n = len(args)
return (sum([abs(arg)**2 for arg in args]))**(1/2) | bigcode/self-oss-instruct-sc2-concepts |
def probe_id(subscription_id, resource_group_name, load_balancer_name, name):
"""Generate the id for a probe"""
return '/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Network/loadBalancers/{}/probes/{}'.format(
subscription_id,
resource_group_name,
load_balancer_name,
na... | bigcode/self-oss-instruct-sc2-concepts |
def search_by_sware_hware(nodes: list, option: int) -> dict:
"""
Search by software/hardware.
Return all unique entries in ``nodes`` list at ``option`` index as
keys and all hostnameswhich contains the entry in list as value.
:param nodes: list of nodes.
:param option: Index in the nodes list(... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Iterable
from typing import List
import string
def quote_args(args: Iterable[str]) -> List[str]:
"""Quote the arguments which contain whitespaces"""
r = []
for arg in args:
if any(map(lambda c: c in string.whitespace, arg)):
r.append(f'"{arg}"')
else:
... | bigcode/self-oss-instruct-sc2-concepts |
import hashlib
def get_file_md5(path):
"""
Retrieves the md5sum of a file's contents.
Args:
path: string path of the file to hash.
Returns:
string md5sum hash.
"""
hash_md5 = hashlib.md5()
with open(path, 'rb') as in_file:
hash_md5.update(in_file.read())
ret... | bigcode/self-oss-instruct-sc2-concepts |
def finite_diff(expression, variable, increment=1):
"""
Takes as input a polynomial expression and the variable used to construct
it and returns the difference between function's value when the input is
incremented to 1 and the original function value. If you want an increment
other than one supply ... | bigcode/self-oss-instruct-sc2-concepts |
def parse_file(file_path):
"""Parse file with lines: retailer url
Args:
file_path: The path to the url file
Returns:
dict: {'retailer1': 'url1', 'retailer2': 'url2'...}
"""
file = open(file_path)
retailer_dict = {}
for line in file:
try:
words_in_lin... | bigcode/self-oss-instruct-sc2-concepts |
def _sar_range(dicoms):
"""Find the minimum and maximum SAR values in a list of DICOM headers."""
sars = set([float(d.SAR) for d in dicoms])
return str(min(sars)), str(max(sars)) | bigcode/self-oss-instruct-sc2-concepts |
def get_from_list(list, name):
""" searches through list of objects with a .name attribute or surface_shaders and returns the object if it exists or None if not """
for item in list:
if item.name == name:
return item
return None | bigcode/self-oss-instruct-sc2-concepts |
def format_size(nb_bytes):
"""
Format a size expressed in bytes as a string
Parameters
----------
nb_bytes : int
the number of bytes
Return
------
formated : str
the given number of bytes fromated
Example
-------
>>> format_size(100)
'100.0 bytes'
>... | bigcode/self-oss-instruct-sc2-concepts |
def get_method_color(method):
"""
Return color given the method name.
"""
color = {}
color['Random'] = 'blue'
color['Target'] = 'cyan'
color['Minority'] = 'cyan'
color['Loss'] = 'yellow'
color['BoostIn'] = 'orange'
color['LeafInfSP'] = 'brown'
color['TREX'] = 'green'
colo... | bigcode/self-oss-instruct-sc2-concepts |
import gzip
import bz2
import lzma
def fopen(filename, mode=None):
"""GZ/BZ2/XZ-aware file opening function."""
# NOTE: Mode is not used but kept for not breaking iterators.
if filename.endswith('.gz'):
return gzip.open(filename, 'rt')
elif filename.endswith('.bz2'):
return bz2.open(fi... | bigcode/self-oss-instruct-sc2-concepts |
def to_celsius(fahrenheit):
"""
Accepts degrees Fahrenheit (fahrenheit argument)
Returns degrees Celsius
"""
celsius = (fahrenheit - 32) * 5/9
return celsius | bigcode/self-oss-instruct-sc2-concepts |
def get_build_info(input_file):
"""Get build information in UCSC notation, if possible."""
build_dict = {
"hg38": ["GRCh38"],
"hg19": ["GRCh37", "b37"],
"mm10": ["GRCm38"],
"mm9": ["MGSCv37"],
"rn6": ["Rnor_6.0"],
}
with open(input_file, "r") as tfile:
bu... | bigcode/self-oss-instruct-sc2-concepts |
def is_even(number: int) -> bool:
"""
This method will find if the number passed is even or not
:param number : a number
:return: True if even False otherwise
"""
if number <= 0:
return False
return number % 2 == 0 | bigcode/self-oss-instruct-sc2-concepts |
def _parse_ref_dict(reference_dict, strict=True):
"""Parse the referenced dict into a tuple (TYPE, ID).
The ``strict`` parameter controls if the number of keys in the
reference dict is checked strictly or not.
"""
keys = list(reference_dict.keys())
if strict and len(keys) != 1:
raise V... | bigcode/self-oss-instruct-sc2-concepts |
def yLP2DP(lpY, lptLT, lPix = 1.0):
"""Convert logical coordinates into device coordinates
lpY - y logical coordinate
lptLT - logical coordinates of left top screen corner
lPix - zoom value, number of logical points inside one device point (aka pixel)
return coordinate in device c... | bigcode/self-oss-instruct-sc2-concepts |
def dot_dir_dir(direction1, direction2):
""" Evaluates the dot product of a direction with another direction.
PARAMETERS
----------
direction{1, 2}: Point
RETURN
------
: float
"""
return sum((dir_coord1*dir_coord2 for dir_coord1, dir_coord2 in zip(direction1.coords, direct... | bigcode/self-oss-instruct-sc2-concepts |
def lowercase_words(text):
"""
Method used to transform text to lowercase"
Parameters:
-----------------
text (string): Text to clean
Returns:
-----------------
text (string): Text after transforming to lowercase.
"""
text = text.lower()
return text | bigcode/self-oss-instruct-sc2-concepts |
def remove_zeros(r, M):
"""
image processor to remove zero
:param r: Source image measure
:param M: Cost matrix
:return: Processed r and M with zeros removed
"""
M = M[r > 0]
r = r[r > 0]
return r, M | bigcode/self-oss-instruct-sc2-concepts |
def cycle_slice(sliceable, start, end):
"""Given a list, return right hand cycle direction slice from start to end.
Usage::
>>> array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> cycle_slice(array, 4, 7) # from array[4] to array[7]
[4, 5, 6, 7]
>>> cycle_slice(array, 8, 2) # from arra... | bigcode/self-oss-instruct-sc2-concepts |
import importlib
def make_checker(checker_cls, tmp_dir, **kwargs):
"""Returns a checker object.
Parameters
-----------
checker_cls : str
the Checker class absolute path name.
tmp_dir : string
directory to save temporary files in.
kwargs : dict
keyword arguments needed ... | bigcode/self-oss-instruct-sc2-concepts |
def index_by_iterable(obj, iterable):
"""
Index the given object iteratively with values from the given iterable.
:param obj: the object to index.
:param iterable: The iterable to get keys from.
:return: The value resulting after all the indexing.
"""
item = obj
for i in iterable:
... | bigcode/self-oss-instruct-sc2-concepts |
def create_8021Q_vea_cmd(lpar_id, slotnum, port_vlan_id, addl_vlan_ids):
"""
Generate IVM command to create 8021Q virtual ethernet adapter.
:param lpar_id: LPAR id
:param slotnum: virtual adapter slot number
:param port_vlan_id: untagged port vlan id
:param addl_vlan_ids: tagged VLAN id list
... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Sequence
from typing import List
from typing import Set
def expand_ranges(ranges: Sequence[Sequence[int]], inclusive: bool = False) -> List[int]:
"""Expand sequence of range definitions into sorted and deduplicated list of individual values.
A range definition is either a:
* one eleme... | bigcode/self-oss-instruct-sc2-concepts |
def GetJidFromHostLog(host_log_file):
"""Parse the me2me host log to obtain the JID that the host registered.
Args:
host_log_file: path to host-log file that should be parsed for a JID.
Returns:
host_jid: host-JID if found in host-log, else None
"""
host_jid = None
with open(host_log_file, 'r') as... | bigcode/self-oss-instruct-sc2-concepts |
def compose2(f, e):
"""Compose 2 functions"""
return lambda x: f(e(x)) | bigcode/self-oss-instruct-sc2-concepts |
def filtered_tooltip(options, filter):
"""Returns tooltip for the filter icon if the filter matches one of the filter options
"""
for option in options:
if filter == option[1]:
return "Showing only %s"%option[0]
return "" | bigcode/self-oss-instruct-sc2-concepts |
def _valvar(unk, vardict):
"""Determines if an unknown string is a value or a dict variable.
Parameters
----------
unk : float or str
The unknown value, either a float or a dictionary key.
vardict : dict
The dictionary to be searched if unk is not a float.
Returns
-------
... | bigcode/self-oss-instruct-sc2-concepts |
def rectangle(a, b):
""" Return classic logic rect function:
^ ......
| | |
|___|____|___
a b
"""
return lambda x, a=a, b=b: 1. if a <= x <= b else 0. | bigcode/self-oss-instruct-sc2-concepts |
def fnCalculate_Bistatic_RangeRate(speed_light,tau_u1,tau_d1,tau_u2,tau_d2,tc):
"""
Calculate the average range rate. eqn 6.37 in Montenbruck 2000.
tc = length of integration interval, i.e. length of CPI
Created: 04/04/17
"""
range_rate = (speed_light/tc)*(tau_u2+tau_d2-tau_u1-tau_d1); # removed 0.5 factor. 19.0... | bigcode/self-oss-instruct-sc2-concepts |
from typing import OrderedDict
def get_wall_duration(op_names, all_ops, pid_list=(11, 7, 13, 15, 9)):
"""
Calculates wall duration for each op in op_names.
Params:
op_names: list (str), names of ops of interest.
pid_list: list (str), names of pid to include.
all_ops: output of get_all_ops().
... | bigcode/self-oss-instruct-sc2-concepts |
def read_biosids(bdfiles, verbose=False):
"""
REad the biosample ID files.
:param bdfiles: iterable of Files with biosample IDs
:param verbose: more output
:return: a dict of the sample_name and biosample ID
"""
biosids = {}
for fl in bdfiles:
with open(fl, 'r') as f:
... | bigcode/self-oss-instruct-sc2-concepts |
import importlib
def _get_module_attr(module_name, attribute_name):
"""Import a module and get an attribute from it.
Args:
module_name (str): The module name.
attribute_name (str): The attribute name.
Returns:
Any: The attribute.
Raises:
ModuleNotFoundError: The modu... | bigcode/self-oss-instruct-sc2-concepts |
def simple_app(environ, start_response):
"""Simplest possible WSGI application object"""
status = '200 OK'
response_headers = [('Content-type','text/plain')]
start_response(status, response_headers)
return ['Hello world!\n' for i in range(100)] | bigcode/self-oss-instruct-sc2-concepts |
def ozone_ppm(results, temperature=22):
"""
Calculate ppm for given results array with Mol/m3 concentrion
:param results: array of results in Mol/m3
:param temperature: gas measurement temperature in celsius
:return: array of ppm
"""
P = 1e5 # pascal
V = 1 # m3
R = 8.314472 # JK-... | bigcode/self-oss-instruct-sc2-concepts |
def css_class(field):
"""
Returns widgets class name in lowercase
"""
return field.field.widget.__class__.__name__.lower() | bigcode/self-oss-instruct-sc2-concepts |
from pathlib import Path
def get_file(filepath):
"""Return the content of a file in the test_files directory."""
full_path = Path(__file__).parent / 'test_files' / filepath
with open(full_path, 'rb') as file:
return file.read() | bigcode/self-oss-instruct-sc2-concepts |
import ipaddress
def calc_prefix(arg, addresses):
"""Calculates the prefix for the list of addresses.
Creates the prefix from arg if one is supplied, otherwise computes the prefix
from the addresses.
"""
# This can throw an exception if they supplied an invalid netmask.
if arg:
... | bigcode/self-oss-instruct-sc2-concepts |
def color_hex_to_dec_tuple(color):
"""Converts a color from hexadecimal to decimal tuple, color can be in
the following formats: 3-digit RGB, 4-digit ARGB, 6-digit RGB and
8-digit ARGB.
"""
assert len(color) in [3, 4, 6, 8]
if len(color) in [3, 4]:
color = "".join([c*2 for c in color])
... | bigcode/self-oss-instruct-sc2-concepts |
def msg(m, ctx):
"""Check if the message is in the same channel, and is by the same author."""
return m.channel == ctx.channel and m.author == ctx.author | bigcode/self-oss-instruct-sc2-concepts |
import torch
def all_or_none_accuracy(preds, targets, dim=-1):
""" Gets the accuracy of the predicted sequence.
:param preds: model predictions
:param targets: the true targets
:param dim: dimension to operate over
:returns: scalar value for all-or-none accuracy
:rtype: float32
"""
p... | bigcode/self-oss-instruct-sc2-concepts |
def get_ee_points(offsets, ee_pos, ee_rot):
"""
Helper method for computing the end effector points given a
position, rotation matrix, and offsets for each of the ee points.
Args:
offsets: N x 3 array where N is the number of points.
ee_pos: 1 x 3 array of the end effector position.
... | bigcode/self-oss-instruct-sc2-concepts |
import math
def get_observation_data(observation, t):
"""
Get observation data at t.
"""
vars = ['Foil', 'Fw', 'Fs', 'Fa', 'Fb', 'Fc', 'Fh', 'Fg', 'Wt', 'discharge', 'DO2', 'T', 'O2', 'pressure']
# convert to pH from H+ concentration
pH = observation.pH.y[t]
pH = -math.log(pH) / math.log(1... | bigcode/self-oss-instruct-sc2-concepts |
def num_cooperators(population):
"""Get the number of cooperators in the population"""
return population['Coop'].sum() | bigcode/self-oss-instruct-sc2-concepts |
def int_or_zero(s):
"""
>>> int_or_zero('')
0
>>> int_or_zero('10')
10
"""
return 0 if not s else int(s) | bigcode/self-oss-instruct-sc2-concepts |
def split_company_name_notes(name):
"""Return two strings, the first representing the company name,
and the other representing the (optional) notes."""
name = name.strip()
notes = u''
if name.endswith(')'):
fpidx = name.find('(')
if fpidx != -1:
notes = name[fpidx:]
... | bigcode/self-oss-instruct-sc2-concepts |
def test_asyncio_request_response(connection, receiver):
"""
Test request/response messaging pattern with coroutine callbacks
"""
async def endpoint_handler(message):
return message.payload + "-pong"
connection.register_async_endpoint(endpoint_handler, "test.asyncio.request")
connectio... | bigcode/self-oss-instruct-sc2-concepts |
import random
def stat_check(stat1, stat2):
"""
Checks if stat1 wins over stat2 in competitive stat check.
"""
roll1 = random.randrange(stat1)
roll2 = random.randrange(stat2)
return roll1 >= roll2 | bigcode/self-oss-instruct-sc2-concepts |
def artists_to_mpd_format(artists):
"""
Format track artists for output to MPD client.
:param artists: the artists
:type track: array of :class:`mopidy.models.Artist`
:rtype: string
"""
artists = list(artists)
artists.sort(key=lambda a: a.name)
return ', '.join([a.name for a in arti... | bigcode/self-oss-instruct-sc2-concepts |
def flatten_substitution_choices(subs_choices):
"""
For a given dict {expr: (expr1, expr2)} returns a list of all possible substitution arising from choosing to subs
expr by expr1 or expr2.
"""
subs_choices = subs_choices.copy()
if not subs_choices:
return [{}]
result = []
expr ... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Any
def cmp(a: Any, b: Any) -> int:
"""
Restores the useful `cmp` function previously in Python 2.
- Implemented according to [What's New in Python 3.0](https://docs.python.org/3.0/whatsnew/3.0.html#ordering-comparisons).
Args:
a: An object.
b: An object.
Retu... | bigcode/self-oss-instruct-sc2-concepts |
def forbidden_view(message, request):
"""Get JSON response for a 403 status code."""
request.response.status = 403
return {'message': str(message), 'status': 403} | bigcode/self-oss-instruct-sc2-concepts |
def normal_diffusion(times, diffusion_coefficient, dimensions=2):
"""Models the relationship between mean squared displacement and time during a normal (Brownian) diffusion process.
During normal diffusion the mean squared displacement increases linearly
with time according to the Einstein relation.
""... | bigcode/self-oss-instruct-sc2-concepts |
import re
def check_mac(mac_address, capital_letters=True):
"""
Check mac address is valid.
Either format of 52:54:00:AE:E3:41, or
52-54-00-AE-E3-41
"""
if capital_letters:
regex = r'^([0-9A-F]{2}[:]){5}([0-9A-F]{2})$'
else:
regex = r'^([0-9a-f]{2}[:]){5}([0-9a-f]{2})$'
... | bigcode/self-oss-instruct-sc2-concepts |
def electrolyte_diffusivity_Valoen2005(c_e, T):
"""
Diffusivity of LiPF6 in EC:DMC as a function of ion concentration, from [1] (eqn 14)
References
----------
.. [1] Valøen, Lars Ole, and Jan N. Reimers. "Transport properties of LiPF6-based
Li-ion battery electrolytes." Journal of The Electroch... | bigcode/self-oss-instruct-sc2-concepts |
def pascal_voc_palette(num_cls=None):
"""
Generates the PASCAL Visual Object Classes (PASCAL VOC) data-set color palette.
Data-Set URL:
http://host.robots.ox.ac.uk/pascal/VOC/ .
Original source taken from:
https://gluon-cv.mxnet.io/_modules/gluoncv/utils/viz/segmentation.html .
`num_cls`: t... | bigcode/self-oss-instruct-sc2-concepts |
def R(units):
"""Universal molar gas constant, R
Parameters
----------
units : str
Units for R. Supported units
============= =============================================== ============
Unit Description Value
... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def compute_pdist_matrix(batch, p=2.0):
"""
Computes the matrix of pairwise distances w.r.t. p-norm
:param batch: torch.Tensor, input vectors
:param p: float, norm parameter, such that ||x||p = (sum_i |x_i|^p)^(1/p)
:return: torch.Tensor, matrix A such that A_ij = ||batch[i] - bat... | bigcode/self-oss-instruct-sc2-concepts |
import socket
import struct
def get_ip_mreqn_struct(multicast_address, interface_address, interface_name):
"""
Set up a mreqn struct to define the interface we want to bind to
"""
# See https://github.com/torvalds/linux/blob/866ba84ea30f94838251f74becf3cfe3c2d5c0f9/include/uapi/linux/in.h#L168
ip_... | bigcode/self-oss-instruct-sc2-concepts |
def _get_id(mf, url=None):
"""
get the uid of the mf object
Args:
mf: python dictionary of some microformats object
url: optional URL to use in case no uid or url in mf
Return: string containing the id or None
"""
props = mf['properties']
if 'uid' in props:
return props['uid'][0]
elif 'url' in props:... | bigcode/self-oss-instruct-sc2-concepts |
def get_worksheet_names(workbook):
"""
Gets the names of all the worksheets of the current workbook.
:param workbook: Current workbook to manipulate.
:return: A list of all the worksheets' names of the current workbook.
"""
return workbook.sheetnames | bigcode/self-oss-instruct-sc2-concepts |
import time
def is_task_successful(task, retry=10 , interval=5):
"""
Method to check the task state.
:param task: VMware task.
:param retry(int): Number of Retries.
:param interval(int): Interval between each retry.
:return: bool(
"""
while retry > 0:
task_status = str(task.inf... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def binary_acc(y_pred, y):
"""Calculates model accuracy
Arguments:
y_pred {torch.Tensor} -- Output of model between 0 and 1
y {torch.Tensor} -- labels/target values
Returns:
[torch.Tensor] -- accuracy
"""
y_pred_tag = torch.round(y_pred)
correct_r... | bigcode/self-oss-instruct-sc2-concepts |
def cvode_stats_to_dict(path: str) -> dict:
"""
Converts a Delphin integrator_cvode_stats file into a dict.
:param path: path to folder
:return: converted tsv dict
"""
file_obj = open(path + '/integrator_cvode_stats.tsv', 'r')
lines = file_obj.readlines()
file_obj.close()
tsv_dict... | bigcode/self-oss-instruct-sc2-concepts |
def _scale_col_to_target(col, target, metric_func):
"""
Scale a column's values so that in aggregate they match some metric,
for example, mean, median, or sum.
Parameters
----------
col : pandas.Series
target : number
metric_func : callable
Must accept a Series and return a numb... | bigcode/self-oss-instruct-sc2-concepts |
def binlogs_to_backup(cursor, last_binlog=None):
"""
Finds list of binlogs to copy. It will return the binlogs
from the last to the current one (excluding it).
:param cursor: MySQL cursor
:param last_binlog: Name of the last copied binlog.
:return: list of binlogs to backup.
:rtype: list
... | bigcode/self-oss-instruct-sc2-concepts |
def performanceCalculator(count, avg, std, maxv, countref, avgref, stdref, maxvref):
"""
===========================================================================
Performance calculator function
===========================================================================
Calculate performance bas... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def weighted_mean_rule_func(predictions: torch.Tensor,
weights: torch.Tensor, *_) -> torch.Tensor:
"""
Mean the predictions of different classifier outputs with classifier weights.
Args:
predictions: outputs of the base models
weights: a one-dimens... | bigcode/self-oss-instruct-sc2-concepts |
def set_val_if_dict( dct, key, val ):
""" Set the { ... `key`:`val` ... } only if `dct` is a dictionary """
try:
dct[ key ] = val
return True
except (TypeError, KeyError):
return False | bigcode/self-oss-instruct-sc2-concepts |
import torch
from typing import Optional
def weighted_average(
x: torch.Tensor, weights: Optional[torch.Tensor] = None, dim=None
) -> torch.Tensor:
"""
Computes the weighted average of a given tensor across a given dim, masking
values associated with weight zero,
meaning instead of `nan * 0 = nan`... | bigcode/self-oss-instruct-sc2-concepts |
def check_sudoku(sudoku):
""" Funktion zur Überprüfung einer Sudoku-Lösung auf Korrektheit.
Als Eingabe an die Funktion wird die Sudoku-Lösung in Form einer
Liste von Listen übergeben. Die Funktion gibt als Ergebnis
einen Wahrheitswert zurück. """
# Prüfe Zeilen
# Gehe jede Zeile durch
for ... | bigcode/self-oss-instruct-sc2-concepts |
import re
def _is_pull_request_base_branch_match(pull_request: dict, base_branch: str) -> bool:
"""
Determine if the pull request represents a notification for a base branch we should consider.
:param pull_request: Pull request section of payload to examine
:type: :class:`~dict`
:param base_branc... | bigcode/self-oss-instruct-sc2-concepts |
def get_contigous_borders(indices):
"""
helper function to derive contiguous borders from a list of indices
Parameters
----------
indicies : all indices at which a certain thing occurs
Returns
-------
list of groups when the indices starts and ends (note: last element is t... | bigcode/self-oss-instruct-sc2-concepts |
import math
def hsvToRGB(h, s, v):
"""Convert HSV color space to RGB color space
@param h: Hue
@param s: Saturation
@param v: Value
return (r, g, b)
"""
hi = math.floor(h / 60.0) % 6
f = (h / 60.0) - math.floor(h / 60.0)
p = v * (1.0 - s)
q = v * (1.0 - (f*s))
t = v * (1.0 - ((1.0 - f) * s))
D = {0... | bigcode/self-oss-instruct-sc2-concepts |
def is_too_similar_for_axes(word1, word2):
""" Checks if the words contain each other """
return word1 in word2 or word2 in word1 | bigcode/self-oss-instruct-sc2-concepts |
def dominance(solution_1, solution_2):
"""
Function that analyze solutions dominance.
Parameters
-----------
:param solution_1: Solution
:param solution_2: Solution
Returns
---------
:return int
If solution_1 dominates solution_2 -> return 1
:return -1
If soluti... | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
def _parse_csv(s: str) -> List[str]:
"""Return the values of a csv string.
>>> _parse_csv("a,b,c")
['a', 'b', 'c']
>>> _parse_csv(" a, b ,c ")
['a', 'b', 'c']
>>> _parse_csv(" a,b,c ")
['a', 'b', 'c']
>>> _parse_csv(" a,")
['a']
>>> _parse_csv("a, ")
... | bigcode/self-oss-instruct-sc2-concepts |
def get_antigen_name(qseqid):
"""
Get the antigen name from the BLASTN result query ID.
The last item delimited by | characters is the antigen name for all
antigens (H1, H2, serogroup)
@type qseqid: str
@param qseqid: BLASTN result query ID
@return: antigen name
"""
if qseqid:
... | bigcode/self-oss-instruct-sc2-concepts |
import requests
def get_img_content(img_url):
"""
函数功能:向服务器请求图片数据
参数:
img_url:图片的链接地址
返回:图片的内容,即图片的二进制数据
"""
header2 = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.70 Safari/537.36'
try:
r = requests.get(img_url, headers... | bigcode/self-oss-instruct-sc2-concepts |
def normalize_matrix(transformer, matrix):
"""Normalize count matrix to scale down the impact of very frequent tokens
:param transformer: A Sklearn TfidfTransformer object
:param matrix: An array representing a term document matrix,
output of CountVectorizer.fit_transform
"""
matrix_normalized ... | bigcode/self-oss-instruct-sc2-concepts |
import tempfile
import zipfile
def unpack_zip(zip_ffn):
"""
Unpacks zip file in temp directory
Parameters:
===========
zip_ffn: str
Full filename to zip file
Returns:
========
temp_dir: string
Path to temp directory
"""
#build ... | bigcode/self-oss-instruct-sc2-concepts |
def _colors(strKey):
"""
Function gives access to the RxCS console colors dictionary. The
Function returns a proper console color formating string (ANSI colors)
based on the key given to the function. |br|
Available keys:
'PURPLE'
'BLUE'
'GREEN'
'YELLOW'
'RE... | bigcode/self-oss-instruct-sc2-concepts |
def get_target_name(item):
"""Take a query record, split the name field, and return the
target name."""
return item.file_location.split('/')[-2].split('_')[-1] | bigcode/self-oss-instruct-sc2-concepts |
import re
def split_by_punct(segment):
"""Splits str segment by punctuation, filters our empties and spaces."""
return [s for s in re.split(r'\W+', segment) if s and not s.isspace()] | bigcode/self-oss-instruct-sc2-concepts |
import re
def filename_safe(name: str, lower: bool = False) -> str:
"""
Perform the necessary replacements in <name> to make it filename safe.
Any char that is not a-z, A-Z, 0-9, '_', ' ', or '-' is replaced with '_'. Convert to lowercase, if lower=True.
:param lower: If True, apply str.lower() to res... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Tuple
from typing import Optional
def _parse_key_value_pair(arg: str) -> Tuple[Optional[str], str]:
"""
Parameters
----------
arg : str
Arg in the format of "Value" or "Key=Value"
Returns
-------
key : Optional[str]
If key is not specified, None will be t... | bigcode/self-oss-instruct-sc2-concepts |
def str_to_bool(val: str) -> bool:
"""Converts a string to a boolean based on its value.
:param val: string being converted
:return: boolean value expressed in the string
:raises: ValueError if the string does not contain a value corresponding to a boolean value
"""
if isinstance(val, str):
... | bigcode/self-oss-instruct-sc2-concepts |
import functools
def require(required):
""" Decorator for checking the required values in state.
It checks the required attributes in the passed state and stop when
any of those is missing. """
def decorator(function):
@functools.wraps(function)
def wrapper(*args, **kwargs):
... | bigcode/self-oss-instruct-sc2-concepts |
def GetNestedAttr(content, nested_attr, default=None):
"""Get the (nested) attribuite from content.
Get the (nested) attribute from the content dict.
E.X. content is {key1: {key2: {key3: value3}}, key4: value4}
nested_attr = [key1] gets {key2: value2, {key3: value3}}
nested_attr = [key1, key2] gets {key3: va... | bigcode/self-oss-instruct-sc2-concepts |
import json
def format_json(json_string):
"""Converts a minified JSON str to a prettified JSON str.
Args:
json_string (str): A str representing minified JSON.
Returns:
(str): A str representing prettified JSON.
"""
parsed = json.loads(json_string)
return json.dumps(parsed, in... | bigcode/self-oss-instruct-sc2-concepts |
def wrapped_list(list, which):
"""
Selects an element from a list, wrapping in either direction.
"""
if which < 0:
ix = len(list) + (which % len(list))
else:
ix = which % len(list)
return list[ix] | 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.