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"...
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 ...
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: ...
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...
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_...
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}.") ...
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_p...
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_num...
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(...
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 ...
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 #d...
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...
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' } """ ...
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) ...
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 Non...
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 +...
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 ite...
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])] ...
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_k...
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: ...
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(f...
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, bi...
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_l...
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', 'nu...
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 `it...
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)...
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':...
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' ...
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: ...
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 ...
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 == 'k...
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 ...
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/...
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...
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 i...
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 ...
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 ...
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...
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): ...
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...
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(quest...
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 ...
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] != "\\"...
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" ...
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 ...
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...