content stringlengths 42 6.51k |
|---|
def get_start_end_from_string(start_end):
""" 111.222 => 111, 222 """
start, end = start_end.split(".")
start = int(start)
end = int(end)
return(start, end) |
def get_full_policy_path(arn):
"""
Resource string will output strings like the following examples.
Case 1:
Input: arn:aws:iam::aws:policy/aws-service-role/AmazonGuardDutyServiceRolePolicy
Output:
aws-service-role/AmazonGuardDutyServiceRolePolicy
Case 2:
Input: arn:aws:iam::123456... |
def fib(n):
"""Fibonacci example function
Args:
n (int): integer
Returns:
int: n-th Fibonacci number
"""
assert n > 0
a, b = 1, 1
for i in range(n - 1):
a, b = b, a + b
return a |
def get_copies(rdoc, pformat):
"""
make copies (Single, Duplicated or Triplicated) only for pdf format
"""
copies = ["Original", "Duplicate", "Triplicate"]
return copies.index(rdoc.jasper_report_number_copies) + 1 if pformat == "pdf" else 1 |
def remove_prefixes_of_others(values):
"""
Removes strings that are prefixes of other strings and returns the result.
"""
to_remove = set()
for value in values:
for other_value in values:
if other_value != value and other_value.startswith(value):
to_remove.add(va... |
def decimalToRoman(index):
"""Converts an int to a roman numerical index"""
assert isinstance(index, int) and index > 0
roman = [(1000, 'M'), (900, 'CM'),
(500, 'D'), (400, 'CD'),
(100, 'C'), (90, 'XC'),
(50, 'L'), (40, 'XL'),
(10, 'X'), (9, 'IX'),
... |
def calc_partial_interia_dat(contrib_dat, ev):
"""
Partial inertias for datasets/tables.
:return:
"""
print("Calculating partial inertias for the datasets... ", end='')
pid = contrib_dat * ev
print('Done!')
return pid |
def reverse_words_in_a_string(string):
"""
Given an input string, reverse the string word by word.
:param string: given string
:type string: str
:return: reversed string
:rtype: str
"""
# return ' '.join(string.strip().split(' ')[::-1])
splited = [word for word in string.strip().spl... |
def tokenize_english(sentence):
"""English language tokenizer."""
return sentence.split(" ") |
def split(seq, length):
"""
Split a list in chunks of specific length
"""
return [seq[i : i + length] for i in range(0, len(seq), length)] |
def OCEANprice(firm_valuation: float, OCEAN_supply: float) -> float:
"""Return price of OCEAN token, in USD"""
assert OCEAN_supply > 0
return firm_valuation / OCEAN_supply |
def _str_to_list(str_or_list):
"""try to return a non-string iterable in either case"""
if isinstance(str_or_list, (tuple, list, set)):
return str_or_list
if str(str_or_list) == str_or_list:
return [str_or_list]
raise ValueError(str_or_list) |
def find_uniques(
test_list,
expected_list
):
"""checks for unique values between two lists.
Args:
test_list (:obj:`list`): values found in test
expected_list (:obj:`list`): values expected
Returns:
(:obj:`list`): unique_test
(:obj:`list`): unique_expected
... |
def validate_rule_association_id(value):
"""Raise exception if resolver rule association id has invalid length."""
if value and len(value) > 64:
return "have length less than or equal to 64"
return "" |
def dictget(d, l):
"""
Lookup item in nested dict using a list of keys, or None if non-existent
d: nested dict
l: list of keys, or None
"""
try:
dl0 = d[l[0]]
except (KeyError, TypeError):
return None
if len(l) == 1:
return dl0
return dictget(dl0, l[1:]) |
def _mask_dict(in_dict, mask):
"""Given a dict and a list of fields removes all fields not in the list"""
for key in (set(in_dict.keys()) - set(mask)):
in_dict.pop(key)
return in_dict |
def sub(value):
""""Subtracts one from `value`.
Args:
value (int): A number.
Returns:
int: `value` minus one.
"""
return (value - 1) |
def reverse_line(line: list) -> list:
"""
Takes a line of edges [(p0, p1), (p1, p2) ... (pn_m_1, pn)] and returns
[(pn, pn_m_1), ... (p1, p0)], where the p's are (x, y) in map coordinates.
Parameters
----------
line : list
List of edges (p0, p1), where p0, p1 in R^2
Returns
---... |
def remove_string_escapes(value: str) -> str:
"""Used when parsing string-literal defaults to prevent escaping the string to write arbitrary Python
**REMOVING OR CHANGING THE USAGE OF THIS FUNCTION HAS SECURITY IMPLICATIONS**
See Also:
- https://github.com/openapi-generators/openapi-python-client/... |
def _split_by_comma(s, length=50):
"""Group a comma-separated string into a list of at-most
``length``-length words each."""
str_split = s.split(',')
str_list = []
for i in range(0, len(str_split) + length, length):
temp_str = ','.join(str_split[i:i+length])
if temp_str:
... |
def get_dimensions(matrix):
"""
A helper function to get the dimensions of the matrix
Args:
matrix (2D array): A 2D array that is
representing a matrix
Returns:
tuple : A tuple containing the dimensions of
the matrix
"""
return len(matrix), l... |
def format_query_params(request, config):
"""formats query parameters from config and attached to URL."""
if "query" in config["request"].keys():
request["request"]["url"]["raw"] += config["request"]["query"]
request["request"]["url"]["host"] = [request["request"]["url"]["raw"]]
return reque... |
def mul_vector_by_scalar(vector, scalar):
"""
Multiplies a vector by a scalar
:param vector: vector
:param scalar: scalar
:return: vector * scalar
"""
return tuple([value * scalar for value in vector]) |
def format_columns(rows, sep=None, align=None):
"""Convert a list (rows) of lists (columns) to a formatted list of lines.
When joined with newlines and printed, the output is similar to
`column -t`.
The optional align may be a list of alignment formatters.
The last (right-most) column will not hav... |
def pointsToList(points):
"""Convert query response from point in time, value format to list with values only.
:param points: query response
:return: list[oldest value, -> , newest value]
"""
list_of_points = []
for point in points:
list_of_points.append(point)
return list_of_point... |
def ms_to_hours(ms):
"""Convert milliseconds to hours"""
return round(ms / 60.0 / 60.0 / 1000.0, 2) |
def makeGameBoard(n):
"""
Create a gameboard represented as a dictionary.
Game board consistis of numeric placeholders starting
with zero and going to the last number stipulated
-------------------------
| 0| 1| 2| 3| 4| 5| 6| 7|
-------------------------
| 8| 9|10|11|12|13|14|15|
... |
def TropicalWeight(param):
"""
Returns the emulated fst TropicalWeight
Args:
param (str): The input
Returns:
bool: The arc weight
"""
if param == (float('inf')):
return False
else:
return True |
def _diag(m):
"""Return the diagonal of a matrix."""
return [m[j][j] for j in range(len(m))] |
def reflection_normal(n1, n2):
"""
Fresnel reflection losses for normal incidence.
For normal incidence no difference between s and p polarisation.
Inputs:
n1 : Refractive index of medium 1 (input)
n2 : Refractive index of medium 2 (output)
Returns:
R : The Fresnel
Doctests:
... |
def migrate_instrument_config(instrument_config):
"""utility function to generate old instrument config dictionary"""
cfg_list = []
for detector_id in instrument_config['detectors']:
cfg_list.append(
dict(
detector=instrument_config['detectors'][detector_id],
... |
def get_current_next_indicator(data):
"""Gets the current/next indicator from the given section data
Parses the given array of section data bytes and returns the current/next indicator. If True, then this
is the currently applicable table. If False then it will become applicable some time in the future.
"""
if d... |
def seconds_to_timeleft(seconds):
"""Utilty function converting seconds to string representation."""
days, seconds = seconds // 86400, seconds % 86400
hours, seconds = seconds // 3600, seconds % 3600
minutes, seconds = seconds // 60, seconds % 60
timeleft = ''
if days:
timeleft +=... |
def find_matching_parenthesis(left, equation):
"""
Ghetto function to find ) that matches (
When p = 0 after finding a ), it should be the matching paren
:param left: The parenthesis to match
:param equation: The equation to match it in
:return: int. Index of right paren
"""
nested_paren... |
def space_replacer(string):
"""
:type string: str
:rtype: str
"""
string = string.replace(" ", "_")
while "__" in string:
string = string.replace("__", "_")
return string |
def determine_archive_version_generic(name, leading_terms, trailing_terms):
"""
Given an archive file name, tries to get version information. Generic version that can cut off leading and trailing
terms and converts to lower case. Give the most special terms first in the list. As many cut offs as possible ar... |
def is_internal(ip_address):
"""Determine if the address is an internal ip address
Note: This is super bad, improve it
"""
# Local networks 10.0.0.0/8, 172.16.0.0/12, '192.168.0.0/16
local_nets = '10.', '172.16.', '192.168.', '169.254', 'fd', 'fe80::'
return any([ip_address.startswith(local) ... |
def get_unique_in_array(lst: list):
"""Returns a list of the unique values within the given list.
Examples:
>>> mylst = [1,1,2,2,3,2,3,4,5,6]\n
>>> get_unique_in_array(mylst)\n
[1, 2, 3, 4, 5, 6]
>>>
"""
return list(set(lst)) |
def get_symminfo(newsymms: dict) -> str:
"""
Adds text about the symmetry generators used in order to add symmetry generated atoms.
"""
line = 'Symmetry transformations used to generate equivalent atoms:\n'
nitems = len(newsymms)
n = 0
for key, value in newsymms.items():
sep = ';'
... |
def _convert_byte32_arr_to_hex_arr(byte32_arr):
"""
This function takes in an array of byte32 strings and
returns an array of hex strings
"""
hex_ids = []
for byte32_str in byte32_arr:
hex_ids = hex_ids + [byte32_str.hex()]
return hex_ids |
def emote(name, action):
"""Emote an action."""
return "{} {}".format(name, action) |
def faces_indices_vectors_to_matrix(indices, faces):
"""faces_indices_vectors_to_matrix(indices, faces) -> List[List[int]]
PyPRT outputs the GeneratedModel face information as a list of vertex indices
and a list of face indices count. This function converts these two lists into
one list of lists c... |
def is_valid_url(url: str) -> bool:
"""
Minimal validation of URLs
Unfortunately urllib.parse.urlparse(...) is not identifying correct URLs
"""
return isinstance(url, (str, bytes)) and len(url) > 8 and url.split('://', 1)[0] in ('http', 'https') |
def tweet_location(tweet):
"""Return a position representing a tweet's location."""
return tweet['latitude'] ,tweet['longitude'] |
def _get_unique_split_data(split_test_targets):
"""Returns all split_test_target 'data' dependencies without duplicates."""
data = []
for split_name in split_test_targets:
split_data = split_test_targets[split_name].get("data", default = [])
[data.append(d) for d in split_data if d not in da... |
def get_batch_asset_task_info(ctx):
"""Parses context data from webpublisher's batch metadata
Returns:
(tuple): asset, task_name (Optional), task_type
"""
task_type = "default_task_type"
task_name = None
asset = None
if ctx["type"] == "task":
items = ctx["path"].spl... |
def klucb(x, d, kl, upperbound, lowerbound=float('-inf'), precision=1e-6, max_iterations=50):
""" The generic KL-UCB index computation.
- x: value of the cum reward,
- d: upper bound on the divergence,
- kl: the KL divergence to be used (:func:`klBern`, :func:`klGauss`, etc),
- upperbound, lowerbou... |
def golomb(n: int, map={}):
"""memoized recursive generation of Nth number in Golomb sequence"""
if n == 1:
return 1
if n not in map:
map[n] = 1 + golomb(n - golomb(golomb(n - 1)))
return map[n] |
def to_alpha(anumber):
"""Convert a positive number n to its digit representation in base 26."""
output = ''
if anumber == 0:
pass
else:
while anumber > 0:
anumber = anumber
output += chr(anumber % 26 + ord('A'))
anumber = anumber // 26
return outp... |
def check_chef_recipe(rec):
"""
Checks if the given file is a chef recipe
:param rec: file path
:return: check result
"""
return rec.lower().endswith(".rb") |
def oneD_linear_interpolation(desired_x, known):
"""
utility function that performs 1D linear interpolation with a known energy value
:param desired_x: integer value of the desired attribute/argument
:param known: list of dictionary [{x: <value>, y: <energy>}]
:return energy value with desired attr... |
def make_unique_name(base, existing=[], format="%s_%s"):
"""
Return a name, unique within a context, based on the specified name.
base: the desired base name of the generated unique name.
existing: a sequence of the existing names to avoid returning.
format: a formatting specification for how the n... |
def has_module(modName):
"""Check if the module is installed
Args:
modName (str): module name to check
Returns:
bool: True if installed, otherwise False
"""
from pkgutil import iter_modules
return modName in (name for loader, name, ispkg in iter_modules()) |
def _get_main_object_id_mappings(main_object_ids, all_object_ids,
output_actions, alias_object_id_to_old_object_id):
"""
Return a list of main object IDs, and a mapping from all object Ids to the main ones
:param main_object_ids: Main ids identified by the sampler
:param... |
def v0_tail(sequence, n):
"""Return the last n items of given sequence.
But this won't pass all our tests. For one thing, the return value will be
the same as the given sequence type. So if the given sequence is a string
then we'll get a string returned and if it's a tuple then we'll get a
tuple re... |
def are_all_equal(tiles):
"""
Checks if all tiles are the same.
"""
return len(set(tiles)) <= 1 |
def _parse_semicolon_separated_data(input_data):
"""Reads semicolon-separated Unicode data from an input string.
Reads a Unicode data file already imported into a string. The format is
the Unicode data file format with a list of values separated by
semicolons. The number of the values on different line... |
def get_addr(host, port):
"""Returns port"""
return "%d" % (port) |
def clamp(x, _min, _max):
"""Clamp a value between a minimum and a maximum"""
return min(_max, max(_min, x)) |
def all_(collection, predicate=None):
""":yaql:all
Returns true if all the elements of a collection evaluate to true.
If a predicate is specified, returns true if the predicate is true for all
elements in the collection.
:signature: collection.all(predicate => null)
:receiverArg collection: in... |
def list_all(node):
"""Retrieve all the key-value pairs in a BST in asc sorted order of keys."""
# To achieve asc sortedness, we can perform an inorder traversal of the BST,
# and then we know from the definition of BST (cf is_bst()) that it's asc. O(N)
if node is None:
return []
return lis... |
def symmetric(l):
"""Returns whether a list is symmetric.
>>> symmetric([])
True
>>> symmetric([1])
True
>>> symmetric([1, 4, 5, 1])
False
>>> symmetric([1, 4, 4, 1])
True
>>> symmetric(['l', 'o', 'l'])
True
"""
"*** YOUR CODE HERE ***"
if (len(l) == 0) or (len(l... |
def dict_compare(d1, d2):
"""Taken from: https://stackoverflow.com/questions/4527942/comparing-two-dictionaries-in-python"""
d1_keys = set(list(d1))
d2_keys = set(list(d2))
intersect_keys = d1_keys.intersection(d2_keys)
added = d1_keys - d2_keys
removed = d2_keys - d1_keys
modified = {o: (d1... |
def _SignedVarintSize(value):
"""Compute the size of a signed varint value."""
if value < 0: return 10
if value <= 0x7f: return 1
if value <= 0x3fff: return 2
if value <= 0x1fffff: return 3
if value <= 0xfffffff: return 4
if value <= 0x7ffffffff: return 5
if value <= 0x3ffffffffff: return 6
if value <... |
def _make_worker_node_script(module_name, function_name, environ):
"""
Returns a string that is a python-script.
This python-script will be executed on the worker-node.
In here, the environment variables are set explicitly.
It reads the job, runs result = function(job), and writes the result.
Th... |
def patch_dict(d, p):
"""Patches the dict `d`.
Patches the dict `d` with values from the "patcher" dict `p`.
"""
for k in p:
if k in d.keys():
if type(d[k]) == dict:
d[k] = patch_dict(d[k], p[k])
else:
d[k] = p[k]
return d |
def count_fixxations(fixxations):
"""
A Function that counts the number of distinct fixxations
:param fixxations: a list with values which indicate if the move from the previos is a fixxations.
:return: a number of indicating the amount of different fixxations
"""
fixxations_count =... |
def ugly_number(n):
"""
Returns the n'th Ugly number.
Ugly Numbers are numbers whose only prime factors are 2,3 or 5.
Parameters
----------
n : int
represent the position of ugly number
"""
if(n<1):
raise NotImplementedError(
"Enter a valid natural numbe... |
def parse_content_type(data):
"""
Parses the provided content type string retrieving both the multiple
mime types associated with the resource and the extra key to value
items associated with the string in case they are defined (it's optional).
:type data: String
:param data: The content... |
def get_configs(configs: dict, operator: str, configs_type: str):
"""
:param configs: the main config file
:param operator: the id of the operator
:param configs_type: the type of configs you want: 'image' or 'text' etc
:return:
"""
for key in configs.keys():
config_item = ... |
def normalize_houndsfield(data_):
"""Normalizes houndsfield values ranging from -1024 to ~+4000 to (0, 1)"""
cpy = data_ + 1024
cpy /= 3000
return cpy |
def apk(actual, predicted, k=10):
"""
Computes the average precision at k.
This function computes the average prescision at k between two lists of
items.
Parameters
----------
actual : list
A list of elements that are to be predicted (order doesn't matter)
predicted : list... |
def remove_artifacts(tree):
"""Removes some artifacts introduced by the preprocessing steps from tree['body']
Additionally, modify this function to distort/modify post-wise text from the training files."""
for post in tree:
post["body"] = post["body"].replace(" ", " ")
return tree |
def int2uint64(value):
"""
Convert a signed 64 bits integer into an unsigned 64 bits integer.
>>> print(int2uint64(1))
1
>>> print(int2uint64(2**64 + 1)) # ignore bits larger than 64 bits
1
>>> print(int2uint64(-1))
18446744073709551615
>>> print(int2uint64(-2))
184467440737095... |
def get_day_suffix(day):
"""
Returns the suffix of the day, such as in 1st, 2nd, ...
"""
if day in (1, 11, 21, 31):
return 'st'
elif day in (2, 12, 22):
return 'nd'
elif day in (3, 13, 23):
return 'rd'
else:
return 'th' |
def multiplicity(p, n):
"""
Return the multiplicity of the number p in n; that is, the greatest
number m such that p**m divides n.
Example usage
=============
>>> multiplicity(5, 8)
0
>>> multiplicity(5, 5)
1
>>> multiplicity(5, 25)
2
... |
def find_direct_conflicts(pull_ops, unversioned_ops):
"""
Detect conflicts where there's both unversioned and pulled
operations, update or delete ones, referering to the same tracked
object. This procedure relies on the uniqueness of the primary
keys through time.
"""
return [
(pull_... |
def ReorderListByIndices(reorder_list:list, ordering_indices:list):
"""
This function reorder a list by a given list of ordering indices.
:param reorder_list:list: list you want to reorder
:param ordering_indices:list: list of indices with desired value order
"""
try:
return [y f... |
def tagcloud_opacity(n):
"""
For the tag cloud on some pages - between 0 and 1
"""
if n:
if n <= 9:
return n / 10.0 + 0.3 # otherwise you don't see it
elif n >= 10:
return 1
else:
print(
"ERROR: tags tot count needs to be a number (did you... |
def _prep_sge_resource(resource):
"""Prepare SGE resource specifications from the command line handling special cases.
"""
resource = resource.strip()
k, v = resource.split("=")
if k in set(["ar"]):
return "#$ -%s %s" % (k, v)
else:
return "#$ -l %s" % resource |
def asn_is_in_ranges(asn, ranges):
"""
Test if an asn falls within any of the ranges provided
Arguments:
- asn<int>
- ranges<list[tuple(min,max)]>
Return:
- bool
"""
asn = int(asn)
for as_range in ranges:
if asn >= as_range[0] and asn <= as_range[1]:
... |
def check_on_not_eq_vals(val1, val2):
"""
Func which check values on non equivalent and return tuple of vals.
:param val1:
:param val2:
:return:
"""
return (val1, val2) if val1 != val2 else (val1,) |
def generate_result_dics(videos, parents, channel_videos):
"""Create a dictionary for video search results"""
all_results = []
for i in range(len(videos)):
out_dic = {"video_id": videos[i],
"position": i,
"channel_id": parents[i],
"channel_vid... |
def to_str(matrix):
"""
:param matrix: the matrix to compute the size
:type matrix: matrix
:return: a string representation of the matrix
:rtype: str
"""
s = ""
# by design all matrix cols have same size
for row in zip(*matrix):
cells = [str(cell) for cell in row]
s += " ".join(cells) + "\n"
return s |
def check_validity(board, number, pos):
"""
Checks the validity of the board.\n
Arguments:\n
board: The sudoku board.
number: Number to insert.
pos: The position of the number. It is (X, Y) tuple.
"""
# Check Row.
for i in range(0, len(board[0])):
if boa... |
def _method_with_key_reference(fake_value, other_value):
"""
:type other_value: [list, dict, str]
"""
return other_value.lower() |
def point_line_nearest_point(p1, l1, l2) -> tuple:
"""Returns a point in line (l1, l2) that is closest to p1."""
a = float(p1[0] - l1[0])
b = float(p1[1] - l1[1])
c = float(l2[0] - l1[0])
d = float(l2[1] - l1[1])
dotprod = a * c + b * d
len_sq = c * c + d * d
param = -1
# in case ... |
def sec2hms(sec):
"""
Convert seconds to hours, minutes and seconds.
"""
hours = int(sec/3600)
minutes = int((sec -3600*hours)/60)
seconds = int(sec -3600*hours -60*minutes)
return hours,minutes,seconds |
def get_control_variation(campaign):
"""Returns control variation from a given campaign
Args:
campaign (dict): Running campaign
Returns:
variation (dict): Control variation from the campaign, ie having id = 1
"""
for variation in campaign.get("variations"):
if int(variation... |
def no_net_connect_disconnect(on=0):
"""Remover a Opcao Mapear Unidade de Rede
DESCRIPTION
Previne que usuarios facam configuracoes adicionais a partir da opcao
Mapear Unidade de Rede. Isto removera a opcao Mapear Unidade de Rede da
barra de ferramentas do Windows Explorer e o do menu ... |
def white_backward_continue(i, text):
"""Scan backward and skip characters.
Skipped characters are those that should be included in the current atom.
"""
# Type casting can have spaces before the variable.
# Example: (NSString *) variable
if text[i - 1] == ')':
return i - 1
return ... |
def flatten_dict(d):
"""
https://stackoverflow.com/questions/52081545/python-3-flattening-nested-dictionaries-and-lists-within-dictionaries
"""
out = {}
for key, val in d.items():
if isinstance(val, dict):
val = [val]
if isinstance(val, list):
for subdict... |
def extract_interaction_labels(fasta_file):
"""
Extracts the binary epitope and ppi annotations from the previously generated fasta files in epitope_dir and/or ppi_dir.
fasta_file format (3 lines):
>1HEZ_E (pdb identifier + optionally... |
def hash_1(key, size):
""" simple hash 1 function """
return sum([i * 256 + ord(v_) for i, v_ in enumerate(str(key))]) % size |
def _gnurl( clientID ):
"""
Helper function to form URL to Gracenote_ API service.
:param str clientID: the Gracenote_ client ID.
:returns: the lower level URL to the Gracenote_ API.
:rtype: str
"""
clientIDprefix = clientID.split('-')[0]
return 'https://c%s.web.cddbp.net/webapi/xml... |
def format_file_size(size):
"""
Formats the file size as string.
@param size numeric value
@return string (something + unit)
"""
if size >= 2 ** 30:
size = size / 2 ** 30
return "%1.2f Gb" % size
elif size >= 2 ** 20:
size = size / 2 ** 20... |
def float_to_bin(num, length):
"""
Convert float number to binary systems
:param num: Number to change
:type num: float
:param length: The maximum length of the number in binary system
:type length: int
:return: Returns a number converted to the binary system
:rtype: string
"""
... |
def parse_query_string(query_string: str) -> dict:
"""
Query strings are basically looks like "q=my-query&search=true". So, here it's parsing the whole strings and
breaks into dictionary
"""
_query_dict = {
_each.split('=')[0]: _each.split('=')[1] for _each in query_string.split('&') if
... |
def multi(q, r):
""" Multiplies Two Numbers"""
aq = q * r
return aq |
def some_function(x):
""" This can be any function """
return x**2 + x + 3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.