content
stringlengths
42
6.51k
def _format_default(expr): """ Return text from a default value expression. Return a simplified form of a PostgreSQL default value. """ if expr.lower().startswith('nextval('): r = expr.split("'", 1)[1] r = r.rsplit("'", 1)[0] return r + '()' elif expr.startswith("'"): r = expr.split("'", 1)[1] r = r.rsplit("'", 1)[0] return "'" + r + "'" else: return expr
def _nbaLeague(x): """Takes in initials of league and returns numeric API Code Input Values: "NBA", "WNBA", or "NBADL" Used in: _Draft.Anthro(), _Draft.Agility(), _Draft.NonStationaryShooting(), _Draft.SpotUpShooting(), _Draft.Combine() """ leagues = {"NBA":"00", "WNBA":"10", "NBADL":"20"} try: return leagues[x.upper()] except: raise ValueError("Please use one of the following values for League: 'NBA', 'WNBA', 'NBADL'")
def pretty_keys(dictionary): """ return pretty printed list of dictionary keys, num per line """ if not dictionary: return [] # - number of keys printed per line num = 5 # - turn into sorted list keys = list(dictionary.keys()) keys.sort() # - fill with blank elements to width num missing = (len(keys) % num) if missing != 0: to_add = num - missing keys.extend([''] * to_add) # - turn into 2D matrix matrix = [[keys[i+j] for i in range(0, num)] for j in range(0, len(keys), num)] # - calculate max width for each column len_matrix = [[len(col) for col in row] for row in matrix] max_len_col = [max([row[j] for row in len_matrix]) for j in range(0, num)] # - pad with spaces matrix = [[row[j].ljust(max_len_col[j]) for j in range(0, num)] for row in matrix] # - return list of lines to print matrix = [' '.join(row) for row in matrix] return matrix
def Name_Validation(Name): """ Function to Validate a Name for Input: Allowing Spaces, - and '""" for Char in Name: if ("A" <= Char <= "Z" or "a" <= Char <= "z" or Char == "-" or Char == "'"): continue else: return False return True
def __sort_element(a, b, offset: int) -> bool: """ Sort elements based on the offset """ # 140, 141, 142 are treated as one point here if abs(a[0] - b[0]) < offset: return a[1] - b[1] return a[0] - b[0]
def sigmoid_derivative(x): """ args: x - some number return: derivative of sigmoid given x """ x_prime = x*(1-x) return x_prime
def count_bits(x): """ A program to count the number of bits in a non-negative integer. It tests one bit at a time, starting with the least significant bit. """ num_bits = 0 while x: num_bits += x & 1 x >>= 1 print(x) return num_bits
def lifetime(duration): """Returns a dictionary that converts a number of seconds into a dictionary object with keys of 'days', 'hours', 'minutes', and 'seconds'. Parameters ---------- duration (int): The duration (in seconds) to be transformed into a dictionary. Returns ------- dict a dictionary in the form of dict('days':int(), 'hours':int(), 'minutes':int(),'seconds':int()) """ dct = {} dct['days'] = duration//86400 dct['hours']= duration%86400//3600 dct['minutes'] = (duration%86400)%3600//60 dct['seconds'] = (duration%86400)%3600%60 return dct
def _divide_or_zero(numerator, denominator): """ Divide numerator by denominator. If the latter is 0, return 0. >>> _divide_or_zero(1, 2) 0.5 >>> _divide_or_zero(1, 0) 0.0 :param numerator: float. :param denominator: float. :return: float. """ if denominator == 0: return 0.0 return numerator / denominator
def make_list(arg): """Returns the argument as a list. If already a list, ``arg`` is returned. """ if not isinstance(arg, list): arg = [arg] return arg
def bezier_quadratic(p0, p1, p2, t): """returns a position on bezier curve defined by 3 points at t""" return p1 + (1-t)**2*(p0-p1) + t**2*(p2-p1)
def quote(arg: object) -> object: """ Puts quotes around a string (so it appears as a string in output). Otherwise returns argument unchanged. :param arg: argument to transform. :return: argument quoted if a string, otherwise unchanged. """ if isinstance(arg,str): return f"'{arg}'" else: return arg
def eratosthenes(n): """ This function generates a list of all primes smaller than n using eratosthenes's algorithm """ #generate a list of integers to filter integers = [x for x in range(2,n)] i = 0 while i<len(integers): #remove all elements that are divisible by the largest prime that hasn't been checked yet #the condition statement is the condition for keeping the value (ie. primeness condition) #the first of these is that it must not be divisible by smaller primes #the second of these ensures that a prime is not removed for being divisible by itself integers = [x for x in integers if ((x%integers[i])!=0 or x==integers[i])] i+=1 return integers
def _split_tag_path_pattern(tag_path_pattern): """ Returns a list of tag patterns and the prefix for a given tag path pattern. Args: tag_path_pattern (str) """ if tag_path_pattern.startswith('+/') or tag_path_pattern.startswith('*/'): prefix = tag_path_pattern[:2] tag_path_pattern = tag_path_pattern[2:] else: prefix = '' return tag_path_pattern.split('.'), prefix
def isinsidebbox(bbox,p): """ does point ``p`` lie inside 3D bounding box ``bbox``?""" return p[0] >= bbox[0][0] and p[0] <= bbox[1][0] and\ p[1] >= bbox[0][1] and p[1] <= bbox[1][1] and\ p[2] >= bbox[0][2] and p[2] <= bbox[1][2]
def factorial(n): """Return the factorial of n A factorial is a number multiplied by all the numbers before it until 1 It's written as the number followed by an exclamation mark: 5! So 5! = 5 * 4 * 3 * 2 * 1 = 120 eg factorial(4) should return: 24 """ result = 1 for i in range(n): result = result + (i * result) return result
def GetUIntLength(length_descriptor): """Returns the amount of bytes that will be consumed, based on the first read byte, the Length Descriptor.""" assert 0 <= length_descriptor <= 0xFF length = 0 for i in range(8): # big endian if (length_descriptor & (0x80 >> i)) != 0: # 128, 64, 32, ..., 1 length = i + 1 break assert 0 <= length <= 8 return length
def octave_from_midi(midi_note): """ Get octave number from MIDI number :param midi_note: MIDI note number :return: octave number """ octave = None if midi_note >= 12: octave = int((midi_note / 12) - 1) elif midi_note >= 0: octave = -1 return octave
def get_max_chkpt_int(algorithm_states): """Get the maximum time in seconds between checkpoints. """ max_chkpt_int = -1 for s in algorithm_states: max_chkpt_int = max(s['chkpt_int'], max_chkpt_int) return max_chkpt_int
def format_description(text): """Format the description. This is too complex to be done in the Jinja template. It can be done, but it'll be messy. - convert underscores in text to URLs and bold, - no need to convert asterisk, since they're underline in myAST already, - no need to format http:// URLs, since they're also handled automatically. :param text: text to process :type text: string :returns: converted string """ if not text or len(text) == 0: return "" # Add spaces after these so we correctly split "(_gbase" type constructs puncts = ["(", ",", ";"] for punct in puncts: text = text.replace(punct, punct + " ") # Add spaces before these for punct in [")"]: text = text.replace(punct, " " + punct) words = text.split() text2 = "" for word in words: if len(word) > 0: if word.count('_') == 2: pre = word[0:word.find('_')] ct = word[word.find('_') + 1:word.rfind('_')] post = word[word.rfind('_') + 1:] word = "{} {{ref}}`schema:{}`{}".format(pre, ct.lower(), post) elif word[0] == '_': word = "**{}**".format(word[1:]) text2 = text2 + word + " " return text2.rstrip()
def bytes2bin(bites, sz=8): """Accepts a string of ``bytes`` (chars) and returns an array of bits representing the bytes in big endian byte order. An optional max ``sz`` for each byte (default 8 bits/byte) which can be used to mask out higher bits.""" if sz < 1 or sz > 8: raise ValueError("Invalid sz value: %d" % sz) ''' # I was willing to bet this implementation was gonna be faster, tis not retval = [] for bite in bytes: bits = [int(b) for b in bin(ord(bite))[2:].zfill(8)][-sz:] assert(len(bits) == sz) retval.extend(bits) return retval ''' retVal = [] for b in [bytes([b]) for b in bites]: bits = [] b = ord(b) while b > 0: bits.append(b & 1) b >>= 1 if len(bits) < sz: bits.extend([0] * (sz - len(bits))) elif len(bits) > sz: bits = bits[:sz] # Big endian byte order. bits.reverse() retVal.extend(bits) return retVal
def validate_sim_measure_type(sim_measure_type): """Check if the input sim_measure_type is one of the supported types.""" sim_measure_types = ['COSINE', 'DICE', 'EDIT_DISTANCE', 'JACCARD', 'OVERLAP'] if sim_measure_type.upper() not in sim_measure_types: raise TypeError('\'' + sim_measure_type + '\' is not a valid ' + \ 'sim_measure_type. Supported types are COSINE, DICE' + \ ', EDIT_DISTANCE, JACCARD and OVERLAP.') return True
def rotate(s, x, y, rx, ry): """Rotate a point.""" if ry is 0: if rx is 1: x = s - 1 - x y = s - 1 - y x, y = y, x return (x, y)
def is_even(x: int) -> bool: """Checks if x is an even number""" return x/2 == x // 2
def is_palindrome(phrase): """Is phrase a palindrome? Return True/False if phrase is a palindrome (same read backwards and forwards). >>> is_palindrome('tacocat') True >>> is_palindrome('noon') True >>> is_palindrome('robert') False Should ignore capitalization/spaces when deciding: >>> is_palindrome('taco cat') True >>> is_palindrome('Noon') True """ normalized = phrase.lower().replace(' ', '') return normalized == normalized[::-1]
def _base_url(host, port): """ Provides base URL for HTTP Management API :param host: JBossAS hostname :param port: JBossAS HTTP Management Port """ return "http://{host}:{port}/management".format(host=host, port=port)
def generate_num_processes_default(AUTOMS_NUM_PROCESSES): """ Generates the default num processes parameter value to use using configured 'num processes' """ if AUTOMS_NUM_PROCESSES is None: num_processes_default = 1 else: num_processes_default = AUTOMS_NUM_PROCESSES return num_processes_default
def redcap_event_to_vbr_protocol(event_name: str) -> int: """Map redcap event name to VBR protocol.""" # NOTE - this must be manually synced with src/scripts/data/protocol.csv events = { "informed_consent_arm_1": 2, "baseline_visit_arm_1": 3, "6wks_postop_arm_1": 30, "3mo_postop_arm_1": 31, "event_1_arm_1": 50, } try: return events[event_name] except KeyError: raise ValueError("Unknown redcap event name: %s", event_name)
def _parse_mdcstat(post_params): """ parses mdcstat from bld in post_params. Parameters ---------- post_params: dict Examples : { "bld": "dbms/MDC/STAT/standard/MDCSTAT01701", "tboxisuCd_finder_stkisu0_2": "060310/3S", "isuCd": "KR7060310000", "isuCd2": "060310", "codeNmisuCd_finder_stkisu0_2": "3S", "param1isuCd_finder_stkisu0_2": "STK", "strtDd": "000040", "endDd": "20210401", "MIME Type": "application/x-www-form-urlencoded; charset=UTF-8", "csvxls_isNo": "false", } Returns ------- In this case, MDCSTAT01701 will be returned """ bld = post_params["bld"] mdcstat = bld.split("/")[-1] return mdcstat
def join_url(base_url, leaf): """Return the result of joining two parts of a url together. Usage Examples: >>> join_url('http://example.com/', 'mypage/') 'http://example.com/mypage/' >>> join_url('http://example.com', 'mypage/') 'http://example.com/mypage/' :base_url: the start of the new url :leaf: the end of the new url :returns: the joined url """ return '/'.join([base_url.rstrip('/'), leaf])
def R0(dw, hmin): """ R0 Determining the nominal diameter d and checking the lomiting size G """ # DSV [Throught bolted joint] G = hmin + dw # (R0/1) # ESV [Tapped thread joint] # G1 = (1.5,...,2) dw return G #
def get_subset_dict(dictionary, subkey): """Function to seperate inner key and its values - to extracting pharmacogenomics_therapeutics, pharmacogenomics_combined_variants_therapeutics, adverse_effect_therapeutics, adverse_effect_combined_variants_therapeutics.""" sub = {} for key, value in dictionary.items(): sub[key] = [] for sub_dict in value: if not sub_dict[subkey]: continue sub[key].append({"variant": sub_dict["variant"], "variant_class": sub_dict["variant_class"], "variant_type": sub_dict["variant_type"], subkey: sub_dict[subkey], "chromosome": sub_dict["chromosome"], "assembly_version": sub_dict["assembly_version"], "alteration_base": sub_dict["alteration_base"], "reference_base": sub_dict["reference_base"], "start": sub_dict["start"], "stop": sub_dict["stop"]}) if not sub[key]: del sub[key] return sub
def gnome_sort(unsorted): """Pure implementation of the gnome sort algorithm in Python.""" if len(unsorted) <= 1: return unsorted i = 1 while i < len(unsorted): if unsorted[i - 1] <= unsorted[i]: i += 1 else: unsorted[i - 1], unsorted[i] = unsorted[i], unsorted[i - 1] i -= 1 if (i == 0): i = 1
def sse_pack(d): """For sending sse to client. Formats a dictionary into correct form for SSE""" buf = '' for k in ['retry','id','event','data']: if k in d.keys(): buf += '{}: {}\n'.format(k, d[k]) return buf + '\n'
def get_neighb_ver(curr_i, curr_j, off, w, h): """Computes the neighbour with vertical offset for upper half of the image and horizontal offset for the lower part of the cubemap image.""" if(0 <= curr_i < h): if(0 <= curr_j < w): if ((curr_i + off) >= h): return 2*h-(curr_i+off-h+1), w-(curr_j+1) elif ((curr_i + off) < 0): return 2*h+(curr_i+off), 2*w+curr_j elif(w <= curr_j < 2*w): if ((curr_i + off) >= h): return 2*h-(curr_j-w+1), (curr_i + off-h) elif ((curr_i + off) < 0): return 2*h-(curr_j-w+1), 3*w + (curr_i + off) elif(2*w <= curr_j < 3*w): if ((curr_i + off) >= h): return (curr_i+off), curr_j-2*w elif ((curr_i + off) < 0): return h - (curr_i+off+1), 3*w - (curr_j-2*w+1) return curr_i+off, curr_j elif(h <= curr_i < 2*h): if(0 <= curr_j < w): if ((curr_j + off) >= w): return curr_i, curr_j + off elif ((curr_j + off) < 0): return w+curr_j+off, 2*w-(curr_i-w+1) elif(w <= curr_j < 2*w): if ((curr_j + off) >= 2*w): return curr_i, curr_j + off elif ((curr_j + off) < w): return curr_i, curr_j + off elif(2*w <= curr_j < 3*w): if ((curr_j + off) >= 3*w): return (curr_j+off-3*w), 2*w-(curr_i-h+1) elif ((curr_j + off) < 2*w): return curr_i, curr_j + off return curr_i, curr_j+off
def round_to_nearest(value, round_value=1000): """Return the value, rounded to nearest round_value (defaults to 1000). Args: value: Value to be rounded. round_value: Number to which the value should be rounded. Returns: Value rounded to nearest desired integer. """ if round_value < 1: ds = str(round_value) nd = len(ds) - (ds.find('.') + 1) value = value * 10**nd round_value = round_value * 10**nd value = int(round(float(value) / round_value) * round_value) value = float(value) / 10**nd else: value = int(round(float(value) / round_value) * round_value) return value
def smallest_sums(partition:list, num_of_sums:int=1)->float: """ Given a partition, return the sum of the smallest k parts (k = num_of_sums) >>> smallest_sums([[1,2],[3,4],[5,6]]) 3 >>> smallest_sums([[1,2],[3,4],[5,6]], num_of_sums=2) 10 """ sorted_sums = sorted([sum(part) for part in partition]) return sum(sorted_sums[:num_of_sums])
def classify_attachments(files): """ Return an (audio_files, related_docs) tuple. """ audio = [] related = [] for f in files: if 'audio' in f['file_mime']: audio.append(f) else: related.append(f) return audio, related
def only_digits(name: str) -> str: """ "O1" -> "1" """ return ''.join([i for i in name if i.isdigit()])
def is_keys_str_decimals(dictionary: dict): """ Checks if the keys are string decimals Args: dictionary: Dictionary object to check Returns: True if keys are numerical strings """ keys = dictionary.keys() are_decimals = [isinstance(k, str) and k.isdecimal() for k in keys] return all(are_decimals)
def is_delete_name(name): """ Determines if the specified name is flagged for deletion with the "!" prefix. :param name: the name to be checked :return: True if the name is prefixed, false otherwise """ return name.startswith("!")
def f(x): """ """ return x*x+1
def oidc_to_user_data(payload): """ Map OIDC claims to Django user fields. """ payload = payload.copy() field_map = { 'given_name': 'first_name', 'family_name': 'last_name', 'email': 'email', } ret = {} for token_attr, user_attr in field_map.items(): if token_attr not in payload: continue ret[user_attr] = payload.pop(token_attr) ret.update(payload) return ret
def getTypeFromStr(s): """ determine the type of the input string string s: the string whose type we wish to get Returns the type of the input string """ try: int(s) return "int" except ValueError: return "string"
def get_comments(events, comments=None): """ Pick comments and pull-request review comments out of a list of events. Args: events: a list of (event_type str, event_body dict, timestamp). comments_prev: the previous output of this function. Returns: comments: a list of dict(author=..., comment=..., timestamp=...), ordered with the earliest comment first. """ if not comments: comments = {} else: comments = {c['id']: c for c in comments} comments = {} # comment_id : comment for event, body, _timestamp in events: action = body.get('action') if event in ('issue_comment', 'pull_request_review_comment'): comment_id = body['comment']['id'] if action == 'deleted': comments.pop(comment_id, None) else: c = body['comment'] comments[comment_id] = { 'author': c['user']['login'], 'comment': c['body'], 'timestamp': c['created_at'], 'id': c['id'], } return sorted(comments.values(), key=lambda c: c['timestamp'])
def dq_string(data): """ repr a string with double quotes. This is probably a fragile hack, so if it breaks, please do something better! """ return '"'+repr("'"+data)[2:]
def remove_duplicates(elements, condition=lambda _: True, operation=lambda x: x): """ Removes duplicates from a list whilst preserving order. We could directly call `set()` on the list but it changes the order of elements. """ local_set = set() local_set_add = local_set.add filtered_list = [] for x in elements: if condition(x) and not (x in local_set or local_set_add(x)): operated = operation(x) filtered_list.append(operated) local_set_add(operated) return filtered_list
def big (cave): """Indicates whether or not `cave` is big.""" return cave.isupper()
def factorial(n): """ To Find Factorial Of n """ if n == 0: result = 1 else: result = n * factorial(n-1) return result
def calc_conformance(results): """Returns a tuple with the number of total and failed testcase variations and the conformance as percentage.""" total = len(results) passed = failed = skipped = 0 for status, _ in results.values(): if status == 'PASS': passed += 1 elif status == 'SKIP': skipped += 1 else: failed += 1 conformance = (total - failed) * 100 / total return total, failed, skipped, conformance
def update_values_in_key_list(existing_values: list, new_values: list or str, remove_values: list or str, replace_values: list or str): """ Updates values within a list by first appending values in the new_values list, removing values in the remove_values list and then replacing values in the replace_values list :param existing_values list with existing values to modify :param new_values list with values to add to the existing value list :param remove_values list with values to remove from the existing value list :param replace_values list with values to replace in the existing value list returns updated existing value list """ if new_values: new_values = new_values.split() if isinstance(new_values, str) else new_values existing_values.extend(new_values) if remove_values: remove_values = remove_values.split() if isinstance(remove_values, str) else remove_values existing_values = list(filter(lambda value: value not in remove_values, existing_values)) if replace_values: replace_values = replace_values.split() if isinstance(replace_values, str) else replace_values existing_values = replace_values return existing_values
def nice(val): """nice printer""" if val == 'M': return 'M' if val < 0.01 and val > 0: return 'Trace' return '%.2f' % (val, )
def check_prev_char(password, current_char_set): """Function to ensure that there are no consecutive UPPERCASE/lowercase/numbers/special-characters.""" index = len(password) if index == 0: return False else: prev_char = password[index - 1] if prev_char in current_char_set: return True else: return False
def get_pathless_file_size(data_file): """ Takes an open file-like object, gets its end location (in bytes), and returns it as a measure of the file size. Traditionally, one would use a systems-call to get the size of a file (using the `os` module). But `TemporaryFileWrapper`s do not feature a location in the filesystem, and so cannot be tested with `os` methods, as they require access to a filepath, or a file-like object that supports a path, in order to work. This function seeks the end of a file-like object, records the location, and then seeks back to the beginning so that the file behaves as if it was opened for the first time. This way you can get a file's size before reading it. (Note how we aren't using a `with` block, which would close the file after use. So this function leaves the file open, as an implicit non-effect. Closing is problematic for TemporaryFileWrappers which wouldn't be operable again) :param data_file: :return size: """ if not data_file.closed: data_file.seek(0, 2) size = data_file.tell() print(size) data_file.seek(0, 0) return size else: return 0
def check_uniqueness_in_rows(board: list): """ Check buildings of unique height in each row. Return True if buildings in a row have unique length, False otherwise. >>> check_uniqueness_in_rows(['***21**', '412453*', '423145*',\ '*543215', '*35214*', '*41532*', '*2*1***']) True >>> check_uniqueness_in_rows(['***21**', '452453*', '423145*',\ '*543215', '*35214*', '*41532*', '*2*1***']) False >>> check_uniqueness_in_rows(['***21**', '412453*', '423145*',\ '*553215', '*35214*', '*41532*', '*2*1***']) False """ for row in board[1:-1]: if ('*' not in row[1:-1]) and (len(set(row[1:-1])) < len(row[1:-1])): return False return True
def get_recommended_simplification_params(warning_len): """Return the recommended geometry simplification tolerance and buffer. These settings are based on the number of warnings present, and designed to prevent the map interface from lagging if many warnings are present. Parameters ---------- warning_len : int number of warnings in the warning list. Returns ------- dict {'tol': float, 'buf': float}. Parameters which determine the degree of shape approximation recommended for mapping. """ if warning_len < 10: return {'tol': 0.000, 'buf': 0.000} tol = (round(warning_len, -1) - 10) * 0.000025 buf = (round(warning_len, -1) - 10) * 0.00005 return {'tol': tol, 'buf': buf}
def mergelistmult(lst1,lst2): """returns the product at each index comparing 2 lists""" try: return [lst1[i]*lst2[i] for i in range(len(lst1))] except: print('incompatible lists')
def _get_sfn_execution_arn_by_name(state_machine_arn, execution_name): """ * Given a state machine arn and execution name, returns the execution's ARN * @param {string} state_machine_arn The ARN of the state machine containing the execution * @param {string} execution_name The name of the execution * @returns {string} The execution's ARN """ return (':').join([state_machine_arn.replace(':stateMachine:', ':execution:'), execution_name])
def validate_severity(parser, arg): """Check that the severity level provided is correct.""" _VALID_SEVERITIES = {'info': 0, 'warning': 1, 'error': 2} if arg.strip().lower() not in _VALID_SEVERITIES: parser.error("Invalid severity. Options are error, warning, or info") else: return _VALID_SEVERITIES[arg.strip().lower()]
def slugify(value): """ Normalizes string, converts to lowercase, removes non-alpha characters, and converts spaces to hyphens. """ import re import unicodedata value = str(value) value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignore').decode('utf8').strip().lower() value = re.sub(r'[^\w\s\-\.]', '', value) value = re.sub(r'[-\s]+', '-', value) return value
def can_be_index(obj): """Determine if an object can be used as the index of a sequence. :param any obj: The object to test :returns bool: Whether it can be an index or not """ try: [][obj] except TypeError: return False except IndexError: return True
def parseStyle(style): """Parse style attribute into dict""" if style is None or style.strip() == '': return {} else: return dict([[part.strip() for part in prop.split(":")] for prop in style.split(";")])
def dictlist_to_dict(dictlist, key): """turn a list of dicts with a common key into a dict. values of the key should be unique within the dictlist Example ------- >>>dict_list = [{"id":"a"}, {"id":"b"}] >>>dictlist_to_dict(dict_list, "id") {'a': {'id': 'a'}, 'b': {'id': 'b'}} """ result = {} for dct in dictlist: k = dct[key] result[k] = dct return result
def readVector(text): """Reads a vector from text 'n v1 ... vn'""" items = text.split() if int(items[0])+1 != len(items): raise ValueError("Invalid number of items") return [float(v) for v in items[1:]]
def parse_header_prot_name( protocol_int # type: int ): """Parse InMon-defined header protocol names""" if protocol_int == 1: protocol_name = "Ethernet" elif protocol_int == 2: protocol_name = "Token Bus" elif protocol_int == 3: protocol_name = "Token Ring" elif protocol_int == 4: protocol_name = "FDDI" elif protocol_int == 5: protocol_name = "Frame Relay" elif protocol_int == 6: protocol_name = "X.25" elif protocol_int == 7: protocol_name = "PPP" elif protocol_int == 8: protocol_name = "SMDS" elif protocol_int == 9: protocol_name = "AAL5" elif protocol_int == 10: protocol_name = "AAL5-IP" elif protocol_int == 11: protocol_name = "IPv4" elif protocol_int == 12: protocol_name = "IPv6" elif protocol_int == 13: protocol_name = "MPLS" elif protocol_int == 14: protocol_name = "POS" elif protocol_int == 15: protocol_name = "802.11 MAC" elif protocol_int == 16: protocol_name = "802.11 AMPDU" elif protocol_int == 17: protocol_name = "802.11 AMSDU Subframe" elif protocol_int == 18: protocol_name = "InfiniBand" else: protocol_name = "Unknown" return protocol_name
def permut(block, table): """Permut the given block using the given table (so generic method)""" return [block[x] for x in table]
def isbool(string): """ Checks if a string can be converted into a boolean. Parameters ---------- value : str Returns ------- bool: True/False if the string can/can not be converted into a boolean. """ return string in ("True", "true", "False", "false")
def _ListOpToList(listOp): """Apply listOp to an empty list, yielding a list.""" return listOp.ApplyOperations([]) if listOp else []
def __calculate_percentage_difference(measure_1, measure_2): """ Percentage difference calculation """ try: return round(abs(100*(measure_1-measure_2)/((measure_1+measure_2)/2)),3) except ZeroDivisionError: return 0
def skill_lvl(lvl, exp_required): """Calculate the essential skills of the player""" for i in range(len(exp_required)): if lvl < exp_required[i]: return i if lvl > exp_required[len(exp_required) - 1]: if len(exp_required) == 50: return 50 else: return 60 if lvl == exp_required[i]: return i
def v_bar(cv): """Return the trace of ``cv`` divided by 2 :arg cv: a variance-covariance matrix :type cv: 4-element sequence of float :returns: float **Example**:: >>> x1 = 1-.5j >>> x2 = .2+7.1j >>> z1 = ucomplex(x1,(1,.2)) >>> z2 = ucomplex(x2,(.2,1)) >>> y = z1 * z2 >>> y.v VarianceCovariance(rr=2.3464, ri=1.8432, ir=1.8432, ii=51.4216) >>> reporting.v_bar(y.v) 26.884 """ assert len(cv) == 4,\ "'%s' a 4-element sequence is needed" % type(cv) return (cv[0] + cv[3]) / 2.0
def numericrange_to_tuple(r): """Helper method to normalize NumericRange into a tuple.""" if r is None: return (None, None) lower = r.lower upper = r.upper if lower and not r.lower_inc: lower -= 1 if upper and not r.upper_inc: upper -= 1 return lower, upper
def demandValue(taglist,liste,phrase1,mot): """ put values of all items in string to insert in database taglist: list with name of all items liste: list of item value phrase1: string with values of all items mot: value of an item return a string with values of all items separated with ',' """ for i in range(len(liste)): mot = str(liste[i]) phrase1 += "'" phrase1 += mot phrase1 += "'" if not i == len(liste)-1: phrase1 += ',' return phrase1
def bool(x): """Implementation of `bool`.""" return x.__bool__()
def kpoints_str(lst, base='nk'): """[3,3,3] -> "nk1=3,nk2=3,nk3=3" Useful for QE's phonon toolchain ph.x, q2r.x, matdyn.x """ return ','.join(['%s%i=%i' %(base, i+1, x) for i, x in enumerate(lst)])
def unflatten(iter, n=2): """Group ``iter`` into tuples of length ``n``. Raise an error if the length of ``iter`` is not a multiple of ``n``. """ if n < 1 or len(iter) % n: raise ValueError('iter length is not a multiple of %i' % n) return list(zip(*(iter[i::n] for i in range(n))))
def calculate_node_degree_in_collection(collection, v): """ calculates the degree of node v in collection by the formula: deg(v, collection) = the number of clusters in collection, v belongs to :param collection: collection of clusters :param v: node :return: degree of v in collection """ counter = 0 for cluster in collection: if v in cluster: counter += 1 return counter
def rgb_to_hex1(rgb): """Receives (r, g, b) tuple, checks if each rgb int is within RGB boundaries (0, 255) and returns its converted hex, for example: Silver: input tuple = (192,192,192) -> output hex str = #C0C0C0""" if not all(0 <= val <= 255 for val in rgb): raise ValueError(f"rgb {rgb} not in range(256)") return "#" + "".join([f"{val:02x}" for val in rgb]).upper()
def recusive_del_key(dic: dict, key: str): """ Recusively remove keys in a dictionary. >>> recusive_del_key({'a': 2, 'b': 1}, 'a') {'b': 1} >>> recusive_del_key({'b': 1}, None) {'b': 1} >>> recusive_del_key({'b': 1}, 'c') {'b': 1} >>> recusive_del_key({'b': {'a': 1, 'c': 4}}, 'c') {'b': {'a': 1}} :type dic: dict[str, unicode] :param dic: dictionary to remove key :type key: str :param key: key to remove """ if not key: return dic dic.pop(key, None) for k in dic: if isinstance(dic[k], dict): recusive_del_key(dic[k], key) return dic
def camel_to_snake_fast(s: str) -> str: """Converts the given text from CamelCase to snake_case, faster. This function is *slightly* faster than the :obj:`camel_to_snake` implementation, however that comes at the expense of accuracy. Please see the warnings below for more information. Parameters ---------- s : str The text to convert. Returns ------- str The converted text. Warnings -------- This is faster than the :obj:`camel_to_snake` - however that speed gain comes with not catching edge-cases such as multiple uppercase letters in a row or non-letter characters. Notes ----- Originally from: https://stackoverflow.com/a/44969381 """ return ''.join('_'+x.lower() if x.isupper() else x for x in s).lstrip('_')
def listobj_or_none(hash, list_obj, list_hash): """ A convenience function for determining which object in a list to return based on a list of the hash values for the objects. Parameters ---------- 1. hash : int The hash value for the desired object 2. list_obj : list A list of objects 3. list_hash : list The hash values for the objects in list_obj Returns ------- 1. obj : object or None The object from list_obj with matching hash or None (if there was no such object) """ try: index = list_hash.index(hash) obj_new = list_obj[index] except: obj_new = None return obj_new
def sessions(event_id=None): """Returns the session ids for the event.""" return [1, 2, 3]
def _merge(*parts): """ Utility function to merge various strings together with no breaks """ return ' '.join(parts)
def _all_good_hits_with_scores(hits_scores, max_bit_score_delta_for_good_hits): """ return a list of (id, score, evalue) tuples representing good scores based on difference between alignment score for each hit and score of the best hit. :param hits_scores: list of tuples [(id,score,evalue),(id,score,evalue)] ranked by score :param max_bit_score_delta_for_good_hits: integer :return: list of 3-part tuples (str,int,float) for (id,score,evalue) """ top_bit_score = hits_scores[0][1] return([x for x in hits_scores if (top_bit_score - x[1]) <= max_bit_score_delta_for_good_hits])
def groupby(seq, key): """ Description ---------- Create a dictionary with keys composed of the return value of the funcion/key\n applied to each item in the sequence. The value for each key is a list of values\n that produced the key. Parameters ---------- seq : (list or tuple or set) - sequence to iterate\n key : (callable or dictionary key) - callable to apply each iteration or key to extract\n from each dictionary per iteration Returns ---------- dict : a dictionary containing keys returned from each iteration and the values that returned it Examples ---------- >>> def even_odd(x): ... if x % 2 == 0: ... return 'even' ... return 'odd' >>> lst = [1, 2, 3, 4, 5, 6, 7] >>> groupby(lst, even_odd) -> {'even': [2, 4, 6], 'odd': [1, 3, 5, 7]} >>> people = [ ... {'name': 'Sam', 'gender': 'male'}, ... {'name': 'John', 'gender': 'male'}, ... {'name': 'Jane', 'gender': 'female'}, ... {'name': 'Chase', 'gender': 'male'}, ... {'name': 'Melanie', 'gender': 'female'}] >>> groupby(people, 'gender') -> { 'male': [ {'name': 'Sam', 'gender': 'male'}, {'name': 'John', 'gender': 'male'}, {'name': 'Chase', 'gender': 'male'} ], 'female': [ {'name': 'Jane', 'gender': 'female'}, {'name': 'Melanie', 'gender': 'female'} ] } """ if not isinstance(seq, (list, tuple, set)): raise TypeError("param 'seq' must be a list, tuple, or set") if len(seq) == 0: return {} dct = {} get = dct.get if callable(key): for item in seq: val = key(item) if get(val) is not None: dct[val].append(item) else: dct[val] = [item] else: for item in seq: val = item[key] if get(val) is not None: dct[val].append(item) else: dct[val] = [item] return dct
def get_program_frames(command_dicts): """ Parces command_dicts to produce a list of frames that represent the programs timestep :param command_dicts: list formatted by mimic_program containing dicts of program info at each program timestep :return frames: list """ frames = [] for command in command_dicts: frames.append(command['Frame']) return frames
def Mean(values): """Returns the arithmetic mean of |values|.""" if not values or None in values: return None return sum(values) / float(len(values))
def transform_resource_name(ctx, param, value): """Callback to transform resource_name into title case.""" if value is not None: return value.title() return value
def get_id_field_from_input_field_name(input_field_name: str) -> str: """ Map plural input fields like children to the appropriate field child_ids in this case. """ if input_field_name == "children": return "child_ids" return input_field_name.rstrip("s") + "_ids"
def deltawords(num, arg): """An adverb to come after the word 'improved' or 'slipped' """ delta = abs(num - arg) # We only pick out changes over 10%; over 30% in 9 months is unheard of. if delta == 0: word = "not at all" elif delta < 10: word = "slightly" elif delta < 20: word = "moderately" elif delta < 30: word = "considerably" else: word = "massively" return word
def extend_points(tip=[[0], [0], [0]], end=[[0], [0], [0]], factor=2): """ returns new coordinates of the points to extend in a list the default value of tip is the origin end is also a list """ # print("extending coords...") xnew = factor * (end[0][0] - tip[0][0]) + tip[0][0] ynew = factor * (end[1][0] - tip[1][0]) + tip[1][0] znew = factor * (end[2][0] - tip[2][0]) + tip[2][0] return [[xnew], [ynew], [znew]]
def upper_camel_case(snake_str): """ Convert a snake case str to upper camel case """ words = snake_str.split("_") return "".join([w.title() for w in words])
def check_valid_image(path_to_image): """ Function to check if a file has valid image extensions and return True if it does. Note: Azure Cognitive Services only accepts below file formats. """ valid_extensions = ['.png', '.jpg', '.jpeg', '.gif', '.bmp', '.jfif'] if path_to_image.endswith((tuple(valid_extensions))): return True
def statuscheck(status, item): """since we are doing this a lot might as well return something more meaningful""" if status == 404: out = "It appears {} does not exist.".format(item) elif status == 503: out = "Qur'an API is having problems, it would be best to check back later." else: out = "Qur'an API returned an error, response: {}".format(status) return out
def build_fib_recursive(n): """ n: number of elements in the sequence Returns a Fibonacci sequence of n elements by recursive method """ if n == 1: return [0] elif n == 2: return [0, 1] else: last_elem = build_fib_recursive(n-1)[-1] + build_fib_recursive(n-2)[-1] return build_fib_recursive(n-1) + [last_elem]
def fill_clusters(clusters, element_i, element_j): """ Fill the list of clusters (sets) with two elements from the same cluster. >>> clusters = [] >>> fill_clusters(clusters, 1, 10) [{1, 10}] >>> fill_clusters(clusters, 10, 100) [{1, 10, 100}] >>> fill_clusters(clusters, 20, 30) [{1, 10, 100}, {20, 30}] """ if not clusters: # i.e. len(clusters) == 0 clusters.append({element_i, element_j}) else: found = False for cluster in clusters: if element_i in cluster: cluster.add(element_j) found = True elif element_j in cluster: cluster.add(element_i) found = True if not found: clusters.append({element_i, element_j}) return clusters
def binary_search(a_list, item): """Performs iterative binary search to find the position of an integer in a given, sorted, list. a_list -- sorted list of integers item -- integer you are searching for the position of """ first = 0 last = len(a_list) - 1 while first <= last: i = (first + last) // 2 if a_list[i] == item: return i elif a_list[i] > item: last = i - 1 elif a_list[i] < item: first = i + 1 else: return -1 return -1
def MakeUrl(host, port=80, location=''): """ Create a Tasmota host url @param host: hostname or IP of Tasmota host @param port: port number to use for http connection @param location: http url location @return: Tasmota http url """ return "http://{shost}{sdelimiter}{sport}/{slocation}".format(\ shost=host, sdelimiter=':' if port != 80 else '', sport=port if port != 80 else '', slocation=location )
def format_policy_listing(data): """Formats a list of policies into human readable format Args: data (list): A list of policies Returns: The formated string """ import re import textwrap out = "" i = 1 for p in data: # Shorten to max chars, remove linebreaks name = re.sub(r'[\n\r]', ' ', p.name[:22] + '..' if len(p.name) > 24 else p.name) # Shorten to 54 chars max, remove linebreaks desc = re.sub(r'[\n\r]', ' ', p.description[:52] + '..' if len(p.description) > 54 else p.description) time = f"{p.time_created:%Y-%m-%d %H:%M}" \ if p.time_created is not None else "" statements = "" for s in p.statements: statements += textwrap.fill( re.sub(r'[\n\r]', ' ', s), width=93, initial_indent=' ' * 5 + '- ', subsequent_indent=' ' * 7) + "\n" out += (f"{i:>4} {name:24} {desc:54} {time:16} {p.lifecycle_state}\n" f"{statements}") i += 1 return out
def partition_names_by_comp(names, compmap=None, boundary_vars=()): """Take an iterator of names and return a dict with component names keyed to lists of variable names. Simple names (having no '.' in them) will have a key of None. For example, the list ['abc.def', 'abc.pdq', 'foo', 'bar'] would return the dict { 'abc': ['def','pdq'], None: ['foo', 'bar'] } If a compmap dict is passed in, it will be populated with data from the iterator of names. boundary_vars is used to check for names that are boundary VariableTree subvars so that they will be placed correctly in the None entry rather than causing the base name of the VariableTree to appear in the list of components. """ if compmap is None: compmap = {} for name in names: parts = name.split('.', 1) if len(parts) == 1 or name in boundary_vars: compmap.setdefault(None, []).append(name) else: compmap.setdefault(parts[0], []).append(parts[1]) return compmap