content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
from operator import lt
from operator import gt
def limit(x,llimit,ulimit):
"""Require x to be within upper and lower limits"""
return lt(gt(x,llimit),ulimit) | e0ce93033cc9150447afe35b3d236546b86707e2 | 607,939 |
def converte_char_int(caractere):
"""Converte um caractere para um inteiro segundo a tabela ASCII
com correção do valor segundo enunciado e uso da função ord(), para que:
'_' = 0, 'a' = 1, 'b' = 2, ..., 'z' = 26 e '.' = 27
Args:
caractere (str): caractere a ser convertido em inteiro
Retur... | ca59878c5b341cbad24e5f878aef184c7616e65d | 607,941 |
import re
def strip_default_values(string):
""" Strip default values from a C++ argument list. """
return re.sub(' *=[^,)]*', '', string) | 7b79126ce44c5447157eb544934104a053be259d | 607,943 |
def parse_uri(uri):
"""
URIs will take the form "rtp:ip_addr" so we just take the "ip_addr" part of the
URI and return it
"""
return uri.split(':')[-1] | 7f0ea6b5166b889af95bbcf15d2d72f6d98a5df2 | 607,948 |
def get_canonical_container_name(container):
"""Return the canonical container name, which should be
of the form dusty_<service_name>_1. Containers are returned
from the Python client with many names based on the containers
to which they are linked, but simply taking the shortest name
should be suff... | 6dd4dabf49d27e99e48025b81ef62789c09d30d8 | 607,955 |
def snorm_to_byte(x):
"""float x in [-1, 1] to an integer [0, 255]"""
return min(int((x + 1) * 128), 255) | a09d2b3c88e2fb9e1eb553ac9ffc44626f15a541 | 607,957 |
def dict_values_to_lists(input_dict):
"""
Converts all values in the dict to a list containing the value.
Args:
input_dict: any dict
Returns:
dict with values converted to lists
"""
if input_dict is None:
return None
for key in input_dict.keys():
input_dict... | 1424cf37049a5096e3bcc6e9f77fab741fa75270 | 607,959 |
def get_id_columns(df):
"""
Utility to identify columns that are some type of IDs and have unique values in every row
These columns can be deleted as they add no useful information for ML model
:param df: dataframe to check for ID columns
:return: list of ID columns
"""
id_cols = []
cols... | ae8b66e16e813bccf745ad34c54216ef6029ce0b | 607,960 |
def extract_layers_by_str(model, layers):
"""
Returns references to layers from model by name
Parameters
----------
model : torch.nn.Module
model where layers should be extracted from
layers : iterable of str
iterable which contains the names of the respective layers
Return... | 9c25579a129f45b16bf67f061497123dfd285f73 | 607,962 |
def get_recommend_portfolio(risk_level):
"""
Returns the investment percentages, based on risk_level:
* **none:** "100% bonds (AGG), 0% equities (SPY)"
* **low:** "60% bonds (AGG), 40% equities (SPY)"
* **medium:** "40% bonds (AGG), 60% equities (SPY)"
* **high:** "20% bonds (AGG... | f204b82731d1cb536fe190426c53c530f21a8057 | 607,964 |
def get_pred(succ):
"""Given a successor edge map, produce an inverted predecessor edge
map.
"""
out = {key: [] for key in succ}
for p, ss in succ.items():
for s in ss:
out[s].append(p)
return out | 658d96292d814915daea273bb7f943ca8c160f3a | 607,974 |
import calendar
def datetime_to_timestamp(value):
"""Converts a datetime to a Unix timestamp."""
return calendar.timegm(value.utctimetuple()) | 1524737517c6ab4b5a805cedd99e43c99d4cb842 | 607,978 |
def cuts(image):
"""Function to perform a double cut (vertical and horizontal) of the lesion. Takes a segmentation mask image as input,
and returns the vertical and horizontal cuts (2 for each dimension). It handles uneven shapes."""
center_h = image.shape[0] // 2 # The image shape contains a tuple with he... | 797252807fa180a11724ac437416620f0c2ce098 | 607,981 |
from typing import Union
from typing import Tuple
def _to_hours_mins_secs(time_taken: Union[float, int]) -> Tuple[int, int, int]:
"""Convert seconds to hours, mins, and seconds."""
mins, secs = divmod(time_taken, 60)
hours, mins = divmod(mins, 60)
return round(hours), round(mins), round(secs) | 7bd461300f338ec8b16e0a3a4c7cfc3c2d4463ee | 607,982 |
import re
def to_spacecase(string):
"""
Converts the given string to space-case.
>>> to_spacecase('helloWorld')
'Hello World'
>>> to_spacecase('__Init__File__')
'Init File'
>>> to_spacecase('')
''
>>> to_spacecase('Already Space Case')
'Already Space Case'
>>> to_spacecase... | ed78e01761aa66a37a8790809892d248ca6bafdf | 607,987 |
def basic_formatter(key, decimals):
"""Create a basic '<key>: <value>' formatting function
This factory creates a function that formats a specified key and with a
numerical value from a dictionary into a string.
Parameters
----------
key
The dictionary key to format.
decimals
... | 7a6a0e1926c5b114c8c0a80dd6ee9a2964822fea | 607,991 |
def update_model_indices_residual_model(model_indices, accepted_index, n_modelpoints):
"""Update model indices and number of points in the residual model."""
model_indices[1 : n_modelpoints + 1] = model_indices[:n_modelpoints]
n_modelpoints += 1
model_indices[0] = accepted_index
return model_indice... | bdb3c0697bc14256a144dbc3fe9d7afed8562a28 | 607,992 |
def modified_secant(f, x0, x1, x2, eps=5e-6, max_iterations=50):
"""
Function that finds a root using a modified Secant (or Inverse quadratic interpolation ) method for a given function
f(x). The function finds the root of f(x) with a predefined absolute accuracy epsilon. The function excepts three
star... | 8d9298d1d488a969c5e4a3410725bd34da358bc4 | 607,995 |
def wrapper_init(orig):
"""
A decorator for the progress bar constructor, to increase the update interval
to 1 sec (and thus reduce the amount of information generated)
"""
def wrapped_init(self, target, **kwargs):
kwargs['interval'] = 1
orig(self, target, **kwargs)
return wrapp... | 9a453118925db16444dc97285029494f42ee9b71 | 607,997 |
def bin_to_text(string: str) -> str:
"""
Convert Binary Numerical Values back to string
returns utf-8 String
:param string: Binary String
:return: str
Example:
>>> bin_to_text("1110100 1100101 1110011 1110100")
>>> 'test'
"""
return "".join([chr(int(binary, 2)) for binar... | 68da4581cfef91638dc6927f5e08f9732332e556 | 607,999 |
def toChoices(object_list):
"""A function to format a list of objects to a list of two-element
tuples expected by django select widgets. Of the form ('value','display')"""
if len(object_list[0]) == 2:
return [(x[1], x[1]) for x in object_list]
else:
return [(x[1], x[2]) for x in object_... | d1d22a98640fc90faa51ae380c706710a367f86d | 608,001 |
def make_album1(name, album, sta=''):
"""Display the singer's name and albums, the optional album numbers"""
# Define the dictionary
zj1 = {'n_name1': name, 'a_album1': album}
# if sta is true, add the sta into the dictionary
if sta:
zj1['sta'] = sta
# Return the dictionary
return zj... | 682eaf7ca0a8f96293f3d2f675db4c2d6bf1777c | 608,003 |
def validate_filter_size_3d(filter_size, in_depth, num_filter):
"""Validates filter size for 3d CNN operations"""
if isinstance(filter_size, int):
return [filter_size, filter_size, filter_size, in_depth, num_filter]
elif isinstance(filter_size, (tuple, list)):
len_filter = len(filter_size)
... | 3f0e878e9ae084905a15b50b09e8ab6f391201ff | 608,004 |
def add_colons(mac):
"""
Add colons to the given MAC address.
:param mac: MAC address to be added with colons.
"""
return ":".join(mac[_:_ + 2] for _ in range(0, len(mac), 2)) | af4bd9aacdd9fc494ae315deed9fd6ed210449a3 | 608,009 |
import json
def read_annots(coco_json, coco_names_path):
"""
Read annotations from VIA exported coco json
format and creates data dicts and names output
file.
Parameters
----------
coco_json : str
COCO json input file
coco_names_path : str
Names or labels output file
... | 8b75a05f8c5ca0025870657ff2394e4b5d9a0bad | 608,010 |
def get_assignment_dict(df, key_col, val_col):
"""Compute a dictionary from the given columns of the dataframe.
:df: Dataframe.
:key_col: Column name to be used for keys.
:val_col: Column name to be used for values.
:returns: Dictionary of {key: val} pairs from the given columns.
"""
dict_... | a2c4b60c65ffc70697f3b726772e7ec639cb4b1e | 608,012 |
import math
def distance_vehicle(waypoint, vehicle_transform):
"""
Returns the 2D distance from a waypoint to a vehicle
:param waypoint: actual waypoint
:param vehicle_transform: transform of the target vehicle
"""
loc = vehicle_transform.location
x = waypoint.transform.location.x... | 9c493f3742b686c7aa9457c7fabb40a090971b23 | 608,013 |
def _get_weights(G):
"""
Returns a list of the weights in the graph.
"""
Graph_data = list(G.edges_iter(data=True))
return [Graph_data[ii][2]['weight'] for ii in range(len(Graph_data))] | 12f3e4d5f7263751cae4f872ab518798feec6961 | 608,024 |
def extend_diff_outliers(diff_indices):
""" Extend difference-based outlier indices `diff_indices` by pairing
Parameters
----------
diff_indices : array
Array of indices of differences that have been detected as outliers. A
difference index of ``i`` refers to the difference between vol... | 8803567fdede0ad585dc21af4660dbc66838af07 | 608,028 |
import click
def print_result(result):
"""
Print successful result to the terminal.
"""
return click.echo(result) | fb34e935ee4f501136d4837d41c8accc4d9b0c91 | 608,031 |
def extension_to_ignore(file, ignore_extensions):
"""check if file need to be ignored
Args:
file (str): file_path or file_name
ignore_extensions (list): Extensions to ignore
Returns:
bol: True to ignore. False to not ignore.
"""
file_lower = file.lower()
if len(ignore_... | 8037f5d20790cb5d0118ed22e9f867744d98d6d2 | 608,032 |
def get_outputs(model, inputs, eval_functions, verbose=False):
"""
Gets the outputs of the Keras model.
Args:
model: Unused.
inputs: Input numpy arrays.
eval_functions: Keras functions for evaluation.
verbose: Whether to print evaluation metrics.
Returns:
List o... | 576489f6c8dedda3d1082bfc7add2f64c6838544 | 608,037 |
def get_cnot_control_positions(k):
"""
Returns a list of positions for the controls of the CNOTs used when
decomposing uniformly controlled rotations, as outlined in
arXiv:quant-ph/0407010.
Referencing Fig. 2 in the aforementioned paper, this method
uses the convention that, going up from the t... | dfc49255e45555b33c72dc686c538199fc8008ef | 608,039 |
def sample_details(document: dict) -> dict:
"""
Capture NWGC sample ID.
Capture details about the go/no-go sequencing call for this sample.
"""
return {
"nwgc_id": [document['sampleId']],
"sequencing_call": {
"comment": document['sampleComment'],
"initial": do... | 7dc937c3cbda35eef1496dfe6e76e813be1419f9 | 608,041 |
def rot13(ciphertext, step=13):
"""
Executes ROT 13 on ciphertext
It can be called with any ROT value; 13 is by default
"""
valid = ""
for x in range(0, len(ciphertext)):
# ROT13 only for ASCII codes from 97 to 122 decimal:
if ord(ciphertext[x]) in range(97, 122):
if... | 68afe9de6bce4086c2ff37df1f532552d04bfd13 | 608,043 |
import re
def name_key_function(name: str) -> str:
"""Order files that start with digits in numeric order so 2 is before 11.
Replace a run of digit characters at the start of the filename with a
5 character string padded out with leading zeros.
Also replace the same if immediately after a slash.
... | 3192c120db01a9d02bfbfb20f974f21e1a0e3b78 | 608,045 |
def is_sequence(obj):
"""
Grabbed from Python Cookbook / matplotlib.cbook. Returns true/false for
Parameters
----------
obj : iterable
"""
try:
len(obj)
return True
except TypeError:
return False | f4cdea43a7b7678861b3b7f58a9b9035fa2d741b | 608,046 |
def _create_session_data(database_name_to_path):
"""Create a nested dictionary with info to be passed between and within bokeh apps.
Args:
short_name_to_path (dict): mapping from the new unique names to their full path.
Returns:
session_data (dict): Infos to be passed between and within ap... | 97ae0e181f831e7f56e13b2bce0f86bfc10d258a | 608,047 |
def cumhist(hist):
"""Takes a histogram and makes a cumulative histogram out of it"""
ret = {}
cur = 0
for k in sorted(hist):
ret[k] = hist[k]+cur
cur = ret[k]
return ret | 587eae6b4fb0e8e67a4100f01ee41eb2f69f6e63 | 608,049 |
def k12_enrollment(parcels):
"""
Enrollment for grades kinder through 12th.
"""
return parcels['k6_enrollment'] + parcels['g7_8_enrollment'] + parcels['g9_12_enrollment'] | e1b8eca67d9e6f35883a2a15ed6f73f511ac4aba | 608,050 |
def auto_line_fitting_filter(param, i1, i2):
"""A filter function for fitting of a single calibration line.
Args:
param ():
i1 (int):
i2 (int):
Return:
bool:
"""
if param[0] <= 0.:
# line amplitdue too small
return False
if param[1] < i1 or param... | 89c76c42c80fef7432692521b63c1e2431df18bd | 608,051 |
def b_to_string(bytes, encoding='utf-8'):
""" Return utf-8 sting, terminating a first null byte"""
bytes = bytes.split(b'\0',1)[0]
string = str(bytes, encoding)
return string | 008e343de5c1148149b62cbd419db260cb0bf2ef | 608,052 |
def parse_data_resources(resource_map=None):
"""
Returns a list of data resources found in a PASTA resource map
"""
data_resources = []
if resource_map:
resources = resource_map.split('\n')
for resource in resources:
if '/data/' in resource:
data_resources... | 6ff01aa1b605a35ca9b89bf87abbff1fcf283332 | 608,056 |
def get_consumedTokens(t, net):
"""
Get tokens consumed firing a transition
Parameters
----------
t
Transition that should be enabled
net
Petri net
"""
consumed = 0
for a in t.in_arcs:
consumed = consumed + a.weight
return consumed | d35fd19b3037eab6c7f29b2a97c81375d22ff1a2 | 608,062 |
import math
def round_repeats(repeats, global_params):
"""
Round number of repeats based on depth multiplier.
Args:
repeats (int): the number of `MBConvBlock` int the stage, see: class: `EfficientNet`.
global_params (EasyDict): global args, see: class: `EfficientNet`.
Returns:
... | 7acc1af237164da4a0ef2eacf09ce43bc076d86c | 608,067 |
def get_network_stats(net):
"""Return the number of connections, neurons and layers."""
return net.get_num_connections(), net.num_neurons, len(net.neurons_in_layer) | 92a21407dc0fadb001c3ff54241993fda51f1db6 | 608,071 |
def getID(file):
"""
This function takes the PDB ID from DSSP file
:param file: input file in DSSP format
:return: PDB ID as string
"""
file.seek(0,0)
splited = []
for line in file:
splited = line.split()
if "HEADER" in line:
return splited[-2] | 997881515805d5e8c7eee3e04ffd7316b6412da5 | 608,072 |
def split_multiplier(string):
"""
Split a string of "1k" in number and letter.
:param string: number with character multiplier as string
:return: number, char
"""
nr = ''
tx = ''
for char in string:
if char.isdigit() or char == '-' or char == '.':
nr += char
... | f40350586641e59844982a486ea361500d48195d | 608,074 |
def parse_tablename(tablename):
"""Given tablename returns (service, name)."""
pieces = tablename.split(':')
if len(pieces) == 1:
return (None, pieces[0])
else:
return (pieces[0], ':'.join(pieces[1:])) | 2727ff87d07e6a5037f5ec323ee92ac7adb39095 | 608,076 |
def pad_lists(lists, pad_token=0):
""" Pads lists with trailing zeros to make them all the same length. """
max_list_len = max(len(l) for l in lists)
for i in range(len(lists)):
lists[i] += [pad_token] * (max_list_len - len(lists[i]))
return lists | 2808d1fb39d033350ed2bfa34356e57c7f2ba9b8 | 608,078 |
from datetime import datetime
def timeToMilli(time):
"""
Converts from a google revision timestamp into milliseconds since the Epoch
:param time: The timestamp to convert
:return: The timestamp in milliseconds
"""
return datetime.strptime(time,
"%Y-%m-%dT%H:%M:%S.... | 1f7391fbc95339bb9ab7b0a467f7201360c1c7bf | 608,080 |
import html
def clean_text(text):
"""
Remove extra quotes from text files and html entities
Args:
text (str): a string of text
Returns: (str): the "cleaned" text
"""
text = text.rstrip()
if '""' in text:
if text[0] == text[-1] == '"':
text = text[1:-1]
... | e0017878acc081e23c7cb9b09ddde01c7198f677 | 608,081 |
def add_at_idx(seq, k, val):
"""
Add (subtract) a value in the tuple at position k
"""
lst = list(seq)
lst[k] += val
return tuple(lst) | 8c827563937ab028a918b21d3bdcaf049a3c6159 | 608,082 |
def adjust_r2(r2, n, k):
"""
https://en.wikipedia.org/wiki/Coefficient_of_determination#Adjusted_R2
:param r2: R2 score (unadjusted yet)
:param n: Number of samples
:param k: Number of features
:return: Adjusted R2 score
"""
nom = (1-r2) * (n-1)
denom = n-k-1
if denom <= 0:
... | 75b239946bcc3a28e331e114f82a936f75ad74f1 | 608,083 |
import re
def remove_colon(string):
"""Remove the trailing colon from some lines."""
string = string.strip()
string = re.sub(r'\s*(?::|:)\s*', '', string)
return string | f4814fb8a171f026175bb8f4f9b36e43acff415e | 608,084 |
def get_folder_name(path: str):
"""Isolate directory name"""
name_folder = path.split('/')[-1]
return name_folder | c10c8cdc030a8d2303d2aa67b327e9bb617cb9aa | 608,086 |
import re
def is_integer(number):
"""Return True if number is an integer"""
pattern = r'^[-+]?[\d]+$'
return bool(re.search(pattern, str(number)))
pass | 68643d1ea51852afe1c905f384b96e6af3a35ad5 | 608,089 |
from typing import OrderedDict
def _limit_params(samples, selector=None):
"""Pick only the selected parameters from all samples.
Parameters
----------
samples : OrderedDict of np.arrays
selector : iterable of ints or strings, optional
Indices or keys to use from samples. Default to all.
... | b7d84fc5a74d6a0802098c561981f5561c3d6277 | 608,090 |
def generate_function_to_remove_element_from_list(functionName, listName):
"""Generate a Batch script function to remove element from a list.
As in Batch scripts it is not possible to dereference twice a variable,
it is easier to generate a function for each variable from which we want
to remove an ele... | 77ea142d65593b1fef75df28204d238cd576035f | 608,092 |
def getObjID(objName, objList):
"""
Returns an object's ID (int) given its 'objName' (str) and a reference 'objList' (list)
Format of 'objList' is [['name_1',id_1], ['name_2',id_2], ...]
"""
for i in range(0, len(objList)):
if objList[i][0] == objName:
return objList[i][1] | c67347031e05815f15d684c0439fa0afaa2bc88e | 608,095 |
def dimensions(paths):
"""
Calculate the dimensions of a set of paths (i.e. minumum box)
Returns (left, top, right, bottom) as a box.
"""
min_x = float('inf')
min_y = float('inf')
max_x = float('-inf')
max_y = float('-inf')
for path in paths:
for point in path:
... | 8330beaaf330bf576460d065783471e38acf6674 | 608,098 |
def readConfigFile(configFile):
"""Reads a config file with no section headers and returns a dictionary of key-value pairs"""
separator = "="
keys = {}
# I named your file conf and stored it
# in the same directory as the script
with open(configFile) as f:
for line in f:
if ... | 8e1a3a7ed85f20b0ab172718ebf2f79355d22534 | 608,102 |
import itertools
def backfill_heights(aliases):
"""
ZP only started recording heights on ~18th Feb, dates before that have
0s for height. Backfill these with the last value.
Example:
>>> backfill_heights([{'height': 10}, {'height': 9}, {'height': 0},
... {'height':... | 3013f581b4bc85bb6bfd88e4a775536bce0f7bbb | 608,106 |
import six
def get_size_bytes(value):
"""
Expand suffixes for object sizes.
For example, '10k' becomes 10240, and '2M' becomes 2097152.
"""
if not isinstance(value, six.string_types):
raise TypeError
value = value.strip()
multiple = {
'G': 1024 ** 3,
'M': 1024 ** 2... | ab6dc89c62e9f1e5e5a04ab61f1fd4955df8f80a | 608,124 |
def pow_mod(n, k, mod):
"""
Exponentiation by squaring
https://atcoder.jp/contests/atc002/tasks/atc002_b
:return: n ** k
"""
if k == 0:
return 1
elif k & 1 == 1:
return pow_mod(n, k - 1, mod) * n % mod
else:
tmp = pow_mod(n, k // 2, mod)
return tmp * tmp... | 1a50abf770ad03d59651cbde5529c7ca309db095 | 608,127 |
def in_box(boxes, x, y):
"""Finds out whether a pixel is inside one of the boxes listed"""
for box in boxes:
x1, y1, x2, y2 = box
if x>=x1 and x<=x2 and y>=y1 and y<=y2:
return True
return False | f11c37a5794e53898f24a526f9a9284aaabc842f | 608,131 |
def get_predict_fstat_parameters_from_dict(signal_parameters, transientWindowType=None):
"""Extract a subset of parameters as needed for predicting F-stats.
Given a dictionary with arbitrary signal parameters,
this extracts only those ones required by `helper_functions.predict_fstat()`:
Freq, Alpha, De... | db9301bdfc092966f074e3721cb68f4fa7d48b09 | 608,132 |
def _clean_pixel(_ds, saturation_threshold=10000):
"""Filters out over-saturated values
Creates a mask from the saturation threshold and > 0 and applies it to _ds.
Args:
_ds: dataset to mask
saturation_threshold: threshold that a pixel must be below to be considered 'clean'
Returns:
... | 6b74553b4194c1955dd26eca2281d2319bf40024 | 608,136 |
def assessment_exists(api, assessment_id):
"""Check if Gophish has at least one campaign for designated assessment.
Args:
api (Gophish API): Connection to Gophish server via the API.
assessment_id (string): Assessment identifier to get campaigns from.
Returns:
boolean: Indicates if... | 8aa06a3d23470db419b6f410edb752ba33e8a52f | 608,138 |
def get_new_ext(path, ext):
"""Returns the given file path, with the file extension changed to the given extension."""
if not ext.startswith('.'):
ext = '.' + ext
# os.path.splitext did not behave as expected here -> splitting extension off manually.
index = path.rfind('.')
asset_path = path... | 04f8636b7b06f57e71ba495121f035818a87be42 | 608,141 |
def bamListCatCmd(samtoolsBin, bamList, output) :
"""
Concatenate an input list of bam files to an output bam file, and index.
If len(bamList) is 1 the file will be moved to the output file name.
"""
assert(len(bamList) > 0)
if len(bamList) > 1:
headerTmp = bamList[0] + "header"
... | 0f97c668b672fa411e4db170efbd5b82476f18d1 | 608,145 |
import logging
def handle_car_arrival(free_cps, busy_cps, event, waiting_queue, counter_rejections,
within_opening_hours, log):
"""Connects car to charging point, to the queue or send it off.
Args:
free_cps: (set): Containing all :obj: `charging_points.ChargingPoint`
... | 28edb2e062bdcc83b7c8e31afffb3c0db0593359 | 608,147 |
import six
def _prompt(message, result_type=str):
"""
Non-public function that prompts the user for input by logging 'message',
converting the input to 'result_type', and returning the value to the
caller.
"""
return result_type(six.moves.input(message)) | 333da5d331a011d0f2e5505276bc1c415360c510 | 608,149 |
def __m_rs(soup):
"""
Gets the most read news from the Rolling Stone page
:param soup: the BeautifulSoup object
:return: a list with the most read news from the Rolling Stone page
"""
news = []
anchors = soup.find('ol', class_='c-trending__list').find_all('a')
for a in anchors:
tit... | 5142ce2a441a7512f641008cc8755a3a45444d0c | 608,152 |
def _none_factory() -> None:
"""
Helper function to construct a default 'None' value.
@return: Default None value.
@rtype: None
"""
return None | 10ae5b0eec6b66801b9cd1011c99d05240387e1b | 608,153 |
def valid(x, y, passed):
"""
This function check if the index is in the valid area.
:param x: row index of a character
:param y: column index of a character
:param passed: a switch used to check if a character have been visited.
:return: bool
"""
return (0 <= x < 4) and (0 <= y < 4) and ... | 30c8385f2ce800d88557ba9b312f4788c2a82761 | 608,155 |
from typing import Set
import re
def extract_cpu_flags(cpuinfo: str) -> Set[str]:
"""
Extract CPU flags from /proc/cpuinfo string
:return: Set of CPU flags for which given cpuinfo string indicates support
:rtype: set
"""
# Prepare cpuinfo str
lines = [line.strip() for line in cpuinfo.spl... | bf668e58ddb560a94d21499e17c7f0954b6eb36a | 608,157 |
def mayan_long_count_date(baktun, katun, tun, uinal, kin):
"""Return a long count Mayan date data structure."""
return [baktun, katun, tun, uinal, kin] | add55c2f680ffacebd8dc8743ffcc646aae6bd3a | 608,159 |
def check_for_workshop_prefix(seq):
"""
Returns either original sequence and empty list or trims "W"
from the front of the sequence.
"""
if len(seq) <= 2:
return seq, []
# workshop alleles start with W
if seq[0].lower() == "w" and seq[1].isdigit() and seq[2].isdigit():
retur... | 7edeb1fb038e3230d630abc271ee030516e7ac1b | 608,160 |
def _pretty_frame_relation(frel):
"""
Helper function for pretty-printing a frame relation.
:param frel: The frame relation to be printed.
:type frel: AttrDict
:return: A nicely formated string representation of the frame relation.
:rtype: str
"""
outstr = "<{0.type.superFrameName}={0.... | ee0ea7a583551aeb13df8670f15f261f17940607 | 608,161 |
def non_faculty_editors(editors):
"""
Get a sublist of non-faculty editors.
"""
return [e for e in editors if e["role"] != "Faculty"] | 00ba91627ff234db51f2f4c55bbc469054c8a3d7 | 608,163 |
def break_before_after(computer, name, value):
"""Compute the ``break-before`` and ``break-after`` properties."""
# 'always' is defined as an alias to 'page' in multi-column
# https://www.w3.org/TR/css3-multicol/#column-breaks
if value == 'always':
return 'page'
else:
return value | 07af9da3d4ab8cf6523f95457525cc2ea47eed73 | 608,164 |
def remove_chars(string: str) -> str:
"""Remove all characters but strings.
Args:
string: <str> input string sequence.
Returns:
string: <str> sorted only letters string.
Examples:
>>> assert remove_chars('.tree1') == 'tree'
"""
return ''.join(
filter(lambda le... | 79baf3839c3c355052ac68bbd2bd793318023d58 | 608,172 |
def indiscriminate_time(r, tau, N_r):
"""
Expected time spent in park by an indiscriminate poacher
Parameters
----------
r: float between 0 and 1 - the proportion of horns devalued
tau: float - the time taken to kill a horn
N_r: int - number ... | b5c45ef1f55c2b5b3942dae3d80f925a82314e31 | 608,174 |
def slice_as_int(s: slice, l: int):
"""Converts slices of length 1 to the integer index they'll access."""
out = list(range(*s.indices(l)))
assert len(out) == 1
return out[0] | fef4cc409cd74b0802a5d2ffd39d6c677a0831de | 608,180 |
def notebook_header(text):
"""
Insert section header into a jinja file, formatted as notebook cell.
Leave 2 blank lines before the header.
"""
return f"""# # {text}
""" | 90d29c9a0cd0d0c6778181f52116b42854138e8c | 608,181 |
from typing import Literal
def is_none(string_: str, default: Literal["raise", False] = "raise") -> bool:
"""
Check if a string is equivalent to None.
Parameters
----------
string_ : str
default : {'raise', False}
Default behaviour if none of the "None" strings is detected.
Retur... | 246bf0a7a914f7e2b6950c48fafed745e0c67d60 | 608,182 |
from typing import Tuple
import random
def train_test_split_file(input_path: str,
output_path_train: str,
output_path_test: str,
test_size: float=0.1,
random_state: int=1234,
encoding: str... | 2c1822fe34fcc4f83c27f63d96ab5cd1428adf18 | 608,185 |
def make_list(strings, delimiter='or'):
"""
Take a list of strings and a string.
If the length of the string is 1 return its element.
If it's 2, return its elements joined by the delimeter.
Otherwise, return its elements joined by commas (',') with
the delimeter before the final element.
Def... | 131d8b214a25beee53a4fc78d9df0f7768e4a5e0 | 608,187 |
from typing import List
def parse_beam_top(parts: List[str]):
"""
Structure: $corpus.beam.$length_penalty_alpha.top.$beam_size.$metric
Example: dev.beam.1.0.top.5.bleu
:param parts:
:return:
"""
corpus, sample_origin, length_penalty_alpha_a, length_penalty_alpha_b, decoding_method, nu... | 826c33e5f3938c88edd266b9dd4c07c65f7aa2f4 | 608,188 |
def get_crop_coords(coords, bb):
"""
Get all coordinates in coords which are within bounding box bb.
Parameters
----------
coords : numpy array of coordinates
bb : bounding box tuple of ints structured as (x_min, x_max, y_min, y_max)
Returns
-------
crop_coords : all coordinates in... | db2e2730521787f3d99ece72de79c61be44303fc | 608,190 |
def get_files_to_package(input_files):
"""Find files to be added to the distribution.
input_files: list of pairs (package_path, real_path)
"""
files = {}
for package_path, real_path in input_files:
files[package_path] = real_path
return files | 35e1982eea2fb81f575fe0a816cc3d919ae639f5 | 608,191 |
def dict_to_str(d):
"""Pretty print contents of a dict, with fixed width as [KEY] : [VALUE]"""
return "\n".join(["{0: <25}: {1}".format(k,v) for k,v in d.items()]) | b60162c923a0df2ab528f97608d348eeea4438a1 | 608,205 |
def Librosa(librosa_features, PID, EXP):
"""
Tidy up Librosa features in pandas data.frame to be stored in sqlite
database:
- Participant and experiment identifiers are added as columns
- Underscores in column names are removed, because sqlite does not like
underscores in column names.
-... | 534857be0d318afed7f464ffd76bb339f21740aa | 608,209 |
import re
def resolve_cardinality(mark,lex):
"""
Find cardinality for Markable based on numerical modifiers or number words
:param mark: The :class:`.Markable` to resolve agreement for
:param lex: the :class:`.LexData` object with gazetteer information and model settings
:return: Cardinality as float, zero if u... | bd4fdc82b13dad6f528734036e490836d45dc076 | 608,211 |
def clamp_to_water(p, water_depth):
"""Clamps a height to be above water level as defined in the given parameter.
If the value gets clamped, it returns True, otherwise it returns False"""
if p. y <= water_depth:
p. y = water_depth
return True
return False | 05149d70364f93bce379c496321cfe0ebdccc804 | 608,213 |
from pathlib import Path
def fullpath(path):
""" Expand '~' and resolve the given path """
return Path(path).expanduser().resolve(strict=False) | 15f75efc3e95e0a33a5cd0727c02c766a2e0d1e7 | 608,217 |
def _comma_separator(i, length):
"""A separator for an entirely comma-separated list given current item
index `i` and total list length `length`. `None` if there should be
no separator (last item).
"""
if length == 1:
return None
elif i != length - 1:
return ", "
else:
... | 5343b0e5ad3dfde4273f1e09b4163ed65170dd9e | 608,219 |
def extract_args_and_kwargs(*args, **kwargs):
"""Accept args and kwargs and return a tuple containing them in the form (args, kwargs)."""
return (args, kwargs) | f10f7558602aba53a09ba59b7b26b292af9a9aa8 | 608,220 |
import torch
from typing import Callable
def split_distance(
a: torch.Tensor,
b: torch.Tensor,
dist_fn_1: Callable,
dist_fn_2: Callable,
split_idx: int,
) -> torch.Tensor:
"""
Splits both `a` and `b` in two parts at `split_idx`, then applies two
different distance functions for each pa... | 31f1ec9396b1bb76352e79d97d8b31ecd8eedf0f | 608,222 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.