content stringlengths 42 6.51k |
|---|
def _unquote(string: str) -> str:
"""Removes the double quotes surrounding a string."""
return string[1:-1] |
def list_to_svm_line(original_list):
"""
Concatenates list elements in consecutive element pairs.
Parameters
----------
original_list : list
The elements to be joined
Returns
-------
String
Returns a string, resulting from concatenation of list elements in consecutive e... |
def random_ints(count=20, min=1, max=50):
"""Return a list of `count` integers sampled uniformly at random from
given range [`min`...`max`] with replacement (duplicates are allowed)."""
import random
return [random.randint(min, max) for _ in range(count)] |
def divide_lists(ls, by):
"""
Divide lists by 'by'.
"""
return [x / float(by) for x in ls] |
def GenerateAnnulusNodeToRZPhi(nRCoords, nZCoords, phiPoints):
"""
Generate the map from node IDs to r, z phi IDs for a structured 3D linear
tet annulus mesh
"""
nodeToRzphi = []
index = 0
index = 0
for i in range(nRCoords):
for j in range(nZCoords):
for k in range(phiPoints):
node... |
def restructure_opentarget_response(json_doc):
"""
Restructure the API output from opentarget API.
:param: json_doc: json output from opentarget API
"""
if not json_doc.get("data"):
return json_doc
for _doc in json_doc['data']:
if "drug" in _doc:
if "CHEMBL" in _doc[... |
def calculate(name_list):
"""Returns the sum of the alphabetical value for each name
in the list multiplied by its position in the list"""
return sum(
(i + 1) * (ord(c) - ord("A") + 1)
for i, name in enumerate(sorted(name_list))
for c in name.strip('"')
) |
def triangle_n(n):
"""Returns the nth triangle number"""
return int(n * (n + 1) / 2) |
def version_1_39_12(model_dict):
"""Implement changes in a Model dict to make it compatible with version 1.39.12."""
removed_equip = 'PSZ-AC district chilled water with baseboard district hot water'
replaced_equip = 'PSZ-AC district chilled water with district hot water'
if 'energy' in model_dict['prope... |
def remove_common_molecules(reactants, products):
"""
Removes common species between two lists leaving only reacting species.
Parameters
----------
reactants, products : list of str
List containing strings all molecular species.
Returns
-------
tuple of str
Reduced list... |
def project_sorted(row, sorted_cols):
"""Extract the values in the ORDER BY columns from a row.
"""
return [ row[col] for col in sorted_cols ] |
def get_kth_inorder_record(root, k):
"""
Question 10.7
"""
current_num = 0
cur = root
prev = None
while cur:
next_node = None
if cur.parent == prev:
if cur.left:
next_node = cur.left
else:
current_num += 1
... |
def binary_search(given_array, key, starting_index, ending_index):
""" Using binary search method to find the accurate(inplace) place for 'key'
to reduce the complexity for comparisons of insertion sort"""
if starting_index == ending_index:
if given_array[starting_index] > key:
return st... |
def _create_default_branch_id(repo_url, default_branch_ref_id):
"""
Return a unique node id for a repo's defaultBranchId using the given repo_url and default_branch_ref_id.
This ensures that default branches for each GitHub repo are unique nodes in the graph.
"""
return f"{repo_url}:{default_branch_... |
def i_sort_rec(seq, i=None):
""" perform insertion sort recursively"""
# if the sequence is empty return it
if not seq:
return seq
if i is None:
i=len(seq)
if i==1:
return
i_sort_rec(seq, i-1)
val = seq[i-1]
del seq[i-1]
seq.insert(0, val)
i2 = 0
while... |
def two_opt_swap(r: list, i: int, k: int) -> list:
"""Reverses items `i`:`k` in the list `r`
https://en.wikipedia.org/wiki/2-opt."""
out = r.copy()
out[i:k + 1] = out[k:i - 1:-1]
return out |
def get_resource_group_name_by_resource_id(resource_id):
"""Returns the resource group name from parsing the resource id.
:param str resource_id: The resource id
"""
resource_id = resource_id.lower()
resource_group_keyword = '/resourcegroups/'
return resource_id[resource_id.index(resource_group_... |
def DIVIDE(x, y):
"""
Divides one number by another and returns the result.
See https://docs.mongodb.com/manual/reference/operator/aggregation/divide/
for more details
:param x: The number or field of number (is the dividend)
:param y: The number or field of number (is the divisor)
:return: ... |
def _rule_compare(rule1, rule2):
"""
Compare the common keys between security group rules against eachother
"""
commonkeys = set(rule1.keys()).intersection(rule2.keys())
for key in commonkeys:
if rule1[key] != rule2[key]:
return False
return True |
def normalize(c: str) -> str:
"""Returns the given char if alphanumeric, or normalizes/elides it"""
if c.isalnum():
return c
elif c == '-':
return '_'
else:
return '' |
def oneHotEncode_4_evtypes(x, r_vals=None):
"""
This function one hot encodes the input for the event types
cascade, tracks, doubel-bang, starting tracks
"""
cascade = [1., 0., 0., 0.]
track = [0., 1., 0., 0.]
doublebang = [0., 0., 1., 0.]
s_track = [0., 0., 0., 1.]
# map x to possi... |
def duration_hm(time_delta):
"""time_delta -> 1:01"""
minutes, s = divmod(time_delta, 60)
h, minutes = divmod(minutes, 60)
return "%d:%02d" % (h, minutes) |
def get_object_value(value) -> str:
"""Get value from object or enum."""
while hasattr(value, "value"):
value = value.value
return value |
def get_ticker_name(s: str) -> str:
"""Gets ticker name from file name."""
x = s.find('_')
name = s[:x]
return name |
def hk_obc_enabled(bits: list) -> bytes:
"""
First bit should be on the left, bitfield is read from left to right
"""
enabled_bits = 0
bits.reverse()
for i in range(len(bits)):
enabled_bits |= bits[i] << i
return enabled_bits.to_bytes(4, byteorder='big') |
def num_docs(a):
""" Return a dict with all the documents returned in all
queries """
full_prediction_set = {}
for item in a:
for doc in a[item]:
if doc not in full_prediction_set:
full_prediction_set[doc] = 0
full_prediction_set[doc] += 1
return ... |
def dequantize(Q, cp, cn):
"""
Dequanitze from the given 1-bit quantization and the reconstruction values.
Parameters:
Q : input quantized values (+/- 1)
cp: center of the quantization bins for positive values
cn: center of the quantization bins for negative values
"""
Qn =... |
def hinge_loss(predicted_value: float, real_label: float) -> float:
"""
Computes hinge loss for given predicted value, given the real label.
:param predicted_value: inner product of data sample and coefficient
vector, possibly corrected by intercept
:param real_label: Real label
:return... |
def parameterize(ref):
"""Rewrites attributes to match the kwarg naming convention in client.
>>> paramterize({'project_id': 0})
{'project': 0}
"""
params = ref.copy()
for key in ref:
if key[-3:] == '_id':
params.setdefault(key[:-3], params.pop(key))
return params |
def _join_smt2(seq, conn):
"""Produces a SMT-LIB 2.0 formula containing all elements of the sequence merged by a provided connective."""
if len(seq) == 0:
return ''
elif len(seq) == 1:
return seq[0]
else:
return '({0} {1})'.format(conn, ' '.join(seq)) |
def count_pattern(pattern, lst):
"""
count_pattern() returns the count of the number of times that the pattern occurs in the lst
"""
count = 0
if type(pattern) != type(lst):
raise TypeError("count_pattern() : arguments must be of the same type")
elif not pattern or not lst:
retur... |
def indent_string(the_string, indent_level):
"""Indents the given string by a given number of spaces
Args:
the_string: str
indent_level: int
Returns a new string that is the same as the_string, except that
each line is indented by 'indent_level' spaces.
In python3, this can be done ... |
def get_readout_time(dicom_img, dcm_info, dwell_time):
""" Get read out time from a dicom image.
Parameters
----------
dicom_img: dicom.dataset.FileDataset object
one of the dicom image loaded by pydicom.
dcm_info: dict
array containing dicom data.
dwell_time: float
Effe... |
def without_http_prefix(url):
"""
Returns a URL without the http:// or https:// prefixes
"""
if url.startswith('http://'):
return url[7:]
elif url.startswith('https://'):
return url[8:]
return url |
def subset_with_values(target, lst):
"""Determines whether or not it is possible to create the target sum using
values in the list. Values in the list can be positive, negative, or zero.
The function returns a tuple of exactly two items. The first is a boolean,
that indicates true if the sum is possible... |
def gabfr_nbrs(gabfr):
"""
gabfr_nbrs(gabfr)
Returns the numbers corresponding to the Gabor frame letters
(A, B, C, D/U, G).
Required args:
- gabfr (str or list): gabor frame letter(s)
Returns:
- gab_nbr (int or list): gabor frame number(s)
"""
if not isinstance(gabf... |
def rpower(n, k):
"""Recursive divide and conquer"""
if k == 0: return 1
p = rpower(n, k >> 1)
if k & 1: return n * p * p
return p * p |
def is_alphanumeric(word: str, valid_punctuation_marks: str = '-') -> bool:
"""
Check if a word contains only alpha-numeric
characters and valid punctuation marks.
Parameters
----------
word: `str`
The given word
valid_punctuation_marks: `str`
Punctuation marks that are val... |
def reverse(string):
"""Native reverse of a string looks a little bit cryptic,
just a readable wrapper"""
return string[::-1] |
def dec_indent(indent, count=1):
"""
decrease indent, e.g.
if indent = " ", and count = 1, return " ",
if indent = " ", and count = 2, return "",
"""
if indent.endswith('\t'):
indent = indent[:len(indent) - 1 * count]
elif indent.endswith(' '):
indent = in... |
def cut(string, characters=2, trailing="normal"):
"""
Split a string into a list of N characters each.
.. code:: python
reusables.cut("abcdefghi")
# ['ab', 'cd', 'ef', 'gh', 'i']
trailing gives you the following options:
* normal: leaves remaining characters in their own last pos... |
def isFormedBy(part, symbol_set):
"""
>>> from production import Production
>>> p = Production(['A'], ['A', 'b', 'C'])
>>> isFormedBy(p.right, ['A', 'b', 'C', 'd'])
True
>>> isFormedBy(p.right, ['A', 'B', 'C', 'd'])
False
"""
for option in part:
for symbol in option:
... |
def flatten(xs):
"""Recursively flattens a list of lists of lists (arbitrarily,
non-uniformly deep) into a single big list.
"""
res = []
def loop(ys):
for i in ys:
if isinstance(i, list):
loop(i)
elif i is None:
pass
else:
... |
def bytesto(bytes, to, bsize=1024):
"""convert bytes to megabytes.
bytes to mb: bytesto(bytes, 'm')
bytes to gb: bytesto(bytes, 'g' etc.
From https://gist.github.com/shawnbutts/3906915
"""
levels = {"k": 1, "m": 2, "g": 3, "t": 4, "p": 5, "e": 6}
answer = float(bytes)
for _ in range(leve... |
def merge_dict(a, b, path=None):
"""merge b into a. The values in b will override values in a.
Args:
a (dict): dict to merge to.
b (dict): dict to merge from.
Returns: dict1 with values merged from b.
"""
if path is None: path = []
for key in b:
if key in a:
... |
def username_first(twitter_data, a, b):
""" (Twitterverse dictionary, str, str) -> int
Return 1 if user a has a username that comes after user b's username
alphabetically, -1 if user a's username comes before user b's username,
and 0 if a tie, based on the data in twitter_data.
>>> twitter_data = ... |
def split_epiweek(epiweek):
""" return a (year, week) pair from this epiweek """
return (epiweek // 100, epiweek % 100) |
def dup_factions(factions, num_winners):
"""Expand a list of factions by a factor of num_winners into a list of candidates
>>> dup_factions(['A', 'B'], 3)
['A1', 'A2', 'A3', 'B1', 'B2', 'B3']
"""
return [f'{f}{n}' for f in factions for n in range(1, num_winners+1)] |
def _merge_entities(e1, e2, primary_property, other_properties=None):
"""
Merge dict objects e1 and e2 so that the resulting dict has the data from both.
Entities are in-particular dicts which may contain an "identifier" field, such as
used by projects and authors.
The primary_property names the f... |
def httpResponse(text, status, start_response):
"""
httpResponse
"""
text = "%s" % str(text)
response_headers = [('Content-type', 'text/html'), ('Content-Length', str(len(text)))]
if start_response:
start_response(status, response_headers)
return [text.encode('utf-8')] |
def first_non_empty(items):
"""
Return first non empty item from the list. If nothing is found, we just
pick the first item. If there is no item, we return the whole form
(defaulting to []).
"""
if items:
for it in items:
if it:
return it
return item... |
def get_first_object_or_none(queryset):
"""
A shortcut to obtain the first object of a queryset if it exists or None
otherwise.
"""
try:
return queryset[:1][0]
except IndexError:
return None |
def incsum(prevsum, prevmean, mean, x):
"""Caclulate incremental sum of square deviations"""
newsum = prevsum + abs((x - prevmean) * (x - mean))
return newsum |
def getNewDimensions(width , height , block_size=8):
""" Since block width = height we can use only one variable to compare"""
if height % block_size !=0 :
new_ht = height + (block_size - (height%block_size))
else:
new_ht = height
if width % block_size !=0:
new_wt = width + (block_size - (width%block_size))
... |
def replace_vars(arg, i=0):
"""
Doc String
"""
if isinstance(arg, tuple):
ret = []
for elem in arg:
replaced, i = replace_vars(elem, i)
ret.append(replaced)
return tuple(ret), i
elif isinstance(arg, str) and len(arg) > 0 and arg[0] == '?':
retu... |
def extract_target_box(proc: str):
"""
Extracts target box as a tuple of 4 integers (x1, y1, x2, y2) from
a string that ends with four integers, in parentheses, separated
by a comma.
"""
a = proc.strip(")").split("(")
assert len(a) == 2
b = a[1].split(",")
assert len(b) == 4
retu... |
def PathArgument(context, path):
"""Resolve path from context variable is possible.
"""
try:
# Path argument was context variable name.
return context[path]
except KeyError:
# Path argument was a string value.
return path |
def instrument_port_prevent_reset(pwr_status, n_intervals, text, placeholder):
"""prevents the input box's value to be reset by dcc.Interval"""
if pwr_status:
return text
else:
return placeholder |
def prepend_speechreps_for_dict_encoding(speechreps, prepend_str="HUB",
mask_symbol="<mask>",
eos_symbol="</s>"):
"""
take list of hubert codes (int from 0 to K-1 where K is number of k-means clusters)
return a string version ... |
def sumorients(in_: list):
"""
Sums the four orientations into one image, computes sum of 4 elements of a list.
"""
out = in_[0] + in_[1] + in_[2] + in_[3]
return out |
def batch_data(data, batch_size):
"""Given a list, batch that list into chunks of size batch_size
Args:
data (List): list to be batched
batch_size (int): size of each batch
Returns:
batches (List[List]): a list of lists, each inner list of size batch_size except possibly
... |
def _escape_dq(s):
"""Lightweight escaping function used in writing curl calls...
"""
if not isinstance(s, str):
if isinstance(s, bool):
return 'true' if s else 'false'
return s
if '"' in s:
ss = s.split('"')
return '"{}"'.format('\\"'.join(ss))
return '"... |
def search( top, aName ):
"""Search down through the copybook structure."""
for aDDE in top:
if aDDE.name == aName:
return aDDE |
def gen_param_help(hyper_parameters):
"""
Generates help for hyper parameters section.
"""
type_map = {"FLOAT": float, "INTEGER": int, "BOOLEAN": bool}
help_keys = ("header", "type", "default_value", "max_value", "min_value")
def _gen_param_help(prefix, cur_params):
cur_help = {}
... |
def say_hello(
greeting: str = "Hello", name: str = "World", print_message: bool = True
):
"""
A simple function to say hello
:param greeting: the greeting to use
:param name: the person to greet
:param print_message: flag to indicate whether to print to the commandline
"""
hello_str = ... |
def limit_throughput_sinr(throughput):
"""Function to limit throughput for SINR!
Args:
throughput: (limit) User throughput in bps!
Returns:
_: (list) Limited User throughput in bps!
"""
_ = list(filter(lambda x: x < 5 * 10 ** 6, throughput))
return... |
def clean_empty_keyvalues_from_dict(d):
"""
Cleans all key value pairs from the object that have empty values, like [], {} and ''.
Arguments:
d {object} -- The object to be sent to metax. (might have empty values)
Returns:
object -- Object without the empty values.
"""
if not... |
def starts_with(match, ignore_case = True):
"""
Starts with a prefix
Parameters
----------
match : str
String to match columns
ignore_case : bool
If TRUE, the default, ignores case when matching names.
Examples
--------
>>> df = tp.Tibble({'a': range(3), 'add': rang... |
def convert(flippy):
""" Convert to Martin's format. """
for char in ('[ ]'):
flippy = str(flippy).replace(char, '')
flippy = flippy.replace('0', '-').replace('1', '#')
return flippy |
def equal_chunks(list, chunk_size):
"""return successive n-sized chunks from l."""
chunks = []
for i in range(0, len(list), chunk_size):
chunks.append(list[i:i + chunk_size])
return chunks |
def date_str(year, month, day, hour=0, minute=0, second=0., microsecond=None):
"""
Creates an ISO 8601 string.
"""
# Get microsecond if not provided
if microsecond is None:
if type(second) is float:
microsecond = int((second - int(second)) * 1000000)
else:
... |
def convert_frequency(value):
"""! @brief Applies scale suffix to frequency value string."""
value = value.strip()
suffix = value[-1].lower()
if suffix in ('k', 'm'):
value = int(value[:-1])
if suffix == 'k':
value *= 1000
elif suffix == 'm':
value *= 1000... |
def lsst_sky_brightness(bands=''):
"""
Sample from the LSST sky brightness distribution
"""
dist = {'u': 22.99, 'g': 22.26, 'r': 21.2, 'i': 20.48, 'z': 19.6, 'Y': 18.61}
return [dist[b] for b in bands.split(',')] |
def replaceRefund(e):
"""Redistribute compensation type values."""
e['compensation_type'] = 'partial_refund' if e['compensation_amount']<55.0 else 'full_refund'
return e |
def flatten(l, ltypes=(list, tuple)):
"""flatten an array or list"""
ltype = type(l)
l = list(l)
i = 0
while i < len(l):
while isinstance(l[i], ltypes):
if not l[i]:
l.pop(i)
i -= 1
break
else:
l[i:i + 1]... |
def denorm(data, mean, std):
"""stream am model need to denorm
"""
return data * std + mean |
def check_bbox(bb):
"""check bounding box"""
bbox = []
bbox.append(bb['coordinate_x'])
bbox.append(bb['coordinate_y'])
bbox.append(bb['width'])
bbox.append(bb['height'])
return bbox |
def clean(some_string, uppercase=False):
"""
helper to clean up an input string
"""
if uppercase:
return some_string.strip().upper()
else:
return some_string.strip().lower() |
def compute_max_len(example):
"""Compute the max length of the sequence, before the padding tokens"""
if '[PAD]' not in example['tokens']:
return len(example['tokens'])
return example['tokens'].index('[PAD]') |
def _GetFailedStepsForEachCL(analysis):
"""Gets suspected CLs and their corresponding failed steps."""
suspected_cl_steps = {}
if (analysis is None or analysis.result is None or
not analysis.result['failures']):
return suspected_cl_steps
for failure in analysis.result['failures']:
for suspected_c... |
def get_digit_at_pos(num, base, pos):
"""
Gets the integer at the given position of the number in a specific base
@param num The number we wish to find the converted digit in
@param base The base in which the digit is calculated
@param pos The position of the digit to be found
... |
def getFaceData( data ):
"""Extracts vertex, normal and uv indices for a face definition.
data consists of strings: i, i/i, i//i, or i/i/i.
All strings in the data should be of the same format. Format determines what
indices are defined"""
dataLists = [[], [], []]
for s in data:
... |
def get_xpath_for_date_of_available_time_element(day_index: int) -> str:
"""
The element showing date of the available time is found in the div having the xpath:
'/html/body/div[4]/div[2]/div/div[5]/div/div[2]/div[3]/div[N]/span'
^
where N ... |
def inc_patch_no(v = "0.0.0"):
"""inc_patch_no takes a symvar and increments the right most value in the dot touple"""
suffix = ''
if "-" in v:
(v, suffix) = v.split("-")
parts = v.split(".")
if len(parts) == 3:
#major_no = parts[0]
#minor_no = parts[1]
patch_no = int... |
def find_final_position(obs: dict) -> int:
"""Find final player position."""
if len(obs["geese"][0]) == 0:
pos = 4 - sum([1 if len(i) == 0 else 0 for i in obs["geese"][1:]])
else:
geese = [0, 1, 2, 3]
length = [len(i) for i in obs["geese"]]
order = list(zip(*sorted(zip(lengt... |
def _docstring(docstring):
"""Return summary of docstring"""
return " ".join(docstring.split("\n")[4:5]) if docstring else "" |
def float_to_uint(x, x_min, x_max, bits):
"""
Converts float to unsigned int
"""
span = float(x_max - x_min)
offset = float(x_min)
return int((x - offset) * float(((1 << bits) - 1) / span)) |
def _kernel(kernel_spec):
"""Expands the kernel spec into a length 2 list.
Args:
kernel_spec: An integer or a length 1 or 2 sequence that is expanded to a
list.
Returns:
A length 2 list.
"""
if isinstance(kernel_spec, int):
return [kernel_spec, kernel_spec]
elif len(kernel_spec) == 1:
... |
def remove(thing, l):
"""
REMOVE thing list
outputs a copy of ``list`` with every member equal to ``thing``
removed.
"""
l = l[:]
l.remove(thing)
return l |
def chieffPH(m1, m2, s1, s2):
"""
Computes the effective spin from PhenomB/C
input: m1, m2, s1z, s2z
output: chi effective
"""
return (m1*s1 + m2*s2) / (m1 + m2) |
def isiterable(obj):
"""
Return whether an object is iterable
"""
# see https://docs.python.org/3/library/collections.abc.html#collections.abc.Iterable
try:
iter(obj)
return True
except:
return False |
def mouv(m_):
"""
Converts SINGLE movement from human comprehensive to boolean and str
Parameters
----------
m_ : str
The movement <F B L R U D> [' 2]
Returns
-------
f : str
The face to move <F B L R U D>
cw : boolean
True = rotates clockwise
r180 : boolean
True = rotates twice
"""
# Creating ret... |
def get_service(vm, port):
"""Return the service for a given port."""
for service in vm.get('suppliedServices', []):
if service['portRange'] == port:
return service |
def formatCurVal(val):
"""
Helper function for formatting current values to 3 significant digits, but
avoiding the use of scientific notation for display. Also, integers are
shown at full precision.
"""
if val is None:
return ''
elif val == int(val):
return '{:,}'.format(in... |
def condensed_coords(i, j, n):
"""Transform square distance matrix coordinates to the corresponding
index into a condensed, 1D form of the matrix.
Parameters
----------
i : int
Row index.
j : int
Column index.
n : int
Size of the square matrix (length of first or sec... |
def chunk_list(items, size):
"""
Return a list of chunks
:param items: List
:param size: int The number of items per chunk
:return: List
"""
size = max(1, size)
return [items[i:i + size] for i in range(0, len(items), size)] |
def create_intersection(whole_dict, sub_dict):
"""
Reduces a dictionary to have the same keys as an another dict.
:param whole_dict: dict, the dictionary to be reduced.
:param sub_dict: dict, the dictionary with the required keys.
:return: dict, the reduced dict.
"""
reduced_dict = {}
fo... |
def gv_get_event_code(event):
"""get the event code"""
#if event == '+RESP:GTFRI': return '5' #programated report
#elif event == '+RESP:GTSOS': return '1' #panic report
#elif event == '+RESP:GTSPD': return '2' #speed alarm
#elif event == '+RESP:GTIGN': return '6' #ignition on report
#elif event ... |
def update(rules):
"""Adjust the rules to contain loops"""
rules["8"] = "42 | 42 8"
rules["11"] = "42 31 | 42 11 31"
return rules |
def get_network(properties):
""" Get the configuration that connects the instance to an existing network
and assigns to it an ephemeral public IP.
"""
network_name = properties.get('network')
return {
'network': 'global/networks/{}'.format(network_name),
'accessConfigs': [
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.