content stringlengths 42 6.51k |
|---|
def build_search(model: str) -> str:
"""Build search for craigslist"""
car = ""
search = model.split()
if len(search) <= 1:
pass
else:
for item in range(len(search) - 1):
car = car + search[item] + "%20"
return car + search[-1] |
def duplicate(A):
"""Find the duplicate in the array."""
n = len(A)
total = (n)*(n+1)//2
sum_A = sum(set(A))
missing_value = total - sum_A
return A[missing_value-1] |
def getcount(inputstr):
"""Function counts num of vowels in string."""
vowels = ['a', 'e', 'i', 'o', 'u']
count = 0
for letter in inputstr:
if letter in vowels:
count += 1
return(count) |
def binary_search(a, key):
"""Meguru type binary search"""
ng = -1
ok = len(a)
def is_ok(a, key, idx):
if key <= a[idx]:
return True
else:
return False
while (abs(ok - ng) > 1):
mid = (ok + ng) // 2
if is_ok(a, key, mid):
ok = mid... |
def add_integer(a, b=98):
"""function to add a and b"""
if isinstance(a, (int, float)) and isinstance(b, (int, float)):
return int(a) + int(b)
else:
raise TypeError("{:} must be an integer"
.format('b' if isinstance(a, (int, float)) else 'a')) |
def cigar_num_matches(pairs):
"""
Are there non-match/mismatch symbols in cigar?
:param pairs:
:return: bool
"""
total = 0
for c, i in pairs:
if c in ["="]:
total += i
return total |
def interval_to_list(interval):
"""Convert interval string to list of number
'1-4'
Returns:
[1, 2, 3, 4]
"""
elements = [e.strip().split('-') for e in interval.split(',')]
return [n for r in elements for n in range(int(r[0]), int(r[-1])+1)] |
def get_last_test_result(release):
"""
:param release: helm release metadata
:return: whether tests are successful (no tests defined implies success)
"""
test_hooks = (
hook for hook in release.get('hooks', []) if any(
e in ['test', 'test-success'] for e in hook['events']))
... |
def parser_rar_over_dvb_stream_Descriptor(data,i,length,end):
"""\
parser_rar_over_dvb_stream_Descriptor(data,i,length,end) -> dict(parsed descriptor elements).
This descriptor is not parsed at the moment. The dict returned is:
{ "type": "rar_over_dvb_stream", "contents" : unparsed_descriptor_co... |
def greeting(name: str) -> str:
"""
Construct a greeting.
:param name: name of the person or object to greet
:return: greeting
"""
return f"Hello, {name}!" if name else "Hello!" |
def walk(i, j):
"""
Walks through the String without crossing the boundaries,
making sure that i < j-1
"""
if i < j - 1:
i += 1
# It is necessary to check again if i < j-1, after we incremented i
if i < j - 1:
j -= 1
return i, j |
def calc_chunksize(n_workers: int, len_iterable: int, factor: int = 4):
"""
Calculate chunksize argument for Pool-methods.
Resembles source-code within `multiprocessing.pool.Pool._map_async`.
"""
chunksize, extra = divmod(len_iterable, n_workers * factor)
if extra:
chunksize += 1
re... |
def get_iho_limits(iho_order: str):
"""
Get fixed and variable Total Vertical Uncertainty components for the different IHO Order categories, see S-44
Table 1 - Minimum Bathymetry Standards for Safety of Navigation Hydrographic Surveys
Parameters
----------
iho_order
string representatio... |
def metalicity_smolec(period, phi31_i):
"""
Returns the Smolec formula metalicity of the given RRab RR Lyrae.
(Smolec, 2005) (2)
(Skowron et al., 2016) (3)
Parameters
----------
period : float64
The period of the star.
phi31_i : float64
The I band phi31 of the star.
... |
def _action(name, params):
"""
Convenience function for constructing an action `dict`.
"""
return {u'action': name,
u'parameters': params} |
def Val(text):
"""Return the value of a string
This function finds the longest leftmost number in the string and
returns it. If there are no valid numbers then it returns 0.
The method chosen here is very poor - we just keep trying to convert the
string to a float and just use the last successful ... |
def make_board(board_string):
"""Make a board from a string.
For example::
>>> board = make_board('''
... N C A N E
... O U I O P
... Z Q Z O N
... F A D P L
... E D E A Z
... ''')
>>> len(board)
5
>>> board[0]
['N', 'C'... |
def gen_repomap_record(arch, src_type, dst_type, index=0):
"""Generate repomap record based on given data."""
return ('src-repoid-{}-{}-{}'.format(arch, src_type, index),
'dst-repoid-{}-{}-{}'.format(arch, dst_type, index),
'pes-name', 'all', 'all', arch, 'rpm', src_type, dst_type) |
def log_progress_message(_process_id, _progression_id, _absolute, _change, _user_id):
"""
Creates a progress message that is save to the Optimal BPM log
:param _process_id:
:param _progression_id:
:param _absolute:
:param _change:
:param _user_id:
:return:
"""
_struct = {
... |
def absurl(rel_url, base_url):
"""Return the absolute url."""
if rel_url == "/":
return base_url
return base_url + rel_url |
def get_node_label(literal, n):
"""node label 1, 2, ..., n for literal 1, 2, ..., n
nodel label n+1, n+2, ..., 2n for literal -1, -2, ..., -n
"""
if literal > 0:
return literal
else:
return (- literal + n) |
def parse_headers(env):
"""Parse HTTP headers out of a WSGI environ dictionary
Args:
env: A WSGI environ dictionary
Returns:
A dict containing (name, value) pairs, one per HTTP header
Raises:
KeyError: The env dictionary did not contain a key that is required by
PE... |
def fmt_d(num):
"""Decimal formatter"""
return f'${num:,.0f}' |
def get_state_tags(src, trg):
"""Compares the src to the trg
Args:
- src (str): the src sentence
- trg (str): the trg sentence
Returns:
- tags (list): list of tags (S or C)
"""
tags = []
for i, src_w in enumerate(src):
if i > len(trg) - 1:
break
... |
def build_thru_packs(packs, max_dv=1, thru_split=3):
"""
Applies THRU and BY to packs to shorten output as Nastran does on
cards like the SPOINT
Parameters
----------
packs : List[pack]
pack : List[id_low, id_high, delta_id]
a list representation of the min/max/delta id values... |
def a_propagator ( t, r, v ):
"""A propagator (drift).
t is the time over which to propagate (typically dt/2)
r and v are the current positions and velocities
The function returns the new positions.
"""
return r + v * t |
def getBosch1617Setting(rpm):
"""
Get bosch 1617 router setting for given rmp.
"""
minSetting = 1.0
maxSetting = 6.0
minSpeed = 8000.0
maxSpeed = 25000.0
slope = (maxSetting - minSetting)/(maxSpeed - minSpeed)
offset = minSetting - slope*minSpeed
return slope*rpm + offset |
def verify_bool(flag):
"""
:type: str
:param flag: Boolean parameter to check
:rtype: str
:return: Fix flag format
:raises: ValueError: invalid form
"""
if flag is None:
return None
flag = str(flag).upper()
if flag not in ['YES', 'NO']:
raise ValueError('"{}" is... |
def _transform_metric(metrics):
"""
Remove the _NUM at the end of metric is applicable
Args:
metrics: a list of str
Returns:
a set of transformed metric
"""
assert isinstance(metrics, list)
metrics = {"_".join(metric.split("_")[:-1]) if "_cut" in metric or "P_" in metric el... |
def combos(trace):
"""
Get the combinations between all the activities of the trace relations given a list of activities
Parameters
--------------
trace
List activities
Returns
--------------
rel
Combos inside the trace
"""
return set((x, y) for x in trace for y... |
def default_env(selected_items=None, results=None, critical_failures=None,
non_critical_failures=None, mode="default",
GOST_address=None, single_command=False):
"""Returns the default environment """
if selected_items is None:
selected_items = []
if results is None:
... |
def digits_sum(n):
"""
Returns sum of digits of number n.
For example:
digits_sum(245) = 2 + 4 + 5
:param n: n
:return: sum of digits
"""
return sum(int(ch) for ch in str(n)) |
def return_arg(query=None):
"""
Helper function that returns its argument. It can't be a lambda because
it will get called inside a decorated function
"""
return {"jobs": query} |
def is_remove(obj):
""" is obj a string that starts with 'remove' (case insensitive)? """
return isinstance(obj, str) and obj.lower().startswith('remove') |
def from_url_representation(url_rep: str) -> str:
"""Reconvert url representation of path to actual path"""
return url_rep.replace("__", "/").replace("-_-", "_") |
def search(_list, target):
"""
This function performs an interpolation search
on a sorted list and returns the index
of item if successful else returns False
:param _list: list to search
:param target: item to search for
:return: index of item if successful else returns False
"""
i... |
def on_segment(p, q, r):
"""
Checks to see if given three collinear points p, q, r, the function checks if
point q lies on line segment 'pr'.
p: First endpoint of line 'pr' described by a tuple.
q: Point being tested described by a tuple.
r: Second endpoint of line 'pr' described by a tuple.
... |
def tree_flatten(tree):
"""Flatten a tree into a list."""
if isinstance(tree, (list, tuple)):
# In python, sum of lists starting from [] is the concatenation.
return sum([tree_flatten(t) for t in tree], [])
if isinstance(tree, dict):
# Only use the values in case of a dictionary node... |
def cookie_count(n, p, c):
"""
Returns the number of cookies it is possible to purchase, starting with n dollars, @ p dollars per cookie
OR c jars per cookie returned, where each cookie is inside one jar when purchased
:param n: a number representing the starting dollars
:param p: a number represen... |
def tagsDict_toLineProtocolString(pTagsDict:dict):
"""Converts a tags dictionnary to a valid LineProtocol string."""
retval = ''
for lTagName in pTagsDict:
lTagValue = pTagsDict[lTagName]
# See https://docs.influxdata.com/influxdb/v1.7/write_protocols/line_protocol_tutorial/#special-characters
if type(lTagV... |
def _test_exception(exc, func, *data):
"""Validate that func(data) raises exc"""
try:
func(*data)
except exc:
return True
except:
pass
return False |
def get_package_info(pkgs_info, pkg_name):
"""."""
package_info = pkgs_info.get(pkg_name, {})
return package_info |
def pkcs7_pad(bytes_, len_):
"""Pad a byte sequence with PKCS #7."""
remainder = len_ % len(bytes_)
pad_len = remainder if remainder != 0 else len_
return bytes_ + bytes([remainder] * pad_len) |
def decode_packet_number(truncated: int, num_bits: int, expected: int) -> int:
"""
Recover a packet number from a truncated packet number.
See: Appendix A - Sample Packet Number Decoding Algorithm
"""
window = 1 << num_bits
half_window = window // 2
candidate = (expected & ~(window - 1)) | ... |
def encrypt_pub(m, n, e):
"""Encrypt message m."""
enc_m = pow(m, e, n)
return enc_m |
def calculate_max_padding(rows, labels, num_of_rows, num_of_cols, centered):
"""
Calculates max padding based on factors such as centering and biggest words in columns
"""
max_length = [0] * num_of_cols
if centered:
padding_l = 2
else:
padding_l = 2
if labels:
for ... |
def which_prize(points=0):
"""
Returns the prize-winning message, given a number of points
"""
if points <= 50:
return "Congratulations! You have won a wooden rabbit!"
elif points <= 150:
return "Oh dear, no prize this time."
elif points <= 180:
return "Congratulations! Y... |
def float_to_mc(value):
"""
Convert from float to millicents
Args:
value: float number
Returns: value in millcents
"""
return int(value * 100 * 1000) |
def stringify(value):
"""Utility for stringifying an event.
"""
string = str(value)
if len(string) > 1:
string = "(%s)" % string
return string |
def parse_enrolled_students(enrolled_users):
"""
Parse the statements containing all enrolled students of a course.
:param enrolled_users: A json statement, received as response on a Moodle call.
:type enrolled_users: list(dict(str, int))
:return: A list of the ids of the enrolled students.
:rt... |
def batch_operation(data_list, func, **kwargs):
"""
Unpacks and repacks a batch.
:param data_list: List of data.
:param func: Targeted function.
:param kwargs: Fixed function parameter.
:return: List of results.
"""
return [func(data, **kwargs) for data in data_list] |
def _force_unicode(number):
"""Convert the number to unicode."""
if not hasattr(number, 'isnumeric'): # pragma: no cover (Python 2 code)
number = number.decode('utf-8')
return number |
def find_matching_obj_def(obj_defs, new_obj_def):
"""Find matching object definition."""
for obj_name in obj_defs:
existing_obj_def = obj_defs[obj_name]
if 'properties' in new_obj_def and 'properties' in existing_obj_def:
if new_obj_def['properties'] == existing_obj_def['properties']... |
def _is_line_from_candidate(line: str, from_imports: list, import_str: str) -> bool:
"""
Check if line has from import
:param line: the line to check
:param from_imports: the from imports list
:param import_str: the import string
:return: True if the line has from import to replace
"""
i... |
def sort_by_value(histogram, topK=None, filterFn=None):
""" Return a sorted list of (value, tag) pairs from a given histogram.
If filter is specified the results are filtered using that function
If topK is specified, only return topK results
"""
res = reversed(
sorted([(val, tag) fo... |
def get_value_after_str(line, key):
""" Get the value after cstate string """
idx = 0
line_in_list = line.split()
for idx_key, val in enumerate(line_in_list):
if val == key:
idx = idx_key
break
return line_in_list[idx + 1] |
def res_2_tuple(resolution):
"""
Converts a resolution map to a tuple
"""
return resolution['h'], resolution['w'] |
def parse_sym_name(line):
""" extract domain and name from head of line
- return domain and sym
e.g. ".rodata.pin_B6"
- domain = rodata, name = .pin_B6
"""
line = line.strip().split()
sym_name = None
if line[0][1:].find(".") > 0:
# found a dot separator
sym ... |
def betabinom_mean(a, b, n):
"""Mean of a beta-binomial discrete random variable
:param a: the alpha parameter, number of prior successes, a > 0
:param b: the beta parameter, number of prior failures, b > 0
:param n: the number of total trials
:return: the mean of the distribution(s)
"""
re... |
def get_list(_list, persistent_attributes):
"""
Check if the user supplied a list and if its a custom list, also check for for any saved lists
:param _list: User supplied list
:param persistent_attributes: The persistent attribs from the app
:return: The list name , If list is custom or not
"""... |
def copy_digesters(digesters):
"""Returns copy of provided digesters since deepcopying doesn't work."""
result = {}
for hash_algorithm in digesters:
result[hash_algorithm] = digesters[hash_algorithm].copy()
return result |
def longest_substring(string):
"""We can reduce complexity to O(n) if we keep an index where the last
value of any particular character was seen. That way we only need to loop
through the i's once
"""
if string == "":
return string
# where each character was last seen
seen = {... |
def answer(s):
"""
Calculates the number of salutes in the hallway
----------
s : string
Hallway formation containing chars <,>,-
Returns
-------
solute_count : int
Number of salutes
Doc Test
----------
>>> answer('>----<')
2
>>> answer('<<>><')
4
... |
def pattern_in_string(pattern: str, string: str) -> int:
"""
>>> pattern_in_string('aba', 'abababa')
3
"""
n = len(string) - len(pattern) + 1
return sum(string[i:].startswith(pattern) for i in range(n)) |
def slurp(filename):
"""Return the contents of a file as a single string."""
with open(filename, 'r') as fh:
contents = fh.read()
return contents |
def _get_alignment_identities(A, B):
"""
This function returns the number of identities between two aligned sequences "A"
and "B". If "A" and "B" have different lengths, returns None.
"""
if len(A) == len(B):
return len([i for i in range(len(A)) if A[i] == B[i]])
return None |
def find_midpoint(low, high):
"""
Find the midpoint between two numbers. Expects low <= high.
Args:
low (int): Low number
high (int): High number
Returns:
(int): midpoint between low and high
"""
if high < low:
raise ValueError("Expected arg \"low\" to be less t... |
def triangle_recursion(n: int) -> int:
"""
slowest method
Three times slower than other two methods.
"""
if n == 1:
return 1
else:
return triangle_recursion(n - 1) + n |
def xroot(x, mu):
"""The equation of which we must find the root."""
return -x + (mu * (-1 + mu + x))/abs(-1 + mu + x)**3 - ((-1 + mu)*(mu + x))/abs(mu + x)**3 |
def compute_acc_bin_legacy(conf_thresh_lower, conf_thresh_upper, conf, pred, true):
"""
# Computes accuracy and average confidence for bin
Args:
conf_thresh_lower (float): Lower Threshold of confidence interval
conf_thresh_upper (float): Upper Threshold of confidence interval
co... |
def GetBaseName( name ):
"""This converts an output name into a directory name. It removes extensions, and also removes the prefix 'lib'"""
ret = name.split( "." )[0]
if ret.startswith( "lib" ):
ret = ret[3:]
return ret |
def sanitize(string):
""" sanitize a string before JSON-ize it """
return string.strip().replace("\\", "") # slash replace is only needed on Windows |
def get_dict(dict_: dict, dict_name: str):
"""
Return Dict value for a key or entire dict if key=all
"""
if dict_name == "all":
return dict_
else:
return dict_[dict_name] |
def contains(item, obj):
"""Support `item in obj` syntax"""
return obj.__contains__(item) |
def str2re(s):
"""Make re specific characters immune to re.compile.
"""
for c in '.()*+?$^\\':
s = s.replace(c, '['+c+']')
return s |
def normalize(x):
"""
normalizes the input
:param x: input
:return: normalized input
"""
return (x - 255 / 2) / 255 |
def int_to_bytearray(val, bytesize):
"""Utility function to convert an integer into a bytearray.
It returns the bytearray in the little endian format. It is easy to get the
big endian format, just do ba.reverse() on the returned object.
"""
import struct
if bytesize == 1:
return bytea... |
def clear(byte: int, index: int) -> int:
"""Set bit at index to 0."""
assert 0 <= byte <= 255
assert 0 <= index <= 7
# Python guarantees the ~ operator will return the 2s complement
# signed integer with the same bit pattern, AKA, ~128 is -129, not 127.
# However, the & operator with the resul... |
def fibonacciSeries(x: int)-> None:
"""
This function prints the fibonacci series upto `x` terms specified by the user.
Args:
This function takes exactly one argument.
`x: int` : x should be an integer which specifies the range upto which the fibonacci series will be generated.
"""
a=... |
def recursive_index_decode(int_array, max=32767, min=-32768):
"""Unpack an array of integers using recursive indexing.
:param int_array: the input array of integers
:param max: the maximum integer size
:param min: the minimum integer size
:return the array of integers after recursive index decoding"... |
def check_types_csv(row: tuple) -> bool:
"""Returns true if row from csv file has correct types"""
if not all((isinstance(x, str) for x in row[1:6])):
return False
if not isinstance(row[7], (str, int, float)):
# 3.27, 3.27a and 137 should all be supported
return False
return True |
def intersection_over_union(bb1, bb2):
"""
Calculate the Intersection over Union (IoU) of two bounding boxes.
Parameters
----------
bb1 : dict
Keys: {'x1', 'x2', 'y1', 'y2'}
The (x1, y1) position is at the top left corner,
the (x2, y2) po... |
def make_int(value):
"""Makes an int value lambda."""
return int(value[0]) |
def sec_to_time(seconds, days_only=False, ):
"""Convert seconds in human readable values
:param int seconds: Time in seconds
:param bool days_only: Output only in days
:return str: Human readable string """
seconds = int(seconds)
if seconds == 0:
seconds = 1
if seconds < 0:
... |
def stopw_removal(inp, stop):
"""
Stopwords removal in line of text.
Input:
- inp: str,
string of the text input
- stop: list,
list of stop-words to be removed
"""
# Final string to be returned
final = ''
for w in inp.lower().split():
if w not in sto... |
def check_empty_file(filename):
"""Checck that a file is empty"""
with open(filename) as f:
return f.read() == "" |
def gen_tfidf(text, idf_dict):
"""
Given a segmented string and idf dict, return a dict of tfidf.
"""
tokens = text.decode("utf8").split()
total = len(tokens)
tfidf_dict = {}
for w in tokens:
tfidf_dict[w] = tfidf_dict.get(w, 0.0) + 1.0
for k in tfidf_dict:
tfidf_dict[k] ... |
def deserialize_tuple(d):
"""
Deserializes a JSONified tuple.
Args:
d (:obj:`dict`): A dictionary representation of the tuple.
Returns:
A tuple.
"""
return tuple(d['items']) |
def extract_cab (archive, compression, cmd, verbosity, interactive, outdir):
"""Extract a CAB archive."""
cmdlist = [cmd, '-d', outdir]
if verbosity > 0:
cmdlist.append('-v')
cmdlist.append(archive)
return cmdlist |
def to_id(item) -> str:
"""
method for getting an id from an item
:param item: the item to get the id from
:return: the id fo the item
"""
if item is not None:
return item.id
else:
return '' |
def mem_empty_payload(mem_default_payload):
"""Provide a membership payload with no action."""
empty_payload = mem_default_payload
empty_payload["action"] = ""
return empty_payload |
def say_hello(name='World'):
"""Say hello to someone
Parameters
----------
name : string
A string containing the name of the person who is to greeted.
Returns
-------
string : string
The greetings string.
"""
if not isinstance(name, str):
raise ValueError("... |
def recover_sentence(sent_ids, id2word):
"""Convert a list of word ids back to a sentence string.
"""
words = list(map(lambda i: id2word[i] if 0 <= i < len(id2word) else '<unk>', sent_ids))
# Then remove tailing <pad>
i = len(words) - 1
while i >= 0 and words[i] == '<pad>':
i -= 1
w... |
def getList(dict):
"""return a list of the keys of the dictionary dict"""
list = []
for key in dict.keys():
list.append(key)
return list |
def features2use(features):
"""
Return just those features which have flag true or are just the name, not the tuple
:param features:
:return:
"""
ret = []
for f in features:
if isinstance(f, str):
ret.append(f)
else:
name, flag, ftype = f
i... |
def max_of_three(i, j, k):
""" returns the max of three """
mot = i if (i > j) else j
return mot if (mot > k) else k |
def get_updated_sheet_details(tracked_sheets, remote_sheets, sheet_frozen):
"""Format details from the various dicts to create rows for sheet.tsv."""
all_sheets = []
for sheet_title, details in tracked_sheets.items():
if sheet_title in remote_sheets:
sid = remote_sheets[sheet_title]
... |
def parse_field_path(field_path):
"""
Take a path to a field like "mezzanine.pages.models.Page.feature_image"
and return a model key, which is a tuple of the form ('pages', 'page'),
and a field name, e.g. "feature_image".
"""
model_path, field_name = field_path.rsplit(".", 1)
app_name, model... |
def check_complete(board):
"""Checks the board. If all matches have been found, returns True."""
for card in board:
if not card["cleared"]:
return False
return True |
def costfunc(circuit_evals, proportions):
"""Takes the expectation values of the circuit evaluations and adds them according to the proportion
Arguments:
circuit_evals :[Float]: the expectation values
proportions :[Float]: the mixing coefficients
"""
loss = 0
for circ_eval, prop in z... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.