content stringlengths 42 6.51k |
|---|
def create_literal(val, datatype=None, lang=None):
"""
Put the value in unicode escaping new special characters to keep canonical form
From NT specification at 'https://www.w3.org/TR/n-triples/#canonical-ntriples':
"Within STRING_LITERAL_QUOTE, only the characters U+0022, U+005C, U+000A, U+000D are
... |
def forceForwardCoordinates(start, end, strand, length):
"""return forward coordinates.
If strand is negative, the coordinates in a and b
will be converted. If they are on the positive
strand, they will be returned as is.
Arguments
---------
start : int
Start coordinate
end : i... |
def appendb(path, data):
"""Write data to a binary file.
Args:
path (str): Full path to file
data (str): File bytes
Returns:
int: Number of bytes appended
"""
with open(path, 'ab') as handle:
return handle.write(data) |
def _first_from_dict(d):
"""Returns the first name/value pair from a dictionary or None if empty."""
for x in list(d.items()):
return x[0], x[1] |
def keyspace_id_prefix(packed_keyspace_id):
"""Return the first str byte of packed_keyspace_id if it exists."""
return '%02x' % ord(packed_keyspace_id[0]) |
def coverageIsFailing(coverage, branches, minCoverage, minBranches) :
"""Checks if coverage or branchs coverage or both are
below minimum to pass workflow run. Logs messages if it is.
Actual failing behavior should be handled by caller.
Keyword arguments:
coverage - instructions coverage in interva... |
def fib(n):
"""Terrible Fibonacci number generator."""
return n if n < 2 else fib(n-1) + fib(n-2) |
def get_var_names(var_name):
"""Defines replacement dictionary for the bare variable name and
the names derived from it - the optimization flag and the identifier name.
"""
repl = dict()
repl['opt_var_name'] = "Opt_%s"%var_name
repl['id_var_name'] = "ID_%s"%var_name
repl['var_name'] = var_name
return... |
def detect_ul(table):
"""Detect unordered list"""
if not len(table):
return False
for tr in table:
if len(tr)!=2:
return False
td1 = tr[0]
if len(td1) or td1.text.strip()!='-':
return False
return True |
def En_Route_Salute(s):
"""
Commander Lambda loves efficiency and hates anything that wastes time.
She's a busy lamb, after all! She generously rewards henchmen who identify
sources of inefficiency and come up with ways to remove them. You've spotted
one such source, and you think solving it will... |
def tuple_from_dict(dict):
"""Turns a dict into a representative sorted tuple of 2-tuples.
Parameters
----------
dict: dict
A dictionary.
Returns
-------
tuple
A unique tuple representation of the dictionary as a sequence of
2-tuples of key-value pairs, sorted by the ... |
def get_ijk_list(m):
"""Form all possible (i, j, k) exponents up to maximum total angular
momentum m.
"""
l = []
for a in range(1, m + 2):
for b in range(1, a + 1):
i = m + 1 - a
j = a - b
k = b - 1
l.append([i, j, k])
return l |
def strip_spaces(s):
""" Strip excess spaces from a string """
return u" ".join([c for c in s.split(u' ') if c]) |
def lucas_lehmer_test(p: int) -> bool:
"""
>>> lucas_lehmer_test(p=7)
True
>>> lucas_lehmer_test(p=11)
False
# M_11 = 2^11 - 1 = 2047 = 23 * 89
"""
if p < 2:
raise ValueError("p should not be less than 2!")
elif p == 2:
return True
s = 4
M = (1 << p) - 1
... |
def rivers_with_stations(stations):
"""Creates a set of names of rivers which have at least one station. Used in Task1D.py
Args: stations (list of MonitoringStation objects)
Returns: rivers_monitored (set of names of rivers)"""
# Create empty set to store the names of rivers monitored (set us... |
def i_to_blue(i, normalize=False):
"""Convert a number between 0.0 and 1.0 to a shade of blue.
Parameters
----------
i : float
A number between 0.0 and 1.0.
normalize : bool, optional
Normalize the resulting RGB values.
Default is to return integer values ranging from 0 to 2... |
def valid(board, pos, num):
"""
Whether a number is valid in that cell, returns a bool
:param board: the board to check
:param pos: position of the cell to check
:param num: the number to test at the position
"""
for i in range(9):
# make sure it isn't the same number we're checking... |
def pct_to_int(amt, pcts):
"""
Distributes amt according to pcts. Last element accumulates all fractions, may be off by (n - 1)
"""
first = [int(amt * pct) for pct in pcts[:-1]]
return first + [amt - sum(first)] |
def factorial(num):
"""
Factorial.
"""
assert isinstance(num, int) and num >= 0
if num == 0:
return 1
return num * factorial(num - 1) |
def create_data_structure(string_input):
"""
Parses a block of text and stores relevant information
into a data structure. You are free to choose and design any
data structure you would like to use to manage the information.
Arguments:
string_input: block of text containing the network informati... |
def _bond_dist(geom, a1, a2):
"""
Computes a simple bond distance between two rows in a flat (n, 3) list of coordinates
"""
a13 = a1 * 3
a23 = a2 * 3
xd = (geom[a13] - geom[a23])**2
yd = (geom[a13 + 1] - geom[a23 + 1])**2
zd = (geom[a13 + 2] - geom[a23 + 2])**2
return (xd + yd + zd... |
def log_duplicates(manual_data):
""" Returns a list of duplicates """
seen = set()
dups = list()
for element in manual_data:
if element not in seen:
seen.add(element)
else:
dups.append(element)
return dups |
def get_substring(data, boundary, offset, end):
""" Retrieves the substring of ``data`` until the next ``boundary`` from a
given offset to a until ``end``.
"""
index = data.find(boundary, offset, end)
if index == -1:
return None, None
return data[offset:index], index + len(boundary) |
def get_parse_valency(i, deps, data):
"""
get number of childs at position 'i' in edges R created so far
"""
if i == -1:
return 0
valency = len(deps[i])
if not valency:
return 0
else:
return valency |
def generate_legend_file(split_names, legend_file_name, out_dir):
"""
generate legend file for each all the splits
"""
legend_file = '{0}/{1}'.format(out_dir, legend_file_name)
with open(legend_file, 'a+') as f:
for split_name in split_names:
f.write('{0}\n'.format(split_name))
... |
def wrap(string, length, indent=0):
"""
Formats the string *string* to ensures the line lengths are not
larger than *length*. The optional argument *indent* specifies the
number of spaces to insert at the beginning of all lines except the
first. The line breaks are inserted at spaces.
... |
def parse_organization(meeting_topic):
"""Derive the organizational identifier from the meeting topic string.
:param meeting_topic: string, Meeting topic from Zoom
:returns: string, Organization
"""
if "OLF" in meeting_topic:
organization = "OLF"
elif "Foundation" in meeting_topic:
... |
def default_cmdline_options(config):
"""
Return default command line options required for every run of terraform.
Args:
config: dictionary containing all variable settings required
to run terraform with
Returns:
cmdline_options: list of command-line arguments to run
... |
def _fstr(in_str, length, index, ESCAPE):
""" in_str[index] is " or ', return index of next in_str[index] without \\ before it. """
ci, index = in_str[index], index + 1
while index < length and in_str[index] != ci:
index += 2 if in_str[index] == ESCAPE else 1
return index |
def intConversion (s):
"""
Method aimed to cast a string as integer. If the conversion is not possible,
it returns None
@ In, s, string, string to be converted
@ Out, response, int or None, the casted value
"""
try:
return int(s)
except (ValueError,TypeError) as e:
return None |
def parse_source_to_dict(source: str) -> str:
"""
Extract dict from source file
:param source:
:return:
"""
line = source.replace("\n", "")
line = line.split("package_dir")[1]
fixed = ""
for char in line:
fixed += char
if char == "}":
break
line = fixe... |
def get_Sn(n):
"""Return the list of n! permutations."""
if n < 0:
raise ValueError("`n` must be >= 0 but got {}.".format(n))
elif n == 0:
return [[]]
elif n == 1:
return [[0]]
res = []
Sn_1 = get_Sn(n - 1)
for s in Sn_1:
for i in range(n - 1, -1, -1):
... |
def _sanitize_dirnames(filename, restore=False):
"""
Remove (or add) leading _ in the directories names in `filename`
The `restore` param means that the path name should be restored from the queryname,
i.e. conversion should be done in the opposite direction
"""
parts = filename.split('/')
n... |
def build_query(start, limit):
"""
Tidak bisa mengandalkan kolom `date` karena semakin kemari jumlah obrolan
semakin banyak.
Kolom `time_added` juga tidak bisa diandalkan mengingat ada duplikasi pada
kolom ini.
Oleh karena itu digunakan `feed_time` sebagai titik mulai dan di limit
sejumlah obrolan dari... |
def concat3DictValues(Dict1, Dict2, Dict3):
"""Concat the positions of three consecutive chords."""
l1 = list(Dict1.values())
l2 = list(Dict2.values())
l3 = list(Dict3.values())
lconcat = l1 + l2 + l3
return lconcat |
def parse_branches(branch_list):
"""
Extract branch meta data from a list of Git response lines.
Arguments
---------
branch_list: iterable
list of branch-related entries beginning with the string '# '
Returns
-------
dict
a dictionary containing branch meta data
"""... |
def ddm_ilu(a):
"""a <-- LU(a)"""
m = len(a)
if not m:
return []
n = len(a[0])
swaps = []
for i in range(min(m, n)):
if not a[i][i]:
for ip in range(i+1, m):
if a[ip][i]:
swaps.append((i, ip))
a[i], a[ip] = a... |
def _parity_set(index):
"""The bits whose parity stores the parity of the bits 0 .. `index`."""
indices = set()
while index > 0:
indices.add(index - 1)
# Remove least significant one from index
# E.g. 00010100 -> 00010000
index &= index - 1
return indices |
def process_labels(string):
"""
Returns the label string as a list of integers
:param string:
:return:
"""
return 0 if string == '01' else 1 |
def is_primitive(item):
"""
Determines if the given item is a primitive value (either an int, float,
str, bool, or None).
Args:
item (any): Any value
Returns:
bool: Whether the item is a primitive value.
"""
return isinstance(item, (int, float, str, bool)) or item is None |
def run_up_stairs_rec(n):
"""Counts number of ways to run up stairs.
Inefficient solution with O(3^n) time.
"""
if n <= 0:
return 0
if n == 1:
return 1
if n == 2:
return 2
if n == 3:
return 4
return run_up_stairs_rec(n-1) + run_up_stairs_rec(n-2) + r... |
def _erbn_to_freq(e):
"""Convert ERB number to frequency"""
return (10 ** (e / 21.4) - 1) / 0.00437 |
def splitSeq(seq, predicates):
"""
Split a sequence into one seq for which predicates is True, and another
for which predicates is False.
Parameters
----------
seq : iterable
An arbitrary sequence.
predicates : iterable( bool )
Same length as seq. Each entry is the truth value o... |
def GetDistinguishableNames(keys, delimiter, prefixes_to_remove):
"""Reduce keys to a concise and distinguishable form.
Example:
GetDistinguishableNames(['Day.NewYork.BigApple', 'Night.NewYork.BigMelon'],
'.', ['Big'])
results in {'Day.NewYork.BigApple': 'Day.Apple',
... |
def get_theoretical_Es(Q):
"""Computes theoretical estimate for power usage.
:param Q: quantization
:return: Emac, Ed, p
"""
return 3.6*10**-3*Q/16, 0.4608*(Q/16), 64*16/Q |
def logical_filter(l, logicals):
"""
Filter the list l down to the elements that correspond to the True
elements in the list logicals.
"""
return [val for (val, b) in zip(l, logicals) if b] |
def check_worker_retrieve_response(response):
"""
This function will verifies the worker retrieve response
"""
if response["result"]["workerType"] == 1:
err_cd = 0
else:
err_cd = 1
return err_cd |
def is_even_or_odd(n: int) -> bool:
"""
Check if the integer is even or odd.
>>> is_even_or_odd(0)
True
>>> is_even_or_odd(1)
False
>>> is_even_or_odd(2)
True
>>> is_even_or_odd(101)
False
"""
return n & 1 == 0 |
def combine_dicts(*post_dicts, **post_vars):
"""Combine positional parameters (dictionaries) and individual
variables specified by keyword into a single parameter dict.
"""
vars = dict()
for pars in post_dicts:
vars.update(pars)
vars.update(post_vars)
return vars |
def sortdict(dict):
"""
sort dictionaries by values
"""
return sorted(dict.items(), key=lambda x: x[1], reverse=True) |
def from_json(data_gen):
"""Get the json values. Return [[row]]"""
all_rows = []
# for current_dict in data_gen:
for current_dict in data_gen:
# current_dict = next(data_gen)
current_row = []
for value in current_dict.values():
# Parse values list into str
... |
def add_logs_to_table_heads(max_logs):
"""Adds log headers to table data depending on the maximum number of logs from trees within the stand"""
master = []
for i in range(2, max_logs + 1):
for name in ['Length', 'Grade', 'Defect']:
master.append(f'Log {i} {name}')
if i < max_logs... |
def configuration_str( configuration, prefix = '', suffix = '' ):
""" Return a string repr (with a prefix and/or suffix) of the configuration or '' if it's None """
if configuration is None:
return ''
return prefix + '[' + ' '.join( configuration ) + ']' + suffix |
def filter_prefix(dictionary, *prefixes):
"""Return dict with keys having any of the prefixes."""
if not prefixes:
return dictionary
out = {}
for key, value in dictionary.items():
if any(map(str(key).startswith, prefixes)):
out[key] = value
# may be empty
return out |
def get_patch_detail(patches):
"""
Iterate over patch details from the response and retrieve details of the patch.
:param patches: List of patch from response.
:return: List of detailed elements of patch
:rtype: list
"""
return [{
'Name': patch.get('name', ''),
'Url': patch.... |
def _urlescape(name):
"""Escape the given name for inclusion in a URL.
Escaping is done in the manner in which AutoDuck(?) seems to be doing
it.
"""
name = name.replace(' ', '_')\
.replace('(', '.28')\
.replace(')', '.29')
return name |
def solveMeFirst(a,b):
"""
Solve a and b.
Args:
a: (array): write your description
b: (array): write your description
"""
# Hint: Type return a+b below
return(a+b) |
def holes2string(hlist):
"""
if hlist is ('b4','c5') return 'b4c5'
"""
hstr = ""
for hn in hlist:
hstr = hstr+hn
return hstr.lower() |
def plugin_init(data):
""" Empty North Plugin """
_config = {}
return _config |
def tail(d, num_of_elements=5):
"""
get the "first" few (num) elements of a dict
"""
return {k: d[k] for k in list(d.keys())[-min(len(d), num_of_elements):]} |
def validate_params(url, depth, is_within_domain, formats):
"""
Validate the input from user
"""
flag = True
if not url:
flag = False
if not depth:
flag = False
if not formats:
flag = False
return flag |
def snspectralist(fname, logffname=None):
"""
List all the spectra files associated with a phosim instance catalog
"""
x = []
with open(fname, 'r') as f:
for line in f:
if 'spectra_file' in line:
x.append(line.split()[5])
return x |
def table_type_validator(type):
"""
Property: TableInput.TableType
"""
valid_types = [
"EXTERNAL_TABLE",
"VIRTUAL_VIEW",
]
if type not in valid_types:
raise ValueError("% is not a valid value for TableType" % type)
return type |
def fst(tup):
"""``fst :: (a, b) -> a``
Extract the first component of a pair.
"""
x, _y = tup
return x |
def replace_relative_links(soup,base_url,debug=False):
""" replaces relative link occurences starting with './' by base url """
# only extract hyperlinks with href atributte
if soup is None:
return None
links = soup.findAll('a', {"href" : True})
links_replaced = 0
for link in links: ... |
def get_novel_zwd_accessions(rfam_urs_accs, new_zwd_accs):
"""
Isolates all new ZWD URS accessions to imported to Rfam
with the use of python sets
rfam_urs_accs: A python dictionary with all Rfam URS accessions
new_zwd_accs: A python dictionary with all new ZWD URS candidates
return: A list o... |
def to_bytes(strlike, encoding="latin-1", errors="backslashreplace"):
"""Turns a str into bytes or leaves it alone.
The default encoding is latin-1 under the assumption that you have
obtained the str from to_str, applied some transformation, and want
to pass it back to the system.
"""
if isinsta... |
def check_permutation(str1: str, str2: str) -> bool:
"""
Determine if one string is a permutation of the other.
Args:
str1 (str): The first string.
str2 (str): The second string.
Returns:
bool: True if string one is a permutation of string two.
"""
# Check the lengths.... |
def get_complex(obj, key, default_value=""):
"""Get a value from the dictionary d by nested.key.value.
If keys contain periods, then use key=['a','b','c'] instead."""
if not obj or not isinstance(obj, dict):
return default_value
_data = obj
try:
parts = key.split(".") if isinstance(k... |
def shouldItBeMute(count):
"""
odd number of times toggle means its not muted
as initially it was muted
"""
return True if not count % 2 else False |
def nonchild(d):
""" Returns a copy of a dictionary where any key prefixed with "child:"
is removed.
"""
return {k: v for k, v in d.items() if not k.startswith('child:')} |
def int_from_byte(value: bytes) -> int:
"""Byte operation, 1 byte to int"""
return int.from_bytes(value, byteorder="big", signed=True) |
def other_heuristic(text, param_vals, metadata):
"""
Post-processing heuristic to handle the word "other"
"""
if ' other ' not in text and ' another ' not in text:
return text
if metadata['dataset'] == 'SHOP-VRB':
target_keys = {
'<Z>', '<W>', '<C>', '<M>', '<F>', '<S>',... |
def skip_row(datum, header):
"""Determine if a row has not been filled in for this sheet."""
values = [datum.get(key) for key in header]
return sum(1 for value in values if value) <= 4 |
def _construct_ws_obj(wsid, objid, is_public=False):
"""Test helper to create a ws_object vertex."""
return {
"_key": f"{wsid}:{objid}",
"workspace_id": wsid,
"object_id": objid,
"deleted": False,
"is_public": is_public,
} |
def escape_html_tags(text: str) -> str:
"""
Current escaping is a hotfix. The issue with replacement is that with a proper symbol escaping the message entities
(offset and length) should also be updated.
The hotfix idea is to remove special symbols and keep message length the same.
Proper escaping ... |
def remove_filename_in_path(path):
"""remove the file name from a path
Args:
path (str): complete path
Returns:
complete path without the file name
"""
if len(path.split("\\")) > 1:
splitter = "\\"
else:
splitter = "/"
path_list = path.split(splitter)[:-1]
... |
def is_issue_canceled(issue_list):
"""
Looks if any of the jira issues passed have the 'Canceled' status
:param issue_list: list of jira issues
:return: True or False
"""
for issue in issue_list:
if str(issue.fields.status) == 'Canceled':
return True
return F... |
def bytes_to_string(byte_value, precision):
"""
Creates a representation of a byte value as a string. This will find the most accurate unit to use
to display the byte value and return the string representation.
:param byte_value: A numerical value.
:param precision: The number of digits that should ... |
def human_seconds(interval):
"""Formats interval, a number of seconds, as a human-readable time
interval using English words.
"""
units = [
(1, 'second'),
(60, 'minute'),
(60, 'hour'),
(24, 'day'),
(7, 'week'),
(52, 'year'),
(10, 'decade'),
]
... |
def nick_that_sent_message(tags, prefix):
"""Returns a nick that sent the message based on the given data passed to
the callback.
"""
# 'tags' is a comma-separated list of tags that WeeChat passed to the
# callback. It should contain a tag of the following form: nick_XYZ, where
# XYZ is the nick... |
def dec_to_str(total):
"""Converts decimals to strings for more natural speech."""
if total == 0.125:
return "an eighth"
elif total == 0.25:
return "a quarter"
elif total == 0.5:
return "a half"
elif total == 0.75:
return "three quarters"
else:
if total % ... |
def factorial(value: int) -> int:
""" Calculates the factorial of the given value.
factorial
=========
The `factorial` function takes an positive integer value and calculates the
factorial (n! = n * (n - 1) * (n - 2) * ... * 3 * 2 * 1).
Parameters
----------
value: int
an positive inte... |
def smart_split(str, sep, lim, default=""):
"""
Split into at least lim elements using default value if needed.
"""
s = str.split(sep, lim - 1)
if len(s) < lim:
s.extend([default] * (lim - len(s)))
return s |
def split_val_condition(input_string):
"""
Split and return a {'value': v, 'condition': c} dict for the value
and the condition.
Condition is empty if no condition was found.
@param input A string of the form XXX @ YYYY
"""
try:
(value, condition) = [x.strip() for x in input_stri... |
def compute_average(grades):
"""
Computes the average of all the grades in the list
Parameters: grades (list)
Returns: the average (float) rounded up to one decimal
"""
average = round(sum(grades)/len(grades), 1)
return average |
def set_length(mag: str, unit: str, long: bool = False, sep: str = '-') -> str:
"""
Set the length of a number's unit string
"""
return ('', sep)[long].join(((mag[0], unit[0]), (mag, unit))[long]) |
def list_tester(user_list, session_list, watch_lists):
"""
:param user_list: The user list if they supplied one
:param session_list: The session attributes or persistent attributes
:param watch_lists: tuple of watch list aliases
:return: True if list is a custom list, False if watchlist
"""
... |
def readbinary(filename):
"""Given a filename, read a file in binary mode. It returns a single string."""
filehandle = open(filename, 'rb')
thisfile = filehandle.read()
filehandle.close()
return thisfile |
def trimstring(data):
"""Trims b- u- prefix"""
if isinstance(data, bytes):
return repr(data)[1:]
if isinstance(data, str):
return repr(data) |
def run_replace(block: str, replace_dict: dict) -> str:
"""Replace routine for dealing with n-grams.
:param block: Contains the text block replacement is done on
:param replace_dict: {token: replacement_token}
:return: Occurrences of token replaced with replacement_token
"""
for k in replace_d... |
def StringsContainSubstrings(strings, substrings):
"""Returns true if every substring is contained in at least one string.
Looks for any of the substrings in each string. Only requires each substring
be found once.
Args:
strings: List of strings to search for substrings in.
substrings: List of strings... |
def index_to_array(idx):
"""Simple inverse of array_to_index"""
return idx % 4, idx // 4 |
def collate_formed_groups(created_groups):
"""
Collates the created groups into a usable summary
collate_formed_groups(list(Group)) -> dict(int : int)
"""
collated_result = {}
for group in created_groups:
if group.get_size() not in collated_result:
collated_... |
def makePlotLabel(task, axis):
"""Build a pyplot label
Cuts the dataset to the range specified in the task.
If necessary, brings the data in ascending-x order
Args:
task (dict): contains xlabel, xunit, ylabel, yunit
axis (String): 'x' or 'y'
Returns:
String: plot lab... |
def get_rc_map(data):
""" Return mapping between row indices and column indices with existing values.
"""
rows = {}
for i, j in data:
s = rows.get (i)
if s is None:
s = rows[i] = set ()
s.add(j)
return rows |
def _replaced(__values, **__replacements):
"""
Replace elements in iterable with values from an alias dict, suppressing empty values.
Used to consistently enhance how certain fields are displayed in list and detail pages.
"""
return tuple(o for o in (__replacements.get(name, name) for name in __val... |
def is_int(value):
"""
test if a value (usually string) is a valid int
"""
try:
int(float(value))
return True
except:
return False |
def total_cost(J_content, J_style, alpha=10, beta=40):
"""
Computes the total cost function
Arguments:
J_content -- content cost coded above
J_style -- style cost coded above
alpha -- hyperparameter weighting the importance of the content cost
beta -- hyperparameter weighting the importance... |
def find_common_prefix(left: str, right: str) -> str:
"""DnC Divide & Conquer"""
min_len: int = min(len(left), len(right))
for idx in range(min_len):
if left[idx] != right[idx]:
return left[:idx]
return left[:min_len] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.