seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
import re
def check_if_border(feature, operon_borders):
"""Return start/end coordinate of the SeqFeature if its accession is the first/last in the given tuple.
Parameters
----------
feature : SeqFeature
Directory with input genbank files.
operon_borders : str
Directory to store th... | bigcode/self-oss-instruct-sc2-concepts |
import random
def random_color_from_string(str):
""" Given a string, return an RGB color string.
The same string will always give the same result but otherwise is random. """
rng = random.Random(str)
cs = ['#d98668', '#d97400', '#bfab5c', '#aee66e', '#9bf2be', '#1b9ca6', '#0088ff', '#0000a6', ... | bigcode/self-oss-instruct-sc2-concepts |
def find_variable(frame, varname):
"""Find variable named varname in the scope of a frame.
Raise a KeyError when the varname cannot be found.
"""
try:
return frame.f_locals[varname]
except KeyError:
return frame.f_globals[varname] | bigcode/self-oss-instruct-sc2-concepts |
def xml_output_document(request):
"""XML document generated by XSLT transform."""
document = request.param
return document | bigcode/self-oss-instruct-sc2-concepts |
def join_ints(ints):
"""Joins list of intergers into the ordered comma-separated text.
"""
return ','.join(map(str, sorted(ints))) | bigcode/self-oss-instruct-sc2-concepts |
import re
def get_version(galaxy_file):
"""
Get the version from the collection manifest file (galaxy.yml).
In order to avoid the dependency to a yaml package, this is done by
parsing the file with a regular expression.
"""
with open(galaxy_file, 'r') as fp:
ftext = fp.read()
m = ... | bigcode/self-oss-instruct-sc2-concepts |
import re
def getIDfromComment(line):
"""
Get id from comment
Returns 1510862771508 from <!-- 1510862771508 -->
"""
idPattern = re.compile("\d{13,}")
return idPattern.findall(line)[0] | bigcode/self-oss-instruct-sc2-concepts |
def _sample_distribution_over_matrix(rng):
"""Samples the config for a distribution over a matrix.
Args:
rng: np.random.RandomState
Returns:
A distribution over matrix config (containing a tuple with the name and
extra args needed to create the distribution).
"""
# At this point, the choices her... | bigcode/self-oss-instruct-sc2-concepts |
from datetime import datetime
def get_todays_date_obj(obj):
"""Get the date of the daily post and return the date
in %d-%B-%Y format"""
title = obj.title
daily_title = title.split(' ')
todays_date = '{}-{}-{}'.format(daily_title[4].rstrip(','),
daily_title[3], d... | bigcode/self-oss-instruct-sc2-concepts |
def _duration_to_nb_windows(
duration, analysis_window, round_fn=round, epsilon=0
):
"""
Converts a given duration into a positive integer of analysis windows.
if `duration / analysis_window` is not an integer, the result will be
rounded to the closest bigger integer. If `duration == 0`, returns `0`... | bigcode/self-oss-instruct-sc2-concepts |
def dt64_epoch(dt64):
"""
Convert a panda or xarray date/time value represented as a datetime64 object (nanoseconds since 1970) to a float,
representing an epoch time stamp (seconds since 1970-01-01).
:param dt64: panda or xarray datatime64 object
:return epts: epoch time as seconds since 1970-01-0... | bigcode/self-oss-instruct-sc2-concepts |
def viss(t, d):
"""Viscosity of vapour as a function of temperature (deg C) and
density (kg / m3)."""
V1 = 0.407 * t + 80.4
if t <= 350.0: return 1.0e-7 * (V1 - d * (1858.0 - 5.9 * t) * 1.0e-3)
else: return 1.0e-7 * (V1 + d * (0.353 + d * (676.5e-6 + d * 102.1e-9))) | bigcode/self-oss-instruct-sc2-concepts |
def get_aggregated_metrics_from_dict(input_metric_dict):
"""Get a dictionary of the mean metric values (to log) from a dictionary of metric values"""
metric_dict = {}
for metric_name, metric_value in input_metric_dict.items():
metric_dim = len(metric_value.shape)
if metric_dim == 0:
metric_dict[metric_name] =... | bigcode/self-oss-instruct-sc2-concepts |
def to_float(v):
"""Convert a string into a better type.
>>> to_float('foo')
'foo'
>>> to_float('1.23')
1.23
>>> to_float('45')
45
"""
try:
if '.' in v:
return float(v)
else:
return int(v)
except:
return v | bigcode/self-oss-instruct-sc2-concepts |
def get_public_instances(game):
""" Return the instance ids of public instances for the specified game.
Args:
game: The parent Game database model to query for instances.
Returns:
An empty list if game is None. Else, returns a list of the
instance ids of all joinable public instances with game as
... | bigcode/self-oss-instruct-sc2-concepts |
def lift_calc(PPV, PRE):
"""
Calculate lift score.
:param PPV: precision or positive predictive value
:type PPV : float
:param PRE: Prevalence
:type PRE : float
:return: lift score as float
"""
try:
return PPV / PRE
except Exception:
return "None" | bigcode/self-oss-instruct-sc2-concepts |
def change_exclusion_header_format(header):
""" Method to modify the exclusion header format.
ex: content-type to Content-Type"""
if type(header) is list:
tmp_list = list()
for head in header:
tmp = head.split("-")
val = str()
for t in tmp:
... | bigcode/self-oss-instruct-sc2-concepts |
def update_mean(new_data, old_mean, num_data):
"""Compute a new mean recursively using the old mean and new measurement
From the arithmetic mean computed using the n-1 measurements (M_n-1), we
compute the new mean (M_n) adding a new measurement (X_n) with the formula:
M_n = M_n-1 + (X_n - M_n-1)/n
... | bigcode/self-oss-instruct-sc2-concepts |
def quantize(source, steps=32767):
"""
Quantize signal so that there are N steps in the unit interval.
"""
i_steps = 1.0 / steps
return [round(sample * steps) * i_steps for sample in source] | bigcode/self-oss-instruct-sc2-concepts |
def fibonacci(n: int) -> int:
"""Compute the N-th fibonacci number."""
if n in (0, 1):
return 1
return fibonacci(n - 1) + fibonacci(n - 2) | bigcode/self-oss-instruct-sc2-concepts |
def test_pp_model(text, pp_tokenizer, pp_model):
"""Get some paraphrases for a bit of text"""
print("ORIGINAL\n",text)
num_beams = 10
num_return_sequences = 10
batch = pp_tokenizer([text], return_tensors='pt', max_length=60, truncation=True)
translated = pp_model.generate(**batch, num_beams=num_... | bigcode/self-oss-instruct-sc2-concepts |
def none_formatter(error):
"""
Formatter that does nothing, no escaping HTML, nothin'
"""
return error | bigcode/self-oss-instruct-sc2-concepts |
def point_inside_polygon(polygon, p, thresh_val=0):
"""
Returns true if the point p lies inside the polygon (ndarray)
Checks if point lies in a thresholded area
:param polygon: ndarray that represents the thresholded image contour that we want to circle pack
:param p: ndarray 1x2 representing a poi... | bigcode/self-oss-instruct-sc2-concepts |
def np_get_index(ndim,axis,slice_number):
"""
Construct an index for used in slicing numpy array by specifying the
axis and the slice in the axis.
Parameters:
-----------
1. axis: the axis of the array.
2. slice_number: the 0-based slice number in the axis.
3. ndim: the ndim of the ... | bigcode/self-oss-instruct-sc2-concepts |
def leftjust_lines(lines): # 2007 May 25
"""Left justify lines of text.
Lines is a Python list of strings *without* new-line terminators.
The result is a Python list of strings *without* new-Line terminators.
"""
result = [line.strip() for line in lines]
return result | bigcode/self-oss-instruct-sc2-concepts |
def final_metric(low_corr: float, high_corr: float) -> float:
"""Metric as defined on the page
https://signate.jp/competitions/423#evaluation
Args:
low_corr (float): low model spearman
high_corr (float): high model spearman
Returns:
float: final evaluation metric as defi... | bigcode/self-oss-instruct-sc2-concepts |
import json
def _parse_json_file(data):
"""Parse the data from a json file.
Args:
data (filepointer): File-like object containing a Json document,
to be parsed into json.
Returns:
dict: The file successfully parsed into a dict.
Raises:
ValueError: If there was an... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Tuple
def parse_description(description: str) -> Tuple[int, str]:
"""Parse task description into amount and currency."""
raw_amount, currency = description.split(' ')
raw_amount = raw_amount.replace('k', '000')
return int(raw_amount), currency | bigcode/self-oss-instruct-sc2-concepts |
from typing import Mapping
def update(to_update, update_with):
"""
Recursively update a dictionary with another.
:param dict to_update: Dictionary to update.
:param dict update_with: Dictionary to update with.
:return: The first dictionary recursively updated by the second.
:rtype: dict
... | bigcode/self-oss-instruct-sc2-concepts |
def _splitter(value, separator):
"""
Return a list of values from a `value` string using `separator` as list delimiters.
Empty values are NOT returned.
"""
if not value:
return []
return [v.strip() for v in value.split(separator) if v.strip()] | bigcode/self-oss-instruct-sc2-concepts |
def rprpet_point(pet, snowmelt, avh2o_3, precip):
"""Calculate the ratio of precipitation to ref evapotranspiration.
The ratio of precipitation or snowmelt to reference
evapotranspiration influences agdefac and bgdefac, the above- and
belowground decomposition factors.
Parameters:
pet (flo... | bigcode/self-oss-instruct-sc2-concepts |
def form2audio(cldf, mimetype='audio/mpeg'):
"""
Read a media table augmented with a formReference column.
:return: `dict` mapping form ID to audio file.
"""
res = {}
for r in cldf.iter_rows('media.csv', 'id', 'formReference'):
if r['mimetype'] == mimetype:
res[r['formRefere... | bigcode/self-oss-instruct-sc2-concepts |
def get_value_of_bills(denomination, number_of_bills):
"""
The total value of bills you now have.
:param denomination: int - the value of a bill.
:param number_of_bills: int - amount of bills you received.
:return: int - total value of bills you now have
"""
return denomination * number_of... | bigcode/self-oss-instruct-sc2-concepts |
def strip_script(environ):
"""
Strips the script portion of a url path so the middleware works even
when mounted under a path other than root.
"""
path = environ['PATH_INFO']
if path.startswith('/') and 'SCRIPT_NAME' in environ:
prefix = environ.get('SCRIPT_NAME')
if prefix.endsw... | bigcode/self-oss-instruct-sc2-concepts |
def truncateWord32(value):
"""
Truncate an unsigned integer to 32 bits.
"""
return value & 0xFFFFFFFF | bigcode/self-oss-instruct-sc2-concepts |
def _strip_comments_from_pex_json_lockfile(lockfile_bytes: bytes) -> bytes:
"""Pex does not like the header Pants adds to lockfiles, as it violates JSON.
Note that we only strip lines starting with `//`, which is all that Pants will ever add. If
users add their own comments, things will fail.
"""
r... | bigcode/self-oss-instruct-sc2-concepts |
def subcloud_db_model_to_dict(subcloud):
"""Convert subcloud db model to dictionary."""
result = {"id": subcloud.id,
"name": subcloud.name,
"description": subcloud.description,
"location": subcloud.location,
"software-version": subcloud.software_version,
... | bigcode/self-oss-instruct-sc2-concepts |
def remove_non_printable_chars(s):
"""
removes
'ZERO WIDTH SPACE' (U+200B)
'ZERO WIDTH NO-BREAK SPACE' (U+FEFF)
"""
return s.replace(u'\ufeff', '').replace(u'\u200f', '') | bigcode/self-oss-instruct-sc2-concepts |
def diffmean(xl, yl):
"""Return the difference between the means of 2 lists."""
return abs(sum(xl) / len(xl) - sum(yl) / len(yl)) | bigcode/self-oss-instruct-sc2-concepts |
def _multihex (blob):
"""Prepare a hex dump of binary data, given in any common form
including [[str]], [[list]], [[bytes]], or [[bytearray]]."""
return ' '.join(['%02X' % b for b in bytearray(blob)]) | bigcode/self-oss-instruct-sc2-concepts |
def is_disabled(field):
"""
Returns True if fields is disabled, readonly or not marked as editable, False otherwise
"""
if not getattr(field.field, 'editable', True):
return True
if getattr(field.field.widget.attrs, 'readonly', False):
return True
if getattr(field.field.widget.at... | bigcode/self-oss-instruct-sc2-concepts |
def escape_chars(s):
"""
Performs character escaping of comma, pipe and equals characters
"""
return "".join(['\\' + ch if ch in '=|,' else ch for ch in s]) | bigcode/self-oss-instruct-sc2-concepts |
def unordered_types_overall(x_name_type_unord):
"""Create dummies capturing if particular types of unordered vars exit.
Parameters
----------
x_name_type_unord : list of 0,1,2
Returns
-------
type_0, type_1, type_2 : Boolean. Type exist
"""
type_2 = bool(2 in x_name_type_unord)
... | bigcode/self-oss-instruct-sc2-concepts |
def slugify(str_):
"""Remove single quotes, brackets, and newline characters from a string."""
bad_chars = ["'", '[', ']', '\n', '<', '>' , '\\']
for ch in bad_chars:
str_ = str_.replace(ch, '')
return str_ | bigcode/self-oss-instruct-sc2-concepts |
def _extract_image(img, x_off, y_off, max_x, max_y):
"""Returns a subsection of the image
Args:
img(numpy array): the source image (with 2 or 3 size dimensions)
x_off(int): the starting X clip position (0th index of image)
y_off(int): the starting Y clip position (1st index of image)
... | bigcode/self-oss-instruct-sc2-concepts |
def _dict_mixed_empty_parser(v, v_delimiter):
"""
Parse a value into the appropriate form, for a mixed value based column.
Args:
v: The raw string value parsed from a column.
v_delimiter: The delimiter between components of the value.
Returns:
The parsed value, which can either... | bigcode/self-oss-instruct-sc2-concepts |
def calc_ifg_delay(master_delay, slave_delay):
"""Calculate the interferometric delay.
Arguments
---------
master_delay : (n,m) ndarray
Matrix containing the atmospheric delay on the master date.
slave_delay : (n,m) ndarray
Matrix containing the atmospheric delay on the slave date.
... | bigcode/self-oss-instruct-sc2-concepts |
import pathlib
def make_subdirectory(directory, append_name=""):
"""Makes subdirectories.
Parameters
----------
directory : str or pathlib object
A string with the path of directory where subdirectories should be created.
append_name : str
A string to be appended to the directory ... | bigcode/self-oss-instruct-sc2-concepts |
def Kt_real_deph(alpha_liq_deph, alpha_cond_deph, sigma_thermpollution_deph):
"""
Calculates the coefficient of heat transfer (Kt).
Parameters
----------
alpha_liq_deph : float
The coefficent of heat transfer(alpha), [W / (m**2 * degrees celcium)]
alpha_cond_deph : float
The coef... | bigcode/self-oss-instruct-sc2-concepts |
def strip_2tuple(dict):
"""
Strips the second value of the tuple out of a dictionary
{key: (first, second)} => {key: first}
"""
new_dict = {}
for key, (first, second) in dict.items():
new_dict[key] = first
return new_dict | bigcode/self-oss-instruct-sc2-concepts |
def create_dict(list1, list2, key1, key2):
"""Create list of dictionaries from two lists
"""
list_dict = []
for i in range(len(list1)):
dictionary = {key1 : list1[i], key2 : list2[i]}
list_dict.append(dictionary)
return list_dict | bigcode/self-oss-instruct-sc2-concepts |
def _num_starting_hashes(line: str) -> int:
"""Return the number of hashes (#) at the beginning of the line."""
if not line:
return 0
for n, char in enumerate(line, start=0):
if char != "#":
return n
return len(line) | bigcode/self-oss-instruct-sc2-concepts |
def greedy_coloring(adj):
"""Determines a vertex coloring.
Args:
adj (dict): The edge structure of the graph to be colored.
`adj` should be of the form {node: neighbors, ...} where
neighbors is a set.
Returns:
dict: the coloring {node: color, ...}
dict: the ... | bigcode/self-oss-instruct-sc2-concepts |
def position_side_formatter(side_name):
"""
Create a formatter that extracts and formats the long or short side from a
Position
Args:
side_name: "long" or "short" indicating which side of the position to
format
"""
def f(p):
"""The formatting function for the ... | bigcode/self-oss-instruct-sc2-concepts |
def get_mean_score(rating_scores):
"""Compute the mean rating score given a list.
Args:
rating_scores: a list of rating scores.
Returns:
The mean rating.
"""
return sum(rating_scores) / len(rating_scores) | bigcode/self-oss-instruct-sc2-concepts |
def tstv(ts, tv):
"""
Calculate ts/tv, and avoid division by zero error
"""
try:
return round(float(ts) / float(tv), 4)
except ZeroDivisionError:
return 0 | bigcode/self-oss-instruct-sc2-concepts |
def is_convolution_or_linear(layer):
""" Return True if `layer` is a convolution or a linear layer
"""
classname = layer.__class__.__name__
if classname.find('Conv') != -1:
return True
if classname.find('Linear') != -1:
return True
return False | bigcode/self-oss-instruct-sc2-concepts |
import requests
from bs4 import BeautifulSoup
def get_chapters_raw(page_url):
"""Return BeautifulSoup object of chapter page"""
r = requests.get(page_url)
return BeautifulSoup(r.text, "lxml") | bigcode/self-oss-instruct-sc2-concepts |
def zero_if_less_than(x, eps):
"""Return 0 if x<eps, otherwise return x"""
if x < eps:
return 0
else:
return x | bigcode/self-oss-instruct-sc2-concepts |
import math
def date_to_jd(year,month,day):
"""
Convert a date to Julian Day.
Algorithm from 'Practical Astronomy with your Calculator or Spreadsheet',
4th ed., Duffet-Smith and Zwart, 2011.
Parameters
----------
year : int
Year as integer. Years preceding 1 A.D. should be 0 ... | bigcode/self-oss-instruct-sc2-concepts |
def create_masked_lm_predictions_force_last(tokens):
"""Creates the predictions for the masked LM objective."""
last_index = -1
for (i, token) in enumerate(tokens):
if token == "[CLS]" or token == "[PAD]" or token == '[NO_USE]':
continue
last_index = i
assert last_index > 0... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Tuple
def deserialize_ecdsa_recoverable(signature: bytes) -> Tuple[int, int, int]:
"""
deserialize recoverable ECDSA signature from bytes to (r, s, recovery_id)
"""
assert len(signature) == 65, 'invalid length of recoverable ECDSA signature'
recovery_id = signature[-1]
asser... | bigcode/self-oss-instruct-sc2-concepts |
def semi_loss_func(ac, full_ob, semi_dataset, is_relative_actions=False):
"""
get the L2 loss between generated actions and semi supervised actions
:param ac: the semi supervised actions
:param full_ob: the full observations of the semi supervised dataset
:param semi_dataset: the semi supervised dat... | bigcode/self-oss-instruct-sc2-concepts |
def index_generation(crt_i, max_n, N, padding='reflection'):
"""Generate an index list for reading N frames from a sequence of images
Args:
crt_i (int): current center index
max_n (int): max number of the sequence of images (calculated from 1)
N (int): reading N frames
padding (s... | bigcode/self-oss-instruct-sc2-concepts |
def NoTestRunnerFiles(path, dent, is_dir):
"""Filter function that can be passed to FindCFiles or FindHeaderFiles in
order to exclude test runner files."""
# NOTE(martinkr): This prevents .h/.cc files in src/ssl/test/runner, which
# are in their own subpackage, from being included in boringssl/BUILD files.
re... | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
def chunk(s: str, n: int = 80) -> List[str]:
"""Chunk string into segments of specified length.
>>> chunk(('wordsX' * 5), 11)
['wordsXwords', 'XwordsXword', 'sXwordsX']
>>> chunk('x', 80)
['x']
"""
return [s[i:i + n] for i in range(0, len(s), n)] | bigcode/self-oss-instruct-sc2-concepts |
import math
def dist(p1, p2):
"""
Compute euclidean distance
:param p1: first coordinate tuple
:param p2: second coordinate tuple
:return: distance Float
"""
return math.sqrt((p2[0] - p1[0]) ** 2 + (p1[1] - p2[1]) ** 2) | bigcode/self-oss-instruct-sc2-concepts |
def get_answer(s):
"""Given a choice (A, B, C, D) this function returns the integer index representation
of that choice (0, 1, 2, 3)"""
return 'ABCD'.index(s) | bigcode/self-oss-instruct-sc2-concepts |
import click
def ensure_valid_type(node_type_choices: click.Choice, node_type: str) -> str:
"""Uses click's convert_type function to check the validity of the
specified node_type. Re-raises with a custom error message to ensure
consistency across click versions.
"""
try:
click.types.conver... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def _mean_plus_r_var(data: torch.Tensor, ratio: float = 0, **kwargs):
"""
Function caclulates mean + ratio * stdv.
and returns the largest of this value and the smallest element
in the list (can happen when ratio is negative).
"""
return max(
data.min().item(),
dat... | bigcode/self-oss-instruct-sc2-concepts |
import base64
def b64_to_utf8_decode(b64_str):
"""Decode base64 string to UTF-8."""
return base64.urlsafe_b64decode(b64_str).decode('utf-8') | bigcode/self-oss-instruct-sc2-concepts |
def roll(l):
"""rolls a list to the right
e.g.: roll([0,1,1]) => [1,0,1]
"""
tmp1, tmp2 = l[:-1], l[-1]
l[1:] = tmp1
l[0] = tmp2
return l | bigcode/self-oss-instruct-sc2-concepts |
def std_pres(elev):
"""Calculate standard pressure.
Args:
elev (float): Elevation above sea-level in meters
Returns:
float: Standard Pressure (kPa)
"""
return 101.325 * (((293.0 - 0.0065 * elev) / 293.0) ** 5.26) | bigcode/self-oss-instruct-sc2-concepts |
def add_obs_prob_to_dict(dictionary, obs, prob):
"""
Updates a dictionary that tracks a probability distribution over observations.
"""
obs_str = obs.tostring()
if obs_str not in dictionary:
dictionary[obs_str] = 0
dictionary[obs_str] += prob
return dictionary | bigcode/self-oss-instruct-sc2-concepts |
def sphere_to_plane_car(az0, el0, az, el):
"""Project sphere to plane using plate carree (CAR) projection.
The target point can be anywhere on the sphere. The output (x, y)
coordinates are likewise unrestricted.
Please read the module documentation for the interpretation of the input
parameters an... | bigcode/self-oss-instruct-sc2-concepts |
import math
def sqrt(value):
"""Returns the square root of a value"""
return math.sqrt(value) | bigcode/self-oss-instruct-sc2-concepts |
def cov_files_by_platform(reads, assembly, platform):
"""
Return a list of coverage files for a given sequencing platform.
"""
accessions = []
if reads is not None:
accessions += [accession for accession in reads if reads[accession]['platform'] == platform]
return list(map(lambda sra: "%... | bigcode/self-oss-instruct-sc2-concepts |
from datetime import datetime
def get_time_delta(start_time: str, end_time: str):
"""Returns the difference between two times in minutes"""
t1 = datetime.strptime(start_time, "%Y-%m-%d_%H-%M-%S")
t2 = datetime.strptime(end_time, "%Y-%m-%d_%H-%M-%S")
delta = t2 - t1
return int(delta.seconds / 60) | bigcode/self-oss-instruct-sc2-concepts |
def symmetric_closure_function(rel):
"""
Function to determine the symmetric closure of a relation
:param rel: A list that represents a relation
:return: The symmetric closure of relation rel
"""
return rel + [(y, x) for (x, y) in rel if (y, x) not in rel] | bigcode/self-oss-instruct-sc2-concepts |
import torch
def get_pyg_edge_index(graph, both_dir=True):
"""
Get edge_index for an instance of torch_geometric.data.Data.
Args:
graph: networkx Graph
both_dir: boolean; whether to include reverse edge from graph
Return:
torch.LongTensor of edge_index with size [2, num_e... | bigcode/self-oss-instruct-sc2-concepts |
def ctypes_shape(x):
"""Infer shape of a ctypes array."""
try:
dim = x._length_
return (dim,) + ctypes_shape(x[0])
except AttributeError:
return () | bigcode/self-oss-instruct-sc2-concepts |
def get_magicc6_to_magicc7_variable_mapping(inverse=False):
"""Get the mappings from MAGICC6 to MAGICC7 variables.
Note that this mapping is not one to one. For example, "HFC4310", "HFC43-10" and
"HFC-43-10" in MAGICC6 both map to "HFC4310" in MAGICC7 but "HFC4310" in
MAGICC7 maps back to "HFC4310".
... | bigcode/self-oss-instruct-sc2-concepts |
def assert_train_test_temporal_consistency(t_train, t_test):
"""Helper function to assert train-test temporal constraint (C1).
All objects in the training set need to be temporally anterior to all
objects in the testing set. Violating this constraint will positively bias
the results by integrating "fut... | bigcode/self-oss-instruct-sc2-concepts |
def _layout_column_width(col):
"""
Returns the logical column width of a column
"""
column_equivs = [pi.column_equiv for pi in col.presinfo if pi.column_equiv is not None]
if len(column_equivs) > 0:
# assume user has not done something silly like put
# *2* column_equiv classes on a c... | bigcode/self-oss-instruct-sc2-concepts |
def get_one_col_str(i_col, line):
"""
extract the column index in line
i_col: index of column
line: string
"""
col_split = '\t'
return line.split(col_split)[i_col] | bigcode/self-oss-instruct-sc2-concepts |
import spwd
def unix_crypted_shadow_password(username):
"""
Requests the crypted shadow password on unix systems for a specific user and returns it.
"""
crypted_password = spwd.getspnam(username)[1]
return crypted_password | bigcode/self-oss-instruct-sc2-concepts |
from typing import Tuple
import re
def _lex_whitespace(header: str) -> Tuple[str, str]:
"""
>>> _lex_whitespace(" \\n a")
('', 'a')
>>> _lex_whitespace(" abc")
('', 'abc')
>>> _lex_whitespace("a ")
('', 'a ')
"""
whitespace_match = re.match(r"\s+", header)
if not whitespace_ma... | bigcode/self-oss-instruct-sc2-concepts |
def compute_cchalf(mean, var):
"""
Compute the CC 1/2 using the formular from Assmann, Brehm and Diederichs 2016
:param mean: The list of mean intensities
:param var: The list of variances on the half set of mean intensities
:returns: The CC 1/2
"""
assert len(mean) == len(var)
n = len(... | bigcode/self-oss-instruct-sc2-concepts |
def attrFinder(attrib, attribString):
"""Easy function to pull attributes from column 8 of gtf files"""
for entry in attribString.split(";"):
if entry.lstrip().startswith(attrib):
return entry.lstrip().split(" ")[1][1:-1]
return None | bigcode/self-oss-instruct-sc2-concepts |
import warnings
def _method_cache_key_generator(*args, **kwargs) -> int:
"""A cache key generator implementation for methods.
This generator does not implement any hashing for keyword arguments.
Additionally, it skips the first argument provided to the function,
which is assumed to be a class instanc... | bigcode/self-oss-instruct-sc2-concepts |
def _mst_path(csgraph, predecessors, start, end):
"""Construct a path along the minimum spanning tree"""
preds = predecessors[start]
path = [end]
while end != start:
end = preds[start, end]
path.append(end)
return path[::-1] | bigcode/self-oss-instruct-sc2-concepts |
def kewley_sf_nii(log_nii_ha):
"""Star forming classification line for log([NII]/Ha)."""
return 0.61 / (log_nii_ha - 0.05) + 1.3 | bigcode/self-oss-instruct-sc2-concepts |
import math
def calc_distance(ij_start, ij_end, R):
""""
Calculate distance from start to end point
Args:
ij_start: The coordinate of origin point with (0,0) in the upper-left corner
ij_end: The coordinate of destination point with (0,0) in the upper-left corner
R: Map resolution ... | bigcode/self-oss-instruct-sc2-concepts |
from datetime import datetime, timedelta
def ldap_to_datetime(timestamp: float):
"""
Takes an LDAP timestamp and converts it to a datetime object
"""
return datetime(1601, 1, 1) + timedelta(timestamp/10000000) | bigcode/self-oss-instruct-sc2-concepts |
def parse_dss_bus_name(dss_bus_name: str, sep='.') -> str:
"""
Given a bus name string that may include phase from opendss, returns just
the busname.
Assumes that dss appends bus names with phases, separated by '.'
Ex: 'sourcebus.1.2.3' -> 'sourcebus'
"""
return dss_bus_name.split(sep)[0] | bigcode/self-oss-instruct-sc2-concepts |
import re
def get_version(filename='canaveral/__init__.py'):
""" Extract version information stored as a tuple in source code """
version = ''
with open(filename, 'r') as fp:
for line in fp:
m = re.search("__version__ = '(.*)'", line)
if m is not None:
versi... | bigcode/self-oss-instruct-sc2-concepts |
def rk4(x,t,tau,derivsRK,**kwargs):
"""
Runge-Kutta integrator (4th order). Calling format derivsRK(x,t,**kwargs).
Inputs:
x current value of dependent variable
t independent variable (usually time)
tau step size (usually timestep)
derivsRK ri... | bigcode/self-oss-instruct-sc2-concepts |
import math
def cos(X, max_order=30):
"""
A taylor series expansion for cos
The parameter `max_order` is the maximum order of the taylor series to use
"""
op = 1 + 0*X
X2 = X * X
X2n = 1 + 0*X
for n in range(1, max_order):
X2n = X2n*X2
op = op + ((-1) ** (n) / math.gamm... | bigcode/self-oss-instruct-sc2-concepts |
def fib(n):
""" Assumes n an int >= 0
Returns Fibonacci of n"""
if n == 0 or n == 1:
return 1
else:
return fib(n-1) + fib(n-2) | bigcode/self-oss-instruct-sc2-concepts |
def _unsplit_name(name):
"""
Convert "this_name" into "This Name".
"""
return " ".join(s.capitalize() for s in name.split('_')) | 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.