content
stringlengths
42
6.51k
def get_margin(length): """Add enough tabs to align in two columns""" if length > 23: margin_left = "\t" chars = 1 elif length > 15: margin_left = "\t\t" chars = 2 elif length > 7: margin_left = "\t\t\t" chars = 3 else: margin_left = "\t\t\t\t" chars = 4 return margin_left
def merge_two_dicts_shallow(x, y): """ Given two dicts, merge them into a new dict as a shallow copy. y members overwrite x members with the same keys. """ z = x.copy() z.update(y) return z
def is_int(value): """ Checks to see if a value is an integer or not :param value: String representation of an equation :type value: str :return: Whether or not value is an int :rtype: bool """ try: int(value) value_bool = True except ValueError: value_bool = False return value_bool
def header_tpl(data): """Generates header file to import Output: #import "XYZUserInfo.h" """ if not data['transform']: return None if data['transform']['type'] == 'BOOL': return None if data['class_name'] == 'NSArray': name = data['transform']['class'] else: name = data['class_name'] result = '#import "{}.h"'.format(name) return result
def get_submission_files(jobs): """ Return the filenames of all jobs within a submission. Args: jobs: jobs to retrieve filenames from Returns: array of all filenames within the jobs given """ job_list = [] for job in jobs: if job.filename not in job_list: job_list.append(job.filename) return job_list
def get_description(description_blob): """descriptions can be a string or a dict""" if isinstance(description_blob, dict): return description_blob.get("value") return description_blob
def pa_to_hpa(pres): """ Parameters Pressure (Pa) Returns Pressure (hPa) """ pres_hpa = pres * 0.01 return pres_hpa
def padding(sample, seq_max_len): """use '0' to padding the sentence""" for i in range(len(sample)): if len(sample[i]) < seq_max_len: sample[i] += [0 for _ in range(seq_max_len - len(sample[i]))] return sample
def S_get_cluster_centroid_data(_data_list): """ Finds the centroid of a given two dimensional data samples cluster """ ds = len(_data_list) if ds > 0: x_sum = 0 y_sum = 0 for i in _data_list: x_sum += i[0] y_sum += i[1] return (x_sum / ds, y_sum / ds)
def all_keys_false(d, keys): """Check for values set to True in a dict""" if isinstance(keys, str): keys = (keys,) for k in keys: if d.get(k, None) is not False: return False return True
def openluke(number): """ Open a juleluke Args: number (int): number of juleluke (1-24) Returns: solution (int): the luke solution """ solution = 0 print(f"Opening luke number: {number}.") if (number == 0): solution = -1 print(f"Solution is: {solution}.") return solution
def getPath(bp, start: int, goal : int): """ @param bp: back pointer @param start: @param goal: @return: """ current = goal s = [current] while current != start: current = bp[current] s += [current] return list(reversed(s))
def get_chunks(arr, num_processors, ratio): """ Get chunks based on a list """ chunks = [] # Collect arrays that will be sent to different processorr counter = int(ratio) for i in range(num_processors): if i == 0: chunks.append(arr[0:counter]) if i != 0 and i<num_processors-1: chunks.append(arr[counter-int(ratio): counter]) if i == num_processors-1: chunks.append(arr[counter-int(ratio): ]) counter += int(ratio) return chunks
def convert_none_type_object_to_empty_string(my_object): """ replace noneType objects with an empty string. Else return the object. """ return ('' if my_object is None else my_object)
def _merge_sorted_nums_recur(sorted_nums1, sorted_nums2): """Helper method for merge_sort_recur(). Merge two sorted lists by recusion. """ if not sorted_nums1 or not sorted_nums2: return sorted_nums1 or sorted_nums2 # Merge two lists one by one element. if sorted_nums1[0] <= sorted_nums2[0]: return ([sorted_nums1[0]] + _merge_sorted_nums_recur(sorted_nums1[1:], sorted_nums2)) else: return ([sorted_nums2[0]] + _merge_sorted_nums_recur(sorted_nums1, sorted_nums2[1:]))
def parse_options(options): """ Parse the options passed by the user. :param options: dictionary of options :return: parsed dictionary """ options["--batch"] = int(options["--batch"]) if options["--epochs"]: options["--epochs"] = int(options["--epochs"]) options["--lr"] = float(options["--lr"]) if options["--measure"] not in ["class", "match"]: raise ValueError(f'{options["--measure"]} is an invalid test measure') if options["--set"]: if options["--set"] != "lfw": options["--set"] = int(options["--set"]) if options["--split"] not in [None, "test", "train"]: raise ValueError(f'{options["--measure"]} is an invalid test measure') if options["--student"]: options["--student"] = int(options["--student"]) if options["--temperature"]: options["--temperature"] = int(options["--temperature"]) if options["--test-set"]: if options["--test-set"] != "lfw": options["--test-set"] = int(options["--test-set"]) if options["--train-set"]: if options["--train-set"] != "vggface2": options["--train-set"] = int(options["--train-set"]) options["--workers"] = int(options["--workers"]) if options["<dataset>"] not in [None, "agedb", "casia", "lfw", "vggface2"]: raise ValueError(f'{options["<dataset>"]} is an invalid dataset') if options["<model_name>"] not in [ None, "mobilenet_v3_large", "mobilenet_v3_small", ]: raise ValueError(f'{options["<model_name>"]} is an invalid model name') if options["<num_triplets>"]: options["<num_triplets>"] = int(options["<num_triplets>"]) return options
def poly(coeffs, n): """Compute value of polynomial given coefficients""" total = 0 for i, c in enumerate(coeffs): total += c * n ** i return total
def is_threshold_sequence(degree_sequence): """ Returns True if the sequence is a threshold degree seqeunce. Uses the property that a threshold graph must be constructed by adding either dominating or isolated nodes. Thus, it can be deconstructed iteratively by removing a node of degree zero or a node that connects to the remaining nodes. If this deconstruction failes then the sequence is not a threshold sequence. """ ds = degree_sequence[:] # get a copy so we don't destroy original ds.sort() while ds: if ds[0] == 0: # if isolated node ds.pop(0) # remove it continue if ds[-1] != len(ds) - 1: # is the largest degree node dominating? return False # no, not a threshold degree sequence ds.pop() # yes, largest is the dominating node ds = [d - 1 for d in ds] # remove it and decrement all degrees return True
def reformat_tweets(tweets: list) -> list: """Return a list of tweets identical to <tweets> except all lowercase, without links and with some other minor adjustments. >>> tweets = ['Today is i monday #day', 'Earth #day is (tmrw &amp always)'] >>> reformat_tweets(tweets) ['today is I monday #day', 'earth #day is tmrw and always'] """ new_tweets = [] for tweet in tweets: words = tweet.lower().split(' ') sentence = '' for word in words: if '@' not in word and 'https://' not in word: if '"' in word: word = word.replace('"', '') if '(' in word: word = word.replace('(', '') if ')' in word: word = word.replace(')', '') if '&amp' in word: word = word.replace('&amp', 'and') if word == 'i': word == 'I' sentence += word + ' ' new_tweets.append(sentence[:-1]) return new_tweets
def dms2dd(d: float, m: float = 0, s: float = 0) -> float: """Convert degree, minutes, seconds into decimal degrees. """ dd = d + float(m) / 60 + float(s) / 3600 return dd
def getBrightness(rgb): """helper for getNeighbors that returns the brightness as the average of the given rgb values""" return (rgb[0] + rgb[1] + rgb[2]) / 765
def key_from_val(dictionary: dict, value) -> str: """ Helper method - get dictionary key corresponding to (unique) value. :param dict dictionary :param object value: unique dictionary value :return dictionary key :rtype str :raises KeyError: if no key found for value """ val = None for key, val in dictionary.items(): if val == value: return key raise KeyError(f"No key found for value {value}")
def value_mapper(a_dict, b_dict): """ a_dict = { 'key1': 'a_value1', 'key2': 'a_value2' } b_dict = { 'key1': 'b_value1', 'key2': 'b_value2' } >>> value_mapper(a_dict, b_dict) { 'a_value1': 'b_value1', 'a_value2': 'b_value2' } """ return {a_value: b_dict.get(a_key) for a_key, a_value in a_dict.items()}
def case2pod(case): """ Convert case into pod-compatible string """ s = case.split(" ") s = [q for q in s if q] # remove empty strings return "-".join(s)
def get_users_for_association(association, valid_users): """get_users_for_association(association, valid_users)""" users_for_association=[] for user in valid_users: user_association=user["association"] if (user_association == association): users_for_association.append(user) return users_for_association
def _GetLineNumberOfSubstring(content, substring): """ Return the line number of |substring| in |content|.""" index = content.index(substring) return content[:index].count('\n') + 1
def calculator(x,y, function): """ Take a breathe and process this black magic. We are passing a function as parameter. In order to use it we need to call the function with the (). """ try: return function(x,y) except Exception as e: print(f"Fix this pls {e}") return None
def crypt(data: bytes, key: bytes) -> bytes: """RC4 algorithm""" x = 0 box = list(range(256)) for i in range(256): x = (x + int(box[i]) + int(key[i % len(key)])) % 256 box[i], box[x] = box[x], box[i] print(len(data)) x = y = 0 out = [] for char in data: x = (x + 1) % 256 y = (y + box[x]) % 256 box[x], box[y] = box[y], box[x] t = char ^ box[(box[x] + box[y]) % 256] out.append(t) return bytes(bytearray(out))
def list_manipulation(lst, command, location, value=None): """Mutate lst to add/remove from beginning or end. - lst: list of values - command: command, either "remove" or "add" - location: location to remove/add, either "beginning" or "end" - value: when adding, value to add remove: remove item at beginning or end, and return item removed >>> lst = [1, 2, 3] >>> list_manipulation(lst, 'remove', 'end') 3 >>> list_manipulation(lst, 'remove', 'beginning') 1 >>> lst [2] add: add item at beginning/end, and return list >>> lst = [1, 2, 3] >>> list_manipulation(lst, 'add', 'beginning', 20) [20, 1, 2, 3] >>> list_manipulation(lst, 'add', 'end', 30) [20, 1, 2, 3, 30] >>> lst [20, 1, 2, 3, 30] Invalid commands or locations should return None: >>> list_manipulation(lst, 'foo', 'end') is None True >>> list_manipulation(lst, 'add', 'dunno') is None True """ if command != "remove" and command != "add": return "None1" if location != "beginning" and location != "end": return "None2" # Should be valid from here on if command == "remove": if location == "beginning": print("0") return lst.pop(0) print("1") return lst.pop(-1) if command == "add": if location == "beginning": print("3") lst.insert(0, value) return lst print("4") lst.append(value) return lst print("WTF")
def destination_name(path, delimiter="__"): """returns a cli option destination name from attribute path""" return "{}".format(delimiter.join(path))
def dbdust_tester_cli_builder(bin_path, zip_path, dump_dir_path, dump_file_path, loop='default', sleep=0, exit_code=0): """ dbust cli tester script included in this package """ return [bin_path, dump_file_path, loop, sleep, exit_code]
def compile_word(word): """Compile a word of uppercase letters as numeric digits. E.g., compile_word('YOU') => '(1*U+10*O+100*Y)' Non-uppercase words uncahanged: compile_word('+') => '+'""" if word.isupper(): terms = [('%s*%s' % (10**i, d)) for (i, d) in enumerate(word[::-1])] return '(' + '+'.join(terms) + ')' else: return word
def filter_tornado_keys_patient_data_kvp(all_patient_data, study_key, query_key, query_val): """ Does a simple kvp filter against the patient data from a study using the data structure loaded by patient_data_etl.load_all_metadata. returns a list of tornado_sample_keys """ cohort_sample_keys = list() study_data = all_patient_data[study_key] for tornado_sample_key in study_data['patients']: patient_data = study_data['patients'][tornado_sample_key] if patient_data[query_key] == query_val: cohort_sample_keys.append(tornado_sample_key) return cohort_sample_keys
def predict(title:str): """ Naive Baseline: Always predicts "fake" """ return {'prediction': 'fake'}
def fibonacci(n: int) -> int: """Implement Fibonacci iteratively Raise: - TypeError for given non integers - ValueError for given negative integers """ if type(n) is not int: raise TypeError("n isn't integer") if n < 0: raise ValueError("n is negative") if n == 0: return 0 a = 0 b = 1 for i in range(2, n+1): a, b = b, a+b return b
def build_sql_insert(table, flds): """ Arguments: - `table`: - `flds`: """ sql_base = "insert into {} ({}) values ({})" # escape and concatenate fields flds_str = ",\n".join(["[{}]".format(x) for x in flds]) # create a parameter list - one ? for each field args = ",".join(len(flds) * ["?"]) return sql_base.format(table, flds_str, args)
def snps_to_genes(snps): """Convert a snps dict to a genes dict.""" genes = {} for chrom in snps.values(): for snp in chrom.values(): if snp.gene.name not in genes: genes[snp.gene.name] = snp.gene return genes
def simplify(alert): """Filter cert alerts""" if alert['labels']['alertname'] in {'CertificateExpirationWarning', 'CertificateExpirationCritical'}: return { 'host': alert['labels']['host'], 'file': alert['labels']['source'] }
def pow2bits(bin_val): """ Convert the integer value to a tuple of the next power of two, and number of bits required to represent it. """ result = -1 bits = (bin_val).bit_length() if bin_val > 1: result = 2**(bits) else: result = 1 bits = 1 return result, bits
def qual(clazz): """Return full import path of a class.""" return clazz.__module__ + '.' + clazz.__name__
def dna_to_rna(seq): """ Converts DNA sequences to RNA sequences. """ rs = [] for s in seq: if s == 'T': rs.append('U') else: rs.append(s) return "".join(rs)
def common_start(sa, sb): """ returns the longest common substring from the beginning of sa and sb """ def _iter(): for a, b in zip(sa, sb): if a == b: yield a else: return return ''.join(_iter())
def Name(uri): """Get just the name of the object the uri refers to.""" # Since the path is assumed valid, we can just take the last piece. return uri.split('/')[-1]
def get_icon(fio): """ Returns a formatted icon name that should be displayed """ icon = fio["icon"] if "-" in icon: icon = icon.replace('-', '_') if icon == "fog": icon = "cloudy" if icon == "sleet": icon = "snow" return icon
def capitalize(x: str, lower_case_remainder: bool = False) -> str: """ Capitalize string with control over whether to lower case the remainder.""" if lower_case_remainder: return x.capitalize() return x[0].upper() + x[1:]
def recursive_tuplify(x): """Recursively convert a nested list to a tuple""" def _tuplify(y): if isinstance(y, list) or isinstance(y, tuple): return tuple(_tuplify(i) if isinstance(i, (list, tuple)) else i for i in y) else: return y return tuple(map(_tuplify, x))
def get_epsilon_inc(epsilon, n, i): """ n: total num of epoch i: current epoch num """ return epsilon / ( 1 - i/float(n))
def find_largest_digit(n): """ :param n: int, an integer :return: int, the biggest digit in the integer. """ if 0 <= n <= 9: return n else: if n < 0: n = -n if n % 10 > (n % 100 - n % 10) // 10: n = (n - n % 100 + n % 10 * 10) // 10 return find_largest_digit(n) else: n = n//10 return find_largest_digit(n)
def get_district_summary_totals(district_list): """ Takes a serialized list of districts and returns totals of certain fields """ fields = ['structures', 'visited_total', 'visited_sprayed', 'visited_not_sprayed', 'visited_refused', 'visited_other', 'not_visited', 'found', 'num_of_spray_areas'] totals = {} for rec in district_list: for field in fields: totals[field] = rec[field] + (totals[field] if field in totals else 0) return totals
def getpage(page): """To change pages number into desired format for saving""" page = str(page) if int(page) < 10: page = '0' + page return page
def is_number(s): """ check if input is a number (check via conversion to string) """ try: float(str(s)) return True except ValueError: return False
def is_location_url(x): """Check whether the """ from urllib.parse import urlparse try: result = urlparse(x) return all([result.scheme in ['http', 'https'], result.netloc, result.path]) except: return False
def convert_iterable_to_string_of_types(iterable_var): """Convert an iterable of values to a string of their types. Parameters ---------- iterable_var : iterable An iterable of variables, e.g. a list of integers. Returns ------- str String representation of the types in `iterable_var`. One per item in `iterable_var`. Separated by commas. """ types = [str(type(var_i)) for var_i in iterable_var] return ", ".join(types)
def split_options(options): """Split options that apply to dual elements, either duplicating or splitting.""" return options if isinstance(options, tuple) else (options, options)
def solve(board, x_pos, y_pos): """Solves a sudoku board, given the x and y coordinates to start on.""" while board[y_pos][x_pos]: if x_pos == 8 and y_pos == 8: return True x_pos += 1 if x_pos == 9: y_pos += 1 x_pos = 0 possible = set(range(1, 10)) for i in range(9): possible.discard(board[y_pos][i]) possible.discard(board[i][x_pos]) possible.discard( board[y_pos - y_pos % 3 + i % 3][x_pos - x_pos % 3 + i // 3]) next_x = (x_pos + 1) % 9 next_y = y_pos + (x_pos == 8) for num in possible: board[y_pos][x_pos] = num if (x_pos == 8 and y_pos == 8) or solve(board, next_x, next_y): return True board[y_pos][x_pos] = 0 return False
def FormatBytes(byte_count): """Pretty-print a number of bytes.""" if byte_count > 1e6: byte_count = byte_count / 1.0e6 return '%.1fm' % byte_count if byte_count > 1e3: byte_count = byte_count / 1.0e3 return '%.1fk' % byte_count return str(byte_count)
def create_bool_select_annotation( keys_list, label, true_label, false_label, class_name=None, description=None): """Creates inputex annotation to display bool type as a select.""" properties = { 'label': label, 'choices': [ {'value': True, 'label': true_label}, {'value': False, 'label': false_label}]} if class_name: properties['className'] = class_name if description: properties['description'] = description return (keys_list, {'type': 'select', '_inputex': properties})
def filterLastCapital(depLine): """ Filters an isolated dependency line by breaking it apart by the periods, and thenfinding the last capitalized sub-property. ----------------- EXAMPLES: ----------------- filterLastCapital('nrg.ui.Component.getElement') >>> 'nrg.ui.Component' filterLastCapital('nrg.ui.Component.SubComponent') >>> 'nrg.ui.Component.SubComponent' ----------------- EXCEPTIONS: ----------------- # Does not filter 2-level dependency lines filterLastCapital('nrg.string') >>> 'nrg.string' # Returns the property/dependecy before the last if no capitals filterLastCapital('nrg.fx.fadeIn') >>> 'nrg.fx' @type depLine: string @param depLine: The dependency line @rtype: string @return: The filtered dependecy line. """ lastCap = -1; count = 0; filteredDepLine = '' #--------------- # split the dependencies #--------------- depArr = depLine.split('.') for depSub in depArr: if len(depSub) > 0 and depSub[0].isupper(): lastCap = count count += 1 #print 'DEP ARR:', depArr[-1], depArr[-1].isupper() #--------------- # If we have a two-level dependecy (i.e 'goog.math') then # we just keep the entire line. # # We can filter any unneeded things manually. #--------------- if len(depArr) == 2: filteredDepLine = depLine #--------------- # If there are no capital letters in the dependency line, we filter # to the second to last property #--------------- elif lastCap == -1: filteredDepLine = depLine.rpartition('.')[0] #--------------- # ALL caps #--------------- elif len(depArr) > 1 and depArr[-1].isupper(): filteredDepLine = depLine.rpartition('.')[0] #--------------- # Otherwise we create a new dependecy based on the last capital letter. # For instance, if we have 'nrg.ui.Component.getElement' we crop this to # 'nrg.ui.Component' #--------------- else: filteredDepLine = '' count = 0; for depSub in depArr: filteredDepLine += depSub + '.' #print filteredDepLine if count == lastCap: filteredDepLine = filteredDepLine[:-1] break count += 1 #print '\ndepLine: ', depLine #print lastCap #print 'depArr:', depArr #print 'filtered:', filteredDepLine return filteredDepLine
def is_dict(context, value): """ Allow us to check for a hash/dict in our J2 templates. """ return isinstance(value, dict)
def convert_data_type(value: str): """ Takes a value as a string and return it with its proper datatype attached Parameters ---------- value: str The value that we want to find its datatype as a string Returns ------- The value with the proper datatype """ try: f = float(value) if f.is_integer(): return int(f) return f except ValueError: return value
def run(arg, v=False): """Short summary. Parameters ---------- arg : type Description of parameter `arg`. v : type Description of parameter `v`. Returns ------- type Description of returned object. """ if v: print("running") out = arg ** 2 return out
def chunker(blob): """ Chunk a blob of data into an iterable of smaller chunks """ return [chunk for chunk in blob.split('\n') if chunk.strip()]
def replace_string(metadata, field, from_str, to_str): """Replace part of a string in given metadata field""" new = None if from_str in metadata[field]: new = metadata[field].replace(from_str, to_str) return new
def get_json_cache_key(keyword): """ Returns a cache key for the given word and dictionary. """ version = "1.0" return ":".join(["entry:utils", version, "meaning", keyword])
def zeros_only(preds, labels): """ Return only those samples having a label=0 """ out_preds = [] out_labels = [] for i, label in enumerate(labels): if label == 0: out_labels.append(label) out_preds.append( preds[i] ) return out_preds, out_labels
def render_mac(oid: str, value: bytes) -> str: """ Render 6 octets as MAC address. Render empty string on length mismatch :param oid: :param value: :return: """ if len(value) != 6: return "" return "%02X:%02X:%02X:%02X:%02X:%02X" % tuple(value)
def f(x): """ A quadratic function. """ y = x**2 + 1. return y
def square(side): """ Takes a side length and returns the side length squared :param side: int or float :return: int or float """ squared = side**2 return squared
def lookup_dict_path(d, path, extra=list()): """Lookup value in dictionary based on path + extra. For instance, [a,b,c] -> d[a][b][c] """ element = None for component in path + extra: d = d[component] element = d return element
def s3_path_to_name(path: str, joiner: str = ":") -> str: """ Remove the bucket name from the path and return the name of the file. """ without_bucket = path.rstrip("/").split("/")[1:] return joiner.join(without_bucket)
def korean_ticker(name, source): """ Return korean index ticker within the source. :param name: (str) index name :param source: (str) source name :return: (str) ticker for the source """ n = name.lower().replace(' ', '').replace('_','') if source == 'yahoo': if n == 'kospi': return '^KS11', source if n == 'kosdaq': return '^KQ11', source if n == 'kospi200': return 'KRX:KOSPI200', 'google' if n == 'kospi100': return 'KRX:KOSPI100', 'google' if n == 'kospi50': return 'KRX:KOSPI50', 'google' if n == 'kospilarge': return 'KRX:KOSPI-2', 'google' if n == 'kospimiddle': return 'KRX:KOSPI-3', 'google' if n == 'kospismall': return 'KRX:KOSPI-4', 'google' if source == 'google': if n == 'kospi': return 'KRX:KOSPI', source return name, source
def compare_payloads(modify_payload, current_payload): """ :param modify_payload: payload created to update existing setting :param current_payload: already existing payload for specified baseline :return: bool - compare existing and requested setting values of baseline in case of modify operations if both are same return True """ diff = False for key, val in modify_payload.items(): if current_payload is None or current_payload.get(key) is None: return True elif isinstance(val, dict): if compare_payloads(val, current_payload.get(key)): return True elif val != current_payload.get(key): return True return diff
def attempt(func, *args, **kargs): """Attempts to execute `func`, returning either the result or the caught error object. Args: func (function): The function to attempt. Returns: mixed: Returns the `func` result or error object. Example: >>> results = attempt(lambda x: x/0, 1) >>> assert isinstance(results, ZeroDivisionError) .. versionadded:: 1.1.0 """ try: ret = func(*args, **kargs) except Exception as ex: # pylint: disable=broad-except ret = ex return ret
def y(v0, t): """ Compute vertical position at time t, given the initial vertical velocity v0. Assume negligible air resistance. """ g = 9.81 return v0*t - 0.5*g*t**2
def pa_bad_mock(url, request): """ Mock for Android autoloader lookup, worst case. """ thebody = "https://bbapps.download.blackberry.com/Priv/bbry_qc8992_autoloader_user-common-AAD250.zip" return {'status_code': 404, 'content': thebody}
def lowercase_all_the_keys(some_dict): """ lowercases all the keys in the supplied dictionary. :param: dict :return: dict """ return dict((key.lower(), val) for key, val in some_dict.items())
def save(p:int, g:int, a:int, b:int, A:int, B:int, a_s:int, b_s:int, path:str="exchange.txt") -> str: """Takes in all the variables needed to perform Diffie-Hellman and stores a text record of the exchange. Parameters ---------- p : int The shared prime g : int The shared base a : int Alice's private secret b : int Bob's private secret A : int Alice's public secret B : int Bob's public secret a_s : int Alice's calculated common secret b_s : int Bob's calculated common secret path : str, optional The path to save the output file to, by default "exchange.txt":str Returns ------- str The text record of the Diffie-Hellman exchange Notes ----- * For better definitions of each of the variables see the readme in the root directory """ exchange = "Begin of exchange\n\n" # The variable that holds the description of the exchange # Generate Initial Variables exchange += f"First a shared prime (p) & shared base (g) were generated(eve knows these also):\n\tp = {p}\n\tg = {g}\n\n" # Secret Generation exchange += f"Next Alice and Bob generated their own private secrets (a and b respectively):\n\ta = {a}\n\tb = {b}\n\n" # Public secret exchange exchange += f"Alice and Bob now compute their public secrets and send them to each other. \nThese are represented as A and B respectively (eve knows these also):\n\tA = g^a mod p = {A}\n\tB = g^b mod p = {B}\n\n" # Handshake exchange += f"Alice and Bob can now calculate a common secret that can be used to encrypt later transmissions:\n\tAlice's Calculation: \n\t\ts = B^a mod p = {a_s} \n\tBob's Calculation: \n\t\ts = A^b mod p = {b_s}" with open(path, "w+") as output_file: output_file.write(exchange) return exchange
def now_time(str=True): """Get the current time and return it back to the app.""" import datetime if str: return datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") return datetime.datetime.now()
def _unit_conll_map(value, empty): """ Map a unit value to its CoNLL-U format equivalent. Args: value: The value to convert to its CoNLL-U format. empty: The empty representation for a unit in CoNLL-U. Returns: empty if value is None and value otherwise. """ return empty if value is None else value
def shell_quote(string): """Escapes by quoting""" return "'" + str(string).replace("'", "'\\''") + "'"
def wrap_emph(str): """Format emph.""" return f"*{str}*"
def _convert_if_int(value): """ .. versionadded:: 2017.7.0 Convert to an int if necessary. :param str value: The value to check/convert. :return: The converted or passed value. :rtype: bool|int|str """ try: value = int(str(value)) # future lint: disable=blacklisted-function except ValueError: pass return value
def call_func(name, *args, **kwargs): """Call a function when all you have is the [str] name and arguments.""" parts = name.split('.') module = __import__(".".join(parts[:-1]), fromlist=[parts[-1]]) return getattr(module, parts[-1])(*args, **kwargs)
def eliminate_targets_decoys(value): """ Check if targets are being consolidated with decoys """ targets_with_decoys = False if len(value) > 1 and 'decoy' in value: targets_with_decoys = True return targets_with_decoys
def linearInterpolation(x_low: float, x: float, x_hi: float, y_low: float, y_hi: float) -> float: """ Helper function to compute linear interpolation of a given value x, and the line i defined by two points :param x_low: first point x :type x_low: float :param x: Input value x :type x: float :param x_hi: second point x :type x_hi: float :param y_low: first point y :type y_low: float :param y_hi: second point y :type y_hi: float :return: the linear interpolation of given x :rtype: float """ return (x - x_low) * (y_hi - y_low) / (x_hi - x_low) + y_low
def __gen_mac(id): """ Generate a MAC address Args: id (int): Snappi port ID Returns: MAC address (string) """ return '00:11:22:33:44:{:02d}'.format(id)
def cdf2histogram(c_in): """ Reads cdf as list and returns histogram. """ h = [] h.append(c_in[0]) for i in range(1, len(c_in)): h.append(c_in[i] - c_in[i-1]) return h
def to_int(val, default=None): """ Convert numeric string value to int and return default value if invalid int :param val: the numeric string value :param default: the default value :return: int if conversion successful, None otherwise """ try: return int(val) except (ValueError, TypeError): return default
def _AppendOrReturn(append, element): """If |append| is None, simply return |element|. If |append| is not None, then add |element| to it, adding each item in |element| if it's a list or tuple.""" if append is not None and element is not None: if isinstance(element, list) or isinstance(element, tuple): append.extend(element) else: append.append(element) else: return element
def solution2(nums): """ graph -> {} number: graph_index; graph[n] = graph_i; nums[graph[n]] == n -> it's the root find root: n -> graph_i = graph[n] -> nums[graph_i] """ l = len(nums) graph = {} graph_size = {} def root_index(n): point_to_n = nums[graph[n]] if point_to_n == n: return graph[n] else: return root_index(point_to_n) max_size = 0 for i in range(l): n = nums[i] if n in graph: continue root_i = i if n - 1 not in graph and n + 1 not in graph: graph[n] = i elif n - 1 in graph and n + 1 in graph: root_i1, root_i2 = root_index(n - 1), root_index(n + 1) graph[n] = root_i1 root_i = root_i1 if root_i1 != root_i2: graph[nums[root_i2]] = root_i1 graph_size[root_i1] += graph_size[root_i2] else: # only one in graph n_in_graph = n - 1 if n - 1 in graph else n + 1 graph[n] = graph[n_in_graph] root_i = root_index(n) # plus count graph_size[root_i] = (graph_size.get(root_i) or 0) + 1 max_size = max(max_size, graph_size[root_i]) return max_size
def response_not_requested_feedback(question_id): """ Feedback when the user tries to answer a question, he was not sent. :return: Feedback message """ return "You were not asked any question corresponding to this question ID -> {0}." \ "\n We are sorry, you can't answer it.".format(question_id)
def validatepin(pin): """returns true if the pin is digits only and has length of 4 or 6""" import re return bool(re.match("^(\d{6}|\d{4})$", pin))
def _apply_default_for_one_key(key, cfg, shared): """apply default to a config for a key Parameters ---------- key : str A config key cfg : dict A config shared : dict A dict of shared objects. Returns ------- function A config with default applied """ ret = {} for default_cfg in shared['default_cfg_stack']: ret.update(default_cfg.get(key, {})) ret.update(cfg) return ret
def split_quoted(message): """Like shlex.split, but preserves quotes.""" pos = -1 inquote = False buffer = "" final = [] while pos < len(message)-1: pos += 1 token = message[pos] if token == " " and not inquote: final.append(buffer) buffer = "" continue if token == "\"" and message[pos-1] != "\\": inquote = not inquote buffer += token final.append(buffer) return final
def _get_text_retweet(retweet): """Return text of retweet.""" retweeted = retweet['retweeted_status'] full_text = retweeted['text'] if retweeted.get('extended_tweet'): return retweeted['extended_tweet'].get('full_text', full_text) return full_text
def squish(tup): """Squishes a singleton tuple ('A',) to 'A' If tup is a singleton tuple, return the underlying singleton. Otherwise, return the original tuple. Args: tup (tuple): Tuple to squish """ if len(tup) == 1: return tup[0] else: return tup
def initial_location(roll): """Return initial hit location for a given roll.""" if roll < 100: roll = (roll // 10) + (10 * (roll % 10)) if roll > 30: if roll <= 70: return "Body" elif roll <= 85: return "Right Leg" else: return "Left Leg" elif roll <= 10: return "Head" elif roll <= 20: return "Right Arm" else: return "Left Arm"
def circular_array_rotation(a, k, queries): """Hackerrank Problem: https://www.hackerrank.com/challenges/circular-array-rotation/problem John Watson knows of an operation called a right circular rotation on an array of integers. One rotation operation moves the last array element to the first position and shifts all remaining elements right one. To test Sherlock's abilities, Watson provides Sherlock with an array of integers. Sherlock is to perform the rotation operation a number of times then determine the value of the element at a given position. For each array, perform a number of right circular rotations and return the value of the element at a given index. For example, array a = [3, 4, 5], number of rotations, k = 2 and indices to check, m = [1, 2]. First we perform the two rotations: [3, 4, 5] -> [5, 3, 4] -> [4, 5, 3] Now return the values from the zero-based indices and as indicated in the array. a[1] = 5 a[2] = 3 Args: a (list): array of integers to rotate k (int): the number of times to shift the array right queries (list): list of indices to query on the newly shifted array Returns: list: a list of values returned from the queries """ query_values = [] for query in queries: query_values.append(a[(query-k) % len(a)]) return query_values
def getCenter(x, y, blockSize): """ Determines center of a block with x, y as top left corner coordinates and blockSize as blockSize :return: x, y coordinates of center of a block """ return (int(x + blockSize/2), int(y + blockSize/2))
def WDM_suppression(m, m_c, a_wdm, b_wdm, c_wdm): """ Suppression function from Lovell et al. 2020 :return: the factor that multiplies the CDM halo mass function to give the WDM halo mass function dN/dm (WDM) = dN/dm (CDM) * WDM_suppression where WDM suppression is (1 + (a_wdm * m_c / m)^b_wdm)^c_wdm """ ratio = a_wdm * m_c / m factor = 1 + ratio ** b_wdm return factor ** c_wdm