content stringlengths 42 6.51k |
|---|
def get_matching(content, match):
""" filters out lines that don't include match """
if match != "":
lines = [line for line in content.split("\n") if match in line]
content = "\n".join(lines)
return content |
def ms_payload_2(payload):
""" Receives the input given by the user from create_payloadS.py """
return {
'1': "shellcode/pyinject",
'2': "shellcode/multipyinject",
'3': "set/reverse_shell",
'4': "set/reverse_shell",
'5': "set/reverse_shell",
'6': "shellcode/alpha... |
def largestPermutation(k:int, arr:list):
"""
"""
sorted_arr = sorted(arr, reverse = True)
index_dict = {v:i for i, v in enumerate(arr)}
counter = 0
if k==0:
print(arr)
else:
for i,v in enumerate(arr):
largest_value = sorted_arr[i]
lg_idx = index_d... |
def get_dims(board) -> tuple:
"""Returns the (y, x) dimensions of a matrix"""
return len(board), len(board[0]) |
def searchRange(nums, target):
"""Find first and last position."""
def midpoint(x, y):
"""Find mid point."""
return x + (y - x) // 2
lo, hi = 0, len(nums)-1
_max = -1
_min = float('inf')
while lo <= hi:
mid = midpoint(lo, hi)
if nums[mid] == target:
... |
def dice_coefficient2(a, b, case_insens=True):
"""
:type a: str
:type b: str
:type case_insens: bool
duplicate bigrams in a word should be counted distinctly
(per discussion), otherwise 'AA' and 'AAAA' would have a
dice coefficient of 1...
https://en.wikibooks.org/wiki/Algorithm_Implemen... |
def is_palindrome_permutation(value):
"""
195. Palindrome Permutation: Given a string, write a function to check if it is a permutation of a palindrome.
"""
length = len(value)
records = []
for i in range(ord('a'), ord('z') + 1):
records.append(0)
# Flip and unflip the values from 0... |
def is_odd(n):
"""
check if number n is odd
:param n:
:return: if is odd return True, otherwise return False
"""
if n % 2:
return False # odd
else:
return True |
def init_result_info(doi, path, defaults=None):
"""Initialise result info."""
info = defaults or {}
info['analysis_complete'] = True
info['analysis_doi'] = doi
info['analysis_path'] = path
return info |
def _split_dict(in_dict, key_names, nullable_fields=frozenset()):
"""
Split a dict into two dicts. Keys in key_names go into the new dict if
their value is present and not None, allowing for None values if the key
name is present in the nullable_fields set.
return (updated original dict, new dict)
... |
def sumOfAbs(array, cutoff):
"""Return sum of absolute values above a cutoff.
:param array:
:type array: :class:`collections.abc.Iterable`
:param cutoff:
:type cutoff: :py:class:`float`
:return: value
:rtype: :py:class:`float`
"""
return sum(abs(value) for value in array if abs(val... |
def add_fmt(nfields, doc):
"""
Function used to define the table's format depending on config.bench
file.
"""
if doc:
tmp = '|lrcr|r|rrrr|rrr|rr|'
for i in range(0, nfields):
tmp += 'rrr|rrrr|'
return tmp
else:
tmp = '|c|c|'
for i in ra... |
def basename(path):
"""
Gets the last component of a path.
Arguments:
path -- File path.
"""
return path.replace("\\", "/").split("/")[-1] |
def get_nestted_dict_value(nested_dict, path_list):
"""
FEtch the value from a dictionary provided the path as list of strings
and indecies
Parameters
----------
nested_dict : dict
path_list : list
list of list of strings and/or indecies
Returns
-------
value : any ty... |
def _lcs(string, sub):
"""
Computes longest common subsequence (LCS) for a pair of tokenized strings
:param string : list of str : tokens from a string split using whitespace
:param sub : list of str : shorter string, also split using whitespace
:returns: length (list of int): length of the LCS betw... |
def first_line(text):
"""Return only the first line of a potential multi-line text"""
return text.split("\n")[0].split("\r")[0] |
def rec_replace(l, d):
""" Recursively replace list l with values of dictionary d
ARGUMENTS:
l - list or list of lists
d - dictionary where if an element in l matches d['key'], it is replaced by the value
OUTPUT:
l - list with elements updated
"""
... |
def clean_data(lst):
"""
Removes artificial NaNs and noisy cells -
Noisy cell contains only special chars.
"""
empty = ['nan', 'NaN']
res = []
for cell in lst:
if str(cell) in empty:
cell = ""
else:
alphaNum = ''.join(e for e in str(cell) if e.isalnum(... |
def to_usd(my_price):
"""
converts a numeric value to usd-formatted string, for printing and display purposes
"""
return "${0:,.2f}".format(my_price) |
def fine_dining_validation(fine_dining):
""" Decide if the cuisine input is valid.
Parameters:
(str): A user's input to the cuisine factor.
Return:
(str): A single valid string, such as "1", "0" or "-5" and so on.
"""
while fine_dining != "5" and fine_dining... |
def get_nested_expression(shifts):
"""Returns a string representing the addition of all the input bitvectors.
Args:
shifts: An integer, the number of nested shift operations.
"""
nested_expressions = []
for i in range(shifts):
rhs = "x_0" if i == 0 else nested_expressions[i - 1]
expression = ["(b... |
def print_hi(name):
"""
:param name: the to say hi
:return: None
"""
# Use a breakpoint in the code line below to debug your script.
return f"Hi, {name}" |
def sense(location, states, moves):
"""
Sense the environment.
:param location: current location
:param states: possible states
:param moves: possible moves
:return: sensor output
"""
ideal = [1] * len(moves)
for index, move in enumerate(moves):
if move(location) in states:
... |
def callback(indata, outdata, frames, time, status):
"""
This function obtains audio data from the input channels.
"""
if status:
print(status)
return indata |
def set_dict_indices(my_array):
"""Creates a dictionary based on values in my_array, and links each of them to an index.
Parameters
----------
my_array:
An array (e.g. [a,b,c])
Returns
-------
my_dict:
A dictionary (e.g. {a:0, b:1, c:2})
"""
my_dict = {}
i = 0
... |
def format_error(msg, row=None, col=None, line=None):
"""
Format the error for human consumption.
"""
if row is None or col is None or line is None:
return 'error: {0}'.format(msg)
else:
return 'error: {0} at column {1} on line {2}:\n{3}{4}\n{5}^'.format(msg,
col, row, ' ' * 2, line, ' ' * (col + 1)) |
def is_vlan_bitmap_empty(bitmap):
"""check VLAN bitmap empty"""
if not bitmap or len(bitmap) == 0:
return True
for bit in bitmap:
if bit != '0':
return False
return True |
def lcm(x, y):
"""This function takes two
integers and returns the L.C.M."""
# choose the greater number
if x > y:
greater = x
else:
greater = y
while(True):
if((greater % x == 0) and (greater % y == 0)):
lcm = greater
break
greater +... |
def MD5_f1(b, c, d):
""" First ternary bitwise operation."""
return ((b & c) | ((~b) & d)) & 0xFFFFFFFF |
def strip_space(x):
""" Strip extra spaces """
return " ".join([s.strip() for s in x.split()]) |
def _standardize_county_name(zipcounty):
"""
Standardize county name to match with our 'San Francisco' like formatting.
Takes a zipcounty dict and updates 'countyName' key if exists.
"""
if 'countyName' in zipcounty.keys():
countyname = zipcounty['countyName'].lower()
county_list = ... |
def _write(fp, lines):
"""
Write a collection of lines to given file.
:param str fp: path to file to write
:param Iterable[str] lines: collection of lines to write
:return str: path to file written
"""
with open(fp, 'w') as f:
for l in lines:
f.write(l)
return fp |
def floor(x):
"""Implementation of `floor`."""
return x.__floor__() |
def get_H_O_index_list(atoms):
"""Returns two lists with the indices of hydrogen and oxygen atoms.
"""
H_list = O_list = []
for index, atom in enumerate(atoms):
if atom[0] == 'H':
H_list.append(index)
if atom[0] == 'O':
O_list.append(index)
return H_list, O_li... |
def normalize_text(text, lower=True):
"""
Normalizes a string.
The string is lowercased and all non-alphanumeric characters are removed.
>>> normalize_text("already normalized")
'already normalized'
>>> normalize_text("This is a fancy title / with subtitle ")
'this is a fancy title with sub... |
def try_get_value(obj, name, default):
"""
Try to get a value that may not exist.
If `obj.name` doesn't have a value, `default` is returned.
"""
try:
return getattr(obj, name)
except LookupError:
return default |
def _get_query_parameters(module_params):
"""Builds query parameter.
:return: dict
:example: {"$filter": Name eq 'template name'}
"""
system_query_param = module_params.get("system_query_options")
query_param = {}
if system_query_param:
query_param = dict([("$" + k, v) for k, v in s... |
def get_top_k_from_counts(n, counts):
"""
Given a map of counts mapping from a key to its frequency, returns the top k keys (based on frequency) after
normalizing the frequencies by the total.
:param n: The number of keys to return
:param counts: A map of counts mapping from a key to its frequency.
... |
def calculate_recursive_fuel(fuel_mass):
"""Calculate the recursive fuel needed to launch a mass of fuel."""
new_fuel_mass = fuel_mass // 3 - 2
if new_fuel_mass <= 0:
return 0
return new_fuel_mass + calculate_recursive_fuel(new_fuel_mass) |
def serialize_classifier_output(analysis, type):
"""."""
return {
'id': None,
'type': type,
'attributes': {
'url': analysis.get('url', None)
}
} |
def strip_str_arr(str_arr):
"""
strips a str_arr, remove \n and spaces
"""
res = []
for string in str_arr:
temp = string.rstrip().strip()
if not temp:
continue
res.append(temp)
return res |
def params(css, encoding, use_bom=False, expect_error=False, **kwargs):
"""Nicer syntax to make a tuple."""
return css, encoding, use_bom, expect_error, kwargs |
def start_quote(text):
"""Check for text starting quote"""
return text.startswith("'") or text.startswith('"') |
def get_name(header, splitchar = "_", items = 2):
"""use own function vs. import from match_contigs_to_probes - we don't want lowercase"""
if splitchar:
return "_".join(header.split(splitchar)[:items]).lstrip('>')
else:
return header.lstrip('>') |
def tag2ts(ts_tag_sequence):
"""
transform ts tag sequence to targeted sentiment
:param ts_tag_sequence: tag sequence for ts task
:return:
"""
n_tags = len(ts_tag_sequence)
ts_sequence, sentiments = [], []
beg, end = -1, -1
for i in range(n_tags):
ts_tag = ts_tag_sequence[i]
... |
def find_first(dictionary, condition):
""" utility for finding the first occurrence of a passing condition for a key and value pair in a dict """
for key, value in dictionary.items():
if condition(key, value):
return key, value
return None |
def dicts_are_consistent(d1: dict, d2: dict) -> bool:
"""
checks if all items whose keys are in (d1 and d2) are equal.
returns bool.
"""
return all(d1[k] == d2[k] for k in set(d1).intersection(set(d2))) |
def build_class(names):
""" Format ZLabels class file.
>>> names = ['Label.AColleague', 'Label.ZipPostalCode']
>>> output = build_class(names)
>>> print output
@isTest
private class ZLabels {
private static List<String> labels = new List<String> {
Label.AColleague,
... |
def fibonacci(n):
"""Return the nth fibonacci number.
>>> fibonacci(11)
89
>>> fibonacci(5)
5
>>> fibonacci(0)
0
>>> fibonacci(1)
1
"""
"*** YOUR CODE HERE ***"
if n is 1:
return 1
elif n is 0:
return 0
else:
return fibonacci(n - 1) + fibo... |
def grid_garden_hatch_time(grid_garden):
"""
Returns the minimum time in seconds, for a grid garden to
to have all its larvae hatched into butterflies.
Parameters:
grid_garden (list): A 2d list
Returns:
seconds (int): Time in seconds
Convention: '0' denotes emp... |
def process_properties(content, sep=': ', comment_char='#'):
"""
Read the file passed as parameter as a properties file.
"""
props = {}
for line in content.split("\n"):
sline = line.strip()
if sline and not sline.startswith(comment_char):
key_value = sline.split(sep)
key = key_value[0].str... |
def strip_biosphere_exc_locations(db):
"""Biosphere flows don't have locations - if any are included they can confuse linking"""
for ds in db:
for exc in ds.get('exchanges', []):
if exc.get('type') == 'biosphere' and 'location' in exc:
del exc['location']
return db |
def testif(b, testname, msgOK="", msgFailed=""):
"""Function used for testing.
param b: boolean, normally a tested condition: true if test passed, false otherwise
param testname: the test name
param msgOK: string to be printed if param b==True ( test condition true)
param msgFailed: string to be pr... |
def a2idx(j, n=None):
"""Return integer after making positive and validating against n."""
if type(j) is not int:
jindex = getattr(j, '__index__', None)
if jindex is not None:
j = jindex()
else:
raise IndexError("Invalid index a[%r]" % (j,))
if n is not None:
... |
def is_next_east_cell_empty(i, j, field):
"""
check if next to the right cell is empty
:param i:
:param j:
:param field:
:return: True if next right cell of the field is empty, False otherwise
"""
if j == len(field[0]) - 1:
if field[i][0] == '.':
return True
r... |
def tuple_map(f, a, b):
"""Zip + Map for tuples
Args:
f (function): The function to apply
a (tuple): The first tuple
b (tuple): The second tuple
Returns:
[type]: [description]
"""
return tuple([f(x) for x in zip(a, b)]) |
def create_new_tarball_name(platform, program, version):
""" Converts the name of a platform as specified to the prepare_release
framework to an archive name according to BLAST release naming conventions.
Note: the platform names come from the prepare_release script conventions,
more information can be... |
def istask(x):
""" Is x a runnable task?
A task is a tuple with a callable first argument
Examples
--------
>>> inc = lambda x: x + 1
>>> istask((inc, 1))
True
>>> istask(1)
False
"""
return type(x) is tuple and x and callable(x[0]) |
def find_ori(dna: list, ori: str) -> int:
"""
A circular DNA, find the origin of replication
Given:
dna: a list of nucleotides ATCG (e.g.: ['A', 'T', 'C', 'C', 'G'])
ori: a string of nucleotides (e.g.: "CGA")
Return:
start index of dna where ori starts. (e.g.: 3)
(any of ... |
def parse_share_url(share_url):
"""Return the group_id and share_token in a group's share url.
:param str share_url: the share url of a group
"""
*__, group_id, share_token = share_url.rstrip('/').split('/')
return group_id, share_token |
def polyarea(poly):
"""Returns the signed area of the given polygon.
The polygon is given as a list of ``(x, y)`` pairs.
Counter-clockwise polys have positive area, and vice-versa.
"""
area = 0.0
p = poly[:]
# close the polygon
if p[0] != p[-1]:
p.append(p[0])
for (x1, y1), (... |
def evaluate_matches(predictions, gold_standard_dict):
"""
Given predictions set and the gold standard, evaluate Precision, Recall and F1-Score.
"""
# annotated as "Yes" and algorithm outputs "Match"
num_true_positives = 0
# annotated as "No" but algorithm outputs "Match"
num_false_positives... |
def f_(x):
"""
Derivate of the function f(x) = x^3 - x - 2
Needed for Newton-Raphson.
"""
return 3*x**2 - 1 |
def get_approval_status(payload):
"""
Gets data from command received from Slack
"""
approve_action = next(a for a in payload["actions"] if a["name"] == "approve")
if approve_action is None:
raise Exception("Request must contain 'approve' action")
action_data = approve_action["value"].s... |
def eat_quoted(i, string):
"""
:param i: Index of the first quote mark
:param string:
:return: Index of the end of the closing quote mark
"""
assert string[i] == '"'
i += 1
while string[i] != '"':
if string[i:i+2] == r'\"':
i += 2
else:
i += 1
... |
def filter_word(word, wordpattern):
"""Checks if a word fits the wordpattern.
Special character mapping is performed as follows:
"-" -> " "
"*" -> <wildcard>"""
if len(word)!=len(wordpattern):
return False
# Enumerate allows iteration over
for ind,char in enumerate(wordpatt... |
def _parse_prop(search, proplist):
"""Extract property value from record using the given urn search filter."""
props = [i for i in proplist if all(item in i['urn'].items() for item in search.items())]
if len(props) > 0:
return props[0]['value'][list(props[0]['value'].keys())[0]] |
def merge(*dicts):
"""Merges N cloudformation definition objects together."""
result = {}
for d in dicts:
for k, v in d.items():
if isinstance(v, dict):
result[k] = {**result.get(k, {}), **v}
else:
result[k] = v
return result |
def annual_post_secondary_expenses(responses, derived):
""" Return the annual cost of the monthly cost of post secondary expense """
try:
return float(responses.get('annual_post_secondary_expenses', 0))
except ValueError:
return 0 |
def get_crop_center_and_size_from_bbox(bbox):
"""Return crop center and size from bbox quadruple
Note that the center and size are in the order of (x, y)
Args:
bbox:
Returns:
"""
ymin, xmin, ymax, xmax = bbox
crop_center = [int((xmin + xmax) / 2), int((ymin + ymax) / 2)]
crop... |
def _isCpuOnly(log):
"""check for CPU-Only mode"""
for l in log:
if "cpu" in l.lower():
return True
return False |
def shake_padding(used_bytes, align_bytes):
"""
The SHAKE padding function
"""
padlen = align_bytes - (used_bytes % align_bytes)
if padlen == 1:
return [0x9f]
elif padlen == 2:
return [0x1f, 0x80]
else:
return [0x1f] + ([0x00] * (padlen - 2)) + [0x80] |
def _should_create_policy_engine_core(policy_configuration):
"""Examine the policy_configuration and decide to start a riemann core
"""
return any(group.get('policies')
for group in policy_configuration['groups'].values()) |
def output_units(un=None):
"""Enable or disable the output of units when printing.
By default output of units is enabled. Do nothing if un is None.
When disabled (un is False) print of Magnitudes will produce only
numbers.
Return: True if output of units enabled, False otherwise.
>>> print(m... |
def insertion_sort(inputArray):
"""input: array
output: sorted array
features: in-place, stable, adaptive, online
efficiency: O(n^2) (worst/avg cases), O(n) (best case)
space complexity: O(1)
method:
Iterate through the array.
If the previous value is greater than the current value,
... |
def round_float(value):
"""Rounds a float to the nearest integer value."""
return int(value + 0.5) |
def _older_than(number: int, unit: str) -> str:
"""
Returns a query term matching messages older than a time period.
Args:
number: The number of units of time of the period.
unit: The unit of time: "day", "month", or "year".
Returns:
The query string.
"""
return f'old... |
def prefixed(strlist, prefix):
"""
Filter a list to values starting with the prefix string
:param strlist: a list of strings
:param prefix: str
:return: a subset of the original list to values only beginning with the prefix string
"""
return [g for g in strlist if str(g).startswith(prefix)] |
def _basis_bitstring(i, num_qubits):
"""Create vector corresponding to i-th basis vector of num_qubits system."""
return [int(char) for char in bin(i)[2:].zfill(num_qubits)] |
def join_list(lst, string=', '):
"""
:param lst: List to be joined
:param string: String that will be used to join the items in the list
:return: List after being converted into a string
"""
lst = str(string).join(str(x) for x in lst)
return lst |
def _pretty_annotation_val(val, cpool):
"""
a pretty display of a tag and data pair annotation value
"""
tag, data = val
if tag in 'BCDFIJSZs':
data = "%s#%i" % (tag, data)
elif tag == 'e':
data = "e#%i.#%i" % data
elif tag == 'c':
data = "c#%i" % data
elif t... |
def cal_pivot(n_losses,network_block_num):
"""
Calculate the inserted layer for additional loss
"""
num_segments = n_losses + 1
num_block_per_segment = (network_block_num // num_segments) + 1
pivot_set = []
for i in range(num_segments - 1):
pivot_set.append(min(num_block_per_se... |
def par(valores_acumulados):
"""
Regresa 1 si encuentra un par,
de lo contrario regresa 0
valores_acumulados es un arreglo con
valores acumulados de la mano
"""
for val in valores_acumulados:
if val == 2:
return 1
return 0 |
def get_fraction(file_name):
"""
return the fraction number encoded in the file name
:param file_name: file name with format .*_fraction[.mgf]
:return: fraction number
"""
lid = file_name.rfind('_')
assert lid != -1
rid = file_name.rfind(".")
if rid == -1:
rid = len(file_nam... |
def vtune(scale, acc_rate):
"""
This is a vectorized version of the pymc3 tune function
Tunes the scaling parameter for the proposal distribution
according to the acceptance rate over the last tune_interval:
Rate Variance adaptation
---- -------------------
<0.001 x 0.1
... |
def daily_cost(lam=0.88, intercept=160):
"""
Return the expected daily cost for machine with lam and intercept
"""
# for a poisson distribution, E(X) = lam, Var(X) = lam,
# since E(X-E(X))^2 = E(X^2) - (EX)^2,
# then E(X^2) = Var(X) + (EX)^2
return intercept + 40*(lam + lam**2) |
def set_ctrl(ctrl=False, comp="unexp"):
"""
set_ctrl()
Sets the control value (only modifies if it is True).
Optional args:
- ctrl (bool): whether the run is a control
default: False
- comp (str) : comparison type
default: "unexp"
... |
def common_letters_in_IDs_differing_with_one_letter(boxes):
"""Find common letters in two IDs, which are differing with one letter."""
for index, box in enumerate(boxes[:-1]):
for other_box in boxes[index + 1:]:
same_letters = [letter_a
for letter_a, letter_b in z... |
def _getvars(expression, user_dict):
"""Get the variables in `expression`."""
cexpr = compile(expression, '<string>', 'eval')
exprvars = [var for var in cexpr.co_names
if var not in ['None', 'False', 'True']]
reqvars = {}
for var in exprvars:
# Get the value
if var i... |
def first(item):
"""
Return an empty dict or the first item in a list
:param item:
:return:
"""
if isinstance(item, list):
return {} if not item else item[0]
return {} |
def ade_fn2index(fn):
"""
Split an ADE filename to get the index
of the file in the lists of the index file.
"""
fn = fn.split(".")[0]
number = fn.split("_")[-1]
number = int(number) - 1
return number |
def quadratic_sum(n: int) -> int:
"""calculate the quadratic num from 1 ~ n"""
return sum(n ** 2 for n in range(1, n + 1)) |
def binarySearch(array, target):
""" Devuelve la posicion del elemento "target" si se encuentra en el array, caso contrario devuelve -1 """
left = 0
right = len(array) - 1
while left <= right:
mid = int(left + (right - left) / 2)
if array[mid] == target:
return mid
if array[mid] < targ... |
def select_from_list(
master_list,
first=None,
last=None,
skip=[],
only=[],
loose=True,
):
"""
Select only part of a list.
"""
sorted_list = sorted(master_list,key=lambda s: s.lower())
sub_list = []
if first is not None:
before_first = True
else:
... |
def _extract_dict(input_dict, output_dict, input_keys):
"""
Recursively extract values from a defaults dictionary.
A defaults dictionary consists of:
- an optional "all" key
- zero or more other keys, each of whose values is a defaults dictionary
The goal is to add any matching va... |
def scale(value):
"""Scale the light sensor values from 0-65535 (AnalogIn range)
to 0-50 (arbitrarily chosen to plot well with temperature)"""
return value / 65535 * 50 |
def adjust_learning_rate(initial_lr, optimizer, epoch):
"""Sets the learning rate to the initial LR decayed by 10 every 10 epochs"""
lr = initial_lr * (0.1 ** (epoch // 10))
return lr |
def counting_sort(A, max_val):
"""
This sorting algorithm will only work with array length n consist of
elements from 0 to k for integer k < n.
"""
k = max_val + 1
count = [0]*k
result = [None]*len(A)
print("Array A = ", A)
# counting the number of i (1 < i < k) in A and store in c... |
def _create_item(target_columns, rows):
"""Creates the 'item' field for a deid or inspect request."""
table = {'headers': [], 'rows': []}
for _ in rows:
table['rows'].append({'values': []})
for col in target_columns:
table['headers'].append({'name': col['name']})
for i in range(len(rows)):
if ... |
def validate_ecl(field):
"""
ecl (Eye Color) - exactly one of: amb blu brn gry grn hzl oth.
"""
return field in ['amb', 'blu', 'brn', 'gry', 'grn', 'hzl', 'oth'] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.