content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def NPL_indicator (row):
"""
Determine the indicator of NPL as one of five indicators
"""
if row < 37:
return "Excellent"
elif row <= 48:
return "Good"
elif row < 61:
return "Fair"
elif row < 93:
return "Poor"
else:
return "Hazard" | 1b6a5fcde487a5f0d256e7be210e8303d909f8a4 | 584,642 |
def clamp_value(val, min_val, max_val):
"""Restrict a value to within the specified range"""
return min_val if val < min_val else max_val if val > max_val else val | 66cbf7d692d1f8be6b82b7f651e525b7fbe04928 | 584,644 |
import hashlib
def truncate_value(value, max_length=63, from_left=True):
"""
Truncate a value (typically a column name) to a certain number of characters,
using a hash to ensure uniqueness.
"""
hash_length = 8
truncated_length = max_length - hash_length - 1
value = value.encode('unicode-es... | 124f90f1da40abaffdd8f3c17ca7692df2c16213 | 584,645 |
def _list_str(lst,sep):
"""
Returns the list as a string with the given separator and no
brackets.
"""
ret = ''
for x in lst:
ret += str(x)+sep
return ret[:-1*len(sep)] # remove extra separator | 2cc0b1f90997f0314abdd8ab769d0e55e9f090db | 584,646 |
def set_out_cell(outSheet, col, row, value):
""" Change cell value without changing formatting. """
def _getOutCell(outSheet, colIndex, rowIndex):
""" HACK: Extract the internal xlwt cell representation. """
row = outSheet._Worksheet__rows.get(rowIndex)
if not row: return None
... | 30843794595c21ab5160f6c95a01ff59c4f97640 | 584,647 |
def unique_doc_id(doc):
"""
Return a string of format "<GlobalJobId>#<RecordTime>"
To uniquely identify documents (not jobs)
Note that this uniqueness breaks if the same jobs are submitted
with the same RecordTime
"""
return f"{doc['GlobalJobId']}#{doc['RecordTime']}" | 7a0b008af7f5222e7d62b35789e7b4e3fd498e69 | 584,648 |
from typing import IO
import hashlib
def _hash_fileobj(fileobj: IO[bytes]) -> str:
""" Compute sha256 hash of a file. File pointer will be reset to 0 on return. """
fileobj.seek(0)
h = hashlib.sha256()
for block in iter(lambda: fileobj.read(2 ** 20), b""):
h.update(block)
fileobj.seek(0)
... | d7bab1e68dca88af9df0a22bb0ba05abc8093ff9 | 584,649 |
def _is_file_like(obj):
"""
Checks if an object is file-like enough to be sent to requests.
In particular, file, StringIO and cStringIO objects are file-like.
Refs http://stackoverflow.com/questions/3450857/python-determining-if-an-object-is-file-like
"""
return hasattr(obj, 'read') and hasattr... | 27928e2679b297c90f1dda2b02796320fb03cee1 | 584,652 |
def subtract_leak(cell, baseline_range, test_range, V_channel=1, I_channel=0):
"""Subtract leak conductance from the I channel of a Cell-like np.ndarray.
Calculates leak conductance based on Rm, which is extracted from test
pulse. Assumes test pulse is the same in each sweep.
Arguments
---------
... | 4c72eef13f0e9d7db173f5ef0a43ea2e9cc7613d | 584,653 |
def check_test(out, my_out):
"""
Function used to determine if output matches between gcc and basic interpreter
:param out: output of executable
:param my_out: output of interpreter
:return: True if both outputs are the same, False otherwise
"""
if (out == my_out):
return True
el... | 353b74e84d56aa30e22632589d821a24c97c2dbb | 584,655 |
def get_null_stats(df):
"""
Function that will return count (absolute and relative) of null
values in each column in `df`.
Parameters
----------
df : pandas.DataFrame
DataFrame on which this function will operate.
Return
------
pandas.DataFrame with `df.columns` as row ... | aca977692497682b1360998f646034cbed841477 | 584,658 |
def get_nb_new(emails):
"""Return formatted string with number of new emails"""
if emails:
return '{}/'.format(len(emails))
return '' | 1ef813e066a3ae44ca7322ac19dab4f798a6d691 | 584,659 |
def target_reachable(env, target, state):
"""
Return True if target is reachable in network.
Target is reachable iff:
1) it's on an exposed subnet
2) it's on a compromised subnet
3) it's on a subnet connected to a compromised subnet
"""
network = env.network
if network.s... | d13221c0698260c65f74b3a624fc76551cb28aab | 584,660 |
def read_input(input_file: str) -> str:
"""
Helper function for reading XML contents from a file.
:param input_file: path to XML file containing input
:return: `string` representing XML input from given file
"""
with open(input_file, 'r') as f:
xml_input = f.read()
return xml_inpu... | ed66652a2d4a0af87fab871f7890d018dc80d8e5 | 584,662 |
def set_input_container(_container, cfg):
"""Save the input for the container in the configurations."""
if not _container:
return False
if _container.exists():
cfg["container"]["input"] = str(_container)
return True
return False | 0a2961cc9288f6899bafebe0bea852b8596be720 | 584,665 |
def fix_static(lines):
"""Fix image links to handle new static path."""
def fix_static_line(line):
return line.replace('/static/images', '/images')
return [fix_static_line(line) for line in lines] | 6324c1a1cbb9e020e10fe13eb97d620d2211b403 | 584,666 |
def sniff_nodata(series):
"""
Attempt to guess the nodata value associated with a series
Parameters
----------
series : pandas series
Returns
-------
str : the nodata placeholder in a series
"""
uniques = series.uniques()
for nd in ['#N/A', '#N/A N/A', '#NA', '-1.#IND', '-... | a74312cb8c545557a640734ea6307d839a2f5728 | 584,667 |
def rescale(f,a=0,b=1):
"""
Rescale linearly the dynamic of a vector to fit within a range [a,b]
"""
v = f.max() - f.min()
g = (f - f.min()).copy()
if v > 0:
g = g / v
return a + g*(b-a) | 3bdff0c805e6b5983096bd0bbd72df7b1e8fdd33 | 584,668 |
def keep_numeric(s: str) -> str:
"""
Keeps only numeric characters in a string
------
PARAMS
------
1. 's' -> input string
"""
return "".join(c for c in list(s) if c.isnumeric()) | c936a6857174dab9d10eaefcb4a5fab1e234ec4e | 584,670 |
def _safe_divide(numerator: int, denominator: int) -> float:
"""Normal division except anything/0 becomes 0.0."""
return numerator / denominator if denominator else 0.0 | fb674fe5eeaf80b25fb03740902d1ca5311fde6c | 584,671 |
def divide(a, b):
"""
Divide two numbers
Parameters:
a (float): counter
b (float): denominator
Returns:
float: division of a and b
"""
if b == 0:
raise ValueError("Cannot divide by zero!")
return a / b | 1ad6d5f5b542e197140797c0cf1d80372547782c | 584,672 |
def equal_or_slightly_less(a, b, threshold=5):
"""
Return boolean depending on whether `a` is equal to or slightly
less than `b` (based on threshold of allowed deviation).
Args:
a (number): first number
b (number): second number
threshold (int, optional): Threshold. Defaults to... | dead5acb7f2031ba1ab0ffbdccff2c8e3cb7cb64 | 584,674 |
from operator import contains
def finds(item, mod):
""" Returns tuple of coordinates of item in mod, if found.
Otherwise, it returns None """
coords = [key for key, val in mod.items() if contains(item, val)]
# If coords!=[], it'll be for eg. [(0,0,0)]. Extract the tuple, return
return coords[0] if... | 70c67340d4632cd2d570c485e56fc3ab310e9fda | 584,675 |
def interleave_channels(*channels):
"""Returns a sequence comprising of interleaved channels"""
return tuple([i for sublist in zip(*channels) for i in sublist]) | 66d16d2c0c923c4f6b6dc9075a4d16a7d68c500b | 584,677 |
from re import match as re_match
def event_nonum_arg_count(e):
"""
Given an EventAnnotation, returns a dictionary containing for each
of its argument without trailing numbers (e.g. "Theme1" ->
"Theme") the number of times the argument appears.
"""
nnc = {}
for arg, aid in e.args:
... | 126d1d400b7eeb183849f8eec0388a72cc4f2359 | 584,678 |
def get_choice_label(label, data_dictionary, language=None):
"""
Return the label matching selected language or simply just the label.
"""
if isinstance(label, dict):
languages = [i for i in label.keys()]
_language = language if language in languages else \
data_dictionary.ge... | 4dab69bca394f597687d2cce1792171c7393f5af | 584,679 |
def __to_sentence(sentence):
"""
Convert a sentence annotation to a gloss.
"""
ret = ""
for tok in sentence['tokens']:
ret += tok['originalText'] + tok['after']
return ret | 9bc20824335ced81dec92a5b7d06dafabab2ac88 | 584,682 |
def uniq(input):
"""Remove duplicates from a list while preserving the list order"""
output = []
for item in input:
if item not in output:
output.append(item)
return output | a0a52d169aee3927a05c4c572367f526f3529ff2 | 584,683 |
def f1_score(precision: float, recall: float) -> float:
"""
Calculates F1 score according to:
.. math:: 2 (P*R)/(P+R)
Parameters
----------
precision
Precision
recall
Recall
Returns
-------
F1 score
"""
try:
return (precision * recall) / ((prec... | 4503c1332cbf5897d06c91ee095d26601fc37ae4 | 584,684 |
from typing import Union
from typing import List
from datetime import datetime
def days_to_datetimes(days: Union[int, List[int]], offset: int = 2100) -> Union[datetime, List[datetime]]:
""" Converts Julian days to datetimes given an offset
"""
days = [days] if isinstance(days, int) else days
return [... | 8a38c4f5ead0869d594894533fab7c47dbbf571a | 584,688 |
def analyze(file_path, pattern_reg_exp):
""" Return the set of passing and failing methods and a map
from failing methods to the reason they failed.
"""
#
# We pass in the pattern regular expression so we will not have
# compile it repeatedly. For reference, here is its definition:
#
... | f864738d97d37584f7bcf38332ada2011a6897be | 584,692 |
def linear_variogram_model(m, d):
"""Linear model, m is [slope, nugget]"""
slope = float(m[0])
nugget = float(m[1])
return slope * d + nugget | f7cb98353a34716f83ed9ce3ddfb8d869e83bd3d | 584,695 |
def diff_state(initial, new, my_id=None):
"""
Return a list of widget model_ids that have changed based on two widget
states
"""
diff = []
for (init_id, init_state), (new_id, new_state) in zip(
initial.items(), new.items()
):
assert init_id == new_id
if init_state != ... | 0fce40723024120999a667a921242c4318980d22 | 584,697 |
def redirect(path):
"""
Redirect requests.
:param str path: Rejection status code
:return dict: Redirection response
"""
return dict(statusCode=301, headers={'Location': path}) | 76f7cc3323d0fb33393bfccc8614fb21079ecae7 | 584,699 |
def countRectsInGrid(gridWidth, gridHeight, abortLimit=None):
"""Count how many rectangles fit in a grid with given dimensions.
'abortLimit' is an optional argument to avoid counting beyond a
certain limit."""
return gridWidth * (gridWidth + 1) * gridHeight * (gridHeight + 1) // 4 | 679825cd076b17dfa505d584e4f1886af638c7f3 | 584,700 |
def count_amino_acids(protein: str) -> dict:
"""
Given:
protein: a string of protein sequence
Return:
A dictionary contains: {amino acid: number of occurrence in protein}
(If some amino acids do not appear in protein,
the output does not need to include it.)
"""
count = {}
... | 8796f8652c65376a56f7b3cad10deb1166fd05e1 | 584,701 |
def mapper_16QAM(QAM16, data):
"""Uses the input data to index the array with the 16QAM amplitudes and phases.
Parameters
----------
QAM16 : 1D array of floats
Array that will be indexed.
data : 1D array of ints
Data that will index the QAM16 array.
Returns
----... | a4e0c5782a7e7cccd0dd000313821344ffea5152 | 584,703 |
def split_format(fmtstring, s):
"""decode a bytestring and split and convert it by a given format code
s: string, i: int, f: float, x: none
Args:
fmtstring: specifies the format of the string, eg 's4,i4,f14,f14'
s: string to decode
Returns:
list: with results
"""
decode... | 5ed28fa226c49e7e74c8d5aee6ca1769691ab395 | 584,715 |
def replaceAll(s, subs, rep):
"""
Replaces all substrings in a string with another string
"""
count = 0
for i in s:
if i == subs:
count += 1
return s.replace(subs, rep, count) | 731cb9f56db778ee219538fbcebf572100a0cee3 | 584,716 |
import copy
def _safe_log(log_func, msg, msg_data):
"""Sanitizes the msg_data field before logging."""
SANITIZE = {
'set_admin_password': ('new_pass',),
'run_instance': ('admin_password',),
}
method = msg_data['method']
if method in SANITIZE:
msg_... | f45e4d6ac3c67b70464b1ec7989e2d4c30394db2 | 584,717 |
import binascii
def b2lx(b):
"""Convert bytes to a little-endian hex string
Lets you show uint256's and uint160's the way the Satoshi codebase shows
them.
"""
return binascii.hexlify(b[::-1]).decode('utf8') | 64b4f8d14c0ce65f8eec446b0b65210b9c73c897 | 584,718 |
def break_chains(df):
"""Break a non-linear alignment in linear parts"""
dataframes = []
last_direction = df["is_reverse"].iloc[0]
initial_index = 0
for index, direction in enumerate(df["is_reverse"]):
if direction != last_direction:
dataframes.append(df.iloc[initial_index:index]... | a7a2e5d24a3728b44ef7c9a7e5505fb8ab25dd26 | 584,727 |
def proportional(raw_value, factor, unit=None):
"""Applies a proportional factor."""
return (float(raw_value) * factor, unit) | 0cdc5c14348f0d99e1de58d6445df69f8a8a39e8 | 584,731 |
def get_lsb(value):
"""
Get least significant bit.
:param value: value to obtain lsb from
:return: least significant bit
"""
return value & 0x1 | faececa9cfb9a43b4bc038e964db98b24250e90e | 584,736 |
def is_usb_serial(device, args):
"""Checks device to see if its a USB Serial device.
The caller already filters on the subsystem being "tty".
If serial_num or vendor is provided, then it will further check to
see if the serial number and vendor of the device also matches.
"""
if "ID_VENDOR" ... | 06ecd226f5ca44724c5045ee4c24056709bb3a41 | 584,739 |
def get_selection(action, suboptions):
"""
param: action (string) - the action that the user
would like to perform; printed as part of
the function prompt
param: suboptions (dictionary) - contains suboptions
that are listed underneath the function prompt.
The ... | a621d87f43459d28214842b5b54cfe3427eacb06 | 584,740 |
import struct
def read_openssh_string(bin_fp):
"""
Read a length-prefixed ("OpenSSH-style Pascal") string from a file.
This format is described in https://tools.ietf.org/html/rfc4251
(look for "Arbitrary length binary string").
:param bin_fp: Binary file-like object
:return: bytes
"""
... | a33d0310b7fec1aff9e3e17adcf14a1acc8ccff6 | 584,741 |
import pytz
from datetime import datetime
def edt_to_utc(date, mask='%m/%d/%Y %I:%M%p'):
"""
Convert EDT (Eastern Daylight Time) to UTC
:param date: EDT date string e.g. '5/26/2014 4:00pm'
:param mask: format of input date e.g '%m/%d/%Y %I:%M%'
:return: UTC date string e.g '2014-03-05 12:23:00 UT... | ee3fd1f05463334f13fc0dae88c029fb167f1209 | 584,742 |
def map_transaction(txn):
"""
Maps a single transaction row to a dictionary.
Parameters
----------
txn : pd.DataFrame
A single transaction object to convert to a dictionary.
Returns
-------
dict
Mapped transaction.
"""
# sid can either be just a single value or ... | 014fb04a93a40bcd324743af5dc4c9b8f20a80dd | 584,745 |
def is_iterable(iterable):
"""
Determine if the provided object is an iterable type.
:param iterable: Object to test
:return: True if the object is an instance of an iterable data type
"""
try:
iter(iterable)
return True
except TypeError:
return False | 828af9d1a0ea965e6ad41e14a55d95e7ac22285d | 584,746 |
from typing import List
def remove_nested_packages(packages: List[str]) -> List[str]:
"""Remove nested packages from a list of packages.
>>> remove_nested_packages(["a", "a.b1", "a.b2", "a.b1.c1"])
['a']
>>> remove_nested_packages(["a", "b", "c.d", "c.d.e.f", "g.h", "a.a1"])
['a', 'b', 'c.d', 'g.... | 04cacb569dbe68b61861462e754d62fd27b22ffe | 584,748 |
def maprange( range_from, range_to, value):# {{{
"""Map value from range_from -> range_to
range_from and range_to are tuples
"""
(f1, f2) = range_from
(t1, t2) = range_to
new_value = t1 + ((value - f1) * (t2 - t1) / (f2 - f1))
return new_value | 5d00a5b5cd983dd8702d37997357f99b81bc6944 | 584,750 |
def summary(file):
"""
Summarize the General Ledger by transaction type.
"""
return (
file.groupby("Transaction Type")["Debit", "Credit", "Net"].sum().round(1).abs()
) | e8c3730bed2aa96e4e9a282c43b8151cc945fc4c | 584,751 |
def squeeze(obj):
"""
Return the item of an array of length 1,
otherwise return original object.
"""
try:
return obj.item()
except (ValueError, AttributeError):
return obj | d9e1412981180f271fa74a790ba8e298be0aa2f8 | 584,753 |
from pathlib import Path
from typing import Tuple
from typing import List
def get_file_paths(
root_dir: Path,
) -> Tuple[List[str], List[str]]:
"""Load the list of training and ground truth image paths.
Args:
root_dir: Path to the directory where the CIL data is extracted
Returns:
Li... | f7283d91a21cff06996d0966bdf2b876ea46169c | 584,754 |
def get_next_available_key(iterable, key, midfix="", suffix="", is_underscore=True, start_from_null=False):
"""Get the next available key that does not collide with the keys in the dictionary."""
if start_from_null and key + suffix not in iterable:
return key + suffix
else:
i = 0
und... | 4918d85fb3708357bbadc988fae4e5a12ba3aa7c | 584,755 |
def transposta_matriz(M):
"""Calcula a transposta de uma matriz."""
lin = len(M[0])
col = len(M)
MT = []
for l in range(lin):
linha = []
for c in range(col):
linha.append(M[c][l])
MT.append(linha)
return MT | 763875fdb2f2e0a4f000c2d6706e9b1795b395d6 | 584,757 |
def clamp(value, min_value, max_value):
"""
Returns *value* clamped to the range *min_value* to *max_value* inclusive.
"""
return min(max_value, max(min_value, value)) | 3ef7157c806dd56eccbd2ac286656ee1e3c9aeac | 584,764 |
def format_property(obj, name):
"""
Format an object property's dotted name.
:param obj: The object that owns the property.
:param name: The name of the property (a string).
:returns: The dotted path (a string).
"""
return "%s.%s" % (obj.__class__.__name__, name) | 4fcfa8ece0ee2aac6874a26c8a570a4cd9f0ac91 | 584,772 |
def strip_id_from_matrix(mat):
"""
Remove the ID (1st row element) form a matrix
:param mat: a 2D list
:rtype: a 2D list with the 1st row elelemnt (ID) removed
"""
new_mat = []
for i in range(0, len(mat)):
new_mat.append(mat[i][1:])
return new_mat | f0478bc5a938857334707f5a1bac5b67bfa71187 | 584,775 |
def get_next_epoch(savedmodel_path):
"""
Read the path to the saved model and returns the next eopch to train on.
Input: string specifying path
Returns: int specifying the next epoch
"""
if savedmodel_path == "":
next_epoch = 1
else:
next_epoch = int(savedmodel_path[savedmode... | 142d3f2a21c38036063f95b437548984f34d54a6 | 584,777 |
def parse_grouping(p):
"""Parse primary and secondary digit grouping
>>> parse_grouping('##')
(1000, 1000)
>>> parse_grouping('#,###')
(3, 3)
>>> parse_grouping('#,####,###')
(3, 4)
"""
width = len(p)
g1 = p.rfind(',')
if g1 == -1:
return 1000, 1000
g1 = width - g... | 9f6d27e1f43fad030463c21bcb3954ca047cf825 | 584,778 |
def id_in_database_check(p_my_cursor, p_id_number_to_remove):
"""Called to check if id number is present in the database. Returns True if ID found, returns false if ID not found."""
sql = f"SELECT * FROM contacts.contact WHERE id={p_id_number_to_remove}"
p_my_cursor.execute(sql)
data_rows = p_my_cursor... | a82da4946d13b7d7349e43020ebb08da1e06657a | 584,779 |
import torch
def outer_pairwise_distance(A, B=None):
"""
Compute pairwise_distance of Tensors
A (size(A) = n x d, where n - rows count, d - vector size) and
B (size(A) = m x d, where m - rows count, d - vector size)
return matrix C (size n x m), such as C_ij = distance(i-th... | de6e13f684a81a049f031f69dfa512b092002478 | 584,780 |
import string
def sanitize(s: str) -> str:
"""
Return sanitized string for printing to cli.
"""
s = s.replace("\n", "\\n")
s = s.replace("\r", "\\r")
s = s.replace("\t", "\\t")
s = s.replace("\\\\", "\\") # print single backslashes
s = "".join(c for c in s if c in string.printable)
... | a2379866dbcaaafc47ff3dd434b95d8977393f10 | 584,781 |
import random
import string
def rand_ascii_str(length=10):
"""
Generates a random string of ascii characters of length 'length'
"""
return ''.join(random.choice(string.ascii_letters) for x in range(length)) | f08e744ffe77f381a4cb924f5d5d2de4fa75601c | 584,784 |
def median_solution_2(a, b, c):
"""
compute the median of three values using built-in min and max functions
and a little bit of arithmetic.
Notes
-----
The median of three values is the sum of the values minus the smallest minus the largest
Parameters
----------
a : f... | 3c9b7ada1c791f230d17c09bddb07909ae1ae279 | 584,793 |
def process_coordinates(df):
"""Takes a dataframe and make a column for `latitude` and another one
for `longitude` with data from `coordinates` column. The new columns
will be float dtype.
Parameters
----------
df :
The dataframe to search.
Returns
-------
The datafr... | 94f5ee0e12e6df69592438fc55044dedac78ea88 | 584,796 |
from bs4 import BeautifulSoup
import re
def parse_saldo(page_source):
"""Parses saldo.
:param page_source: HTML page source
:return: Saldo or None
:rtype: str or None
"""
soup = BeautifulSoup(page_source, 'lxml')
lines = soup.find_all('div', class_='kontozeile_center')
if lines:
... | 26bbaeeab8e18a92c5af45bd3504b4f90215dc12 | 584,797 |
def car(pair):
"""Return the first element of a pair created with `cons`
param pair: A pair that was created with `cons`
returns: The first element of the pair
"""
def fst(x, _):
return x
return pair(fst) | 4877787d8e6c0313def2467aabd8485c2025e4b2 | 584,800 |
def toint2(i):
""" Convert a number to a binary string of length 8 """
return f'{i:08b}' | 6b5abb4409349db3ec13b26f64a3c27fc4e4c470 | 584,804 |
def inline_code(text: str) -> str:
"""Formats text for discord message as inline code"""
return f"`{text}`" | 383de38fedcc6f06505333b7a3ea9a66fa991a10 | 584,805 |
def srf_dxy(srf):
"""
Retrieve SRF dx and dy.
Assumes all planes have same dx, dy.
srf: SRF file path to read from
"""
with open(srf, "r") as sf:
# version
sf.readline()
# planes definition
sf.readline()
# first plane
elon, elat, nstk, ndip, length... | 3ad653a15cd4460262cfb3d8f5203d070401c01f | 584,806 |
import difflib
def diff(old, new):
"""
Helper function. Returns a string containing the unified diff of two multiline strings.
"""
old=old.splitlines(1)
new=new.splitlines(1)
diff=difflib.unified_diff(old, new)
return ''.join(diff) | 9c892a14a61264d1a3a77ce75b3c234e3dc5ff09 | 584,808 |
def trimandshift(t, p):
"""
Takes the vectors given by the above function,
and chops out a day and samples at half hourly intervals.
"""
t3, p3 = [], []
t2 = t[132+4*144:276+4*144]
p2 = p[132+4*144:276+4*144]
for i in range(len(t2)):
if (i%3) == 0:
t3.append(t2[i])
p3.append(p2[i])
return t3, p3 | 5bb2a3aa01667b58f7b925ae3b4f92ee37193e15 | 584,810 |
def highzvpickup(I, RL, Rct, CTR=1, threephase=False, Ks=1.5,
Vstd=400, Kd=0.5):
"""
High Impedance Pickup Setting Function.
Evaluates the voltage pickup setting for a high
impedance bus protection system.
Parameters
----------
I: float
Fault curre... | 649f8ee3a5bd420713b523baa8f1d767f941acec | 584,816 |
def identity_step(iterator):
"""A pipeline-step which does nothing."""
return iterator | d4e7ac57f5be9295ba7695190e2909c2c1e33232 | 584,821 |
def _substr(s, n, split_string):
""" Recursively get string between n-th and (n+1)-th occurence. Useful
for getting band information (bandinf) such as polarisation VV, VH, ...
"""
if n == 0:
return s[:s.find(split_string)]
else:
return _substr(s[s.find(split_string)+1:], n-1, spl... | 76542c15c17538092e1862942491d6b5a5be2a44 | 584,824 |
def single_point_truncation(f, x_0, x_1, eps=0, eta=0, max_steps=20, verbose=False):
"""单点弦截法
Args:
f: function, 迭代函数
x_0, x_1: float, 初值
eps: float, 根的容许误差, default 0.
eta: float, abs(f(x)) 的容许误差, default 0.
max_steps: int, 最大迭代次数, default 20.
verbose: bool, 打... | 19f1ebae5770be21c5b767340633823a4bb63735 | 584,827 |
def f(L1, L2):
"""L1, L2 lists of same length of numbers
returns the sum of raising each element in L1
to the power of the element in the same index in L2
For example, f([1,2], [2,3]) returns 9"""
return sum(n for n in map(lambda x, y: x ** y, L1, L2)) | 88bc319eb43590f8b44d3724e80cf874f50d66ee | 584,828 |
def update_light(command, light):
"""Compute new light value.
Args:
command (str): 'toggle', 'turn on' or 'turn off'
light (int): Light status before command execution
Returns:
int: New light status
"""
logic = {
"toggle": light + 2,
"turn on": light + 1,
... | c6854f725853ad5253005880c1cb87e5287eff10 | 584,834 |
def getOverviewName(viewName):
"""
Return Overview sheet name formatted with given view.
"""
return 'Overview ({})'.format(viewName) | 033b99bb8bdd28dbc78b53ae6d9b22cbbab29e2c | 584,835 |
def split_at(string, sep, pos):
"""
Return string splitted at the desired separator.
Args:
string (str): The supplied string that will be splitted.
sep (str): The desired separator to use for the split.
pos (int): The desired occurence of the defined separator
within the... | fbf3c3bf2de389d2ea1f1142c3b314718e36f73c | 584,840 |
def degree(node, row, col):
"""return the degree of the given node"""
neighbors = col[row == node]
return len(neighbors) | 9186f748b84ccae5d274a01c47e02d8e078ec08d | 584,841 |
def a(a1, a2):
"""
Return the sum of a1 and a2.
"""
return a1 + a2 | 0767a4050819bdf1ae2522f60fa815abba776976 | 584,842 |
def disabled(cls):
"""
Testcase decorator that marks the test as being disabled.
These tests are not automatically added to the "standard" group or
their module's group.
"""
cls._disabled = True
return cls | cf80ed90f001bf60bf681b15aff80987e661bcab | 584,846 |
def semPad(ver: list[str], length: int) -> list[str]:
"""Pad a semver list to the required size. e.g. ["1", "0"] to ["1", "0", "0"].
Args:
ver (list[str]): the semver representation
length (int): the new length
Returns:
list[str]: the new semver
"""
char = "0"
if ver[-1] == "*":
char = "*"
return ver +... | 6e794fddc961d16c5f24ba66624360ec13394739 | 584,848 |
import re
def is_valid_doi(doi: str) -> bool:
"""Validate a DOI via regular expressions.
Parameters
----------
doi : string
A single DOI to be validated.
Returns
-------
bool
True, if DOI is valid, False if not.
"""
patterns = [
r"^10.\d{4,9}/[-._;()/:A-Z... | aa68070230fc3aa4709cef03b95ff2457803618f | 584,851 |
from typing import List
def _get_shared_columns(source_columns: List[str], destination_columns: List[str]) -> List[str]:
""" Return the list of columns contained in both lists. """
shared_columns = [c for c in destination_columns if c in source_columns]
if not shared_columns:
raise RuntimeError("... | 661e37e16e9db541ebb554ec503e61bfd9f2fbac | 584,858 |
def get_format_vertical_parity_sign(format):
"""
Get the vertical data layout associated with an image format, expressed as a
coordinate system parity sign.
Parameters
----------
format : :class:`str`
The format name; one of ``SUPPORTED_FORMATS``
Returns
-------
Either +1 o... | 1b61839cc249d791b2345bf5a268b7a7fefad553 | 584,859 |
def countBits(value):
"""
Count number of bits needed to store a (positive) integer number.
>>> countBits(0)
1
>>> countBits(1000)
10
>>> countBits(44100)
16
>>> countBits(18446744073709551615)
64
"""
assert 0 <= value
count = 1
bits = 1
while (1 << bits) <= ... | d345aa1f93a18087a3c37446f814ea0d84ccd391 | 584,860 |
def string_to_bool(s):
"""
Helper function to convert any strings of those to be true
We have different way to say yes!"
:param s: input
:type s: str
:return: True or False
:rtype: bool
"""
if s.lower() in ["true", "t", "yes", "yeah", "yup", "y", "certainly",
... | fd66f144171f21d2ee4c925cb0462d28b0502ef8 | 584,862 |
import csv
def load_pose(filename):
"""
Loads initial and goal state information for a robot from a text file
:param filename: path and name to the file with robot state information
:return: dictionaries for the initial state and goal state
"""
with open(filename, 'r', encoding='utf8') as fin... | 35cf0c3089708531abe4f7d2b706c06b1d7d8789 | 584,867 |
def stimulus(t):
"""
External Current
| :param t: time
| :return: step up to 10 uA/cm^2 at t>100
| step down to 0 uA/cm^2 at t>200
| step up to 35 uA/cm^2 at t>300
| step down to 0 uA/cm^2 at t>400
"""
return 10 * (t > 100) - 10 * (t > 200) + 35 * (t ... | b25ea28f2c8e1e3c165de5776a148888e21c92fd | 584,868 |
def _flip(arr, axes=None):
""" Reverse array over many axes. Generalization of arr[::-1] for many
dimensions. If `axes` is `None`, flip along all axes. """
if axes is None:
reverse = [slice(None, None, -1)] * arr.ndim
else:
reverse = [slice(None, None, None)] * arr.ndim
for axis ... | 17b0b9b0e65ff97eea22f38da97bd292a8fa594d | 584,870 |
import torch
def set_device(cuda: bool) -> torch.device:
"""Set the device for computation.
Args:
cuda (bool): Determine whether to use GPU or not (if available).
Returns:
Device that will be use for compute.
"""
device = torch.device("cuda" if (torch.cuda.is_available() and cuda... | 31619ee83bb1f93aae5eac63094ddee4ebc634e4 | 584,875 |
def is_valid_index(idx, in_list, start_idx=0):
"""
param: idx (str) - a string that is expected to
contain an integer index to validate
param: in_list - a list that the idx indexes
param: start_idx (int) - an expected starting
value for idx (default is 0); gets
subtra... | c52e93a059d7f0e20a910bb4831cc4779a82f6ac | 584,880 |
def handleNameConstant(node, line):
""" Converts the NameConstant node to represent the type of the value (True, False, None). """
return str(node.value) | 7dcaa517069cd52b3d1718a72311eb2b742e664d | 584,884 |
def get_formatted_wwn(wwn_str):
"""Utility API that formats WWN to insert ':'.
"""
if (len(wwn_str) != 16):
return wwn_str
else:
return ':'.join(
[wwn_str[i:i + 2] for i in range(0, len(wwn_str), 2)]) | f639653beda49f8bae61586789b1ede4f73ae48a | 584,885 |
import mimetypes
import io
import re
def template_strings(self):
"""Check for template placeholders.
The ``nf-core create`` pipeline template uses
`Jinja <https://jinja.palletsprojects.com/en/2.11.x/>`_ behind the scenes.
This lint test fails if any Jinja template variables such as
``{{ pipeline... | 80fe14b9783e17a5f9ec2b107c53334aa26ab4ca | 584,887 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.