content stringlengths 42 6.51k |
|---|
def member_header_bytestring(dataset_bytestring):
"""
First 5 lines of the member dataset, plus namestrs and a final line.
"""
index = 80 * 5 + 140 * 4 + 80 * 1
return dataset_bytestring[:index] |
def wiki(title):
"""Takes a title and wraps it to form a https://en.wikipedia.org URL
Arguments:
title {str} -- Title of Wikipedia Article
Returns:
{str} -- URL on wikipedia
"""
return f"https://en.wikipedia.org/wiki/{title}" |
def calc_speed(u, v):
"""Calculate the speed"""
speed = (u**2 + v**2)**0.5
return speed |
def f2b_marked(s):
"""
fail2ban responds to connection overload by replying with ICMP type 3 "unreachable"
if this exists in the connection, we'll presume that this host was flooding
"""
if 'icmp' in s:
return True
return False |
def build_param_bul (param):
""" Builds a configuration parameter documentation bullet from a parameter tuple.
Args:
param (tuple): The parameter tuple.
Returns:
string: The documentation bullet markdown.
"""
return param[0] + ' (' + param[1] + '): ' + param[2] |
def round_to_period(current_time, period_min, direction='floor', offset=0):
"""
Args:
current_time ([type]): [description]
period_min ([type]): [description]
direction (str, optional): [floor|ceiling]. Defaults to 'floor'.
offset (int, optional): [description]. Defaults to 0.
... |
def encode_function_data(*args, initializer=None):
"""Encodes the function call so we can work with an initializer.
Args:
initializer ([brownie.network.contract.ContractTx], optional):
The initializer function we want to call. Example: `box.store`.
Defaults to None.
args (A... |
def check(number: int) -> bool:
"""
Takes a number and checks if it is pandigital both from start and end
>>> check(123456789987654321)
True
>>> check(120000987654321)
False
>>> check(1234567895765677987654321)
True
"""
check_last = [0] * 11
check_front = [0] * 11
... |
def point_on_image(x: int, y: int, image_shape: tuple):
"""
Returns true is x and y are on the image
"""
return 0 <= y < image_shape[0] and 0 <= x < image_shape[1] |
def chunks(l, n, o):
"""
Yield successive n-sized chunks with o-sized overlap from l.
"""
return [l[i: i + n] for i in range(0, len(l), n-o)] |
def count_species(list_of_labels):
"""From the list of labels creates a dictionary where the keys represents labels and
values are numbers of their repetitions in the list
Parameters
----------
list_of_labels :
return:
Returns
-------
"""
counter = {}
for item in list... |
def pad(data, limit):
"""Pad a given string `data` by spaces to length `limit`."""
if len(data) > limit:
raise Exception(
f"length of string {data} is higher than your requested limit, {limit}"
)
return data + (limit - len(data)) * " " |
def should_be_zipped(input_file, input_files):
"""
Determine whether a given input file should be included in the zip.
Compiler includes and target files should only be included if there is
no compiler info file present.
"""
return (input_file in ['metadata.json', 'compiler_info.json']
... |
def validate_location(msg_payload, config):
"""
Validates that the latitude and longitude values for a query result is within the requested
bounding box region. .
:return:
"""
service_region = config['SERVICE_REGION']
if float(service_region['seLat']) <= float(msg_payload['latitude']) <= f... |
def L50_indicator(row):
"""
Detemine the Indicator of L50 as one of five indicators
"""
if row < 35:
return "Excellent"
elif row < 45:
return "Good"
elif row < 5:
return "Fair"
elif row <= 82:
return "Poor"
else:
return "Hazard" |
def find_postprocess_fields(parameter, value):
"""Find the fields that need to be postprocessed for a given parameter."""
if type(parameter) is bool:
return value if parameter else []
else:
return parameter |
def example_func(param1, param2):
"""
demodemodemo
:param param1:
:param param2:
:return:
"""
print(param1)
print(param2)
return True |
def list_multiply(a, b):
""" Sums two lists of integers and multiplies them together
>>> list_multiply([3,4],[3,4])
49
>>> list_multiply([1,2,3,4],[10,20])
300
"""
return sum(a) * sum(b) |
def as_complex(dct):
"""JSON decoder for complex numbers."""
if "__complex__" in dct:
return complex(dct["__complex__"][0], dct["__complex__"][1])
return dct |
def slice_geo_data(ld):
"""given a list of raw record dictionaries, pull out geo data,
and convert to floats
"""
float_fields = ["latitude","longitude"]
result = []
for rec in ld:
newr = {}
for field in float_fields:
newr[field] = float(rec[field])
result.app... |
def c_binary_string(n, numBits=32):
"""Return `n` as a clean 32-bit/64-bit binary number, without a leading '0b'.
Usage: c_binary_string(n [,numBits])->binary_string
Parameters
----------
n : positive or negative integer
numBits (optional) : 32 or 64 indicating the string length.
Returns
... |
def ref_clock_source(session, Type='Int32', RepCap='', AttrID=1250002, buffsize=0, action=['Get', '']):
"""The source of the reference clock.
The function generator derives frequencies and sample rates that it uses to generate waveforms from the reference clock.
The allowable sources are PXI backplane, Ex... |
def column_names(wide):
"""
"""
if wide is True:
return ['Summary Level', 'Geographic Component', 'State FIPS', 'Place FIPS', 'County FIPS', 'Tract', 'Zip', 'Block', 'Name', 'Latitude', 'Longitude', 'Land Area', 'Water Area', 'Population', 'Housing Units']
elif wide is False:
return ['St... |
def durationString(start, end):
"""Returns a relative time based on stop-start (duration) time."""
seconds = end-start # first math.
seconds = (round(seconds))
minutes, seconds = divmod(seconds, 60)
hours, minutes = divmod(minutes, 60)
days, hours = divmod(hours, 24)
minutes = (minutes)
hours = (hours)
days ... |
def high_and_low(nums):
"""Return highest and lowest nums separated by space as a string."""
new = [int(x) for x in nums.split()]
return str(max(new)) + ' ' + str(min(new)) |
def get_attackId(data, aId):
"""
returns the Attack record and Damage record given an attack id
:param data: data to scan.
:param aId: Attack id to look for
:return: pair [AttackRecord, DamageRecord]
"""
dr = None
ar = None
for t in data:
if 'attackId' in t and t['attackId']... |
def dict_values(d):
"""In python 3, the ``d.values()`` method
returns a view and not an actual list.
Parameters
----------
d : dict
The dictionary
Returns
-------
list
"""
return list(d.values()) |
def getNamespace(modelName):
"""Get the name space from rig root
Args:
modelName (str): Rig top node name
Returns:
str: Namespace
"""
if not modelName:
return ""
if len(modelName.split(":")) >= 2:
nameSpace = ":".join(modelName.split(":")[:-1])
else:
... |
def chunk(l, chunk_size):
"""Splits the given list into chunks of size chunk_size. The last chunk will eventually be smaller than chunk_size."""
result = []
for i in range(0, len(l), chunk_size):
result.append(l[i:i + chunk_size])
return result |
def overlap(a, b, x, y, inc=True):
"""
Returns True if range [a,b] overlaps [x,y]
inc: if True, treat [a,b] and [x,y] as inclusive
"""
if inc:
return (y >= a) and (x <= b)
else:
return (y > a) and (x < b) |
def hms_string(sec_elapsed):
"""
Returns the formatted time
Parameters:
-----------
sec_elapsed: int
second elapsed
Return:
--------
str
the formatted time
"""
h = int(sec_elapsed / (60 * 60))
m = int((sec_elapsed % (60 * 60)) / 60)
s = sec_elapsed % 6... |
def get_use_env(args) -> bool:
"""
Retrieves ``use_env`` from the args.
``use_env`` is a legacy argument, if ``use_env`` is False, the
``--node_rank`` argument will be transferred to all worker processes.
``use_env`` is only used by the ``torch.distributed.launch`` and will
be deprecated i... |
def patch_stanza(struc, diff):
"""Applies the diff stanza ``diff`` to the structure ``struc`` as
a patch.
Note that this function modifies ``struc`` in-place into the target
of ``diff``. If ``struc`` is a tuple, you get a new tuple with the
appropriate modification made:
>>> patch_stanza((17,... |
def rgb2(r, g, b):
"""
>>> rgb(0,0,0)
'000000'
>>> rgb(1,2,3)
'010203'
>>> rgb(255,255,255)
'FFFFFF'
>>> rgb(254,253,252)
'FEFDFC'
>>> rgb(-20,275,125)
'00FF7D'
:param r:
:param g:
:param b:
:return:
"""
r, g, b = [min(255, max... |
def create_plain_text_with_doc(name, label, doc_link):
"""
Create a plain text field with links for the settings.
Args:
(String) name - unique name for switch.
(String) label - Display text.
(Dict) doc_link - documentation props.
Returns:
[Dict] - plain text with links ... |
def get_nodes_by_public_key(nodes):
"""Get nodes by public key as a dictionary"""
return {node['publicKey']: node for node in nodes} |
def sortScore(modelScore):
"""
param1: Dictionary
return: Dictionary
Function return a sorted dictionary on the basis of values.
"""
return dict(sorted(modelScore.items(), key=lambda item: item[1],reverse=True)) |
def tamper(payload, **kwargs):
"""
Appends (Access) NULL byte character (%00) at the end of payload
Requirement:
* Microsoft Access
Notes:
* Useful to bypass weak web application firewalls when the back-end
database management system is Microsoft Access - further uses are
... |
def is_weekend(x):
"""
Returns whether it is a weekend or not
"""
if (x==5 or x==6) :
weekend = 1
else:
weekend = 0
return weekend |
def extract_stack(f=None, limit=0):
"""Extract the raw traceback from the current stack frame. The return value has
the same format as for :func:`extract_tb`. The optional *f* and *limit*
arguments have the same meaning as for :func:`print_stack`."""
return [('make_mock.py', 211, '<module>', 'gl... |
def shunt(infix):
"""Return the infix regular expression in postfix."""
# Convert input to stack-like list
infix = list(infix)[::-1] # reverse order of list
operators = [] # Operator stack
postfix = [] # Postfix regular expression
# Operator precedence
precedence = {'*': 100, '+': 90, '... |
def _count_leading(line, ch):
"""
Return number of `ch` characters at the start of `line`.
Example:
>>> _count_leading(' abc', ' ')
3
"""
i, n = 0, len(line)
while i < n and line[i] == ch:
i += 1
return i |
def parse_list_option(opt):
"""Parse options as list.
Strings are split based on comma separated elements.
Result is sorted.
>>> parse_list_option('')
[]
>>> parse_list_option('opt1,opt2,opt3')
['opt1', 'opt2', 'opt3']
>>> parse_list_option(['opt1','opt3','opt2'])
['opt1', 'opt2', ... |
def fixed_or_variable(all_mods, aa_freq):
"""Assigns special symbols to variable mods. None assigned to fixed mods."""
# define some symbols and such
reg_symbols = ['*', '#', '@', '^', '~', '$', '%', '!', '+'] # as of last Comet iteration (first 6 match SEQUEST)
nt_symbols = [']', ')', '}'] # ol... |
def horspool_P(text, pattern):
"""Function that implement the Boyer Moore Horspool algorithm for exact string
matching. It has two inputs, the characters chain and the pattern """
m = len(pattern)
n = len(text)
ocurr = 0
shift = {}
for i in range(m):
shift[pattern[i]] = m
for... |
def forgot(command):
""" Check if command is to reset password (f | forgot). """
return (command.lower() == 'f' or command.lower() == 'forgot') |
def degree_to_DMS(degree):
"""Convert from plain degrees format to DMS format of geolocalization.
DMS: "Degrees, Minutes, Seconds" is a format for coordinates at the surface
of earth. Decimal Degrees = degrees + (minutes/60) + (seconds/3600)
This measure permit to gain in precision when a degree... |
def _dynamic_outputs_creation(dynamic_io_settings):
"""Creates a list of outputs names, supplied to the Task class."""
parameters = dynamic_io_settings["TaskSettings"]["Parameters"]
return ["TopicData({},{})".format(*parameters.values())] |
def count(lines, bit_pos, keep_equal):
"""
if keep_equal = "1", then return the most number of bits
otherwise return the fewest number of bits
"""
count_bits = 0
for line in lines:
if line[bit_pos] == keep_equal:
count_bits += 1
if keep_equal == "0":
# Return few... |
def get_speed_model_indices(reduced_tile):
""" Extracts the speed model indices for the data structure """
speed_model_indices = set()
for site in reduced_tile['sites']:
for site_pin in site['site_pins'].keys():
if site['site_pins'][site_pin] is None:
continue
... |
def parse_env_urls(urls=None):
"""Parses a list of urls
>>> parse_env_urls(urls='https://kibana.energy.svc.dbg.com | https://grafana.energy.svc.dbg.com')
['https://kibana.energy.svc.dbg.com', 'https://grafana.energy.svc.dbg.com']
"""
urls_list = [] if urls == None else urls.split('|')
urls_... |
def get_units_type(channel):
"""
Determines the units type ('acc' or 'vel') based on the three-character
channel code. The units type indicates whether the instrument natively
measures acceleration or velocity.
"""
if channel[1] == 'N':
return 'acc'
else:
return 'vel' |
def _plugged_in_supported(data):
"""Determine if 'plugged in' binary sensor is supported."""
return (
data["isElectric"] and data["evStatus"]["chargeInfo"]["pluggedIn"] is not None
) |
def get_width_and_height_from_size(x):
"""Obtain height and width from x.
Args:
x (int, tuple or list): Data size.
Returns:
size: A tuple or list (H,W).
"""
if isinstance(x, int):
return x, x
if isinstance(x, list) or isinstance(x, tuple):
return x
else:
... |
def validate_dates_list(recv_dates_list):
"""Element in the list must be able to become an integer in range(1,32)"""
for i in recv_dates_list:
try:
tmp = int(i)
if tmp < 0:
return False
except ValueError as e:
return False
return True |
def rreplace(string, old, new, count):
"""Replace old with new in a string in reverse order.
Args:
string: String to modify
old: Sub-string to replace
new: Sub-string to replace old
count: The number old sub-strings to be replaced"""
li = string.rsplit(old, count)
return ... |
def edit_distance(s1, s2):
"""
Levenshtein distance
Complexity: O(len(s1)*len(s2))
"""
n = len(s1)
m = len(s2)
dp = [[0] * (m+1) for _ in range(n+1)]
for j in range(1, m):
dp[0][j] = j
for i in range(1, n):
dp[i][0] = i
for i in range(1, n+1):
for j in r... |
def fragment_4(N):
"""Fragment-4 for exercise."""
ct = 0
while N > 1:
ct += 1
N = N // 2
return ct |
def get_mwis(input_tree):
"""Get minimum weight independent set
"""
num_nodes = input_tree['num_nodes']
nodes = input_tree['nodes']
if num_nodes <= 0:
return []
weights = [0, nodes[0][0]]
for idx, node_pair in enumerate(nodes[1:], start=1):
node_weight, node_idx = node_pair
... |
def findHighPoints(elevations):
"""
6
5
1 1 1 1 1
1 2 2 2 1
1 2 3 2 1
1 2 2 2 1
1 1 1 1 1
1 1 1 1 3
:param elevations:
:return:
"""
# Write your code here
num_rows = len(elevations)
num_cols = len(elevations[0])
truth_array = [[True for c in range(num_cols)] for r in ra... |
def vdiv(v, a):
"""Divide a vector by a scalar."""
try:
return tuple(i / a for i in v)
except TypeError:
return v / a |
def hook_force(eps, sig, rr):
"""
eps = Q1 (charge of particle 1)
sig = Q2 (charge of particle 2)
rr = distance between particles
"""
return eps*(rr-sig) |
def build_profile(first, last, **user_info):
"""Build a dictionary containing everything we know about a user."""
profile = {}
profile['first name'], profile['last name'] = first, last
for key, value in user_info.items():
profile[key] = value
return profile |
def r_vis_b(t_vis):
"""The visible light reflectance for the back surface.
Args:
t_vis: The visible transmittance
Returns:
double: The visible light reflectance for the back surface
"""
return -0.7409 * t_vis ** 3 + 1.6531 * t_vis ** 2 - 1.2299 * t_vis + 0.4547 |
def unk_counter(sentence, vocab_to_int):
"""Counts the number of time UNK appears in a sentence."""
unk_count = 0
for word in sentence:
if word == vocab_to_int["<UNK>"]:
unk_count += 1
return unk_count |
def store(alist):
"""increment counter in a counter array for every integer encountered"""
klist = [0] * (max(alist)+1) #O(n)
#O(n)
for i in alist:
klist[i] += 1
return klist |
def cubes_intersect(a, b):
"""
Find if two cubes intersect w/ each other
:param a: cube a, tuple of min, max tuple of coords
:param b: cube a, tuple of min, max tuple of coords
:return: bool, if cubes intersect
"""
for i, j, k, l in zip(a[0], a[1], b[0], b[1]):
if i >= l or k >= j:
... |
def INK(n):
"""
Returns control codes to set the ink colour (0-7).
Use this in a ``PRINT`` or ``SET`` command. Example:
``PRINT("normal",INK(1),"blue",INK(2),"red")``
Args:
- n - integer - the ink colour (0-7)
"""
return "".join((chr(16),chr(int(n)))) |
def prod(X):
"""
Return the product of elements in X
:param X:
:return:
"""
y = 1
for x in X:
y *= x
return y |
def int_or_none(x, limit):
"""Returns `int(x)` if `x` is a valid `int` or `None` otherwise.
`x` is valid if `1 <= x <= limit`.
"""
try:
value = int(x)
if 1 <= value <= limit:
return value
else:
return None
except ValueError:
return None |
def is_str(s):
"""Return True for native strings (for str on Py2 and Py3)."""
return isinstance(s, str) |
def mid(s, offset, amount):
"""
Returns the middle characters starting at offset of length amount
"""
return s[offset:offset + amount] |
def replicaset_votes(config_document):
"""
Return the number of votes in the replicaset
"""
votes = 0
for member in config_document["config"]['members']:
votes += member['votes']
return votes |
def _add_cache_age_max(coverage, cache_age_max):
"""Add maximum cache age parameter to HTTP responses."""
if cache_age_max is None:
return coverage
metadata = coverage.metadata.copy()
metadata["cacheAgeMax"] = str(cache_age_max)
metadata["cachingEnabled"] = "true"
coverage.metadata = met... |
def arabic_to_roman(number=None):
"""Converts an arabic number to a Roman numeral."""
conv = [[1000, "M"], [900, "CM"], [500, "D"], [400, "CD"],
[ 100, "C"], [ 90, "XC"], [ 50, "L"], [ 40, "XL"],
[ 10, "X"], [ 9, "IX"], [ 5, "V"], [ 4, "IV"],
[ 1, "I"]]
if number i... |
def version_to_tuple(version):
"""Removes preview suffix"""
if version.endswith('(preview)'):
version = version[:-len('(preview)')]
return tuple(map(int, (version.split('.')))) |
def aneuploidy_code_for_chr_count(chr_count):
""" Output a letter code based on chromosome copy number (0,1,2,3,4)"""
return {0: 'N',
1: 'U',
2: 'B',
3: 'U',
4: 'N'}[chr_count] |
def compute_average_metrics(meters):
"""
Compute averages from meters. Handle tensors vs floats (always return a
float)
Parameters
----------
meters : Dict[str, util.AverageMeter]
Dict of average meters, whose averages may be of type ``float`` or ``torch.Tensor``
Returns
------... |
def flatten_list(nested_list, list_types=(list, tuple), return_type=list):
"""Flatten `nested_list`.
All the nested lists in `nested_list` will be flatten, and the elements
in all these lists will be gathered together into one new list.
Parameters
----------
nested_list : list | tuple
... |
def readShimadzuSection(section):
""" the chromtographic data section starts with a header
followed by 2-column data
the input is a collection of strings
"""
xdata = []
ydata = []
for line in section:
tt = line.split()
if len(tt)==2:
try:
x... |
def handle_url(e, key):
""" Handle a public:hostURL field. """
url, useProxy = "", ""
if key in e:
url = e[key]["public:url"]
useProxy = str(e[key]["public:useProxy"])
return url, useProxy |
def sorted_dict(a_dict):
"""Simple helper for sorting dictionaries."""
return dict(
sorted(a_dict.items()),
) |
def find_tag(tag_list, method, priority_labels=[], worker_indices=[]):
""" given a list of tags, return the appropriate one for the selection method """
if method == 'first':
# remove ? tags
tag_list = [x for x in tag_list if x != '?']
return tag_list[0]
elif method == 'last':
... |
def quaternion_to_rotation_matrix(q):
"""Return a 3x3 rotation matrix representing the orientation specified by a quaternion in x,y,z,w format.
The matrix is a Python list of lists.
"""
x = q[0]
y = q[1]
z = q[2]
w = q[3]
return [[ w*w + x*x - y*y - z*z, 2*(x*y - w*z), ... |
def new_guess(guess, bad):
"""
Given the original guess and the bad door, return the alternative
"""
if bad==1:
return 3 if guess==2 else 2
if bad==2:
return 1 if guess==3 else 3
if bad==3:
return 2 if guess==1 else 1 |
def split_dataset(dataset, ratio):
"""Shuffle and split a dataset."""
# np.random.seed(111) # fix the seed for shuffle.
#np.random.shuffle(dataset)
n = int(ratio * len(dataset))
return dataset[:n], dataset[n:] |
def numbers_letters_count(my_str):
"""
:param my_str:
:return: Counter list of digits and alphabetic characters in the string
"""
counter_list = [0, 0]
for char in my_str:
if str(char).isdigit():
counter_list[0] += 1
else:
counter_list[1] += 1
return c... |
def get_music_url(array):
"""
get music url from list
:param array:
:return:
"""
if isinstance(array, list) and len(array) >= 1:
return array[-1]
return None |
def fibonacciList(n):
"""
:return: Return Fibonacci List Upto N Number by Reursion
"""
if n <= 1:
return n
else:
return fibonacciList(n - 1) + fibonacciList(n - 2) |
def caught(try_function, *args):
"""
Tries a function and checks if it throws an exception.
:param Callable try_function: callable object representing the function that must be tried
:param list args: arguments to pass to the callable function
:rtype: bool
:return: True if an exception was cau... |
def gcd(a, b):
"""Calculate the Greatest Common Divisor of a and b.
Unless b==0, the result will have the same sign as b (so that when
b is divided by it, the result comes out positive).
"""
while b:
a, b = b, a % b
return a |
def sql_render(hpo_id, cdm_schema, results_schema, vocab_schema, sql_text):
"""
Replace template parameters
:param hpo_id: will be the source name in Achilles report
:param cdm_schema: schema of the cdm
:param results_schema: schema of the results tables
:param vocab_schema: schema of the vocabu... |
def _round_down(num, divisor):
"""
Ex:
in : _round_down(19,10)
out: 10
"""
return num - (num % divisor) |
def split_skills(skills_list, char='-'):
"""
Splits each skill in skills_list on char
"""
clean_skills_list = []
for s in skills_list:
clean_skills_list.extend(s.split('/'))
return clean_skills_list |
def from_json_string(s, object_hook):
"""
Given the string as json, loads it into a nested dictionary and passes it into the object_ctor
provided to yield an instance of the object
:param s: A json formatted string
:param object_hook: A function that takes a dictionary and yields a new object instan... |
def validate_params(params):
"""Validate parameters passed to this Ansible module.
When ``rf_profile_name`` is passed, we need to lookup the ID as that's what
the API expects. To look up the RF Profile ID, we need the network ID,
which might be derived based on the network name, in which case we need ... |
def fibonacci_without_dynamic(number) -> int:
"""
This function calculate in recursive mode the value of the required position.
E.g.: position 10 result 55
E.g.: position 35 result 9227465
Parameters:
int number
Returns:
int
"""
if type(number) != int or number < 0:
... |
def format_cmd_name(python_name):
"""Convert module name (with ``_``) to command name (with ``-``)."""
return python_name.replace('_', '-') |
def get_indexable_filter_columns(predicate):
"""
Returns all of the columns in a filter which the operation benefits
from an index
This creates an list of tuples of (field,value) that we can feed to the
index search.
"""
INDEXABLE_OPS = {"=", "==", "is", "in", "contains"}
if predicate i... |
def commands_match(user_command, expected_command):
"""
Checks if the commands are essentially equivalent after whitespace
differences and quote differences.
Returns:
match: boolean
True if the commands appear to be equivalent.
"""
def normalize(command):
return comman... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.