content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def listUpTo(num):
"""
Returns a lists of integers from 1 up to num
"""
return list(range(1, num + 1)) | aa15d7e14912bdaf3bc8801c4b853c8b392db021 | 29,330 |
def mirror(matrix):
"""Mirror a matrix."""
return [reversed(_row) for _row in matrix] | 778405db16d5865a555db44538e0e11d9c9258f9 | 29,332 |
def is_category_suspicious(category, reputation_params):
"""
determine if category is suspicious in reputation_params
"""
return category and category.lower() in reputation_params['suspicious_categories'] | 864aa520eba53c2e0ea2a6d2fbd3f0172bcab05f | 29,335 |
from typing import Iterable
def replace_symbols_with_values(list_of_lists, replacements):
"""
Take iteratively a list of lists (at any depth level) and replace strings with
the corresponding values in the ``replacements`` dictionary, leaving other
types of values (floats, ints, ...) untouched.
:r... | d3ab32e2527ad2e29515aa727676f8cbc86c9ee0 | 29,336 |
def _return_value(resource, key):
""" Return the value from the resource """
return resource[key] | 80cc72be0955e1b931422288dc84ede1d2098334 | 29,339 |
def handled_float(value, default=0):
"""
Returns ``float(value)`` if value is parseable by ``float()``.
Otherwise returns ``default``.
"""
ret_val = default
try:
ret_val = float(value)
except (TypeError, ValueError):
pass
return ret_val | d905695486c05ed11413307d3f5877ff905654d4 | 29,343 |
def group_by_company(devices):
"""Group a list of devices by company."""
grouped = {}
for dev in devices:
try:
grouped[dev['company']['name']].append(dev)
except KeyError:
grouped[dev['company']['name']] = [dev]
return grouped | 9b5b1c56a95132a8777e3206116819e528483a43 | 29,344 |
def first(items):
"""
Get the first item from an iterable.
Warning: It consumes from a generator.
:param items: an iterable
:return: the first in the iterable
"""
for item in items:
return item | 2ed7fa730b1b1c1588bc98e93ac8ef02a669ae98 | 29,346 |
from typing import List
import itertools
def mixup_arguments(*args) -> List:
"""mixups given arguments
[argument_1_1, argument_1_2], [argument_2_1] =>
[(argument_1_1, argument_2_1), (argument_1_2, argument_2_1)]
Returns:
List: [(arg1, arg2), ...]
"""
return list(itertools.product(*arg... | cf21e83b2ac07834220fab4bf000f98462c33a01 | 29,348 |
def cal_words_num(lines):
"""
Calculate number of words in lines
:param lines: lines to be calculate
:return: number of words
"""
return sum(map(len, lines)) | fc8f6022620687d21d0fa26bd51466a738eb0333 | 29,351 |
def add_delayed(df):
"""
Add col Delayed. 0 = punctual, 1 = delayed by more than 10 min
"""
_df = df.copy()
delayed = []
for index, row in _df.iterrows():
if row['Timedelta'] > 10:
delayed.append(1)
else:
delayed.append(0)
_df['Delayed'] = delayed
... | 06f187dc06b934a8f9384972c2f6bfe9461607b7 | 29,357 |
from typing import Collection
def key_map(data_: Collection) -> dict:
"""
Map all keys in a given data collection to their respective values.
e.g.
For the next data collection:
data = [
{
'name': 'foo',
'age': 31,
'country': 'UK'
... | f9939e79090831d140e41158e175bc61661cc740 | 29,359 |
def _parse_cpmd_atoms_block(lines, line_idx, parsed):
"""Add to ``parsed`` ``cpmd_atom_to_line_idx``.
``cpmd_atom_to_line_idx`` is a Dict[int, int] that associates a CPMD atom
index to the line number where its coordinates are stored.
Parameters
----------
lines : List[str]
The lines o... | 0dd693c4ca02af2b77288fd1c7a8ce2d2ab213bd | 29,363 |
def mndvi(b2, b4, b8):
"""
Modified Normalized Difference Vegetation Index \
(Main et al., 2011).
.. math:: MNDVI = (b8 - b4) / (b8 + b4 - 2 * b2)
:param b2: Blue.
:type b2: numpy.ndarray or float
:param b4: Red.
:type b4: numpy.ndarray or float
:param b8: NIR.
:type b8: numpy.... | af90990cf706ec353b1b435dc3d48a3c9801be92 | 29,366 |
def get_heading_text_lines(heading_regions):
"""
Given a list of TextRegion objects ``heading_regions`` (of type heading) return all of their text lines as one big
list.
:param heading_regions: List of TextRegion objects of type heading.
:type heading_regions: List[TextRegion]
:return: List of a... | 671d2de7ce90319307199d14805f9ac0f0bf76fd | 29,367 |
from typing import List
from typing import Dict
from typing import Any
def validate_cell_header(
headers: List[str], cell: Dict[str, Any]
) -> List[str]:
"""Check that header of a cell meets project specifications."""
content = [line.rstrip('\n') for line in cell['source']]
curr_header = content[0... | c18c385792a0f04661ca3961e31d7bb7ce8e5801 | 29,372 |
def zaction(op, inv):
"""
Return a function
f: (G, Z) -> G
g, n |-> g op g op ... (n-1 times) ... op g
If n is zero, it returns identity element. If n is negative, it
returns |n|-1 times op on the inverse of g.
"""
def f(g, n):
result = op(g, inv(g)) # identity
... | a75f061221ce28b03f3bcc4ddbbc6985f20339b2 | 29,376 |
def percentage_to_int(value):
"""
Scale values from 0-100 to 0-255
"""
return round((255.0 / 100.0) * float(value)) | b7bbc35da0fc704db0f454692b52286123cbb942 | 29,380 |
import torch
def select_seeds(dist1: torch.Tensor, R1: float, scores1: torch.Tensor, fnn12: torch.Tensor, mnn: torch.Tensor):
"""
Select seed correspondences among the set of available matches.
dist1: Precomputed distance matrix between keypoints in image I_1
R1: Base radius of neighborho... | 36ac7c9e9f6ccef31e487d350acfa2b4e496a7d4 | 29,381 |
def getarg(args, index):
"""
Helper to retrieve value from command line args
"""
return args[index] if index < len(args) else None | 256de43dda23c9f613c61a8dca456a3d507ca332 | 29,384 |
def resize_to(img_obj, new_height, new_width):
"""
Resize an image to the specified dimensions
"""
assert isinstance(new_height, int)
assert isinstance(new_width, int)
assert new_height > 0
assert new_width > 0
return img_obj.resize((new_width, new_height)) | 38303694e840ca29f01d6cb5b80e54d6f1c29008 | 29,387 |
def label(dt):
""" Setting the label for the integration timestep """
return 'dt = {} s'.format(dt) | 5cf5bce8079b2a0685eab0d54f16c4e61028b279 | 29,393 |
def try_to_convert(value):
"""Tries to convert [value] to an int, returns the original string on fail"""
try:
return int(value)
except:
return value | a4358e0827691262469ca776af6c207e5e09f8a2 | 29,395 |
def sf_mag(a: tuple) -> int:
"""
Calculates the magnitude of a snailfish number
:param a: a snailfish number
:return: the magnitude as int
>>> sf_mag((9, 1))
29
>>> sf_mag((1, 9))
21
>>> sf_mag(((9, 1),(1, 9)))
129
>>> sf_mag(((1,2),((3,4),5)))
143
>>> sf_mag((((... | 8292494f9e8ef4fe63dbaa7aef1c0973576aba64 | 29,399 |
import time
def create_datasplit(train_set, validation_set, test_set, name=None):
"""Create a datasplit dict from user-defined data sets
Args:
train_set (set): set of audio file paths
valid_set (set): set of audio file paths
test_set (set): set of audio file paths
name (str): ... | a6d35205dc8c5d31662301a471e291cd578f77ee | 29,408 |
def ndmi(b8, b11):
"""
Normalized Difference Moisture Index \
(Gerard et al., 2003).
.. math:: NDMI = (b8 - b11) / (b8 + b11)
:param b8: NIR.
:type b8: numpy.ndarray or float
:param b11: SWIR 1.
:type b11: numpy.ndarray or float
:returns NDMI: Index value
.. Tip::
Ge... | ed60cd5bae20167a747d3df1e9a5e9aa386ce385 | 29,411 |
def chunker(df, size):
"""
Split dataframe *df* into chunks of size *size*
"""
return [df[pos:pos + size] for pos in range(0, len(df), size)] | ea96315f9963551f4870d6732570d0ae375bd3c3 | 29,418 |
def clean_advance_reservation(text):
""" The advance reservation field identifies whether or not advance
reservations are required to use these facilities (day use areas). If there
is not recorded answer (blank) we default to 'no reservation required'.
Returns 'True' if reservation required, False other... | 8f707074f62ff605935737e3a6fa4cf2dc492de2 | 29,428 |
def _get_question_features(conv_id, QUESTIONS):
"""
Given conversation id and a dictionary QUESTIONS
Returns an one-hot vector of length 8, the Xth entry being 1 iff the conversation contains question type X.
"""
ret = {}
for ind in range(8):
ret['question_type%d'%(ind)] = 0
if c... | 7e81b6aed3f7fdd4aae1cd9e8cafdb43ebea2586 | 29,433 |
def validate_csv(row0, required_fields):
"""
:param row0:
:param required_fields:
:return: a tuple, True if all requirements are met and a dictionary with the index for all the fields
"""
for field in required_fields:
if field not in row0:
return False, {}
field_pos = {}
... | 6a126f22a86fbcfa4192ec4f9104faab7efd6b3f | 29,439 |
from typing import Sequence
from typing import Callable
from typing import Any
def batch_by_property(
items: Sequence, property_func: Callable
) -> list[tuple[list, Any]]:
"""Takes in a Sequence, and returns a list of tuples, (batch, prop)
such that all items in a batch have the same output when
put i... | 733dae3d31219dafbe115f12263a3da735409c30 | 29,440 |
def transpose_func(classes, table):
"""
Transpose table.
:param classes: confusion matrix classes
:type classes: list
:param table: input confusion matrix
:type table: dict
:return: transposed table as dict
"""
transposed_table = {k: table[k].copy() for k in classes}
for i, item... | 6c59feef2b735076c5768e086ef2e91331b78a73 | 29,450 |
from functools import reduce
def traverse_dict_children(data, *keys, fallback=None):
"""attempts to retrieve the config value under the given nested keys"""
value = reduce(lambda d, l: d.get(l, None) or {}, keys, data)
return value or fallback | 2c6f28259136bd8248306b7e759540fc3877d46f | 29,451 |
def get_idxs_in_correct_order(idx1, idx2):
"""First idx must be smaller than second when using upper-triangular arrays (matches, keypoints)"""
if idx1 < idx2: return idx1, idx2
else: return idx2, idx1 | 05963c4f4b692b362980fde3cf6bb1de1b8a21e0 | 29,453 |
from typing import Dict
from typing import Any
def source_startswith(cell: Dict[str, Any], key: str) -> bool:
"""Return True if cell source start with the key."""
source = cell.get("source", [])
return len(source) > 0 and source[0].startswith(key) | a3dab1e72488a5075832432f36c6fc10d9808a7f | 29,455 |
def _sabr_implied_vol_hagan_A4(
underlying, strike, maturity, alpha, beta, rho, nu):
"""_sabr_implied_vol_hagan_A4
One of factor in hagan formua.
See :py:func:`sabr_implied_vol_hagan`.
A_{4}(K, S; T)
& := &
1
+
\left(
\\frac{(1 - \\bet... | 704f4db60570cc18ad16b17d9b6ba93747d373d4 | 29,466 |
import glob
def get_sorted_files(files):
"""Given a Unix-style pathname pattern, returns a sorted list of files matching that pattern"""
files = glob.glob(files)
files.sort()
return files | 9bed6be4c57846c39290d4b72dba1577f9d76396 | 29,474 |
from typing import Dict
from typing import Any
def modify_namelist_template(
namelist_template: str,
placeholder_dict: Dict[str, Any]
):
"""
Placeholders in the form of %PLACEHOLDER_NAME% are replaced within the
given namelist template.
Parameters
----------
namelist_template ... | 2a872b20caf871ff6406e04a91d69ee2f33ba66c | 29,479 |
import pickle
def load_results(path, filename):
"""
load result from pickle files.
args:
path: path to directory in which file is located
filename: name of the file (without pickle extention)
"""
with open(path+filename+'.pickle', 'rb') as handle:
return pickle.load(han... | 6f76914cdbb25c4c5f81bc2bd61b61da5b34777a | 29,481 |
from pathlib import Path
def create_target_absolute_file_path(file_path, source_absolute_root, target_path_root, target_suffix):
"""
Create an absolute path to a file.
Create an absolute path to a file replacing the source_absolute_root part of the path with the target_path_root path
if file_path is ... | 0d24f8544752967815bd8ddceea15b371076c500 | 29,485 |
def query_prefix_transform(query_term):
"""str -> (str, bool)
return (query-term, is-prefix) tuple
"""
is_prefix = query_term.endswith('*')
query_term = query_term[:-1] if is_prefix else query_term
return (query_term, is_prefix) | d33dd4222f53cba471be349b61e969838f6188d5 | 29,486 |
def consolidate_conversion(x):
"""
Collapses the conversion status to Yes or No.
"""
xl = x.str.lower()
if any(xl.str.startswith('purchase')) or any(xl.str.startswith('converted')) or \
any(xl.str.startswith('y')) or any(xl.str.startswith('processed')) or \
any(xl.str.startsw... | fa9e8c93705d9d1941c12aeae293dc32750853d2 | 29,489 |
def fix_msg(msg, name):
"""Return msg with name inserted in square brackets"""
b1 = msg.index('[')+1
b2 = msg.index(']')
return msg[:b1] + name + msg[b2:] | 66544f811a9cead0a40b6685f60a7de8f219e254 | 29,491 |
def reshape_as_vectors(tensor):
"""Reshape from (b, c, h, w) to (b, h*w, c)."""
b, c = tensor.shape[:2]
return tensor.reshape(b, c, -1).permute(0, 2, 1) | 79044cc2061d0a4368922c3dc6c1324eb5fe315b | 29,493 |
def get_common_items(list1, list2):
"""
Compares two lists and returns the common items in a new list. Used internally.
Example
-------
>>> list1 = [1, 2, 3, 4]
>>> list2 = [2, 3, 4, 5]
>>> common = get_common_items(list1, list2)
list1: list
list2: list
returns: list
"""
... | 4978429d7d255270b4e4e52e44159e934cbd5ba5 | 29,497 |
def Powerlaw(x, amp, index, xp):
"""
Differential spectrum of simple Powerlaw normlized at xp
:param x: Energies where to calculate differential spectrum
:param amp: Amplitude of pl
:param index: Index of pl
:param xp: Normalization energy
:return: differential spectrum of a Powerlaw at ener... | 6e31d7a85998f762ff27305a38535487db6592fb | 29,501 |
def get_by_tag_name(element, tag):
"""
Get elements by tag name.
:param element: element
:param tag: tag string
:return: list of elements that matches tag
"""
results = []
for child in element.findall('.//'):
if tag in child.tag:
results.append(child)
return resul... | d1e2d196cae5c3a0de00c624f5df28c988eaa088 | 29,504 |
def clamp(value, min=0, max=255):
"""
Clamps a value to be within the specified range
Since led shop uses bytes for most data, the defaults are 0-255
"""
if value > max:
return max
elif value < min:
return min
else:
return value | 2d6e01daddc3603527021e4dbab261f82b3f8862 | 29,505 |
def clamp_value(value, minimum, maximum):
"""Clamp a value to fit within a range.
* If `value` is less than `minimum`, return `minimum`.
* If `value` is greater than `maximum`, return `maximum`
* Otherwise, return `value`
Args:
value (number or Unit): The value to clamp
minimum (nu... | 1224b7ed098781d66721dceef5c837470f1195a6 | 29,507 |
def make_signatures_with_minhash(family, seqs):
"""Construct a signature using MinHash for each sequence.
Args:
family: lsh.MinHashFamily object
seqs: dict mapping sequence header to sequences
Returns:
dict mapping sequence header to signature
"""
# Construct a single hash ... | c6366811536f1e32c29e3a00c91267bde85969fa | 29,510 |
import socket
def resolve_fqdn_ip(fqdn):
"""Attempt to retrieve the IPv4 or IPv6 address to a given hostname."""
try:
return socket.inet_ntop(socket.AF_INET, socket.inet_pton(socket.AF_INET, socket.gethostbyname(fqdn)))
except Exception:
# Probably using ipv6
pass
try:
... | 2e7680fe3a4ea174f3f7b22e4991a3a65e5e4995 | 29,516 |
from pathlib import Path
def field_name_from_path(path):
"""Extract field name from file path."""
parts = Path(path).stem.split('.')
field_name = parts[-1]
if len(parts) > 1:
if parts[-1] in ('bam', 'sam', 'cram'):
field_name = parts[-2]
return field_name | 9d21b760bccb6557f5450921482d76917ba13981 | 29,519 |
def binaryStringDigitDiff(binstr1, binstr2):
"""
Count the number of digits that differ between two
same-length binary strings
Parameters
----------
binstr1 : string
A binary (base-2) numeric string.
binstr2 : string
A binary (base-2) numeric string.
Returns
-------... | be39c7dbc30f6e49263a880254a021ff6873d240 | 29,521 |
from datetime import datetime
def timestamp_to_datetime(timestamp):
"""Generate datetime string formatted for the ontology timeseries
Args:
timestamp (float, timemstamp): Timestamp value as float
Returns:
str: Returns the timestamp with the format necessary to insert in the Ontology
... | b894c3610842bf62387cbed77047fe4cc4d577a5 | 29,524 |
def setdiag(G, val):
"""
Sets the diagonal elements of a matrix to a specified value.
Parameters
----------
G: A 2D matrix or array.
The matrix to modify.
val: Int or float
The value to which the diagonal of 'G' will be set.
"""
n = G.shape[0]
for i in range(0,n):
... | 74a1e2899a8575f04692f74ad01e122b3639d2b1 | 29,526 |
def get_operation_full_job_id(op):
"""Returns the job-id or job-id.task-id for the operation."""
job_id = op.get_field('job-id')
task_id = op.get_field('task-id')
if task_id:
return '%s.%s' % (job_id, task_id)
else:
return job_id | 6c0258d5c2053a5320d78340979fe60c8ea88980 | 29,530 |
def get_conditions(worksheet):
"""
Get the conditions displayed on a worksheet.
args:
worksheet (seeq.spy.workbooks._worksheet.AnalysisWorksheet): Worksheet
returns:
conditions (pandas.DataFrame): Displayed Conditions
"""
display_items = worksheet.display_items
if len(display_items) == 0:
raise ValueErr... | f3fe0bd58f9a0344f047e3ae6eef6bdefa325c21 | 29,534 |
def TailFile(fname, lines=20):
"""Return the last lines from a file.
@note: this function will only read and parse the last 4KB of
the file; if the lines are very long, it could be that less
than the requested number of lines are returned
@param fname: the file name
@type lines: int
@param lines... | 39f2f07421f150df16061219790e49f222f284e7 | 29,535 |
def get_df_subset(df, column_one, value_one, column_two, value_two):
"""
Takes a dataframe and filters it based on two columns and their matching values
"""
return df.loc[(df[column_one] == value_one) & (df[column_two] == value_two), :] | 4971af24f33b12d00a2385b7c5ee295630f385de | 29,538 |
def zoom_to_roi(zoom, resolution):
"""Gets region of interest coordinates from x,y,w,h zoom parameters"""
x1 = int(zoom[0] * resolution[0])
x2 = int((zoom[0]+zoom[2]) * resolution[0])
y1 = int(zoom[1] * resolution[1])
y2 = int((zoom[1]+zoom[3]) * resolution[1])
return ((x1,y1),(x2,y2)) | cd77da9a67713ed7f76f4d41a7b7bee7e2f54a78 | 29,540 |
def get_ext(path):
"""Get file extension.
Finds a file's extension and returns it.
Parameters
----------
path : str
The path to a file.
Returns
-------
str
The file extension including leading "."
"""
return path[path.rfind(".") :] | 80ba4fb8686b2a7454240a56aa0c3a7d41636f27 | 29,541 |
def _engprop(l): # {{{1
"""Print the engineering properties as a HTML table."""
lines = [
"</tbody>",
"<tbody>",
'<tr><td colspan="6" align="center"><strong>Engineering properties</strong></td></tr>',
'<tr><td colspan="3" align="center"><strong>In-plane</strong></td>',
'... | e6bbaa4a39265b2703aa623a99a73f5b4e471023 | 29,544 |
import typing
import hashlib
def create_sf_instance(entity_name: str, property_label: str) -> typing.Tuple[str, str]:
"""Creates a slot filling instance by combining a name and a relation.
Arguments:
entity_name: ``str`` The name of the AmbER set to fill into the template.
property_label: ``s... | 02e69115261b148c7fdb270864095c63bbdb2278 | 29,549 |
def ensure_keys(dict_obj, *keys):
"""
Ensure ``dict_obj`` has the hierarchy ``{keys[0]: {keys[1]: {...}}}``
The innermost key will have ``{}`` has value if didn't exist already.
"""
if len(keys) == 0:
return dict_obj
else:
first, rest = keys[0], keys[1:]
if first not in ... | e8d87444ed8961d8d650b49c8670dca1496623b1 | 29,550 |
import re
def middle_coord(text):
"""Get the middle coordinate from a coordinate range.
The input is in the form <start> to <end> with both extents being in
degrees and minutes as N/S/W/E. S and W thus need to be negated as we only
care about N/E.
"""
def numbers_from_string(s):
"""F... | 4e8148102ff04969279690922ddce5bd767fed55 | 29,554 |
def convert_webaccess_datestamp(entry):
"""Set date and time attributes based on an iso date stamp"""
attrlist = entry['date_stamp'].split('/')
timelist = attrlist[-1].split(':')
entry['year'] = timelist[0]
months = {'Jan': '01', 'Feb': '02', 'Mar': '03',
'Apr': '04', 'May': '05', 'Jun':... | 795c889f93f6d87cced5f9aa9293e6491f6b2678 | 29,561 |
def multipart_content_type(boundary, subtype='mixed'):
"""Creates a MIME multipart header with the given configuration.
Returns a dict containing a MIME multipart header with the given
boundary.
.. code-block:: python
>>> multipart_content_type('8K5rNKlLQVyreRNncxOTeg')
{'Content-Type... | a19cb6fcf43f2b3c2abecf3af960f57987967c0e | 29,563 |
import re
def pattern_count(pattern, text):
"""Counts apperances of a Regex pattern in a string."""
return len(re.findall(pattern, text)) | b12c8bc2132a9fd9afba7468befceac7edfb636f | 29,564 |
from typing import List
from typing import Any
from typing import Dict
from typing import Counter
def get_common_items(list_to_count: List[Any], top_n: int) -> Dict[Any, int]:
"""Get the n most common items in descending order in a list of items.
Args:
text (List[Any]): List of items to be counted.
... | 928a243ab48cce35ead2c821b1891f88ce20123e | 29,568 |
def trycast(value):
"""
Try to cast a string attribute from an XML tag to an integer, then to a
float. If both fails, return the original string.
"""
for cast in (int, float):
try:
return cast(value)
except ValueError:
continue
return value | 3faaaa52a2d50e20a925db96de884709c052e7e3 | 29,571 |
def _fix_bed_coltype(bed):
"""Fix bed chrom and name columns to be string
This is necessary since the chromosome numbers are often interpreted as int
"""
bed["chrom"] = bed["chrom"].astype(str)
bed["name"] = bed["name"].astype(str)
return bed | 471410f31675d0de2f35883679e760c515ff0880 | 29,573 |
def get_time_slot(hour, minute):
"""
Computes time_slot id for given hour and minute. Time slot is corresponding to 15 minutes time
slots in reservation table on Sutka pool web page (https://www.sutka.eu/en/obsazenost-bazenu).
time_slot = 0 is time from 6:00 to 6:15, time_slot = 59 is time from 20:45 to 21:00.
:pa... | dbfc510755a0b0a9612c0aa7d94922199c3f7f7d | 29,576 |
from datetime import datetime
def int_to_date_str(i_time):
"""unix epoc time in seconds to YYYY-MM-DD hh:mm:ss"""
return str(datetime.fromtimestamp(i_time)) | 27f0773a78202e57ae498c1d40faabb29877b573 | 29,581 |
def get_waist_to_height_ratio(df):
"""Waist-to-height ratio
A measure of the distribution of body fat.
WHR= waist/height
Ref.: https://en.wikipedia.org/wiki/Waist-to-height_ratio
"""
df["WHR"] = df["ac"] / df["height"]
return df | 0720dcda80bd5bccb3e121ca9859ea2da3b75144 | 29,586 |
def evaluate_acc(predictions, outputs):
"""Compute accuracy score by comparing two lists
of same length element-wise
Arguments:
predictions {series} -- first list to be compared with the second one
outputs {series} -- same length as predictions
"""
assert len(predictions) == len(out... | 299086ba456799241505ab9df6c64e3cf54ea13a | 29,590 |
def has_tool_tag(invocation):
"""
Checks if invocation has a tool_tag in workspace info
Args:
invocation (Invocation)
Returns:
True if tool_tag exists else false
"""
if (hasattr(invocation, 'workspace_info')
and hasattr(invocation.workspace_info, 'tool_tag')
... | 7ea992c62d6d3f9ec5e3d26d5e1c3ab850d6fe04 | 29,591 |
from typing import List
def get_param_with_name(parameters: List[dict], name: str) -> dict:
"""Get the parameter that has the given name."""
matched_params = (p for p in parameters if p["name"] == name)
return next(matched_params) | ea1f527bc03cb41a77e3b9743ee372246dc12f54 | 29,594 |
def extract_layout_switch(dic, default=None, do_pop=True):
"""
Extract the layout and/or view_id value
from the given dict; if both are present but different,
a ValueError is raised.
Futhermore, the "layout" might be got (.getLayout) or set
(.selectViewTemplate);
thus, a 3-tuple ('layout_id... | 41a7a11e72ed70dee1456334a93a5cfe0651ec37 | 29,600 |
from bs4 import BeautifulSoup
def get_targets(html):
"""
Return bolded targeting parameters
"""
if html:
doc = BeautifulSoup(html, "html.parser")
return " ".join([b.get_text(" ") for b in doc.find_all("b")])
return "" | 04248637d3f77d4ed5b5365e60298e7bfb0c6933 | 29,601 |
def diff_possible(numbers, k):
"""
Given a list of sorted integers and a non negative
integer k, find if there exists 2 indicies i and j
such that A[i] - A[j] = k, i != j
"""
if k < 0:
raise ValueError('k can not be non negative')
# Find k since as long as i is not larger than k
... | 54c45f24644c478dc48679c11c5217c0318af2b4 | 29,604 |
import tarfile
def smart_is_tarfile(filepath):
"""
:func:`tarfile.is_tarfile` plus error handling.
:param filepath: Filename.
:type filepath: str
"""
try:
istar = tarfile.is_tarfile(filepath)
except (OSError, IOError):
return False
else:
return istar | 4fb203685100204ea4a28d7854634628599801ce | 29,605 |
def to_cmd_string(unquoted_str: str) -> str:
"""
Add quotes around the string in order to make the command understand it's a string
(useful with tricky symbols like & or white spaces):
.. code-block:: python
>>> # This str wont work in the terminal without quotes (because of the &)
>>>... | bdba5138daa580c34d49618da511ff0e20f192d4 | 29,607 |
from typing import Optional
from typing import Dict
from typing import Any
def define_by_run_func(trial) -> Optional[Dict[str, Any]]:
"""Define-by-run function to create the search space.
Ensure no actual computation takes place here. That should go into
the trainable passed to ``tune.run`` (in this exam... | f8237b135e3a6467bdefd397f1da0ebaec0f4380 | 29,608 |
def rectangle_to_square(rectangle, width, height):
"""
Converts a rectangle in the image, to a valid square. Keeps the original
rectangle centered whenever possible, but when that requires going outside
the original picture, it moves the square so it stays inside.
Assumes the square is able to fit ... | e879cf81c1448f72d1d5326b0a8f964e47173f07 | 29,613 |
def check_treedepth(samples, max_treedepth=10, quiet=False, return_diagnostics=False):
"""Check transitions that ended prematurely due to maximum tree depth limit.
Parameters
----------
samples : ArviZ InferenceData instance
Contains samples to be checked. Must contain both `posterior`
... | ed949405b408841d4d716151187c65d2638b1b4e | 29,617 |
def inchesToMeters(inches):
"""Convert inches to meters."""
return inches * 0.0254 | b9f87ddc885474964ff59618bd560fb20ac9d7ff | 29,640 |
import bs4
def get_navigable_string_type(obj):
"""Get navigable string type."""
return bs4.NavigableString | 79d47783e0441a17fc3016218683dc19c7dc78f2 | 29,650 |
def convert_parentheses_back(text: str):
"""Replaces ( and ) tokens with -LRB- and -RRB-"""
return text.replace("(", "-LRB-").replace(")", "-RRB-") | 7bf23c858ade23d61c3d12b39cb3a76b840aefc0 | 29,651 |
def is_asc_sorted(lst: list) -> bool:
"""
Utility that tells whether a given list is already ascendentally sorted
with every item in the list greater than the previous.
:param lst: list to check
:return: true if and only if the given list is ascendentally sorted
"""
return all(lst[i+1] > lst... | 9c1fcd2354196ca33c3f61fc91c17fa5cf6907a8 | 29,654 |
def identifyFileType(suffix):
"""Identify the file type and return correct syntax.
:suffix: file suffix
:returns: [inline comment syntax, multiple line comment syntax]
"""
if suffix == "py":
return "#", "\"\"\"", "\"\"\""
elif suffix == "c" or suffix == "h" or suffix == "cpp" or suffix... | b4a6de0039fc7ca1459fffb56b0e95b884a10704 | 29,655 |
def parse_walltime(wt_arg):
""" Converts walltimes to format dd:hh:mm:ss.
"""
# Clean the wt
parts = wt_arg.split(":")
wt_clean = ["{0:02d}".format(int(value)) for value in parts]
# Pad with 00
wt_clean = ["00"] * (4 - len(wt_clean)) + wt_clean
# Join and return
return ":".join(wt_cl... | 85327866ccf738f4212324f258e7400318b6a2d1 | 29,659 |
def read_list(fn):
"""Reads a list from a file without using readline.
Uses standard line endings ("\n") to delimit list items.
"""
f = open(fn, "r")
s = f.read()
# If the last character in the file is a newline, delete it
if s[-1] == "\n":
s = s[:-1]
l = s.split("\n")
return... | 0b73082074914b824e93cceb18ea773a916db5bc | 29,660 |
def difference(f1_d, f2_d, out_f1_head, out_f2_head):
"""
Figures out the difference between two dictionaries
and reports the difference
Parameters
----------
f1_d : dict
Dictionary for first fasta, chromosome names as values
f2_d : dict
Dictionary for second fasta, chromosom... | 4f25fc4595fbc59f02121a772123413a9e2a61a6 | 29,663 |
def add_error_total_and_proportion_cols(
total_errs, total_rows, date,
errs_by_table, total_by_table,
aggregate_df_total, aggregate_df_error,
aggregate_df_proportion):
"""
Function adds a new column to the growing dataframes. This
column contains information depending on the ... | 3f1e6b7aa675d0184cde7d7712e41b89d689a536 | 29,664 |
import yaml
def parse_str(source: str, model_content: str) -> dict[str, dict]:
"""Parse a string containing one or more yaml model definitions.
Args:
source: The file the content came from (to help with better logging)
model_content: The yaml to parse
Returns:
A dictionary of t... | acbca7fb764b09c8ccb2b5d7e28748bbb74ad870 | 29,665 |
def int_scale(val, val_range, out_range):
"""
Scale val in the range [0, val_range-1] to an integer in the range
[0, out_range-1]. This implementation uses the "round-half-up" rounding
method.
>>> "%x" % int_scale(0x7, 0x10, 0x10000)
'7777'
>>> "%x" % int_scale(0x5f, 0x100, 0x10)
'6'... | a58bd33dd0712444bbfbd91e4f988a44780de323 | 29,667 |
def dict_search(data: dict, key: str, depth: int = 3):
"""Search a key value in a dict, return None if not found.
Warn: This method can be slow due to the amount of depth
"""
data_keys = data.keys()
for keys in data_keys:
if keys == key:
return data[key]
if depth > 0:
... | 94bf3753b8b37afb313983ff8a0d99a14b2e9b98 | 29,668 |
import importlib
def load_plugin(plugin):
"""Get the plugin module
"""
return importlib.import_module(plugin) | 5a59ee8f41e7a0e3d96e0582937a7f9eb7fa4be8 | 29,669 |
def bisection_search2(L, e):
"""
Implementation 2 for the divide-and-conquer algorithm
Complexity: O(log n)
:param L: List-object
:param e: Element to look for
:return: Boolean value if element has been found
"""
def helper(L, e, low, high):
if high == low:
... | d3bda3698b5a321ac6307fe2a068c4ec61d6c57b | 29,670 |
from importlib import import_module
def try_import_for_setup(module_name):
"""
Returns the imported module named :samp:`{module_name}`.
Attempts to import the module named :samp:`{module_name}` and
translates any raised :obj:`ImportError` into a :obj:`NotImplementedError`.
This is useful in benchm... | 9dc45df6372276258f6b0b9aab2a151e9b4b75af | 29,671 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.