seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
def rtf_encode(text):
"""
Convert unicode text to rtf format with substitution of non-ascii
characters. (Based on Martijn Pieters' code.)
"""
return ''.join(['\\u%i?' % (ord(e) if e < u'\u8000' else ord(e) - 65536) if (e > '\x7f' or e < '\x20' or e in u'\\{}') else str(e) for e in text]) | bigcode/self-oss-instruct-sc2-concepts |
from pathlib import Path
def get_project_path(project_name: str) -> Path:
"""Get the assets project path for the given project name (with no ".flxproj").
If you want to open the project, please use open_project() or copy_project() instead,
as they will copy the project to a temporary directory and clean ... | bigcode/self-oss-instruct-sc2-concepts |
def mirror_from(source, attributes, only_getters=True):
"""Decorator (factory) for classes that mirror some attributes from an
instance variable.
:param source: the name of the instance variable to mirror from
:param attributes: list of attribute names to mirror
:param only_getters: if true only ge... | bigcode/self-oss-instruct-sc2-concepts |
def get_netcdf_response(coverage_offering, dataset, crs):
"""Uses a standard xarray function to create a bytes-like data stream for http response"""
dataset.attrs['crs'] = crs
return dataset.to_netcdf() | bigcode/self-oss-instruct-sc2-concepts |
def echo(s):
"""Return the string passed in."""
return "We are echoing: %s" % s | bigcode/self-oss-instruct-sc2-concepts |
import math
def round_up(x, near):
"""
Round x to nearest number e.g. round_up(76, 5) gives 80
Args:
x: Number to round-up
near: Number to which round-up to
Returns:
rounded up number
"""
return int(math.ceil(float(x) / float(near))) * near | bigcode/self-oss-instruct-sc2-concepts |
def cleanFilePaths(file, listOfResults, type=None):
"""
Constructs the data which consists of a dictionary within a dictionary.
The first level has keys that are the data file name, and the second
level contains two keys: saved and read. Within 'saved' and 'read'
are a list that contains the scripts... | bigcode/self-oss-instruct-sc2-concepts |
def qe_at(df, energy):
""" Extracts QE at the specified energy.
"""
return df[df.E >= energy].sort_values(by='E', ascending=True).iloc[0].QE | bigcode/self-oss-instruct-sc2-concepts |
def dot(u1,u2):
""" Dot product of two vectors """
return u1[0]*u2[0] + u1[1]*u2[1] + u1[2]*u2[2] | bigcode/self-oss-instruct-sc2-concepts |
def exists_jpg_extension(files):
"""Checks whether any file in files is a jpg image
Args:
files: List of filenames
Returns:
True if any file is a jpg otherwise False
"""
has_jpg_extension = ['jpg' in fname for fname in files]
return any(has_jpg_extension) | bigcode/self-oss-instruct-sc2-concepts |
import string
def num_to_str(num, b=36, numerals=string.digits + string.ascii_lowercase):
"""
Converts integer num into a string representation on base b
@param b {int} base to use
@param numerals {string} characters used for string representation
@returns {string} string representation of num in ... | bigcode/self-oss-instruct-sc2-concepts |
def UppercaseMutator(current, value):
"""Uppercase the value."""
return current.upper() | bigcode/self-oss-instruct-sc2-concepts |
def seconds_until_start(start_time, current_time):
"""Return the number of seconds until start time"""
difference = start_time - current_time
return difference.seconds | bigcode/self-oss-instruct-sc2-concepts |
def n_subsystems(request):
"""Number of qubits or qumodes."""
return request.param | bigcode/self-oss-instruct-sc2-concepts |
import base64
def img_stream_to_b64str(stream, urlsafe=False):
"""
Convert a byte stream of image file to Base64 encoded string.
:param stream: The byte stream of the file.
:param urlsafe: Trigger using URL-Safe format.
:return: Encoded Base64 string.
"""
if urlsafe:
stream_base64 ... | bigcode/self-oss-instruct-sc2-concepts |
def area(circle):
"""Get area of a circle"""
return circle.get('radius') ** 2 * 3.14159 | bigcode/self-oss-instruct-sc2-concepts |
def get_reference_source(lockin):
"""Get the reference source. Return either internal (1) or external (0).
args:
lockin (pyvisa.resources.gpib.GPIBInstrument): SRS830
returns:
(int): 1 for internal, 0 for external.
"""
return int(lockin.query("fmod?").split("\n")[0]) | bigcode/self-oss-instruct-sc2-concepts |
from datetime import datetime
def get_tag(tag=None):
"""
Simple helper function to create a tag for saving a file if one does not already exist.
This is useful because in some places we don't know whether we will have a tag or not,
but still want to save files.
Parameters
----------
tag ... | bigcode/self-oss-instruct-sc2-concepts |
def array_to_dict(rows, key="openstack_id"):
""" Convert a list of dicts into a dict based on key"""
result = {}
for row in rows:
key_value = row.pop(key)
result[key_value] = row
return result | bigcode/self-oss-instruct-sc2-concepts |
def is_(t, x):
""" Check whether the type of a given x is a given type t.
"""
return type(x) is t | bigcode/self-oss-instruct-sc2-concepts |
import socket
def dnsname(ip):
"""Returns the DNS hostname of the provided IP address if it's in DNS (PTR record)"""
try:
return socket.gethostbyaddr(ip)[0]
except:
return 'null' | bigcode/self-oss-instruct-sc2-concepts |
def first_differences(signal):
"""The mean of the absolute values of the first differences of the raw signal"""
# build the first differences list
first_diff = []
for i in range(0,len(signal)-1):
first_diff.append(abs(signal[i+1]-signal[i]))
fd_sum = sum(first_diff)
delta = float(fd_sum)/(len(signal)-1)
retur... | bigcode/self-oss-instruct-sc2-concepts |
def extract_components_from_flow(flow):
"""Given a versionedFlowSnapshot object, extract out the processors
and create a list of tuples where each tuple is
(component name, component version)"""
extract = lambda p: (p["bundle"]["artifact"], p["bundle"]["version"])
return [ extract(p) for p in flow["... | bigcode/self-oss-instruct-sc2-concepts |
import re
def format(changelog):
"""Clean up changelog formatting"""
changelog = re.sub(r"\n\n+", r"\n\n", changelog)
return re.sub(r"\n\n+$", r"\n", changelog) | bigcode/self-oss-instruct-sc2-concepts |
def my_extract(value, delim=',', index=0):
"""Split a given string and return value at given index position."""
return value.split(delim)[index] | bigcode/self-oss-instruct-sc2-concepts |
def parse_percent(val):
"""Turns values like "97.92%" into 0.9792."""
return float(val.replace('%', '')) / 100 | bigcode/self-oss-instruct-sc2-concepts |
def log_target_types(all_logs=False, **kwargs):
"""
Log targets for log tasks. A log target defines the log types
that will be affected by the operation. For example, when creating
a DeleteLogTask, you can specify which log types are deleted.
:param bool for_alert_event_log: alert events traces... | bigcode/self-oss-instruct-sc2-concepts |
def mblg_to_mw_johnston_96(mag):
"""
Convert magnitude value from Mblg to Mw using Johnston 1996 conversion
equation.
Implements equation as in line 1654 in hazgridXnga2.f
"""
return 1.14 + 0.24 * mag + 0.0933 * mag * mag | bigcode/self-oss-instruct-sc2-concepts |
def interactions(G, nbunch=None, t=None):
"""Return the list of edges present in a given snapshot.
Edges are returned as tuples
in the order (node, neighbor).
Parameters
----------
G : Graph opject
DyNetx graph object
nbunch : ite... | bigcode/self-oss-instruct-sc2-concepts |
def weasyl_sysname(target):
"""Return the Weasyl sysname for use in a URL for a given username."""
return ''.join(i for i in target if i.isalnum()).lower() | bigcode/self-oss-instruct-sc2-concepts |
def set_of_words2vec(vocab_list, input_set):
"""
句子转换为向量,如果字典中有这个词则将该单词置1,否则置0
:param vocab_list: 所有单词集合列表
:param input_set: 输入数据集
:return: 匹配列表[0,1,0,1...],其中 1与0 表示词汇表中的单词是否出现在输入的数据集中
"""
# 创建一个和词汇表等长的向量,并将其元素都设置为0
result = [0] * len(vocab_list)
# 遍历文档中的所有单词,如果出现了词汇表中的单词,则将输出的文档向... | bigcode/self-oss-instruct-sc2-concepts |
def by_date_range(analysis, from_timestamp, to_timestamp):
"""
Filters list of analysis objects with attribute "createdDate".
Returns a new list of analyses objects that were created between from_timestamp and to_timestamp
:param analysis:
:param from_timestamp: unix timestamp (float)
:param to_... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def log_bound_and_scale(scale, bounds):
"""
Scale, de-log, and bound
Args:
scale (torch.tensor): divide input by this value, then take exp
bounds (torch.tensor): tuple, clamp to (bounds[0], bounds[1])
"""
return lambda x: torch.clamp(torch.exp(x / scale), bounds[0]... | bigcode/self-oss-instruct-sc2-concepts |
import struct
import binascii
def make_chunk(chunk_type, chunk_data):
"""Create a raw chunk by composing chunk type and data. It
calculates chunk length and CRC for you.
:arg str chunk_type: PNG chunk type.
:arg bytes chunk_data: PNG chunk data, **excluding chunk length, type, and CRC**.
:rtype: bytes
"""
out... | bigcode/self-oss-instruct-sc2-concepts |
def is_iterable(value):
# noinspection PyUnresolvedReferences
"""
Returns ``True`` if *value* is an iterable container (e.g. ``list`` or ``tuple`` but not a **generator**).
Note that :func:`is_iterable` will return ``False`` for string-like objects as well, even though they are iterable.
The same a... | bigcode/self-oss-instruct-sc2-concepts |
def encrypt(plaintext, key, cipher):
"""
Using Vignere cipher to encrypt plaintext.
:param plaintext: plaintext to encrypt with given key and given cipher
:param key: the key is appended until it has same length as plaintext;
each character of the key decides which cipher to use to
... | bigcode/self-oss-instruct-sc2-concepts |
import inspect
def is_class(object):
"""Check if the given object is a class"""
return inspect.isclass(object) | bigcode/self-oss-instruct-sc2-concepts |
def init_guess_word(length):
"""
Returns the initial guess word state.
The guess word is initialised with underscores, one for each letter
of the target word.
Args:
length: the length of the target word
Returns:
The initialised guess word, a list of `length` underscores
... | bigcode/self-oss-instruct-sc2-concepts |
def gcp_histone_normalize(data_df, gcp_normalization_peptide_id):
"""Subtract values of gcp_normalization_peptide_id from all the other probes.
Remove the row of data corresponding to the normalization histone.
Assumes that all probes should be normalized to the same peptide id.
Args:
data_df ... | bigcode/self-oss-instruct-sc2-concepts |
def HHMM_to_dec_deg(HHMM):
"""Converts a string HHMM to decimal hours."""
return 15*(int(HHMM[0:2])+float(HHMM[2:4])/60.) | bigcode/self-oss-instruct-sc2-concepts |
def get_tagname(tags, tagid):
"""Get tag name from tag ID from extracted Ghost tags."""
for tag in tags:
if tag['id'] == tagid:
return tag['name'] | bigcode/self-oss-instruct-sc2-concepts |
def aggregate_values_by_key(rdd):
"""Given an RDD in the form of:
``RDD[(0, 1), (0, 2), (1, 2)]``
Aggregate each key (first index in the tuple) into an RDD of
keys to lists of all values associated with the key.
Examples
--------
>>> x = sc.parallelize([("a", 1), ("b", 1), ("a", 2)])... | bigcode/self-oss-instruct-sc2-concepts |
def generate_num_processes_default(AUTOMS_NUM_PROCESSES):
""" Generates the default num processes parameter value to use using configured 'num processes' """
if AUTOMS_NUM_PROCESSES is None:
num_processes_default = 1
else:
num_processes_default = AUTOMS_NUM_PROCESSES
return num_proces... | bigcode/self-oss-instruct-sc2-concepts |
import six
def as_bool(val):
"""Converts an arbitary value into a boolean."""
if isinstance(val, bool):
return val
if isinstance(val, six.string_types):
if val.lower() in ('f', 'false', '0', 'n', 'no'):
return False
if val.lower() in ('t', 'true', '1', 'y', 'yes'):
... | bigcode/self-oss-instruct-sc2-concepts |
def populated_table(empty_table, request):
"""
Populate a table within the test database before executing test.
The table will have the same name as the test_function itself. Setup and teardown
of the database is handled by the unique_database fixture.
Args:
empty_table: pytest fixture that creates an e... | bigcode/self-oss-instruct-sc2-concepts |
def find_image(text: str) -> int:
"""Function to find if pdf has image only page.
text: text version of pdf document
return: 1 if image was found, 0 otherwise
"""
list_of_pages = text.split('\x0c')[:-1]
page_number = 0
found_image = 0
while page_number < len(list_of_page... | bigcode/self-oss-instruct-sc2-concepts |
def _totalValue(comb):
""" Total a particular combination of items
Args:
comb tuple of items in the form (item, weight, value)
Returns:
tuple (total value, total weight)
"""
totwt = totval = 0
for item, wt, val in comb:
totwt += wt
totval += val
return (totval, totwt) | bigcode/self-oss-instruct-sc2-concepts |
def default_income(time, dt, *args):
"""
Income method stub
:param time: current simulation time
:param dt: time step for which production limits are calculated
:param args: additional arguments
:return: 0
"""
return 0 | bigcode/self-oss-instruct-sc2-concepts |
def avg(list):
"""Find average value in a list or list-like object"""
return sum(list) / len(list) | bigcode/self-oss-instruct-sc2-concepts |
def distance(x, y):
""" Calculate the euclidean distance between two point in three dimensional space. """
return ((x[0] - y[0]) ** 2 + (x[1] - y[1]) ** 2 + (x[2] - y[2]) ** 2) ** 0.5 | bigcode/self-oss-instruct-sc2-concepts |
def d_y_diffr_dy(x, y):
"""
derivative of d(y/r)/dy
equivalent to second order derivatives dr_dyy
:param x:
:param y:
:return:
"""
return x**2 / (x**2 + y**2)**(3/2.) | bigcode/self-oss-instruct-sc2-concepts |
def non_neg(x):
""" return 0 if x is negative, else return x """
if x < 0:
return 0
else:
return x | bigcode/self-oss-instruct-sc2-concepts |
import glob
def get_file_paths_from_glob_patterns(glob_patterns):
""" Return a set of files matching the given list of glob patterns
(for example ["./test.sql", "./other_tables/*.sql"])
"""
file_paths = set()
for glob_pattern in glob_patterns:
file_paths |= set(glob.glob(glob_pattern))
... | bigcode/self-oss-instruct-sc2-concepts |
def reduce_reflex_angle_deg(angle):
""" Given an angle in degrees, normalises in [-179, 180] """
new_angle = angle % 360
if new_angle > 180:
new_angle -= 360
return new_angle | bigcode/self-oss-instruct-sc2-concepts |
def func(foo, bar):
"""Return the args."""
return foo, bar | bigcode/self-oss-instruct-sc2-concepts |
def pct_to_kelvin(pct, max_k=6500, min_k=2700):
"""Convert percent to kelvin."""
kelvin = ((max_k - min_k) * pct / 100) + min_k
return kelvin | bigcode/self-oss-instruct-sc2-concepts |
def es_par(numero: int) -> bool:
"""Determina si un número es par o no.
:param numero: Número a evaluar.
:type numero: int
:return: True si el número es par, False si no lo es.
:rtype: bool
"""
return numero % 2 == 0 | bigcode/self-oss-instruct-sc2-concepts |
import re
def get_step_from_checkpoint_path(checkpoint_path):
"""Returns the global step for the checkpoint at `checkpoint_path`.
**Note**: This function works for checkpoints that are saved in the TF format
only.
Assumes `checkpoint_path` corresponds to a file which contains the substring
model.ckpt-{g... | bigcode/self-oss-instruct-sc2-concepts |
def merge_dictionaries(a, b):
"""
merging two dictionaries
"""
merged = {**a, **b}
return merged | bigcode/self-oss-instruct-sc2-concepts |
def make_portfolio(df, date_level='date'):
"""
Make a portfolio of assets by grouping by date and summing all columns.
Note: the caller is responsible for making sure the dates line up across
assets and handling when they don't.
"""
return (
df
.groupby(level=date_level)
... | bigcode/self-oss-instruct-sc2-concepts |
def mie(r, eps, sig, m=12, n=6):
"""Mie pair potential. """
prefactor = (m / (m - n)) * (m / n) ** (n / (m - n))
return prefactor * eps * ((sig / r) ** m - (sig / r) ** n) | bigcode/self-oss-instruct-sc2-concepts |
import json
def read_config_file(config_file):
"""
Read a json configuration file
:param config_file: path to a json file containing the algorithm parameters
:type config_file: string
:return: the configuration
:rtype: dict
"""
with open(config_file, "r") as file:
user_configu... | bigcode/self-oss-instruct-sc2-concepts |
def PrintBox(loc, height, width, style='r-'):
"""A utility function to help visualizing boxes."""
xmin, ymin, xmax, ymax = loc[0] * width, loc[1] * height, loc[2] * width, loc[3] * height
#pyplot.plot([xmin, xmax, xmax, xmin, xmin], [ymin, ymin, ymax, ymax, ymin], style)
return [xmin, ymin, xmax, ymax] | bigcode/self-oss-instruct-sc2-concepts |
from typing import OrderedDict
def dictify(od):
"""Recursively replace OrderedDict with dict"""
if isinstance(od, OrderedDict):
return dict((k, dictify(v)) for k, v in od.items())
else:
return od | bigcode/self-oss-instruct-sc2-concepts |
def generate_list(iterable_a, iterable_b):
"""Return a list of a+b combinations"""
result = []
for iter_a in iterable_a:
for iter_b in iterable_b:
result.append(iter_a+iter_b)
return result | bigcode/self-oss-instruct-sc2-concepts |
import torch
def _roll_by_shifts(src: torch.Tensor, shifts: torch.LongTensor):
"""Roll tensor with different shifts for each row.
Note:
We assume the src is a 3 dimensions tensor and roll the last dimension.
Example:
>>> src = torch.arange(15).reshape((1,3,5))
>>> src
tensor([[[... | bigcode/self-oss-instruct-sc2-concepts |
def alignto(alignment_value: int, bitposition: int) -> int:
"""
Aligns the bit size to the given alignment value.
:param alignment_value: Value to align.
:param bitposition: Current bit position where to apply alignment.
:returns: Aligned bit position.
"""
if bitposition <= 0 or alignment_... | bigcode/self-oss-instruct-sc2-concepts |
def get_digit_b(number, digit):
""" Given a number, returns the digit in the specified position, for an out of range digit returns 0 """
return number % 10**digit // 10**(digit-1) | bigcode/self-oss-instruct-sc2-concepts |
def _to_np_mode(mode):
"""Convert padding modes from `ndi.correlate` to `np.pad`."""
mode_translation_dict = dict(nearest='edge', reflect='symmetric',
mirror='reflect')
if mode in mode_translation_dict:
mode = mode_translation_dict[mode]
return mode | bigcode/self-oss-instruct-sc2-concepts |
def get_abc(V, E, dE, ddE):
"""
Given the volume, energy, energy first derivative and energy
second derivative, return the a,b,c coefficients of
a parabola E = a*V^2 + b*V + c
"""
a = ddE / 2.
b = dE - ddE * V
c = E - V * dE + V ** 2 * ddE / 2.
return a, b, c | bigcode/self-oss-instruct-sc2-concepts |
from typing import Union
from pathlib import Path
import hashlib
def compute_sha256(filename: Union[Path, str]):
"""Return SHA256 checksum of a file."""
with open(filename, 'rb') as f:
return hashlib.sha256(f.read()).hexdigest() | bigcode/self-oss-instruct-sc2-concepts |
def is_int_even_v01(num):
"""
Use the modulo operator to evaluate whether an integer provided by
the caller is even or odd, returning either True or False.
Parameters:
num (int): the integer to be evaluated.
Returns:
is_even (boolean): True or False depending on the modulo check
... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def get_cuda_memory_used(device):
"""
Get the free memory info of device.
Notice that for CPU, this function will return 1/N of the total free memory,
where N is the world size.
"""
ret = torch.cuda.memory_allocated()
# get the peak memory to report correct data, so reset the ... | bigcode/self-oss-instruct-sc2-concepts |
import json
def load_templates_dict() -> dict:
"""Loads template strings dict from 'template_strings.json'.
Should be hierarchy of dict->dict>values based on context.
Important: Curly braces '{}' in template strings will be replaced with corresponding values using str.format
For instance
{
... | bigcode/self-oss-instruct-sc2-concepts |
def _get_loc_item_node(loc_json: dict, key_to_find: str) -> dict:
""" Return the item node of interest within the LOC results """
for node in loc_json:
if node.get('@id', '') == key_to_find:
return node
return {} | bigcode/self-oss-instruct-sc2-concepts |
def in_between_points_on_list(points_list, divisions):
"""
This takes a list of numerical values (floats or ints) and a list of divisions of ints of (points_list) - 1. This
method will then uses the number of sub divisions within the list of divisions to add new points to the points list
where you have ... | bigcode/self-oss-instruct-sc2-concepts |
import calendar
def datetime_to_unixtime(dt_obj):
"""Converts datetime timestamp into a unix timestamp (as an int)
Args:
dt_obj (datetime): a datetime object
Returns:
A unix timestamp as an int
"""
return calendar.timegm(dt_obj.utctimetuple()) | bigcode/self-oss-instruct-sc2-concepts |
import re
def is_palindrome(word):
"""Return if word is palindrome, 'madam' would be one.
Case insensitive, so Madam is valid too.
It should work for phrases too so strip all but alphanumeric chars.
So "No 'x' in 'Nixon'" should pass (see tests for more)"""
# [^0-9a-zA-Z]+ equals \W+
... | bigcode/self-oss-instruct-sc2-concepts |
from pathlib import Path
def localize_path(path_string):
"""Localize path for Windows, Unix, i.e. / or \
Args:
path_string (str): path using /
Returns:
str: path depending on OS
"""
return str(Path(path_string)) | bigcode/self-oss-instruct-sc2-concepts |
def merged_dict(itr):
""" Create a merged dict of dict (of dict) based on input.
Input is an iteratable of (keys, value).
Return value is root dictionary
Keys are successive dictionaries indicies. For example:
(('a', 'b', 'c'), 1)
would set:
output['a']['b']['c'] = 1
This function... | bigcode/self-oss-instruct-sc2-concepts |
def review_rating(review):
"""Return the number of stars given by the review, which is a
floating point number between 1 and 5."""
return review[1] | bigcode/self-oss-instruct-sc2-concepts |
import codecs
def read_vocabulary(vocab_inpath):
"""
Read a vocabulary file with one word per line.
Args:
vocab_inpath (str): Path to vocabulary file.
Returns:
set: Set of all words in vocabulary.
"""
vocab = set()
with codecs.open(vocab_inpath, 'rb', 'utf-8') as vocab_in... | bigcode/self-oss-instruct-sc2-concepts |
import time
def is_entry_added_to_table(switch_inst, table_name, srch_params, timeout=1, expect_count=1, exist=True):
"""Check if entry with specified fields values is added to table
Args:
switch_inst(object): Switch instance to work with
table_name(str): The name of table to perform search... | bigcode/self-oss-instruct-sc2-concepts |
def probability_sum(probability, token_frequency, n):
"""Assigns score to document based on summation of probabilities.
Args:
probability (float): Previously calculated probability.
token_frequency (float): Number of appearances of token in text.
n (int): Length of text.
Returns:
... | bigcode/self-oss-instruct-sc2-concepts |
def extract_goal(goal_map):
"""Returns the goal location."""
for o in range(goal_map.shape[0]):
for y in range(goal_map.shape[1]):
for x in range(goal_map.shape[2]):
if goal_map[o][y][x] == 1.:
return (o, y, x)
assert False | bigcode/self-oss-instruct-sc2-concepts |
def arqexiste(arq):
"""
-> Verifica se existe o arquivo arq
:param arq: Nome do arquivo a ser testado.
:return: retorna True se o arquivo for encontrado,
caso contrário False
"""
try:
a = open(arq)
except FileNotFoundError: # O arquivo não foi encontrado
print('Arquivo não encontrado!')
return False
els... | bigcode/self-oss-instruct-sc2-concepts |
def calc_pid(seq1, seq2):
"""
Calculates the percentage ID (still as a decimal)
between two sequences.
Parameters
----------
seq1: str
seq2: str
Returns
-------
pid: float
"""
alnlen = len(seq1)
identical = 0
for i in range(0, len(seq1)):
if seq1[i].isal... | bigcode/self-oss-instruct-sc2-concepts |
def mk_rank(rank, default_rank, level):
"""Create a rank from a result rank, a default rank, and a level
level can be one of: "pass", "warning", "error", "open", "notApplicable", or "note".
These don't correspond very well to traditional scoring, but they're all we've got.
Note that the Sarif "rank" i... | bigcode/self-oss-instruct-sc2-concepts |
def get_text_colour_analytics_sentiment(score):
"""
Returns RGB code text to represent the strength of negative or positive sentiment
:param score: Sentiment score in range +/- 5.0
:return: Background RGB colour text string to use in sentiment text
"""
# Get our score into the range [0..4], whi... | bigcode/self-oss-instruct-sc2-concepts |
def duplicate_package_status(original_status, override_version=None):
"""
Given a status generated by parse_package_status(), duplicate it for a different source package.
:param original_status: the status to clone
:param override_version: the cloned package version (different)
:return: new status (... | bigcode/self-oss-instruct-sc2-concepts |
def is_private(obj):
"""Return True if object is private."""
if obj is not None:
return isinstance(obj, str) and obj.startswith('_') | bigcode/self-oss-instruct-sc2-concepts |
def get_board_as_string(game):
"""
Returns a string representation of the game board in the current state.
"""
board_str = """
{} | {} | {}
--------------
{} | {} | {}
--------------
{} | {} | {}
"""
return board_str.format(game["board"][0][0], game["board"][0][1],game["board"][0][2],ga... | bigcode/self-oss-instruct-sc2-concepts |
import re
def check_convert_chr_id(chr_id):
"""
Check and convert chromosome IDs to format:
chr1, chr2, chrX, ...
If chromosome IDs like 1,2,X, .. given, convert to chr1, chr2, chrX ..
Return False if given chr_id not standard and not convertable.
Filter out scaffold IDs like:
GL000009.2,... | bigcode/self-oss-instruct-sc2-concepts |
import collections
def merge(qrels, run, queries):
"""Merge qrels and runs into a single dict of key: query,
value: tuple(relevant_doc_ids, candidate_doc_ids)"""
data = collections.OrderedDict()
for query_id, candidate_doc_ids in run.items():
query = queries[query_id]
relevant_doc_ids = set()
if ... | bigcode/self-oss-instruct-sc2-concepts |
def poisson_pipeline(infile, outfile, depth=8):
"""Makes a dictionary describing PDAL pipeline for generating Poisson
surface mesh.
Parameters
-----------
infile : str, path to file
input file to be converted into a mesh
outfile : str, path to file
output file for storing Poisso... | bigcode/self-oss-instruct-sc2-concepts |
def gpsfix2str(fix: int) -> str:
"""
Convert GPS fix integer to descriptive string.
:param int fix: GPS fix type (0-5)
:return: GPS fix type as string
:rtype: str
"""
if fix == 5:
fixs = "TIME ONLY"
elif fix == 4:
fixs = "GPS + DR"
elif fix == 3:
fixs = "3D... | bigcode/self-oss-instruct-sc2-concepts |
def _get_exchange_key_ntlm_v2(session_base_key):
"""
[MS-NLMP] v28.0 2016-07-14
4.3.5.1 KXKEY
Calculates the Key Exchange Key for NTLMv2 authentication. Used for signing and sealing messages.
According to docs, 'If NTLM v2 is used, KeyExchangeKey MUST be set to the given 128-bit SessionBaseKey
... | bigcode/self-oss-instruct-sc2-concepts |
def process_path(module_path):
"""
Method to obtain module and class_name from a module path
Args:
module_path(String): path in the format module.class_name
Returns:
tuple containing class_name and module
"""
if module_path == 'numpy.ndarray':
return 'StorageNumpy', 'hec... | bigcode/self-oss-instruct-sc2-concepts |
def _GetProfileInfoDict(profile_info):
"""Convert profile_info to a dict.
Args:
profile_info (ArtifactProfileInfo): The artifact profile_info.
Returns:
A dictionary containing profile info.
"""
ret = {}
which = profile_info.WhichOneof('artifact_profile_info')
if which:
value = getattr(profil... | bigcode/self-oss-instruct-sc2-concepts |
def form1(x, y, n, ind, ax, line):
"""Default annotation for plots with 1 line"""
return f"x: {x:.5g}\ny: {y:.5g}" | 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.