content
stringlengths
42
6.51k
def is_list_unique(list_of_cards): """ Checks if list members are unique :param list_of_cards: :return: """ salonga = False buffer = list(set(list_of_cards)) if len(buffer) == len(list_of_cards): salonga = True return salonga
def _add_trits(left: int, right: int) -> int: """ Adds two individual trits together. The result is always a single trit. """ res = left + right return res if -2 < res < 2 else (res < 0) - (res > 0)
def is_prime(num): """Uses the (6k+-1) algorithm; all primes > 3 are of the form 6k+-1, since 2 divides (6k+0), (6k+2), (6k+4), and 3 divides (6k+3).""" if num == 2 or num == 3: return True if num % 6 not in (1, 5) or num == 1: return False i = 5 while i in range(int(num**.5)+1): if not num % i: return False i += (i + 3) % 6 return True
def find_period(n, a): """ Classical period-finding algorithm, by simply increasing the power by 1, till the a^p mod n = 1. :param n: The number that should be factored into primes. :param a: A number co-prime with n. :return: The period after which a^p mod n = 1. """ for i in range(2 * n ** 2)[1:]: if pow(a, i, n) == 1: return i
def precision_at_k(k, relevant, retrieved, ignore = []): """ Computes the precision among the top `k` retrieval results for a particular query. k - Number of best-scoring results to be considered. Instead of a single number, a list of `k` values may be given to evaluate precision at. In this case, this function will return a list of corresponding precisions as well. relevant - Ground-Truth: Set of IDs relevant to the query. retrieved - Ranked list of retrieved IDs. ignore - Optionally, a set of IDs to be ignored, i.e., to be counted neither as true nor as false positive. Returns: Precision@k, given as a single number or a list, depending on the value of `k` """ ks = [k] if isinstance(k, int) else list(k) ks.sort() k_index = 0 precisions = [] rank, tp = 0, 0 for ret in retrieved: if ret not in ignore: if ret in relevant: tp += 1 rank += 1 while (k_index < len(ks)) and (rank >= ks[k_index]): precisions.append(float(tp) / float(rank)) k_index += 1 if k_index >= len(ks): break return precisions[0] if isinstance(k, int) else precisions
def colored(color, text): """ Returns a string of text suitable for colored output on a terminal. """ # These magic numbers are standard ANSI terminal escape codes for # formatting text. colors = { "red": "\033[0;31m", "green": "\033[0;32m", "blue": "\033[0;1;34m", "yellow": "\033[0;33m", "gray": "\033[0;90m", "bold": "\033[1m", "reset": "\033[0m", } return "{start}{text}{end}".format( start = colors.get(color, ""), end = colors["reset"], text = text, )
def get_child_object_id(parent, number): """ Returning child object entity_id """ if number < 10: s_number = "0" + str(number) else: s_number = str(number) return "{}_{}".format(parent, s_number)
def convert_rawdata(data_str): """Parse a C++ rawdata declaration into a list of values.""" start = data_str.find('{') end = data_str.find('}') if end == -1: end = len(data_str) if start > end: raise ValueError("Raw Data not parsible due to parentheses placement.") data_str = data_str[start + 1:end] results = [] for timing in [x.strip() for x in data_str.split(',')]: try: results.append(int(timing)) except ValueError: raise ValueError( "Raw Data contains a non-numeric value of '%s'." % timing) return results
def square_matrix_subtract(A, B): """ Subtract two square matrices of equal size. """ n = len(A) C = [[0] * n for _ in range(n)] for i in range(n): for j in range(n): C[i][j] = A[i][j] - B[i][j] return C
def add_slash(url): """Add a slash at the end of URL if the slash is not already presented.""" if url and not url.endswith('/'): url += '/' return url
def min_value_constraint(value, limit): """Test minimum value constraint.""" if value >= limit: return True return False
def extract_ratelimit(headers_dict): """Returns rate limit dict, extracted from full headers.""" return { "used": int(headers_dict.get("X-RateLimit-Used", 0)), "expire": float(headers_dict.get("X-RateLimit-Expire", 0)), "limit": int(headers_dict.get("X-RateLimit-Limit", 0)), "remain": int(headers_dict.get("X-RateLimit-Remaining", 0)), }
def _create_statistics_data(data_list, is_multi_series=False): """ Transforms the given list of data to the format suitable for presenting it on the front-end. Supports multi series charts (like line and bar charts) and or single series ones (like pie/donut charts). :param data_list: a list of pairs (label, value) :param is_multi_series: true if data will be shown on multi series charts :return: a dictionary of formatted input data """ statistics_data = { 'labels': [], 'series': [[]] if is_multi_series else [] } for data in data_list: statistics_data['labels'].append(data[0]) if is_multi_series: statistics_data['series'][0].append(data[1]) else: statistics_data['series'].append(data[1]) return statistics_data
def hexstr_to_bytes(input_str: str) -> bytes: """ Converts a hex string into bytes, removing the 0x if it's present. """ if input_str.startswith("0x") or input_str.startswith("0X"): return bytes.fromhex(input_str[2:]) return bytes.fromhex(input_str)
def command_clone(ctx, src, dest, mirror=False, branch=None): """Produce a command-line string to clone a repository. Take in ``ctx`` to allow more configurability down the road. """ cmd = ['git', 'clone'] if mirror: cmd.append("--mirror") if branch is not None: cmd.extend(["--branch", branch]) cmd.extend([src, dest]) return cmd
def is_address(provided): """ Check if the value is a proper Ethereum address. :param provided: The value to check. :return: True iff the value is of correct type. """ return type(provided) == bytes and len(provided) == 20
def number_of_digits(number): """ Returns the number of digits of @number. """ digits = 0 while number > 0: digits += 1 number /= 10 return digits
def chessboard_3DPoints(board_size, square_size): """ - board_size: a tuple (rows,columns) representing the number of rows and columns of the board. - square_size: the size of a square (cell) on the board in mm """ corners = [] for col in range(0, board_size[1]): for row in range(0, board_size[0]): corners.append((row * square_size, col * square_size, 0)) return corners
def get_gtest_filter(tests, invert=False): """Returns the GTest filter to filter the given test cases. Args: tests: List of test cases to filter. invert: Whether to invert the filter or not. Inverted, the filter will match everything except the given test cases. Returns: A string which can be supplied to --gtest_filter. """ # A colon-separated list of tests cases. # e.g. a:b:c matches a, b, c. # e.g. -a:b:c matches everything except a, b, c. test_filter = ':'.join(test for test in tests) if invert: return '-%s' % test_filter return test_filter
def to_boolean(input_string: str): """Returns True, False or None, based on the contents of the input_string (any form of capitalization is allowed)""" if input_string.lower() == "true": return True elif input_string.lower() == "false": return False else: return None
def tokenize_and_encode(obj,tokenizer): """ Tokenize and encode a nested object """ if isinstance(obj, str): return tokenizer.convert_tokens_to_ids(tokenizer.tokenize(obj)) elif isinstance(obj, int): return obj return list(tokenize_and_encode(o,tokenizer) for o in obj)
def fizzbuzz(x: int) -> str: """FizzBuzz >>> fizzbuzz(1) '1' >>> fizzbuzz(3) 'Fizz' >>> fizzbuzz(5) 'Buzz' >>> fizzbuzz(15) 'FizzBuzz' """ if x % 3 == 0 and x % 5 == 0: return "FizzBuzz" elif x % 3 == 0: return "Fizz" elif x % 5 == 0: return "Buzz" return str(x)
def add_111(any_number): """ This function adds 111 to any_number """ response = any_number + 111 print(f"Your number is: {response}") return response
def get_cscyc_colname(csname): """ Given 'csname' is a C-state name, this method retruns the corresponding C-state cycles count CSV column name. """ return f"{csname}Cyc"
def keyLengthInBitsOf(k): """Take a string k in I/O format and return the number of bits in it.""" return len(k) * 4
def decode_base64(data): """Decode base64, padding being optional. :param data: Base64 data as an ASCII byte string :returns: The decoded byte string. """ missing_padding = len(data) % 4 if missing_padding != 0: data += "=" * (4 - missing_padding) return data
def pixel_volume_to_cubed_um(pixel_volume, resolution_lateral_um, resolution_axial_um): """Convert volume in pixels to volume in cubed microns based on microscope resolution""" return pixel_volume * (resolution_lateral_um ** 2) * resolution_axial_um
def rgb_to_dec(value): """ Converts rgb to decimal colours (i.e. divides each value by 256) value: list (length 3) of RGB values Returns: list (length 3) of decimal values """ return [v / 256 for v in value]
def json_complex_hook(dct): """ Return an encoded complex number to it's python representation. :param dct: (dict) json encoded complex number (__complex__) :return: python complex number """ if isinstance(dct, dict): if '__complex__' in dct: parts = dct['__complex__'] assert len(parts) == 2 return parts[0] + parts[1] * 1j return dct
def match(reportBody: str, reportWeakness: str) -> bool: """ Returns whether or not the given report body or report weakness are about a sqli vulnerability """ return ("sqli" in reportBody.lower() or "sql injection" in reportBody.lower() or "SQL Injection" in reportWeakness)
def is_nan(x): """ Returns `True` if x is a NaN value. """ if isinstance(x, float): return x != x return False
def is_article(post_links, post): """Checks that an article is valid and returns a bool""" # Return false if post is a section of today.com if post["href"].count("-") < 4: return False # Return False if post is a video elif "video" in post["href"]: return False # Return False if post is already in post_links elif post["href"] in post_links: return False # If all checks pass, return True else: return True
def owl_or_skos(label_safe, prefixes): """ Build a generic RDF import substring. Parameters ---------- label_safe : string URI prefixes : dictionary dictionary {string : string} of prefix keys and conceptualization values Returns ------- conceptualisation : string "OWL" or "SKOS", default "OWL" """ return (prefixes[label_safe.split(":")[0]] if ( ":" in label_safe and "//" not in label_safe and not label_safe.startswith(":") and label_safe.split(":")[0] in prefixes ) else "OWL")
def check_name(name): """ Checks name for problematic characters and replaces them :param name: object name :type name: str :return: converted name :rtype: str """ name = name.replace('>', '_geq_') name = name.replace('<', '_leq_') name = name.replace('=', '_eq_') return name
def get_server_name(prefix, xid, wid): """Gets unique server name for each work unit in the experiment. Args: prefix: String, the prefix of the server. xid: Integer, the experiment id. wid: Integer, the work unit id. Returns: String. """ return f'{prefix}-{xid}-{wid}'
def create_dockerfile(dockerfile, tag, pythons): """Create a Dockerfile. Args: dockerfile: The path to the dockerfile. tag: The tag assigned after 'FROM' in the first line of the dockerfile. pythons: A list of python versions. Example: ['2.7.12', '3.4.1'] Returns: The contents of the dockerfile created. """ contents = [] with open(dockerfile, 'w') as dfile: contents.append('FROM {tag}\n'.format(tag=tag)) for python in pythons: contents.append('RUN pyenv install {python}\n'.format(python=python)) dfile.writelines(contents) return contents
def parse_logs(logs): """Load previous ... """ import json if isinstance(logs, str): print(len(logs)) logs = [logs] timings = [] for log in logs: with open(log, "r") as j: while True: try: iteration = next(j) except StopIteration: break iteration = json.loads(iteration) try: timings.append(iteration["datetime"]) except KeyError: pass return timings
def generate_sequential_BAOAB_string(force_group_list): """Generate BAOAB-like schemes that break up the "V R" step into multiple sequential updates >>> generate_sequential_BAOAB_string(force_group_list=(0,1,2)) ... "V0 R V1 R V2 R O R V2 R V1 R V0" """ VR = [] for i in force_group_list: VR.append("V{}".format(i)) VR.append("R") return " ".join(VR + ["O"] + VR[::-1])
def get_reproducibility(bib): """Description of get_reproducibility Generate insights on reproducibility """ cpt = 0 for entry in bib: if "code" in entry: if entry["code"][:2] != "No": cpt += 1 print(str(cpt) + " articles provide their source code.") return cpt
def fatorial(num, show=False): """ -> Calculo de Fatorial :param num: Numero a ser calculado :param show: (opcional) mostra o calculo :return: fatorial de num """ from math import factorial if show: for n in range(num, 0, -1): if n == 1: print(f'{n} = ', end='') else: print(f'{n} x ', end='') return factorial(num)
def order_typo_candidates(tcs): """ Order typo candidates, according to which have the highest maximum ratio between a candidate's count and a (suspected) typo's count. The idea is that the rarer a "typo" is, the more likely it is to be a genuine typo. Input: - tcs : list of tuples, [(typo, [(candidate, candidate_cnt, typo_cnt)])] Output: - ordered list of tuples, [(typo, [(candidate, candidate_cnt, typo_cnt)])] >>> t1 = ('t1', [('c1', 10, 1), ('c2', 11, 1)]) >>> t2 = ('t2', [('c1', 10, 4)]) >>> t3 = ('t3', [('c1', 10, 2), ('c3', 100, 99)]) >>> tcands = [t1, t2, t3] >>> order_typo_candidates(tcands) [('t1', [('c1', 10, 1), ('c2', 11, 1)]), ('t3', [('c1', 10, 2), ('c3', 100, 99)]), ('t2', [('c1', 10, 4)])] """ return sorted( tcs, reverse=True, key=lambda x: max([cc / tc for (_, cc, tc) in x[1]]) )
def flatten(list_): """Via https://stackoverflow.com/questions/952914/how-to-make-a-flat-list-out-of-list-of-lists""" return [item for sublist in list_ for item in sublist]
def getCrossReportName(submissionId, sourceFile, targetFile): """Return filename for a cross file error report.""" return "submission_{}_cross_{}_{}.csv".format(submissionId, sourceFile, targetFile)
def clamp(value, _min, _max): """ Returns a value clamped between two bounds (inclusive) >>> clamp(17, 0, 100) 17 >>> clamp(-89, 0, 100) 0 >>> clamp(65635, 0, 100) 100 """ return max(_min, min(value, _max))
def stata_string_escape(text: str) -> str: """Escape a string for Stata. Use this when a string needs to be escaped for a single line. Args: text: A string for a Stata argument Returns: A quoted string. """ new_text = text new_text = new_text.replace('\n', ' ') new_text = new_text.replace('\t', ' ') new_text = new_text.replace('"', "'") return f'"{new_text}"'
def _py_expand_short(subsequence, sequence, max_l_dist): """Straightforward implementation of partial match expansion.""" # The following diagram shows the score calculation step. # # Each new score is the minimum of: # * a OR a + 1 (substitution, if needed) # * b + 1 (deletion, i.e. skipping a sequence character) # * c + 1 (insertion, i.e. skipping a sub-sequence character) # # a -- +1 -> c # # | \ | # | \ | # +1 +1? +1 # | \ | # v \ v # # b -- +1 -> scores[subseq_index] subseq_len = len(subsequence) if subseq_len == 0: return (0, 0) # Initialize the scores array with values for just skipping sub-sequence # chars. scores = list(range(1, subseq_len + 1)) min_score = subseq_len min_score_idx = -1 for seq_index, char in enumerate(sequence): # calculate scores, one for each character in the sub-sequence a = seq_index c = a + 1 for subseq_index in range(subseq_len): b = scores[subseq_index] c = scores[subseq_index] = min( a + (char != subsequence[subseq_index]), b + 1, c + 1, ) a = b # keep the minimum score found for matches of the entire sub-sequence if c <= min_score: min_score = c min_score_idx = seq_index # bail early when it is impossible to find a better expansion elif min(scores) >= min_score: break return (min_score, min_score_idx + 1) if min_score <= max_l_dist else (None, None)
def rm_whitespace(string): """ Removes the whitespace at the end of a string """ # Convert string to list for easier manipulation string_ls = list(string) # Reverse because we want to remove the spaces at the # end of the line string_ls.reverse() # This for loop will get the index of the first character that # isnt a space char = 0 for char in range(len(string_ls)): if string_ls[char] != " ": break # Get from the list only the chars that arent spaces new_string_ls = string_ls[char:] # Put it back into the order it's supposed to have new_string_ls.reverse() # Convert to string new_string = ''.join(new_string_ls) # When the string is just spaces new_string will equal # a single space, we do not want this! This if checks for that return "" if new_string == " " else new_string
def buildFITSName(geisname): """Build a new FITS filename for a GEIS input image.""" # User wants to make a FITS copy and update it... _indx = geisname.rfind('.') _fitsname = geisname[:_indx] + '_' + geisname[_indx + 1:-1] + 'h.fits' return _fitsname
def generate_function_typedefs(functions): """ Generate typedef for functions: typedef return_type (*tMyFunction)(arguments). """ lines = [] for function in functions: line = "typedef {} (*t{}) ({});" . format( function.return_type, function.name, ",".join(str(arg) for arg in function.arguments)) lines.append(line) return lines
def _std(var:list, mean:float, length:int): """ Compute the Standar Deviation of a point Parameters: ------------ var: list The variance between all points mean: float The mean of the point lenght: int The lenght of all routes Return ------- Return the standar deviation of a point """ summatory = 0 for i in range(length): summatory += (var[i] - mean)**2 return (summatory / length)**0.5
def error_response(message): """ An error occurred in processing the request, i.e. an exception was thrown { "status" : "error", "message" : "Unable to communicate with database" } required keys: status: Should always be set to "error". message: A meaningful, end-user-readable (or at the least log-worthy) message, explaining what went wrong. Optional keys: code: A numeric code corresponding to the error, if applicable data: A generic container for any other information about the error, i.e. the conditions that caused the error, stack traces, etc. """ return {'status': 'error','message': message}
def compute_K(dl: float, avdl: float, b: float = 0.75, k1: float = 1.2) -> float: """ Parameters ---------- dl: length of a document avdl: average length of documents Returns ------- """ return k1 * ((1 - b) + b * (float(dl) / float(avdl)) )
def flatten_list(items): """ List flattener helper function """ for i, x in enumerate(items): while isinstance(items[i], list): items[i:i+1] = items[i] return items
def create_table_stmt(tablename,dbflavor='sqlite'): """ create table statement input: tablename ifnotexists: if true, add IF NOT EXISTS """ if dbflavor=='sqlite': result='CREATE TABLE IF NOT EXISTS %s '%(tablename) else: result='CREATE TABLE %s'%(tablename) return result
def monomial_gcd(A, B): """Greatest common divisor of tuples representing monomials. Lets compute GCD of `x**3*y**4*z` and `x*y**2`:: >>> from sympy.polys.monomialtools import monomial_gcd >>> monomial_gcd((3, 4, 1), (1, 2, 0)) (1, 2, 0) which gives `x*y**2`. """ return tuple([ min(a, b) for a, b in zip(A, B) ])
def get_folders_from_params(advanced_args): """ Extracts and returns the list of file hash IDs from the input `advanced_args`. `folders` is an expected property on `advanced_args`, if it does not exist, or it is empty, then an empty list is returned instead. """ try: if advanced_args['folders'] != '': return advanced_args['folders'].split(';') else: return [] except KeyError: return []
def _handle_curly_braces_in_docstring(s: str, **kwargs) -> str: """Replace missing keys with a pattern.""" RET = "{{{}}}" try: return s.format(**kwargs) except KeyError as e: keyname = e.args[0] return _handle_curly_braces_in_docstring( s, **{keyname: RET.format(keyname)}, **kwargs )
def addIt(in_str, my_list): """adds an element if not already in a list""" if in_str not in my_list: my_list.append(in_str) else: pass return my_list
def binary_integer_format(integer: int, number_of_bits: int) -> str: """ Return binary representation of an integer :param integer: :param number_of_bits: NOTE: number of bits can be greater than minimal needed to represent integer :return: """ return "{0:b}".format(integer).zfill(number_of_bits)
def namelist(arr: list) -> str: """ This function returns a string formatted as a list of names separated by commas except for the last two names, which should be separated by an ampersand. """ if len(arr) == 0: return '' elif len(arr) == 1: return ''.join([i['name'] for i in arr]) elif len(arr) == 2: return ' & '.join([i['name'] for i in arr]) else: return ', '.join([i['name'] for i in arr][:-1]) + ' & ' + ''.join([i['name'] for i in arr][-1])
def quicksort (a): """quick sorter""" if len(a) <= 1: return a else: return quicksort ([e for e in a[1:] if e < a[0]]) + [a[0]] + quicksort([e for e in a[1:] if e >= a[0]])
def fib_iterative(n): """Find the n-th fibonacci number, iteratively""" if n < 1: return 0 a, b = 0, 1 while n > 2: a = a + b b = a + b n -= 2 return a if (n == 1) else b
def _get_filename(fd): """ Helper function to get to file name from a file descriptor or filename. :param fd: file descriptor or filename. :returns: the filename. """ if hasattr(fd, 'name'): # fd object return fd.name # fd is a filename return fd
def get_auth_http_headers(username, password): """Get HTTP header for basic authentication""" from base64 import b64encode authorization = ('Basic ' + b64encode(f'{username}:{password}'.encode('utf-8')).decode('utf-8')) headers = {'Authorization': authorization} return headers
def parse_method_path(method_path): """ Returns (package, service, method) tuple from parsing method path """ # unpack method path based on "/{package}.{service}/{method}" # first remove leading "/" as unnecessary package_service, method_name = method_path.lstrip('/').rsplit('/', 1) # {package} is optional package_service = package_service.rsplit('.', 1) if len(package_service) == 2: return package_service[0], package_service[1], method_name return None, package_service[0], method_name
def iters_equal(iter1, iter2): """Assert that the given iterators are equal.""" iter1, iter2 = list(iter1), list(iter2) if len(iter1) != len(iter2): return False if not all(iter1[i] == iter2[i] for i in range(len(iter1))): return False return True
def normalize_newlines(s: str) -> str: """ Normalizes new lines such they are comparable across different operating systems :param s: :return: """ return s.replace("\r\n", "\n").replace("\r", "\n")
def _has_numbers(text): """ Checks if any characters in the input text contain numbers """ return any(char.isdigit() for char in text)
def powerhalo(r,rs=1.,rc=0.,alpha=1.,beta=1.e-7): """return generic twopower law distribution inputs ---------- r : (float) radius values rs : (float, default=1.) scale radius rc : (float, default=0. i.e. no core) core radius alpha : (float, default=1.) inner halo slope beta : (float, default=1.e-7) outer halo slope returns ---------- densities evaluated at r notes ---------- different combinations are known distributions. alpha=1,beta=2 is NFW alpha=1,beta=3 is Hernquist alpha=2.5,beta=0 is a typical single power law halo """ ra = r/rs return 1./(((ra+rc)**alpha)*((1+ra)**beta))
def convert_mib_to_bytes(size_in_mib: float) -> int: """Converts a size expressed in MiB to Bytes. Parameters ---------- size_in_mib: float A file size in MiB. Returns ------- int The size in Bytes equivalent to the passed size in MiB. """ return round(size_in_mib * (1024**2))
def not_data_key(s): """Make sure the GitHub name is not a data line at the wrong indent.""" return s not in [ 'name', 'email', 'agreement', 'institution', 'jira', 'comments', 'other_emails', 'before', 'beta', 'committer', 'email_ok', ]
def foo(x,y): """Summary Parameters ---------- x : TYPE Description y : TYPE Description Returns ------- TYPE Description """ return (x+y)
def env_apply_operator(operator, value): """Apply operator. Args: operator (str): Operator value (Any): Value Returns: Value with applied operator. """ # Negation operator if operator == "!": if isinstance(value, str): # Check for bool try: bool_value = str(value).lower() if bool_value == "true": return False elif bool_value == "false": return True except (ValueError, TypeError): pass # Check for int try: value = int(value) if value == 0: return 1 else: return 0 except ValueError: pass elif isinstance(value, bool): return not value elif isinstance(value, int): if value == 0: return 1 else: return 0 return value
def _process_get_set_SystemProperty(code, reply): """Process reply for functions zGetSystemProperty and zSetSystemProperty""" # Convert reply to proper type if code in (102,103, 104,105,106,107,108,109,110,202,203): # unexpected (identified) cases sysPropData = reply elif code in (16,17,23,40,41,42,43): # string sysPropData = reply.rstrip() #str(reply) elif code in (11,13,24,53,54,55,56,60,61,62,63,71,72,73,77,78): # floats sysPropData = float(reply) else: sysPropData = int(float(reply)) # integer return sysPropData
def distance_sq_2d(a, b): """Return the squared distance between two points in two dimensions. Usage examples: >>> distance_sq_2d((1, 1), (1, 1)) 0 >>> distance_sq_2d((0, 0), (0, 2)) 4 """ assert len(a) == 2 assert len(b) == 2 x = a[0] - b[0] y = a[1] - b[1] return (x * x) + (y * y)
def single_used_variables(lines): """ This function returns a dictionary stating if the key is used more than once """ l = {} for i in range(len(lines)): l[lines[i][0]] = 0 if lines[i][1] not in l.keys(): l[lines[i][1]] = 0 else: l[lines[i][1]] = 1 if lines[i][2] not in l.keys(): l[lines[i][2]] = 0 else: l[lines[i][2]] = 1 for j in range(len(lines)): if lines[j][1] == lines[i][0] or lines[j][2] == lines[i][0]: l[lines[i][0]] = 1 break return l
def _to_list(var): """ Make variable to list. >>> _to_list(None) [] >>> _to_list('whee') ['whee'] >>> _to_list([None]) [None] >>> _to_list((1, 2, 3)) [1, 2, 3] :param var: variable of any type :return: list """ if isinstance(var, list): return var elif var is None: return [] elif isinstance(var, str) or isinstance(var, dict): # We dont want to make a list out of those via the default constructor return [var] else: try: return list(var) except TypeError: return [var]
def assign_targets(agents_position: list, targets_position_1d: list): """ Assign targets to agents. Input: agents_position = [a0,b0, a1,b1, ...] targets_position_1d = [x0,y0, x1,y1, x2,y2, x3,y3, x4,y4, ...] Output: targets_position: 2D list, targets positions for multi-agent path planning, i-th sub-list is a list of targets for i-th agent Example: agents_position = [a0,b0, a1,b1, a2,b2] targets_position_1d = [x0,y0, x1,y1, x2,y2, x3,y3, x4,y4, x5,y5, x6,y6, x7,y7] targets_position = assign_targets(agents_position, targets_position_1d) ==> targets_position = [[x0,y0, x3,y3, x6,y6], [x1,y1, x4,y4, x7,y7], [x2,y2, x5,y5]] """ num_agents = int(len(agents_position) / 2) num_targets = int(len(targets_position_1d) / 2) num_group = num_targets // num_agents num_reminder = num_targets % num_agents assert num_group > 0, "Each agent should have at least 1 task!" # 2D target list for multi-agent path planning targets_position = [[] for _ in range(num_agents)] for idx_group in range(num_group): for idx_agent in range(num_agents): idx_x = idx_group * num_agents * 2 + 2 * idx_agent idx_y = idx_x + 1 targets_position[idx_agent].extend([targets_position_1d[idx_x], targets_position_1d[idx_y]]) for idx_reminder in range(num_reminder): idx_x = num_group * num_agents * 2 + 2 * idx_reminder idx_y = idx_x + 1 targets_position[idx_reminder].extend([targets_position_1d[idx_x], targets_position_1d[idx_y]]) return targets_position
def ffmt(val): """format None or floating point as string""" if val is not None: try: return "%.5g" % val except: pass return repr(val)
def deleteAllInUsed(total, used): """ Return the list "total" after removing all appearances of elements in "used". Parameters ---------- total : list-like of any The original list from which we want to remove some elements. used : iterable of any The elements we want to remove from total. Returns ------- list of any The list total after removing all elements appearing in used. """ usedSet = set(used) ret = list(total) return [x for x in ret if not (x in usedSet)]
def get_quarter(month): """return quarter for month""" if month not in range(1, 13): raise ValueError("invalid month") d = {1: 1, 2: 1, 3: 1, 4: 2, 5: 2, 6: 2, 7: 3, 8: 3, 9: 3, 10: 4, 11: 4, 12: 4} return d[month] # return (month + 2) // 3
def sanitize_dict(value): """Recursively remove special characters from dictionary keys. The special characters are . and $, eg the special characters for MongoDB. Note that, in case of key collision after the removal of special characters, the common key will be updated with the value of the renamed key. """ if isinstance(value, dict): for key in value.keys(): try: cleaned = key.translate({ord(c): None for c in '$.'}) except TypeError: cleaned = key.translate(None, '$.') # Note that translate() signature changes with key # type but one # # can't use isinstance since, in Python3, # key may be of type str or bytes; In Python2 it # will # be unicode or str. value[cleaned] = sanitize_dict(value.pop(key)) elif isinstance(value, list): for item in value: sanitize_dict(item) return value
def sakura_fall(v): """ Suppose that the falling speed of a petal is 5 centimeters per second (5 cm/s), and it takes 80 seconds for the petal to reach the ground from a certain branch. :param v: integer value of speed in centimeters per second. :return: the time it takes for that petal to reach the ground from the same branch. """ if v < 1: return 0 else: return 80 / (v / 5)
def expand_call(kwargs): """Execute function from dictionary input""" func = kwargs['func'] del kwargs['func'] out = func(**kwargs) return out
def extract_gps_exif(exif_tags): """Extracts and returns GPS in degrees from exif_tags""" # Invalid values if tags do not exist gps_lat_out = 91 gps_lon_out = 181 if 'GPS GPSLatitude' in exif_tags: gps_lat = exif_tags['GPS GPSLatitude'].values gps_lat_ref = exif_tags['GPS GPSLatitudeRef'].values gps_lon = exif_tags['GPS GPSLongitude'].values gps_lon_ref = exif_tags['GPS GPSLongitudeRef'].values gps_lat_out = gps_lat[0].num + gps_lat[1].num / 60.0 + gps_lat[2].num / 3600.0 if gps_lat_ref == 'S': gps_lat_out = -gps_lat_out gps_lon_out = gps_lon[0].num + gps_lon[1].num / 60.0 + gps_lon[2].num / 3600.0 if gps_lon_ref == 'W': gps_lon_out = -gps_lon_out return gps_lat_out, gps_lon_out
def clean_services(services): """Transform string with services to list""" services = services.split(',') services = [service.strip() for service in services] return services
def identical_prediction_lists(prev_prediction_list, curr_prediction_list): """ Check if two predictions lists are the same :param prev_prediction_list: list Last iterations predictions :param curr_prediction_list: list current iterations predictions :return: bool false = not identical, true = identical """ for x, y in zip(prev_prediction_list, curr_prediction_list): if x != y: return False return True
def reverse_class_dependencies(dependencies): """ Reverses class dependency dictionary Consumes dictionary in format { 'test_class_name_1': { 'Id': '01pU00000026druIAA', 'References': ['class_name_1', 'class_name_2'] } } produces dictionary in format { 'class_name_1': ['test_class_name_1'], 'class_name_2': ['test_class_name_1'] } """ reverse_deps = dict() for class_name, data in dependencies.items(): for dep_class_name in data['References']: if dep_class_name in reverse_deps: if class_name in reverse_deps[dep_class_name]: continue cur_class_deps = reverse_deps[dep_class_name] else: cur_class_deps = list() cur_class_deps.append(class_name) cur_class_deps.sort() reverse_deps[dep_class_name] = cur_class_deps return reverse_deps
def toposorted(graph, parents): """ Returns vertices of a directed acyclic graph in topological order. Arguments: graph -- vetices of a graph to be toposorted parents -- function (vertex) -> vertices to preceed given vertex in output """ result = [] used = set() def use(v, top): if id(v) in used: return for parent in parents(v): if parent is top: raise ValueError('graph is cyclical', graph) use(parent, v) used.add(id(v)) result.append(v) for v in graph: use(v, v) return result
def all_notes_line_up(a_list, b_list): """ Takes two lists of NoteNode objects. These may be NoteList objects. Returns 2 lists. The first list contains the NoteNode objects in a_list that are unmatched in b_list. The second list contains the NoteNode objects in b_list that are unmatched in a_list. """ a_list = [x for x in a_list if not x.is_rest] # copy NoteList to list b_list = [x for x in b_list if not x.is_rest] # copy NoteList to list # remove matched notes for a_note in a_list[:]: for b_note in b_list[:]: if (a_note.start, a_note.end) == (b_note.start, b_note.end): # remove the matched pair from their respective lists a_list.remove(a_note) b_list.remove(b_note) break return a_list, b_list
def eliminate_suffix(v, w): """ Removes suffix w from the input word v If v = uw (u=prefix, w=suffix), u = v w-1 Parameters: ----------------------------------- v: str A (sub)word w: str The suffix to remove Returns: ----------------------------------- u: str (sub)word with the suffix removed """ u = v.rstrip(w) return(u)
def intersection(groups): """returns the intersection of all groups""" common = set(groups.pop()) return common.intersection(*map(set, groups))
def _split_section_and_key(key): """Return a tuple with config section and key.""" parts = key.split('.') if len(parts) > 1: return 'renku "{0}"'.format(parts[0]), '.'.join(parts[1:]) return 'renku', key
def extract_face_colors(faces, material_colors): """Extract colors from materials and assign them to faces """ faceColors = [] for face in faces: material_index = face['material'] faceColors.append(material_colors[material_index]) return faceColors
def get_shape(tensor): """Get shape.""" if not isinstance(tensor, list): return () return (len(tensor),) + get_shape(tensor[0])
def alterarPosicao(changePosition, change): """This looks complicated but I'm doing this: Current_pos == (x, y) change == (a, b) new_position == ((x + a), (y + b)) """ return (changePosition[0] + change[0]), (changePosition[1] + change[1])
def range_intersect(a, b, extend=0): """ Returns the intersection between two reanges. >>> range_intersect((30, 45), (55, 65)) >>> range_intersect((48, 65), (45, 55)) [48, 55] """ a_min, a_max = a if a_min > a_max: a_min, a_max = a_max, a_min b_min, b_max = b if b_min > b_max: b_min, b_max = b_max, b_min if a_max + extend < b_min or b_max + extend < a_min: return None i_min = max(a_min, b_min) i_max = min(a_max, b_max) if i_min > i_max + extend: return None return [i_min, i_max]
def dms_to_decimal(degrees, minutes, northeast=True): """ Function that transforms degrees-minutes coordinate (lon or lat) to decimal coordinates (lon or lat). :param degrees: degree :param minutes: minute of degree :return: decimal longitude or latitude """ c = degrees + float(minutes) / 60 if not northeast: c*=-1 return c
def parse_hcount(hcount_str): """ Parses a SMILES hydrogen count specifications. Parameters ---------- hcount_str : str The hydrogen count specification to parse. Returns ------- int The number of hydrogens specified. """ if not hcount_str: return 0 if hcount_str == 'H': return 1 return int(hcount_str[1:])
def DGS3420(v): """ DGS-3420-series :param v: :return: """ return v["platform"].startswith("DGS-3420")