content stringlengths 42 6.51k |
|---|
def part1(data):
"""Return how many passports have all info except possibly cid."""
expected = {'byr', 'iyr', 'eyr', 'hgt', 'hcl', 'ecl', 'pid'}
fields, valid = set(), 0
for line in data.splitlines():
if line: # non-empty line
fields.update(field[:3] for field in line.split())
... |
def split(value, key):
"""
Returns the value turned into a list.
"""
return value.split(key) |
def search(text, pattern):
"""
Takes a string and searches if the `pattern` is substring within `text`.
:param text: A string that will be searched.
:param pattern: A string that will be searched as a substring within
`text`.
:rtype: The indices of all occurences of where the su... |
def getname(obj):
"""Get the default name for a test."""
try:
return obj.__name__
except AttributeError:
return repr(obj) |
def reverse_mac(rmac):
"""Change LE order to BE."""
if len(rmac) != 12:
return None
return (
rmac[10:12]
+ rmac[8:10]
+ rmac[6:8]
+ rmac[4:6]
+ rmac[2:4]
+ rmac[0:2]
) |
def degree_sequence_regular(n, k):
"""
Generates a degree sequnce following k-regular distribution
:param n: Number of vertices.
:param k: The parameter k for k-regular distribution
:return: A list containing n integers representing degrees of vertices following k-regular distribution.
"""
... |
def norm(vector):
"""Makes a vector unit length.
If original vLen is 0, leave vector as [0,...]"""
vLen = sum([e**2 for e in vector])**(1/2)
if vLen != 0:
return [e/vLen for e in vector]
else:
return [0 for e in vector] |
def get_tld_from_domain_name(domain_name):
"""
:param domain_name: the domain name from which to get the TLD from
:return: Returns the TLD from a domain name (google.com would return 'com')
"""
return domain_name.split('.')[-1] |
def versionate(s):
"""
Assumes s is a slug-type string.
Returns another slug-type string with a number at the the end.
Useful when you want unique slugs that may have been hashed to the same string.
"""
words = s.split("-")
if len(words) > 1:
try:
# Check if the ... |
def zagzig(du):
""" Put the coefficients in the right order """
map = [[0, 1, 5, 6, 14, 15, 27, 28],
[2, 4, 7, 13, 16, 26, 29, 42],
[3, 8, 12, 17, 25, 30, 41, 43],
[9, 11, 18, 24, 31, 40, 44, 53],
[10, 19, 23, 32, 39, 45, 52, 54],
[20, 22, 33, 38, 46, 51, 5... |
def get_novel_smiles(new_unique_smiles, reference_unique_smiles):
"""Get novel smiles which do not appear in the reference set.
Parameters
----------
new_unique_smiles : list of str
List of SMILES from which we want to identify novel ones
reference_unique_smiles : list of str
List o... |
def l_to_d(td):
"""Transform a list of Key/Value dicts to a single dict
"""
return { i['Key']: i['Value'] for i in td } |
def tfds_split_for_mode(mode):
"""Return the TFDS split to use for a given input dataset."""
if mode == 'test':
# The labels for the real ImageNet test set were never released. So we
# follow the standard (although admitted confusing) practice of obtain
# "test set" accuracy numbers from the ImageNet va... |
def _generate_graph_state(frame):
"""Returns a game state as a graph
Args:
frame (dict) : Dict output of a frame generated from the DemoParser class
Returns:
A dict with keys "T", "CT" and "Global", where each entry is a vector. Global vector is CT + T concatenated
"""
return {"ct"... |
def extract_output(line):
"""
Extract the index of the tree and the matched tree fragment from a line of Tregex outout.
"""
line = line.strip()
index = None
fragment = None
for k, c in enumerate(line):
if c == ':':
index = line[:k]
fragment = line[(k+1):].stri... |
def get_value(header_dict, header_name, default=None, strip_value=""):
""" Return last header value, or default value (None)
If strip_value, remove strip_value (e.g., 'keep-alive') if it occurs in addition to other values
"""
if header_name in header_dict:
value = header_dict[header_name][-1]
... |
def merge_similarities(oldsims, newsims, clip=None):
"""
Merge two precomputed similarity lists, truncating the result to clip most similar items.
"""
if oldsims is None:
result = newsims or []
elif newsims is None:
result = oldsims
else:
result = sorted(oldsims + newsims... |
def parsever(apiver):
"""Parse a string representing an api version.
:param apiver: a string representing an api version
:return: a tuple containing the major and minor version numbers
"""
maj, min = apiver.split('.')
return int(maj), int(min) |
def merge_pixels(pixel1, pixel2):
"""
Merge two R or G or B pixels using 4 least significant bits.
INPUT: A string tuple (e.g. ("00101010")),
Another string tuple (e.g. ("00101010"))
OUTPUT: An integer tuple with the two RGB values merged 00100010
"""
merged_pixel = (pixel1[:4] + pix... |
def _add_to_metadata(metadata, name, value):
"""
Add the name value pair to the metadata dict
Args:
metadata (dict): a dictionary containing the metadata
name (string): the dictionary key
value: the value to add
Returns:
dict: the new metadata dictionary
"""
if... |
def define_logistic_regression(n_classes, l1_reg=0, l2_reg=0):
"""Shortcut to build the list of layer definitions (a single layer,
in this case) for a logistic regression classifier.
Parameters
----------
n_classes : int
Number of classes to calculate probabilities for
l1_reg, l2_reg : ... |
def filter_phrases(input_str, filter_list):
"""
Filters out phrases/words from the input string
:param input_str: String to be processed.
:return: string with phrases from filter_list removed.
"""
for phrase in filter_list:
input_str = input_str.replace(phrase,'')
return input_str |
def go_up(x: int, y: int) -> tuple:
"""
Go 1 unit in positive y-direction
:param x: x-coordinate of the node
:param y: y-coordinate of the node
:return: new coordinates of the node after moving a unit in the positive y-direction
"""
return x, y + 1 |
def extract_keys(keys, dic, drop=True):
"""
Extract keys from dictionary and return a dictionary with the extracted
values.
If key is not included in the dictionary, it will also be absent from the
output.
"""
out = {}
for k in keys:
try:
if drop:
ou... |
def calculate_ir(p, q, vr, vj):
"""
Compute ir from power flows and voltages
"""
ir = (q*vj+p*vr)/(vj**2 + vr**2)
return ir |
def is_hashable(obj: object) -> bool:
"""Return whether an object is hashable."""
try:
hash(obj)
except Exception:
return False
else:
return True |
def get_omega_k_0(**cosmo):
"""'Spatial curvature density' omega_k_0 for a cosmology (if needed).
If omega_k_0 is specified, return it. Otherwise return:
1.0 - omega_M_0 - omega_lambda_0
"""
if 'omega_k_0' in cosmo:
omega_k_0 = cosmo['omega_k_0']
else:
omega_k_0 = 1. - cos... |
def strip_ddp_state_dict(state_dict):
""" Workaround the fact that DistributedDataParallel prepends 'module.' to
every key, but the sampler models will not be wrapped in
DistributedDataParallel. (Solution from PyTorch forums.)"""
clean_state_dict = type(state_dict)()
for k, v in state_dict.items():
... |
def x_range(a):
"""
Get the valid x range (x_min,x_max) for the given [a] parameter.
"""
return (4 * a**2 - a**3) / 16, a / 4 |
def _GetDockerImageName(image_name, tag=None):
"""Get a Docker image name to use.
Args:
image_name: an image name.
tag: an image tag (optional).
Returns:
a Docker image name.
"""
if tag:
image_name = image_name.split(':', 2)[0] + ':' + tag
return image_name |
def set_id_type(
id: int, # noqa
type: int, # noqa
) -> int:
"""
Replaces the type-part in an ID with the given ``type``.
Parameters
----------
id, type: int
Returns
-------
int
"""
return ((id >> 16) << 16) + (type << 11) + (id & 2047) |
def get_split_ind(seq, N):
"""seq is a list of words. Return the index into seq such that
len(' '.join(seq[:ind])<=N
"""
sLen = 0
# todo: use Alex's xrange pattern from the cbook for efficiency
for (word, ind) in zip(seq, range(len(seq))):
sLen += len(word) + 1 # +1 to account for the len(' '... |
def query_fragility_curve(f_curve, depth):
"""
Query the fragility curve.
"""
if depth < 0:
return 0
for item in f_curve:
if item['depth_lower_m'] <= depth < item['depth_upper_m']:
return item['fragility']
else:
continue
print('fragility curve f... |
def set_voltage(channel: int, value: float):
"""
Sets voltage on channel to the value.
"""
return f"VSET{channel}:{value}" |
def _merge_peaks(l):
"""
Merge signals if the difference of Nuclear to cytoplasmic ratio is 1
"""
idx = []
while len(l)>0:
first, *rest = l
first = set(first)
lf = -1
while len(first)>lf:
lf = len(first)
rest2 = []
for r in rest:
... |
def avg(l):
"""Compute the average of a list"""
return sum(l) / len(l) |
def _get_cased(case_sensitive, *args):
"""
Get the cased versions of the provided strings if applicable.
Args:
case_sensitive: If False, then returns lowercase versions of all
strings.
args: The strings to get appropriately cased versions of.
Returns:
An iterable of... |
def _calculate_texture_sim(ri, rj):
"""Calculate texture similarity using histogram intersection"""
return sum([min(a, b) for a, b in zip(ri["texture_hist"], rj["texture_hist"])]) |
def _to_str(t) -> str:
"""
Transform binary into string.
"""
return t.decode("utf-8") |
def update_options(*dict_args):
"""
Given any number of dicts, shallow copy and merge into a new dict,
precedence goes to key value pairs in latter dicts.
"""
result = {}
for dictionary in dict_args:
result.update(dictionary)
return result |
def sext_24(value):
"""Sign-extended 24 bit number.
"""
if value & 0x800000:
return 0xff000000 | value
return value |
def lib2name(lib):
"""Convert an OS dependent library name to the base name::
libfoo.so.0.1 => foo
foo.dll => foo
"""
if lib.startswith('lib'):
lib = lib[4:]
return lib.split('.',1)[0] |
def roundToNearest(number, nearest):
""" Rounds a decimal number to the closest value, nearest, given
Arguments:
number: [float] the number to be rounded
nearest: [float] the number to be rouned to
Returns:
rounded: [float] the rounded number
"""
A = 1/nearest
rounde... |
def is_sorted(list_):
"""
Return True iff list_ is in non-decreasing order.
@param list list_: list to inspect
@rtype bool:
>>> is_sorted([1, 3, 5])
True
>>> is_sorted([3, 1, 5])
False
"""
for j in range(1, len(list_)):
if list_[j - 1] > list_[j]:
return Fal... |
def parse_ifname(ifname):
"""
parse interface name(<name>.<index>)
"""
items = ifname.split(".", 2)
if len(items) == 1:
return ifname, "0"
return items[0], items[1] |
def ibits(ival, ipos, ilen):
"""Same usage as Fortran ibits function."""
ones = ((1 << ilen)-1)
return (ival & (ones << ipos)) >> ipos |
def calculate_weights(counts, total):
""" Modifies the counts dictionary in place to produce fractional weights.
Each weight is the ratio of this keyword to the total size of the body
of keywords. """
for k in counts.keys():
counts[k] /= total
return counts |
def none_if_na(s):
"""Return None if s == 'N/A'. Return s otherwise."""
return None if s == 'N/A' else s |
def countSelectedPairs(all_selected_idx, print_msg = True, string = 'Major merger cut: '):
"""
Function to count selected pairs from the list of lists outputted by ball tree
@all_selected_idx ::
"""
count_selected_pairs = 0
for j, mm in enumerate(all_selected_idx):
if len(... |
def ABCDFrequencyList_to_HFrequencyList(ABCD_frequency_list):
""" Converts ABCD parameters into h-parameters. ABCD-parameters should be in the form [[f,A,B,C,D],...]
Returns data in the form
[[f,h11,h12,h21,h22],...]
"""
h_frequency_list=[]
for row in ABCD_frequency_list[:]:
[frequency,A... |
def largest_element(a,loc=False):
""" Return the largest element of a sequence a.
"""
maxval = a[0]
indicii = 0
for i in range(1, len(a)):
if a[i] > maxval:
maxval = a[i]
indicii = i
large = sorted(a)
index = len(a)
if loc == True:
#return large[ind... |
def pitremove(np, input, output):
""" command: pitremove -z dem.tif -fel demfel.tif, demfile: input elevation grid, felfile: output elevations with pits filled """
pitremove = "mpirun -np {} pitremove -z {} -fel {}".format(
np, input, output)
return pitremove |
def DM_Sum(DMvec, qlist):
"""Helper function to matrix dot product the DM matrix with a qvector
Assumes that DMVec is the same length as qlist
"""
sum = 0
for j in range(len(DMvec)):
sum += DMvec[j]*qlist[j]
return sum |
def get_rnx_band_from_freq(frequency):
"""
Obtain the frequency band
>>> get_rnx_band_from_freq(1575420030.0)
1
>>> get_rnx_band_from_freq(1600875010.0)
1
>>> get_rnx_band_from_freq(1176450050.0)
5
>>> get_rnx_band_from_freq(1561097980.0)
2
"""
# Backwards compatibility... |
def ncartesian(L):
"""
Computes the number of cartesian functions for a given angular momentum.
Parameters
----------
L : int
The input angular momentum
Returns
-------
ncartesian : int
The number of cartesian functions
"""
return int((L + 1) * (L + 2) / 2) |
def IndexOfMin(inputList):
"""
Return the index of the min value in the supplied list
"""
assert(len(inputList) > 0)
index = 0
minVal = inputList[0]
for i, val in enumerate(inputList[1:]):
if val < minVal:
minVal = val
index = i + 1
return index |
def doc_missing(obj):
"""
Check *obj* for a non-empty __doc__ element
"""
if not hasattr(obj, '__doc__') or obj.__doc__ is None:
return True
else:
return False |
def min_bounded(table, coin_denminations, i, j):
"""
we have the case where if anything = 0 it means we can't make that value of j
additionally when checking in the same row to extend the solution, should check if the value is 0
if so we can't just +1 to it
if both value are 0, return 0
else if... |
def whitespace(line):
"""Return index of first non whitespace character on a line."""
i = 0
for char in line:
if char != " ":
break
i += 1
return i |
def swap_dictionary(dictionary):
"""Swap keys for values in the given dictionary
>>> swap_dictionary({'one': 1})[1] == 'one'
True
"""
if dictionary is None:
return None
return {v: k for k, v in dictionary.items()} |
def _cdp_split_reads_for_header(split_align_dict, split_align_count_dict, seq_dict):
"""
Dict -->Even split read aligned counts, so total reads aligned = read count
in original seq file
{header:split_count}
"""
header_split_count = {}
for header, sRNA_dict in split_align_dict.items():
... |
def encode_string(ls):
"""
Question 7.12: Implement run-length encoding
for strings
"""
result = []
last = ls[0]
count = 1
for elt in ls[1:]:
if elt != last:
result.append(str(count))
result.append(last)
count = 1
else:
coun... |
def is_balanced(node):
""" 4.4 Check Balanced: Implement a function to check if a binary tree is
balanced. For the purposes of this question, a balanced tree is defined to
be a tree such that the heights of the two subtrees of any node never
differ by more than one
"""
def max_and_min_heights(no... |
def retsup_cmp(a, b):
"""
:param a, b:
:return:
"""
ret = b[1] - a[1]
if ret == 0:
al = a[0]
bl = b[0]
if al == bl:
ret = 0
elif al < bl:
ret = -1
else:
ret = 1
return ret |
def intervals_union(S):
"""Union of intervals
:param S: list of pairs (low, high) defining intervals [low, high)
:returns: ordered list of disjoint intervals with the same union as S
:complexity: O(n log n)
"""
E = [(low, -1) for (low, high) in S]
E += [(high, +1) for (low, high) in S]
... |
def force_force_list(data):
"""Wrap data in list.
We need to define this awkardly named method because DoJSON's method
force_list returns tuples or None instead of lists.
"""
if data is None:
return []
elif not isinstance(data, (list, tuple, set)):
return [data]
elif isinstan... |
def _select_rej_stat(rej_stat, ewmean, ewsdev, uwmean, uwsdev, uwmed, uwmad):
"""
Select and return the desired rejection statistic.
"""
if rej_stat == 'ew':
return ewmean, ewsdev
if rej_stat == 'uw':
return uwmean, uwsdev
if rej_stat == 'ro':
return uwmed, uwmad
rai... |
def isCSERelative(uri : str) -> bool:
""" Check whether a URI is CSE-Relative. """
return uri is not None and uri[0] != '/' |
def fuzzyMatch(string1, string2):
"""Compare the English character content of two strings."""
replacements = {"1": "one", "2": "two", "3": "three", "4": "four", "5": "five", "6": "six", "7": "seven",
"8": "eight", "9": "nine", "gonna": "going to"}
whiteout = '.,"\'!?/$()'
string1 = s... |
def normalize_prefix(prefix):
"""
Removes slashes from a URL path prefix.
:param str prefix:
:rtype: str
"""
if prefix and prefix.startswith("/"):
prefix = prefix[1:]
if prefix and prefix.endswith("/"):
prefix = prefix[:-1]
return prefix |
def conflict(prec, other_prec):
"""Whether the ranges `prec` and `other_prec` overlap."""
a, b = prec
c, d = other_prec
return (a <= c and c <= b) or (c <= a and a <= d) |
def inherits_from(obj, a_class):
""" Returns booleanType response
for class inheritance test
Args:
obj: object to evaluate
a_class: class value for testing
"""
if (type(obj) != a_class):
return isinstance(obj, a_class)
else:
return False |
def _get_paths(base_path):
"""
A service endpoints base path is typically something like /preview/mlflow/experiment.
We should register paths like /api/2.0/preview/mlflow/experiment and
/ajax-api/2.0/preview/mlflow/experiment in the Flask router.
"""
return ['/api/2.0{}'.format(base_path), '/aja... |
def process_url(url):
""" Process url to get to correct page
"""
url += '&showAllReviews=true'
return url |
def build_about_page_url_from_id(user_id):
"""
>>> build_about_page_url_from_id(123)
'https://mbasic.facebook.com/profile.php?v=info&id=123'
"""
return "https://mbasic.facebook.com/profile.php?v=info&id={0}". \
format(user_id) |
def chk_for_gz(filenm):
""" Checks for .gz extension to an input filename and returns file
Also parses the ~ if given
Parameters
----------
filenm : string
Filename to query
Returns
-------
filenm+XX : string
Returns in this order:
i. Input filename if it exists
... |
def call_instance_method(instance, name, args, kwargs):
"""indirect caller for instance methods for multiprocessing
Args:
instance: the instance to call method with
name (str): method name to call
args (tuple or None): arguments to be passed to getattr(instance, name)
kwargs (di... |
def get_options(options):
"""
Get options for dcc.Dropdown from a list of options
"""
opts = []
for opt in options:
opts.append({'label': opt.title(), 'value': opt})
return opts |
def calc_internal_hours(entries):
"""
Calculates internal utilizable hours from an array of entry dictionaries
"""
internal_hours = 0.0
for entry in entries:
if entry['project_name'][:22] == "TTS Acq / Internal Acq" and not entry['billable']:
internal_hours = internal_hours + flo... |
def readAttributes(serverName, itemId, attributeIds, startDate, endDate):
"""Reads the specified attributes for the given item over a time
range.
Attributes and their IDs are defined in the OPC-HDA specification,
and can be discovered by calling system.opchda.getAttributes().
Args:
serverN... |
def require_channel(slack_event_json):
"""
Require a channel be present in the JSON from the Events API
:params dict slack_event_json: The JSON from the events API
:rtype: bool (False) or str
"""
# Get the channel, else false so we
# don't reply to mention without channel info
# eg: me... |
def kalkulasi_waktu(
kecepatan_akhir: float, kecepatan_awal: float, percepatan: float
) -> float:
"""
Menghitung waktu
>>> kalkulasi_waktu(10, 22, 2.4)
-5.0
>>> kalkulasi_waktu(9, 0, 7.2)
1.25
"""
return (kecepatan_akhir - kecepatan_awal) / percepatan |
def calculate_frip(nreads, noverlaps):
""" calculate FRiP score from nreads and noverlaps """
return( float(noverlaps) / nreads ) |
def get_components_with_cve(components):
"""Get all components with CVE record(s)."""
result = []
for component in components:
assert "security" in component
cve_items = component["security"]
for cve_item in cve_items:
if "CVE" in cve_item:
result.append(... |
def find_index(p, xs):
"""Returns the index of the first element of the list which matches the
predicate, or -1 if no element matches.
Acts as a transducer if a transformer is given in list position"""
for i in (i for i, x in enumerate(xs) if p(x)):
return i |
def should_render_json(accepts, content_type):
"""Check accepts and content_type to see if we should render JSON."""
return 'application/json' in accepts or content_type == 'application/json' |
def largest_element(a, loc = False):
""" Return the largest element of a sequence a.
"""
max = a[0]
maxelem = 0
try:
for i in range(0, len(a)):
if a[i] > max:
max = a[i]
maxelem = i
if (loc):
return (max, maxelem)
return... |
def random_str(length=8):
""" Return random string of specified length """
import string
import random
choose_from = string.ascii_letters + string.ascii_uppercase + string.digits
return ''.join(random.choice(choose_from) for _ in range(length)) |
def sent_padding(tokens_list, SEQ_LEN):
""" Padding the token list with '-1' up to SEQ_LEN """
final_list = tokens_list
for i in range(len(tokens_list), SEQ_LEN):
final_list.append(-1)
return final_list |
def isValidChannelName(channelName):
"""
Determines whether the given channel name is in a valid format.
"""
if channelName[0] != "#":
return False
for char in "\x07 ,?*": # \x07, space, and comma are explicitly denied by RFC; * and ? make matching a channel name difficult
if char in channelName:
return Fal... |
def create_smifile_from_string(smiles='', filename=''):
"""
Writes a SMILES string to a file.
:param smiles: SMILES Code of the molecule.
:param filename: Filename (.smi)
:return:
"""
f = open(filename, 'w')
f.write(smiles)
f.close()
return 0 |
def age_name(
agenamelist, prefixes=["Lower", "Middle", "Upper"], suffixes=["Stage", "Series"]
):
"""
Condenses an agename list to a specific agename, given a subset of
ambiguous_names.
Parameters
----------
agenamelist : :class:`list`
List of name components (i.e. :code:`[Eon, Era,... |
def get_fg_tone(value):
"""Returns a foreground black-white color in the range 0-24"""
return '38;5;%d' % (232 + int(value)) |
def pruner(data):
"""
Prune the data to remove the data that is not needed.
:param data: The data to be pruned.
:type data: dict
:return: The pruned data.
:rtype: dict
"""
new_data = {}
for k, v in data.items():
if isinstance(v, dict):
v = pruner(v)
if not... |
def get_multi_values(columns_to_insert,insert_values_dict_lst):
"""
returns the values for the placeholders in query.
:param columns_to_insert:
:param insert_values_dict_lst:
:return:
"""
values = []
for value_dict in insert_values_dict_lst:
for col in columns_to_insert:
... |
def getCommands(args):
"""Split (if needed) and obtain the list of commands that were sent into Skelebot"""
commands = []
command = []
for arg in args:
if arg == "+":
commands.append(command)
command = []
else:
command.append(arg)
commands.append(... |
def distance(x1,y1,x2,y2):
"""
Compute the distance between two points
"""
dist=((x1-x2)**2+(y1-y2)**2)**0.5
return dist |
def sort_states_response(response_list):
"""Sorting response since on Travis order of breakdown response list is different"""
return sorted(response_list, key=lambda k: k['fips']) |
def lowest_uniq_timestamp(used_timestamps, timestamp):
"""resolve duplicate timestamps by appending a decimal 1234, 1234 -> 1234.1, 1234.2"""
timestamp = timestamp.split('.')[0]
nonce = 0
# first try 152323423 before 152323423.0
if timestamp not in used_timestamps:
return timestamp
ne... |
def sigma_z(state, site):
"""
Returns `(sign, state)` where `sign` is 1 or -1 if the `site`th bit of the int `state`
is 0 or 1 respectively. Can also accept numpy arrays of ints and gives numpy arrays back
"""
return (-1.0) ** ((state >> site) & 1), state |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.