seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
def parr_to_pdict(arr, measures_optimized):
"""Convert BO parameter tensor to parameter dict"""
if measures_optimized:
d = {
'p_stay_home': arr[0].tolist(),
}
return d
else:
d = {
'betas': {
'education': arr[0].tolist(),
... | bigcode/self-oss-instruct-sc2-concepts |
def trapply_calib(trin):
"""Apply calibration values to data-points in a trace object"""
return trin.apply_calib() | bigcode/self-oss-instruct-sc2-concepts |
def all_names(command):
"""Return a list of all possible names in a command"""
return [command.name, *command.aliases] | bigcode/self-oss-instruct-sc2-concepts |
import string
def get_printable(text):
""" Return string if printable, else None
"""
try:
if all(c in string.printable for c in text):
return text
except TypeError:
if all(chr(c) in string.printable for c in text):
return text
return None | bigcode/self-oss-instruct-sc2-concepts |
import time
def is_noncomplex(obj):
"""Returns True if *obj* is a special (weird) class, that is complex than
primitive data types, but is not a full object. Including:
* :class:`~time.struct_time`
"""
if type(obj) is time.struct_time:
return True
return False | bigcode/self-oss-instruct-sc2-concepts |
def split_index(index, n=8):
"""Split a conversions index, which is a list of tuples (file position,
number of lines, alignment position), one for each read, into `n`
approximately equal parts. This function is used to split the conversions
CSV for multiprocessing.
:param index: index
:type ind... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Counter
import pickle
def build_dict(examples, filepath, max_words=50000):
"""
Build a dictionary for the words in `sentences` and a dictionary for the entities.
Only the max_words ones are kept and the remaining will be mapped to <UNK>.
"""
documents, questions, answers... | bigcode/self-oss-instruct-sc2-concepts |
def get_value(input: int) -> str:
"""Given an int it return Fizz, Buzz or FizzBuzz if it is a multiple of 3, 5 or both"""
if input % 15 == 0:
return "FizzBuzz"
elif input % 3 == 0:
return "Fizz"
elif input % 5 == 0:
return "Buzz"
else:
return f"{input}" | bigcode/self-oss-instruct-sc2-concepts |
import copy
def get_topic_with_children(prefix, children):
"""
Reuse the three-nodes sequence form sample_children to create a topic node.
Modify `node_id`s and `content_id`s to make sure nodes are different.
"""
topic = {
"title": "Topic " + prefix,
"node_id": prefix,
"con... | bigcode/self-oss-instruct-sc2-concepts |
def chi2fn_2outcome_wfreqs(N, p, f):
"""
Computes chi^2 for a 2-outcome measurement using frequency-weighting.
The chi-squared function for a 2-outcome measurement using
the observed frequency in the statistical weight.
Parameters
----------
N : float or numpy array
Number of sampl... | bigcode/self-oss-instruct-sc2-concepts |
def get_wikidata_id(wikidata_uri):
"""
Returns Wikidata ID (e.g. "Q92212") given Wikidata entity URI, or None.
"""
wikidata_base_uri = "http://www.wikidata.org/entity/"
if wikidata_uri.startswith(wikidata_base_uri):
wikidata_id = wikidata_uri[len(wikidata_base_uri):]
else:
wikida... | bigcode/self-oss-instruct-sc2-concepts |
def get_feature_code(properties, yearsuffix):
"""
Get code from GeoJSON feature
"""
code = None
if 'code' in properties: code = properties['code']
elif ('lau1' + yearsuffix + 'cd') in properties: code = properties['lau1' + yearsuffix + 'cd']
return code | bigcode/self-oss-instruct-sc2-concepts |
def key_check(line,keyword):
"""
For ARGS, checks if a line of the input file has a keyword on it
"""
if keyword in line:
return True ... | bigcode/self-oss-instruct-sc2-concepts |
def validate_vector(obj, throwerr=False):
"""
Given an object obj, check if it is a valid raw representation of a real
mathematical vector. An accepted object would:
1. be a Python list or Python tuple
2. be 2 or 3 items in length
:param obj: Test subject
:param throwerr: Raise an e... | bigcode/self-oss-instruct-sc2-concepts |
def check_member_in_project(project, user):
"""
Check user whether or not in project.
"""
if user.is_staff:
return True
if user in project.members.all():
return True
return False | bigcode/self-oss-instruct-sc2-concepts |
def factor_n(n):
"""
Converts input n to the form 2^exp * mult + 1, where mult is the greatest odd
divisor of n - 1, and returns mult and exp.
"""
assert n >= 3 and n % 2 != 0, "n must be an odd integer > 2"
mult = n - 1
exp = 0
while mult % 2 == 0:
mult //= 2
exp += ... | bigcode/self-oss-instruct-sc2-concepts |
def get_sym(pair):
"""
reformats a tuple of (team, rival) so that the first element is smaller than the other
(by convention, this is how we represent a match without home-away status).
"""
if pair[0] > pair[1]:
return pair[1], pair[0]
else:
return pair | bigcode/self-oss-instruct-sc2-concepts |
def fromPoint3d( pt ):
"""Converts a Point3d to a tuple"""
if pt is None: return None
return (pt.x, pt.y, pt.z) | bigcode/self-oss-instruct-sc2-concepts |
def acidity (NaOH_volume, NaOH_molarity, NaOH_fc, honey_solution_concentration, honey_solution_volume):
"""
Function to get acidity in honey - meq/kg
"""
mili_eq_NaOH = NaOH_volume * NaOH_molarity * NaOH_fc
grams_of_honey = (honey_solution_concentration * honey_solution_volume) / 100
acidity = (... | bigcode/self-oss-instruct-sc2-concepts |
def parse_node_coverage(line):
# S s34 CGTGACT LN:i:7 SN:Z:1 SO:i:122101 SR:i:0 dc:f:0
# "nodeid","nodelen","chromo","pos","rrank",assemb
"""
Parse the gaf alignment
Input: line from gaf alignment
Output: tuple of nodeid, nodelen, start_chromo, start_pos, coverage
"""
l... | bigcode/self-oss-instruct-sc2-concepts |
import re
def apply_formatting(locator, args):
"""Apply formatting to the locator
If there are no named fields in the locator this is just a simple
call to .format. However, some locators have named fields, and we
don't support named arguments to keep the syntax simple, so we
need to map position... | bigcode/self-oss-instruct-sc2-concepts |
def direction_name(angle):
"""
Returns a name for a direction given in degrees.
Example: direction_name(0.0) returns "N"
direction_name(90.0) returns "E"
direction_name(152.0) returns "SSE".
"""
direction_names = ["N", "NNE", "NE", "ENE", "E", "ESE", "SE", "SSE", "S",
... | bigcode/self-oss-instruct-sc2-concepts |
def make_query(specific_table, offset):
"""
Generate a query to retrieve data from database.
:param specific_table: Name of table to retrieve data from.
:param offset: Optional offset to start from.
"""
query = 'select DISTINCT * from `{}`'.format(specific_table)
if isinstance(offset, int):... | bigcode/self-oss-instruct-sc2-concepts |
def is_builtin_reducer(fn_reducer):
"""
Returns True if fn_reducer specifies the built-in reducer.
"""
return (fn_reducer == 'aggregate') | bigcode/self-oss-instruct-sc2-concepts |
def format_code(entry):
"""
Formats the viewing of code and errors
"""
code = ""
for line in entry.split('\n'):
code += "\n|G>>>|n %s" % line
return code.strip() | bigcode/self-oss-instruct-sc2-concepts |
from typing import Union
def _is_dict(data: Union[dict, list]) -> bool:
"""
Checks whether provided data structure is a dictionary or not.
:param data: The data to check
:return: true if is dict, false otherwise
"""
if isinstance(data, dict):
return True
return False | bigcode/self-oss-instruct-sc2-concepts |
def flatten(data):
"""Returns a flattened version of a list.
Courtesy of https://stackoverflow.com/a/12472564
Args:
data (`tuple` or `list`): Input data
Returns:
`list`
"""
if not data:
return data
if type(data[0]) in (list, tuple):
return list(flatten(dat... | bigcode/self-oss-instruct-sc2-concepts |
def clip(min, val, max):
"""
Returns `val` clipped to `min` and `max`.
"""
return min if val < min else max if val > max else val | bigcode/self-oss-instruct-sc2-concepts |
def unique(lst):
"""
Returns a list made up of the unique values found in lst. i.e., it
removes the redundant values in lst.
"""
lst = lst[:]
unique_lst = []
# Cycle through the list and add each value to the unique list only once.
for item in lst:
if unique_lst.count(item) <= ... | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
def linear_search(arr: List[int], target: int) -> int:
"""
:param arr: Array of integers (may be sorted or unsorted)
:param target: integer we want to find
:return: position of the target in the array, -1 if not found
"""
for i in range(0, len(arr)):
if arr[i] =... | bigcode/self-oss-instruct-sc2-concepts |
import yaml
def load_local_paths(path):
"""
Load local paths .yaml file.
Parameters
==========
path : str
Path to .env file.
Returns
=======
local_paths : dict
Dictionary with environmental variables from .yaml file.
"""
with open(path, 'r') as f:
try... | bigcode/self-oss-instruct-sc2-concepts |
def mass_from_column_name(mass):
"""Return the PVMassSpec mass 'M<x>' given the column name '<x>_amu' as string"""
return f"M{mass[:-4]}" | bigcode/self-oss-instruct-sc2-concepts |
def gram_align_right(s, line_width: int = 20):
"""
Format for telegram, align right.
:param s: input text
:param int line_width: Width
:return: str
"""
return '`{}`'.format(str(s).rjust(line_width)) | bigcode/self-oss-instruct-sc2-concepts |
import torch
from typing import Tuple
def get_idxs_tuple(idxs: torch.Tensor
) -> Tuple[torch.Tensor, ...]:
"""
@param idxs - Shape (num indices, num dimensions that the indices index into).
@returns - A tuple, which can be directly used to index into a tensor, eg tensor[idxs_tuple].
... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Set
from typing import Dict
def make_indices_to_labels(labels: Set[str]) -> Dict[int, str]:
""" Creates a mapping from indices to labels. """
return {index: label for index, label in
enumerate(["pad"] + sorted(list(labels)))} | bigcode/self-oss-instruct-sc2-concepts |
def pstring(state, num):
"""Return a nice string give a state and its count.
Example:
>>> pstring(X(0,-1,1),4)
( 0, *, 1) : 4
"""
a,b,c = state
if b == -1:
b = " *"
return f"({a:2},{b:2},{c:2}) : {num:2}" | bigcode/self-oss-instruct-sc2-concepts |
import requests
from typing import Optional
def size_from_headers(response: requests.Response) -> Optional[int]:
"""
Return the size of the download based on the response headers.
Arguments:
response {requests.Response} -- the response
Returns:
Optional[int] -- the size
"""
i... | bigcode/self-oss-instruct-sc2-concepts |
def try_or_none(f):
"""wraps f to return None if f raises an exception
assumes f takes only one input"""
def f_or_none(x):
try:
return f(x)
except:
return None
return f_or_none | bigcode/self-oss-instruct-sc2-concepts |
def GetAllLengths( tbl_nrdb, nids ):
"""retrieve all lengths for a set of nids.
"""
lengths = []
for nid in nids:
lengths.append( tbl_nrdb.GetLength( nid ))
return lengths | bigcode/self-oss-instruct-sc2-concepts |
def find_lambda_jit(target, source):
"""
Finds the longest subsequence of the target array,
starting from index 0, that is contained in the source array.
Returns the length of that subsequence + 1.
i.e. returns the length of the shortest subsequence starting at 0
that has not previously a... | bigcode/self-oss-instruct-sc2-concepts |
def getPlayer(f,columns,x):
"""Return the dataframe of a specific player with subject ID x"""
return f[f['Subject'].isin([x])] | bigcode/self-oss-instruct-sc2-concepts |
def _get_tmpdir_fixture_name(scope: str) -> str:
"""Get appropriately-scoped tmpdir fixture."""
if scope == 'session':
return 'session_tmpdir_path'
else:
return 'tmpdir_path' | bigcode/self-oss-instruct-sc2-concepts |
def strip_comments(s):
"""Strips comment lines and docstring from Python source string."""
o = ''
in_docstring = False
for l in s.split('\n'):
if l.strip().startswith(('#', '"', "'")) or in_docstring:
in_docstring = l.strip().startswith(('"""', "'''")) + in_docstring == 1
... | bigcode/self-oss-instruct-sc2-concepts |
def find_keywords_sentences(keywords, cleaned_lines):
"""
Find the occurrences of the keywords in the text.
:param keywords: The keywords to be searched in the lines
:param cleaned_lines: The lines of the document
:return: The lines with the given keywords
"""
accepted_lines = list()
for... | bigcode/self-oss-instruct-sc2-concepts |
def resolveArgPrefix(function) -> str:
"""
Resolve the command line prefix for a function.
:param function: The function to resolve.
:return: The value of the '_func' property set by @ArgMap or the function name if not set.
"""
# Handle _func in argMap
prefix = function.__name__ + ':'
i... | bigcode/self-oss-instruct-sc2-concepts |
from bs4 import BeautifulSoup
import requests
def download_html(url: str) -> BeautifulSoup:
"""The download_html method downloads the html tree based on the argument `url`.
Args:
url (str): the url that users want to scrap
Returns:
a BeautifulSoup object
"""
res = requests.get(url... | bigcode/self-oss-instruct-sc2-concepts |
def check_output_format(expected_formats):
"""
Decorator for stream outputs that checks the format of the outputs after modifiers have been applied
:param expected_formats: The expected output formats
:type expected_formats: tuple, set
:return: the decorator
"""
def output_format_decorator(f... | bigcode/self-oss-instruct-sc2-concepts |
def get_hex(num, digits=2):
"""
Convert an integer to a hex string of 'digit' characters.
Args:
num (int): The value to be converted.
digits (int): The number of characters the final string should comprise. Default: 2.
Returns:
str: The hex string.
"""
format_str = ... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Dict
from typing import Callable
from datetime import datetime
from typing import Tuple
def season_binner(rules: Dict[int, str]) -> Callable[[datetime], str]:
"""
Construct mapping from datetime to a string in the form like 2010-06--P3M
:param rules: Is a mapping from month (1-Jan, 2-F... | bigcode/self-oss-instruct-sc2-concepts |
from datetime import datetime
def l2l_dt(value):
"""
Detects if value is a datetime object. If it is, object is converted to a string that is formatted '%Y-%m-%d %H:%M:%S'.
If value is a string, we convert it to a datetime object and then perform the step mentioned above.
"""
format = "%Y-%m-%d... | bigcode/self-oss-instruct-sc2-concepts |
def _enum_to_int(value):
"""Convert an IntEnum member to a numeric value.
If it's not an IntEnum member return the value itself.
"""
try:
return int(value)
except (ValueError, TypeError):
return value | bigcode/self-oss-instruct-sc2-concepts |
def locate(actuator, *extra_args, **extra_kwargs):
"""
Example target function for example-locate
Any parameter of an OpenC2-Command message can be used as an argument [action, actuator, args, id as cmd_id, target]
Target will be the contents of the target object
:param actuator: the instance of the... | bigcode/self-oss-instruct-sc2-concepts |
import struct
def pack_dint(n):
"""pack 32 bit into 4 bytes little endian"""
return struct.pack('<i', n) | bigcode/self-oss-instruct-sc2-concepts |
def truncate(toTruncate, charsToKeep=50):
"""
Returns a string truncated to 'charsToKeep' length plus ellipses.
"""
if len(toTruncate) > charsToKeep:
truncated = toTruncate[:charsToKeep] + "..."
return truncated
else:
return toTruncate | bigcode/self-oss-instruct-sc2-concepts |
import math
def compute_distance(x1, y1, x2, y2):
"""
function to compute distance between points
Inputs:
x1: x-coordinate of point1
y1: y-coordinate of point1
x2: x-coordinate of point2
y2: y-coordinate of point2
Outputs:
dist: ... | bigcode/self-oss-instruct-sc2-concepts |
def mock_ingest_queue(mocker):
"""
Mock the IngestRun queue.
"""
ingest_queue = mocker.patch(
"creator.ingest_runs.mutations.ingest_run.IngestRun.queue",
)
return ingest_queue | bigcode/self-oss-instruct-sc2-concepts |
import random
def random_subset(seq, n):
"""
Return n unique elements from seq.
"""
res = set()
while len(res) < n:
x = random.choice(seq)
res.add(x)
return res | bigcode/self-oss-instruct-sc2-concepts |
def rpad(ls, size, val):
"""Right-pads a list with a prescribed value to a set length."""
return ls + (size - len(ls))*[val] | bigcode/self-oss-instruct-sc2-concepts |
def join_by_comma(iterable, key=None):
"""
Helper to create a comma separated label out of an iterable.
:param iterable: an iterable to be joined by comma
:param key: if the iterable contains dicts, which key would you want to extract
:return: comma separated string
"""
if key:
thing... | bigcode/self-oss-instruct-sc2-concepts |
def resolve_cyvcf2_genotype(cyvcf2_gt):
"""
Given a genotype given by cyvcf2, translate this to a valid
genotype string.
Args:
cyvcf2_gt (cyvcf2.variant.genotypes)
Returns:
genotype (str)
"""
if cyvcf2_gt[2]:
separator = "|"
else:
... | bigcode/self-oss-instruct-sc2-concepts |
def find_start_end(case, control):
"""
Find the measurement start and end of a control, treatment pair.
:param case: The treatment ExperimentalCondition
:param controL: The control ExperimentalCondition
:return a [tuple]:
- the start index point
- the end index point
"""
if c... | bigcode/self-oss-instruct-sc2-concepts |
def is_in_prereg_group(user):
"""Determines whether a user is in the prereg_group
:param user: User wanting access to prereg material
:return: True if prereg False if not
"""
return user.is_in_group('prereg_group') | bigcode/self-oss-instruct-sc2-concepts |
def get_message_type(type_in_bytes):
"""Return the type of a binary message as a string."""
return type_in_bytes.decode('ascii') | bigcode/self-oss-instruct-sc2-concepts |
import json
def get_r_version(path):
"""Get the version of R specified in the renv.lock file
Parameters
----------
path : str
Path to the project directory. The file path/renv.lock must exist.
Returns
-------
str
R version
"""
with open(f"{path}/renv.lock", "r") a... | bigcode/self-oss-instruct-sc2-concepts |
import string
def is_pangram(text: str) -> bool:
"""Determine if text is a pangram.
..note:: A pangram is a string that contains every single letter of the \
alphabet at least once (case is irrelevant).
:param text: text to evaluate
:return: True if text is a pangram
"""
return set(st... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Union
from typing import Mapping
from typing import Sequence
from typing import Any
def get_nested(obj: Union[Mapping, Sequence], path: Sequence) -> Any:
"""Get element of a sequence or map based on multiple nested keys.
Args:
obj: Object to index from
path: Sequence of nes... | bigcode/self-oss-instruct-sc2-concepts |
import gzip
import json
def load_gzipped_jsonl(filename: str, encoding: str = 'UTF-8') -> dict:
"""
Function loads data stored in gzipped JSON Lines.
Parameters
----------
filename : str
Path to the file.
encoding : str, default = 'utf-8'
Returns
-------
: dict
... | bigcode/self-oss-instruct-sc2-concepts |
def _merge_dicts(*dict_args):
"""
Given any number of dicts, shallow copy and merge into a new dict,
precedence goes to key value pairs in latter dicts.
See http://stackoverflow.com/a/26853961/2680824
"""
result = {}
for dictionary in dict_args:
result.update(dictionary)
return r... | bigcode/self-oss-instruct-sc2-concepts |
def timestamptz_to_unix(timestamptz):
"""
Converts timestamp with time zone to epoch
"""
return timestamptz.timestamp() | bigcode/self-oss-instruct-sc2-concepts |
def calc_bpm(peaks, fs):
"""Calculates average HR based on array of peaks found in ECG strip
Args:
peaks (ndarray): array of indices corresponding to location of R peaks
fs (float): sampling frequency of ECG strip
Returns:
float: average heart rate in bpm
"""
sec_per_beat =... | bigcode/self-oss-instruct-sc2-concepts |
def inv_price_sigmoid(forecast_price, w_param, m_bet_size):
"""
Part of SNIPPET 10.4
Calculates the inverse of the bet size with respect to the market price.
Based on a sigmoid function for a bet size algorithm.
:param forecast_price: (float) Forecast price.
:param w_param: (float) Coefficient ... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Dict
def _sum_expectation_values(
expectation_values_per_bitstring: Dict[str, float],
probability_per_bitstring: Dict[str, float],
alpha: float,
) -> float:
"""Returns the cumulative sum of expectation values until the cumulative probability of bitstrings
s_k = p(x_1) + … + p(x_... | bigcode/self-oss-instruct-sc2-concepts |
def is_auto_primary_key(primary_key: bool, autoincrement: bool) -> bool:
"""
Checks if field is an autoincrement pk -> if yes it's optional.
:param primary_key: flag if field is a pk field
:type primary_key: bool
:param autoincrement: flag if field should be autoincrement
:type autoincrement: b... | bigcode/self-oss-instruct-sc2-concepts |
def create_primes(threshold):
"""
Generate prime values using sieve of Eratosthenes method.
Args:
threshold (int):
The upper bound for the size of the prime values.
Returns (List[int]):
All primes from 2 and up to ``threshold``.
"""
if threshold == 2:
return... | bigcode/self-oss-instruct-sc2-concepts |
import pathlib
import shutil
def prep_dir(dir_path, clobber=False):
"""Create (or delete and recreate) a directory.
Args:
dir_path (path-like): path to the directory that you are trying to
clean and prepare.
clobber (bool): If True and dir_path exists, it will be removed and
... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Tuple
from typing import Optional
def normalize_parameter(parameter: str, expression: str) -> Tuple[Optional[str], str, str]:
"""Normalize runtime expressions.
Runtime expressions may have parameter names prefixed with their location - `path.id`.
At the same time, parameters could be d... | bigcode/self-oss-instruct-sc2-concepts |
def stations_level_over_threshold(stations, tol):
"""returns a list of tuples (MonitoringStation, MonitoringStation.relative_water_level) where
all relative water levels are > tol"""
statlist = []
for i in stations:
if i.relative_water_level() == None: #discounts all invalid data
... | bigcode/self-oss-instruct-sc2-concepts |
def score4_evaluation_function(game_state, agent, **context):
"""
This evaluation function comes from Score4 project:
https://github.com/ttsiodras/Score4
"Speaking of the scoreBoard function, I tried various forms to evaluate the
board. I ended up on a simple policy: measuring how many chips of th... | bigcode/self-oss-instruct-sc2-concepts |
def check_valid(subset_json):
"""Helper to check if a file is valid, given a subset json instance
Args:
subset_json: Defined subset json file data
Returns:
bool: True/false value for validity
"""
if subset_json is None:
return lambda path: True
def curry(image_path):
... | bigcode/self-oss-instruct-sc2-concepts |
def irc_prefix(var):
"""
Prefix a string with the irc_
:param var: Variable to prefix
:return: Prefixed variable
"""
if isinstance(var, str):
return 'irc_%s' % var.lower() | bigcode/self-oss-instruct-sc2-concepts |
def get_data_files(filepath, prefix, num_epochs, num_features=41,
model_type='lstm'):
"""
model folder of type: type_prefix_features
model file of type: prefix_features_epochs.model
means and stddev file of type: means/stddev_prefix_numfeatures.npy
"""
num_epochs = str(num_epo... | bigcode/self-oss-instruct-sc2-concepts |
def success_email_subject_msid_author(identity, msid, author):
"""email subject for a success email with msid and author values"""
return u"{identity}JATS posted for article {msid:0>5}, author {author}".format(
identity=identity, msid=str(msid), author=author
) | bigcode/self-oss-instruct-sc2-concepts |
def add_match_to_profile(profile, match, ismap=True, nucl=None):
"""Merge current read-gene matches to master profile.
Parameters
----------
profile : dict
Master gene profile.
match : dict
Read-gene matches.
ismap : bool, optional
Whether matches are a read-to-gene(s) m... | bigcode/self-oss-instruct-sc2-concepts |
def wildcard_filter( input_string ):
"""
A helper function which filters out a wildcard string containing
'ANY' and converts it to 'N/A'.
"""
if str(input_string).strip() == 'ANY':
return 'N/A'
else:
return input_string | bigcode/self-oss-instruct-sc2-concepts |
def array(num_elements, element_func, *element_func_args):
"""
Returns array of elements with a length of num_elements.
Every element is generated by a call to element_func(*element_func_args).
"""
return [element_func(*element_func_args) for _ in range(num_elements)] | bigcode/self-oss-instruct-sc2-concepts |
def deg_dms(decimal_degree):
"""
Convert angle in degrees to degree, minute, second tuple
:param degree: Angle in degrees
:return: (degree, minutes, second)
Example:
>>> import units as u
>>>
>>> u.dms_deg((45, 23, 34))
45.39277777777778
>>>
... | bigcode/self-oss-instruct-sc2-concepts |
def _last_test(test):
"""Returns True if given test is the last one."""
parent_tests = tuple(test.parent.testcases)
return parent_tests.index(test) == (len(parent_tests) - 1) | bigcode/self-oss-instruct-sc2-concepts |
def required_jenkins_settings(settings):
""" Checks if all settings required for interacting with jenkins build are set """
try:
return all([ settings.get('jenkins', setting) != '' for setting in ['url', 'username', 'password', 'job_name', 'build_num'] ])
except KeyError:
return False | bigcode/self-oss-instruct-sc2-concepts |
import requests
def _return_response_and_status_code(response, json_results=True):
""" Output the requests response content or content as json and status code
:rtype : dict
:param response: requests response object
:param json_results: Should return JSON or raw content
:return: dict containing th... | bigcode/self-oss-instruct-sc2-concepts |
def prune_wv(df, vocab, extra=["UUUNKKK"]):
"""Prune word vectors to vocabulary."""
items = set(vocab).union(set(extra))
return df.filter(items=items, axis='index') | bigcode/self-oss-instruct-sc2-concepts |
def addressInNetwork(ip, net):
"""
Is an address in a network
"""
return ip & net == net | bigcode/self-oss-instruct-sc2-concepts |
import torch
def get_all_pairs_indices(labels, ref_labels=None):
"""
Given a tensor of labels, this will return 4 tensors.
The first 2 tensors are the indices which form all positive pairs
The second 2 tensors are the indices which form all negative pairs
"""
if ref_labels is None:
ref... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Set
def _negative_to_positive_state_indexes(indexes: Set[int], n_entries) -> Set[int]:
""" Convert negative indexes of an iterable to positive ones
Parameters
----------
indexes: Set[int]
indexes to check and convert
n_entries: int
total number of entries
R... | bigcode/self-oss-instruct-sc2-concepts |
import math
def distance(point_one, point_two):
"""Calculates the Euclidean distance from point_one to point_two
"""
return math.sqrt((point_two[0] - point_one[0]) ** 2 + (point_two[1] - point_one[1]) ** 2) | bigcode/self-oss-instruct-sc2-concepts |
def matches_have_unknown(matches, licensing):
"""
Return True if any of the LicenseMatch in `matches` has an unknown license.
"""
for match in matches:
exp = match.rule.license_expression_object
if any(key in ('unknown', 'unknown-spdx') for key in licensing.license_keys(exp)):
... | bigcode/self-oss-instruct-sc2-concepts |
def mvt(a, b, fx = lambda x: x):
"""
Mean value theorem
Params:
a: start of interval
b: end of interval
fx: function
Returns:
f_c: derivative of some point c that is a <= c <= b
"""
return (fx(b) - fx(a))/(b - a) | bigcode/self-oss-instruct-sc2-concepts |
def add_prefix(prefix, split, string):
"""
Adds a prefix to the given string
:param prefix: str, prefix to add to the string
:param split: str, split character
:param string: str, string to add prefix to
:return: str
"""
return split.join([prefix, string]) | bigcode/self-oss-instruct-sc2-concepts |
import pathlib
def md_files(file_list):
"""Get list of markdown files from the repository file list"""
md_files = []
while file_list:
git_file = file_list.pop()
if pathlib.Path(git_file.name).suffix == ".md":
md_files.append(git_file)
return md_files | bigcode/self-oss-instruct-sc2-concepts |
import math
def next_byte_power(value):
"""Calculate the next power of 2 from a value."""
char_bit = 8
byte_length = int(math.ceil(value.bit_length() / char_bit))
return 2 ** (char_bit * byte_length) | bigcode/self-oss-instruct-sc2-concepts |
def serialize_structures(storage):
"""
Serializes storage structures into dict.
:param dict storage: Storage dict.
:return: Serialized storage.
:rtype: dict
"""
return {
"tasks": [list(t._asdict().values()) for t in storage["tasks"]],
"groups": [list(g._asdict().values()) f... | 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.