content stringlengths 42 6.51k |
|---|
def remove_nullchars(block):
"""Strips NULL chars taking care of bytes alignment."""
data = block.lstrip(b'\00')
padding = b'\00' * ((len(block) - len(data)) % 8)
return padding + data |
def isPalindrome(x):
"""
Take integer number and determine if palindrome.
:type x: int
:rtype: bool
"""
if x < 0:
return False
# convert to string
x = str(x)
if x[-1] == '0' and len(x) > 1:
return False
if x == x[::-1]:
return True
return False |
def read_file(file_path):
""" There are problems with pd.read_csv() for the retail.csv that's why this implementation.
:param file_path: path to file
:return: List of transactions with items
"""
dataset = []
with open(file_path, 'r') as f:
transactions = f.readlines()
for trans... |
def b2u(string):
""" bytes to unicode """
if isinstance(string, bytes):
return string.decode('utf-8')
return string |
def flatten_dictionary(nested_dict, separator):
"""Flattens a nested dictionary.
New keys are concatenations of nested keys with the `separator` in between.
"""
flat_dict = {}
for key, val in nested_dict.items():
if isinstance(val, dict):
new_flat_dict = flatten_dictionary(val,... |
def select_params(params):
""" Grabs just the necessary keys from params """
return {
'Bucket': params['Bucket'],
'NotificationConfiguration': params['NotificationConfiguration']
} |
def curl_field_vector(x, y, z, px, py, pz):
"""calculate a 3D velocity field using vector curl noise"""
eps = 1.0e-4
offset = 100.0
def deriv(a1, a2):
return (a1 - a2) / (2.0 * eps)
# x_dx = deriv(px(x + eps, y, z), px(x - eps, y, z))
x_dy = deriv(px(x, y + eps, z), px(x, y - eps, z))... |
def hashable_key(key):
"""
Convert the key from couch into something hasable.
Mostly, just need to make it a tuple and remove the special
{} value.
"""
return tuple('{}' if item == {} else item for item in key) |
def MathMLExtraction(s):
"""
Takes a MathML expression as string, returns the last mn or mo value.
To-do: @@ this is a very rough implementation based on string operations. Should have parsed the mathML
:param s: mathML string with mo or mn components
:return: the value of the last mn or mo elemen... |
def links(links_title, links=None, **kwargs):
"""
A section of the list. Please see 'link'.
:param links_title: A title of the section.
:param links: list of the links
:param kwargs: additional links defined is simplified form:
links(..., home="Go home", index="Main page")
"""... |
def test_vertically(board: list) -> bool:
"""
test vertically
"""
i = 0
while i < 9:
col = []
for row in board:
col.append(row[i])
if sorted(col) != [1, 2, 3, 4, 5, 6, 7, 8, 9]:
return False
i += 1
return True |
def remove_trailings(input_string):
"""
Remove duplicated spaces.
"""
output_string = " ".join(input_string.split())
return output_string |
def generatePercentage (frequency, base_parameter):
"""Function that generate a frequency percentage and includes one global variable that determines
the proportionate of each frequency."""
# for each item of the function input list that is the incedent of a particular result, turn
# i... |
def dict_from_list(keys, values):
"""
Generate a dictionary from a list of keys and values.
:param keys: A list of keys.
:param values: A list of values.
:returns: dict
Example::
>>> bpy.dict_from_list(['a', 'b', 'c'], [1, 2, 3])
{'a': 1, 'b': 2, 'c': 3}
"""
return di... |
def parse_requirements(filename):
""" load requirements from a pip requirements file """
lines = (line.strip() for line in open(filename))
return [line for line in lines if line and not line.startswith("#")] |
def number_filter(value, fmt="{:,.0f}"):
"""
Format numbers, default format is integer with commas
"""
return fmt.format(float(value)) |
def song_has_info(db_session, song_id):
"""Check to see if a portion of the table is empty."""
try:
c = db_session.cursor()
c.execute("""SELECT 1 FROM %s WHERE song_id = ? LIMIT 1""" % 'songs', [song_id])
result = c.fetchone()
#db_session.commit()
c.close()
if res... |
def portmerge(current, new):
"""Merge ports
Parameters
----------
current : str or List
Current set of ports
Returns:
str or List
The list will be a sorted unique set of ports
"""
if isinstance(current, str):
return current
if isinstance(new, str):
... |
def load_json_file(infile):
"""Read file. Strip out lines that begin with '//'."""
lines = []
for line in infile:
if not line.lstrip().startswith('//'):
lines.append(line)
content = ''.join(lines)
return content |
def shorten(text, length, placeholder):
"""
Truncate *text* to a maximum *length* (if necessary), indicating truncation
with the given *placeholder*.
The maximum *length* must be longer than the length of the *placeholder*.
Behaviour is slightly different than :py:func:`textwrap.shorten` which is
... |
def find_data_path(bone_name_list, data_path):
"""find bone_name from from data_path"""
for x in bone_name_list:
if data_path == 'pose.bones["' + x + '"].location':
return True, x
return False, "" |
def flip_bit(bit):
"""
:param bit: '0' or '1'
:return: '1' or '0', respectively
"""
return str(1 - int(bit)) |
def try_decode(obj: bytes, encoding="utf-8"):
"""
Try decode given bytes with encoding (default utf-8)
:return: Decoded bytes to string if succeeded, else object itself
"""
try:
rc = obj.decode(encoding=encoding)
except AttributeError:
rc = obj
return rc.strip() |
def get_is_head_of_word(naive_tokens, sequence_tokens):
"""
Return a list of flags whether the token is head(prefix) of naively split tokens
ex) naive_tokens: ["hello.", "how", "are", "you?"]
sequence_tokens: ["hello", ".", "how", "are", "you", "?"]
=> [1, 0, 1, 1, 1, 0]
*... |
def castable_to_int(s):
"""
Return True if the string `s` can be interpreted as an integer
"""
try:
int(s)
except ValueError:
return False
else:
return True |
def offset_for_stacking(items, offset):
""" Remove offset items from the end and copy out items from the start
of the list to offset to the original length. """
if offset < 1:
return items
return [items[0] for _ in range(offset)] + items[:-offset] |
def get_thresholds(col,act_threshold=0.995,attr_threshold=0.99):
"""
Defines a custom threshold function
"""
if col =='activity':
return act_threshold
else:
return attr_threshold |
def init_actions_(service, args):
"""
this needs to returns an array of actions representing the depencies between actions.
Looks at ACTION_DEPS in this module for an example of what is expected
"""
# some default logic for simple actions
return {
'test': ['install'],
'test2... |
def get_rate_units(units, time_units, deriv=1):
"""
Return a string for rate units given units for the variable and time units.
Parameters
----------
units : str
Units of a given variable.
time_units : str
Time units.
deriv : int
If 1, provide the units of the first ... |
def add_column(content, col_index, col_info=[]):
"""
From the position of the cursor add a column
Arguments:
- the table content, a list of list of strings:
- First dimension: the columns
- Second dimensions: the column's content
- cursor index for col
- op... |
def compare_rrs(expected, got):
""" Compare lists of RR sets, throw exception if different. """
for rr in expected:
if rr not in got:
raise Exception("expected record '%s'" % rr.to_text())
for rr in got:
if rr not in expected:
raise Exception("unexpected record '%s'" ... |
def tableau_string(text):
"""Transforms to a string representation in Tableau
"""
value = repr(text)
if isinstance(text, str):
return value[1:]
return value |
def variance_covariance(data, population_variance=False):
"""
Returns the Variance-Covariance matrix for ``data``.
From: http://www.python-forum.org/pythonforum/viewtopic.php?f=3&t=17441
"""
N = len(data) # number of vectors
D = len(data[0]) # dimensions per vector
if population_variance:
... |
def human_friendly_temp(my_temperature_f):
"""Rounds a decimal fahrenheit temperature to the nearest whole degree, adds degree symbol"""
degree_sign = u"\N{DEGREE SIGN}"
return f"{round(my_temperature_f)} {degree_sign}F" |
def _transform_column(raw, type_overrides):
"""helper function to facilitate converting specs to SQL
"""
output = {}
output['name'] = raw['field']
output['type'] = type_overrides.get(raw['type'], raw['type'])
return output |
def calc_spiral_size(number):
"""
Tries to calculate the maximum size of the spiral.
"""
size = 1
found = False
while not found:
if (size * size) < number:
size += 1
else:
found = True
return size |
def getQStr(dateStr) :
"""
Converts a date in YYYYMMDD format to YYYY/QTRn/
where n is the quarter number from 1 to 4."
"""
return dateStr[:4] + '/QTR' + str((int(dateStr[4:6])+2) // 3) + '/' |
def _DoRemapping(element, map):
"""If |element| then remap it through |map|. If |element| is iterable then
each item will be remapped. Any elements not found will be removed."""
if map is not None and element is not None:
if not callable(map):
map = map.get # Assume it's a dict, otherwise a callabl... |
def GetLapicVersionFields(reg_val):
""" Helper function for DoLapicDump that prints the fields of the
version register.
Params:
reg_val: int - the value of the version register to print
Returns:
string showing the fields
"""
lvt_num = (reg_val >> 16) + 1
... |
def get_head(phrase):
"""Retrieve a phrase head."""
src, tgt, rela = phrase
if type(tgt) == int:
return tgt
else:
return get_head(tgt) |
def teorijska_hrapavost(posmak, radijus_alata):
"""
"""
return posmak**2./8./radijus_alata |
def cmp(x, y): # from: https://portingguide.readthedocs.io/en/latest/comparisons.html
"""
Replacement for built-in function cmp that was removed in Python 3
Compare the two objects x and y and return an integer according to
the outcome. The return value is negative if x < y, zero if x == y
and str... |
def round_blend_step(step):
"""
get the blendshape weight value
:param step:
:return:
"""
return int(step * 1000) / 1000.0 |
def get_supported_os(scheduler):
"""
Return a tuple of the os supported by parallelcluster for the specific scheduler.
:param scheduler: the scheduler for which we want to know the supported os
:return: a tuple of strings of the supported os
"""
return "alinux" if scheduler == "awsbatch" else "... |
def getStatus(sig, det_status):
"""
Determine a signal's detection status based on the status
of its detectors
Parameters
----------
sig : dict | (required)
A signal record dict generated from a Knack.View instance
det_status : dict | (required)
A lookup dictionary gener... |
def xgcd(a, b):
"""
Extended Euclid GCD algorithm.
Return (x, y, g) : a * x + b * y = gcd(a, b) = g.
"""
if a == 0:
return 0, 1, b
if b == 0:
return 1, 0, a
px, ppx = 0, 1
py, ppy = 1, 0
while b:
q = a // b
a, b = b, a % b
x = ppx - q * px
... |
def cumulativeMass(listOfPlanets):
"""
Calculates the total mass of all given masses
@param listOfMasses: A list that contains all the different masses
@return totalMass:
>>> lop = list()
>>> lop.append(Planet(1, 500, 0, numpy.array([5, 7, 3]), 0))
>>> lop.append(Planet(2, 600, 0, nump... |
def exact_matches(data_1, data_2, match_fields):
""" Identifies exact and non-exact matches between data sets. """
nonexact_1 = {}
nonexact_2 = {}
exact_pairs = []
redundant = {}
for key, record in data_1.items():
record_hash = hash(tuple(record[f] for f in match_fields))
redun... |
def flatten(ls):
"""flatten a list one level
>>> flatten([[1,2],[3,4],[5,6]])
[1, 2, 3, 4, 5, 6]
"""
return [v for sub in ls for v in sub] |
def normaliseFrequency(f, timespan):
"""Convert a frequency in the units of the data into normalised frequency.
Useful for computing input arguments in {high|low}Pass()
Inputs:
f (float) Frequency in, e.g, Hz
timespace (float) Range of data in , eg, seconds. This is the time
... |
def merge_two_lists(t1, t2):
"""
Merge two tuples of lists
Args:
t1: the tuple of the first lists
t2: the tuple of the second lists
Returns:
a new tuple of the merged lists
"""
a1, b1 = t1
a2, b2 = t2
return a1 + a2, b1 + b2 |
def convolution_math(in_features, filter_size, out_features):
"""
Convolution math: Implement how parameters scale as a function of feature maps
and filter size in convolution vs depthwise separable convolution.
Args:
in_features: number of input features
filter_size: size of the filter
out_featu... |
def get_sec(time_str):
"""Get Seconds from time."""
h, m, s = time_str.split(':')
return int(h) * 3600 + int(m) * 60 + float(s) |
def _normalize_activity_share_format(share):
"""
Convert the input share format to the internally format expected by FTS3
{"A": 1, "B": 2} => [{"A": 1}, {"B": 2}]
[{"A": 1}, {"B": 2}] => [{"A": 1}, {"B": 2}]
"""
if isinstance(share, list):
return share
new_share = list()
for key,... |
def is_empty_line(line: str) -> bool:
"""
Tell if a line is empty.
Arguments:
line: The line to check.
Returns:
True if the line is empty or composed of blanks only, False otherwise.
"""
return not line.strip() |
def validate_input_command(input_val):
"""Validates that the Command line includes
numbers"""
val = [input_val[0]]
if input_val[0].upper() == 'B':
for i in input_val[1:-1]:
try:
val.append(int(i))
except ValueError:
print('Parameters must ... |
def get_job_def(env_filename, args, sig_owners):
"""Returns the job definition given the env_filename and the args."""
return {
'scenario': 'kubernetes_e2e',
'args': ['--env-file=%s' % env_filename] + args,
'sigOwners': sig_owners or ['UNNOWN'],
# Indicates that this job definiti... |
def create_tweet_history_msg(tweet_content: str) -> str:
"""
Create history message based on tweet content.
Arguments:
tweet_content (str): Content string of the tweet.
Returns:
str: Single line log message for the tweet. Log messages should be
single line for readability a... |
def choose_index(keys, df):
"""
Chooses key from a list of keys. Order of priority:
1) shortest length
2) has "id" in some form in name of an attribute
3) has attribute furthest to the left in table
Arguments:
keys (list[set[str]]) : list of keys to choose from
df (pd.DataFrame)... |
def _get_pipeline_configs_for_project(project_id, data):
"""
Given a project id, return a list of associated pipeline configurations.
Based on the Shotgun cache data, generates a list of project root locations.
These are then compared (case insensitively) against the given path and
if it is determi... |
def calc(x, y, serial):
"""
Find the fuel cell's rack ID, which is its X coordinate plus 10.
Begin with a power level of the rack ID times the Y coordinate.
Increase the power level by the value of the grid serial number (your puzzle
input).
Set the power level to itself multiplied by the rack I... |
def get_detection_rate(stats):
"""Get detection rate as string."""
return f'{stats["malicious"]}/{sum(stats.values())}' |
def trunc(x, y, w, h):
"""Truncates x and y coordinates to live in the (0, 0) to (w, h)
Args:
x: the x-coordinate of a point
y: the y-coordinate of a point
w: the width of the truncation box
h: the height of the truncation box.
"""
return min(max(x, 0), w - 1), min... |
def triplets_with_sum(number):
"""
Get all triplets
"""
result = []
for _a in range(1, number - 1):
if _a ** 2 % (number - _a) == 0:
if (number - _a + (_a ** 2) // (number - _a)) % 2 == 0:
_c = (number - _a + (_a ** 2) // (number - _a)) // 2
_b... |
def adjusted_r2(ord_r2, sample_size, n_of_feat):
"""
This function calcualted the adjusted R-squared value from the ordinary
R-squared value reported from sklearn
"""
adj_r2 = 1-(1-ord_r2)*(sample_size-1)/(sample_size-n_of_feat-1)
return adj_r2 |
def sigmoid(x):
"""Numerically-stable sigmoid function."""
import math
if x >= 0:
z = math.exp(-x)
return 1 / (1 + z)
else:
z = math.exp(x)
return z / (1 + z) |
def update_dict(old_data, new_data):
"""
Overwrites old usa_ids, descriptions, and abbreviation with data from
the USA contacts API
"""
old_data['usa_id'] = new_data.get('usa_id')
if new_data.get('description') and not old_data.get('description'):
old_data['description'] = new_data.get(... |
def scramble_soft(bits, seq):
"""Convert between type 4 and type 5 soft bits"""
return bits ^ (seq * 0xFF) |
def calc_elo(elo, true, expected):
"""
Calculates the increase/decrease in ELO,
with a K value of 32.
"""
return elo + 32 * (true - expected) |
def summary_ranges(nums):
"""
:type nums: List[int]
:rtype: List[str]
"""
res = []
if len(nums) == 1:
return [str(nums[0])]
i = 0
while i < len(nums):
num = nums[i]
while i+1 < len(nums) and nums[i+1] - nums[i] == 1:
i += 1
if nums[i] != num:
... |
def Lambda(zhub, IECedition=3):
"""
IEC length scale. Lambda = 0.7*min(Zhat,zhub)
Where: Zhat = 30,60 for IECedition = 2,3, respectively.
"""
if IECedition <= 2:
return 0.7 * min(30, zhub)
return 0.7 * min(60, zhub) |
def get_num_species(dim, q):
"""Return number of mixture species."""
return len(q) - (dim + 2) |
def point_avg(points):
"""
Accepts a list of points, each with the same number of dimensions.
NB. points can have more dimensions than 2
Returns a new point which is the center of all the points.
"""
dimensions = len(points[0])
new_center = []
for dimension in range(dimensions):
... |
def parse_image_url(url):
"""
Parses a url continaing the image id to return the image id.
"""
# Check if it was a url or actual image id
# eg: https://map.openaerialmap.org/#/.../59e62b9a3d6412ef7220a51f?_k=vy2p83
image_id = url.split("/")[-1].split("?")[0]
return image_id |
def is_lambda_reduce(mod):
"""check for the presence of the LambdReduce block used by the
torch -> pytorch converter
"""
return 'LambdaReduce' in mod.__repr__().split('\n')[0] |
def parse_vref_from_product(product):
"""
:param product: Product name (typically from satimg.parse_metadata_from_fn)
:type product: str
:return: vref_name: Vertical reference name
:rtype: vref_name: str
"""
# sources for defining vertical references:
# AW3D30: https://www.eorc.jaxa.jp... |
def approx_second_derivative(f,x,h):
"""
Numerical differentiation by finite differences. Uses central point formula
to approximate second derivative of function.
Args:
f (function): function definition.
x (float): point where second derivative will be approximated
h (float): step size for cen... |
def atexit_shutdown_grace_period(grace_period=-1.0):
"""Return and optionally set the default worker cache shutdown grace period.
This only affects the `atexit` behavior of the default context corresponding to
:func:`trio_parallel.run_sync`. Existing and future `WorkerContext` instances
are unaffected.... |
def _unescape_nl(text):
"""Convert escaped newline characters ``\\n`` back into newlines"""
return str(text).replace('\\n', '\n') |
def get_filename(url):
"""
get_filename(string) -> string
extracts the filename from a given url
"""
pos = (url.rfind('/')+1)
return url[pos:] |
def compute_f1_score(precision, recall):
"""
Computes the F1-score between the precision and recall
:param precision: float number
:param recall: float number
:return: The float corresponding to F1-score
"""
if precision == 0 and recall == 0:
return 0
else:
retu... |
def url(endpoint, path):
"""append the provided path to the endpoint to build an url"""
return f"{endpoint.rstrip('/')}/{path}" |
def is_bool(s):
"""
Returns True if the given object has None type or False otherwise
:param s: object
:return: bool
"""
return isinstance(s, bool) or str(s).lower() in ['true', 'false'] |
def exc_msg_str(exception, default="") -> str:
"""
Extract the exception's message, or its str representation, or the default message, in order of
priority.
"""
try:
msg = exception.args[0]
except (AttributeError, IndexError):
msg = None
if not msg or not isinstance(msg, str... |
def batch_axis(input_shape):
"""Get the batch axis entry of an input shape.
Parameters
----------
input_shape : tuple
The data shape related to dataset.
Returns
-------
axis : int
The batch axis entry of an input shape.
"""
idx = [i for i, s in enumerate(input_shape... |
def convert_atid_to_key(atid_name_list):
"""Removes last letter from all strings in list."""
key_name_list = [atid_name[:-1] for atid_name in atid_name_list]
return key_name_list |
def except_or(f, exception, *default):
"""Catch Exception and Return Default."""
try:
return f()
except exception:
if default:
return default[0]
return |
def vectorize(dictionary, words):
"""
Converts a list of words into a list of frequency position numbers.
Args:
dictionary(dict): Dictionary containing the words in the vocabulary together
with their frequency position.
words(list): List of words that are to be converted.
Re... |
def files_have_same_point_format_id(las_files):
"""Returns true if all the files have the same points format id"""
point_format_found = {las.header.point_format_id for las in las_files}
return len(point_format_found) == 1 |
def single_number(integers):
"""
Naive version: Given a non-empty array of integers, every element appears
twice except for one. Find that single one.
Runtime: O(n), Space: O(n)
"""
seen = set()
for integer in integers:
if integer in seen:
seen.remove(integer)
els... |
def read_whole_file(filename: str) -> str:
"""
reads the whole file into a string, for example
>>> read_whole_file("README.md").split("\\n")[2]
'# Neural Semigroups'
:param filename: a name of the file to read
:returns: whole contents of the file
"""
with open(filename, "r", encoding=... |
def flatten(list_, ltypes=(list, tuple)):
"""Flatten lists of list into a list."""
ltype = type(list_)
list_ = list(list_)
i = 0
while i < len(list_):
while isinstance(list_[i], ltypes):
if not list_[i]:
list_.pop(i)
i -= 1
break
... |
def _calculate_step_sizes(x_size, y_size, num_chunks):
""" Calculate the strides in x and y.
Notes
-----
Calculate the strides in x and y to achieve at least the
`num_chunks` pieces.
Direct copy from ccdproc:
https://github.com/astropy/ccdproc/blob/b9ec64dfb59aac1d9ca500ad172c4eb31ec305f8/c... |
def check_required_hash(md5_hash):
"""Check if the Md5 hash satisfies the required conditions"""
# Check if MD5 hash starts with 5 zeroes
if md5_hash.find('00000') == 0:
return True
return False |
def get_hidden_state(cell_state):
""" Get the hidden state needed in cell state which is
possibly returned by LSTMCell, GRUCell, RNNCell or MultiRNNCell.
Args:
cell_state: a structure of cell state
Returns:
hidden_state: A Tensor
"""
if type(cell_state) is tuple:
cell_state = cell_stat... |
def _get_sentences_with_word_count(sentences, words):
""" Given a list of sentences, returns a list of sentences with a
total word count similar to the word count provided.
"""
word_count = 0
selected_sentences = []
# Loops until the word count is reached.
for sentence in sentences:
... |
def demo(x, y) -> bool:
"""
Demo function which prints output to console
"""
product = x * y
if product < 10:
return product * 2
else:
return product |
def kappa_no_prevalence_calc(overall_accuracy):
"""
Calculate Kappa no prevalence.
:param overall_accuracy: overall accuracy
:type overall_accuracy: float
:return: Kappa no prevalence as float
"""
try:
result = 2 * overall_accuracy - 1
return result
except Exception:
... |
def from_pairs(pairs):
"""
Implementation of ramda from_pairs Converts a list of pairs or tuples of pairs to a dict
:param pairs:
:return:
"""
return {k: v for k, v in pairs} |
def factory_test_account(is_model=False):
"""JSON data to create TestAccount."""
test_accounts = {
'testAccounts': 'SS4BPS201,98901,ONE,SS4BPS Felecia,F,4732 Easy Street,,V9B 3V9,1998-04-30\nSS4BPS999,' +
('98989' if is_model else '') +
',TWO,SS4BPS Benjamin,M,308-2464 Crimson Vale,Penti... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.