seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
from typing import Dict
def calculateHandlen(hand: Dict[str, int]) -> int:
"""Calculate hand length
Args:
hand:
Returns:
int: the length (number of letters) in the current hand.
"""
return sum(hand.values()) | bigcode/self-oss-instruct-sc2-concepts |
def normalize_url(url: str) -> str:
"""Normalize URL
Arguments:
url {str} -- A URL
Returns:
str -- A normalized URL
"""
# remove string after "?" to comply with Pydantic AnyHttpUrl validation
# e.g. http:/example.com/test.js?foo=bar to http://example.com/test.js
splitted = ... | bigcode/self-oss-instruct-sc2-concepts |
import math
def calculate_tail_correction(num_particles, box_length, cutoff):
"""
The tail correction associated with using a cutoff radius.
Computes the tail correction based on a cutoff radius used in the LJ energy calculation in reduced units.
Parameters
----------
num_particles :... | bigcode/self-oss-instruct-sc2-concepts |
def get_surt_association_script(surt, sheet):
"""Creates the beanshell script for a SURT->Sheet association."""
return "appCtx.getBean(\"sheetOverlaysManager\").addSurtAssociation(\"%s\", \"%s\" );" % (surt, sheet) | bigcode/self-oss-instruct-sc2-concepts |
def get_citation_links(session, profile_url):
"""
From the given url to Google scholar page, extract all absolute links to
paper citations.
Args:
session (HTMLSession)
profile_url (str): a url to a person's Google Scholar page.
Returns:
list: list of absolute URLs to paper ci... | bigcode/self-oss-instruct-sc2-concepts |
from operator import add
def element_wise(list1, list2):
"""
Perform element wise sum between two lists.
"""
return list(map(add, list1, list2)) | bigcode/self-oss-instruct-sc2-concepts |
import torch
def sum_rightmost(value: torch.Tensor, dim: int):
"""Sum out ``dim`` many rightmost dimensions of a given tensor.
Args:
value: A tensor of ``.dim()`` at least ``dim``.
dim: The number of rightmost dims to sum out.
"""
if dim == 0:
return value
required_shape =... | bigcode/self-oss-instruct-sc2-concepts |
from pathlib import Path
from typing import Optional
def load_latest_model(model_folder: Path) -> Optional[Path]:
"""Finds the latest model inside the folder where
all the models are saved
Args:
model_folder (Path): folder containing the models
Returns:
Path: file path of the most re... | bigcode/self-oss-instruct-sc2-concepts |
def Mgap(d, Cij):
"""
returns the resonator gap between the lid and resonator to provide the necessary capacitance:
given the capacitance and resonator diameter
equation 13
"""
return 0.695*d*d/(100*Cij-2.61*d) | bigcode/self-oss-instruct-sc2-concepts |
def load_events(filename, energy_thr = 0.01, nof_events = -1):
"""
load photon events from a text file (W,E,X,Y,Z,WX,WY,WZ), remove events with energy below threshold
:param filename: file name to load events from
:param energy_thr: energy threshold, events with energy below threshold will be thrown out... | bigcode/self-oss-instruct-sc2-concepts |
def bytes_to_hex(bytes_str):
"""Convert a byte string to it's hex string representation"""
return ''.join(["%02X " % ord(x) for x in bytes_str]).strip() | bigcode/self-oss-instruct-sc2-concepts |
def prefix(values, content):
"""
Discover start and separate from content.
Will raise ValueError if none of the starts match.
"""
for value in values:
if content.startswith(value):
break
else:
raise ValueError('invalid starts')
content = content[len(value):... | bigcode/self-oss-instruct-sc2-concepts |
def add_inputs(input_1: float, input_2: float, *extra) -> float:
"""
adds 2 or more numbers together
:param input_1: first number
:type input_1: float
:param input_2: second number
:type input_2: float
:return: all the inputs added together
:rtype: float
"""
... | bigcode/self-oss-instruct-sc2-concepts |
def applianceSystemStoragePath(config):
"""
Returns the path to the internal appliance persistent storage.
"""
return config['storage.system.path'] | bigcode/self-oss-instruct-sc2-concepts |
import math
def DistanceBetweenCoordinates(lat1, lon1, lat2, lon2):
"""Distance between two coordinate pairs (in km)
Based on:
http://cyberpython.wordpress.com/2010/03/31/python-calculate-the-distance-between-2-points-given-their-coordinates/
"""
lat1_r = math.radians(lat1)
lat2_r = math.radians(lat2)
l... | bigcode/self-oss-instruct-sc2-concepts |
import json
def read_result(outfile):
""" Reads the result of an experiment """
return json.load(open(outfile, "rb")) | bigcode/self-oss-instruct-sc2-concepts |
def directory_structure(tmpdir):
"""Create a directory structure like this:
root
_____|___________________
| | | |
repo Main.java epic.py other_repo
________|________ ______|_________
... | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
from typing import Union
from typing import Tuple
def linear_search(arr: List[Union[int, float, str]], ele: Union[int, float, str]) -> Union[Tuple[bool, int], Tuple[bool, None]]:
"""Linear search algorithm
Args:
arr (List[Union[int,float,str]]): array list to search
el... | bigcode/self-oss-instruct-sc2-concepts |
def _calculate_total_mass_(elemental_array):
"""
Sums the total weight from all the element dictionaries in the elemental_array after each weight has been added (after _add_ideal_atomic_weights_())
:param elemental_array: an array of dictionaries containing information about the elements in the system
... | bigcode/self-oss-instruct-sc2-concepts |
def _cleave(
sequence,
sites,
missed_cleavages,
min_length,
max_length,
semi,
clip_nterm_met,
):
"""Digest a protein sequence into its constituent peptides.
Parameters
----------
sequence : str
A protein sequence to digest.
sites : list of int
The cleavag... | bigcode/self-oss-instruct-sc2-concepts |
def find_link_href(links: list, rel: str) -> str:
"""Extract link href by rel for linkdto instances."""
return next(l for l in links if l.rel == rel).href | bigcode/self-oss-instruct-sc2-concepts |
def _no_spaces(string, replace_with='_'):
"""
Remove whitespace from a string, replacing chunks of whitespace with a
particular character combination (replace_with, default is underscore)
"""
return replace_with.join(string.split()) | bigcode/self-oss-instruct-sc2-concepts |
from typing import Dict
from typing import Any
def __get_cumulative_cases_count(data_json: Dict[str, Any]) -> int:
"""
Returns the cumulative number of cases stored in the given data point.
"""
try:
return data_json["cumCasesByPublishDate"]
except KeyError:
return 0 | bigcode/self-oss-instruct-sc2-concepts |
def get_copy(o, copy):
"""Returns copy of object."""
if copy:
return copy(o)
else:
return o | bigcode/self-oss-instruct-sc2-concepts |
from typing import Dict
from typing import Tuple
def calc_nsplits(chunk_idx_to_shape: Dict[Tuple[int], Tuple[int]]) -> Tuple[Tuple[int]]:
"""
Calculate a tiled entity's nsplits.
Parameters
----------
chunk_idx_to_shape : Dict type, {chunk_idx: chunk_shape}
Returns
-------
nsplits
... | bigcode/self-oss-instruct-sc2-concepts |
import typing
def IndentList(num_spaces: int, strings: typing.List[str]) -> typing.List[str]:
"""Indent each string in a list of strings by a number of spaces.
Args:
num_spaces: The number of spacces to indent by. Must be greater than or
equal to zero.
strings: The list of strings to indent.
... | bigcode/self-oss-instruct-sc2-concepts |
def overlapped_slices(bbox1, bbox2):
"""Slices of bbox1 and bbox2 that overlap
Parameters
----------
bbox1: `~scarlet.bbox.Box`
bbox2: `~scarlet.bbox.Box`
Returns
-------
slices: tuple of slices
The slice of an array bounded by `bbox1` and
the slice of an array bounded ... | bigcode/self-oss-instruct-sc2-concepts |
def format_list(list1, fmt = '%16s', delimiter = ","):
"""
format list of numbers to string.
delimiter defaults = ','
"""
string1 = delimiter.join(fmt % h for h in list1) + '\n'
return string1 | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
def piecewise_volume_conversion(
ul: float, sequence: List[List[float]]) -> float:
"""
Takes a volume in microliters and a sequence representing a piecewise
function for the slope and y-intercept of a ul/mm function, where each
sub-list in the sequence contains:
... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Any
def add_price_in_dollars(row: Any) -> float:
"""
Calculate the price in dollars by converting the value of the 'priceInCents` to dollars.
Args:
row: The pandas row to be analysed
Raises:
N/A
Returns:
dollars: The price in dollars, calculated from the... | bigcode/self-oss-instruct-sc2-concepts |
import math
def square_image_shape_from_1d(filters):
"""
Make 1d tensor as square as possible. If the length is a prime, the worst case, it will remain 1d.
Assumes and retains first dimension as batches.
"""
height = int(math.sqrt(filters))
while height > 1:
width_remainder = filters % height
if ... | bigcode/self-oss-instruct-sc2-concepts |
def filter_per_split(dataset, train=True):
""" Filter samples depending on their split """
return dataset['is_train'] if train else ~dataset['is_train'] | bigcode/self-oss-instruct-sc2-concepts |
def has_dependencies(node, dag):
"""Checks if the node has dependencies."""
for downstream_nodes in dag.values():
if node in downstream_nodes:
return True
return False | bigcode/self-oss-instruct-sc2-concepts |
def static_vars(**kwargs):
"""
Custom decorator to allow declaration of static variables like this:\n
@static_var(variable = 0)\n
def foo(parameters):\n
foo.variable += 1
"""
def decorate(func):
for k in kwargs:
setattr(func, k, kwargs[k])
return func
retu... | bigcode/self-oss-instruct-sc2-concepts |
import re
def realname(module_name):
"""
Return the real name of a module. The real name of a modules
is in lower snake_case.
Transform a CamelCase name into snake_case name.
"""
reg_first = re.compile(r'(.)([A-Z][a-z]+)')
reg_all = re.compile(r'([a-z0-9])([A-Z])')
s1 = reg_first.sub(r... | bigcode/self-oss-instruct-sc2-concepts |
def is_callback(func):
"""Check if function is callback."""
return "_pyhap_callback" in getattr(func, "__dict__", {}) | bigcode/self-oss-instruct-sc2-concepts |
def has_points(user, points):
"""Returns True if the user has more than the specified points."""
return user.get_profile().points() >= points | bigcode/self-oss-instruct-sc2-concepts |
def get_fig_size(ratio=None, scale=None):
"""Get size of figure given a ratio and a scale.
Parameters
----------
ratio: float
Something like 16:9 or 4:3
scale: float
A multiplicative factor to ccale the original figure keeping its ratio"""
ratio = 4 / 3.0 if ratio is None else r... | bigcode/self-oss-instruct-sc2-concepts |
def is_article_link(wikilink):
"""Return True is wikilink is an article link.
Parameters
----------
wikilink : str
Wikilink to be tested
Returns
-------
result : bool
True is wikilink is an article link
Examples
--------
>>> is_article_link('[[Danmark]]')
T... | bigcode/self-oss-instruct-sc2-concepts |
def timeToSeconds(d: int = 0, h: int = 0, m: int = 0, s: float = 0.0) -> float:
""" Return 'seconds' representation of a given time as defined by days, hours,
minutes and seconds.
Args:
d: number of days to add to returned seconds.
h: number of hours to add to returned seconds.
m: n... | bigcode/self-oss-instruct-sc2-concepts |
def dicts_are_consistent(d1: dict, d2: dict) -> bool:
"""
checks if all items whose keys are in (d1 and d2) are equal.
returns bool.
"""
return all(d1[k] == d2[k] for k in set(d1).intersection(set(d2))) | bigcode/self-oss-instruct-sc2-concepts |
def get_number_line(selected_file: str) -> int:
""" Return a int with the number line from sentences.txt """
with open(selected_file) as f:
return sum(1 for line in f) | bigcode/self-oss-instruct-sc2-concepts |
def read_input(path: str):
"""
Read game board file from path.
Return list of str.
"""
with open(path, mode='r', encoding='utf-8') as data:
content = data.readlines()
for i in range(len(content)):
content[i] = content[i].strip()
return content | bigcode/self-oss-instruct-sc2-concepts |
def _GetProcStatusPath(pid):
"""Returns the path for a PID's proc status file.
@type pid: int
@param pid: Process ID
@rtype: string
"""
return "/proc/%d/status" % pid | bigcode/self-oss-instruct-sc2-concepts |
import torch
def gaussian_radius(det_size, min_overlap=0.5):
"""Get radius of gaussian.
Args:
det_size (tuple[torch.Tensor]): Size of the detection result.
min_overlap (float): Gaussian_overlap. Defaults to 0.5.
Returns:
torch.Tensor: Computed radius.
"""
height, width = ... | bigcode/self-oss-instruct-sc2-concepts |
def action_of(origin: str, destination: str) -> int:
"""Finds which action was taken from origin to destination.
If the states origin and destination are separated by one action, it returns
the numeric value of the action taken (0 = up, 1 = right, 2 = down, 3 = left).
It returns -1 if they are separate... | bigcode/self-oss-instruct-sc2-concepts |
def title(name):
""" Write title keyword"""
return [f'*TITLE\n{name:s}\n'] | bigcode/self-oss-instruct-sc2-concepts |
def get_resource_requests_from_networktab(networktab):
"""
Parse `networktab` to extract only `ResourceSendRequest` information.
"""
events = networktab['traceEvents']
network_events = []
for event in events:
if event['name'] == 'ResourceSendRequest':
network_events.append(ev... | bigcode/self-oss-instruct-sc2-concepts |
def Vdiode(Icell, Vcell, Rs):
"""
Calculate Vdiode from current, voltage and series resistance.
:param Icell: cell current [A]
:param Vcell: cell voltage [V]
:param Rs: cell series resistance [:math:`\Omega`]
:return: diode voltage [V]
"""
return Vcell + Icell * Rs | bigcode/self-oss-instruct-sc2-concepts |
from functools import reduce
import operator
def product(iterable):
"""
Returns the product of an iterable
If the list is empty, returns 1
"""
product = reduce(operator.mul, iterable, 1)
return product | bigcode/self-oss-instruct-sc2-concepts |
def nested_value(d, keys):
"""Access an element in nested dictioary `d` with path given by list of `keys`"""
for k in keys:
d = d[k]
return d | bigcode/self-oss-instruct-sc2-concepts |
def to_hex(payload):
"""
Converts an int or long to hex but removes the "0x" at the start.
@rtype: str
@return: A string representing the number in hex without "0x".
"""
return hex(payload)[2:] | bigcode/self-oss-instruct-sc2-concepts |
def GetRank(text, header):
"""
Get the rank under header.
Possible Headers: Tournament results, Match results
"""
headerStart = text.find(header)
found = text.find("Yomi AI", headerStart)
if found == -1:
raise Exception("MAJOR PARSING ERROR. Yomi AI text not found.")
en... | bigcode/self-oss-instruct-sc2-concepts |
def dump(file_path, yaml, objyaml):
"""Write the value of objyaml into file path."""
def start_end_lines(input_str):
"""Return formatted string"""
return "---\n{0}---\n".format(input_str)
with open(file_path, 'w') as target_yaml_file:
yaml.dump(objyaml, target_yaml_file, transform=st... | bigcode/self-oss-instruct-sc2-concepts |
import time
def timestamp_datetime(value):
"""
transfer unix time to formatted timestamp.
Args:
value (int): unix time.
Returns:
str: formatted time.
"""
time_format = '%Y-%m-%dT%H:%M:%S%z'
time_struct = time.localtime(value)
return time.strftime(time_format, time_str... | bigcode/self-oss-instruct-sc2-concepts |
def adt_object_to_element_name(adt_object):
"""Returns XML element name for the given adt_object"""
objtype = adt_object.objtype
return f'{objtype.xmlnamespace.name}:{objtype.xmlname}' | bigcode/self-oss-instruct-sc2-concepts |
def max_discharge_rule(mod, s, tmp):
"""
**Constraint Name**: Stor_Max_Discharge_Constraint
**Enforced Over**: STOR_OPR_TMPS
Storage discharging power can't exceed available capacity.
"""
return mod.Stor_Discharge_MW[s, tmp] \
<= mod.Capacity_MW[s, mod.period[tmp]] \
* mod.Avail... | bigcode/self-oss-instruct-sc2-concepts |
def add_eprint_to_bib(bib, eprint):
"""
Insert the eprint information in a given bibtex string
Parameters
----------
bib: str
The bibtex string without the arxiv number
eprint: str
The arxiv number
Returns
-------
bib: str
The bibtex ... | bigcode/self-oss-instruct-sc2-concepts |
def get_throw_descriptions(get_nb_floor_objects, initial_state, current_state):
"""
Get all 'throw' descriptions from the current state (if any).
Parameters
----------
get_nb_floor_objects: function
Function that gets the number of objects thrown on the floor of the current state compared to... | bigcode/self-oss-instruct-sc2-concepts |
def _merge(listA, listB):
""" Merges two list of objects removing
repetitions.
"""
listA = [x.id for x in listA]
listB = [x.id for x in listB]
listA.extend(listB)
set_ = set(listA)
return list(set_) | bigcode/self-oss-instruct-sc2-concepts |
def relu_backward(z, a_grad):
"""relu反向
:param z: shape[Out]
:param a_grad: shape[Out]
:return: shape[Out]
"""
return a_grad * (z > 0) | bigcode/self-oss-instruct-sc2-concepts |
import random
def randpop(seq):
""" removes and returns a random item from the sequence """
return seq.pop(random.randrange(len(seq))) | bigcode/self-oss-instruct-sc2-concepts |
import threading
def startWithCallback(process, onExit):
"""
Call process.start(), and then calls the function onExit when the
subprocess completes.
onExit is a callable object, will receive process as parameter.
"""
def runInThread(process, onExit):
process.join()
onExit(proc... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Iterable
def read_nested_dict_value(nested_dict, nested_keys: Iterable, default_value=None, error_on_miss=False):
"""
Read a value from a series of nested dictionaries, such as returned by ruamel.yaml
:param nested_dict: The nested dictionaries (configuration map) to read from
:par... | bigcode/self-oss-instruct-sc2-concepts |
import re
def update_max_version(src, key, new_max_version, category):
"""
Examples
========
>>> src = '''
... sklearn:
... ...
... models:
... minimum: "0.0.0"
... maximum: "0.0.0"
... xgboost:
... ...
... autologging:
... minimum: "1.1.1"
.... | bigcode/self-oss-instruct-sc2-concepts |
def c2k(c: float, r: int = 2) -> float:
"""Celsius to Kelvin."""
return round(c + 273.15, r) | bigcode/self-oss-instruct-sc2-concepts |
def drop_duplicates(data):
"""Drop duplicate rows in a DataFrame."""
return data.drop_duplicates() | bigcode/self-oss-instruct-sc2-concepts |
def fixIoU(bb1, bb2):
"""
Calculate the fix Intersection over Union (IoU) of two bounding boxes.
fixiou = intersection_area / min(bb1_area, bb2_area)
Parameters
----------
bb1 : set
Keys: ('x1', 'y1', 'x2', 'y2')
The (x1, y1) position is at the top left corner,
the ... | bigcode/self-oss-instruct-sc2-concepts |
import pickle
def load_pickle(parent_dir):
"""
Accepts a parent directory Path object
which can contain only one pickled file with a .pkl extension
Finds the file, loads it, and returns it
"""
# print(parent_dir)
filepath = list(parent_dir.glob('*.pkl'))[0]
with open(str(filepath), 'rb... | bigcode/self-oss-instruct-sc2-concepts |
def date_to_epoch(date):
"""Convert a datetime stamp to epoch time."""
epoch_time = date.strftime('%s')
return int(epoch_time) | bigcode/self-oss-instruct-sc2-concepts |
def ParseAction(messages, action):
"""Converts an action string to the corresponding enum value.
Options are: 'allow' or 'deny', otherwise None will be returned.
Args:
messages: apitools.base.protorpclite.messages, the proto messages class for
this API version for firewall.
action: str, the action... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def pad_charts(charts, padding_value=-100):
"""Pad a list of variable-length charts with `padding_value`."""
batch_size = len(charts)
max_len = max(chart.shape[0] for chart in charts)
padded_charts = torch.full(
(batch_size, max_len, max_len),
padding_value,
dtype=... | bigcode/self-oss-instruct-sc2-concepts |
def array_to_string(array):
"""Turns a array into a string separated by §."""
string = ''
for s in array:
string += '§' + s
return string[1:] | bigcode/self-oss-instruct-sc2-concepts |
from typing import Dict
def _filter_frequency(ngrams: Dict[str, int], min_freq: int) -> Dict[str, int]:
"""
Filter a ngram list for ngrams with a minimum frequency.
:param ngrams:
:param min_freq:
:return:
"""
output = {}
for (ngram, freq) in ngrams.items():
if freq >= min_fre... | bigcode/self-oss-instruct-sc2-concepts |
def convert_postag(pos):
"""Convert NLTK POS tags to SentiWordNet's POS tags."""
if pos in ['VB', 'VBD', 'VBG', 'VBN', 'VBP', 'VBZ']:
return 'v'
elif pos in ['JJ', 'JJR', 'JJS']:
return 'a'
elif pos in ['RB', 'RBR', 'RBS']:
return 'r'
elif pos in ['NNS', 'NN', 'NNP', 'NNPS']:... | bigcode/self-oss-instruct-sc2-concepts |
def get_hierarchical_net_pos(net):
""" Get x,y positions for plotting hierarchical graph.
For example:
.. plot::
:include-source:
>>> import graphy
>>> G = graphy.graphgen.gen_hierarchical_net(5, 2)
>>> pos = graphy.graphgen.get_hierarchical_net_pos(G)
>>> graphy.p... | bigcode/self-oss-instruct-sc2-concepts |
from typing import OrderedDict
def ordered_dict(iterable):
"""Create an OrderedDict from an iterable of (key, value) tuples.
"""
ordict = OrderedDict()
for key, value in iterable:
ordict[key] = value
return ordict | bigcode/self-oss-instruct-sc2-concepts |
def pick_third_largest_num(sequence: list[int]) -> int:
"""数列から3番目に大きい整数を取得する
Args:
sequence (list): 整数のリスト
Returns:
(int): 3番目に大きい整数
"""
return sorted(sequence)[-3] | bigcode/self-oss-instruct-sc2-concepts |
def build_gnab_feature_id(gene_label, genomic_build):
"""
Creates a GNAB v2 feature identifier that will be used to fetch data to be rendered in SeqPeek.
For more information on GNAB feature IDs, please see:
bq_data_access/data_types/gnab.py
bq_data_accvess/v2/gnab_data.py
Params:
gene... | bigcode/self-oss-instruct-sc2-concepts |
def domains_to_samples(domains, sample_column='contig_id', target_column=None):
"""
Group Domain DataFrame into a list of DataFrames and list of output states based on given sample_id column
:param domains: Domain DataFrame with multiple sequences (samples), each marked by a unique ID in the sample_column
... | bigcode/self-oss-instruct-sc2-concepts |
def EncodePrivate(sk):
"""
Encode a private key into bytes (exactly 32 bytes for both
do255e and do255s).
"""
return bytes(sk) | bigcode/self-oss-instruct-sc2-concepts |
import re
def get_prefixlength(ip):
"""Returns the length of the network prefix, in bits."""
regex = r'(\d+)[.](\d+)[.](\d+)[.](\d+)[/](\d+)'
if not re.findall(regex, ip):
return ip
p = re.split(regex, ip)
return int(p[5]) | bigcode/self-oss-instruct-sc2-concepts |
from typing import Dict
import pathlib
import json
def load_git_info(input_path=None) -> Dict[str, str]:
"""
Load previously saved output of git_info from a json file.
Args:
input_path: Input path to json file. If None, the default will be
bclustering/git_info.json
Returns:
... | bigcode/self-oss-instruct-sc2-concepts |
def OutputGraphViz(scenario, final_tasks, output):
"""Outputs the build dependency graph covered by this scenario.
Args:
scenario: The generated scenario.
final_tasks: The final tasks used to generate the scenario.
output: A file-like output stream to receive the dot file.
Graph interpretations:
... | bigcode/self-oss-instruct-sc2-concepts |
def Linear(score, score_min, score_max, val_start, val_end):
"""Computes a value as a linear function of a score within given bounds.
This computes the linear growth/decay of a value based on a given score.
Roughly speaking:
ret = val_start + C * (score - score_min)
where
C = (val_end - val_start) /... | bigcode/self-oss-instruct-sc2-concepts |
def bytes_packet(_bytes, termination_string=']'):
"""
Create a packet containing the amount of bytes for the proceeding data.
:param _bytes:
:param termination_string:
:return:
"""
return '{}{}'.format(len(_bytes), termination_string) | bigcode/self-oss-instruct-sc2-concepts |
def all_besides_none_equal(*args):
"""Return True if all of the (non-None) elements are equal"""
non_none = list(filter(lambda x: x is not None, args))
for i, arg in enumerate(non_none):
if i + 1 < len(non_none) and arg != args[i + 1]:
print(arg)
return False
return True | bigcode/self-oss-instruct-sc2-concepts |
import math
def compute_rows_columns(num_wells):
"""Convert 96->(8,12), 384->(16,24), etc."""
a = math.sqrt(num_wells / 6)
n_rows = int(round(2 * a))
n_columns = int(round(3 * a))
return n_rows, n_columns | bigcode/self-oss-instruct-sc2-concepts |
def skip_zone_record(zone_record):
"""Whether a zone record should be skipped or not.
Records are skipped if they are empty or start with
a # (indicating a comment).
:param zone_record: Full zone record, including the command (e.g. ADD).
:returns: True if the record should be skipped, false otherw... | bigcode/self-oss-instruct-sc2-concepts |
def map_value(value, min_, max_):
"""
Map a value from 0-1 range to min_-max_ range.
"""
return value * (max_ - min_) + min_ | bigcode/self-oss-instruct-sc2-concepts |
def check_influxdb_response(response):
"""Check if the response from influxdb is correct.
InfluxDB normally responds with a 404 on GET to /, but also allow other
non-server-error response codes to allow for that behaviour to change.
"""
return response.code < 500 | bigcode/self-oss-instruct-sc2-concepts |
def dop2str(dop: float) -> str:
"""
Convert Dilution of Precision float to descriptive string.
:param float dop: dilution of precision as float
:return: dilution of precision as string
:rtype: str
"""
if dop == 1:
dops = "Ideal"
elif dop <= 2:
dops = "Excellent"
el... | bigcode/self-oss-instruct-sc2-concepts |
def get_complexity(data):
"""
Gets the complexity of the given trial data -- the number of degrees of
freedom that are active, or under control of the subject.
"""
return int(len(data['active_classes'])/2) | bigcode/self-oss-instruct-sc2-concepts |
def prepare_feed_dict(placeholders, images, labels, batch_size, use_generated_data, idx=0):
"""Return the feed dict per batch with the input data."""
idx = idx * batch_size
if use_generated_data:
return {
placeholders[0]: images
}
return {
placeholders[0]: images[idx:... | bigcode/self-oss-instruct-sc2-concepts |
def list2str_str(list):
"""Convert list to a single string. Inverse of str2list."""
return ''.join([str(i) + '\n' for i in list]) | bigcode/self-oss-instruct-sc2-concepts |
from typing import Union
def format_indexing_element(indexing_element: Union[int, slice]) -> str:
"""Format an indexing element.
This is required mainly for slices. The reason is that string representation of slices
are very long and verbose. To give an example, `x[:, 2:]` will have the following index
... | bigcode/self-oss-instruct-sc2-concepts |
def indent_string(the_string, indent_level):
"""Indents the given string by a given number of spaces
Args:
the_string: str
indent_level: int
Returns a new string that is the same as the_string, except that
each line is indented by 'indent_level' spaces.
In python3, this can be done ... | bigcode/self-oss-instruct-sc2-concepts |
def getSamplerFun(sampler, distributions):
"""
get distributions' function by class sampler.
Inputs:
sampler : sampler class, pydpm._sampler.Basic_Sampler;
distributions : [str] list of distributions;
Outputs:
funcs : {str: fun}, dict of distributions' functions;
... | bigcode/self-oss-instruct-sc2-concepts |
def line_intersects_segment(line, line_segment):
"""Returns the intersection the Line and LineSegment or None if they do
not intersect.
This function is useful for splitting polygons by a straight line.
"""
linesegform = line_segment.to_line()
if line.is_parallel_to(linesegform):
retur... | bigcode/self-oss-instruct-sc2-concepts |
import math
def calc_haversine_distance(p1, p2):
"""calculate haversine distance between two points
# formula info
# https://en.wikipedia.org/wiki/Haversine_formula
# http://www.movable-type.co.uk/scripts/latlong.html
Args
p1: tuple of (longitude, latitude) format containing int or float... | 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.