seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
def get_z(coeffs, x, y):
"""
Calculate and return the height z given the coefficients and ordinates of ax + by + c = z
:param coeffs: numpy ndarray of coefficients a, b, c, in the order (c, a, b)
:param x: x value
:param y: y vakye
:return: the calculated z value
"""
as... | bigcode/self-oss-instruct-sc2-concepts |
def canonicalize(doc):
"""De-duplicate environment vars and sort them alphabetically."""
spec = doc.get('spec')
if not spec: return doc
template = spec.get('template')
if not template: return doc
spec2 = template.get('spec')
if not spec2: return doc
containers = spec2.get('containers')
... | bigcode/self-oss-instruct-sc2-concepts |
def count_results(performances, result):
"""Count the number of performances with the specified result"""
return len([performance for performance in performances if performance['result'] == result]) | bigcode/self-oss-instruct-sc2-concepts |
def logpofr_old(r):
"""
Returns the nat. logarithm of a fit to the probability of finding
a zone of density contrast r in a Poisson particle simulation
"""
# 2D
#p = -2.6*(r-1.)
# 3D
p = -5.12*(r-1) - 0.8*(r-1)**2.8
return p | bigcode/self-oss-instruct-sc2-concepts |
def is_broadcastable_and_smaller(shp1, shp2):
"""
Test if shape 1 can be broadcast to shape 2, not allowing the case
where shape 2 has a dimension length 1
"""
for a, b in zip(shp1[::-1], shp2[::-1]):
# b==1 is broadcastable but not desired
if a == 1 or a == b:
pass
... | bigcode/self-oss-instruct-sc2-concepts |
def time_format(secs):
"""Convert seconds to h:mm:ss."""
m, s = divmod(secs, 60)
h, m = divmod(m, 60)
return "%d:%02d:%02d" % (h, m, s) | bigcode/self-oss-instruct-sc2-concepts |
def round_upper_bound (value):
"""
This method expects an integer or float value, and will return an integer upper
bound suitable for example to define plot ranges. The upper bound is the
smallest value larger than the input value which is a multiple of 1, 2 or
5 times the order of magnitude (10**x... | bigcode/self-oss-instruct-sc2-concepts |
def ltv_predict(data, mbg, ggf, discount_rate, time):
"""
Predict dollar value of customers from today up to time t.
"""
return ggf.customer_lifetime_value(mbg,
data['frequency_cal'],
data['recency_cal'],
... | bigcode/self-oss-instruct-sc2-concepts |
import json
def json_pretty(obj):
"""Convert obj into pretty-printed JSON"""
return json.dumps(obj, indent=4, sort_keys=True) | bigcode/self-oss-instruct-sc2-concepts |
def fixed_point_integer_part(fixed_point_val: int, precision: int) -> int:
"""
Extracts the integer part from the given fixed point value.
"""
if (precision >= 0):
return fixed_point_val >> precision
return fixed_point_val << precision | bigcode/self-oss-instruct-sc2-concepts |
def select_single_mlvl(mlvl_tensors, batch_id, detach=True):
"""Extract a multi-scale single image tensor from a multi-scale batch
tensor based on batch index.
Note: The default value of detach is True, because the proposal gradient
needs to be detached during the training of the two-stage model. E.g
... | bigcode/self-oss-instruct-sc2-concepts |
import csv
def parse_fastqc_result(path_to_qc_summary):
"""
Args:
path_to_qc_summary (str): Path to the fastqc report summary file.
Returns:
dict: Parsed fastqc R1 report.
All values except are either "PASS", "WARN", or "FAIL".
For example:
{ "basic_statistic... | bigcode/self-oss-instruct-sc2-concepts |
def process_test_result(passed, info, is_verbose, exit):
"""
Process and print test results to the console.
"""
# if the environment does not contain necessary programs, exit early.
if passed is False and "spellbook: command not found" in info["stderr"]:
print(f"\nMissing from environment:\n... | bigcode/self-oss-instruct-sc2-concepts |
def get_cls_dict(category_list):
"""Get the class ID to name translation dictionary."""
return {i: n for i, n in enumerate(category_list)} | bigcode/self-oss-instruct-sc2-concepts |
import random
def get_random_int(min_v=0, max_v=10, number=5, seed=None):
"""Return a list of random integer by the given range and quantity.
Parameters
-----------
min_v : number
The minimum value.
max_v : number
The maximum value.
number : int
Number of value.
se... | bigcode/self-oss-instruct-sc2-concepts |
def bounds4(grid):
"""Return a list of tuples reporting the min and max value of each coordinate
in the given grid.
"""
xmin, ymin, zmin, wmin = list(grid.keys())[0]
xmax, ymax, zmax, wmax = xmin, ymin, zmin, wmin
for x, y, z, w in grid:
xmin = min(xmin, x)
ymin = min(ymin, y)
... | bigcode/self-oss-instruct-sc2-concepts |
def dictmax(d):
""" returns key with maximum value in dictionary """
return max(d.keys(), key = lambda x: d[x]) | bigcode/self-oss-instruct-sc2-concepts |
def _extract_dataset_from_db(force_sets_in_db, displacements_in_db, probs_in_db=None):
"""Collect force_sets, energies, and displacements to numpy arrays.
Parameters
----------
force_sets_in_db : List of ArrayData
Each ArrayData is the output of PhonopyWorkChain.
displacements_in_db : List ... | bigcode/self-oss-instruct-sc2-concepts |
def prevent_search(relation):
"""
Used to mark a model field or relation as "restricted from filtering"
e.g.,
class AuthToken(BaseModel):
user = prevent_search(models.ForeignKey(...))
sensitive_data = prevent_search(models.CharField(...))
The flag set by this function is used by
... | bigcode/self-oss-instruct-sc2-concepts |
def head_of_all(x, l):
"""List of lists from l where x is the head of all the lists."""
return [[x] + p for p in l] | bigcode/self-oss-instruct-sc2-concepts |
def is_list_of(value, elem_type):
""" Is the given value a list where each element is the elem_type
:param value: The value being checked
:type value: Any
:param elem_type: The element type
:type elem_type: type
:return: True is the value is a list and each element in the list is of the given ty... | bigcode/self-oss-instruct-sc2-concepts |
import socket
def ipv4(value):
"""Return true if IP address v4 is valid, otherwise - false."""
try:
socket.inet_pton(socket.AF_INET, value)
return True
except socket.error:
return False | bigcode/self-oss-instruct-sc2-concepts |
def one_hot_encode(label):
"""
Given a label - "red", "green", or "yellow". Returns a one-hot encoded label
"""
if label == "red":
return [1, 0, 0]
if label == "green":
return [0, 0, 1]
return [0, 1, 0] | bigcode/self-oss-instruct-sc2-concepts |
def _string_bool(value):
"""Returns the equivalent boolean if the input string is 'true' or 'false', else no change."""
if value == 'true': return True
if value == 'false': return False
return value | bigcode/self-oss-instruct-sc2-concepts |
def _paginated_scan(ddb_table, filter_exp=None):
"""performs a paginated scan of the DynamoDB table
"""
if filter_exp:
response = ddb_table.scan(FilterExpression=filter_exp)
else:
response = ddb_table.scan()
data = response['Items']
print(len(data))
while response.get('LastE... | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
def update_current_measure_durations(
current_measure_durations: List[float], next_duration: float
) -> List[float]:
"""
Update a list of notes durations from a measure in progress.
:param current_measure_durations:
durations of notes (in fractions of whole measure... | bigcode/self-oss-instruct-sc2-concepts |
def scale(v: float, a: float, b: float, c: float, d: float) -> float:
"""Scale a value, v on a line with anchor points a,b to new anchors c,d."""
v01 = (v - a) / (b - a)
return c - v01 * (c - d) | bigcode/self-oss-instruct-sc2-concepts |
def extract_subset_from_monolithic_flags_as_dict_from_stream(
monolithic_trie, stream):
"""Extract a subset of flags from the trie of monolithic flags.
:param monolithic_trie: the trie containing all the monolithic flags.
:param stream: a stream containing a list of signature patterns that define
... | bigcode/self-oss-instruct-sc2-concepts |
def get_pids(search):
"""Get a list of pids of the search results."""
pids = []
for hit in search().scan():
pids.append(hit["pid"])
return pids | bigcode/self-oss-instruct-sc2-concepts |
import logging
def _setup_logger() -> logging.Logger:
"""Set up the logger."""
FORMAT = "[%(asctime)s][%(levelname)s] %(message)s"
logging.basicConfig(format=FORMAT)
logger_ = logging.getLogger("generate_all_protocols")
logger_.setLevel(logging.INFO)
return logger_ | bigcode/self-oss-instruct-sc2-concepts |
def parse_enum_constant(enum_constant_or_name, enum_type):
"""
Return the enumerated constant corresponding to 'enum_constant_or_name', which
can be either this constant or a its name (string).
"""
if isinstance(enum_constant_or_name, enum_type):
return enum_constant_or_name
else:
... | bigcode/self-oss-instruct-sc2-concepts |
def top_player_ids(info, statistics, formula, numplayers):
"""
Inputs:
info - Baseball data information dictionary
statistics - List of batting statistics dictionaries
formula - function that takes an info dictionary and a
batting statistics dictionary as input and
... | bigcode/self-oss-instruct-sc2-concepts |
import ipaddress
def get_ip_list(ip_network, mask=None):
"""
Quickly convert an IPv4 or IPv6 network (CIDR or Subnet) to a list
of individual IPs in their string representation.
:param str ip_network:
:param int mask:
:return: list
"""
if mask and '/' not in ip_network:
net = ipaddress.ip_network("{0}/{1}"... | bigcode/self-oss-instruct-sc2-concepts |
def _hashString (text):
"""
Compute hash for a string, returns an unsigned 64 bit number.
"""
value = 0x35af7b2c97a78b9e
step = 0x072f2b592a4c57f9
for ch in text:
value = ((value * 104297) + (step * ord (ch))) & 0xFFFFFFFFFFFFFFFF
return value | bigcode/self-oss-instruct-sc2-concepts |
def exists(field):
"""Only return docs which have a value for ``field``"""
return {"exists": {"field": field}} | bigcode/self-oss-instruct-sc2-concepts |
from typing import AnyStr
from typing import Union
from typing import Sequence
def separate(text: AnyStr, sep: Union[str, Sequence[str]] = ('!', '?', '.'), between_char=False) -> str:
"""
Creating a space between an element in sep values
e.g:
>>> separate('how are you?', sep='?')
'how are you ?'
... | bigcode/self-oss-instruct-sc2-concepts |
import uuid
def create_id() -> str:
"""
Create a unique id using uuid4
:return: str of the id
"""
id_unique = uuid.uuid4()
return str(id_unique) | bigcode/self-oss-instruct-sc2-concepts |
def value_or_from_dict(obj, key, default=None):
"""
Many Polygraphy APIs can accept a `Union[obj, Dict[str, obj]]` to allow
for specifying either a global value, or a per-key (e.g. input, output, etc.) value.
When a dictionary is provided, the `""` key indiciates a default value to use for keys
not... | bigcode/self-oss-instruct-sc2-concepts |
def all_tree_names(pathnames):
"""Returns the set of all names, including intermediate names,
given a list of pathnames. For example, given the pathname 'a.b.c',
it would return set(['a', 'a.b', 'a.b.c'])
"""
allnames = set()
for key in pathnames:
parts = key.split('.')
allnames.... | bigcode/self-oss-instruct-sc2-concepts |
def datetime_to_iso(date):
"""Convert a datetime object to a iso date string"""
return date.isoformat().replace('+00:00', 'Z') | bigcode/self-oss-instruct-sc2-concepts |
def sanitize_cr(clientrep):
""" Removes probably sensitive details from a client representation
:param clientrep: the clientrep dict to be sanitized
:return: sanitized clientrep dict
"""
result = clientrep.copy()
if 'secret' in result:
result['secret'] = 'no_log'
if 'attributes' in r... | bigcode/self-oss-instruct-sc2-concepts |
def readXRSL(filepath):
"""Return contents of given file."""
with open(filepath, 'r') as xrsl:
return xrsl.read() | bigcode/self-oss-instruct-sc2-concepts |
def is_same_sensor(sicd1, sicd2):
"""
Are the two SICD structures from the same sensor?
Parameters
----------
sicd1 : sarpy.io.complex.sicd_elements.SICD.SICDType
sicd2 : sarpy.io.complex.sicd_elements.SICD.SICDType
Returns
-------
bool
"""
if sicd1 is sicd2:
retur... | bigcode/self-oss-instruct-sc2-concepts |
from datetime import datetime
def _convert_tstamp(val):
"""
Safe convert string timestamp into a ``datetime`` object. Returns None if
it can't be converted.
"""
if val:
return datetime.fromtimestamp(float(val) / 1000) | bigcode/self-oss-instruct-sc2-concepts |
def _RecoverGaps(text, starts, ends):
"""Recovers gaps from the segmenter-produced start and end indices.
The segmenter may produce gaps around spaces, e.g. segment("hello world") => "hello|world"
"""
out_starts = []
out_ends = []
prev_end = 0
for start, end in zip(starts, ends):
if start != prev_end:
out_... | bigcode/self-oss-instruct-sc2-concepts |
def infer_n_hypers(kernel):
"""Infer number of MCMC chains that should be used based on size of kernel"""
n_hypers = 3 * len(kernel)
if n_hypers % 2 == 1:
n_hypers += 1
return n_hypers | bigcode/self-oss-instruct-sc2-concepts |
def permute_bond(bond, cycle):
"""
Permutes a bond indice if the bond indice is affected by the permutation cycle.
Parameters
----------
bond : list
A list of length 2, a subscript of an interatom distance
cycle : list
A cycle-notation permutation operation.
Returns
---... | bigcode/self-oss-instruct-sc2-concepts |
def iob2(tags):
"""
Check that tags have a valid BIO format.
Tags in BIO1 format are converted to BIO2.
"""
for i, tag in enumerate(tags):
if tag == 'O':
continue
split = tag.split('-')
if len(split) != 2 or split[0] not in ['I', 'B']:
return False
... | bigcode/self-oss-instruct-sc2-concepts |
def is_subseq(needle_seq, haystack_seq):
"""Determine if haystack_seq contains all items in needle_seq, in
the same order."""
# source: https://stackoverflow.com/questions/24017363/how-to-test-if-one-string-is-a-subsequence-of-another # NOQA
haystack_iter = iter(haystack_seq)
return all(item in hay... | bigcode/self-oss-instruct-sc2-concepts |
import random
def sampleIndexWithinRegionOfLength(length, lengthOfThingToEmbed):
"""Uniformly at random samples integers from 0 to
``length``-``lengthOfThingToEmbedIn``.
Arguments:
length: length of full region that could be embedded in
lengthOfThingToEmbed: length of thing being embedde... | bigcode/self-oss-instruct-sc2-concepts |
def oauth2_client_id() -> str:
"""The Oauth client id obtained from the BingAds developer center"""
return 'abc1234-1234-1234-abc-abcd1234' | bigcode/self-oss-instruct-sc2-concepts |
import math
def date_label(i):
"""
Helper funtion, label 67 quarters, from 2000q1 to 2016q3.
Takes current iteration and returns quarter label.
"""
dlab = '{0}q{1}'
# count years
yr = 2000 + math.floor(i/4)
# count quarters
qt = i % 4+1
return(dlab.format(yr, qt)) | bigcode/self-oss-instruct-sc2-concepts |
from datetime import datetime
def set_created_at(v):
"""
Set created_at field to current datetime
"""
return datetime.utcnow() | bigcode/self-oss-instruct-sc2-concepts |
def spring_torsion_torque_t31(hatch, tors_bar):
"""
Determine the torque due to the laminated torsion bar
The ICD for this part also calls for stress limit check
"""
torque_bar = - tors_bar.tors_stiff * (tors_bar.windup_angle - hatch.angle_range)
max_stress = ((tors_bar.lam_thick * tors_bar.sh... | bigcode/self-oss-instruct-sc2-concepts |
def client(app):
"""A test client for the app. You can think of the test like a web browser;
it retrieves data from the website in a similar way that a browser would.
"""
return app.test_client() | bigcode/self-oss-instruct-sc2-concepts |
def q_i(c1, **params):
"""
Implements Eq. 9.67 from Nawalka, Beliaeva, Soto (pg. 435)
Need params: k
"""
return 1 - params['k'] * c1 | bigcode/self-oss-instruct-sc2-concepts |
def load_dic(path):
"""
The format of word dictionary : each line is a word.
Args:
Input path
Returns:
load dict {k, v} = {term, id}
"""
dic = {}
with open(path) as f:
for id, line in enumerate(f):
w = line.strip()
dic[w] = id
return dic | bigcode/self-oss-instruct-sc2-concepts |
def make_base_metainfo() -> dict:
"""Return generic metainfo.
"""
return {
'uuid': '',
'path_to_content': '',
'path_to_preview': '',
'path_to_thumbnail': '',
'original_filename': '',
'original_name': '',
'original_extension': '',
'series': '... | bigcode/self-oss-instruct-sc2-concepts |
def kaimal(f, sigma2, **kwargs):
""" one-side Kaimal spectra, adopted in Amercian code ASCE7
Args:
f (1d-ndarray): freqency, unit: Hz
sigma2 (float): variance, (Iu * vz) ** 2
**kwargs: spectrum propeteries
z (float): height, unit:m
vz (float): mean wind speed at z heigh... | bigcode/self-oss-instruct-sc2-concepts |
def sec_dev(f, x, h=1e-6):
"""
Calculates the second derivative of a function at a given x, given a small h
"""
return (f(x - h) - 2 * f(x) + f(x + h)) / float(h**2) | bigcode/self-oss-instruct-sc2-concepts |
def coord_linha(c):
"""
coord_linha: coordenada --> inteiro positivo
coord_linha(c) tem como valor a linha da coordenada.
"""
return c[0] | bigcode/self-oss-instruct-sc2-concepts |
def anonymize_ip(real_ip: str) -> str:
"""
Sets the last byte of the IP address `real_ip`.
.. note::
It is a good step but it may be possible to find out the physical address
with some efforts.
Example:
If the input is "595.42.122.983", the output is "595.42.122.0".
Raises... | bigcode/self-oss-instruct-sc2-concepts |
import logging
def _get_logger(logger_name: str = "default_logger") -> logging.Logger:
"""Get logger for a given name.
Args:
logger_name (str, optional): Name of the logger (to retrieve).
Defaults to "default_logger"
Returns:
logging.Logger: Logger object
"""
return l... | bigcode/self-oss-instruct-sc2-concepts |
def round_temp(temperature):
"""Round a temperature to the resolution of the thermostat.
RadioThermostats can handle 0.5 degree temps so the input
temperature is rounded to that value and returned.
"""
return round(temperature * 2.0) / 2.0 | bigcode/self-oss-instruct-sc2-concepts |
def numéroPlusGrande(tas):
"""
numéroPlusGrand(tas) donne l'indice dans la liste d'entiers tas
du plus grand élément. Si la liste est vide, le résultat est -1 par
convention. On suppose les entiers positifs ou nuls.
"""
# Si le tas est vide, on rend la valeur -1
if tas == []:
return(-1)
# On trouve ... | bigcode/self-oss-instruct-sc2-concepts |
def create_intervals(interval_length: int, n_intervals: int):
"""
Creates the intervals for observations.
:param interval_length: Length of the one interval in seconds.
:param n_intervals: Number of intervals.
:return: List of intervals.
"""
return list(range(0, (interval_length * n_interval... | bigcode/self-oss-instruct-sc2-concepts |
def strip_flags(flags):
"""
Remove leading and trailing spaces from the list of flags.
:param flags: The list of flags which should be stripped.
:type flags: list[str]
:rtype: list[str]
:return: The list of flags with leading and trailing spaces removed.
"""
return [flag.strip() for fla... | bigcode/self-oss-instruct-sc2-concepts |
def hexStrToInt(inputstr):
"""
Converts a string with hex bytes to a numeric value
Arguments:
inputstr - A string representing the bytes to convert. Example : 41414141
Return:
the numeric value
"""
valtoreturn = 0
try:
valtoreturn = int(inputstr,16)
except:
valtoreturn = 0
return valtoreturn | bigcode/self-oss-instruct-sc2-concepts |
def rgb2lab(R_G_B):
"""Convert RGB colorspace to Lab
Adapted from http://www.easyrgb.com/index.php?X=MATH.
"""
R, G, B = R_G_B
# Convert RGB to XYZ
var_R = ( R / 255.0 ) # R from 0 to 255
var_G = ( G / 255.0 ) # G from 0 to 255
var_B = ( B / 255.0 ) ... | bigcode/self-oss-instruct-sc2-concepts |
def convert_bytes(tot_bytes):
"""Convert bytes to human-readable GB, MB, KB.
Parameters
----------
tot_bytes : int
Total number of bytes.
Returns
-------
[GB, MB, KB, rem] : list
Bytes divided into Giga, Mega, Kilo bytes.
"""
GB, rem = divmod(tot_bytes, 1024 * 1024 ... | bigcode/self-oss-instruct-sc2-concepts |
def log_index(caplog, loggerpart, level, msg, after=0):
"""Find a log in line in the captured log, return the index of the first occurrence
:param after: only consider records after the given index"""
close = []
for i, (logger_name, log_level, message) in enumerate(caplog.record_tuples[after:]):
... | bigcode/self-oss-instruct-sc2-concepts |
def low_left_digit(in_txt):
"""
Return the digit in the lower left corner for the board 'in_txt'
given as a 81 length string.
"""
return(in_txt[9*8 + 0]) | bigcode/self-oss-instruct-sc2-concepts |
from typing import Iterable
def loadtest_base_name(scenario_name: str, uniquifiers: Iterable[str]) -> str:
"""Constructs and returns the base name for a LoadTest resource."""
elements = scenario_name.split('_')
elements.extend(uniquifiers)
return '-'.join(elements) | bigcode/self-oss-instruct-sc2-concepts |
def _subs(value):
"""Return a list of subclass strings.
The strings represent the ldap objectclass plus any subclasses that
inherit from it. Fakeldap doesn't know about the ldap object structure,
so subclasses need to be defined manually in the dictionary below.
"""
subs = {'groupOfNames': ['k... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def _get_entropy(p):
"""
Compute entropy of the input prob vector p
Inputs:
p -- torch variable, a list of prob vectors
Outputs:
entropy -- the average entropy of all the vectors
"""
log_p = torch.log(p)
return torch.mean(- p * log_p) | bigcode/self-oss-instruct-sc2-concepts |
import json
def get_json_columns(json_file_or_dict, check_row_count=1):
"""Determines the names of columns in a JSON file
Args:
json_file_or_dict (str or dict): The file name of the JSON file, or a dict
check_row_count (int, optional): The number of rows to use to get columns
Returns:
... | bigcode/self-oss-instruct-sc2-concepts |
import re
def get_error_num(function):
"""
Extract first number from function name and return string with it.
Leading zeroes will be truncated.
"""
match_obj = re.search(r"\d+", function.__name__)
if match_obj is None:
return "0"
result = match_obj.group(0).lstrip("0")
if resu... | bigcode/self-oss-instruct-sc2-concepts |
import base64
def _base64encode_dict(dict_):
"""
Base64-encode all `bytes`-items in this `dict_` and recursively in all sub-dicts.
:param dict dict_: dict, potentially containing bytes objects
:returns: dict with bytes-objects base64-encoded
"""
def _encoded(val):
if isinstance(val, by... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Dict
from typing import Any
def txt_to_dict(txt_val: str) -> Dict[str, Any]:
"""
Return dict from string of "key:val; key2:val2" pairs.
Parameters
----------
txt_val : str
The key/value string (items separated by ";",
key/value separated by ":")
Returns
... | bigcode/self-oss-instruct-sc2-concepts |
def has_key(dictionary, key) -> bool:
"""Dictionary contain the key."""
return key in dictionary.keys() | bigcode/self-oss-instruct-sc2-concepts |
def separateUnit(string):
"""
Separates the unit and number in given string
e.g. '1 em' will return (float(1), 'em')
"""
# create an array of valid numbers (and '.')
nums = ['.'] + [str(x) for x in range(10)]
num_str = str()
unit_str = str()
# find first char in string that i... | bigcode/self-oss-instruct-sc2-concepts |
def dict_has_key(target_dict, key):
"""
Judge if target_dict has target key
"""
return key in target_dict | bigcode/self-oss-instruct-sc2-concepts |
def duration_str(s):
"""
s: number of seconds
Return a human-readable string.
Example: 100 => "1m40s", 10000 => "2h46m"
"""
if s is None:
return None
m = int(s // 60)
if m == 0:
return "%.1fs" % s
s -= m * 60
h = int(m // 60)
if h == 0:
return "%dm%d... | bigcode/self-oss-instruct-sc2-concepts |
def read_file(path):
"""Returns file content as string."""
file_handler = open(path, 'r')
content = file_handler.read()
file_handler.close()
return content | bigcode/self-oss-instruct-sc2-concepts |
def diff(list1, list2):
"""
Difference between unique elements of lists
:type list1: list
:param list1: first list
:type list2: list
:param list2: second list
"""
c = set(list1).union(set(list2))
d = set(list1).intersection(set(list2))
return list(c - d) | bigcode/self-oss-instruct-sc2-concepts |
def manage_met(met_input):
"""Manage metadata."""
final = []
with open(met_input, 'r') as metadata:
for i in metadata:
i = i.strip().split('\t')
result = [j.strip() for j in i]
final.append(result)
return(final) | bigcode/self-oss-instruct-sc2-concepts |
def get_release_status(release):
"""
:param release: helm release metadata
:return: status name of release
"""
return release['info']['status'] | bigcode/self-oss-instruct-sc2-concepts |
def fix_constants(constants):
"""Given a dict of constant parameters this function returns a fixer
function that updates the json to include these constants"""
def fix_const_updater(json):
json.update(constants)
return json
return fix_const_updater | bigcode/self-oss-instruct-sc2-concepts |
def rect_to_bounding_box(rect):
"""
Method for converting the dlib's rect object
to standard --coordinates of (x1, y1) and (x2, y2)
:param rect:
:return tuple: (x1, y1, x2, y2)
"""
x = rect.left()
y = rect.top()
w = rect.right() - x
h = rect.bottom() - y
return x, y, w, h | bigcode/self-oss-instruct-sc2-concepts |
def make_create_payload(**kwargs):
"""Create payload for upload/check-upload operations."""
# Remove empty arguments
for k, v in kwargs.items():
if not v:
del kwargs[k]
payload = {}
payload.update(kwargs)
return payload | bigcode/self-oss-instruct-sc2-concepts |
def tokenize(records):
"""Create a token mapping from objects to integers.
Parameters
----------
records : array_like of iterables.
Collection of nested arrays.
Returns
-------
enum_map : dict
Enumeration map of objects (any hashable) to tokens (int).
"""
unique_ite... | bigcode/self-oss-instruct-sc2-concepts |
def get_controller_object(controller):
"""
Get the object associated with a controller, or None if there's no object,
which is usually a group.
"""
controller_objects = controller.controllerObject.listConnections(s=True, d=False)
# controller_objects = pm.ls(cmds.listConnections(unicode(controlle... | bigcode/self-oss-instruct-sc2-concepts |
def convert_dict_keys(func, in_dict):
"""Apply a conversion function to all keys in a dict.
Parameters
----------
func : callable
The function to apply. Takes a str and returns a str.
in_dict : dict
The dictionary to convert. If some value in this dict is itself a dict,
it a... | bigcode/self-oss-instruct-sc2-concepts |
def overlap(response1, response2):
"""Any overlap between two responses?"""
if response1.protein == response2.protein:
coord2 = response2.coords
for i in response1.coords:
if i in coord2:
return True
return False | bigcode/self-oss-instruct-sc2-concepts |
def parse_bro_metadata(filename, meta_separator):
"""Parses Bro metadata.
This function parses Bro metadata that is encoded in the filename. The
parsed metadata can include any of the following, in order:
File source (e.g. HTTP, SMTP, SMB)
Connection UID
File UID
Originator ... | bigcode/self-oss-instruct-sc2-concepts |
def in_range(value, rng):
""" Check if value(s) are in the range of list[0], list[1] """
return (rng[0] <= value).all() and (value <= rng[1]).all() | bigcode/self-oss-instruct-sc2-concepts |
def front(inlist):
"""
Pop from a list or tuple, otherwise return untouched.
Examples
--------
>>> front([1, 0])
1
>>> front("/path/somewhere")
'/path/somewhere'
"""
if isinstance(inlist, (list, tuple)):
return inlist[0]
return inlist | bigcode/self-oss-instruct-sc2-concepts |
def build_flags(flags):
"""Convert `flags` to a string of flag fields."""
return "\n".join([" flag: '" + flag + "'" for flag in flags]) | bigcode/self-oss-instruct-sc2-concepts |
def centers(array):
"""
Centers corresponding to bin edges (assuming regular linear intervals).
"""
return array[0: -1] + (0.5 * (array[1] - array[0])) | bigcode/self-oss-instruct-sc2-concepts |
def apache_client_convert(client_dn, client_ca=None):
"""
Convert Apache style client certs.
Convert from the Apache comma delimited style to the
more usual slash delimited style.
Args:
client_dn (str): The client DN
client_ca (str): [Optional] The client CA
Returns:
t... | 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.