content stringlengths 42 6.51k |
|---|
def combine_values(*values):
"""Return the last value in *values* that is not ``None``.
The default combiner; good for simple values (booleans, strings, numbers).
"""
for v in reversed(values):
if v is not None:
return v
else:
return None |
def missing_digits(n):
"""Given a number a that is in sorted, increasing order,
return the number of missing digits in n. A missing digit is
a number between the first and last digit of a that is not in n.
>>> missing_digits(1248) # 3, 5, 6, 7
4
>>> missing_digits(1122) # No missing numbers
0
>>> missing_digits(123456) # No missing numbers
0
>>> missing_digits(3558) # 4, 6, 7
3
>>> missing_digits(35578) # 4, 6
2
>>> missing_digits(12456) # 3
1
>>> missing_digits(16789) # 2, 3, 4, 5
4
>>> missing_digits(19) # 2, 3, 4, 5, 6, 7, 8
7
>>> missing_digits(4) # No missing numbers between 4 and 4
0
>>> from construct_check import check
>>> # ban while or for loops
>>> check(HW_SOURCE_FILE, 'missing_digits', ['While', 'For'])
True
"""
"*** YOUR CODE HERE ***"
def cal_missing(x, y):
"""Calculate how many numbers between x and y.
x, y -- two single-digit number, and y is greater than x
>>> cal_missing(1, 1)
0
>>> cal_missing(2, 3)
0
>>> cal_missing(2, 8)
5 # 3, 4, 5, 6, 7, it has 5 numbers between 2 and 8
"""
if x == y:
return 0
else:
return y - x - 1
if n < 10:
return 0
else:
all_but_last, last = n // 10, n % 10
return missing_digits(all_but_last) + cal_missing(all_but_last % 10, last) |
def ptp_distance(x, y):
"""point to point distance"""
return 5*max(abs(x[0]-y[0]),abs(x[1]-y[1]),abs(x[2]-y[2])) |
def find_tweets_with_keywords(tweets, keywords, combination=1):
""" Tries to find tweets that have at least one of the keywords in them
:param tweets: The to be checked tweets
:param article: The article
:param combination: The minimal number of keywords that need to be in the tweet to select it
:return: A list of the ids that are in the article
"""
article_tweets = []
for tweet in tweets:
combi_number = 0
for keyword in keywords:
tweet_keywords = tweet.get_keywords()
if keyword in tweet_keywords:
combi_number += 1
if combi_number == combination:
article_tweets.append(tweet)
break
return article_tweets |
def check(a,n_list):
"""Returns the operation performed (such as append(),remove(),insert(),print(),etc) in the list if the operations are valid, -1 otherwise"""
#split the given string a
s = a.split()
#Check the length of splited String 'a'
#if length(s) == 1,it means string should be print,sort,pop and reverse
if len(s) == 1:
#check for print only
if s[0]=='print':
return eval(s[0]+'(' + 'n_list' + ')')
#if s contains other than 'print'
else:
return eval('n_list' + '.' + s[0] + '()')
#if length == 2, it means 's' contains either ['append','e'] or ['remove','e']
elif len(s) == 2:
return eval('n_list' + '.' + s[0] + '(' + s[1] + ')')
#if length == 3,it means 's' contains ['insert', 'i', 'e']
elif len(s) == 3:
return eval('n_list' + '.' + s[0] + '(' + s[1] + ',' + s[2] + ')')
#if invalid operations return -1
else:
return -1 |
def vLength(v):
""" Return Vector length """
return (v[0]*v[0] + v[1]*v[1] + v[2]*v[2]) ** 0.5 |
def hapax_legomena_ratio_extractor(word_tokens):
"""hapax_legomena_ratio
Counts word token occurs only once over total words in the text.
Words of different form are counted as different word tokens. The token.text presents only once in spaCy's doc
instance over "total_words" is counted.
Known differences with Writeprints Static feature "Ratio of hapax legomena": None.
Args:
word_tokens: List of lists of token.text in spaCy doc instances.
Returns:
Ratio of hapax legomena in the document.
"""
hapax_legomena_ratio = [
[
len([word for word in word_token if word_token.count(word) == 1])
/ len(set([word for word in word_token]))
]
for word_token in word_tokens
]
label = ["hapax_legomena_ratio"]
return hapax_legomena_ratio, label |
def calc_agg_polarsim(sim, sent_stance, sent_stance_conf, cfg):
"""Calculate the polar similarity value based on a (unipolar)
similarity rating and a sentence stance rating.
:param sim: float, a (unipolar) sentence similarity rating
:param sent_stance: a stance rating label. Must be either `agree`,
`disagree`, `unrelated` or `discuss`
:param sent_stance_conf: confidence value for the `sent_stance` label
:param cfg: configuration options
:returns: an updated similarity rating value, taking into account
:rtype:
"""
assert sim >= 0.0 and sim <= 1.0
if sent_stance is None:
sent_stance = 'unrelated'
assert sent_stance in ['agree', 'disagree', 'unrelated', 'discuss'], sent_stance
assert sent_stance_conf >= 0.0 and sent_stance_conf <= 1.0
# if stance is agree -> inc sim confidence, positive polarity
# if stance is disagree -> inc sim confidence, negative polarity
# if stance is discuss -> keep sim?, positive polarity
# if stance is unrelated -> dec sim confidence, positive polarity
if sent_stance in ['agree']:
return sim if (sim > sent_stance_conf) else (sent_stance_conf + sim)/2.0
elif sent_stance in ['disagree']:
return -sim if (sim > sent_stance_conf) else -(sent_stance_conf + sim)/2.0
elif sent_stance == 'unrelated':
factor = float(cfg.get('sentence_similarity_unrelated_factor', 0.9))
assert factor >= 0.0 and factor <= 1.0, factor
return sim * factor # not so similar after all
else: # discuss
factor = float(cfg.get('sentence_similarity_discuss_factor', 0.9))
assert factor >= 0.0 and factor <= 1.0, factor
return sim * factor |
def pyramid(number):
"""
Function that make a coefficient's list.
number: integer
return: list.
"""
_list = []
pyramids_number = number + 1
for times in range(pyramids_number):
string = str(times)
value_list = string * times
_list.append(value_list)
inverse = _list[::-1]
_list.extend(inverse)
_list.pop(pyramids_number)
_list.pop(0)
_list.pop(-1)
return _list |
def get_column_width_ignore_header(runs_str, idx):
""" returns the maximum width of the given column """
return max([len(r[idx]) for r in runs_str]) |
def transform_to_seconds(duration: str) -> float:
"""Transform string (with hours, minutes, and seconds) to seconds.
Args:
duration: Examples: '1m27s', '1m27.3s', '27s', '1h27s', '1h1m27s'
Raises:
Exception: If the input is not supported.
Returns:
Duration converted in seconds.
"""
h_split = duration.split("h")
if len(h_split) == 1:
rest = h_split[0]
hours = 0
else:
hours = int(h_split[0])
rest = h_split[1]
m_split = rest.split("m")
if len(m_split) == 2:
minutes = int(m_split[0])
seconds = float(m_split[1].rstrip("s"))
elif len(m_split) == 1:
minutes = 0
seconds = float(m_split[0].rstrip("s"))
else:
raise Exception(f"Unsupported duration: {duration}")
overall_seconds = hours * 60 * 60 + minutes * 60 + seconds
return overall_seconds |
def decode_offer_str(offer_str):
""" create a dictionary from offer_str in outputfile """
offer_dict = {}
try:
offer_strs = offer_str.split("|")
except:
return {}
for offer_str in offer_strs:
x = offer_str.split(":")
op = int(x[0])
vals = ":".join(x[1:])
if len(vals) == 0:
continue
offer_dict[op] = {}
for offer_entries in vals.split(";"):
try:
offer_at, v2 = offer_entries.split(":")
except:
continue
try:
v2 = int(v2)
except:
try:
v2 = float(v2)
except:
pass
offer_dict[op][offer_at] = v2
return offer_dict |
def strip_sbol2_version(identity: str) -> str:
"""Ensure that an SBOL2 or SBOL3 URI is an SBOL3 URI by stripping any SBOL2 version identifier
from the end to the URI
:param identity: URI to be sanitized
:return: URI without terminal version, if any
"""
last_segment = identity.split('/')[-1]
try:
_ = int(last_segment) # if last segment is a number...
return identity.rsplit('/', 1)[0] # ... then return everything else
except ValueError: # if last segment was not a number, there is no version to strip
return identity |
def normalize(x,min, max):
"""
Scale [min, max] to [0, 1]
Normalize x to [min, max]
"""
return (x - min) / (max - min) |
def is_sorted(lst):
"""Checks whether the input list is sorted."""
for i in range(len(lst) - 1):
if lst[i] > lst[i + 1]:
print(lst)
return False
return True |
def checksum_bytes(data):
"""Sum data, truncate to 8 bits"""
cs = sum(data) % 256
return cs |
def identify_unique_number(value: str) -> int:
"""
Identifies the corresponding value based on the number
This only works if the value is of length 2, 3, 4 or 7
"""
length = len(value)
if length not in (2, 3, 4, 7):
raise ValueError("Value can only be identified if it's length is 2, 3, 4 or 7")
elif length == 2:
return 1
elif length == 3:
return 7
elif length == 4:
return 4
else:
return 8 |
def compute(input_string):
"""Perform simple arithmetic based on string input.
Example: '5 + 7' -> 12
"""
values = input_string.split(' ')
num0 = int(values[0])
operator = values[1]
num1 = int(values[2])
if operator == '+':
return num0 + num1
elif operator == '-':
return num0 - num1
elif operator == '*':
return num0 * num1
elif operator == '/':
return num0 / num1
else:
msg = f"Unknown operator: '{operator}'\n"
msg += "choose from '+' and '-'."
raise ValueError(msg) |
def ArchForAsmFilename(filename):
"""Returns the architectures that a given asm file should be compiled for
based on substrings in the filename."""
if 'x86_64' in filename or 'avx2' in filename:
return ['x86_64']
elif ('x86' in filename and 'x86_64' not in filename) or '586' in filename:
return ['x86']
elif 'armx' in filename:
return ['arm', 'aarch64']
elif 'armv8' in filename:
return ['aarch64']
elif 'arm' in filename:
return ['arm']
elif 'ppc' in filename:
return ['ppc64le']
else:
raise ValueError('Unknown arch for asm filename: ' + filename) |
def lengthOfLastWord(s):
"""
:type s: str
:rtype: int
"""
if not s:
return 0
try:
return len(s.split()[-1])
except:
return 0 |
def merge_dicts(*dict_args):
"""
Given any number of dicts, shallow copy and merge into a new dict.
Report error on conflicting keys.
"""
result = {}
for dictionary in dict_args:
for key, value in dictionary.items():
if key in result and result[key] != value:
raise ValueError('Conflicting definitions for', key)
result[key] = value
return result |
def clean_string(string: str) -> str:
"""
input -> output
"updatedAt" -> "updated_at"
"UpdatedAt" -> "updated_at"
"base URL" -> "base_url"
"UPdatedAt" -> "u_pdated_at"
"updated_at" -> "updated_at"
" updated_at " -> "updated_at"
"updatedat" -> "updatedat"
"""
abbreviations = ("URL", "GUID", "IP")
if any(map(lambda w: w in string, abbreviations)):
return string.lower().replace(" ", "_")
return "".join("_" + c.lower() if c.isupper() else c for c in string if c != " ").strip("_") |
def indent(
text, # Text to indent
char=' ', # Character to use in indenting
indent=2 # Repeats of char
):
"""
Indent single- or multi-lined text.
"""
prefix = char * indent
return "\n".join([prefix + s for s in text.split("\n")]) |
def io_table_header(io_params, io_prefixes):
"""podmd
podmd"""
header_labs = [ ]
for collection, pars in io_params.items():
if 'non_collection' in collection:
collection = ''
else:
collection += '.'
for par in pars.keys():
header_labs.append( collection+par )
for collection, pres in io_prefixes.items():
for pre in pres:
header_labs.append( collection+pre+"::id" )
header_labs.append( collection+pre+"::label" )
return header_labs |
def history_join(old_history, new_history):
"""Join two history dicts"""
if not old_history:
return new_history
if not new_history:
return old_history
history = old_history
for key in history:
history[key].extend(new_history[key])
return history |
def nsrGenera(taxonList, synonymList):
""" Extracts the unique genera from both taxonomy and synonym lists.
Combines the scientific names of obtained taxonomy and synonyms to
one list, filtering out empty lines. Selects all unique genera.
Arguments:
species: Scientific notation of all species and known synonyms
Return:
generaList: List of all unique genera
"""
species = list(filter(None, sorted(taxonList + synonymList)))
generaList = [i.split()[0] for i in species]
generaList = list(dict.fromkeys(generaList))
return generaList |
def curve_between(
coordinates, start_at, end_at, start_of_contour, end_of_contour):
"""Returns indices of a part of a contour between start and end of a curve.
The contour is the cycle between start_of_contour and end_of_contour,
and start_at and end_at are on-curve points, and the return value
is the part of the curve between them.
Args:
coordinates: An slicable object containing the data.
start_at: The index of on-curve beginning of the range.
end_at: The index of on-curve end of the range.
start_of_contour: The index of beginning point of the contour.
end_of_contour: The index of ending point of the contour.
Returns:
A list of coordinates, including both start_at and end_at. Will go around
the contour if necessary.
"""
if end_at > start_at:
return list(coordinates[start_at:end_at + 1])
elif start_of_contour == end_of_contour: # single-point contour
assert start_at == end_at == start_of_contour
return [coordinates[start_at]]
else: # the curve goes around the range
return (list(coordinates[start_at:end_of_contour + 1]) +
list(coordinates[start_of_contour:end_at + 1])) |
def insert_tag(name: str, tag: str) -> str:
"""inserts tag name right before the filename:
insert_tag('ex11','some_tag') -> 'some_tag/ex11'
insert_tag('solutions/ex11','some_tag') -> 'solutions/some_tag/ex11'
"""
name_split = name.split("/")
name_split.insert(-1, tag)
return "/".join(name_split) |
def get_common_introduced(db_entry, arches):
"""Returns the common introduction API level or None.
If the symbol was introduced in the same API level for all architectures,
return that API level. If the symbol is not present in all architectures or
was introduced to them at different times, return None.
"""
introduced = None
for arch in arches:
introduced_tag = 'introduced-' + arch
if introduced_tag not in db_entry:
return None
if introduced is None:
introduced = db_entry[introduced_tag]
elif db_entry[introduced_tag] != introduced:
return None
# Else we have the symbol in this arch and it's the same introduction
# level. Keep going.
return introduced |
def wait(time,duration,*args):
"""
Delay a command.
instead of executing it at the time specified, add a delay and then execute
"""
duration = int(duration,10)
cmd = '"'+('" "'.join(args))+'"'
return [(time+duration,cmd)] |
def ran_check(num, low, high):
"""
Write a function that checks whether a number is in a given range
(inclusive of high and low)
ran_check(5,2,7)-> 5 is in the range between 2 and 7
"""
if num in range(low, high + 1):
return '{} is in the range between {} and {}'.format(num, low, high)
else:
return 'The number is outside the range' |
def filter_horizontal_edges(edges, normal):
""" Determine edges that are horizontal based on a normal value """
res = []
rnd = lambda val: round(val, 3)
for e in edges:
if normal.z:
s = set([rnd(v.co.y) for v in e.verts])
else:
s = set([rnd(v.co.z) for v in e.verts])
if len(s) == 1:
res.append(e)
return res |
def update_yaml_versions(yaml_versions, json_versions):
"""
Update the versions dictionnary to be printed in YAML with values from
the JSON versions dictionnary found in versions.json.
:param yaml_versions: versions dict to be printed in YAML format
:type yaml_versions: dict
:param json_versions: versions dict in JSON format
:type json_versions: dict
:return: versions dict to be printed in YAML format
:rtype: dict
"""
if json_versions.get('services', False):
for service in json_versions['services']:
version, url = [(v, u) for (v, u) in service['versions'].items()
if v == service['default']][0]
yaml_versions['services'].update({
service['name']: {
"version": version,
"url": url
}
})
if json_versions.get('platforms', False):
for platform in json_versions['platforms']:
version, resources = [(v, r) for (v, r)
in platform['versions'].items()
if v == platform['default']][0]
platform_resources = {}
for item in resources:
url = [r for r in json_versions['resources']
if r['name'] == item['resource']][0]['versions'][
item['version']]
platform_resources.update({
item['resource']: {
'version': item['version'],
'url': url
}
})
yaml_versions['platform'].update({
platform['name']: {
'version': version,
'resources': platform_resources
}
})
return yaml_versions |
def getFirstMatching(values, matches):
"""
Return the first element in :py:obj:`values` that is also in
:py:obj:`matches`.
Return None if values is None, empty or no element in values is also in
matches.
:type values: collections.abc.Iterable
:param values: list of items to look through, can be None
:type matches: collections.abc.Container
:param matches: list of items to check against
"""
assert matches is not None
if not values:
return None
return next((i for i in values if i in matches), None) |
def laxfilt(items, keymap, sep='.'):
"""
Like filt(), except that KeyErrors are not raised.
Instead, a missing key is considered to be a mismatch.
For example:
items = [
{'name': 'foo', 'server': {'id': 1234, 'hostname': 'host1'}, 'loc': 4, 'yyy': 'zzz'},
{'name': 'bar', 'server': {'id': 2345, 'hostname': 'host2'}, 'loc': 3},
{'name': 'baz', 'server': {'id': 3456, 'hostname': 'host3'}, 'loc': 4},
]
filt(items, {'yyy': 'zzz'}) # Raises KeyError
laxfilt(items, {'yyy': 'zzz'}) # Returns [foo]
"""
filtered = []
for item in items:
for keypath in keymap:
ok = True
val = item.copy()
for key in keypath.split(sep):
try:
val = val[key]
except KeyError:
ok = False
break
if not ok or val != keymap[keypath]: break
else:
filtered.append(item)
return filtered |
def get_user_first_name(data):
"""
Method to extract a newly added user's first name
from telegram request
"""
try:
first_name = data['message']['new_chat_member']['first_name']
return first_name
except KeyError:
exit |
def sans_ns(tag):
"""Remove the namespace prefix from a tag."""
return tag.split("}")[-1] |
def get_plist_key(plist_file, key):
"""
Returns the value of a given plist key, given the JSON encoded equivalent
of a plist file (this goes hand in hand with read_plist)
"""
try:
return plist_file[key]
except (KeyError, TypeError):
return False |
def _removeSingleMemberGroupReferences(kerning, leftGroups, rightGroups):
"""
Translate group names into glyph names in pairs
if the group only contains one glyph.
"""
new = {}
for (left, right), value in kerning.items():
left = leftGroups.get(left, left)
right = rightGroups.get(right, right)
new[left, right] = value
return new |
def access_list_list(config_list):
"""extracts access-lists from provided configuration list ie.config_list.
returns access-lists lines in a list
"""
return [line.rstrip() for line in config_list if line.startswith("access-list ")] |
def alpha_ordering(index, collection):
"""
0 -> A, 1 -> B, ... 25 -> Z, 26 -> AA, 27 -> AB, ...
"""
s = ""
while index > 25:
d = index / 26
s += chr((d % 26) + 64)
index -= d * 26
s += chr(index + 65)
return s |
def calculate_check_digit(data):
"""Calculate MRZ check digits for data.
:data data: Data to calculate the check digit of
:returns: check digit
"""
values = {
"0": 0, "1": 1, "2": 2, "3": 3, "4": 4, "5": 5,
"6": 6, "7": 7, "8": 8, "9": 9, "<": 0, "A": 10,
"B": 11, "C": 12, "D": 13, "E": 14, "F": 15, "G": 16,
"H": 17, "I": 18, "J": 19, "K": 20, "L": 21, "M": 22,
"N": 23, "O": 24, "P": 25, "Q": 26, "R": 27, "S": 28,
"T": 29, "U": 30, "V": 31, "W": 32, "X": 33, "Y": 34, "Z": 35,
}
weights = [7, 3, 1]
total = 0
for counter, value in enumerate(data):
total += weights[counter % 3] * values[value]
return str(total % 10) |
def scale_frequencies(lo, hi, nyq):
"""
Scales frequencies in Hz to be between [0,1], 1 = nyquist frequency.
"""
lo = lo / nyq
hi = hi / nyq
return lo, hi |
def _fib_rec(n):
""" Calculate nth Fibonacci number using Binet's Method. Assumes
Fib(0) = Fib(1) = 1.
Args:
n integer
Returns:
tuple (Fib(n), Fib(n-1))
Preconditions:
n >= 0
"""
(f1, f2), i = (1, 0), 31
while i >= 0:
if (n >> i) > 0:
f1, f2 = f1**2 + f2**2, f2 * (2*f1 - f2)
if (n >> i) % 2 == 1:
f1, f2 = f1 + f2, f1
i -= 1
return f1, f2 |
def join_paths(*args):
"""Join paths without duplicating separators.
This is roughly equivalent to Python's `os.path.join`.
Args:
*args (:obj:`list` of :obj:`str`): Path components to be joined.
Returns:
:obj:`str`: The concatenation of the input path components.
"""
result = ""
for part in args:
if part.endswith("/"):
part = part[-1]
if part == "" or part == ".":
continue
result += part + "/"
return result[:-1] |
def get_default_readout(n_atom_basis):
"""Default setting for readout layers. Predicts only the energy of the system.
Args:
n_atom_basis (int): number of atomic basis. Necessary to match the dimensions of
the linear layer.
Returns:
DEFAULT_READOUT (dict)
"""
DEFAULT_READOUT = {
'energy': [
{'name': 'linear', 'param' : { 'in_features': n_atom_basis, 'out_features': int(n_atom_basis / 2)}},
{'name': 'shifted_softplus', 'param': {}},
{'name': 'linear', 'param' : { 'in_features': int(n_atom_basis / 2), 'out_features': 1}}
]
}
return DEFAULT_READOUT |
def flatten_json(b, delim):
"""
A simple function for flattening JSON by concatenating keys w/ a delimiter.
"""
val = {}
for i in b.keys():
if isinstance(b[i], dict):
get = flatten_json(b[i], delim)
for j in get.keys():
val[i + delim + j] = get[j]
else:
val[i] = b[i]
return val |
def apple_url_fix(url):
"""
Fix Apple URL.
:param url: URL to fix
:return: fixed URL
"""
if url.startswith("webcal://"):
url = url.replace('webcal://', 'http://', 1)
return url |
def rangify(value):
"""Return a range around a given number."""
span = 5
min_val = max(value - span, 1)
max_val = max(value + span, span * 2)
return range(min_val, max_val) |
def escape(string, quote=True):
"""Returns a string where HTML metacharacters are properly escaped.
Compatibility layer to avoid incompatibilities between Python versions,
Qt versions and Qt bindings.
>>> import silx.utils.html
>>> silx.utils.html.escape("<html>")
>>> "<html>"
.. note:: Since Python 3.3 you can use the `html` module. For previous
version, it is provided by `sgi` module.
.. note:: Qt4 provides it with `Qt.escape` while Qt5 provide it with
`QString.toHtmlEscaped`. But `QString` is not exposed by `PyQt` or
`PySide`.
:param str string: Human readable string.
:param bool quote: Escape quote and double quotes (default behaviour).
:returns: Valid HTML syntax to display the input string.
:rtype: str
"""
string = string.replace("&", "&") # must be done first
string = string.replace("<", "<")
string = string.replace(">", ">")
if quote:
string = string.replace("'", "'")
string = string.replace("\"", """)
return string |
def constrain(value, lowest, highest):
"""Test whether `value` is within the range `(highest, lowest)`.
Return `value` if it is inside the range, otherwise return
`highest` if the value is *above* the range or `lowest` it the value
is *below* the range.
>>> constrain(-1, 2, 5)
2
>>> constrain(1, 2, 5)
2
>>> constrain(0, 2, 5)
2
>>> constrain(2, 2, 5)
2
>>> constrain(3, 2, 5)
3
>>> constrain(5, 2, 5)
5
>>> constrain(6, 2, 5)
5
>>> constrain(10, 2, 5)
5
"""
return min(highest, max(value, lowest)) |
def _is_basic_type(s):
"""
Helper function used to check if the value of the type attribute is valid
:param s: the str value in the type attribute
:type s: str
:return: `True` if the str value is valid, else return `False`
:rtype: bool
"""
s = s.strip().casefold()
if s in ["objectid", "int", "integer", "float", "double", "bool", "boolean", "str", "string", "list", "dict", "bytes", "byte", "object"]:
return True
return False |
def mangle_string(string):
"""
Turns an arbitrary string into a decent foldername/filename
(no underscores allowed)!
"""
string = string.replace(' ', '-')
string = string.strip(",./;'[]\|_=+<>?:{}!@#$%^&*()`~")
string = string.strip('"')
return string |
def is_node_locked(node):
"""Check if node is locked. Implementation level LOL.
"""
r = False
if "isHardLocked" in dir(node):
r = node.isHardLocked()
elif "isLocked" in dir(node):
r = node.isLocked()
return r |
def whittle_dict(d, keys):
"""
Returns D2, containing just the KEYS from dictionary D,
e.g.
whittle_dict({'a': 100, 'b': 200}, ['a']) -> {'a': 100}
Will raise an exception if any of KEYS aren't keys in D.
xxx - maybe this should instead do a copy, and delete any not needed???
"""
d2 = {}
for k in keys:
d2[k] = d[k]
return d2 |
def f(integer):
"""
factorcalc.f(int > 0) -> list of int -- provides a list of all the factors of the first argument
"""
if type(integer)==int:
if integer>0:
possible_factors=[integer]
possible_factor=integer-1
for i in range(integer):
possible_factors.append(possible_factor)
possible_factor-=1
possible_factors.remove(0)
index=0
factors=[]
for i in possible_factors:
if str(integer/possible_factors[index]).endswith('0'):
factors.append(possible_factors[index])
index+=1
return factors
else:
raise ValueError('first argument must be > 0')
else:
raise TypeError('first argument must be <class \'int\'> (not '+str(type(integer))+')') |
def makeMushedKey(row):
""""Return a unique key based on a row, sortcat+name+edition+condition+foil+cardNumber"""
return row["SortCategory"] + "-" + row["Name"] + "-" + row["Edition"] + "-" + row["Condition"] + "-" + str(row["CardNumber"]) + "-" + str(row["IsFoil"]) |
def locateSquareHelper(x):
"""
Helps find square units, the nine 3x3 cells in a puzzle, in which a cell is in.
Input
x : row or column index of the cell in the puzzle.
Output
x : location of square unit, specifically the first cell of the unit.
"""
if x < 6:
if x < 3:
x = 0
else:
x = 3
else:
x = 6
return x |
def set_gpu_entry(entry_information, want_whole_node):
"""Set gpu entry
Args:
entry_information (dict): a dictionary of entry information from white list file
Returns:
dict: a dictionary of entry information from white list file with gpu settings
"""
if "attrs" not in entry_information:
entry_information["attrs"] = {}
if "GLIDEIN_Resource_Slots" not in entry_information["attrs"]:
if want_whole_node:
value = "GPUs,type=main"
else:
value = "GPUs," + str(entry_information["submit_attrs"]["Request_GPUs"]) + ",type=main"
entry_information["attrs"]["GLIDEIN_Resource_Slots"] = {"value": value}
return entry_information |
def bsi(items, value):
"""Returns the middle index if value matches, otherwise -1"""
lo = 0
hi = len(items) - 1
while lo <= hi:
mid = int((lo + hi) / 2)
if items[mid] == value:
return mid
elif items[mid] < value:
lo = mid + 1
else:
hi = mid - 1
return -1 |
def bubble(L, swap=None):
"""Bubble sort function
Parameters:
L (list): Unsorted (eventually sorted) list.
swap (boolean): Whether list's elements have been swapped before, serves as an indicator on whether we're done sorting.
Returns:
L (list): Sorted list.
"""
print(f'{L} : {swap}')
if len(L) == 0:
return L
if swap == True or swap == None:
i = 0
swap = False
while i < len(L):
ii = i + 1
if L[i] > L[ii]:
(L[i], L[ii]) = (L[ii], L[i])
swap = True
i += 1
if i == len(L)-1:
return bubble(L, swap)
else:
return L |
def get_path_part_from_sequence_number(sequence_number, denominator):
"""
Get a path part of a sequence number styled path (e.g. 000/002/345)
Args:
sequence_number (int): sequence number (a positive integer)
denominator (int): denominator used to extract the relevant part of a path
Returns:
str: part of a path
"""
return '{:03d}'.format(int(sequence_number / denominator))[-3:] |
def range_squared(n):
"""Computes and returns the squares of the numbers from 0 to n-1."""
squares = []
for k in range(n):
squares.append(k ** 2)
return squares |
def degrees_to_kilometers_lat(degrees: int) -> float:
"""
Convert degrees of longitude into kilometres
:param degrees:
:return:
"""
return (63567523 * degrees / 90) / 1000 |
def _cleanup_non_fields(terms):
"""Removes unwanted fields and empty terms from final json"""
to_delete = ['relationships', 'all_parents', 'development',
'has_part_inverse', 'develops_from',
'closure', 'closure_with_develops_from',
'achieves_planned_objective', 'part_of' # these 2 should never be present
]
tids2delete = []
for termid, term in terms.items():
if not term:
tids2delete.append(termid)
else:
for field in to_delete:
if field in term:
del term[field]
for tid in tids2delete:
del terms[tid]
return terms |
def get_total_tiles(min_zoom: int, max_zoom: int) -> int:
"""Returns the total number of tiles that will be generated from an image.
Args:
min_zoom (int): The minimum zoom level te image will be tiled at
max_zoom (int): The maximum zoom level te image will be tiled at
Returns:
The total number of tiles that will be generated
"""
return int(sum([4 ** i for i in range(min_zoom, max_zoom + 1)])) |
def solution2(nums):
"""
Efficient solution written by other guy
---
:type nums: list[int]
:rtype: list[int]
"""
output = []
for num in nums:
# Same number in the array must conduct to the same index
# And we should note that the number is always between 1 and n
idx = abs(num) - 1
if nums[idx] < 0:
output.append(idx + 1)
nums[idx] *= -1
return output |
def _unprefix_attrs(value):
"""Internally, nested objects are stored in attrs prefixed with `_`, and wrapped in a @property.
This recursively removes the `_` prefix from all attribute names.
"""
if isinstance(value, (list, tuple)):
return [_unprefix_attrs(v) for v in value]
elif not isinstance(value, dict):
return value
value = value.copy()
for k in [k for k in value if k.startswith('_')]:
value[k.lstrip('_')] = _unprefix_attrs(value.pop(k))
return value |
def abbrev(term_list):
"""Given a list of terms, return the corresponding list of abbreviated terms."""
abbrev_dict = {"Point": "Pt",
"ProperInterval": "PInt",
"Interval": "Int",
"Region": "Reg"}
return '|'.join([abbrev_dict[term] for term in term_list]) |
def parse_ID_from_query_comment(comment):
"""
Parses the NCBI-specific ID from the comment reported by the Mash match. The comment will look something like:
[1870 seqs] NC_004354.4 Drosophila melanogaster chromosome X [...]
and this function will return the "NC_004354.4" part of the comment. This function is -VERY- specific to the
formatting of a particular Mash (RefSeq) database.
PARAMETERS:
comment (str): the query comment to parse
RETURNS:
id (str): the NCBI-specific ID parsed from the passed comment
"""
line = comment.strip()
# Check for the optional [# seqs] at the start of line:
if line.startswith("["):
tokens = line.split("] ")
line = tokens[1].strip() # Grabbing everything after the "[# seqs] "
id = line.split(" ")[0]
return id |
def isjpeg(filename):
"""
Returns true if filename has jpeg file extension
:param filename:
:return:
"""
jpeg_exts = ['jpg', 'jpeg']
if '.' not in filename:
return False
return filename.split('.')[-1].lower() in jpeg_exts |
def longest_subseq(arr):
"""
Given an array of integers, find the length of the longest sub-sequence
such that elements in the sub-sequence are consecutive integers,
the consecutive numbers can be in any order.
>>> longest_subseq([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
10
>>> longest_subseq([10, 9, 8, 7, 6, 5, 4, 3, 2, 1])
10
>>> longest_subseq([])
0
>>> longest_subseq([1])
1
>>> longest_subseq([1,3,5,7,9])
1
>>> longest_subseq([1,3,5,7,9,10])
2
>>> longest_subseq([1, 9, 87, 3, 10, 4, 20, 2, 45])
4
>>> longest_subseq([36, 41, 56, 35, 91, 33, 34, 92, 43, 37, 42])
5
"""
if not arr:
return 0
sorted_array = sorted(arr)
max_length = 1
current_length = 1
last = sorted_array[0]
for i in sorted_array[1:]:
if i == last + 1:
current_length += 1
if current_length > max_length:
max_length = current_length
else:
current_length = 1
last = i
return max_length |
def update(old, new):
"""Updates the old value with the new value
Args:
old: old value to update
new: new value with updates
Returns:
updated old value
"""
old.update(new)
return old |
def convert_ip(address) :
""" Converts IP to bytes
:param str address: IP address that should be converted to bytes
:return bytes: IP converted to bytes format
"""
res = b""
for i in address.split("."):
res += bytes([int(i)])
return res |
def calculate_max_width(poly):
"""
Calculate the maximum width of a polygon and
the cooresponding y coordinate of the vertex used to calculate the maximum width
Input
poly: a set of vertices of a polygon
Ouput
width_y: the y coordinate of the vertex used to calculate the maximum width
"""
width = 0
width_y = 0
for p0 in poly:
x0, y0 = p0[0], p0[1]
for i in range(len(poly)):
x1, y1 = poly[i-1][0], poly[i-1][1]
x2, y2 = poly[i][0], poly[i][1]
if y0 == y1 == y2:
if abs(x1 - x2) > width:
width = abs(x1 - x2)
width_y = y0
elif y0 != y1 != y2:
x = (y0 - y2)/(y1 - y2) * (x1 - x2) + x2
if x > x0 and x - x0 > width:
width = x - x0
width_y = y0
return width_y |
def data_calculation(sites):
"""
param sites: list of website data.
Returns the total of all site values.
"""
total = 0
for data_item in sites:
total += data_item['value']
return total |
def parse_reward_values(reward_values):
"""
Parse rewards values.
"""
values = reward_values.split(',')
reward_values = {}
for x in values:
if x == '':
continue
split = x.split('=')
assert len(split) == 2
reward_values[split[0]] = float(split[1])
return reward_values |
def common_prefix(l):
"""
Return common prefix of the stings
>>> common_prefix(['abcd', 'abc1'])
'abc'
"""
commons = []
for i in range(min(len(s) for s in l)):
common = l[0][i]
for c in l[1:]:
if c[i] != common:
return ''.join(commons)
commons.append(common)
return ''.join(commons) |
def strip_right_multiline(txt: str):
"""Useful for prettytable output where there is a lot of right spaces,"""
return '\n'.join([x.strip() for x in txt.splitlines()]) |
def filter_dict(fl, vocab):
"""Removes entries from the :param fl: frequency list not appearing in :param vocab:."""
out = {}
for k, v in fl.items():
if k in vocab:
out[k] = v
return out |
def remove_encoding_indicator(func_string):
"""
In many functions there is a following "A" or "W" to indicate unicode or ANSI respectively that we want to remove.
Make a check that we have a lower case letter
"""
if (func_string[-1] == 'A' or func_string[-1] == 'W') and func_string[-2].islower():
return func_string[:-1]
else:
return func_string |
def mock_walk(examples_folder):
"""Mock the os.walk function to return a single file."""
folder_list = []
file_list = ["metadata.yaml"]
return [("", folder_list, file_list)] |
def _is_chief(task_type, task_id):
"""Determines if the replica is the Chief."""
return task_type is None or task_type == 'chief' or (
task_type == 'worker' and task_id == 0) |
def _int_if_possible(string):
"""
PRIVATE METHOD
Tries to convert a string to an integer, falls back to the original value
"""
try:
return int(string)
except ValueError:
return string |
def divider(string):
"""Inserts a Verilog style divider into a string"""
return '\n// ' + '-' * 70 + '\n// ' + string + '\n// ' + '-' * 70 + '\n' |
def get_server_cyverse_push_config(config:dict):
"""
takes a config dictionary and returns the variables related to server deployment (push to CyVerse).
If there is any error in the configuration, returns a quadruple of -1 with a console output of the exception
"""
try:
server = config["DataTransfer"]["server"]
intersection = config["DataTransfer"]["intersection"]
startHour = config["DataTransfer"]["StartTime_PushToCyverse"]["hour"]
startMinute = config["DataTransfer"]["StartTime_PushToCyverse"]["minute"]
return server, intersection, startHour, startMinute
except Exception as e:
print(e)
return -1, -1, -1, -1 |
def linear_interpolation(x, x_0, x_1, y_0, y_1):
""" return the linearly interpolated value between two points """
return y_0+(x-x_0)*(y_1-y_0)/(x_1 - x_0) |
def find_appendix(filename):
"""if filename contains suffix '_old' or '_new', remember it to add it to sequence ID
"""
if "_new." in filename:
appendix = "_new"
elif "_old." in filename:
appendix = "_old"
else:
appendix = ""
return appendix |
def get_accuracy(class_metrics, N):
"""
Get accuracy as total # of TP / total # of samples
:param class_metrics : Map from class name to metrics (which are map from TP, TN, FP, FN to values)
:param N: total number of samples
"""
if N == 0:
return 0
TP_total = 0
for class_name in class_metrics.keys():
metrics = class_metrics[class_name]
TP = metrics["TP"]
TP_total += TP
return TP_total / N |
def have_common_elements(first_list, second_list):
"""
Retuns True if all the elements in the first list are also in the second.
:param list[T] first_list:
:param list[T] second_list:
:return: True if lists are the same, else False
"""
return len(set(first_list).intersection(
set(second_list))) == len(second_list) |
def return_to_string(msg):
"""
Return a string of the encoded message
@type msg: [int]
@rtype: str
"""
returned_str = ""
for char in msg:
returned_str += chr(char + 65)
return returned_str |
def filter_dict(d, *keys):
"""Filter keys from a dictionary."""
f = {}
for k, v in d.items():
if k in keys:
f[k] = v
return f |
def dictflip(dictionary):
"""
Flip the names and keys in a dictionary.
This means that this:
{'key1': 'value1', 'key2': 'value2'}
will be converted into this:
{'value1': 'key1', 'value2': 'key2'}
:type dictionary: dictionary
:param dictionary: The dictionary to flip.
"""
return {v: k for k, v in dictionary.items()} |
def add_color(value: str) -> str:
"""
Modifies the value from the parameter to a colored version of itself
Args:
value: str: the value of a particular position on the gameboard
Returns:
str: returns a string containing the value at the coord in the matching color
"""
color = ''
if value == 'M':
color = '\033[0;31mM\033[0m'
elif value in ('F','?'):
color = '\033[1;33m'+value+'\033[0m'
elif value == '1':
color = '\033[0;34m'+value+'\033[0m'
elif value == '2':
color = '\033[0;32m'+value+'\033[0m'
elif value == '3':
color = '\033[1;31m'+value+'\033[0m'
elif value == '4':
color = '\033[0;35m'+value+'\033[0m'
elif value == '5':
color = '\033[0;33m'+value+'\033[0m'
elif value == '6':
color = '\033[0;36m'+value+'\033[0m'
elif value == '7':
color = '\033[1;30m'+value+'\033[0m'
elif value == '8':
color = '\033[0;37m'+value+'\033[0m'
else: #0
return value
return color |
def sphinx_doi_link(doi):
"""
Generate a string with a restructured text link to a given DOI.
Parameters
----------
doi : :class:`str`
Returns
--------
:class:`str`
String with doi link.
"""
return "`{} <https://dx.doi.org/{}>`__".format(doi, doi) |
def _set(iterable):
"""Return a set from an iterable, treating multicharacter strings as one element."""
if type(iterable) is str:
return set() if iterable == '' else {iterable}
else: return set(iterable) |
def blending(f, coal, biomass):
"""
f : float
%wt biomass in coal-biomass blend
"""
return (1.0 - f)*coal + (f)*biomass |
def RPL_WHOREPLY(sender, receipient, message):
""" Reply Code 352 """
return "<" + sender + ">: " + message |
def version_greater_or_equal_to(version, min_version):
"""Compares two version strings and returns True if version > min_version
>>> version_greater_or_equal_to('1.0', '0')
True
>>> version_greater_or_equal_to('1.0', '0.9.9.9')
True
>>> version_greater_or_equal_to('1.0', '2.0')
False
>>> version_greater_or_equal_to('0.9.9.9', '1.0')
False
>>> version_greater_or_equal_to('1.0', '1.0')
True
>>> version_greater_or_equal_to('9.8.7.6.5.4.32.1', '9.8.7.6.5.4.3.1')
True
"""
for i in range(0, min(len(min_version), len(version))):
if version[i] < min_version[i]:
return False
elif version[i] > min_version[i]:
return True
# if equal we need to check the next least-significant number
# All checked numbers were equal, but version could be smaller if it is
# shorter, e.g. 2.4 < 2.4.1
return len(version) <= len(min_version) |
def str2bool(pstr):
"""Convert ESRI boolean string to Python boolean type"""
return pstr == 'true' |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.