content stringlengths 42 6.51k |
|---|
def solution1(nums):
"""
Inefficient solution written by myself
---
:type nums: list[int]
:rtype: list[int]
"""
repeated_nums = []
for i, num in enumerate(nums):
if num in nums[:i]:
repeated_nums.append(num)
return repeated_nums |
def _GetFields(trace=None):
"""Returns the field names to include in the help text for a component."""
del trace # Unused.
return [
'type_name',
'string_form',
'file',
'line',
'docstring',
'init_docstring',
'class_docstring',
'call_docstring',
'length',
... |
def get_branch(branch_dict, n_hash_chars=7, hash_prefix=':'):
"""
Extract branch name from banch meta data.
If no branch name is found, fall back to HEAD's hash.
Arguments
---------
branch_dict: dict
branch meta data dictionary
n_hash_chars: int
number of characters to print... |
def feature_vectors_calculated_message(body):
"""
Method for make message with data which would be send
to rabbitmq features vectors calculated queue, if calculation success
:param body: body of message received from RabbitMQ queue
:type body: dict
:return: features vectors calculated message
... |
def arg_str2dict(arg):
"""
Converting argument from "arg1=va1 arg2=val2 ..." to dict {arg1:va1, arg2:val2, ...}
:param args: str
:return: dict
"""
try:
arg_dict = {i.split('=')[0]: i.split('=')[1] for i in arg.split()}
except Exception as e:
raise TypeError(
"Inva... |
def small_vote_power(karma):
"""See
https://github.com/LessWrong2/Lesswrong2/blob/devel/packages/lesswrong/lib/voting/new_vote_types.ts
for the vote power implementation. See also the blog post at
https://lw2.issarice.com/posts/7Sx3CJXA7JHxY2yDG/strong-votes-update-deployed#Vote_Power_by_Karma"""
if... |
def _article_has_problem(article):
"""Helper function to filter out articles with problems.
:param article: input article
:type article: dict
:return: `True` or `False`
:rtype: boolean
"""
return article['has_problem'] |
def dict_domains_in_chromosomes(domains_list):
"""Given a list of domains (chr start end) return a dictionary of with chromosomes as keys and list of domains
as values"""
chromosomes = {}
for i in domains_list:
chrom = i[0]
if chrom not in chromosomes.keys():
chromosomes[chro... |
def get_closest_fibonacci_number(current_fib: int, previous_fib: int, fibonacci_number: int) -> int:
"""
Returns the fibonacci number with the shortest distance of two consecutive fibonacci numbers.
"""
if abs(previous_fib - fibonacci_number) <= abs(current_fib - fibonacci_number):
return previo... |
def proxy_three(f, args, stdin, stdout, stderr, spec, stack):
"""Calls a proxy function which takes three parameter: args, stdin, stdout.
"""
return f(args, stdin, stdout) |
def _build_param_docstring(param):
"""Builds param docstring from the param dict
:param param: data to create docstring from
:type param: dict
:returns: string giving meta info
Example: ::
status (string) : Statuses to be considered for filter
from_date (string) : Start date filter... |
def check_matrix_equality(A, B, tol=None):
"""
Checks the equality of two matrices.
:param A: The first matrix
:param B: The second matrix
:param tol: The decimal place tolerance of the check
:return: The boolean result of the equality check
"""
# Section 1: First... |
def vec_cross (v1,v2):
""" vector cross product """
return [ (v1[1] * v2[2]) - ( v1[2] * v2[1]), (v1[2] * v2[0]) - ( v1[0] * v2[2]), (v1[0] * v2[1]) - ( v1[1] * v2[0]) ] |
def _pad_jagged_sequence(seq):
"""
Pads a 2D jagged sequence with the default value of the element type to make it rectangular.
The type of each sequence (tuple, list, etc) is maintained.
"""
columns = max(map(len, seq)) # gets length of the longest row
return type(seq)(
(
... |
def clean_prefix(x: str, prefix: str) -> str:
"""Remove a prefix and all options from the command x."""
if not x.startswith(prefix):
return x
x = x[len(prefix) :]
i = 0
last_was_minus = False
for i, char in enumerate(x):
if last_was_minus:
if char == " ":
... |
def get_maximum_samples_to_search_among(maximum_samples_to_search_among, X_unlabelled_np, nr_of_samples):
"""
get_maximum_samples_to_search_among internal function used by the module
Returns the number of samples that should be searched among.
If maximum_samples_to_search_among.lower() == "all", it re... |
def puncify(s):
"""Replaces unicode characters with the appropriate ASCII punctuation"""
return s.replace(u'\xa0', u' ').replace(u'\u201c', '"').replace(u'\u201d', '"').replace(u'\u2019', "'").replace(u"&", '&').replace(u'\u2026', '...') |
def GetUpdatesUrl(project_name, max_results=1000):
"""Construct the URL to the issues updates for the given project."""
return ('http://code.google.com/feeds/p/%s'
'/issueupdates/basic?max-results=%d' %
(project_name, max_results)) |
def _cached_call(cache, estimator, method, *args, **kwargs):
"""Call estimator with method and args and kwargs."""
if cache is None:
return getattr(estimator, method)(*args, **kwargs)
try:
return cache[method]
except KeyError:
result = getattr(estimator, method)(*args, **kwargs)... |
def _find_stream_by_type(streams, stream_type="EEG"):
"""Find the first stream that matches the given type."""
for stream in streams:
if stream["info"]["type"][0] == stream_type:
return stream |
def dict_keys_to_comma_str(dict):
""" Comma seperates dict keys into string
Args:
dict (dict): A dictionary.
Returns:
str: Comma seperated string of keys.
"""
return ', '.join([str(i) for i in dict.keys()]) |
def _capitalize_first_letter(c):
"""Capitalize the first letter of the input.
Unlike the built-in capitalize() method, doesn't lower-case the other
characters. This helps mimic the behavior of proto-lens-protoc, which turns
Foo/Bar/BAZ.proto into Foo/Bar/BAZ.hs (rather than Foo/Bar/Baz.hs).
Args:... |
def _groupid_artifactid(name):
"""
@name - string - package name of the form groupid:artifactid, e.g. junit:junit
@return - list - [groupid, artifactid]
"""
return name.split(':') |
def trunc(s, n):
"""
Truncate a string to N characters, appending '...' if truncated.
trunc('1234567890', 10) -> '1234567890'
trunc('12345678901', 10) -> '1234567890...'
"""
if not s:
return s
return s[:n] + "..." if len(s) > n else s |
def ngpu(gpus):
"""
count how many gpus used.
"""
gpus = [gpus] if isinstance(gpus, int) else list(gpus)
return len(gpus) |
def pentagon_number(n):
"""Get the nth pentagon number
Pn = n * (3 * n - 1) / 2
Test cases:
- 044
"""
pentagon = (n * (3 * n - 1)) / 2
return pentagon |
def same(effective_kernel_size: int):
"""Pads such that the output size matches input size for stride=1."""
return [(effective_kernel_size - 1) // 2, effective_kernel_size // 2] |
def track_prop_dict_length(track_prop_dict):
"""Returns the number of tracks in a track properties dictionary.
Raises an exception if the value lists in the input dictionary are
not all of the same length. Returns zero if the track properties
dict is empty."""
# A fancy way of checking if all value... |
def align_decimal(number, left_pad=7, precision=2):
"""Format a number in a way that will align decimal points."""
outer = '{0:>%i}.{1:<%i}' % (left_pad, precision)
inner = '{:.%if}' % (precision,)
return outer.format(*(inner.format(number).split('.'))) |
def factorial(a):
"""Accepts one integer and prints its factorial (recursive)"""
if a == 1 or a == 0:
return 1
else:
return factorial(a - 1) * a |
def int_to_bytes(integer: int) -> list:
"""
Converts a single integer number to an list with the length 2 with highest byte first.
The returned list contains values in the range [0-255]
:param integer: the integer to convert
:return: the list with the high byte first
"""
return [(integer >> ... |
def id_to_ec2_id(instance_id, template='i-%08x'):
"""Convert an instance ID (int) to an ec2 ID (i-[base 16 number])."""
return template % int(instance_id) |
def default_port(protocol):
""" Returns the default port based on the protocol
Args:
protocol (str): The protocol to return the default port for. Valid
values are "http" and "https"
Returns:
str: The default protocol port value as a string
"""
return '443' if protocol... |
def RelativeChange(before, after):
"""Returns the absolute value of the relative change between two values.
Args:
before: First value.
after: Second value.
Returns:
Relative change from the first to the second value, or infinity if the
first value is zero. This is guaranteed to be non-negative.
... |
def get_number_of_bills(budget: float, denomination: int) -> int:
"""Calculate the number of bills after exchanging whole budget.
:param budget: float - the amount of money you are planning to exchange.
:param denomination: int - the value of a single bill.
:return: int - number of bills after exchangi... |
def rotate_clockwise(shape):
""" Rotates a matrix clockwise """
return [[shape[len(shape)-y-1][x] for y in range(len(shape))] for x in range(len(shape[0]))] |
def find_val_or_next_smaller_iter(bst, x, d=None):
"""Get the greatest value <= x in a binary search tree.
Returns None if no such value can be found.
"""
while True:
if bst is None:
return d
elif bst.val == x:
return x
elif bst.val > x:
(bst, ... |
def get_gps_check_fail_flags(estimator_status: dict) -> dict:
"""
:param estimator_status:
:return:
"""
gps_fail_flags = dict()
# 0 : insufficient fix type (no 3D solution)
# 1 : minimum required sat count fail
# 2 : minimum required GDoP fail
# 3 : maximum allowed horizontal positi... |
def html_escape(s):
"""
Replace special characters "&", "<" and ">" to HTML-safe sequences.
If the optional flag quote is true, the quotation mark character (")
is also translated.
"""
s = s.replace("&", "&")
s = s.replace("<", "<")
s = s.replace(">", ">")
s = s.replace(" "... |
def __split_line_comment(line):
"""
Splits a line into the data part and the comment part
@ In, line, string, line
@ Out, (data, comment), (string, string), The comment part maybe empty
"""
data = ''
comment = ''
in_string = False
in_comment = False
for char in line:
if char == "'":
... |
def process_3col_csv(lol, type_id):
"""
3 column format is a legacy format that allows for a ds config
file in the format of:
new-ds-name,new-ds-ip,rec-ip
linux_123,10.0.2.3,172.16.12.30
This is dependant on creating a section in the ini file
called [types] with f... |
def add_leading_gaps(t_aligned, s_aligned, i, j):
"""Add the leading gaps to alignments."""
for _ in range(i):
t_aligned = t_aligned[:0] + '-' + t_aligned[0:]
for _ in range(j):
s_aligned = s_aligned[:0] + '-' + s_aligned[0:] # pragma: no cover
return s_aligned, t_aligned |
def producto_punto(vector_a, vector_b):
"""
(list, list) -> num
calcula el producto escalar entre dos vectores
>>> producto_punto([1,2], [1,2])
5
>>> producto_punto([2,2,2], [2,2,2])
12
:param vector_a: el primer vector
:param vector_b: el segundo vector
:return: num el escal... |
def matrixMul(a, b):
"""
Returns the product of the given matrices
"""
# Initializing Empty Matrix
c = [[0, 0], [0, 0]]
# 2x2 matrix multiplication. Essentially O(1)
for i in range(2):
for j in range(2):
for k in range(2):
c[i][j] = (c[i][j] + (a[i][k... |
def lower_dict_keys(some_dict):
"""Convert all keys to lowercase"""
result = {}
for key, value in some_dict.items():
try:
result[key.lower()] = value
except AttributeError:
result[key] = value
return result |
def cw_distance(az1: float, az2: float) -> float:
"""
Calculates the 'clockwise' distance between two azimuths, where 0 = North
and the direction of increasing angle is clockwise.
:param az1: Azimuth 1.
:type az1: float
:param az2: Azimuth 2.
:type az2: float
:returns: The angular dista... |
def MatchingBtoC(B, C):
"""
Searches observations in B, and returns a dict of which source is in which publication.
"""
my_search = dict()
for obj in B:
if obj:
name = obj['Source_Name']
my_search[name] = []
for index, pub in enumerate(C):
... |
def keyword_detection(text, keyword):
"""
keyword detection function from given input text and keyword to be detected in the text.
arguments:
-- text -- input text <string>
-- keyword -- keyword to be found in the text <string>
return:
-- Boolean True ... |
def line2dict (feat_names, feat_vals, ignore_blank):
""" Create dictionary from the input line."""
result = {}
if len(feat_names) != len(feat_vals):
raise ValueError("Feature vector length does not match: expected=%s got=%s" % (len(feat_names),len(feat_vals)))
for i in range(len(feat_names)):
... |
def make_disjoint_sets(lists):
"""
Take list of lists and create disjoint lists by merging the input lists
:param lists:
:return:
"""
sets = [set(l) for l in lists]
merged = True
while merged:
merged = False
result = []
while sets:
common, rest = sets... |
def make_sequence_tree(size):
"""Make a maximally unbalanced tree (a sequence) with size nodes."""
if size <= 1:
return 0
return (make_sequence_tree(size-1), 0) |
def nds_coord(x, y, width, height):
"""Convert SCS to NDS."""
return (2 * x - width) / width, (height - 2 * y) / height |
def rtable_q_target(route_entry):
"""
Args:
route_entry: (dict)
Returns:
string: returns route table entry destination exit point
"""
if route_entry.get('GatewayId'):
return route_entry.get('GatewayId')
elif route_entry.get('InstanceId... |
def format_dict(dict_: dict) -> str:
"""Method to take a dictionary and
return a string of comma seperated key, value
in below format
>>> d = {"key1": "value1", "key2": "value2"}
>>> s = format_dict(d)
>>> assert s == "key1=value1, key2=value2"
"""
pairs = []
for key, value in dict_... |
def force_harmonic(x, x0, k):
"""
force_harmonic(x, x0, k)
Returns force acting from displacememt of x away from x0 from harmonic potential
"""
return 2 * k * (x0 - x) |
def ct_compare(a, b):
"""
** From Django source **
Run a constant time comparison against two strings
Returns true if a and b are equal.
a and b must both be the same length, or False is
returned immediately
"""
if len(a) != len(b):
return False
result = 0
for ch_a, ch_b in zip(a, b):
result |= ord(c... |
def pad(value, return_type=str):
"""
Pad binary value with zeros
:param value: string
:param return_type: string
"""
if type(value) is not str:
raise TypeError("pad only accepts str, not {}".format(str(type(value))))
if len(value) % 4 != 0:
pad_amount = 4 - (len(v... |
def argmax(a):
"""Return (index,val) for the largest element in a"""
besti = -1
for i in range(len(a)):
if besti == -1 or a[i] > a[besti]:
besti = i
return besti, a[besti] |
def directory_fmt(directory):
"""In ensure that directories end with '/'; fixes recursive copy."""
return directory.rstrip('/') + '/' |
def vnfd_vl_maps_on_nsd_vl(nsd, vnfd, vl):
"""
This method returns whether a vnfd vl maps on an nsd vl
"""
name = vnfd['name']
version = vnfd['version']
vendor = vnfd['vendor']
res_cp = None
for cp in vl['connection_points_reference']:
if ':' not in cp:
res_cp = cp... |
def get_requested_roles(settings):
"""Retrieve any valid requested_roles from dict settings"""
if ('requested_roles' in settings and
settings['requested_roles'] not in ['None', None]):
return settings['requested_roles'].split(',')
else:
return [] |
def reward_1(distance_to_center_line, delta_heading, current_speed, target_speed,
max_reward=1.0, min_reward=-1.0, weights=[0.6, 0.4, 0.5]):
"""Returns the reward based on distance to center line and delta heading"""
# Distance reward 1
distance_reward = max(
max_reward - (distance_to_c... |
def capitalize(string):
"""Return string with first character capitalised. Some acronym like XML, XRC.
@note: Be carefully it possibly breaks i18n."""
# Don't capitalise those terms
if string.upper() in ['XML', 'XRC', 'URL']:
return string.upper()
return string.capitalize() |
def calculate_levenshtein_distance(string1, string2):
"""
Compute the minimum number of substitutions, deletions, and additions
needed to change string1 into string2.
Parameters
----------
string1 : str
string to calculate distance from
string2 : str
string to calculate dist... |
def rhs_count(list_to_search, sublist):
"""Returns count of occurances of sublist in list_to_search."""
if len(sublist) > len(list_to_search):
return 0
count = 0
for idx in range(len(list_to_search) - len(sublist) + 1):
if list_to_search[idx:idx + len(sublist)] == sublist:
count += 1
return coun... |
def is_zero_dict( dict ):
"""
Identifies empty feature vectors
"""
has_any_features = False
for key in dict:
has_any_features = has_any_features or dict[key]
return not has_any_features |
def globalOutgassing(Fmod_out, Q, m):
"""
This function will calculate the outgassing flux (equation S9).
Inputs:
Fmod_out - the modern Earth's outgassing rate [mol C yr-1]
Q - pore space heat flow relative to modern Earth [dimensionless]
m - scaling parameter [dimensi... |
def _default_cache_key(args, kwargs):
"""By default, toolz.memoize will only cache positional args if no cache
key is passed and it can't determine if there's keyword arguments. However,
this will cause memoize to cache *both* if a cache key func isn't provided.
"""
return (args or None, frozenset(k... |
def add_IFD(metadata: dict, ifd: str) -> dict:
"""Adds an empty object to a dictionary if one does not already exist"""
if ifd not in metadata:
metadata.update({ifd: {}})
return metadata |
def has_disk_dev(mapping, disk_dev):
"""Determine if a disk device name has already been used.
Looks at all the keys in mapping to see if any
corresponding disk_info tuple has a device name
matching disk_dev
Returns True if the disk_dev is in use."""
for disk in mapping:
i... |
def alpha_operation_sorter(endpoint):
""" sort endpoints first alphanumerically by path, then by method order """
path, method, callback = endpoint
method_priority = {
'GET': 0,
'POST': 1,
'PUT': 2,
'PATCH': 3,
'DELETE': 4
}.get(method, 5)
return path, method_... |
def _get_experiment_name(experiment_config: dict) -> str:
"""Returns the name of the experiment described by |experiment_config| as a
string."""
# Use str because the yaml parser will parse things like `2020-05-06` as
# a datetime if not included in quotes.
return str(experiment_config['experiment']... |
def _is_madx_string_col_identifier(type_str: str) -> bool:
"""
``MAD-X`` likes to return the string columns by also indicating their width, so trying to parse
`%s` identifiers only we might miss those looking like `%20s` specifying (here) a 20-character
wide column for strings.
Args:
type_... |
def collapse_lines(str):
""" strip() each line in a string and return the remaining non-empty lines joined together"""
return ''.join(filter(bool, (line.strip() for line in str.split('\n')))) |
def slice_whole(x,u,step,lnpdf,pdf_params,isDomainFinite,domain):
"""
NAME:
slice_whole
PURPOSE:
create the interval in slice sampling by using the whole, finite domain
INPUT:
x - current sample
u - current (log) height of the slice
step - step ... |
def type_dist(corpus):
"""Counts number of types in a corpus"""
output = {}
for text in corpus:
for word_type in set(text):
output[word_type] = output.get(word_type, 0) + 1
return output |
def gray_encode(i):
"""Gray encode the given integer."""
return i ^ (i >> 1) |
def values_from_list_of_dicts(lst, key):
"""
Converts a list of dictionaries to a list of values from the given key.
"""
return [d[key] if isinstance(d, dict) else d[0][key] for d in lst] |
def maybe_route_func(func, count):
"""
Routes the given `func` `count` times if applicable.
Parameters
----------
func : `callable`
The respective callable to ass
count : `int`
The expected amount of functions to return.
Returns
-------
result : `list` of `f... |
def distance2(cell1, cell2):
"""Return euclidean distance between cells."""
return ((cell1[0] - cell2[0])**2 + (cell1[1] - cell2[1])**2)**0.5 |
def get_ir_frame_number(rgb_idx, n_ir, n_rgb):
"""Returns index of IR frame corresponding to the RGB frame idx."""
ir_idx = round(n_ir*float(rgb_idx)/n_rgb)
return ir_idx |
def square(root):
"""This function calculates the square of the argument value"""
result = root * root
return result |
def get_inverse_matrix(matrix, size):
"""
Since we cannot use numpy, we need to do the matrix inversion
Use Gaussian elimination simplified for our case as we know that the matrix can be inversed
:param matrix: the matrix to be inverted
:param size: the matrix size
:return: the inverted matrix
... |
def revpow(n, base):
"""
Reverse of ``pow`` built-in function.
>>> for i in range(4):
... revpow(pow(2, i), 2) == i
...
True
True
True
True
:param n: number that is a power of base
:param base: the base
:return: int
"""
res = 0
... |
def is_comparison_pass(avg_historical_throughput, test_throughput, tolerance, ref_type='none'):
""" Determine whether or not to consider the benchmark test as passed.
This is based on whether the throughput of the microbenchmark has decreased
more than the allowed tolerance %.
Parameters
-... |
def tc(text: str) -> str:
"""Filter for table cell content."""
return text.replace("|", "{vbar}") |
def _remove_trailing_zeros(lst):
"""
Removes any zeros at the end of the list.
"""
k=0
for k, value in enumerate( lst[::-1] ):
if value != 0:
break
lst_no_trailing_zeroes = lst if k == 0 else lst[:-k]
return lst_no_trailing_zeroes |
def part1(data):
"""
>>> part1([[5, 1, 9, 5], [7, 5, 3], [2, 4, 6, 8,]])
18
>>> part1(read_input())
43074
"""
return sum(max(row) - min(row) for row in data) |
def _full_index(sample_id_col):
"""Return all columns necessary to uniquely specify a junction"""
return [sample_id_col, 'chrom', 'intron_start', 'intron_stop', 'strand'] |
def filter_func(row):
"""
Filter function for data
:param row: row, dictionary
:return: True if it should be included, False if skipped
"""
items_to_keep = {"99197", "105574", "1963838"}
return row['item_nbr'] in items_to_keep |
def orGate(argumentValues):
"""
Method that evaluates the OR gate
@ In, argumentValues, list, list of values
@ Out, outcome, float, calculated outcome of the gate
"""
if 1 in argumentValues:
outcome = 1
else:
outcome = 0
return outcome |
def PieceWiseOptimalityFunction(Min, Optimal, Max, X_in):
"""
A piecewise function of X_in, with parameters of Min, Max, and Optimal, that will return a number between 0 and 1.
A linear increase from 0 to 1 across the X_in range of (Min, Optimal].
A linear decrease from 1 to 0 across the X_in range of (... |
def dot_to_underscore(string):
"""
Replace every dot with an underscore in a string.
"""
return string.replace('.','_') |
def factorial(i):
"""
This function return i! if i is in [1, 10], -1 otherwise.
"""
if i <=0 or i >10:
return -1
curr = 1
for k in range(2, i+1):
curr *= k
return curr |
def dict_islice(Dict, *keys):
"""Returns a shallow copy of the subset of a given dict (or an otherwise
hashable object) with a given set of keys.
The return object is a dict.
This is similar to dict_slice, except that missing keys in
Dict will be ignored.
"""
# This is fancy but we require Dict to have ke... |
def _range_checker(ip_check, first, last):
"""
Tests whether an ip address is within the bounds of the first and last address.
:param ip_check: The ip to test if it is within first and last.
:param first: The first IP in the range to test against.
:param last: The last IP in the range to test again... |
def xorbytes(a, b):
""" Convert from bytes > int > xor > int > bytes """
a = int.from_bytes(a, byteorder='big')
b = int.from_bytes(b, byteorder='big')
xor = a ^ b
# Determine number of bytes, equivalent to math.ceil
numbytes = (xor.bit_length() + 7) // 8
return xor.to_bytes(numbytes, byteord... |
def unsquash(string):
"""camelCase / PascalCase -> camel Case / Pascal Case"""
new = ""
for char in string:
new += f" {char}" if char.isupper() else char
return new.strip() |
def common(expected_payload, json_data):
"""
The expected payload is the expected data and we compare it
to the json data
"""
for key in json_data.keys():
if key not in expected_payload:
msg = 'The field {} is not required'.format(key)
return {"status": "Failed!", "m... |
def kUB_(B,kUB,Cooperativity,P):
"""Returns the receptor binding rate kUB for either the cooperative or the non-cooperative binding model.
Parameters
----------
B : float
Number of bound receptors.
kUB : float
Rate at which AMPARs bind to PSD slots.
Cooperativity : 0, 1
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.