seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
def first_where(L,val):
"""
First index of list L that equals val
"""
for pos,l in enumerate(L):
if l == val:
return pos
return None | bigcode/self-oss-instruct-sc2-concepts |
def join_anchor_base_score(anchor_df, base_df):
"""Join anchor DataFrame with Base LFCs on anchor_guide
Parameters
----------
anchor_df: DataFrame
DataFrame with anchor and target guides
base_df: DataFrame
Base LFC DataFrame
Returns
-------
DataFrame
"""
joined_... | bigcode/self-oss-instruct-sc2-concepts |
def _IsSuccessfulDmlOrDdlJob(printable_job_info):
"""Returns True iff the job is successful and is a DML/DDL query job."""
return ('Affected Rows' in printable_job_info or
'DDL Operation Performed' in printable_job_info) | bigcode/self-oss-instruct-sc2-concepts |
def merge_sort(items):
""" the merge sort algorithm takes in an unsorted list of numbers.
returns a list in ascending order.
Parameters
----------
items : list
list of unordered numbers
Returns
-------
list
list of elements in items in ascending order
"""
d... | bigcode/self-oss-instruct-sc2-concepts |
from tabulate import tabulate
def list_to_html(data, has_header=True, table_format=None):
"""
Convenience function to convert tables to html for attaching as message text.
:param data: Table data
:type data: list of lists
:param has_header: Flag whether data contains a header in the first row.
... | bigcode/self-oss-instruct-sc2-concepts |
def seconds_to_minutes(seconds):
"""
Returns a number of seconds formatted as minutes:seconds.
"""
return '{}:{:0>2}'.format(int(seconds / 60), seconds % 60) | bigcode/self-oss-instruct-sc2-concepts |
def has_no_e( word ):
"""Retruns True if the given word have no 'e', False otherwise.
"""
for i in word:
if i == 'e':
return False
return True | bigcode/self-oss-instruct-sc2-concepts |
def get_materials_dict(lm):
"""Build the list of coordinates corresponding to each material"""
d = {}
for x in range(lm.nx):
for y in range(lm.ny):
mat = lm.cells[x][y].material.name.lower()
if mat in d:
d[mat].append((x,y))
else:
d... | bigcode/self-oss-instruct-sc2-concepts |
def return_index_name(collection_name, doc_type_str, sep="__"):
"""Return formatted index string"""
index_name = f"{collection_name}{sep}{doc_type_str}".lower()
return index_name | bigcode/self-oss-instruct-sc2-concepts |
def cTA(H, DIC, BT, TP, TSi, TS, TF, Ks, mode="multi"):
"""
Calculate Alkalinity. H is on Total scale.
Returns
-------
If mode == 'multi' returns TA, CAlk, PAlk, SiAlk, OH
else: returns TA
"""
# negative
Denom = H ** 2 + Ks.K1 * H + Ks.K1 * Ks.K2
CAlk = DIC * Ks.K1 * (H + 2 * Ks... | bigcode/self-oss-instruct-sc2-concepts |
def process_somaticsniper_vcf(job, somaticsniper_vcf, work_dir, univ_options):
"""
Process the SomaticSniper vcf for accepted calls. Since the calls are pre-filtered, we just
obtain the file from the file store and return it.
:param toil.fileStore.FileID somaticsniper_vcf: fsID for a SomaticSniper gen... | bigcode/self-oss-instruct-sc2-concepts |
def _split_divisible(num, num_ways, divisible_by=8):
"""Evenly splits num, num_ways so each piece is a multiple of divisible_by."""
assert num % divisible_by == 0
assert num / num_ways >= divisible_by
# Note: want to round down, we adjust each split to match the total.
base = num // num_ways // divisible_by *... | bigcode/self-oss-instruct-sc2-concepts |
def array_split(ary,n):
"""
>>> data = [1,2,3,4,5]
>>> array_split(data,3)
[[1, 2], [3, 4], [5]]
>>> grps = array_split(range(0,1121),8)
>>> total_len = 0
>>> for grp in grps: total_len += len(grp)
>>> assert(total_len == len(range(0,1121)))
"""
step = int(round(len(ary)/float(n)... | bigcode/self-oss-instruct-sc2-concepts |
def objdict_to_dict(objdict):
""" Convert an objdict structure into a dict structure
Args:
obj (objdict): the objdict to convert
Returns:
dict: the objdict as standard dictionnary
"""
d = {}
if objdict:
for k, v in objdict.items():
if type(v) == dict:
... | bigcode/self-oss-instruct-sc2-concepts |
def type_check(name, correct_type):
"""
decorator function for checking correctness of input type
name: attribute name --> str
correct_type: correct_type of name attribute --> type
Procedure:
1. call type_check first,return prop setter,and convert name to private attribute. Store private_name &... | bigcode/self-oss-instruct-sc2-concepts |
def _str(uni):
"""
Make inbound a string
Encoding to utf-8 if needed
"""
try:
return str(uni)
except:
return uni.encode('utf-8') | bigcode/self-oss-instruct-sc2-concepts |
def create_query(keyword, start_date, end_date, max_results) -> dict:
"""
Creates the params part in the GET request
Parameters
----------
keyword : str
The key word/words that you want to be included in your search
start_date : str
The start of the time period that you would li... | bigcode/self-oss-instruct-sc2-concepts |
def clean_text(identifica, ementa, fulltext):
"""
Given a DOU article titles `identifica` and an abstract `ementa`,
remove the first title in `identifica`, `ementa` and the hard-coded
footnote from the full text of the DOU article `fulltext`.
"""
# ATTENTION: this code should reproduce the clea... | bigcode/self-oss-instruct-sc2-concepts |
def is_basestring(s):
"""Return True for any string type (for str/unicode on Py2 and bytes/str on Py3)."""
return isinstance(s, (str, bytes)) | bigcode/self-oss-instruct-sc2-concepts |
def _hc2rgb1(h, c):
"""
Takes the hue and chroma and returns the helper rgb1.
Parameters
----------
h float The hue in degrees
c float The chroma in [0, 1]
"""
try:
h = float(h)
c = float(c)
except ValueError:
raise ValueError("h (%s) and c (%s) must be (convertible to) floats" %
(str(h), str(c)... | bigcode/self-oss-instruct-sc2-concepts |
def is_segment_tokenized(segment):
"""Return True, iff the segment is already tokenized.
Examples
--------
>>> s = ('<segment id="1"><sign pos="ART">Die</sign>'
... '<sign pos="NN">Antwort</sign></segment>')
>>> is_segment_tokenized(seg)
True
>>> seg = etree.fromstring('<segment i... | bigcode/self-oss-instruct-sc2-concepts |
def int_to_mask(mask_int):
""" Convert int to mask
Args:
mask_int ('int'): prefix length is convert to mask
Returns:
mask value
"""
bin_arr = ["0" for i in range(32)]
for i in range(int(mask_int)):
bin_arr[i] = "1"
tmpmask = ["".join(bin_arr[i * ... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def _coordinate_grid(dims, align_corners=False):
"""
Creates a homogenous coordinate system.
Args:
dims (Tuple[int*]): height / width or depth / height / width
align_corners (bool):
returns a grid where the left and right corners assigned to the
extre... | bigcode/self-oss-instruct-sc2-concepts |
def str_to_orientation(value, reversed_horizontal=False, reversed_vertical=False):
"""Tries to interpret a string as an orientation value.
The following basic values are understood: ``left-right``, ``bottom-top``,
``right-left``, ``top-bottom``. Possible aliases are:
- ``horizontal``, ``horiz``, ``h... | bigcode/self-oss-instruct-sc2-concepts |
def is_valid_pid(value: str) -> bool:
"""
Return if value is a valid pid (passport id).
Parameter
---------
value: str
a pid.
Return
------
bool
True if pid is valid, False othewise.
"""
return len(value) == 9 and all((char.isdigit()) for char in value) | bigcode/self-oss-instruct-sc2-concepts |
def swap_columns(df, col1, col2):
"""Swaps the two given columns of the DataFrame."""
col_list = list(df.columns)
a, b = col_list.index(col1), col_list.index(col2)
col_list[b], col_list[a] = col_list[a], col_list[b]
return df[col_list] | bigcode/self-oss-instruct-sc2-concepts |
def is_value_1(for_):
"""check if for_["value"] == 1"""
v = for_.get("value", None)
return v == 1 | bigcode/self-oss-instruct-sc2-concepts |
def find_first_list_element_above(a_list, value):
"""
Simple method to return the index of the first element of a list that is greater than a specified value.
Args:
a_list: List of floats
value: The value that the element must be greater than
"""
if max(a_list) <= value:
Val... | bigcode/self-oss-instruct-sc2-concepts |
def scale(value):
"""Scale an value from 0-65535 (AnalogIn range) to 0-255 (RGB range)"""
return int(value / 65535 * 255) | bigcode/self-oss-instruct-sc2-concepts |
def date_to_iso8601(date):
"""Converts a date to an ISO 8601 date"""
return '%s-%02d-%02d' % (date.year, date.month, date.day) | bigcode/self-oss-instruct-sc2-concepts |
def depth(data):
"""
Get the depth of a dictionary
Args:
data: data in dictionary type
Returns: the depth of a dictionary
"""
if isinstance(data, dict):
return 1 + (max(map(depth, data.values())) if data else 0)
return 0 | bigcode/self-oss-instruct-sc2-concepts |
import pickle
def load_obj(name: str):
"""Load object as a pickle file to a given path."""
with open(f'{name}.pkl', 'rb') as f:
return pickle.load(f) | bigcode/self-oss-instruct-sc2-concepts |
import time
def timeit(do=True, name=""):
"""
Decorator to print the time that the function has taken to execute.
"""
def inner0(function):
if not do: return function
def inner(*args, **kw):
start = time.time()
val = function(*args, **kw)
end = time.... | bigcode/self-oss-instruct-sc2-concepts |
def gmail_timestamp_to_epoch_seconds(epoch_time_ms: int) -> int:
"""
Convert GMail `internalDate` into epoch time in seconds.
Arguments:
epoch_time_ms {int} -- the GMail `internalDate` epoch time which is in milliseconds.
Returns:
int -- epoch time in seconds
"""
epoch_time_sec... | bigcode/self-oss-instruct-sc2-concepts |
def derivative_polynomial_latitude(lon_norm, lat_norm, alt_norm, coeff):
"""
Compute latitude derivative polynomial equation
:param lon_norm: Normalized longitude position
:type lon_norm: float 64
:param lat_norm: Normalized latitude position
:type lat_norm: float 64
:param alt_norm: Normal... | bigcode/self-oss-instruct-sc2-concepts |
from io import StringIO
import contextlib
def format_check(file_or_dir):
"""Perform format and return True if changes were made (False otherwise)."""
capture = StringIO()
with contextlib.redirect_stderr(capture):
format(file_or_dir)
output = capture.getvalue()
made_changes = any(["file ref... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Iterable
import functools
import operator
def _prod(vs: Iterable[float]) -> float:
"""Product function."""
return functools.reduce(operator.mul, vs, 1) | bigcode/self-oss-instruct-sc2-concepts |
def sizeof_fmt(size, binary=True, separator=' ', suffix='B', digits=2):
"""
takes a *size* (in bytes) and convert it in a human readable format.
:param size: size in bytes
:param digits: amount of decimals for any number
:param binary: `True` for binary (:math:`2^x`) or `False` for decimal (:math:`... | bigcode/self-oss-instruct-sc2-concepts |
def sort_numbers(nums):
"""
Sorts an array of numbers.
:param nums: array of integers.
:return: sorted array.
"""
if nums:
return sorted(nums)
return [] | bigcode/self-oss-instruct-sc2-concepts |
def split_array_half(array):
"""
Splits an array like object in half, into two arrays.
If of an odd length, the first half will be larger by 1.
:param array: array like object to be split in half
:return: Two arrays (first_half and second_half)
"""
midpoint = len(array) // 2
first_half ... | bigcode/self-oss-instruct-sc2-concepts |
def clean_stix_data(data):
""" Clean stix data from unwanted characters """
return data.replace("\n", "")\
.replace("{", "{{")\
.replace("}", "}}")\
.replace("”","\"")\
.replace("“","\"") | bigcode/self-oss-instruct-sc2-concepts |
def contains_no_complete_reductions(reductions):
"""Checks whether reductions contains a reduction with the empty word."""
for reduction in reductions:
if reduction[-1] == "":
return False
return True | bigcode/self-oss-instruct-sc2-concepts |
import copy
def clone(obj):
"""Clone the object
@param obj: object to be cloned
@return object cloned.
"""
return copy.copy(obj) | bigcode/self-oss-instruct-sc2-concepts |
def quaternionMsgToTuple(msg):
"""Helper function for converting a quaternion msg to a tuple"""
return (msg.x, msg.y, msg.z, msg.w) | bigcode/self-oss-instruct-sc2-concepts |
def _do_magick_convert_enlighten_border(width, height):
"""
Build the command line arguments to enlighten the border in four regions.
:param int width: The width of the image.
:param int height: The height of the image.
:return: Command line arguments for imagemagicks’ `convert`.
:rtype: list
... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Union
def any_to_int(any: Union[None, str]) -> int:
"""
Convert int string to integer. if this value is `None`, return `0`
Args:
any (Union[None, str]): value to convert
Returns:
int: converted integer
"""
if any is None:
return 0
return int(any) | bigcode/self-oss-instruct-sc2-concepts |
def args_dict_split(all_arguments):
"""
This functions split the super set of arguments to smaller dictionaries
all_arguments: Dictionary
All input arguments parsed
return: Dictionary, Dictionary, Dictionary
We return four dictionaries for init, script, spark arguments, singlenode arguments
... | bigcode/self-oss-instruct-sc2-concepts |
def fake_urldelete(c_client, url, headers):
"""
A stub delete_status() implementation that returns True
"""
return True | bigcode/self-oss-instruct-sc2-concepts |
def fn1Test(string, outputFile):
"""
Function appends the next character after the last character in the given
string to the string, writes the string to a file, and returns it. For
example, if string is "AB", we will write and return "ABC".
"""
rV = string + chr(ord(string[-1]) + 1)
with o... | bigcode/self-oss-instruct-sc2-concepts |
def _get_attention_sizes(resnet_size):
"""The number of block layers used for the Resnet model varies according
to the size of the model. This helper grabs the layer set we want, throwing
an error if a non-standard size has been selected.
"""
choices = {
18: [False, [False, True], [True, False], False],... | bigcode/self-oss-instruct-sc2-concepts |
def load_sum(sum_file):
"""
*.sum file is the catalog summary file after Hyperinverse.
This function returns a dict:
-key is event id
-value is an array with below component:
--Str format event time "yyyymmddhhmmss**", also the event folder.
--event longitude
... | bigcode/self-oss-instruct-sc2-concepts |
def echo(**kwargs):
"""Can take any keyword argument and prints its name and value"""
for k, v in kwargs.items():
print('**', k, '=', v)
return kwargs | bigcode/self-oss-instruct-sc2-concepts |
from datetime import datetime
def parse_datetime(s, fmt='%Y%m%d%H%M%S'):
"""
>>> parse_datetime('20170403153428')
datetime.datetime(2017, 4, 3, 15, 34, 28)
>>> parse_datetime('2017-04-03T15:34:28', fmt='%Y-%m-%dT%H:%M:%S')
datetime.datetime(2017, 4, 3, 15, 34, 28)
"""
return datetime.strp... | bigcode/self-oss-instruct-sc2-concepts |
def _str_to_bool(string):
"""
Converts command line boolean string to python boolean
:param string: The command line string
:return: The boolean interpretation of the string
"""
return string.lower() in ("yes", "true", "t", "1") | bigcode/self-oss-instruct-sc2-concepts |
import re
def _triple_under_to_dots(astring):
"""Convert all instances of '___' to '.'."""
return re.sub(r'___', '.', astring) | bigcode/self-oss-instruct-sc2-concepts |
def generate_codex(lexicon, inverse_codex=False):
"""
Given a list of words, creates a codex of unique numeric keys assigned to the words.
Example:
input: ['boy', 'apple', 'dog', 'cat']
output: {'apple': 0, 'boy': 1, 'cat': 2, 'dog': 3}
Input:
lexicon: (list) List of strings, c... | bigcode/self-oss-instruct-sc2-concepts |
import math
def LinEx(y: int, est: int):
"""
A function that return the error for a given estimation of the number of calls
:param y: truth
:param est: estimation (ŷ in the folowing formula)
:return: LinEx(y, ŷ) = exp[α(y − ŷ)] − α(y − ŷ) − 1
"""
alpha = 0.1
prod = alpha * (y - est)
... | bigcode/self-oss-instruct-sc2-concepts |
import copy
import random
def nx_color_spread(init_pt, graph,maxtsteps):
""" Function to perform the random simulation of spreading the GHZ state on
a weighted graph
Parameters
----------
init_pt, any type:
Label for the initial point we are spreading from. Should be present in
th... | bigcode/self-oss-instruct-sc2-concepts |
def AZ2pdg(A, Z):
"""Conversion of nucleus with mass A and chage Z
to PDG nuclear code"""
# 10LZZZAAAI
pdg_id = 1000000000
pdg_id += 10*A
pdg_id += 10000*Z
return pdg_id | bigcode/self-oss-instruct-sc2-concepts |
import torch
def farthest_point_sample(x, npoint):
"""
Input:
xyz: pointcloud data, [B, N, C]
npoint: number of samples
Return:
centroids: sampled pointcloud data, [B, npoint, C]
"""
B, N, C = x.shape
S = npoint
y = torch.zeros(B, S, C).cuda()
distance = torch.o... | bigcode/self-oss-instruct-sc2-concepts |
import inspect
def _get_frame_args(frame):
"""Get the formatted arguments and class (if available) for a frame"""
arginfo = inspect.getargvalues(frame)
try:
if not arginfo.args:
return '', None
# There have been reports from the field of python 2.6 which doesn't
# return a na... | bigcode/self-oss-instruct-sc2-concepts |
def attribute(key, value):
"""
Makes an attribute for lxml.
"key"="value"
:param str key: key of the attribute
:param str value: value of the attribute
:return dict attr: attribute for lxml
"""
attr = {key: value}
return attr | bigcode/self-oss-instruct-sc2-concepts |
from textwrap import dedent
def map_strings_to_line_numbers(module):
"""
Walk ``module.ast``, looking at all string literals. Return a map from
string literals to line numbers (1-index).
:rtype:
``dict`` from ``str`` to (``int``, ``str``)
"""
d = {}
for field in module.block.string... | bigcode/self-oss-instruct-sc2-concepts |
def _match_authorizables(base_authorizables, authorizables):
"""
Method to check if authorizables (entity in CDAP) is contained (the children) of base_authorizables
If so, base_authorizables should be exactly the same as the leading part of authorizables
:return: bool: True if match else False
"""
return au... | bigcode/self-oss-instruct-sc2-concepts |
def processor(document: dict) -> dict:
"""
The default document processor for job documents. Transforms projected job documents to a structure that can be
dispatches to clients.
1. Removes the ``status`` and ``args`` fields from the job document.
2. Adds a ``username`` field.
3. Adds a ``create... | bigcode/self-oss-instruct-sc2-concepts |
def is_solvable_seed(seed):
"""Returns True if the given seed would generate a solvable pirellone instance, False otherwise."""
# We reserve those seed divisible by 3 to the NOT solvable instances
return (seed % 3) != 0 | bigcode/self-oss-instruct-sc2-concepts |
def clean_string(string: str) -> str:
"""
Removes control characters from a string.
>>> clean_string('This is a sentence\\r with newline.')
'This is a sentence with newline'
>>> clean_string('')
''
>>> clean_string(' This is a sentence\\r with. newline. ')
'This is a sentence with. n... | bigcode/self-oss-instruct-sc2-concepts |
import sqlite3
def fetch_naming_prefix(database):
""" Get naming prefix from the database run_info table """
conn = sqlite3.connect(database)
conn.row_factory = sqlite3.Row
cursor = conn.cursor()
cursor.execute("SELECT value FROM run_info WHERE item = 'idprefix'")
prefix = cursor.fetchone()[0]... | bigcode/self-oss-instruct-sc2-concepts |
def call_sig(args, kwargs):
"""Generates a function-like signature of function called with certain parameters.
Args:
args: *args
kwargs: **kwargs
Returns:
A string that contains parameters in parentheses like the call to it.
"""
arglist = [repr(x) for x in args]
arglist... | bigcode/self-oss-instruct-sc2-concepts |
import cmath
def is_integral(x):
"""Return whether the argument is equal to its integer part."""
if isinstance(x, complex):
if x.imag:
return False
x = x.real
return not cmath.isinf(x) and not cmath.isnan(x) and x == int(x) | bigcode/self-oss-instruct-sc2-concepts |
def parse_claim(claim):
"""
Parse a line of input
Example claim:
#1 @ 861,330: 20x10
"""
tokens = claim.split(" ")
claim_id = int(tokens[0][1:])
(offset_x, offset_y) = tokens[2].split(',')
offset_x = int(offset_x)
offset_y = int(offset_y[:-1])
(width, height) = tokens[3].sp... | bigcode/self-oss-instruct-sc2-concepts |
import ast
def matches_attr(node, name):
"""Determines if the ``ast.Call`` node points to an ``ast.Attribute`` node with a matching name.
Args:
node (ast.Call): a node that represents a function call. For more,
see https://docs.python.org/3/library/ast.html#abstract-grammar.
name ... | bigcode/self-oss-instruct-sc2-concepts |
def delete_comma(value):
""" Returns a string without its final comma."""
items = value.split(',')
last = items.pop()
return '%s%s' % (','.join(items), last) | bigcode/self-oss-instruct-sc2-concepts |
import pprint
def _get_column_index(i, inputs):
"""
Taken from https://github.com/onnx/sklearn-onnx/blob/9939c089a467676f4ffe9f3cb91098c4841f89d8/skl2onnx/common/utils.py#L50.
Returns a tuples (variable index, column index in that variable).
The function has two different behaviours, one when *i* (col... | bigcode/self-oss-instruct-sc2-concepts |
import networkx
def walls_to_graph(walls):
"""Return a networkx Graph object given the walls of a maze.
Parameters
----------
walls : list[(x0,y0), (x1,y1), ...]
a list of wall coordinates
Returns
-------
graph : networkx.Graph
a networkx Graph representing the free squ... | bigcode/self-oss-instruct-sc2-concepts |
def dict2xml(dictionary, root="topsApp", topcomp="topsinsar"):
"""Convert simple dictionary to XML for ISCE."""
def add_property(property, value):
xml = f" <property name='{property}'>{value}</property>\n"
return xml
def add_component(name, properties):
xml = f" <componen... | bigcode/self-oss-instruct-sc2-concepts |
def build_args_stdio(settings):
"""Build arguments for calling pylint.
:param settings: client settings
:type settings: dict
:return: arguments to path to pylint
:rtype: list
"""
pylint_args = settings.get('args')
if pylint_args is None:
return []
return pylint_args | bigcode/self-oss-instruct-sc2-concepts |
def _list_to_index_dict(lst):
"""Create dictionary mapping list items to their indices in the list."""
return {item: n for n, item in enumerate(lst)} | bigcode/self-oss-instruct-sc2-concepts |
import random
import string
def random_id(length=5):
"""Generate a random ID of 5 characters to append to qsub job name."""
return ''.join(random.sample(string.ascii_letters + string.digits, length)) | bigcode/self-oss-instruct-sc2-concepts |
import json
def intrinsics(kinect, path='calibrate/IR/intrinsics_retrieved_from_kinect_mapper.json', write=False):
"""
Retrieve the depth camera intrinsics from the kinect's mapper
and write them at: calibrate/IR/intrinsics_retrieved_from_kinect_mapper.json
:param kinect: kinect instance
:param pa... | bigcode/self-oss-instruct-sc2-concepts |
import requests
def connection_ok(base_url):
"""Check whetcher connection is ok
Post a request to server, if connection ok, server will return http response 'ok'
Args:
none
Returns:
if connection ok, return True
if connection not ok, return False
Raises:
none
... | bigcode/self-oss-instruct-sc2-concepts |
def _display_time(seconds: float, granularity=2) -> str:
"""Return a human readable instruction for some time duration.
Copy and pasted from:
https://stackoverflow.com/questions/4048651/python-function-to-convert-seconds-into-minutes-hours-and-days/4048773
If the number is positive, it returns the tim... | bigcode/self-oss-instruct-sc2-concepts |
import random
import copy
def partition(n,m,minQuota,maxQuota):
"""
Function to partion a particular integer.
Parameters:
n (int) - the number we want to partition.
m (int) - the number of blocks we want.
minQuota (int) - the minimum size of a block.
maxQuota (int) - the m... | bigcode/self-oss-instruct-sc2-concepts |
def PPV_OR(odd_ratio, power, alpha, verbose=True):
"""
returns PPV from odd_ratio, power and alpha
parameters:
-----------
odd_ratio: float
P(H_A)/(1-P(H_A))
power: float
Power for this study
alpha: float
type I risk of error
Returns:
----------
... | bigcode/self-oss-instruct-sc2-concepts |
def split_by_link(data):
"""
splits PTCF information by link ids (e.g. "ds1_1-ds2_1") to store the data under a given key for easier access (-> focus-on-hover!)
:param data: ptcf data frame
:return: PTCF split by link
"""
split_data = {}
data['cluster_id'] = data['ds1_cluster'] + "-" + data['ds2... | bigcode/self-oss-instruct-sc2-concepts |
def extractStationsFromFile(stations_file):
"""
Reads file and extracts stations to a list.
"""
df = open(stations_file)
station_ids = df.read().split()
df.close()
return station_ids | bigcode/self-oss-instruct-sc2-concepts |
def create_violin_plot(df, columns, title):
"""
This method will create violin plots given a DataFrame and columns.
Args:
df (pandas.DataFrame): data that will be displayed
columns (list): list of columns
title (str): violin plot title
Returns:
... | bigcode/self-oss-instruct-sc2-concepts |
def safe_ord(character):
"""
Ethereum RLP Utils:
Returns an integer representing the Unicode code point of the character or int if int argument is passed
:param character: character or integer
:return: integer representing the Unicode code point of the character or int if int argument is passed
... | bigcode/self-oss-instruct-sc2-concepts |
def from_bar(bar):
"""
Generate DbBarData object from BarData.
"""
db_bar = dict(
index = bar.datetime,
volume = bar.volume,
open_int = bar.open_interest,
open = bar.open_price,
high = bar.high_price,
low = bar.low_price,
close = bar.close_price
... | bigcode/self-oss-instruct-sc2-concepts |
def _lookup_enum_in_ns(namespace, value):
"""Return the attribute of namespace corresponding to value."""
for attribute in dir(namespace):
if getattr(namespace, attribute) == value:
return attribute | bigcode/self-oss-instruct-sc2-concepts |
def is_instance_or_subclass(x, cls):
"""Return True if ``x`` is either a subclass or instance of ``cls``."""
try:
return issubclass(x, cls)
except TypeError:
return isinstance(x, cls) | bigcode/self-oss-instruct-sc2-concepts |
def is_host(ip):
"""
Checks whether an address is a subnet address or a single address
:param ip: ip address or subnet
:return: True if host
"""
r = ip.split("/")
if len(r) > 1:
return False
return True | bigcode/self-oss-instruct-sc2-concepts |
def get_ssa_def(mlil, var):
""" Gets the IL that defines var in the SSA form of mlil """
return mlil.ssa_form.get_ssa_var_definition(var) | bigcode/self-oss-instruct-sc2-concepts |
def __getmappinglabel__(mapping, value):
"""
Gets index of label value in mapping.
:param mapping: mapping dictionary
:param value: value for which the mapping is searched for
:return: index of value in mapping
"""
if value in mapping["labels"]:
return mapping["labels"].index(value)
... | bigcode/self-oss-instruct-sc2-concepts |
def _strip_frbr_section_from_pnx(pnx_xml):
""" We must strip the frbr section from a PNX record before re-inserting it """
for frbr_section in pnx_xml.findall('frbr'):
pnx_xml.remove(frbr_section)
return(pnx_xml) | bigcode/self-oss-instruct-sc2-concepts |
def IsInRangeInclusive(a, low, high):
"""
Return True if 'a' in 'low' <= a >= 'high'
"""
return (a >= low and a <= high) | bigcode/self-oss-instruct-sc2-concepts |
def qualify(name, prefix):
"""
Qualify a property name with the given prefix
"""
return "{prefix}:{name}".format(name=name, prefix=prefix) | bigcode/self-oss-instruct-sc2-concepts |
def get_dataset_features(dataset):
"""
Takes in the name of a dataset and returns the relevant parameters
"""
groups_to_drop = []
if dataset == 'COMPAS':
path = 'datasets/compas-scores-two-years.csv'
label = 'two_year_recid' # binary
group = 'race' # 'sex' also an option
... | bigcode/self-oss-instruct-sc2-concepts |
import string
def preprocess_article(text):
""" Changes an articles text to lowercase, removes punctuation """
return text.encode('ascii', 'ignore').lower().replace("\n", "").translate(None, string.punctuation) | bigcode/self-oss-instruct-sc2-concepts |
def _break(s, find):
"""Break a string s into the part before the substring to find,
and the part including and after the substring."""
i = s.find(find)
return s[:i], s[i:] | 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.