seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
def get_total_interconnector_violation(model):
"""Total interconnector violation"""
# Total forward and reverse interconnector violation
forward = sum(v.value for v in model.V_CV_INTERCONNECTOR_FORWARD.values())
reverse = sum(v.value for v in model.V_CV_INTERCONNECTOR_REVERSE.values())
return forw... | bigcode/self-oss-instruct-sc2-concepts |
import hashlib
def Many_Hash(filename):
""" calculate hashes for given filename """
with open(filename, "rb") as f:
data = f.read()
md5 = hashlib.md5(data).hexdigest()
sha1 = hashlib.sha1(data).hexdigest()
sha256 = hashlib.sha256(data).hexdigest()
sha512 = hashlib.sha512(data).hexdiges... | bigcode/self-oss-instruct-sc2-concepts |
def grad_likelihood(*X, Y=0, W=1):
"""Gradient of the log-likelihood of NMF assuming Gaussian error model.
Args:
X: tuple of (A,S) matrix factors
Y: target matrix
W: (optional weight matrix MxN)
Returns:
grad_A f, grad_S f
"""
A, S = X
D = W * (A.dot(S) - Y)
... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Sequence
from typing import List
def chain(items: Sequence, cycle: bool = False) -> List:
"""Creates a chain between items
Parameters
----------
items : Sequence
items to join to chain
cycle : bool, optional
cycle to the start of the chain if True, default: Fals... | bigcode/self-oss-instruct-sc2-concepts |
def _ensure_list_of_lists(entries):
"""Transform input to being a list of lists."""
if not isinstance(entries, list):
# user passed in single object
# wrap in a list
# (next transformation will make this a list of lists)
entries = [entries]
if not any(isinstance(element, list... | bigcode/self-oss-instruct-sc2-concepts |
def get_daily_returns(df):
"""Compute and return the daily return values."""
daily_returns = df.copy()
daily_returns[1:] = (df[1:] / df[:-1].values) - 1
daily_returns.iloc[0] = 0 # set daily returns for row 0 to 0
return daily_returns | bigcode/self-oss-instruct-sc2-concepts |
def bitarray2dec(in_bitarray):
"""
Converts an input NumPy array of bits (0 and 1) to a decimal integer.
Parameters
----------
in_bitarray : 1D ndarray of ints
Input NumPy array of bits.
Returns
-------
number : int
Integer representation of input bit array.
"""
... | bigcode/self-oss-instruct-sc2-concepts |
def set_state_dict(model, state_dict):
"""Load state dictionary whether or not distributed training was used"""
if hasattr(model, "module"):
return model.module.load_state_dict(state_dict)
return model.load_state_dict(state_dict) | bigcode/self-oss-instruct-sc2-concepts |
import re
def _parse_line(cpuid, match):
"""Search a line with the content <match>: <value> in the given
StringIO instance and return <value>
"""
cpuid.seek(0)
for l in cpuid.readlines():
m = re.match('^(%s.*):\s+(.+)' % match, l)
if m:
return (m.group(1), m.group(2).r... | bigcode/self-oss-instruct-sc2-concepts |
def other_options(options):
"""
Replaces None with an empty dict for plotting options.
"""
return dict() if options is None else options.copy() | bigcode/self-oss-instruct-sc2-concepts |
import re
def demo_id(filename):
"""Get the demo_number from a test macro"""
b1 = re.match('.*/test_demo\d{2}\.py', filename)
found = re.findall('.*/test_demo(\d{2})\.py', filename)
b2 = len(found) == 1
is_test_file = b1 and b2
assert is_test_file, 'Not a test file: "%s"' % filename
return... | bigcode/self-oss-instruct-sc2-concepts |
def read_classification_from_file(filename):
""" Return { <filename> : <classification> } dict """
with open(filename, "rt") as f:
classification = {}
for line in f:
key, value = line.split()
classification[key] = value
return classification | bigcode/self-oss-instruct-sc2-concepts |
def truncate(message, limit=500):
"""
Truncates the message to the given limit length. The beginning and the
end of the message are left untouched.
"""
if len(message) > limit:
trc_msg = ''.join([message[:limit // 2 - 2],
' .. ',
message[... | bigcode/self-oss-instruct-sc2-concepts |
def findDataStart(lines, delin = ' '):
"""
Finds the line where the data starts
input:
lines = list of strings (probably from a data file)
delin = optional string, tells how the data would be separated, default is a space (' ')
output:
i = integer where the data stops being... | bigcode/self-oss-instruct-sc2-concepts |
def pa_bbm_hash_mock(url, request):
"""
Mock for Android autoloader lookup, new site.
"""
thebody = "http://54.247.87.13/softwareupgrade/BBM/bbry_qc8953_autoloader_user-common-AAL093.sha512sum"
return {'status_code': 200, 'content': thebody} | bigcode/self-oss-instruct-sc2-concepts |
import itertools
import random
def generate_comparison_pairs(condition_datas):
"""
Generate all stimulus comparison pairs for a condition and return in a random order for a paired comparison test.
Parameters
----------
condition_datas: list of dict
List of dictionary of condition data as ... | bigcode/self-oss-instruct-sc2-concepts |
def alltrue(seq):
"""
Return *True* if all elements of *seq* evaluate to *True*. If
*seq* is empty, return *False*.
"""
if not len(seq):
return False
for val in seq:
if not val:
return False
return True | bigcode/self-oss-instruct-sc2-concepts |
def test(classifier, data, labels):
"""
Test a classifier.
Parameters
----------
classifier : sklearn classifier
The classifier to test.
data : numpy array
The data with which to test the
classifier.
labels : numpy array
The labels with which to test the
the classifier.
Returns
... | bigcode/self-oss-instruct-sc2-concepts |
def reverse_complement(s):
"""Return reverse complement sequence"""
ret = ''
complement = {"A": "T", "T": "A", "C": "G", "G": "C", "N": "N", "a": "t", "t": "a", "c": "g", "g": "c", "n": "n"}
for base in s[::-1]:
ret += complement[base]
return ret | bigcode/self-oss-instruct-sc2-concepts |
def hex_to_rgb(col_hex):
"""Convert a hex colour to an RGB tuple."""
col_hex = col_hex.lstrip('#')
return bytearray.fromhex(col_hex) | bigcode/self-oss-instruct-sc2-concepts |
def page_query_with_skip(query, skip=0, limit=100, max_count=None, lazy_count=False):
"""Query data with skip, limit and count by `QuerySet`
Args:
query(mongoengine.queryset.QuerySet): A valid `QuerySet` object.
skip(int): Skip N items.
limit(int): Maximum number of items returned.
... | bigcode/self-oss-instruct-sc2-concepts |
def nvt_cv(e1, e2, kt, volume = 1.0):
"""Compute (specific) heat capacity in NVT ensemble.
C_V = 1/kT^2 . ( <E^2> - <E>^2 )
"""
cv = (1.0/(volume*kt**2))*(e2 - e1*e1)
return cv | bigcode/self-oss-instruct-sc2-concepts |
def rectangle_to_cv_bbox(rectangle_points):
"""
Convert the CVAT rectangle points (serverside) to a OpenCV rectangle.
:param tuple rectangle_points: Tuple of form (x1,y1,x2,y2)
:return: Form (x1, y1, width, height)
"""
# Dimensions must be ints, otherwise tracking throws a exception
return (int(rectangle_points[... | bigcode/self-oss-instruct-sc2-concepts |
def dijkstra(g, source):
"""Return distance where distance[v] is min distance from source to v.
This will return a dictionary distance.
g is a Graph object.
source is a Vertex object in g.
"""
unvisited = set(g)
distance = dict.fromkeys(g, float('inf'))
distance[source] = 0
whi... | bigcode/self-oss-instruct-sc2-concepts |
def calc_gross_profit_margin(revenue_time_series, cogs_time_series): # Profit and Cost of Goods Sold - i.e. cost of materials and director labour costs
"""
Gross Profit Margins Formula
Notes
------------
Profit Margins = Total revenue - Cost of goods sold (COGS) / revenue
... | bigcode/self-oss-instruct-sc2-concepts |
import asyncio
def event_loop() -> asyncio.AbstractEventLoop:
"""Returns an event loop for the current thread"""
return asyncio.get_event_loop_policy().get_event_loop() | bigcode/self-oss-instruct-sc2-concepts |
def set_discover_targets(discover: bool) -> dict:
"""Controls whether to discover available targets and notify via
`targetCreated/targetInfoChanged/targetDestroyed` events.
Parameters
----------
discover: bool
Whether to discover available targets.
"""
return {"method": "Target.... | bigcode/self-oss-instruct-sc2-concepts |
def notas(*nt, sit=False):
"""
-> Função para analisar notas e situação de vários alunos.
:param nt: recebe uma ou mais notas dos alunos.
:param sit: valor opcional, mostrando ou não a situação do aluno(True/False).
:return: dicionário com várias informações sobre a situação da turma.
"""
pr... | bigcode/self-oss-instruct-sc2-concepts |
def _get_binary(value, bits):
"""
Provides the given value as a binary string, padded with zeros to the given
number of bits.
:param int value: value to be converted
:param int bits: number of bits to pad to
"""
# http://www.daniweb.com/code/snippet216539.html
return ''.join([str((value >> y) & 1) for... | bigcode/self-oss-instruct-sc2-concepts |
def count_null_values_for_each_column(spark_df):
"""Creates a dictionary of the number of nulls in each column
Args:
spark_df (pyspark.sql.dataframe.DataFrame): The spark dataframe for which the nulls need to be counted
Returns:
dict: A dictionary with column name as key and null count as ... | bigcode/self-oss-instruct-sc2-concepts |
def __version_compare(v1, v2):
"""
Compare two Commander version versions and will return:
1 if version 1 is bigger
0 if equal
-1 if version 2 is bigger
"""
# This will split both the versions by '.'
arr1 = v1.split(".")
arr2 = v2.split(".")
n = len(arr1)
m =... | bigcode/self-oss-instruct-sc2-concepts |
def create_vocab_item(vocab_class, row, row_key):
"""gets or create a vocab entry based on name and name_reverse"""
try:
name_reverse = row[row_key].split("|")[1]
name = row[row_key].split("|")[0]
except IndexError:
name_reverse = row[row_key]
name = row[row_key]
temp_ite... | bigcode/self-oss-instruct-sc2-concepts |
import json
def _load_repo_configs(path):
"""
load repository configs from the specified json file
:param path:
:return: list of json objects
"""
with open(path) as f:
return json.loads(f.read()) | bigcode/self-oss-instruct-sc2-concepts |
def get_if_all_equal(data, default=None):
"""Get value of all are the same, else return default value.
Arguments:
data {TupleTree} -- TupleTree data.
Keyword Arguments:
default {any} -- Return if all are not equal (default: {None})
"""
if data.all_equal():
return da... | bigcode/self-oss-instruct-sc2-concepts |
def convert_compartment_id(modelseed_id, format_type):
""" Convert a compartment ID in ModelSEED source format to another format.
No conversion is done for unknown format types.
Parameters
----------
modelseed_id : str
Compartment ID in ModelSEED source format
format_type : {'modelseed... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def dirichlet_common_loss(alphas, y_one_hot, lam=0):
"""
Use Evidential Learning Dirichlet loss from Sensoy et al. This function follows
after the classification and multiclass specific functions that reshape the
alpha inputs and create one-hot targets.
:param alphas: Predicted para... | bigcode/self-oss-instruct-sc2-concepts |
def merge_dicts(base, updates):
"""
Given two dicts, merge them into a new dict as a shallow copy.
Parameters
----------
base: dict
The base dictionary.
updates: dict
Secondary dictionary whose values override the base.
"""
if not base:
base = dict()
if not u... | bigcode/self-oss-instruct-sc2-concepts |
def get_hashes_from_file_manifest(file_manifest):
""" Return a string that is a concatenation of the file hashes provided in the bundle manifest entry for a file:
{sha1}{sha256}{s3_etag}{crc32c}
"""
sha1 = file_manifest.sha1
sha256 = file_manifest.sha256
s3_etag = file_manifest.s3_etag
c... | bigcode/self-oss-instruct-sc2-concepts |
def lowerColumn(r, c):
"""
>>> lowerColumn(5, 4)
[(5, 4), (6, 4), (7, 4), (8, 4)]
"""
x = range(r, 9)
y = [c, ] * (9-r)
return zip(x, y) | bigcode/self-oss-instruct-sc2-concepts |
def summarize_filetypes(dir_map):
"""
Given a directory map dataframe, this returns a simple summary of the
filetypes contained therein and whether or not those are supported or not
----------
dir_map: pandas dictionary with columns path, extension, filetype, support;
this is the ouput o... | bigcode/self-oss-instruct-sc2-concepts |
def staticTunnelTemplate(user, device, ip, aaa_server, group_policy):
"""
Template for static IP tunnel configuration for a user.
This creates a unique address pool and tunnel group for a user.
:param user: username id associated with static IP
:type user: str
:param device:... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Tuple
def _build_label_attribute_names(
should_include_handler: bool,
should_include_method: bool,
should_include_status: bool,
) -> Tuple[list, list]:
"""Builds up tuple with to be used label and attribute names.
Args:
should_include_handler (bool): Should the `handler... | bigcode/self-oss-instruct-sc2-concepts |
def constructQuery(column_lst, case_id):
"""
Construct the query to public dataset: aketari-covid19-public.covid19.ISMIR
Args:
column_lst: list - ["*"] or ["column_name1", "column_name2" ...]
case_id: str - Optional e.g "case1"
Returns:
query object
"""
# Public dataset
... | bigcode/self-oss-instruct-sc2-concepts |
def batch_unflatten(x, shape):
"""Revert `batch_flatten`."""
return x.reshape(*shape[:-1], -1) | bigcode/self-oss-instruct-sc2-concepts |
def prepend_batch_seq_axis(tensor):
"""
CNTK uses 2 dynamic axes (batch, sequence, input_shape...).
To have a single sample with length 1 you need to pass (1, 1, input_shape...)
This method reshapes a tensor to add to the batch and sequence axis equal to 1.
:param tensor: The tensor to be reshaped
... | bigcode/self-oss-instruct-sc2-concepts |
def dms2dd(d, m, s):
"""
Convert degrees minutes seconds to decimanl degrees
:param d: degrees
:param m: minutes
:param s: seconds
:return: decimal
"""
return d+((m+(s/60.0))/60.0) | bigcode/self-oss-instruct-sc2-concepts |
def transpose_dataframe(df): # pragma: no cover
"""
Check if the input is a column-wise Pandas `DataFrame`. If `True`, return a
transpose dataframe since stumpy assumes that each row represents data from a
different dimension while each column represents data from the same dimension.
If `False`, re... | bigcode/self-oss-instruct-sc2-concepts |
def write_data(f, grp, name, data, type_string, options):
""" Writes a piece of data into an open HDF5 file.
Low level function to store a Python type (`data`) into the
specified Group.
.. versionchanged:: 0.2
Added return value `obj`.
Parameters
----------
f : h5py.File
Th... | bigcode/self-oss-instruct-sc2-concepts |
def find_collection(client, dbid, id):
"""Find whether or not a CosmosDB collection exists.
Args:
client (obj): A pydocumentdb client object.
dbid (str): Database ID.
id (str): Collection ID.
Returns:
bool: True if the collection exists, False otherwise.
"""
... | bigcode/self-oss-instruct-sc2-concepts |
import json
def load_dicefile(file):
""" Load the dicewords file from disk. """
with open(file) as f:
dicewords_dict = json.load(f)
return dicewords_dict | bigcode/self-oss-instruct-sc2-concepts |
def get_soup_search(x, search):
"""Searches to see if search is in the soup content and returns true if it is (false o/w)."""
if len(x.contents) == 0:
return False
return x.contents[0] == search | bigcode/self-oss-instruct-sc2-concepts |
def EVLACalModel(Source,
CalDataType=" ", CalFile=" ", CalName=" ", CalClass=" ", CalSeq=0, CalDisk=0, \
CalNfield=0, CalCCVer=1, CalBComp=[1], CalEComp=[0], CalCmethod=" ", CalCmode=" ", CalFlux=0.0, \
CalModelFlux=0.0, CalModelSI=0.0,CalModelPos=[0.,0.], CalModelPar... | bigcode/self-oss-instruct-sc2-concepts |
def split(children):
"""Returns the field that is used by the node to make a decision.
"""
field = set([child.predicate.field for child in children])
if len(field) == 1:
return field.pop() | bigcode/self-oss-instruct-sc2-concepts |
def reverse_str(input_str):
"""
Reverse a string
"""
return input_str[::-1] | bigcode/self-oss-instruct-sc2-concepts |
def drop_suffix_from_str(item: str, suffix: str, divider: str = '') -> str:
"""Drops 'suffix' from 'item' with 'divider' in between.
Args:
item (str): item to be modified.
suffix (str): suffix to be added to 'item'.
Returns:
str: modified str.
"""
suffix = ''.join([suf... | bigcode/self-oss-instruct-sc2-concepts |
def compute_reporting_interval(item_count):
"""
Computes for a given number of items that will be processed how often the
progress should be reported
"""
if item_count > 100000:
log_interval = item_count // 100
elif item_count > 30:
log_interval = item_count // 10
else:
... | bigcode/self-oss-instruct-sc2-concepts |
def _preprocess_graphql_string(graphql_string):
"""Apply any necessary preprocessing to the input GraphQL string, returning the new version."""
# HACK(predrag): Workaround for graphql-core issue, to avoid needless errors:
# https://github.com/graphql-python/graphql-core/issues/98
return g... | bigcode/self-oss-instruct-sc2-concepts |
def get_yn_input(prompt):
"""
Get Yes/No prompt answer.
:param prompt: string prompt
:return: bool
"""
answer = None
while answer not in ["y", "n", ""]:
answer = (input(prompt + " (y/N): ") or "").lower() or "n"
return answer == "y" | bigcode/self-oss-instruct-sc2-concepts |
def form_clean_components(rmsynth_pixel, faraday_peak, rmclean_gain):
"""Extract a complex-valued clean component.
Args:
rmsynth_pixel (numpy array): the dirty RM data for a specific pixel.
faraday_peak (int): the index of the peak of the clean component.
rmclean_gain (float): loop gain for cle... | bigcode/self-oss-instruct-sc2-concepts |
import re
import json
def fix_hunspell_json(badjson_path='en_us.json', goodjson_path='en_us_fixed.json'):
"""Fix the invalid hunspellToJSON.py json format by inserting double-quotes in list of affix strings
Args:
badjson_path (str): path to input json file that doesn't properly quote
goodjson_pat... | bigcode/self-oss-instruct-sc2-concepts |
def get_axe_names(image, ext_info):
"""
Derive the name of all aXe products for a given image
"""
# make an empty dictionary
axe_names = {}
# get the root of the image name
pos = image.rfind('.fits')
root = image[:pos]
# FILL the dictionary with names of aXe products
#
# th... | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
def arrayToFloatList(x_array) -> List[float]:
"""Convert array to list of float.
Args:
x_array: array[Any] --
Returns:
List[float]
"""
return [float(x_item) for x_item in x_array] | bigcode/self-oss-instruct-sc2-concepts |
def fetch_neighbours(matrix, y, x):
"""Find all neigbouring values and add them together"""
neighbours = []
try:
neighbours.append(matrix[y-1][x-1])
except IndexError:
neighbours.append(0)
try:
neighbours.append(matrix[y-1][x])
except IndexError:
neighb... | bigcode/self-oss-instruct-sc2-concepts |
def maybe_unsorted(start, end):
"""Tells if a range is big enough to potentially be unsorted."""
return end - start > 1 | bigcode/self-oss-instruct-sc2-concepts |
import requests
def get_residue_info(name, num_scheme=None, verbose=False):
"""
Gets residue info from the GPCRdb
Parameters
----------
name : str
Name of the protein to download (as in its GPCRdb URL).
num_scheme : str
Alternative numbering scheme to use.... | bigcode/self-oss-instruct-sc2-concepts |
def sample_builder(samples):
"""
Given a dictionary with value: count pairs, build a list.
"""
data = []
for key in samples:
data.extend([key] * samples[key])
data.sort()
return data | bigcode/self-oss-instruct-sc2-concepts |
import logging
from typing import Any
def _value(record: logging.LogRecord, field_name_or_value: Any) -> Any:
"""
Retrieve value from record if possible. Otherwise use value.
:param record: The record to extract a field named as in field_name_or_value.
:param field_name_or_value: The field name to ext... | bigcode/self-oss-instruct-sc2-concepts |
def replace_tags(string, from_tag="i", to_tag="italic"):
"""
Replace tags such as <i> to <italic>
<sup> and <sub> are allowed and do not need to be replaced
This does not validate markup
"""
string = string.replace("<" + from_tag + ">", "<" + to_tag + ">")
string = string.replace("</" + from... | bigcode/self-oss-instruct-sc2-concepts |
def fourcc_to_string(fourcc):
"""
Convert fourcc integer code into codec string.
Parameters
----------
fourcc : int
Fourcc integer code.
Returns
-------
codec : str
Codec string corresponding to fourcc code.
"""
char1 = str(chr(fourcc & 255))
char2 = str(ch... | bigcode/self-oss-instruct-sc2-concepts |
def shape_of_horizontal_links(shape):
"""Shape of horizontal link grid.
Number of rows and columns of *horizontal* links that connect nodes in a
structured grid of quadrilaterals.
Parameters
----------
shape : tuple of int
Shape of grid of nodes.
Returns
-------
tuple of i... | bigcode/self-oss-instruct-sc2-concepts |
def most_common(hist):
"""Makes a list of word-freq pairs in descending order of frequency.
hist: map from word to frequency
returns: list of (frequency, word) pairs
"""
t = []
for key, value in hist.items():
t.append((value, key))
t.sort()
t.reverse()
return t | bigcode/self-oss-instruct-sc2-concepts |
from typing import Any
from typing import Optional
def arg_to_int(arg: Any, arg_name: str, required: bool = False) -> Optional[int]:
"""Converts an XSOAR argument to a Python int
This function is used to quickly validate an argument provided to XSOAR
via ``demisto.args()`` into an ``int`` type. It will t... | bigcode/self-oss-instruct-sc2-concepts |
import random
def populate(num_rats, min_wt, max_wt, mode_wt):
"""Initialize a population with a triangular distribution of weights."""
return [int(random.triangular(min_wt, max_wt, mode_wt))\
for i in range(num_rats)] | bigcode/self-oss-instruct-sc2-concepts |
def calc_freq_from_interval(interval, unit='msec'):
"""
given an interval in the provided unit, returns the frequency
:param interval:
:param unit: unit of time interval given, valid values include ('msec', 'sec')
:return: frequency in hertz
"""
if interval <= 0:
print('Invalid inter... | bigcode/self-oss-instruct-sc2-concepts |
def unganged_me1a_geometry(process):
"""Customise digi/reco geometry to use unganged ME1/a channels
"""
if hasattr(process,"CSCGeometryESModule"):
process.CSCGeometryESModule.useGangedStripsInME1a = False
if hasattr(process,"idealForDigiCSCGeometry"):
process.idealForDigiCSCGeometry.useG... | bigcode/self-oss-instruct-sc2-concepts |
import random
import string
def random_string(n):
"""ランダム文字列生成 random string generator
Args:
n (int): 文字数 length
Returns:
str: ランダム文字列 random string
"""
return ''.join(random.choices(string.ascii_letters + string.digits, k=n)) | bigcode/self-oss-instruct-sc2-concepts |
def convert_timestamp_to_seconds(timestamp):
"""Convert timestamp (hh:mm:ss) to seconds
Args:
timestamp (str): timestamp text in `hh:mm:ss` format
Returns:
float: timestamp converted to seconds
"""
timestamp_split = timestamp.split(":")
hour = int(timestamp_split[0])
minute... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def kpts_2_img_coordinates(kpt_coordinates: torch.Tensor,
img_shape: tuple) -> torch.Tensor:
""" Converts the (h, w) key-point coordinates from video structure format [-1,1]x[-1,1]
to image coordinates in [0,W]x[0,H].
:param kpt_coordinates: Torch tensor in (N,... | bigcode/self-oss-instruct-sc2-concepts |
def combine(*dep_lists):
"""Combines multiple lists into a single sorted list of distinct items."""
return list(sorted(set(
dep
for dep_list in dep_lists
for dep in dep_list))) | bigcode/self-oss-instruct-sc2-concepts |
def _get_fn_name_key(fn):
"""
Get the name (str) used to hash the function `fn`
Parameters
----------
fn : function
The function to get the hash key for.
Returns
-------
str
"""
name = fn.__name__
if hasattr(fn, '__self__'):
name = fn.__self__.__class__.__na... | bigcode/self-oss-instruct-sc2-concepts |
def getPep (site, pos_in_pep, ref_seq):
"""
get the pep seq arount the given site from the reference sequence
Parameters
----------
site : int
pos in protein seq
pos_in_pep : int
position in the peptide (defines the number of aa will get around the site)
ref_seq : str
... | bigcode/self-oss-instruct-sc2-concepts |
def parse_lines_to_dict(lines):
"""
Parse a list of message into a dictionnary.
Used for command like status and stats.
:param lines: an array of string where each item has the following format
'name: value'
:return: a dictionary with the names (as keys) and values found in the
lines.
"... | bigcode/self-oss-instruct-sc2-concepts |
import string
import re
import hashlib
def get_hash(text):
"""Generate a hashkey of text using the MD5 algorithm."""
punctuation = string.punctuation
punctuation = punctuation + "’" + "“" + "?" + "‘"
text = [c if c not in punctuation else ' ' for c in text]
text = ''.join(text)
text = re.sub(... | bigcode/self-oss-instruct-sc2-concepts |
def fletcher_reeves(algo):
"""
Fletcher-Reeves descent direction update method.
"""
return algo.current_gradient_norm / algo.last_gradient_norm | bigcode/self-oss-instruct-sc2-concepts |
from typing import Union
def calculate_digital_sum(number: Union[int, str]) -> int:
"""Calculate the digital sum of the number `number`."""
return sum([int(digit) for digit in str(number)]) | bigcode/self-oss-instruct-sc2-concepts |
def tile_type(tile_ref, level, ground_default, sky_default):
"""Returns the tile type at the given column and row in the level.
tile_ref is the column and row of a tile as a 2-item sequence
level is the nested list of tile types representing the level map.
ground_default is the tile type to r... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Optional
def validate_state_of_charge_min(state_of_charge_min: Optional[float]) -> Optional[float]:
"""
Validates the state of charge min of an object.
State of charge min is always optional.
:param state_of_charge_min: The state of charge min of the object.
:return: The valida... | bigcode/self-oss-instruct-sc2-concepts |
def int_to_name(n,hyphen=False,use_and=False,long_scale=False):
"""
Convert an integer to its English name, defaults to short scale (1,000,000 = 'one billion'), returns a string
Args:
n -- int to be named
hyphen --bool, use hyphens for numbers like forty-eight
use_and -- bool, u... | bigcode/self-oss-instruct-sc2-concepts |
def get_token_types(input, enc):
"""
This method generates toke_type_ids that correspond to the given input_ids.
:param input: Input_ids (tokenised input)
:param enc: Model tokenizer object
:return: A list of toke_type_ids corresponding to the input_ids
"""
meta_dict = {
"genre": {
... | bigcode/self-oss-instruct-sc2-concepts |
def string_permutation(s1,s2):
"""
Edge case: If the strings are not the same length, they are not permutations of each other.
Count the occurence of each individual character in each string.
If the counts are the same, the strings are permutations of each other.
Counts are stored in array of 128 s... | bigcode/self-oss-instruct-sc2-concepts |
def get_cdk_context_value(scope, key):
"""
get_cdk_context_value gets the cdk context value for a provided key
:scope: CDK Construct scope
:returns: context value
:Raises: Exception: The context key: {key} is undefined.
"""
value = scope.node.try_get_context(key)
if value is None:
... | bigcode/self-oss-instruct-sc2-concepts |
def missing_to_default(field, default):
"""
Function to convert missing values into default values.
:param field: the original, missing, value.
:param default: the new, default, value.
:return: field; the new value if field is an empty string, the old value
otherwise.
:rtype: any
... | bigcode/self-oss-instruct-sc2-concepts |
def format_setting_name(token):
"""Returns string in style in upper case
with underscores to separate words"""
token = token.replace(' ', '_')
token = token.replace('-', '_')
bits = token.split('_')
return '_'.join(bits).upper() | bigcode/self-oss-instruct-sc2-concepts |
def simple_request_messages_to_str(messages):
"""
Returns a readable string from a simple request response message
Arguments
messages -- The simple request response message to parse
"""
entries = []
for message in messages:
entries.append(message.get('text'))
return ','.join(ent... | bigcode/self-oss-instruct-sc2-concepts |
def get_angle_errors(errors):
"""
Takes error vectors computed over full state predictions and picks the
dimensions corresponding to angle predictions. Notice that it is assumed
that the first three dimenions contain angle errors.
"""
return errors[:,:, :3] | bigcode/self-oss-instruct-sc2-concepts |
def apply_filter_list(func, obj):
"""Apply `func` to list or tuple `obj` element-wise and directly otherwise."""
if isinstance(obj, (list, tuple)):
return [func(item) for item in obj]
return func(obj) | bigcode/self-oss-instruct-sc2-concepts |
def intensity2color(scale):
"""Interpolate from pale grey to deep red-orange.
Boundaries:
min, 0.0: #cccccc = (204, 204, 204)
max, 1.0: #ff2000 = (255, 32, 0)
"""
assert 0.0 <= scale <= 1.0
baseline = 204
max_rgb = (255, 32, 0)
new_rbg = tuple(baseline + int(round(scale * (... | bigcode/self-oss-instruct-sc2-concepts |
def calc_gamma_components(Data_ref, Data):
"""
Calculates the components of Gamma (Gamma0 and delta_Gamma),
assuming that the Data_ref is uncooled data (ideally at 3mbar
for best fitting). It uses the fact that A_prime=A/Gamma0 should
be constant for a particular particle under changes in pressure
... | bigcode/self-oss-instruct-sc2-concepts |
import json
def get_ikhints_json() -> str:
"""Return a test document-config/ikhints.json."""
ikhints = {
"hints":
("[\r\n [\r\n 1.33904457092285,\r\n -1.30520141124725,\r\n"
" 1.83943212032318,\r\n -2.18432211875916,\r\n"
" 4.76191997528076,\r\n -0.29564744... | bigcode/self-oss-instruct-sc2-concepts |
def _backup_path(target):
"""Return a path from the directory this is in to the Bazel root.
Args:
target: File
Returns:
A path of the form "../../.."
"""
n = len(target.dirname.split("/"))
return "/".join([".."] * n) | 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.